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": "About:\n tabTitle: \"Pri\"\n releaseNotes: \"Eldonaj Notoj\"\n newUpdate: \"Nova Ĝisdatigo\"\n upToDate: \"Atom ", "end": 55, "score": 0.9757124185562134, "start": 42, "tag": "NAME", "value": "Eldonaj Notoj" } ]
def/eo/about.cson
abilogos/atom-i18n
76
About: tabTitle: "Pri" releaseNotes: "Eldonaj Notoj" newUpdate: "Nova Ĝisdatigo" upToDate: "Atom estas ĝisdata!" checkingForUpdates: "Kontrolas ĝisdatigojn..." checkUpdatesNow: "Kontroli nun" automaticDownloadUpdates: "Aŭtomate elŝuti ĝisdatigon" restartInstall: "Restartigi kaj instali" license: "Permesilo" termsOfUse: "Kondiĉoj de uzado" with: " kun " by: " de " andTheAwesome: "Kaj la mojosa " atomCommunity: "Atom Komunumo"
97532
About: tabTitle: "Pri" releaseNotes: "<NAME>" newUpdate: "Nova Ĝisdatigo" upToDate: "Atom estas ĝisdata!" checkingForUpdates: "Kontrolas ĝisdatigojn..." checkUpdatesNow: "Kontroli nun" automaticDownloadUpdates: "Aŭtomate elŝuti ĝisdatigon" restartInstall: "Restartigi kaj instali" license: "Permesilo" termsOfUse: "Kondiĉoj de uzado" with: " kun " by: " de " andTheAwesome: "Kaj la mojosa " atomCommunity: "Atom Komunumo"
true
About: tabTitle: "Pri" releaseNotes: "PI:NAME:<NAME>END_PI" newUpdate: "Nova Ĝisdatigo" upToDate: "Atom estas ĝisdata!" checkingForUpdates: "Kontrolas ĝisdatigojn..." checkUpdatesNow: "Kontroli nun" automaticDownloadUpdates: "Aŭtomate elŝuti ĝisdatigon" restartInstall: "Restartigi kaj instali" license: "Permesilo" termsOfUse: "Kondiĉoj de uzado" with: " kun " by: " de " andTheAwesome: "Kaj la mojosa " atomCommunity: "Atom Komunumo"
[ { "context": " { name: '+', description: '+' } }\n name: 'Name'\n description: 'Description'\n inner", "end": 6036, "score": 0.9808523058891296, "start": 6032, "tag": "NAME", "value": "Name" }, { "context": "' }, de: { name: '+' }, fr: {} }\n name: 'Name'\n }\n })\n\n m.updateI18NCoverage()", "end": 6182, "score": 0.6642037034034729, "start": 6178, "tag": "NAME", "value": "Name" }, { "context": " new FlexibleClass()\n m.set({\n name: 'Name'\n i18n: {\n '-': {'-':'-'}\n ", "end": 6432, "score": 0.9971626400947571, "start": 6428, "tag": "NAME", "value": "Name" } ]
test/app/models/CocoModel.spec.coffee
cihatislamdede/codecombat
4,858
CocoModel = require 'models/CocoModel' utils = require 'core/utils' class BlandClass extends CocoModel @className: 'Bland' @schema: { type: 'object' additionalProperties: false properties: number: {type: 'number'} object: {type: 'object'} string: {type: 'string'} _id: {type: 'string'} } urlRoot: '/db/bland' describe 'CocoModel', -> describe 'setProjection', -> it 'takes an array of properties to project and adds them as a query parameter', -> b = new BlandClass({}) b.setProjection ['number', 'object'] b.fetch() request = jasmine.Ajax.requests.mostRecent() expect(decodeURIComponent(request.url).indexOf('project=number,object')).toBeGreaterThan(-1) it 'can update its projection', -> baseURL = '/db/bland/test?filter-creator=Mojambo&project=number,object&ignore-evil=false' unprojectedURL = baseURL.replace /&project=number,object/, '' b = new BlandClass({}) b.setURL baseURL expect(b.getURL()).toBe baseURL b.setProjection ['number', 'object'] expect(b.getURL()).toBe baseURL b.setProjection ['number'] expect(b.getURL()).toBe baseURL.replace /,object/, '' b.setProjection [] expect(b.getURL()).toBe unprojectedURL b.setProjection null expect(b.getURL()).toBe unprojectedURL b.setProjection ['object', 'number'] expect(b.getURL()).toBe unprojectedURL + '&project=object,number' describe 'save', -> it 'saves to db/<urlRoot>', -> b = new BlandClass({}) res = b.save() request = jasmine.Ajax.requests.mostRecent() expect(res).toBeDefined() expect(request.url).toBe(b.urlRoot) expect(request.method).toBe('POST') it 'does not save if the data is invalid based on the schema', -> b = new BlandClass({number: 'NaN'}) res = b.save() expect(res).toBe(false) request = jasmine.Ajax.requests.mostRecent() expect(request).toBeUndefined() it 'uses PUT when _id is included', -> b = new BlandClass({_id: 'test'}) b.save() request = jasmine.Ajax.requests.mostRecent() expect(request.method).toBe('PUT') describe 'patch', -> it 'PATCHes only properties that have changed', -> b = new BlandClass({_id: 'test', number: 1}) b.loaded = true b.set('string', 'string') b.patch() request = jasmine.Ajax.requests.mostRecent() params = JSON.parse request.params expect(params.string).toBeDefined() expect(params.number).toBeUndefined() it 'collates all changes made over several sets', -> b = new BlandClass({_id: 'test', number: 1}) b.loaded = true b.set('string', 'string') b.set('object', {4: 5}) b.patch() request = jasmine.Ajax.requests.mostRecent() params = JSON.parse request.params expect(params.string).toBeDefined() expect(params.object).toBeDefined() expect(params.number).toBeUndefined() it 'does not include data from previous patches', -> b = new BlandClass({_id: 'test', number: 1}) b.loaded = true b.set('object', {1: 2}) b.patch() request = jasmine.Ajax.requests.mostRecent() attrs = JSON.stringify(b.attributes) # server responds with all request.respondWith({status: 200, responseText: attrs}) b.set('number', 3) b.patch() request = jasmine.Ajax.requests.mostRecent() params = JSON.parse request.params expect(params.object).toBeUndefined() it 'does nothing when there\'s nothing to patch', -> b = new BlandClass({_id: 'test', number: 1}) b.loaded = true b.set('number', 1) b.patch() request = jasmine.Ajax.requests.mostRecent() expect(request).toBeUndefined() xdescribe 'Achievement polling', -> # TODO: Figure out how to do debounce in tests so that this test doesn't need to use keepDoingUntil it 'achievements are polled upon saving a model', (done) -> #spyOn(CocoModel, 'pollAchievements') Backbone.Mediator.subscribe 'achievements:new', (collection) -> Backbone.Mediator.unsubscribe 'achievements:new' expect(collection.constructor.name).toBe('NewAchievementCollection') done() b = new BlandClass({}) res = b.save() request = jasmine.Ajax.requests.mostRecent() request.respondWith(status: 200, responseText: '{}') collection = [] model = _id: "5390f7637b4d6f2a074a7bb4" achievement: "537ce4855c91b8d1dda7fda8" collection.push model utils.keepDoingUntil (ready) -> request = jasmine.Ajax.requests.mostRecent() achievementURLMatch = (/.*achievements\?notified=false$/).exec request.url if achievementURLMatch ready true else return ready false request.respondWith {status: 200, responseText: JSON.stringify collection} utils.keepDoingUntil (ready) -> request = jasmine.Ajax.requests.mostRecent() userURLMatch = (/^\/db\/user\/[a-zA-Z0-9]*$/).exec request.url if userURLMatch ready true else return ready false request.respondWith {status:200, responseText: JSON.stringify me} describe 'updateI18NCoverage', -> class FlexibleClass extends CocoModel @className: 'Flexible' @schema: { type: 'object' properties: { name: { type: 'string' } description: { type: 'string' } innerObject: { type: 'object' properties: { name: { type: 'string' } i18n: { type: 'object', format: 'i18n', props: ['name']} } } i18n: { type: 'object', format: 'i18n', props: ['description', 'name', 'prop1']} } } it 'only includes languages for which all objects include a translation', -> m = new FlexibleClass({ i18n: { es: { name: '+', description: '+' }, fr: { name: '+', description: '+' } } name: 'Name' description: 'Description' innerObject: { i18n: { es: { name: '+' }, de: { name: '+' }, fr: {} } name: 'Name' } }) m.updateI18NCoverage() expect(_.isEqual(m.get('i18nCoverage'), ['es'])).toBe(true) it 'ignores objects for which there is nothing to translate', -> m = new FlexibleClass() m.set({ name: 'Name' i18n: { '-': {'-':'-'} 'es': {name: 'Name in Spanish'} } innerObject: { i18n: { '-': {'-':'-'} } } }) m.updateI18NCoverage() expect(_.isEqual(m.get('i18nCoverage'), ['es'])).toBe(true)
113060
CocoModel = require 'models/CocoModel' utils = require 'core/utils' class BlandClass extends CocoModel @className: 'Bland' @schema: { type: 'object' additionalProperties: false properties: number: {type: 'number'} object: {type: 'object'} string: {type: 'string'} _id: {type: 'string'} } urlRoot: '/db/bland' describe 'CocoModel', -> describe 'setProjection', -> it 'takes an array of properties to project and adds them as a query parameter', -> b = new BlandClass({}) b.setProjection ['number', 'object'] b.fetch() request = jasmine.Ajax.requests.mostRecent() expect(decodeURIComponent(request.url).indexOf('project=number,object')).toBeGreaterThan(-1) it 'can update its projection', -> baseURL = '/db/bland/test?filter-creator=Mojambo&project=number,object&ignore-evil=false' unprojectedURL = baseURL.replace /&project=number,object/, '' b = new BlandClass({}) b.setURL baseURL expect(b.getURL()).toBe baseURL b.setProjection ['number', 'object'] expect(b.getURL()).toBe baseURL b.setProjection ['number'] expect(b.getURL()).toBe baseURL.replace /,object/, '' b.setProjection [] expect(b.getURL()).toBe unprojectedURL b.setProjection null expect(b.getURL()).toBe unprojectedURL b.setProjection ['object', 'number'] expect(b.getURL()).toBe unprojectedURL + '&project=object,number' describe 'save', -> it 'saves to db/<urlRoot>', -> b = new BlandClass({}) res = b.save() request = jasmine.Ajax.requests.mostRecent() expect(res).toBeDefined() expect(request.url).toBe(b.urlRoot) expect(request.method).toBe('POST') it 'does not save if the data is invalid based on the schema', -> b = new BlandClass({number: 'NaN'}) res = b.save() expect(res).toBe(false) request = jasmine.Ajax.requests.mostRecent() expect(request).toBeUndefined() it 'uses PUT when _id is included', -> b = new BlandClass({_id: 'test'}) b.save() request = jasmine.Ajax.requests.mostRecent() expect(request.method).toBe('PUT') describe 'patch', -> it 'PATCHes only properties that have changed', -> b = new BlandClass({_id: 'test', number: 1}) b.loaded = true b.set('string', 'string') b.patch() request = jasmine.Ajax.requests.mostRecent() params = JSON.parse request.params expect(params.string).toBeDefined() expect(params.number).toBeUndefined() it 'collates all changes made over several sets', -> b = new BlandClass({_id: 'test', number: 1}) b.loaded = true b.set('string', 'string') b.set('object', {4: 5}) b.patch() request = jasmine.Ajax.requests.mostRecent() params = JSON.parse request.params expect(params.string).toBeDefined() expect(params.object).toBeDefined() expect(params.number).toBeUndefined() it 'does not include data from previous patches', -> b = new BlandClass({_id: 'test', number: 1}) b.loaded = true b.set('object', {1: 2}) b.patch() request = jasmine.Ajax.requests.mostRecent() attrs = JSON.stringify(b.attributes) # server responds with all request.respondWith({status: 200, responseText: attrs}) b.set('number', 3) b.patch() request = jasmine.Ajax.requests.mostRecent() params = JSON.parse request.params expect(params.object).toBeUndefined() it 'does nothing when there\'s nothing to patch', -> b = new BlandClass({_id: 'test', number: 1}) b.loaded = true b.set('number', 1) b.patch() request = jasmine.Ajax.requests.mostRecent() expect(request).toBeUndefined() xdescribe 'Achievement polling', -> # TODO: Figure out how to do debounce in tests so that this test doesn't need to use keepDoingUntil it 'achievements are polled upon saving a model', (done) -> #spyOn(CocoModel, 'pollAchievements') Backbone.Mediator.subscribe 'achievements:new', (collection) -> Backbone.Mediator.unsubscribe 'achievements:new' expect(collection.constructor.name).toBe('NewAchievementCollection') done() b = new BlandClass({}) res = b.save() request = jasmine.Ajax.requests.mostRecent() request.respondWith(status: 200, responseText: '{}') collection = [] model = _id: "5390f7637b4d6f2a074a7bb4" achievement: "537ce4855c91b8d1dda7fda8" collection.push model utils.keepDoingUntil (ready) -> request = jasmine.Ajax.requests.mostRecent() achievementURLMatch = (/.*achievements\?notified=false$/).exec request.url if achievementURLMatch ready true else return ready false request.respondWith {status: 200, responseText: JSON.stringify collection} utils.keepDoingUntil (ready) -> request = jasmine.Ajax.requests.mostRecent() userURLMatch = (/^\/db\/user\/[a-zA-Z0-9]*$/).exec request.url if userURLMatch ready true else return ready false request.respondWith {status:200, responseText: JSON.stringify me} describe 'updateI18NCoverage', -> class FlexibleClass extends CocoModel @className: 'Flexible' @schema: { type: 'object' properties: { name: { type: 'string' } description: { type: 'string' } innerObject: { type: 'object' properties: { name: { type: 'string' } i18n: { type: 'object', format: 'i18n', props: ['name']} } } i18n: { type: 'object', format: 'i18n', props: ['description', 'name', 'prop1']} } } it 'only includes languages for which all objects include a translation', -> m = new FlexibleClass({ i18n: { es: { name: '+', description: '+' }, fr: { name: '+', description: '+' } } name: '<NAME>' description: 'Description' innerObject: { i18n: { es: { name: '+' }, de: { name: '+' }, fr: {} } name: '<NAME>' } }) m.updateI18NCoverage() expect(_.isEqual(m.get('i18nCoverage'), ['es'])).toBe(true) it 'ignores objects for which there is nothing to translate', -> m = new FlexibleClass() m.set({ name: '<NAME>' i18n: { '-': {'-':'-'} 'es': {name: 'Name in Spanish'} } innerObject: { i18n: { '-': {'-':'-'} } } }) m.updateI18NCoverage() expect(_.isEqual(m.get('i18nCoverage'), ['es'])).toBe(true)
true
CocoModel = require 'models/CocoModel' utils = require 'core/utils' class BlandClass extends CocoModel @className: 'Bland' @schema: { type: 'object' additionalProperties: false properties: number: {type: 'number'} object: {type: 'object'} string: {type: 'string'} _id: {type: 'string'} } urlRoot: '/db/bland' describe 'CocoModel', -> describe 'setProjection', -> it 'takes an array of properties to project and adds them as a query parameter', -> b = new BlandClass({}) b.setProjection ['number', 'object'] b.fetch() request = jasmine.Ajax.requests.mostRecent() expect(decodeURIComponent(request.url).indexOf('project=number,object')).toBeGreaterThan(-1) it 'can update its projection', -> baseURL = '/db/bland/test?filter-creator=Mojambo&project=number,object&ignore-evil=false' unprojectedURL = baseURL.replace /&project=number,object/, '' b = new BlandClass({}) b.setURL baseURL expect(b.getURL()).toBe baseURL b.setProjection ['number', 'object'] expect(b.getURL()).toBe baseURL b.setProjection ['number'] expect(b.getURL()).toBe baseURL.replace /,object/, '' b.setProjection [] expect(b.getURL()).toBe unprojectedURL b.setProjection null expect(b.getURL()).toBe unprojectedURL b.setProjection ['object', 'number'] expect(b.getURL()).toBe unprojectedURL + '&project=object,number' describe 'save', -> it 'saves to db/<urlRoot>', -> b = new BlandClass({}) res = b.save() request = jasmine.Ajax.requests.mostRecent() expect(res).toBeDefined() expect(request.url).toBe(b.urlRoot) expect(request.method).toBe('POST') it 'does not save if the data is invalid based on the schema', -> b = new BlandClass({number: 'NaN'}) res = b.save() expect(res).toBe(false) request = jasmine.Ajax.requests.mostRecent() expect(request).toBeUndefined() it 'uses PUT when _id is included', -> b = new BlandClass({_id: 'test'}) b.save() request = jasmine.Ajax.requests.mostRecent() expect(request.method).toBe('PUT') describe 'patch', -> it 'PATCHes only properties that have changed', -> b = new BlandClass({_id: 'test', number: 1}) b.loaded = true b.set('string', 'string') b.patch() request = jasmine.Ajax.requests.mostRecent() params = JSON.parse request.params expect(params.string).toBeDefined() expect(params.number).toBeUndefined() it 'collates all changes made over several sets', -> b = new BlandClass({_id: 'test', number: 1}) b.loaded = true b.set('string', 'string') b.set('object', {4: 5}) b.patch() request = jasmine.Ajax.requests.mostRecent() params = JSON.parse request.params expect(params.string).toBeDefined() expect(params.object).toBeDefined() expect(params.number).toBeUndefined() it 'does not include data from previous patches', -> b = new BlandClass({_id: 'test', number: 1}) b.loaded = true b.set('object', {1: 2}) b.patch() request = jasmine.Ajax.requests.mostRecent() attrs = JSON.stringify(b.attributes) # server responds with all request.respondWith({status: 200, responseText: attrs}) b.set('number', 3) b.patch() request = jasmine.Ajax.requests.mostRecent() params = JSON.parse request.params expect(params.object).toBeUndefined() it 'does nothing when there\'s nothing to patch', -> b = new BlandClass({_id: 'test', number: 1}) b.loaded = true b.set('number', 1) b.patch() request = jasmine.Ajax.requests.mostRecent() expect(request).toBeUndefined() xdescribe 'Achievement polling', -> # TODO: Figure out how to do debounce in tests so that this test doesn't need to use keepDoingUntil it 'achievements are polled upon saving a model', (done) -> #spyOn(CocoModel, 'pollAchievements') Backbone.Mediator.subscribe 'achievements:new', (collection) -> Backbone.Mediator.unsubscribe 'achievements:new' expect(collection.constructor.name).toBe('NewAchievementCollection') done() b = new BlandClass({}) res = b.save() request = jasmine.Ajax.requests.mostRecent() request.respondWith(status: 200, responseText: '{}') collection = [] model = _id: "5390f7637b4d6f2a074a7bb4" achievement: "537ce4855c91b8d1dda7fda8" collection.push model utils.keepDoingUntil (ready) -> request = jasmine.Ajax.requests.mostRecent() achievementURLMatch = (/.*achievements\?notified=false$/).exec request.url if achievementURLMatch ready true else return ready false request.respondWith {status: 200, responseText: JSON.stringify collection} utils.keepDoingUntil (ready) -> request = jasmine.Ajax.requests.mostRecent() userURLMatch = (/^\/db\/user\/[a-zA-Z0-9]*$/).exec request.url if userURLMatch ready true else return ready false request.respondWith {status:200, responseText: JSON.stringify me} describe 'updateI18NCoverage', -> class FlexibleClass extends CocoModel @className: 'Flexible' @schema: { type: 'object' properties: { name: { type: 'string' } description: { type: 'string' } innerObject: { type: 'object' properties: { name: { type: 'string' } i18n: { type: 'object', format: 'i18n', props: ['name']} } } i18n: { type: 'object', format: 'i18n', props: ['description', 'name', 'prop1']} } } it 'only includes languages for which all objects include a translation', -> m = new FlexibleClass({ i18n: { es: { name: '+', description: '+' }, fr: { name: '+', description: '+' } } name: 'PI:NAME:<NAME>END_PI' description: 'Description' innerObject: { i18n: { es: { name: '+' }, de: { name: '+' }, fr: {} } name: 'PI:NAME:<NAME>END_PI' } }) m.updateI18NCoverage() expect(_.isEqual(m.get('i18nCoverage'), ['es'])).toBe(true) it 'ignores objects for which there is nothing to translate', -> m = new FlexibleClass() m.set({ name: 'PI:NAME:<NAME>END_PI' i18n: { '-': {'-':'-'} 'es': {name: 'Name in Spanish'} } innerObject: { i18n: { '-': {'-':'-'} } } }) m.updateI18NCoverage() expect(_.isEqual(m.get('i18nCoverage'), ['es'])).toBe(true)
[ { "context": "##############################################\n#\n# Markus 12/10/2017\n#\n####################################", "end": 75, "score": 0.9989625811576843, "start": 69, "tag": "NAME", "value": "Markus" } ]
server/methods/admissions.coffee
MooqitaSFH/worklearn
0
################################################################ # # Markus 12/10/2017 # ################################################################ ############################################### Meteor.methods add_admissions: (collection_name, item_id, admissions) -> #TODO: This is not working do we need it? Or something similar? return [] check collection_name, String check item_id, String check admissions, [{email:String, role:String}] user = Meteor.user() if not user throw new Meteor.Error('Not permitted.') collection = get_collection_save collection_name item = collection.findOne item_id return gen_admissions collection_name, item, admissions
2808
################################################################ # # <NAME> 12/10/2017 # ################################################################ ############################################### Meteor.methods add_admissions: (collection_name, item_id, admissions) -> #TODO: This is not working do we need it? Or something similar? return [] check collection_name, String check item_id, String check admissions, [{email:String, role:String}] user = Meteor.user() if not user throw new Meteor.Error('Not permitted.') collection = get_collection_save collection_name item = collection.findOne item_id return gen_admissions collection_name, item, admissions
true
################################################################ # # PI:NAME:<NAME>END_PI 12/10/2017 # ################################################################ ############################################### Meteor.methods add_admissions: (collection_name, item_id, admissions) -> #TODO: This is not working do we need it? Or something similar? return [] check collection_name, String check item_id, String check admissions, [{email:String, role:String}] user = Meteor.user() if not user throw new Meteor.Error('Not permitted.') collection = get_collection_save collection_name item = collection.findOne item_id return gen_admissions collection_name, item, admissions
[ { "context": "oretical+Physics&sort=published&order=desc&mailto=wolfwm@uwec.edu'\n $.ajax(url, ->\n\n $('#paper-list').html\n", "end": 187, "score": 0.99991774559021, "start": 172, "tag": "EMAIL", "value": "wolfwm@uwec.edu" } ]
assets/js/application.coffee
wmwolf/kitp_papers
0
CrossRef = papers: [] get_json: -> url = 'https://api.crossref.org/works?query.affiliation=Kavli+Institute+for+Theoretical+Physics&sort=published&order=desc&mailto=wolfwm@uwec.edu' $.ajax(url, -> $('#paper-list').html ) getPapers: (institution, numPapers) -> query = this.query(institution, numPapers) $.get(query, CrossRef.addPapersContent) addPapersContent: xml -> content = $('<div class="row" id="crossref"><div class="col">' + '<a id="papers"></a><div class="card">' + '<div class="card-header"><h3 class="card-title">Recent Papers from ' + 'KITP Scholars</h3></div><div class="card-content">'+ '<ul class="list-group" id="papers-content">' + '</div><a href="#papers"><div class="card-footer text-center ' + 'expandable"><span class="glyphicon glyphicon-chevron-down"></span>' + '</div></a></div></div></div>'); content.insertAfter('#insert-here'); $('.expandable').click(Arxiv.toggleExtraPapers); # initially only show this many papers, make others visible via dropdown displayNum = 3; papersDisplayed = 0; # individual papers are wrapped in <entry></entry>, so find each of those # and iterate through them to extract paper details $(xml).find('entry').each(function() { var title = $(this).find('title').text(); var author = ''; $(this).find('author').each(function() { author = author + $(this).find('name').text() + ', '; }); // remove trailing comma and space author = author.substring(0, author.length - 2); var url = $(this).find('id').text(); var toAdd; if (papersDisplayed >= displayNum) { toAdd = $('<a href=' + url + ' class="list-group-item paper toggle">' + '<h4>' + title + '</h4>' + author + '</a>'); } else { toAdd = $('<a href=' + url + ' class="list-group-item paper"><h4>' + title + '</h4>' + author + '</a>'); } toAdd.appendTo('#papers-content') papersDisplayed += 1 }); return content; setup: -> CrossRef.papers = CrossRef.get_json
61946
CrossRef = papers: [] get_json: -> url = 'https://api.crossref.org/works?query.affiliation=Kavli+Institute+for+Theoretical+Physics&sort=published&order=desc&mailto=<EMAIL>' $.ajax(url, -> $('#paper-list').html ) getPapers: (institution, numPapers) -> query = this.query(institution, numPapers) $.get(query, CrossRef.addPapersContent) addPapersContent: xml -> content = $('<div class="row" id="crossref"><div class="col">' + '<a id="papers"></a><div class="card">' + '<div class="card-header"><h3 class="card-title">Recent Papers from ' + 'KITP Scholars</h3></div><div class="card-content">'+ '<ul class="list-group" id="papers-content">' + '</div><a href="#papers"><div class="card-footer text-center ' + 'expandable"><span class="glyphicon glyphicon-chevron-down"></span>' + '</div></a></div></div></div>'); content.insertAfter('#insert-here'); $('.expandable').click(Arxiv.toggleExtraPapers); # initially only show this many papers, make others visible via dropdown displayNum = 3; papersDisplayed = 0; # individual papers are wrapped in <entry></entry>, so find each of those # and iterate through them to extract paper details $(xml).find('entry').each(function() { var title = $(this).find('title').text(); var author = ''; $(this).find('author').each(function() { author = author + $(this).find('name').text() + ', '; }); // remove trailing comma and space author = author.substring(0, author.length - 2); var url = $(this).find('id').text(); var toAdd; if (papersDisplayed >= displayNum) { toAdd = $('<a href=' + url + ' class="list-group-item paper toggle">' + '<h4>' + title + '</h4>' + author + '</a>'); } else { toAdd = $('<a href=' + url + ' class="list-group-item paper"><h4>' + title + '</h4>' + author + '</a>'); } toAdd.appendTo('#papers-content') papersDisplayed += 1 }); return content; setup: -> CrossRef.papers = CrossRef.get_json
true
CrossRef = papers: [] get_json: -> url = 'https://api.crossref.org/works?query.affiliation=Kavli+Institute+for+Theoretical+Physics&sort=published&order=desc&mailto=PI:EMAIL:<EMAIL>END_PI' $.ajax(url, -> $('#paper-list').html ) getPapers: (institution, numPapers) -> query = this.query(institution, numPapers) $.get(query, CrossRef.addPapersContent) addPapersContent: xml -> content = $('<div class="row" id="crossref"><div class="col">' + '<a id="papers"></a><div class="card">' + '<div class="card-header"><h3 class="card-title">Recent Papers from ' + 'KITP Scholars</h3></div><div class="card-content">'+ '<ul class="list-group" id="papers-content">' + '</div><a href="#papers"><div class="card-footer text-center ' + 'expandable"><span class="glyphicon glyphicon-chevron-down"></span>' + '</div></a></div></div></div>'); content.insertAfter('#insert-here'); $('.expandable').click(Arxiv.toggleExtraPapers); # initially only show this many papers, make others visible via dropdown displayNum = 3; papersDisplayed = 0; # individual papers are wrapped in <entry></entry>, so find each of those # and iterate through them to extract paper details $(xml).find('entry').each(function() { var title = $(this).find('title').text(); var author = ''; $(this).find('author').each(function() { author = author + $(this).find('name').text() + ', '; }); // remove trailing comma and space author = author.substring(0, author.length - 2); var url = $(this).find('id').text(); var toAdd; if (papersDisplayed >= displayNum) { toAdd = $('<a href=' + url + ' class="list-group-item paper toggle">' + '<h4>' + title + '</h4>' + author + '</a>'); } else { toAdd = $('<a href=' + url + ' class="list-group-item paper"><h4>' + title + '</h4>' + author + '</a>'); } toAdd.appendTo('#papers-content') papersDisplayed += 1 }); return content; setup: -> CrossRef.papers = CrossRef.get_json
[ { "context": " server.respondWith '/aoo', JSON.stringify keyA: 'valueA'\n server.respondWith '/boo', JSON.strin", "end": 1920, "score": 0.5740281939506531, "start": 1915, "tag": "KEY", "value": "value" }, { "context": " server.respondWith '/coo', JSON.stringify keyC: 'valueC'\n model.fetch()\n\n it 'should mak", "end": 2054, "score": 0.5888025760650635, "start": 2049, "tag": "KEY", "value": "value" } ]
lib/swiss-ajax.spec.coffee
kpunith8/gringotts
0
import Backbone from 'backbone' import Chaplin from 'chaplin' import swissAjax from './swiss-ajax' class MockModelString extends Chaplin.Model url: '/foo' class MockModelSingleArray extends Chaplin.Model url: ['/foo'] class MockModelArray extends Chaplin.Model url: ['/aoo', '/boo', '/coo'] # It's recommended to handle multiple data results in parse() method. # Normally the only instance of JSON object should be passed down to # Backbone Model class for further processing. parse: (resp) -> super _.extend {}, resp[0], resp[1], resp[2] class MockModelHash extends Chaplin.Model url: {aoo: '/aoo', boo: '/boo', coo: '/coo'} parse: (resp) -> super _.extend {}, resp.aoo, resp.boo, resp.coo factory = String: MockModelString SingleArray: MockModelSingleArray Array: MockModelArray Hash: MockModelHash describe 'swissAjax', -> server = null model = null beforeEach -> Backbone.ajax = swissAjax.ajax server = sinon.fakeServer.create() afterEach -> Backbone.ajax = swissAjax.backboneAjax server.restore() model.dispose() simpleUrlTypes = ['String', 'SingleArray'] simpleUrlTypes.forEach (urlType) -> context "with url of #{urlType} type", -> beforeEach -> model = new factory["#{urlType}"]() server.respondWith JSON.stringify key: 'value' model.fetch() it 'should make one call', -> expect(server.requests.length).to.equal 1 expect(server.requests[0].url).to.equal '/foo' it 'should set model proper data', -> expect(model.get 'key').to.be.equal 'value' urlTypes = ['Array', 'Hash'] urlTypes.forEach (urlType) -> context "with url of #{urlType} type", -> promise = null beforeEach -> model = new factory["#{urlType}"]() context 'on request success', -> beforeEach -> server.respondWith '/aoo', JSON.stringify keyA: 'valueA' server.respondWith '/boo', JSON.stringify keyB: 'valueB' server.respondWith '/coo', JSON.stringify keyC: 'valueC' model.fetch() it 'should make all calls', -> expect(server.requests.length).to.equal 3 expect(server.requests[0].url).to.equal '/aoo' expect(server.requests[1].url).to.equal '/boo' expect(server.requests[2].url).to.equal '/coo' it 'should set model proper data', -> expect(model.get 'keyA').to.be.equal 'valueA' expect(model.get 'keyB').to.be.equal 'valueB' expect(model.get 'keyC').to.be.equal 'valueC' context 'on request error', -> errorHandler = null catchSpy = null beforeEach -> errorHandler = sinon.spy() model.on 'error', errorHandler server.respondWith '/aoo', '{}' server.respondWith '/boo', [500, {}, '{}'] server.respondWith '/coo', [404, {}, '{}'] model.fetch().catch catchSpy = sinon.spy() it 'should trigger all errors', -> expect(errorHandler).to.have.been.calledTwice expect(errorHandler).to.have.been.calledWith model, sinon.match.has 'status', 500 expect(errorHandler).to.have.been.calledWith model, sinon.match.has 'status', 404 it 'should call catchSpy', -> expect(catchSpy).to.have.been.calledOnce
85740
import Backbone from 'backbone' import Chaplin from 'chaplin' import swissAjax from './swiss-ajax' class MockModelString extends Chaplin.Model url: '/foo' class MockModelSingleArray extends Chaplin.Model url: ['/foo'] class MockModelArray extends Chaplin.Model url: ['/aoo', '/boo', '/coo'] # It's recommended to handle multiple data results in parse() method. # Normally the only instance of JSON object should be passed down to # Backbone Model class for further processing. parse: (resp) -> super _.extend {}, resp[0], resp[1], resp[2] class MockModelHash extends Chaplin.Model url: {aoo: '/aoo', boo: '/boo', coo: '/coo'} parse: (resp) -> super _.extend {}, resp.aoo, resp.boo, resp.coo factory = String: MockModelString SingleArray: MockModelSingleArray Array: MockModelArray Hash: MockModelHash describe 'swissAjax', -> server = null model = null beforeEach -> Backbone.ajax = swissAjax.ajax server = sinon.fakeServer.create() afterEach -> Backbone.ajax = swissAjax.backboneAjax server.restore() model.dispose() simpleUrlTypes = ['String', 'SingleArray'] simpleUrlTypes.forEach (urlType) -> context "with url of #{urlType} type", -> beforeEach -> model = new factory["#{urlType}"]() server.respondWith JSON.stringify key: 'value' model.fetch() it 'should make one call', -> expect(server.requests.length).to.equal 1 expect(server.requests[0].url).to.equal '/foo' it 'should set model proper data', -> expect(model.get 'key').to.be.equal 'value' urlTypes = ['Array', 'Hash'] urlTypes.forEach (urlType) -> context "with url of #{urlType} type", -> promise = null beforeEach -> model = new factory["#{urlType}"]() context 'on request success', -> beforeEach -> server.respondWith '/aoo', JSON.stringify keyA: '<KEY>A' server.respondWith '/boo', JSON.stringify keyB: 'valueB' server.respondWith '/coo', JSON.stringify keyC: '<KEY>C' model.fetch() it 'should make all calls', -> expect(server.requests.length).to.equal 3 expect(server.requests[0].url).to.equal '/aoo' expect(server.requests[1].url).to.equal '/boo' expect(server.requests[2].url).to.equal '/coo' it 'should set model proper data', -> expect(model.get 'keyA').to.be.equal 'valueA' expect(model.get 'keyB').to.be.equal 'valueB' expect(model.get 'keyC').to.be.equal 'valueC' context 'on request error', -> errorHandler = null catchSpy = null beforeEach -> errorHandler = sinon.spy() model.on 'error', errorHandler server.respondWith '/aoo', '{}' server.respondWith '/boo', [500, {}, '{}'] server.respondWith '/coo', [404, {}, '{}'] model.fetch().catch catchSpy = sinon.spy() it 'should trigger all errors', -> expect(errorHandler).to.have.been.calledTwice expect(errorHandler).to.have.been.calledWith model, sinon.match.has 'status', 500 expect(errorHandler).to.have.been.calledWith model, sinon.match.has 'status', 404 it 'should call catchSpy', -> expect(catchSpy).to.have.been.calledOnce
true
import Backbone from 'backbone' import Chaplin from 'chaplin' import swissAjax from './swiss-ajax' class MockModelString extends Chaplin.Model url: '/foo' class MockModelSingleArray extends Chaplin.Model url: ['/foo'] class MockModelArray extends Chaplin.Model url: ['/aoo', '/boo', '/coo'] # It's recommended to handle multiple data results in parse() method. # Normally the only instance of JSON object should be passed down to # Backbone Model class for further processing. parse: (resp) -> super _.extend {}, resp[0], resp[1], resp[2] class MockModelHash extends Chaplin.Model url: {aoo: '/aoo', boo: '/boo', coo: '/coo'} parse: (resp) -> super _.extend {}, resp.aoo, resp.boo, resp.coo factory = String: MockModelString SingleArray: MockModelSingleArray Array: MockModelArray Hash: MockModelHash describe 'swissAjax', -> server = null model = null beforeEach -> Backbone.ajax = swissAjax.ajax server = sinon.fakeServer.create() afterEach -> Backbone.ajax = swissAjax.backboneAjax server.restore() model.dispose() simpleUrlTypes = ['String', 'SingleArray'] simpleUrlTypes.forEach (urlType) -> context "with url of #{urlType} type", -> beforeEach -> model = new factory["#{urlType}"]() server.respondWith JSON.stringify key: 'value' model.fetch() it 'should make one call', -> expect(server.requests.length).to.equal 1 expect(server.requests[0].url).to.equal '/foo' it 'should set model proper data', -> expect(model.get 'key').to.be.equal 'value' urlTypes = ['Array', 'Hash'] urlTypes.forEach (urlType) -> context "with url of #{urlType} type", -> promise = null beforeEach -> model = new factory["#{urlType}"]() context 'on request success', -> beforeEach -> server.respondWith '/aoo', JSON.stringify keyA: 'PI:KEY:<KEY>END_PIA' server.respondWith '/boo', JSON.stringify keyB: 'valueB' server.respondWith '/coo', JSON.stringify keyC: 'PI:KEY:<KEY>END_PIC' model.fetch() it 'should make all calls', -> expect(server.requests.length).to.equal 3 expect(server.requests[0].url).to.equal '/aoo' expect(server.requests[1].url).to.equal '/boo' expect(server.requests[2].url).to.equal '/coo' it 'should set model proper data', -> expect(model.get 'keyA').to.be.equal 'valueA' expect(model.get 'keyB').to.be.equal 'valueB' expect(model.get 'keyC').to.be.equal 'valueC' context 'on request error', -> errorHandler = null catchSpy = null beforeEach -> errorHandler = sinon.spy() model.on 'error', errorHandler server.respondWith '/aoo', '{}' server.respondWith '/boo', [500, {}, '{}'] server.respondWith '/coo', [404, {}, '{}'] model.fetch().catch catchSpy = sinon.spy() it 'should trigger all errors', -> expect(errorHandler).to.have.been.calledTwice expect(errorHandler).to.have.been.calledWith model, sinon.match.has 'status', 500 expect(errorHandler).to.have.been.calledWith model, sinon.match.has 'status', 404 it 'should call catchSpy', -> expect(catchSpy).to.have.been.calledOnce
[ { "context": " static properties should be positioned.\n# @author Daniel Mason\n###\n\n'use strict'\n\n# ----------------------------", "end": 113, "score": 0.9980961680412292, "start": 101, "tag": "NAME", "value": "Daniel Mason" }, { "context": "\n getDefaultProps: ->\n name: 'Bob'\n\n displayName: 'Hello',\n\n prop", "end": 1906, "score": 0.9998072981834412, "start": 1903, "tag": "NAME", "value": "Bob" }, { "context": " },\n\n getDefaultProps: ->\n name: 'Bob'\n\n displayName: 'Hello',\n\n propType", "end": 2430, "score": 0.9998165965080261, "start": 2427, "tag": "NAME", "value": "Bob" }, { "context": " MyComponent.defaultProps = {\n something: 'Bob'\n }\n\n MyComponent.displayName = 'Hello'", "end": 2975, "score": 0.9989729523658752, "start": 2972, "tag": "NAME", "value": "Bob" }, { "context": " MyComponent.defaultProps = {\n something: 'Bob'\n }\n\n MyComponent.displayName = 'Hello'", "end": 3452, "score": 0.9987640380859375, "start": 3449, "tag": "NAME", "value": "Bob" }, { "context": " MyComponent.defaultProps = {\n something: 'Bob'\n }\n\n MyComponent.displayName = 'Hello'", "end": 3932, "score": 0.9993575215339661, "start": 3929, "tag": "NAME", "value": "Bob" }, { "context": "mponent\n @randomlyNamed =\n name: 'random'\n '''\n ,\n # Do not error if unchecked stat", "end": 4580, "score": 0.6548526883125305, "start": 4574, "tag": "NAME", "value": "random" }, { "context": "mponent\n @randomlyNamed =\n name: 'random'\n '''\n options: [PROPERTY_ASSIGNMENT]\n ,\n ", "end": 4790, "score": 0.6643826365470886, "start": 4784, "tag": "NAME", "value": "random" }, { "context": "\n MyComponent.randomlyNamed =\n name: 'random'\n '''\n options: [PROPERTY_ASSIGNMENT]\n ,\n ", "end": 5088, "score": 0.6687896251678467, "start": 5082, "tag": "NAME", "value": "random" }, { "context": "\n MyComponent.randomlyNamed =\n name: 'random'\n '''\n ,\n # ------------------------------", "end": 5382, "score": 0.5688767433166504, "start": 5376, "tag": "NAME", "value": "random" }, { "context": " return null\n\n MyComponent.displayName = \"Hello\"\n '''\n options: [PROPERTY_ASSIGNMENT]\n ,\n ", "end": 14804, "score": 0.6282967329025269, "start": 14799, "tag": "NAME", "value": "Hello" }, { "context": " return null\n\n MyComponent.displayName = \"Hello\"\n '''\n options: [STATIC_PUBLIC_FIELD, {disp", "end": 15060, "score": 0.6775152683258057, "start": 15055, "tag": "NAME", "value": "Hello" }, { "context": "t\n @defaultProps = {\n something: 'Bob'\n }\n '''\n ,\n # Do not error if defa", "end": 15530, "score": 0.9957016706466675, "start": 15527, "tag": "NAME", "value": "Bob" }, { "context": "ent\n @defaultProps =\n something: 'Bob'\n '''\n options: [PROPERTY_ASSIGNMENT, {defa", "end": 15733, "score": 0.985062837600708, "start": 15730, "tag": "NAME", "value": "Bob" }, { "context": " # return {\n # something: 'Bob'\n # };\n # }\n # }\n #", "end": 16283, "score": 0.9996306300163269, "start": 16280, "tag": "NAME", "value": "Bob" }, { "context": " # return {\n # something: 'Bob'\n # };\n # }\n # }\n #", "end": 16642, "score": 0.999659538269043, "start": 16639, "tag": "NAME", "value": "Bob" }, { "context": " MyComponent.defaultProps = {\n name: 'Bob'\n }\n '''\n options: [PROPERTY_ASSIGNMEN", "end": 17210, "score": 0.999796986579895, "start": 17207, "tag": "NAME", "value": "Bob" }, { "context": " MyComponent.defaultProps = {\n name: 'Bob'\n }\n '''\n options: [STATIC_PUBLIC_FIEL", "end": 17490, "score": 0.9997915625572205, "start": 17487, "tag": "NAME", "value": "Bob" }, { "context": "llo\"\n\n @defaultProps = {\n something: 'Bob'\n }\n\n @propTypes = {\n something:", "end": 20646, "score": 0.9979792237281799, "start": 20643, "tag": "NAME", "value": "Bob" }, { "context": "\n\n @defaultProps = {\n something: 'Bob'\n };\n\n @propTypes = {\n som", "end": 21136, "score": 0.9950839877128601, "start": 21133, "tag": "NAME", "value": "Bob" }, { "context": " MyComponent.defaultProps = {\n name: 'Bob'\n }\n\n MyComponent.propTypes = {\n ", "end": 24533, "score": 0.9997994303703308, "start": 24530, "tag": "NAME", "value": "Bob" }, { "context": " MyComponent.defaultProps = {\n name: 'Bob'\n }\n\n MyComponent.propTypes = {\n ", "end": 25122, "score": 0.9997999668121338, "start": 25119, "tag": "NAME", "value": "Bob" }, { "context": " MyComponent.defaultProps = {\n name: 'Bob'\n }\n\n MyComponent.propTypes = {\n ", "end": 26085, "score": 0.9997832179069519, "start": 26082, "tag": "NAME", "value": "Bob" }, { "context": " MyComponent.defaultProps = {\n name: 'Bob'\n }\n\n MyComponent.propTypes = {\n ", "end": 26776, "score": 0.9998024106025696, "start": 26773, "tag": "NAME", "value": "Bob" }, { "context": " OtherComponent.defaultProps = {\n name: 'Bob'\n }\n\n OtherComponent.propTypes = {\n ", "end": 27657, "score": 0.9998224377632141, "start": 27654, "tag": "NAME", "value": "Bob" }, { "context": "ponent\n @defaultProps = {\n name: 'Bob'\n }\n\n @propTypes = {\n name", "end": 28159, "score": 0.9998123645782471, "start": 28156, "tag": "NAME", "value": "Bob" }, { "context": " MyComponent.defaultProps = {\n name: 'Bob'\n }\n\n MyComponent.propTypes = {\n ", "end": 29723, "score": 0.9998407363891602, "start": 29720, "tag": "NAME", "value": "Bob" }, { "context": " MyComponent.defaultProps = {\n name: 'Bob'\n }\n\n MyComponent.propTypes = {\n ", "end": 30860, "score": 0.9998527765274048, "start": 30857, "tag": "NAME", "value": "Bob" }, { "context": "\n\n @defaultProps = {\n something: 'Bob'\n }\n\n @propTypes = {\n some", "end": 36171, "score": 0.9992451667785645, "start": 36168, "tag": "NAME", "value": "Bob" }, { "context": "\n\n @defaultProps = {\n something: 'Bob'\n }\n\n @propTypes = {\n some", "end": 37212, "score": 0.9690155982971191, "start": 37209, "tag": "NAME", "value": "Bob" }, { "context": "\n\n @defaultProps = {\n something: 'Bob'\n };\n\n @propTypes = {\n som", "end": 42444, "score": 0.9986237287521362, "start": 42441, "tag": "NAME", "value": "Bob" }, { "context": "\n\n @defaultProps = {\n something: 'Bob'\n }\n\n @propTypes = {\n some", "end": 43594, "score": 0.9989767074584961, "start": 43591, "tag": "NAME", "value": "Bob" }, { "context": " MyComponent.defaultProps = {\n name: 'Bob'\n }\n\n MyComponent.propTypes = {\n ", "end": 45267, "score": 0.9998065233230591, "start": 45264, "tag": "NAME", "value": "Bob" }, { "context": " MyComponent.defaultProps = {\n name: 'Bob'\n }\n\n MyComponent.propTypes = {\n ", "end": 46515, "score": 0.9998157024383545, "start": 46512, "tag": "NAME", "value": "Bob" }, { "context": " MyComponent.defaultProps = {\n name: 'Bob'\n }\n\n MyComponent.propTypes = {\n ", "end": 48134, "score": 0.9998263716697693, "start": 48131, "tag": "NAME", "value": "Bob" }, { "context": " MyComponent.defaultProps = {\n name: 'Bob'\n }\n\n MyComponent.propTypes = {\n ", "end": 49387, "score": 0.9998292922973633, "start": 49384, "tag": "NAME", "value": "Bob" }, { "context": " OtherComponent.defaultProps = {\n name: 'Bob'\n }\n\n OtherComponent.propTypes = {\n ", "end": 50929, "score": 0.9997804760932922, "start": 50926, "tag": "NAME", "value": "Bob" }, { "context": " }\n\n @defaultProps = {\n name: 'Bob'\n }\n\n @propTypes: {\n name:", "end": 52027, "score": 0.9998155236244202, "start": 52024, "tag": "NAME", "value": "Bob" } ]
src/tests/rules/static-property-placement.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Defines where React component static properties should be positioned. # @author Daniel Mason ### 'use strict' # ------------------------------------------------------------------------------ # Positioning Options # ------------------------------------------------------------------------------ STATIC_PUBLIC_FIELD = 'static public field' STATIC_GETTER = 'static getter' PROPERTY_ASSIGNMENT = 'property assignment' # ------------------------------------------------------------------------------ # Requirements # ------------------------------------------------------------------------------ path = require 'path' {RuleTester} = require 'eslint' rule = require 'eslint-plugin-react/lib/rules/static-property-placement' # parsers = require 'eslint-plugin-react/tests/helpers/parsers' ruleTesterConfig = # parser: parsers.BABEL_ESLINT # parserOptions: # ecmaVersion: 2018 # sourceType: 'module' # ecmaFeatures: # jsx: yes settings: react: version: '15' # ------------------------------------------------------------------------------ # Tests # ------------------------------------------------------------------------------ ruleTester = new RuleTester { ...ruleTesterConfig parser: path.join __dirname, '../../..' } ruleTester.run 'static-property-placement', rule, valid: [ # ------------------------------------------------------------------------------ # Ignore creatClass/createReactClass and Static Functional Components # ------------------------------------------------------------------------------ # Do not error on createReactClass pragma code: [ ''' MyComponent = createReactClass({ childContextTypes: { something: PropTypes.bool }, contextTypes: { something: PropTypes.bool }, getDefaultProps: -> name: 'Bob' displayName: 'Hello', propTypes: { something: PropTypes.bool }, render: -> return null }) ''' ].join '\n' options: [PROPERTY_ASSIGNMENT] , # Do not error on createClass pragma code: ''' MyComponent = React.createClass({ childContextTypes: { something: PropTypes.bool }, contextTypes: { something: PropTypes.bool }, getDefaultProps: -> name: 'Bob' displayName: 'Hello', propTypes: { something: PropTypes.bool }, render: -> return null }) ''' options: [PROPERTY_ASSIGNMENT] , # Do not error on SFC arrow function with return code: ''' MyComponent = () => return <div>Hello</div> MyComponent.childContextTypes = { something: PropTypes.bool } MyComponent.contextTypes = { something: PropTypes.bool } MyComponent.defaultProps = { something: 'Bob' } MyComponent.displayName = 'Hello' MyComponent.propTypes = { something: PropTypes.bool } ''' , # Do not error on SFC arrow function with direct return code: ''' MyComponent = () => (<div>Hello</div>) MyComponent.childContextTypes = { something: PropTypes.bool } MyComponent.contextTypes = { something: PropTypes.bool } MyComponent.defaultProps = { something: 'Bob' } MyComponent.displayName = 'Hello' MyComponent.propTypes = { something: PropTypes.bool } ''' , # Do not error on SFC as unnamed function code: ''' export MyComponent = -> return <div>Hello</div> MyComponent.childContextTypes = { something: PropTypes.bool } MyComponent.contextTypes = { something: PropTypes.bool } MyComponent.defaultProps = { something: 'Bob' } MyComponent.displayName = 'Hello' MyComponent.propTypes = { something: PropTypes.bool } ''' , # ------------------------------------------------------------------------------ # no properties # ------------------------------------------------------------------------------ # Do not error if no properties defined code: ''' class MyComponent extends React.Component render: -> return null ''' , # Do not error if unchecked properties defined code: ''' class MyComponent extends React.Component @randomlyNamed = name: 'random' ''' , # Do not error if unchecked static properties defined and assignment rule enabled code: ''' class MyComponent extends React.Component @randomlyNamed = name: 'random' ''' options: [PROPERTY_ASSIGNMENT] , # Do not error if unchecked assignment properties defined and assignment rule enabled code: ''' class MyComponent extends React.Component render: -> return null MyComponent.randomlyNamed = name: 'random' ''' options: [PROPERTY_ASSIGNMENT] , # Do not error if unchecked assignment properties defined and static rule enabled code: ''' class MyComponent extends React.Component render: -> return null MyComponent.randomlyNamed = name: 'random' ''' , # ------------------------------------------------------------------------------ # childContextTypes - static field # ------------------------------------------------------------------------------ # Do not error if childContextTypes correctly defined - static field code: ''' class MyComponent extends React.Component @childContextTypes = something: PropTypes.bool ''' , # Do not error if childContextTypes correctly defined - static field code: ''' class MyComponent extends React.Component @childContextTypes: something: PropTypes.bool ''' options: [PROPERTY_ASSIGNMENT, {childContextTypes: STATIC_PUBLIC_FIELD}] , # , # # ------------------------------------------------------------------------------ # # childContextTypes - static getter # # ------------------------------------------------------------------------------ # # Do not error if childContextTypes correctly defined - static getter # code: [ # ''' # class MyComponent extends React.Component { # static get childContextTypes() { # return { # something: PropTypes.bool # }; # } # } # ''' # ].join '\n' # options: [STATIC_GETTER] # , # # Do not error if contextTypes correctly defined - static getter # code: [ # ''' # class MyComponent extends React.Component { # static get childContextTypes() { # return { # something: PropTypes.bool # }; # } # } # ''' # ].join '\n' # options: [PROPERTY_ASSIGNMENT, {childContextTypes: STATIC_GETTER}] # ------------------------------------------------------------------------------ # childContextTypes - assignment # ------------------------------------------------------------------------------ # Do not error if childContextTypes correctly defined - assignment code: ''' class MyComponent extends React.Component render: -> return null MyComponent.childContextTypes = name: PropTypes.string.isRequired ''' options: [PROPERTY_ASSIGNMENT] , # Do not error if childContextTypes correctly defined - assignment code: ''' class MyComponent extends React.Component render: -> return null MyComponent.childContextTypes = { name: PropTypes.string.isRequired } ''' options: [STATIC_PUBLIC_FIELD, {childContextTypes: PROPERTY_ASSIGNMENT}] , # ------------------------------------------------------------------------------ # contextTypes - static field # ------------------------------------------------------------------------------ # Do not error if contextTypes correctly defined - static field code: ''' class MyComponent extends React.Component @contextTypes = { something: PropTypes.bool } ''' , # Do not error if contextTypes correctly defined - static field code: ''' class MyComponent extends React.Component @contextTypes = something: PropTypes.bool ''' options: [PROPERTY_ASSIGNMENT, {contextTypes: STATIC_PUBLIC_FIELD}] , # , # # ------------------------------------------------------------------------------ # # contextTypes - static getter # # ------------------------------------------------------------------------------ # # Do not error if contextTypes correctly defined - static getter # code: [ # ''' # class MyComponent extends React.Component { # static get contextTypes() { # return { # something: PropTypes.bool # }; # } # } # ''' # ].join '\n' # options: [STATIC_GETTER] # , # # Do not error if contextTypes correctly defined - static getter # code: [ # ''' # class MyComponent extends React.Component { # static get contextTypes() { # return { # something: PropTypes.bool # }; # } # } # ''' # ].join '\n' # options: [PROPERTY_ASSIGNMENT, {contextTypes: STATIC_GETTER}] # ------------------------------------------------------------------------------ # contextTypes - assignment # ------------------------------------------------------------------------------ # Do not error if contextTypes correctly defined - assignment code: ''' class MyComponent extends React.Component render: -> return null MyComponent.contextTypes = { name: PropTypes.string.isRequired } ''' options: [PROPERTY_ASSIGNMENT] , # Do not error if contextTypes correctly defined - assignment code: ''' class MyComponent extends React.Component render: -> return null MyComponent.contextTypes = { name: PropTypes.string.isRequired } ''' options: [STATIC_PUBLIC_FIELD, {contextTypes: PROPERTY_ASSIGNMENT}] , # ------------------------------------------------------------------------------ # contextType - static field # ------------------------------------------------------------------------------ # Do not error if contextType correctly defined - static field code: ''' class MyComponent extends React.Component @contextType = MyContext ''' , # Do not error if contextType correctly defined - static field code: ''' class MyComponent extends React.Component @contextType = MyContext ''' options: [PROPERTY_ASSIGNMENT, {contextType: STATIC_PUBLIC_FIELD}] , # , # # ------------------------------------------------------------------------------ # # contextType - static getter # # ------------------------------------------------------------------------------ # # Do not error if contextType correctly defined - static field # code: [ # ''' # class MyComponent extends React.Component { # static get contextType() { # return MyContext; # } # } # ''' # ].join '\n' # options: [STATIC_GETTER] # , # # Do not error if contextType correctly defined - static field # code: [ # ''' # class MyComponent extends React.Component { # static get contextType() { # return MyContext; # } # } # ''' # ].join '\n' # options: [PROPERTY_ASSIGNMENT, {contextType: STATIC_GETTER}] # ------------------------------------------------------------------------------ # contextType - assignment # ------------------------------------------------------------------------------ # Do not error if contextType correctly defined - assignment code: ''' class MyComponent extends React.Component render: -> return null MyComponent.contextType = MyContext ''' options: [PROPERTY_ASSIGNMENT] , # Do not error if contextType correctly defined - assignment code: ''' class MyComponent extends React.Component render: -> return null MyComponent.contextType = MyContext ''' options: [STATIC_PUBLIC_FIELD, {contextType: PROPERTY_ASSIGNMENT}] , # ------------------------------------------------------------------------------ # displayName - static field # ------------------------------------------------------------------------------ # Do not error if displayName correctly defined - static field code: ''' class MyComponent extends React.Component @displayName = "Hello" ''' , # Do not error if displayName correctly defined - static field code: ''' class MyComponent extends React.Component @displayName = "Hello" ''' options: [PROPERTY_ASSIGNMENT, {displayName: STATIC_PUBLIC_FIELD}] , # ------------------------------------------------------------------------------ # displayName - static getter # ------------------------------------------------------------------------------ # Do not error if displayName correctly defined - static getter # code: [ # ''' # class MyComponent extends React.Component { # static get displayName() { # return \"Hello\"; # } # } # ''' # ].join '\n' # options: [STATIC_GETTER] # , # # Do not error if contextTypes correctly defined - static getter # code: [ # ''' # class MyComponent extends React.Component { # static get displayName() { # return \"Hello\"; # } # } # ''' # ].join '\n' # options: [PROPERTY_ASSIGNMENT, {displayName: STATIC_GETTER}] # ------------------------------------------------------------------------------ # displayName - assignment # ------------------------------------------------------------------------------ # Do not error if displayName correctly defined - assignment code: ''' class MyComponent extends React.Component render: -> return null MyComponent.displayName = "Hello" ''' options: [PROPERTY_ASSIGNMENT] , # Do not error if displayName correctly defined - assignment code: ''' class MyComponent extends React.Component render: -> return null MyComponent.displayName = "Hello" ''' options: [STATIC_PUBLIC_FIELD, {displayName: PROPERTY_ASSIGNMENT}] , # ------------------------------------------------------------------------------ # defaultProps - static field # ------------------------------------------------------------------------------ # Do not error if defaultProps correctly defined - static field code: ''' class MyComponent extends React.Component @defaultProps = { something: 'Bob' } ''' , # Do not error if defaultProps correctly defined - static field code: ''' class MyComponent extends React.Component @defaultProps = something: 'Bob' ''' options: [PROPERTY_ASSIGNMENT, {defaultProps: STATIC_PUBLIC_FIELD}] , # , # # ------------------------------------------------------------------------------ # # defaultProps - static getter # # ------------------------------------------------------------------------------ # # Do not error if defaultProps correctly defined - static getter # code: [ # ''' # class MyComponent extends React.Component { # static get defaultProps() { # return { # something: 'Bob' # }; # } # } # ''' # ].join '\n' # options: [STATIC_GETTER] # , # # Do not error if contextTypes correctly defined - static getter # code: [ # ''' # class MyComponent extends React.Component { # static get defaultProps() { # return { # something: 'Bob' # }; # } # } # ''' # ].join '\n' # options: [PROPERTY_ASSIGNMENT, {defaultProps: STATIC_GETTER}] # ------------------------------------------------------------------------------ # defaultProps - assignment # ------------------------------------------------------------------------------ # Do not error if defaultProps correctly defined - assignment code: ''' class MyComponent extends React.Component render: -> return null MyComponent.defaultProps = { name: 'Bob' } ''' options: [PROPERTY_ASSIGNMENT] , # Do not error if defaultProps correctly defined - assignment code: ''' class MyComponent extends React.Component render: -> return null MyComponent.defaultProps = { name: 'Bob' } ''' options: [STATIC_PUBLIC_FIELD, {defaultProps: PROPERTY_ASSIGNMENT}] , # ------------------------------------------------------------------------------ # propTypes - static field # ------------------------------------------------------------------------------ # Do not error if propTypes correctly defined - static field code: ''' class MyComponent extends React.Component @propTypes = { something: PropTypes.bool } ''' , # Do not error if propTypes correctly defined - static field code: ''' class MyComponent extends React.Component @propTypes = { something: PropTypes.bool } ''' options: [PROPERTY_ASSIGNMENT, {propTypes: STATIC_PUBLIC_FIELD}] , # , # # ------------------------------------------------------------------------------ # # propTypes - static getter # # ------------------------------------------------------------------------------ # # Do not error if propTypes correctly defined - static getter # code: [ # ''' # class MyComponent extends React.Component { # static get propTypes() { # return { # something: PropTypes.bool # }; # } # } # ''' # ].join '\n' # options: [STATIC_GETTER] # , # # Do not error if contextTypes correctly defined - static getter # code: [ # ''' # class MyComponent extends React.Component { # static get propTypes() { # return { # something: PropTypes.bool # }; # } # } # ''' # ].join '\n' # options: [PROPERTY_ASSIGNMENT, {propTypes: STATIC_GETTER}] # ------------------------------------------------------------------------------ # propTypes - assignment # ------------------------------------------------------------------------------ # Do not error if propTypes correctly defined - assignment code: ''' class MyComponent extends React.Component render: -> return null MyComponent.propTypes = { name: PropTypes.string.isRequired } ''' options: [PROPERTY_ASSIGNMENT] , # Do not error if propTypes correctly defined - assignment code: ''' class MyComponent extends React.Component render: -> return null MyComponent.propTypes = { name: PropTypes.string.isRequired } ''' options: [STATIC_PUBLIC_FIELD, {propTypes: PROPERTY_ASSIGNMENT}] , # ------------------------------------------------------------------------------ # multiple - static field # ------------------------------------------------------------------------------ # Do not error if multiple properties and match config - static field code: ''' class MyComponent extends React.Component @childContextTypes = { something: PropTypes.bool } @contextTypes = { something: PropTypes.bool } @contextType = MyContext @displayName = "Hello" @defaultProps = { something: 'Bob' } @propTypes = { something: PropTypes.bool } ''' , # Do not error if multiple properties and match config - static field code: ''' class MyComponent extends React.Component @childContextTypes = { something: PropTypes.bool } @contextTypes = { something: PropTypes.bool } @contextType = MyContext @displayName = "Hello" @defaultProps = { something: 'Bob' }; @propTypes = { something: PropTypes.bool } ''' options: [ PROPERTY_ASSIGNMENT , childContextTypes: STATIC_PUBLIC_FIELD contextTypes: STATIC_PUBLIC_FIELD contextType: STATIC_PUBLIC_FIELD displayName: STATIC_PUBLIC_FIELD defaultProps: STATIC_PUBLIC_FIELD propTypes: STATIC_PUBLIC_FIELD ] , # , # # ------------------------------------------------------------------------------ # # multiple - static getter # # ------------------------------------------------------------------------------ # # Do not error if childContextTypes correctly defined - static getter # code: [ # ''' # class MyComponent extends React.Component { # static get childContextTypes() { # return { # something: PropTypes.bool # }; # } # static get contextTypes() { # return { # something: PropTypes.bool # }; # } # static get contextType() { # return MyContext; # } # static get displayName() { # return \"Hello\"; # } # static get defaultProps() { # return { # something: PropTypes.bool # }; # } # static get propTypes() { # return { # something: PropTypes.bool # }; # } # } # ''' # ].join '\n' # options: [STATIC_GETTER] # , # # Do not error if contextTypes correctly defined - static getter # code: [ # ''' # class MyComponent extends React.Component { # static get childContextTypes() { # return { # something: PropTypes.bool # }; # } # static get contextTypes() { # return { # something: PropTypes.bool # }; # } # static get contextType() { # return MyContext; # } # static get displayName() { # return \"Hello\"; # } # static get defaultProps() { # return { # something: PropTypes.bool # }; # } # static get propTypes() { # return { # something: PropTypes.bool # }; # } # } # ''' # ].join '\n' # options: [ # PROPERTY_ASSIGNMENT # , # childContextTypes: STATIC_GETTER # contextTypes: STATIC_GETTER # contextType: STATIC_GETTER # displayName: STATIC_GETTER # defaultProps: STATIC_GETTER # propTypes: STATIC_GETTER # ] # ------------------------------------------------------------------------------ # multiple - assignment # ------------------------------------------------------------------------------ # Do not error if multiple properties and match config - assignment code: ''' class MyComponent extends React.Component render: -> return null MyComponent.childContextTypes = { name: PropTypes.string.isRequired } MyComponent.contextTypes = { name: PropTypes.string.isRequired } MyComponent.displayName = "Hello" MyComponent.defaultProps = { name: 'Bob' } MyComponent.propTypes = { name: PropTypes.string.isRequired } ''' options: [PROPERTY_ASSIGNMENT] , # Do not error if multiple properties and match config - static field code: ''' class MyComponent extends React.Component render: -> return null MyComponent.childContextTypes = { name: PropTypes.string.isRequired } MyComponent.contextTypes = { name: PropTypes.string.isRequired } MyComponent.displayName = "Hello" MyComponent.defaultProps = { name: 'Bob' } MyComponent.propTypes = { name: PropTypes.string.isRequired } ''' options: [ STATIC_PUBLIC_FIELD , childContextTypes: PROPERTY_ASSIGNMENT contextTypes: PROPERTY_ASSIGNMENT displayName: PROPERTY_ASSIGNMENT defaultProps: PROPERTY_ASSIGNMENT propTypes: PROPERTY_ASSIGNMENT ] , # ------------------------------------------------------------------------------ # combined - mixed # ------------------------------------------------------------------------------ # Do not error if mixed property positions and match config code: ''' class MyComponent extends React.Component @childContextTypes = name: PropTypes.string.isRequired @contextTypes = { name: PropTypes.string.isRequired } # static get displayName() { # return "Hello" # } MyComponent.defaultProps = { name: 'Bob' } MyComponent.propTypes = { name: PropTypes.string.isRequired } ''' options: [ STATIC_PUBLIC_FIELD , displayName: STATIC_GETTER defaultProps: PROPERTY_ASSIGNMENT propTypes: PROPERTY_ASSIGNMENT ] , # Do not error if mixed property positions and match config code: ''' class MyComponent extends React.Component @childContextTypes = { name: PropTypes.string.isRequired } @contextTypes = { name: PropTypes.string.isRequired } # static get displayName() { # return "Hello" # } MyComponent.defaultProps = { name: 'Bob' } MyComponent.propTypes = { name: PropTypes.string.isRequired } ''' options: [ PROPERTY_ASSIGNMENT , childContextTypes: STATIC_PUBLIC_FIELD contextTypes: STATIC_PUBLIC_FIELD displayName: STATIC_GETTER ] , # ------------------------------------------------------------------------------ # mixed component types # ------------------------------------------------------------------------------ # SFC ignored and component is valid code: ''' class MyComponent extends React.Component @childContextTypes = { name: PropTypes.string.isRequired } @contextTypes = { name: PropTypes.string.isRequired } @displayName = "Hello" OtherComponent = () => (<div>Hello</div>) OtherComponent.defaultProps = { name: 'Bob' } OtherComponent.propTypes = { name: PropTypes.string.isRequired } ''' , # Multiple components validated code: ''' class MyComponent extends React.Component @childContextTypes = { name: PropTypes.string.isRequired } @contextTypes = { name: PropTypes.string.isRequired } @displayName = "Hello" class OtherComponent extends React.Component @defaultProps = { name: 'Bob' } @propTypes = { name: PropTypes.string.isRequired } ''' , # ------------------------------------------------------------------------------ # edge cases # ------------------------------------------------------------------------------ # Do not error if property assignment is inside a class function code: ''' class MyComponent extends React.Component @displayName = "Hello" myMethod: -> console.log(MyComponent.displayName) ''' options: [STATIC_PUBLIC_FIELD] , # Do not error if display name value changed code: ''' class MyComponent extends React.Component @displayName = "Hello" myMethod: -> MyComponent.displayName = "Bonjour" ''' options: [STATIC_PUBLIC_FIELD] ] invalid: [ # ------------------------------------------------------------------------------ # expected static field when got property assigment # ------------------------------------------------------------------------------ # Error if multiple properties are incorrectly positioned according to config code: ''' class MyComponent extends React.Component render: -> return null MyComponent.childContextTypes = { name: PropTypes.string.isRequired } MyComponent.contextTypes = { name: PropTypes.string.isRequired } MyComponent.contextType = MyContext MyComponent.displayName = "Hello" MyComponent.defaultProps = { name: 'Bob' } MyComponent.propTypes = { name: PropTypes.string.isRequired } ''' errors: [ message: "'childContextTypes' should be declared as a static class property." , message: "'contextTypes' should be declared as a static class property." , message: "'contextType' should be declared as a static class property." , message: "'displayName' should be declared as a static class property." , message: "'defaultProps' should be declared as a static class property." , message: "'propTypes' should be declared as a static class property." ] , # Error if multiple properties are incorrectly positioned according to config code: ''' class MyComponent extends React.Component render: -> return null MyComponent.childContextTypes = { name: PropTypes.string.isRequired } MyComponent.contextTypes = { name: PropTypes.string.isRequired } MyComponent.contextType = MyContext MyComponent.displayName = "Hello" MyComponent.defaultProps = { name: 'Bob' } MyComponent.propTypes = { name: PropTypes.string.isRequired } ''' options: [ PROPERTY_ASSIGNMENT , childContextTypes: STATIC_PUBLIC_FIELD contextTypes: STATIC_PUBLIC_FIELD contextType: STATIC_PUBLIC_FIELD displayName: STATIC_PUBLIC_FIELD defaultProps: STATIC_PUBLIC_FIELD propTypes: STATIC_PUBLIC_FIELD ] errors: [ message: "'childContextTypes' should be declared as a static class property." , message: "'contextTypes' should be declared as a static class property." , message: "'contextType' should be declared as a static class property." , message: "'displayName' should be declared as a static class property." , message: "'defaultProps' should be declared as a static class property." , message: "'propTypes' should be declared as a static class property." ] , , # # ------------------------------------------------------------------------------ # # expected static field when got static getter # # ------------------------------------------------------------------------------ # # Error if multiple properties are incorrectly positioned according to config # code: [ # ''' # class MyComponent extends React.Component { # static get childContextTypes() { # return { # something: PropTypes.bool # }; # } # static get contextTypes() { # return { # something: PropTypes.bool # }; # } # static get contextType() { # return MyContext; # } # static get displayName() { # return \"Hello\"; # } # static get defaultProps() { # return { # something: PropTypes.bool # }; # } # static get propTypes() { # return { # something: PropTypes.bool # }; # } # } # ''' # ].join '\n' # errors: [ # message: # "'childContextTypes' should be declared as a static class property." # , # message: "'contextTypes' should be declared as a static class property." # , # message: "'contextType' should be declared as a static class property." # , # message: "'displayName' should be declared as a static class property." # , # message: "'defaultProps' should be declared as a static class property." # , # message: "'propTypes' should be declared as a static class property." # ] # , # # Error if multiple properties are incorrectly positioned according to config # code: [ # ''' # class MyComponent extends React.Component { # static get childContextTypes() { # return { # something: PropTypes.bool # }; # } # static get contextTypes() { # return { # something: PropTypes.bool # }; # } # static get contextType() { # return MyContext; # } # static get displayName() { # return \"Hello\"; # } # static get defaultProps() { # return { # something: PropTypes.bool # }; # } # static get propTypes() { # return { # something: PropTypes.bool # }; # } # } # ''' # ].join '\n' # options: [ # PROPERTY_ASSIGNMENT # , # childContextTypes: STATIC_PUBLIC_FIELD # contextTypes: STATIC_PUBLIC_FIELD # contextType: STATIC_PUBLIC_FIELD # displayName: STATIC_PUBLIC_FIELD # defaultProps: STATIC_PUBLIC_FIELD # propTypes: STATIC_PUBLIC_FIELD # ] # errors: [ # message: # "'childContextTypes' should be declared as a static class property." # , # message: "'contextTypes' should be declared as a static class property." # , # message: "'contextType' should be declared as a static class property." # , # message: "'displayName' should be declared as a static class property." # , # message: "'defaultProps' should be declared as a static class property." # , # message: "'propTypes' should be declared as a static class property." # ] # ------------------------------------------------------------------------------ # expected property assignment when got static field # ------------------------------------------------------------------------------ # Error if multiple properties are incorrectly positioned according to config code: ''' class MyComponent extends React.Component @childContextTypes = { something: PropTypes.bool } @contextTypes = { something: PropTypes.bool } @contextType = MyContext @displayName = "Hello" @defaultProps = { something: 'Bob' } @propTypes = { something: PropTypes.bool } ''' options: [PROPERTY_ASSIGNMENT] errors: [ message: "'childContextTypes' should be declared outside the class body." , message: "'contextTypes' should be declared outside the class body." , message: "'contextType' should be declared outside the class body." , message: "'displayName' should be declared outside the class body." , message: "'defaultProps' should be declared outside the class body." , message: "'propTypes' should be declared outside the class body." ] , # Error if multiple properties are incorrectly positioned according to config code: ''' class MyComponent extends React.Component @childContextTypes = { something: PropTypes.bool } @contextTypes = { something: PropTypes.bool } @contextType = MyContext @displayName = "Hello" @defaultProps = { something: 'Bob' } @propTypes = { something: PropTypes.bool } ''' options: [ STATIC_PUBLIC_FIELD , childContextTypes: PROPERTY_ASSIGNMENT contextTypes: PROPERTY_ASSIGNMENT contextType: PROPERTY_ASSIGNMENT displayName: PROPERTY_ASSIGNMENT defaultProps: PROPERTY_ASSIGNMENT propTypes: PROPERTY_ASSIGNMENT ] errors: [ message: "'childContextTypes' should be declared outside the class body." , message: "'contextTypes' should be declared outside the class body." , message: "'contextType' should be declared outside the class body." , message: "'displayName' should be declared outside the class body." , message: "'defaultProps' should be declared outside the class body." , message: "'propTypes' should be declared outside the class body." ] , # # ------------------------------------------------------------------------------ # # expected property assignment when got static getter # # ------------------------------------------------------------------------------ # # Error if multiple properties are incorrectly positioned according to config # code: [ # ''' # class MyComponent extends React.Component { # static get childContextTypes() { # return { # something: PropTypes.bool # }; # } # static get contextTypes() { # return { # something: PropTypes.bool # }; # } # static get contextType() { # return MyContext; # } # static get displayName() { # return \"Hello\"; # } # static get defaultProps() { # return { # something: PropTypes.bool # }; # } # static get propTypes() { # return { # something: PropTypes.bool # }; # } # } # ''' # ].join '\n' # options: [PROPERTY_ASSIGNMENT] # errors: [ # message: "'childContextTypes' should be declared outside the class body." # , # message: "'contextTypes' should be declared outside the class body." # , # message: "'contextType' should be declared outside the class body." # , # message: "'displayName' should be declared outside the class body." # , # message: "'defaultProps' should be declared outside the class body." # , # message: "'propTypes' should be declared outside the class body." # ] # , # # Error if multiple properties are incorrectly positioned according to config # code: [ # ''' # class MyComponent extends React.Component { # static get childContextTypes() { # return { # something: PropTypes.bool # }; # } # static get contextTypes() { # return { # something: PropTypes.bool # }; # } # static get contextType() { # return MyContext; # } # static get displayName() { # return \"Hello\"; # } # static get defaultProps() { # return { # something: PropTypes.bool # }; # } # static get propTypes() { # return { # something: PropTypes.bool # }; # } # } # ''' # ].join '\n' # options: [ # STATIC_GETTER # , # childContextTypes: PROPERTY_ASSIGNMENT # contextTypes: PROPERTY_ASSIGNMENT # contextType: PROPERTY_ASSIGNMENT # displayName: PROPERTY_ASSIGNMENT # defaultProps: PROPERTY_ASSIGNMENT # propTypes: PROPERTY_ASSIGNMENT # ] # errors: [ # message: "'childContextTypes' should be declared outside the class body." # , # message: "'contextTypes' should be declared outside the class body." # , # message: "'contextType' should be declared outside the class body." # , # message: "'displayName' should be declared outside the class body." # , # message: "'defaultProps' should be declared outside the class body." # , # message: "'propTypes' should be declared outside the class body." # ] # , # ------------------------------------------------------------------------------ # expected static getter when got static field # ------------------------------------------------------------------------------ # Error if multiple properties are incorrectly positioned according to config code: ''' class MyComponent extends React.Component @childContextTypes = { something: PropTypes.bool } @contextTypes = { something: PropTypes.bool } @contextType = MyContext @displayName = "Hello" @defaultProps = { something: 'Bob' }; @propTypes = { something: PropTypes.bool } ''' options: [STATIC_GETTER] errors: [ message: "'childContextTypes' should be declared as a static getter class function." , message: "'contextTypes' should be declared as a static getter class function." , message: "'contextType' should be declared as a static getter class function." , message: "'displayName' should be declared as a static getter class function." , message: "'defaultProps' should be declared as a static getter class function." , message: "'propTypes' should be declared as a static getter class function." ] , # Error if multiple properties are incorrectly positioned according to config code: ''' class MyComponent extends React.Component @childContextTypes = { something: PropTypes.bool } @contextTypes = { something: PropTypes.bool } @contextType = MyContext @displayName = "Hello" @defaultProps = { something: 'Bob' } @propTypes = { something: PropTypes.bool } ''' options: [ STATIC_PUBLIC_FIELD , childContextTypes: STATIC_GETTER contextTypes: STATIC_GETTER contextType: STATIC_GETTER displayName: STATIC_GETTER defaultProps: STATIC_GETTER propTypes: STATIC_GETTER ] errors: [ message: "'childContextTypes' should be declared as a static getter class function." , message: "'contextTypes' should be declared as a static getter class function." , message: "'contextType' should be declared as a static getter class function." , message: "'displayName' should be declared as a static getter class function." , message: "'defaultProps' should be declared as a static getter class function." , message: "'propTypes' should be declared as a static getter class function." ] , # ------------------------------------------------------------------------------ # expected static getter when got property assignment # ------------------------------------------------------------------------------ # Error if multiple properties are incorrectly positioned according to config code: ''' class MyComponent extends React.Component render: -> return null MyComponent.childContextTypes = name: PropTypes.string.isRequired MyComponent.contextTypes = name: PropTypes.string.isRequired MyComponent.contextType = MyContext MyComponent.displayName = "Hello" MyComponent.defaultProps = { name: 'Bob' } MyComponent.propTypes = { name: PropTypes.string.isRequired } ''' options: [STATIC_GETTER] errors: [ message: "'childContextTypes' should be declared as a static getter class function." , message: "'contextTypes' should be declared as a static getter class function." , message: "'contextType' should be declared as a static getter class function." , message: "'displayName' should be declared as a static getter class function." , message: "'defaultProps' should be declared as a static getter class function." , message: "'propTypes' should be declared as a static getter class function." ] , # Error if multiple properties are incorrectly positioned according to config code: ''' class MyComponent extends React.Component render: -> return null MyComponent.childContextTypes = { name: PropTypes.string.isRequired } MyComponent.contextTypes = { name: PropTypes.string.isRequired } MyComponent.contextType = MyContext MyComponent.displayName = "Hello" MyComponent.defaultProps = { name: 'Bob' } MyComponent.propTypes = { name: PropTypes.string.isRequired } ''' options: [ PROPERTY_ASSIGNMENT , childContextTypes: STATIC_GETTER contextTypes: STATIC_GETTER contextType: STATIC_GETTER displayName: STATIC_GETTER defaultProps: STATIC_GETTER propTypes: STATIC_GETTER ] errors: [ message: "'childContextTypes' should be declared as a static getter class function." , message: "'contextTypes' should be declared as a static getter class function." , message: "'contextType' should be declared as a static getter class function." , message: "'displayName' should be declared as a static getter class function." , message: "'defaultProps' should be declared as a static getter class function." , message: "'propTypes' should be declared as a static getter class function." ] , # ------------------------------------------------------------------------------ # combined - mixed # ------------------------------------------------------------------------------ # Error if mixed property positions but dont match config code: ''' class MyComponent extends React.Component @childContextTypes = { name: PropTypes.string.isRequired } @contextTypes = { name: PropTypes.string.isRequired } @contextType = MyContext # @get displayName() { # return "Hello"; # } MyComponent.defaultProps = { name: 'Bob' } MyComponent.propTypes = { name: PropTypes.string.isRequired } ''' options: [ PROPERTY_ASSIGNMENT , defaultProps: STATIC_GETTER propTypes: STATIC_PUBLIC_FIELD displayName: STATIC_PUBLIC_FIELD ] errors: [ message: "'childContextTypes' should be declared outside the class body." , message: "'contextTypes' should be declared outside the class body." , message: "'contextType' should be declared outside the class body." , # , # message: "'displayName' should be declared as a static class property." message: "'defaultProps' should be declared as a static getter class function." , message: "'propTypes' should be declared as a static class property." ] , # Error if mixed property positions but dont match config code: ''' class MyComponent extends React.Component @childContextTypes = { name: PropTypes.string.isRequired } @contextTypes = { name: PropTypes.string.isRequired } @contextType = MyContext # @get displayName() { # return "Hello"; # } MyComponent.defaultProps = { name: 'Bob' } MyComponent.propTypes = { name: PropTypes.string.isRequired } ''' options: [ STATIC_GETTER , childContextTypes: PROPERTY_ASSIGNMENT contextTypes: PROPERTY_ASSIGNMENT contextType: PROPERTY_ASSIGNMENT displayName: PROPERTY_ASSIGNMENT ] errors: [ message: "'childContextTypes' should be declared outside the class body." , message: "'contextTypes' should be declared outside the class body." , message: "'contextType' should be declared outside the class body." , # , # message: "'displayName' should be declared outside the class body." message: "'defaultProps' should be declared as a static getter class function." , message: "'propTypes' should be declared as a static getter class function." ] , # ------------------------------------------------------------------------------ # mixed component types # ------------------------------------------------------------------------------ # SFC ignored and component is invalid code: ''' class MyComponent extends React.Component @childContextTypes = { name: PropTypes.string.isRequired } @contextTypes = { name: PropTypes.string.isRequired } @contextType = MyContext # @get displayName() { # return "Hello"; # } OtherComponent = () => (<div>Hello</div>) OtherComponent.defaultProps = { name: 'Bob' } OtherComponent.propTypes = { name: PropTypes.string.isRequired } ''' options: [ PROPERTY_ASSIGNMENT , defaultProps: STATIC_PUBLIC_FIELD propTypes: STATIC_GETTER ] errors: [ message: "'childContextTypes' should be declared outside the class body." , message: "'contextTypes' should be declared outside the class body." , message: "'contextType' should be declared outside the class body." # , # message: "'displayName' should be declared outside the class body." ] , # Multiple components validated code: ''' class MyComponent extends React.Component @childContextTypes = { name: PropTypes.string.isRequired } @contextTypes = { name: PropTypes.string.isRequired } @contextType = MyContext @displayName = "Hello" class OtherComponent extends React.Component @contextTypes = { name: PropTypes.string.isRequired } @defaultProps = { name: 'Bob' } @propTypes: { name: PropTypes.string.isRequired } # static get displayName() { # return "Hello" # } ''' options: [PROPERTY_ASSIGNMENT] errors: [ message: "'childContextTypes' should be declared outside the class body." , message: "'contextTypes' should be declared outside the class body." , message: "'contextType' should be declared outside the class body." , message: "'displayName' should be declared outside the class body." , message: "'contextTypes' should be declared outside the class body." , message: "'defaultProps' should be declared outside the class body." , message: "'propTypes' should be declared outside the class body." # , # message: "'displayName' should be declared outside the class body." ] ]
215901
###* # @fileoverview Defines where React component static properties should be positioned. # @author <NAME> ### 'use strict' # ------------------------------------------------------------------------------ # Positioning Options # ------------------------------------------------------------------------------ STATIC_PUBLIC_FIELD = 'static public field' STATIC_GETTER = 'static getter' PROPERTY_ASSIGNMENT = 'property assignment' # ------------------------------------------------------------------------------ # Requirements # ------------------------------------------------------------------------------ path = require 'path' {RuleTester} = require 'eslint' rule = require 'eslint-plugin-react/lib/rules/static-property-placement' # parsers = require 'eslint-plugin-react/tests/helpers/parsers' ruleTesterConfig = # parser: parsers.BABEL_ESLINT # parserOptions: # ecmaVersion: 2018 # sourceType: 'module' # ecmaFeatures: # jsx: yes settings: react: version: '15' # ------------------------------------------------------------------------------ # Tests # ------------------------------------------------------------------------------ ruleTester = new RuleTester { ...ruleTesterConfig parser: path.join __dirname, '../../..' } ruleTester.run 'static-property-placement', rule, valid: [ # ------------------------------------------------------------------------------ # Ignore creatClass/createReactClass and Static Functional Components # ------------------------------------------------------------------------------ # Do not error on createReactClass pragma code: [ ''' MyComponent = createReactClass({ childContextTypes: { something: PropTypes.bool }, contextTypes: { something: PropTypes.bool }, getDefaultProps: -> name: '<NAME>' displayName: 'Hello', propTypes: { something: PropTypes.bool }, render: -> return null }) ''' ].join '\n' options: [PROPERTY_ASSIGNMENT] , # Do not error on createClass pragma code: ''' MyComponent = React.createClass({ childContextTypes: { something: PropTypes.bool }, contextTypes: { something: PropTypes.bool }, getDefaultProps: -> name: '<NAME>' displayName: 'Hello', propTypes: { something: PropTypes.bool }, render: -> return null }) ''' options: [PROPERTY_ASSIGNMENT] , # Do not error on SFC arrow function with return code: ''' MyComponent = () => return <div>Hello</div> MyComponent.childContextTypes = { something: PropTypes.bool } MyComponent.contextTypes = { something: PropTypes.bool } MyComponent.defaultProps = { something: '<NAME>' } MyComponent.displayName = 'Hello' MyComponent.propTypes = { something: PropTypes.bool } ''' , # Do not error on SFC arrow function with direct return code: ''' MyComponent = () => (<div>Hello</div>) MyComponent.childContextTypes = { something: PropTypes.bool } MyComponent.contextTypes = { something: PropTypes.bool } MyComponent.defaultProps = { something: '<NAME>' } MyComponent.displayName = 'Hello' MyComponent.propTypes = { something: PropTypes.bool } ''' , # Do not error on SFC as unnamed function code: ''' export MyComponent = -> return <div>Hello</div> MyComponent.childContextTypes = { something: PropTypes.bool } MyComponent.contextTypes = { something: PropTypes.bool } MyComponent.defaultProps = { something: '<NAME>' } MyComponent.displayName = 'Hello' MyComponent.propTypes = { something: PropTypes.bool } ''' , # ------------------------------------------------------------------------------ # no properties # ------------------------------------------------------------------------------ # Do not error if no properties defined code: ''' class MyComponent extends React.Component render: -> return null ''' , # Do not error if unchecked properties defined code: ''' class MyComponent extends React.Component @randomlyNamed = name: '<NAME>' ''' , # Do not error if unchecked static properties defined and assignment rule enabled code: ''' class MyComponent extends React.Component @randomlyNamed = name: '<NAME>' ''' options: [PROPERTY_ASSIGNMENT] , # Do not error if unchecked assignment properties defined and assignment rule enabled code: ''' class MyComponent extends React.Component render: -> return null MyComponent.randomlyNamed = name: '<NAME>' ''' options: [PROPERTY_ASSIGNMENT] , # Do not error if unchecked assignment properties defined and static rule enabled code: ''' class MyComponent extends React.Component render: -> return null MyComponent.randomlyNamed = name: '<NAME>' ''' , # ------------------------------------------------------------------------------ # childContextTypes - static field # ------------------------------------------------------------------------------ # Do not error if childContextTypes correctly defined - static field code: ''' class MyComponent extends React.Component @childContextTypes = something: PropTypes.bool ''' , # Do not error if childContextTypes correctly defined - static field code: ''' class MyComponent extends React.Component @childContextTypes: something: PropTypes.bool ''' options: [PROPERTY_ASSIGNMENT, {childContextTypes: STATIC_PUBLIC_FIELD}] , # , # # ------------------------------------------------------------------------------ # # childContextTypes - static getter # # ------------------------------------------------------------------------------ # # Do not error if childContextTypes correctly defined - static getter # code: [ # ''' # class MyComponent extends React.Component { # static get childContextTypes() { # return { # something: PropTypes.bool # }; # } # } # ''' # ].join '\n' # options: [STATIC_GETTER] # , # # Do not error if contextTypes correctly defined - static getter # code: [ # ''' # class MyComponent extends React.Component { # static get childContextTypes() { # return { # something: PropTypes.bool # }; # } # } # ''' # ].join '\n' # options: [PROPERTY_ASSIGNMENT, {childContextTypes: STATIC_GETTER}] # ------------------------------------------------------------------------------ # childContextTypes - assignment # ------------------------------------------------------------------------------ # Do not error if childContextTypes correctly defined - assignment code: ''' class MyComponent extends React.Component render: -> return null MyComponent.childContextTypes = name: PropTypes.string.isRequired ''' options: [PROPERTY_ASSIGNMENT] , # Do not error if childContextTypes correctly defined - assignment code: ''' class MyComponent extends React.Component render: -> return null MyComponent.childContextTypes = { name: PropTypes.string.isRequired } ''' options: [STATIC_PUBLIC_FIELD, {childContextTypes: PROPERTY_ASSIGNMENT}] , # ------------------------------------------------------------------------------ # contextTypes - static field # ------------------------------------------------------------------------------ # Do not error if contextTypes correctly defined - static field code: ''' class MyComponent extends React.Component @contextTypes = { something: PropTypes.bool } ''' , # Do not error if contextTypes correctly defined - static field code: ''' class MyComponent extends React.Component @contextTypes = something: PropTypes.bool ''' options: [PROPERTY_ASSIGNMENT, {contextTypes: STATIC_PUBLIC_FIELD}] , # , # # ------------------------------------------------------------------------------ # # contextTypes - static getter # # ------------------------------------------------------------------------------ # # Do not error if contextTypes correctly defined - static getter # code: [ # ''' # class MyComponent extends React.Component { # static get contextTypes() { # return { # something: PropTypes.bool # }; # } # } # ''' # ].join '\n' # options: [STATIC_GETTER] # , # # Do not error if contextTypes correctly defined - static getter # code: [ # ''' # class MyComponent extends React.Component { # static get contextTypes() { # return { # something: PropTypes.bool # }; # } # } # ''' # ].join '\n' # options: [PROPERTY_ASSIGNMENT, {contextTypes: STATIC_GETTER}] # ------------------------------------------------------------------------------ # contextTypes - assignment # ------------------------------------------------------------------------------ # Do not error if contextTypes correctly defined - assignment code: ''' class MyComponent extends React.Component render: -> return null MyComponent.contextTypes = { name: PropTypes.string.isRequired } ''' options: [PROPERTY_ASSIGNMENT] , # Do not error if contextTypes correctly defined - assignment code: ''' class MyComponent extends React.Component render: -> return null MyComponent.contextTypes = { name: PropTypes.string.isRequired } ''' options: [STATIC_PUBLIC_FIELD, {contextTypes: PROPERTY_ASSIGNMENT}] , # ------------------------------------------------------------------------------ # contextType - static field # ------------------------------------------------------------------------------ # Do not error if contextType correctly defined - static field code: ''' class MyComponent extends React.Component @contextType = MyContext ''' , # Do not error if contextType correctly defined - static field code: ''' class MyComponent extends React.Component @contextType = MyContext ''' options: [PROPERTY_ASSIGNMENT, {contextType: STATIC_PUBLIC_FIELD}] , # , # # ------------------------------------------------------------------------------ # # contextType - static getter # # ------------------------------------------------------------------------------ # # Do not error if contextType correctly defined - static field # code: [ # ''' # class MyComponent extends React.Component { # static get contextType() { # return MyContext; # } # } # ''' # ].join '\n' # options: [STATIC_GETTER] # , # # Do not error if contextType correctly defined - static field # code: [ # ''' # class MyComponent extends React.Component { # static get contextType() { # return MyContext; # } # } # ''' # ].join '\n' # options: [PROPERTY_ASSIGNMENT, {contextType: STATIC_GETTER}] # ------------------------------------------------------------------------------ # contextType - assignment # ------------------------------------------------------------------------------ # Do not error if contextType correctly defined - assignment code: ''' class MyComponent extends React.Component render: -> return null MyComponent.contextType = MyContext ''' options: [PROPERTY_ASSIGNMENT] , # Do not error if contextType correctly defined - assignment code: ''' class MyComponent extends React.Component render: -> return null MyComponent.contextType = MyContext ''' options: [STATIC_PUBLIC_FIELD, {contextType: PROPERTY_ASSIGNMENT}] , # ------------------------------------------------------------------------------ # displayName - static field # ------------------------------------------------------------------------------ # Do not error if displayName correctly defined - static field code: ''' class MyComponent extends React.Component @displayName = "Hello" ''' , # Do not error if displayName correctly defined - static field code: ''' class MyComponent extends React.Component @displayName = "Hello" ''' options: [PROPERTY_ASSIGNMENT, {displayName: STATIC_PUBLIC_FIELD}] , # ------------------------------------------------------------------------------ # displayName - static getter # ------------------------------------------------------------------------------ # Do not error if displayName correctly defined - static getter # code: [ # ''' # class MyComponent extends React.Component { # static get displayName() { # return \"Hello\"; # } # } # ''' # ].join '\n' # options: [STATIC_GETTER] # , # # Do not error if contextTypes correctly defined - static getter # code: [ # ''' # class MyComponent extends React.Component { # static get displayName() { # return \"Hello\"; # } # } # ''' # ].join '\n' # options: [PROPERTY_ASSIGNMENT, {displayName: STATIC_GETTER}] # ------------------------------------------------------------------------------ # displayName - assignment # ------------------------------------------------------------------------------ # Do not error if displayName correctly defined - assignment code: ''' class MyComponent extends React.Component render: -> return null MyComponent.displayName = "<NAME>" ''' options: [PROPERTY_ASSIGNMENT] , # Do not error if displayName correctly defined - assignment code: ''' class MyComponent extends React.Component render: -> return null MyComponent.displayName = "<NAME>" ''' options: [STATIC_PUBLIC_FIELD, {displayName: PROPERTY_ASSIGNMENT}] , # ------------------------------------------------------------------------------ # defaultProps - static field # ------------------------------------------------------------------------------ # Do not error if defaultProps correctly defined - static field code: ''' class MyComponent extends React.Component @defaultProps = { something: '<NAME>' } ''' , # Do not error if defaultProps correctly defined - static field code: ''' class MyComponent extends React.Component @defaultProps = something: '<NAME>' ''' options: [PROPERTY_ASSIGNMENT, {defaultProps: STATIC_PUBLIC_FIELD}] , # , # # ------------------------------------------------------------------------------ # # defaultProps - static getter # # ------------------------------------------------------------------------------ # # Do not error if defaultProps correctly defined - static getter # code: [ # ''' # class MyComponent extends React.Component { # static get defaultProps() { # return { # something: '<NAME>' # }; # } # } # ''' # ].join '\n' # options: [STATIC_GETTER] # , # # Do not error if contextTypes correctly defined - static getter # code: [ # ''' # class MyComponent extends React.Component { # static get defaultProps() { # return { # something: '<NAME>' # }; # } # } # ''' # ].join '\n' # options: [PROPERTY_ASSIGNMENT, {defaultProps: STATIC_GETTER}] # ------------------------------------------------------------------------------ # defaultProps - assignment # ------------------------------------------------------------------------------ # Do not error if defaultProps correctly defined - assignment code: ''' class MyComponent extends React.Component render: -> return null MyComponent.defaultProps = { name: '<NAME>' } ''' options: [PROPERTY_ASSIGNMENT] , # Do not error if defaultProps correctly defined - assignment code: ''' class MyComponent extends React.Component render: -> return null MyComponent.defaultProps = { name: '<NAME>' } ''' options: [STATIC_PUBLIC_FIELD, {defaultProps: PROPERTY_ASSIGNMENT}] , # ------------------------------------------------------------------------------ # propTypes - static field # ------------------------------------------------------------------------------ # Do not error if propTypes correctly defined - static field code: ''' class MyComponent extends React.Component @propTypes = { something: PropTypes.bool } ''' , # Do not error if propTypes correctly defined - static field code: ''' class MyComponent extends React.Component @propTypes = { something: PropTypes.bool } ''' options: [PROPERTY_ASSIGNMENT, {propTypes: STATIC_PUBLIC_FIELD}] , # , # # ------------------------------------------------------------------------------ # # propTypes - static getter # # ------------------------------------------------------------------------------ # # Do not error if propTypes correctly defined - static getter # code: [ # ''' # class MyComponent extends React.Component { # static get propTypes() { # return { # something: PropTypes.bool # }; # } # } # ''' # ].join '\n' # options: [STATIC_GETTER] # , # # Do not error if contextTypes correctly defined - static getter # code: [ # ''' # class MyComponent extends React.Component { # static get propTypes() { # return { # something: PropTypes.bool # }; # } # } # ''' # ].join '\n' # options: [PROPERTY_ASSIGNMENT, {propTypes: STATIC_GETTER}] # ------------------------------------------------------------------------------ # propTypes - assignment # ------------------------------------------------------------------------------ # Do not error if propTypes correctly defined - assignment code: ''' class MyComponent extends React.Component render: -> return null MyComponent.propTypes = { name: PropTypes.string.isRequired } ''' options: [PROPERTY_ASSIGNMENT] , # Do not error if propTypes correctly defined - assignment code: ''' class MyComponent extends React.Component render: -> return null MyComponent.propTypes = { name: PropTypes.string.isRequired } ''' options: [STATIC_PUBLIC_FIELD, {propTypes: PROPERTY_ASSIGNMENT}] , # ------------------------------------------------------------------------------ # multiple - static field # ------------------------------------------------------------------------------ # Do not error if multiple properties and match config - static field code: ''' class MyComponent extends React.Component @childContextTypes = { something: PropTypes.bool } @contextTypes = { something: PropTypes.bool } @contextType = MyContext @displayName = "Hello" @defaultProps = { something: '<NAME>' } @propTypes = { something: PropTypes.bool } ''' , # Do not error if multiple properties and match config - static field code: ''' class MyComponent extends React.Component @childContextTypes = { something: PropTypes.bool } @contextTypes = { something: PropTypes.bool } @contextType = MyContext @displayName = "Hello" @defaultProps = { something: '<NAME>' }; @propTypes = { something: PropTypes.bool } ''' options: [ PROPERTY_ASSIGNMENT , childContextTypes: STATIC_PUBLIC_FIELD contextTypes: STATIC_PUBLIC_FIELD contextType: STATIC_PUBLIC_FIELD displayName: STATIC_PUBLIC_FIELD defaultProps: STATIC_PUBLIC_FIELD propTypes: STATIC_PUBLIC_FIELD ] , # , # # ------------------------------------------------------------------------------ # # multiple - static getter # # ------------------------------------------------------------------------------ # # Do not error if childContextTypes correctly defined - static getter # code: [ # ''' # class MyComponent extends React.Component { # static get childContextTypes() { # return { # something: PropTypes.bool # }; # } # static get contextTypes() { # return { # something: PropTypes.bool # }; # } # static get contextType() { # return MyContext; # } # static get displayName() { # return \"Hello\"; # } # static get defaultProps() { # return { # something: PropTypes.bool # }; # } # static get propTypes() { # return { # something: PropTypes.bool # }; # } # } # ''' # ].join '\n' # options: [STATIC_GETTER] # , # # Do not error if contextTypes correctly defined - static getter # code: [ # ''' # class MyComponent extends React.Component { # static get childContextTypes() { # return { # something: PropTypes.bool # }; # } # static get contextTypes() { # return { # something: PropTypes.bool # }; # } # static get contextType() { # return MyContext; # } # static get displayName() { # return \"Hello\"; # } # static get defaultProps() { # return { # something: PropTypes.bool # }; # } # static get propTypes() { # return { # something: PropTypes.bool # }; # } # } # ''' # ].join '\n' # options: [ # PROPERTY_ASSIGNMENT # , # childContextTypes: STATIC_GETTER # contextTypes: STATIC_GETTER # contextType: STATIC_GETTER # displayName: STATIC_GETTER # defaultProps: STATIC_GETTER # propTypes: STATIC_GETTER # ] # ------------------------------------------------------------------------------ # multiple - assignment # ------------------------------------------------------------------------------ # Do not error if multiple properties and match config - assignment code: ''' class MyComponent extends React.Component render: -> return null MyComponent.childContextTypes = { name: PropTypes.string.isRequired } MyComponent.contextTypes = { name: PropTypes.string.isRequired } MyComponent.displayName = "Hello" MyComponent.defaultProps = { name: '<NAME>' } MyComponent.propTypes = { name: PropTypes.string.isRequired } ''' options: [PROPERTY_ASSIGNMENT] , # Do not error if multiple properties and match config - static field code: ''' class MyComponent extends React.Component render: -> return null MyComponent.childContextTypes = { name: PropTypes.string.isRequired } MyComponent.contextTypes = { name: PropTypes.string.isRequired } MyComponent.displayName = "Hello" MyComponent.defaultProps = { name: '<NAME>' } MyComponent.propTypes = { name: PropTypes.string.isRequired } ''' options: [ STATIC_PUBLIC_FIELD , childContextTypes: PROPERTY_ASSIGNMENT contextTypes: PROPERTY_ASSIGNMENT displayName: PROPERTY_ASSIGNMENT defaultProps: PROPERTY_ASSIGNMENT propTypes: PROPERTY_ASSIGNMENT ] , # ------------------------------------------------------------------------------ # combined - mixed # ------------------------------------------------------------------------------ # Do not error if mixed property positions and match config code: ''' class MyComponent extends React.Component @childContextTypes = name: PropTypes.string.isRequired @contextTypes = { name: PropTypes.string.isRequired } # static get displayName() { # return "Hello" # } MyComponent.defaultProps = { name: '<NAME>' } MyComponent.propTypes = { name: PropTypes.string.isRequired } ''' options: [ STATIC_PUBLIC_FIELD , displayName: STATIC_GETTER defaultProps: PROPERTY_ASSIGNMENT propTypes: PROPERTY_ASSIGNMENT ] , # Do not error if mixed property positions and match config code: ''' class MyComponent extends React.Component @childContextTypes = { name: PropTypes.string.isRequired } @contextTypes = { name: PropTypes.string.isRequired } # static get displayName() { # return "Hello" # } MyComponent.defaultProps = { name: '<NAME>' } MyComponent.propTypes = { name: PropTypes.string.isRequired } ''' options: [ PROPERTY_ASSIGNMENT , childContextTypes: STATIC_PUBLIC_FIELD contextTypes: STATIC_PUBLIC_FIELD displayName: STATIC_GETTER ] , # ------------------------------------------------------------------------------ # mixed component types # ------------------------------------------------------------------------------ # SFC ignored and component is valid code: ''' class MyComponent extends React.Component @childContextTypes = { name: PropTypes.string.isRequired } @contextTypes = { name: PropTypes.string.isRequired } @displayName = "Hello" OtherComponent = () => (<div>Hello</div>) OtherComponent.defaultProps = { name: '<NAME>' } OtherComponent.propTypes = { name: PropTypes.string.isRequired } ''' , # Multiple components validated code: ''' class MyComponent extends React.Component @childContextTypes = { name: PropTypes.string.isRequired } @contextTypes = { name: PropTypes.string.isRequired } @displayName = "Hello" class OtherComponent extends React.Component @defaultProps = { name: '<NAME>' } @propTypes = { name: PropTypes.string.isRequired } ''' , # ------------------------------------------------------------------------------ # edge cases # ------------------------------------------------------------------------------ # Do not error if property assignment is inside a class function code: ''' class MyComponent extends React.Component @displayName = "Hello" myMethod: -> console.log(MyComponent.displayName) ''' options: [STATIC_PUBLIC_FIELD] , # Do not error if display name value changed code: ''' class MyComponent extends React.Component @displayName = "Hello" myMethod: -> MyComponent.displayName = "Bonjour" ''' options: [STATIC_PUBLIC_FIELD] ] invalid: [ # ------------------------------------------------------------------------------ # expected static field when got property assigment # ------------------------------------------------------------------------------ # Error if multiple properties are incorrectly positioned according to config code: ''' class MyComponent extends React.Component render: -> return null MyComponent.childContextTypes = { name: PropTypes.string.isRequired } MyComponent.contextTypes = { name: PropTypes.string.isRequired } MyComponent.contextType = MyContext MyComponent.displayName = "Hello" MyComponent.defaultProps = { name: '<NAME>' } MyComponent.propTypes = { name: PropTypes.string.isRequired } ''' errors: [ message: "'childContextTypes' should be declared as a static class property." , message: "'contextTypes' should be declared as a static class property." , message: "'contextType' should be declared as a static class property." , message: "'displayName' should be declared as a static class property." , message: "'defaultProps' should be declared as a static class property." , message: "'propTypes' should be declared as a static class property." ] , # Error if multiple properties are incorrectly positioned according to config code: ''' class MyComponent extends React.Component render: -> return null MyComponent.childContextTypes = { name: PropTypes.string.isRequired } MyComponent.contextTypes = { name: PropTypes.string.isRequired } MyComponent.contextType = MyContext MyComponent.displayName = "Hello" MyComponent.defaultProps = { name: '<NAME>' } MyComponent.propTypes = { name: PropTypes.string.isRequired } ''' options: [ PROPERTY_ASSIGNMENT , childContextTypes: STATIC_PUBLIC_FIELD contextTypes: STATIC_PUBLIC_FIELD contextType: STATIC_PUBLIC_FIELD displayName: STATIC_PUBLIC_FIELD defaultProps: STATIC_PUBLIC_FIELD propTypes: STATIC_PUBLIC_FIELD ] errors: [ message: "'childContextTypes' should be declared as a static class property." , message: "'contextTypes' should be declared as a static class property." , message: "'contextType' should be declared as a static class property." , message: "'displayName' should be declared as a static class property." , message: "'defaultProps' should be declared as a static class property." , message: "'propTypes' should be declared as a static class property." ] , , # # ------------------------------------------------------------------------------ # # expected static field when got static getter # # ------------------------------------------------------------------------------ # # Error if multiple properties are incorrectly positioned according to config # code: [ # ''' # class MyComponent extends React.Component { # static get childContextTypes() { # return { # something: PropTypes.bool # }; # } # static get contextTypes() { # return { # something: PropTypes.bool # }; # } # static get contextType() { # return MyContext; # } # static get displayName() { # return \"Hello\"; # } # static get defaultProps() { # return { # something: PropTypes.bool # }; # } # static get propTypes() { # return { # something: PropTypes.bool # }; # } # } # ''' # ].join '\n' # errors: [ # message: # "'childContextTypes' should be declared as a static class property." # , # message: "'contextTypes' should be declared as a static class property." # , # message: "'contextType' should be declared as a static class property." # , # message: "'displayName' should be declared as a static class property." # , # message: "'defaultProps' should be declared as a static class property." # , # message: "'propTypes' should be declared as a static class property." # ] # , # # Error if multiple properties are incorrectly positioned according to config # code: [ # ''' # class MyComponent extends React.Component { # static get childContextTypes() { # return { # something: PropTypes.bool # }; # } # static get contextTypes() { # return { # something: PropTypes.bool # }; # } # static get contextType() { # return MyContext; # } # static get displayName() { # return \"Hello\"; # } # static get defaultProps() { # return { # something: PropTypes.bool # }; # } # static get propTypes() { # return { # something: PropTypes.bool # }; # } # } # ''' # ].join '\n' # options: [ # PROPERTY_ASSIGNMENT # , # childContextTypes: STATIC_PUBLIC_FIELD # contextTypes: STATIC_PUBLIC_FIELD # contextType: STATIC_PUBLIC_FIELD # displayName: STATIC_PUBLIC_FIELD # defaultProps: STATIC_PUBLIC_FIELD # propTypes: STATIC_PUBLIC_FIELD # ] # errors: [ # message: # "'childContextTypes' should be declared as a static class property." # , # message: "'contextTypes' should be declared as a static class property." # , # message: "'contextType' should be declared as a static class property." # , # message: "'displayName' should be declared as a static class property." # , # message: "'defaultProps' should be declared as a static class property." # , # message: "'propTypes' should be declared as a static class property." # ] # ------------------------------------------------------------------------------ # expected property assignment when got static field # ------------------------------------------------------------------------------ # Error if multiple properties are incorrectly positioned according to config code: ''' class MyComponent extends React.Component @childContextTypes = { something: PropTypes.bool } @contextTypes = { something: PropTypes.bool } @contextType = MyContext @displayName = "Hello" @defaultProps = { something: '<NAME>' } @propTypes = { something: PropTypes.bool } ''' options: [PROPERTY_ASSIGNMENT] errors: [ message: "'childContextTypes' should be declared outside the class body." , message: "'contextTypes' should be declared outside the class body." , message: "'contextType' should be declared outside the class body." , message: "'displayName' should be declared outside the class body." , message: "'defaultProps' should be declared outside the class body." , message: "'propTypes' should be declared outside the class body." ] , # Error if multiple properties are incorrectly positioned according to config code: ''' class MyComponent extends React.Component @childContextTypes = { something: PropTypes.bool } @contextTypes = { something: PropTypes.bool } @contextType = MyContext @displayName = "Hello" @defaultProps = { something: '<NAME>' } @propTypes = { something: PropTypes.bool } ''' options: [ STATIC_PUBLIC_FIELD , childContextTypes: PROPERTY_ASSIGNMENT contextTypes: PROPERTY_ASSIGNMENT contextType: PROPERTY_ASSIGNMENT displayName: PROPERTY_ASSIGNMENT defaultProps: PROPERTY_ASSIGNMENT propTypes: PROPERTY_ASSIGNMENT ] errors: [ message: "'childContextTypes' should be declared outside the class body." , message: "'contextTypes' should be declared outside the class body." , message: "'contextType' should be declared outside the class body." , message: "'displayName' should be declared outside the class body." , message: "'defaultProps' should be declared outside the class body." , message: "'propTypes' should be declared outside the class body." ] , # # ------------------------------------------------------------------------------ # # expected property assignment when got static getter # # ------------------------------------------------------------------------------ # # Error if multiple properties are incorrectly positioned according to config # code: [ # ''' # class MyComponent extends React.Component { # static get childContextTypes() { # return { # something: PropTypes.bool # }; # } # static get contextTypes() { # return { # something: PropTypes.bool # }; # } # static get contextType() { # return MyContext; # } # static get displayName() { # return \"Hello\"; # } # static get defaultProps() { # return { # something: PropTypes.bool # }; # } # static get propTypes() { # return { # something: PropTypes.bool # }; # } # } # ''' # ].join '\n' # options: [PROPERTY_ASSIGNMENT] # errors: [ # message: "'childContextTypes' should be declared outside the class body." # , # message: "'contextTypes' should be declared outside the class body." # , # message: "'contextType' should be declared outside the class body." # , # message: "'displayName' should be declared outside the class body." # , # message: "'defaultProps' should be declared outside the class body." # , # message: "'propTypes' should be declared outside the class body." # ] # , # # Error if multiple properties are incorrectly positioned according to config # code: [ # ''' # class MyComponent extends React.Component { # static get childContextTypes() { # return { # something: PropTypes.bool # }; # } # static get contextTypes() { # return { # something: PropTypes.bool # }; # } # static get contextType() { # return MyContext; # } # static get displayName() { # return \"Hello\"; # } # static get defaultProps() { # return { # something: PropTypes.bool # }; # } # static get propTypes() { # return { # something: PropTypes.bool # }; # } # } # ''' # ].join '\n' # options: [ # STATIC_GETTER # , # childContextTypes: PROPERTY_ASSIGNMENT # contextTypes: PROPERTY_ASSIGNMENT # contextType: PROPERTY_ASSIGNMENT # displayName: PROPERTY_ASSIGNMENT # defaultProps: PROPERTY_ASSIGNMENT # propTypes: PROPERTY_ASSIGNMENT # ] # errors: [ # message: "'childContextTypes' should be declared outside the class body." # , # message: "'contextTypes' should be declared outside the class body." # , # message: "'contextType' should be declared outside the class body." # , # message: "'displayName' should be declared outside the class body." # , # message: "'defaultProps' should be declared outside the class body." # , # message: "'propTypes' should be declared outside the class body." # ] # , # ------------------------------------------------------------------------------ # expected static getter when got static field # ------------------------------------------------------------------------------ # Error if multiple properties are incorrectly positioned according to config code: ''' class MyComponent extends React.Component @childContextTypes = { something: PropTypes.bool } @contextTypes = { something: PropTypes.bool } @contextType = MyContext @displayName = "Hello" @defaultProps = { something: '<NAME>' }; @propTypes = { something: PropTypes.bool } ''' options: [STATIC_GETTER] errors: [ message: "'childContextTypes' should be declared as a static getter class function." , message: "'contextTypes' should be declared as a static getter class function." , message: "'contextType' should be declared as a static getter class function." , message: "'displayName' should be declared as a static getter class function." , message: "'defaultProps' should be declared as a static getter class function." , message: "'propTypes' should be declared as a static getter class function." ] , # Error if multiple properties are incorrectly positioned according to config code: ''' class MyComponent extends React.Component @childContextTypes = { something: PropTypes.bool } @contextTypes = { something: PropTypes.bool } @contextType = MyContext @displayName = "Hello" @defaultProps = { something: '<NAME>' } @propTypes = { something: PropTypes.bool } ''' options: [ STATIC_PUBLIC_FIELD , childContextTypes: STATIC_GETTER contextTypes: STATIC_GETTER contextType: STATIC_GETTER displayName: STATIC_GETTER defaultProps: STATIC_GETTER propTypes: STATIC_GETTER ] errors: [ message: "'childContextTypes' should be declared as a static getter class function." , message: "'contextTypes' should be declared as a static getter class function." , message: "'contextType' should be declared as a static getter class function." , message: "'displayName' should be declared as a static getter class function." , message: "'defaultProps' should be declared as a static getter class function." , message: "'propTypes' should be declared as a static getter class function." ] , # ------------------------------------------------------------------------------ # expected static getter when got property assignment # ------------------------------------------------------------------------------ # Error if multiple properties are incorrectly positioned according to config code: ''' class MyComponent extends React.Component render: -> return null MyComponent.childContextTypes = name: PropTypes.string.isRequired MyComponent.contextTypes = name: PropTypes.string.isRequired MyComponent.contextType = MyContext MyComponent.displayName = "Hello" MyComponent.defaultProps = { name: '<NAME>' } MyComponent.propTypes = { name: PropTypes.string.isRequired } ''' options: [STATIC_GETTER] errors: [ message: "'childContextTypes' should be declared as a static getter class function." , message: "'contextTypes' should be declared as a static getter class function." , message: "'contextType' should be declared as a static getter class function." , message: "'displayName' should be declared as a static getter class function." , message: "'defaultProps' should be declared as a static getter class function." , message: "'propTypes' should be declared as a static getter class function." ] , # Error if multiple properties are incorrectly positioned according to config code: ''' class MyComponent extends React.Component render: -> return null MyComponent.childContextTypes = { name: PropTypes.string.isRequired } MyComponent.contextTypes = { name: PropTypes.string.isRequired } MyComponent.contextType = MyContext MyComponent.displayName = "Hello" MyComponent.defaultProps = { name: '<NAME>' } MyComponent.propTypes = { name: PropTypes.string.isRequired } ''' options: [ PROPERTY_ASSIGNMENT , childContextTypes: STATIC_GETTER contextTypes: STATIC_GETTER contextType: STATIC_GETTER displayName: STATIC_GETTER defaultProps: STATIC_GETTER propTypes: STATIC_GETTER ] errors: [ message: "'childContextTypes' should be declared as a static getter class function." , message: "'contextTypes' should be declared as a static getter class function." , message: "'contextType' should be declared as a static getter class function." , message: "'displayName' should be declared as a static getter class function." , message: "'defaultProps' should be declared as a static getter class function." , message: "'propTypes' should be declared as a static getter class function." ] , # ------------------------------------------------------------------------------ # combined - mixed # ------------------------------------------------------------------------------ # Error if mixed property positions but dont match config code: ''' class MyComponent extends React.Component @childContextTypes = { name: PropTypes.string.isRequired } @contextTypes = { name: PropTypes.string.isRequired } @contextType = MyContext # @get displayName() { # return "Hello"; # } MyComponent.defaultProps = { name: '<NAME>' } MyComponent.propTypes = { name: PropTypes.string.isRequired } ''' options: [ PROPERTY_ASSIGNMENT , defaultProps: STATIC_GETTER propTypes: STATIC_PUBLIC_FIELD displayName: STATIC_PUBLIC_FIELD ] errors: [ message: "'childContextTypes' should be declared outside the class body." , message: "'contextTypes' should be declared outside the class body." , message: "'contextType' should be declared outside the class body." , # , # message: "'displayName' should be declared as a static class property." message: "'defaultProps' should be declared as a static getter class function." , message: "'propTypes' should be declared as a static class property." ] , # Error if mixed property positions but dont match config code: ''' class MyComponent extends React.Component @childContextTypes = { name: PropTypes.string.isRequired } @contextTypes = { name: PropTypes.string.isRequired } @contextType = MyContext # @get displayName() { # return "Hello"; # } MyComponent.defaultProps = { name: '<NAME>' } MyComponent.propTypes = { name: PropTypes.string.isRequired } ''' options: [ STATIC_GETTER , childContextTypes: PROPERTY_ASSIGNMENT contextTypes: PROPERTY_ASSIGNMENT contextType: PROPERTY_ASSIGNMENT displayName: PROPERTY_ASSIGNMENT ] errors: [ message: "'childContextTypes' should be declared outside the class body." , message: "'contextTypes' should be declared outside the class body." , message: "'contextType' should be declared outside the class body." , # , # message: "'displayName' should be declared outside the class body." message: "'defaultProps' should be declared as a static getter class function." , message: "'propTypes' should be declared as a static getter class function." ] , # ------------------------------------------------------------------------------ # mixed component types # ------------------------------------------------------------------------------ # SFC ignored and component is invalid code: ''' class MyComponent extends React.Component @childContextTypes = { name: PropTypes.string.isRequired } @contextTypes = { name: PropTypes.string.isRequired } @contextType = MyContext # @get displayName() { # return "Hello"; # } OtherComponent = () => (<div>Hello</div>) OtherComponent.defaultProps = { name: '<NAME>' } OtherComponent.propTypes = { name: PropTypes.string.isRequired } ''' options: [ PROPERTY_ASSIGNMENT , defaultProps: STATIC_PUBLIC_FIELD propTypes: STATIC_GETTER ] errors: [ message: "'childContextTypes' should be declared outside the class body." , message: "'contextTypes' should be declared outside the class body." , message: "'contextType' should be declared outside the class body." # , # message: "'displayName' should be declared outside the class body." ] , # Multiple components validated code: ''' class MyComponent extends React.Component @childContextTypes = { name: PropTypes.string.isRequired } @contextTypes = { name: PropTypes.string.isRequired } @contextType = MyContext @displayName = "Hello" class OtherComponent extends React.Component @contextTypes = { name: PropTypes.string.isRequired } @defaultProps = { name: '<NAME>' } @propTypes: { name: PropTypes.string.isRequired } # static get displayName() { # return "Hello" # } ''' options: [PROPERTY_ASSIGNMENT] errors: [ message: "'childContextTypes' should be declared outside the class body." , message: "'contextTypes' should be declared outside the class body." , message: "'contextType' should be declared outside the class body." , message: "'displayName' should be declared outside the class body." , message: "'contextTypes' should be declared outside the class body." , message: "'defaultProps' should be declared outside the class body." , message: "'propTypes' should be declared outside the class body." # , # message: "'displayName' should be declared outside the class body." ] ]
true
###* # @fileoverview Defines where React component static properties should be positioned. # @author PI:NAME:<NAME>END_PI ### 'use strict' # ------------------------------------------------------------------------------ # Positioning Options # ------------------------------------------------------------------------------ STATIC_PUBLIC_FIELD = 'static public field' STATIC_GETTER = 'static getter' PROPERTY_ASSIGNMENT = 'property assignment' # ------------------------------------------------------------------------------ # Requirements # ------------------------------------------------------------------------------ path = require 'path' {RuleTester} = require 'eslint' rule = require 'eslint-plugin-react/lib/rules/static-property-placement' # parsers = require 'eslint-plugin-react/tests/helpers/parsers' ruleTesterConfig = # parser: parsers.BABEL_ESLINT # parserOptions: # ecmaVersion: 2018 # sourceType: 'module' # ecmaFeatures: # jsx: yes settings: react: version: '15' # ------------------------------------------------------------------------------ # Tests # ------------------------------------------------------------------------------ ruleTester = new RuleTester { ...ruleTesterConfig parser: path.join __dirname, '../../..' } ruleTester.run 'static-property-placement', rule, valid: [ # ------------------------------------------------------------------------------ # Ignore creatClass/createReactClass and Static Functional Components # ------------------------------------------------------------------------------ # Do not error on createReactClass pragma code: [ ''' MyComponent = createReactClass({ childContextTypes: { something: PropTypes.bool }, contextTypes: { something: PropTypes.bool }, getDefaultProps: -> name: 'PI:NAME:<NAME>END_PI' displayName: 'Hello', propTypes: { something: PropTypes.bool }, render: -> return null }) ''' ].join '\n' options: [PROPERTY_ASSIGNMENT] , # Do not error on createClass pragma code: ''' MyComponent = React.createClass({ childContextTypes: { something: PropTypes.bool }, contextTypes: { something: PropTypes.bool }, getDefaultProps: -> name: 'PI:NAME:<NAME>END_PI' displayName: 'Hello', propTypes: { something: PropTypes.bool }, render: -> return null }) ''' options: [PROPERTY_ASSIGNMENT] , # Do not error on SFC arrow function with return code: ''' MyComponent = () => return <div>Hello</div> MyComponent.childContextTypes = { something: PropTypes.bool } MyComponent.contextTypes = { something: PropTypes.bool } MyComponent.defaultProps = { something: 'PI:NAME:<NAME>END_PI' } MyComponent.displayName = 'Hello' MyComponent.propTypes = { something: PropTypes.bool } ''' , # Do not error on SFC arrow function with direct return code: ''' MyComponent = () => (<div>Hello</div>) MyComponent.childContextTypes = { something: PropTypes.bool } MyComponent.contextTypes = { something: PropTypes.bool } MyComponent.defaultProps = { something: 'PI:NAME:<NAME>END_PI' } MyComponent.displayName = 'Hello' MyComponent.propTypes = { something: PropTypes.bool } ''' , # Do not error on SFC as unnamed function code: ''' export MyComponent = -> return <div>Hello</div> MyComponent.childContextTypes = { something: PropTypes.bool } MyComponent.contextTypes = { something: PropTypes.bool } MyComponent.defaultProps = { something: 'PI:NAME:<NAME>END_PI' } MyComponent.displayName = 'Hello' MyComponent.propTypes = { something: PropTypes.bool } ''' , # ------------------------------------------------------------------------------ # no properties # ------------------------------------------------------------------------------ # Do not error if no properties defined code: ''' class MyComponent extends React.Component render: -> return null ''' , # Do not error if unchecked properties defined code: ''' class MyComponent extends React.Component @randomlyNamed = name: 'PI:NAME:<NAME>END_PI' ''' , # Do not error if unchecked static properties defined and assignment rule enabled code: ''' class MyComponent extends React.Component @randomlyNamed = name: 'PI:NAME:<NAME>END_PI' ''' options: [PROPERTY_ASSIGNMENT] , # Do not error if unchecked assignment properties defined and assignment rule enabled code: ''' class MyComponent extends React.Component render: -> return null MyComponent.randomlyNamed = name: 'PI:NAME:<NAME>END_PI' ''' options: [PROPERTY_ASSIGNMENT] , # Do not error if unchecked assignment properties defined and static rule enabled code: ''' class MyComponent extends React.Component render: -> return null MyComponent.randomlyNamed = name: 'PI:NAME:<NAME>END_PI' ''' , # ------------------------------------------------------------------------------ # childContextTypes - static field # ------------------------------------------------------------------------------ # Do not error if childContextTypes correctly defined - static field code: ''' class MyComponent extends React.Component @childContextTypes = something: PropTypes.bool ''' , # Do not error if childContextTypes correctly defined - static field code: ''' class MyComponent extends React.Component @childContextTypes: something: PropTypes.bool ''' options: [PROPERTY_ASSIGNMENT, {childContextTypes: STATIC_PUBLIC_FIELD}] , # , # # ------------------------------------------------------------------------------ # # childContextTypes - static getter # # ------------------------------------------------------------------------------ # # Do not error if childContextTypes correctly defined - static getter # code: [ # ''' # class MyComponent extends React.Component { # static get childContextTypes() { # return { # something: PropTypes.bool # }; # } # } # ''' # ].join '\n' # options: [STATIC_GETTER] # , # # Do not error if contextTypes correctly defined - static getter # code: [ # ''' # class MyComponent extends React.Component { # static get childContextTypes() { # return { # something: PropTypes.bool # }; # } # } # ''' # ].join '\n' # options: [PROPERTY_ASSIGNMENT, {childContextTypes: STATIC_GETTER}] # ------------------------------------------------------------------------------ # childContextTypes - assignment # ------------------------------------------------------------------------------ # Do not error if childContextTypes correctly defined - assignment code: ''' class MyComponent extends React.Component render: -> return null MyComponent.childContextTypes = name: PropTypes.string.isRequired ''' options: [PROPERTY_ASSIGNMENT] , # Do not error if childContextTypes correctly defined - assignment code: ''' class MyComponent extends React.Component render: -> return null MyComponent.childContextTypes = { name: PropTypes.string.isRequired } ''' options: [STATIC_PUBLIC_FIELD, {childContextTypes: PROPERTY_ASSIGNMENT}] , # ------------------------------------------------------------------------------ # contextTypes - static field # ------------------------------------------------------------------------------ # Do not error if contextTypes correctly defined - static field code: ''' class MyComponent extends React.Component @contextTypes = { something: PropTypes.bool } ''' , # Do not error if contextTypes correctly defined - static field code: ''' class MyComponent extends React.Component @contextTypes = something: PropTypes.bool ''' options: [PROPERTY_ASSIGNMENT, {contextTypes: STATIC_PUBLIC_FIELD}] , # , # # ------------------------------------------------------------------------------ # # contextTypes - static getter # # ------------------------------------------------------------------------------ # # Do not error if contextTypes correctly defined - static getter # code: [ # ''' # class MyComponent extends React.Component { # static get contextTypes() { # return { # something: PropTypes.bool # }; # } # } # ''' # ].join '\n' # options: [STATIC_GETTER] # , # # Do not error if contextTypes correctly defined - static getter # code: [ # ''' # class MyComponent extends React.Component { # static get contextTypes() { # return { # something: PropTypes.bool # }; # } # } # ''' # ].join '\n' # options: [PROPERTY_ASSIGNMENT, {contextTypes: STATIC_GETTER}] # ------------------------------------------------------------------------------ # contextTypes - assignment # ------------------------------------------------------------------------------ # Do not error if contextTypes correctly defined - assignment code: ''' class MyComponent extends React.Component render: -> return null MyComponent.contextTypes = { name: PropTypes.string.isRequired } ''' options: [PROPERTY_ASSIGNMENT] , # Do not error if contextTypes correctly defined - assignment code: ''' class MyComponent extends React.Component render: -> return null MyComponent.contextTypes = { name: PropTypes.string.isRequired } ''' options: [STATIC_PUBLIC_FIELD, {contextTypes: PROPERTY_ASSIGNMENT}] , # ------------------------------------------------------------------------------ # contextType - static field # ------------------------------------------------------------------------------ # Do not error if contextType correctly defined - static field code: ''' class MyComponent extends React.Component @contextType = MyContext ''' , # Do not error if contextType correctly defined - static field code: ''' class MyComponent extends React.Component @contextType = MyContext ''' options: [PROPERTY_ASSIGNMENT, {contextType: STATIC_PUBLIC_FIELD}] , # , # # ------------------------------------------------------------------------------ # # contextType - static getter # # ------------------------------------------------------------------------------ # # Do not error if contextType correctly defined - static field # code: [ # ''' # class MyComponent extends React.Component { # static get contextType() { # return MyContext; # } # } # ''' # ].join '\n' # options: [STATIC_GETTER] # , # # Do not error if contextType correctly defined - static field # code: [ # ''' # class MyComponent extends React.Component { # static get contextType() { # return MyContext; # } # } # ''' # ].join '\n' # options: [PROPERTY_ASSIGNMENT, {contextType: STATIC_GETTER}] # ------------------------------------------------------------------------------ # contextType - assignment # ------------------------------------------------------------------------------ # Do not error if contextType correctly defined - assignment code: ''' class MyComponent extends React.Component render: -> return null MyComponent.contextType = MyContext ''' options: [PROPERTY_ASSIGNMENT] , # Do not error if contextType correctly defined - assignment code: ''' class MyComponent extends React.Component render: -> return null MyComponent.contextType = MyContext ''' options: [STATIC_PUBLIC_FIELD, {contextType: PROPERTY_ASSIGNMENT}] , # ------------------------------------------------------------------------------ # displayName - static field # ------------------------------------------------------------------------------ # Do not error if displayName correctly defined - static field code: ''' class MyComponent extends React.Component @displayName = "Hello" ''' , # Do not error if displayName correctly defined - static field code: ''' class MyComponent extends React.Component @displayName = "Hello" ''' options: [PROPERTY_ASSIGNMENT, {displayName: STATIC_PUBLIC_FIELD}] , # ------------------------------------------------------------------------------ # displayName - static getter # ------------------------------------------------------------------------------ # Do not error if displayName correctly defined - static getter # code: [ # ''' # class MyComponent extends React.Component { # static get displayName() { # return \"Hello\"; # } # } # ''' # ].join '\n' # options: [STATIC_GETTER] # , # # Do not error if contextTypes correctly defined - static getter # code: [ # ''' # class MyComponent extends React.Component { # static get displayName() { # return \"Hello\"; # } # } # ''' # ].join '\n' # options: [PROPERTY_ASSIGNMENT, {displayName: STATIC_GETTER}] # ------------------------------------------------------------------------------ # displayName - assignment # ------------------------------------------------------------------------------ # Do not error if displayName correctly defined - assignment code: ''' class MyComponent extends React.Component render: -> return null MyComponent.displayName = "PI:NAME:<NAME>END_PI" ''' options: [PROPERTY_ASSIGNMENT] , # Do not error if displayName correctly defined - assignment code: ''' class MyComponent extends React.Component render: -> return null MyComponent.displayName = "PI:NAME:<NAME>END_PI" ''' options: [STATIC_PUBLIC_FIELD, {displayName: PROPERTY_ASSIGNMENT}] , # ------------------------------------------------------------------------------ # defaultProps - static field # ------------------------------------------------------------------------------ # Do not error if defaultProps correctly defined - static field code: ''' class MyComponent extends React.Component @defaultProps = { something: 'PI:NAME:<NAME>END_PI' } ''' , # Do not error if defaultProps correctly defined - static field code: ''' class MyComponent extends React.Component @defaultProps = something: 'PI:NAME:<NAME>END_PI' ''' options: [PROPERTY_ASSIGNMENT, {defaultProps: STATIC_PUBLIC_FIELD}] , # , # # ------------------------------------------------------------------------------ # # defaultProps - static getter # # ------------------------------------------------------------------------------ # # Do not error if defaultProps correctly defined - static getter # code: [ # ''' # class MyComponent extends React.Component { # static get defaultProps() { # return { # something: 'PI:NAME:<NAME>END_PI' # }; # } # } # ''' # ].join '\n' # options: [STATIC_GETTER] # , # # Do not error if contextTypes correctly defined - static getter # code: [ # ''' # class MyComponent extends React.Component { # static get defaultProps() { # return { # something: 'PI:NAME:<NAME>END_PI' # }; # } # } # ''' # ].join '\n' # options: [PROPERTY_ASSIGNMENT, {defaultProps: STATIC_GETTER}] # ------------------------------------------------------------------------------ # defaultProps - assignment # ------------------------------------------------------------------------------ # Do not error if defaultProps correctly defined - assignment code: ''' class MyComponent extends React.Component render: -> return null MyComponent.defaultProps = { name: 'PI:NAME:<NAME>END_PI' } ''' options: [PROPERTY_ASSIGNMENT] , # Do not error if defaultProps correctly defined - assignment code: ''' class MyComponent extends React.Component render: -> return null MyComponent.defaultProps = { name: 'PI:NAME:<NAME>END_PI' } ''' options: [STATIC_PUBLIC_FIELD, {defaultProps: PROPERTY_ASSIGNMENT}] , # ------------------------------------------------------------------------------ # propTypes - static field # ------------------------------------------------------------------------------ # Do not error if propTypes correctly defined - static field code: ''' class MyComponent extends React.Component @propTypes = { something: PropTypes.bool } ''' , # Do not error if propTypes correctly defined - static field code: ''' class MyComponent extends React.Component @propTypes = { something: PropTypes.bool } ''' options: [PROPERTY_ASSIGNMENT, {propTypes: STATIC_PUBLIC_FIELD}] , # , # # ------------------------------------------------------------------------------ # # propTypes - static getter # # ------------------------------------------------------------------------------ # # Do not error if propTypes correctly defined - static getter # code: [ # ''' # class MyComponent extends React.Component { # static get propTypes() { # return { # something: PropTypes.bool # }; # } # } # ''' # ].join '\n' # options: [STATIC_GETTER] # , # # Do not error if contextTypes correctly defined - static getter # code: [ # ''' # class MyComponent extends React.Component { # static get propTypes() { # return { # something: PropTypes.bool # }; # } # } # ''' # ].join '\n' # options: [PROPERTY_ASSIGNMENT, {propTypes: STATIC_GETTER}] # ------------------------------------------------------------------------------ # propTypes - assignment # ------------------------------------------------------------------------------ # Do not error if propTypes correctly defined - assignment code: ''' class MyComponent extends React.Component render: -> return null MyComponent.propTypes = { name: PropTypes.string.isRequired } ''' options: [PROPERTY_ASSIGNMENT] , # Do not error if propTypes correctly defined - assignment code: ''' class MyComponent extends React.Component render: -> return null MyComponent.propTypes = { name: PropTypes.string.isRequired } ''' options: [STATIC_PUBLIC_FIELD, {propTypes: PROPERTY_ASSIGNMENT}] , # ------------------------------------------------------------------------------ # multiple - static field # ------------------------------------------------------------------------------ # Do not error if multiple properties and match config - static field code: ''' class MyComponent extends React.Component @childContextTypes = { something: PropTypes.bool } @contextTypes = { something: PropTypes.bool } @contextType = MyContext @displayName = "Hello" @defaultProps = { something: 'PI:NAME:<NAME>END_PI' } @propTypes = { something: PropTypes.bool } ''' , # Do not error if multiple properties and match config - static field code: ''' class MyComponent extends React.Component @childContextTypes = { something: PropTypes.bool } @contextTypes = { something: PropTypes.bool } @contextType = MyContext @displayName = "Hello" @defaultProps = { something: 'PI:NAME:<NAME>END_PI' }; @propTypes = { something: PropTypes.bool } ''' options: [ PROPERTY_ASSIGNMENT , childContextTypes: STATIC_PUBLIC_FIELD contextTypes: STATIC_PUBLIC_FIELD contextType: STATIC_PUBLIC_FIELD displayName: STATIC_PUBLIC_FIELD defaultProps: STATIC_PUBLIC_FIELD propTypes: STATIC_PUBLIC_FIELD ] , # , # # ------------------------------------------------------------------------------ # # multiple - static getter # # ------------------------------------------------------------------------------ # # Do not error if childContextTypes correctly defined - static getter # code: [ # ''' # class MyComponent extends React.Component { # static get childContextTypes() { # return { # something: PropTypes.bool # }; # } # static get contextTypes() { # return { # something: PropTypes.bool # }; # } # static get contextType() { # return MyContext; # } # static get displayName() { # return \"Hello\"; # } # static get defaultProps() { # return { # something: PropTypes.bool # }; # } # static get propTypes() { # return { # something: PropTypes.bool # }; # } # } # ''' # ].join '\n' # options: [STATIC_GETTER] # , # # Do not error if contextTypes correctly defined - static getter # code: [ # ''' # class MyComponent extends React.Component { # static get childContextTypes() { # return { # something: PropTypes.bool # }; # } # static get contextTypes() { # return { # something: PropTypes.bool # }; # } # static get contextType() { # return MyContext; # } # static get displayName() { # return \"Hello\"; # } # static get defaultProps() { # return { # something: PropTypes.bool # }; # } # static get propTypes() { # return { # something: PropTypes.bool # }; # } # } # ''' # ].join '\n' # options: [ # PROPERTY_ASSIGNMENT # , # childContextTypes: STATIC_GETTER # contextTypes: STATIC_GETTER # contextType: STATIC_GETTER # displayName: STATIC_GETTER # defaultProps: STATIC_GETTER # propTypes: STATIC_GETTER # ] # ------------------------------------------------------------------------------ # multiple - assignment # ------------------------------------------------------------------------------ # Do not error if multiple properties and match config - assignment code: ''' class MyComponent extends React.Component render: -> return null MyComponent.childContextTypes = { name: PropTypes.string.isRequired } MyComponent.contextTypes = { name: PropTypes.string.isRequired } MyComponent.displayName = "Hello" MyComponent.defaultProps = { name: 'PI:NAME:<NAME>END_PI' } MyComponent.propTypes = { name: PropTypes.string.isRequired } ''' options: [PROPERTY_ASSIGNMENT] , # Do not error if multiple properties and match config - static field code: ''' class MyComponent extends React.Component render: -> return null MyComponent.childContextTypes = { name: PropTypes.string.isRequired } MyComponent.contextTypes = { name: PropTypes.string.isRequired } MyComponent.displayName = "Hello" MyComponent.defaultProps = { name: 'PI:NAME:<NAME>END_PI' } MyComponent.propTypes = { name: PropTypes.string.isRequired } ''' options: [ STATIC_PUBLIC_FIELD , childContextTypes: PROPERTY_ASSIGNMENT contextTypes: PROPERTY_ASSIGNMENT displayName: PROPERTY_ASSIGNMENT defaultProps: PROPERTY_ASSIGNMENT propTypes: PROPERTY_ASSIGNMENT ] , # ------------------------------------------------------------------------------ # combined - mixed # ------------------------------------------------------------------------------ # Do not error if mixed property positions and match config code: ''' class MyComponent extends React.Component @childContextTypes = name: PropTypes.string.isRequired @contextTypes = { name: PropTypes.string.isRequired } # static get displayName() { # return "Hello" # } MyComponent.defaultProps = { name: 'PI:NAME:<NAME>END_PI' } MyComponent.propTypes = { name: PropTypes.string.isRequired } ''' options: [ STATIC_PUBLIC_FIELD , displayName: STATIC_GETTER defaultProps: PROPERTY_ASSIGNMENT propTypes: PROPERTY_ASSIGNMENT ] , # Do not error if mixed property positions and match config code: ''' class MyComponent extends React.Component @childContextTypes = { name: PropTypes.string.isRequired } @contextTypes = { name: PropTypes.string.isRequired } # static get displayName() { # return "Hello" # } MyComponent.defaultProps = { name: 'PI:NAME:<NAME>END_PI' } MyComponent.propTypes = { name: PropTypes.string.isRequired } ''' options: [ PROPERTY_ASSIGNMENT , childContextTypes: STATIC_PUBLIC_FIELD contextTypes: STATIC_PUBLIC_FIELD displayName: STATIC_GETTER ] , # ------------------------------------------------------------------------------ # mixed component types # ------------------------------------------------------------------------------ # SFC ignored and component is valid code: ''' class MyComponent extends React.Component @childContextTypes = { name: PropTypes.string.isRequired } @contextTypes = { name: PropTypes.string.isRequired } @displayName = "Hello" OtherComponent = () => (<div>Hello</div>) OtherComponent.defaultProps = { name: 'PI:NAME:<NAME>END_PI' } OtherComponent.propTypes = { name: PropTypes.string.isRequired } ''' , # Multiple components validated code: ''' class MyComponent extends React.Component @childContextTypes = { name: PropTypes.string.isRequired } @contextTypes = { name: PropTypes.string.isRequired } @displayName = "Hello" class OtherComponent extends React.Component @defaultProps = { name: 'PI:NAME:<NAME>END_PI' } @propTypes = { name: PropTypes.string.isRequired } ''' , # ------------------------------------------------------------------------------ # edge cases # ------------------------------------------------------------------------------ # Do not error if property assignment is inside a class function code: ''' class MyComponent extends React.Component @displayName = "Hello" myMethod: -> console.log(MyComponent.displayName) ''' options: [STATIC_PUBLIC_FIELD] , # Do not error if display name value changed code: ''' class MyComponent extends React.Component @displayName = "Hello" myMethod: -> MyComponent.displayName = "Bonjour" ''' options: [STATIC_PUBLIC_FIELD] ] invalid: [ # ------------------------------------------------------------------------------ # expected static field when got property assigment # ------------------------------------------------------------------------------ # Error if multiple properties are incorrectly positioned according to config code: ''' class MyComponent extends React.Component render: -> return null MyComponent.childContextTypes = { name: PropTypes.string.isRequired } MyComponent.contextTypes = { name: PropTypes.string.isRequired } MyComponent.contextType = MyContext MyComponent.displayName = "Hello" MyComponent.defaultProps = { name: 'PI:NAME:<NAME>END_PI' } MyComponent.propTypes = { name: PropTypes.string.isRequired } ''' errors: [ message: "'childContextTypes' should be declared as a static class property." , message: "'contextTypes' should be declared as a static class property." , message: "'contextType' should be declared as a static class property." , message: "'displayName' should be declared as a static class property." , message: "'defaultProps' should be declared as a static class property." , message: "'propTypes' should be declared as a static class property." ] , # Error if multiple properties are incorrectly positioned according to config code: ''' class MyComponent extends React.Component render: -> return null MyComponent.childContextTypes = { name: PropTypes.string.isRequired } MyComponent.contextTypes = { name: PropTypes.string.isRequired } MyComponent.contextType = MyContext MyComponent.displayName = "Hello" MyComponent.defaultProps = { name: 'PI:NAME:<NAME>END_PI' } MyComponent.propTypes = { name: PropTypes.string.isRequired } ''' options: [ PROPERTY_ASSIGNMENT , childContextTypes: STATIC_PUBLIC_FIELD contextTypes: STATIC_PUBLIC_FIELD contextType: STATIC_PUBLIC_FIELD displayName: STATIC_PUBLIC_FIELD defaultProps: STATIC_PUBLIC_FIELD propTypes: STATIC_PUBLIC_FIELD ] errors: [ message: "'childContextTypes' should be declared as a static class property." , message: "'contextTypes' should be declared as a static class property." , message: "'contextType' should be declared as a static class property." , message: "'displayName' should be declared as a static class property." , message: "'defaultProps' should be declared as a static class property." , message: "'propTypes' should be declared as a static class property." ] , , # # ------------------------------------------------------------------------------ # # expected static field when got static getter # # ------------------------------------------------------------------------------ # # Error if multiple properties are incorrectly positioned according to config # code: [ # ''' # class MyComponent extends React.Component { # static get childContextTypes() { # return { # something: PropTypes.bool # }; # } # static get contextTypes() { # return { # something: PropTypes.bool # }; # } # static get contextType() { # return MyContext; # } # static get displayName() { # return \"Hello\"; # } # static get defaultProps() { # return { # something: PropTypes.bool # }; # } # static get propTypes() { # return { # something: PropTypes.bool # }; # } # } # ''' # ].join '\n' # errors: [ # message: # "'childContextTypes' should be declared as a static class property." # , # message: "'contextTypes' should be declared as a static class property." # , # message: "'contextType' should be declared as a static class property." # , # message: "'displayName' should be declared as a static class property." # , # message: "'defaultProps' should be declared as a static class property." # , # message: "'propTypes' should be declared as a static class property." # ] # , # # Error if multiple properties are incorrectly positioned according to config # code: [ # ''' # class MyComponent extends React.Component { # static get childContextTypes() { # return { # something: PropTypes.bool # }; # } # static get contextTypes() { # return { # something: PropTypes.bool # }; # } # static get contextType() { # return MyContext; # } # static get displayName() { # return \"Hello\"; # } # static get defaultProps() { # return { # something: PropTypes.bool # }; # } # static get propTypes() { # return { # something: PropTypes.bool # }; # } # } # ''' # ].join '\n' # options: [ # PROPERTY_ASSIGNMENT # , # childContextTypes: STATIC_PUBLIC_FIELD # contextTypes: STATIC_PUBLIC_FIELD # contextType: STATIC_PUBLIC_FIELD # displayName: STATIC_PUBLIC_FIELD # defaultProps: STATIC_PUBLIC_FIELD # propTypes: STATIC_PUBLIC_FIELD # ] # errors: [ # message: # "'childContextTypes' should be declared as a static class property." # , # message: "'contextTypes' should be declared as a static class property." # , # message: "'contextType' should be declared as a static class property." # , # message: "'displayName' should be declared as a static class property." # , # message: "'defaultProps' should be declared as a static class property." # , # message: "'propTypes' should be declared as a static class property." # ] # ------------------------------------------------------------------------------ # expected property assignment when got static field # ------------------------------------------------------------------------------ # Error if multiple properties are incorrectly positioned according to config code: ''' class MyComponent extends React.Component @childContextTypes = { something: PropTypes.bool } @contextTypes = { something: PropTypes.bool } @contextType = MyContext @displayName = "Hello" @defaultProps = { something: 'PI:NAME:<NAME>END_PI' } @propTypes = { something: PropTypes.bool } ''' options: [PROPERTY_ASSIGNMENT] errors: [ message: "'childContextTypes' should be declared outside the class body." , message: "'contextTypes' should be declared outside the class body." , message: "'contextType' should be declared outside the class body." , message: "'displayName' should be declared outside the class body." , message: "'defaultProps' should be declared outside the class body." , message: "'propTypes' should be declared outside the class body." ] , # Error if multiple properties are incorrectly positioned according to config code: ''' class MyComponent extends React.Component @childContextTypes = { something: PropTypes.bool } @contextTypes = { something: PropTypes.bool } @contextType = MyContext @displayName = "Hello" @defaultProps = { something: 'PI:NAME:<NAME>END_PI' } @propTypes = { something: PropTypes.bool } ''' options: [ STATIC_PUBLIC_FIELD , childContextTypes: PROPERTY_ASSIGNMENT contextTypes: PROPERTY_ASSIGNMENT contextType: PROPERTY_ASSIGNMENT displayName: PROPERTY_ASSIGNMENT defaultProps: PROPERTY_ASSIGNMENT propTypes: PROPERTY_ASSIGNMENT ] errors: [ message: "'childContextTypes' should be declared outside the class body." , message: "'contextTypes' should be declared outside the class body." , message: "'contextType' should be declared outside the class body." , message: "'displayName' should be declared outside the class body." , message: "'defaultProps' should be declared outside the class body." , message: "'propTypes' should be declared outside the class body." ] , # # ------------------------------------------------------------------------------ # # expected property assignment when got static getter # # ------------------------------------------------------------------------------ # # Error if multiple properties are incorrectly positioned according to config # code: [ # ''' # class MyComponent extends React.Component { # static get childContextTypes() { # return { # something: PropTypes.bool # }; # } # static get contextTypes() { # return { # something: PropTypes.bool # }; # } # static get contextType() { # return MyContext; # } # static get displayName() { # return \"Hello\"; # } # static get defaultProps() { # return { # something: PropTypes.bool # }; # } # static get propTypes() { # return { # something: PropTypes.bool # }; # } # } # ''' # ].join '\n' # options: [PROPERTY_ASSIGNMENT] # errors: [ # message: "'childContextTypes' should be declared outside the class body." # , # message: "'contextTypes' should be declared outside the class body." # , # message: "'contextType' should be declared outside the class body." # , # message: "'displayName' should be declared outside the class body." # , # message: "'defaultProps' should be declared outside the class body." # , # message: "'propTypes' should be declared outside the class body." # ] # , # # Error if multiple properties are incorrectly positioned according to config # code: [ # ''' # class MyComponent extends React.Component { # static get childContextTypes() { # return { # something: PropTypes.bool # }; # } # static get contextTypes() { # return { # something: PropTypes.bool # }; # } # static get contextType() { # return MyContext; # } # static get displayName() { # return \"Hello\"; # } # static get defaultProps() { # return { # something: PropTypes.bool # }; # } # static get propTypes() { # return { # something: PropTypes.bool # }; # } # } # ''' # ].join '\n' # options: [ # STATIC_GETTER # , # childContextTypes: PROPERTY_ASSIGNMENT # contextTypes: PROPERTY_ASSIGNMENT # contextType: PROPERTY_ASSIGNMENT # displayName: PROPERTY_ASSIGNMENT # defaultProps: PROPERTY_ASSIGNMENT # propTypes: PROPERTY_ASSIGNMENT # ] # errors: [ # message: "'childContextTypes' should be declared outside the class body." # , # message: "'contextTypes' should be declared outside the class body." # , # message: "'contextType' should be declared outside the class body." # , # message: "'displayName' should be declared outside the class body." # , # message: "'defaultProps' should be declared outside the class body." # , # message: "'propTypes' should be declared outside the class body." # ] # , # ------------------------------------------------------------------------------ # expected static getter when got static field # ------------------------------------------------------------------------------ # Error if multiple properties are incorrectly positioned according to config code: ''' class MyComponent extends React.Component @childContextTypes = { something: PropTypes.bool } @contextTypes = { something: PropTypes.bool } @contextType = MyContext @displayName = "Hello" @defaultProps = { something: 'PI:NAME:<NAME>END_PI' }; @propTypes = { something: PropTypes.bool } ''' options: [STATIC_GETTER] errors: [ message: "'childContextTypes' should be declared as a static getter class function." , message: "'contextTypes' should be declared as a static getter class function." , message: "'contextType' should be declared as a static getter class function." , message: "'displayName' should be declared as a static getter class function." , message: "'defaultProps' should be declared as a static getter class function." , message: "'propTypes' should be declared as a static getter class function." ] , # Error if multiple properties are incorrectly positioned according to config code: ''' class MyComponent extends React.Component @childContextTypes = { something: PropTypes.bool } @contextTypes = { something: PropTypes.bool } @contextType = MyContext @displayName = "Hello" @defaultProps = { something: 'PI:NAME:<NAME>END_PI' } @propTypes = { something: PropTypes.bool } ''' options: [ STATIC_PUBLIC_FIELD , childContextTypes: STATIC_GETTER contextTypes: STATIC_GETTER contextType: STATIC_GETTER displayName: STATIC_GETTER defaultProps: STATIC_GETTER propTypes: STATIC_GETTER ] errors: [ message: "'childContextTypes' should be declared as a static getter class function." , message: "'contextTypes' should be declared as a static getter class function." , message: "'contextType' should be declared as a static getter class function." , message: "'displayName' should be declared as a static getter class function." , message: "'defaultProps' should be declared as a static getter class function." , message: "'propTypes' should be declared as a static getter class function." ] , # ------------------------------------------------------------------------------ # expected static getter when got property assignment # ------------------------------------------------------------------------------ # Error if multiple properties are incorrectly positioned according to config code: ''' class MyComponent extends React.Component render: -> return null MyComponent.childContextTypes = name: PropTypes.string.isRequired MyComponent.contextTypes = name: PropTypes.string.isRequired MyComponent.contextType = MyContext MyComponent.displayName = "Hello" MyComponent.defaultProps = { name: 'PI:NAME:<NAME>END_PI' } MyComponent.propTypes = { name: PropTypes.string.isRequired } ''' options: [STATIC_GETTER] errors: [ message: "'childContextTypes' should be declared as a static getter class function." , message: "'contextTypes' should be declared as a static getter class function." , message: "'contextType' should be declared as a static getter class function." , message: "'displayName' should be declared as a static getter class function." , message: "'defaultProps' should be declared as a static getter class function." , message: "'propTypes' should be declared as a static getter class function." ] , # Error if multiple properties are incorrectly positioned according to config code: ''' class MyComponent extends React.Component render: -> return null MyComponent.childContextTypes = { name: PropTypes.string.isRequired } MyComponent.contextTypes = { name: PropTypes.string.isRequired } MyComponent.contextType = MyContext MyComponent.displayName = "Hello" MyComponent.defaultProps = { name: 'PI:NAME:<NAME>END_PI' } MyComponent.propTypes = { name: PropTypes.string.isRequired } ''' options: [ PROPERTY_ASSIGNMENT , childContextTypes: STATIC_GETTER contextTypes: STATIC_GETTER contextType: STATIC_GETTER displayName: STATIC_GETTER defaultProps: STATIC_GETTER propTypes: STATIC_GETTER ] errors: [ message: "'childContextTypes' should be declared as a static getter class function." , message: "'contextTypes' should be declared as a static getter class function." , message: "'contextType' should be declared as a static getter class function." , message: "'displayName' should be declared as a static getter class function." , message: "'defaultProps' should be declared as a static getter class function." , message: "'propTypes' should be declared as a static getter class function." ] , # ------------------------------------------------------------------------------ # combined - mixed # ------------------------------------------------------------------------------ # Error if mixed property positions but dont match config code: ''' class MyComponent extends React.Component @childContextTypes = { name: PropTypes.string.isRequired } @contextTypes = { name: PropTypes.string.isRequired } @contextType = MyContext # @get displayName() { # return "Hello"; # } MyComponent.defaultProps = { name: 'PI:NAME:<NAME>END_PI' } MyComponent.propTypes = { name: PropTypes.string.isRequired } ''' options: [ PROPERTY_ASSIGNMENT , defaultProps: STATIC_GETTER propTypes: STATIC_PUBLIC_FIELD displayName: STATIC_PUBLIC_FIELD ] errors: [ message: "'childContextTypes' should be declared outside the class body." , message: "'contextTypes' should be declared outside the class body." , message: "'contextType' should be declared outside the class body." , # , # message: "'displayName' should be declared as a static class property." message: "'defaultProps' should be declared as a static getter class function." , message: "'propTypes' should be declared as a static class property." ] , # Error if mixed property positions but dont match config code: ''' class MyComponent extends React.Component @childContextTypes = { name: PropTypes.string.isRequired } @contextTypes = { name: PropTypes.string.isRequired } @contextType = MyContext # @get displayName() { # return "Hello"; # } MyComponent.defaultProps = { name: 'PI:NAME:<NAME>END_PI' } MyComponent.propTypes = { name: PropTypes.string.isRequired } ''' options: [ STATIC_GETTER , childContextTypes: PROPERTY_ASSIGNMENT contextTypes: PROPERTY_ASSIGNMENT contextType: PROPERTY_ASSIGNMENT displayName: PROPERTY_ASSIGNMENT ] errors: [ message: "'childContextTypes' should be declared outside the class body." , message: "'contextTypes' should be declared outside the class body." , message: "'contextType' should be declared outside the class body." , # , # message: "'displayName' should be declared outside the class body." message: "'defaultProps' should be declared as a static getter class function." , message: "'propTypes' should be declared as a static getter class function." ] , # ------------------------------------------------------------------------------ # mixed component types # ------------------------------------------------------------------------------ # SFC ignored and component is invalid code: ''' class MyComponent extends React.Component @childContextTypes = { name: PropTypes.string.isRequired } @contextTypes = { name: PropTypes.string.isRequired } @contextType = MyContext # @get displayName() { # return "Hello"; # } OtherComponent = () => (<div>Hello</div>) OtherComponent.defaultProps = { name: 'PI:NAME:<NAME>END_PI' } OtherComponent.propTypes = { name: PropTypes.string.isRequired } ''' options: [ PROPERTY_ASSIGNMENT , defaultProps: STATIC_PUBLIC_FIELD propTypes: STATIC_GETTER ] errors: [ message: "'childContextTypes' should be declared outside the class body." , message: "'contextTypes' should be declared outside the class body." , message: "'contextType' should be declared outside the class body." # , # message: "'displayName' should be declared outside the class body." ] , # Multiple components validated code: ''' class MyComponent extends React.Component @childContextTypes = { name: PropTypes.string.isRequired } @contextTypes = { name: PropTypes.string.isRequired } @contextType = MyContext @displayName = "Hello" class OtherComponent extends React.Component @contextTypes = { name: PropTypes.string.isRequired } @defaultProps = { name: 'PI:NAME:<NAME>END_PI' } @propTypes: { name: PropTypes.string.isRequired } # static get displayName() { # return "Hello" # } ''' options: [PROPERTY_ASSIGNMENT] errors: [ message: "'childContextTypes' should be declared outside the class body." , message: "'contextTypes' should be declared outside the class body." , message: "'contextType' should be declared outside the class body." , message: "'displayName' should be declared outside the class body." , message: "'contextTypes' should be declared outside the class body." , message: "'defaultProps' should be declared outside the class body." , message: "'propTypes' should be declared outside the class body." # , # message: "'displayName' should be declared outside the class body." ] ]
[ { "context": "###\n backbone-orm.js 0.5.12\n Copyright (c) 2013 Vidigami - https://github.com/vidigami/backbone-orm\n Lice", "end": 58, "score": 0.9921421408653259, "start": 50, "tag": "NAME", "value": "Vidigami" }, { "context": " Copyright (c) 2013 Vidigami - https://github.com/vidigami/backbone-orm\n License: MIT (http://www.opensourc", "end": 88, "score": 0.9997381567955017, "start": 80, "tag": "USERNAME", "value": "vidigami" } ]
src/cache/query_cache.coffee
michaelBenin/backbone-orm
1
### backbone-orm.js 0.5.12 Copyright (c) 2013 Vidigami - https://github.com/vidigami/backbone-orm License: MIT (http://www.opensource.org/licenses/mit-license.php) Dependencies: Backbone.js, Underscore.js, and Moment.js. ### _ = require 'underscore' inflection = require 'inflection' Queue = require '../queue' JSONUtils = require '../json_utils' MemoryStore = require './memory_store' CLONE_DEPTH = 2 module.exports = class QueryCache constructor: -> @enabled = false configure: (options={}) => @enabled = !!options.enabled @verbose = !!options.verbose @hits = @misses = @clears = 0 @store = options.store or new MemoryStore() # sync model cache CacheSingletons = require('../index').CacheSingletons CacheSingletons.ModelTypeID?.configure({enabled: @enabled, verbose: @verbose}) # only for query cache return @ cacheKey: (model_type, query) -> "#{model_type.model_id}_#{JSON.stringify(query)}" cacheKeyMeta: (model_type) -> "meta_#{model_type.model_id}" set: (model_type, query, related_model_types, value, callback) => return callback() unless @enabled console.log 'QueryCache:set', model_type.model_name, (m.model_name for m in related_model_types), @cacheKey(model_type, query), JSON.stringify(value), '\n-----------' if @verbose model_types = [model_type].concat(related_model_types or []) cache_key = @cacheKey(model_type, query) @store.set cache_key, JSONUtils.deepClone(value, CLONE_DEPTH), (err) => return callback(err) if err @storeKeyForModelTypes model_types, cache_key, callback get: (model_type, query, callback) => return callback() unless @enabled @getKey(@cacheKey(model_type, query), callback) getKey: (key, callback) => return callback() unless @enabled @store.get key, (err, value) => return callback(err) if err if _.isUndefined(value) or _.isNull(value) @misses++ console.log 'QueryCache:miss', key, value, '\n-----------' if @verbose callback() else @hits++ console.log 'QueryCache:hit', key, value, '\n-----------' if @verbose callback(null, JSONUtils.deepClone(value, CLONE_DEPTH)) getMeta: (model_type, callback) => return callback() unless @enabled @store.get @cacheKeyMeta(model_type), callback hardReset: (callback) => return callback() unless @enabled console.log 'QueryCache:hardReset' if @verbose @hits = @misses = @clears = 0 return @store.reset(callback) if @store callback() reset: (model_types, callback) => # clear the full cache return @hardReset(model_types) if arguments.length is 1 return callback() unless @enabled model_types = [model_types] unless _.isArray(model_types) related_model_types = [] related_model_types = related_model_types.concat(model_type.schema().allRelations()) for model_type in model_types model_types = model_types.concat(related_model_types) @clearModelTypes(model_types, callback) # Remove the model_types meta key then clear all cache keys depending on them clearModelTypes: (model_types, callback) => return callback() unless model_types.length @getKeysForModelTypes model_types, (err, to_clear) => return callback(err) if err queue = new Queue() queue.defer (callback) => @clearMetaForModelTypes(model_types, callback) for key in _.uniq(to_clear) do (key) => queue.defer (callback) => console.log 'QueryCache:cleared', key, '\n-----------' if @verbose @clears++ @store.destroy(key, callback) queue.await callback # Clear the meta storage for given model types clearMetaForModelTypes: (model_types, callback) => queue = new Queue() for model_type in model_types do (model_type) => queue.defer (callback) => console.log 'QueryCache:meta cleared', model_type.model_name, '\n-----------' if @verbose @store.destroy @cacheKeyMeta(model_type), callback queue.await callback # Find all cache keys recorded as depending on the given model types getKeysForModelTypes: (model_types, callback) => all_keys = [] queue = new Queue(1) for model_type in model_types do (model_type) => queue.defer (callback) => @getMeta model_type, (err, keys) => return callback(err) if err or not keys all_keys = all_keys.concat(keys) callback() queue.await (err) -> callback(err, all_keys) # Add a key to the list of keys stored for a set of model types storeKeyForModelTypes: (model_types, cache_key, callback) => queue = new Queue(1) for model_type in model_types do (model_type) => queue.defer (callback) => model_type_key = @cacheKeyMeta(model_type) @store.get model_type_key, (err, keys) => return callback(err) if err (keys or= []).push(cache_key) @store.set model_type_key, _.uniq(keys), callback queue.await callback
98490
### backbone-orm.js 0.5.12 Copyright (c) 2013 <NAME> - https://github.com/vidigami/backbone-orm License: MIT (http://www.opensource.org/licenses/mit-license.php) Dependencies: Backbone.js, Underscore.js, and Moment.js. ### _ = require 'underscore' inflection = require 'inflection' Queue = require '../queue' JSONUtils = require '../json_utils' MemoryStore = require './memory_store' CLONE_DEPTH = 2 module.exports = class QueryCache constructor: -> @enabled = false configure: (options={}) => @enabled = !!options.enabled @verbose = !!options.verbose @hits = @misses = @clears = 0 @store = options.store or new MemoryStore() # sync model cache CacheSingletons = require('../index').CacheSingletons CacheSingletons.ModelTypeID?.configure({enabled: @enabled, verbose: @verbose}) # only for query cache return @ cacheKey: (model_type, query) -> "#{model_type.model_id}_#{JSON.stringify(query)}" cacheKeyMeta: (model_type) -> "meta_#{model_type.model_id}" set: (model_type, query, related_model_types, value, callback) => return callback() unless @enabled console.log 'QueryCache:set', model_type.model_name, (m.model_name for m in related_model_types), @cacheKey(model_type, query), JSON.stringify(value), '\n-----------' if @verbose model_types = [model_type].concat(related_model_types or []) cache_key = @cacheKey(model_type, query) @store.set cache_key, JSONUtils.deepClone(value, CLONE_DEPTH), (err) => return callback(err) if err @storeKeyForModelTypes model_types, cache_key, callback get: (model_type, query, callback) => return callback() unless @enabled @getKey(@cacheKey(model_type, query), callback) getKey: (key, callback) => return callback() unless @enabled @store.get key, (err, value) => return callback(err) if err if _.isUndefined(value) or _.isNull(value) @misses++ console.log 'QueryCache:miss', key, value, '\n-----------' if @verbose callback() else @hits++ console.log 'QueryCache:hit', key, value, '\n-----------' if @verbose callback(null, JSONUtils.deepClone(value, CLONE_DEPTH)) getMeta: (model_type, callback) => return callback() unless @enabled @store.get @cacheKeyMeta(model_type), callback hardReset: (callback) => return callback() unless @enabled console.log 'QueryCache:hardReset' if @verbose @hits = @misses = @clears = 0 return @store.reset(callback) if @store callback() reset: (model_types, callback) => # clear the full cache return @hardReset(model_types) if arguments.length is 1 return callback() unless @enabled model_types = [model_types] unless _.isArray(model_types) related_model_types = [] related_model_types = related_model_types.concat(model_type.schema().allRelations()) for model_type in model_types model_types = model_types.concat(related_model_types) @clearModelTypes(model_types, callback) # Remove the model_types meta key then clear all cache keys depending on them clearModelTypes: (model_types, callback) => return callback() unless model_types.length @getKeysForModelTypes model_types, (err, to_clear) => return callback(err) if err queue = new Queue() queue.defer (callback) => @clearMetaForModelTypes(model_types, callback) for key in _.uniq(to_clear) do (key) => queue.defer (callback) => console.log 'QueryCache:cleared', key, '\n-----------' if @verbose @clears++ @store.destroy(key, callback) queue.await callback # Clear the meta storage for given model types clearMetaForModelTypes: (model_types, callback) => queue = new Queue() for model_type in model_types do (model_type) => queue.defer (callback) => console.log 'QueryCache:meta cleared', model_type.model_name, '\n-----------' if @verbose @store.destroy @cacheKeyMeta(model_type), callback queue.await callback # Find all cache keys recorded as depending on the given model types getKeysForModelTypes: (model_types, callback) => all_keys = [] queue = new Queue(1) for model_type in model_types do (model_type) => queue.defer (callback) => @getMeta model_type, (err, keys) => return callback(err) if err or not keys all_keys = all_keys.concat(keys) callback() queue.await (err) -> callback(err, all_keys) # Add a key to the list of keys stored for a set of model types storeKeyForModelTypes: (model_types, cache_key, callback) => queue = new Queue(1) for model_type in model_types do (model_type) => queue.defer (callback) => model_type_key = @cacheKeyMeta(model_type) @store.get model_type_key, (err, keys) => return callback(err) if err (keys or= []).push(cache_key) @store.set model_type_key, _.uniq(keys), callback queue.await callback
true
### backbone-orm.js 0.5.12 Copyright (c) 2013 PI:NAME:<NAME>END_PI - https://github.com/vidigami/backbone-orm License: MIT (http://www.opensource.org/licenses/mit-license.php) Dependencies: Backbone.js, Underscore.js, and Moment.js. ### _ = require 'underscore' inflection = require 'inflection' Queue = require '../queue' JSONUtils = require '../json_utils' MemoryStore = require './memory_store' CLONE_DEPTH = 2 module.exports = class QueryCache constructor: -> @enabled = false configure: (options={}) => @enabled = !!options.enabled @verbose = !!options.verbose @hits = @misses = @clears = 0 @store = options.store or new MemoryStore() # sync model cache CacheSingletons = require('../index').CacheSingletons CacheSingletons.ModelTypeID?.configure({enabled: @enabled, verbose: @verbose}) # only for query cache return @ cacheKey: (model_type, query) -> "#{model_type.model_id}_#{JSON.stringify(query)}" cacheKeyMeta: (model_type) -> "meta_#{model_type.model_id}" set: (model_type, query, related_model_types, value, callback) => return callback() unless @enabled console.log 'QueryCache:set', model_type.model_name, (m.model_name for m in related_model_types), @cacheKey(model_type, query), JSON.stringify(value), '\n-----------' if @verbose model_types = [model_type].concat(related_model_types or []) cache_key = @cacheKey(model_type, query) @store.set cache_key, JSONUtils.deepClone(value, CLONE_DEPTH), (err) => return callback(err) if err @storeKeyForModelTypes model_types, cache_key, callback get: (model_type, query, callback) => return callback() unless @enabled @getKey(@cacheKey(model_type, query), callback) getKey: (key, callback) => return callback() unless @enabled @store.get key, (err, value) => return callback(err) if err if _.isUndefined(value) or _.isNull(value) @misses++ console.log 'QueryCache:miss', key, value, '\n-----------' if @verbose callback() else @hits++ console.log 'QueryCache:hit', key, value, '\n-----------' if @verbose callback(null, JSONUtils.deepClone(value, CLONE_DEPTH)) getMeta: (model_type, callback) => return callback() unless @enabled @store.get @cacheKeyMeta(model_type), callback hardReset: (callback) => return callback() unless @enabled console.log 'QueryCache:hardReset' if @verbose @hits = @misses = @clears = 0 return @store.reset(callback) if @store callback() reset: (model_types, callback) => # clear the full cache return @hardReset(model_types) if arguments.length is 1 return callback() unless @enabled model_types = [model_types] unless _.isArray(model_types) related_model_types = [] related_model_types = related_model_types.concat(model_type.schema().allRelations()) for model_type in model_types model_types = model_types.concat(related_model_types) @clearModelTypes(model_types, callback) # Remove the model_types meta key then clear all cache keys depending on them clearModelTypes: (model_types, callback) => return callback() unless model_types.length @getKeysForModelTypes model_types, (err, to_clear) => return callback(err) if err queue = new Queue() queue.defer (callback) => @clearMetaForModelTypes(model_types, callback) for key in _.uniq(to_clear) do (key) => queue.defer (callback) => console.log 'QueryCache:cleared', key, '\n-----------' if @verbose @clears++ @store.destroy(key, callback) queue.await callback # Clear the meta storage for given model types clearMetaForModelTypes: (model_types, callback) => queue = new Queue() for model_type in model_types do (model_type) => queue.defer (callback) => console.log 'QueryCache:meta cleared', model_type.model_name, '\n-----------' if @verbose @store.destroy @cacheKeyMeta(model_type), callback queue.await callback # Find all cache keys recorded as depending on the given model types getKeysForModelTypes: (model_types, callback) => all_keys = [] queue = new Queue(1) for model_type in model_types do (model_type) => queue.defer (callback) => @getMeta model_type, (err, keys) => return callback(err) if err or not keys all_keys = all_keys.concat(keys) callback() queue.await (err) -> callback(err, all_keys) # Add a key to the list of keys stored for a set of model types storeKeyForModelTypes: (model_types, cache_key, callback) => queue = new Queue(1) for model_type in model_types do (model_type) => queue.defer (callback) => model_type_key = @cacheKeyMeta(model_type) @store.get model_type_key, (err, keys) => return callback(err) if err (keys or= []).push(cache_key) @store.set model_type_key, _.uniq(keys), callback queue.await callback
[ { "context": "local SOCKS5 proxy port\n @password=null, # shadowsocks password\n @method='", "end": 628, "score": 0.9842648506164551, "start": 624, "tag": "PASSWORD", "value": "null" }, { "context": "onfig,\n# new args.ServerConfig\n# '209.141.36.62',\n# 8348,\n# 1080,\n# '$", "end": 3372, "score": 0.9997634291648865, "start": 3359, "tag": "IP_ADDRESS", "value": "209.141.36.62" } ]
args.coffee
yaleh/shadowsocks-gui
0
localStorage = null if window? # node-webkit, apply windows.localStroage localStorage = window.localStorage else # node.js, load node-localstorage LocalStorage = require('node-localstorage').LocalStorage localStorage = new LocalStorage './test_storage' util = require 'util' fs = require 'fs' hydrate = require 'hydrate' # A config of a shadowsocks server # class ServerConfig # Constructor of ServerConfig # constructor: (@server=null, # server address, IP or hostname @server_port=8388, # server port @local_port=1080, # local SOCKS5 proxy port @password=null, # shadowsocks password @method='aes-256-cfb', # encrypting method @timeout=600 ) -> # timeout in seconds # A container of ServerConfig items # # Accessing config items: # # configs.setConfig n, new ServerConfig() # config = configs.getConfig n # class Configs # The index of the default config @DEFAULT_CONFIG_INDEX = -2 # The index of the public config @PUBLIC_CONFIG_INDEX = -1 # Constructor of Configs # constructor: (@defaultConfig = null, # object of the default config @publicConfig = null ) -> # object of the public config @configs = [] @activeConfigIndex = NaN # Get the **n**th config # getConfig: (n) -> # console.log "getConfig(): #{ n }" if n == null or n == Configs.DEFAULT_CONFIG_INDEX return @defaultConfig else if n == Configs.PUBLIC_CONFIG_INDEX return @publicConfig else return @configs[n] # Set the **n**th config # setConfig: (n, config) -> if n < 0 or n >= @getConfigCount() return null @configs[n] = config # Add a new config to the end # addConfig: (config) -> @configs.push config # Get the count of configs # getConfigCount: -> @configs.length # Delete a config # deleteConfig: (n) -> if (n != null) and (n != Configs.DEFAULT_CONFIG_INDEX) and (n != Configs.PUBLIC_CONFIG_INDEX) @configs.splice n,1 # setActiveConfigIndex will adjust the active index after deleting a config @setActiveConfigIndex @getActiveConfigIndex() # Get the current active config index # getActiveConfigIndex: -> return if @activeConfigIndex? and not isNaN(@activeConfigIndex) \ then @activeConfigIndex \ else Configs.DEFAULT_CONFIG_INDEX # Set the active config index # setActiveConfigIndex: (n) -> if not n? @activeConfigIndex = Configs.PUBLIC_CONFIG_INDEX if n >= @getConfigCount() n = @getConfigCount() - 1 if n >= 0 or n == Configs.DEFAULT_CONFIG_INDEX or n == Configs.PUBLIC_CONFIG_INDEX @activeConfigIndex = n else @activeConfigIndex = Configs.PUBLIC_CONFIG_INDEX # Get the active config # getActiveConfig: -> # console.log "getActiveConfig(): #{ @getActiveConfigIndex() }" return @getConfig @getActiveConfigIndex() # Set default config # setDefaultConfig: (config) -> @defaultConfig = config # Set public config # setPublicConfig: (config) -> @publicConfig = config # The storage of configs, handling loading/saving ops # # Example: # # configsStorage = new args.ConfigsLocalStorage 'key' # confs = configsStorage.loadConfigs # new args.ServerConfig, # new args.ServerConfig # '209.141.36.62', # 8348, # 1080, # '$#HAL9000!', # 'aes-256-cfb', # 600 # class ConfigsLocalStorage # Constructor # # **@key** for the storage key # constructor: (@key) -> resolver = new hydrate.ContextResolver Configs:Configs ServerConfig:ServerConfig @hydrate = new hydrate resolver # A private function to initializing config container # initConfigs: (defaultConfig, publicConfig) -> configs = new Configs(defaultConfig, publicConfig) return configs # Load configs from storage. # # * localStorage[] for node-webkit # * node-localstorage for node.js ( mocha test ) # loadConfigs: (defaultConfig = null, publicConfig = null) -> s = @loadString(@key) try if s? configs = @hydrate.parse s configs.setDefaultConfig defaultConfig configs.setPublicConfig publicConfig return configs else return new Configs defaultConfig, publicConfig catch SyntaxError return new Configs defaultConfig, publicConfig s = @hydrate.stringify configs if window? localStorage[@key] = s else localStorage.setItem @key, s # Save configs to storage. # saveConfigs: (configs) -> s = @hydrate.stringify configs if window? localStorage[@key] = s else localStorage.setItem @key, s # A function to test localStorage # loadString: (k=@key) -> return if window? then localStorage[k] else localStorage.getItem k # Return the key for server history # getServerHistoryKey: -> "#{ @key }/history" # Get server history # getServerHistory: -> s = @loadString @getServerHistoryKey() return (s || '').split('|') # Add a new item to server history # addServerHistory: (server) -> servers = @getServerHistory() servers.push server newServers = [] for server in servers if server and server not in newServers newServers.push server s = newServers.join '|' if window? localStorage[@getServerHistoryKey()] = s else localStorage.setItem @getServerHistoryKey(), s reset: -> if window? delete localStorage[@key] delete localStorage[@getServerHistoryKey()] else localStorage.removeItem @key localStorage.removeItem @getServerHistoryKey() exports.ServerConfig = ServerConfig exports.Configs = Configs exports.ConfigsLocalStorage = ConfigsLocalStorage
117423
localStorage = null if window? # node-webkit, apply windows.localStroage localStorage = window.localStorage else # node.js, load node-localstorage LocalStorage = require('node-localstorage').LocalStorage localStorage = new LocalStorage './test_storage' util = require 'util' fs = require 'fs' hydrate = require 'hydrate' # A config of a shadowsocks server # class ServerConfig # Constructor of ServerConfig # constructor: (@server=null, # server address, IP or hostname @server_port=8388, # server port @local_port=1080, # local SOCKS5 proxy port @password=<PASSWORD>, # shadowsocks password @method='aes-256-cfb', # encrypting method @timeout=600 ) -> # timeout in seconds # A container of ServerConfig items # # Accessing config items: # # configs.setConfig n, new ServerConfig() # config = configs.getConfig n # class Configs # The index of the default config @DEFAULT_CONFIG_INDEX = -2 # The index of the public config @PUBLIC_CONFIG_INDEX = -1 # Constructor of Configs # constructor: (@defaultConfig = null, # object of the default config @publicConfig = null ) -> # object of the public config @configs = [] @activeConfigIndex = NaN # Get the **n**th config # getConfig: (n) -> # console.log "getConfig(): #{ n }" if n == null or n == Configs.DEFAULT_CONFIG_INDEX return @defaultConfig else if n == Configs.PUBLIC_CONFIG_INDEX return @publicConfig else return @configs[n] # Set the **n**th config # setConfig: (n, config) -> if n < 0 or n >= @getConfigCount() return null @configs[n] = config # Add a new config to the end # addConfig: (config) -> @configs.push config # Get the count of configs # getConfigCount: -> @configs.length # Delete a config # deleteConfig: (n) -> if (n != null) and (n != Configs.DEFAULT_CONFIG_INDEX) and (n != Configs.PUBLIC_CONFIG_INDEX) @configs.splice n,1 # setActiveConfigIndex will adjust the active index after deleting a config @setActiveConfigIndex @getActiveConfigIndex() # Get the current active config index # getActiveConfigIndex: -> return if @activeConfigIndex? and not isNaN(@activeConfigIndex) \ then @activeConfigIndex \ else Configs.DEFAULT_CONFIG_INDEX # Set the active config index # setActiveConfigIndex: (n) -> if not n? @activeConfigIndex = Configs.PUBLIC_CONFIG_INDEX if n >= @getConfigCount() n = @getConfigCount() - 1 if n >= 0 or n == Configs.DEFAULT_CONFIG_INDEX or n == Configs.PUBLIC_CONFIG_INDEX @activeConfigIndex = n else @activeConfigIndex = Configs.PUBLIC_CONFIG_INDEX # Get the active config # getActiveConfig: -> # console.log "getActiveConfig(): #{ @getActiveConfigIndex() }" return @getConfig @getActiveConfigIndex() # Set default config # setDefaultConfig: (config) -> @defaultConfig = config # Set public config # setPublicConfig: (config) -> @publicConfig = config # The storage of configs, handling loading/saving ops # # Example: # # configsStorage = new args.ConfigsLocalStorage 'key' # confs = configsStorage.loadConfigs # new args.ServerConfig, # new args.ServerConfig # '172.16.31.10', # 8348, # 1080, # '$#HAL9000!', # 'aes-256-cfb', # 600 # class ConfigsLocalStorage # Constructor # # **@key** for the storage key # constructor: (@key) -> resolver = new hydrate.ContextResolver Configs:Configs ServerConfig:ServerConfig @hydrate = new hydrate resolver # A private function to initializing config container # initConfigs: (defaultConfig, publicConfig) -> configs = new Configs(defaultConfig, publicConfig) return configs # Load configs from storage. # # * localStorage[] for node-webkit # * node-localstorage for node.js ( mocha test ) # loadConfigs: (defaultConfig = null, publicConfig = null) -> s = @loadString(@key) try if s? configs = @hydrate.parse s configs.setDefaultConfig defaultConfig configs.setPublicConfig publicConfig return configs else return new Configs defaultConfig, publicConfig catch SyntaxError return new Configs defaultConfig, publicConfig s = @hydrate.stringify configs if window? localStorage[@key] = s else localStorage.setItem @key, s # Save configs to storage. # saveConfigs: (configs) -> s = @hydrate.stringify configs if window? localStorage[@key] = s else localStorage.setItem @key, s # A function to test localStorage # loadString: (k=@key) -> return if window? then localStorage[k] else localStorage.getItem k # Return the key for server history # getServerHistoryKey: -> "#{ @key }/history" # Get server history # getServerHistory: -> s = @loadString @getServerHistoryKey() return (s || '').split('|') # Add a new item to server history # addServerHistory: (server) -> servers = @getServerHistory() servers.push server newServers = [] for server in servers if server and server not in newServers newServers.push server s = newServers.join '|' if window? localStorage[@getServerHistoryKey()] = s else localStorage.setItem @getServerHistoryKey(), s reset: -> if window? delete localStorage[@key] delete localStorage[@getServerHistoryKey()] else localStorage.removeItem @key localStorage.removeItem @getServerHistoryKey() exports.ServerConfig = ServerConfig exports.Configs = Configs exports.ConfigsLocalStorage = ConfigsLocalStorage
true
localStorage = null if window? # node-webkit, apply windows.localStroage localStorage = window.localStorage else # node.js, load node-localstorage LocalStorage = require('node-localstorage').LocalStorage localStorage = new LocalStorage './test_storage' util = require 'util' fs = require 'fs' hydrate = require 'hydrate' # A config of a shadowsocks server # class ServerConfig # Constructor of ServerConfig # constructor: (@server=null, # server address, IP or hostname @server_port=8388, # server port @local_port=1080, # local SOCKS5 proxy port @password=PI:PASSWORD:<PASSWORD>END_PI, # shadowsocks password @method='aes-256-cfb', # encrypting method @timeout=600 ) -> # timeout in seconds # A container of ServerConfig items # # Accessing config items: # # configs.setConfig n, new ServerConfig() # config = configs.getConfig n # class Configs # The index of the default config @DEFAULT_CONFIG_INDEX = -2 # The index of the public config @PUBLIC_CONFIG_INDEX = -1 # Constructor of Configs # constructor: (@defaultConfig = null, # object of the default config @publicConfig = null ) -> # object of the public config @configs = [] @activeConfigIndex = NaN # Get the **n**th config # getConfig: (n) -> # console.log "getConfig(): #{ n }" if n == null or n == Configs.DEFAULT_CONFIG_INDEX return @defaultConfig else if n == Configs.PUBLIC_CONFIG_INDEX return @publicConfig else return @configs[n] # Set the **n**th config # setConfig: (n, config) -> if n < 0 or n >= @getConfigCount() return null @configs[n] = config # Add a new config to the end # addConfig: (config) -> @configs.push config # Get the count of configs # getConfigCount: -> @configs.length # Delete a config # deleteConfig: (n) -> if (n != null) and (n != Configs.DEFAULT_CONFIG_INDEX) and (n != Configs.PUBLIC_CONFIG_INDEX) @configs.splice n,1 # setActiveConfigIndex will adjust the active index after deleting a config @setActiveConfigIndex @getActiveConfigIndex() # Get the current active config index # getActiveConfigIndex: -> return if @activeConfigIndex? and not isNaN(@activeConfigIndex) \ then @activeConfigIndex \ else Configs.DEFAULT_CONFIG_INDEX # Set the active config index # setActiveConfigIndex: (n) -> if not n? @activeConfigIndex = Configs.PUBLIC_CONFIG_INDEX if n >= @getConfigCount() n = @getConfigCount() - 1 if n >= 0 or n == Configs.DEFAULT_CONFIG_INDEX or n == Configs.PUBLIC_CONFIG_INDEX @activeConfigIndex = n else @activeConfigIndex = Configs.PUBLIC_CONFIG_INDEX # Get the active config # getActiveConfig: -> # console.log "getActiveConfig(): #{ @getActiveConfigIndex() }" return @getConfig @getActiveConfigIndex() # Set default config # setDefaultConfig: (config) -> @defaultConfig = config # Set public config # setPublicConfig: (config) -> @publicConfig = config # The storage of configs, handling loading/saving ops # # Example: # # configsStorage = new args.ConfigsLocalStorage 'key' # confs = configsStorage.loadConfigs # new args.ServerConfig, # new args.ServerConfig # 'PI:IP_ADDRESS:172.16.31.10END_PI', # 8348, # 1080, # '$#HAL9000!', # 'aes-256-cfb', # 600 # class ConfigsLocalStorage # Constructor # # **@key** for the storage key # constructor: (@key) -> resolver = new hydrate.ContextResolver Configs:Configs ServerConfig:ServerConfig @hydrate = new hydrate resolver # A private function to initializing config container # initConfigs: (defaultConfig, publicConfig) -> configs = new Configs(defaultConfig, publicConfig) return configs # Load configs from storage. # # * localStorage[] for node-webkit # * node-localstorage for node.js ( mocha test ) # loadConfigs: (defaultConfig = null, publicConfig = null) -> s = @loadString(@key) try if s? configs = @hydrate.parse s configs.setDefaultConfig defaultConfig configs.setPublicConfig publicConfig return configs else return new Configs defaultConfig, publicConfig catch SyntaxError return new Configs defaultConfig, publicConfig s = @hydrate.stringify configs if window? localStorage[@key] = s else localStorage.setItem @key, s # Save configs to storage. # saveConfigs: (configs) -> s = @hydrate.stringify configs if window? localStorage[@key] = s else localStorage.setItem @key, s # A function to test localStorage # loadString: (k=@key) -> return if window? then localStorage[k] else localStorage.getItem k # Return the key for server history # getServerHistoryKey: -> "#{ @key }/history" # Get server history # getServerHistory: -> s = @loadString @getServerHistoryKey() return (s || '').split('|') # Add a new item to server history # addServerHistory: (server) -> servers = @getServerHistory() servers.push server newServers = [] for server in servers if server and server not in newServers newServers.push server s = newServers.join '|' if window? localStorage[@getServerHistoryKey()] = s else localStorage.setItem @getServerHistoryKey(), s reset: -> if window? delete localStorage[@key] delete localStorage[@getServerHistoryKey()] else localStorage.removeItem @key localStorage.removeItem @getServerHistoryKey() exports.ServerConfig = ServerConfig exports.Configs = Configs exports.ConfigsLocalStorage = ConfigsLocalStorage
[ { "context": " id = ''\n doc = {}\n data =\n name: 'Look, an event!'\n date: '4/3/21'\n\n # ==== He", "end": 378, "score": 0.6636850833892822, "start": 374, "tag": "NAME", "value": "Look" }, { "context": "one)->\n event =\n name: 'An Event'\n date: '1/2/34'\n\n serv", "end": 1517, "score": 0.8336039781570435, "start": 1509, "tag": "NAME", "value": "An Event" }, { "context": " _id: id\n name: 'An Event'\n date: '1/2/34'\n\n ", "end": 1912, "score": 0.8765031099319458, "start": 1904, "tag": "NAME", "value": "An Event" }, { "context": " newData =\n name: 'A new event'\n date: '9/8/76'\n\n ", "end": 3520, "score": 0.6210353970527649, "start": 3509, "tag": "NAME", "value": "A new event" }, { "context": " newData =\n name: 'A new event'\n\n expected =\n ", "end": 4151, "score": 0.7012861371040344, "start": 4140, "tag": "NAME", "value": "A new event" } ]
tests/default-controllers.test.coffee
mattbalmer/monsoon
1
supertest = require 'supertest' db = require './helpers/db' h = require './helpers/common' {last, status, body, expectDocument} = require './helpers/supertest' describe 'http-controllers', -> server = supertest 'http://localhost:3000/api/events' # ==== Sample Data ==== sampleId = '0123456789abcdefghijklmn' id = '' doc = {} data = name: 'Look, an event!' date: '4/3/21' # ==== Helper Functions ==== clearCollection = (done)-> db.Event.collection.remove {}, ()-> done() create = (done)-> db.Event.create data, (err, _doc)-> throw new Error('Setup failed to create an Event') if err throw new Error('Setup failed to create an Event') unless h.aIncludesB(_doc, data) doc = h.docObj(_doc) id = doc._id done(_doc) # ==== Before ==== before (done)-> db.drop(done) beforeEach (done)-> id = sampleId doc = {} clearCollection(done) # ==== Tests ==== describe 'GET /', -> it 'no entries', (done)-> server.get '/' .expect status 200 .expect body [] .end done it 'one entry', (done)-> create ()-> server.get '/' .expect status 200 .expect body [doc] .end done describe 'POST /', -> it 'successful insertion', (done)-> event = name: 'An Event' date: '1/2/34' server.post '/' .send event .expect status 201 .end last (res)-> expectDocument res.body._id .toEqual res.body .end done it 'conflict', (done)-> create ()-> event = _id: id name: 'An Event' date: '1/2/34' server.post '/' .send event .expect status 409 .expect body {} .end done it 'missing required fields', (done)-> create ()-> event = date: '1/2/34' server.post '/' .send event .expect status 500 .expect body {} .end done describe 'GET /:id', -> it 'not found', (done)-> server.get '/'+id .expect status 404 .expect body '' .end done it 'found', (done)-> create ()-> server.get '/'+id .expect status 200 .expect body doc .end done describe 'DELETE /:id', -> it 'not found', (done)-> server.delete '/'+id .expect status 404 .expect body '' .end done it 'deleted', (done)-> create ()-> server.delete '/'+id .expect status 204 .expect body {} .end last (res)-> expectDocument doc._id .toEqual null .end done describe 'PUT /:id', -> it 'not found', (done)-> server.put '/'+id .expect status 404 .expect body '' .end done it 'overwritten', (done)-> create ()-> newData = name: 'A new event' date: '9/8/76' server.put '/'+id .send newData .expect status 200 .expect body.includes newData .end last (res)-> expectDocument res.body._id .toInclude newData .end done describe 'PATCH /:id', -> it 'not found', (done)-> server.patch '/'+id .expect status 404 .expect body '' .end done it 'updated', (done)-> create ()-> newData = name: 'A new event' expected = name: newData.name date: data.date server.patch '/'+id .send newData .expect status 200 .expect body.includes expected .end last (res)-> expectDocument res.body._id .toInclude newData .end done
193018
supertest = require 'supertest' db = require './helpers/db' h = require './helpers/common' {last, status, body, expectDocument} = require './helpers/supertest' describe 'http-controllers', -> server = supertest 'http://localhost:3000/api/events' # ==== Sample Data ==== sampleId = '0123456789abcdefghijklmn' id = '' doc = {} data = name: '<NAME>, an event!' date: '4/3/21' # ==== Helper Functions ==== clearCollection = (done)-> db.Event.collection.remove {}, ()-> done() create = (done)-> db.Event.create data, (err, _doc)-> throw new Error('Setup failed to create an Event') if err throw new Error('Setup failed to create an Event') unless h.aIncludesB(_doc, data) doc = h.docObj(_doc) id = doc._id done(_doc) # ==== Before ==== before (done)-> db.drop(done) beforeEach (done)-> id = sampleId doc = {} clearCollection(done) # ==== Tests ==== describe 'GET /', -> it 'no entries', (done)-> server.get '/' .expect status 200 .expect body [] .end done it 'one entry', (done)-> create ()-> server.get '/' .expect status 200 .expect body [doc] .end done describe 'POST /', -> it 'successful insertion', (done)-> event = name: '<NAME>' date: '1/2/34' server.post '/' .send event .expect status 201 .end last (res)-> expectDocument res.body._id .toEqual res.body .end done it 'conflict', (done)-> create ()-> event = _id: id name: '<NAME>' date: '1/2/34' server.post '/' .send event .expect status 409 .expect body {} .end done it 'missing required fields', (done)-> create ()-> event = date: '1/2/34' server.post '/' .send event .expect status 500 .expect body {} .end done describe 'GET /:id', -> it 'not found', (done)-> server.get '/'+id .expect status 404 .expect body '' .end done it 'found', (done)-> create ()-> server.get '/'+id .expect status 200 .expect body doc .end done describe 'DELETE /:id', -> it 'not found', (done)-> server.delete '/'+id .expect status 404 .expect body '' .end done it 'deleted', (done)-> create ()-> server.delete '/'+id .expect status 204 .expect body {} .end last (res)-> expectDocument doc._id .toEqual null .end done describe 'PUT /:id', -> it 'not found', (done)-> server.put '/'+id .expect status 404 .expect body '' .end done it 'overwritten', (done)-> create ()-> newData = name: '<NAME>' date: '9/8/76' server.put '/'+id .send newData .expect status 200 .expect body.includes newData .end last (res)-> expectDocument res.body._id .toInclude newData .end done describe 'PATCH /:id', -> it 'not found', (done)-> server.patch '/'+id .expect status 404 .expect body '' .end done it 'updated', (done)-> create ()-> newData = name: '<NAME>' expected = name: newData.name date: data.date server.patch '/'+id .send newData .expect status 200 .expect body.includes expected .end last (res)-> expectDocument res.body._id .toInclude newData .end done
true
supertest = require 'supertest' db = require './helpers/db' h = require './helpers/common' {last, status, body, expectDocument} = require './helpers/supertest' describe 'http-controllers', -> server = supertest 'http://localhost:3000/api/events' # ==== Sample Data ==== sampleId = '0123456789abcdefghijklmn' id = '' doc = {} data = name: 'PI:NAME:<NAME>END_PI, an event!' date: '4/3/21' # ==== Helper Functions ==== clearCollection = (done)-> db.Event.collection.remove {}, ()-> done() create = (done)-> db.Event.create data, (err, _doc)-> throw new Error('Setup failed to create an Event') if err throw new Error('Setup failed to create an Event') unless h.aIncludesB(_doc, data) doc = h.docObj(_doc) id = doc._id done(_doc) # ==== Before ==== before (done)-> db.drop(done) beforeEach (done)-> id = sampleId doc = {} clearCollection(done) # ==== Tests ==== describe 'GET /', -> it 'no entries', (done)-> server.get '/' .expect status 200 .expect body [] .end done it 'one entry', (done)-> create ()-> server.get '/' .expect status 200 .expect body [doc] .end done describe 'POST /', -> it 'successful insertion', (done)-> event = name: 'PI:NAME:<NAME>END_PI' date: '1/2/34' server.post '/' .send event .expect status 201 .end last (res)-> expectDocument res.body._id .toEqual res.body .end done it 'conflict', (done)-> create ()-> event = _id: id name: 'PI:NAME:<NAME>END_PI' date: '1/2/34' server.post '/' .send event .expect status 409 .expect body {} .end done it 'missing required fields', (done)-> create ()-> event = date: '1/2/34' server.post '/' .send event .expect status 500 .expect body {} .end done describe 'GET /:id', -> it 'not found', (done)-> server.get '/'+id .expect status 404 .expect body '' .end done it 'found', (done)-> create ()-> server.get '/'+id .expect status 200 .expect body doc .end done describe 'DELETE /:id', -> it 'not found', (done)-> server.delete '/'+id .expect status 404 .expect body '' .end done it 'deleted', (done)-> create ()-> server.delete '/'+id .expect status 204 .expect body {} .end last (res)-> expectDocument doc._id .toEqual null .end done describe 'PUT /:id', -> it 'not found', (done)-> server.put '/'+id .expect status 404 .expect body '' .end done it 'overwritten', (done)-> create ()-> newData = name: 'PI:NAME:<NAME>END_PI' date: '9/8/76' server.put '/'+id .send newData .expect status 200 .expect body.includes newData .end last (res)-> expectDocument res.body._id .toInclude newData .end done describe 'PATCH /:id', -> it 'not found', (done)-> server.patch '/'+id .expect status 404 .expect body '' .end done it 'updated', (done)-> create ()-> newData = name: 'PI:NAME:<NAME>END_PI' expected = name: newData.name date: data.date server.patch '/'+id .send newData .expect status 200 .expect body.includes expected .end last (res)-> expectDocument res.body._id .toInclude newData .end done
[ { "context": "#\n# Author: Peter K. Lee (peter@corenova.com)\n#\n# All rights reserved. Thi", "end": 24, "score": 0.9998681545257568, "start": 12, "tag": "NAME", "value": "Peter K. Lee" }, { "context": "#\n# Author: Peter K. Lee (peter@corenova.com)\n#\n# All rights reserved. This program and the ac", "end": 44, "score": 0.9999251365661621, "start": 26, "tag": "EMAIL", "value": "peter@corenova.com" } ]
src/server.coffee
opencord/composer
0
# # Author: Peter K. Lee (peter@corenova.com) # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 # Yang = require('yang-js') app = require('yang-express') -> @enable 'yangapi' @enable 'openapi', require('../package.json') @enable 'restjson' @enable 'websocket' @open 'cord', -> @import Yang.require('cord-core') @import Yang.require('xos-core') @connect require('../sample-data.json') @on 'update', (prop) -> console.log "[#{prop.path}] got updated, should consider persisting the change somewhere" module.exports = app # only start if directly invoked if require.main is module argv = require('minimist')(process.argv.slice(2)) argv.port ?= 5050 app.listen argv.port
30864
# # Author: <NAME> (<EMAIL>) # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 # Yang = require('yang-js') app = require('yang-express') -> @enable 'yangapi' @enable 'openapi', require('../package.json') @enable 'restjson' @enable 'websocket' @open 'cord', -> @import Yang.require('cord-core') @import Yang.require('xos-core') @connect require('../sample-data.json') @on 'update', (prop) -> console.log "[#{prop.path}] got updated, should consider persisting the change somewhere" module.exports = app # only start if directly invoked if require.main is module argv = require('minimist')(process.argv.slice(2)) argv.port ?= 5050 app.listen argv.port
true
# # Author: PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI) # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 # Yang = require('yang-js') app = require('yang-express') -> @enable 'yangapi' @enable 'openapi', require('../package.json') @enable 'restjson' @enable 'websocket' @open 'cord', -> @import Yang.require('cord-core') @import Yang.require('xos-core') @connect require('../sample-data.json') @on 'update', (prop) -> console.log "[#{prop.path}] got updated, should consider persisting the change somewhere" module.exports = app # only start if directly invoked if require.main is module argv = require('minimist')(process.argv.slice(2)) argv.port ?= 5050 app.listen argv.port
[ { "context": "\n\n ciphers : () -> [ \"aes-256-cbc\", \"camellia-256-cbc\" ]\n\n num_ciphers : () -> @ciphers().length\n\n ", "end": 1803, "score": 0.5523456931114197, "start": 1803, "tag": "KEY", "value": "" }, { "context": " @ciphers = for c, i in ciphers\n key = @keys[c.split(\"-\")[0]]\n iv = @_ivs[i]\n fn = if", "end": 5822, "score": 0.8643845915794373, "start": 5822, "tag": "KEY", "value": "" }, { "context": " @ciphers = for c, i in ciphers\n key = @keys[c.split(\"-\")[0]]\n iv = @_ivs[i]\n fn = if enc then crypto", "end": 5839, "score": 0.9244292974472046, "start": 5823, "tag": "KEY", "value": "c.split(\"-\")[0]]" } ]
src/attic/crypto.iced
AngelKey/Angelkey.nodeclient
151
crypto = require 'crypto' purepack = require 'purepack' log = require './log' {constants} = require './constants' stream = require 'stream' {Queue} = require './queue' iced.catchExceptions() #================================================================== pack2 = (o) -> b1 = purepack.pack o, 'buffer', { byte_arrays : true } b0 = purepack.pack b1.length, 'buffer' Buffer.concat [ b0, b1 ] #================================================================== # pad datasz bytes to be a multiple of blocksz pkcs7_padding = (datasz, blocksz) -> plen = blocksz - (datasz % blocksz) new Buffer (plen for i in plen) #================================================================== bufeq = (b1, b2) -> return false unless b1.length is b2.length for b, i in b1 return false unless b is b2[i] return true #================================================================== nibble_to_str = (n) -> ret = n.toString 16 ret = "0" + ret if ret.length is 1 ret #================================================================== dump_buf = (b) -> l = b.length bytes = (nibble_to_str c for c in b) "Buffer(#{l})<#{bytes.join ' '}>" #================================================================== secure_bufeq = (b1, b2) -> ret = true if b1.length isnt b2.length ret = false else for b, i in b1 ret = false unless b is b2[i] return ret #================================================================== class AlgoFactory constructor : -> # Keysize in bytes for AES256 and Blowfish @ENC_KEY_SIZE = 32 @ENC_BLOCK_SIZE = 16 # Use the same keysize for our MAC too @MAC_KEY_SIZE = 32 @MAC_OUT_SIZE = 32 total_key_size : () -> 2 * @ENC_KEY_SIZE + @MAC_KEY_SIZE ciphers : () -> [ "aes-256-cbc", "camellia-256-cbc" ] num_ciphers : () -> @ciphers().length pad : (buf) -> padding = pkcs7_padding buf.length, @ENC_BLOCK_SIZE Buffer.concat [ buf, padding ] produce_keys : (bytes) -> eks = @ENC_KEY_SIZE mks = @MAC_KEY_SIZE parts = keysplit bytes, [ eks, eks, mks ] ret = { aes : parts[0] camellia : parts[1] hmac : parts[2] } ret #================================================================== gaf = new AlgoFactory() #================================================================== class FooterizingFilter #---------------- constructor : (@filesz) -> @_i = 0 @_footer_blocks = [] @_footer_len = null #---------------- filter : (block) -> # See Preamble --- the footer len is encoded in the first byte # of the file. This is a hack that should work for all practical # purposes. @_footer_len = block[0] unless @_footer_len? # Bytes of the body of the file that remain. bdrem = @filesz - @_i - @_footer_len if block.length > bdrem footer_part = if (bdrem > 0) then block[bdrem...] else block @_footer_blocks.push footer_part ret = if (bdrem > 0) then block[0...bdrem] else null else ret = block @_i += block.length return ret #---------------- footer : () -> ret = Buffer.concat @_footer_blocks if ret.length isnt @_footer_len log.warn "Got wrong footer size; wanted #{@_footer_len}, but got #{ret.length}" ret #================================================================== class Preamble @pack : () -> C = constants.Preamble i = new Buffer 4 i.writeUInt32BE C.FILE_VERSION, 0 ret = Buffer.concat [ new Buffer(C.FILE_MAGIC), i ] # As a pseudo-hack, the first byte is the length of the footer. # This makes framing the file convenient. footer_len = pack2(new Buffer [0...(gaf.MAC_OUT_SIZE) ]).length ret[0] = footer_len ret @unpack : (b) -> bufeq Preamble.pack(), b @len : () -> 12 #================================================================== msgpack_packed_numlen = (byt) -> if byt < 0x80 then 1 else if byt is 0xcc then 2 else if byt is 0xcd then 3 else if byt is 0xce then 5 else if byt is 0xcf then 9 else 0 #================================================================== keysplit = (key, splits) -> ret = [] start = 0 for s in splits end = start + s ret.push key[start...end] start = end ret.push key[start...] ret #================================================================== class Transform extends stream.Transform #--------------------------- constructor : (pipe_opts) -> super pipe_opts @_blocks = [] @_disable_ciphers() @_disable_streaming() @_ivs = null #--------------------------- _enable_ciphers : -> @_cipher_fn = (block) => @_update_ciphers block _disable_ciphers : -> @_cipher_fn = (block) => block #--------------------------- _disable_streaming : -> @_blocks = [] @_sink_fn = (block) -> @_blocks.push block #--------------------------- _enable_streaming : -> buf = Buffer.concat @_blocks @_blocks = [] @push buf @_sink_fn = (block) -> @push block #--------------------------- _send_to_sink : (block, cb) -> @_sink_fn @_process block cb() if cb? #--------------------------- _process : (chunk) -> @_mac @_cipher_fn chunk #--------------------------- _prepare_macs : () -> # One mac for the header, and another for the whole file (including # the header MAC) @macs = (crypto.createHmac('sha256', @keys.hmac) for i in [0...2]) #--------------------------- _mac : (block) -> for m,i in @macs m.update block block #--------------------------- _prepare_ciphers : () -> enc = @is_enc() ciphers = gaf.ciphers() @_ivs = (crypto.rng(gaf.ENC_BLOCK_SIZE) for i in ciphers) unless @_ivs? prev = null @ciphers = for c, i in ciphers key = @keys[c.split("-")[0]] iv = @_ivs[i] fn = if enc then crypto.createCipheriv else crypto.createDecipheriv fn c, key, iv # decrypt in the opposite order @ciphers.reverse() unless enc #--------------------------- # Called before init_stream() to key our ciphers and MACs. setup_keys : (cb) -> if @key_material? if (got = @key_material.length) is (wanted = gaf.total_key_size()) km = @key_material else log.error "Key material size mismatch: #{got} != #{wanted}" else await derive_key_material @pwmgr, @is_enc(), defer km if km @keys = gaf.produce_keys km ok = true else ok = false cb ok #--------------------------- # Chain the ciphers together, without any additional buffering from # pipes. We're going to simplify this alot... _update_ciphers : (chunk) -> for c in @ciphers chunk = c.update chunk chunk #--------------------------- # Cascading final update, the final from one cipher needs to be # run through all of the downstream ciphers... _final : () -> bufs = for c,i in @ciphers chunk = c.final() for d in @ciphers[(i+1)...] chunk = d.update chunk chunk Buffer.concat bufs #--------------------------- init : (cb) -> await @setup_keys defer ok @init_stream() if ok cb ok #================================================================== exports.derive_key_material = derive_key_material = (pwmgr, enc, cb) -> tks = gaf.total_key_size() await pwmgr.derive_key_material tks, enc, defer km cb km #================================================================== exports.Encryptor = class Encryptor extends Transform constructor : ({@stat, @pwmgr}, pipe_opts) -> super pipe_opts @packed_stat = pack2 @stat, 'buffer' #--------------------------- validate : () -> [ true ] is_enc : () -> true version : () -> constants.VERSION #--------------------------- _flush_ciphers : () -> @_sink_fn @_mac @_final() #--------------------------- _write_preamble : () -> @_send_to_sink Preamble.pack() _write_pack : (d) -> @_send_to_sink pack2 d _write_header : () -> @_write_pack @_make_header() _write_mac : () -> @_write_pack @macs.pop().digest() _write_metadata : () -> @_send_to_sink @packed_stat #--------------------------- _make_header : () -> out = version : constants.VERSION ivs : @_ivs statsize : @packed_stat.length filesize : @stat.size return out #--------------------------- _flush : (cb) -> @_flush_ciphers() @_disable_ciphers() @_write_mac() cb() #--------------------------- init_stream : () -> @_prepare_ciphers() @_prepare_macs() @_write_preamble() @_write_header() @_write_mac() # Finally, we're starting to encrypt... @_enable_ciphers() @_write_metadata() # Now, we're all set, and subsequent operations are going # to stream to the output.... @_enable_streaming() #--------------------------- _transform : (block, encoding, cb) -> @_send_to_sink block, cb #================================================================== [HEADER, BODY, FOOTER] = [0..2] #================================================================== exports.Decryptor = class Decryptor extends Transform constructor : ({@pwmgr, @stat, @total_size, @key_material}, pipe_opts) -> super pipe_opts @_section = HEADER @_n = 0 # number of body bytes reads @_q = new Queue @_enable_clear_queuing() @total_size = @stat.size if @stat? and not @total_size? if not @total_size? throw new Error "cannot find filesize" @_ff = new FooterizingFilter @total_size #--------------------------- is_enc : () -> false #--------------------------- _enable_clear_queuing : -> @_enqueue = (block) => @_q.push block @_dequeue = (n, cb) => await @_q.read n, defer b @_mac b if b? cb b #--------------------------- _enable_deciphered_queueing : -> @_enqueue = (block) -> if block? @_mac block out = @_update_ciphers block @_q.push out @_dequeue = (n, cb) => @_q.read n, cb #--------------------------- _disable_queueing : -> @_enqueue = null @_dequeue = null #--------------------------- _read_preamble : (cb) -> await @_dequeue Preamble.len(), defer b ok = Preamble.unpack b log.error "Failed to unpack preamble: #{b.inspect()}" unless ok cb ok #--------------------------- _read_unpack : (cb) -> await @_dequeue 1, defer b0 framelen = msgpack_packed_numlen b0[0] if framelen is 0 log.error "Bad msgpack len header: #{b.inspect()}" else if framelen > 1 # Read the rest out... await @_dequeue (framelen-1), defer b1 b = Buffer.concat [b0, b1] else b = b0 # We've read the framing in two parts -- the first byte # and then the rest [err, frame] = purepack.unpack b if err? log.error "In reading msgpack frame: #{err}" else if not (typeof(frame) is 'number') log.error "Expected frame as a number: got #{frame}" else await @_dequeue frame, defer b [err, out] = purepack.unpack b log.error "In unpacking #{b.inspect()}: #{err}" if err? cb out #--------------------------- _read_header : (cb) -> ok = false await @_read_unpack defer @hdr if not @hdr? log.error "Failed to read header" else if @hdr.version isnt constants.VERSION log.error "Only know version #{constants.VERSION}; got #{@hdr.version}" else if not (@_ivs = @hdr.ivs)? or (@_ivs.length isnt gaf.num_ciphers()) log.error "Malformed headers; didn't find #{gaf.num_ciphers()} IVs" else ok = true cb ok #--------------------------- _check_mac : (cb) -> wanted = @macs.pop().digest() await @_read_unpack defer given ok = false if not given? log.error "Couldn't read MAC from file" else if not secure_bufeq given, wanted log.error "Header MAC mismatch error" else ok = true cb ok #--------------------------- _enable_queued_ciphertext : () => buf = @_q.flush() @_enable_deciphered_queueing() @_enqueue buf #--------------------------- init_stream : () -> ok = true @_prepare_macs() # Set this up to fly in the background... @_read_headers() #--------------------------- _read_headers : (cb) -> await @_read_preamble defer ok await @_read_header defer ok if ok # can only prepare the ciphers after we've read the header # (since the header has the IV!) @_prepare_ciphers() await @_check_mac defer ok if ok @_enable_queued_ciphertext() if ok await @_read_metadata defer ok if ok @_start_body() if ok cb?() #--------------------------- validate : () -> if @_final_mac_ok then [ true, null ] else [ false, "Full-file MAC failed" ] #--------------------------- _flush : (cb)-> # First flush the decryption pipeline and write any # new blocks out to the output stream block = @_final() @push block if block? and block.length # Now change over the clear block queuing. @_enable_clear_queuing() # The footer is in the FooterizingFilter, which kept the # last N bytes of the stream... @_enqueue @_ff.footer() # Finally, we can check the mac and hope that it works... await @_check_mac defer @_final_mac_ok cb() #--------------------------- _stream_body : (block, cb) -> @push bl if (bl = @_update_ciphers @_mac block)? cb?() #--------------------------- _start_body : () -> @_section = BODY buf = @_q.flush() @_disable_queueing() @push buf #--------------------------- _read_metadata : (cb) -> await @_read_unpack defer @_metadata cb !!@_metadata #--------------------------- _transform : (block, encoding, cb) -> block = @_ff.filter block if not block? or not block.length then null else if @_enqueue? then @_enqueue block else await @_stream_body block, defer() cb() #==================================================================
144590
crypto = require 'crypto' purepack = require 'purepack' log = require './log' {constants} = require './constants' stream = require 'stream' {Queue} = require './queue' iced.catchExceptions() #================================================================== pack2 = (o) -> b1 = purepack.pack o, 'buffer', { byte_arrays : true } b0 = purepack.pack b1.length, 'buffer' Buffer.concat [ b0, b1 ] #================================================================== # pad datasz bytes to be a multiple of blocksz pkcs7_padding = (datasz, blocksz) -> plen = blocksz - (datasz % blocksz) new Buffer (plen for i in plen) #================================================================== bufeq = (b1, b2) -> return false unless b1.length is b2.length for b, i in b1 return false unless b is b2[i] return true #================================================================== nibble_to_str = (n) -> ret = n.toString 16 ret = "0" + ret if ret.length is 1 ret #================================================================== dump_buf = (b) -> l = b.length bytes = (nibble_to_str c for c in b) "Buffer(#{l})<#{bytes.join ' '}>" #================================================================== secure_bufeq = (b1, b2) -> ret = true if b1.length isnt b2.length ret = false else for b, i in b1 ret = false unless b is b2[i] return ret #================================================================== class AlgoFactory constructor : -> # Keysize in bytes for AES256 and Blowfish @ENC_KEY_SIZE = 32 @ENC_BLOCK_SIZE = 16 # Use the same keysize for our MAC too @MAC_KEY_SIZE = 32 @MAC_OUT_SIZE = 32 total_key_size : () -> 2 * @ENC_KEY_SIZE + @MAC_KEY_SIZE ciphers : () -> [ "aes-256-cbc", "camellia-256<KEY>-cbc" ] num_ciphers : () -> @ciphers().length pad : (buf) -> padding = pkcs7_padding buf.length, @ENC_BLOCK_SIZE Buffer.concat [ buf, padding ] produce_keys : (bytes) -> eks = @ENC_KEY_SIZE mks = @MAC_KEY_SIZE parts = keysplit bytes, [ eks, eks, mks ] ret = { aes : parts[0] camellia : parts[1] hmac : parts[2] } ret #================================================================== gaf = new AlgoFactory() #================================================================== class FooterizingFilter #---------------- constructor : (@filesz) -> @_i = 0 @_footer_blocks = [] @_footer_len = null #---------------- filter : (block) -> # See Preamble --- the footer len is encoded in the first byte # of the file. This is a hack that should work for all practical # purposes. @_footer_len = block[0] unless @_footer_len? # Bytes of the body of the file that remain. bdrem = @filesz - @_i - @_footer_len if block.length > bdrem footer_part = if (bdrem > 0) then block[bdrem...] else block @_footer_blocks.push footer_part ret = if (bdrem > 0) then block[0...bdrem] else null else ret = block @_i += block.length return ret #---------------- footer : () -> ret = Buffer.concat @_footer_blocks if ret.length isnt @_footer_len log.warn "Got wrong footer size; wanted #{@_footer_len}, but got #{ret.length}" ret #================================================================== class Preamble @pack : () -> C = constants.Preamble i = new Buffer 4 i.writeUInt32BE C.FILE_VERSION, 0 ret = Buffer.concat [ new Buffer(C.FILE_MAGIC), i ] # As a pseudo-hack, the first byte is the length of the footer. # This makes framing the file convenient. footer_len = pack2(new Buffer [0...(gaf.MAC_OUT_SIZE) ]).length ret[0] = footer_len ret @unpack : (b) -> bufeq Preamble.pack(), b @len : () -> 12 #================================================================== msgpack_packed_numlen = (byt) -> if byt < 0x80 then 1 else if byt is 0xcc then 2 else if byt is 0xcd then 3 else if byt is 0xce then 5 else if byt is 0xcf then 9 else 0 #================================================================== keysplit = (key, splits) -> ret = [] start = 0 for s in splits end = start + s ret.push key[start...end] start = end ret.push key[start...] ret #================================================================== class Transform extends stream.Transform #--------------------------- constructor : (pipe_opts) -> super pipe_opts @_blocks = [] @_disable_ciphers() @_disable_streaming() @_ivs = null #--------------------------- _enable_ciphers : -> @_cipher_fn = (block) => @_update_ciphers block _disable_ciphers : -> @_cipher_fn = (block) => block #--------------------------- _disable_streaming : -> @_blocks = [] @_sink_fn = (block) -> @_blocks.push block #--------------------------- _enable_streaming : -> buf = Buffer.concat @_blocks @_blocks = [] @push buf @_sink_fn = (block) -> @push block #--------------------------- _send_to_sink : (block, cb) -> @_sink_fn @_process block cb() if cb? #--------------------------- _process : (chunk) -> @_mac @_cipher_fn chunk #--------------------------- _prepare_macs : () -> # One mac for the header, and another for the whole file (including # the header MAC) @macs = (crypto.createHmac('sha256', @keys.hmac) for i in [0...2]) #--------------------------- _mac : (block) -> for m,i in @macs m.update block block #--------------------------- _prepare_ciphers : () -> enc = @is_enc() ciphers = gaf.ciphers() @_ivs = (crypto.rng(gaf.ENC_BLOCK_SIZE) for i in ciphers) unless @_ivs? prev = null @ciphers = for c, i in ciphers key = @keys<KEY>[<KEY> iv = @_ivs[i] fn = if enc then crypto.createCipheriv else crypto.createDecipheriv fn c, key, iv # decrypt in the opposite order @ciphers.reverse() unless enc #--------------------------- # Called before init_stream() to key our ciphers and MACs. setup_keys : (cb) -> if @key_material? if (got = @key_material.length) is (wanted = gaf.total_key_size()) km = @key_material else log.error "Key material size mismatch: #{got} != #{wanted}" else await derive_key_material @pwmgr, @is_enc(), defer km if km @keys = gaf.produce_keys km ok = true else ok = false cb ok #--------------------------- # Chain the ciphers together, without any additional buffering from # pipes. We're going to simplify this alot... _update_ciphers : (chunk) -> for c in @ciphers chunk = c.update chunk chunk #--------------------------- # Cascading final update, the final from one cipher needs to be # run through all of the downstream ciphers... _final : () -> bufs = for c,i in @ciphers chunk = c.final() for d in @ciphers[(i+1)...] chunk = d.update chunk chunk Buffer.concat bufs #--------------------------- init : (cb) -> await @setup_keys defer ok @init_stream() if ok cb ok #================================================================== exports.derive_key_material = derive_key_material = (pwmgr, enc, cb) -> tks = gaf.total_key_size() await pwmgr.derive_key_material tks, enc, defer km cb km #================================================================== exports.Encryptor = class Encryptor extends Transform constructor : ({@stat, @pwmgr}, pipe_opts) -> super pipe_opts @packed_stat = pack2 @stat, 'buffer' #--------------------------- validate : () -> [ true ] is_enc : () -> true version : () -> constants.VERSION #--------------------------- _flush_ciphers : () -> @_sink_fn @_mac @_final() #--------------------------- _write_preamble : () -> @_send_to_sink Preamble.pack() _write_pack : (d) -> @_send_to_sink pack2 d _write_header : () -> @_write_pack @_make_header() _write_mac : () -> @_write_pack @macs.pop().digest() _write_metadata : () -> @_send_to_sink @packed_stat #--------------------------- _make_header : () -> out = version : constants.VERSION ivs : @_ivs statsize : @packed_stat.length filesize : @stat.size return out #--------------------------- _flush : (cb) -> @_flush_ciphers() @_disable_ciphers() @_write_mac() cb() #--------------------------- init_stream : () -> @_prepare_ciphers() @_prepare_macs() @_write_preamble() @_write_header() @_write_mac() # Finally, we're starting to encrypt... @_enable_ciphers() @_write_metadata() # Now, we're all set, and subsequent operations are going # to stream to the output.... @_enable_streaming() #--------------------------- _transform : (block, encoding, cb) -> @_send_to_sink block, cb #================================================================== [HEADER, BODY, FOOTER] = [0..2] #================================================================== exports.Decryptor = class Decryptor extends Transform constructor : ({@pwmgr, @stat, @total_size, @key_material}, pipe_opts) -> super pipe_opts @_section = HEADER @_n = 0 # number of body bytes reads @_q = new Queue @_enable_clear_queuing() @total_size = @stat.size if @stat? and not @total_size? if not @total_size? throw new Error "cannot find filesize" @_ff = new FooterizingFilter @total_size #--------------------------- is_enc : () -> false #--------------------------- _enable_clear_queuing : -> @_enqueue = (block) => @_q.push block @_dequeue = (n, cb) => await @_q.read n, defer b @_mac b if b? cb b #--------------------------- _enable_deciphered_queueing : -> @_enqueue = (block) -> if block? @_mac block out = @_update_ciphers block @_q.push out @_dequeue = (n, cb) => @_q.read n, cb #--------------------------- _disable_queueing : -> @_enqueue = null @_dequeue = null #--------------------------- _read_preamble : (cb) -> await @_dequeue Preamble.len(), defer b ok = Preamble.unpack b log.error "Failed to unpack preamble: #{b.inspect()}" unless ok cb ok #--------------------------- _read_unpack : (cb) -> await @_dequeue 1, defer b0 framelen = msgpack_packed_numlen b0[0] if framelen is 0 log.error "Bad msgpack len header: #{b.inspect()}" else if framelen > 1 # Read the rest out... await @_dequeue (framelen-1), defer b1 b = Buffer.concat [b0, b1] else b = b0 # We've read the framing in two parts -- the first byte # and then the rest [err, frame] = purepack.unpack b if err? log.error "In reading msgpack frame: #{err}" else if not (typeof(frame) is 'number') log.error "Expected frame as a number: got #{frame}" else await @_dequeue frame, defer b [err, out] = purepack.unpack b log.error "In unpacking #{b.inspect()}: #{err}" if err? cb out #--------------------------- _read_header : (cb) -> ok = false await @_read_unpack defer @hdr if not @hdr? log.error "Failed to read header" else if @hdr.version isnt constants.VERSION log.error "Only know version #{constants.VERSION}; got #{@hdr.version}" else if not (@_ivs = @hdr.ivs)? or (@_ivs.length isnt gaf.num_ciphers()) log.error "Malformed headers; didn't find #{gaf.num_ciphers()} IVs" else ok = true cb ok #--------------------------- _check_mac : (cb) -> wanted = @macs.pop().digest() await @_read_unpack defer given ok = false if not given? log.error "Couldn't read MAC from file" else if not secure_bufeq given, wanted log.error "Header MAC mismatch error" else ok = true cb ok #--------------------------- _enable_queued_ciphertext : () => buf = @_q.flush() @_enable_deciphered_queueing() @_enqueue buf #--------------------------- init_stream : () -> ok = true @_prepare_macs() # Set this up to fly in the background... @_read_headers() #--------------------------- _read_headers : (cb) -> await @_read_preamble defer ok await @_read_header defer ok if ok # can only prepare the ciphers after we've read the header # (since the header has the IV!) @_prepare_ciphers() await @_check_mac defer ok if ok @_enable_queued_ciphertext() if ok await @_read_metadata defer ok if ok @_start_body() if ok cb?() #--------------------------- validate : () -> if @_final_mac_ok then [ true, null ] else [ false, "Full-file MAC failed" ] #--------------------------- _flush : (cb)-> # First flush the decryption pipeline and write any # new blocks out to the output stream block = @_final() @push block if block? and block.length # Now change over the clear block queuing. @_enable_clear_queuing() # The footer is in the FooterizingFilter, which kept the # last N bytes of the stream... @_enqueue @_ff.footer() # Finally, we can check the mac and hope that it works... await @_check_mac defer @_final_mac_ok cb() #--------------------------- _stream_body : (block, cb) -> @push bl if (bl = @_update_ciphers @_mac block)? cb?() #--------------------------- _start_body : () -> @_section = BODY buf = @_q.flush() @_disable_queueing() @push buf #--------------------------- _read_metadata : (cb) -> await @_read_unpack defer @_metadata cb !!@_metadata #--------------------------- _transform : (block, encoding, cb) -> block = @_ff.filter block if not block? or not block.length then null else if @_enqueue? then @_enqueue block else await @_stream_body block, defer() cb() #==================================================================
true
crypto = require 'crypto' purepack = require 'purepack' log = require './log' {constants} = require './constants' stream = require 'stream' {Queue} = require './queue' iced.catchExceptions() #================================================================== pack2 = (o) -> b1 = purepack.pack o, 'buffer', { byte_arrays : true } b0 = purepack.pack b1.length, 'buffer' Buffer.concat [ b0, b1 ] #================================================================== # pad datasz bytes to be a multiple of blocksz pkcs7_padding = (datasz, blocksz) -> plen = blocksz - (datasz % blocksz) new Buffer (plen for i in plen) #================================================================== bufeq = (b1, b2) -> return false unless b1.length is b2.length for b, i in b1 return false unless b is b2[i] return true #================================================================== nibble_to_str = (n) -> ret = n.toString 16 ret = "0" + ret if ret.length is 1 ret #================================================================== dump_buf = (b) -> l = b.length bytes = (nibble_to_str c for c in b) "Buffer(#{l})<#{bytes.join ' '}>" #================================================================== secure_bufeq = (b1, b2) -> ret = true if b1.length isnt b2.length ret = false else for b, i in b1 ret = false unless b is b2[i] return ret #================================================================== class AlgoFactory constructor : -> # Keysize in bytes for AES256 and Blowfish @ENC_KEY_SIZE = 32 @ENC_BLOCK_SIZE = 16 # Use the same keysize for our MAC too @MAC_KEY_SIZE = 32 @MAC_OUT_SIZE = 32 total_key_size : () -> 2 * @ENC_KEY_SIZE + @MAC_KEY_SIZE ciphers : () -> [ "aes-256-cbc", "camellia-256PI:KEY:<KEY>END_PI-cbc" ] num_ciphers : () -> @ciphers().length pad : (buf) -> padding = pkcs7_padding buf.length, @ENC_BLOCK_SIZE Buffer.concat [ buf, padding ] produce_keys : (bytes) -> eks = @ENC_KEY_SIZE mks = @MAC_KEY_SIZE parts = keysplit bytes, [ eks, eks, mks ] ret = { aes : parts[0] camellia : parts[1] hmac : parts[2] } ret #================================================================== gaf = new AlgoFactory() #================================================================== class FooterizingFilter #---------------- constructor : (@filesz) -> @_i = 0 @_footer_blocks = [] @_footer_len = null #---------------- filter : (block) -> # See Preamble --- the footer len is encoded in the first byte # of the file. This is a hack that should work for all practical # purposes. @_footer_len = block[0] unless @_footer_len? # Bytes of the body of the file that remain. bdrem = @filesz - @_i - @_footer_len if block.length > bdrem footer_part = if (bdrem > 0) then block[bdrem...] else block @_footer_blocks.push footer_part ret = if (bdrem > 0) then block[0...bdrem] else null else ret = block @_i += block.length return ret #---------------- footer : () -> ret = Buffer.concat @_footer_blocks if ret.length isnt @_footer_len log.warn "Got wrong footer size; wanted #{@_footer_len}, but got #{ret.length}" ret #================================================================== class Preamble @pack : () -> C = constants.Preamble i = new Buffer 4 i.writeUInt32BE C.FILE_VERSION, 0 ret = Buffer.concat [ new Buffer(C.FILE_MAGIC), i ] # As a pseudo-hack, the first byte is the length of the footer. # This makes framing the file convenient. footer_len = pack2(new Buffer [0...(gaf.MAC_OUT_SIZE) ]).length ret[0] = footer_len ret @unpack : (b) -> bufeq Preamble.pack(), b @len : () -> 12 #================================================================== msgpack_packed_numlen = (byt) -> if byt < 0x80 then 1 else if byt is 0xcc then 2 else if byt is 0xcd then 3 else if byt is 0xce then 5 else if byt is 0xcf then 9 else 0 #================================================================== keysplit = (key, splits) -> ret = [] start = 0 for s in splits end = start + s ret.push key[start...end] start = end ret.push key[start...] ret #================================================================== class Transform extends stream.Transform #--------------------------- constructor : (pipe_opts) -> super pipe_opts @_blocks = [] @_disable_ciphers() @_disable_streaming() @_ivs = null #--------------------------- _enable_ciphers : -> @_cipher_fn = (block) => @_update_ciphers block _disable_ciphers : -> @_cipher_fn = (block) => block #--------------------------- _disable_streaming : -> @_blocks = [] @_sink_fn = (block) -> @_blocks.push block #--------------------------- _enable_streaming : -> buf = Buffer.concat @_blocks @_blocks = [] @push buf @_sink_fn = (block) -> @push block #--------------------------- _send_to_sink : (block, cb) -> @_sink_fn @_process block cb() if cb? #--------------------------- _process : (chunk) -> @_mac @_cipher_fn chunk #--------------------------- _prepare_macs : () -> # One mac for the header, and another for the whole file (including # the header MAC) @macs = (crypto.createHmac('sha256', @keys.hmac) for i in [0...2]) #--------------------------- _mac : (block) -> for m,i in @macs m.update block block #--------------------------- _prepare_ciphers : () -> enc = @is_enc() ciphers = gaf.ciphers() @_ivs = (crypto.rng(gaf.ENC_BLOCK_SIZE) for i in ciphers) unless @_ivs? prev = null @ciphers = for c, i in ciphers key = @keysPI:KEY:<KEY>END_PI[PI:KEY:<KEY>END_PI iv = @_ivs[i] fn = if enc then crypto.createCipheriv else crypto.createDecipheriv fn c, key, iv # decrypt in the opposite order @ciphers.reverse() unless enc #--------------------------- # Called before init_stream() to key our ciphers and MACs. setup_keys : (cb) -> if @key_material? if (got = @key_material.length) is (wanted = gaf.total_key_size()) km = @key_material else log.error "Key material size mismatch: #{got} != #{wanted}" else await derive_key_material @pwmgr, @is_enc(), defer km if km @keys = gaf.produce_keys km ok = true else ok = false cb ok #--------------------------- # Chain the ciphers together, without any additional buffering from # pipes. We're going to simplify this alot... _update_ciphers : (chunk) -> for c in @ciphers chunk = c.update chunk chunk #--------------------------- # Cascading final update, the final from one cipher needs to be # run through all of the downstream ciphers... _final : () -> bufs = for c,i in @ciphers chunk = c.final() for d in @ciphers[(i+1)...] chunk = d.update chunk chunk Buffer.concat bufs #--------------------------- init : (cb) -> await @setup_keys defer ok @init_stream() if ok cb ok #================================================================== exports.derive_key_material = derive_key_material = (pwmgr, enc, cb) -> tks = gaf.total_key_size() await pwmgr.derive_key_material tks, enc, defer km cb km #================================================================== exports.Encryptor = class Encryptor extends Transform constructor : ({@stat, @pwmgr}, pipe_opts) -> super pipe_opts @packed_stat = pack2 @stat, 'buffer' #--------------------------- validate : () -> [ true ] is_enc : () -> true version : () -> constants.VERSION #--------------------------- _flush_ciphers : () -> @_sink_fn @_mac @_final() #--------------------------- _write_preamble : () -> @_send_to_sink Preamble.pack() _write_pack : (d) -> @_send_to_sink pack2 d _write_header : () -> @_write_pack @_make_header() _write_mac : () -> @_write_pack @macs.pop().digest() _write_metadata : () -> @_send_to_sink @packed_stat #--------------------------- _make_header : () -> out = version : constants.VERSION ivs : @_ivs statsize : @packed_stat.length filesize : @stat.size return out #--------------------------- _flush : (cb) -> @_flush_ciphers() @_disable_ciphers() @_write_mac() cb() #--------------------------- init_stream : () -> @_prepare_ciphers() @_prepare_macs() @_write_preamble() @_write_header() @_write_mac() # Finally, we're starting to encrypt... @_enable_ciphers() @_write_metadata() # Now, we're all set, and subsequent operations are going # to stream to the output.... @_enable_streaming() #--------------------------- _transform : (block, encoding, cb) -> @_send_to_sink block, cb #================================================================== [HEADER, BODY, FOOTER] = [0..2] #================================================================== exports.Decryptor = class Decryptor extends Transform constructor : ({@pwmgr, @stat, @total_size, @key_material}, pipe_opts) -> super pipe_opts @_section = HEADER @_n = 0 # number of body bytes reads @_q = new Queue @_enable_clear_queuing() @total_size = @stat.size if @stat? and not @total_size? if not @total_size? throw new Error "cannot find filesize" @_ff = new FooterizingFilter @total_size #--------------------------- is_enc : () -> false #--------------------------- _enable_clear_queuing : -> @_enqueue = (block) => @_q.push block @_dequeue = (n, cb) => await @_q.read n, defer b @_mac b if b? cb b #--------------------------- _enable_deciphered_queueing : -> @_enqueue = (block) -> if block? @_mac block out = @_update_ciphers block @_q.push out @_dequeue = (n, cb) => @_q.read n, cb #--------------------------- _disable_queueing : -> @_enqueue = null @_dequeue = null #--------------------------- _read_preamble : (cb) -> await @_dequeue Preamble.len(), defer b ok = Preamble.unpack b log.error "Failed to unpack preamble: #{b.inspect()}" unless ok cb ok #--------------------------- _read_unpack : (cb) -> await @_dequeue 1, defer b0 framelen = msgpack_packed_numlen b0[0] if framelen is 0 log.error "Bad msgpack len header: #{b.inspect()}" else if framelen > 1 # Read the rest out... await @_dequeue (framelen-1), defer b1 b = Buffer.concat [b0, b1] else b = b0 # We've read the framing in two parts -- the first byte # and then the rest [err, frame] = purepack.unpack b if err? log.error "In reading msgpack frame: #{err}" else if not (typeof(frame) is 'number') log.error "Expected frame as a number: got #{frame}" else await @_dequeue frame, defer b [err, out] = purepack.unpack b log.error "In unpacking #{b.inspect()}: #{err}" if err? cb out #--------------------------- _read_header : (cb) -> ok = false await @_read_unpack defer @hdr if not @hdr? log.error "Failed to read header" else if @hdr.version isnt constants.VERSION log.error "Only know version #{constants.VERSION}; got #{@hdr.version}" else if not (@_ivs = @hdr.ivs)? or (@_ivs.length isnt gaf.num_ciphers()) log.error "Malformed headers; didn't find #{gaf.num_ciphers()} IVs" else ok = true cb ok #--------------------------- _check_mac : (cb) -> wanted = @macs.pop().digest() await @_read_unpack defer given ok = false if not given? log.error "Couldn't read MAC from file" else if not secure_bufeq given, wanted log.error "Header MAC mismatch error" else ok = true cb ok #--------------------------- _enable_queued_ciphertext : () => buf = @_q.flush() @_enable_deciphered_queueing() @_enqueue buf #--------------------------- init_stream : () -> ok = true @_prepare_macs() # Set this up to fly in the background... @_read_headers() #--------------------------- _read_headers : (cb) -> await @_read_preamble defer ok await @_read_header defer ok if ok # can only prepare the ciphers after we've read the header # (since the header has the IV!) @_prepare_ciphers() await @_check_mac defer ok if ok @_enable_queued_ciphertext() if ok await @_read_metadata defer ok if ok @_start_body() if ok cb?() #--------------------------- validate : () -> if @_final_mac_ok then [ true, null ] else [ false, "Full-file MAC failed" ] #--------------------------- _flush : (cb)-> # First flush the decryption pipeline and write any # new blocks out to the output stream block = @_final() @push block if block? and block.length # Now change over the clear block queuing. @_enable_clear_queuing() # The footer is in the FooterizingFilter, which kept the # last N bytes of the stream... @_enqueue @_ff.footer() # Finally, we can check the mac and hope that it works... await @_check_mac defer @_final_mac_ok cb() #--------------------------- _stream_body : (block, cb) -> @push bl if (bl = @_update_ciphers @_mac block)? cb?() #--------------------------- _start_body : () -> @_section = BODY buf = @_q.flush() @_disable_queueing() @push buf #--------------------------- _read_metadata : (cb) -> await @_read_unpack defer @_metadata cb !!@_metadata #--------------------------- _transform : (block, encoding, cb) -> block = @_ff.filter block if not block? or not block.length then null else if @_enqueue? then @_enqueue block else await @_stream_body block, defer() cb() #==================================================================
[ { "context": "ompatible\n# @public\n# @param\t{String}\tpassword\t\t\t\tPassword\n# @param\t{String}\thash\t\t\t\t\tHash to compare to\n# @", "end": 1028, "score": 0.9847439527511597, "start": 1020, "tag": "PASSWORD", "value": "Password" } ]
server/lib/hash_helpers.coffee
willroberts/duelyst
5
### # A small helper module for hash generation and compares # Uses Bluebird to promisify the bcrypt modules # Methods are both node style callback and promise compatible # @module hash_helpers ### Promise = require 'bluebird' bcrypt = require 'bcrypt' ### This call wraps the bcrypt module in a Promise compatible interface ### Promise.promisifyAll(bcrypt) ###* # Generate a salt and hash using bcrypt when provided with a password # .nodeify(callback) makes this function both callback and promise compatible # @public # @param {String} password A password to hash # @param {Function} [callback] Optional callback(err,hash) # @return {Promise} Promise returning hash ### module.exports.generateHash = (password, callback) -> return bcrypt.genSaltAsync(10).then((salt) -> return bcrypt.hashAsync(password,salt).nodeify(callback) ) ###* # Compare a password against a bcrypt hash # .nodeify(callback) makes this function both callback and promise compatible # @public # @param {String} password Password # @param {String} hash Hash to compare to # @param {Function} [callback] Optional callback(err,match) # @return {Promise} Promise returning true/false ### module.exports.comparePassword = (password, hash, callback) -> return bcrypt.compareAsync(password,hash).nodeify(callback)
156211
### # A small helper module for hash generation and compares # Uses Bluebird to promisify the bcrypt modules # Methods are both node style callback and promise compatible # @module hash_helpers ### Promise = require 'bluebird' bcrypt = require 'bcrypt' ### This call wraps the bcrypt module in a Promise compatible interface ### Promise.promisifyAll(bcrypt) ###* # Generate a salt and hash using bcrypt when provided with a password # .nodeify(callback) makes this function both callback and promise compatible # @public # @param {String} password A password to hash # @param {Function} [callback] Optional callback(err,hash) # @return {Promise} Promise returning hash ### module.exports.generateHash = (password, callback) -> return bcrypt.genSaltAsync(10).then((salt) -> return bcrypt.hashAsync(password,salt).nodeify(callback) ) ###* # Compare a password against a bcrypt hash # .nodeify(callback) makes this function both callback and promise compatible # @public # @param {String} password <PASSWORD> # @param {String} hash Hash to compare to # @param {Function} [callback] Optional callback(err,match) # @return {Promise} Promise returning true/false ### module.exports.comparePassword = (password, hash, callback) -> return bcrypt.compareAsync(password,hash).nodeify(callback)
true
### # A small helper module for hash generation and compares # Uses Bluebird to promisify the bcrypt modules # Methods are both node style callback and promise compatible # @module hash_helpers ### Promise = require 'bluebird' bcrypt = require 'bcrypt' ### This call wraps the bcrypt module in a Promise compatible interface ### Promise.promisifyAll(bcrypt) ###* # Generate a salt and hash using bcrypt when provided with a password # .nodeify(callback) makes this function both callback and promise compatible # @public # @param {String} password A password to hash # @param {Function} [callback] Optional callback(err,hash) # @return {Promise} Promise returning hash ### module.exports.generateHash = (password, callback) -> return bcrypt.genSaltAsync(10).then((salt) -> return bcrypt.hashAsync(password,salt).nodeify(callback) ) ###* # Compare a password against a bcrypt hash # .nodeify(callback) makes this function both callback and promise compatible # @public # @param {String} password PI:PASSWORD:<PASSWORD>END_PI # @param {String} hash Hash to compare to # @param {Function} [callback] Optional callback(err,match) # @return {Promise} Promise returning true/false ### module.exports.comparePassword = (password, hash, callback) -> return bcrypt.compareAsync(password,hash).nodeify(callback)
[ { "context": "./lib/swag'\n\ncontext =\n collection: [\n 'Amy Wong'\n 'Bender'\n 'Dr. Zoidberg'\n ", "end": 127, "score": 0.9997377395629883, "start": 119, "tag": "NAME", "value": "Amy Wong" }, { "context": "t =\n collection: [\n 'Amy Wong'\n 'Bender'\n 'Dr. Zoidberg'\n 'Fry'\n 'He", "end": 144, "score": 0.9995601177215576, "start": 138, "tag": "NAME", "value": "Bender" }, { "context": "[\n 'Amy Wong'\n 'Bender'\n 'Dr. Zoidberg'\n 'Fry'\n 'Hermes Conrad'\n 'L", "end": 167, "score": 0.9996588826179504, "start": 159, "tag": "NAME", "value": "Zoidberg" }, { "context": "\n 'Bender'\n 'Dr. Zoidberg'\n 'Fry'\n 'Hermes Conrad'\n 'Leela'\n ", "end": 181, "score": 0.9997879266738892, "start": 178, "tag": "NAME", "value": "Fry" }, { "context": "er'\n 'Dr. Zoidberg'\n 'Fry'\n 'Hermes Conrad'\n 'Leela'\n 'Professor Farnsworth'\n ", "end": 205, "score": 0.9998794198036194, "start": 192, "tag": "NAME", "value": "Hermes Conrad" }, { "context": "g'\n 'Fry'\n 'Hermes Conrad'\n 'Leela'\n 'Professor Farnsworth'\n 'Scruffy'", "end": 221, "score": 0.9995031356811523, "start": 216, "tag": "NAME", "value": "Leela" }, { "context": "\n 'Hermes Conrad'\n 'Leela'\n 'Professor Farnsworth'\n 'Scruffy'\n ]\n\ndescribe 'first', ->\n ", "end": 252, "score": 0.9080057144165039, "start": 232, "tag": "NAME", "value": "Professor Farnsworth" }, { "context": " 'Leela'\n 'Professor Farnsworth'\n 'Scruffy'\n ]\n\ndescribe 'first', ->\n describe '{{firs", "end": 270, "score": 0.9991015195846558, "start": 263, "tag": "NAME", "value": "Scruffy" }, { "context": "urce)\n\n template(context).should.eql ['Professor Farnsworth', 'Scruffy']\n\ndescribe 'withLast', ->\n describ", "end": 2239, "score": 0.9986125826835632, "start": 2219, "tag": "NAME", "value": "Professor Farnsworth" }, { "context": "e(context).should.eql ['Professor Farnsworth', 'Scruffy']\n\ndescribe 'withLast', ->\n describe '{{#withL", "end": 2250, "score": 0.777776300907135, "start": 2245, "tag": "NAME", "value": "ruffy" }, { "context": ")\n\n template(context).should.equal '<p>Professor Farnsworth is dumb.</p><p>Scruffy is dumb.</p>'\n\ndescribe 'a", "end": 3050, "score": 0.9977686405181885, "start": 3030, "tag": "NAME", "value": "Professor Farnsworth" }, { "context": " template(context).should.eql ['Leela', 'Professor Farnsworth', 'Scruffy']\n\ndescribe 'withAfter', ->\n descri", "end": 3414, "score": 0.9990175366401672, "start": 3394, "tag": "NAME", "value": "Professor Farnsworth" }, { "context": ").should.eql ['Leela', 'Professor Farnsworth', 'Scruffy']\n\ndescribe 'withAfter', ->\n describe '{{#with", "end": 3425, "score": 0.6854556202888489, "start": 3420, "tag": "NAME", "value": "ruffy" }, { "context": "urce)\n\n template(context).should.eql ['Amy Wong', 'Bender', 'Dr. Zoidberg']\n\ndescribe 'withBefore", "end": 4169, "score": 0.9988804459571838, "start": 4161, "tag": "NAME", "value": "Amy Wong" }, { "context": " template(context).should.eql ['Amy Wong', 'Bender', 'Dr. Zoidberg']\n\ndescribe 'withBefore', ->\n ", "end": 4179, "score": 0.9659327268600464, "start": 4173, "tag": "NAME", "value": "Bender" }, { "context": "(context).should.eql ['Amy Wong', 'Bender', 'Dr. Zoidberg']\n\ndescribe 'withBefore', ->\n describe '{{#wit", "end": 4195, "score": 0.8767767548561096, "start": 4188, "tag": "NAME", "value": "oidberg" }, { "context": "ce)\n\n template(context).should.equal '<Amy Wong><Bender><Dr. Zoidberg>'\n\ndescribe 'join', ->\n ", "end": 4605, "score": 0.9554729461669922, "start": 4597, "tag": "NAME", "value": "Amy Wong" }, { "context": "rce)\n\n template(context).should.equal 'Amy Wong | Bender | Dr. Zoidberg | Fry | Hermes Conrad | L", "end": 4943, "score": 0.9989486932754517, "start": 4935, "tag": "NAME", "value": "Amy Wong" }, { "context": " template(context).should.equal 'Amy Wong | Bender | Dr. Zoidberg | Fry | Hermes Conrad | Leela | Pr", "end": 4952, "score": 0.9745906591415405, "start": 4946, "tag": "NAME", "value": "Bender" }, { "context": "e(context).should.equal 'Amy Wong | Bender | Dr. Zoidberg | Fry | Hermes Conrad | Leela | Professor Farnswo", "end": 4967, "score": 0.9109914302825928, "start": 4960, "tag": "NAME", "value": "oidberg" }, { "context": ").should.equal 'Amy Wong | Bender | Dr. Zoidberg | Fry | Hermes Conrad | Leela | Professor Farnsworth | ", "end": 4973, "score": 0.9821207523345947, "start": 4970, "tag": "NAME", "value": "Fry" }, { "context": "ld.equal 'Amy Wong | Bender | Dr. Zoidberg | Fry | Hermes Conrad | Leela | Professor Farnsworth | Scruffy'\n\ndescri", "end": 4989, "score": 0.9994382858276367, "start": 4976, "tag": "NAME", "value": "Hermes Conrad" }, { "context": "ng | Bender | Dr. Zoidberg | Fry | Hermes Conrad | Leela | Professor Farnsworth | Scruffy'\n\ndescribe 'sort", "end": 4997, "score": 0.9588254690170288, "start": 4992, "tag": "NAME", "value": "Leela" }, { "context": " Dr. Zoidberg | Fry | Hermes Conrad | Leela | Professor Farnsworth | Scruffy'\n\ndescribe 'sort', ->\n describe '{{s", "end": 5020, "score": 0.9662788510322571, "start": 5004, "tag": "NAME", "value": "essor Farnsworth" }, { "context": "Hermes Conrad | Leela | Professor Farnsworth | Scruffy'\n\ndescribe 'sort', ->\n describe '{{sort collec", "end": 5030, "score": 0.8677833080291748, "start": 5026, "tag": "NAME", "value": "uffy" }, { "context": "urce)\n\n template(context).should.eql ['Amy Wong', 'Bender', 'Dr. Zoidberg', 'Fry', 'Hermes Conrad", "end": 5329, "score": 0.998491644859314, "start": 5321, "tag": "NAME", "value": "Amy Wong" }, { "context": " template(context).should.eql ['Amy Wong', 'Bender', 'Dr. Zoidberg', 'Fry', 'Hermes Conrad', 'Leela'", "end": 5339, "score": 0.991547703742981, "start": 5333, "tag": "NAME", "value": "Bender" }, { "context": "ate(context).should.eql ['Amy Wong', 'Bender', 'Dr. Zoidberg', 'Fry', 'Hermes Conrad', 'Leela', 'Professor Far", "end": 5355, "score": 0.8832803964614868, "start": 5347, "tag": "NAME", "value": "Zoidberg" }, { "context": "hould.eql ['Amy Wong', 'Bender', 'Dr. Zoidberg', 'Fry', 'Hermes Conrad', 'Leela', 'Professor Farnsworth", "end": 5362, "score": 0.9967045783996582, "start": 5359, "tag": "NAME", "value": "Fry" }, { "context": "ql ['Amy Wong', 'Bender', 'Dr. Zoidberg', 'Fry', 'Hermes Conrad', 'Leela', 'Professor Farnsworth', 'Scruffy']\n\n ", "end": 5379, "score": 0.9996207356452942, "start": 5366, "tag": "NAME", "value": "Hermes Conrad" }, { "context": "Bender', 'Dr. Zoidberg', 'Fry', 'Hermes Conrad', 'Leela', 'Professor Farnsworth', 'Scruffy']\n\n describ", "end": 5388, "score": 0.9662611484527588, "start": 5383, "tag": "NAME", "value": "Leela" }, { "context": "'Dr. Zoidberg', 'Fry', 'Hermes Conrad', 'Leela', 'Professor Farnsworth', 'Scruffy']\n\n describe '{{sort collection \"na", "end": 5412, "score": 0.9929101467132568, "start": 5392, "tag": "NAME", "value": "Professor Farnsworth" }, { "context": "Hermes Conrad', 'Leela', 'Professor Farnsworth', 'Scruffy']\n\n describe '{{sort collection \"name\"}}', ->\n", "end": 5423, "score": 0.9407598972320557, "start": 5416, "tag": "NAME", "value": "Scruffy" }, { "context": " collection: [\n name: 'Leela'\n deliveries: 8021\n ", "end": 5736, "score": 0.9980025291442871, "start": 5731, "tag": "NAME", "value": "Leela" }, { "context": "8021\n ,\n name: 'Bender'\n deliveries: 239\n ", "end": 5826, "score": 0.9950203895568848, "start": 5820, "tag": "NAME", "value": "Bender" }, { "context": " 239\n ,\n name: 'Fry'\n deliveries: -12\n ", "end": 5912, "score": 0.997407078742981, "start": 5909, "tag": "NAME", "value": "Fry" }, { "context": " template(_context).should.eql [{name: 'Bender', deliveries: 239}, {name: 'Fry', deliveries: -12", "end": 6026, "score": 0.9924677014350891, "start": 6020, "tag": "NAME", "value": "Bender" }, { "context": "d.eql [{name: 'Bender', deliveries: 239}, {name: 'Fry', deliveries: -12}, {name: 'Leela', deliveries: 8", "end": 6058, "score": 0.9908754229545593, "start": 6055, "tag": "NAME", "value": "Fry" }, { "context": "es: 239}, {name: 'Fry', deliveries: -12}, {name: 'Leela', deliveries: 8021}]\n\ndescribe 'withSort', ->\n ", "end": 6092, "score": 0.9993504285812378, "start": 6087, "tag": "NAME", "value": "Leela" }, { "context": ")\n\n template(context).should.equal '<p>Amy Wong</p><p>Bender</p><p>Dr. Zoidberg</p><p>Fry</p><p>H", "end": 6507, "score": 0.9997725486755371, "start": 6499, "tag": "NAME", "value": "Amy Wong" }, { "context": "template(context).should.equal '<p>Amy Wong</p><p>Bender</p><p>Dr. Zoidberg</p><p>Fry</p><p>Hermes Conrad<", "end": 6520, "score": 0.9995968341827393, "start": 6514, "tag": "NAME", "value": "Bender" }, { "context": ").should.equal '<p>Amy Wong</p><p>Bender</p><p>Dr. Zoidberg</p><p>Fry</p><p>Hermes Conrad</p><p>Leela</p><p>P", "end": 6539, "score": 0.9991395473480225, "start": 6531, "tag": "NAME", "value": "Zoidberg" }, { "context": "<p>Amy Wong</p><p>Bender</p><p>Dr. Zoidberg</p><p>Fry</p><p>Hermes Conrad</p><p>Leela</p><p>Professor F", "end": 6549, "score": 0.9996764659881592, "start": 6546, "tag": "NAME", "value": "Fry" }, { "context": "g</p><p>Bender</p><p>Dr. Zoidberg</p><p>Fry</p><p>Hermes Conrad</p><p>Leela</p><p>Professor Farnsworth</p><p>Scru", "end": 6569, "score": 0.9998253583908081, "start": 6556, "tag": "NAME", "value": "Hermes Conrad" }, { "context": ">Dr. Zoidberg</p><p>Fry</p><p>Hermes Conrad</p><p>Leela</p><p>Professor Farnsworth</p><p>Scruffy</p>'\n\n ", "end": 6581, "score": 0.9972919225692749, "start": 6576, "tag": "NAME", "value": "Leela" }, { "context": "g</p><p>Fry</p><p>Hermes Conrad</p><p>Leela</p><p>Professor Farnsworth</p><p>Scruffy</p>'\n\n describe '{{#withSort col", "end": 6608, "score": 0.9967445731163025, "start": 6588, "tag": "NAME", "value": "Professor Farnsworth" }, { "context": "nrad</p><p>Leela</p><p>Professor Farnsworth</p><p>Scruffy</p>'\n\n describe '{{#withSort collection \"deliv", "end": 6622, "score": 0.9988363981246948, "start": 6615, "tag": "NAME", "value": "Scruffy" }, { "context": " collection: [\n name: 'Leela'\n deliveries: 8021\n ", "end": 7069, "score": 0.9994099140167236, "start": 7064, "tag": "NAME", "value": "Leela" }, { "context": "8021\n ,\n name: 'Bender'\n deliveries: 239\n ", "end": 7159, "score": 0.9995758533477783, "start": 7153, "tag": "NAME", "value": "Bender" }, { "context": " 239\n ,\n name: 'Fry'\n deliveries: -12\n ", "end": 7245, "score": 0.9996618032455444, "start": 7242, "tag": "NAME", "value": "Fry" }, { "context": "e)\n\n template(context).should.equal ' Amy Wong is 0 Bender is 1 Dr. Zoidberg is 2 Fry is", "end": 10042, "score": 0.8473695516586304, "start": 10040, "tag": "NAME", "value": "my" }, { "context": "xt).should.equal ' Amy Wong is 0 Bender is 1 Dr. Zoidberg is 2 Fry is 3 Hermes Conrad is 4 Leela is 5 P", "end": 10079, "score": 0.9920229911804199, "start": 10071, "tag": "NAME", "value": "Zoidberg" }, { "context": "l ' Amy Wong is 0 Bender is 1 Dr. Zoidberg is 2 Fry is 3 Hermes Conrad is 4 Leela is 5 Professor F", "end": 10089, "score": 0.9022185206413269, "start": 10086, "tag": "NAME", "value": "Fry" }, { "context": "ng is 0 Bender is 1 Dr. Zoidberg is 2 Fry is 3 Hermes Conrad is 4 Leela is 5 Professor Farnsworth is 6 Scru", "end": 10109, "score": 0.9998747110366821, "start": 10096, "tag": "NAME", "value": "Hermes Conrad" }, { "context": "ry is 3 Hermes Conrad is 4 Leela is 5 Professor Farnsworth is 6 Scruffy is 7 '\n\ndescribe 'eachProperty', ->", "end": 10148, "score": 0.9976292848587036, "start": 10138, "tag": "NAME", "value": "Farnsworth" } ]
test/collections_test.coffee
SBoudrias/swag
0
require 'should' Handlebars = require 'handlebars' Swag = require '../lib/swag' context = collection: [ 'Amy Wong' 'Bender' 'Dr. Zoidberg' 'Fry' 'Hermes Conrad' 'Leela' 'Professor Farnsworth' 'Scruffy' ] describe 'first', -> describe '{{first collection}}', -> it 'should return the first item in a collection.', -> source = '{{first collection}}' template = Handlebars.compile(source) template(context).should.equal 'Amy Wong' describe '{{first collection 2}}', -> it 'should return an array with the first two items in a collection.', -> source = '{{first collection 2}}' template = Handlebars.compile(source) template(context).should.eql ['Amy Wong', 'Bender'] describe 'withFirst', -> describe '{{#withFirst collection}} \n <p>{{this}} is smart.</p> \n {{/withFirst}}', -> it 'should use the first item in a collection inside a block.', -> source = '{{#withFirst collection}}<p>{{this}} is smart.</p>{{/withFirst}}' template = Handlebars.compile(source) template(context).should.equal '<p>Amy Wong is smart.</p>' describe '{{#withFirst collection 2}} \n <p>{{this}} is smart.</p> \n {{/withFirst}}', -> it 'should use the first two items in a collection inside a block.', -> source = '{{#withFirst collection 2}}<p>{{this}} is smart.</p>{{/withFirst}}' template = Handlebars.compile(source) template(context).should.equal '<p>Amy Wong is smart.</p><p>Bender is smart.</p>' describe 'last', -> describe '{{last collection}}', -> it 'should return the last item in a collection.', -> source = '{{last collection}}' template = Handlebars.compile(source) template(context).should.equal 'Scruffy' describe '{{last collection 2}}', -> it 'should return an array with the last two items in a collection.', -> source = '{{last collection 2}}' template = Handlebars.compile(source) template(context).should.eql ['Professor Farnsworth', 'Scruffy'] describe 'withLast', -> describe '{{#withLast collection}} \n <p>{{this}} is dumb.</p> \n {{/withLast}}', -> it 'should use the last item in a collection inside a block.', -> source = '{{#withLast collection}}<p>{{this}} is dumb.</p>{{/withLast}}' template = Handlebars.compile(source) template(context).should.equal '<p>Scruffy is dumb.</p>' describe '{{#withLast collection 2}} \n <p>{{this}} is dumb.</p> \n {{/withLast}}', -> it 'should use the last two items in a collection inside a block.', -> source = '{{#withLast collection 2}}<p>{{this}} is dumb.</p>{{/withLast}}' template = Handlebars.compile(source) template(context).should.equal '<p>Professor Farnsworth is dumb.</p><p>Scruffy is dumb.</p>' describe 'after', -> describe '{{after collection 5}}', -> it 'should return all of the items in a collection after the specified count.', -> source = '{{after collection 5}}' template = Handlebars.compile(source) template(context).should.eql ['Leela', 'Professor Farnsworth', 'Scruffy'] describe 'withAfter', -> describe '{{#withAfter collection 5}} \n <{{this}}> \n {{/withAfter}}', -> it 'should use all of the items in a collection after the specified count inside a block.', -> source = '{{#withAfter collection 5}}<{{this}}>{{/withAfter}}' template = Handlebars.compile(source) template(context).should.equal '<Leela><Professor Farnsworth><Scruffy>' describe 'before', -> describe '{{before collection 5}}', -> it 'should return all of the items in a collection before the specified count.', -> source = '{{before collection 5}}' template = Handlebars.compile(source) template(context).should.eql ['Amy Wong', 'Bender', 'Dr. Zoidberg'] describe 'withBefore', -> describe '{{#withBefore collection 5}} \n <{{this}}> \n {{/withBefore}}', -> it 'should use all of the items in a collection before the specified count inside a block.', -> source = '{{#withBefore collection 5}}<{{this}}>{{/withBefore}}' template = Handlebars.compile(source) template(context).should.equal '<Amy Wong><Bender><Dr. Zoidberg>' describe 'join', -> describe '{{join collection " | "}}', -> it 'should return all items in a collection joined by a separator if specified.', -> source = '{{join collection " | "}}' template = Handlebars.compile(source) template(context).should.equal 'Amy Wong | Bender | Dr. Zoidberg | Fry | Hermes Conrad | Leela | Professor Farnsworth | Scruffy' describe 'sort', -> describe '{{sort collection}}', -> it 'should return all items in a collection sorted in lexicographical order.', -> source = '{{sort collection}}' template = Handlebars.compile(source) template(context).should.eql ['Amy Wong', 'Bender', 'Dr. Zoidberg', 'Fry', 'Hermes Conrad', 'Leela', 'Professor Farnsworth', 'Scruffy'] describe '{{sort collection "name"}}', -> it 'should return all items in a collection sorted in by name.', -> source = '{{sort collection "name"}}' template = Handlebars.compile(source) _context = collection: [ name: 'Leela' deliveries: 8021 , name: 'Bender' deliveries: 239 , name: 'Fry' deliveries: -12 ] template(_context).should.eql [{name: 'Bender', deliveries: 239}, {name: 'Fry', deliveries: -12}, {name: 'Leela', deliveries: 8021}] describe 'withSort', -> describe '{{#withSort collection}} \n <p>{{this}}</p> \n {{/withSort}}', -> it 'should sort the collection in lexicographical order and use it in a block.', -> source = '{{#withSort collection}}<p>{{this}}</p>{{/withSort}}' template = Handlebars.compile(source) template(context).should.equal '<p>Amy Wong</p><p>Bender</p><p>Dr. Zoidberg</p><p>Fry</p><p>Hermes Conrad</p><p>Leela</p><p>Professor Farnsworth</p><p>Scruffy</p>' describe '{{#withSort collection "deliveries"}} \n {{name}}: {{deliveries}} <br> \n {{/withSort}}', -> it 'should sort the collection by deliveries and use it in a block.', -> source = '{{#withSort collection "deliveries"}}{{name}}: {{deliveries}} <br>{{/withSort}}' template = Handlebars.compile(source) _context = collection: [ name: 'Leela' deliveries: 8021 , name: 'Bender' deliveries: 239 , name: 'Fry' deliveries: -12 ] template(_context).should.equal 'Fry: -12 <br>Bender: 239 <br>Leela: 8021 <br>' describe 'length', -> describe '{{length collection}}', -> it 'should return the length of the collection', -> source = '{{length collection}}' template = Handlebars.compile(source) template(context).should.equal 8 describe 'lengthEqual', -> describe '{{#lengthEqual collection 3}} \n There are 3 people in Planet Express. \n {{else}} \n This is not Planet Express. \n {{/lengthEqual}}', -> it 'should conditionally render a block based on the length of a collection.', -> source = '{{#lengthEqual collection 3}}There are 3 people in Planet Express.{{else}}This is not Planet Express.{{/lengthEqual}}' template = Handlebars.compile(source) template(context).should.equal 'This is not Planet Express.' describe 'empty', -> describe '{{#empty collection}} \n Bad news everyone! \n {{else}} \n Good news everyone! \n {{/empty}}', -> it 'should conditionally render a block the collection is empty.', -> source = '{{#empty collection}}Bad news everyone!{{else}}Good news everyone!{{/empty}}' template = Handlebars.compile(source) template(context).should.equal 'Good news everyone!' describe 'any', -> describe '{{#any collection}} \n Bad news everyone! \n {{else}} \n Good news everyone! \n {{/any}}', -> it 'should conditionally render a block the collection isn\'t empty.', -> source = '{{#any collection}}Bad news everyone!{{else}}Good news everyone!{{/any}}' template = Handlebars.compile(source) template(context).should.equal 'Bad news everyone!' describe 'inArray', -> describe '{{#inArray collection "Fry"}} \n I\'m walking on sunshine! \n {{else}} \n I\'m walking in darkness. \n {{/inArray}}', -> it 'should conditionally render a block if a specified value is in the collection.', -> source = '{{#inArray collection "Fry"}}I\'m walking on sunshine!{{else}}I\'m walking in darkness.{{/inArray}}' template = Handlebars.compile(source) template(context).should.equal 'I\'m walking on sunshine!' describe 'eachIndex', -> describe '{{#eachIndex collection}} \n {{item}} is {{index}} \n {{/eachIndex}}', -> it 'should render the block using the array and each item\'s index.', -> source = '{{#eachIndex collection}} {{item}} is {{index}} {{/eachIndex}}' template = Handlebars.compile(source) template(context).should.equal ' Amy Wong is 0 Bender is 1 Dr. Zoidberg is 2 Fry is 3 Hermes Conrad is 4 Leela is 5 Professor Farnsworth is 6 Scruffy is 7 ' describe 'eachProperty', -> describe '{{#eachProperty collection}} \n {{key}}: {{value}} \n {{/eachProperty}}', -> it 'should use the key and value of each property in an object inside a block.', -> source = '{{#eachProperty collection}}{{key}}: {{value}} {{/eachProperty}}' template = Handlebars.compile(source) _context = collection: fry: 3, bender: 120 template(_context).should.equal 'fry: 3 bender: 120 '
110652
require 'should' Handlebars = require 'handlebars' Swag = require '../lib/swag' context = collection: [ '<NAME>' '<NAME>' 'Dr. <NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' ] describe 'first', -> describe '{{first collection}}', -> it 'should return the first item in a collection.', -> source = '{{first collection}}' template = Handlebars.compile(source) template(context).should.equal 'Amy Wong' describe '{{first collection 2}}', -> it 'should return an array with the first two items in a collection.', -> source = '{{first collection 2}}' template = Handlebars.compile(source) template(context).should.eql ['Amy Wong', 'Bender'] describe 'withFirst', -> describe '{{#withFirst collection}} \n <p>{{this}} is smart.</p> \n {{/withFirst}}', -> it 'should use the first item in a collection inside a block.', -> source = '{{#withFirst collection}}<p>{{this}} is smart.</p>{{/withFirst}}' template = Handlebars.compile(source) template(context).should.equal '<p>Amy Wong is smart.</p>' describe '{{#withFirst collection 2}} \n <p>{{this}} is smart.</p> \n {{/withFirst}}', -> it 'should use the first two items in a collection inside a block.', -> source = '{{#withFirst collection 2}}<p>{{this}} is smart.</p>{{/withFirst}}' template = Handlebars.compile(source) template(context).should.equal '<p>Amy Wong is smart.</p><p>Bender is smart.</p>' describe 'last', -> describe '{{last collection}}', -> it 'should return the last item in a collection.', -> source = '{{last collection}}' template = Handlebars.compile(source) template(context).should.equal 'Scruffy' describe '{{last collection 2}}', -> it 'should return an array with the last two items in a collection.', -> source = '{{last collection 2}}' template = Handlebars.compile(source) template(context).should.eql ['<NAME>', 'Sc<NAME>'] describe 'withLast', -> describe '{{#withLast collection}} \n <p>{{this}} is dumb.</p> \n {{/withLast}}', -> it 'should use the last item in a collection inside a block.', -> source = '{{#withLast collection}}<p>{{this}} is dumb.</p>{{/withLast}}' template = Handlebars.compile(source) template(context).should.equal '<p>Scruffy is dumb.</p>' describe '{{#withLast collection 2}} \n <p>{{this}} is dumb.</p> \n {{/withLast}}', -> it 'should use the last two items in a collection inside a block.', -> source = '{{#withLast collection 2}}<p>{{this}} is dumb.</p>{{/withLast}}' template = Handlebars.compile(source) template(context).should.equal '<p><NAME> is dumb.</p><p>Scruffy is dumb.</p>' describe 'after', -> describe '{{after collection 5}}', -> it 'should return all of the items in a collection after the specified count.', -> source = '{{after collection 5}}' template = Handlebars.compile(source) template(context).should.eql ['Leela', '<NAME>', 'Sc<NAME>'] describe 'withAfter', -> describe '{{#withAfter collection 5}} \n <{{this}}> \n {{/withAfter}}', -> it 'should use all of the items in a collection after the specified count inside a block.', -> source = '{{#withAfter collection 5}}<{{this}}>{{/withAfter}}' template = Handlebars.compile(source) template(context).should.equal '<Leela><Professor Farnsworth><Scruffy>' describe 'before', -> describe '{{before collection 5}}', -> it 'should return all of the items in a collection before the specified count.', -> source = '{{before collection 5}}' template = Handlebars.compile(source) template(context).should.eql ['<NAME>', '<NAME>', 'Dr. Z<NAME>'] describe 'withBefore', -> describe '{{#withBefore collection 5}} \n <{{this}}> \n {{/withBefore}}', -> it 'should use all of the items in a collection before the specified count inside a block.', -> source = '{{#withBefore collection 5}}<{{this}}>{{/withBefore}}' template = Handlebars.compile(source) template(context).should.equal '<<NAME>><Bender><Dr. Zoidberg>' describe 'join', -> describe '{{join collection " | "}}', -> it 'should return all items in a collection joined by a separator if specified.', -> source = '{{join collection " | "}}' template = Handlebars.compile(source) template(context).should.equal '<NAME> | <NAME> | Dr. Z<NAME> | <NAME> | <NAME> | <NAME> | Prof<NAME> | Scr<NAME>' describe 'sort', -> describe '{{sort collection}}', -> it 'should return all items in a collection sorted in lexicographical order.', -> source = '{{sort collection}}' template = Handlebars.compile(source) template(context).should.eql ['<NAME>', '<NAME>', 'Dr. <NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>'] describe '{{sort collection "name"}}', -> it 'should return all items in a collection sorted in by name.', -> source = '{{sort collection "name"}}' template = Handlebars.compile(source) _context = collection: [ name: '<NAME>' deliveries: 8021 , name: '<NAME>' deliveries: 239 , name: '<NAME>' deliveries: -12 ] template(_context).should.eql [{name: '<NAME>', deliveries: 239}, {name: '<NAME>', deliveries: -12}, {name: '<NAME>', deliveries: 8021}] describe 'withSort', -> describe '{{#withSort collection}} \n <p>{{this}}</p> \n {{/withSort}}', -> it 'should sort the collection in lexicographical order and use it in a block.', -> source = '{{#withSort collection}}<p>{{this}}</p>{{/withSort}}' template = Handlebars.compile(source) template(context).should.equal '<p><NAME></p><p><NAME></p><p>Dr. <NAME></p><p><NAME></p><p><NAME></p><p><NAME></p><p><NAME></p><p><NAME></p>' describe '{{#withSort collection "deliveries"}} \n {{name}}: {{deliveries}} <br> \n {{/withSort}}', -> it 'should sort the collection by deliveries and use it in a block.', -> source = '{{#withSort collection "deliveries"}}{{name}}: {{deliveries}} <br>{{/withSort}}' template = Handlebars.compile(source) _context = collection: [ name: '<NAME>' deliveries: 8021 , name: '<NAME>' deliveries: 239 , name: '<NAME>' deliveries: -12 ] template(_context).should.equal 'Fry: -12 <br>Bender: 239 <br>Leela: 8021 <br>' describe 'length', -> describe '{{length collection}}', -> it 'should return the length of the collection', -> source = '{{length collection}}' template = Handlebars.compile(source) template(context).should.equal 8 describe 'lengthEqual', -> describe '{{#lengthEqual collection 3}} \n There are 3 people in Planet Express. \n {{else}} \n This is not Planet Express. \n {{/lengthEqual}}', -> it 'should conditionally render a block based on the length of a collection.', -> source = '{{#lengthEqual collection 3}}There are 3 people in Planet Express.{{else}}This is not Planet Express.{{/lengthEqual}}' template = Handlebars.compile(source) template(context).should.equal 'This is not Planet Express.' describe 'empty', -> describe '{{#empty collection}} \n Bad news everyone! \n {{else}} \n Good news everyone! \n {{/empty}}', -> it 'should conditionally render a block the collection is empty.', -> source = '{{#empty collection}}Bad news everyone!{{else}}Good news everyone!{{/empty}}' template = Handlebars.compile(source) template(context).should.equal 'Good news everyone!' describe 'any', -> describe '{{#any collection}} \n Bad news everyone! \n {{else}} \n Good news everyone! \n {{/any}}', -> it 'should conditionally render a block the collection isn\'t empty.', -> source = '{{#any collection}}Bad news everyone!{{else}}Good news everyone!{{/any}}' template = Handlebars.compile(source) template(context).should.equal 'Bad news everyone!' describe 'inArray', -> describe '{{#inArray collection "Fry"}} \n I\'m walking on sunshine! \n {{else}} \n I\'m walking in darkness. \n {{/inArray}}', -> it 'should conditionally render a block if a specified value is in the collection.', -> source = '{{#inArray collection "Fry"}}I\'m walking on sunshine!{{else}}I\'m walking in darkness.{{/inArray}}' template = Handlebars.compile(source) template(context).should.equal 'I\'m walking on sunshine!' describe 'eachIndex', -> describe '{{#eachIndex collection}} \n {{item}} is {{index}} \n {{/eachIndex}}', -> it 'should render the block using the array and each item\'s index.', -> source = '{{#eachIndex collection}} {{item}} is {{index}} {{/eachIndex}}' template = Handlebars.compile(source) template(context).should.equal ' A<NAME> Wong is 0 Bender is 1 Dr. <NAME> is 2 <NAME> is 3 <NAME> is 4 Leela is 5 Professor <NAME> is 6 Scruffy is 7 ' describe 'eachProperty', -> describe '{{#eachProperty collection}} \n {{key}}: {{value}} \n {{/eachProperty}}', -> it 'should use the key and value of each property in an object inside a block.', -> source = '{{#eachProperty collection}}{{key}}: {{value}} {{/eachProperty}}' template = Handlebars.compile(source) _context = collection: fry: 3, bender: 120 template(_context).should.equal 'fry: 3 bender: 120 '
true
require 'should' Handlebars = require 'handlebars' Swag = require '../lib/swag' context = collection: [ 'PI:NAME:<NAME>END_PI' 'PI:NAME:<NAME>END_PI' 'Dr. 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' ] describe 'first', -> describe '{{first collection}}', -> it 'should return the first item in a collection.', -> source = '{{first collection}}' template = Handlebars.compile(source) template(context).should.equal 'Amy Wong' describe '{{first collection 2}}', -> it 'should return an array with the first two items in a collection.', -> source = '{{first collection 2}}' template = Handlebars.compile(source) template(context).should.eql ['Amy Wong', 'Bender'] describe 'withFirst', -> describe '{{#withFirst collection}} \n <p>{{this}} is smart.</p> \n {{/withFirst}}', -> it 'should use the first item in a collection inside a block.', -> source = '{{#withFirst collection}}<p>{{this}} is smart.</p>{{/withFirst}}' template = Handlebars.compile(source) template(context).should.equal '<p>Amy Wong is smart.</p>' describe '{{#withFirst collection 2}} \n <p>{{this}} is smart.</p> \n {{/withFirst}}', -> it 'should use the first two items in a collection inside a block.', -> source = '{{#withFirst collection 2}}<p>{{this}} is smart.</p>{{/withFirst}}' template = Handlebars.compile(source) template(context).should.equal '<p>Amy Wong is smart.</p><p>Bender is smart.</p>' describe 'last', -> describe '{{last collection}}', -> it 'should return the last item in a collection.', -> source = '{{last collection}}' template = Handlebars.compile(source) template(context).should.equal 'Scruffy' describe '{{last collection 2}}', -> it 'should return an array with the last two items in a collection.', -> source = '{{last collection 2}}' template = Handlebars.compile(source) template(context).should.eql ['PI:NAME:<NAME>END_PI', 'ScPI:NAME:<NAME>END_PI'] describe 'withLast', -> describe '{{#withLast collection}} \n <p>{{this}} is dumb.</p> \n {{/withLast}}', -> it 'should use the last item in a collection inside a block.', -> source = '{{#withLast collection}}<p>{{this}} is dumb.</p>{{/withLast}}' template = Handlebars.compile(source) template(context).should.equal '<p>Scruffy is dumb.</p>' describe '{{#withLast collection 2}} \n <p>{{this}} is dumb.</p> \n {{/withLast}}', -> it 'should use the last two items in a collection inside a block.', -> source = '{{#withLast collection 2}}<p>{{this}} is dumb.</p>{{/withLast}}' template = Handlebars.compile(source) template(context).should.equal '<p>PI:NAME:<NAME>END_PI is dumb.</p><p>Scruffy is dumb.</p>' describe 'after', -> describe '{{after collection 5}}', -> it 'should return all of the items in a collection after the specified count.', -> source = '{{after collection 5}}' template = Handlebars.compile(source) template(context).should.eql ['Leela', 'PI:NAME:<NAME>END_PI', 'ScPI:NAME:<NAME>END_PI'] describe 'withAfter', -> describe '{{#withAfter collection 5}} \n <{{this}}> \n {{/withAfter}}', -> it 'should use all of the items in a collection after the specified count inside a block.', -> source = '{{#withAfter collection 5}}<{{this}}>{{/withAfter}}' template = Handlebars.compile(source) template(context).should.equal '<Leela><Professor Farnsworth><Scruffy>' describe 'before', -> describe '{{before collection 5}}', -> it 'should return all of the items in a collection before the specified count.', -> source = '{{before collection 5}}' template = Handlebars.compile(source) template(context).should.eql ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'Dr. ZPI:NAME:<NAME>END_PI'] describe 'withBefore', -> describe '{{#withBefore collection 5}} \n <{{this}}> \n {{/withBefore}}', -> it 'should use all of the items in a collection before the specified count inside a block.', -> source = '{{#withBefore collection 5}}<{{this}}>{{/withBefore}}' template = Handlebars.compile(source) template(context).should.equal '<PI:NAME:<NAME>END_PI><Bender><Dr. Zoidberg>' describe 'join', -> describe '{{join collection " | "}}', -> it 'should return all items in a collection joined by a separator if specified.', -> source = '{{join collection " | "}}' template = Handlebars.compile(source) template(context).should.equal 'PI:NAME:<NAME>END_PI | PI:NAME:<NAME>END_PI | Dr. ZPI:NAME:<NAME>END_PI | PI:NAME:<NAME>END_PI | PI:NAME:<NAME>END_PI | PI:NAME:<NAME>END_PI | ProfPI:NAME:<NAME>END_PI | ScrPI:NAME:<NAME>END_PI' describe 'sort', -> describe '{{sort collection}}', -> it 'should return all items in a collection sorted in lexicographical order.', -> source = '{{sort collection}}' template = Handlebars.compile(source) template(context).should.eql ['PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'Dr. 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'] describe '{{sort collection "name"}}', -> it 'should return all items in a collection sorted in by name.', -> source = '{{sort collection "name"}}' template = Handlebars.compile(source) _context = collection: [ name: 'PI:NAME:<NAME>END_PI' deliveries: 8021 , name: 'PI:NAME:<NAME>END_PI' deliveries: 239 , name: 'PI:NAME:<NAME>END_PI' deliveries: -12 ] template(_context).should.eql [{name: 'PI:NAME:<NAME>END_PI', deliveries: 239}, {name: 'PI:NAME:<NAME>END_PI', deliveries: -12}, {name: 'PI:NAME:<NAME>END_PI', deliveries: 8021}] describe 'withSort', -> describe '{{#withSort collection}} \n <p>{{this}}</p> \n {{/withSort}}', -> it 'should sort the collection in lexicographical order and use it in a block.', -> source = '{{#withSort collection}}<p>{{this}}</p>{{/withSort}}' template = Handlebars.compile(source) template(context).should.equal '<p>PI:NAME:<NAME>END_PI</p><p>PI:NAME:<NAME>END_PI</p><p>Dr. PI:NAME:<NAME>END_PI</p><p>PI:NAME:<NAME>END_PI</p><p>PI:NAME:<NAME>END_PI</p><p>PI:NAME:<NAME>END_PI</p><p>PI:NAME:<NAME>END_PI</p><p>PI:NAME:<NAME>END_PI</p>' describe '{{#withSort collection "deliveries"}} \n {{name}}: {{deliveries}} <br> \n {{/withSort}}', -> it 'should sort the collection by deliveries and use it in a block.', -> source = '{{#withSort collection "deliveries"}}{{name}}: {{deliveries}} <br>{{/withSort}}' template = Handlebars.compile(source) _context = collection: [ name: 'PI:NAME:<NAME>END_PI' deliveries: 8021 , name: 'PI:NAME:<NAME>END_PI' deliveries: 239 , name: 'PI:NAME:<NAME>END_PI' deliveries: -12 ] template(_context).should.equal 'Fry: -12 <br>Bender: 239 <br>Leela: 8021 <br>' describe 'length', -> describe '{{length collection}}', -> it 'should return the length of the collection', -> source = '{{length collection}}' template = Handlebars.compile(source) template(context).should.equal 8 describe 'lengthEqual', -> describe '{{#lengthEqual collection 3}} \n There are 3 people in Planet Express. \n {{else}} \n This is not Planet Express. \n {{/lengthEqual}}', -> it 'should conditionally render a block based on the length of a collection.', -> source = '{{#lengthEqual collection 3}}There are 3 people in Planet Express.{{else}}This is not Planet Express.{{/lengthEqual}}' template = Handlebars.compile(source) template(context).should.equal 'This is not Planet Express.' describe 'empty', -> describe '{{#empty collection}} \n Bad news everyone! \n {{else}} \n Good news everyone! \n {{/empty}}', -> it 'should conditionally render a block the collection is empty.', -> source = '{{#empty collection}}Bad news everyone!{{else}}Good news everyone!{{/empty}}' template = Handlebars.compile(source) template(context).should.equal 'Good news everyone!' describe 'any', -> describe '{{#any collection}} \n Bad news everyone! \n {{else}} \n Good news everyone! \n {{/any}}', -> it 'should conditionally render a block the collection isn\'t empty.', -> source = '{{#any collection}}Bad news everyone!{{else}}Good news everyone!{{/any}}' template = Handlebars.compile(source) template(context).should.equal 'Bad news everyone!' describe 'inArray', -> describe '{{#inArray collection "Fry"}} \n I\'m walking on sunshine! \n {{else}} \n I\'m walking in darkness. \n {{/inArray}}', -> it 'should conditionally render a block if a specified value is in the collection.', -> source = '{{#inArray collection "Fry"}}I\'m walking on sunshine!{{else}}I\'m walking in darkness.{{/inArray}}' template = Handlebars.compile(source) template(context).should.equal 'I\'m walking on sunshine!' describe 'eachIndex', -> describe '{{#eachIndex collection}} \n {{item}} is {{index}} \n {{/eachIndex}}', -> it 'should render the block using the array and each item\'s index.', -> source = '{{#eachIndex collection}} {{item}} is {{index}} {{/eachIndex}}' template = Handlebars.compile(source) template(context).should.equal ' API:NAME:<NAME>END_PI Wong is 0 Bender is 1 Dr. PI:NAME:<NAME>END_PI is 2 PI:NAME:<NAME>END_PI is 3 PI:NAME:<NAME>END_PI is 4 Leela is 5 Professor PI:NAME:<NAME>END_PI is 6 Scruffy is 7 ' describe 'eachProperty', -> describe '{{#eachProperty collection}} \n {{key}}: {{value}} \n {{/eachProperty}}', -> it 'should use the key and value of each property in an object inside a block.', -> source = '{{#eachProperty collection}}{{key}}: {{value}} {{/eachProperty}}' template = Handlebars.compile(source) _context = collection: fry: 3, bender: 120 template(_context).should.equal 'fry: 3 bender: 120 '
[ { "context": " Basic tools\n# @date 2014-12-2 15:10:14\n# @author pjg <iampjg@gmail.com>\n# @link http://pjg.pw\n# @versi", "end": 74, "score": 0.9994415044784546, "start": 71, "tag": "USERNAME", "value": "pjg" }, { "context": "c tools\n# @date 2014-12-2 15:10:14\n# @author pjg <iampjg@gmail.com>\n# @link http://pjg.pw\n# @version $Id$\n###\n\nfs ", "end": 92, "score": 0.9999216198921204, "start": 76, "tag": "EMAIL", "value": "iampjg@gmail.com" }, { "context": "('/js/')[1].replace(/\\.js$/, '')\n\n # @writeFile(@jsLibs, JSON.stringify(_libs, null, 2))\n global.Cache", "end": 7595, "score": 0.8865644931793213, "start": 7588, "tag": "USERNAME", "value": "@jsLibs" }, { "context": "Paths\n if key isnt 'require' and key isnt 'almond'\n newPaths[key] = val\n reqCfg =", "end": 8257, "score": 0.7131803035736084, "start": 8255, "tag": "KEY", "value": "al" } ]
node_modules/vbuilder/lib/utils/index.coffee
duolaimi/v.builder.site
0
###* # @fileOverview Basic tools # @date 2014-12-2 15:10:14 # @author pjg <iampjg@gmail.com> # @link http://pjg.pw # @version $Id$ ### fs = require 'fs' path = require 'path' _ = require 'lodash' _url = require 'url' crypto = require 'crypto' http = require 'http' https = require 'https' uglify = require 'uglify-js' gutil = require 'gulp-util' color = gutil.colors Cfg = require '../cfg' # numCPUs = require('os').cpus().length opts = global.Cache['gOpts'] # console.log opts Tools = {} # md5 hash Tools.md5 = (source) -> # 使用二进制转换,解决中文摘要计算不准的问题 _buf = new Buffer(source) _str = _buf.toString "binary" crypto.createHash('md5').update(_str, 'utf8').digest('hex') # 错误报警,beep响两声 Tools.errrHandler = (e) -> gutil.beep() gutil.beep() gutil.log e ### # @fileOverview makedir ### Tools.mkdirsSync = (dirpath, mode)-> if fs.existsSync(dirpath) return true else if Tools.mkdirsSync path.dirname(dirpath), mode fs.mkdirSync(dirpath, mode) return true ### # @fileOverview makedirs ### Tools.mkdirs = (dirpath, mode, callback)-> fs.exists dirpath,(exists)-> if exists callback(exists) else # Try made the parent's dir,then make the current dir mkdirs path.dirname(dirpath), mode, -> fs.mkdir dirpath, mode, callback ### # @fileOverview obj mixin function # @Example # food = {'key':'apple'} # food2 = {'name':'banana','type':'fruit'} # console.log objMixin(food2,food) # console.log objMixin(food,food2) ### Tools.objMixin = _.partialRight _.assign, (a, b) -> val = if (typeof a is 'undefined') then b else a return val # 获取文件 Tools.getFileSync = (file, encoding)-> _encoding = encoding or 'utf8' fileCon = '' if fs.existsSync(file) stats = fs.statSync(file) if stats.isFile() fileCon = fs.readFileSync(file, _encoding) return fileCon # 获取文件json对象 Tools.getJSONSync = (file) -> fileCon = Tools.getFileSync(file) data = {} if fileCon fileCon = fileCon.replace(/\/\/[^\n]*/g, '') try data = JSON.parse(fileCon) catch e console.log e return data # 判断是否是空对象 Tools.isEmptyObject = (obj)-> for name of obj return false return true # 文件写入磁盘 Tools.writeFile = (file,source,isNotLog)-> # Tools.mkdirsSync(path.dirname(file)) # fs.writeFileSync file, source, 'utf8' # name = path.basename(file) # not isNotLog && gutil.log("'" + gutil.colors.cyan(name) + "'", "build success.") # 文件存在并且MD5值一样,则不重复写入 name = path.basename(file); if fs.existsSync(file) and Tools.md5(Tools.getFileSync(file)) is Tools.md5(source) return false Tools.mkdirsSync(path.dirname(file)) fs.writeFileSync(file, source, 'utf8') isNotLog or gutil.log("'" + gutil.colors.cyan(name) + "'", "build success.") # 压缩js源码 Tools.minifyJs = (source)-> mangled = uglify.minify(source,{fromString: true}) return mangled.code # 获取hash map Tools.getMap= (type)-> _this = Tools _map = {} _name = if type in ["css","img","js"] then "#{type}Map" else "#{type}" _file = opts.mapPath + _name.toLowerCase() + '.json' if not fs.existsSync(_file) # console.log _file _this.writeFile(_file,'{}') else _source = fs.readFileSync(_file) try _map = JSON.parse(_source, 'utf8') # console.log _map global.Cache[_name] = _map catch e try # console.log "#{_file}--->",e # 解决json文件冲突, git冲突 _source = _source.toString().replace(/<<<<<<<([\s\S]*?)>>>>>>>\s*\w*/g,'') _map = global.Cache[_name] = JSON.parse(_source) or {} _this.writeFile(_file,_source) catch e global.Cache[_name] = {} # opts = global.Cache['gOpts'] switch _name when 'imgMap' _ctl = require('../imgCtl') new _ctl(opts).init() when 'cssMap' _ctl = require('../cssCtl') new _ctl(opts).init() else global.Cache[_name] = {} _map = _.assign _map,global.Cache[_name] return _map # 更新map缓存 Tools.updateMap = (obj,mapName)-> if _.has(global.Cache,mapName) _.assign global.Cache[mapName],obj # 保存map文件 Tools.saveMapFile = (name)-> _name = name _file = opts.mapPath + _name.toLowerCase() + '.json' _map = {} try _map = JSON.parse(fs.readFileSync(_file), 'utf8') catch e console.log e _map = _.assign _map,global.Cache[_name] _data = JSON.stringify(_map, null, 4) Tools.writeFile(_file,_data) # 保存缓存文件 Tools.saveCache = -> _cache = global.Cache delete _cache.gOpts Tools.writeFile(opts.mapPath + 'cache.json',JSON.stringify(_cache, null, 0)) # 替换html模板中的img,原构建流程的保留方法 # 新版中请使用 ejs 语法,<@- init_img('logo.png') @> Tools.replaceImg = (source)-> Tools.getMap('img') imgPath = Tools.getStaticPath() + 'img/' imgMap = global.Cache['imgMap'] imgReg = /<img[\s\S]*?[^(src)]src=('|")([^'|^"]*)('|")/g file_source = source.replace imgReg,(str)-> # console.log str map = '' str.replace /src=('|")([^'|^"]*)('|")/,($1)-> map = $1.replace(/^src=/,'').replace(/(\'|\")|(\'|\"$)/g, '') if map.indexOf('/img/') isnt 0 or map.indexOf('http://') is 0 or map.indexOf('data:') is 0 or map.indexOf('/<?php/') isnt -1 return str else key = map.replace(/(^\'|\")|(\'|\"$)/g, '').split('img/')[1] val = imgPath + (if _.has(imgMap,key) and opts.env isnt 'local' then imgMap[key].distname else key + '?=t' + String(new Date().getTime()).substr(0,8)) # console.log "#{map}--> #{val}" return str.replace(map, val) return file_source # 压缩html Tools.htmlMinify = (source)-> s = source .replace(/\/\*([\s\S]*?)\*\//g, '') .replace(/<!--([\s\S]*?)-->/g, '') .replace(/^\s+$/g, '') .replace(/\n/g, '') .replace(/\t/g, '') .replace(/\r/g, '') .replace(/\n\s+/g, ' ') .replace(/\s+/g, ' ') .replace(/>([\n\s]*?)</g,'><') # .replace(/<?phpforeach/g,'<?php foreach') # .replace(/<?phpecho/g,'<?php echo') return s #判断是否window系统 Tools.isWin = -> return process.platform is "win32" #转换文件路径 Tools.tranFilePath = (filePath)-> _file = filePath or "" if Tools.isWin() _file = _file.replace /\\/g,'\/' return _file ### # build the three part's js libs paths ### Tools.buildReqPaths = (cb)-> _cb = cb or -> if _.has(global.Cache,'jsLibs') return false _libs = {} _reqPathsFile = path.join(opts.mapPath, 'req_paths.json') try _libs = JSON.parse fs.readFileSync(_reqPathsFile, 'utf8') catch err Tools.writeFile(_reqPathsFile,"{}") filePath = opts.srcPath + 'js/vendor/' fs.readdirSync(filePath).forEach (v)-> _path = path.join(filePath, v) if fs.statSync(_path).isDirectory() fs.readdirSync(_path).forEach (f)-> _file = path.join(_path, f) if fs.existsSync(_file) and f.indexOf('.') != 0 and f.indexOf('.js') != -1 _file = Tools.tranFilePath _file _libs[v] = _file.split('/js/')[1].replace(/\.js$/, '') # @writeFile(@jsLibs, JSON.stringify(_libs, null, 2)) global.Cache['jsLibs'] = _libs _cb() # 生成require的配置文件 Tools.buildReqCfg = (cb)-> # return false if _.has global.Cache,'reqCfg' Tools.getMap("jsHash") # 如果没有生成 jslibs,则重新生成 Tools.buildReqPaths() if not _.has global.Cache,'jsLibs' jsLibPaths = global.Cache['jsLibs'] reqShim = {} _reqShimFile = path.join(opts.mapPath, 'req_shim.json') try # 读取json配置 reqShim = JSON.parse fs.readFileSync(_reqShimFile, 'utf8') catch e Tools.writeFile(_reqShimFile,"{}") # 过滤核心库 newPaths = {} for key,val of jsLibPaths if key isnt 'require' and key isnt 'almond' newPaths[key] = val reqCfg = baseUrl: opts.cdnDomain + path.join(opts.debugPath,'js') paths: newPaths shim: reqShim # 写入缓存 global.Cache['reqCfg'] = reqCfg # 生成文件 reqCfgStr = "require.config(#{JSON.stringify(reqCfg, null, 2)});" curHash = Tools.md5(reqCfgStr) file = path.join(opts.debugPath, "js/reqcfg.js") global.Cache['jsHash']['reqcfg.js'] = curHash Tools.saveMapFile('jsHash') Tools.writeFile(file,reqCfgStr) cb and cb() # 获取静态资源的路径 Tools.getStaticPath = -> _isDebug = !!opts.isDebug _env = opts.env _debugPath = opts.cdnDomain + opts.debugPath _distPath = opts.cdnDomain + opts.distPath _staticPath = '' if _env isnt 'local' and _env isnt 'dev' _staticPath = _distPath else if _env is 'local' and _isDebug _staticPath = _distPath else _staticPath = _debugPath return _staticPath # 插入到页面中的全局变量 Tools.getGloabVars = ()-> _staticPath = Tools.getStaticPath() GLOBAL_VARS = "var STATIC_PATH='#{_staticPath}',sbLib = window['sbLib'] = {},_VM_ = window['_VM_'] = {};sbLib.getStaticUri = {img: function(n){return STATIC_PATH+'img/'+n;},css: function(n) {return STATIC_PATH+'css/'+n;},js: function(n) {return STATIC_PATH+'js/'+n}};" return "<script>#{GLOBAL_VARS}</script>" ###* * 构造 css 资源路径 * @param {string} cssList css列表 * @example * cssList = 'main.css,index.css' * init_css(cssList) ### Tools.init_css = (cssList)-> Tools.getMap('css') if not _.has global.Cache,"cssMap" _cssMap = global.Cache['cssMap'] # console.log _cssMap _env = opts.env _ver = opts.ver _isDebug = !!opts.isDebug _cssPath = Tools.getStaticPath() + 'css' _cssArr = cssList.split(',') _cssLinks = '' _timestamp = String(new Date().getTime()).substr(0,8) _cssArr.forEach (key)-> if key.indexOf(/\.css$/) == -1 key = key + '.css' if _env isnt 'local' and _env isnt 'dev' val = if _.has(_cssMap,key) then _cssMap[key].distname + "?v=#{_ver}" else "#{key}?v=#{_ver}&t=#{_timestamp}" else if _isDebug and _env is 'local' and _.has(_cssMap,key) val = _cssMap[key].distname + "?v=#{_ver}" else val = "#{key}?v=#{_ver}&t=#{_timestamp}" _cssLinks += "<link href='#{_cssPath}/#{val}' rel='stylesheet' type='text/css' />" return _cssLinks + Tools.getGloabVars() ###* * 构造 js 资源路径 * @param {string} jsList js列表 * @example * jsList = 'sb.corelibs.js,sb.app_index.js,piwik.js' * init_js(jsList) ### Tools.init_js = (jsList)-> _isDebug = !!opts.isDebug _env = opts.env _ver = opts.ver _jsLinks = "" Tools.getMap('js') if not _.has global.Cache,"jsMap" _jsMap = global.Cache['jsMap'] _jsPath = Tools.getStaticPath() + 'js' _coreJsName = opts.prefix + '.' + opts.coreJs.name + '.js' # console.log _coreJsName _jsArr = jsList.split(',') _timestamp = String(new Date().getTime()).substr(0,8) _reqJs = "<script src='#{_jsPath}/vendor/require/require.js?v=#{_ver}'></script>" if "Zepto" in opts.coreJs.mods or "zepto" in opts.coreJs.mods _reqJs += "<script src='#{_jsPath}/vendor/Zepto/zepto.js?v=#{_ver}'></script>" else _reqJs += "<script src='#{_jsPath}/vendor/jquery/jquery.js?v=#{_ver}'></script>" _reqJs += "<script src='#{_jsPath}/reqcfg.js?v=#{_ver}&t=#{_timestamp}'></script>" _buildSrcLink =(key)-> _link = '' if key.indexOf(opts.prefix) isnt 0 val = "#{key}?v=#{_ver}&t=#{_timestamp}" _link += "<script src='#{_jsPath}/#{val}'></script>" else if key is _coreJsName _link += _reqJs else _modName = key.replace("#{opts.prefix}.",'') .replace('.js','').replace(/\_/g,'/') _link += "<script>require(['#{_modName}'])</script>" return _link _buildDistLink = (key)-> _link = '' val = if _.has(_jsMap,key) then _jsMap[key].distname + "?v=#{_ver}" else "#{key}?v=#{_ver}&t=#{_timestamp}" _link += "<script src='#{_jsPath}/#{val}'></script>" return _link _jsArr.forEach (key)-> if key.indexOf(/\.js$/) == -1 key = key + '.js' if _env isnt 'local' and _env isnt 'dev' _jsLinks += _buildDistLink(key) else if _isDebug and _env is 'local' _jsLinks += _buildDistLink(key) else _jsLinks += _buildSrcLink(key) return _jsLinks # 构造 img 资源路径 Tools.init_img = (imgName)-> _this = Tools _env = opts.env _ver = opts.ver _isDebug = !!opts.isDebug _this.getMap('img') if not _.has global.Cache,"imgMap" _imgMap = global.Cache['imgMap'] _imgPath = _this.getStaticPath() + 'img' _timestamp = String(new Date().getTime()).substr(0,8) _val = if _env isnt 'local' and _env isnt 'dev' and not _isDebug and _.has(_imgMap,imgName) then _imgMap[imgName].distname + "?v=#{_ver}" else "#{imgName}?v=#{_ver}&t=#{_timestamp}" return "#{_imgPath}/#{_val}" Tools.jsonToPhpArray = (cb)-> _cb = cb or -> _mapPath = opts.mapPath _outPath = opts.viewPath _temp = [] _maps = ['cssmap','jsmap','imgmap'] _maps.forEach (key)-> file = _mapPath + key + '.json' phpFile = path.join(_outPath, 'map', key + ".php") _jsonData = JSON.parse fs.readFileSync(file, 'utf8') _tempArr = [] for name,val of _jsonData _name = val.distname _hash = val.hash _tempArr.push "'#{name}' => array('distname' => '#{_name}', 'hash' => '#{_hash}')" _temp[key] = _tempArr.join() _arrStr = '<?php' + '\r\n' + 'return array(' + _tempArr + ');' + '\r\n' + '?>' Tools.writeFile phpFile,_arrStr _cb() Tools.jsonToviewPath = (cb)-> _cb = cb or -> _mapPath = opts.mapPath _outPath = opts.viewPath _temp = [] _maps = ['cssmap','jsmap','imgmap'] _maps.forEach (key)-> file = _mapPath + key + '.json' mapFile = path.join(_outPath, 'map', key + ".json") _jsonData = fs.readFileSync(file, 'utf8') # console.log mapFile Tools.writeFile mapFile,_jsonData gutil.log color.green "Map done!" _cb() # 生成 dist 文件路径 Tools.setDistPath = (parse,hash)-> parse.base = parse.name + "." + hash.substring(0,Cfg.hashLen) + parse.ext return path.format(parse) module.exports = Tools
53474
###* # @fileOverview Basic tools # @date 2014-12-2 15:10:14 # @author pjg <<EMAIL>> # @link http://pjg.pw # @version $Id$ ### fs = require 'fs' path = require 'path' _ = require 'lodash' _url = require 'url' crypto = require 'crypto' http = require 'http' https = require 'https' uglify = require 'uglify-js' gutil = require 'gulp-util' color = gutil.colors Cfg = require '../cfg' # numCPUs = require('os').cpus().length opts = global.Cache['gOpts'] # console.log opts Tools = {} # md5 hash Tools.md5 = (source) -> # 使用二进制转换,解决中文摘要计算不准的问题 _buf = new Buffer(source) _str = _buf.toString "binary" crypto.createHash('md5').update(_str, 'utf8').digest('hex') # 错误报警,beep响两声 Tools.errrHandler = (e) -> gutil.beep() gutil.beep() gutil.log e ### # @fileOverview makedir ### Tools.mkdirsSync = (dirpath, mode)-> if fs.existsSync(dirpath) return true else if Tools.mkdirsSync path.dirname(dirpath), mode fs.mkdirSync(dirpath, mode) return true ### # @fileOverview makedirs ### Tools.mkdirs = (dirpath, mode, callback)-> fs.exists dirpath,(exists)-> if exists callback(exists) else # Try made the parent's dir,then make the current dir mkdirs path.dirname(dirpath), mode, -> fs.mkdir dirpath, mode, callback ### # @fileOverview obj mixin function # @Example # food = {'key':'apple'} # food2 = {'name':'banana','type':'fruit'} # console.log objMixin(food2,food) # console.log objMixin(food,food2) ### Tools.objMixin = _.partialRight _.assign, (a, b) -> val = if (typeof a is 'undefined') then b else a return val # 获取文件 Tools.getFileSync = (file, encoding)-> _encoding = encoding or 'utf8' fileCon = '' if fs.existsSync(file) stats = fs.statSync(file) if stats.isFile() fileCon = fs.readFileSync(file, _encoding) return fileCon # 获取文件json对象 Tools.getJSONSync = (file) -> fileCon = Tools.getFileSync(file) data = {} if fileCon fileCon = fileCon.replace(/\/\/[^\n]*/g, '') try data = JSON.parse(fileCon) catch e console.log e return data # 判断是否是空对象 Tools.isEmptyObject = (obj)-> for name of obj return false return true # 文件写入磁盘 Tools.writeFile = (file,source,isNotLog)-> # Tools.mkdirsSync(path.dirname(file)) # fs.writeFileSync file, source, 'utf8' # name = path.basename(file) # not isNotLog && gutil.log("'" + gutil.colors.cyan(name) + "'", "build success.") # 文件存在并且MD5值一样,则不重复写入 name = path.basename(file); if fs.existsSync(file) and Tools.md5(Tools.getFileSync(file)) is Tools.md5(source) return false Tools.mkdirsSync(path.dirname(file)) fs.writeFileSync(file, source, 'utf8') isNotLog or gutil.log("'" + gutil.colors.cyan(name) + "'", "build success.") # 压缩js源码 Tools.minifyJs = (source)-> mangled = uglify.minify(source,{fromString: true}) return mangled.code # 获取hash map Tools.getMap= (type)-> _this = Tools _map = {} _name = if type in ["css","img","js"] then "#{type}Map" else "#{type}" _file = opts.mapPath + _name.toLowerCase() + '.json' if not fs.existsSync(_file) # console.log _file _this.writeFile(_file,'{}') else _source = fs.readFileSync(_file) try _map = JSON.parse(_source, 'utf8') # console.log _map global.Cache[_name] = _map catch e try # console.log "#{_file}--->",e # 解决json文件冲突, git冲突 _source = _source.toString().replace(/<<<<<<<([\s\S]*?)>>>>>>>\s*\w*/g,'') _map = global.Cache[_name] = JSON.parse(_source) or {} _this.writeFile(_file,_source) catch e global.Cache[_name] = {} # opts = global.Cache['gOpts'] switch _name when 'imgMap' _ctl = require('../imgCtl') new _ctl(opts).init() when 'cssMap' _ctl = require('../cssCtl') new _ctl(opts).init() else global.Cache[_name] = {} _map = _.assign _map,global.Cache[_name] return _map # 更新map缓存 Tools.updateMap = (obj,mapName)-> if _.has(global.Cache,mapName) _.assign global.Cache[mapName],obj # 保存map文件 Tools.saveMapFile = (name)-> _name = name _file = opts.mapPath + _name.toLowerCase() + '.json' _map = {} try _map = JSON.parse(fs.readFileSync(_file), 'utf8') catch e console.log e _map = _.assign _map,global.Cache[_name] _data = JSON.stringify(_map, null, 4) Tools.writeFile(_file,_data) # 保存缓存文件 Tools.saveCache = -> _cache = global.Cache delete _cache.gOpts Tools.writeFile(opts.mapPath + 'cache.json',JSON.stringify(_cache, null, 0)) # 替换html模板中的img,原构建流程的保留方法 # 新版中请使用 ejs 语法,<@- init_img('logo.png') @> Tools.replaceImg = (source)-> Tools.getMap('img') imgPath = Tools.getStaticPath() + 'img/' imgMap = global.Cache['imgMap'] imgReg = /<img[\s\S]*?[^(src)]src=('|")([^'|^"]*)('|")/g file_source = source.replace imgReg,(str)-> # console.log str map = '' str.replace /src=('|")([^'|^"]*)('|")/,($1)-> map = $1.replace(/^src=/,'').replace(/(\'|\")|(\'|\"$)/g, '') if map.indexOf('/img/') isnt 0 or map.indexOf('http://') is 0 or map.indexOf('data:') is 0 or map.indexOf('/<?php/') isnt -1 return str else key = map.replace(/(^\'|\")|(\'|\"$)/g, '').split('img/')[1] val = imgPath + (if _.has(imgMap,key) and opts.env isnt 'local' then imgMap[key].distname else key + '?=t' + String(new Date().getTime()).substr(0,8)) # console.log "#{map}--> #{val}" return str.replace(map, val) return file_source # 压缩html Tools.htmlMinify = (source)-> s = source .replace(/\/\*([\s\S]*?)\*\//g, '') .replace(/<!--([\s\S]*?)-->/g, '') .replace(/^\s+$/g, '') .replace(/\n/g, '') .replace(/\t/g, '') .replace(/\r/g, '') .replace(/\n\s+/g, ' ') .replace(/\s+/g, ' ') .replace(/>([\n\s]*?)</g,'><') # .replace(/<?phpforeach/g,'<?php foreach') # .replace(/<?phpecho/g,'<?php echo') return s #判断是否window系统 Tools.isWin = -> return process.platform is "win32" #转换文件路径 Tools.tranFilePath = (filePath)-> _file = filePath or "" if Tools.isWin() _file = _file.replace /\\/g,'\/' return _file ### # build the three part's js libs paths ### Tools.buildReqPaths = (cb)-> _cb = cb or -> if _.has(global.Cache,'jsLibs') return false _libs = {} _reqPathsFile = path.join(opts.mapPath, 'req_paths.json') try _libs = JSON.parse fs.readFileSync(_reqPathsFile, 'utf8') catch err Tools.writeFile(_reqPathsFile,"{}") filePath = opts.srcPath + 'js/vendor/' fs.readdirSync(filePath).forEach (v)-> _path = path.join(filePath, v) if fs.statSync(_path).isDirectory() fs.readdirSync(_path).forEach (f)-> _file = path.join(_path, f) if fs.existsSync(_file) and f.indexOf('.') != 0 and f.indexOf('.js') != -1 _file = Tools.tranFilePath _file _libs[v] = _file.split('/js/')[1].replace(/\.js$/, '') # @writeFile(@jsLibs, JSON.stringify(_libs, null, 2)) global.Cache['jsLibs'] = _libs _cb() # 生成require的配置文件 Tools.buildReqCfg = (cb)-> # return false if _.has global.Cache,'reqCfg' Tools.getMap("jsHash") # 如果没有生成 jslibs,则重新生成 Tools.buildReqPaths() if not _.has global.Cache,'jsLibs' jsLibPaths = global.Cache['jsLibs'] reqShim = {} _reqShimFile = path.join(opts.mapPath, 'req_shim.json') try # 读取json配置 reqShim = JSON.parse fs.readFileSync(_reqShimFile, 'utf8') catch e Tools.writeFile(_reqShimFile,"{}") # 过滤核心库 newPaths = {} for key,val of jsLibPaths if key isnt 'require' and key isnt '<KEY>mond' newPaths[key] = val reqCfg = baseUrl: opts.cdnDomain + path.join(opts.debugPath,'js') paths: newPaths shim: reqShim # 写入缓存 global.Cache['reqCfg'] = reqCfg # 生成文件 reqCfgStr = "require.config(#{JSON.stringify(reqCfg, null, 2)});" curHash = Tools.md5(reqCfgStr) file = path.join(opts.debugPath, "js/reqcfg.js") global.Cache['jsHash']['reqcfg.js'] = curHash Tools.saveMapFile('jsHash') Tools.writeFile(file,reqCfgStr) cb and cb() # 获取静态资源的路径 Tools.getStaticPath = -> _isDebug = !!opts.isDebug _env = opts.env _debugPath = opts.cdnDomain + opts.debugPath _distPath = opts.cdnDomain + opts.distPath _staticPath = '' if _env isnt 'local' and _env isnt 'dev' _staticPath = _distPath else if _env is 'local' and _isDebug _staticPath = _distPath else _staticPath = _debugPath return _staticPath # 插入到页面中的全局变量 Tools.getGloabVars = ()-> _staticPath = Tools.getStaticPath() GLOBAL_VARS = "var STATIC_PATH='#{_staticPath}',sbLib = window['sbLib'] = {},_VM_ = window['_VM_'] = {};sbLib.getStaticUri = {img: function(n){return STATIC_PATH+'img/'+n;},css: function(n) {return STATIC_PATH+'css/'+n;},js: function(n) {return STATIC_PATH+'js/'+n}};" return "<script>#{GLOBAL_VARS}</script>" ###* * 构造 css 资源路径 * @param {string} cssList css列表 * @example * cssList = 'main.css,index.css' * init_css(cssList) ### Tools.init_css = (cssList)-> Tools.getMap('css') if not _.has global.Cache,"cssMap" _cssMap = global.Cache['cssMap'] # console.log _cssMap _env = opts.env _ver = opts.ver _isDebug = !!opts.isDebug _cssPath = Tools.getStaticPath() + 'css' _cssArr = cssList.split(',') _cssLinks = '' _timestamp = String(new Date().getTime()).substr(0,8) _cssArr.forEach (key)-> if key.indexOf(/\.css$/) == -1 key = key + '.css' if _env isnt 'local' and _env isnt 'dev' val = if _.has(_cssMap,key) then _cssMap[key].distname + "?v=#{_ver}" else "#{key}?v=#{_ver}&t=#{_timestamp}" else if _isDebug and _env is 'local' and _.has(_cssMap,key) val = _cssMap[key].distname + "?v=#{_ver}" else val = "#{key}?v=#{_ver}&t=#{_timestamp}" _cssLinks += "<link href='#{_cssPath}/#{val}' rel='stylesheet' type='text/css' />" return _cssLinks + Tools.getGloabVars() ###* * 构造 js 资源路径 * @param {string} jsList js列表 * @example * jsList = 'sb.corelibs.js,sb.app_index.js,piwik.js' * init_js(jsList) ### Tools.init_js = (jsList)-> _isDebug = !!opts.isDebug _env = opts.env _ver = opts.ver _jsLinks = "" Tools.getMap('js') if not _.has global.Cache,"jsMap" _jsMap = global.Cache['jsMap'] _jsPath = Tools.getStaticPath() + 'js' _coreJsName = opts.prefix + '.' + opts.coreJs.name + '.js' # console.log _coreJsName _jsArr = jsList.split(',') _timestamp = String(new Date().getTime()).substr(0,8) _reqJs = "<script src='#{_jsPath}/vendor/require/require.js?v=#{_ver}'></script>" if "Zepto" in opts.coreJs.mods or "zepto" in opts.coreJs.mods _reqJs += "<script src='#{_jsPath}/vendor/Zepto/zepto.js?v=#{_ver}'></script>" else _reqJs += "<script src='#{_jsPath}/vendor/jquery/jquery.js?v=#{_ver}'></script>" _reqJs += "<script src='#{_jsPath}/reqcfg.js?v=#{_ver}&t=#{_timestamp}'></script>" _buildSrcLink =(key)-> _link = '' if key.indexOf(opts.prefix) isnt 0 val = "#{key}?v=#{_ver}&t=#{_timestamp}" _link += "<script src='#{_jsPath}/#{val}'></script>" else if key is _coreJsName _link += _reqJs else _modName = key.replace("#{opts.prefix}.",'') .replace('.js','').replace(/\_/g,'/') _link += "<script>require(['#{_modName}'])</script>" return _link _buildDistLink = (key)-> _link = '' val = if _.has(_jsMap,key) then _jsMap[key].distname + "?v=#{_ver}" else "#{key}?v=#{_ver}&t=#{_timestamp}" _link += "<script src='#{_jsPath}/#{val}'></script>" return _link _jsArr.forEach (key)-> if key.indexOf(/\.js$/) == -1 key = key + '.js' if _env isnt 'local' and _env isnt 'dev' _jsLinks += _buildDistLink(key) else if _isDebug and _env is 'local' _jsLinks += _buildDistLink(key) else _jsLinks += _buildSrcLink(key) return _jsLinks # 构造 img 资源路径 Tools.init_img = (imgName)-> _this = Tools _env = opts.env _ver = opts.ver _isDebug = !!opts.isDebug _this.getMap('img') if not _.has global.Cache,"imgMap" _imgMap = global.Cache['imgMap'] _imgPath = _this.getStaticPath() + 'img' _timestamp = String(new Date().getTime()).substr(0,8) _val = if _env isnt 'local' and _env isnt 'dev' and not _isDebug and _.has(_imgMap,imgName) then _imgMap[imgName].distname + "?v=#{_ver}" else "#{imgName}?v=#{_ver}&t=#{_timestamp}" return "#{_imgPath}/#{_val}" Tools.jsonToPhpArray = (cb)-> _cb = cb or -> _mapPath = opts.mapPath _outPath = opts.viewPath _temp = [] _maps = ['cssmap','jsmap','imgmap'] _maps.forEach (key)-> file = _mapPath + key + '.json' phpFile = path.join(_outPath, 'map', key + ".php") _jsonData = JSON.parse fs.readFileSync(file, 'utf8') _tempArr = [] for name,val of _jsonData _name = val.distname _hash = val.hash _tempArr.push "'#{name}' => array('distname' => '#{_name}', 'hash' => '#{_hash}')" _temp[key] = _tempArr.join() _arrStr = '<?php' + '\r\n' + 'return array(' + _tempArr + ');' + '\r\n' + '?>' Tools.writeFile phpFile,_arrStr _cb() Tools.jsonToviewPath = (cb)-> _cb = cb or -> _mapPath = opts.mapPath _outPath = opts.viewPath _temp = [] _maps = ['cssmap','jsmap','imgmap'] _maps.forEach (key)-> file = _mapPath + key + '.json' mapFile = path.join(_outPath, 'map', key + ".json") _jsonData = fs.readFileSync(file, 'utf8') # console.log mapFile Tools.writeFile mapFile,_jsonData gutil.log color.green "Map done!" _cb() # 生成 dist 文件路径 Tools.setDistPath = (parse,hash)-> parse.base = parse.name + "." + hash.substring(0,Cfg.hashLen) + parse.ext return path.format(parse) module.exports = Tools
true
###* # @fileOverview Basic tools # @date 2014-12-2 15:10:14 # @author pjg <PI:EMAIL:<EMAIL>END_PI> # @link http://pjg.pw # @version $Id$ ### fs = require 'fs' path = require 'path' _ = require 'lodash' _url = require 'url' crypto = require 'crypto' http = require 'http' https = require 'https' uglify = require 'uglify-js' gutil = require 'gulp-util' color = gutil.colors Cfg = require '../cfg' # numCPUs = require('os').cpus().length opts = global.Cache['gOpts'] # console.log opts Tools = {} # md5 hash Tools.md5 = (source) -> # 使用二进制转换,解决中文摘要计算不准的问题 _buf = new Buffer(source) _str = _buf.toString "binary" crypto.createHash('md5').update(_str, 'utf8').digest('hex') # 错误报警,beep响两声 Tools.errrHandler = (e) -> gutil.beep() gutil.beep() gutil.log e ### # @fileOverview makedir ### Tools.mkdirsSync = (dirpath, mode)-> if fs.existsSync(dirpath) return true else if Tools.mkdirsSync path.dirname(dirpath), mode fs.mkdirSync(dirpath, mode) return true ### # @fileOverview makedirs ### Tools.mkdirs = (dirpath, mode, callback)-> fs.exists dirpath,(exists)-> if exists callback(exists) else # Try made the parent's dir,then make the current dir mkdirs path.dirname(dirpath), mode, -> fs.mkdir dirpath, mode, callback ### # @fileOverview obj mixin function # @Example # food = {'key':'apple'} # food2 = {'name':'banana','type':'fruit'} # console.log objMixin(food2,food) # console.log objMixin(food,food2) ### Tools.objMixin = _.partialRight _.assign, (a, b) -> val = if (typeof a is 'undefined') then b else a return val # 获取文件 Tools.getFileSync = (file, encoding)-> _encoding = encoding or 'utf8' fileCon = '' if fs.existsSync(file) stats = fs.statSync(file) if stats.isFile() fileCon = fs.readFileSync(file, _encoding) return fileCon # 获取文件json对象 Tools.getJSONSync = (file) -> fileCon = Tools.getFileSync(file) data = {} if fileCon fileCon = fileCon.replace(/\/\/[^\n]*/g, '') try data = JSON.parse(fileCon) catch e console.log e return data # 判断是否是空对象 Tools.isEmptyObject = (obj)-> for name of obj return false return true # 文件写入磁盘 Tools.writeFile = (file,source,isNotLog)-> # Tools.mkdirsSync(path.dirname(file)) # fs.writeFileSync file, source, 'utf8' # name = path.basename(file) # not isNotLog && gutil.log("'" + gutil.colors.cyan(name) + "'", "build success.") # 文件存在并且MD5值一样,则不重复写入 name = path.basename(file); if fs.existsSync(file) and Tools.md5(Tools.getFileSync(file)) is Tools.md5(source) return false Tools.mkdirsSync(path.dirname(file)) fs.writeFileSync(file, source, 'utf8') isNotLog or gutil.log("'" + gutil.colors.cyan(name) + "'", "build success.") # 压缩js源码 Tools.minifyJs = (source)-> mangled = uglify.minify(source,{fromString: true}) return mangled.code # 获取hash map Tools.getMap= (type)-> _this = Tools _map = {} _name = if type in ["css","img","js"] then "#{type}Map" else "#{type}" _file = opts.mapPath + _name.toLowerCase() + '.json' if not fs.existsSync(_file) # console.log _file _this.writeFile(_file,'{}') else _source = fs.readFileSync(_file) try _map = JSON.parse(_source, 'utf8') # console.log _map global.Cache[_name] = _map catch e try # console.log "#{_file}--->",e # 解决json文件冲突, git冲突 _source = _source.toString().replace(/<<<<<<<([\s\S]*?)>>>>>>>\s*\w*/g,'') _map = global.Cache[_name] = JSON.parse(_source) or {} _this.writeFile(_file,_source) catch e global.Cache[_name] = {} # opts = global.Cache['gOpts'] switch _name when 'imgMap' _ctl = require('../imgCtl') new _ctl(opts).init() when 'cssMap' _ctl = require('../cssCtl') new _ctl(opts).init() else global.Cache[_name] = {} _map = _.assign _map,global.Cache[_name] return _map # 更新map缓存 Tools.updateMap = (obj,mapName)-> if _.has(global.Cache,mapName) _.assign global.Cache[mapName],obj # 保存map文件 Tools.saveMapFile = (name)-> _name = name _file = opts.mapPath + _name.toLowerCase() + '.json' _map = {} try _map = JSON.parse(fs.readFileSync(_file), 'utf8') catch e console.log e _map = _.assign _map,global.Cache[_name] _data = JSON.stringify(_map, null, 4) Tools.writeFile(_file,_data) # 保存缓存文件 Tools.saveCache = -> _cache = global.Cache delete _cache.gOpts Tools.writeFile(opts.mapPath + 'cache.json',JSON.stringify(_cache, null, 0)) # 替换html模板中的img,原构建流程的保留方法 # 新版中请使用 ejs 语法,<@- init_img('logo.png') @> Tools.replaceImg = (source)-> Tools.getMap('img') imgPath = Tools.getStaticPath() + 'img/' imgMap = global.Cache['imgMap'] imgReg = /<img[\s\S]*?[^(src)]src=('|")([^'|^"]*)('|")/g file_source = source.replace imgReg,(str)-> # console.log str map = '' str.replace /src=('|")([^'|^"]*)('|")/,($1)-> map = $1.replace(/^src=/,'').replace(/(\'|\")|(\'|\"$)/g, '') if map.indexOf('/img/') isnt 0 or map.indexOf('http://') is 0 or map.indexOf('data:') is 0 or map.indexOf('/<?php/') isnt -1 return str else key = map.replace(/(^\'|\")|(\'|\"$)/g, '').split('img/')[1] val = imgPath + (if _.has(imgMap,key) and opts.env isnt 'local' then imgMap[key].distname else key + '?=t' + String(new Date().getTime()).substr(0,8)) # console.log "#{map}--> #{val}" return str.replace(map, val) return file_source # 压缩html Tools.htmlMinify = (source)-> s = source .replace(/\/\*([\s\S]*?)\*\//g, '') .replace(/<!--([\s\S]*?)-->/g, '') .replace(/^\s+$/g, '') .replace(/\n/g, '') .replace(/\t/g, '') .replace(/\r/g, '') .replace(/\n\s+/g, ' ') .replace(/\s+/g, ' ') .replace(/>([\n\s]*?)</g,'><') # .replace(/<?phpforeach/g,'<?php foreach') # .replace(/<?phpecho/g,'<?php echo') return s #判断是否window系统 Tools.isWin = -> return process.platform is "win32" #转换文件路径 Tools.tranFilePath = (filePath)-> _file = filePath or "" if Tools.isWin() _file = _file.replace /\\/g,'\/' return _file ### # build the three part's js libs paths ### Tools.buildReqPaths = (cb)-> _cb = cb or -> if _.has(global.Cache,'jsLibs') return false _libs = {} _reqPathsFile = path.join(opts.mapPath, 'req_paths.json') try _libs = JSON.parse fs.readFileSync(_reqPathsFile, 'utf8') catch err Tools.writeFile(_reqPathsFile,"{}") filePath = opts.srcPath + 'js/vendor/' fs.readdirSync(filePath).forEach (v)-> _path = path.join(filePath, v) if fs.statSync(_path).isDirectory() fs.readdirSync(_path).forEach (f)-> _file = path.join(_path, f) if fs.existsSync(_file) and f.indexOf('.') != 0 and f.indexOf('.js') != -1 _file = Tools.tranFilePath _file _libs[v] = _file.split('/js/')[1].replace(/\.js$/, '') # @writeFile(@jsLibs, JSON.stringify(_libs, null, 2)) global.Cache['jsLibs'] = _libs _cb() # 生成require的配置文件 Tools.buildReqCfg = (cb)-> # return false if _.has global.Cache,'reqCfg' Tools.getMap("jsHash") # 如果没有生成 jslibs,则重新生成 Tools.buildReqPaths() if not _.has global.Cache,'jsLibs' jsLibPaths = global.Cache['jsLibs'] reqShim = {} _reqShimFile = path.join(opts.mapPath, 'req_shim.json') try # 读取json配置 reqShim = JSON.parse fs.readFileSync(_reqShimFile, 'utf8') catch e Tools.writeFile(_reqShimFile,"{}") # 过滤核心库 newPaths = {} for key,val of jsLibPaths if key isnt 'require' and key isnt 'PI:KEY:<KEY>END_PImond' newPaths[key] = val reqCfg = baseUrl: opts.cdnDomain + path.join(opts.debugPath,'js') paths: newPaths shim: reqShim # 写入缓存 global.Cache['reqCfg'] = reqCfg # 生成文件 reqCfgStr = "require.config(#{JSON.stringify(reqCfg, null, 2)});" curHash = Tools.md5(reqCfgStr) file = path.join(opts.debugPath, "js/reqcfg.js") global.Cache['jsHash']['reqcfg.js'] = curHash Tools.saveMapFile('jsHash') Tools.writeFile(file,reqCfgStr) cb and cb() # 获取静态资源的路径 Tools.getStaticPath = -> _isDebug = !!opts.isDebug _env = opts.env _debugPath = opts.cdnDomain + opts.debugPath _distPath = opts.cdnDomain + opts.distPath _staticPath = '' if _env isnt 'local' and _env isnt 'dev' _staticPath = _distPath else if _env is 'local' and _isDebug _staticPath = _distPath else _staticPath = _debugPath return _staticPath # 插入到页面中的全局变量 Tools.getGloabVars = ()-> _staticPath = Tools.getStaticPath() GLOBAL_VARS = "var STATIC_PATH='#{_staticPath}',sbLib = window['sbLib'] = {},_VM_ = window['_VM_'] = {};sbLib.getStaticUri = {img: function(n){return STATIC_PATH+'img/'+n;},css: function(n) {return STATIC_PATH+'css/'+n;},js: function(n) {return STATIC_PATH+'js/'+n}};" return "<script>#{GLOBAL_VARS}</script>" ###* * 构造 css 资源路径 * @param {string} cssList css列表 * @example * cssList = 'main.css,index.css' * init_css(cssList) ### Tools.init_css = (cssList)-> Tools.getMap('css') if not _.has global.Cache,"cssMap" _cssMap = global.Cache['cssMap'] # console.log _cssMap _env = opts.env _ver = opts.ver _isDebug = !!opts.isDebug _cssPath = Tools.getStaticPath() + 'css' _cssArr = cssList.split(',') _cssLinks = '' _timestamp = String(new Date().getTime()).substr(0,8) _cssArr.forEach (key)-> if key.indexOf(/\.css$/) == -1 key = key + '.css' if _env isnt 'local' and _env isnt 'dev' val = if _.has(_cssMap,key) then _cssMap[key].distname + "?v=#{_ver}" else "#{key}?v=#{_ver}&t=#{_timestamp}" else if _isDebug and _env is 'local' and _.has(_cssMap,key) val = _cssMap[key].distname + "?v=#{_ver}" else val = "#{key}?v=#{_ver}&t=#{_timestamp}" _cssLinks += "<link href='#{_cssPath}/#{val}' rel='stylesheet' type='text/css' />" return _cssLinks + Tools.getGloabVars() ###* * 构造 js 资源路径 * @param {string} jsList js列表 * @example * jsList = 'sb.corelibs.js,sb.app_index.js,piwik.js' * init_js(jsList) ### Tools.init_js = (jsList)-> _isDebug = !!opts.isDebug _env = opts.env _ver = opts.ver _jsLinks = "" Tools.getMap('js') if not _.has global.Cache,"jsMap" _jsMap = global.Cache['jsMap'] _jsPath = Tools.getStaticPath() + 'js' _coreJsName = opts.prefix + '.' + opts.coreJs.name + '.js' # console.log _coreJsName _jsArr = jsList.split(',') _timestamp = String(new Date().getTime()).substr(0,8) _reqJs = "<script src='#{_jsPath}/vendor/require/require.js?v=#{_ver}'></script>" if "Zepto" in opts.coreJs.mods or "zepto" in opts.coreJs.mods _reqJs += "<script src='#{_jsPath}/vendor/Zepto/zepto.js?v=#{_ver}'></script>" else _reqJs += "<script src='#{_jsPath}/vendor/jquery/jquery.js?v=#{_ver}'></script>" _reqJs += "<script src='#{_jsPath}/reqcfg.js?v=#{_ver}&t=#{_timestamp}'></script>" _buildSrcLink =(key)-> _link = '' if key.indexOf(opts.prefix) isnt 0 val = "#{key}?v=#{_ver}&t=#{_timestamp}" _link += "<script src='#{_jsPath}/#{val}'></script>" else if key is _coreJsName _link += _reqJs else _modName = key.replace("#{opts.prefix}.",'') .replace('.js','').replace(/\_/g,'/') _link += "<script>require(['#{_modName}'])</script>" return _link _buildDistLink = (key)-> _link = '' val = if _.has(_jsMap,key) then _jsMap[key].distname + "?v=#{_ver}" else "#{key}?v=#{_ver}&t=#{_timestamp}" _link += "<script src='#{_jsPath}/#{val}'></script>" return _link _jsArr.forEach (key)-> if key.indexOf(/\.js$/) == -1 key = key + '.js' if _env isnt 'local' and _env isnt 'dev' _jsLinks += _buildDistLink(key) else if _isDebug and _env is 'local' _jsLinks += _buildDistLink(key) else _jsLinks += _buildSrcLink(key) return _jsLinks # 构造 img 资源路径 Tools.init_img = (imgName)-> _this = Tools _env = opts.env _ver = opts.ver _isDebug = !!opts.isDebug _this.getMap('img') if not _.has global.Cache,"imgMap" _imgMap = global.Cache['imgMap'] _imgPath = _this.getStaticPath() + 'img' _timestamp = String(new Date().getTime()).substr(0,8) _val = if _env isnt 'local' and _env isnt 'dev' and not _isDebug and _.has(_imgMap,imgName) then _imgMap[imgName].distname + "?v=#{_ver}" else "#{imgName}?v=#{_ver}&t=#{_timestamp}" return "#{_imgPath}/#{_val}" Tools.jsonToPhpArray = (cb)-> _cb = cb or -> _mapPath = opts.mapPath _outPath = opts.viewPath _temp = [] _maps = ['cssmap','jsmap','imgmap'] _maps.forEach (key)-> file = _mapPath + key + '.json' phpFile = path.join(_outPath, 'map', key + ".php") _jsonData = JSON.parse fs.readFileSync(file, 'utf8') _tempArr = [] for name,val of _jsonData _name = val.distname _hash = val.hash _tempArr.push "'#{name}' => array('distname' => '#{_name}', 'hash' => '#{_hash}')" _temp[key] = _tempArr.join() _arrStr = '<?php' + '\r\n' + 'return array(' + _tempArr + ');' + '\r\n' + '?>' Tools.writeFile phpFile,_arrStr _cb() Tools.jsonToviewPath = (cb)-> _cb = cb or -> _mapPath = opts.mapPath _outPath = opts.viewPath _temp = [] _maps = ['cssmap','jsmap','imgmap'] _maps.forEach (key)-> file = _mapPath + key + '.json' mapFile = path.join(_outPath, 'map', key + ".json") _jsonData = fs.readFileSync(file, 'utf8') # console.log mapFile Tools.writeFile mapFile,_jsonData gutil.log color.green "Map done!" _cb() # 生成 dist 文件路径 Tools.setDistPath = (parse,hash)-> parse.base = parse.name + "." + hash.substring(0,Cfg.hashLen) + parse.ext return path.format(parse) module.exports = Tools
[ { "context": " }\n\n statusNode =\n node:\n key: '/foo/bar/status'\n dir: true\n nodes: [\n key", "end": 3154, "score": 0.8865167498588562, "start": 3138, "tag": "KEY", "value": "'/foo/bar/status" }, { "context": " dir: true\n nodes: [\n key: '/foo/bar/status/travis'\n value: 'build successful", "end": 3215, "score": 0.8010784983634949, "start": 3208, "tag": "KEY", "value": "foo/bar" }, { "context": "u-foo-bar-development-1\"\n URL: \"http://127.0.0.1:#{@server1.address().port}\"\n }\n }", "end": 3989, "score": 0.9997171759605408, "start": 3980, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "u-foo-bar-development-2\"\n URL: \"http://127.0.0.1:#{@server2.address().port}\"\n }\n }", "end": 4241, "score": 0.9997169971466064, "start": 4232, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "u-foo-bar-development-3\"\n URL: \"http://0.0.0.0:0\"\n }\n }]\n\n @etcdMajorStatusHa", "end": 4491, "score": 0.8986910581588745, "start": 4484, "tag": "IP_ADDRESS", "value": "0.0.0.0" }, { "context": "'\n baseUrl: @baseUrl\n auth: {username: 'deploy-uuid', password: 'deploy-token'}\n\n request.get opti", "end": 5507, "score": 0.9908781051635742, "start": 5496, "tag": "USERNAME", "value": "deploy-uuid" }, { "context": "\n auth: {username: 'deploy-uuid', password: 'deploy-token'}\n\n request.get options, (error, @response, @b", "end": 5533, "score": 0.9993615746498108, "start": 5521, "tag": "PASSWORD", "value": "deploy-token" }, { "context": "blu-foo-bar-development-1'\n url: \"http://127.0.0.1:#{@server1.address().port}\"\n version: 'v", "end": 6234, "score": 0.9996865391731262, "start": 6225, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "blu-foo-bar-development-2'\n url: \"http://127.0.0.1:#{@server2.address().port}\"\n version: \"(", "end": 6384, "score": 0.9997122287750244, "start": 6375, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "lu-foo-bar-development-3'\n url: \"http://0.0.0.0:0\"\n }]\n quay:\n tag: 'v1.0.0'\n ", "end": 6537, "score": 0.7760515213012695, "start": 6532, "tag": "IP_ADDRESS", "value": "0.0.0" } ]
test/integration/v2-status-spec.coffee
octoblu/deployinate-service
1
{afterEach, beforeEach, describe, it} = global {expect} = require 'chai' request = require 'request' enableDestroy = require 'server-destroy' shmock = require 'shmock' url = require 'url' Server = require '../../src/server' describe 'GET /v2/status/foo/bar', -> beforeEach (done) -> @meshbluServer = shmock() enableDestroy @meshbluServer meshbluAddress = @meshbluServer.address() @governatorMajor = shmock() @governatorMinor = shmock() @server1 = shmock() @server2 = shmock() GOVERNATOR_MAJOR_URL = url.format protocol: 'http' hostname: 'localhost' port: @governatorMajor.address().port auth: 'guv-uuid:guv-token' GOVERNATOR_MINOR_URL = url.format protocol: 'http' hostname: 'localhost' port: @governatorMinor.address().port auth: 'guv-uuid:guv-token' @etcdMajor = shmock() @etcdMinor = shmock() ETCD_MAJOR_URI = url.format protocol: 'http', hostname: 'localhost', port: @etcdMajor.address().port ETCD_MINOR_URI = url.format protocol: 'http', hostname: 'localhost', port: @etcdMinor.address().port @quay = shmock() QUAY_URL = url.format protocol: 'http' hostname: 'localhost' port: @quay.address().port meshbluConfig = protocol: 'http' server: 'localhost' port: meshbluAddress.port uuid: 'deploy-uuid' @sut = new Server { ETCD_MAJOR_URI ETCD_MINOR_URI GOVERNATOR_MAJOR_URL GOVERNATOR_MINOR_URL TRAVIS_ORG_URL: 'nothing' TRAVIS_ORG_TOKEN: 'nothing' TRAVIS_PRO_URL: 'nothing' TRAVIS_PRO_TOKEN: 'nothing' QUAY_URL: QUAY_URL QUAY_TOKEN: 'quay-token' meshbluConfig } @sut.run done afterEach (done) -> @sut.close done afterEach (done) -> @quay.close done afterEach (done) -> @etcdMajor.close done afterEach (done) -> @etcdMinor.close done afterEach (done) -> @server2.close done afterEach (done) -> @server1.close done afterEach (done) -> @governatorMinor.close done afterEach (done) -> @governatorMajor.close done afterEach (done) -> @meshbluServer.destroy done beforeEach -> {port} = @sut.address() @baseUrl = url.format protocol: 'http', hostname: 'localhost', port: port deployAuth = new Buffer('deploy-uuid:deploy-token').toString 'base64' guvAuth = new Buffer('guv-uuid:guv-token').toString 'base64' @meshbluHandler = @meshbluServer .post '/authenticate' .set 'Authorization', "Basic #{deployAuth}" .reply 200, uuid: 'governator-uuid' @majorHandler = @governatorMajor .get '/status' .set 'Authorization', "Basic #{guvAuth}" .reply 200, { 'governator:/foo/bar:quay.io/foo/bar:v1.0.0': key: 'governator:/foo/bar:quay.io/foo/bar:v1.0.0' deployAt: 2005059595 status: 'pending' 'governator:/baz/awefaw:quay.io/foo/bar:v1.0.0': key: 'governator:/baz/awefaw:quay.io/foo/bar:v1.0.0' deployAt: 2005059595 status: 'pending' } statusNode = node: key: '/foo/bar/status' dir: true nodes: [ key: '/foo/bar/status/travis' value: 'build successful: v1.0.0' ] majorVersionNode = node: key: '/foo/bar/docker_url' dir: true nodes: [ key: '/foo/bar/docker_url' value: 'quay.io/foo/bar:v0.9.9' ] minorVersionNode = node: key: '/foo/bar/docker_url' dir: true nodes: [ key: '/foo/bar/docker_url' value: 'quay.io/foo/bar:v1.0.0' ] vulcandNode = node: key: '/vulcand/backends/foo-bar/servers' dir: true nodes: [{ key: '/vulcand/backends/foo-bar/servers/octoblu-foo-bar-development-1' value: JSON.stringify { Id: "octoblu-foo-bar-development-1" URL: "http://127.0.0.1:#{@server1.address().port}" } }, { key: '/vulcand/backends/foo-bar/servers/octoblu-foo-bar-development-2' value: JSON.stringify { Id: "octoblu-foo-bar-development-2" URL: "http://127.0.0.1:#{@server2.address().port}" } }, { key: '/vulcand/backends/foo-bar/servers/octoblu-foo-bar-development-3' value: JSON.stringify { Id: "octoblu-foo-bar-development-3" URL: "http://0.0.0.0:0" } }] @etcdMajorStatusHandler = @etcdMajor .get '/v2/keys/foo/bar/status' .reply 200, statusNode @etcdMajorVulcandHandler = @etcdMajor .get '/v2/keys/vulcand/backends/foo-bar/servers' .reply 200, vulcandNode @etcdMajorDockerUrlHandler = @etcdMajor .get '/v2/keys/foo/bar/docker_url' .reply 200, majorVersionNode @etcdMinorDockerUrlHandler = @etcdMinor .get '/v2/keys/foo/bar/docker_url' .reply 200, minorVersionNode @quayHandler = @quay .get '/api/v1/repository/foo/bar/build/' .set 'Authorization', 'Bearer quay-token' .reply 200, builds: [{tags: ['v1.0.0'], phase: 'building', started: 'blah blah'}] @server1Handler = @server1 .get '/version' .reply 200, version: '2.2.0' @server2Handler = @server2 .get '/version' .reply 404, 'Not Found' beforeEach (done) -> options = uri: '/v2/status/foo/bar' baseUrl: @baseUrl auth: {username: 'deploy-uuid', password: 'deploy-token'} request.get options, (error, @response, @body) => return done error if error? done() it 'should return a 200', -> expect(@response.statusCode).to.equal 200, JSON.stringify(@body) it 'should return a status', -> expectedResponse = majorVersion: 'quay.io/foo/bar:v0.9.9' minorVersion: 'quay.io/foo/bar:v1.0.0' status: travis: 'build successful: v1.0.0' deployments: "governator:/foo/bar:quay.io/foo/bar:v1.0.0": deployAt: 2005059595 key: "governator:/foo/bar:quay.io/foo/bar:v1.0.0" status: "pending" servers: [{ name: 'octoblu-foo-bar-development-1' url: "http://127.0.0.1:#{@server1.address().port}" version: 'v2.2.0' }, { name: 'octoblu-foo-bar-development-2' url: "http://127.0.0.1:#{@server2.address().port}" version: "(HTTP: 404)" }, { name: 'octoblu-foo-bar-development-3' url: "http://0.0.0.0:0" }] quay: tag: 'v1.0.0' phase: 'building' startedAt: 'blah blah' expect(JSON.parse @response.body).to.containSubset expectedResponse it 'should call the handlers', -> expect(@meshbluHandler.isDone).to.be.true expect(@etcdMajorStatusHandler.isDone).to.be.true expect(@etcdMajorVulcandHandler.isDone).to.be.true expect(@etcdMajorDockerUrlHandler.isDone).to.be.true expect(@etcdMinorDockerUrlHandler.isDone).to.be.true expect(@majorHandler.isDone).to.be.true expect(@quayHandler.isDone).to.be.true expect(@server1Handler.isDone).to.be.true expect(@server2Handler.isDone).to.be.true
45860
{afterEach, beforeEach, describe, it} = global {expect} = require 'chai' request = require 'request' enableDestroy = require 'server-destroy' shmock = require 'shmock' url = require 'url' Server = require '../../src/server' describe 'GET /v2/status/foo/bar', -> beforeEach (done) -> @meshbluServer = shmock() enableDestroy @meshbluServer meshbluAddress = @meshbluServer.address() @governatorMajor = shmock() @governatorMinor = shmock() @server1 = shmock() @server2 = shmock() GOVERNATOR_MAJOR_URL = url.format protocol: 'http' hostname: 'localhost' port: @governatorMajor.address().port auth: 'guv-uuid:guv-token' GOVERNATOR_MINOR_URL = url.format protocol: 'http' hostname: 'localhost' port: @governatorMinor.address().port auth: 'guv-uuid:guv-token' @etcdMajor = shmock() @etcdMinor = shmock() ETCD_MAJOR_URI = url.format protocol: 'http', hostname: 'localhost', port: @etcdMajor.address().port ETCD_MINOR_URI = url.format protocol: 'http', hostname: 'localhost', port: @etcdMinor.address().port @quay = shmock() QUAY_URL = url.format protocol: 'http' hostname: 'localhost' port: @quay.address().port meshbluConfig = protocol: 'http' server: 'localhost' port: meshbluAddress.port uuid: 'deploy-uuid' @sut = new Server { ETCD_MAJOR_URI ETCD_MINOR_URI GOVERNATOR_MAJOR_URL GOVERNATOR_MINOR_URL TRAVIS_ORG_URL: 'nothing' TRAVIS_ORG_TOKEN: 'nothing' TRAVIS_PRO_URL: 'nothing' TRAVIS_PRO_TOKEN: 'nothing' QUAY_URL: QUAY_URL QUAY_TOKEN: 'quay-token' meshbluConfig } @sut.run done afterEach (done) -> @sut.close done afterEach (done) -> @quay.close done afterEach (done) -> @etcdMajor.close done afterEach (done) -> @etcdMinor.close done afterEach (done) -> @server2.close done afterEach (done) -> @server1.close done afterEach (done) -> @governatorMinor.close done afterEach (done) -> @governatorMajor.close done afterEach (done) -> @meshbluServer.destroy done beforeEach -> {port} = @sut.address() @baseUrl = url.format protocol: 'http', hostname: 'localhost', port: port deployAuth = new Buffer('deploy-uuid:deploy-token').toString 'base64' guvAuth = new Buffer('guv-uuid:guv-token').toString 'base64' @meshbluHandler = @meshbluServer .post '/authenticate' .set 'Authorization', "Basic #{deployAuth}" .reply 200, uuid: 'governator-uuid' @majorHandler = @governatorMajor .get '/status' .set 'Authorization', "Basic #{guvAuth}" .reply 200, { 'governator:/foo/bar:quay.io/foo/bar:v1.0.0': key: 'governator:/foo/bar:quay.io/foo/bar:v1.0.0' deployAt: 2005059595 status: 'pending' 'governator:/baz/awefaw:quay.io/foo/bar:v1.0.0': key: 'governator:/baz/awefaw:quay.io/foo/bar:v1.0.0' deployAt: 2005059595 status: 'pending' } statusNode = node: key: <KEY>' dir: true nodes: [ key: '/<KEY>/status/travis' value: 'build successful: v1.0.0' ] majorVersionNode = node: key: '/foo/bar/docker_url' dir: true nodes: [ key: '/foo/bar/docker_url' value: 'quay.io/foo/bar:v0.9.9' ] minorVersionNode = node: key: '/foo/bar/docker_url' dir: true nodes: [ key: '/foo/bar/docker_url' value: 'quay.io/foo/bar:v1.0.0' ] vulcandNode = node: key: '/vulcand/backends/foo-bar/servers' dir: true nodes: [{ key: '/vulcand/backends/foo-bar/servers/octoblu-foo-bar-development-1' value: JSON.stringify { Id: "octoblu-foo-bar-development-1" URL: "http://127.0.0.1:#{@server1.address().port}" } }, { key: '/vulcand/backends/foo-bar/servers/octoblu-foo-bar-development-2' value: JSON.stringify { Id: "octoblu-foo-bar-development-2" URL: "http://127.0.0.1:#{@server2.address().port}" } }, { key: '/vulcand/backends/foo-bar/servers/octoblu-foo-bar-development-3' value: JSON.stringify { Id: "octoblu-foo-bar-development-3" URL: "http://0.0.0.0:0" } }] @etcdMajorStatusHandler = @etcdMajor .get '/v2/keys/foo/bar/status' .reply 200, statusNode @etcdMajorVulcandHandler = @etcdMajor .get '/v2/keys/vulcand/backends/foo-bar/servers' .reply 200, vulcandNode @etcdMajorDockerUrlHandler = @etcdMajor .get '/v2/keys/foo/bar/docker_url' .reply 200, majorVersionNode @etcdMinorDockerUrlHandler = @etcdMinor .get '/v2/keys/foo/bar/docker_url' .reply 200, minorVersionNode @quayHandler = @quay .get '/api/v1/repository/foo/bar/build/' .set 'Authorization', 'Bearer quay-token' .reply 200, builds: [{tags: ['v1.0.0'], phase: 'building', started: 'blah blah'}] @server1Handler = @server1 .get '/version' .reply 200, version: '2.2.0' @server2Handler = @server2 .get '/version' .reply 404, 'Not Found' beforeEach (done) -> options = uri: '/v2/status/foo/bar' baseUrl: @baseUrl auth: {username: 'deploy-uuid', password: '<PASSWORD>'} request.get options, (error, @response, @body) => return done error if error? done() it 'should return a 200', -> expect(@response.statusCode).to.equal 200, JSON.stringify(@body) it 'should return a status', -> expectedResponse = majorVersion: 'quay.io/foo/bar:v0.9.9' minorVersion: 'quay.io/foo/bar:v1.0.0' status: travis: 'build successful: v1.0.0' deployments: "governator:/foo/bar:quay.io/foo/bar:v1.0.0": deployAt: 2005059595 key: "governator:/foo/bar:quay.io/foo/bar:v1.0.0" status: "pending" servers: [{ name: 'octoblu-foo-bar-development-1' url: "http://127.0.0.1:#{@server1.address().port}" version: 'v2.2.0' }, { name: 'octoblu-foo-bar-development-2' url: "http://127.0.0.1:#{@server2.address().port}" version: "(HTTP: 404)" }, { name: 'octoblu-foo-bar-development-3' url: "http://0.0.0.0:0" }] quay: tag: 'v1.0.0' phase: 'building' startedAt: 'blah blah' expect(JSON.parse @response.body).to.containSubset expectedResponse it 'should call the handlers', -> expect(@meshbluHandler.isDone).to.be.true expect(@etcdMajorStatusHandler.isDone).to.be.true expect(@etcdMajorVulcandHandler.isDone).to.be.true expect(@etcdMajorDockerUrlHandler.isDone).to.be.true expect(@etcdMinorDockerUrlHandler.isDone).to.be.true expect(@majorHandler.isDone).to.be.true expect(@quayHandler.isDone).to.be.true expect(@server1Handler.isDone).to.be.true expect(@server2Handler.isDone).to.be.true
true
{afterEach, beforeEach, describe, it} = global {expect} = require 'chai' request = require 'request' enableDestroy = require 'server-destroy' shmock = require 'shmock' url = require 'url' Server = require '../../src/server' describe 'GET /v2/status/foo/bar', -> beforeEach (done) -> @meshbluServer = shmock() enableDestroy @meshbluServer meshbluAddress = @meshbluServer.address() @governatorMajor = shmock() @governatorMinor = shmock() @server1 = shmock() @server2 = shmock() GOVERNATOR_MAJOR_URL = url.format protocol: 'http' hostname: 'localhost' port: @governatorMajor.address().port auth: 'guv-uuid:guv-token' GOVERNATOR_MINOR_URL = url.format protocol: 'http' hostname: 'localhost' port: @governatorMinor.address().port auth: 'guv-uuid:guv-token' @etcdMajor = shmock() @etcdMinor = shmock() ETCD_MAJOR_URI = url.format protocol: 'http', hostname: 'localhost', port: @etcdMajor.address().port ETCD_MINOR_URI = url.format protocol: 'http', hostname: 'localhost', port: @etcdMinor.address().port @quay = shmock() QUAY_URL = url.format protocol: 'http' hostname: 'localhost' port: @quay.address().port meshbluConfig = protocol: 'http' server: 'localhost' port: meshbluAddress.port uuid: 'deploy-uuid' @sut = new Server { ETCD_MAJOR_URI ETCD_MINOR_URI GOVERNATOR_MAJOR_URL GOVERNATOR_MINOR_URL TRAVIS_ORG_URL: 'nothing' TRAVIS_ORG_TOKEN: 'nothing' TRAVIS_PRO_URL: 'nothing' TRAVIS_PRO_TOKEN: 'nothing' QUAY_URL: QUAY_URL QUAY_TOKEN: 'quay-token' meshbluConfig } @sut.run done afterEach (done) -> @sut.close done afterEach (done) -> @quay.close done afterEach (done) -> @etcdMajor.close done afterEach (done) -> @etcdMinor.close done afterEach (done) -> @server2.close done afterEach (done) -> @server1.close done afterEach (done) -> @governatorMinor.close done afterEach (done) -> @governatorMajor.close done afterEach (done) -> @meshbluServer.destroy done beforeEach -> {port} = @sut.address() @baseUrl = url.format protocol: 'http', hostname: 'localhost', port: port deployAuth = new Buffer('deploy-uuid:deploy-token').toString 'base64' guvAuth = new Buffer('guv-uuid:guv-token').toString 'base64' @meshbluHandler = @meshbluServer .post '/authenticate' .set 'Authorization', "Basic #{deployAuth}" .reply 200, uuid: 'governator-uuid' @majorHandler = @governatorMajor .get '/status' .set 'Authorization', "Basic #{guvAuth}" .reply 200, { 'governator:/foo/bar:quay.io/foo/bar:v1.0.0': key: 'governator:/foo/bar:quay.io/foo/bar:v1.0.0' deployAt: 2005059595 status: 'pending' 'governator:/baz/awefaw:quay.io/foo/bar:v1.0.0': key: 'governator:/baz/awefaw:quay.io/foo/bar:v1.0.0' deployAt: 2005059595 status: 'pending' } statusNode = node: key: PI:KEY:<KEY>END_PI' dir: true nodes: [ key: '/PI:KEY:<KEY>END_PI/status/travis' value: 'build successful: v1.0.0' ] majorVersionNode = node: key: '/foo/bar/docker_url' dir: true nodes: [ key: '/foo/bar/docker_url' value: 'quay.io/foo/bar:v0.9.9' ] minorVersionNode = node: key: '/foo/bar/docker_url' dir: true nodes: [ key: '/foo/bar/docker_url' value: 'quay.io/foo/bar:v1.0.0' ] vulcandNode = node: key: '/vulcand/backends/foo-bar/servers' dir: true nodes: [{ key: '/vulcand/backends/foo-bar/servers/octoblu-foo-bar-development-1' value: JSON.stringify { Id: "octoblu-foo-bar-development-1" URL: "http://127.0.0.1:#{@server1.address().port}" } }, { key: '/vulcand/backends/foo-bar/servers/octoblu-foo-bar-development-2' value: JSON.stringify { Id: "octoblu-foo-bar-development-2" URL: "http://127.0.0.1:#{@server2.address().port}" } }, { key: '/vulcand/backends/foo-bar/servers/octoblu-foo-bar-development-3' value: JSON.stringify { Id: "octoblu-foo-bar-development-3" URL: "http://0.0.0.0:0" } }] @etcdMajorStatusHandler = @etcdMajor .get '/v2/keys/foo/bar/status' .reply 200, statusNode @etcdMajorVulcandHandler = @etcdMajor .get '/v2/keys/vulcand/backends/foo-bar/servers' .reply 200, vulcandNode @etcdMajorDockerUrlHandler = @etcdMajor .get '/v2/keys/foo/bar/docker_url' .reply 200, majorVersionNode @etcdMinorDockerUrlHandler = @etcdMinor .get '/v2/keys/foo/bar/docker_url' .reply 200, minorVersionNode @quayHandler = @quay .get '/api/v1/repository/foo/bar/build/' .set 'Authorization', 'Bearer quay-token' .reply 200, builds: [{tags: ['v1.0.0'], phase: 'building', started: 'blah blah'}] @server1Handler = @server1 .get '/version' .reply 200, version: '2.2.0' @server2Handler = @server2 .get '/version' .reply 404, 'Not Found' beforeEach (done) -> options = uri: '/v2/status/foo/bar' baseUrl: @baseUrl auth: {username: 'deploy-uuid', password: 'PI:PASSWORD:<PASSWORD>END_PI'} request.get options, (error, @response, @body) => return done error if error? done() it 'should return a 200', -> expect(@response.statusCode).to.equal 200, JSON.stringify(@body) it 'should return a status', -> expectedResponse = majorVersion: 'quay.io/foo/bar:v0.9.9' minorVersion: 'quay.io/foo/bar:v1.0.0' status: travis: 'build successful: v1.0.0' deployments: "governator:/foo/bar:quay.io/foo/bar:v1.0.0": deployAt: 2005059595 key: "governator:/foo/bar:quay.io/foo/bar:v1.0.0" status: "pending" servers: [{ name: 'octoblu-foo-bar-development-1' url: "http://127.0.0.1:#{@server1.address().port}" version: 'v2.2.0' }, { name: 'octoblu-foo-bar-development-2' url: "http://127.0.0.1:#{@server2.address().port}" version: "(HTTP: 404)" }, { name: 'octoblu-foo-bar-development-3' url: "http://0.0.0.0:0" }] quay: tag: 'v1.0.0' phase: 'building' startedAt: 'blah blah' expect(JSON.parse @response.body).to.containSubset expectedResponse it 'should call the handlers', -> expect(@meshbluHandler.isDone).to.be.true expect(@etcdMajorStatusHandler.isDone).to.be.true expect(@etcdMajorVulcandHandler.isDone).to.be.true expect(@etcdMajorDockerUrlHandler.isDone).to.be.true expect(@etcdMinorDockerUrlHandler.isDone).to.be.true expect(@majorHandler.isDone).to.be.true expect(@quayHandler.isDone).to.be.true expect(@server1Handler.isDone).to.be.true expect(@server2Handler.isDone).to.be.true
[ { "context": "url', token.url)\n formData =\n key: token.path + '/' + file.name\n AWSAccesskeyId: toke", "end": 6374, "score": 0.6776461601257324, "start": 6364, "tag": "KEY", "value": "token.path" }, { "context": ".path + '/' + file.name\n AWSAccesskeyId: token.accessKey\n acl: \"public-read\"\n policy:", "end": 6432, "score": 0.6625712513923645, "start": 6420, "tag": "KEY", "value": "token.access" }, { "context": "h resizeDeferred.promise\n\n formData.key = token.path + \"/\" + f.name\n elem.fileupload('send', ", "end": 7162, "score": 0.6799871921539307, "start": 7152, "tag": "KEY", "value": "token.path" } ]
client/directives/fileUpload.coffee
aitutaki/gi-ui
0
angular.module('gi.ui').directive 'giFileupload' , [ '$q', 'giFileManager' , ($q, FileManager) -> restrict: 'E' templateUrl: 'gi.ui.fileUpload.html' scope: { files: '=' parent: '=' } link: (scope, elem, attrs) -> scope.addText = "Add an image" scope.pendingFiles = [] scope.uploadedFiles = [] scope.erroredFiles = [] #I would like to get rid of the form-upload ui altogether in the future #It's nearly there at the moment, just need to sort out the progress bar downloadTemplate = (o) -> return uploadTemplate = (o) -> scope.$apply () -> angular.forEach o.files, (file) -> if file.error fu = locale.fileupload file.errorMessage = fu.errors[file.error] or file.error scope.erroredFiles.push file return else unless file.order? file.order = 0 unless file.exclude file.exclude = true unless file.primary file.primary = true console.log file file.preview = previews[file.name] scope.pendingFiles.push file return scope.formatFileSize = (bytes) -> if not typeof(bytes) is 'number' 'N/A' else if bytes >= 1073741824 (bytes / 1073741824).toFixed(2) + ' GB' else if bytes >= 1048576 (bytes / 1048576).toFixed(2) + ' MB' else (bytes / 1024).toFixed(2) + ' KB' getResizedImage = (data, options) -> deferred = $q.defer() options.canvas = true img = data.canvas || data.img if img newImg = loadImage.scale img, options if not newImg? console.log 'there is no resized image to get' deferred.resolve() else that = @ file = data.files[data.index] name = file.name callback = (blob) -> if not blob.name? if file.type is blob.type blob.name = options.prefix + file.name else if file.name? blob.name = options.prefix + file.name.replace /\..+$/, '.' + blob.type.substr(6) deferred.resolve blob # Use canvas.mozGetAsFile directly, to retain the filename, as # Gecko doesn't support the filename option for FormData.append: if newImg.mozGetAsFile if /^image\/(jpeg|png)$/.test(file.type) param = options.prefix + name else if name param = options.prefix + name.replace(/\..+$/, '') + '.png' else param = options.prefix + 'blob.png' callback newImg.mozGetAsFile(param, file.type) else if newImg.toBlob newImg.toBlob callback, file.type else console.log 'THIS SHOULD NOT HAPPEN' deferred.resolve() deferred.promise extend = (object, properties) -> for key, val of properties object[key] = val object optionsObj = uploadTemplateId: null downloadTemplateId: null uploadTemplate: uploadTemplate downloadTemplate: downloadTemplate disableImagePreview: true autoUpload: false previewMaxWidth: 100 previewMaxHeight: 100 previewCrop: true dropZone: elem dataType: 'xml' elem.fileupload(optionsObj) resized = {} previews = {} elem.bind 'fileuploaddone', (e, data) -> scope.$apply () -> name = data.files[0].name if name.indexOf('thumb') is 0 console.log 'resolving: ' + name data.files[0].promise.resolve() else scope.removeFromQueue data.files[0] console.log data FileManager.save(data.files[0], scope.parent , data.formData).then (fileInfo) -> console.log 'resolving: ' + name data.files[0].promise.resolve() if data.files[0].error fu = locale.fileupload file.errorMessage = fu.errors[file.error] or file.error scope.erroredFiles.push file else scope.uploadedFiles.push fileInfo elem.bind 'fileuploadprocessdone', (e, data) -> scope.$apply () -> name = data.files[0].name data.files[0].s3alternates = [] resized[name] = [] getResizedImage(data, {maxWidth: 940, maxHeight: 530 , prefix: 'thumb/940/'}).then (blob) -> resized[name].push blob data.files[0].s3alternates.push 'thumb/940/' getResizedImage(data, {maxWidth: 940, maxHeight: 300 , prefix: 'thumb/300h/'}).then (blob) -> resized[name].push blob data.files[0].s3alternates.push 'thumb/300h/' getResizedImage(data, {maxWidth: 350, maxHeight: 200 , prefix: 'thumb/350/'}).then (blob) -> resized[name].push blob data.files[0].s3alternates.push 'thumb/350/' getResizedImage(data, {maxWidth: 150, maxHeight: 150 , prefix: 'thumb/'}).then (blob) -> resized[name].push blob data.files[0].s3alternates.push 'thumb/' previewImg = loadImage.scale data.img, {maxWidth: 80 , maxHeight: 80, canvas: true} previews[name] = previewImg scope.removeFromQueue = (file) -> resultIndex = -1 angular.forEach scope.pendingFiles, (f, index) -> if f.name is file.name resultIndex = index unless resultIndex is -1 scope.pendingFiles.splice resultIndex, 1 previews[file.name] = null resized[file.name] = null scope.removeFromS3 = (file, $event) -> $event.preventDefault() #stop this event submitting the parent form console.log 'remove from S3 called for:' + file.name FileManager.destroy(file._id).then () -> resultIndex = -1 angular.forEach scope.uploadedFiles, (f, index) -> if f._id is file._id resultIndex = index unless resultIndex is -1 scope.uploadedFiles.splice resultIndex, 1 uploadToS3 = (file) -> console.log 'in send test' console.log file deferred = $q.defer() FileManager.getUploadToken(file, scope.parent).then (token) -> elem.fileupload('option', 'url', token.url) formData = key: token.path + '/' + file.name AWSAccesskeyId: token.accessKey acl: "public-read" policy: token.policy signature: token.signature success_action_status: "201" "Content-Type": file.type primary: file.primary exclude: file.exclude order: file.order elem.fileupload('send', {formData: formData, files: [file]}) promises = [] promises.push file.promise mainFileDeferred = $q.defer() file.promise = mainFileDeferred promises.push mainFileDeferred.promise angular.forEach resized[file.name], (f) -> resizeDeferred = $q.defer() f.promise = resizeDeferred promises.push resizeDeferred.promise formData.key = token.path + "/" + f.name elem.fileupload('send', {files: [f], formData: formData}) resized[file.name] = null $q.all(promises).then () -> console.log 'all promises resolved for ' + file.name #When all the resized and the original file have been uploaded #then the done handler will have rexsolved all the promises deferred.resolve() deferred.promise scope.$watch 'parent', (newVal, oldVal) -> if newVal != oldVal FileManager.forParent(scope.parent).then (files) -> scope.uploadedFiles = [] resized = {} angular.forEach files, (file) -> scope.uploadedFiles.push file scope.$on 'start-file-upload', (e, parent, promise) -> promises = [] angular.forEach scope.pendingFiles, (file) -> promises.push uploadToS3(file) console.log 'waiting on ' + promises.length + ' files to be uploaded to S3' $q.all(promises).then () -> console.log 'all files uploaded to S3' promise.resolve() return ]
66897
angular.module('gi.ui').directive 'giFileupload' , [ '$q', 'giFileManager' , ($q, FileManager) -> restrict: 'E' templateUrl: 'gi.ui.fileUpload.html' scope: { files: '=' parent: '=' } link: (scope, elem, attrs) -> scope.addText = "Add an image" scope.pendingFiles = [] scope.uploadedFiles = [] scope.erroredFiles = [] #I would like to get rid of the form-upload ui altogether in the future #It's nearly there at the moment, just need to sort out the progress bar downloadTemplate = (o) -> return uploadTemplate = (o) -> scope.$apply () -> angular.forEach o.files, (file) -> if file.error fu = locale.fileupload file.errorMessage = fu.errors[file.error] or file.error scope.erroredFiles.push file return else unless file.order? file.order = 0 unless file.exclude file.exclude = true unless file.primary file.primary = true console.log file file.preview = previews[file.name] scope.pendingFiles.push file return scope.formatFileSize = (bytes) -> if not typeof(bytes) is 'number' 'N/A' else if bytes >= 1073741824 (bytes / 1073741824).toFixed(2) + ' GB' else if bytes >= 1048576 (bytes / 1048576).toFixed(2) + ' MB' else (bytes / 1024).toFixed(2) + ' KB' getResizedImage = (data, options) -> deferred = $q.defer() options.canvas = true img = data.canvas || data.img if img newImg = loadImage.scale img, options if not newImg? console.log 'there is no resized image to get' deferred.resolve() else that = @ file = data.files[data.index] name = file.name callback = (blob) -> if not blob.name? if file.type is blob.type blob.name = options.prefix + file.name else if file.name? blob.name = options.prefix + file.name.replace /\..+$/, '.' + blob.type.substr(6) deferred.resolve blob # Use canvas.mozGetAsFile directly, to retain the filename, as # Gecko doesn't support the filename option for FormData.append: if newImg.mozGetAsFile if /^image\/(jpeg|png)$/.test(file.type) param = options.prefix + name else if name param = options.prefix + name.replace(/\..+$/, '') + '.png' else param = options.prefix + 'blob.png' callback newImg.mozGetAsFile(param, file.type) else if newImg.toBlob newImg.toBlob callback, file.type else console.log 'THIS SHOULD NOT HAPPEN' deferred.resolve() deferred.promise extend = (object, properties) -> for key, val of properties object[key] = val object optionsObj = uploadTemplateId: null downloadTemplateId: null uploadTemplate: uploadTemplate downloadTemplate: downloadTemplate disableImagePreview: true autoUpload: false previewMaxWidth: 100 previewMaxHeight: 100 previewCrop: true dropZone: elem dataType: 'xml' elem.fileupload(optionsObj) resized = {} previews = {} elem.bind 'fileuploaddone', (e, data) -> scope.$apply () -> name = data.files[0].name if name.indexOf('thumb') is 0 console.log 'resolving: ' + name data.files[0].promise.resolve() else scope.removeFromQueue data.files[0] console.log data FileManager.save(data.files[0], scope.parent , data.formData).then (fileInfo) -> console.log 'resolving: ' + name data.files[0].promise.resolve() if data.files[0].error fu = locale.fileupload file.errorMessage = fu.errors[file.error] or file.error scope.erroredFiles.push file else scope.uploadedFiles.push fileInfo elem.bind 'fileuploadprocessdone', (e, data) -> scope.$apply () -> name = data.files[0].name data.files[0].s3alternates = [] resized[name] = [] getResizedImage(data, {maxWidth: 940, maxHeight: 530 , prefix: 'thumb/940/'}).then (blob) -> resized[name].push blob data.files[0].s3alternates.push 'thumb/940/' getResizedImage(data, {maxWidth: 940, maxHeight: 300 , prefix: 'thumb/300h/'}).then (blob) -> resized[name].push blob data.files[0].s3alternates.push 'thumb/300h/' getResizedImage(data, {maxWidth: 350, maxHeight: 200 , prefix: 'thumb/350/'}).then (blob) -> resized[name].push blob data.files[0].s3alternates.push 'thumb/350/' getResizedImage(data, {maxWidth: 150, maxHeight: 150 , prefix: 'thumb/'}).then (blob) -> resized[name].push blob data.files[0].s3alternates.push 'thumb/' previewImg = loadImage.scale data.img, {maxWidth: 80 , maxHeight: 80, canvas: true} previews[name] = previewImg scope.removeFromQueue = (file) -> resultIndex = -1 angular.forEach scope.pendingFiles, (f, index) -> if f.name is file.name resultIndex = index unless resultIndex is -1 scope.pendingFiles.splice resultIndex, 1 previews[file.name] = null resized[file.name] = null scope.removeFromS3 = (file, $event) -> $event.preventDefault() #stop this event submitting the parent form console.log 'remove from S3 called for:' + file.name FileManager.destroy(file._id).then () -> resultIndex = -1 angular.forEach scope.uploadedFiles, (f, index) -> if f._id is file._id resultIndex = index unless resultIndex is -1 scope.uploadedFiles.splice resultIndex, 1 uploadToS3 = (file) -> console.log 'in send test' console.log file deferred = $q.defer() FileManager.getUploadToken(file, scope.parent).then (token) -> elem.fileupload('option', 'url', token.url) formData = key: <KEY> + '/' + file.name AWSAccesskeyId: <KEY>Key acl: "public-read" policy: token.policy signature: token.signature success_action_status: "201" "Content-Type": file.type primary: file.primary exclude: file.exclude order: file.order elem.fileupload('send', {formData: formData, files: [file]}) promises = [] promises.push file.promise mainFileDeferred = $q.defer() file.promise = mainFileDeferred promises.push mainFileDeferred.promise angular.forEach resized[file.name], (f) -> resizeDeferred = $q.defer() f.promise = resizeDeferred promises.push resizeDeferred.promise formData.key = <KEY> + "/" + f.name elem.fileupload('send', {files: [f], formData: formData}) resized[file.name] = null $q.all(promises).then () -> console.log 'all promises resolved for ' + file.name #When all the resized and the original file have been uploaded #then the done handler will have rexsolved all the promises deferred.resolve() deferred.promise scope.$watch 'parent', (newVal, oldVal) -> if newVal != oldVal FileManager.forParent(scope.parent).then (files) -> scope.uploadedFiles = [] resized = {} angular.forEach files, (file) -> scope.uploadedFiles.push file scope.$on 'start-file-upload', (e, parent, promise) -> promises = [] angular.forEach scope.pendingFiles, (file) -> promises.push uploadToS3(file) console.log 'waiting on ' + promises.length + ' files to be uploaded to S3' $q.all(promises).then () -> console.log 'all files uploaded to S3' promise.resolve() return ]
true
angular.module('gi.ui').directive 'giFileupload' , [ '$q', 'giFileManager' , ($q, FileManager) -> restrict: 'E' templateUrl: 'gi.ui.fileUpload.html' scope: { files: '=' parent: '=' } link: (scope, elem, attrs) -> scope.addText = "Add an image" scope.pendingFiles = [] scope.uploadedFiles = [] scope.erroredFiles = [] #I would like to get rid of the form-upload ui altogether in the future #It's nearly there at the moment, just need to sort out the progress bar downloadTemplate = (o) -> return uploadTemplate = (o) -> scope.$apply () -> angular.forEach o.files, (file) -> if file.error fu = locale.fileupload file.errorMessage = fu.errors[file.error] or file.error scope.erroredFiles.push file return else unless file.order? file.order = 0 unless file.exclude file.exclude = true unless file.primary file.primary = true console.log file file.preview = previews[file.name] scope.pendingFiles.push file return scope.formatFileSize = (bytes) -> if not typeof(bytes) is 'number' 'N/A' else if bytes >= 1073741824 (bytes / 1073741824).toFixed(2) + ' GB' else if bytes >= 1048576 (bytes / 1048576).toFixed(2) + ' MB' else (bytes / 1024).toFixed(2) + ' KB' getResizedImage = (data, options) -> deferred = $q.defer() options.canvas = true img = data.canvas || data.img if img newImg = loadImage.scale img, options if not newImg? console.log 'there is no resized image to get' deferred.resolve() else that = @ file = data.files[data.index] name = file.name callback = (blob) -> if not blob.name? if file.type is blob.type blob.name = options.prefix + file.name else if file.name? blob.name = options.prefix + file.name.replace /\..+$/, '.' + blob.type.substr(6) deferred.resolve blob # Use canvas.mozGetAsFile directly, to retain the filename, as # Gecko doesn't support the filename option for FormData.append: if newImg.mozGetAsFile if /^image\/(jpeg|png)$/.test(file.type) param = options.prefix + name else if name param = options.prefix + name.replace(/\..+$/, '') + '.png' else param = options.prefix + 'blob.png' callback newImg.mozGetAsFile(param, file.type) else if newImg.toBlob newImg.toBlob callback, file.type else console.log 'THIS SHOULD NOT HAPPEN' deferred.resolve() deferred.promise extend = (object, properties) -> for key, val of properties object[key] = val object optionsObj = uploadTemplateId: null downloadTemplateId: null uploadTemplate: uploadTemplate downloadTemplate: downloadTemplate disableImagePreview: true autoUpload: false previewMaxWidth: 100 previewMaxHeight: 100 previewCrop: true dropZone: elem dataType: 'xml' elem.fileupload(optionsObj) resized = {} previews = {} elem.bind 'fileuploaddone', (e, data) -> scope.$apply () -> name = data.files[0].name if name.indexOf('thumb') is 0 console.log 'resolving: ' + name data.files[0].promise.resolve() else scope.removeFromQueue data.files[0] console.log data FileManager.save(data.files[0], scope.parent , data.formData).then (fileInfo) -> console.log 'resolving: ' + name data.files[0].promise.resolve() if data.files[0].error fu = locale.fileupload file.errorMessage = fu.errors[file.error] or file.error scope.erroredFiles.push file else scope.uploadedFiles.push fileInfo elem.bind 'fileuploadprocessdone', (e, data) -> scope.$apply () -> name = data.files[0].name data.files[0].s3alternates = [] resized[name] = [] getResizedImage(data, {maxWidth: 940, maxHeight: 530 , prefix: 'thumb/940/'}).then (blob) -> resized[name].push blob data.files[0].s3alternates.push 'thumb/940/' getResizedImage(data, {maxWidth: 940, maxHeight: 300 , prefix: 'thumb/300h/'}).then (blob) -> resized[name].push blob data.files[0].s3alternates.push 'thumb/300h/' getResizedImage(data, {maxWidth: 350, maxHeight: 200 , prefix: 'thumb/350/'}).then (blob) -> resized[name].push blob data.files[0].s3alternates.push 'thumb/350/' getResizedImage(data, {maxWidth: 150, maxHeight: 150 , prefix: 'thumb/'}).then (blob) -> resized[name].push blob data.files[0].s3alternates.push 'thumb/' previewImg = loadImage.scale data.img, {maxWidth: 80 , maxHeight: 80, canvas: true} previews[name] = previewImg scope.removeFromQueue = (file) -> resultIndex = -1 angular.forEach scope.pendingFiles, (f, index) -> if f.name is file.name resultIndex = index unless resultIndex is -1 scope.pendingFiles.splice resultIndex, 1 previews[file.name] = null resized[file.name] = null scope.removeFromS3 = (file, $event) -> $event.preventDefault() #stop this event submitting the parent form console.log 'remove from S3 called for:' + file.name FileManager.destroy(file._id).then () -> resultIndex = -1 angular.forEach scope.uploadedFiles, (f, index) -> if f._id is file._id resultIndex = index unless resultIndex is -1 scope.uploadedFiles.splice resultIndex, 1 uploadToS3 = (file) -> console.log 'in send test' console.log file deferred = $q.defer() FileManager.getUploadToken(file, scope.parent).then (token) -> elem.fileupload('option', 'url', token.url) formData = key: PI:KEY:<KEY>END_PI + '/' + file.name AWSAccesskeyId: PI:KEY:<KEY>END_PIKey acl: "public-read" policy: token.policy signature: token.signature success_action_status: "201" "Content-Type": file.type primary: file.primary exclude: file.exclude order: file.order elem.fileupload('send', {formData: formData, files: [file]}) promises = [] promises.push file.promise mainFileDeferred = $q.defer() file.promise = mainFileDeferred promises.push mainFileDeferred.promise angular.forEach resized[file.name], (f) -> resizeDeferred = $q.defer() f.promise = resizeDeferred promises.push resizeDeferred.promise formData.key = PI:KEY:<KEY>END_PI + "/" + f.name elem.fileupload('send', {files: [f], formData: formData}) resized[file.name] = null $q.all(promises).then () -> console.log 'all promises resolved for ' + file.name #When all the resized and the original file have been uploaded #then the done handler will have rexsolved all the promises deferred.resolve() deferred.promise scope.$watch 'parent', (newVal, oldVal) -> if newVal != oldVal FileManager.forParent(scope.parent).then (files) -> scope.uploadedFiles = [] resized = {} angular.forEach files, (file) -> scope.uploadedFiles.push file scope.$on 'start-file-upload', (e, parent, promise) -> promises = [] angular.forEach scope.pendingFiles, (file) -> promises.push uploadToS3(file) console.log 'waiting on ' + promises.length + ' files to be uploaded to S3' $q.all(promises).then () -> console.log 'all files uploaded to S3' promise.resolve() return ]
[ { "context": " a←13 8 122 4 ⋄ a[⍋a] ←→ 4 8 13 122\n # ⍋\"ZAMBIA\" ←→ 1 5 3 4 2 0\n # s←\"ZAMBIA\"", "end": 118, "score": 0.5822644829750061, "start": 112, "tag": "NAME", "value": "ZAMBIA" }, { "context": "3 4\n # ... 0 1 0)\n #\n # a←3 2 5⍴\"joe doe bob jonesbob zwart\" ⋄ a[⍋a;;]\n # ... ←", "end": 669, "score": 0.9790499210357666, "start": 666, "tag": "NAME", "value": "joe" }, { "context": "\n # ... 0 1 0)\n #\n # a←3 2 5⍴\"joe doe bob jonesbob zwart\" ⋄ a[⍋a;;]\n # ... ←→ 3 2", "end": 674, "score": 0.9783173203468323, "start": 671, "tag": "NAME", "value": "doe" }, { "context": "... 0 1 0)\n #\n # a←3 2 5⍴\"joe doe bob jonesbob zwart\" ⋄ a[⍋a;;]\n # ... ←→ 3 2 5 ⍴ ", "end": 679, "score": 0.8862742185592651, "start": 676, "tag": "NAME", "value": "bob" }, { "context": " 0 1 0)\n #\n # a←3 2 5⍴\"joe doe bob jonesbob zwart\" ⋄ a[⍋a;;]\n # ... ←→ 3 2 5 ⍴ 'bob jone", "end": 689, "score": 0.9502465724945068, "start": 681, "tag": "USERNAME", "value": "jonesbob" }, { "context": "0 1 0)\n #\n # a←3 2 5⍴\"joe doe bob jonesbob zwart\" ⋄ a[⍋a;;]\n # ... ←→ 3 2 5 ⍴ 'bob jonesbo", "end": 692, "score": 0.5239200592041016, "start": 691, "tag": "USERNAME", "value": "z" }, { "context": " 1 0)\n #\n # a←3 2 5⍴\"joe doe bob jonesbob zwart\" ⋄ a[⍋a;;]\n # ... ←→ 3 2 5 ⍴ 'bob jonesbob z", "end": 696, "score": 0.8014050722122192, "start": 692, "tag": "NAME", "value": "wart" }, { "context": " jonesbob zwart\" ⋄ a[⍋a;;]\n # ... ←→ 3 2 5 ⍴ 'bob jonesbob zwartjoe doe '\n #\n # \"ZYXWVUTSRQPO", "end": 733, "score": 0.7476232051849365, "start": 730, "tag": "NAME", "value": "bob" }, { "context": "esbob zwart\" ⋄ a[⍋a;;]\n # ... ←→ 3 2 5 ⍴ 'bob jonesbob zwartjoe doe '\n #\n # \"ZYXWVUTSRQPONMLKJIHGFE", "end": 743, "score": 0.9041040539741516, "start": 735, "tag": "USERNAME", "value": "jonesbob" }, { "context": "rt\" ⋄ a[⍋a;;]\n # ... ←→ 3 2 5 ⍴ 'bob jonesbob zwartjoe doe '\n #\n # \"ZYXWVUTSRQPONMLKJIHGFEDCBA\"⍋\"", "end": 750, "score": 0.7400772571563721, "start": 745, "tag": "NAME", "value": "zwart" }, { "context": " a[⍋a;;]\n # ... ←→ 3 2 5 ⍴ 'bob jonesbob zwartjoe doe '\n #\n # \"ZYXWVUTSRQPONMLKJIHGFEDCBA\"⍋\"ZA", "end": 752, "score": 0.640895664691925, "start": 750, "tag": "USERNAME", "value": "jo" }, { "context": "a[⍋a;;]\n # ... ←→ 3 2 5 ⍴ 'bob jonesbob zwartjoe doe '\n #\n # \"ZYXWVUTSRQPONMLKJIHGFEDCBA\"⍋\"ZAM", "end": 753, "score": 0.8382318615913391, "start": 752, "tag": "NAME", "value": "e" }, { "context": "⍋a;;]\n # ... ←→ 3 2 5 ⍴ 'bob jonesbob zwartjoe doe '\n #\n # \"ZYXWVUTSRQPONMLKJIHGFEDCBA\"⍋\"ZAMBIA\" ", "end": 758, "score": 0.9489881992340088, "start": 755, "tag": "NAME", "value": "doe" } ]
src/vocabulary/grade.coffee
brunogal/apl
0
addVocabulary # ⍋13 8 122 4 ←→ 3 1 0 2 # a←13 8 122 4 ⋄ a[⍋a] ←→ 4 8 13 122 # ⍋"ZAMBIA" ←→ 1 5 3 4 2 0 # s←"ZAMBIA" ⋄ s[⍋s] ←→ 'AABIMZ' # t←3 3⍴"BOBALFZAK" ⋄ ⍋t ←→ 1 0 2 # t←3 3⍴4 5 6 1 1 3 1 1 2 ⋄ ⍋t ←→ 2 1 0 # # t←3 3⍴4 5 6 1 1 3 1 1 2 ⋄ t[⍋t;] # ... ←→ (3 3⍴ 1 1 2 # ... 1 1 3 # ... 4 5 6) # # a←3 2 3⍴2 3 4 0 1 0 1 1 3 4 5 6 1 1 2 10 11 12 ⋄ a[⍋a;;] # ... ←→ (3 2 3⍴ 1 1 2 # ... 10 11 12 # ... # ... 1 1 3 # ... 4 5 6 # ... # ... 2 3 4 # ... 0 1 0) # # a←3 2 5⍴"joe doe bob jonesbob zwart" ⋄ a[⍋a;;] # ... ←→ 3 2 5 ⍴ 'bob jonesbob zwartjoe doe ' # # "ZYXWVUTSRQPONMLKJIHGFEDCBA"⍋"ZAMBIA" ←→ 0 2 4 3 1 5 # ⎕A←"ABCDEFGHIJKLMNOPQRSTUVWXYZ" ⋄ (⌽⎕A)⍋3 3⍴"BOBALFZAK" ←→ 2 0 1 # # data←6 4⍴"ABLEaBLEACREABELaBELACES" # ... coll←2 26⍴"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" # ... data[coll⍋data;] # ... ←→ 6 4⍴'ABELaBELABLEaBLEACESACRE' # # data←6 4⍴"ABLEaBLEACREABELaBELACES" # ... coll1←"AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz" # ... data[coll1⍋data;] # ... ←→ 6 4⍴'ABELABLEACESACREaBELaBLE' # # ⍋0 1 2 3 4 3 6 6 4 9 1 11 12 13 14 15 ←→ 0 1 10 2 3 5 4 8 6 7 9 11 12 13 14 15 '⍋': (⍵, ⍺) -> grade ⍵, ⍺, 1 # ⍒3 1 8 ←→ 2 0 1 '⍒': (⍵, ⍺) -> grade ⍵, ⍺, -1 # Helper for `⍋` and `⍒` grade = (⍵, ⍺, direction) -> h = {} # maps a character to its index in the collation if ⍺ if !⍴⍴ ⍺ then rankError() h = {} each ⍺, (x, indices) -> if typeof x isnt 'string' then domainError() h[x] = indices[indices.length - 1] if !⍴⍴ ⍵ then rankError() new A [0...⍴(⍵)[0]] .sort (i, j) -> p = ⍵.offset indices = repeat [0], ⍴⍴ ⍵ loop x = ⍵.data[p + i * ⍵.stride[0]] y = ⍵.data[p + j * ⍵.stride[0]] tx = typeof x ty = typeof y if tx < ty then return -direction if tx > ty then return direction if h[x]? then x = h[x] if h[y]? then y = h[y] if x < y then return -direction if x > y then return direction a = indices.length - 1 while a > 0 and indices[a] + 1 is ⍴(⍵)[a] p -= ⍵.stride[a] * indices[a] indices[a--] = 0 if a <= 0 then break p += ⍵.stride[a] indices[a]++ (i > j) - (i < j)
124003
addVocabulary # ⍋13 8 122 4 ←→ 3 1 0 2 # a←13 8 122 4 ⋄ a[⍋a] ←→ 4 8 13 122 # ⍋"<NAME>" ←→ 1 5 3 4 2 0 # s←"ZAMBIA" ⋄ s[⍋s] ←→ 'AABIMZ' # t←3 3⍴"BOBALFZAK" ⋄ ⍋t ←→ 1 0 2 # t←3 3⍴4 5 6 1 1 3 1 1 2 ⋄ ⍋t ←→ 2 1 0 # # t←3 3⍴4 5 6 1 1 3 1 1 2 ⋄ t[⍋t;] # ... ←→ (3 3⍴ 1 1 2 # ... 1 1 3 # ... 4 5 6) # # a←3 2 3⍴2 3 4 0 1 0 1 1 3 4 5 6 1 1 2 10 11 12 ⋄ a[⍋a;;] # ... ←→ (3 2 3⍴ 1 1 2 # ... 10 11 12 # ... # ... 1 1 3 # ... 4 5 6 # ... # ... 2 3 4 # ... 0 1 0) # # a←3 2 5⍴"<NAME> <NAME> <NAME> jonesbob z<NAME>" ⋄ a[⍋a;;] # ... ←→ 3 2 5 ⍴ '<NAME> jonesbob <NAME>jo<NAME> <NAME> ' # # "ZYXWVUTSRQPONMLKJIHGFEDCBA"⍋"ZAMBIA" ←→ 0 2 4 3 1 5 # ⎕A←"ABCDEFGHIJKLMNOPQRSTUVWXYZ" ⋄ (⌽⎕A)⍋3 3⍴"BOBALFZAK" ←→ 2 0 1 # # data←6 4⍴"ABLEaBLEACREABELaBELACES" # ... coll←2 26⍴"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" # ... data[coll⍋data;] # ... ←→ 6 4⍴'ABELaBELABLEaBLEACESACRE' # # data←6 4⍴"ABLEaBLEACREABELaBELACES" # ... coll1←"AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz" # ... data[coll1⍋data;] # ... ←→ 6 4⍴'ABELABLEACESACREaBELaBLE' # # ⍋0 1 2 3 4 3 6 6 4 9 1 11 12 13 14 15 ←→ 0 1 10 2 3 5 4 8 6 7 9 11 12 13 14 15 '⍋': (⍵, ⍺) -> grade ⍵, ⍺, 1 # ⍒3 1 8 ←→ 2 0 1 '⍒': (⍵, ⍺) -> grade ⍵, ⍺, -1 # Helper for `⍋` and `⍒` grade = (⍵, ⍺, direction) -> h = {} # maps a character to its index in the collation if ⍺ if !⍴⍴ ⍺ then rankError() h = {} each ⍺, (x, indices) -> if typeof x isnt 'string' then domainError() h[x] = indices[indices.length - 1] if !⍴⍴ ⍵ then rankError() new A [0...⍴(⍵)[0]] .sort (i, j) -> p = ⍵.offset indices = repeat [0], ⍴⍴ ⍵ loop x = ⍵.data[p + i * ⍵.stride[0]] y = ⍵.data[p + j * ⍵.stride[0]] tx = typeof x ty = typeof y if tx < ty then return -direction if tx > ty then return direction if h[x]? then x = h[x] if h[y]? then y = h[y] if x < y then return -direction if x > y then return direction a = indices.length - 1 while a > 0 and indices[a] + 1 is ⍴(⍵)[a] p -= ⍵.stride[a] * indices[a] indices[a--] = 0 if a <= 0 then break p += ⍵.stride[a] indices[a]++ (i > j) - (i < j)
true
addVocabulary # ⍋13 8 122 4 ←→ 3 1 0 2 # a←13 8 122 4 ⋄ a[⍋a] ←→ 4 8 13 122 # ⍋"PI:NAME:<NAME>END_PI" ←→ 1 5 3 4 2 0 # s←"ZAMBIA" ⋄ s[⍋s] ←→ 'AABIMZ' # t←3 3⍴"BOBALFZAK" ⋄ ⍋t ←→ 1 0 2 # t←3 3⍴4 5 6 1 1 3 1 1 2 ⋄ ⍋t ←→ 2 1 0 # # t←3 3⍴4 5 6 1 1 3 1 1 2 ⋄ t[⍋t;] # ... ←→ (3 3⍴ 1 1 2 # ... 1 1 3 # ... 4 5 6) # # a←3 2 3⍴2 3 4 0 1 0 1 1 3 4 5 6 1 1 2 10 11 12 ⋄ a[⍋a;;] # ... ←→ (3 2 3⍴ 1 1 2 # ... 10 11 12 # ... # ... 1 1 3 # ... 4 5 6 # ... # ... 2 3 4 # ... 0 1 0) # # a←3 2 5⍴"PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI jonesbob zPI:NAME:<NAME>END_PI" ⋄ a[⍋a;;] # ... ←→ 3 2 5 ⍴ 'PI:NAME:<NAME>END_PI jonesbob PI:NAME:<NAME>END_PIjoPI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI ' # # "ZYXWVUTSRQPONMLKJIHGFEDCBA"⍋"ZAMBIA" ←→ 0 2 4 3 1 5 # ⎕A←"ABCDEFGHIJKLMNOPQRSTUVWXYZ" ⋄ (⌽⎕A)⍋3 3⍴"BOBALFZAK" ←→ 2 0 1 # # data←6 4⍴"ABLEaBLEACREABELaBELACES" # ... coll←2 26⍴"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" # ... data[coll⍋data;] # ... ←→ 6 4⍴'ABELaBELABLEaBLEACESACRE' # # data←6 4⍴"ABLEaBLEACREABELaBELACES" # ... coll1←"AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz" # ... data[coll1⍋data;] # ... ←→ 6 4⍴'ABELABLEACESACREaBELaBLE' # # ⍋0 1 2 3 4 3 6 6 4 9 1 11 12 13 14 15 ←→ 0 1 10 2 3 5 4 8 6 7 9 11 12 13 14 15 '⍋': (⍵, ⍺) -> grade ⍵, ⍺, 1 # ⍒3 1 8 ←→ 2 0 1 '⍒': (⍵, ⍺) -> grade ⍵, ⍺, -1 # Helper for `⍋` and `⍒` grade = (⍵, ⍺, direction) -> h = {} # maps a character to its index in the collation if ⍺ if !⍴⍴ ⍺ then rankError() h = {} each ⍺, (x, indices) -> if typeof x isnt 'string' then domainError() h[x] = indices[indices.length - 1] if !⍴⍴ ⍵ then rankError() new A [0...⍴(⍵)[0]] .sort (i, j) -> p = ⍵.offset indices = repeat [0], ⍴⍴ ⍵ loop x = ⍵.data[p + i * ⍵.stride[0]] y = ⍵.data[p + j * ⍵.stride[0]] tx = typeof x ty = typeof y if tx < ty then return -direction if tx > ty then return direction if h[x]? then x = h[x] if h[y]? then y = h[y] if x < y then return -direction if x > y then return direction a = indices.length - 1 while a > 0 and indices[a] + 1 is ⍴(⍵)[a] p -= ⍵.stride[a] * indices[a] indices[a--] = 0 if a <= 0 then break p += ⍵.stride[a] indices[a]++ (i > j) - (i < j)
[ { "context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>\nAll rights reserved.\n\nRedistri", "end": 42, "score": 0.999851405620575, "start": 24, "tag": "NAME", "value": "Alexander Cherniuk" }, { "context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>\nAll rights reserved.\n\nRedistribution and use in ", "end": 60, "score": 0.9999293684959412, "start": 44, "tag": "EMAIL", "value": "ts33kr@gmail.com" } ]
library/membrane/endpoint.coffee
ts33kr/granite
6
### Copyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### _ = require "lodash" logger = require "winston" crossroads = require "crossroads" uuid = require "node-uuid" assert = require "assert" colors = require "colors" crypto = require "crypto" nconf = require "nconf" async = require "async" https = require "https" http = require "http" util = require "util" url = require "url" {EOL} = require "os" {format} = require "util" {STATUS_CODES} = require "http" {Barebones} = require "./skeleton" {remote, external} = require "./remote" # This is an internal component that is a part of the new API engine # implementation. It holds a supplementary toolkit that is intended # for defining pieces that go along with the API endpoint definition. # These pieces are documentation of arbitrary kind, as well as param # declarations and their respective rules, et cetera. Please refer to # the implementation of this toolkit as well as to the implementation # of its direct implementation `ApiService` for more information bits. module.exports.EndpointToolkit = class EndpointToolkit extends Barebones # This is a marker that indicates to some internal subsystems # that this class has to be considered abstract and therefore # can not be treated as a complete class implementation. This # mainly is used to exclude or account for abstract classes. # Once inherited from, the inheritee is not abstract anymore. @abstract yes # Class directive that sets the specified documentations in # the documentation sequence that will be used & emptied when # a API method is defined below. That is, this method operates # in a sequential mode. The documentation data is supplied to # this method as an object argument with arbitrary key/value # pairs, where keys are doc name and value is the doc itself. # Multiple docs with the same key name may exist just fine. this.defineDocument = this.docs = (xsignature) -> assert {ApiService} = try require "./api" noSignature = "please, supply a plain object" noDocuments = "cannot find the documents seq" internal = "an anomaly found in doc sequence" malfuncs = "derived from the incorrect source" message = "Setting an API documentation in %s" @documents ?= new Array() # document sequence assert previous = this.documents or new Array assert _.all(previous, _.isObject), internal return previous unless arguments.length > 0 signature = _.find arguments, _.isPlainObject assert _.isPlainObject(signature), noSignature assert _.isArray(this.documents), noDocuments assert (try @derives(ApiService)), malfuncs assert identify = this.identify().underline logger.silly message.yellow, identify.bold fn = (arbitraryVector) -> return signature fn @documents = previous.concat signature # Class directive that sets the specified Crossroads rule in # a Crossroads rules sequence that will be used & emptied when # a API method is defined below. That is, this method operates # in a sequential mode. The Crossroads rule gets supplied to # this method as an object argument with arbitrary key/value # pairs, where keys are rule name and value is a rule itself. # Rules are attached to the route defined right after rules. this.crossroadsRule = this.rule = (xsignature) -> assert {ApiService} = try require "./api" noSignature = "please, supply a plain object" noCrossRules = "cannot find a cross-rules seq" internal = "an anomaly found in rule sequence" malfuncs = "derived from the incorrect source" message = "Setting the Crossroads rule in %s" @crossRules ?= new Array() # cross-rules seqs assert previous = this.crossRules or Array() assert _.all(previous, _.isObject), internal return previous unless arguments.length > 0 signature = _.find arguments, _.isPlainObject assert _.isPlainObject(signature), noSignature assert _.isArray(this.crossRules), noCrossRules assert (try @derives(ApiService)), malfuncs assert identify = this.identify().underline logger.silly message.yellow, identify.bold fn = (arbitraryVector) -> return signature fn @crossRules = previous.concat signature # Class directive that sets the specified parameter summary in # the parameters/arg sequence that will be used & emptied when # a API method is defined below. That is, this method operates # in a sequential mode. The parameter summary gets supplied to # this method as an object argument with arbitrary key/value # pairs, where keys are arg names and values are the synopsis. # Params are attached to the route defined right after docs. this.defineParameter = this.argv = (xsignature) -> assert {ApiService} = try require "./api" noSignature = "please, supply a plain object" noParamStore = "cannot find a param-store seq" internal = "an anomaly found in argv sequence" malfuncs = "derived from the incorrect source" message = "Setting the parameter value in %s" @paramStore ?= new Array() # cross-rules seqs assert previous = this.paramStore or Array() assert _.all(previous, _.isObject), internal return previous unless arguments.length > 0 signature = _.find arguments, _.isPlainObject assert _.isPlainObject(signature), noSignature assert _.isArray(this.paramStore), noParamStore assert (try @derives(ApiService)), malfuncs assert identify = this.identify().underline logger.silly message.yellow, identify.bold fn = (arbitraryVector) -> return signature fn @paramStore = previous.concat signature
172922
### Copyright (c) 2013, <NAME> <<EMAIL>> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### _ = require "lodash" logger = require "winston" crossroads = require "crossroads" uuid = require "node-uuid" assert = require "assert" colors = require "colors" crypto = require "crypto" nconf = require "nconf" async = require "async" https = require "https" http = require "http" util = require "util" url = require "url" {EOL} = require "os" {format} = require "util" {STATUS_CODES} = require "http" {Barebones} = require "./skeleton" {remote, external} = require "./remote" # This is an internal component that is a part of the new API engine # implementation. It holds a supplementary toolkit that is intended # for defining pieces that go along with the API endpoint definition. # These pieces are documentation of arbitrary kind, as well as param # declarations and their respective rules, et cetera. Please refer to # the implementation of this toolkit as well as to the implementation # of its direct implementation `ApiService` for more information bits. module.exports.EndpointToolkit = class EndpointToolkit extends Barebones # This is a marker that indicates to some internal subsystems # that this class has to be considered abstract and therefore # can not be treated as a complete class implementation. This # mainly is used to exclude or account for abstract classes. # Once inherited from, the inheritee is not abstract anymore. @abstract yes # Class directive that sets the specified documentations in # the documentation sequence that will be used & emptied when # a API method is defined below. That is, this method operates # in a sequential mode. The documentation data is supplied to # this method as an object argument with arbitrary key/value # pairs, where keys are doc name and value is the doc itself. # Multiple docs with the same key name may exist just fine. this.defineDocument = this.docs = (xsignature) -> assert {ApiService} = try require "./api" noSignature = "please, supply a plain object" noDocuments = "cannot find the documents seq" internal = "an anomaly found in doc sequence" malfuncs = "derived from the incorrect source" message = "Setting an API documentation in %s" @documents ?= new Array() # document sequence assert previous = this.documents or new Array assert _.all(previous, _.isObject), internal return previous unless arguments.length > 0 signature = _.find arguments, _.isPlainObject assert _.isPlainObject(signature), noSignature assert _.isArray(this.documents), noDocuments assert (try @derives(ApiService)), malfuncs assert identify = this.identify().underline logger.silly message.yellow, identify.bold fn = (arbitraryVector) -> return signature fn @documents = previous.concat signature # Class directive that sets the specified Crossroads rule in # a Crossroads rules sequence that will be used & emptied when # a API method is defined below. That is, this method operates # in a sequential mode. The Crossroads rule gets supplied to # this method as an object argument with arbitrary key/value # pairs, where keys are rule name and value is a rule itself. # Rules are attached to the route defined right after rules. this.crossroadsRule = this.rule = (xsignature) -> assert {ApiService} = try require "./api" noSignature = "please, supply a plain object" noCrossRules = "cannot find a cross-rules seq" internal = "an anomaly found in rule sequence" malfuncs = "derived from the incorrect source" message = "Setting the Crossroads rule in %s" @crossRules ?= new Array() # cross-rules seqs assert previous = this.crossRules or Array() assert _.all(previous, _.isObject), internal return previous unless arguments.length > 0 signature = _.find arguments, _.isPlainObject assert _.isPlainObject(signature), noSignature assert _.isArray(this.crossRules), noCrossRules assert (try @derives(ApiService)), malfuncs assert identify = this.identify().underline logger.silly message.yellow, identify.bold fn = (arbitraryVector) -> return signature fn @crossRules = previous.concat signature # Class directive that sets the specified parameter summary in # the parameters/arg sequence that will be used & emptied when # a API method is defined below. That is, this method operates # in a sequential mode. The parameter summary gets supplied to # this method as an object argument with arbitrary key/value # pairs, where keys are arg names and values are the synopsis. # Params are attached to the route defined right after docs. this.defineParameter = this.argv = (xsignature) -> assert {ApiService} = try require "./api" noSignature = "please, supply a plain object" noParamStore = "cannot find a param-store seq" internal = "an anomaly found in argv sequence" malfuncs = "derived from the incorrect source" message = "Setting the parameter value in %s" @paramStore ?= new Array() # cross-rules seqs assert previous = this.paramStore or Array() assert _.all(previous, _.isObject), internal return previous unless arguments.length > 0 signature = _.find arguments, _.isPlainObject assert _.isPlainObject(signature), noSignature assert _.isArray(this.paramStore), noParamStore assert (try @derives(ApiService)), malfuncs assert identify = this.identify().underline logger.silly message.yellow, identify.bold fn = (arbitraryVector) -> return signature fn @paramStore = previous.concat signature
true
### Copyright (c) 2013, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### _ = require "lodash" logger = require "winston" crossroads = require "crossroads" uuid = require "node-uuid" assert = require "assert" colors = require "colors" crypto = require "crypto" nconf = require "nconf" async = require "async" https = require "https" http = require "http" util = require "util" url = require "url" {EOL} = require "os" {format} = require "util" {STATUS_CODES} = require "http" {Barebones} = require "./skeleton" {remote, external} = require "./remote" # This is an internal component that is a part of the new API engine # implementation. It holds a supplementary toolkit that is intended # for defining pieces that go along with the API endpoint definition. # These pieces are documentation of arbitrary kind, as well as param # declarations and their respective rules, et cetera. Please refer to # the implementation of this toolkit as well as to the implementation # of its direct implementation `ApiService` for more information bits. module.exports.EndpointToolkit = class EndpointToolkit extends Barebones # This is a marker that indicates to some internal subsystems # that this class has to be considered abstract and therefore # can not be treated as a complete class implementation. This # mainly is used to exclude or account for abstract classes. # Once inherited from, the inheritee is not abstract anymore. @abstract yes # Class directive that sets the specified documentations in # the documentation sequence that will be used & emptied when # a API method is defined below. That is, this method operates # in a sequential mode. The documentation data is supplied to # this method as an object argument with arbitrary key/value # pairs, where keys are doc name and value is the doc itself. # Multiple docs with the same key name may exist just fine. this.defineDocument = this.docs = (xsignature) -> assert {ApiService} = try require "./api" noSignature = "please, supply a plain object" noDocuments = "cannot find the documents seq" internal = "an anomaly found in doc sequence" malfuncs = "derived from the incorrect source" message = "Setting an API documentation in %s" @documents ?= new Array() # document sequence assert previous = this.documents or new Array assert _.all(previous, _.isObject), internal return previous unless arguments.length > 0 signature = _.find arguments, _.isPlainObject assert _.isPlainObject(signature), noSignature assert _.isArray(this.documents), noDocuments assert (try @derives(ApiService)), malfuncs assert identify = this.identify().underline logger.silly message.yellow, identify.bold fn = (arbitraryVector) -> return signature fn @documents = previous.concat signature # Class directive that sets the specified Crossroads rule in # a Crossroads rules sequence that will be used & emptied when # a API method is defined below. That is, this method operates # in a sequential mode. The Crossroads rule gets supplied to # this method as an object argument with arbitrary key/value # pairs, where keys are rule name and value is a rule itself. # Rules are attached to the route defined right after rules. this.crossroadsRule = this.rule = (xsignature) -> assert {ApiService} = try require "./api" noSignature = "please, supply a plain object" noCrossRules = "cannot find a cross-rules seq" internal = "an anomaly found in rule sequence" malfuncs = "derived from the incorrect source" message = "Setting the Crossroads rule in %s" @crossRules ?= new Array() # cross-rules seqs assert previous = this.crossRules or Array() assert _.all(previous, _.isObject), internal return previous unless arguments.length > 0 signature = _.find arguments, _.isPlainObject assert _.isPlainObject(signature), noSignature assert _.isArray(this.crossRules), noCrossRules assert (try @derives(ApiService)), malfuncs assert identify = this.identify().underline logger.silly message.yellow, identify.bold fn = (arbitraryVector) -> return signature fn @crossRules = previous.concat signature # Class directive that sets the specified parameter summary in # the parameters/arg sequence that will be used & emptied when # a API method is defined below. That is, this method operates # in a sequential mode. The parameter summary gets supplied to # this method as an object argument with arbitrary key/value # pairs, where keys are arg names and values are the synopsis. # Params are attached to the route defined right after docs. this.defineParameter = this.argv = (xsignature) -> assert {ApiService} = try require "./api" noSignature = "please, supply a plain object" noParamStore = "cannot find a param-store seq" internal = "an anomaly found in argv sequence" malfuncs = "derived from the incorrect source" message = "Setting the parameter value in %s" @paramStore ?= new Array() # cross-rules seqs assert previous = this.paramStore or Array() assert _.all(previous, _.isObject), internal return previous unless arguments.length > 0 signature = _.find arguments, _.isPlainObject assert _.isPlainObject(signature), noSignature assert _.isArray(this.paramStore), noParamStore assert (try @derives(ApiService)), malfuncs assert identify = this.identify().underline logger.silly message.yellow, identify.bold fn = (arbitraryVector) -> return signature fn @paramStore = previous.concat signature
[ { "context": "nect: (config, callback) ->\n\t\t\tcfg =\n\t\t\t\tuserName: config.user\n\t\t\t\tpassword: config.password\n\t\t\t\thost: config.se", "end": 3176, "score": 0.9236633777618408, "start": 3165, "tag": "USERNAME", "value": "config.user" }, { "context": ">\n\t\t\tcfg =\n\t\t\t\tuserName: config.user\n\t\t\t\tpassword: config.password\n\t\t\t\thost: config.server\n\t\t\t\tport: config.port\n\t\t\t", "end": 3206, "score": 0.9992873072624207, "start": 3191, "tag": "PASSWORD", "value": "config.password" } ]
node_modules/mssql/src/tds.coffee
kaushik-hemant/workingp2p
0
{Pool} = require 'generic-pool' tds = require 'tds' util = require 'util' FIXED = false {TYPES, declare} = require('./datatypes') ISOLATION_LEVEL = require('./isolationlevel') ### @ignore ### castParameter = (value, type) -> unless value? then return null switch type when TYPES.VarChar, TYPES.NVarChar, TYPES.Char, TYPES.NChar, TYPES.Xml, TYPES.Text, TYPES.NText if typeof value isnt 'string' and value not instanceof String value = value.toString() when TYPES.Int, TYPES.TinyInt, TYPES.BigInt, TYPES.SmallInt if typeof value isnt 'number' and value not instanceof Number value = parseInt(value) if isNaN(value) then value = null when TYPES.Float, TYPES.Real, TYPES.Decimal, TYPES.Numeric, TYPES.SmallMoney, TYPES.Money if typeof value isnt 'number' and value not instanceof Number value = parseFloat(value) if isNaN(value) then value = null when TYPES.Bit if typeof value isnt 'boolean' and value not instanceof Boolean value = Boolean(value) when TYPES.DateTime, TYPES.SmallDateTime, TYPES.DateTimeOffset, TYPES.Date if value not instanceof Date value = new Date(value) when TYPES.Binary, TYPES.VarBinary, TYPES.Image if value not instanceof Buffer value = new Buffer(value.toString()) value ### @ignore ### createParameterHeader = (param) -> header = type: param.type.declaration switch param.type when TYPES.VarChar, TYPES.NVarChar, TYPES.VarBinary header.size = "MAX" when TYPES.Char, TYPES.NChar, TYPES.Binary header.size = param.length ? param.value?.length ? 1 header ### @ignore ### createColumns = (metadata) -> out = {} for column, index in metadata out[column.name] = index: index name: column.name length: column.length type: TYPES[column.type.sqlType] out ### @ignore ### isolationLevelDeclaration = (type) -> switch type when ISOLATION_LEVEL.READ_UNCOMMITTED then return "READ UNCOMMITTED" when ISOLATION_LEVEL.READ_COMMITTED then return "READ COMMITTED" when ISOLATION_LEVEL.REPEATABLE_READ then return "REPEATABLE READ" when ISOLATION_LEVEL.SERIALIZABLE then return "SERIALIZABLE" when ISOLATION_LEVEL.SNAPSHOT then return "SNAPSHOT" else throw new TransactionError "Invalid isolation level." ### Taken from Tedious. @private ### formatHex = (number) -> hex = number.toString(16) if hex.length == 1 hex = '0' + hex hex ### Taken from Tedious. @private ### parseGuid = (buffer) -> guid = formatHex(buffer[3]) + formatHex(buffer[2]) + formatHex(buffer[1]) + formatHex(buffer[0]) + '-' + formatHex(buffer[5]) + formatHex(buffer[4]) + '-' + formatHex(buffer[7]) + formatHex(buffer[6]) + '-' + formatHex(buffer[8]) + formatHex(buffer[9]) + '-' + formatHex(buffer[10]) + formatHex(buffer[11]) + formatHex(buffer[12]) + formatHex(buffer[13]) + formatHex(buffer[14]) + formatHex(buffer[15]) guid.toUpperCase() ### @ignore ### module.exports = (Connection, Transaction, Request, ConnectionError, TransactionError, RequestError) -> class TDSConnection extends Connection pool: null connect: (config, callback) -> cfg = userName: config.user password: config.password host: config.server port: config.port database: config.database cfg_pool = name: 'mssql' max: 10 min: 0 idleTimeoutMillis: 30000 create: (callback) => c = new tds.Connection cfg c.on 'error', (err) => if err.code is 'ECONNRESET' c.hasError = true return @emit 'error', err timeouted = false tmr = setTimeout -> timeouted = true c._client._socket.destroy() callback new ConnectionError("Connection timeout.", 'ETIMEOUT'), null # there must be a second argument null , config.timeout ? 15000 c.connect (err) => clearTimeout tmr if timeouted then return if err then err = ConnectionError err if err then return callback err, null # there must be a second argument null callback null, c validate: (c) -> c? and not c.hasError destroy: (c) -> c?.end() if config.pool for key, value of config.pool cfg_pool[key] = value @pool = Pool cfg_pool, cfg #create one testing connection to check if everything is ok @pool.acquire (err, connection) => if err and err not instanceof Error then err = new Error err if err @pool.drain => #prevent the pool from creating additional connections. we're done with it @pool?.destroyAllNow() @pool = null else # and release it immediately @pool.release connection callback err close: (callback) -> unless @pool then return callback null @pool.drain => @pool?.destroyAllNow() @pool = null callback null class TDSTransaction extends Transaction begin: (callback) -> @connection.pool.acquire (err, connection) => if err then return callback err @_pooledConnection = connection @request().query "set transaction isolation level #{isolationLevelDeclaration(@isolationLevel)}", (err) => if err then return TransactionError err connection.setAutoCommit false, callback commit: (callback) -> @_pooledConnection.commit (err) => if err then err = TransactionError err @connection.pool.release @_pooledConnection @_pooledConnection = null callback err rollback: (callback) -> @_pooledConnection.rollback (err) => if err then err = TransactionError err @connection.pool.release @_pooledConnection @_pooledConnection = null callback err class TDSRequest extends Request batch: (batch, callback) -> TDSRequest::query.call @, batch, callback bulk: (table, callback) -> process.nextTick -> callback RequestError("Bulk insert is not supported in 'msnodesql' driver.", 'ENOTSUPP') query: (command, callback) -> if @verbose and not @nested then @_log "---------- sql query ----------\n query: #{command}" if command.length is 0 return process.nextTick -> if @verbose and not @nested @_log "---------- response -----------" elapsed = Date.now() - started @_log " duration: #{elapsed}ms" @_log "---------- completed ----------" callback? null, if @multiple or @nested then [] else null recordset = null recordsets = [] started = Date.now() handleOutput = false errors = [] lastrow = null paramHeaders = {} paramValues = {} for name, param of @parameters when param.io is 1 paramHeaders[name] = createParameterHeader param paramValues[name] = castParameter(param.value, param.type) # nested = function is called by this.execute unless @nested input = ("@#{param.name} #{declare(param.type, param)}" for name, param of @parameters when param.io is 2) output = ("@#{param.name} as '#{param.name}'" for name, param of @parameters when param.io is 2) if input.length then command = "declare #{input.join ','};#{command};" if output.length command += "select #{output.join ','};" handleOutput = true @_acquire (err, connection) => unless err if @canceled if @verbose then @_log "---------- canceling ----------" @_release connection return callback? new RequestError "Canceled.", 'ECANCEL' @_cancel = => if @verbose then @_log "---------- canceling ----------" req.cancel() req = connection.createStatement command, paramHeaders req.on 'row', (tdsrow) => row = {} for col in tdsrow.metadata.columns value = tdsrow.getValue col.name if value? # convert uniqueidentifier to string if col.type.name is 'GUIDTYPE' value = parseGuid value exi = row[col.name] if exi? if exi instanceof Array exi.push col.value else row[col.name] = [exi, value] else row[col.name] = value if @verbose @_log util.inspect(row) @_log "---------- --------------------" unless row["___return___"]? # row with ___return___ col is the last row if @stream then @emit 'row', row else lastrow = row unless @stream recordset.push row req.on 'metadata', (metadata) => recordset = [] Object.defineProperty recordset, 'columns', enumerable: false value: createColumns(metadata.columns) @nested if @stream unless recordset.columns["___return___"]? # row with ___return___ col is the last row @emit 'recordset', recordset.columns else recordsets.push recordset req.on 'done', (res) => if @canceled e = new RequestError "Canceled.", 'ECANCEL' if @stream @emit 'error', e else errors.push e unless @nested # do we have output parameters to handle? if handleOutput last = recordsets.pop()?[0] for name, param of @parameters when param.io is 2 param.value = last[param.name] if @verbose @_log " output: @#{param.name}, #{param.type.declaration}, #{param.value}" if @verbose if errors.length @_log " error: #{error}" for error in errors elapsed = Date.now() - started @_log " duration: #{elapsed}ms" @_log "---------- completed ----------" if errors.length and not @stream error = errors.pop() error.precedingErrors = errors @_release connection if @stream callback null, if @nested then lastrow else null else callback? error, if @multiple or @nested then recordsets else recordsets[0] req.on 'message', (msg) => @emit 'info', message: msg.text number: msg.number state: msg.state class: msg.severity lineNumber: msg.lineNumber serverName: msg.serverName procName: msg.procName req.on 'error', (err) => e = RequestError err, 'EREQUEST' if @stream @emit 'error', e else errors.push e req.execute paramValues else if connection then @_release connection callback? err execute: (procedure, callback) -> if @verbose then @_log "---------- sql execute --------\n proc: #{procedure}" started = Date.now() cmd = "declare #{['@___return___ int'].concat("@#{param.name} #{declare(param.type, param)}" for name, param of @parameters when param.io is 2).join ', '};" cmd += "exec @___return___ = #{procedure} " spp = [] for name, param of @parameters if @verbose @_log " #{if param.io is 1 then " input" else "output"}: @#{param.name}, #{param.type.declaration}, #{param.value}" if param.io is 2 # output parameter spp.push "@#{param.name}=@#{param.name} output" else # input parameter spp.push "@#{param.name}=@#{param.name}" cmd += "#{spp.join ', '};" cmd += "select #{['@___return___ as \'___return___\''].concat("@#{param.name} as '#{param.name}'" for name, param of @parameters when param.io is 2).join ', '};" if @verbose then @_log "---------- response -----------" @nested = true # direct call to query, in case method on main request object is overriden (e.g. co-mssql) TDSRequest::query.call @, cmd, (err, recordsets) => @nested = false if err if @verbose elapsed = Date.now() - started @_log " error: #{err}" @_log " duration: #{elapsed}ms" @_log "---------- completed ----------" callback? err else if @stream last = recordsets else last = recordsets.pop()?[0] if last and last.___return___? returnValue = last.___return___ for name, param of @parameters when param.io is 2 param.value = last[param.name] if @verbose @_log " output: @#{param.name}, #{param.type.declaration}, #{param.value}" if @verbose elapsed = Date.now() - started @_log " return: #{returnValue}" @_log " duration: #{elapsed}ms" @_log "---------- completed ----------" if @stream callback null, null, returnValue else recordsets.returnValue = returnValue callback? null, recordsets, returnValue ### Cancel currently executed request. ### cancel: -> if @_cancel then return @_cancel() true return { Connection: TDSConnection Transaction: TDSTransaction Request: TDSRequest fix: -> unless FIXED require './tds-fix' FIXED = true }
462
{Pool} = require 'generic-pool' tds = require 'tds' util = require 'util' FIXED = false {TYPES, declare} = require('./datatypes') ISOLATION_LEVEL = require('./isolationlevel') ### @ignore ### castParameter = (value, type) -> unless value? then return null switch type when TYPES.VarChar, TYPES.NVarChar, TYPES.Char, TYPES.NChar, TYPES.Xml, TYPES.Text, TYPES.NText if typeof value isnt 'string' and value not instanceof String value = value.toString() when TYPES.Int, TYPES.TinyInt, TYPES.BigInt, TYPES.SmallInt if typeof value isnt 'number' and value not instanceof Number value = parseInt(value) if isNaN(value) then value = null when TYPES.Float, TYPES.Real, TYPES.Decimal, TYPES.Numeric, TYPES.SmallMoney, TYPES.Money if typeof value isnt 'number' and value not instanceof Number value = parseFloat(value) if isNaN(value) then value = null when TYPES.Bit if typeof value isnt 'boolean' and value not instanceof Boolean value = Boolean(value) when TYPES.DateTime, TYPES.SmallDateTime, TYPES.DateTimeOffset, TYPES.Date if value not instanceof Date value = new Date(value) when TYPES.Binary, TYPES.VarBinary, TYPES.Image if value not instanceof Buffer value = new Buffer(value.toString()) value ### @ignore ### createParameterHeader = (param) -> header = type: param.type.declaration switch param.type when TYPES.VarChar, TYPES.NVarChar, TYPES.VarBinary header.size = "MAX" when TYPES.Char, TYPES.NChar, TYPES.Binary header.size = param.length ? param.value?.length ? 1 header ### @ignore ### createColumns = (metadata) -> out = {} for column, index in metadata out[column.name] = index: index name: column.name length: column.length type: TYPES[column.type.sqlType] out ### @ignore ### isolationLevelDeclaration = (type) -> switch type when ISOLATION_LEVEL.READ_UNCOMMITTED then return "READ UNCOMMITTED" when ISOLATION_LEVEL.READ_COMMITTED then return "READ COMMITTED" when ISOLATION_LEVEL.REPEATABLE_READ then return "REPEATABLE READ" when ISOLATION_LEVEL.SERIALIZABLE then return "SERIALIZABLE" when ISOLATION_LEVEL.SNAPSHOT then return "SNAPSHOT" else throw new TransactionError "Invalid isolation level." ### Taken from Tedious. @private ### formatHex = (number) -> hex = number.toString(16) if hex.length == 1 hex = '0' + hex hex ### Taken from Tedious. @private ### parseGuid = (buffer) -> guid = formatHex(buffer[3]) + formatHex(buffer[2]) + formatHex(buffer[1]) + formatHex(buffer[0]) + '-' + formatHex(buffer[5]) + formatHex(buffer[4]) + '-' + formatHex(buffer[7]) + formatHex(buffer[6]) + '-' + formatHex(buffer[8]) + formatHex(buffer[9]) + '-' + formatHex(buffer[10]) + formatHex(buffer[11]) + formatHex(buffer[12]) + formatHex(buffer[13]) + formatHex(buffer[14]) + formatHex(buffer[15]) guid.toUpperCase() ### @ignore ### module.exports = (Connection, Transaction, Request, ConnectionError, TransactionError, RequestError) -> class TDSConnection extends Connection pool: null connect: (config, callback) -> cfg = userName: config.user password: <PASSWORD> host: config.server port: config.port database: config.database cfg_pool = name: 'mssql' max: 10 min: 0 idleTimeoutMillis: 30000 create: (callback) => c = new tds.Connection cfg c.on 'error', (err) => if err.code is 'ECONNRESET' c.hasError = true return @emit 'error', err timeouted = false tmr = setTimeout -> timeouted = true c._client._socket.destroy() callback new ConnectionError("Connection timeout.", 'ETIMEOUT'), null # there must be a second argument null , config.timeout ? 15000 c.connect (err) => clearTimeout tmr if timeouted then return if err then err = ConnectionError err if err then return callback err, null # there must be a second argument null callback null, c validate: (c) -> c? and not c.hasError destroy: (c) -> c?.end() if config.pool for key, value of config.pool cfg_pool[key] = value @pool = Pool cfg_pool, cfg #create one testing connection to check if everything is ok @pool.acquire (err, connection) => if err and err not instanceof Error then err = new Error err if err @pool.drain => #prevent the pool from creating additional connections. we're done with it @pool?.destroyAllNow() @pool = null else # and release it immediately @pool.release connection callback err close: (callback) -> unless @pool then return callback null @pool.drain => @pool?.destroyAllNow() @pool = null callback null class TDSTransaction extends Transaction begin: (callback) -> @connection.pool.acquire (err, connection) => if err then return callback err @_pooledConnection = connection @request().query "set transaction isolation level #{isolationLevelDeclaration(@isolationLevel)}", (err) => if err then return TransactionError err connection.setAutoCommit false, callback commit: (callback) -> @_pooledConnection.commit (err) => if err then err = TransactionError err @connection.pool.release @_pooledConnection @_pooledConnection = null callback err rollback: (callback) -> @_pooledConnection.rollback (err) => if err then err = TransactionError err @connection.pool.release @_pooledConnection @_pooledConnection = null callback err class TDSRequest extends Request batch: (batch, callback) -> TDSRequest::query.call @, batch, callback bulk: (table, callback) -> process.nextTick -> callback RequestError("Bulk insert is not supported in 'msnodesql' driver.", 'ENOTSUPP') query: (command, callback) -> if @verbose and not @nested then @_log "---------- sql query ----------\n query: #{command}" if command.length is 0 return process.nextTick -> if @verbose and not @nested @_log "---------- response -----------" elapsed = Date.now() - started @_log " duration: #{elapsed}ms" @_log "---------- completed ----------" callback? null, if @multiple or @nested then [] else null recordset = null recordsets = [] started = Date.now() handleOutput = false errors = [] lastrow = null paramHeaders = {} paramValues = {} for name, param of @parameters when param.io is 1 paramHeaders[name] = createParameterHeader param paramValues[name] = castParameter(param.value, param.type) # nested = function is called by this.execute unless @nested input = ("@#{param.name} #{declare(param.type, param)}" for name, param of @parameters when param.io is 2) output = ("@#{param.name} as '#{param.name}'" for name, param of @parameters when param.io is 2) if input.length then command = "declare #{input.join ','};#{command};" if output.length command += "select #{output.join ','};" handleOutput = true @_acquire (err, connection) => unless err if @canceled if @verbose then @_log "---------- canceling ----------" @_release connection return callback? new RequestError "Canceled.", 'ECANCEL' @_cancel = => if @verbose then @_log "---------- canceling ----------" req.cancel() req = connection.createStatement command, paramHeaders req.on 'row', (tdsrow) => row = {} for col in tdsrow.metadata.columns value = tdsrow.getValue col.name if value? # convert uniqueidentifier to string if col.type.name is 'GUIDTYPE' value = parseGuid value exi = row[col.name] if exi? if exi instanceof Array exi.push col.value else row[col.name] = [exi, value] else row[col.name] = value if @verbose @_log util.inspect(row) @_log "---------- --------------------" unless row["___return___"]? # row with ___return___ col is the last row if @stream then @emit 'row', row else lastrow = row unless @stream recordset.push row req.on 'metadata', (metadata) => recordset = [] Object.defineProperty recordset, 'columns', enumerable: false value: createColumns(metadata.columns) @nested if @stream unless recordset.columns["___return___"]? # row with ___return___ col is the last row @emit 'recordset', recordset.columns else recordsets.push recordset req.on 'done', (res) => if @canceled e = new RequestError "Canceled.", 'ECANCEL' if @stream @emit 'error', e else errors.push e unless @nested # do we have output parameters to handle? if handleOutput last = recordsets.pop()?[0] for name, param of @parameters when param.io is 2 param.value = last[param.name] if @verbose @_log " output: @#{param.name}, #{param.type.declaration}, #{param.value}" if @verbose if errors.length @_log " error: #{error}" for error in errors elapsed = Date.now() - started @_log " duration: #{elapsed}ms" @_log "---------- completed ----------" if errors.length and not @stream error = errors.pop() error.precedingErrors = errors @_release connection if @stream callback null, if @nested then lastrow else null else callback? error, if @multiple or @nested then recordsets else recordsets[0] req.on 'message', (msg) => @emit 'info', message: msg.text number: msg.number state: msg.state class: msg.severity lineNumber: msg.lineNumber serverName: msg.serverName procName: msg.procName req.on 'error', (err) => e = RequestError err, 'EREQUEST' if @stream @emit 'error', e else errors.push e req.execute paramValues else if connection then @_release connection callback? err execute: (procedure, callback) -> if @verbose then @_log "---------- sql execute --------\n proc: #{procedure}" started = Date.now() cmd = "declare #{['@___return___ int'].concat("@#{param.name} #{declare(param.type, param)}" for name, param of @parameters when param.io is 2).join ', '};" cmd += "exec @___return___ = #{procedure} " spp = [] for name, param of @parameters if @verbose @_log " #{if param.io is 1 then " input" else "output"}: @#{param.name}, #{param.type.declaration}, #{param.value}" if param.io is 2 # output parameter spp.push "@#{param.name}=@#{param.name} output" else # input parameter spp.push "@#{param.name}=@#{param.name}" cmd += "#{spp.join ', '};" cmd += "select #{['@___return___ as \'___return___\''].concat("@#{param.name} as '#{param.name}'" for name, param of @parameters when param.io is 2).join ', '};" if @verbose then @_log "---------- response -----------" @nested = true # direct call to query, in case method on main request object is overriden (e.g. co-mssql) TDSRequest::query.call @, cmd, (err, recordsets) => @nested = false if err if @verbose elapsed = Date.now() - started @_log " error: #{err}" @_log " duration: #{elapsed}ms" @_log "---------- completed ----------" callback? err else if @stream last = recordsets else last = recordsets.pop()?[0] if last and last.___return___? returnValue = last.___return___ for name, param of @parameters when param.io is 2 param.value = last[param.name] if @verbose @_log " output: @#{param.name}, #{param.type.declaration}, #{param.value}" if @verbose elapsed = Date.now() - started @_log " return: #{returnValue}" @_log " duration: #{elapsed}ms" @_log "---------- completed ----------" if @stream callback null, null, returnValue else recordsets.returnValue = returnValue callback? null, recordsets, returnValue ### Cancel currently executed request. ### cancel: -> if @_cancel then return @_cancel() true return { Connection: TDSConnection Transaction: TDSTransaction Request: TDSRequest fix: -> unless FIXED require './tds-fix' FIXED = true }
true
{Pool} = require 'generic-pool' tds = require 'tds' util = require 'util' FIXED = false {TYPES, declare} = require('./datatypes') ISOLATION_LEVEL = require('./isolationlevel') ### @ignore ### castParameter = (value, type) -> unless value? then return null switch type when TYPES.VarChar, TYPES.NVarChar, TYPES.Char, TYPES.NChar, TYPES.Xml, TYPES.Text, TYPES.NText if typeof value isnt 'string' and value not instanceof String value = value.toString() when TYPES.Int, TYPES.TinyInt, TYPES.BigInt, TYPES.SmallInt if typeof value isnt 'number' and value not instanceof Number value = parseInt(value) if isNaN(value) then value = null when TYPES.Float, TYPES.Real, TYPES.Decimal, TYPES.Numeric, TYPES.SmallMoney, TYPES.Money if typeof value isnt 'number' and value not instanceof Number value = parseFloat(value) if isNaN(value) then value = null when TYPES.Bit if typeof value isnt 'boolean' and value not instanceof Boolean value = Boolean(value) when TYPES.DateTime, TYPES.SmallDateTime, TYPES.DateTimeOffset, TYPES.Date if value not instanceof Date value = new Date(value) when TYPES.Binary, TYPES.VarBinary, TYPES.Image if value not instanceof Buffer value = new Buffer(value.toString()) value ### @ignore ### createParameterHeader = (param) -> header = type: param.type.declaration switch param.type when TYPES.VarChar, TYPES.NVarChar, TYPES.VarBinary header.size = "MAX" when TYPES.Char, TYPES.NChar, TYPES.Binary header.size = param.length ? param.value?.length ? 1 header ### @ignore ### createColumns = (metadata) -> out = {} for column, index in metadata out[column.name] = index: index name: column.name length: column.length type: TYPES[column.type.sqlType] out ### @ignore ### isolationLevelDeclaration = (type) -> switch type when ISOLATION_LEVEL.READ_UNCOMMITTED then return "READ UNCOMMITTED" when ISOLATION_LEVEL.READ_COMMITTED then return "READ COMMITTED" when ISOLATION_LEVEL.REPEATABLE_READ then return "REPEATABLE READ" when ISOLATION_LEVEL.SERIALIZABLE then return "SERIALIZABLE" when ISOLATION_LEVEL.SNAPSHOT then return "SNAPSHOT" else throw new TransactionError "Invalid isolation level." ### Taken from Tedious. @private ### formatHex = (number) -> hex = number.toString(16) if hex.length == 1 hex = '0' + hex hex ### Taken from Tedious. @private ### parseGuid = (buffer) -> guid = formatHex(buffer[3]) + formatHex(buffer[2]) + formatHex(buffer[1]) + formatHex(buffer[0]) + '-' + formatHex(buffer[5]) + formatHex(buffer[4]) + '-' + formatHex(buffer[7]) + formatHex(buffer[6]) + '-' + formatHex(buffer[8]) + formatHex(buffer[9]) + '-' + formatHex(buffer[10]) + formatHex(buffer[11]) + formatHex(buffer[12]) + formatHex(buffer[13]) + formatHex(buffer[14]) + formatHex(buffer[15]) guid.toUpperCase() ### @ignore ### module.exports = (Connection, Transaction, Request, ConnectionError, TransactionError, RequestError) -> class TDSConnection extends Connection pool: null connect: (config, callback) -> cfg = userName: config.user password: PI:PASSWORD:<PASSWORD>END_PI host: config.server port: config.port database: config.database cfg_pool = name: 'mssql' max: 10 min: 0 idleTimeoutMillis: 30000 create: (callback) => c = new tds.Connection cfg c.on 'error', (err) => if err.code is 'ECONNRESET' c.hasError = true return @emit 'error', err timeouted = false tmr = setTimeout -> timeouted = true c._client._socket.destroy() callback new ConnectionError("Connection timeout.", 'ETIMEOUT'), null # there must be a second argument null , config.timeout ? 15000 c.connect (err) => clearTimeout tmr if timeouted then return if err then err = ConnectionError err if err then return callback err, null # there must be a second argument null callback null, c validate: (c) -> c? and not c.hasError destroy: (c) -> c?.end() if config.pool for key, value of config.pool cfg_pool[key] = value @pool = Pool cfg_pool, cfg #create one testing connection to check if everything is ok @pool.acquire (err, connection) => if err and err not instanceof Error then err = new Error err if err @pool.drain => #prevent the pool from creating additional connections. we're done with it @pool?.destroyAllNow() @pool = null else # and release it immediately @pool.release connection callback err close: (callback) -> unless @pool then return callback null @pool.drain => @pool?.destroyAllNow() @pool = null callback null class TDSTransaction extends Transaction begin: (callback) -> @connection.pool.acquire (err, connection) => if err then return callback err @_pooledConnection = connection @request().query "set transaction isolation level #{isolationLevelDeclaration(@isolationLevel)}", (err) => if err then return TransactionError err connection.setAutoCommit false, callback commit: (callback) -> @_pooledConnection.commit (err) => if err then err = TransactionError err @connection.pool.release @_pooledConnection @_pooledConnection = null callback err rollback: (callback) -> @_pooledConnection.rollback (err) => if err then err = TransactionError err @connection.pool.release @_pooledConnection @_pooledConnection = null callback err class TDSRequest extends Request batch: (batch, callback) -> TDSRequest::query.call @, batch, callback bulk: (table, callback) -> process.nextTick -> callback RequestError("Bulk insert is not supported in 'msnodesql' driver.", 'ENOTSUPP') query: (command, callback) -> if @verbose and not @nested then @_log "---------- sql query ----------\n query: #{command}" if command.length is 0 return process.nextTick -> if @verbose and not @nested @_log "---------- response -----------" elapsed = Date.now() - started @_log " duration: #{elapsed}ms" @_log "---------- completed ----------" callback? null, if @multiple or @nested then [] else null recordset = null recordsets = [] started = Date.now() handleOutput = false errors = [] lastrow = null paramHeaders = {} paramValues = {} for name, param of @parameters when param.io is 1 paramHeaders[name] = createParameterHeader param paramValues[name] = castParameter(param.value, param.type) # nested = function is called by this.execute unless @nested input = ("@#{param.name} #{declare(param.type, param)}" for name, param of @parameters when param.io is 2) output = ("@#{param.name} as '#{param.name}'" for name, param of @parameters when param.io is 2) if input.length then command = "declare #{input.join ','};#{command};" if output.length command += "select #{output.join ','};" handleOutput = true @_acquire (err, connection) => unless err if @canceled if @verbose then @_log "---------- canceling ----------" @_release connection return callback? new RequestError "Canceled.", 'ECANCEL' @_cancel = => if @verbose then @_log "---------- canceling ----------" req.cancel() req = connection.createStatement command, paramHeaders req.on 'row', (tdsrow) => row = {} for col in tdsrow.metadata.columns value = tdsrow.getValue col.name if value? # convert uniqueidentifier to string if col.type.name is 'GUIDTYPE' value = parseGuid value exi = row[col.name] if exi? if exi instanceof Array exi.push col.value else row[col.name] = [exi, value] else row[col.name] = value if @verbose @_log util.inspect(row) @_log "---------- --------------------" unless row["___return___"]? # row with ___return___ col is the last row if @stream then @emit 'row', row else lastrow = row unless @stream recordset.push row req.on 'metadata', (metadata) => recordset = [] Object.defineProperty recordset, 'columns', enumerable: false value: createColumns(metadata.columns) @nested if @stream unless recordset.columns["___return___"]? # row with ___return___ col is the last row @emit 'recordset', recordset.columns else recordsets.push recordset req.on 'done', (res) => if @canceled e = new RequestError "Canceled.", 'ECANCEL' if @stream @emit 'error', e else errors.push e unless @nested # do we have output parameters to handle? if handleOutput last = recordsets.pop()?[0] for name, param of @parameters when param.io is 2 param.value = last[param.name] if @verbose @_log " output: @#{param.name}, #{param.type.declaration}, #{param.value}" if @verbose if errors.length @_log " error: #{error}" for error in errors elapsed = Date.now() - started @_log " duration: #{elapsed}ms" @_log "---------- completed ----------" if errors.length and not @stream error = errors.pop() error.precedingErrors = errors @_release connection if @stream callback null, if @nested then lastrow else null else callback? error, if @multiple or @nested then recordsets else recordsets[0] req.on 'message', (msg) => @emit 'info', message: msg.text number: msg.number state: msg.state class: msg.severity lineNumber: msg.lineNumber serverName: msg.serverName procName: msg.procName req.on 'error', (err) => e = RequestError err, 'EREQUEST' if @stream @emit 'error', e else errors.push e req.execute paramValues else if connection then @_release connection callback? err execute: (procedure, callback) -> if @verbose then @_log "---------- sql execute --------\n proc: #{procedure}" started = Date.now() cmd = "declare #{['@___return___ int'].concat("@#{param.name} #{declare(param.type, param)}" for name, param of @parameters when param.io is 2).join ', '};" cmd += "exec @___return___ = #{procedure} " spp = [] for name, param of @parameters if @verbose @_log " #{if param.io is 1 then " input" else "output"}: @#{param.name}, #{param.type.declaration}, #{param.value}" if param.io is 2 # output parameter spp.push "@#{param.name}=@#{param.name} output" else # input parameter spp.push "@#{param.name}=@#{param.name}" cmd += "#{spp.join ', '};" cmd += "select #{['@___return___ as \'___return___\''].concat("@#{param.name} as '#{param.name}'" for name, param of @parameters when param.io is 2).join ', '};" if @verbose then @_log "---------- response -----------" @nested = true # direct call to query, in case method on main request object is overriden (e.g. co-mssql) TDSRequest::query.call @, cmd, (err, recordsets) => @nested = false if err if @verbose elapsed = Date.now() - started @_log " error: #{err}" @_log " duration: #{elapsed}ms" @_log "---------- completed ----------" callback? err else if @stream last = recordsets else last = recordsets.pop()?[0] if last and last.___return___? returnValue = last.___return___ for name, param of @parameters when param.io is 2 param.value = last[param.name] if @verbose @_log " output: @#{param.name}, #{param.type.declaration}, #{param.value}" if @verbose elapsed = Date.now() - started @_log " return: #{returnValue}" @_log " duration: #{elapsed}ms" @_log "---------- completed ----------" if @stream callback null, null, returnValue else recordsets.returnValue = returnValue callback? null, recordsets, returnValue ### Cancel currently executed request. ### cancel: -> if @_cancel then return @_cancel() true return { Connection: TDSConnection Transaction: TDSTransaction Request: TDSRequest fix: -> unless FIXED require './tds-fix' FIXED = true }
[ { "context": "###\n\tFlexNav.js 1.2\n\n\tCreated by Jason Weaver http://jasonweaver.name\n\tReleased under http://un", "end": 45, "score": 0.999855101108551, "start": 33, "tag": "NAME", "value": "Jason Weaver" } ]
assets/zengrids-demo/javascripts/flexnav-master/coffeescripts/jquery.flexnav.coffee
macmladen/lucar
0
### FlexNav.js 1.2 Created by Jason Weaver http://jasonweaver.name Released under http://unlicense.org/ // ### # Use local alias for $.noConflict() compatibility $ = jQuery $.fn.flexNav = (options) -> settings = $.extend 'animationSpeed': 250, 'transitionOpacity': true, 'buttonSelector': '.menu-button', 'hoverIntent': false, 'hoverIntentTimeout': 150 options $nav = $(@) # Set some classes in the markup $nav.addClass('with-js') if settings.transitionOpacity is true $nav.addClass('opacity') $nav.find("li").each -> if $(@).has("ul").length $(@).addClass("item-with-ul").find("ul").hide() # Get the breakpoint set with data-breakpoint if $nav.data('breakpoint') then breakpoint = $nav.data('breakpoint') # Functions for hover support showMenu = -> if $nav.hasClass('lg-screen') is true if settings.transitionOpacity is true $(@).find('>ul') .addClass('show') .stop(true, true) .animate( height: [ "toggle", "swing" ], opacity: "toggle", settings.animationSpeed ) else $(@).find('>ul') .addClass('show') .stop(true, true) .animate( height: [ "toggle", "swing" ], settings.animationSpeed ) resetMenu = -> if $nav.hasClass('lg-screen') is true and $(@).find('>ul').hasClass('show') is true if settings.transitionOpacity is true $(@).find('>ul') .removeClass('show') .stop(true, true) .animate( height: [ "toggle", "swing" ], opacity: "toggle", settings.animationSpeed ) else $(@).find('>ul') .removeClass('show') .stop(true, true) .animate( height: [ "toggle", "swing" ], settings.animationSpeed ) # Changing classes depending on viewport width and adding in hover support resizer = -> if $(window).width() <= breakpoint $nav.removeClass("lg-screen").addClass("sm-screen") # Toggle nav menu closed for one pager after anchor clicked $('.one-page li a').on( 'click', -> $nav.removeClass('show') ) else if $(window).width() > breakpoint $nav.removeClass("sm-screen").addClass("lg-screen") # Make sure navigation is closed when going back to large screens $nav.removeClass('show') if settings.hoverIntent is true # Requires hoverIntent jquery plugin http://cherne.net/brian/resources/jquery.hoverIntent.html $('.item-with-ul').hoverIntent( over: showMenu, out: resetMenu, timeout: settings.hoverIntentTimeout ) else if settings.hoverIntent is false $('.item-with-ul').on('mouseenter', showMenu).on('mouseleave', resetMenu) # Set navigation element for this instantiation $(settings['buttonSelector']).data('navEl', $nav) # Add in touch buttons selector = '.item-with-ul, ' + settings['buttonSelector'] $(selector).append('<span class="touch-button"><i class="navicon">&#9660;</i></span>') # Toggle touch for nav menu selector = settings['buttonSelector'] + ', ' + settings['buttonSelector'] + ' .touch-button' $(selector).on('click', (e) -> e.preventDefault() e.stopPropagation() bs = settings['buttonSelector'] $btnParent = if ($(@).is(bs)) then $(@) else $(@).parent(bs) $thisNav = $btnParent.data('navEl') $thisNav.toggleClass('show') ) # Toggle for sub-menus $('.touch-button').on('click', (e) -> $sub = $(@).parent('.item-with-ul').find('>ul') $touchButton = $(@).parent('.item-with-ul').find('>span.touch-button') # remove class of show from all elements that are not current if $nav.hasClass('lg-screen') is true $(@).parent('.item-with-ul').siblings().find('ul.show').removeClass('show').hide() # add class of show to current if $sub.hasClass('show') is true $sub.removeClass('show').slideUp(settings.animationSpeed) $touchButton.removeClass('active') else if $sub.hasClass('show') is false $sub.addClass('show').slideDown(settings.animationSpeed) $touchButton.addClass('active') ) # Sub ul's should have a class of 'open' if an element has focus $nav.find('.item-with-ul *').focus -> # remove class of open from all elements that are not focused $(@).parent('.item-with-ul').parent().find(".open").not(@).removeClass("open").hide() # add class of open to focused ul $(@).parent('.item-with-ul').find('>ul').addClass("open").show() # Call once to set resizer() # Call on browser resize $(window).on('resize', resizer)
93400
### FlexNav.js 1.2 Created by <NAME> http://jasonweaver.name Released under http://unlicense.org/ // ### # Use local alias for $.noConflict() compatibility $ = jQuery $.fn.flexNav = (options) -> settings = $.extend 'animationSpeed': 250, 'transitionOpacity': true, 'buttonSelector': '.menu-button', 'hoverIntent': false, 'hoverIntentTimeout': 150 options $nav = $(@) # Set some classes in the markup $nav.addClass('with-js') if settings.transitionOpacity is true $nav.addClass('opacity') $nav.find("li").each -> if $(@).has("ul").length $(@).addClass("item-with-ul").find("ul").hide() # Get the breakpoint set with data-breakpoint if $nav.data('breakpoint') then breakpoint = $nav.data('breakpoint') # Functions for hover support showMenu = -> if $nav.hasClass('lg-screen') is true if settings.transitionOpacity is true $(@).find('>ul') .addClass('show') .stop(true, true) .animate( height: [ "toggle", "swing" ], opacity: "toggle", settings.animationSpeed ) else $(@).find('>ul') .addClass('show') .stop(true, true) .animate( height: [ "toggle", "swing" ], settings.animationSpeed ) resetMenu = -> if $nav.hasClass('lg-screen') is true and $(@).find('>ul').hasClass('show') is true if settings.transitionOpacity is true $(@).find('>ul') .removeClass('show') .stop(true, true) .animate( height: [ "toggle", "swing" ], opacity: "toggle", settings.animationSpeed ) else $(@).find('>ul') .removeClass('show') .stop(true, true) .animate( height: [ "toggle", "swing" ], settings.animationSpeed ) # Changing classes depending on viewport width and adding in hover support resizer = -> if $(window).width() <= breakpoint $nav.removeClass("lg-screen").addClass("sm-screen") # Toggle nav menu closed for one pager after anchor clicked $('.one-page li a').on( 'click', -> $nav.removeClass('show') ) else if $(window).width() > breakpoint $nav.removeClass("sm-screen").addClass("lg-screen") # Make sure navigation is closed when going back to large screens $nav.removeClass('show') if settings.hoverIntent is true # Requires hoverIntent jquery plugin http://cherne.net/brian/resources/jquery.hoverIntent.html $('.item-with-ul').hoverIntent( over: showMenu, out: resetMenu, timeout: settings.hoverIntentTimeout ) else if settings.hoverIntent is false $('.item-with-ul').on('mouseenter', showMenu).on('mouseleave', resetMenu) # Set navigation element for this instantiation $(settings['buttonSelector']).data('navEl', $nav) # Add in touch buttons selector = '.item-with-ul, ' + settings['buttonSelector'] $(selector).append('<span class="touch-button"><i class="navicon">&#9660;</i></span>') # Toggle touch for nav menu selector = settings['buttonSelector'] + ', ' + settings['buttonSelector'] + ' .touch-button' $(selector).on('click', (e) -> e.preventDefault() e.stopPropagation() bs = settings['buttonSelector'] $btnParent = if ($(@).is(bs)) then $(@) else $(@).parent(bs) $thisNav = $btnParent.data('navEl') $thisNav.toggleClass('show') ) # Toggle for sub-menus $('.touch-button').on('click', (e) -> $sub = $(@).parent('.item-with-ul').find('>ul') $touchButton = $(@).parent('.item-with-ul').find('>span.touch-button') # remove class of show from all elements that are not current if $nav.hasClass('lg-screen') is true $(@).parent('.item-with-ul').siblings().find('ul.show').removeClass('show').hide() # add class of show to current if $sub.hasClass('show') is true $sub.removeClass('show').slideUp(settings.animationSpeed) $touchButton.removeClass('active') else if $sub.hasClass('show') is false $sub.addClass('show').slideDown(settings.animationSpeed) $touchButton.addClass('active') ) # Sub ul's should have a class of 'open' if an element has focus $nav.find('.item-with-ul *').focus -> # remove class of open from all elements that are not focused $(@).parent('.item-with-ul').parent().find(".open").not(@).removeClass("open").hide() # add class of open to focused ul $(@).parent('.item-with-ul').find('>ul').addClass("open").show() # Call once to set resizer() # Call on browser resize $(window).on('resize', resizer)
true
### FlexNav.js 1.2 Created by PI:NAME:<NAME>END_PI http://jasonweaver.name Released under http://unlicense.org/ // ### # Use local alias for $.noConflict() compatibility $ = jQuery $.fn.flexNav = (options) -> settings = $.extend 'animationSpeed': 250, 'transitionOpacity': true, 'buttonSelector': '.menu-button', 'hoverIntent': false, 'hoverIntentTimeout': 150 options $nav = $(@) # Set some classes in the markup $nav.addClass('with-js') if settings.transitionOpacity is true $nav.addClass('opacity') $nav.find("li").each -> if $(@).has("ul").length $(@).addClass("item-with-ul").find("ul").hide() # Get the breakpoint set with data-breakpoint if $nav.data('breakpoint') then breakpoint = $nav.data('breakpoint') # Functions for hover support showMenu = -> if $nav.hasClass('lg-screen') is true if settings.transitionOpacity is true $(@).find('>ul') .addClass('show') .stop(true, true) .animate( height: [ "toggle", "swing" ], opacity: "toggle", settings.animationSpeed ) else $(@).find('>ul') .addClass('show') .stop(true, true) .animate( height: [ "toggle", "swing" ], settings.animationSpeed ) resetMenu = -> if $nav.hasClass('lg-screen') is true and $(@).find('>ul').hasClass('show') is true if settings.transitionOpacity is true $(@).find('>ul') .removeClass('show') .stop(true, true) .animate( height: [ "toggle", "swing" ], opacity: "toggle", settings.animationSpeed ) else $(@).find('>ul') .removeClass('show') .stop(true, true) .animate( height: [ "toggle", "swing" ], settings.animationSpeed ) # Changing classes depending on viewport width and adding in hover support resizer = -> if $(window).width() <= breakpoint $nav.removeClass("lg-screen").addClass("sm-screen") # Toggle nav menu closed for one pager after anchor clicked $('.one-page li a').on( 'click', -> $nav.removeClass('show') ) else if $(window).width() > breakpoint $nav.removeClass("sm-screen").addClass("lg-screen") # Make sure navigation is closed when going back to large screens $nav.removeClass('show') if settings.hoverIntent is true # Requires hoverIntent jquery plugin http://cherne.net/brian/resources/jquery.hoverIntent.html $('.item-with-ul').hoverIntent( over: showMenu, out: resetMenu, timeout: settings.hoverIntentTimeout ) else if settings.hoverIntent is false $('.item-with-ul').on('mouseenter', showMenu).on('mouseleave', resetMenu) # Set navigation element for this instantiation $(settings['buttonSelector']).data('navEl', $nav) # Add in touch buttons selector = '.item-with-ul, ' + settings['buttonSelector'] $(selector).append('<span class="touch-button"><i class="navicon">&#9660;</i></span>') # Toggle touch for nav menu selector = settings['buttonSelector'] + ', ' + settings['buttonSelector'] + ' .touch-button' $(selector).on('click', (e) -> e.preventDefault() e.stopPropagation() bs = settings['buttonSelector'] $btnParent = if ($(@).is(bs)) then $(@) else $(@).parent(bs) $thisNav = $btnParent.data('navEl') $thisNav.toggleClass('show') ) # Toggle for sub-menus $('.touch-button').on('click', (e) -> $sub = $(@).parent('.item-with-ul').find('>ul') $touchButton = $(@).parent('.item-with-ul').find('>span.touch-button') # remove class of show from all elements that are not current if $nav.hasClass('lg-screen') is true $(@).parent('.item-with-ul').siblings().find('ul.show').removeClass('show').hide() # add class of show to current if $sub.hasClass('show') is true $sub.removeClass('show').slideUp(settings.animationSpeed) $touchButton.removeClass('active') else if $sub.hasClass('show') is false $sub.addClass('show').slideDown(settings.animationSpeed) $touchButton.addClass('active') ) # Sub ul's should have a class of 'open' if an element has focus $nav.find('.item-with-ul *').focus -> # remove class of open from all elements that are not focused $(@).parent('.item-with-ul').parent().find(".open").not(@).removeClass("open").hide() # add class of open to focused ul $(@).parent('.item-with-ul').find('>ul').addClass("open").show() # Call once to set resizer() # Call on browser resize $(window).on('resize', resizer)
[ { "context": "fig:\n template: 'HI'\n key: 'nested.squirrel'\n\n it 'should return the message with the ke", "end": 1689, "score": 0.9990699887275696, "start": 1674, "tag": "KEY", "value": "nested.squirrel" } ]
test/template-spec.coffee
octoblu/nanocyte-component-template
0
ReturnValue = require 'nanocyte-component-return-value' Template = require '../src/template' describe 'Template', -> beforeEach -> @sut = new Template it 'should exist', -> expect(@sut).to.be.an.instanceOf ReturnValue describe '->onEnvelope', -> describe 'when called with a template and no key', -> beforeEach -> @response = text: 'anything' @envelope = config: template: "anything" key: null message: "somethingElse" it 'should return the message with the key defaulted to text', -> expect(@sut.onEnvelope(@envelope)).to.deep.equal @response describe 'when called with a template and a key', -> beforeEach -> @response = atemplate: 'anything' @envelope = config: template: "anything" key: "atemplate" message: "somethingElse" it 'should return the message with the key assigned', -> expect(@sut.onEnvelope(@envelope)).to.deep.equal @response describe 'when called with a blank template and a key', -> beforeEach -> @response = atemplate: null @envelope = config: template: null key: "atemplate" message: "somethingElse" it 'should return the message with the key assigned', -> expect(@sut.onEnvelope(@envelope)).to.deep.equal @response describe 'when called with a template and a deep key', -> beforeEach -> @response = nested: squirrel: 'HI' @envelope = config: template: 'HI' key: 'nested.squirrel' it 'should return the message with the key assigned', -> expect(@sut.onEnvelope(@envelope)).to.deep.equal @response
217031
ReturnValue = require 'nanocyte-component-return-value' Template = require '../src/template' describe 'Template', -> beforeEach -> @sut = new Template it 'should exist', -> expect(@sut).to.be.an.instanceOf ReturnValue describe '->onEnvelope', -> describe 'when called with a template and no key', -> beforeEach -> @response = text: 'anything' @envelope = config: template: "anything" key: null message: "somethingElse" it 'should return the message with the key defaulted to text', -> expect(@sut.onEnvelope(@envelope)).to.deep.equal @response describe 'when called with a template and a key', -> beforeEach -> @response = atemplate: 'anything' @envelope = config: template: "anything" key: "atemplate" message: "somethingElse" it 'should return the message with the key assigned', -> expect(@sut.onEnvelope(@envelope)).to.deep.equal @response describe 'when called with a blank template and a key', -> beforeEach -> @response = atemplate: null @envelope = config: template: null key: "atemplate" message: "somethingElse" it 'should return the message with the key assigned', -> expect(@sut.onEnvelope(@envelope)).to.deep.equal @response describe 'when called with a template and a deep key', -> beforeEach -> @response = nested: squirrel: 'HI' @envelope = config: template: 'HI' key: '<KEY>' it 'should return the message with the key assigned', -> expect(@sut.onEnvelope(@envelope)).to.deep.equal @response
true
ReturnValue = require 'nanocyte-component-return-value' Template = require '../src/template' describe 'Template', -> beforeEach -> @sut = new Template it 'should exist', -> expect(@sut).to.be.an.instanceOf ReturnValue describe '->onEnvelope', -> describe 'when called with a template and no key', -> beforeEach -> @response = text: 'anything' @envelope = config: template: "anything" key: null message: "somethingElse" it 'should return the message with the key defaulted to text', -> expect(@sut.onEnvelope(@envelope)).to.deep.equal @response describe 'when called with a template and a key', -> beforeEach -> @response = atemplate: 'anything' @envelope = config: template: "anything" key: "atemplate" message: "somethingElse" it 'should return the message with the key assigned', -> expect(@sut.onEnvelope(@envelope)).to.deep.equal @response describe 'when called with a blank template and a key', -> beforeEach -> @response = atemplate: null @envelope = config: template: null key: "atemplate" message: "somethingElse" it 'should return the message with the key assigned', -> expect(@sut.onEnvelope(@envelope)).to.deep.equal @response describe 'when called with a template and a deep key', -> beforeEach -> @response = nested: squirrel: 'HI' @envelope = config: template: 'HI' key: 'PI:KEY:<KEY>END_PI' it 'should return the message with the key assigned', -> expect(@sut.onEnvelope(@envelope)).to.deep.equal @response
[ { "context": " Meteor.users.findOne('emails.address': 'admin@fbriders.ch')._id\n autoform:\n options: ->\n _.m", "end": 926, "score": 0.9999164938926697, "start": 909, "tag": "EMAIL", "value": "admin@fbriders.ch" } ]
collections/helpertasks.coffee
meip/vmt
0
@Helpertasks = new Meteor.Collection('helpertasks'); Schemas.Helpertasks = new SimpleSchema description: type: String autoform: rows: 5 startTime: type: Date endTime: type: Date numPersons: type: Number regEx: /[0-9]{1,3}/ helpertaskType: type: String regEx: SimpleSchema.RegEx.Id autoform: options: -> _.map HelpertaskTypes.find().fetch(), (helpertaskType)-> label: helpertaskType.title value: helpertaskType._id event: type: String regEx: SimpleSchema.RegEx.Id autoform: options: -> _.map Events.find().fetch(), (event)-> label: event.title value: event._id owner: type: String regEx: SimpleSchema.RegEx.Id autoValue: -> if this.isInsert try Meteor.userId() catch error Meteor.users.findOne('emails.address': 'admin@fbriders.ch')._id autoform: options: -> _.map Meteor.users.find().fetch(), (user)-> label: user.emails[0].address value: user._id createdAt: type: Date autoValue: -> if this.isInsert new Date() updatedAt: type: Date optional: true autoValue: -> if this.isUpdate new Date() Helpertasks.attachSchema(Schemas.Helpertasks) Helpertasks.helpers helpertaskTypeTitle: -> HelpertaskTypes.findOne(this.helpertaskType).title eventData: -> Events.findOne(this.event)
83553
@Helpertasks = new Meteor.Collection('helpertasks'); Schemas.Helpertasks = new SimpleSchema description: type: String autoform: rows: 5 startTime: type: Date endTime: type: Date numPersons: type: Number regEx: /[0-9]{1,3}/ helpertaskType: type: String regEx: SimpleSchema.RegEx.Id autoform: options: -> _.map HelpertaskTypes.find().fetch(), (helpertaskType)-> label: helpertaskType.title value: helpertaskType._id event: type: String regEx: SimpleSchema.RegEx.Id autoform: options: -> _.map Events.find().fetch(), (event)-> label: event.title value: event._id owner: type: String regEx: SimpleSchema.RegEx.Id autoValue: -> if this.isInsert try Meteor.userId() catch error Meteor.users.findOne('emails.address': '<EMAIL>')._id autoform: options: -> _.map Meteor.users.find().fetch(), (user)-> label: user.emails[0].address value: user._id createdAt: type: Date autoValue: -> if this.isInsert new Date() updatedAt: type: Date optional: true autoValue: -> if this.isUpdate new Date() Helpertasks.attachSchema(Schemas.Helpertasks) Helpertasks.helpers helpertaskTypeTitle: -> HelpertaskTypes.findOne(this.helpertaskType).title eventData: -> Events.findOne(this.event)
true
@Helpertasks = new Meteor.Collection('helpertasks'); Schemas.Helpertasks = new SimpleSchema description: type: String autoform: rows: 5 startTime: type: Date endTime: type: Date numPersons: type: Number regEx: /[0-9]{1,3}/ helpertaskType: type: String regEx: SimpleSchema.RegEx.Id autoform: options: -> _.map HelpertaskTypes.find().fetch(), (helpertaskType)-> label: helpertaskType.title value: helpertaskType._id event: type: String regEx: SimpleSchema.RegEx.Id autoform: options: -> _.map Events.find().fetch(), (event)-> label: event.title value: event._id owner: type: String regEx: SimpleSchema.RegEx.Id autoValue: -> if this.isInsert try Meteor.userId() catch error Meteor.users.findOne('emails.address': 'PI:EMAIL:<EMAIL>END_PI')._id autoform: options: -> _.map Meteor.users.find().fetch(), (user)-> label: user.emails[0].address value: user._id createdAt: type: Date autoValue: -> if this.isInsert new Date() updatedAt: type: Date optional: true autoValue: -> if this.isUpdate new Date() Helpertasks.attachSchema(Schemas.Helpertasks) Helpertasks.helpers helpertaskTypeTitle: -> HelpertaskTypes.findOne(this.helpertaskType).title eventData: -> Events.findOne(this.event)
[ { "context": "PI key'}\n ]\n localFilters: [\n {title: 'Assignee', stateAttribute: 'assignees', ticketField: 'as", "end": 3668, "score": 0.8816404342651367, "start": 3662, "tag": "NAME", "value": "Assign" }, { "context": "'}\n ]\n localFilters: [\n {title: 'Assignee', stateAttribute: 'assignees', ticketField: 'assi", "end": 3670, "score": 0.6046656370162964, "start": 3668, "tag": "NAME", "value": "ee" }, { "context": "PI key'}\n ]\n localFilters: [\n {title: 'Author', stateAttribute: 'authors', ticketField: 'author", "end": 5054, "score": 0.5451485514640808, "start": 5048, "tag": "NAME", "value": "Author" }, { "context": "t: '#f6d2d2'\n id: 'removed'\n name: 'Feedback'\n statusId: 4\n statusName: 'Feedbac", "end": 7450, "score": 0.7755043506622314, "start": 7442, "tag": "NAME", "value": "Feedback" } ]
src/coffee/config/KanbanConfig.coffee
marcosnasp/kanbanboard
2
exports.KanbanConfig = { serverConfig: null #will be updated from TicketCollection getRedmineIssueUrl: (redmineId) -> return "https://#{@serverConfig.redmineHost}/issues/#{redmineId}" teamViewConfig: path: 'team' title: 'Team' issuesUrl: '/teamissues' remoteFilters: [ {text: 'Key', name: 'key', type: 'password', description: 'Redmine API key'} {text: 'Team', name: 'team', type: 'text', description: 'Team name'} {text: 'Sprint', name: 'sprint', type: 'text', description: 'Sprint number'} ] localFilters: [ {title: 'Assignee', stateAttribute: 'assignees', ticketField: 'assigned_to', position: 'top'} {title: 'Project', stateAttribute: 'projects', ticketField: 'project', position: 'bottom'} ] columns: [ { colorEnd: '#75a7f1' colorStart: '#d4e3fa' id: 'new' name: 'New' statusId: 7 statusName: 'Queued ' statuses: ['New', 'Queued '] } { colorEnd: '#7fe3f3' colorStart: '#e1fafe' id: 'todo' name: 'To Do' statusId: 8 statusName: 'Groomed ' statuses: ['Groomed ', 'Committed '] } { colorEnd: 'orange' colorStart: '#ffecc8' id: 'inprogress' name: 'In Progress...' statusId: 2 statusName: 'In Progress' statuses: ['In Progress'] } { colorEnd: '#8ac383' colorStart: '#daffd5' id: 'resolved' name: 'Resolved' statusId: 3 statusName: 'Resolved' statuses: ['Resolved'] } { colorEnd: '#f37f7f' colorStart: '#f6d2d2' id: 'removed' name: 'Feedback' statusId: 4 statusName: 'Feedback' statuses: ['Feedback', 'Rejected', 'Blocked'] } ] ticketConfig: nameField: 'assigned_to' unassignedViewConfig: path: 'unassigned' title: 'Unassigned' issuesUrl: '/unassignedissues' remoteFilters: [ {text: 'Key', name: 'key', type: 'password', description: 'Redmine API key'} ] localFilters: [ {title: 'Author', stateAttribute: 'authors', ticketField: 'author', position: 'top'} {title: 'Projects', stateAttribute: 'projects', ticketField: 'project', position: 'bottom'} ] columns: [ { colorEnd: '#75a7f1' colorStart: '#d4e3fa' id: 'new' name: 'New' statusId: 7 statusName: 'Queued ' statuses: ['New', 'Queued '] } { colorEnd: '#7fe3f3' colorStart: '#e1fafe' id: 'todo' name: 'To Do' statusId: 8 statusName: 'Groomed ' statuses: ['Groomed ', 'Committed '] } { colorEnd: 'orange' colorStart: '#ffecc8' id: 'inprogress' name: 'In Progress...' statusId: 2 statusName: 'In Progress' statuses: ['In Progress'] } { colorEnd: '#8ac383' colorStart: '#daffd5' id: 'resolved' name: 'Resolved' statusId: 3 statusName: 'Resolved' statuses: ['Resolved'] } { colorEnd: '#f37f7f' colorStart: '#f6d2d2' id: 'removed' name: 'Feedback' statusId: 4 statusName: 'Feedback' statuses: ['Feedback', 'Rejected', 'Blocked'] } ] ticketConfig: nameField: 'author' poViewConfig: path: 'po' title: 'PO' issuesUrl: '/poissues' remoteFilters: [ {text: 'Key', name: 'key', type: 'password', description: 'Redmine API key'} ] localFilters: [ {title: 'Assignee', stateAttribute: 'assignees', ticketField: 'assigned_to', position: 'top'} {title: 'Project', stateAttribute: 'projects', ticketField: 'project', position: 'bottom'} ] columns: [ { colorEnd: '#75a7f1' colorStart: '#d4e3fa' id: 'backlog' name: 'Backlog' statusId: 7 statusName: 'Queued ' statuses: ['New', 'Queued ', 'Groomed ', 'Committed '] } { colorEnd: 'orange' colorStart: '#ffecc8' id: 'inprogress' name: 'In Progress...' statusId: 2 statusName: 'In Progress' statuses: ['In Progress'] } { colorEnd: '#8ac383' colorStart: '#daffd5' id: 'resolved' name: 'Resolved' statusId: 3 statusName: 'Resolved' statuses: ['Resolved'] } { colorEnd: '#f37f7f' colorStart: '#f6d2d2' id: 'removed' name: 'Feedback' statusId: 4 statusName: 'Feedback' statuses: ['Feedback', 'Rejected', 'Blocked'] } ] ticketConfig: nameField: 'assigned_to' developerViewConfig: path: 'developer' title: 'Developer' issuesUrl: '/developerissues' remoteFilters: [ {text: 'Key', name: 'key', type: 'password', description: 'Redmine API key'} ] localFilters: [ {title: 'Author', stateAttribute: 'authors', ticketField: 'author', position: 'top'} {title: 'Project', stateAttribute: 'projects', ticketField: 'project', position: 'bottom'} ] columns: [ { colorEnd: '#75a7f1' colorStart: '#d4e3fa' id: 'backlog' name: 'Backlog' statusId: 7 statusName: 'Queued ' statuses: ['New', 'Queued ', 'Groomed ', 'Committed '] } { colorEnd: 'orange' colorStart: '#ffecc8' id: 'inprogress' name: 'In Progress...' statusId: 2 statusName: 'In Progress' statuses: ['In Progress'] } { colorEnd: '#8ac383' colorStart: '#daffd5' id: 'resolved' name: 'Resolved' statusId: 3 statusName: 'Resolved' statuses: ['Resolved'] } { colorEnd: '#f37f7f' colorStart: '#f6d2d2' id: 'removed' name: 'Feedback' statusId: 4 statusName: 'Feedback' statuses: ['Feedback', 'Rejected', 'Blocked'] } ] ticketConfig: nameField: 'author' ticketViewConfig: path: 'tickets' title: 'Tickets' issuesUrl: '/specificissues' remoteFilters: [ {text: 'Key', name: 'key', type: 'password', description: 'Redmine API key'} {text: 'Tickets', name: 'tickets', type: 'text', description: 'Comma separated tickets'} ] columns: [ { colorEnd: '#75a7f1' colorStart: '#d4e3fa' id: 'backlog' name: 'Backlog' statusId: 7 statusName: 'Queued ' statuses: ['New', 'Queued ', 'Groomed ', 'Committed '] } { colorEnd: 'orange' colorStart: '#ffecc8' id: 'inprogress' name: 'In Progress...' statusId: 2 statusName: 'In Progress' statuses: ['In Progress'] } { colorEnd: '#8ac383' colorStart: '#daffd5' id: 'resolved' name: 'Resolved' statusId: 3 statusName: 'Resolved' statuses: ['Resolved'] } { colorEnd: 'lightgrey' colorStart: '#efefef' id: 'closed' name: 'Closed' statusId: 5 statusName: 'Closed' statuses: ['Closed'] } { colorEnd: '#f37f7f' colorStart: '#f6d2d2' id: 'removed' name: 'Feedback' statusId: 4 statusName: 'Feedback' statuses: ['Feedback', 'Rejected', 'Blocked'] } ] ticketConfig: nameField: 'author' navigationItems: [ {path: 'team', template: '<i class="fa fa-users" aria-hidden="true"></i>Team'} {path: 'po', template: '<i class="fa fa-user-secret" aria-hidden="true"></i>PO'} {path: 'developer', template: '<i class="fa fa-laptop" aria-hidden="true"></i>Developer'} {path: 'tickets', template: '<i class="fa fa-ticket" aria-hidden="true"></i>Tickets'} {path: 'unassigned', template: '<i class="fa fa-exclamation-circle" aria-hidden="true"></i>Unassigned'} {path: 'detailed', template: '<i class="fa fa-list-ol" aria-hidden="true"></i>Detailed'} ] detailedViewConfig: issuesUrl: '/specificissues' path: 'detailed' title: 'Detailed' remoteFilters: [ {text: 'Key', name: 'key', type: 'password', description: 'Redmine API key'} {text: 'Tickets', name: 'tickets', type: 'text', description: 'Comma separated tickets'} ] }
127291
exports.KanbanConfig = { serverConfig: null #will be updated from TicketCollection getRedmineIssueUrl: (redmineId) -> return "https://#{@serverConfig.redmineHost}/issues/#{redmineId}" teamViewConfig: path: 'team' title: 'Team' issuesUrl: '/teamissues' remoteFilters: [ {text: 'Key', name: 'key', type: 'password', description: 'Redmine API key'} {text: 'Team', name: 'team', type: 'text', description: 'Team name'} {text: 'Sprint', name: 'sprint', type: 'text', description: 'Sprint number'} ] localFilters: [ {title: 'Assignee', stateAttribute: 'assignees', ticketField: 'assigned_to', position: 'top'} {title: 'Project', stateAttribute: 'projects', ticketField: 'project', position: 'bottom'} ] columns: [ { colorEnd: '#75a7f1' colorStart: '#d4e3fa' id: 'new' name: 'New' statusId: 7 statusName: 'Queued ' statuses: ['New', 'Queued '] } { colorEnd: '#7fe3f3' colorStart: '#e1fafe' id: 'todo' name: 'To Do' statusId: 8 statusName: 'Groomed ' statuses: ['Groomed ', 'Committed '] } { colorEnd: 'orange' colorStart: '#ffecc8' id: 'inprogress' name: 'In Progress...' statusId: 2 statusName: 'In Progress' statuses: ['In Progress'] } { colorEnd: '#8ac383' colorStart: '#daffd5' id: 'resolved' name: 'Resolved' statusId: 3 statusName: 'Resolved' statuses: ['Resolved'] } { colorEnd: '#f37f7f' colorStart: '#f6d2d2' id: 'removed' name: 'Feedback' statusId: 4 statusName: 'Feedback' statuses: ['Feedback', 'Rejected', 'Blocked'] } ] ticketConfig: nameField: 'assigned_to' unassignedViewConfig: path: 'unassigned' title: 'Unassigned' issuesUrl: '/unassignedissues' remoteFilters: [ {text: 'Key', name: 'key', type: 'password', description: 'Redmine API key'} ] localFilters: [ {title: 'Author', stateAttribute: 'authors', ticketField: 'author', position: 'top'} {title: 'Projects', stateAttribute: 'projects', ticketField: 'project', position: 'bottom'} ] columns: [ { colorEnd: '#75a7f1' colorStart: '#d4e3fa' id: 'new' name: 'New' statusId: 7 statusName: 'Queued ' statuses: ['New', 'Queued '] } { colorEnd: '#7fe3f3' colorStart: '#e1fafe' id: 'todo' name: 'To Do' statusId: 8 statusName: 'Groomed ' statuses: ['Groomed ', 'Committed '] } { colorEnd: 'orange' colorStart: '#ffecc8' id: 'inprogress' name: 'In Progress...' statusId: 2 statusName: 'In Progress' statuses: ['In Progress'] } { colorEnd: '#8ac383' colorStart: '#daffd5' id: 'resolved' name: 'Resolved' statusId: 3 statusName: 'Resolved' statuses: ['Resolved'] } { colorEnd: '#f37f7f' colorStart: '#f6d2d2' id: 'removed' name: 'Feedback' statusId: 4 statusName: 'Feedback' statuses: ['Feedback', 'Rejected', 'Blocked'] } ] ticketConfig: nameField: 'author' poViewConfig: path: 'po' title: 'PO' issuesUrl: '/poissues' remoteFilters: [ {text: 'Key', name: 'key', type: 'password', description: 'Redmine API key'} ] localFilters: [ {title: '<NAME> <NAME>', stateAttribute: 'assignees', ticketField: 'assigned_to', position: 'top'} {title: 'Project', stateAttribute: 'projects', ticketField: 'project', position: 'bottom'} ] columns: [ { colorEnd: '#75a7f1' colorStart: '#d4e3fa' id: 'backlog' name: 'Backlog' statusId: 7 statusName: 'Queued ' statuses: ['New', 'Queued ', 'Groomed ', 'Committed '] } { colorEnd: 'orange' colorStart: '#ffecc8' id: 'inprogress' name: 'In Progress...' statusId: 2 statusName: 'In Progress' statuses: ['In Progress'] } { colorEnd: '#8ac383' colorStart: '#daffd5' id: 'resolved' name: 'Resolved' statusId: 3 statusName: 'Resolved' statuses: ['Resolved'] } { colorEnd: '#f37f7f' colorStart: '#f6d2d2' id: 'removed' name: 'Feedback' statusId: 4 statusName: 'Feedback' statuses: ['Feedback', 'Rejected', 'Blocked'] } ] ticketConfig: nameField: 'assigned_to' developerViewConfig: path: 'developer' title: 'Developer' issuesUrl: '/developerissues' remoteFilters: [ {text: 'Key', name: 'key', type: 'password', description: 'Redmine API key'} ] localFilters: [ {title: '<NAME>', stateAttribute: 'authors', ticketField: 'author', position: 'top'} {title: 'Project', stateAttribute: 'projects', ticketField: 'project', position: 'bottom'} ] columns: [ { colorEnd: '#75a7f1' colorStart: '#d4e3fa' id: 'backlog' name: 'Backlog' statusId: 7 statusName: 'Queued ' statuses: ['New', 'Queued ', 'Groomed ', 'Committed '] } { colorEnd: 'orange' colorStart: '#ffecc8' id: 'inprogress' name: 'In Progress...' statusId: 2 statusName: 'In Progress' statuses: ['In Progress'] } { colorEnd: '#8ac383' colorStart: '#daffd5' id: 'resolved' name: 'Resolved' statusId: 3 statusName: 'Resolved' statuses: ['Resolved'] } { colorEnd: '#f37f7f' colorStart: '#f6d2d2' id: 'removed' name: 'Feedback' statusId: 4 statusName: 'Feedback' statuses: ['Feedback', 'Rejected', 'Blocked'] } ] ticketConfig: nameField: 'author' ticketViewConfig: path: 'tickets' title: 'Tickets' issuesUrl: '/specificissues' remoteFilters: [ {text: 'Key', name: 'key', type: 'password', description: 'Redmine API key'} {text: 'Tickets', name: 'tickets', type: 'text', description: 'Comma separated tickets'} ] columns: [ { colorEnd: '#75a7f1' colorStart: '#d4e3fa' id: 'backlog' name: 'Backlog' statusId: 7 statusName: 'Queued ' statuses: ['New', 'Queued ', 'Groomed ', 'Committed '] } { colorEnd: 'orange' colorStart: '#ffecc8' id: 'inprogress' name: 'In Progress...' statusId: 2 statusName: 'In Progress' statuses: ['In Progress'] } { colorEnd: '#8ac383' colorStart: '#daffd5' id: 'resolved' name: 'Resolved' statusId: 3 statusName: 'Resolved' statuses: ['Resolved'] } { colorEnd: 'lightgrey' colorStart: '#efefef' id: 'closed' name: 'Closed' statusId: 5 statusName: 'Closed' statuses: ['Closed'] } { colorEnd: '#f37f7f' colorStart: '#f6d2d2' id: 'removed' name: '<NAME>' statusId: 4 statusName: 'Feedback' statuses: ['Feedback', 'Rejected', 'Blocked'] } ] ticketConfig: nameField: 'author' navigationItems: [ {path: 'team', template: '<i class="fa fa-users" aria-hidden="true"></i>Team'} {path: 'po', template: '<i class="fa fa-user-secret" aria-hidden="true"></i>PO'} {path: 'developer', template: '<i class="fa fa-laptop" aria-hidden="true"></i>Developer'} {path: 'tickets', template: '<i class="fa fa-ticket" aria-hidden="true"></i>Tickets'} {path: 'unassigned', template: '<i class="fa fa-exclamation-circle" aria-hidden="true"></i>Unassigned'} {path: 'detailed', template: '<i class="fa fa-list-ol" aria-hidden="true"></i>Detailed'} ] detailedViewConfig: issuesUrl: '/specificissues' path: 'detailed' title: 'Detailed' remoteFilters: [ {text: 'Key', name: 'key', type: 'password', description: 'Redmine API key'} {text: 'Tickets', name: 'tickets', type: 'text', description: 'Comma separated tickets'} ] }
true
exports.KanbanConfig = { serverConfig: null #will be updated from TicketCollection getRedmineIssueUrl: (redmineId) -> return "https://#{@serverConfig.redmineHost}/issues/#{redmineId}" teamViewConfig: path: 'team' title: 'Team' issuesUrl: '/teamissues' remoteFilters: [ {text: 'Key', name: 'key', type: 'password', description: 'Redmine API key'} {text: 'Team', name: 'team', type: 'text', description: 'Team name'} {text: 'Sprint', name: 'sprint', type: 'text', description: 'Sprint number'} ] localFilters: [ {title: 'Assignee', stateAttribute: 'assignees', ticketField: 'assigned_to', position: 'top'} {title: 'Project', stateAttribute: 'projects', ticketField: 'project', position: 'bottom'} ] columns: [ { colorEnd: '#75a7f1' colorStart: '#d4e3fa' id: 'new' name: 'New' statusId: 7 statusName: 'Queued ' statuses: ['New', 'Queued '] } { colorEnd: '#7fe3f3' colorStart: '#e1fafe' id: 'todo' name: 'To Do' statusId: 8 statusName: 'Groomed ' statuses: ['Groomed ', 'Committed '] } { colorEnd: 'orange' colorStart: '#ffecc8' id: 'inprogress' name: 'In Progress...' statusId: 2 statusName: 'In Progress' statuses: ['In Progress'] } { colorEnd: '#8ac383' colorStart: '#daffd5' id: 'resolved' name: 'Resolved' statusId: 3 statusName: 'Resolved' statuses: ['Resolved'] } { colorEnd: '#f37f7f' colorStart: '#f6d2d2' id: 'removed' name: 'Feedback' statusId: 4 statusName: 'Feedback' statuses: ['Feedback', 'Rejected', 'Blocked'] } ] ticketConfig: nameField: 'assigned_to' unassignedViewConfig: path: 'unassigned' title: 'Unassigned' issuesUrl: '/unassignedissues' remoteFilters: [ {text: 'Key', name: 'key', type: 'password', description: 'Redmine API key'} ] localFilters: [ {title: 'Author', stateAttribute: 'authors', ticketField: 'author', position: 'top'} {title: 'Projects', stateAttribute: 'projects', ticketField: 'project', position: 'bottom'} ] columns: [ { colorEnd: '#75a7f1' colorStart: '#d4e3fa' id: 'new' name: 'New' statusId: 7 statusName: 'Queued ' statuses: ['New', 'Queued '] } { colorEnd: '#7fe3f3' colorStart: '#e1fafe' id: 'todo' name: 'To Do' statusId: 8 statusName: 'Groomed ' statuses: ['Groomed ', 'Committed '] } { colorEnd: 'orange' colorStart: '#ffecc8' id: 'inprogress' name: 'In Progress...' statusId: 2 statusName: 'In Progress' statuses: ['In Progress'] } { colorEnd: '#8ac383' colorStart: '#daffd5' id: 'resolved' name: 'Resolved' statusId: 3 statusName: 'Resolved' statuses: ['Resolved'] } { colorEnd: '#f37f7f' colorStart: '#f6d2d2' id: 'removed' name: 'Feedback' statusId: 4 statusName: 'Feedback' statuses: ['Feedback', 'Rejected', 'Blocked'] } ] ticketConfig: nameField: 'author' poViewConfig: path: 'po' title: 'PO' issuesUrl: '/poissues' remoteFilters: [ {text: 'Key', name: 'key', type: 'password', description: 'Redmine API key'} ] localFilters: [ {title: 'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI', stateAttribute: 'assignees', ticketField: 'assigned_to', position: 'top'} {title: 'Project', stateAttribute: 'projects', ticketField: 'project', position: 'bottom'} ] columns: [ { colorEnd: '#75a7f1' colorStart: '#d4e3fa' id: 'backlog' name: 'Backlog' statusId: 7 statusName: 'Queued ' statuses: ['New', 'Queued ', 'Groomed ', 'Committed '] } { colorEnd: 'orange' colorStart: '#ffecc8' id: 'inprogress' name: 'In Progress...' statusId: 2 statusName: 'In Progress' statuses: ['In Progress'] } { colorEnd: '#8ac383' colorStart: '#daffd5' id: 'resolved' name: 'Resolved' statusId: 3 statusName: 'Resolved' statuses: ['Resolved'] } { colorEnd: '#f37f7f' colorStart: '#f6d2d2' id: 'removed' name: 'Feedback' statusId: 4 statusName: 'Feedback' statuses: ['Feedback', 'Rejected', 'Blocked'] } ] ticketConfig: nameField: 'assigned_to' developerViewConfig: path: 'developer' title: 'Developer' issuesUrl: '/developerissues' remoteFilters: [ {text: 'Key', name: 'key', type: 'password', description: 'Redmine API key'} ] localFilters: [ {title: 'PI:NAME:<NAME>END_PI', stateAttribute: 'authors', ticketField: 'author', position: 'top'} {title: 'Project', stateAttribute: 'projects', ticketField: 'project', position: 'bottom'} ] columns: [ { colorEnd: '#75a7f1' colorStart: '#d4e3fa' id: 'backlog' name: 'Backlog' statusId: 7 statusName: 'Queued ' statuses: ['New', 'Queued ', 'Groomed ', 'Committed '] } { colorEnd: 'orange' colorStart: '#ffecc8' id: 'inprogress' name: 'In Progress...' statusId: 2 statusName: 'In Progress' statuses: ['In Progress'] } { colorEnd: '#8ac383' colorStart: '#daffd5' id: 'resolved' name: 'Resolved' statusId: 3 statusName: 'Resolved' statuses: ['Resolved'] } { colorEnd: '#f37f7f' colorStart: '#f6d2d2' id: 'removed' name: 'Feedback' statusId: 4 statusName: 'Feedback' statuses: ['Feedback', 'Rejected', 'Blocked'] } ] ticketConfig: nameField: 'author' ticketViewConfig: path: 'tickets' title: 'Tickets' issuesUrl: '/specificissues' remoteFilters: [ {text: 'Key', name: 'key', type: 'password', description: 'Redmine API key'} {text: 'Tickets', name: 'tickets', type: 'text', description: 'Comma separated tickets'} ] columns: [ { colorEnd: '#75a7f1' colorStart: '#d4e3fa' id: 'backlog' name: 'Backlog' statusId: 7 statusName: 'Queued ' statuses: ['New', 'Queued ', 'Groomed ', 'Committed '] } { colorEnd: 'orange' colorStart: '#ffecc8' id: 'inprogress' name: 'In Progress...' statusId: 2 statusName: 'In Progress' statuses: ['In Progress'] } { colorEnd: '#8ac383' colorStart: '#daffd5' id: 'resolved' name: 'Resolved' statusId: 3 statusName: 'Resolved' statuses: ['Resolved'] } { colorEnd: 'lightgrey' colorStart: '#efefef' id: 'closed' name: 'Closed' statusId: 5 statusName: 'Closed' statuses: ['Closed'] } { colorEnd: '#f37f7f' colorStart: '#f6d2d2' id: 'removed' name: 'PI:NAME:<NAME>END_PI' statusId: 4 statusName: 'Feedback' statuses: ['Feedback', 'Rejected', 'Blocked'] } ] ticketConfig: nameField: 'author' navigationItems: [ {path: 'team', template: '<i class="fa fa-users" aria-hidden="true"></i>Team'} {path: 'po', template: '<i class="fa fa-user-secret" aria-hidden="true"></i>PO'} {path: 'developer', template: '<i class="fa fa-laptop" aria-hidden="true"></i>Developer'} {path: 'tickets', template: '<i class="fa fa-ticket" aria-hidden="true"></i>Tickets'} {path: 'unassigned', template: '<i class="fa fa-exclamation-circle" aria-hidden="true"></i>Unassigned'} {path: 'detailed', template: '<i class="fa fa-list-ol" aria-hidden="true"></i>Detailed'} ] detailedViewConfig: issuesUrl: '/specificissues' path: 'detailed' title: 'Detailed' remoteFilters: [ {text: 'Key', name: 'key', type: 'password', description: 'Redmine API key'} {text: 'Tickets', name: 'tickets', type: 'text', description: 'Comma separated tickets'} ] }
[ { "context": "# @author Tim Knip / http://www.floorplanner.com/ / tim at floorplan", "end": 18, "score": 0.9998839497566223, "start": 10, "tag": "NAME", "value": "Tim Knip" }, { "context": "orplanner.com/ / tim at floorplanner.com\n# @author aladjev.andrew@gmail.com\n\nclass Key\n constructor: (time) ->\n @targets ", "end": 110, "score": 0.999925971031189, "start": 86, "tag": "EMAIL", "value": "aladjev.andrew@gmail.com" } ]
source/javascripts/new_src/loaders/collada/key.coffee
andrew-aladev/three.js
0
# @author Tim Knip / http://www.floorplanner.com/ / tim at floorplanner.com # @author aladjev.andrew@gmail.com class Key constructor: (time) -> @targets = [] @time = time addTarget: (fullSid, transform, member, data) -> @targets.push sid: fullSid member: member transform: transform data: data apply: (opt_sid) -> length = @targets.length for i in [0...length] target = @targets[i] if not opt_sid or target.sid is opt_sid target.transform.update target.data, target.member getTarget: (fullSid) -> length = @targets.length for i in [0...length] if @targets[i].sid is fullSid return @targets[i] null hasTarget: (fullSid) -> length = @targets.length for i in [0...length] if @targets[i].sid is fullSid return true false # TODO: Currently only doing linear interpolation. Should support full COLLADA spec interpolate: (nextKey, time) -> length = @targets.length for i in [0...length] target = @targets[i] nextTarget = nextKey.getTarget target.sid if target.transform.type isnt "matrix" and nextTarget scale = (time - @time) / (nextKey.time - @time) nextData = nextTarget.data prevData = target.data # check scale error if scale < 0 or scale > 1 console.warn "Key.interpolate: Warning! Scale out of bounds:", scale if scale < 0 scale = 0 else scale = 1 if prevData.length data = [] prev_length = prevData.length for j in [0...prev_length] data[j] = prevData[j] + (nextData[j] - prevData[j]) * scale else data = prevData + (nextData - prevData) * scale else data = target.data target.transform.update data, target.member namespace "THREE.Collada", (exports) -> exports.Key = Key
18893
# @author <NAME> / http://www.floorplanner.com/ / tim at floorplanner.com # @author <EMAIL> class Key constructor: (time) -> @targets = [] @time = time addTarget: (fullSid, transform, member, data) -> @targets.push sid: fullSid member: member transform: transform data: data apply: (opt_sid) -> length = @targets.length for i in [0...length] target = @targets[i] if not opt_sid or target.sid is opt_sid target.transform.update target.data, target.member getTarget: (fullSid) -> length = @targets.length for i in [0...length] if @targets[i].sid is fullSid return @targets[i] null hasTarget: (fullSid) -> length = @targets.length for i in [0...length] if @targets[i].sid is fullSid return true false # TODO: Currently only doing linear interpolation. Should support full COLLADA spec interpolate: (nextKey, time) -> length = @targets.length for i in [0...length] target = @targets[i] nextTarget = nextKey.getTarget target.sid if target.transform.type isnt "matrix" and nextTarget scale = (time - @time) / (nextKey.time - @time) nextData = nextTarget.data prevData = target.data # check scale error if scale < 0 or scale > 1 console.warn "Key.interpolate: Warning! Scale out of bounds:", scale if scale < 0 scale = 0 else scale = 1 if prevData.length data = [] prev_length = prevData.length for j in [0...prev_length] data[j] = prevData[j] + (nextData[j] - prevData[j]) * scale else data = prevData + (nextData - prevData) * scale else data = target.data target.transform.update data, target.member namespace "THREE.Collada", (exports) -> exports.Key = Key
true
# @author PI:NAME:<NAME>END_PI / http://www.floorplanner.com/ / tim at floorplanner.com # @author PI:EMAIL:<EMAIL>END_PI class Key constructor: (time) -> @targets = [] @time = time addTarget: (fullSid, transform, member, data) -> @targets.push sid: fullSid member: member transform: transform data: data apply: (opt_sid) -> length = @targets.length for i in [0...length] target = @targets[i] if not opt_sid or target.sid is opt_sid target.transform.update target.data, target.member getTarget: (fullSid) -> length = @targets.length for i in [0...length] if @targets[i].sid is fullSid return @targets[i] null hasTarget: (fullSid) -> length = @targets.length for i in [0...length] if @targets[i].sid is fullSid return true false # TODO: Currently only doing linear interpolation. Should support full COLLADA spec interpolate: (nextKey, time) -> length = @targets.length for i in [0...length] target = @targets[i] nextTarget = nextKey.getTarget target.sid if target.transform.type isnt "matrix" and nextTarget scale = (time - @time) / (nextKey.time - @time) nextData = nextTarget.data prevData = target.data # check scale error if scale < 0 or scale > 1 console.warn "Key.interpolate: Warning! Scale out of bounds:", scale if scale < 0 scale = 0 else scale = 1 if prevData.length data = [] prev_length = prevData.length for j in [0...prev_length] data[j] = prevData[j] + (nextData[j] - prevData[j]) * scale else data = prevData + (nextData - prevData) * scale else data = target.data target.transform.update data, target.member namespace "THREE.Collada", (exports) -> exports.Key = Key
[ { "context": " coco which contains:\nmodule.exports = username: 'email@example.com', password: 'your_password'\n3. Run `./node_module", "end": 257, "score": 0.9997571706771851, "start": 240, "tag": "EMAIL", "value": "email@example.com" }, { "context": "ports = username: 'email@example.com', password: 'your_password'\n3. Run `./node_modules/coffee-script/bin/coffee ", "end": 284, "score": 0.9991719126701355, "start": 271, "tag": "PASSWORD", "value": "your_password" }, { "context": "heapdump\nserver = if options.testing then 'http://127.0.0.1:3000' else 'https://codecombat.com'\n# Use direct ", "end": 1617, "score": 0.9996652603149414, "start": 1608, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "'\n\n# Hook node.js require. See https://github.com/mfncooper/mockery/blob/master/mockery.js\n# The signature of", "end": 2987, "score": 0.999671459197998, "start": 2978, "tag": "USERNAME", "value": "mfncooper" }, { "context": "' #should contain an object containing they keys 'username' and 'password'\n\n#Login user and start the code.\n", "end": 4733, "score": 0.995355486869812, "start": 4725, "tag": "USERNAME", "value": "username" } ]
headless_client.coffee
JurianLock/codecombat
1
### This file will simulate games on node.js by emulating the browser environment. In order to use, followed these steps: 1. Setup dev environment as usual 2. Create a `login.coffee` file in coco which contains: module.exports = username: 'email@example.com', password: 'your_password' 3. Run `./node_modules/coffee-script/bin/coffee ./headless_client.coffee` Alternatively, if you wish only to simulate a single game run `coffee ./headless_client.coffee one-game` Or, if you want to always simulate only one game, change the line below this to "true". This takes way more bandwidth. ### simulateOneGame = false if process.argv[2] is 'one-game' #calculate result of one game here simulateOneGame = true console.log "Simulating #{process.argv[3]} vs #{process.argv[4]}" bowerComponentsPath = './bower_components/' headlessClientPath = './headless_client/' # SETTINGS options = workerCode: require headlessClientPath + 'worker_world' debug: false # Enable logging of ajax calls mainly testing: false # Instead of simulating 'real' games, use the same one over and over again. Good for leak hunting. testFile: require headlessClientPath + 'test.js' leakTest: false # Install callback that tries to find leaks automatically exitOnLeak: false # Exit if leak is found. Only useful if leaktest is set to true, obviously. heapdump: false # Dumps the whole heap after every pass. The heap dumps can then be viewed in Chrome browser. headlessClient: true simulateOnlyOneGame: simulateOneGame options.heapdump = require('heapdump') if options.heapdump server = if options.testing then 'http://127.0.0.1:3000' else 'https://codecombat.com' # Use direct instead of live site because jQlone's requests proxy doesn't do caching properly and CloudFlare gets too aggressive. # Disabled modules disable = [ 'lib/AudioPlayer' 'locale/locale' '../locale/locale' ] # Start of the actual code. Setting up the enivronment to match the environment of the browser # Global emulated stuff GLOBAL.window = GLOBAL GLOBAL.document = location: pathname: 'headless_client' GLOBAL.console.debug = console.log try GLOBAL.Worker = require('webworker-threads').Worker catch console.log "" console.log "Headless client needs the webworker-threads package from NPM to function." console.log "Try installing it with the command:" console.log "" console.log " npm install webworker-threads" console.log "" process.exit(1) Worker::removeEventListener = (what) -> if what is 'message' @onmessage = -> #This webworker api has only one event listener at a time. GLOBAL.tv4 = require('tv4').tv4 GLOBAL.TreemaUtils = require bowerComponentsPath + 'treema/treema-utils' GLOBAL.marked = setOptions: -> store = {} GLOBAL.localStorage = getItem: (key) => store[key] setItem: (key, s) => store[key] = s removeItem: (key) => delete store[key] GLOBAL.lscache = require bowerComponentsPath + 'lscache/lscache' # Hook node.js require. See https://github.com/mfncooper/mockery/blob/master/mockery.js # The signature of this function *must* match that of Node's Module._load, # since it will replace that. # (Why is there no easier way?) # the path used for the loader. __dirname is module dependent. path = __dirname m = require 'module' originalLoader = m._load hookedLoader = (request, parent, isMain) -> if request in disable or ~request.indexOf('templates') console.log 'Ignored ' + request if options.debug return class fake else if /node_modules[\\\/]aether[\\\/]/.test parent.id null # Let it through else if '/' in request and not (request[0] is '.') or request is 'application' #console.log 'making path', path + '/app/' + request, 'from', path, request, 'with parent', parent request = path + '/app/' + request else if request is 'underscore' request = 'lodash' console.log 'loading ' + request if options.debug originalLoader request, parent, isMain unhook = () -> m._load = originalLoader hook = () -> m._load = hookedLoader GLOBAL.$ = GLOBAL.jQuery = require headlessClientPath + 'jQlone' $._debug = options.debug $._server = server do (setupLodash = this) -> GLOBAL._ = require 'lodash' _.str = require 'underscore.string' _.string = _.str _.mixin _.str.exports() # load Backbone. Needs hooked loader to reroute underscore to lodash. hook() GLOBAL.Backbone = require bowerComponentsPath + 'backbone/backbone' # Use original loader for theese unhook() Backbone.$ = $ require bowerComponentsPath + 'validated-backbone-mediator/backbone-mediator' Backbone.Mediator.setValidationEnabled false GLOBAL.Aether = require 'aether' # Set up new loader. Again. hook() login = require './login.coffee' #should contain an object containing they keys 'username' and 'password' #Login user and start the code. $.ajax url: '/auth/login' type: 'POST' data: login parse: true error: (error) -> 'Bad Error. Can\'t connect to server or something. ' + error success: (response, textStatus, jqXHR) -> console.log 'User: ', response if options.debug unless jqXHR.status is 200 console.log 'User not authenticated. Status code: ', jqXHR.status return GLOBAL.window.userObject = response # JSON.parse response Simulator = require 'lib/simulator/Simulator' sim = new Simulator options if simulateOneGame sim.fetchAndSimulateOneGame(process.argv[3],process.argv[4]) else sim.fetchAndSimulateTask()
116459
### This file will simulate games on node.js by emulating the browser environment. In order to use, followed these steps: 1. Setup dev environment as usual 2. Create a `login.coffee` file in coco which contains: module.exports = username: '<EMAIL>', password: '<PASSWORD>' 3. Run `./node_modules/coffee-script/bin/coffee ./headless_client.coffee` Alternatively, if you wish only to simulate a single game run `coffee ./headless_client.coffee one-game` Or, if you want to always simulate only one game, change the line below this to "true". This takes way more bandwidth. ### simulateOneGame = false if process.argv[2] is 'one-game' #calculate result of one game here simulateOneGame = true console.log "Simulating #{process.argv[3]} vs #{process.argv[4]}" bowerComponentsPath = './bower_components/' headlessClientPath = './headless_client/' # SETTINGS options = workerCode: require headlessClientPath + 'worker_world' debug: false # Enable logging of ajax calls mainly testing: false # Instead of simulating 'real' games, use the same one over and over again. Good for leak hunting. testFile: require headlessClientPath + 'test.js' leakTest: false # Install callback that tries to find leaks automatically exitOnLeak: false # Exit if leak is found. Only useful if leaktest is set to true, obviously. heapdump: false # Dumps the whole heap after every pass. The heap dumps can then be viewed in Chrome browser. headlessClient: true simulateOnlyOneGame: simulateOneGame options.heapdump = require('heapdump') if options.heapdump server = if options.testing then 'http://127.0.0.1:3000' else 'https://codecombat.com' # Use direct instead of live site because jQlone's requests proxy doesn't do caching properly and CloudFlare gets too aggressive. # Disabled modules disable = [ 'lib/AudioPlayer' 'locale/locale' '../locale/locale' ] # Start of the actual code. Setting up the enivronment to match the environment of the browser # Global emulated stuff GLOBAL.window = GLOBAL GLOBAL.document = location: pathname: 'headless_client' GLOBAL.console.debug = console.log try GLOBAL.Worker = require('webworker-threads').Worker catch console.log "" console.log "Headless client needs the webworker-threads package from NPM to function." console.log "Try installing it with the command:" console.log "" console.log " npm install webworker-threads" console.log "" process.exit(1) Worker::removeEventListener = (what) -> if what is 'message' @onmessage = -> #This webworker api has only one event listener at a time. GLOBAL.tv4 = require('tv4').tv4 GLOBAL.TreemaUtils = require bowerComponentsPath + 'treema/treema-utils' GLOBAL.marked = setOptions: -> store = {} GLOBAL.localStorage = getItem: (key) => store[key] setItem: (key, s) => store[key] = s removeItem: (key) => delete store[key] GLOBAL.lscache = require bowerComponentsPath + 'lscache/lscache' # Hook node.js require. See https://github.com/mfncooper/mockery/blob/master/mockery.js # The signature of this function *must* match that of Node's Module._load, # since it will replace that. # (Why is there no easier way?) # the path used for the loader. __dirname is module dependent. path = __dirname m = require 'module' originalLoader = m._load hookedLoader = (request, parent, isMain) -> if request in disable or ~request.indexOf('templates') console.log 'Ignored ' + request if options.debug return class fake else if /node_modules[\\\/]aether[\\\/]/.test parent.id null # Let it through else if '/' in request and not (request[0] is '.') or request is 'application' #console.log 'making path', path + '/app/' + request, 'from', path, request, 'with parent', parent request = path + '/app/' + request else if request is 'underscore' request = 'lodash' console.log 'loading ' + request if options.debug originalLoader request, parent, isMain unhook = () -> m._load = originalLoader hook = () -> m._load = hookedLoader GLOBAL.$ = GLOBAL.jQuery = require headlessClientPath + 'jQlone' $._debug = options.debug $._server = server do (setupLodash = this) -> GLOBAL._ = require 'lodash' _.str = require 'underscore.string' _.string = _.str _.mixin _.str.exports() # load Backbone. Needs hooked loader to reroute underscore to lodash. hook() GLOBAL.Backbone = require bowerComponentsPath + 'backbone/backbone' # Use original loader for theese unhook() Backbone.$ = $ require bowerComponentsPath + 'validated-backbone-mediator/backbone-mediator' Backbone.Mediator.setValidationEnabled false GLOBAL.Aether = require 'aether' # Set up new loader. Again. hook() login = require './login.coffee' #should contain an object containing they keys 'username' and 'password' #Login user and start the code. $.ajax url: '/auth/login' type: 'POST' data: login parse: true error: (error) -> 'Bad Error. Can\'t connect to server or something. ' + error success: (response, textStatus, jqXHR) -> console.log 'User: ', response if options.debug unless jqXHR.status is 200 console.log 'User not authenticated. Status code: ', jqXHR.status return GLOBAL.window.userObject = response # JSON.parse response Simulator = require 'lib/simulator/Simulator' sim = new Simulator options if simulateOneGame sim.fetchAndSimulateOneGame(process.argv[3],process.argv[4]) else sim.fetchAndSimulateTask()
true
### This file will simulate games on node.js by emulating the browser environment. In order to use, followed these steps: 1. Setup dev environment as usual 2. Create a `login.coffee` file in coco which contains: module.exports = username: 'PI:EMAIL:<EMAIL>END_PI', password: 'PI:PASSWORD:<PASSWORD>END_PI' 3. Run `./node_modules/coffee-script/bin/coffee ./headless_client.coffee` Alternatively, if you wish only to simulate a single game run `coffee ./headless_client.coffee one-game` Or, if you want to always simulate only one game, change the line below this to "true". This takes way more bandwidth. ### simulateOneGame = false if process.argv[2] is 'one-game' #calculate result of one game here simulateOneGame = true console.log "Simulating #{process.argv[3]} vs #{process.argv[4]}" bowerComponentsPath = './bower_components/' headlessClientPath = './headless_client/' # SETTINGS options = workerCode: require headlessClientPath + 'worker_world' debug: false # Enable logging of ajax calls mainly testing: false # Instead of simulating 'real' games, use the same one over and over again. Good for leak hunting. testFile: require headlessClientPath + 'test.js' leakTest: false # Install callback that tries to find leaks automatically exitOnLeak: false # Exit if leak is found. Only useful if leaktest is set to true, obviously. heapdump: false # Dumps the whole heap after every pass. The heap dumps can then be viewed in Chrome browser. headlessClient: true simulateOnlyOneGame: simulateOneGame options.heapdump = require('heapdump') if options.heapdump server = if options.testing then 'http://127.0.0.1:3000' else 'https://codecombat.com' # Use direct instead of live site because jQlone's requests proxy doesn't do caching properly and CloudFlare gets too aggressive. # Disabled modules disable = [ 'lib/AudioPlayer' 'locale/locale' '../locale/locale' ] # Start of the actual code. Setting up the enivronment to match the environment of the browser # Global emulated stuff GLOBAL.window = GLOBAL GLOBAL.document = location: pathname: 'headless_client' GLOBAL.console.debug = console.log try GLOBAL.Worker = require('webworker-threads').Worker catch console.log "" console.log "Headless client needs the webworker-threads package from NPM to function." console.log "Try installing it with the command:" console.log "" console.log " npm install webworker-threads" console.log "" process.exit(1) Worker::removeEventListener = (what) -> if what is 'message' @onmessage = -> #This webworker api has only one event listener at a time. GLOBAL.tv4 = require('tv4').tv4 GLOBAL.TreemaUtils = require bowerComponentsPath + 'treema/treema-utils' GLOBAL.marked = setOptions: -> store = {} GLOBAL.localStorage = getItem: (key) => store[key] setItem: (key, s) => store[key] = s removeItem: (key) => delete store[key] GLOBAL.lscache = require bowerComponentsPath + 'lscache/lscache' # Hook node.js require. See https://github.com/mfncooper/mockery/blob/master/mockery.js # The signature of this function *must* match that of Node's Module._load, # since it will replace that. # (Why is there no easier way?) # the path used for the loader. __dirname is module dependent. path = __dirname m = require 'module' originalLoader = m._load hookedLoader = (request, parent, isMain) -> if request in disable or ~request.indexOf('templates') console.log 'Ignored ' + request if options.debug return class fake else if /node_modules[\\\/]aether[\\\/]/.test parent.id null # Let it through else if '/' in request and not (request[0] is '.') or request is 'application' #console.log 'making path', path + '/app/' + request, 'from', path, request, 'with parent', parent request = path + '/app/' + request else if request is 'underscore' request = 'lodash' console.log 'loading ' + request if options.debug originalLoader request, parent, isMain unhook = () -> m._load = originalLoader hook = () -> m._load = hookedLoader GLOBAL.$ = GLOBAL.jQuery = require headlessClientPath + 'jQlone' $._debug = options.debug $._server = server do (setupLodash = this) -> GLOBAL._ = require 'lodash' _.str = require 'underscore.string' _.string = _.str _.mixin _.str.exports() # load Backbone. Needs hooked loader to reroute underscore to lodash. hook() GLOBAL.Backbone = require bowerComponentsPath + 'backbone/backbone' # Use original loader for theese unhook() Backbone.$ = $ require bowerComponentsPath + 'validated-backbone-mediator/backbone-mediator' Backbone.Mediator.setValidationEnabled false GLOBAL.Aether = require 'aether' # Set up new loader. Again. hook() login = require './login.coffee' #should contain an object containing they keys 'username' and 'password' #Login user and start the code. $.ajax url: '/auth/login' type: 'POST' data: login parse: true error: (error) -> 'Bad Error. Can\'t connect to server or something. ' + error success: (response, textStatus, jqXHR) -> console.log 'User: ', response if options.debug unless jqXHR.status is 200 console.log 'User not authenticated. Status code: ', jqXHR.status return GLOBAL.window.userObject = response # JSON.parse response Simulator = require 'lib/simulator/Simulator' sim = new Simulator options if simulateOneGame sim.fetchAndSimulateOneGame(process.argv[3],process.argv[4]) else sim.fetchAndSimulateTask()
[ { "context": "\n equal Posts.first().getAuthor().get('jid'), 'joe@diaspora-x.com'\n", "end": 375, "score": 0.9999242424964905, "start": 357, "tag": "EMAIL", "value": "joe@diaspora-x.com" } ]
test/models/post_test.coffee
bnolan/diaspora-x2
7
runTests -> module('post model'); new PostFixtures test 'model exists', -> ok(Post) test 'getName()', -> ok(true) test "isReply()", -> ok Posts.first().isReply() test 'getAuthor()', -> ok Posts.first().getAuthor() ok(Posts.first().getAuthor() instanceof User) equal Posts.first().getAuthor().get('jid'), 'joe@diaspora-x.com'
2882
runTests -> module('post model'); new PostFixtures test 'model exists', -> ok(Post) test 'getName()', -> ok(true) test "isReply()", -> ok Posts.first().isReply() test 'getAuthor()', -> ok Posts.first().getAuthor() ok(Posts.first().getAuthor() instanceof User) equal Posts.first().getAuthor().get('jid'), '<EMAIL>'
true
runTests -> module('post model'); new PostFixtures test 'model exists', -> ok(Post) test 'getName()', -> ok(true) test "isReply()", -> ok Posts.first().isReply() test 'getAuthor()', -> ok Posts.first().getAuthor() ok(Posts.first().getAuthor() instanceof User) equal Posts.first().getAuthor().get('jid'), 'PI:EMAIL:<EMAIL>END_PI'
[ { "context": "\t\t\ticon: 'users'\n\t\t\ttableColumns: [\n\t\t\t\t{ label: 'First Name', name: 'first_name' }\n\t\t\t\t{ label: 'Last Name', ", "end": 134, "score": 0.9746434688568115, "start": 124, "tag": "NAME", "value": "First Name" }, { "context": "tableColumns: [\n\t\t\t\t{ label: 'First Name', name: 'first_name' }\n\t\t\t\t{ label: 'Last Name', name: 'last_name' }\n", "end": 154, "score": 0.9311006665229797, "start": 144, "tag": "NAME", "value": "first_name" }, { "context": " 'First Name', name: 'first_name' }\n\t\t\t\t{ label: 'Last Name', name: 'last_name' }\n\t\t\t\t{ label: 'Phone Number'", "end": 181, "score": 0.9874207973480225, "start": 172, "tag": "NAME", "value": "Last Name" }, { "context": ": 'first_name' }\n\t\t\t\t{ label: 'Last Name', name: 'last_name' }\n\t\t\t\t{ label: 'Phone Number', name: 'phone_numb", "end": 200, "score": 0.9681839942932129, "start": 191, "tag": "NAME", "value": "last_name" } ]
lib/_config/admin_config.coffee
niinyarko/retail-pay
0
@AdminConfig = name: Config.name collections: Payees: color: 'red' icon: 'users' tableColumns: [ { label: 'First Name', name: 'first_name' } { label: 'Last Name', name: 'last_name' } { label: 'Phone Number', name: 'phone_number' } ] Transactions: color: 'green' icon: 'money' tableColumns: [ { label: 'Payee', name: 'payee_name' } { label: 'Amount Paid', name: 'amount' } { label: 'Transaction Date', name: 'createdAt'} ] templates: new: name: 'createTransaction' PettyCashFund: color: 'yellow' icon: 'money' tableColumns: [ { label: 'Amount (GHS)', name: 'amount' } { label: 'Created At', name: 'createdAt'} { label: 'Updated At', name: 'updatedAt' } ] dashboard: homeUrl: '/dashboard', autoForm: omitFields: ['createdAt', 'updatedAt']
209041
@AdminConfig = name: Config.name collections: Payees: color: 'red' icon: 'users' tableColumns: [ { label: '<NAME>', name: '<NAME>' } { label: '<NAME>', name: '<NAME>' } { label: 'Phone Number', name: 'phone_number' } ] Transactions: color: 'green' icon: 'money' tableColumns: [ { label: 'Payee', name: 'payee_name' } { label: 'Amount Paid', name: 'amount' } { label: 'Transaction Date', name: 'createdAt'} ] templates: new: name: 'createTransaction' PettyCashFund: color: 'yellow' icon: 'money' tableColumns: [ { label: 'Amount (GHS)', name: 'amount' } { label: 'Created At', name: 'createdAt'} { label: 'Updated At', name: 'updatedAt' } ] dashboard: homeUrl: '/dashboard', autoForm: omitFields: ['createdAt', 'updatedAt']
true
@AdminConfig = name: Config.name collections: Payees: color: 'red' icon: 'users' tableColumns: [ { label: 'PI:NAME:<NAME>END_PI', name: 'PI:NAME:<NAME>END_PI' } { label: 'PI:NAME:<NAME>END_PI', name: 'PI:NAME:<NAME>END_PI' } { label: 'Phone Number', name: 'phone_number' } ] Transactions: color: 'green' icon: 'money' tableColumns: [ { label: 'Payee', name: 'payee_name' } { label: 'Amount Paid', name: 'amount' } { label: 'Transaction Date', name: 'createdAt'} ] templates: new: name: 'createTransaction' PettyCashFund: color: 'yellow' icon: 'money' tableColumns: [ { label: 'Amount (GHS)', name: 'amount' } { label: 'Created At', name: 'createdAt'} { label: 'Updated At', name: 'updatedAt' } ] dashboard: homeUrl: '/dashboard', autoForm: omitFields: ['createdAt', 'updatedAt']
[ { "context": "efix: \"s-user-add-hash\"\n\t\tbody: \"CREATE USER '${1:username}'@'${2:localhost}' IDENTIFIED BY PASSWORD '*832EB", "end": 169, "score": 0.5402026176452637, "start": 161, "tag": "USERNAME", "value": "username" }, { "context": "username}'@'${2:localhost}' IDENTIFIED BY PASSWORD '*832EB84CB764129D05D498ED9CA7E5CE9B8F83EB';$0\"\n", "end": 254, "score": 0.9911258220672607, "start": 212, "tag": "PASSWORD", "value": "'*832EB84CB764129D05D498ED9CA7E5CE9B8F83EB" }, { "context": "WORD '*832EB84CB764129D05D498ED9CA7E5CE9B8F83EB';$0\"\n", "end": 258, "score": 0.5210456848144531, "start": 257, "tag": "PASSWORD", "value": "0" } ]
snippets/sql-user-add-hash.cson
cliffordfajardo/mysql-snippets
1
# Generated with Atomizr – https://atom.io/packages/atomizr ".source.sql": "(new user, hashed password)": prefix: "s-user-add-hash" body: "CREATE USER '${1:username}'@'${2:localhost}' IDENTIFIED BY PASSWORD '*832EB84CB764129D05D498ED9CA7E5CE9B8F83EB';$0"
70431
# Generated with Atomizr – https://atom.io/packages/atomizr ".source.sql": "(new user, hashed password)": prefix: "s-user-add-hash" body: "CREATE USER '${1:username}'@'${2:localhost}' IDENTIFIED BY PASSWORD <PASSWORD>';$<PASSWORD>"
true
# Generated with Atomizr – https://atom.io/packages/atomizr ".source.sql": "(new user, hashed password)": prefix: "s-user-add-hash" body: "CREATE USER '${1:username}'@'${2:localhost}' IDENTIFIED BY PASSWORD PI:PASSWORD:<PASSWORD>END_PI';$PI:PASSWORD:<PASSWORD>END_PI"
[ { "context": "###\nCC JS Helpers\n\nCopyright (c) 2015 Scott Yang\n\nDependencies:\nCC Core (cc.core.js)\njQuery (Ver 1", "end": 48, "score": 0.9996463656425476, "start": 38, "tag": "NAME", "value": "Scott Yang" } ]
public/core/js/cc.helpers.coffee
yisyang/loves_money
1
### CC JS Helpers Copyright (c) 2015 Scott Yang Dependencies: CC Core (cc.core.js) jQuery (Ver 1.11+) ### ((global) -> "use strict" ### Verify that CSS file is loaded and alternatively load from local source @param {String} filename File name of remotely loaded CSS @param {String} localpath Local path of css file Example: CC = new CarCrashSingletonClass({foo: 'bar'}) CC.verifyCssRequire('some.css.file.css', '/vendor/somewhere/some.css.file.css') ### global.CarCrashSingletonClass::verifyCssRequire = (filename, localpath) -> $.each document.styleSheets, (i, sheet) -> if sheet.href.substring(0 - filename.length) is filename rules = (if sheet.rules then sheet.rules else sheet.cssRules) if rules.length is 0 $("<link />") .attr( rel: "stylesheet" type: "text/css" href: localpath ) .appendTo("head") return return return ) window
226192
### CC JS Helpers Copyright (c) 2015 <NAME> Dependencies: CC Core (cc.core.js) jQuery (Ver 1.11+) ### ((global) -> "use strict" ### Verify that CSS file is loaded and alternatively load from local source @param {String} filename File name of remotely loaded CSS @param {String} localpath Local path of css file Example: CC = new CarCrashSingletonClass({foo: 'bar'}) CC.verifyCssRequire('some.css.file.css', '/vendor/somewhere/some.css.file.css') ### global.CarCrashSingletonClass::verifyCssRequire = (filename, localpath) -> $.each document.styleSheets, (i, sheet) -> if sheet.href.substring(0 - filename.length) is filename rules = (if sheet.rules then sheet.rules else sheet.cssRules) if rules.length is 0 $("<link />") .attr( rel: "stylesheet" type: "text/css" href: localpath ) .appendTo("head") return return return ) window
true
### CC JS Helpers Copyright (c) 2015 PI:NAME:<NAME>END_PI Dependencies: CC Core (cc.core.js) jQuery (Ver 1.11+) ### ((global) -> "use strict" ### Verify that CSS file is loaded and alternatively load from local source @param {String} filename File name of remotely loaded CSS @param {String} localpath Local path of css file Example: CC = new CarCrashSingletonClass({foo: 'bar'}) CC.verifyCssRequire('some.css.file.css', '/vendor/somewhere/some.css.file.css') ### global.CarCrashSingletonClass::verifyCssRequire = (filename, localpath) -> $.each document.styleSheets, (i, sheet) -> if sheet.href.substring(0 - filename.length) is filename rules = (if sheet.rules then sheet.rules else sheet.cssRules) if rules.length is 0 $("<link />") .attr( rel: "stylesheet" type: "text/css" href: localpath ) .appendTo("head") return return return ) window
[ { "context": "->\n beforeEach ->\n @getCurrentUser.resolve(@user)\n\n describe \"general behavior\", ->\n b", "end": 1665, "score": 0.7301507592201233, "start": 1665, "tag": "USERNAME", "value": "" }, { "context": "([{\n \"id\": \"000\",\n \"name\": \"Jane Lane\",\n \"default\": true\n }])\n ", "end": 5617, "score": 0.9997020363807678, "start": 5608, "tag": "NAME", "value": "Jane Lane" }, { "context": "n list on successful poll\", ->\n @name = \"Foo Bar Devs\"\n @orgs[0].name = @name\n @getOr", "end": 6685, "score": 0.9458680152893066, "start": 6673, "tag": "NAME", "value": "Foo Bar Devs" }, { "context": " \"id\": \"333\",\n \"name\": \"Ivory Developers\",\n \"default\": false\n })\n ", "end": 7043, "score": 0.9991732239723206, "start": 7027, "tag": "NAME", "value": "Ivory Developers" }, { "context": "ach ->\n cy.stub(@ipc, \"beginAuth\").resolves(@user)\n cy.contains(\"button\", \"Log In to Dashboa", "end": 12297, "score": 0.9993444085121155, "start": 12292, "tag": "USERNAME", "value": "@user" } ]
packages/desktop-gui/cypress/integration/setup_project_modal_spec.coffee
zacharoth/cypress
0
describe "Set Up Project", -> beforeEach -> cy.fixture("user").as("user") cy.fixture("projects").as("projects") cy.fixture("projects_statuses").as("projectStatuses") cy.fixture("config").as("config") cy.fixture("specs").as("specs") cy.fixture("organizations").as("orgs") cy.fixture("keys").as("keys") cy.visitIndex().then (win) -> { start, @ipc } = win.App @config.projectName = "my-kitchen-sink" cy.stub(@ipc, "getOptions").resolves({projectRoot: "/foo/bar"}) cy.stub(@ipc, "updaterCheck").resolves(false) cy.stub(@ipc, "closeBrowser").resolves(null) @config.projectId = null cy.stub(@ipc, "openProject").resolves(@config) cy.stub(@ipc, "getSpecs").yields(null, @specs) cy.stub(@ipc, "getRuns").resolves([]) cy.stub(@ipc, "getRecordKeys").resolves(@keys) cy.stub(@ipc, "pingApiServer").resolves() cy.stub(@ipc, "externalOpen") @getCurrentUser = @util.deferred() cy.stub(@ipc, "getCurrentUser").resolves(@getCurrentUser.promise) @getOrgs = @util.deferred() cy.stub(@ipc, "getOrgs").returns(@getOrgs.promise) @getProjectStatus = @util.deferred() cy.stub(@ipc, "getProjectStatus").returns(@getProjectStatus.promise) @setupDashboardProject = @util.deferred() cy.stub(@ipc, "setupDashboardProject").returns(@setupDashboardProject.promise) start() cy.get(".navbar-default a") .contains("Runs").click() it "displays 'need to set up' message", -> cy.contains("You have no recorded runs") describe "when there is a current user", -> beforeEach -> @getCurrentUser.resolve(@user) describe "general behavior", -> beforeEach -> @getOrgs.resolve(@orgs) cy.get(".btn").contains("Set up project").click() it "clicking link opens setup project window", -> cy.get(".modal").should("be.visible") it "submit button is disabled", -> cy.get(".modal").contains(".btn", "Set up project") .should("be.disabled") it "prefills Project Name", -> cy.get("#projectName").should("have.value", @config.projectName) it "allows me to change Project Name value", -> cy.get("#projectName").clear().type("New Project Here") .should("have.value", "New Project Here") describe "default owner", -> it "has no owner selected by default", -> cy.get("#me").should("not.be.selected") cy.get("#org").should("not.be.selected") it "org docs are linked", -> cy.contains("label", "Who should own this") .find("a").click().then -> expect(@ipc.externalOpen).to.be.calledWith("https://on.cypress.io/what-are-organizations") describe "selecting me as owner", -> beforeEach -> cy.get(".privacy-radio").should("not.be.visible") cy.get(".modal-content") .contains(".btn", "Me").click() it "access docs are linked", -> cy.contains("label", "Who should see the runs") .find("a").click().then -> expect(@ipc.externalOpen).to.be.calledWith("https://on.cypress.io/what-is-project-access") it "displays public & private radios with no preselects", -> cy.get(".privacy-radio").should("be.visible") .find("input").should("not.be.checked") describe "selecting an org", -> context "with orgs", -> beforeEach -> @getOrgs.resolve(@orgs) cy.get(".btn").contains("Set up project").click() cy.get(".modal-content") .contains(".btn", "An Organization").click() it "lists organizations to assign to project", -> cy.get("#organizations-select").find("option") .should("have.length", @orgs.length) it "selects none by default", -> cy.get("#organizations-select").should("have.value", "") it "opens external link on click of manage", -> cy.get(".manage-orgs-btn").click().then -> expect(@ipc.externalOpen).to.be.calledWith("https://on.cypress.io/dashboard/organizations") it "displays public & private radios on select", -> cy.get(".privacy-radio").should("not.be.visible") cy.get("select").select("Acme Developers") cy.get(".privacy-radio").should("be.visible") .find("input").should("not.be.checked") it "clears selections when switching back to Me", -> cy.get("select").select("Acme Developers") cy.get(".privacy-radio") .find("input").first().check() cy.get(".btn").contains("Me").click() cy.get(".privacy-radio").find("input").should("not.be.checked") cy.get(".btn").contains("An Organization").click() cy.get("#organizations-select").should("have.value", "") context "without orgs", -> beforeEach -> @getOrgs.resolve([]) cy.get(".btn").contains("Set up project").click() cy.get(".modal-content") .contains(".btn", "An Organization").click() it "displays empty message", -> cy.get(".empty-select-orgs").should("be.visible") it "opens dashboard organizations when 'create org' is clicked", -> cy.contains("Create organization").click().then -> expect(@ipc.externalOpen).to.be.calledWith("https://on.cypress.io/dashboard/organizations") context "without only default org", -> beforeEach -> @getOrgs.resolve([{ "id": "000", "name": "Jane Lane", "default": true }]) cy.get(".btn").contains("Set up project").click() cy.get(".modal-content") .contains(".btn", "An Organization").click() it "displays empty message", -> cy.get(".empty-select-orgs").should("be.visible") it "opens dashboard organizations when 'create org' is clicked", -> cy.contains("Create organization").click().then -> expect(@ipc.externalOpen).to.be.calledWith("https://on.cypress.io/dashboard/organizations") context "polls for updates to organizations", -> beforeEach -> cy.clock() @getOrgs.resolve(@orgs) cy.get(".btn").contains("Set up project").click() cy.get(".modal-content") .contains(".btn", "An Organization").click() it "polls for orgs twice in 10+sec on click of org", -> cy.tick(11000).then => expect(@ipc.getOrgs).to.be.calledTwice it "updates org name on list on successful poll", -> @name = "Foo Bar Devs" @orgs[0].name = @name @getOrgsAgain = @ipc.getOrgs.onCall(2).resolves(@orgs) cy.tick(11000) cy.get("#organizations-select").find("option") .contains(@name) it "adds new org to list on successful poll", -> @orgs.push({ "id": "333", "name": "Ivory Developers", "default": false }) @getOrgsAgain = @ipc.getOrgs.onCall(2).resolves(@orgs) cy.tick(11000) cy.get("#organizations-select").find("option") .should('have.length', @orgs.length) describe "on submit", -> beforeEach -> @getOrgs.resolve(@orgs) cy.contains(".btn", "Set up project").click() cy.get(".modal-body") .contains(".btn", "Me").click() cy.get(".privacy-radio").find("input").last().check() cy.get(".modal-body") .contains(".btn", "Set up project").click() it "disables button", -> cy.get(".modal-body") .contains(".btn", "Set up project") .should("be.disabled") it "shows spinner", -> cy.get(".modal-body") .contains(".btn", "Set up project") .find("i") .should("be.visible") describe "successfully submit form", -> beforeEach -> @getOrgs.resolve(@orgs) @setupDashboardProject.resolve({ id: "project-id-123" public: true orgId: "000" }) cy.contains(".btn", "Set up project").click() it "sends project name, org id, and public flag to ipc event", -> cy.get(".modal-body") .contains(".btn", "An Organization").click() cy.get("#projectName").clear().type("New Project") cy.get("select").select("Acme Developers") cy.get(".privacy-radio").find("input").first().check() cy.get(".modal-body") .contains(".btn", "Set up project").click() .then => expect(@ipc.setupDashboardProject).to.be.calledWith({ projectName: "New Project" orgId: "777" public: true }) context "org/public", -> beforeEach -> cy.get(".modal-body") .contains(".btn", "An Organization").click() cy.get("select").select("Acme Developers") cy.get(".privacy-radio").find("input").first().check() cy.get(".modal-body") .contains(".btn", "Set up project").click() it "sends data from form to ipc event", -> expect(@ipc.setupDashboardProject).to.be.calledWith({ projectName: @config.projectName orgId: "777" public: true }) context "me/private", -> beforeEach -> cy.get(".modal-body") .contains(".btn", "Me").click() cy.get(".privacy-radio").find("input").last().check() cy.get(".modal-body") .contains(".btn", "Set up project").click() it "sends data from form to ipc event", -> expect(@ipc.setupDashboardProject).to.be.calledWith({ projectName: @config.projectName orgId: "000" public: false }) context "me/public", -> beforeEach -> cy.get(".modal-body") .contains(".btn", "Me").click() cy.get(".privacy-radio").find("input").first().check() cy.get(".modal-body") .contains(".btn", "Set up project").click() it "sends data from form to ipc event", -> expect(@ipc.setupDashboardProject).to.be.calledWith({ projectName: @config.projectName orgId: "000" public: true }) it "closes modal", -> cy.get(".modal").should("not.be.visible") it "updates localStorage projects cache", -> expect(JSON.parse(localStorage.projects || "[]")[0].orgName).to.equal("Jane Lane") it "displays empty runs page", -> cy.contains("To record your first") it "displays command to run with the record key", -> cy.contains("cypress run --record --key record-key-123") describe "errors", -> beforeEach -> @getOrgs.resolve(@orgs) cy.contains(".btn", "Set up project").click() cy.get(".modal-body") .contains(".btn", "Me").click() cy.get(".privacy-radio").find("input").last().check() cy.get(".modal-body") .contains(".btn", "Set up project").click() it "logs user out when 401", -> @setupDashboardProject.reject({ name: "", message: "", statusCode: 401 }) cy.shouldBeLoggedOut() it "displays error name and message when unexpected", -> @setupDashboardProject.reject({ name: "Fatal Error!" message: """ { "system": "down", "toxicity": "of the city" } """ }) cy.contains('"system": "down"') describe "when get orgs 401s", -> beforeEach -> cy.contains(".btn", "Set up project").click() .then => @getOrgs.reject({ name: "", message: "", statusCode: 401 }) it "logs user out", -> cy.shouldBeLoggedOut() describe "when there is no current user", -> beforeEach -> @getCurrentUser.resolve(null) cy.get(".btn").contains("Set up project").click() it "shows login", -> cy.get(".modal").contains("Log In to Dashboard") describe "when login succeeds", -> beforeEach -> cy.stub(@ipc, "beginAuth").resolves(@user) cy.contains("button", "Log In to Dashboard").click() it "shows setup", -> cy.contains("h4", "Set up project")
180006
describe "Set Up Project", -> beforeEach -> cy.fixture("user").as("user") cy.fixture("projects").as("projects") cy.fixture("projects_statuses").as("projectStatuses") cy.fixture("config").as("config") cy.fixture("specs").as("specs") cy.fixture("organizations").as("orgs") cy.fixture("keys").as("keys") cy.visitIndex().then (win) -> { start, @ipc } = win.App @config.projectName = "my-kitchen-sink" cy.stub(@ipc, "getOptions").resolves({projectRoot: "/foo/bar"}) cy.stub(@ipc, "updaterCheck").resolves(false) cy.stub(@ipc, "closeBrowser").resolves(null) @config.projectId = null cy.stub(@ipc, "openProject").resolves(@config) cy.stub(@ipc, "getSpecs").yields(null, @specs) cy.stub(@ipc, "getRuns").resolves([]) cy.stub(@ipc, "getRecordKeys").resolves(@keys) cy.stub(@ipc, "pingApiServer").resolves() cy.stub(@ipc, "externalOpen") @getCurrentUser = @util.deferred() cy.stub(@ipc, "getCurrentUser").resolves(@getCurrentUser.promise) @getOrgs = @util.deferred() cy.stub(@ipc, "getOrgs").returns(@getOrgs.promise) @getProjectStatus = @util.deferred() cy.stub(@ipc, "getProjectStatus").returns(@getProjectStatus.promise) @setupDashboardProject = @util.deferred() cy.stub(@ipc, "setupDashboardProject").returns(@setupDashboardProject.promise) start() cy.get(".navbar-default a") .contains("Runs").click() it "displays 'need to set up' message", -> cy.contains("You have no recorded runs") describe "when there is a current user", -> beforeEach -> @getCurrentUser.resolve(@user) describe "general behavior", -> beforeEach -> @getOrgs.resolve(@orgs) cy.get(".btn").contains("Set up project").click() it "clicking link opens setup project window", -> cy.get(".modal").should("be.visible") it "submit button is disabled", -> cy.get(".modal").contains(".btn", "Set up project") .should("be.disabled") it "prefills Project Name", -> cy.get("#projectName").should("have.value", @config.projectName) it "allows me to change Project Name value", -> cy.get("#projectName").clear().type("New Project Here") .should("have.value", "New Project Here") describe "default owner", -> it "has no owner selected by default", -> cy.get("#me").should("not.be.selected") cy.get("#org").should("not.be.selected") it "org docs are linked", -> cy.contains("label", "Who should own this") .find("a").click().then -> expect(@ipc.externalOpen).to.be.calledWith("https://on.cypress.io/what-are-organizations") describe "selecting me as owner", -> beforeEach -> cy.get(".privacy-radio").should("not.be.visible") cy.get(".modal-content") .contains(".btn", "Me").click() it "access docs are linked", -> cy.contains("label", "Who should see the runs") .find("a").click().then -> expect(@ipc.externalOpen).to.be.calledWith("https://on.cypress.io/what-is-project-access") it "displays public & private radios with no preselects", -> cy.get(".privacy-radio").should("be.visible") .find("input").should("not.be.checked") describe "selecting an org", -> context "with orgs", -> beforeEach -> @getOrgs.resolve(@orgs) cy.get(".btn").contains("Set up project").click() cy.get(".modal-content") .contains(".btn", "An Organization").click() it "lists organizations to assign to project", -> cy.get("#organizations-select").find("option") .should("have.length", @orgs.length) it "selects none by default", -> cy.get("#organizations-select").should("have.value", "") it "opens external link on click of manage", -> cy.get(".manage-orgs-btn").click().then -> expect(@ipc.externalOpen).to.be.calledWith("https://on.cypress.io/dashboard/organizations") it "displays public & private radios on select", -> cy.get(".privacy-radio").should("not.be.visible") cy.get("select").select("Acme Developers") cy.get(".privacy-radio").should("be.visible") .find("input").should("not.be.checked") it "clears selections when switching back to Me", -> cy.get("select").select("Acme Developers") cy.get(".privacy-radio") .find("input").first().check() cy.get(".btn").contains("Me").click() cy.get(".privacy-radio").find("input").should("not.be.checked") cy.get(".btn").contains("An Organization").click() cy.get("#organizations-select").should("have.value", "") context "without orgs", -> beforeEach -> @getOrgs.resolve([]) cy.get(".btn").contains("Set up project").click() cy.get(".modal-content") .contains(".btn", "An Organization").click() it "displays empty message", -> cy.get(".empty-select-orgs").should("be.visible") it "opens dashboard organizations when 'create org' is clicked", -> cy.contains("Create organization").click().then -> expect(@ipc.externalOpen).to.be.calledWith("https://on.cypress.io/dashboard/organizations") context "without only default org", -> beforeEach -> @getOrgs.resolve([{ "id": "000", "name": "<NAME>", "default": true }]) cy.get(".btn").contains("Set up project").click() cy.get(".modal-content") .contains(".btn", "An Organization").click() it "displays empty message", -> cy.get(".empty-select-orgs").should("be.visible") it "opens dashboard organizations when 'create org' is clicked", -> cy.contains("Create organization").click().then -> expect(@ipc.externalOpen).to.be.calledWith("https://on.cypress.io/dashboard/organizations") context "polls for updates to organizations", -> beforeEach -> cy.clock() @getOrgs.resolve(@orgs) cy.get(".btn").contains("Set up project").click() cy.get(".modal-content") .contains(".btn", "An Organization").click() it "polls for orgs twice in 10+sec on click of org", -> cy.tick(11000).then => expect(@ipc.getOrgs).to.be.calledTwice it "updates org name on list on successful poll", -> @name = "<NAME>" @orgs[0].name = @name @getOrgsAgain = @ipc.getOrgs.onCall(2).resolves(@orgs) cy.tick(11000) cy.get("#organizations-select").find("option") .contains(@name) it "adds new org to list on successful poll", -> @orgs.push({ "id": "333", "name": "<NAME>", "default": false }) @getOrgsAgain = @ipc.getOrgs.onCall(2).resolves(@orgs) cy.tick(11000) cy.get("#organizations-select").find("option") .should('have.length', @orgs.length) describe "on submit", -> beforeEach -> @getOrgs.resolve(@orgs) cy.contains(".btn", "Set up project").click() cy.get(".modal-body") .contains(".btn", "Me").click() cy.get(".privacy-radio").find("input").last().check() cy.get(".modal-body") .contains(".btn", "Set up project").click() it "disables button", -> cy.get(".modal-body") .contains(".btn", "Set up project") .should("be.disabled") it "shows spinner", -> cy.get(".modal-body") .contains(".btn", "Set up project") .find("i") .should("be.visible") describe "successfully submit form", -> beforeEach -> @getOrgs.resolve(@orgs) @setupDashboardProject.resolve({ id: "project-id-123" public: true orgId: "000" }) cy.contains(".btn", "Set up project").click() it "sends project name, org id, and public flag to ipc event", -> cy.get(".modal-body") .contains(".btn", "An Organization").click() cy.get("#projectName").clear().type("New Project") cy.get("select").select("Acme Developers") cy.get(".privacy-radio").find("input").first().check() cy.get(".modal-body") .contains(".btn", "Set up project").click() .then => expect(@ipc.setupDashboardProject).to.be.calledWith({ projectName: "New Project" orgId: "777" public: true }) context "org/public", -> beforeEach -> cy.get(".modal-body") .contains(".btn", "An Organization").click() cy.get("select").select("Acme Developers") cy.get(".privacy-radio").find("input").first().check() cy.get(".modal-body") .contains(".btn", "Set up project").click() it "sends data from form to ipc event", -> expect(@ipc.setupDashboardProject).to.be.calledWith({ projectName: @config.projectName orgId: "777" public: true }) context "me/private", -> beforeEach -> cy.get(".modal-body") .contains(".btn", "Me").click() cy.get(".privacy-radio").find("input").last().check() cy.get(".modal-body") .contains(".btn", "Set up project").click() it "sends data from form to ipc event", -> expect(@ipc.setupDashboardProject).to.be.calledWith({ projectName: @config.projectName orgId: "000" public: false }) context "me/public", -> beforeEach -> cy.get(".modal-body") .contains(".btn", "Me").click() cy.get(".privacy-radio").find("input").first().check() cy.get(".modal-body") .contains(".btn", "Set up project").click() it "sends data from form to ipc event", -> expect(@ipc.setupDashboardProject).to.be.calledWith({ projectName: @config.projectName orgId: "000" public: true }) it "closes modal", -> cy.get(".modal").should("not.be.visible") it "updates localStorage projects cache", -> expect(JSON.parse(localStorage.projects || "[]")[0].orgName).to.equal("Jane Lane") it "displays empty runs page", -> cy.contains("To record your first") it "displays command to run with the record key", -> cy.contains("cypress run --record --key record-key-123") describe "errors", -> beforeEach -> @getOrgs.resolve(@orgs) cy.contains(".btn", "Set up project").click() cy.get(".modal-body") .contains(".btn", "Me").click() cy.get(".privacy-radio").find("input").last().check() cy.get(".modal-body") .contains(".btn", "Set up project").click() it "logs user out when 401", -> @setupDashboardProject.reject({ name: "", message: "", statusCode: 401 }) cy.shouldBeLoggedOut() it "displays error name and message when unexpected", -> @setupDashboardProject.reject({ name: "Fatal Error!" message: """ { "system": "down", "toxicity": "of the city" } """ }) cy.contains('"system": "down"') describe "when get orgs 401s", -> beforeEach -> cy.contains(".btn", "Set up project").click() .then => @getOrgs.reject({ name: "", message: "", statusCode: 401 }) it "logs user out", -> cy.shouldBeLoggedOut() describe "when there is no current user", -> beforeEach -> @getCurrentUser.resolve(null) cy.get(".btn").contains("Set up project").click() it "shows login", -> cy.get(".modal").contains("Log In to Dashboard") describe "when login succeeds", -> beforeEach -> cy.stub(@ipc, "beginAuth").resolves(@user) cy.contains("button", "Log In to Dashboard").click() it "shows setup", -> cy.contains("h4", "Set up project")
true
describe "Set Up Project", -> beforeEach -> cy.fixture("user").as("user") cy.fixture("projects").as("projects") cy.fixture("projects_statuses").as("projectStatuses") cy.fixture("config").as("config") cy.fixture("specs").as("specs") cy.fixture("organizations").as("orgs") cy.fixture("keys").as("keys") cy.visitIndex().then (win) -> { start, @ipc } = win.App @config.projectName = "my-kitchen-sink" cy.stub(@ipc, "getOptions").resolves({projectRoot: "/foo/bar"}) cy.stub(@ipc, "updaterCheck").resolves(false) cy.stub(@ipc, "closeBrowser").resolves(null) @config.projectId = null cy.stub(@ipc, "openProject").resolves(@config) cy.stub(@ipc, "getSpecs").yields(null, @specs) cy.stub(@ipc, "getRuns").resolves([]) cy.stub(@ipc, "getRecordKeys").resolves(@keys) cy.stub(@ipc, "pingApiServer").resolves() cy.stub(@ipc, "externalOpen") @getCurrentUser = @util.deferred() cy.stub(@ipc, "getCurrentUser").resolves(@getCurrentUser.promise) @getOrgs = @util.deferred() cy.stub(@ipc, "getOrgs").returns(@getOrgs.promise) @getProjectStatus = @util.deferred() cy.stub(@ipc, "getProjectStatus").returns(@getProjectStatus.promise) @setupDashboardProject = @util.deferred() cy.stub(@ipc, "setupDashboardProject").returns(@setupDashboardProject.promise) start() cy.get(".navbar-default a") .contains("Runs").click() it "displays 'need to set up' message", -> cy.contains("You have no recorded runs") describe "when there is a current user", -> beforeEach -> @getCurrentUser.resolve(@user) describe "general behavior", -> beforeEach -> @getOrgs.resolve(@orgs) cy.get(".btn").contains("Set up project").click() it "clicking link opens setup project window", -> cy.get(".modal").should("be.visible") it "submit button is disabled", -> cy.get(".modal").contains(".btn", "Set up project") .should("be.disabled") it "prefills Project Name", -> cy.get("#projectName").should("have.value", @config.projectName) it "allows me to change Project Name value", -> cy.get("#projectName").clear().type("New Project Here") .should("have.value", "New Project Here") describe "default owner", -> it "has no owner selected by default", -> cy.get("#me").should("not.be.selected") cy.get("#org").should("not.be.selected") it "org docs are linked", -> cy.contains("label", "Who should own this") .find("a").click().then -> expect(@ipc.externalOpen).to.be.calledWith("https://on.cypress.io/what-are-organizations") describe "selecting me as owner", -> beforeEach -> cy.get(".privacy-radio").should("not.be.visible") cy.get(".modal-content") .contains(".btn", "Me").click() it "access docs are linked", -> cy.contains("label", "Who should see the runs") .find("a").click().then -> expect(@ipc.externalOpen).to.be.calledWith("https://on.cypress.io/what-is-project-access") it "displays public & private radios with no preselects", -> cy.get(".privacy-radio").should("be.visible") .find("input").should("not.be.checked") describe "selecting an org", -> context "with orgs", -> beforeEach -> @getOrgs.resolve(@orgs) cy.get(".btn").contains("Set up project").click() cy.get(".modal-content") .contains(".btn", "An Organization").click() it "lists organizations to assign to project", -> cy.get("#organizations-select").find("option") .should("have.length", @orgs.length) it "selects none by default", -> cy.get("#organizations-select").should("have.value", "") it "opens external link on click of manage", -> cy.get(".manage-orgs-btn").click().then -> expect(@ipc.externalOpen).to.be.calledWith("https://on.cypress.io/dashboard/organizations") it "displays public & private radios on select", -> cy.get(".privacy-radio").should("not.be.visible") cy.get("select").select("Acme Developers") cy.get(".privacy-radio").should("be.visible") .find("input").should("not.be.checked") it "clears selections when switching back to Me", -> cy.get("select").select("Acme Developers") cy.get(".privacy-radio") .find("input").first().check() cy.get(".btn").contains("Me").click() cy.get(".privacy-radio").find("input").should("not.be.checked") cy.get(".btn").contains("An Organization").click() cy.get("#organizations-select").should("have.value", "") context "without orgs", -> beforeEach -> @getOrgs.resolve([]) cy.get(".btn").contains("Set up project").click() cy.get(".modal-content") .contains(".btn", "An Organization").click() it "displays empty message", -> cy.get(".empty-select-orgs").should("be.visible") it "opens dashboard organizations when 'create org' is clicked", -> cy.contains("Create organization").click().then -> expect(@ipc.externalOpen).to.be.calledWith("https://on.cypress.io/dashboard/organizations") context "without only default org", -> beforeEach -> @getOrgs.resolve([{ "id": "000", "name": "PI:NAME:<NAME>END_PI", "default": true }]) cy.get(".btn").contains("Set up project").click() cy.get(".modal-content") .contains(".btn", "An Organization").click() it "displays empty message", -> cy.get(".empty-select-orgs").should("be.visible") it "opens dashboard organizations when 'create org' is clicked", -> cy.contains("Create organization").click().then -> expect(@ipc.externalOpen).to.be.calledWith("https://on.cypress.io/dashboard/organizations") context "polls for updates to organizations", -> beforeEach -> cy.clock() @getOrgs.resolve(@orgs) cy.get(".btn").contains("Set up project").click() cy.get(".modal-content") .contains(".btn", "An Organization").click() it "polls for orgs twice in 10+sec on click of org", -> cy.tick(11000).then => expect(@ipc.getOrgs).to.be.calledTwice it "updates org name on list on successful poll", -> @name = "PI:NAME:<NAME>END_PI" @orgs[0].name = @name @getOrgsAgain = @ipc.getOrgs.onCall(2).resolves(@orgs) cy.tick(11000) cy.get("#organizations-select").find("option") .contains(@name) it "adds new org to list on successful poll", -> @orgs.push({ "id": "333", "name": "PI:NAME:<NAME>END_PI", "default": false }) @getOrgsAgain = @ipc.getOrgs.onCall(2).resolves(@orgs) cy.tick(11000) cy.get("#organizations-select").find("option") .should('have.length', @orgs.length) describe "on submit", -> beforeEach -> @getOrgs.resolve(@orgs) cy.contains(".btn", "Set up project").click() cy.get(".modal-body") .contains(".btn", "Me").click() cy.get(".privacy-radio").find("input").last().check() cy.get(".modal-body") .contains(".btn", "Set up project").click() it "disables button", -> cy.get(".modal-body") .contains(".btn", "Set up project") .should("be.disabled") it "shows spinner", -> cy.get(".modal-body") .contains(".btn", "Set up project") .find("i") .should("be.visible") describe "successfully submit form", -> beforeEach -> @getOrgs.resolve(@orgs) @setupDashboardProject.resolve({ id: "project-id-123" public: true orgId: "000" }) cy.contains(".btn", "Set up project").click() it "sends project name, org id, and public flag to ipc event", -> cy.get(".modal-body") .contains(".btn", "An Organization").click() cy.get("#projectName").clear().type("New Project") cy.get("select").select("Acme Developers") cy.get(".privacy-radio").find("input").first().check() cy.get(".modal-body") .contains(".btn", "Set up project").click() .then => expect(@ipc.setupDashboardProject).to.be.calledWith({ projectName: "New Project" orgId: "777" public: true }) context "org/public", -> beforeEach -> cy.get(".modal-body") .contains(".btn", "An Organization").click() cy.get("select").select("Acme Developers") cy.get(".privacy-radio").find("input").first().check() cy.get(".modal-body") .contains(".btn", "Set up project").click() it "sends data from form to ipc event", -> expect(@ipc.setupDashboardProject).to.be.calledWith({ projectName: @config.projectName orgId: "777" public: true }) context "me/private", -> beforeEach -> cy.get(".modal-body") .contains(".btn", "Me").click() cy.get(".privacy-radio").find("input").last().check() cy.get(".modal-body") .contains(".btn", "Set up project").click() it "sends data from form to ipc event", -> expect(@ipc.setupDashboardProject).to.be.calledWith({ projectName: @config.projectName orgId: "000" public: false }) context "me/public", -> beforeEach -> cy.get(".modal-body") .contains(".btn", "Me").click() cy.get(".privacy-radio").find("input").first().check() cy.get(".modal-body") .contains(".btn", "Set up project").click() it "sends data from form to ipc event", -> expect(@ipc.setupDashboardProject).to.be.calledWith({ projectName: @config.projectName orgId: "000" public: true }) it "closes modal", -> cy.get(".modal").should("not.be.visible") it "updates localStorage projects cache", -> expect(JSON.parse(localStorage.projects || "[]")[0].orgName).to.equal("Jane Lane") it "displays empty runs page", -> cy.contains("To record your first") it "displays command to run with the record key", -> cy.contains("cypress run --record --key record-key-123") describe "errors", -> beforeEach -> @getOrgs.resolve(@orgs) cy.contains(".btn", "Set up project").click() cy.get(".modal-body") .contains(".btn", "Me").click() cy.get(".privacy-radio").find("input").last().check() cy.get(".modal-body") .contains(".btn", "Set up project").click() it "logs user out when 401", -> @setupDashboardProject.reject({ name: "", message: "", statusCode: 401 }) cy.shouldBeLoggedOut() it "displays error name and message when unexpected", -> @setupDashboardProject.reject({ name: "Fatal Error!" message: """ { "system": "down", "toxicity": "of the city" } """ }) cy.contains('"system": "down"') describe "when get orgs 401s", -> beforeEach -> cy.contains(".btn", "Set up project").click() .then => @getOrgs.reject({ name: "", message: "", statusCode: 401 }) it "logs user out", -> cy.shouldBeLoggedOut() describe "when there is no current user", -> beforeEach -> @getCurrentUser.resolve(null) cy.get(".btn").contains("Set up project").click() it "shows login", -> cy.get(".modal").contains("Log In to Dashboard") describe "when login succeeds", -> beforeEach -> cy.stub(@ipc, "beginAuth").resolves(@user) cy.contains("button", "Log In to Dashboard").click() it "shows setup", -> cy.contains("h4", "Set up project")
[ { "context": "layer = new Player\n x: 0, y: 0, z: 0, name: 'bob'\n player.toJSON().should.eql x: 0, y: 0, z: 0,", "end": 498, "score": 0.5791761875152588, "start": 495, "tag": "USERNAME", "value": "bob" }, { "context": "ayer.toJSON().should.eql x: 0, y: 0, z: 0, name: 'bob'\n", "end": 559, "score": 0.4440297782421112, "start": 556, "tag": "NAME", "value": "bob" } ]
test/app/player_spec.coffee
davemaurakis/sumbro
0
Player = require '../../src/app/player.coffee' describe 'Player', -> it 'can be required', -> Player.should.be.a.function it 'should have a starting position', -> player = new Player x: 0, y: 0, z: 0 player.x.should.equal 0 player.y.should.equal 0 player.z.should.equal 0 it 'should have a name', -> player = new Player name: 'me' player.name.should.equal 'me' it 'can serialze its data', -> player = new Player x: 0, y: 0, z: 0, name: 'bob' player.toJSON().should.eql x: 0, y: 0, z: 0, name: 'bob'
140444
Player = require '../../src/app/player.coffee' describe 'Player', -> it 'can be required', -> Player.should.be.a.function it 'should have a starting position', -> player = new Player x: 0, y: 0, z: 0 player.x.should.equal 0 player.y.should.equal 0 player.z.should.equal 0 it 'should have a name', -> player = new Player name: 'me' player.name.should.equal 'me' it 'can serialze its data', -> player = new Player x: 0, y: 0, z: 0, name: 'bob' player.toJSON().should.eql x: 0, y: 0, z: 0, name: '<NAME>'
true
Player = require '../../src/app/player.coffee' describe 'Player', -> it 'can be required', -> Player.should.be.a.function it 'should have a starting position', -> player = new Player x: 0, y: 0, z: 0 player.x.should.equal 0 player.y.should.equal 0 player.z.should.equal 0 it 'should have a name', -> player = new Player name: 'me' player.name.should.equal 'me' it 'can serialze its data', -> player = new Player x: 0, y: 0, z: 0, name: 'bob' player.toJSON().should.eql x: 0, y: 0, z: 0, name: 'PI:NAME:<NAME>END_PI'
[ { "context": "T'\n options.data ?= {}\n options.data.token = token.id\n options.data.timestamp = new Date().getTim", "end": 746, "score": 0.5940307378768921, "start": 741, "tag": "KEY", "value": "token" }, { "context": "options.data ?= {}\n options.data.token = token.id\n options.data.timestamp = new Date().getTime()", "end": 749, "score": 0.6446433067321777, "start": 747, "tag": "KEY", "value": "id" } ]
app/models/Product.coffee
mcgilvrayb/codecombat
0
CocoModel = require './CocoModel' module.exports = class ProductModel extends CocoModel @className: 'Product' @schema: require 'schemas/models/product.schema' urlRoot: '/db/products' priceStringNoSymbol: -> (@get('amount') / 100).toFixed(2) adjustedPriceStringNoSymbol: -> amt = @get('amount') if @get('coupons')? and @get('coupons').length > 0 amt = @get('coupons')[0].amount (amt / 100).toFixed(2) adjustedPrice: -> amt = @get('amount') if @get('coupons')? and @get('coupons').length > 0 amt = @get('coupons')[0].amount amt purchase: (token, options={}) -> options.url = _.result(@, 'url') + '/purchase' options.method = 'POST' options.data ?= {} options.data.token = token.id options.data.timestamp = new Date().getTime() options.data = JSON.stringify(options.data) options.contentType = 'application/json' return $.ajax(options)
178337
CocoModel = require './CocoModel' module.exports = class ProductModel extends CocoModel @className: 'Product' @schema: require 'schemas/models/product.schema' urlRoot: '/db/products' priceStringNoSymbol: -> (@get('amount') / 100).toFixed(2) adjustedPriceStringNoSymbol: -> amt = @get('amount') if @get('coupons')? and @get('coupons').length > 0 amt = @get('coupons')[0].amount (amt / 100).toFixed(2) adjustedPrice: -> amt = @get('amount') if @get('coupons')? and @get('coupons').length > 0 amt = @get('coupons')[0].amount amt purchase: (token, options={}) -> options.url = _.result(@, 'url') + '/purchase' options.method = 'POST' options.data ?= {} options.data.token = <KEY>.<KEY> options.data.timestamp = new Date().getTime() options.data = JSON.stringify(options.data) options.contentType = 'application/json' return $.ajax(options)
true
CocoModel = require './CocoModel' module.exports = class ProductModel extends CocoModel @className: 'Product' @schema: require 'schemas/models/product.schema' urlRoot: '/db/products' priceStringNoSymbol: -> (@get('amount') / 100).toFixed(2) adjustedPriceStringNoSymbol: -> amt = @get('amount') if @get('coupons')? and @get('coupons').length > 0 amt = @get('coupons')[0].amount (amt / 100).toFixed(2) adjustedPrice: -> amt = @get('amount') if @get('coupons')? and @get('coupons').length > 0 amt = @get('coupons')[0].amount amt purchase: (token, options={}) -> options.url = _.result(@, 'url') + '/purchase' options.method = 'POST' options.data ?= {} options.data.token = PI:KEY:<KEY>END_PI.PI:KEY:<KEY>END_PI options.data.timestamp = new Date().getTime() options.data = JSON.stringify(options.data) options.contentType = 'application/json' return $.ajax(options)
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9956175684928894, "start": 12, "tag": "NAME", "value": "Joyent" }, { "context": "ot\nnameBuilder2:: = nbRoot\nnb1 = new nameBuilder(\"Ryan\", \"Dahl\")\nnb2 = new nameBuilder2(\"Ryan\", \"Dahl\")\n", "end": 5671, "score": 0.9997069835662842, "start": 5667, "tag": "NAME", "value": "Ryan" }, { "context": "uilder2:: = nbRoot\nnb1 = new nameBuilder(\"Ryan\", \"Dahl\")\nnb2 = new nameBuilder2(\"Ryan\", \"Dahl\")\nassert.d", "end": 5679, "score": 0.9990885257720947, "start": 5675, "tag": "NAME", "value": "Dahl" }, { "context": "meBuilder(\"Ryan\", \"Dahl\")\nnb2 = new nameBuilder2(\"Ryan\", \"Dahl\")\nassert.doesNotThrow makeBlock(a.deepEqu", "end": 5710, "score": 0.9997751712799072, "start": 5706, "tag": "NAME", "value": "Ryan" }, { "context": "r(\"Ryan\", \"Dahl\")\nnb2 = new nameBuilder2(\"Ryan\", \"Dahl\")\nassert.doesNotThrow makeBlock(a.deepEqual, nb1,", "end": 5718, "score": 0.9985224008560181, "start": 5714, "tag": "NAME", "value": "Dahl" }, { "context": ")\nnameBuilder2:: = Object\nnb2 = new nameBuilder2(\"Ryan\", \"Dahl\")\nassert.throws makeBlock(a.deepEqual, nb", "end": 5826, "score": 0.9996826648712158, "start": 5822, "tag": "NAME", "value": "Ryan" }, { "context": "ilder2:: = Object\nnb2 = new nameBuilder2(\"Ryan\", \"Dahl\")\nassert.throws makeBlock(a.deepEqual, nb1, nb2),", "end": 5834, "score": 0.9994418621063232, "start": 5830, "tag": "NAME", "value": "Dahl" } ]
test/simple/test-assert.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. makeBlock = (f) -> args = Array::slice.call(arguments, 1) -> f.apply this, args # deepEquals joy! # 7.2 # 7.3 # 7.4 # 7.5 # having the same number of owned properties && the same set of keys #(although not necessarily the same order), # having an identical prototype property nameBuilder = (first, last) -> @first = first @last = last this nameBuilder2 = (first, last) -> @first = first @last = last this # String literal + object blew up my implementation... # Testing the throwing thrower = (errorConstructor) -> throw new errorConstructor("test")return # the basic calls work # if not passing an error, catch all. # when passing a type, only catch errors of the appropriate type # doesNotThrow should pass through all errors # key difference is that throwing our correct error makes an assertion error # make sure that validating using constructor really works # use a RegExp to validate error message # use a fn to validate error object # GH-207. Make sure deepEqual doesn't loop forever on circular refs # GH-7178. Ensure reflexivity of deepEqual with `arguments` objects. # #217 testAssertionMessage = (actual, expected) -> try assert.equal actual, "" catch e assert.equal e.toString(), [ "AssertionError:" expected "==" "\"\"" ].join(" ") assert.ok e.generatedMessage, "Message not marked as generated" return common = require("../common") assert = require("assert") a = require("assert") assert.ok common.indirectInstanceOf(a.AssertionError::, Error), "a.AssertionError instanceof Error" assert.throws makeBlock(a, false), a.AssertionError, "ok(false)" assert.doesNotThrow makeBlock(a, true), a.AssertionError, "ok(true)" assert.doesNotThrow makeBlock(a, "test", "ok('test')") assert.throws makeBlock(a.ok, false), a.AssertionError, "ok(false)" assert.doesNotThrow makeBlock(a.ok, true), a.AssertionError, "ok(true)" assert.doesNotThrow makeBlock(a.ok, "test"), "ok('test')" assert.throws makeBlock(a.equal, true, false), a.AssertionError, "equal" assert.doesNotThrow makeBlock(a.equal, null, null), "equal" assert.doesNotThrow makeBlock(a.equal, `undefined`, `undefined`), "equal" assert.doesNotThrow makeBlock(a.equal, null, `undefined`), "equal" assert.doesNotThrow makeBlock(a.equal, true, true), "equal" assert.doesNotThrow makeBlock(a.equal, 2, "2"), "equal" assert.doesNotThrow makeBlock(a.notEqual, true, false), "notEqual" assert.throws makeBlock(a.notEqual, true, true), a.AssertionError, "notEqual" assert.throws makeBlock(a.strictEqual, 2, "2"), a.AssertionError, "strictEqual" assert.throws makeBlock(a.strictEqual, null, `undefined`), a.AssertionError, "strictEqual" assert.doesNotThrow makeBlock(a.notStrictEqual, 2, "2"), "notStrictEqual" assert.doesNotThrow makeBlock(a.deepEqual, new Date(2000, 3, 14), new Date(2000, 3, 14)), "deepEqual date" assert.throws makeBlock(a.deepEqual, new Date(), new Date(2000, 3, 14)), a.AssertionError, "deepEqual date" assert.doesNotThrow makeBlock(a.deepEqual, /a/, /a/) assert.doesNotThrow makeBlock(a.deepEqual, /a/g, /a/g) assert.doesNotThrow makeBlock(a.deepEqual, /a/i, /a/i) assert.doesNotThrow makeBlock(a.deepEqual, /a/m, /a/m) assert.doesNotThrow makeBlock(a.deepEqual, /a/g, /a/g) assert.throws makeBlock(a.deepEqual, /ab/, /a/) assert.throws makeBlock(a.deepEqual, /a/g, /a/) assert.throws makeBlock(a.deepEqual, /a/i, /a/) assert.throws makeBlock(a.deepEqual, /a/m, /a/) assert.throws makeBlock(a.deepEqual, /a/g, /a/i) re1 = /a/ re1.lastIndex = 3 assert.throws makeBlock(a.deepEqual, re1, /a/) assert.doesNotThrow makeBlock(a.deepEqual, 4, "4"), "deepEqual == check" assert.doesNotThrow makeBlock(a.deepEqual, true, 1), "deepEqual == check" assert.throws makeBlock(a.deepEqual, 4, "5"), a.AssertionError, "deepEqual == check" assert.doesNotThrow makeBlock(a.deepEqual, a: 4 , a: 4 ) assert.doesNotThrow makeBlock(a.deepEqual, a: 4 b: "2" , a: 4 b: "2" ) assert.doesNotThrow makeBlock(a.deepEqual, [4], ["4"]) assert.throws makeBlock(a.deepEqual, a: 4 , a: 4 b: true ), a.AssertionError assert.doesNotThrow makeBlock(a.deepEqual, ["a"], 0: "a" ) assert.doesNotThrow makeBlock(a.deepEqual, a: 4 b: "1" , b: "1" a: 4 ) a1 = [ 1 2 3 ] a2 = [ 1 2 3 ] a1.a = "test" a1.b = true a2.b = true a2.a = "test" assert.throws makeBlock(a.deepEqual, Object.keys(a1), Object.keys(a2)), a.AssertionError assert.doesNotThrow makeBlock(a.deepEqual, a1, a2) nbRoot = toString: -> @first + " " + @last nameBuilder:: = nbRoot nameBuilder2:: = nbRoot nb1 = new nameBuilder("Ryan", "Dahl") nb2 = new nameBuilder2("Ryan", "Dahl") assert.doesNotThrow makeBlock(a.deepEqual, nb1, nb2) nameBuilder2:: = Object nb2 = new nameBuilder2("Ryan", "Dahl") assert.throws makeBlock(a.deepEqual, nb1, nb2), a.AssertionError assert.throws makeBlock(a.deepEqual, "a", {}), a.AssertionError aethrow = makeBlock(thrower, a.AssertionError) aethrow = makeBlock(thrower, a.AssertionError) assert.throws makeBlock(thrower, a.AssertionError), a.AssertionError, "message" assert.throws makeBlock(thrower, a.AssertionError), a.AssertionError assert.throws makeBlock(thrower, a.AssertionError) assert.throws makeBlock(thrower, TypeError) threw = false try a.throws makeBlock(thrower, TypeError), a.AssertionError catch e threw = true assert.ok e instanceof TypeError, "type" assert.equal true, threw, "a.throws with an explicit error is eating extra errors", a.AssertionError threw = false try a.doesNotThrow makeBlock(thrower, TypeError), a.AssertionError catch e threw = true assert.ok e instanceof TypeError assert.equal true, threw, "a.doesNotThrow with an explicit error is eating extra errors" try a.doesNotThrow makeBlock(thrower, TypeError), TypeError catch e threw = true assert.ok e instanceof a.AssertionError assert.equal true, threw, "a.doesNotThrow is not catching type matching errors" assert.throws -> assert.ifError new Error("test error") return assert.doesNotThrow -> assert.ifError null return assert.doesNotThrow -> assert.ifError() return threw = false try assert.throws (-> throw ({})return ), Array catch e threw = true assert.ok threw, "wrong constructor validation" a.throws makeBlock(thrower, TypeError), /test/ a.throws makeBlock(thrower, TypeError), (err) -> true if (err instanceof TypeError) and /test/.test(err) b = {} b.b = b c = {} c.b = c gotError = false try assert.deepEqual b, c catch e gotError = true args = (-> arguments )() a.throws makeBlock(a.deepEqual, [], args) a.throws makeBlock(a.deepEqual, args, []) console.log "All OK" assert.ok gotError testAssertionMessage `undefined`, "\"undefined\"" testAssertionMessage null, "null" testAssertionMessage true, "true" testAssertionMessage false, "false" testAssertionMessage 0, "0" testAssertionMessage 100, "100" testAssertionMessage NaN, "\"NaN\"" testAssertionMessage Infinity, "\"Infinity\"" testAssertionMessage -Infinity, "\"-Infinity\"" testAssertionMessage "", "\"\"" testAssertionMessage "foo", "\"foo\"" testAssertionMessage [], "[]" testAssertionMessage [ 1 2 3 ], "[1,2,3]" testAssertionMessage /a/, "\"/a/\"" testAssertionMessage /abc/g, "\"/abc/gim\"" testAssertionMessage (f = -> ), "\"function f() {}\"" testAssertionMessage {}, "{}" testAssertionMessage a: `undefined` b: null , "{\"a\":\"undefined\",\"b\":null}" testAssertionMessage a: NaN b: Infinity c: -Infinity , "{\"a\":\"NaN\",\"b\":\"Infinity\",\"c\":\"-Infinity\"}" # #2893 try assert.throws -> assert.ifError null return catch e threw = true assert.equal e.message, "Missing expected exception.." assert.ok threw # #5292 try assert.equal 1, 2 catch e assert.equal e.toString().split("\n")[0], "AssertionError: 1 == 2" assert.ok e.generatedMessage, "Message not marked as generated" try assert.equal 1, 2, "oh no" catch e assert.equal e.toString().split("\n")[0], "AssertionError: oh no" assert.equal e.generatedMessage, false, "Message incorrectly marked as generated"
161549
# 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. makeBlock = (f) -> args = Array::slice.call(arguments, 1) -> f.apply this, args # deepEquals joy! # 7.2 # 7.3 # 7.4 # 7.5 # having the same number of owned properties && the same set of keys #(although not necessarily the same order), # having an identical prototype property nameBuilder = (first, last) -> @first = first @last = last this nameBuilder2 = (first, last) -> @first = first @last = last this # String literal + object blew up my implementation... # Testing the throwing thrower = (errorConstructor) -> throw new errorConstructor("test")return # the basic calls work # if not passing an error, catch all. # when passing a type, only catch errors of the appropriate type # doesNotThrow should pass through all errors # key difference is that throwing our correct error makes an assertion error # make sure that validating using constructor really works # use a RegExp to validate error message # use a fn to validate error object # GH-207. Make sure deepEqual doesn't loop forever on circular refs # GH-7178. Ensure reflexivity of deepEqual with `arguments` objects. # #217 testAssertionMessage = (actual, expected) -> try assert.equal actual, "" catch e assert.equal e.toString(), [ "AssertionError:" expected "==" "\"\"" ].join(" ") assert.ok e.generatedMessage, "Message not marked as generated" return common = require("../common") assert = require("assert") a = require("assert") assert.ok common.indirectInstanceOf(a.AssertionError::, Error), "a.AssertionError instanceof Error" assert.throws makeBlock(a, false), a.AssertionError, "ok(false)" assert.doesNotThrow makeBlock(a, true), a.AssertionError, "ok(true)" assert.doesNotThrow makeBlock(a, "test", "ok('test')") assert.throws makeBlock(a.ok, false), a.AssertionError, "ok(false)" assert.doesNotThrow makeBlock(a.ok, true), a.AssertionError, "ok(true)" assert.doesNotThrow makeBlock(a.ok, "test"), "ok('test')" assert.throws makeBlock(a.equal, true, false), a.AssertionError, "equal" assert.doesNotThrow makeBlock(a.equal, null, null), "equal" assert.doesNotThrow makeBlock(a.equal, `undefined`, `undefined`), "equal" assert.doesNotThrow makeBlock(a.equal, null, `undefined`), "equal" assert.doesNotThrow makeBlock(a.equal, true, true), "equal" assert.doesNotThrow makeBlock(a.equal, 2, "2"), "equal" assert.doesNotThrow makeBlock(a.notEqual, true, false), "notEqual" assert.throws makeBlock(a.notEqual, true, true), a.AssertionError, "notEqual" assert.throws makeBlock(a.strictEqual, 2, "2"), a.AssertionError, "strictEqual" assert.throws makeBlock(a.strictEqual, null, `undefined`), a.AssertionError, "strictEqual" assert.doesNotThrow makeBlock(a.notStrictEqual, 2, "2"), "notStrictEqual" assert.doesNotThrow makeBlock(a.deepEqual, new Date(2000, 3, 14), new Date(2000, 3, 14)), "deepEqual date" assert.throws makeBlock(a.deepEqual, new Date(), new Date(2000, 3, 14)), a.AssertionError, "deepEqual date" assert.doesNotThrow makeBlock(a.deepEqual, /a/, /a/) assert.doesNotThrow makeBlock(a.deepEqual, /a/g, /a/g) assert.doesNotThrow makeBlock(a.deepEqual, /a/i, /a/i) assert.doesNotThrow makeBlock(a.deepEqual, /a/m, /a/m) assert.doesNotThrow makeBlock(a.deepEqual, /a/g, /a/g) assert.throws makeBlock(a.deepEqual, /ab/, /a/) assert.throws makeBlock(a.deepEqual, /a/g, /a/) assert.throws makeBlock(a.deepEqual, /a/i, /a/) assert.throws makeBlock(a.deepEqual, /a/m, /a/) assert.throws makeBlock(a.deepEqual, /a/g, /a/i) re1 = /a/ re1.lastIndex = 3 assert.throws makeBlock(a.deepEqual, re1, /a/) assert.doesNotThrow makeBlock(a.deepEqual, 4, "4"), "deepEqual == check" assert.doesNotThrow makeBlock(a.deepEqual, true, 1), "deepEqual == check" assert.throws makeBlock(a.deepEqual, 4, "5"), a.AssertionError, "deepEqual == check" assert.doesNotThrow makeBlock(a.deepEqual, a: 4 , a: 4 ) assert.doesNotThrow makeBlock(a.deepEqual, a: 4 b: "2" , a: 4 b: "2" ) assert.doesNotThrow makeBlock(a.deepEqual, [4], ["4"]) assert.throws makeBlock(a.deepEqual, a: 4 , a: 4 b: true ), a.AssertionError assert.doesNotThrow makeBlock(a.deepEqual, ["a"], 0: "a" ) assert.doesNotThrow makeBlock(a.deepEqual, a: 4 b: "1" , b: "1" a: 4 ) a1 = [ 1 2 3 ] a2 = [ 1 2 3 ] a1.a = "test" a1.b = true a2.b = true a2.a = "test" assert.throws makeBlock(a.deepEqual, Object.keys(a1), Object.keys(a2)), a.AssertionError assert.doesNotThrow makeBlock(a.deepEqual, a1, a2) nbRoot = toString: -> @first + " " + @last nameBuilder:: = nbRoot nameBuilder2:: = nbRoot nb1 = new nameBuilder("<NAME>", "<NAME>") nb2 = new nameBuilder2("<NAME>", "<NAME>") assert.doesNotThrow makeBlock(a.deepEqual, nb1, nb2) nameBuilder2:: = Object nb2 = new nameBuilder2("<NAME>", "<NAME>") assert.throws makeBlock(a.deepEqual, nb1, nb2), a.AssertionError assert.throws makeBlock(a.deepEqual, "a", {}), a.AssertionError aethrow = makeBlock(thrower, a.AssertionError) aethrow = makeBlock(thrower, a.AssertionError) assert.throws makeBlock(thrower, a.AssertionError), a.AssertionError, "message" assert.throws makeBlock(thrower, a.AssertionError), a.AssertionError assert.throws makeBlock(thrower, a.AssertionError) assert.throws makeBlock(thrower, TypeError) threw = false try a.throws makeBlock(thrower, TypeError), a.AssertionError catch e threw = true assert.ok e instanceof TypeError, "type" assert.equal true, threw, "a.throws with an explicit error is eating extra errors", a.AssertionError threw = false try a.doesNotThrow makeBlock(thrower, TypeError), a.AssertionError catch e threw = true assert.ok e instanceof TypeError assert.equal true, threw, "a.doesNotThrow with an explicit error is eating extra errors" try a.doesNotThrow makeBlock(thrower, TypeError), TypeError catch e threw = true assert.ok e instanceof a.AssertionError assert.equal true, threw, "a.doesNotThrow is not catching type matching errors" assert.throws -> assert.ifError new Error("test error") return assert.doesNotThrow -> assert.ifError null return assert.doesNotThrow -> assert.ifError() return threw = false try assert.throws (-> throw ({})return ), Array catch e threw = true assert.ok threw, "wrong constructor validation" a.throws makeBlock(thrower, TypeError), /test/ a.throws makeBlock(thrower, TypeError), (err) -> true if (err instanceof TypeError) and /test/.test(err) b = {} b.b = b c = {} c.b = c gotError = false try assert.deepEqual b, c catch e gotError = true args = (-> arguments )() a.throws makeBlock(a.deepEqual, [], args) a.throws makeBlock(a.deepEqual, args, []) console.log "All OK" assert.ok gotError testAssertionMessage `undefined`, "\"undefined\"" testAssertionMessage null, "null" testAssertionMessage true, "true" testAssertionMessage false, "false" testAssertionMessage 0, "0" testAssertionMessage 100, "100" testAssertionMessage NaN, "\"NaN\"" testAssertionMessage Infinity, "\"Infinity\"" testAssertionMessage -Infinity, "\"-Infinity\"" testAssertionMessage "", "\"\"" testAssertionMessage "foo", "\"foo\"" testAssertionMessage [], "[]" testAssertionMessage [ 1 2 3 ], "[1,2,3]" testAssertionMessage /a/, "\"/a/\"" testAssertionMessage /abc/g, "\"/abc/gim\"" testAssertionMessage (f = -> ), "\"function f() {}\"" testAssertionMessage {}, "{}" testAssertionMessage a: `undefined` b: null , "{\"a\":\"undefined\",\"b\":null}" testAssertionMessage a: NaN b: Infinity c: -Infinity , "{\"a\":\"NaN\",\"b\":\"Infinity\",\"c\":\"-Infinity\"}" # #2893 try assert.throws -> assert.ifError null return catch e threw = true assert.equal e.message, "Missing expected exception.." assert.ok threw # #5292 try assert.equal 1, 2 catch e assert.equal e.toString().split("\n")[0], "AssertionError: 1 == 2" assert.ok e.generatedMessage, "Message not marked as generated" try assert.equal 1, 2, "oh no" catch e assert.equal e.toString().split("\n")[0], "AssertionError: oh no" assert.equal e.generatedMessage, false, "Message incorrectly marked as generated"
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. makeBlock = (f) -> args = Array::slice.call(arguments, 1) -> f.apply this, args # deepEquals joy! # 7.2 # 7.3 # 7.4 # 7.5 # having the same number of owned properties && the same set of keys #(although not necessarily the same order), # having an identical prototype property nameBuilder = (first, last) -> @first = first @last = last this nameBuilder2 = (first, last) -> @first = first @last = last this # String literal + object blew up my implementation... # Testing the throwing thrower = (errorConstructor) -> throw new errorConstructor("test")return # the basic calls work # if not passing an error, catch all. # when passing a type, only catch errors of the appropriate type # doesNotThrow should pass through all errors # key difference is that throwing our correct error makes an assertion error # make sure that validating using constructor really works # use a RegExp to validate error message # use a fn to validate error object # GH-207. Make sure deepEqual doesn't loop forever on circular refs # GH-7178. Ensure reflexivity of deepEqual with `arguments` objects. # #217 testAssertionMessage = (actual, expected) -> try assert.equal actual, "" catch e assert.equal e.toString(), [ "AssertionError:" expected "==" "\"\"" ].join(" ") assert.ok e.generatedMessage, "Message not marked as generated" return common = require("../common") assert = require("assert") a = require("assert") assert.ok common.indirectInstanceOf(a.AssertionError::, Error), "a.AssertionError instanceof Error" assert.throws makeBlock(a, false), a.AssertionError, "ok(false)" assert.doesNotThrow makeBlock(a, true), a.AssertionError, "ok(true)" assert.doesNotThrow makeBlock(a, "test", "ok('test')") assert.throws makeBlock(a.ok, false), a.AssertionError, "ok(false)" assert.doesNotThrow makeBlock(a.ok, true), a.AssertionError, "ok(true)" assert.doesNotThrow makeBlock(a.ok, "test"), "ok('test')" assert.throws makeBlock(a.equal, true, false), a.AssertionError, "equal" assert.doesNotThrow makeBlock(a.equal, null, null), "equal" assert.doesNotThrow makeBlock(a.equal, `undefined`, `undefined`), "equal" assert.doesNotThrow makeBlock(a.equal, null, `undefined`), "equal" assert.doesNotThrow makeBlock(a.equal, true, true), "equal" assert.doesNotThrow makeBlock(a.equal, 2, "2"), "equal" assert.doesNotThrow makeBlock(a.notEqual, true, false), "notEqual" assert.throws makeBlock(a.notEqual, true, true), a.AssertionError, "notEqual" assert.throws makeBlock(a.strictEqual, 2, "2"), a.AssertionError, "strictEqual" assert.throws makeBlock(a.strictEqual, null, `undefined`), a.AssertionError, "strictEqual" assert.doesNotThrow makeBlock(a.notStrictEqual, 2, "2"), "notStrictEqual" assert.doesNotThrow makeBlock(a.deepEqual, new Date(2000, 3, 14), new Date(2000, 3, 14)), "deepEqual date" assert.throws makeBlock(a.deepEqual, new Date(), new Date(2000, 3, 14)), a.AssertionError, "deepEqual date" assert.doesNotThrow makeBlock(a.deepEqual, /a/, /a/) assert.doesNotThrow makeBlock(a.deepEqual, /a/g, /a/g) assert.doesNotThrow makeBlock(a.deepEqual, /a/i, /a/i) assert.doesNotThrow makeBlock(a.deepEqual, /a/m, /a/m) assert.doesNotThrow makeBlock(a.deepEqual, /a/g, /a/g) assert.throws makeBlock(a.deepEqual, /ab/, /a/) assert.throws makeBlock(a.deepEqual, /a/g, /a/) assert.throws makeBlock(a.deepEqual, /a/i, /a/) assert.throws makeBlock(a.deepEqual, /a/m, /a/) assert.throws makeBlock(a.deepEqual, /a/g, /a/i) re1 = /a/ re1.lastIndex = 3 assert.throws makeBlock(a.deepEqual, re1, /a/) assert.doesNotThrow makeBlock(a.deepEqual, 4, "4"), "deepEqual == check" assert.doesNotThrow makeBlock(a.deepEqual, true, 1), "deepEqual == check" assert.throws makeBlock(a.deepEqual, 4, "5"), a.AssertionError, "deepEqual == check" assert.doesNotThrow makeBlock(a.deepEqual, a: 4 , a: 4 ) assert.doesNotThrow makeBlock(a.deepEqual, a: 4 b: "2" , a: 4 b: "2" ) assert.doesNotThrow makeBlock(a.deepEqual, [4], ["4"]) assert.throws makeBlock(a.deepEqual, a: 4 , a: 4 b: true ), a.AssertionError assert.doesNotThrow makeBlock(a.deepEqual, ["a"], 0: "a" ) assert.doesNotThrow makeBlock(a.deepEqual, a: 4 b: "1" , b: "1" a: 4 ) a1 = [ 1 2 3 ] a2 = [ 1 2 3 ] a1.a = "test" a1.b = true a2.b = true a2.a = "test" assert.throws makeBlock(a.deepEqual, Object.keys(a1), Object.keys(a2)), a.AssertionError assert.doesNotThrow makeBlock(a.deepEqual, a1, a2) nbRoot = toString: -> @first + " " + @last nameBuilder:: = nbRoot nameBuilder2:: = nbRoot nb1 = new nameBuilder("PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI") nb2 = new nameBuilder2("PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI") assert.doesNotThrow makeBlock(a.deepEqual, nb1, nb2) nameBuilder2:: = Object nb2 = new nameBuilder2("PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI") assert.throws makeBlock(a.deepEqual, nb1, nb2), a.AssertionError assert.throws makeBlock(a.deepEqual, "a", {}), a.AssertionError aethrow = makeBlock(thrower, a.AssertionError) aethrow = makeBlock(thrower, a.AssertionError) assert.throws makeBlock(thrower, a.AssertionError), a.AssertionError, "message" assert.throws makeBlock(thrower, a.AssertionError), a.AssertionError assert.throws makeBlock(thrower, a.AssertionError) assert.throws makeBlock(thrower, TypeError) threw = false try a.throws makeBlock(thrower, TypeError), a.AssertionError catch e threw = true assert.ok e instanceof TypeError, "type" assert.equal true, threw, "a.throws with an explicit error is eating extra errors", a.AssertionError threw = false try a.doesNotThrow makeBlock(thrower, TypeError), a.AssertionError catch e threw = true assert.ok e instanceof TypeError assert.equal true, threw, "a.doesNotThrow with an explicit error is eating extra errors" try a.doesNotThrow makeBlock(thrower, TypeError), TypeError catch e threw = true assert.ok e instanceof a.AssertionError assert.equal true, threw, "a.doesNotThrow is not catching type matching errors" assert.throws -> assert.ifError new Error("test error") return assert.doesNotThrow -> assert.ifError null return assert.doesNotThrow -> assert.ifError() return threw = false try assert.throws (-> throw ({})return ), Array catch e threw = true assert.ok threw, "wrong constructor validation" a.throws makeBlock(thrower, TypeError), /test/ a.throws makeBlock(thrower, TypeError), (err) -> true if (err instanceof TypeError) and /test/.test(err) b = {} b.b = b c = {} c.b = c gotError = false try assert.deepEqual b, c catch e gotError = true args = (-> arguments )() a.throws makeBlock(a.deepEqual, [], args) a.throws makeBlock(a.deepEqual, args, []) console.log "All OK" assert.ok gotError testAssertionMessage `undefined`, "\"undefined\"" testAssertionMessage null, "null" testAssertionMessage true, "true" testAssertionMessage false, "false" testAssertionMessage 0, "0" testAssertionMessage 100, "100" testAssertionMessage NaN, "\"NaN\"" testAssertionMessage Infinity, "\"Infinity\"" testAssertionMessage -Infinity, "\"-Infinity\"" testAssertionMessage "", "\"\"" testAssertionMessage "foo", "\"foo\"" testAssertionMessage [], "[]" testAssertionMessage [ 1 2 3 ], "[1,2,3]" testAssertionMessage /a/, "\"/a/\"" testAssertionMessage /abc/g, "\"/abc/gim\"" testAssertionMessage (f = -> ), "\"function f() {}\"" testAssertionMessage {}, "{}" testAssertionMessage a: `undefined` b: null , "{\"a\":\"undefined\",\"b\":null}" testAssertionMessage a: NaN b: Infinity c: -Infinity , "{\"a\":\"NaN\",\"b\":\"Infinity\",\"c\":\"-Infinity\"}" # #2893 try assert.throws -> assert.ifError null return catch e threw = true assert.equal e.message, "Missing expected exception.." assert.ok threw # #5292 try assert.equal 1, 2 catch e assert.equal e.toString().split("\n")[0], "AssertionError: 1 == 2" assert.ok e.generatedMessage, "Message not marked as generated" try assert.equal 1, 2, "oh no" catch e assert.equal e.toString().split("\n")[0], "AssertionError: oh no" assert.equal e.generatedMessage, false, "Message incorrectly marked as generated"
[ { "context": "llowing text is an excerpt from Finnegan's Wake by James Joyce\", done\n\n it 'verifies that an element does not", "end": 780, "score": 0.9998499155044556, "start": 769, "tag": "NAME", "value": "James Joyce" }, { "context": "llowing text is an excerpt from Finnegan's Wake by James Joyce\"\n expect(promise).to.exist.and.to.have.prope", "end": 1081, "score": 0.9998206496238708, "start": 1070, "tag": "NAME", "value": "James Joyce" }, { "context": "one) ->\n expect('h1').dom.to.contain.text \"Finnegan\", done\n\n it 'verifies that an element does n", "end": 2262, "score": 0.8499091267585754, "start": 2254, "tag": "NAME", "value": "Finnegan" }, { "context": " ->\n expect('h1').dom.not.to.contain.text \"Bibimbap\", done\n\n it 'returns a promise for affirmati", "end": 2394, "score": 0.6315744519233704, "start": 2386, "tag": "NAME", "value": "Bibimbap" }, { "context": " promise = expect('h1').dom.to.contain.text \"Finnegan\"\n expect(promise).to.exist.and.to.have.pro", "end": 2518, "score": 0.8150426745414734, "start": 2510, "tag": "NAME", "value": "Finnegan" }, { "context": " promise = expect('h1').dom.not.to.contain.text \"Bibimbap\"\n expect(promise).to.exist.and.to.have.pro", "end": 2729, "score": 0.8127648234367371, "start": 2721, "tag": "NAME", "value": "Bibimbap" }, { "context": " that a string contains text', ->\n expect('John Finnegan').to.contain \"Finnegan\"\n\n it 'verifies that ", "end": 2946, "score": 0.9992073774337769, "start": 2933, "tag": "NAME", "value": "John Finnegan" }, { "context": "', ->\n expect('John Finnegan').to.contain \"Finnegan\"\n\n it 'verifies that a string does not conta", "end": 2969, "score": 0.9895620346069336, "start": 2961, "tag": "NAME", "value": "Finnegan" }, { "context": "string does not contain text', ->\n expect('John Finnegan').not.to.contain \"Bibimbap\"\n\n it 'does NOT r", "end": 3061, "score": 0.9993547201156616, "start": 3048, "tag": "NAME", "value": "John Finnegan" }, { "context": ">\n expect('John Finnegan').not.to.contain \"Bibimbap\"\n\n it 'does NOT return a promise', ->\n ", "end": 3088, "score": 0.9698482155799866, "start": 3080, "tag": "NAME", "value": "Bibimbap" }, { "context": "eturn a promise', ->\n notPromise = expect('John Finnegan').to.contain \"Finnegan\"\n expect(notPromise", "end": 3174, "score": 0.9992691278457642, "start": 3161, "tag": "NAME", "value": "John Finnegan" }, { "context": " notPromise = expect('John Finnegan').to.contain \"Finnegan\"\n expect(notPromise).not.to.have.property ", "end": 3197, "score": 0.9624078869819641, "start": 3189, "tag": "NAME", "value": "Finnegan" } ]
node_modules/chai-webdriver/spec/suite.spec.coffee
imaarthi/blockchain-explorer
70
path = require 'path' webdriver = require 'selenium-webdriver' chai = require 'chai' chaiWebdriver = require '..' webdriver.logging = LevelName: 'DEBUG' # this seems like a bug in webdriver... driver = new webdriver.Builder() .withCapabilities(webdriver.Capabilities.phantomjs()) .build() chai.use chaiWebdriver(driver) {expect} = chai url = (page) -> "file://#{path.join __dirname, page}" after (done) -> driver.quit().then -> done() describe 'the basics', -> before (done) -> @timeout 0 # this may take a while in CI driver.get(url 'finnegan.html').then -> done() describe '#text', -> it 'verifies that an element has exact text', (done) -> expect('h1').dom.to.have.text "The following text is an excerpt from Finnegan's Wake by James Joyce", done it 'verifies that an element does not have exact text', (done) -> expect('h1').dom.not.to.have.text "Wake", done it 'returns a promise for affirmative', (done)-> promise = expect('h1').dom.to.have.text "The following text is an excerpt from Finnegan's Wake by James Joyce" expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for negative', (done)-> promise = expect('h1').dom.not.to.have.text "Wake" expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() describe '#text (regexp version)', -> it 'verifies that an element has a regexp match', (done) -> expect('h1').dom.to.have.text /following.*excerpt/, done it 'verifies that an element does not match the regexp', (done) -> expect('h1').dom.not.to.have.text /following.*food/, done it 'returns a promise for affirmative', (done)-> promise = expect('h1').dom.to.have.text /following.*excerpt/ expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for negative', (done)-> promise = expect('h1').dom.not.to.have.text /following.*food/ expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() describe '#contain', -> describe 'on a dom element', -> it 'verifies that an element contains text', (done) -> expect('h1').dom.to.contain.text "Finnegan", done it 'verifies that an element does not contain text', (done) -> expect('h1').dom.not.to.contain.text "Bibimbap", done it 'returns a promise for affirmative', (done)-> promise = expect('h1').dom.to.contain.text "Finnegan" expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for negative', (done)-> promise = expect('h1').dom.not.to.contain.text "Bibimbap" expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() describe 'not on a dom element', -> it 'verifies that a string contains text', -> expect('John Finnegan').to.contain "Finnegan" it 'verifies that a string does not contain text', -> expect('John Finnegan').not.to.contain "Bibimbap" it 'does NOT return a promise', -> notPromise = expect('John Finnegan').to.contain "Finnegan" expect(notPromise).not.to.have.property 'then' describe '#match', -> it 'verifies that an element has a regexp match', (done) -> expect('h1').dom.to.match /following.*excerpt/, done it 'verifies that an element does not match the regexp', (done) -> expect('h1').dom.not.to.match /following.*food/, done it 'returns a promise for affirmative', (done)-> promise = expect('h1').dom.to.match /following.*excerpt/ expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for negative', (done)-> promise = expect('h1').dom.not.to.match /following.*food/ expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() describe 'not on a dom element', -> it 'verifies that a string does match the regexp', -> expect('some test text').to.match /test/ it 'verifies that a string does not match the regexp', -> expect('some test text').not.to.match /taste/ it 'does NOT return a promise', -> notPromise = expect('some test text').to.match /test/ expect(notPromise).not.to.have.property 'then' describe '#visible', -> it 'verifies that an element is visible', (done) -> expect('.does-exist:text').dom.to.be.visible done it 'verifies that a non-existing element is not visible', (done) -> expect('.does-not-exist').dom.not.to.be.visible done it 'verifies that a hidden element is not visible', (done) -> expect('.exists-but-hidden').dom.not.to.be.visible done it 'returns a promise for affirmative', (done)-> promise = expect('.does-exist:text').dom.to.be.visible() expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for non-existing', (done)-> promise = expect('.does-not-exist').dom.not.to.be.visible() expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for invisible', (done)-> promise = expect('.exists-but-hidden').dom.not.to.be.visible() expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() describe '#count', -> it 'verifies that an element appears thrice', (done) -> expect('input').dom.to.have.count 3, done it 'verifies that a non-existing element has a count of 0', (done) -> expect('.does-not-exist').dom.to.have.count 0, done it 'returns a promise for affirmative', (done)-> promise = expect('input').dom.to.have.count 3 expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for negative', (done)-> promise = expect('.does-not-exist').dom.not.to.have.count 3 expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() describe '#style', -> it 'verifies that an element has a red background', (done) -> expect('.red-bg').dom.to.have.style 'background-color', 'rgba(255, 0, 0, 1)', done it 'verifies that an element does not have a red background', (done) -> expect('.green-text').dom.to.have.style 'background-color', 'rgba(0, 0, 0, 0)', done it 'returns a promise for affirmative', (done)-> promise = expect('.red-bg').dom.to.have.style 'background-color', 'rgba(255, 0, 0, 1)' expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for negative', (done)-> promise = expect('.green-text').dom.to.have.style 'background-color', 'rgba(0, 0, 0, 0)' expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() describe '#value', -> it 'verifies that a text field has an equal value', (done) -> expect('.does-exist').dom.to.have.value 'People put stuff here', done it 'verifies that a text field has a matching value', (done) -> expect('.does-exist').dom.to.have.value /stuff/i, done it 'verifies that a text field does not have an equal value', (done) -> expect('.does-exist').dom.not.to.have.value 'Beep boop', done it 'returns a promise for affirmative', (done)-> promise = expect('.does-exist').dom.to.have.value 'People put stuff here' expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for negative', (done)-> promise = expect('.does-exist').dom.not.to.have.value 'Beep boop' expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() describe '#disabled', -> it 'verifies that an input is disabled', (done) -> expect('.i-am-disabled').dom.to.be.disabled done it 'verifies that an input is not disabled', (done) -> expect('.does-exist').dom.not.to.be.disabled done it 'returns a promise for affirmative', (done)-> promise = expect('.i-am-disabled').dom.to.be.disabled() expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for negative', (done)-> promise = expect('.does-exist').dom.not.to.be.disabled() expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() describe 'htmlClass', -> it 'verifies that an element has a given class', (done) -> expect('.does-exist').dom.to.have.htmlClass 'second-class', done it 'verifies than an element does not have a given class', (done) -> expect('.green-text').dom.not.to.have.htmlClass 'second-class', done it 'returns a promise for affirmative', (done)-> promise = expect('.does-exist').dom.to.have.htmlClass 'second-class' expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for negative', (done)-> promise = expect('.green-text').dom.not.to.have.htmlClass 'second-class' expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() describe 'attribute', -> it 'verifies that an element attribute has an equal value', (done) -> expect('input.does-exist').dom.to.have.attribute 'value', 'People put stuff here', done it 'verifies that an element attribute has a matching value', (done) -> expect('input.does-exist').dom.to.have.attribute 'value', /stuff/i, done it 'verifies that an element attribute does not have an equal value', (done) -> expect('input.does-exist').dom.not.to.have.attribute 'input', 'radio', done it 'verifies that an attribute does not exist', (done) -> expect('input.does-exist').dom.not.to.have.attribute 'href', done it 'verifies that an attribute exists', (done) -> expect('input.does-exist').dom.to.have.attribute 'type', done it 'verifies that an empty attribute exists', (done) -> expect('input.does-exist').dom.to.have.attribute 'empty', done it 'returns a promise for affirmative value', (done)-> promise = expect('input.does-exist').dom.to.have.attribute 'value', 'People put stuff here' expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for negative value', (done)-> promise = expect('input.does-exist').dom.not.to.have.attribute 'input', 'radio' expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for affirmative existence', (done)-> promise = expect('input.does-exist').dom.to.have.attribute 'type' expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for negative existence', (done)-> promise = expect('input.does-exist').dom.not.to.have.attribute 'href' expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() describe 'errors on failures', -> before (done) -> @timeout 0 # this may take a while in CI driver.get(url 'finnegan.html').then -> done() ## TODO -- actually they're just thrown. worth making this work? it.skip 'are passed to callback', (done) -> expect('h1').dom.to.have.text "La di da di da", (err)-> expect(err).to.exist.and.to.be.an.instanceOf(Error) expect(err.message).to.contain('Expected text of element') done() it 'are rejected with promise', (done)-> promise = expect('h1').dom.to.have.text "La di da di da" promise .then -> done new Error "Did not get expected error" .thenCatch (err)-> expect(err).to.exist.and.to.be.an.instanceOf(Error) expect(err.message).to.contain('Expected text of element') done() describe 'going to a different page', -> before (done) -> @timeout 0 driver.get(url 'link.html') driver.findElement(webdriver.By.name('link')).click().then -> done() it 'still allows you to make assertions', (done) -> expect('.does-exist:text').dom.to.to.be.visible done
210954
path = require 'path' webdriver = require 'selenium-webdriver' chai = require 'chai' chaiWebdriver = require '..' webdriver.logging = LevelName: 'DEBUG' # this seems like a bug in webdriver... driver = new webdriver.Builder() .withCapabilities(webdriver.Capabilities.phantomjs()) .build() chai.use chaiWebdriver(driver) {expect} = chai url = (page) -> "file://#{path.join __dirname, page}" after (done) -> driver.quit().then -> done() describe 'the basics', -> before (done) -> @timeout 0 # this may take a while in CI driver.get(url 'finnegan.html').then -> done() describe '#text', -> it 'verifies that an element has exact text', (done) -> expect('h1').dom.to.have.text "The following text is an excerpt from Finnegan's Wake by <NAME>", done it 'verifies that an element does not have exact text', (done) -> expect('h1').dom.not.to.have.text "Wake", done it 'returns a promise for affirmative', (done)-> promise = expect('h1').dom.to.have.text "The following text is an excerpt from Finnegan's Wake by <NAME>" expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for negative', (done)-> promise = expect('h1').dom.not.to.have.text "Wake" expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() describe '#text (regexp version)', -> it 'verifies that an element has a regexp match', (done) -> expect('h1').dom.to.have.text /following.*excerpt/, done it 'verifies that an element does not match the regexp', (done) -> expect('h1').dom.not.to.have.text /following.*food/, done it 'returns a promise for affirmative', (done)-> promise = expect('h1').dom.to.have.text /following.*excerpt/ expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for negative', (done)-> promise = expect('h1').dom.not.to.have.text /following.*food/ expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() describe '#contain', -> describe 'on a dom element', -> it 'verifies that an element contains text', (done) -> expect('h1').dom.to.contain.text "<NAME>", done it 'verifies that an element does not contain text', (done) -> expect('h1').dom.not.to.contain.text "<NAME>", done it 'returns a promise for affirmative', (done)-> promise = expect('h1').dom.to.contain.text "<NAME>" expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for negative', (done)-> promise = expect('h1').dom.not.to.contain.text "<NAME>" expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() describe 'not on a dom element', -> it 'verifies that a string contains text', -> expect('<NAME>').to.contain "<NAME>" it 'verifies that a string does not contain text', -> expect('<NAME>').not.to.contain "<NAME>" it 'does NOT return a promise', -> notPromise = expect('<NAME>').to.contain "<NAME>" expect(notPromise).not.to.have.property 'then' describe '#match', -> it 'verifies that an element has a regexp match', (done) -> expect('h1').dom.to.match /following.*excerpt/, done it 'verifies that an element does not match the regexp', (done) -> expect('h1').dom.not.to.match /following.*food/, done it 'returns a promise for affirmative', (done)-> promise = expect('h1').dom.to.match /following.*excerpt/ expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for negative', (done)-> promise = expect('h1').dom.not.to.match /following.*food/ expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() describe 'not on a dom element', -> it 'verifies that a string does match the regexp', -> expect('some test text').to.match /test/ it 'verifies that a string does not match the regexp', -> expect('some test text').not.to.match /taste/ it 'does NOT return a promise', -> notPromise = expect('some test text').to.match /test/ expect(notPromise).not.to.have.property 'then' describe '#visible', -> it 'verifies that an element is visible', (done) -> expect('.does-exist:text').dom.to.be.visible done it 'verifies that a non-existing element is not visible', (done) -> expect('.does-not-exist').dom.not.to.be.visible done it 'verifies that a hidden element is not visible', (done) -> expect('.exists-but-hidden').dom.not.to.be.visible done it 'returns a promise for affirmative', (done)-> promise = expect('.does-exist:text').dom.to.be.visible() expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for non-existing', (done)-> promise = expect('.does-not-exist').dom.not.to.be.visible() expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for invisible', (done)-> promise = expect('.exists-but-hidden').dom.not.to.be.visible() expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() describe '#count', -> it 'verifies that an element appears thrice', (done) -> expect('input').dom.to.have.count 3, done it 'verifies that a non-existing element has a count of 0', (done) -> expect('.does-not-exist').dom.to.have.count 0, done it 'returns a promise for affirmative', (done)-> promise = expect('input').dom.to.have.count 3 expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for negative', (done)-> promise = expect('.does-not-exist').dom.not.to.have.count 3 expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() describe '#style', -> it 'verifies that an element has a red background', (done) -> expect('.red-bg').dom.to.have.style 'background-color', 'rgba(255, 0, 0, 1)', done it 'verifies that an element does not have a red background', (done) -> expect('.green-text').dom.to.have.style 'background-color', 'rgba(0, 0, 0, 0)', done it 'returns a promise for affirmative', (done)-> promise = expect('.red-bg').dom.to.have.style 'background-color', 'rgba(255, 0, 0, 1)' expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for negative', (done)-> promise = expect('.green-text').dom.to.have.style 'background-color', 'rgba(0, 0, 0, 0)' expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() describe '#value', -> it 'verifies that a text field has an equal value', (done) -> expect('.does-exist').dom.to.have.value 'People put stuff here', done it 'verifies that a text field has a matching value', (done) -> expect('.does-exist').dom.to.have.value /stuff/i, done it 'verifies that a text field does not have an equal value', (done) -> expect('.does-exist').dom.not.to.have.value 'Beep boop', done it 'returns a promise for affirmative', (done)-> promise = expect('.does-exist').dom.to.have.value 'People put stuff here' expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for negative', (done)-> promise = expect('.does-exist').dom.not.to.have.value 'Beep boop' expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() describe '#disabled', -> it 'verifies that an input is disabled', (done) -> expect('.i-am-disabled').dom.to.be.disabled done it 'verifies that an input is not disabled', (done) -> expect('.does-exist').dom.not.to.be.disabled done it 'returns a promise for affirmative', (done)-> promise = expect('.i-am-disabled').dom.to.be.disabled() expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for negative', (done)-> promise = expect('.does-exist').dom.not.to.be.disabled() expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() describe 'htmlClass', -> it 'verifies that an element has a given class', (done) -> expect('.does-exist').dom.to.have.htmlClass 'second-class', done it 'verifies than an element does not have a given class', (done) -> expect('.green-text').dom.not.to.have.htmlClass 'second-class', done it 'returns a promise for affirmative', (done)-> promise = expect('.does-exist').dom.to.have.htmlClass 'second-class' expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for negative', (done)-> promise = expect('.green-text').dom.not.to.have.htmlClass 'second-class' expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() describe 'attribute', -> it 'verifies that an element attribute has an equal value', (done) -> expect('input.does-exist').dom.to.have.attribute 'value', 'People put stuff here', done it 'verifies that an element attribute has a matching value', (done) -> expect('input.does-exist').dom.to.have.attribute 'value', /stuff/i, done it 'verifies that an element attribute does not have an equal value', (done) -> expect('input.does-exist').dom.not.to.have.attribute 'input', 'radio', done it 'verifies that an attribute does not exist', (done) -> expect('input.does-exist').dom.not.to.have.attribute 'href', done it 'verifies that an attribute exists', (done) -> expect('input.does-exist').dom.to.have.attribute 'type', done it 'verifies that an empty attribute exists', (done) -> expect('input.does-exist').dom.to.have.attribute 'empty', done it 'returns a promise for affirmative value', (done)-> promise = expect('input.does-exist').dom.to.have.attribute 'value', 'People put stuff here' expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for negative value', (done)-> promise = expect('input.does-exist').dom.not.to.have.attribute 'input', 'radio' expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for affirmative existence', (done)-> promise = expect('input.does-exist').dom.to.have.attribute 'type' expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for negative existence', (done)-> promise = expect('input.does-exist').dom.not.to.have.attribute 'href' expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() describe 'errors on failures', -> before (done) -> @timeout 0 # this may take a while in CI driver.get(url 'finnegan.html').then -> done() ## TODO -- actually they're just thrown. worth making this work? it.skip 'are passed to callback', (done) -> expect('h1').dom.to.have.text "La di da di da", (err)-> expect(err).to.exist.and.to.be.an.instanceOf(Error) expect(err.message).to.contain('Expected text of element') done() it 'are rejected with promise', (done)-> promise = expect('h1').dom.to.have.text "La di da di da" promise .then -> done new Error "Did not get expected error" .thenCatch (err)-> expect(err).to.exist.and.to.be.an.instanceOf(Error) expect(err.message).to.contain('Expected text of element') done() describe 'going to a different page', -> before (done) -> @timeout 0 driver.get(url 'link.html') driver.findElement(webdriver.By.name('link')).click().then -> done() it 'still allows you to make assertions', (done) -> expect('.does-exist:text').dom.to.to.be.visible done
true
path = require 'path' webdriver = require 'selenium-webdriver' chai = require 'chai' chaiWebdriver = require '..' webdriver.logging = LevelName: 'DEBUG' # this seems like a bug in webdriver... driver = new webdriver.Builder() .withCapabilities(webdriver.Capabilities.phantomjs()) .build() chai.use chaiWebdriver(driver) {expect} = chai url = (page) -> "file://#{path.join __dirname, page}" after (done) -> driver.quit().then -> done() describe 'the basics', -> before (done) -> @timeout 0 # this may take a while in CI driver.get(url 'finnegan.html').then -> done() describe '#text', -> it 'verifies that an element has exact text', (done) -> expect('h1').dom.to.have.text "The following text is an excerpt from Finnegan's Wake by PI:NAME:<NAME>END_PI", done it 'verifies that an element does not have exact text', (done) -> expect('h1').dom.not.to.have.text "Wake", done it 'returns a promise for affirmative', (done)-> promise = expect('h1').dom.to.have.text "The following text is an excerpt from Finnegan's Wake by PI:NAME:<NAME>END_PI" expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for negative', (done)-> promise = expect('h1').dom.not.to.have.text "Wake" expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() describe '#text (regexp version)', -> it 'verifies that an element has a regexp match', (done) -> expect('h1').dom.to.have.text /following.*excerpt/, done it 'verifies that an element does not match the regexp', (done) -> expect('h1').dom.not.to.have.text /following.*food/, done it 'returns a promise for affirmative', (done)-> promise = expect('h1').dom.to.have.text /following.*excerpt/ expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for negative', (done)-> promise = expect('h1').dom.not.to.have.text /following.*food/ expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() describe '#contain', -> describe 'on a dom element', -> it 'verifies that an element contains text', (done) -> expect('h1').dom.to.contain.text "PI:NAME:<NAME>END_PI", done it 'verifies that an element does not contain text', (done) -> expect('h1').dom.not.to.contain.text "PI:NAME:<NAME>END_PI", done it 'returns a promise for affirmative', (done)-> promise = expect('h1').dom.to.contain.text "PI:NAME:<NAME>END_PI" expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for negative', (done)-> promise = expect('h1').dom.not.to.contain.text "PI:NAME:<NAME>END_PI" expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() describe 'not on a dom element', -> it 'verifies that a string contains text', -> expect('PI:NAME:<NAME>END_PI').to.contain "PI:NAME:<NAME>END_PI" it 'verifies that a string does not contain text', -> expect('PI:NAME:<NAME>END_PI').not.to.contain "PI:NAME:<NAME>END_PI" it 'does NOT return a promise', -> notPromise = expect('PI:NAME:<NAME>END_PI').to.contain "PI:NAME:<NAME>END_PI" expect(notPromise).not.to.have.property 'then' describe '#match', -> it 'verifies that an element has a regexp match', (done) -> expect('h1').dom.to.match /following.*excerpt/, done it 'verifies that an element does not match the regexp', (done) -> expect('h1').dom.not.to.match /following.*food/, done it 'returns a promise for affirmative', (done)-> promise = expect('h1').dom.to.match /following.*excerpt/ expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for negative', (done)-> promise = expect('h1').dom.not.to.match /following.*food/ expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() describe 'not on a dom element', -> it 'verifies that a string does match the regexp', -> expect('some test text').to.match /test/ it 'verifies that a string does not match the regexp', -> expect('some test text').not.to.match /taste/ it 'does NOT return a promise', -> notPromise = expect('some test text').to.match /test/ expect(notPromise).not.to.have.property 'then' describe '#visible', -> it 'verifies that an element is visible', (done) -> expect('.does-exist:text').dom.to.be.visible done it 'verifies that a non-existing element is not visible', (done) -> expect('.does-not-exist').dom.not.to.be.visible done it 'verifies that a hidden element is not visible', (done) -> expect('.exists-but-hidden').dom.not.to.be.visible done it 'returns a promise for affirmative', (done)-> promise = expect('.does-exist:text').dom.to.be.visible() expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for non-existing', (done)-> promise = expect('.does-not-exist').dom.not.to.be.visible() expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for invisible', (done)-> promise = expect('.exists-but-hidden').dom.not.to.be.visible() expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() describe '#count', -> it 'verifies that an element appears thrice', (done) -> expect('input').dom.to.have.count 3, done it 'verifies that a non-existing element has a count of 0', (done) -> expect('.does-not-exist').dom.to.have.count 0, done it 'returns a promise for affirmative', (done)-> promise = expect('input').dom.to.have.count 3 expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for negative', (done)-> promise = expect('.does-not-exist').dom.not.to.have.count 3 expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() describe '#style', -> it 'verifies that an element has a red background', (done) -> expect('.red-bg').dom.to.have.style 'background-color', 'rgba(255, 0, 0, 1)', done it 'verifies that an element does not have a red background', (done) -> expect('.green-text').dom.to.have.style 'background-color', 'rgba(0, 0, 0, 0)', done it 'returns a promise for affirmative', (done)-> promise = expect('.red-bg').dom.to.have.style 'background-color', 'rgba(255, 0, 0, 1)' expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for negative', (done)-> promise = expect('.green-text').dom.to.have.style 'background-color', 'rgba(0, 0, 0, 0)' expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() describe '#value', -> it 'verifies that a text field has an equal value', (done) -> expect('.does-exist').dom.to.have.value 'People put stuff here', done it 'verifies that a text field has a matching value', (done) -> expect('.does-exist').dom.to.have.value /stuff/i, done it 'verifies that a text field does not have an equal value', (done) -> expect('.does-exist').dom.not.to.have.value 'Beep boop', done it 'returns a promise for affirmative', (done)-> promise = expect('.does-exist').dom.to.have.value 'People put stuff here' expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for negative', (done)-> promise = expect('.does-exist').dom.not.to.have.value 'Beep boop' expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() describe '#disabled', -> it 'verifies that an input is disabled', (done) -> expect('.i-am-disabled').dom.to.be.disabled done it 'verifies that an input is not disabled', (done) -> expect('.does-exist').dom.not.to.be.disabled done it 'returns a promise for affirmative', (done)-> promise = expect('.i-am-disabled').dom.to.be.disabled() expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for negative', (done)-> promise = expect('.does-exist').dom.not.to.be.disabled() expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() describe 'htmlClass', -> it 'verifies that an element has a given class', (done) -> expect('.does-exist').dom.to.have.htmlClass 'second-class', done it 'verifies than an element does not have a given class', (done) -> expect('.green-text').dom.not.to.have.htmlClass 'second-class', done it 'returns a promise for affirmative', (done)-> promise = expect('.does-exist').dom.to.have.htmlClass 'second-class' expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for negative', (done)-> promise = expect('.green-text').dom.not.to.have.htmlClass 'second-class' expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() describe 'attribute', -> it 'verifies that an element attribute has an equal value', (done) -> expect('input.does-exist').dom.to.have.attribute 'value', 'People put stuff here', done it 'verifies that an element attribute has a matching value', (done) -> expect('input.does-exist').dom.to.have.attribute 'value', /stuff/i, done it 'verifies that an element attribute does not have an equal value', (done) -> expect('input.does-exist').dom.not.to.have.attribute 'input', 'radio', done it 'verifies that an attribute does not exist', (done) -> expect('input.does-exist').dom.not.to.have.attribute 'href', done it 'verifies that an attribute exists', (done) -> expect('input.does-exist').dom.to.have.attribute 'type', done it 'verifies that an empty attribute exists', (done) -> expect('input.does-exist').dom.to.have.attribute 'empty', done it 'returns a promise for affirmative value', (done)-> promise = expect('input.does-exist').dom.to.have.attribute 'value', 'People put stuff here' expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for negative value', (done)-> promise = expect('input.does-exist').dom.not.to.have.attribute 'input', 'radio' expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for affirmative existence', (done)-> promise = expect('input.does-exist').dom.to.have.attribute 'type' expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() it 'returns a promise for negative existence', (done)-> promise = expect('input.does-exist').dom.not.to.have.attribute 'href' expect(promise).to.exist.and.to.have.property 'then' promise.then -> done() describe 'errors on failures', -> before (done) -> @timeout 0 # this may take a while in CI driver.get(url 'finnegan.html').then -> done() ## TODO -- actually they're just thrown. worth making this work? it.skip 'are passed to callback', (done) -> expect('h1').dom.to.have.text "La di da di da", (err)-> expect(err).to.exist.and.to.be.an.instanceOf(Error) expect(err.message).to.contain('Expected text of element') done() it 'are rejected with promise', (done)-> promise = expect('h1').dom.to.have.text "La di da di da" promise .then -> done new Error "Did not get expected error" .thenCatch (err)-> expect(err).to.exist.and.to.be.an.instanceOf(Error) expect(err.message).to.contain('Expected text of element') done() describe 'going to a different page', -> before (done) -> @timeout 0 driver.get(url 'link.html') driver.findElement(webdriver.By.name('link')).click().then -> done() it 'still allows you to make assertions', (done) -> expect('.does-exist:text').dom.to.to.be.visible done
[ { "context": "rbot\n# A NodeJS module for creating Twitter Bots\n# Nathaniel Kirby <nate@projectspong.com\n# https://github.com/nkirb", "end": 132, "score": 0.9998750686645508, "start": 117, "tag": "NAME", "value": "Nathaniel Kirby" }, { "context": "dule for creating Twitter Bots\n# Nathaniel Kirby <nate@projectspong.com\n# https://github.com/nkirby/node-twitterbot\n#####", "end": 155, "score": 0.9999342560768127, "start": 134, "tag": "EMAIL", "value": "nate@projectspong.com" }, { "context": "Kirby <nate@projectspong.com\n# https://github.com/nkirby/node-twitterbot\n#################################", "end": 183, "score": 0.9988481402397156, "start": 177, "tag": "USERNAME", "value": "nkirby" } ]
src/twitterbot.coffee
nkirby/node-twitterbot
75
#################################################### # node-twitterbot # A NodeJS module for creating Twitter Bots # Nathaniel Kirby <nate@projectspong.com # https://github.com/nkirby/node-twitterbot #################################################### fs = require 'fs' Twit = require 'twit' eventEmitter = require('events').EventEmitter class TwitterBot extends eventEmitter constructor: (configOrFile) -> if typeof configOrFile is "string" try @config = JSON.parse fs.readFileSync(configOrFile) catch e throw e else @config = configOrFile @actions = [] @streamAction = new TwitterBotStreamAction( () -> @start() this ) @setupTwit() setupTwit: () -> @twitter = new Twit({ consumer_secret: @config.consumer_secret consumer_key: @config.consumer_key access_token: @config.access_token access_token_secret: @config.access_token_secret }) this #################################################### # Tweeting tweet: (text, callback) -> if typeof text isnt "string" return callback {message:"Cannot post a non-string"}, null; @twitter.post "statuses/update", {status:text}, (err, response) -> if callback and typeof callback is "function" callback err, response #################################################### # Actions addAction: (actionName, callback) -> if typeof callback is "function" action = new TwitterBotAction callback, this else action = callback action.name = actionName @actions.push action @on actionName, (params) => action.emit "action", params action removeAction: (actionName) -> @removeAllListeners actionName index = @actions.indexOf actionName if index > -1 @actions.splice index, 1 allActions: (groupName) -> actions = [] for action in @actions if groupName if action.isPartOfGroup(groupName) actions.push action.name else actions.push action actions actionWithName: (actionName) -> for action in @actions if action.name is actionName return action null randomAction: (groupName) -> actions = @allActions groupName actionItem = actions[Math.floor(Math.random()*actions.length)] actionItem randomWeightedAction: (groupName) -> weightedActions = []; for action in @actions weight = action.getWeight() for i in [0..weight] weightedActions.push action.name weightedActions[Math.floor(Math.random() * weightedActions.length)] #################################################### # Streaming startStreaming: () -> @streamAction.start() stopStreaming: () -> @streamAction.stop() listen: (name, match, action) -> @streamAction.listen name, match, action #################################################### # Scheduling schedule: (action, timeout, tweet) -> if not timeout return @now action now: (action, tweet) -> if typeof action is "string" action = @actionWithName action else if typeof action is "function" action = new TwitterBotAction callback, this action.emit "action", @twitter, tweet module.exports.TwitterBot = TwitterBot
121897
#################################################### # node-twitterbot # A NodeJS module for creating Twitter Bots # <NAME> <<EMAIL> # https://github.com/nkirby/node-twitterbot #################################################### fs = require 'fs' Twit = require 'twit' eventEmitter = require('events').EventEmitter class TwitterBot extends eventEmitter constructor: (configOrFile) -> if typeof configOrFile is "string" try @config = JSON.parse fs.readFileSync(configOrFile) catch e throw e else @config = configOrFile @actions = [] @streamAction = new TwitterBotStreamAction( () -> @start() this ) @setupTwit() setupTwit: () -> @twitter = new Twit({ consumer_secret: @config.consumer_secret consumer_key: @config.consumer_key access_token: @config.access_token access_token_secret: @config.access_token_secret }) this #################################################### # Tweeting tweet: (text, callback) -> if typeof text isnt "string" return callback {message:"Cannot post a non-string"}, null; @twitter.post "statuses/update", {status:text}, (err, response) -> if callback and typeof callback is "function" callback err, response #################################################### # Actions addAction: (actionName, callback) -> if typeof callback is "function" action = new TwitterBotAction callback, this else action = callback action.name = actionName @actions.push action @on actionName, (params) => action.emit "action", params action removeAction: (actionName) -> @removeAllListeners actionName index = @actions.indexOf actionName if index > -1 @actions.splice index, 1 allActions: (groupName) -> actions = [] for action in @actions if groupName if action.isPartOfGroup(groupName) actions.push action.name else actions.push action actions actionWithName: (actionName) -> for action in @actions if action.name is actionName return action null randomAction: (groupName) -> actions = @allActions groupName actionItem = actions[Math.floor(Math.random()*actions.length)] actionItem randomWeightedAction: (groupName) -> weightedActions = []; for action in @actions weight = action.getWeight() for i in [0..weight] weightedActions.push action.name weightedActions[Math.floor(Math.random() * weightedActions.length)] #################################################### # Streaming startStreaming: () -> @streamAction.start() stopStreaming: () -> @streamAction.stop() listen: (name, match, action) -> @streamAction.listen name, match, action #################################################### # Scheduling schedule: (action, timeout, tweet) -> if not timeout return @now action now: (action, tweet) -> if typeof action is "string" action = @actionWithName action else if typeof action is "function" action = new TwitterBotAction callback, this action.emit "action", @twitter, tweet module.exports.TwitterBot = TwitterBot
true
#################################################### # node-twitterbot # A NodeJS module for creating Twitter Bots # PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI # https://github.com/nkirby/node-twitterbot #################################################### fs = require 'fs' Twit = require 'twit' eventEmitter = require('events').EventEmitter class TwitterBot extends eventEmitter constructor: (configOrFile) -> if typeof configOrFile is "string" try @config = JSON.parse fs.readFileSync(configOrFile) catch e throw e else @config = configOrFile @actions = [] @streamAction = new TwitterBotStreamAction( () -> @start() this ) @setupTwit() setupTwit: () -> @twitter = new Twit({ consumer_secret: @config.consumer_secret consumer_key: @config.consumer_key access_token: @config.access_token access_token_secret: @config.access_token_secret }) this #################################################### # Tweeting tweet: (text, callback) -> if typeof text isnt "string" return callback {message:"Cannot post a non-string"}, null; @twitter.post "statuses/update", {status:text}, (err, response) -> if callback and typeof callback is "function" callback err, response #################################################### # Actions addAction: (actionName, callback) -> if typeof callback is "function" action = new TwitterBotAction callback, this else action = callback action.name = actionName @actions.push action @on actionName, (params) => action.emit "action", params action removeAction: (actionName) -> @removeAllListeners actionName index = @actions.indexOf actionName if index > -1 @actions.splice index, 1 allActions: (groupName) -> actions = [] for action in @actions if groupName if action.isPartOfGroup(groupName) actions.push action.name else actions.push action actions actionWithName: (actionName) -> for action in @actions if action.name is actionName return action null randomAction: (groupName) -> actions = @allActions groupName actionItem = actions[Math.floor(Math.random()*actions.length)] actionItem randomWeightedAction: (groupName) -> weightedActions = []; for action in @actions weight = action.getWeight() for i in [0..weight] weightedActions.push action.name weightedActions[Math.floor(Math.random() * weightedActions.length)] #################################################### # Streaming startStreaming: () -> @streamAction.start() stopStreaming: () -> @streamAction.stop() listen: (name, match, action) -> @streamAction.listen name, match, action #################################################### # Scheduling schedule: (action, timeout, tweet) -> if not timeout return @now action now: (action, tweet) -> if typeof action is "string" action = @actionWithName action else if typeof action is "function" action = new TwitterBotAction callback, this action.emit "action", @twitter, tweet module.exports.TwitterBot = TwitterBot
[ { "context": " sessionSecret: process.env.SESSION_SECRET or \"9a205fba94b140e59456d3a5128075bd\"\n port: process.env", "end": 154, "score": 0.6117697954177856, "start": 149, "tag": "KEY", "value": "9a205" }, { "context": "cret: process.env.SESSION_SECRET or \"9a205fba94b140e59456d3a5128075bd\"\n port: process.env.PORT or ", "end": 163, "score": 0.5220791697502136, "start": 162, "tag": "KEY", "value": "0" }, { "context": "et: process.env.SESSION_SECRET or \"9a205fba94b140e59456d3a5128075bd\"\n port: process.env.PORT or 300", "end": 166, "score": 0.5451518297195435, "start": 164, "tag": "KEY", "value": "59" }, { "context": "ess.env.SESSION_SECRET or \"9a205fba94b140e59456d3a5128075bd\"\n port: process.env.PORT or 3000\n\n gi", "end": 175, "score": 0.5273436903953552, "start": 172, "tag": "KEY", "value": "512" }, { "context": "v.SESSION_SECRET or \"9a205fba94b140e59456d3a5128075bd\"\n port: process.env.PORT or 3000\n\n githubAp", "end": 181, "score": 0.5491105318069458, "start": 178, "tag": "KEY", "value": "5bd" }, { "context": "ithubAppSecret: process.env.GITHUB_APP_SECRET or \"580bca105f63c8173cfa72832c99f7d96a832662\"\n githubRedirectRoute: \"/login/github/callback", "end": 383, "score": 0.9946767091751099, "start": 343, "tag": "KEY", "value": "580bca105f63c8173cfa72832c99f7d96a832662" } ]
config.coffee
rfloriano/pagarme-github-test
0
module.exports = mongoUrl: process.env.MONGO_URL or "mongodb://localhost/pagarme-github-test" sessionSecret: process.env.SESSION_SECRET or "9a205fba94b140e59456d3a5128075bd" port: process.env.PORT or 3000 githubAppId: process.env.GITHUB_APP_ID or "9e0a6ba06413b22eea38" githubAppSecret: process.env.GITHUB_APP_SECRET or "580bca105f63c8173cfa72832c99f7d96a832662" githubRedirectRoute: "/login/github/callback" githubAppRedirect: process.env.GITHUB_APP_REDIRECT or "http://local.pagarme-github-test.com:3000/login/github/callback"
186965
module.exports = mongoUrl: process.env.MONGO_URL or "mongodb://localhost/pagarme-github-test" sessionSecret: process.env.SESSION_SECRET or "<KEY>fba94b14<KEY>e<KEY>456d3a<KEY>807<KEY>" port: process.env.PORT or 3000 githubAppId: process.env.GITHUB_APP_ID or "9e0a6ba06413b22eea38" githubAppSecret: process.env.GITHUB_APP_SECRET or "<KEY>" githubRedirectRoute: "/login/github/callback" githubAppRedirect: process.env.GITHUB_APP_REDIRECT or "http://local.pagarme-github-test.com:3000/login/github/callback"
true
module.exports = mongoUrl: process.env.MONGO_URL or "mongodb://localhost/pagarme-github-test" sessionSecret: process.env.SESSION_SECRET or "PI:KEY:<KEY>END_PIfba94b14PI:KEY:<KEY>END_PIePI:KEY:<KEY>END_PI456d3aPI:KEY:<KEY>END_PI807PI:KEY:<KEY>END_PI" port: process.env.PORT or 3000 githubAppId: process.env.GITHUB_APP_ID or "9e0a6ba06413b22eea38" githubAppSecret: process.env.GITHUB_APP_SECRET or "PI:KEY:<KEY>END_PI" githubRedirectRoute: "/login/github/callback" githubAppRedirect: process.env.GITHUB_APP_REDIRECT or "http://local.pagarme-github-test.com:3000/login/github/callback"
[ { "context": "xtrous', 'flow'\n\t]\n\tauthor: '2015+ Bevry Pty Ltd <us@bevry.me> (http://bevry.me), 2011-2014 Benjamin Lupton <b@", "end": 539, "score": 0.9999310374259949, "start": 528, "tag": "EMAIL", "value": "us@bevry.me" }, { "context": "Pty Ltd <us@bevry.me> (http://bevry.me), 2011-2014 Benjamin Lupton <b@lupton.cc> (http://balupton.com)'\n\tmaintainers", "end": 585, "score": 0.9999030828475952, "start": 570, "tag": "NAME", "value": "Benjamin Lupton" }, { "context": "me> (http://bevry.me), 2011-2014 Benjamin Lupton <b@lupton.cc> (http://balupton.com)'\n\tmaintainers: [\n\t\t'Benjam", "end": 598, "score": 0.9999268054962158, "start": 587, "tag": "EMAIL", "value": "b@lupton.cc" }, { "context": "ton.cc> (http://balupton.com)'\n\tmaintainers: [\n\t\t'Benjamin Lupton <b@lupton.cc> (https://github.com/balupton)'\n\t]\n\t", "end": 657, "score": 0.9999023675918579, "start": 642, "tag": "NAME", "value": "Benjamin Lupton" }, { "context": "alupton.com)'\n\tmaintainers: [\n\t\t'Benjamin Lupton <b@lupton.cc> (https://github.com/balupton)'\n\t]\n\tbadges: {\n\t\t\"", "end": 670, "score": 0.9999274611473083, "start": 659, "tag": "EMAIL", "value": "b@lupton.cc" }, { "context": "Benjamin Lupton <b@lupton.cc> (https://github.com/balupton)'\n\t]\n\tbadges: {\n\t\t\"list\": [\n\t\t\t\"travisci\",\n\t\t\t\"np", "end": 700, "score": 0.9994065761566162, "start": 692, "tag": "USERNAME", "value": "balupton" }, { "context": "shlist\"\n\t\t],\n\t\t\"config\": {\n\t\t\t\"patreonUsername\": \"bevry\",\n\t\t\t\"gratipayUsername\": \"bevry\",\n\t\t\t\"flattrCode\"", "end": 965, "score": 0.9996358752250671, "start": 960, "tag": "USERNAME", "value": "bevry" }, { "context": "atreonUsername\": \"bevry\",\n\t\t\t\"gratipayUsername\": \"bevry\",\n\t\t\t\"flattrCode\": \"344188/balupton-on-Flattr\",\n\t", "end": 997, "score": 0.9996287226676941, "start": 992, "tag": "USERNAME", "value": "bevry" } ]
test-fixtures/src/projectz.cson
oliverlorenz/projectz
1
{ # ================================= # META name: "ambi" repo: "bevry/ambi" version: "2.1.4" license: "(MIT AND CC-BY-4.0)" description: "Execute a function ambidextrously (normalizes the differences between synchronous and asynchronous functions). Useful for treating synchronous functions as asynchronous functions (like supporting both synchronous and asynchronous event definitions automatically)." keywords: [ 'sync', 'async', 'fire', 'exec', 'execute', 'ambidextrous', 'flow' ] author: '2015+ Bevry Pty Ltd <us@bevry.me> (http://bevry.me), 2011-2014 Benjamin Lupton <b@lupton.cc> (http://balupton.com)' maintainers: [ 'Benjamin Lupton <b@lupton.cc> (https://github.com/balupton)' ] badges: { "list": [ "travisci", "npmversion", "npmdownloads", "daviddm", "daviddmdev", "---", "slackin", "patreon", "gratipay", "flattr", "paypal", "bitcoin", "wishlist" ], "config": { "patreonUsername": "bevry", "gratipayUsername": "bevry", "flattrCode": "344188/balupton-on-Flattr", "paypalButtonID": "QB8GQPZAH84N6", "bitcoinURL": "https://bevry.me/bitcoin", "wishlistURL": "https://bevry.me/wishlist", "slackinURL": "https://slack.bevry.me" } } dependencies: "typechecker": "~2.0.6" engines: node: ">=0.8" scripts: preinstall: "node ./cyclic.js" test: "node ./out/text/everything-test.js" main: "./out/lib/ambi.js" # auto detected and enhanced # - homepage # - authors # - maintainers # - keywords # - license # - repository # - bugs # - badges # ================================= # Custom Configuration packages: component: dependencies: "bevry/typechecker": "master" }
174223
{ # ================================= # META name: "ambi" repo: "bevry/ambi" version: "2.1.4" license: "(MIT AND CC-BY-4.0)" description: "Execute a function ambidextrously (normalizes the differences between synchronous and asynchronous functions). Useful for treating synchronous functions as asynchronous functions (like supporting both synchronous and asynchronous event definitions automatically)." keywords: [ 'sync', 'async', 'fire', 'exec', 'execute', 'ambidextrous', 'flow' ] author: '2015+ Bevry Pty Ltd <<EMAIL>> (http://bevry.me), 2011-2014 <NAME> <<EMAIL>> (http://balupton.com)' maintainers: [ '<NAME> <<EMAIL>> (https://github.com/balupton)' ] badges: { "list": [ "travisci", "npmversion", "npmdownloads", "daviddm", "daviddmdev", "---", "slackin", "patreon", "gratipay", "flattr", "paypal", "bitcoin", "wishlist" ], "config": { "patreonUsername": "bevry", "gratipayUsername": "bevry", "flattrCode": "344188/balupton-on-Flattr", "paypalButtonID": "QB8GQPZAH84N6", "bitcoinURL": "https://bevry.me/bitcoin", "wishlistURL": "https://bevry.me/wishlist", "slackinURL": "https://slack.bevry.me" } } dependencies: "typechecker": "~2.0.6" engines: node: ">=0.8" scripts: preinstall: "node ./cyclic.js" test: "node ./out/text/everything-test.js" main: "./out/lib/ambi.js" # auto detected and enhanced # - homepage # - authors # - maintainers # - keywords # - license # - repository # - bugs # - badges # ================================= # Custom Configuration packages: component: dependencies: "bevry/typechecker": "master" }
true
{ # ================================= # META name: "ambi" repo: "bevry/ambi" version: "2.1.4" license: "(MIT AND CC-BY-4.0)" description: "Execute a function ambidextrously (normalizes the differences between synchronous and asynchronous functions). Useful for treating synchronous functions as asynchronous functions (like supporting both synchronous and asynchronous event definitions automatically)." keywords: [ 'sync', 'async', 'fire', 'exec', 'execute', 'ambidextrous', 'flow' ] author: '2015+ Bevry Pty Ltd <PI:EMAIL:<EMAIL>END_PI> (http://bevry.me), 2011-2014 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> (http://balupton.com)' maintainers: [ 'PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> (https://github.com/balupton)' ] badges: { "list": [ "travisci", "npmversion", "npmdownloads", "daviddm", "daviddmdev", "---", "slackin", "patreon", "gratipay", "flattr", "paypal", "bitcoin", "wishlist" ], "config": { "patreonUsername": "bevry", "gratipayUsername": "bevry", "flattrCode": "344188/balupton-on-Flattr", "paypalButtonID": "QB8GQPZAH84N6", "bitcoinURL": "https://bevry.me/bitcoin", "wishlistURL": "https://bevry.me/wishlist", "slackinURL": "https://slack.bevry.me" } } dependencies: "typechecker": "~2.0.6" engines: node: ">=0.8" scripts: preinstall: "node ./cyclic.js" test: "node ./out/text/everything-test.js" main: "./out/lib/ambi.js" # auto detected and enhanced # - homepage # - authors # - maintainers # - keywords # - license # - repository # - bugs # - badges # ================================= # Custom Configuration packages: component: dependencies: "bevry/typechecker": "master" }
[ { "context": "# Author: Josh Bass\n# Description: Purpose of main here is to create ", "end": 19, "score": 0.9998711943626404, "start": 10, "tag": "NAME", "value": "Josh Bass" } ]
src/client/main.coffee
jbass86/Aroma
0
# Author: Josh Bass # Description: Purpose of main here is to create the main react component and lay out all of the # sub components window.$ = window.jQuery = window.jquery = require("jquery"); require('bootstrap'); React = require("react"); ReactDOM = require("react-dom"); #require ("css/main.css"); require("../../node_modules/bootstrap/dist/css/bootstrap.css"); require("../../node_modules/react-datepicker/dist/react-datepicker.css"); #require("../../node_modules/react-widgets/dist/css/react-widgets.css"); require("styles/main.scss"); HeaderBar = require("components/header_bar/HeaderBarView.coffee"); NavigationBar = require("components/navigation_bar/NavigationBarview.coffee"); LoginView = require("components/login/LoginView.coffee"); NavView = require("components/navigation_view/NavigationView.coffee"); Inventory = require("components/inventory/InventoryView.coffee"); Customers = require("components/customers/CustomerView.coffee"); Orders = require("components/orders/OrderView.coffee"); Analytics = require("components/analytics/AnalyticsView.coffee"); #DropdownList = require("react-widgets").DropdownList; Backbone = require("backbone"); $(() -> nav_model = new Backbone.Model(); nav_model.set("authenticated", false); nav_model.set("remove_login", false); order_model = new Backbone.Model(); comp = React.createClass getInitialState: () -> {authenticated: nav_model.get("authenticated"), remove_login: nav_model.get("remove_login")}; render: () -> <div> <div className={@getLoginClasses()}> <LoginView login_success={@handleLoginSuccess}/> </div> {@renderMain()} </div> renderMain: () -> if (@state.authenticated) <div> <NavigationBar nav_model={nav_model}/> <div className={"header-area" + @getMainClasses()}> <HeaderBar nav_model={nav_model}/> </div> <div className={"main-area" + @getMainClasses()} onClick={@closeNav}> <NavView nav_model={nav_model} name="orders"> <Orders nav_model={nav_model} order_model={order_model} /> </NavView> <NavView nav_model={nav_model} name="customers"> <Customers nav_model={nav_model} order_model={order_model} /> </NavView> <NavView nav_model={nav_model} name="inventory"> <Inventory order_model={order_model} /> </NavView> <NavView nav_model={nav_model} name="analytics"> <Analytics nav_model={nav_model} /> </NavView> </div> </div> else <div style={{"width": "100vw", "height": "100vh"}}></div> getLoginClasses: () -> classes = ""; if (@state.authenticated) classes += " fade-out"; if (@state.remove_login) classes += " display-none"; classes; getMainClasses: () -> classes = ""; if (@state.authenticated) classes += " fade-in"; else classes += " fade-out" classes; handleLoginSuccess: (login_data) -> window.sessionStorage.token = login_data.token; window.user_info = {username: login_data.username, group: login_data.group}; @setState({authenticated: true}); window.setTimeout(()=> @setState({remove_login: true}); , 1000); closeNav: () -> nav_model.set("nav_visible", false); if (window.sessionStorage.token) $.post("aroma/secure/authenticate_token", {token: window.sessionStorage.token}, (response) => window.user_info = {username: response.username, group: response.group}; nav_model.set("authenticated", response.success); nav_model.set("remove_login", response.success); ReactDOM.render(React.createElement(comp, null), $("#react-body").get(0)); ); else ReactDOM.render(React.createElement(comp, null), $("#react-body").get(0)); );
134583
# Author: <NAME> # Description: Purpose of main here is to create the main react component and lay out all of the # sub components window.$ = window.jQuery = window.jquery = require("jquery"); require('bootstrap'); React = require("react"); ReactDOM = require("react-dom"); #require ("css/main.css"); require("../../node_modules/bootstrap/dist/css/bootstrap.css"); require("../../node_modules/react-datepicker/dist/react-datepicker.css"); #require("../../node_modules/react-widgets/dist/css/react-widgets.css"); require("styles/main.scss"); HeaderBar = require("components/header_bar/HeaderBarView.coffee"); NavigationBar = require("components/navigation_bar/NavigationBarview.coffee"); LoginView = require("components/login/LoginView.coffee"); NavView = require("components/navigation_view/NavigationView.coffee"); Inventory = require("components/inventory/InventoryView.coffee"); Customers = require("components/customers/CustomerView.coffee"); Orders = require("components/orders/OrderView.coffee"); Analytics = require("components/analytics/AnalyticsView.coffee"); #DropdownList = require("react-widgets").DropdownList; Backbone = require("backbone"); $(() -> nav_model = new Backbone.Model(); nav_model.set("authenticated", false); nav_model.set("remove_login", false); order_model = new Backbone.Model(); comp = React.createClass getInitialState: () -> {authenticated: nav_model.get("authenticated"), remove_login: nav_model.get("remove_login")}; render: () -> <div> <div className={@getLoginClasses()}> <LoginView login_success={@handleLoginSuccess}/> </div> {@renderMain()} </div> renderMain: () -> if (@state.authenticated) <div> <NavigationBar nav_model={nav_model}/> <div className={"header-area" + @getMainClasses()}> <HeaderBar nav_model={nav_model}/> </div> <div className={"main-area" + @getMainClasses()} onClick={@closeNav}> <NavView nav_model={nav_model} name="orders"> <Orders nav_model={nav_model} order_model={order_model} /> </NavView> <NavView nav_model={nav_model} name="customers"> <Customers nav_model={nav_model} order_model={order_model} /> </NavView> <NavView nav_model={nav_model} name="inventory"> <Inventory order_model={order_model} /> </NavView> <NavView nav_model={nav_model} name="analytics"> <Analytics nav_model={nav_model} /> </NavView> </div> </div> else <div style={{"width": "100vw", "height": "100vh"}}></div> getLoginClasses: () -> classes = ""; if (@state.authenticated) classes += " fade-out"; if (@state.remove_login) classes += " display-none"; classes; getMainClasses: () -> classes = ""; if (@state.authenticated) classes += " fade-in"; else classes += " fade-out" classes; handleLoginSuccess: (login_data) -> window.sessionStorage.token = login_data.token; window.user_info = {username: login_data.username, group: login_data.group}; @setState({authenticated: true}); window.setTimeout(()=> @setState({remove_login: true}); , 1000); closeNav: () -> nav_model.set("nav_visible", false); if (window.sessionStorage.token) $.post("aroma/secure/authenticate_token", {token: window.sessionStorage.token}, (response) => window.user_info = {username: response.username, group: response.group}; nav_model.set("authenticated", response.success); nav_model.set("remove_login", response.success); ReactDOM.render(React.createElement(comp, null), $("#react-body").get(0)); ); else ReactDOM.render(React.createElement(comp, null), $("#react-body").get(0)); );
true
# Author: PI:NAME:<NAME>END_PI # Description: Purpose of main here is to create the main react component and lay out all of the # sub components window.$ = window.jQuery = window.jquery = require("jquery"); require('bootstrap'); React = require("react"); ReactDOM = require("react-dom"); #require ("css/main.css"); require("../../node_modules/bootstrap/dist/css/bootstrap.css"); require("../../node_modules/react-datepicker/dist/react-datepicker.css"); #require("../../node_modules/react-widgets/dist/css/react-widgets.css"); require("styles/main.scss"); HeaderBar = require("components/header_bar/HeaderBarView.coffee"); NavigationBar = require("components/navigation_bar/NavigationBarview.coffee"); LoginView = require("components/login/LoginView.coffee"); NavView = require("components/navigation_view/NavigationView.coffee"); Inventory = require("components/inventory/InventoryView.coffee"); Customers = require("components/customers/CustomerView.coffee"); Orders = require("components/orders/OrderView.coffee"); Analytics = require("components/analytics/AnalyticsView.coffee"); #DropdownList = require("react-widgets").DropdownList; Backbone = require("backbone"); $(() -> nav_model = new Backbone.Model(); nav_model.set("authenticated", false); nav_model.set("remove_login", false); order_model = new Backbone.Model(); comp = React.createClass getInitialState: () -> {authenticated: nav_model.get("authenticated"), remove_login: nav_model.get("remove_login")}; render: () -> <div> <div className={@getLoginClasses()}> <LoginView login_success={@handleLoginSuccess}/> </div> {@renderMain()} </div> renderMain: () -> if (@state.authenticated) <div> <NavigationBar nav_model={nav_model}/> <div className={"header-area" + @getMainClasses()}> <HeaderBar nav_model={nav_model}/> </div> <div className={"main-area" + @getMainClasses()} onClick={@closeNav}> <NavView nav_model={nav_model} name="orders"> <Orders nav_model={nav_model} order_model={order_model} /> </NavView> <NavView nav_model={nav_model} name="customers"> <Customers nav_model={nav_model} order_model={order_model} /> </NavView> <NavView nav_model={nav_model} name="inventory"> <Inventory order_model={order_model} /> </NavView> <NavView nav_model={nav_model} name="analytics"> <Analytics nav_model={nav_model} /> </NavView> </div> </div> else <div style={{"width": "100vw", "height": "100vh"}}></div> getLoginClasses: () -> classes = ""; if (@state.authenticated) classes += " fade-out"; if (@state.remove_login) classes += " display-none"; classes; getMainClasses: () -> classes = ""; if (@state.authenticated) classes += " fade-in"; else classes += " fade-out" classes; handleLoginSuccess: (login_data) -> window.sessionStorage.token = login_data.token; window.user_info = {username: login_data.username, group: login_data.group}; @setState({authenticated: true}); window.setTimeout(()=> @setState({remove_login: true}); , 1000); closeNav: () -> nav_model.set("nav_visible", false); if (window.sessionStorage.token) $.post("aroma/secure/authenticate_token", {token: window.sessionStorage.token}, (response) => window.user_info = {username: response.username, group: response.group}; nav_model.set("authenticated", response.success); nav_model.set("remove_login", response.success); ReactDOM.render(React.createElement(comp, null), $("#react-body").get(0)); ); else ReactDOM.render(React.createElement(comp, null), $("#react-body").get(0)); );
[ { "context": "e.equal ''\n expect(wallet.name).to.be.equal 'Qiwi'\n expect(wallet.pattern).to.contain 'Номер", "end": 1319, "score": 0.6213667988777161, "start": 1317, "tag": "NAME", "value": "Qi" } ]
src/Vifeed/FrontendBundle/Tests/unit/publisher/resources/wallets.spec.coffee
bzis/zomba
0
describe 'Wallets', -> beforeEach( -> module 'resources.wallets' ) describe 'Resource', -> wallets = {} httpBackend = {} mock = {} expect = chai.expect beforeEach(inject ($httpBackend, Wallets) -> httpBackend = $httpBackend wallets = Wallets mock = new WalletsMock(httpBackend) mock.mockOkResponse() ) it 'should have default resource url', -> expect(wallets.resourceUrl).to.equal '/api/wallets' it 'should have 3 constants', -> expect(wallets.TYPE_YANDEX_MONEY).to.equal 'yandex' expect(wallets.TYPE_WEB_MONEY).to.equal 'wm' expect(wallets.TYPE_QIWI).to.equal 'qiwi' it 'should have Qiwi as default wallet', -> wallet = null wallets.new().then (response) -> wallet = response httpBackend.flush() expect(wallet).to.have.ownProperty 'id' expect(wallet).to.have.ownProperty 'type' expect(wallet).to.have.ownProperty 'number' expect(wallet).to.have.ownProperty 'name' expect(wallet).to.have.ownProperty 'format' expect(wallet).to.have.ownProperty 'pattern' expect(wallet).to.have.ownProperty 'hint' expect(wallet.id).to.be.equal null expect(wallet.type).to.be.equal 'qiwi' expect(wallet.number).to.be.equal '' expect(wallet.name).to.be.equal 'Qiwi' expect(wallet.pattern).to.contain 'Номер Qiwi' expect(wallet.hint).to.contain 'Номер кошелька Qiwi' it 'should return list of wallets', -> reply = [] wallets.all().then (response) -> reply = response httpBackend.flush() expect(reply).to.have.length 3 expect(reply[0]).to.have.ownProperty 'name' expect(reply[0].name).to.be.equal 'Qiwi' expect(reply[1]).to.have.ownProperty 'name' expect(reply[1].name).to.be.equal 'WebMoney' expect(reply[2]).to.have.ownProperty 'name' expect(reply[2].name).to.be.equal 'Яндекс.Деньги'
172876
describe 'Wallets', -> beforeEach( -> module 'resources.wallets' ) describe 'Resource', -> wallets = {} httpBackend = {} mock = {} expect = chai.expect beforeEach(inject ($httpBackend, Wallets) -> httpBackend = $httpBackend wallets = Wallets mock = new WalletsMock(httpBackend) mock.mockOkResponse() ) it 'should have default resource url', -> expect(wallets.resourceUrl).to.equal '/api/wallets' it 'should have 3 constants', -> expect(wallets.TYPE_YANDEX_MONEY).to.equal 'yandex' expect(wallets.TYPE_WEB_MONEY).to.equal 'wm' expect(wallets.TYPE_QIWI).to.equal 'qiwi' it 'should have Qiwi as default wallet', -> wallet = null wallets.new().then (response) -> wallet = response httpBackend.flush() expect(wallet).to.have.ownProperty 'id' expect(wallet).to.have.ownProperty 'type' expect(wallet).to.have.ownProperty 'number' expect(wallet).to.have.ownProperty 'name' expect(wallet).to.have.ownProperty 'format' expect(wallet).to.have.ownProperty 'pattern' expect(wallet).to.have.ownProperty 'hint' expect(wallet.id).to.be.equal null expect(wallet.type).to.be.equal 'qiwi' expect(wallet.number).to.be.equal '' expect(wallet.name).to.be.equal '<NAME>wi' expect(wallet.pattern).to.contain 'Номер Qiwi' expect(wallet.hint).to.contain 'Номер кошелька Qiwi' it 'should return list of wallets', -> reply = [] wallets.all().then (response) -> reply = response httpBackend.flush() expect(reply).to.have.length 3 expect(reply[0]).to.have.ownProperty 'name' expect(reply[0].name).to.be.equal 'Qiwi' expect(reply[1]).to.have.ownProperty 'name' expect(reply[1].name).to.be.equal 'WebMoney' expect(reply[2]).to.have.ownProperty 'name' expect(reply[2].name).to.be.equal 'Яндекс.Деньги'
true
describe 'Wallets', -> beforeEach( -> module 'resources.wallets' ) describe 'Resource', -> wallets = {} httpBackend = {} mock = {} expect = chai.expect beforeEach(inject ($httpBackend, Wallets) -> httpBackend = $httpBackend wallets = Wallets mock = new WalletsMock(httpBackend) mock.mockOkResponse() ) it 'should have default resource url', -> expect(wallets.resourceUrl).to.equal '/api/wallets' it 'should have 3 constants', -> expect(wallets.TYPE_YANDEX_MONEY).to.equal 'yandex' expect(wallets.TYPE_WEB_MONEY).to.equal 'wm' expect(wallets.TYPE_QIWI).to.equal 'qiwi' it 'should have Qiwi as default wallet', -> wallet = null wallets.new().then (response) -> wallet = response httpBackend.flush() expect(wallet).to.have.ownProperty 'id' expect(wallet).to.have.ownProperty 'type' expect(wallet).to.have.ownProperty 'number' expect(wallet).to.have.ownProperty 'name' expect(wallet).to.have.ownProperty 'format' expect(wallet).to.have.ownProperty 'pattern' expect(wallet).to.have.ownProperty 'hint' expect(wallet.id).to.be.equal null expect(wallet.type).to.be.equal 'qiwi' expect(wallet.number).to.be.equal '' expect(wallet.name).to.be.equal 'PI:NAME:<NAME>END_PIwi' expect(wallet.pattern).to.contain 'Номер Qiwi' expect(wallet.hint).to.contain 'Номер кошелька Qiwi' it 'should return list of wallets', -> reply = [] wallets.all().then (response) -> reply = response httpBackend.flush() expect(reply).to.have.length 3 expect(reply[0]).to.have.ownProperty 'name' expect(reply[0].name).to.be.equal 'Qiwi' expect(reply[1]).to.have.ownProperty 'name' expect(reply[1].name).to.be.equal 'WebMoney' expect(reply[2]).to.have.ownProperty 'name' expect(reply[2].name).to.be.equal 'Яндекс.Деньги'
[ { "context": "eoverview Tests for max-statements rule.\n# @author Ian Christian Myers\n###\n\n'use strict'\n\n#-----------------------------", "end": 81, "score": 0.9996980428695679, "start": 62, "tag": "NAME", "value": "Ian Christian Myers" } ]
src/tests/rules/max-statements.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Tests for max-statements rule. # @author Ian Christian Myers ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/max-statements' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'max-statements', rule, valid: [ code: ''' -> bar = 1 -> noCount = 2 return 3 ''' options: [3] , code: ''' -> bar = 1 if yes loop qux = null else quxx() return 3 ''' options: [6] , code: ''' x = 5 -> y = 6 bar() z = 10 baz() ''' options: [5] , ''' -> a = null b = null c = null x = null y = null z = null bar() baz() qux() quxx() ''' , code: ''' do -> bar = 1 return -> return 42 ''' options: [1, {ignoreTopLevelFunctions: yes}] , code: ''' foo = -> bar = 1 baz = 2 ''' options: [1, {ignoreTopLevelFunctions: yes}] , code: ''' define ['foo', 'qux'], (foo, qux) -> bar = 1 baz = 2 ''' options: [1, {ignoreTopLevelFunctions: yes}] , # object property options code: ''' foo = thing: -> bar = 1 baz = 2 ''' options: [2] , code: ''' foo = ['thing']: -> bar = 1 baz = 2 ''' options: [2] ] invalid: [ code: ''' foo = -> bar = 1 baz = 2 qux = 3 ''' options: [2] errors: [ message: 'Function has too many statements (3). Maximum allowed is 2.' ] , code: ''' foo = -> bar = 1 if yes while no qux = null return 3 ''' options: [4] errors: [ message: 'Function has too many statements (5). Maximum allowed is 4.' ] , code: ''' foo = -> bar = 1 if yes loop qux = null return 3 ''' options: [4] errors: [ message: 'Function has too many statements (5). Maximum allowed is 4.' ] , code: ''' foo = -> bar = 1 if yes loop qux = null else quxx() return 3 ''' options: [5] errors: [ message: 'Function has too many statements (6). Maximum allowed is 5.' ] , code: ''' foo = -> x = 5 bar = -> y = 6 bar() z = 10 baz() ''' options: [3] errors: [ message: 'Function has too many statements (5). Maximum allowed is 3.' ] , code: ''' foo = -> x = 5 bar = -> y = 6 bar() z = 10 baz() ''' options: [4] errors: [ message: 'Function has too many statements (5). Maximum allowed is 4.' ] , code: ''' do -> bar = 1 -> z = null return 42 ''' options: [1, {ignoreTopLevelFunctions: yes}] errors: [ message: 'Function has too many statements (2). Maximum allowed is 1.' ] , code: ''' do -> bar = 1 baz = 2 do -> bar = 1 baz = 2 ''' options: [1, {ignoreTopLevelFunctions: yes}] errors: [ message: 'Function has too many statements (2). Maximum allowed is 1.' , message: 'Function has too many statements (2). Maximum allowed is 1.' ] , code: ''' define ['foo', 'qux'], (foo, qux) -> bar = 1 baz = 2 -> z = null return 42 ''' options: [1, {ignoreTopLevelFunctions: yes}] errors: [ message: 'Function has too many statements (2). Maximum allowed is 1.' ] , code: ''' -> a = null b = null c = null x = null y = null z = null bar() baz() qux() quxx() foo() ''' errors: [ message: 'Function has too many statements (11). Maximum allowed is 10.' ] , # object property options code: ''' foo = { thing: -> bar = 1 baz = 2 baz2 } ''' options: [2] errors: [ message: "Method 'thing' has too many statements (3). Maximum allowed is 2." ] ### # TODO decide if we want this or not # { # code: "var foo = { ['thing']() { var bar = 1; var baz = 2; var baz2; } }", # options: [2], # parserOptions: { ecmaVersion: 6 }, # errors: [{ message: "Method ''thing'' has too many statements (3). Maximum allowed is 2." }] # }, ### ]
89493
###* # @fileoverview Tests for max-statements rule. # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/max-statements' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'max-statements', rule, valid: [ code: ''' -> bar = 1 -> noCount = 2 return 3 ''' options: [3] , code: ''' -> bar = 1 if yes loop qux = null else quxx() return 3 ''' options: [6] , code: ''' x = 5 -> y = 6 bar() z = 10 baz() ''' options: [5] , ''' -> a = null b = null c = null x = null y = null z = null bar() baz() qux() quxx() ''' , code: ''' do -> bar = 1 return -> return 42 ''' options: [1, {ignoreTopLevelFunctions: yes}] , code: ''' foo = -> bar = 1 baz = 2 ''' options: [1, {ignoreTopLevelFunctions: yes}] , code: ''' define ['foo', 'qux'], (foo, qux) -> bar = 1 baz = 2 ''' options: [1, {ignoreTopLevelFunctions: yes}] , # object property options code: ''' foo = thing: -> bar = 1 baz = 2 ''' options: [2] , code: ''' foo = ['thing']: -> bar = 1 baz = 2 ''' options: [2] ] invalid: [ code: ''' foo = -> bar = 1 baz = 2 qux = 3 ''' options: [2] errors: [ message: 'Function has too many statements (3). Maximum allowed is 2.' ] , code: ''' foo = -> bar = 1 if yes while no qux = null return 3 ''' options: [4] errors: [ message: 'Function has too many statements (5). Maximum allowed is 4.' ] , code: ''' foo = -> bar = 1 if yes loop qux = null return 3 ''' options: [4] errors: [ message: 'Function has too many statements (5). Maximum allowed is 4.' ] , code: ''' foo = -> bar = 1 if yes loop qux = null else quxx() return 3 ''' options: [5] errors: [ message: 'Function has too many statements (6). Maximum allowed is 5.' ] , code: ''' foo = -> x = 5 bar = -> y = 6 bar() z = 10 baz() ''' options: [3] errors: [ message: 'Function has too many statements (5). Maximum allowed is 3.' ] , code: ''' foo = -> x = 5 bar = -> y = 6 bar() z = 10 baz() ''' options: [4] errors: [ message: 'Function has too many statements (5). Maximum allowed is 4.' ] , code: ''' do -> bar = 1 -> z = null return 42 ''' options: [1, {ignoreTopLevelFunctions: yes}] errors: [ message: 'Function has too many statements (2). Maximum allowed is 1.' ] , code: ''' do -> bar = 1 baz = 2 do -> bar = 1 baz = 2 ''' options: [1, {ignoreTopLevelFunctions: yes}] errors: [ message: 'Function has too many statements (2). Maximum allowed is 1.' , message: 'Function has too many statements (2). Maximum allowed is 1.' ] , code: ''' define ['foo', 'qux'], (foo, qux) -> bar = 1 baz = 2 -> z = null return 42 ''' options: [1, {ignoreTopLevelFunctions: yes}] errors: [ message: 'Function has too many statements (2). Maximum allowed is 1.' ] , code: ''' -> a = null b = null c = null x = null y = null z = null bar() baz() qux() quxx() foo() ''' errors: [ message: 'Function has too many statements (11). Maximum allowed is 10.' ] , # object property options code: ''' foo = { thing: -> bar = 1 baz = 2 baz2 } ''' options: [2] errors: [ message: "Method 'thing' has too many statements (3). Maximum allowed is 2." ] ### # TODO decide if we want this or not # { # code: "var foo = { ['thing']() { var bar = 1; var baz = 2; var baz2; } }", # options: [2], # parserOptions: { ecmaVersion: 6 }, # errors: [{ message: "Method ''thing'' has too many statements (3). Maximum allowed is 2." }] # }, ### ]
true
###* # @fileoverview Tests for max-statements rule. # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/max-statements' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'max-statements', rule, valid: [ code: ''' -> bar = 1 -> noCount = 2 return 3 ''' options: [3] , code: ''' -> bar = 1 if yes loop qux = null else quxx() return 3 ''' options: [6] , code: ''' x = 5 -> y = 6 bar() z = 10 baz() ''' options: [5] , ''' -> a = null b = null c = null x = null y = null z = null bar() baz() qux() quxx() ''' , code: ''' do -> bar = 1 return -> return 42 ''' options: [1, {ignoreTopLevelFunctions: yes}] , code: ''' foo = -> bar = 1 baz = 2 ''' options: [1, {ignoreTopLevelFunctions: yes}] , code: ''' define ['foo', 'qux'], (foo, qux) -> bar = 1 baz = 2 ''' options: [1, {ignoreTopLevelFunctions: yes}] , # object property options code: ''' foo = thing: -> bar = 1 baz = 2 ''' options: [2] , code: ''' foo = ['thing']: -> bar = 1 baz = 2 ''' options: [2] ] invalid: [ code: ''' foo = -> bar = 1 baz = 2 qux = 3 ''' options: [2] errors: [ message: 'Function has too many statements (3). Maximum allowed is 2.' ] , code: ''' foo = -> bar = 1 if yes while no qux = null return 3 ''' options: [4] errors: [ message: 'Function has too many statements (5). Maximum allowed is 4.' ] , code: ''' foo = -> bar = 1 if yes loop qux = null return 3 ''' options: [4] errors: [ message: 'Function has too many statements (5). Maximum allowed is 4.' ] , code: ''' foo = -> bar = 1 if yes loop qux = null else quxx() return 3 ''' options: [5] errors: [ message: 'Function has too many statements (6). Maximum allowed is 5.' ] , code: ''' foo = -> x = 5 bar = -> y = 6 bar() z = 10 baz() ''' options: [3] errors: [ message: 'Function has too many statements (5). Maximum allowed is 3.' ] , code: ''' foo = -> x = 5 bar = -> y = 6 bar() z = 10 baz() ''' options: [4] errors: [ message: 'Function has too many statements (5). Maximum allowed is 4.' ] , code: ''' do -> bar = 1 -> z = null return 42 ''' options: [1, {ignoreTopLevelFunctions: yes}] errors: [ message: 'Function has too many statements (2). Maximum allowed is 1.' ] , code: ''' do -> bar = 1 baz = 2 do -> bar = 1 baz = 2 ''' options: [1, {ignoreTopLevelFunctions: yes}] errors: [ message: 'Function has too many statements (2). Maximum allowed is 1.' , message: 'Function has too many statements (2). Maximum allowed is 1.' ] , code: ''' define ['foo', 'qux'], (foo, qux) -> bar = 1 baz = 2 -> z = null return 42 ''' options: [1, {ignoreTopLevelFunctions: yes}] errors: [ message: 'Function has too many statements (2). Maximum allowed is 1.' ] , code: ''' -> a = null b = null c = null x = null y = null z = null bar() baz() qux() quxx() foo() ''' errors: [ message: 'Function has too many statements (11). Maximum allowed is 10.' ] , # object property options code: ''' foo = { thing: -> bar = 1 baz = 2 baz2 } ''' options: [2] errors: [ message: "Method 'thing' has too many statements (3). Maximum allowed is 2." ] ### # TODO decide if we want this or not # { # code: "var foo = { ['thing']() { var bar = 1; var baz = 2; var baz2; } }", # options: [2], # parserOptions: { ecmaVersion: 6 }, # errors: [{ message: "Method ''thing'' has too many statements (3). Maximum allowed is 2." }] # }, ### ]
[ { "context": "on/.test(name)\n\nisSmokeTestEmail = (email) ->\n /@example.com/.test(email) or /smoketest/.test(email)\n\nround = ", "end": 16427, "score": 0.848573625087738, "start": 16416, "tag": "EMAIL", "value": "example.com" }, { "context": "\n quote: \"The kids love it.\"\n source: \"Leo Joseph Tran, Athlos Leadership Academy\"\n },\n {\n qu", "end": 21312, "score": 0.9995624423027039, "start": 21297, "tag": "NAME", "value": "Leo Joseph Tran" }, { "context": "The kids love it.\"\n source: \"Leo Joseph Tran, Athlos Leadership Academy\"\n },\n {\n quote", "end": 21315, "score": 0.6043943762779236, "start": 21314, "tag": "NAME", "value": "A" }, { "context": "couple of weeks and they love it.\"\n source: \"Scott Hatfield, Computer Applications Teacher, School Technology", "end": 21475, "score": 0.999456524848938, "start": 21461, "tag": "NAME", "value": "Scott Hatfield" }, { "context": " site. My eighth graders love it.\"\n source: \"Janet Cook, Ansbach Middle/High School\"\n },\n {\n q", "end": 21676, "score": 0.8823180794715881, "start": 21666, "tag": "NAME", "value": "Janet Cook" }, { "context": "ls without them even knowing it!!\"\n source: \"Kristin Huff, Special Education Teacher, Webb City School Dist", "end": 21916, "score": 0.9997240900993347, "start": 21904, "tag": "NAME", "value": "Kristin Huff" }, { "context": "h graders and they are loving it!\"\n source: \"Shauna Hamman, Fifth Grade Teacher, Four Peaks Elementary Schoo", "end": 22115, "score": 0.9996997714042664, "start": 22102, "tag": "NAME", "value": "Shauna Hamman" }, { "context": "ry kid who has tried it is a fan.\"\n source: \"Aibinder Andrew, Technology Teacher\"\n },\n {\n quote: \"I", "end": 22377, "score": 0.9989454746246338, "start": 22362, "tag": "NAME", "value": "Aibinder Andrew" }, { "context": "created. The kids are so engaged.\"\n source: \"Desmond Smith, 4KS Academy\"\n },\n {\n quote: \"My stude", "end": 22510, "score": 0.9952883720397949, "start": 22497, "tag": "NAME", "value": "Desmond Smith" }, { "context": "red around it in the near future.\"\n source: \"Michael Leonard, Science Teacher, Clearwater Central Catholic Hig", "end": 22682, "score": 0.9369022250175476, "start": 22667, "tag": "NAME", "value": "Michael Leonard" }, { "context": "\n index\n\nusStateCodes =\n # https://github.com/mdzhang/us-state-codes\n # generated by js2coffee 2.2.0\n ", "end": 29622, "score": 0.9996083378791809, "start": 29615, "tag": "USERNAME", "value": "mdzhang" }, { "context": "Never')\n\ngetApiClientIdFromEmail = (email) ->\n if /@codeninjas.com$/i.test(email) # hard coded for co", "end": 32970, "score": 0.5025814771652222, "start": 32970, "tag": "EMAIL", "value": "" }, { "context": "ver')\n\ngetApiClientIdFromEmail = (email) ->\n if /@codeninjas.com$/i.test(email) # hard coded for code ninjas since", "end": 32987, "score": 0.9913698434829712, "start": 32972, "tag": "EMAIL", "value": "@codeninjas.com" } ]
app/core/utils.coffee
kremerben/codecombat
1
slugify = _.str?.slugify ? _.string?.slugify # TODO: why _.string on client and _.str on server? translatejs2cpp = (jsCode, fullCode=true) -> matchBrackets = (str, startIndex) -> cc = 0 for i in [startIndex..str.length-1] by 1 cc += 1 if str[i] == '{' if str[i] == '}' cc -= 1 return i+2 unless cc splitFunctions = (str) -> creg = /\n[ \t]*[^\/]/ codeIndex = creg.exec(str) if str and str[0] != '/' startComments = '' else if codeIndex codeIndex = codeIndex.index + 1 startComments = str.slice 0, codeIndex str = str.slice codeIndex else return [str, ''] indices = [] reg = /\nfunction/gi indices.push 0 if str.startsWith("function ") while (result = reg.exec(str)) indices.push result.index+1 split = [] end = 0 split.push {s: 0, e: indices[0]} if indices.length for i in indices end = matchBrackets str, i split.push {s: i, e: end} split.push {s: end, e: str.length} header = if startComments then [startComments] else [] return header.concat split.map (s) -> str.slice s.s, s.e jsCodes = splitFunctions jsCode len = jsCodes.length lines = jsCodes[len-1].split '\n' if fullCode jsCodes[len-1] = """ int main() { #{(lines.map (line) -> ' ' + line).join '\n'} return 0; } """ else jsCodes[len-1] = (lines.map (line) -> ' ' + line).join('\n') for i in [0..len-1] by 1 if /^ *function/.test(jsCodes[i]) variables = jsCodes[i].match(/function.*\((.*)\)/)[1] v = '' v = variables.split(', ').map((e) -> 'auto ' + e).join(', ') if variables jsCodes[i] = jsCodes[i].replace(/function(.*)\((.*)\)/, 'auto$1(' + v + ')') jsCodes[i] = jsCodes[i].replace /var x/g, 'float x' jsCodes[i] = jsCodes[i].replace /var y/g, 'float y' jsCodes[i] = jsCodes[i].replace /var dist/g, 'float dist' jsCodes[i] = jsCodes[i].replace /var (\w+)Index/g, 'int $1Index' jsCodes[i] = jsCodes[i].replace /\ ===\ /g, ' == ' jsCodes[i] = jsCodes[i].replace /\.length/g, '.size()' jsCodes[i] = jsCodes[i].replace /\.push\(/g, '.push_back(' jsCodes[i] = jsCodes[i].replace /\.pop\(/g, '.pop_back(' jsCodes[i] = jsCodes[i].replace /\.shift\(/g, '.pop(' jsCodes[i] = jsCodes[i].replace /\ new /g, ' *new ' jsCodes[i] = jsCodes[i].replace /\ !== /g, ' != ' jsCodes[i] = jsCodes[i].replace /\ var /g, ' auto ' jsCodes[i] = jsCodes[i].replace /\ = \[([^;]*)\];/g, ' = {$1};' jsCodes[i] = jsCodes[i].replace /\(var /g, '(auto ' jsCodes[i] = jsCodes[i].replace /\nvar /g, '\nauto ' jsCodes[i] = jsCodes[i].replace /\ return \[([^;]*)\];/g, ' return {$1};' # Don't substitute these within comments noComment = '^ *([^/\\r\\n]*?)' quotesReg = new RegExp(noComment + "'(.*?)'", 'gm') while quotesReg.test(jsCodes[i]) jsCodes[i] = jsCodes[i].replace quotesReg, '$1"$2"' # first replace ' to " then replace object jsCodes[i] = jsCodes[i].replace /\{\s*"?x"?\s*:\s*([^,]+),\s*"?y"?\s*:\s*([^\}]*)\}/g, '{$1, $2}' # {x:1, y:1} -> {1, 1} unless fullCode lines = jsCodes[len-1].split '\n' jsCodes[len-1] = (lines.map (line) -> line.slice 1).join('\n') cppCodes = jsCodes.join('').split('\n') for i in [1..cppCodes.length-1] by 1 if cppCodes[i].match(/^\s*else/) and cppCodes[i-1].match("//") tmp = cppCodes[i] cppCodes[i] = cppCodes[i-1] cppCodes[i-1] = tmp cppCodes.join '\n' clone = (obj) -> return obj if obj is null or typeof (obj) isnt 'object' temp = obj.constructor() for key of obj temp[key] = clone(obj[key]) temp combineAncestralObject = (obj, propertyName) -> combined = {} while obj?[propertyName] for key, value of obj[propertyName] continue if combined[key] combined[key] = value if obj.__proto__ obj = obj.__proto__ else # IE has no __proto__. TODO: does this even work? At most it doesn't crash. obj = Object.getPrototypeOf(obj) combined countries = [ {country: 'united-states', countryCode: 'US', ageOfConsent: 13, addressesIncludeAdministrativeRegion:true} {country: 'china', countryCode: 'CN', addressesIncludeAdministrativeRegion:true} {country: 'brazil', countryCode: 'BR'} # Loosely ordered by decreasing traffic as measured 2016-09-01 - 2016-11-07 # TODO: switch to alphabetical ordering {country: 'united-kingdom', countryCode: 'GB', inEU: true, ageOfConsent: 13} {country: 'russia', countryCode: 'RU'} {country: 'australia', countryCode: 'AU', addressesIncludeAdministrativeRegion:true} {country: 'canada', countryCode: 'CA', addressesIncludeAdministrativeRegion:true} {country: 'france', countryCode: 'FR', inEU: true, ageOfConsent: 15} {country: 'taiwan', countryCode: 'TW'} {country: 'ukraine', countryCode: 'UA'} {country: 'poland', countryCode: 'PL', inEU: true, ageOfConsent: 13} {country: 'spain', countryCode: 'ES', inEU: true, ageOfConsent: 13} {country: 'germany', countryCode: 'DE', inEU: true, ageOfConsent: 16} {country: 'netherlands', countryCode: 'NL', inEU: true, ageOfConsent: 16} {country: 'hungary', countryCode: 'HU', inEU: true, ageOfConsent: 16} {country: 'japan', countryCode: 'JP'} {country: 'turkey', countryCode: 'TR'} {country: 'south-africa', countryCode: 'ZA'} {country: 'indonesia', countryCode: 'ID'} {country: 'new-zealand', countryCode: 'NZ'} {country: 'finland', countryCode: 'FI', inEU: true, ageOfConsent: 13} {country: 'south-korea', countryCode: 'KR'} {country: 'mexico', countryCode: 'MX', addressesIncludeAdministrativeRegion:true} {country: 'vietnam', countryCode: 'VN'} {country: 'singapore', countryCode: 'SG'} {country: 'colombia', countryCode: 'CO'} {country: 'india', countryCode: 'IN', addressesIncludeAdministrativeRegion:true} {country: 'thailand', countryCode: 'TH'} {country: 'belgium', countryCode: 'BE', inEU: true, ageOfConsent: 13} {country: 'sweden', countryCode: 'SE', inEU: true, ageOfConsent: 13} {country: 'denmark', countryCode: 'DK', inEU: true, ageOfConsent: 13} {country: 'czech-republic', countryCode: 'CZ', inEU: true, ageOfConsent: 15} {country: 'hong-kong', countryCode: 'HK'} {country: 'italy', countryCode: 'IT', inEU: true, ageOfConsent: 16, addressesIncludeAdministrativeRegion:true} {country: 'romania', countryCode: 'RO', inEU: true, ageOfConsent: 16} {country: 'belarus', countryCode: 'BY'} {country: 'norway', countryCode: 'NO', inEU: true, ageOfConsent: 13} # GDPR applies to EFTA {country: 'philippines', countryCode: 'PH'} {country: 'lithuania', countryCode: 'LT', inEU: true, ageOfConsent: 16} {country: 'argentina', countryCode: 'AR'} {country: 'malaysia', countryCode: 'MY', addressesIncludeAdministrativeRegion:true} {country: 'pakistan', countryCode: 'PK'} {country: 'serbia', countryCode: 'RS'} {country: 'greece', countryCode: 'GR', inEU: true, ageOfConsent: 15} {country: 'israel', countryCode: 'IL', inEU: true} {country: 'portugal', countryCode: 'PT', inEU: true, ageOfConsent: 13} {country: 'slovakia', countryCode: 'SK', inEU: true, ageOfConsent: 16} {country: 'ireland', countryCode: 'IE', inEU: true, ageOfConsent: 16} {country: 'switzerland', countryCode: 'CH', inEU: true, ageOfConsent: 16} # GDPR applies to EFTA {country: 'peru', countryCode: 'PE'} {country: 'bulgaria', countryCode: 'BG', inEU: true, ageOfConsent: 14} {country: 'venezuela', countryCode: 'VE'} {country: 'austria', countryCode: 'AT', inEU: true, ageOfConsent: 14} {country: 'croatia', countryCode: 'HR', inEU: true, ageOfConsent: 16} {country: 'saudia-arabia', countryCode: 'SA'} {country: 'chile', countryCode: 'CL'} {country: 'united-arab-emirates', countryCode: 'AE'} {country: 'kazakhstan', countryCode: 'KZ'} {country: 'estonia', countryCode: 'EE', inEU: true, ageOfConsent: 13} {country: 'iran', countryCode: 'IR'} {country: 'egypt', countryCode: 'EG'} {country: 'ecuador', countryCode: 'EC'} {country: 'slovenia', countryCode: 'SI', inEU: true, ageOfConsent: 15} {country: 'macedonia', countryCode: 'MK'} {country: 'cyprus', countryCode: 'CY', inEU: true, ageOfConsent: 14} {country: 'latvia', countryCode: 'LV', inEU: true, ageOfConsent: 13} {country: 'luxembourg', countryCode: 'LU', inEU: true, ageOfConsent: 16} {country: 'malta', countryCode: 'MT', inEU: true, ageOfConsent: 16} {country: 'lichtenstein', countryCode: 'LI', inEU: true} # GDPR applies to EFTA {country: 'iceland', countryCode: 'IS', inEU: true} # GDPR applies to EFTA ] inEU = (country) -> !!_.find(countries, (c) => c.country is slugify(country))?.inEU addressesIncludeAdministrativeRegion = (country) -> !!_.find(countries, (c) => c.country is slugify(country))?.addressesIncludeAdministrativeRegion ageOfConsent = (countryName, defaultIfUnknown=0) -> return defaultIfUnknown unless countryName country = _.find(countries, (c) => c.country is slugify(countryName)) return defaultIfUnknown unless country return country.ageOfConsent if country.ageOfConsent return 16 if country.inEU return defaultIfUnknown countryCodeToFlagEmoji = (code) -> return code unless code?.length is 2 (String.fromCodePoint(c.charCodeAt() + 0x1F1A5) for c in code.toUpperCase()).join('') countryCodeToName = (code) -> return code unless code?.length is 2 return code unless country = _.find countries, countryCode: code.toUpperCase() titleize country.country titleize = (s) -> # Turns things like 'dungeons-of-kithgard' into 'Dungeons of Kithgard' _.string.titleize(_.string.humanize(s)).replace(/ (and|or|but|nor|yet|so|for|a|an|the|in|to|of|at|by|up|for|off|on|with|from)(?= )/ig, (word) => word.toLowerCase()) campaignIDs = INTRO: '55b29efd1cd6abe8ce07db0d' courseIDs = INTRODUCTION_TO_COMPUTER_SCIENCE: '560f1a9f22961295f9427742' GAME_DEVELOPMENT_1: '5789587aad86a6efb573701e' WEB_DEVELOPMENT_1: '5789587aad86a6efb573701f' COMPUTER_SCIENCE_2: '5632661322961295f9428638' GAME_DEVELOPMENT_2: '57b621e7ad86a6efb5737e64' WEB_DEVELOPMENT_2: '5789587aad86a6efb5737020' COMPUTER_SCIENCE_3: '56462f935afde0c6fd30fc8c' GAME_DEVELOPMENT_3: '5a0df02b8f2391437740f74f' COMPUTER_SCIENCE_4: '56462f935afde0c6fd30fc8d' COMPUTER_SCIENCE_5: '569ed916efa72b0ced971447' COMPUTER_SCIENCE_6: '5817d673e85d1220db624ca4' CSCourseIDs = [ courseIDs.INTRODUCTION_TO_COMPUTER_SCIENCE courseIDs.COMPUTER_SCIENCE_2 courseIDs.COMPUTER_SCIENCE_3 courseIDs.COMPUTER_SCIENCE_4 courseIDs.COMPUTER_SCIENCE_5 courseIDs.COMPUTER_SCIENCE_6 ] orderedCourseIDs = [ courseIDs.INTRODUCTION_TO_COMPUTER_SCIENCE courseIDs.GAME_DEVELOPMENT_1 courseIDs.WEB_DEVELOPMENT_1 courseIDs.COMPUTER_SCIENCE_2 courseIDs.GAME_DEVELOPMENT_2 courseIDs.WEB_DEVELOPMENT_2 courseIDs.COMPUTER_SCIENCE_3 courseIDs.GAME_DEVELOPMENT_3 courseIDs.COMPUTER_SCIENCE_4 courseIDs.COMPUTER_SCIENCE_5 courseIDs.COMPUTER_SCIENCE_6 ] courseAcronyms = {} courseAcronyms[courseIDs.INTRODUCTION_TO_COMPUTER_SCIENCE] = 'CS1' courseAcronyms[courseIDs.GAME_DEVELOPMENT_1] = 'GD1' courseAcronyms[courseIDs.WEB_DEVELOPMENT_1] = 'WD1' courseAcronyms[courseIDs.COMPUTER_SCIENCE_2] = 'CS2' courseAcronyms[courseIDs.GAME_DEVELOPMENT_2] = 'GD2' courseAcronyms[courseIDs.WEB_DEVELOPMENT_2] = 'WD2' courseAcronyms[courseIDs.COMPUTER_SCIENCE_3] = 'CS3' courseAcronyms[courseIDs.GAME_DEVELOPMENT_3] = 'GD3' courseAcronyms[courseIDs.COMPUTER_SCIENCE_4] = 'CS4' courseAcronyms[courseIDs.COMPUTER_SCIENCE_5] = 'CS5' courseAcronyms[courseIDs.COMPUTER_SCIENCE_6] = 'CS6' courseLessonSlidesURLs = {} unless features?.china courseLessonSlidesURLs[courseIDs.INTRODUCTION_TO_COMPUTER_SCIENCE] = 'https://drive.google.com/drive/folders/1YU7LEZ6TLQzbAsSMw90nNJfvU7gDrcid?usp=sharing' courseLessonSlidesURLs[courseIDs.COMPUTER_SCIENCE_2] = 'https://drive.google.com/drive/folders/1x24P6ZY_MBOBoHvlikbDr7jvMPYVRVkJ?usp=sharing' courseLessonSlidesURLs[courseIDs.COMPUTER_SCIENCE_3] = 'https://drive.google.com/drive/folders/1hBl-h5Xvo5chYH4q9e6IEo42JozlrTG9?usp=sharing' courseLessonSlidesURLs[courseIDs.COMPUTER_SCIENCE_4] = 'https://drive.google.com/drive/folders/1tbuE4Xn0ahJ0xcF1-OaiPs9lHeIs9zqG?usp=sharing' courseLessonSlidesURLs[courseIDs.COMPUTER_SCIENCE_5] = 'https://drive.google.com/drive/folders/1ThxWFZjoXzU5INtMzlqKEn8xkgHhVnl4?usp=sharing' petThangIDs = [ '578d320d15e2501f00a585bd' # Wolf Pup '5744e3683af6bf590cd27371' # Cougar '5786a472a6c64135009238d3' # Raven '577d5d4dab818b210046b3bf' # Pugicorn '58c74b7c3d4a3d2900d43b7e' # Brown Rat '58c7614a62cc3a1f00442240' # Yetibab '58a262520b43652f00dad75e' # Phoenix '57869cf7bd31c14400834028' # Frog '578691f9bd31c1440083251d' # Polar Bear Cub '58a2712b0b43652f00dae5a4' # Blue Fox '58c737140ca7852e005deb8a' # Mimic '57586f0a22179b2800efda37' # Baby Griffin ] premiumContent = premiumHeroesCount: '12' totalHeroesCount: '16' premiumLevelsCount: '330' freeLevelsCount: '100' normalizeFunc = (func_thing, object) -> # func could be a string to a function in this class # or a function in its own right object ?= {} if _.isString(func_thing) func = object[func_thing] if not func console.error "Could not find method #{func_thing} in object", object return => null # always return a func, or Mediator will go boom func_thing = func return func_thing objectIdToDate = (objectID) -> new Date(parseInt(objectID.toString().slice(0,8), 16)*1000) hexToHSL = (hex) -> rgbToHsl(hexToR(hex), hexToG(hex), hexToB(hex)) hexToR = (h) -> parseInt (cutHex(h)).substring(0, 2), 16 hexToG = (h) -> parseInt (cutHex(h)).substring(2, 4), 16 hexToB = (h) -> parseInt (cutHex(h)).substring(4, 6), 16 cutHex = (h) -> (if (h.charAt(0) is '#') then h.substring(1, 7) else h) hslToHex = (hsl) -> '#' + (toHex(n) for n in hslToRgb(hsl...)).join('') toHex = (n) -> h = Math.floor(n).toString(16) h = '0'+h if h.length is 1 h pathToUrl = (path) -> base = location.protocol + '//' + location.hostname + (location.port && ":" + location.port) base + path extractPlayerCodeTag = (code) -> unwrappedDefaultCode = code.match(/<playercode>\n([\s\S]*)\n *<\/playercode>/)?[1] if unwrappedDefaultCode return stripIndentation(unwrappedDefaultCode) else return undefined stripIndentation = (code) -> codeLines = code.split('\n') indentation = _.min(_.filter(codeLines.map (line) -> line.match(/^\s*/)?[0]?.length)) strippedCode = (line.substr(indentation) for line in codeLines).join('\n') return strippedCode # @param {Object} say - the object containing an i18n property. # @param {string} target - the attribute that you want to access. # @returns {string} translated string if possible # Example usage: # `courseName = utils.i18n(course.attributes, 'name')` i18n = (say, target, language=me.get('preferredLanguage', true), fallback='en') -> generalResult = null fallBackResult = null fallForwardResult = null # If a general language isn't available, the first specific one will do. fallSidewaysResult = null # If a specific language isn't available, its sibling specific language will do. matches = (/\w+/gi).exec(language) generalName = matches[0] if matches for localeName, locale of say.i18n continue if localeName is '-' if target of locale result = locale[target] else continue return result if localeName is language generalResult = result if localeName is generalName fallBackResult = result if localeName is fallback fallForwardResult = result if localeName.indexOf(language) is 0 and not fallForwardResult? fallSidewaysResult = result if localeName.indexOf(generalName) is 0 and not fallSidewaysResult? return generalResult if generalResult? return fallForwardResult if fallForwardResult? return fallSidewaysResult if fallSidewaysResult? return fallBackResult if fallBackResult? return say[target] if target of say null getByPath = (target, path) -> throw new Error 'Expected an object to match a query against, instead got null' unless target pieces = path.split('.') obj = target for piece in pieces return undefined unless piece of obj obj = obj[piece] obj isID = (id) -> _.isString(id) and id.length is 24 and id.match(/[a-f0-9]/gi)?.length is 24 isIE = -> $?.browser?.msie ? false isRegionalSubscription = (name) -> /_basic_subscription/.test(name) isSmokeTestEmail = (email) -> /@example.com/.test(email) or /smoketest/.test(email) round = _.curry (digits, n) -> n = +n.toFixed(digits) positify = (func) -> (params) -> (x) -> if x > 0 then func(params)(x) else 0 # f(x) = ax + b createLinearFunc = (params) -> (x) -> (params.a or 1) * x + (params.b or 0) # f(x) = ax² + bx + c createQuadraticFunc = (params) -> (x) -> (params.a or 1) * x * x + (params.b or 1) * x + (params.c or 0) # f(x) = a log(b (x + c)) + d createLogFunc = (params) -> (x) -> if x > 0 then (params.a or 1) * Math.log((params.b or 1) * (x + (params.c or 0))) + (params.d or 0) else 0 # f(x) = ax^b + c createPowFunc = (params) -> (x) -> (params.a or 1) * Math.pow(x, params.b or 1) + (params.c or 0) functionCreators = linear: positify(createLinearFunc) quadratic: positify(createQuadraticFunc) logarithmic: positify(createLogFunc) pow: positify(createPowFunc) # Call done with true to satisfy the 'until' goal and stop repeating func keepDoingUntil = (func, wait=100, totalWait=5000) -> waitSoFar = 0 (done = (success) -> if (waitSoFar += wait) <= totalWait and not success _.delay (-> func done), wait) false grayscale = (imageData) -> d = imageData.data for i in [0..d.length] by 4 r = d[i] g = d[i+1] b = d[i+2] v = 0.2126*r + 0.7152*g + 0.0722*b d[i] = d[i+1] = d[i+2] = v imageData # Deep compares l with r, with the exception that undefined values are considered equal to missing values # Very practical for comparing Mongoose documents where undefined is not allowed, instead fields get deleted kindaEqual = compare = (l, r) -> if _.isObject(l) and _.isObject(r) for key in _.union Object.keys(l), Object.keys(r) return false unless compare l[key], r[key] return true else if l is r return true else return false # Return UTC string "YYYYMMDD" for today + offset getUTCDay = (offset=0) -> day = new Date() day.setDate(day.getUTCDate() + offset) partYear = day.getUTCFullYear() partMonth = (day.getUTCMonth() + 1) partMonth = "0" + partMonth if partMonth < 10 partDay = day.getUTCDate() partDay = "0" + partDay if partDay < 10 "#{partYear}#{partMonth}#{partDay}" # Fast, basic way to replace text in an element when you don't need much. # http://stackoverflow.com/a/4962398/540620 if document?.createElement dummy = document.createElement 'div' dummy.innerHTML = 'text' TEXT = if dummy.textContent is 'text' then 'textContent' else 'innerText' replaceText = (elems, text) -> elem[TEXT] = text for elem in elems null # Add a stylesheet rule # http://stackoverflow.com/questions/524696/how-to-create-a-style-tag-with-javascript/26230472#26230472 # Don't use wantonly, or we'll have to implement a simple mechanism for clearing out old rules. if document?.createElement injectCSS = ((doc) -> # wrapper for all injected styles and temp el to create them wrap = doc.createElement("div") temp = doc.createElement("div") # rules like "a {color: red}" etc. return (cssRules) -> # append wrapper to the body on the first call unless wrap.id wrap.id = "injected-css" wrap.style.display = "none" doc.body.appendChild wrap # <br> for IE: http://goo.gl/vLY4x7 temp.innerHTML = "<br><style>" + cssRules + "</style>" wrap.appendChild temp.children[1] return )(document) # So that we can stub out userAgent in tests userAgent = -> window.navigator.userAgent getDocumentSearchString = -> # moved to a separate function so it can be mocked for testing return document.location.search getQueryVariables = -> query = module.exports.getDocumentSearchString().substring(1) # use module.exports so spy is used in testing pairs = (pair.split('=') for pair in query.split '&') variables = {} for [key, value] in pairs variables[key] = {'true': true, 'false': false}[value] ? decodeURIComponent(value) return variables getQueryVariable = (param, defaultValue) -> variables = getQueryVariables() return variables[param] ? defaultValue getSponsoredSubsAmount = (price=999, subCount=0, personalSub=false) -> # 1 100% # 2-11 80% # 12+ 60% # TODO: make this less confusing return 0 unless subCount > 0 offset = if personalSub then 1 else 0 if subCount <= 1 - offset price else if subCount <= 11 - offset Math.round((1 - offset) * price + (subCount - 1 + offset) * price * 0.8) else Math.round((1 - offset) * price + 10 * price * 0.8 + (subCount - 11 + offset) * price * 0.6) getCourseBundlePrice = (coursePrices, seats=20) -> totalPricePerSeat = coursePrices.reduce ((a, b) -> a + b), 0 if coursePrices.length > 2 pricePerSeat = Math.round(totalPricePerSeat / 2.0) else pricePerSeat = parseInt(totalPricePerSeat) seats * pricePerSeat getCoursePraise = -> praise = [ { quote: "The kids love it." source: "Leo Joseph Tran, Athlos Leadership Academy" }, { quote: "My students have been using the site for a couple of weeks and they love it." source: "Scott Hatfield, Computer Applications Teacher, School Technology Coordinator, Eastside Middle School" }, { quote: "Thanks for the captivating site. My eighth graders love it." source: "Janet Cook, Ansbach Middle/High School" }, { quote: "My students have started working on CodeCombat and love it! I love that they are learning coding and problem solving skills without them even knowing it!!" source: "Kristin Huff, Special Education Teacher, Webb City School District" }, { quote: "I recently introduced Code Combat to a few of my fifth graders and they are loving it!" source: "Shauna Hamman, Fifth Grade Teacher, Four Peaks Elementary School" }, { quote: "Overall I think it's a fantastic service. Variables, arrays, loops, all covered in very fun and imaginative ways. Every kid who has tried it is a fan." source: "Aibinder Andrew, Technology Teacher" }, { quote: "I love what you have created. The kids are so engaged." source: "Desmond Smith, 4KS Academy" }, { quote: "My students love the website and I hope on having content structured around it in the near future." source: "Michael Leonard, Science Teacher, Clearwater Central Catholic High School" } ] praise[_.random(0, praise.length - 1)] getPrepaidCodeAmount = (price=0, users=0, months=0) -> return 0 unless users > 0 and months > 0 total = price * users * months total formatDollarValue = (dollars) -> '$' + (parseFloat(dollars).toFixed(2)) startsWithVowel = (s) -> s[0] in 'aeiouAEIOU' filterMarkdownCodeLanguages = (text, language) -> return '' unless text currentLanguage = language or me.get('aceConfig')?.language or 'python' excludedLanguages = _.without ['javascript', 'python', 'coffeescript', 'lua', 'java', 'cpp', 'html'], if currentLanguage == 'cpp' then 'javascript' else currentLanguage # Exclude language-specific code blocks like ```python (... code ...)`` # ` for each non-target language. codeBlockExclusionRegex = new RegExp "```(#{excludedLanguages.join('|')})\n[^`]+```\n?", 'gm' # Exclude language-specific images like ![python - image description](image url) for each non-target language. imageExclusionRegex = new RegExp "!\\[(#{excludedLanguages.join('|')}) - .+?\\]\\(.+?\\)\n?", 'gm' text = text.replace(codeBlockExclusionRegex, '').replace(imageExclusionRegex, '') commonLanguageReplacements = python: [ ['true', 'True'], ['false', 'False'], ['null', 'None'], ['object', 'dictionary'], ['Object', 'Dictionary'], ['array', 'list'], ['Array', 'List'], ] lua: [ ['null', 'nil'], ['object', 'table'], ['Object', 'Table'], ['array', 'table'], ['Array', 'Table'], ] for [from, to] in commonLanguageReplacements[currentLanguage] ? [] # Convert JS-specific keywords and types to Python ones, if in simple `code` tags. # This won't cover it when it's not in an inline code tag by itself or when it's not in English. text = text.replace ///`#{from}`///g, "`#{to}`" # Now change "An `dictionary`" to "A `dictionary`", etc. if startsWithVowel(from) and not startsWithVowel(to) text = text.replace ///(\ a|A)n(\ `#{to}`)///g, "$1$2" if not startsWithVowel(from) and startsWithVowel(to) text = text.replace ///(\ a|A)(\ `#{to}`)///g, "$1n$2" if currentLanguage == 'cpp' jsRegex = new RegExp "```javascript\n([^`]+)```", 'gm' text = text.replace jsRegex, (a, l) => """```cpp #{@translatejs2cpp a[13..a.length-4], false} ```""" return text capitalLanguages = 'javascript': 'JavaScript' 'coffeescript': 'CoffeeScript' 'python': 'Python' 'java': 'Java' 'cpp': 'C++' 'lua': 'Lua' 'html': 'HTML' createLevelNumberMap = (levels) -> levelNumberMap = {} practiceLevelTotalCount = 0 practiceLevelCurrentCount = 0 for level, i in levels levelNumber = i - practiceLevelTotalCount + 1 if level.practice levelNumber = i - practiceLevelTotalCount + String.fromCharCode('a'.charCodeAt(0) + practiceLevelCurrentCount) practiceLevelTotalCount++ practiceLevelCurrentCount++ else if level.assessment practiceLevelTotalCount++ practiceLevelCurrentCount++ levelNumber = if level.assessment is 'cumulative' then $.t('play_level.combo_challenge') else $.t('play_level.concept_challenge') else practiceLevelCurrentCount = 0 levelNumberMap[level.key] = levelNumber levelNumberMap findNextLevel = (levels, currentIndex, needsPractice) -> # Find next available incomplete level, depending on whether practice is needed # levels = [{practice: true/false, complete: true/false, assessment: true/false, locked: true/false}] # Skip over assessment levels # return -1 if at or beyond locked level return -1 for i in [0..currentIndex] when levels[i].locked index = currentIndex index++ if needsPractice if levels[currentIndex].practice or index < levels.length and levels[index].practice # Needs practice, current level is practice or next is practice; return the next incomplete practice-or-normal level # May leave earlier practice levels incomplete and reach end of course while index < levels.length and (levels[index].complete or levels[index].assessment) return -1 if levels[index].locked index++ else # Needs practice, current level is required, next level is required or assessment; return the first incomplete level of previous practice chain index-- index-- while index >= 0 and not levels[index].practice if index >= 0 index-- while index >= 0 and levels[index].practice if index >= 0 index++ index++ while index < levels.length and levels[index].practice and levels[index].complete if levels[index].practice and not levels[index].complete return index # Last set of practice levels is complete; return the next incomplete normal level instead. index = currentIndex + 1 while index < levels.length and (levels[index].complete or levels[index].assessment) return -1 if levels[index].locked index++ else # No practice needed; return the next required incomplete level while index < levels.length and (levels[index].practice or levels[index].complete or levels[index].assessment) return -1 if levels[index].locked index++ index findNextAssessmentForLevel = (levels, currentIndex, needsPractice) -> # Find assessment level immediately after current level (and its practice levels) # Only return assessment if it's the next level # Skip over practice levels unless practice neeeded # levels = [{practice: true/false, complete: true/false, assessment: true/false, locked: true/false}] # eg: l*,p,p,a*,a',l,... # given index l*, return index a* # given index a*, return index a' index = currentIndex index++ while index < levels.length if levels[index].practice return -1 if needsPractice and not levels[index].complete index++ # It's a practice level but do not need practice, keep looking else if levels[index].assessment return -1 if levels[index].complete return index else if levels[index].complete # It's completed, keep looking index++ else # we got to a normal level; we didn't find an assessment for the given level. return -1 return -1 # we got to the end of the list and found nothing needsPractice = (playtime=0, threshold=5) -> playtime / 60 > threshold sortCourses = (courses) -> _.sortBy courses, (course) -> # ._id can be from classroom.courses, otherwise it's probably .id index = orderedCourseIDs.indexOf(course.id ? course._id) index = 9001 if index is -1 index sortCoursesByAcronyms = (courses) -> orderedCourseAcronyms = _.sortBy(courseAcronyms) _.sortBy courses, (course) -> # ._id can be from classroom.courses, otherwise it's probably .id index = orderedCourseAcronyms.indexOf(courseAcronyms[course.id ? course._id]) index = 9001 if index is -1 index usStateCodes = # https://github.com/mdzhang/us-state-codes # generated by js2coffee 2.2.0 (-> stateNamesByCode = 'AL': 'Alabama' 'AK': 'Alaska' 'AZ': 'Arizona' 'AR': 'Arkansas' 'CA': 'California' 'CO': 'Colorado' 'CT': 'Connecticut' 'DE': 'Delaware' 'DC': 'District of Columbia' 'FL': 'Florida' 'GA': 'Georgia' 'HI': 'Hawaii' 'ID': 'Idaho' 'IL': 'Illinois' 'IN': 'Indiana' 'IA': 'Iowa' 'KS': 'Kansas' 'KY': 'Kentucky' 'LA': 'Louisiana' 'ME': 'Maine' 'MD': 'Maryland' 'MA': 'Massachusetts' 'MI': 'Michigan' 'MN': 'Minnesota' 'MS': 'Mississippi' 'MO': 'Missouri' 'MT': 'Montana' 'NE': 'Nebraska' 'NV': 'Nevada' 'NH': 'New Hampshire' 'NJ': 'New Jersey' 'NM': 'New Mexico' 'NY': 'New York' 'NC': 'North Carolina' 'ND': 'North Dakota' 'OH': 'Ohio' 'OK': 'Oklahoma' 'OR': 'Oregon' 'PA': 'Pennsylvania' 'RI': 'Rhode Island' 'SC': 'South Carolina' 'SD': 'South Dakota' 'TN': 'Tennessee' 'TX': 'Texas' 'UT': 'Utah' 'VT': 'Vermont' 'VA': 'Virginia' 'WA': 'Washington' 'WV': 'West Virginia' 'WI': 'Wisconsin' 'WY': 'Wyoming' stateCodesByName = _.invert(stateNamesByCode) # normalizes case and removes invalid characters # returns null if can't find sanitized code in the state map sanitizeStateCode = (code) -> code = if _.isString(code) then code.trim().toUpperCase().replace(/[^A-Z]/g, '') else null if stateNamesByCode[code] then code else null # returns a valid state name else null getStateNameByStateCode = (code) -> stateNamesByCode[sanitizeStateCode(code)] or null # normalizes case and removes invalid characters # returns null if can't find sanitized name in the state map sanitizeStateName = (name) -> if !_.isString(name) return null # bad whitespace remains bad whitespace e.g. "O hi o" is not valid name = name.trim().toLowerCase().replace(/[^a-z\s]/g, '').replace(/\s+/g, ' ') tokens = name.split(/\s+/) tokens = _.map(tokens, (token) -> token.charAt(0).toUpperCase() + token.slice(1) ) # account for District of Columbia if tokens.length > 2 tokens[1] = tokens[1].toLowerCase() name = tokens.join(' ') if stateCodesByName[name] then name else null # returns a valid state code else null getStateCodeByStateName = (name) -> stateCodesByName[sanitizeStateName(name)] or null return { sanitizeStateCode: sanitizeStateCode getStateNameByStateCode: getStateNameByStateCode sanitizeStateName: sanitizeStateName getStateCodeByStateName: getStateCodeByStateName } )() emailRegex = /[A-z0-9._%+-]+@[A-z0-9.-]+\.[A-z]{2,63}/ isValidEmail = (email) -> emailRegex.test(email?.trim().toLowerCase()) formatStudentLicenseStatusDate = (status, date) -> string = switch status when 'not-enrolled' then $.i18n.t('teacher.status_not_enrolled') when 'enrolled' then (if date then $.i18n.t('teacher.status_enrolled') else '-') when 'expired' then $.i18n.t('teacher.status_expired') string.replace('{{date}}', date or 'Never') getApiClientIdFromEmail = (email) -> if /@codeninjas.com$/i.test(email) # hard coded for code ninjas since a lot of their users do not have clientCreator set clientID = '57fff652b0783842003fed00' return clientID # hard-coded 3 CS1 levels with concept video details # TODO: move them to database if more such levels videoLevels = { # gems in the deep "54173c90844506ae0195a0b4": { i18name: 'basic_syntax', url: "https://player.vimeo.com/video/310626758", cn_url: "https://assets.koudashijie.com/videos/%E5%AF%BC%E8%AF%BE01-%E5%9F%BA%E6%9C%AC%E8%AF%AD%E6%B3%95-Codecombat%20Instruction%20for%20Teachers.mp4", title: "Basic Syntax", original: "54173c90844506ae0195a0b4", thumbnail_locked: "/images/level/videos/basic_syntax_locked.png", thumbnail_unlocked: "/images/level/videos/basic_syntax_unlocked.png" }, # fire dancing "55ca293b9bc1892c835b0136": { i18name: 'while_loops', url: "https://player.vimeo.com/video/310626741", cn_url: "https://assets.koudashijie.com/videos/%E5%AF%BC%E8%AF%BE03-CodeCombat%E6%95%99%E5%AD%A6%E5%AF%BC%E8%AF%BE-CS1-%E5%BE%AA%E7%8E%AFlogo.mp4", title: "While Loops", original: "55ca293b9bc1892c835b0136" thumbnail_locked: "/images/level/videos/while_loops_locked.png", thumbnail_unlocked: "/images/level/videos/while_loops_unlocked.png" } # known enemy "5452adea57e83800009730ee": { i18name: 'variables', url: "https://player.vimeo.com/video/310626807", cn_url: "https://assets.koudashijie.com/videos/%E5%AF%BC%E8%AF%BE02-%E5%8F%98%E9%87%8F-CodeCombat-CS1-%E5%8F%98%E9%87%8Flogo.mp4", title: "Variables", original: "5452adea57e83800009730ee" thumbnail_locked: "/images/level/videos/variables_locked.png", thumbnail_unlocked: "/images/level/videos/variables_unlocked.png" } } yearsSinceMonth = (start) -> return undefined unless start # Should probably review this logic, written quickly and haven't tested any edge cases if _.isString start return undefined unless /\d{4}-\d{2}(-\d{2})?/.test start if start.length is 7 start = start + '-28' # Assume near the end of the month, don't let timezones mess it up, skew younger in interpretation start = new Date(start) return undefined unless _.isDate start now = new Date() now.getFullYear() - start.getFullYear() + (now.getMonth() - start.getMonth()) / 12 # Keep in sync with the copy in background-processor ageBrackets = [ {slug: '0-11', max: 11.33} {slug: '11-14', max: 14.33} {slug: '14-18', max: 18.99} {slug: 'open', max: 9001} ] ageToBracket = (age) -> # Convert years to an age bracket return 'open' unless age for bracket in ageBrackets if age < bracket.max return bracket.slug return 'open' bracketToAge = (slug) -> for i in [0...ageBrackets.length] if ageBrackets[i].slug == slug lowerBound = if i == 0 then 0 else ageBrackets[i-1].max higherBound = ageBrackets[i].max return { $gt: lowerBound, $lte: higherBound } CODECOMBAT = 'codecombat' CODECOMBAT_CHINA = 'koudashijie' OZARIA = 'ozaria' OZARIA_CHINA = 'aojiarui' isOldBrowser = () -> if features.china and $.browser return true if not ($.browser.webkit or $.browser.mozilla or $.browser.msedge) majorVersion = $.browser.versionNumber return true if $.browser.mozilla && majorVersion < 25 return true if $.browser.chrome && majorVersion < 72 # forbid some chinese browser return true if $.browser.safari && majorVersion < 6 # 6 might have problems with Aether, or maybe just old minors of 6: https://errorception.com/projects/51a79585ee207206390002a2/errors/547a202e1ead63ba4e4ac9fd return false isCodeCombat = true isOzaria = false arenas = [ {slug: 'blazing-battle' , type: 'regular', start: new Date(2021, 0, 1), end: new Date(2021, 4, 1), levelOriginal: '5fca06dc8b4da8002889dbf1', image: '/file/db/level/5fca06dc8b4da8002889dbf1/Blazing Battle Final cut.jpg'} {slug: 'infinite-inferno' , type: 'championship', start: new Date(2021, 3, 1), end: new Date(2021, 4, 1), levelOriginal: '602cdc204ef0480075fbd954', image: '/file/db/level/602cdc204ef0480075fbd954/InfiniteInferno_Banner_Final.jpg'} {slug: 'mages-might' , type: 'regular', start: new Date(2021, 4, 1), end: new Date(2021, 8, 1), levelOriginal: '6066f956ddfd6f003d1ed6bb', image: '/file/db/level/6066f956ddfd6f003d1ed6bb/Mages\'%20Might%20Banner.jpg'} {slug: 'sorcerers' , type: 'championship', start: new Date(2021, 7, 1), end: new Date(2021, 8, 1), levelOriginal: '609a6ad2e1eb34001a84e7af'} {slug: 'giants-gate' , type: 'regular', start: new Date(2021, 8, 1), end: new Date(2022, 0, 1)} {slug: 'colossus' , type: 'championship', start: new Date(2021, 11, 1), end: new Date(2022, 0, 1)} ] activeArenas = -> daysActiveAfterEnd = regular: 7, championship: 14 (_.clone(a) for a in arenas when a.start <= new Date() < a.end.getTime() + daysActiveAfterEnd[a.type] * 86400 * 1000) module.exports = { activeArenas addressesIncludeAdministrativeRegion ageBrackets ageOfConsent ageToBracket arenas bracketToAge campaignIDs capitalLanguages clone combineAncestralObject countries countryCodeToFlagEmoji countryCodeToName courseAcronyms courseIDs courseLessonSlidesURLs CSCourseIDs createLevelNumberMap extractPlayerCodeTag filterMarkdownCodeLanguages findNextAssessmentForLevel findNextLevel formatDollarValue formatStudentLicenseStatusDate functionCreators getApiClientIdFromEmail getByPath getCourseBundlePrice getCoursePraise getDocumentSearchString getPrepaidCodeAmount getQueryVariable getQueryVariables getSponsoredSubsAmount getUTCDay grayscale hexToHSL hslToHex i18n inEU injectCSS isID isIE isRegionalSubscription isSmokeTestEmail isValidEmail keepDoingUntil kindaEqual needsPractice normalizeFunc objectIdToDate orderedCourseIDs pathToUrl petThangIDs premiumContent replaceText round sortCourses sortCoursesByAcronyms stripIndentation titleize translatejs2cpp usStateCodes userAgent videoLevels yearsSinceMonth CODECOMBAT OZARIA CODECOMBAT_CHINA OZARIA_CHINA isOldBrowser isCodeCombat isOzaria titleize }
225143
slugify = _.str?.slugify ? _.string?.slugify # TODO: why _.string on client and _.str on server? translatejs2cpp = (jsCode, fullCode=true) -> matchBrackets = (str, startIndex) -> cc = 0 for i in [startIndex..str.length-1] by 1 cc += 1 if str[i] == '{' if str[i] == '}' cc -= 1 return i+2 unless cc splitFunctions = (str) -> creg = /\n[ \t]*[^\/]/ codeIndex = creg.exec(str) if str and str[0] != '/' startComments = '' else if codeIndex codeIndex = codeIndex.index + 1 startComments = str.slice 0, codeIndex str = str.slice codeIndex else return [str, ''] indices = [] reg = /\nfunction/gi indices.push 0 if str.startsWith("function ") while (result = reg.exec(str)) indices.push result.index+1 split = [] end = 0 split.push {s: 0, e: indices[0]} if indices.length for i in indices end = matchBrackets str, i split.push {s: i, e: end} split.push {s: end, e: str.length} header = if startComments then [startComments] else [] return header.concat split.map (s) -> str.slice s.s, s.e jsCodes = splitFunctions jsCode len = jsCodes.length lines = jsCodes[len-1].split '\n' if fullCode jsCodes[len-1] = """ int main() { #{(lines.map (line) -> ' ' + line).join '\n'} return 0; } """ else jsCodes[len-1] = (lines.map (line) -> ' ' + line).join('\n') for i in [0..len-1] by 1 if /^ *function/.test(jsCodes[i]) variables = jsCodes[i].match(/function.*\((.*)\)/)[1] v = '' v = variables.split(', ').map((e) -> 'auto ' + e).join(', ') if variables jsCodes[i] = jsCodes[i].replace(/function(.*)\((.*)\)/, 'auto$1(' + v + ')') jsCodes[i] = jsCodes[i].replace /var x/g, 'float x' jsCodes[i] = jsCodes[i].replace /var y/g, 'float y' jsCodes[i] = jsCodes[i].replace /var dist/g, 'float dist' jsCodes[i] = jsCodes[i].replace /var (\w+)Index/g, 'int $1Index' jsCodes[i] = jsCodes[i].replace /\ ===\ /g, ' == ' jsCodes[i] = jsCodes[i].replace /\.length/g, '.size()' jsCodes[i] = jsCodes[i].replace /\.push\(/g, '.push_back(' jsCodes[i] = jsCodes[i].replace /\.pop\(/g, '.pop_back(' jsCodes[i] = jsCodes[i].replace /\.shift\(/g, '.pop(' jsCodes[i] = jsCodes[i].replace /\ new /g, ' *new ' jsCodes[i] = jsCodes[i].replace /\ !== /g, ' != ' jsCodes[i] = jsCodes[i].replace /\ var /g, ' auto ' jsCodes[i] = jsCodes[i].replace /\ = \[([^;]*)\];/g, ' = {$1};' jsCodes[i] = jsCodes[i].replace /\(var /g, '(auto ' jsCodes[i] = jsCodes[i].replace /\nvar /g, '\nauto ' jsCodes[i] = jsCodes[i].replace /\ return \[([^;]*)\];/g, ' return {$1};' # Don't substitute these within comments noComment = '^ *([^/\\r\\n]*?)' quotesReg = new RegExp(noComment + "'(.*?)'", 'gm') while quotesReg.test(jsCodes[i]) jsCodes[i] = jsCodes[i].replace quotesReg, '$1"$2"' # first replace ' to " then replace object jsCodes[i] = jsCodes[i].replace /\{\s*"?x"?\s*:\s*([^,]+),\s*"?y"?\s*:\s*([^\}]*)\}/g, '{$1, $2}' # {x:1, y:1} -> {1, 1} unless fullCode lines = jsCodes[len-1].split '\n' jsCodes[len-1] = (lines.map (line) -> line.slice 1).join('\n') cppCodes = jsCodes.join('').split('\n') for i in [1..cppCodes.length-1] by 1 if cppCodes[i].match(/^\s*else/) and cppCodes[i-1].match("//") tmp = cppCodes[i] cppCodes[i] = cppCodes[i-1] cppCodes[i-1] = tmp cppCodes.join '\n' clone = (obj) -> return obj if obj is null or typeof (obj) isnt 'object' temp = obj.constructor() for key of obj temp[key] = clone(obj[key]) temp combineAncestralObject = (obj, propertyName) -> combined = {} while obj?[propertyName] for key, value of obj[propertyName] continue if combined[key] combined[key] = value if obj.__proto__ obj = obj.__proto__ else # IE has no __proto__. TODO: does this even work? At most it doesn't crash. obj = Object.getPrototypeOf(obj) combined countries = [ {country: 'united-states', countryCode: 'US', ageOfConsent: 13, addressesIncludeAdministrativeRegion:true} {country: 'china', countryCode: 'CN', addressesIncludeAdministrativeRegion:true} {country: 'brazil', countryCode: 'BR'} # Loosely ordered by decreasing traffic as measured 2016-09-01 - 2016-11-07 # TODO: switch to alphabetical ordering {country: 'united-kingdom', countryCode: 'GB', inEU: true, ageOfConsent: 13} {country: 'russia', countryCode: 'RU'} {country: 'australia', countryCode: 'AU', addressesIncludeAdministrativeRegion:true} {country: 'canada', countryCode: 'CA', addressesIncludeAdministrativeRegion:true} {country: 'france', countryCode: 'FR', inEU: true, ageOfConsent: 15} {country: 'taiwan', countryCode: 'TW'} {country: 'ukraine', countryCode: 'UA'} {country: 'poland', countryCode: 'PL', inEU: true, ageOfConsent: 13} {country: 'spain', countryCode: 'ES', inEU: true, ageOfConsent: 13} {country: 'germany', countryCode: 'DE', inEU: true, ageOfConsent: 16} {country: 'netherlands', countryCode: 'NL', inEU: true, ageOfConsent: 16} {country: 'hungary', countryCode: 'HU', inEU: true, ageOfConsent: 16} {country: 'japan', countryCode: 'JP'} {country: 'turkey', countryCode: 'TR'} {country: 'south-africa', countryCode: 'ZA'} {country: 'indonesia', countryCode: 'ID'} {country: 'new-zealand', countryCode: 'NZ'} {country: 'finland', countryCode: 'FI', inEU: true, ageOfConsent: 13} {country: 'south-korea', countryCode: 'KR'} {country: 'mexico', countryCode: 'MX', addressesIncludeAdministrativeRegion:true} {country: 'vietnam', countryCode: 'VN'} {country: 'singapore', countryCode: 'SG'} {country: 'colombia', countryCode: 'CO'} {country: 'india', countryCode: 'IN', addressesIncludeAdministrativeRegion:true} {country: 'thailand', countryCode: 'TH'} {country: 'belgium', countryCode: 'BE', inEU: true, ageOfConsent: 13} {country: 'sweden', countryCode: 'SE', inEU: true, ageOfConsent: 13} {country: 'denmark', countryCode: 'DK', inEU: true, ageOfConsent: 13} {country: 'czech-republic', countryCode: 'CZ', inEU: true, ageOfConsent: 15} {country: 'hong-kong', countryCode: 'HK'} {country: 'italy', countryCode: 'IT', inEU: true, ageOfConsent: 16, addressesIncludeAdministrativeRegion:true} {country: 'romania', countryCode: 'RO', inEU: true, ageOfConsent: 16} {country: 'belarus', countryCode: 'BY'} {country: 'norway', countryCode: 'NO', inEU: true, ageOfConsent: 13} # GDPR applies to EFTA {country: 'philippines', countryCode: 'PH'} {country: 'lithuania', countryCode: 'LT', inEU: true, ageOfConsent: 16} {country: 'argentina', countryCode: 'AR'} {country: 'malaysia', countryCode: 'MY', addressesIncludeAdministrativeRegion:true} {country: 'pakistan', countryCode: 'PK'} {country: 'serbia', countryCode: 'RS'} {country: 'greece', countryCode: 'GR', inEU: true, ageOfConsent: 15} {country: 'israel', countryCode: 'IL', inEU: true} {country: 'portugal', countryCode: 'PT', inEU: true, ageOfConsent: 13} {country: 'slovakia', countryCode: 'SK', inEU: true, ageOfConsent: 16} {country: 'ireland', countryCode: 'IE', inEU: true, ageOfConsent: 16} {country: 'switzerland', countryCode: 'CH', inEU: true, ageOfConsent: 16} # GDPR applies to EFTA {country: 'peru', countryCode: 'PE'} {country: 'bulgaria', countryCode: 'BG', inEU: true, ageOfConsent: 14} {country: 'venezuela', countryCode: 'VE'} {country: 'austria', countryCode: 'AT', inEU: true, ageOfConsent: 14} {country: 'croatia', countryCode: 'HR', inEU: true, ageOfConsent: 16} {country: 'saudia-arabia', countryCode: 'SA'} {country: 'chile', countryCode: 'CL'} {country: 'united-arab-emirates', countryCode: 'AE'} {country: 'kazakhstan', countryCode: 'KZ'} {country: 'estonia', countryCode: 'EE', inEU: true, ageOfConsent: 13} {country: 'iran', countryCode: 'IR'} {country: 'egypt', countryCode: 'EG'} {country: 'ecuador', countryCode: 'EC'} {country: 'slovenia', countryCode: 'SI', inEU: true, ageOfConsent: 15} {country: 'macedonia', countryCode: 'MK'} {country: 'cyprus', countryCode: 'CY', inEU: true, ageOfConsent: 14} {country: 'latvia', countryCode: 'LV', inEU: true, ageOfConsent: 13} {country: 'luxembourg', countryCode: 'LU', inEU: true, ageOfConsent: 16} {country: 'malta', countryCode: 'MT', inEU: true, ageOfConsent: 16} {country: 'lichtenstein', countryCode: 'LI', inEU: true} # GDPR applies to EFTA {country: 'iceland', countryCode: 'IS', inEU: true} # GDPR applies to EFTA ] inEU = (country) -> !!_.find(countries, (c) => c.country is slugify(country))?.inEU addressesIncludeAdministrativeRegion = (country) -> !!_.find(countries, (c) => c.country is slugify(country))?.addressesIncludeAdministrativeRegion ageOfConsent = (countryName, defaultIfUnknown=0) -> return defaultIfUnknown unless countryName country = _.find(countries, (c) => c.country is slugify(countryName)) return defaultIfUnknown unless country return country.ageOfConsent if country.ageOfConsent return 16 if country.inEU return defaultIfUnknown countryCodeToFlagEmoji = (code) -> return code unless code?.length is 2 (String.fromCodePoint(c.charCodeAt() + 0x1F1A5) for c in code.toUpperCase()).join('') countryCodeToName = (code) -> return code unless code?.length is 2 return code unless country = _.find countries, countryCode: code.toUpperCase() titleize country.country titleize = (s) -> # Turns things like 'dungeons-of-kithgard' into 'Dungeons of Kithgard' _.string.titleize(_.string.humanize(s)).replace(/ (and|or|but|nor|yet|so|for|a|an|the|in|to|of|at|by|up|for|off|on|with|from)(?= )/ig, (word) => word.toLowerCase()) campaignIDs = INTRO: '55b29efd1cd6abe8ce07db0d' courseIDs = INTRODUCTION_TO_COMPUTER_SCIENCE: '560f1a9f22961295f9427742' GAME_DEVELOPMENT_1: '5789587aad86a6efb573701e' WEB_DEVELOPMENT_1: '5789587aad86a6efb573701f' COMPUTER_SCIENCE_2: '5632661322961295f9428638' GAME_DEVELOPMENT_2: '57b621e7ad86a6efb5737e64' WEB_DEVELOPMENT_2: '5789587aad86a6efb5737020' COMPUTER_SCIENCE_3: '56462f935afde0c6fd30fc8c' GAME_DEVELOPMENT_3: '5a0df02b8f2391437740f74f' COMPUTER_SCIENCE_4: '56462f935afde0c6fd30fc8d' COMPUTER_SCIENCE_5: '569ed916efa72b0ced971447' COMPUTER_SCIENCE_6: '5817d673e85d1220db624ca4' CSCourseIDs = [ courseIDs.INTRODUCTION_TO_COMPUTER_SCIENCE courseIDs.COMPUTER_SCIENCE_2 courseIDs.COMPUTER_SCIENCE_3 courseIDs.COMPUTER_SCIENCE_4 courseIDs.COMPUTER_SCIENCE_5 courseIDs.COMPUTER_SCIENCE_6 ] orderedCourseIDs = [ courseIDs.INTRODUCTION_TO_COMPUTER_SCIENCE courseIDs.GAME_DEVELOPMENT_1 courseIDs.WEB_DEVELOPMENT_1 courseIDs.COMPUTER_SCIENCE_2 courseIDs.GAME_DEVELOPMENT_2 courseIDs.WEB_DEVELOPMENT_2 courseIDs.COMPUTER_SCIENCE_3 courseIDs.GAME_DEVELOPMENT_3 courseIDs.COMPUTER_SCIENCE_4 courseIDs.COMPUTER_SCIENCE_5 courseIDs.COMPUTER_SCIENCE_6 ] courseAcronyms = {} courseAcronyms[courseIDs.INTRODUCTION_TO_COMPUTER_SCIENCE] = 'CS1' courseAcronyms[courseIDs.GAME_DEVELOPMENT_1] = 'GD1' courseAcronyms[courseIDs.WEB_DEVELOPMENT_1] = 'WD1' courseAcronyms[courseIDs.COMPUTER_SCIENCE_2] = 'CS2' courseAcronyms[courseIDs.GAME_DEVELOPMENT_2] = 'GD2' courseAcronyms[courseIDs.WEB_DEVELOPMENT_2] = 'WD2' courseAcronyms[courseIDs.COMPUTER_SCIENCE_3] = 'CS3' courseAcronyms[courseIDs.GAME_DEVELOPMENT_3] = 'GD3' courseAcronyms[courseIDs.COMPUTER_SCIENCE_4] = 'CS4' courseAcronyms[courseIDs.COMPUTER_SCIENCE_5] = 'CS5' courseAcronyms[courseIDs.COMPUTER_SCIENCE_6] = 'CS6' courseLessonSlidesURLs = {} unless features?.china courseLessonSlidesURLs[courseIDs.INTRODUCTION_TO_COMPUTER_SCIENCE] = 'https://drive.google.com/drive/folders/1YU7LEZ6TLQzbAsSMw90nNJfvU7gDrcid?usp=sharing' courseLessonSlidesURLs[courseIDs.COMPUTER_SCIENCE_2] = 'https://drive.google.com/drive/folders/1x24P6ZY_MBOBoHvlikbDr7jvMPYVRVkJ?usp=sharing' courseLessonSlidesURLs[courseIDs.COMPUTER_SCIENCE_3] = 'https://drive.google.com/drive/folders/1hBl-h5Xvo5chYH4q9e6IEo42JozlrTG9?usp=sharing' courseLessonSlidesURLs[courseIDs.COMPUTER_SCIENCE_4] = 'https://drive.google.com/drive/folders/1tbuE4Xn0ahJ0xcF1-OaiPs9lHeIs9zqG?usp=sharing' courseLessonSlidesURLs[courseIDs.COMPUTER_SCIENCE_5] = 'https://drive.google.com/drive/folders/1ThxWFZjoXzU5INtMzlqKEn8xkgHhVnl4?usp=sharing' petThangIDs = [ '578d320d15e2501f00a585bd' # Wolf Pup '5744e3683af6bf590cd27371' # Cougar '5786a472a6c64135009238d3' # Raven '577d5d4dab818b210046b3bf' # Pugicorn '58c74b7c3d4a3d2900d43b7e' # Brown Rat '58c7614a62cc3a1f00442240' # Yetibab '58a262520b43652f00dad75e' # Phoenix '57869cf7bd31c14400834028' # Frog '578691f9bd31c1440083251d' # Polar Bear Cub '58a2712b0b43652f00dae5a4' # Blue Fox '58c737140ca7852e005deb8a' # Mimic '57586f0a22179b2800efda37' # Baby Griffin ] premiumContent = premiumHeroesCount: '12' totalHeroesCount: '16' premiumLevelsCount: '330' freeLevelsCount: '100' normalizeFunc = (func_thing, object) -> # func could be a string to a function in this class # or a function in its own right object ?= {} if _.isString(func_thing) func = object[func_thing] if not func console.error "Could not find method #{func_thing} in object", object return => null # always return a func, or Mediator will go boom func_thing = func return func_thing objectIdToDate = (objectID) -> new Date(parseInt(objectID.toString().slice(0,8), 16)*1000) hexToHSL = (hex) -> rgbToHsl(hexToR(hex), hexToG(hex), hexToB(hex)) hexToR = (h) -> parseInt (cutHex(h)).substring(0, 2), 16 hexToG = (h) -> parseInt (cutHex(h)).substring(2, 4), 16 hexToB = (h) -> parseInt (cutHex(h)).substring(4, 6), 16 cutHex = (h) -> (if (h.charAt(0) is '#') then h.substring(1, 7) else h) hslToHex = (hsl) -> '#' + (toHex(n) for n in hslToRgb(hsl...)).join('') toHex = (n) -> h = Math.floor(n).toString(16) h = '0'+h if h.length is 1 h pathToUrl = (path) -> base = location.protocol + '//' + location.hostname + (location.port && ":" + location.port) base + path extractPlayerCodeTag = (code) -> unwrappedDefaultCode = code.match(/<playercode>\n([\s\S]*)\n *<\/playercode>/)?[1] if unwrappedDefaultCode return stripIndentation(unwrappedDefaultCode) else return undefined stripIndentation = (code) -> codeLines = code.split('\n') indentation = _.min(_.filter(codeLines.map (line) -> line.match(/^\s*/)?[0]?.length)) strippedCode = (line.substr(indentation) for line in codeLines).join('\n') return strippedCode # @param {Object} say - the object containing an i18n property. # @param {string} target - the attribute that you want to access. # @returns {string} translated string if possible # Example usage: # `courseName = utils.i18n(course.attributes, 'name')` i18n = (say, target, language=me.get('preferredLanguage', true), fallback='en') -> generalResult = null fallBackResult = null fallForwardResult = null # If a general language isn't available, the first specific one will do. fallSidewaysResult = null # If a specific language isn't available, its sibling specific language will do. matches = (/\w+/gi).exec(language) generalName = matches[0] if matches for localeName, locale of say.i18n continue if localeName is '-' if target of locale result = locale[target] else continue return result if localeName is language generalResult = result if localeName is generalName fallBackResult = result if localeName is fallback fallForwardResult = result if localeName.indexOf(language) is 0 and not fallForwardResult? fallSidewaysResult = result if localeName.indexOf(generalName) is 0 and not fallSidewaysResult? return generalResult if generalResult? return fallForwardResult if fallForwardResult? return fallSidewaysResult if fallSidewaysResult? return fallBackResult if fallBackResult? return say[target] if target of say null getByPath = (target, path) -> throw new Error 'Expected an object to match a query against, instead got null' unless target pieces = path.split('.') obj = target for piece in pieces return undefined unless piece of obj obj = obj[piece] obj isID = (id) -> _.isString(id) and id.length is 24 and id.match(/[a-f0-9]/gi)?.length is 24 isIE = -> $?.browser?.msie ? false isRegionalSubscription = (name) -> /_basic_subscription/.test(name) isSmokeTestEmail = (email) -> /@<EMAIL>/.test(email) or /smoketest/.test(email) round = _.curry (digits, n) -> n = +n.toFixed(digits) positify = (func) -> (params) -> (x) -> if x > 0 then func(params)(x) else 0 # f(x) = ax + b createLinearFunc = (params) -> (x) -> (params.a or 1) * x + (params.b or 0) # f(x) = ax² + bx + c createQuadraticFunc = (params) -> (x) -> (params.a or 1) * x * x + (params.b or 1) * x + (params.c or 0) # f(x) = a log(b (x + c)) + d createLogFunc = (params) -> (x) -> if x > 0 then (params.a or 1) * Math.log((params.b or 1) * (x + (params.c or 0))) + (params.d or 0) else 0 # f(x) = ax^b + c createPowFunc = (params) -> (x) -> (params.a or 1) * Math.pow(x, params.b or 1) + (params.c or 0) functionCreators = linear: positify(createLinearFunc) quadratic: positify(createQuadraticFunc) logarithmic: positify(createLogFunc) pow: positify(createPowFunc) # Call done with true to satisfy the 'until' goal and stop repeating func keepDoingUntil = (func, wait=100, totalWait=5000) -> waitSoFar = 0 (done = (success) -> if (waitSoFar += wait) <= totalWait and not success _.delay (-> func done), wait) false grayscale = (imageData) -> d = imageData.data for i in [0..d.length] by 4 r = d[i] g = d[i+1] b = d[i+2] v = 0.2126*r + 0.7152*g + 0.0722*b d[i] = d[i+1] = d[i+2] = v imageData # Deep compares l with r, with the exception that undefined values are considered equal to missing values # Very practical for comparing Mongoose documents where undefined is not allowed, instead fields get deleted kindaEqual = compare = (l, r) -> if _.isObject(l) and _.isObject(r) for key in _.union Object.keys(l), Object.keys(r) return false unless compare l[key], r[key] return true else if l is r return true else return false # Return UTC string "YYYYMMDD" for today + offset getUTCDay = (offset=0) -> day = new Date() day.setDate(day.getUTCDate() + offset) partYear = day.getUTCFullYear() partMonth = (day.getUTCMonth() + 1) partMonth = "0" + partMonth if partMonth < 10 partDay = day.getUTCDate() partDay = "0" + partDay if partDay < 10 "#{partYear}#{partMonth}#{partDay}" # Fast, basic way to replace text in an element when you don't need much. # http://stackoverflow.com/a/4962398/540620 if document?.createElement dummy = document.createElement 'div' dummy.innerHTML = 'text' TEXT = if dummy.textContent is 'text' then 'textContent' else 'innerText' replaceText = (elems, text) -> elem[TEXT] = text for elem in elems null # Add a stylesheet rule # http://stackoverflow.com/questions/524696/how-to-create-a-style-tag-with-javascript/26230472#26230472 # Don't use wantonly, or we'll have to implement a simple mechanism for clearing out old rules. if document?.createElement injectCSS = ((doc) -> # wrapper for all injected styles and temp el to create them wrap = doc.createElement("div") temp = doc.createElement("div") # rules like "a {color: red}" etc. return (cssRules) -> # append wrapper to the body on the first call unless wrap.id wrap.id = "injected-css" wrap.style.display = "none" doc.body.appendChild wrap # <br> for IE: http://goo.gl/vLY4x7 temp.innerHTML = "<br><style>" + cssRules + "</style>" wrap.appendChild temp.children[1] return )(document) # So that we can stub out userAgent in tests userAgent = -> window.navigator.userAgent getDocumentSearchString = -> # moved to a separate function so it can be mocked for testing return document.location.search getQueryVariables = -> query = module.exports.getDocumentSearchString().substring(1) # use module.exports so spy is used in testing pairs = (pair.split('=') for pair in query.split '&') variables = {} for [key, value] in pairs variables[key] = {'true': true, 'false': false}[value] ? decodeURIComponent(value) return variables getQueryVariable = (param, defaultValue) -> variables = getQueryVariables() return variables[param] ? defaultValue getSponsoredSubsAmount = (price=999, subCount=0, personalSub=false) -> # 1 100% # 2-11 80% # 12+ 60% # TODO: make this less confusing return 0 unless subCount > 0 offset = if personalSub then 1 else 0 if subCount <= 1 - offset price else if subCount <= 11 - offset Math.round((1 - offset) * price + (subCount - 1 + offset) * price * 0.8) else Math.round((1 - offset) * price + 10 * price * 0.8 + (subCount - 11 + offset) * price * 0.6) getCourseBundlePrice = (coursePrices, seats=20) -> totalPricePerSeat = coursePrices.reduce ((a, b) -> a + b), 0 if coursePrices.length > 2 pricePerSeat = Math.round(totalPricePerSeat / 2.0) else pricePerSeat = parseInt(totalPricePerSeat) seats * pricePerSeat getCoursePraise = -> praise = [ { quote: "The kids love it." source: "<NAME>, <NAME>thlos Leadership Academy" }, { quote: "My students have been using the site for a couple of weeks and they love it." source: "<NAME>, Computer Applications Teacher, School Technology Coordinator, Eastside Middle School" }, { quote: "Thanks for the captivating site. My eighth graders love it." source: "<NAME>, Ansbach Middle/High School" }, { quote: "My students have started working on CodeCombat and love it! I love that they are learning coding and problem solving skills without them even knowing it!!" source: "<NAME>, Special Education Teacher, Webb City School District" }, { quote: "I recently introduced Code Combat to a few of my fifth graders and they are loving it!" source: "<NAME>, Fifth Grade Teacher, Four Peaks Elementary School" }, { quote: "Overall I think it's a fantastic service. Variables, arrays, loops, all covered in very fun and imaginative ways. Every kid who has tried it is a fan." source: "<NAME>, Technology Teacher" }, { quote: "I love what you have created. The kids are so engaged." source: "<NAME>, 4KS Academy" }, { quote: "My students love the website and I hope on having content structured around it in the near future." source: "<NAME>, Science Teacher, Clearwater Central Catholic High School" } ] praise[_.random(0, praise.length - 1)] getPrepaidCodeAmount = (price=0, users=0, months=0) -> return 0 unless users > 0 and months > 0 total = price * users * months total formatDollarValue = (dollars) -> '$' + (parseFloat(dollars).toFixed(2)) startsWithVowel = (s) -> s[0] in 'aeiouAEIOU' filterMarkdownCodeLanguages = (text, language) -> return '' unless text currentLanguage = language or me.get('aceConfig')?.language or 'python' excludedLanguages = _.without ['javascript', 'python', 'coffeescript', 'lua', 'java', 'cpp', 'html'], if currentLanguage == 'cpp' then 'javascript' else currentLanguage # Exclude language-specific code blocks like ```python (... code ...)`` # ` for each non-target language. codeBlockExclusionRegex = new RegExp "```(#{excludedLanguages.join('|')})\n[^`]+```\n?", 'gm' # Exclude language-specific images like ![python - image description](image url) for each non-target language. imageExclusionRegex = new RegExp "!\\[(#{excludedLanguages.join('|')}) - .+?\\]\\(.+?\\)\n?", 'gm' text = text.replace(codeBlockExclusionRegex, '').replace(imageExclusionRegex, '') commonLanguageReplacements = python: [ ['true', 'True'], ['false', 'False'], ['null', 'None'], ['object', 'dictionary'], ['Object', 'Dictionary'], ['array', 'list'], ['Array', 'List'], ] lua: [ ['null', 'nil'], ['object', 'table'], ['Object', 'Table'], ['array', 'table'], ['Array', 'Table'], ] for [from, to] in commonLanguageReplacements[currentLanguage] ? [] # Convert JS-specific keywords and types to Python ones, if in simple `code` tags. # This won't cover it when it's not in an inline code tag by itself or when it's not in English. text = text.replace ///`#{from}`///g, "`#{to}`" # Now change "An `dictionary`" to "A `dictionary`", etc. if startsWithVowel(from) and not startsWithVowel(to) text = text.replace ///(\ a|A)n(\ `#{to}`)///g, "$1$2" if not startsWithVowel(from) and startsWithVowel(to) text = text.replace ///(\ a|A)(\ `#{to}`)///g, "$1n$2" if currentLanguage == 'cpp' jsRegex = new RegExp "```javascript\n([^`]+)```", 'gm' text = text.replace jsRegex, (a, l) => """```cpp #{@translatejs2cpp a[13..a.length-4], false} ```""" return text capitalLanguages = 'javascript': 'JavaScript' 'coffeescript': 'CoffeeScript' 'python': 'Python' 'java': 'Java' 'cpp': 'C++' 'lua': 'Lua' 'html': 'HTML' createLevelNumberMap = (levels) -> levelNumberMap = {} practiceLevelTotalCount = 0 practiceLevelCurrentCount = 0 for level, i in levels levelNumber = i - practiceLevelTotalCount + 1 if level.practice levelNumber = i - practiceLevelTotalCount + String.fromCharCode('a'.charCodeAt(0) + practiceLevelCurrentCount) practiceLevelTotalCount++ practiceLevelCurrentCount++ else if level.assessment practiceLevelTotalCount++ practiceLevelCurrentCount++ levelNumber = if level.assessment is 'cumulative' then $.t('play_level.combo_challenge') else $.t('play_level.concept_challenge') else practiceLevelCurrentCount = 0 levelNumberMap[level.key] = levelNumber levelNumberMap findNextLevel = (levels, currentIndex, needsPractice) -> # Find next available incomplete level, depending on whether practice is needed # levels = [{practice: true/false, complete: true/false, assessment: true/false, locked: true/false}] # Skip over assessment levels # return -1 if at or beyond locked level return -1 for i in [0..currentIndex] when levels[i].locked index = currentIndex index++ if needsPractice if levels[currentIndex].practice or index < levels.length and levels[index].practice # Needs practice, current level is practice or next is practice; return the next incomplete practice-or-normal level # May leave earlier practice levels incomplete and reach end of course while index < levels.length and (levels[index].complete or levels[index].assessment) return -1 if levels[index].locked index++ else # Needs practice, current level is required, next level is required or assessment; return the first incomplete level of previous practice chain index-- index-- while index >= 0 and not levels[index].practice if index >= 0 index-- while index >= 0 and levels[index].practice if index >= 0 index++ index++ while index < levels.length and levels[index].practice and levels[index].complete if levels[index].practice and not levels[index].complete return index # Last set of practice levels is complete; return the next incomplete normal level instead. index = currentIndex + 1 while index < levels.length and (levels[index].complete or levels[index].assessment) return -1 if levels[index].locked index++ else # No practice needed; return the next required incomplete level while index < levels.length and (levels[index].practice or levels[index].complete or levels[index].assessment) return -1 if levels[index].locked index++ index findNextAssessmentForLevel = (levels, currentIndex, needsPractice) -> # Find assessment level immediately after current level (and its practice levels) # Only return assessment if it's the next level # Skip over practice levels unless practice neeeded # levels = [{practice: true/false, complete: true/false, assessment: true/false, locked: true/false}] # eg: l*,p,p,a*,a',l,... # given index l*, return index a* # given index a*, return index a' index = currentIndex index++ while index < levels.length if levels[index].practice return -1 if needsPractice and not levels[index].complete index++ # It's a practice level but do not need practice, keep looking else if levels[index].assessment return -1 if levels[index].complete return index else if levels[index].complete # It's completed, keep looking index++ else # we got to a normal level; we didn't find an assessment for the given level. return -1 return -1 # we got to the end of the list and found nothing needsPractice = (playtime=0, threshold=5) -> playtime / 60 > threshold sortCourses = (courses) -> _.sortBy courses, (course) -> # ._id can be from classroom.courses, otherwise it's probably .id index = orderedCourseIDs.indexOf(course.id ? course._id) index = 9001 if index is -1 index sortCoursesByAcronyms = (courses) -> orderedCourseAcronyms = _.sortBy(courseAcronyms) _.sortBy courses, (course) -> # ._id can be from classroom.courses, otherwise it's probably .id index = orderedCourseAcronyms.indexOf(courseAcronyms[course.id ? course._id]) index = 9001 if index is -1 index usStateCodes = # https://github.com/mdzhang/us-state-codes # generated by js2coffee 2.2.0 (-> stateNamesByCode = 'AL': 'Alabama' 'AK': 'Alaska' 'AZ': 'Arizona' 'AR': 'Arkansas' 'CA': 'California' 'CO': 'Colorado' 'CT': 'Connecticut' 'DE': 'Delaware' 'DC': 'District of Columbia' 'FL': 'Florida' 'GA': 'Georgia' 'HI': 'Hawaii' 'ID': 'Idaho' 'IL': 'Illinois' 'IN': 'Indiana' 'IA': 'Iowa' 'KS': 'Kansas' 'KY': 'Kentucky' 'LA': 'Louisiana' 'ME': 'Maine' 'MD': 'Maryland' 'MA': 'Massachusetts' 'MI': 'Michigan' 'MN': 'Minnesota' 'MS': 'Mississippi' 'MO': 'Missouri' 'MT': 'Montana' 'NE': 'Nebraska' 'NV': 'Nevada' 'NH': 'New Hampshire' 'NJ': 'New Jersey' 'NM': 'New Mexico' 'NY': 'New York' 'NC': 'North Carolina' 'ND': 'North Dakota' 'OH': 'Ohio' 'OK': 'Oklahoma' 'OR': 'Oregon' 'PA': 'Pennsylvania' 'RI': 'Rhode Island' 'SC': 'South Carolina' 'SD': 'South Dakota' 'TN': 'Tennessee' 'TX': 'Texas' 'UT': 'Utah' 'VT': 'Vermont' 'VA': 'Virginia' 'WA': 'Washington' 'WV': 'West Virginia' 'WI': 'Wisconsin' 'WY': 'Wyoming' stateCodesByName = _.invert(stateNamesByCode) # normalizes case and removes invalid characters # returns null if can't find sanitized code in the state map sanitizeStateCode = (code) -> code = if _.isString(code) then code.trim().toUpperCase().replace(/[^A-Z]/g, '') else null if stateNamesByCode[code] then code else null # returns a valid state name else null getStateNameByStateCode = (code) -> stateNamesByCode[sanitizeStateCode(code)] or null # normalizes case and removes invalid characters # returns null if can't find sanitized name in the state map sanitizeStateName = (name) -> if !_.isString(name) return null # bad whitespace remains bad whitespace e.g. "O hi o" is not valid name = name.trim().toLowerCase().replace(/[^a-z\s]/g, '').replace(/\s+/g, ' ') tokens = name.split(/\s+/) tokens = _.map(tokens, (token) -> token.charAt(0).toUpperCase() + token.slice(1) ) # account for District of Columbia if tokens.length > 2 tokens[1] = tokens[1].toLowerCase() name = tokens.join(' ') if stateCodesByName[name] then name else null # returns a valid state code else null getStateCodeByStateName = (name) -> stateCodesByName[sanitizeStateName(name)] or null return { sanitizeStateCode: sanitizeStateCode getStateNameByStateCode: getStateNameByStateCode sanitizeStateName: sanitizeStateName getStateCodeByStateName: getStateCodeByStateName } )() emailRegex = /[A-z0-9._%+-]+@[A-z0-9.-]+\.[A-z]{2,63}/ isValidEmail = (email) -> emailRegex.test(email?.trim().toLowerCase()) formatStudentLicenseStatusDate = (status, date) -> string = switch status when 'not-enrolled' then $.i18n.t('teacher.status_not_enrolled') when 'enrolled' then (if date then $.i18n.t('teacher.status_enrolled') else '-') when 'expired' then $.i18n.t('teacher.status_expired') string.replace('{{date}}', date or 'Never') getApiClientIdFromEmail = (email) -> if<EMAIL> /<EMAIL>$/i.test(email) # hard coded for code ninjas since a lot of their users do not have clientCreator set clientID = '57fff652b0783842003fed00' return clientID # hard-coded 3 CS1 levels with concept video details # TODO: move them to database if more such levels videoLevels = { # gems in the deep "54173c90844506ae0195a0b4": { i18name: 'basic_syntax', url: "https://player.vimeo.com/video/310626758", cn_url: "https://assets.koudashijie.com/videos/%E5%AF%BC%E8%AF%BE01-%E5%9F%BA%E6%9C%AC%E8%AF%AD%E6%B3%95-Codecombat%20Instruction%20for%20Teachers.mp4", title: "Basic Syntax", original: "54173c90844506ae0195a0b4", thumbnail_locked: "/images/level/videos/basic_syntax_locked.png", thumbnail_unlocked: "/images/level/videos/basic_syntax_unlocked.png" }, # fire dancing "55ca293b9bc1892c835b0136": { i18name: 'while_loops', url: "https://player.vimeo.com/video/310626741", cn_url: "https://assets.koudashijie.com/videos/%E5%AF%BC%E8%AF%BE03-CodeCombat%E6%95%99%E5%AD%A6%E5%AF%BC%E8%AF%BE-CS1-%E5%BE%AA%E7%8E%AFlogo.mp4", title: "While Loops", original: "55ca293b9bc1892c835b0136" thumbnail_locked: "/images/level/videos/while_loops_locked.png", thumbnail_unlocked: "/images/level/videos/while_loops_unlocked.png" } # known enemy "5452adea57e83800009730ee": { i18name: 'variables', url: "https://player.vimeo.com/video/310626807", cn_url: "https://assets.koudashijie.com/videos/%E5%AF%BC%E8%AF%BE02-%E5%8F%98%E9%87%8F-CodeCombat-CS1-%E5%8F%98%E9%87%8Flogo.mp4", title: "Variables", original: "5452adea57e83800009730ee" thumbnail_locked: "/images/level/videos/variables_locked.png", thumbnail_unlocked: "/images/level/videos/variables_unlocked.png" } } yearsSinceMonth = (start) -> return undefined unless start # Should probably review this logic, written quickly and haven't tested any edge cases if _.isString start return undefined unless /\d{4}-\d{2}(-\d{2})?/.test start if start.length is 7 start = start + '-28' # Assume near the end of the month, don't let timezones mess it up, skew younger in interpretation start = new Date(start) return undefined unless _.isDate start now = new Date() now.getFullYear() - start.getFullYear() + (now.getMonth() - start.getMonth()) / 12 # Keep in sync with the copy in background-processor ageBrackets = [ {slug: '0-11', max: 11.33} {slug: '11-14', max: 14.33} {slug: '14-18', max: 18.99} {slug: 'open', max: 9001} ] ageToBracket = (age) -> # Convert years to an age bracket return 'open' unless age for bracket in ageBrackets if age < bracket.max return bracket.slug return 'open' bracketToAge = (slug) -> for i in [0...ageBrackets.length] if ageBrackets[i].slug == slug lowerBound = if i == 0 then 0 else ageBrackets[i-1].max higherBound = ageBrackets[i].max return { $gt: lowerBound, $lte: higherBound } CODECOMBAT = 'codecombat' CODECOMBAT_CHINA = 'koudashijie' OZARIA = 'ozaria' OZARIA_CHINA = 'aojiarui' isOldBrowser = () -> if features.china and $.browser return true if not ($.browser.webkit or $.browser.mozilla or $.browser.msedge) majorVersion = $.browser.versionNumber return true if $.browser.mozilla && majorVersion < 25 return true if $.browser.chrome && majorVersion < 72 # forbid some chinese browser return true if $.browser.safari && majorVersion < 6 # 6 might have problems with Aether, or maybe just old minors of 6: https://errorception.com/projects/51a79585ee207206390002a2/errors/547a202e1ead63ba4e4ac9fd return false isCodeCombat = true isOzaria = false arenas = [ {slug: 'blazing-battle' , type: 'regular', start: new Date(2021, 0, 1), end: new Date(2021, 4, 1), levelOriginal: '5fca06dc8b4da8002889dbf1', image: '/file/db/level/5fca06dc8b4da8002889dbf1/Blazing Battle Final cut.jpg'} {slug: 'infinite-inferno' , type: 'championship', start: new Date(2021, 3, 1), end: new Date(2021, 4, 1), levelOriginal: '602cdc204ef0480075fbd954', image: '/file/db/level/602cdc204ef0480075fbd954/InfiniteInferno_Banner_Final.jpg'} {slug: 'mages-might' , type: 'regular', start: new Date(2021, 4, 1), end: new Date(2021, 8, 1), levelOriginal: '6066f956ddfd6f003d1ed6bb', image: '/file/db/level/6066f956ddfd6f003d1ed6bb/Mages\'%20Might%20Banner.jpg'} {slug: 'sorcerers' , type: 'championship', start: new Date(2021, 7, 1), end: new Date(2021, 8, 1), levelOriginal: '609a6ad2e1eb34001a84e7af'} {slug: 'giants-gate' , type: 'regular', start: new Date(2021, 8, 1), end: new Date(2022, 0, 1)} {slug: 'colossus' , type: 'championship', start: new Date(2021, 11, 1), end: new Date(2022, 0, 1)} ] activeArenas = -> daysActiveAfterEnd = regular: 7, championship: 14 (_.clone(a) for a in arenas when a.start <= new Date() < a.end.getTime() + daysActiveAfterEnd[a.type] * 86400 * 1000) module.exports = { activeArenas addressesIncludeAdministrativeRegion ageBrackets ageOfConsent ageToBracket arenas bracketToAge campaignIDs capitalLanguages clone combineAncestralObject countries countryCodeToFlagEmoji countryCodeToName courseAcronyms courseIDs courseLessonSlidesURLs CSCourseIDs createLevelNumberMap extractPlayerCodeTag filterMarkdownCodeLanguages findNextAssessmentForLevel findNextLevel formatDollarValue formatStudentLicenseStatusDate functionCreators getApiClientIdFromEmail getByPath getCourseBundlePrice getCoursePraise getDocumentSearchString getPrepaidCodeAmount getQueryVariable getQueryVariables getSponsoredSubsAmount getUTCDay grayscale hexToHSL hslToHex i18n inEU injectCSS isID isIE isRegionalSubscription isSmokeTestEmail isValidEmail keepDoingUntil kindaEqual needsPractice normalizeFunc objectIdToDate orderedCourseIDs pathToUrl petThangIDs premiumContent replaceText round sortCourses sortCoursesByAcronyms stripIndentation titleize translatejs2cpp usStateCodes userAgent videoLevels yearsSinceMonth CODECOMBAT OZARIA CODECOMBAT_CHINA OZARIA_CHINA isOldBrowser isCodeCombat isOzaria titleize }
true
slugify = _.str?.slugify ? _.string?.slugify # TODO: why _.string on client and _.str on server? translatejs2cpp = (jsCode, fullCode=true) -> matchBrackets = (str, startIndex) -> cc = 0 for i in [startIndex..str.length-1] by 1 cc += 1 if str[i] == '{' if str[i] == '}' cc -= 1 return i+2 unless cc splitFunctions = (str) -> creg = /\n[ \t]*[^\/]/ codeIndex = creg.exec(str) if str and str[0] != '/' startComments = '' else if codeIndex codeIndex = codeIndex.index + 1 startComments = str.slice 0, codeIndex str = str.slice codeIndex else return [str, ''] indices = [] reg = /\nfunction/gi indices.push 0 if str.startsWith("function ") while (result = reg.exec(str)) indices.push result.index+1 split = [] end = 0 split.push {s: 0, e: indices[0]} if indices.length for i in indices end = matchBrackets str, i split.push {s: i, e: end} split.push {s: end, e: str.length} header = if startComments then [startComments] else [] return header.concat split.map (s) -> str.slice s.s, s.e jsCodes = splitFunctions jsCode len = jsCodes.length lines = jsCodes[len-1].split '\n' if fullCode jsCodes[len-1] = """ int main() { #{(lines.map (line) -> ' ' + line).join '\n'} return 0; } """ else jsCodes[len-1] = (lines.map (line) -> ' ' + line).join('\n') for i in [0..len-1] by 1 if /^ *function/.test(jsCodes[i]) variables = jsCodes[i].match(/function.*\((.*)\)/)[1] v = '' v = variables.split(', ').map((e) -> 'auto ' + e).join(', ') if variables jsCodes[i] = jsCodes[i].replace(/function(.*)\((.*)\)/, 'auto$1(' + v + ')') jsCodes[i] = jsCodes[i].replace /var x/g, 'float x' jsCodes[i] = jsCodes[i].replace /var y/g, 'float y' jsCodes[i] = jsCodes[i].replace /var dist/g, 'float dist' jsCodes[i] = jsCodes[i].replace /var (\w+)Index/g, 'int $1Index' jsCodes[i] = jsCodes[i].replace /\ ===\ /g, ' == ' jsCodes[i] = jsCodes[i].replace /\.length/g, '.size()' jsCodes[i] = jsCodes[i].replace /\.push\(/g, '.push_back(' jsCodes[i] = jsCodes[i].replace /\.pop\(/g, '.pop_back(' jsCodes[i] = jsCodes[i].replace /\.shift\(/g, '.pop(' jsCodes[i] = jsCodes[i].replace /\ new /g, ' *new ' jsCodes[i] = jsCodes[i].replace /\ !== /g, ' != ' jsCodes[i] = jsCodes[i].replace /\ var /g, ' auto ' jsCodes[i] = jsCodes[i].replace /\ = \[([^;]*)\];/g, ' = {$1};' jsCodes[i] = jsCodes[i].replace /\(var /g, '(auto ' jsCodes[i] = jsCodes[i].replace /\nvar /g, '\nauto ' jsCodes[i] = jsCodes[i].replace /\ return \[([^;]*)\];/g, ' return {$1};' # Don't substitute these within comments noComment = '^ *([^/\\r\\n]*?)' quotesReg = new RegExp(noComment + "'(.*?)'", 'gm') while quotesReg.test(jsCodes[i]) jsCodes[i] = jsCodes[i].replace quotesReg, '$1"$2"' # first replace ' to " then replace object jsCodes[i] = jsCodes[i].replace /\{\s*"?x"?\s*:\s*([^,]+),\s*"?y"?\s*:\s*([^\}]*)\}/g, '{$1, $2}' # {x:1, y:1} -> {1, 1} unless fullCode lines = jsCodes[len-1].split '\n' jsCodes[len-1] = (lines.map (line) -> line.slice 1).join('\n') cppCodes = jsCodes.join('').split('\n') for i in [1..cppCodes.length-1] by 1 if cppCodes[i].match(/^\s*else/) and cppCodes[i-1].match("//") tmp = cppCodes[i] cppCodes[i] = cppCodes[i-1] cppCodes[i-1] = tmp cppCodes.join '\n' clone = (obj) -> return obj if obj is null or typeof (obj) isnt 'object' temp = obj.constructor() for key of obj temp[key] = clone(obj[key]) temp combineAncestralObject = (obj, propertyName) -> combined = {} while obj?[propertyName] for key, value of obj[propertyName] continue if combined[key] combined[key] = value if obj.__proto__ obj = obj.__proto__ else # IE has no __proto__. TODO: does this even work? At most it doesn't crash. obj = Object.getPrototypeOf(obj) combined countries = [ {country: 'united-states', countryCode: 'US', ageOfConsent: 13, addressesIncludeAdministrativeRegion:true} {country: 'china', countryCode: 'CN', addressesIncludeAdministrativeRegion:true} {country: 'brazil', countryCode: 'BR'} # Loosely ordered by decreasing traffic as measured 2016-09-01 - 2016-11-07 # TODO: switch to alphabetical ordering {country: 'united-kingdom', countryCode: 'GB', inEU: true, ageOfConsent: 13} {country: 'russia', countryCode: 'RU'} {country: 'australia', countryCode: 'AU', addressesIncludeAdministrativeRegion:true} {country: 'canada', countryCode: 'CA', addressesIncludeAdministrativeRegion:true} {country: 'france', countryCode: 'FR', inEU: true, ageOfConsent: 15} {country: 'taiwan', countryCode: 'TW'} {country: 'ukraine', countryCode: 'UA'} {country: 'poland', countryCode: 'PL', inEU: true, ageOfConsent: 13} {country: 'spain', countryCode: 'ES', inEU: true, ageOfConsent: 13} {country: 'germany', countryCode: 'DE', inEU: true, ageOfConsent: 16} {country: 'netherlands', countryCode: 'NL', inEU: true, ageOfConsent: 16} {country: 'hungary', countryCode: 'HU', inEU: true, ageOfConsent: 16} {country: 'japan', countryCode: 'JP'} {country: 'turkey', countryCode: 'TR'} {country: 'south-africa', countryCode: 'ZA'} {country: 'indonesia', countryCode: 'ID'} {country: 'new-zealand', countryCode: 'NZ'} {country: 'finland', countryCode: 'FI', inEU: true, ageOfConsent: 13} {country: 'south-korea', countryCode: 'KR'} {country: 'mexico', countryCode: 'MX', addressesIncludeAdministrativeRegion:true} {country: 'vietnam', countryCode: 'VN'} {country: 'singapore', countryCode: 'SG'} {country: 'colombia', countryCode: 'CO'} {country: 'india', countryCode: 'IN', addressesIncludeAdministrativeRegion:true} {country: 'thailand', countryCode: 'TH'} {country: 'belgium', countryCode: 'BE', inEU: true, ageOfConsent: 13} {country: 'sweden', countryCode: 'SE', inEU: true, ageOfConsent: 13} {country: 'denmark', countryCode: 'DK', inEU: true, ageOfConsent: 13} {country: 'czech-republic', countryCode: 'CZ', inEU: true, ageOfConsent: 15} {country: 'hong-kong', countryCode: 'HK'} {country: 'italy', countryCode: 'IT', inEU: true, ageOfConsent: 16, addressesIncludeAdministrativeRegion:true} {country: 'romania', countryCode: 'RO', inEU: true, ageOfConsent: 16} {country: 'belarus', countryCode: 'BY'} {country: 'norway', countryCode: 'NO', inEU: true, ageOfConsent: 13} # GDPR applies to EFTA {country: 'philippines', countryCode: 'PH'} {country: 'lithuania', countryCode: 'LT', inEU: true, ageOfConsent: 16} {country: 'argentina', countryCode: 'AR'} {country: 'malaysia', countryCode: 'MY', addressesIncludeAdministrativeRegion:true} {country: 'pakistan', countryCode: 'PK'} {country: 'serbia', countryCode: 'RS'} {country: 'greece', countryCode: 'GR', inEU: true, ageOfConsent: 15} {country: 'israel', countryCode: 'IL', inEU: true} {country: 'portugal', countryCode: 'PT', inEU: true, ageOfConsent: 13} {country: 'slovakia', countryCode: 'SK', inEU: true, ageOfConsent: 16} {country: 'ireland', countryCode: 'IE', inEU: true, ageOfConsent: 16} {country: 'switzerland', countryCode: 'CH', inEU: true, ageOfConsent: 16} # GDPR applies to EFTA {country: 'peru', countryCode: 'PE'} {country: 'bulgaria', countryCode: 'BG', inEU: true, ageOfConsent: 14} {country: 'venezuela', countryCode: 'VE'} {country: 'austria', countryCode: 'AT', inEU: true, ageOfConsent: 14} {country: 'croatia', countryCode: 'HR', inEU: true, ageOfConsent: 16} {country: 'saudia-arabia', countryCode: 'SA'} {country: 'chile', countryCode: 'CL'} {country: 'united-arab-emirates', countryCode: 'AE'} {country: 'kazakhstan', countryCode: 'KZ'} {country: 'estonia', countryCode: 'EE', inEU: true, ageOfConsent: 13} {country: 'iran', countryCode: 'IR'} {country: 'egypt', countryCode: 'EG'} {country: 'ecuador', countryCode: 'EC'} {country: 'slovenia', countryCode: 'SI', inEU: true, ageOfConsent: 15} {country: 'macedonia', countryCode: 'MK'} {country: 'cyprus', countryCode: 'CY', inEU: true, ageOfConsent: 14} {country: 'latvia', countryCode: 'LV', inEU: true, ageOfConsent: 13} {country: 'luxembourg', countryCode: 'LU', inEU: true, ageOfConsent: 16} {country: 'malta', countryCode: 'MT', inEU: true, ageOfConsent: 16} {country: 'lichtenstein', countryCode: 'LI', inEU: true} # GDPR applies to EFTA {country: 'iceland', countryCode: 'IS', inEU: true} # GDPR applies to EFTA ] inEU = (country) -> !!_.find(countries, (c) => c.country is slugify(country))?.inEU addressesIncludeAdministrativeRegion = (country) -> !!_.find(countries, (c) => c.country is slugify(country))?.addressesIncludeAdministrativeRegion ageOfConsent = (countryName, defaultIfUnknown=0) -> return defaultIfUnknown unless countryName country = _.find(countries, (c) => c.country is slugify(countryName)) return defaultIfUnknown unless country return country.ageOfConsent if country.ageOfConsent return 16 if country.inEU return defaultIfUnknown countryCodeToFlagEmoji = (code) -> return code unless code?.length is 2 (String.fromCodePoint(c.charCodeAt() + 0x1F1A5) for c in code.toUpperCase()).join('') countryCodeToName = (code) -> return code unless code?.length is 2 return code unless country = _.find countries, countryCode: code.toUpperCase() titleize country.country titleize = (s) -> # Turns things like 'dungeons-of-kithgard' into 'Dungeons of Kithgard' _.string.titleize(_.string.humanize(s)).replace(/ (and|or|but|nor|yet|so|for|a|an|the|in|to|of|at|by|up|for|off|on|with|from)(?= )/ig, (word) => word.toLowerCase()) campaignIDs = INTRO: '55b29efd1cd6abe8ce07db0d' courseIDs = INTRODUCTION_TO_COMPUTER_SCIENCE: '560f1a9f22961295f9427742' GAME_DEVELOPMENT_1: '5789587aad86a6efb573701e' WEB_DEVELOPMENT_1: '5789587aad86a6efb573701f' COMPUTER_SCIENCE_2: '5632661322961295f9428638' GAME_DEVELOPMENT_2: '57b621e7ad86a6efb5737e64' WEB_DEVELOPMENT_2: '5789587aad86a6efb5737020' COMPUTER_SCIENCE_3: '56462f935afde0c6fd30fc8c' GAME_DEVELOPMENT_3: '5a0df02b8f2391437740f74f' COMPUTER_SCIENCE_4: '56462f935afde0c6fd30fc8d' COMPUTER_SCIENCE_5: '569ed916efa72b0ced971447' COMPUTER_SCIENCE_6: '5817d673e85d1220db624ca4' CSCourseIDs = [ courseIDs.INTRODUCTION_TO_COMPUTER_SCIENCE courseIDs.COMPUTER_SCIENCE_2 courseIDs.COMPUTER_SCIENCE_3 courseIDs.COMPUTER_SCIENCE_4 courseIDs.COMPUTER_SCIENCE_5 courseIDs.COMPUTER_SCIENCE_6 ] orderedCourseIDs = [ courseIDs.INTRODUCTION_TO_COMPUTER_SCIENCE courseIDs.GAME_DEVELOPMENT_1 courseIDs.WEB_DEVELOPMENT_1 courseIDs.COMPUTER_SCIENCE_2 courseIDs.GAME_DEVELOPMENT_2 courseIDs.WEB_DEVELOPMENT_2 courseIDs.COMPUTER_SCIENCE_3 courseIDs.GAME_DEVELOPMENT_3 courseIDs.COMPUTER_SCIENCE_4 courseIDs.COMPUTER_SCIENCE_5 courseIDs.COMPUTER_SCIENCE_6 ] courseAcronyms = {} courseAcronyms[courseIDs.INTRODUCTION_TO_COMPUTER_SCIENCE] = 'CS1' courseAcronyms[courseIDs.GAME_DEVELOPMENT_1] = 'GD1' courseAcronyms[courseIDs.WEB_DEVELOPMENT_1] = 'WD1' courseAcronyms[courseIDs.COMPUTER_SCIENCE_2] = 'CS2' courseAcronyms[courseIDs.GAME_DEVELOPMENT_2] = 'GD2' courseAcronyms[courseIDs.WEB_DEVELOPMENT_2] = 'WD2' courseAcronyms[courseIDs.COMPUTER_SCIENCE_3] = 'CS3' courseAcronyms[courseIDs.GAME_DEVELOPMENT_3] = 'GD3' courseAcronyms[courseIDs.COMPUTER_SCIENCE_4] = 'CS4' courseAcronyms[courseIDs.COMPUTER_SCIENCE_5] = 'CS5' courseAcronyms[courseIDs.COMPUTER_SCIENCE_6] = 'CS6' courseLessonSlidesURLs = {} unless features?.china courseLessonSlidesURLs[courseIDs.INTRODUCTION_TO_COMPUTER_SCIENCE] = 'https://drive.google.com/drive/folders/1YU7LEZ6TLQzbAsSMw90nNJfvU7gDrcid?usp=sharing' courseLessonSlidesURLs[courseIDs.COMPUTER_SCIENCE_2] = 'https://drive.google.com/drive/folders/1x24P6ZY_MBOBoHvlikbDr7jvMPYVRVkJ?usp=sharing' courseLessonSlidesURLs[courseIDs.COMPUTER_SCIENCE_3] = 'https://drive.google.com/drive/folders/1hBl-h5Xvo5chYH4q9e6IEo42JozlrTG9?usp=sharing' courseLessonSlidesURLs[courseIDs.COMPUTER_SCIENCE_4] = 'https://drive.google.com/drive/folders/1tbuE4Xn0ahJ0xcF1-OaiPs9lHeIs9zqG?usp=sharing' courseLessonSlidesURLs[courseIDs.COMPUTER_SCIENCE_5] = 'https://drive.google.com/drive/folders/1ThxWFZjoXzU5INtMzlqKEn8xkgHhVnl4?usp=sharing' petThangIDs = [ '578d320d15e2501f00a585bd' # Wolf Pup '5744e3683af6bf590cd27371' # Cougar '5786a472a6c64135009238d3' # Raven '577d5d4dab818b210046b3bf' # Pugicorn '58c74b7c3d4a3d2900d43b7e' # Brown Rat '58c7614a62cc3a1f00442240' # Yetibab '58a262520b43652f00dad75e' # Phoenix '57869cf7bd31c14400834028' # Frog '578691f9bd31c1440083251d' # Polar Bear Cub '58a2712b0b43652f00dae5a4' # Blue Fox '58c737140ca7852e005deb8a' # Mimic '57586f0a22179b2800efda37' # Baby Griffin ] premiumContent = premiumHeroesCount: '12' totalHeroesCount: '16' premiumLevelsCount: '330' freeLevelsCount: '100' normalizeFunc = (func_thing, object) -> # func could be a string to a function in this class # or a function in its own right object ?= {} if _.isString(func_thing) func = object[func_thing] if not func console.error "Could not find method #{func_thing} in object", object return => null # always return a func, or Mediator will go boom func_thing = func return func_thing objectIdToDate = (objectID) -> new Date(parseInt(objectID.toString().slice(0,8), 16)*1000) hexToHSL = (hex) -> rgbToHsl(hexToR(hex), hexToG(hex), hexToB(hex)) hexToR = (h) -> parseInt (cutHex(h)).substring(0, 2), 16 hexToG = (h) -> parseInt (cutHex(h)).substring(2, 4), 16 hexToB = (h) -> parseInt (cutHex(h)).substring(4, 6), 16 cutHex = (h) -> (if (h.charAt(0) is '#') then h.substring(1, 7) else h) hslToHex = (hsl) -> '#' + (toHex(n) for n in hslToRgb(hsl...)).join('') toHex = (n) -> h = Math.floor(n).toString(16) h = '0'+h if h.length is 1 h pathToUrl = (path) -> base = location.protocol + '//' + location.hostname + (location.port && ":" + location.port) base + path extractPlayerCodeTag = (code) -> unwrappedDefaultCode = code.match(/<playercode>\n([\s\S]*)\n *<\/playercode>/)?[1] if unwrappedDefaultCode return stripIndentation(unwrappedDefaultCode) else return undefined stripIndentation = (code) -> codeLines = code.split('\n') indentation = _.min(_.filter(codeLines.map (line) -> line.match(/^\s*/)?[0]?.length)) strippedCode = (line.substr(indentation) for line in codeLines).join('\n') return strippedCode # @param {Object} say - the object containing an i18n property. # @param {string} target - the attribute that you want to access. # @returns {string} translated string if possible # Example usage: # `courseName = utils.i18n(course.attributes, 'name')` i18n = (say, target, language=me.get('preferredLanguage', true), fallback='en') -> generalResult = null fallBackResult = null fallForwardResult = null # If a general language isn't available, the first specific one will do. fallSidewaysResult = null # If a specific language isn't available, its sibling specific language will do. matches = (/\w+/gi).exec(language) generalName = matches[0] if matches for localeName, locale of say.i18n continue if localeName is '-' if target of locale result = locale[target] else continue return result if localeName is language generalResult = result if localeName is generalName fallBackResult = result if localeName is fallback fallForwardResult = result if localeName.indexOf(language) is 0 and not fallForwardResult? fallSidewaysResult = result if localeName.indexOf(generalName) is 0 and not fallSidewaysResult? return generalResult if generalResult? return fallForwardResult if fallForwardResult? return fallSidewaysResult if fallSidewaysResult? return fallBackResult if fallBackResult? return say[target] if target of say null getByPath = (target, path) -> throw new Error 'Expected an object to match a query against, instead got null' unless target pieces = path.split('.') obj = target for piece in pieces return undefined unless piece of obj obj = obj[piece] obj isID = (id) -> _.isString(id) and id.length is 24 and id.match(/[a-f0-9]/gi)?.length is 24 isIE = -> $?.browser?.msie ? false isRegionalSubscription = (name) -> /_basic_subscription/.test(name) isSmokeTestEmail = (email) -> /@PI:EMAIL:<EMAIL>END_PI/.test(email) or /smoketest/.test(email) round = _.curry (digits, n) -> n = +n.toFixed(digits) positify = (func) -> (params) -> (x) -> if x > 0 then func(params)(x) else 0 # f(x) = ax + b createLinearFunc = (params) -> (x) -> (params.a or 1) * x + (params.b or 0) # f(x) = ax² + bx + c createQuadraticFunc = (params) -> (x) -> (params.a or 1) * x * x + (params.b or 1) * x + (params.c or 0) # f(x) = a log(b (x + c)) + d createLogFunc = (params) -> (x) -> if x > 0 then (params.a or 1) * Math.log((params.b or 1) * (x + (params.c or 0))) + (params.d or 0) else 0 # f(x) = ax^b + c createPowFunc = (params) -> (x) -> (params.a or 1) * Math.pow(x, params.b or 1) + (params.c or 0) functionCreators = linear: positify(createLinearFunc) quadratic: positify(createQuadraticFunc) logarithmic: positify(createLogFunc) pow: positify(createPowFunc) # Call done with true to satisfy the 'until' goal and stop repeating func keepDoingUntil = (func, wait=100, totalWait=5000) -> waitSoFar = 0 (done = (success) -> if (waitSoFar += wait) <= totalWait and not success _.delay (-> func done), wait) false grayscale = (imageData) -> d = imageData.data for i in [0..d.length] by 4 r = d[i] g = d[i+1] b = d[i+2] v = 0.2126*r + 0.7152*g + 0.0722*b d[i] = d[i+1] = d[i+2] = v imageData # Deep compares l with r, with the exception that undefined values are considered equal to missing values # Very practical for comparing Mongoose documents where undefined is not allowed, instead fields get deleted kindaEqual = compare = (l, r) -> if _.isObject(l) and _.isObject(r) for key in _.union Object.keys(l), Object.keys(r) return false unless compare l[key], r[key] return true else if l is r return true else return false # Return UTC string "YYYYMMDD" for today + offset getUTCDay = (offset=0) -> day = new Date() day.setDate(day.getUTCDate() + offset) partYear = day.getUTCFullYear() partMonth = (day.getUTCMonth() + 1) partMonth = "0" + partMonth if partMonth < 10 partDay = day.getUTCDate() partDay = "0" + partDay if partDay < 10 "#{partYear}#{partMonth}#{partDay}" # Fast, basic way to replace text in an element when you don't need much. # http://stackoverflow.com/a/4962398/540620 if document?.createElement dummy = document.createElement 'div' dummy.innerHTML = 'text' TEXT = if dummy.textContent is 'text' then 'textContent' else 'innerText' replaceText = (elems, text) -> elem[TEXT] = text for elem in elems null # Add a stylesheet rule # http://stackoverflow.com/questions/524696/how-to-create-a-style-tag-with-javascript/26230472#26230472 # Don't use wantonly, or we'll have to implement a simple mechanism for clearing out old rules. if document?.createElement injectCSS = ((doc) -> # wrapper for all injected styles and temp el to create them wrap = doc.createElement("div") temp = doc.createElement("div") # rules like "a {color: red}" etc. return (cssRules) -> # append wrapper to the body on the first call unless wrap.id wrap.id = "injected-css" wrap.style.display = "none" doc.body.appendChild wrap # <br> for IE: http://goo.gl/vLY4x7 temp.innerHTML = "<br><style>" + cssRules + "</style>" wrap.appendChild temp.children[1] return )(document) # So that we can stub out userAgent in tests userAgent = -> window.navigator.userAgent getDocumentSearchString = -> # moved to a separate function so it can be mocked for testing return document.location.search getQueryVariables = -> query = module.exports.getDocumentSearchString().substring(1) # use module.exports so spy is used in testing pairs = (pair.split('=') for pair in query.split '&') variables = {} for [key, value] in pairs variables[key] = {'true': true, 'false': false}[value] ? decodeURIComponent(value) return variables getQueryVariable = (param, defaultValue) -> variables = getQueryVariables() return variables[param] ? defaultValue getSponsoredSubsAmount = (price=999, subCount=0, personalSub=false) -> # 1 100% # 2-11 80% # 12+ 60% # TODO: make this less confusing return 0 unless subCount > 0 offset = if personalSub then 1 else 0 if subCount <= 1 - offset price else if subCount <= 11 - offset Math.round((1 - offset) * price + (subCount - 1 + offset) * price * 0.8) else Math.round((1 - offset) * price + 10 * price * 0.8 + (subCount - 11 + offset) * price * 0.6) getCourseBundlePrice = (coursePrices, seats=20) -> totalPricePerSeat = coursePrices.reduce ((a, b) -> a + b), 0 if coursePrices.length > 2 pricePerSeat = Math.round(totalPricePerSeat / 2.0) else pricePerSeat = parseInt(totalPricePerSeat) seats * pricePerSeat getCoursePraise = -> praise = [ { quote: "The kids love it." source: "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PIthlos Leadership Academy" }, { quote: "My students have been using the site for a couple of weeks and they love it." source: "PI:NAME:<NAME>END_PI, Computer Applications Teacher, School Technology Coordinator, Eastside Middle School" }, { quote: "Thanks for the captivating site. My eighth graders love it." source: "PI:NAME:<NAME>END_PI, Ansbach Middle/High School" }, { quote: "My students have started working on CodeCombat and love it! I love that they are learning coding and problem solving skills without them even knowing it!!" source: "PI:NAME:<NAME>END_PI, Special Education Teacher, Webb City School District" }, { quote: "I recently introduced Code Combat to a few of my fifth graders and they are loving it!" source: "PI:NAME:<NAME>END_PI, Fifth Grade Teacher, Four Peaks Elementary School" }, { quote: "Overall I think it's a fantastic service. Variables, arrays, loops, all covered in very fun and imaginative ways. Every kid who has tried it is a fan." source: "PI:NAME:<NAME>END_PI, Technology Teacher" }, { quote: "I love what you have created. The kids are so engaged." source: "PI:NAME:<NAME>END_PI, 4KS Academy" }, { quote: "My students love the website and I hope on having content structured around it in the near future." source: "PI:NAME:<NAME>END_PI, Science Teacher, Clearwater Central Catholic High School" } ] praise[_.random(0, praise.length - 1)] getPrepaidCodeAmount = (price=0, users=0, months=0) -> return 0 unless users > 0 and months > 0 total = price * users * months total formatDollarValue = (dollars) -> '$' + (parseFloat(dollars).toFixed(2)) startsWithVowel = (s) -> s[0] in 'aeiouAEIOU' filterMarkdownCodeLanguages = (text, language) -> return '' unless text currentLanguage = language or me.get('aceConfig')?.language or 'python' excludedLanguages = _.without ['javascript', 'python', 'coffeescript', 'lua', 'java', 'cpp', 'html'], if currentLanguage == 'cpp' then 'javascript' else currentLanguage # Exclude language-specific code blocks like ```python (... code ...)`` # ` for each non-target language. codeBlockExclusionRegex = new RegExp "```(#{excludedLanguages.join('|')})\n[^`]+```\n?", 'gm' # Exclude language-specific images like ![python - image description](image url) for each non-target language. imageExclusionRegex = new RegExp "!\\[(#{excludedLanguages.join('|')}) - .+?\\]\\(.+?\\)\n?", 'gm' text = text.replace(codeBlockExclusionRegex, '').replace(imageExclusionRegex, '') commonLanguageReplacements = python: [ ['true', 'True'], ['false', 'False'], ['null', 'None'], ['object', 'dictionary'], ['Object', 'Dictionary'], ['array', 'list'], ['Array', 'List'], ] lua: [ ['null', 'nil'], ['object', 'table'], ['Object', 'Table'], ['array', 'table'], ['Array', 'Table'], ] for [from, to] in commonLanguageReplacements[currentLanguage] ? [] # Convert JS-specific keywords and types to Python ones, if in simple `code` tags. # This won't cover it when it's not in an inline code tag by itself or when it's not in English. text = text.replace ///`#{from}`///g, "`#{to}`" # Now change "An `dictionary`" to "A `dictionary`", etc. if startsWithVowel(from) and not startsWithVowel(to) text = text.replace ///(\ a|A)n(\ `#{to}`)///g, "$1$2" if not startsWithVowel(from) and startsWithVowel(to) text = text.replace ///(\ a|A)(\ `#{to}`)///g, "$1n$2" if currentLanguage == 'cpp' jsRegex = new RegExp "```javascript\n([^`]+)```", 'gm' text = text.replace jsRegex, (a, l) => """```cpp #{@translatejs2cpp a[13..a.length-4], false} ```""" return text capitalLanguages = 'javascript': 'JavaScript' 'coffeescript': 'CoffeeScript' 'python': 'Python' 'java': 'Java' 'cpp': 'C++' 'lua': 'Lua' 'html': 'HTML' createLevelNumberMap = (levels) -> levelNumberMap = {} practiceLevelTotalCount = 0 practiceLevelCurrentCount = 0 for level, i in levels levelNumber = i - practiceLevelTotalCount + 1 if level.practice levelNumber = i - practiceLevelTotalCount + String.fromCharCode('a'.charCodeAt(0) + practiceLevelCurrentCount) practiceLevelTotalCount++ practiceLevelCurrentCount++ else if level.assessment practiceLevelTotalCount++ practiceLevelCurrentCount++ levelNumber = if level.assessment is 'cumulative' then $.t('play_level.combo_challenge') else $.t('play_level.concept_challenge') else practiceLevelCurrentCount = 0 levelNumberMap[level.key] = levelNumber levelNumberMap findNextLevel = (levels, currentIndex, needsPractice) -> # Find next available incomplete level, depending on whether practice is needed # levels = [{practice: true/false, complete: true/false, assessment: true/false, locked: true/false}] # Skip over assessment levels # return -1 if at or beyond locked level return -1 for i in [0..currentIndex] when levels[i].locked index = currentIndex index++ if needsPractice if levels[currentIndex].practice or index < levels.length and levels[index].practice # Needs practice, current level is practice or next is practice; return the next incomplete practice-or-normal level # May leave earlier practice levels incomplete and reach end of course while index < levels.length and (levels[index].complete or levels[index].assessment) return -1 if levels[index].locked index++ else # Needs practice, current level is required, next level is required or assessment; return the first incomplete level of previous practice chain index-- index-- while index >= 0 and not levels[index].practice if index >= 0 index-- while index >= 0 and levels[index].practice if index >= 0 index++ index++ while index < levels.length and levels[index].practice and levels[index].complete if levels[index].practice and not levels[index].complete return index # Last set of practice levels is complete; return the next incomplete normal level instead. index = currentIndex + 1 while index < levels.length and (levels[index].complete or levels[index].assessment) return -1 if levels[index].locked index++ else # No practice needed; return the next required incomplete level while index < levels.length and (levels[index].practice or levels[index].complete or levels[index].assessment) return -1 if levels[index].locked index++ index findNextAssessmentForLevel = (levels, currentIndex, needsPractice) -> # Find assessment level immediately after current level (and its practice levels) # Only return assessment if it's the next level # Skip over practice levels unless practice neeeded # levels = [{practice: true/false, complete: true/false, assessment: true/false, locked: true/false}] # eg: l*,p,p,a*,a',l,... # given index l*, return index a* # given index a*, return index a' index = currentIndex index++ while index < levels.length if levels[index].practice return -1 if needsPractice and not levels[index].complete index++ # It's a practice level but do not need practice, keep looking else if levels[index].assessment return -1 if levels[index].complete return index else if levels[index].complete # It's completed, keep looking index++ else # we got to a normal level; we didn't find an assessment for the given level. return -1 return -1 # we got to the end of the list and found nothing needsPractice = (playtime=0, threshold=5) -> playtime / 60 > threshold sortCourses = (courses) -> _.sortBy courses, (course) -> # ._id can be from classroom.courses, otherwise it's probably .id index = orderedCourseIDs.indexOf(course.id ? course._id) index = 9001 if index is -1 index sortCoursesByAcronyms = (courses) -> orderedCourseAcronyms = _.sortBy(courseAcronyms) _.sortBy courses, (course) -> # ._id can be from classroom.courses, otherwise it's probably .id index = orderedCourseAcronyms.indexOf(courseAcronyms[course.id ? course._id]) index = 9001 if index is -1 index usStateCodes = # https://github.com/mdzhang/us-state-codes # generated by js2coffee 2.2.0 (-> stateNamesByCode = 'AL': 'Alabama' 'AK': 'Alaska' 'AZ': 'Arizona' 'AR': 'Arkansas' 'CA': 'California' 'CO': 'Colorado' 'CT': 'Connecticut' 'DE': 'Delaware' 'DC': 'District of Columbia' 'FL': 'Florida' 'GA': 'Georgia' 'HI': 'Hawaii' 'ID': 'Idaho' 'IL': 'Illinois' 'IN': 'Indiana' 'IA': 'Iowa' 'KS': 'Kansas' 'KY': 'Kentucky' 'LA': 'Louisiana' 'ME': 'Maine' 'MD': 'Maryland' 'MA': 'Massachusetts' 'MI': 'Michigan' 'MN': 'Minnesota' 'MS': 'Mississippi' 'MO': 'Missouri' 'MT': 'Montana' 'NE': 'Nebraska' 'NV': 'Nevada' 'NH': 'New Hampshire' 'NJ': 'New Jersey' 'NM': 'New Mexico' 'NY': 'New York' 'NC': 'North Carolina' 'ND': 'North Dakota' 'OH': 'Ohio' 'OK': 'Oklahoma' 'OR': 'Oregon' 'PA': 'Pennsylvania' 'RI': 'Rhode Island' 'SC': 'South Carolina' 'SD': 'South Dakota' 'TN': 'Tennessee' 'TX': 'Texas' 'UT': 'Utah' 'VT': 'Vermont' 'VA': 'Virginia' 'WA': 'Washington' 'WV': 'West Virginia' 'WI': 'Wisconsin' 'WY': 'Wyoming' stateCodesByName = _.invert(stateNamesByCode) # normalizes case and removes invalid characters # returns null if can't find sanitized code in the state map sanitizeStateCode = (code) -> code = if _.isString(code) then code.trim().toUpperCase().replace(/[^A-Z]/g, '') else null if stateNamesByCode[code] then code else null # returns a valid state name else null getStateNameByStateCode = (code) -> stateNamesByCode[sanitizeStateCode(code)] or null # normalizes case and removes invalid characters # returns null if can't find sanitized name in the state map sanitizeStateName = (name) -> if !_.isString(name) return null # bad whitespace remains bad whitespace e.g. "O hi o" is not valid name = name.trim().toLowerCase().replace(/[^a-z\s]/g, '').replace(/\s+/g, ' ') tokens = name.split(/\s+/) tokens = _.map(tokens, (token) -> token.charAt(0).toUpperCase() + token.slice(1) ) # account for District of Columbia if tokens.length > 2 tokens[1] = tokens[1].toLowerCase() name = tokens.join(' ') if stateCodesByName[name] then name else null # returns a valid state code else null getStateCodeByStateName = (name) -> stateCodesByName[sanitizeStateName(name)] or null return { sanitizeStateCode: sanitizeStateCode getStateNameByStateCode: getStateNameByStateCode sanitizeStateName: sanitizeStateName getStateCodeByStateName: getStateCodeByStateName } )() emailRegex = /[A-z0-9._%+-]+@[A-z0-9.-]+\.[A-z]{2,63}/ isValidEmail = (email) -> emailRegex.test(email?.trim().toLowerCase()) formatStudentLicenseStatusDate = (status, date) -> string = switch status when 'not-enrolled' then $.i18n.t('teacher.status_not_enrolled') when 'enrolled' then (if date then $.i18n.t('teacher.status_enrolled') else '-') when 'expired' then $.i18n.t('teacher.status_expired') string.replace('{{date}}', date or 'Never') getApiClientIdFromEmail = (email) -> ifPI:EMAIL:<EMAIL>END_PI /PI:EMAIL:<EMAIL>END_PI$/i.test(email) # hard coded for code ninjas since a lot of their users do not have clientCreator set clientID = '57fff652b0783842003fed00' return clientID # hard-coded 3 CS1 levels with concept video details # TODO: move them to database if more such levels videoLevels = { # gems in the deep "54173c90844506ae0195a0b4": { i18name: 'basic_syntax', url: "https://player.vimeo.com/video/310626758", cn_url: "https://assets.koudashijie.com/videos/%E5%AF%BC%E8%AF%BE01-%E5%9F%BA%E6%9C%AC%E8%AF%AD%E6%B3%95-Codecombat%20Instruction%20for%20Teachers.mp4", title: "Basic Syntax", original: "54173c90844506ae0195a0b4", thumbnail_locked: "/images/level/videos/basic_syntax_locked.png", thumbnail_unlocked: "/images/level/videos/basic_syntax_unlocked.png" }, # fire dancing "55ca293b9bc1892c835b0136": { i18name: 'while_loops', url: "https://player.vimeo.com/video/310626741", cn_url: "https://assets.koudashijie.com/videos/%E5%AF%BC%E8%AF%BE03-CodeCombat%E6%95%99%E5%AD%A6%E5%AF%BC%E8%AF%BE-CS1-%E5%BE%AA%E7%8E%AFlogo.mp4", title: "While Loops", original: "55ca293b9bc1892c835b0136" thumbnail_locked: "/images/level/videos/while_loops_locked.png", thumbnail_unlocked: "/images/level/videos/while_loops_unlocked.png" } # known enemy "5452adea57e83800009730ee": { i18name: 'variables', url: "https://player.vimeo.com/video/310626807", cn_url: "https://assets.koudashijie.com/videos/%E5%AF%BC%E8%AF%BE02-%E5%8F%98%E9%87%8F-CodeCombat-CS1-%E5%8F%98%E9%87%8Flogo.mp4", title: "Variables", original: "5452adea57e83800009730ee" thumbnail_locked: "/images/level/videos/variables_locked.png", thumbnail_unlocked: "/images/level/videos/variables_unlocked.png" } } yearsSinceMonth = (start) -> return undefined unless start # Should probably review this logic, written quickly and haven't tested any edge cases if _.isString start return undefined unless /\d{4}-\d{2}(-\d{2})?/.test start if start.length is 7 start = start + '-28' # Assume near the end of the month, don't let timezones mess it up, skew younger in interpretation start = new Date(start) return undefined unless _.isDate start now = new Date() now.getFullYear() - start.getFullYear() + (now.getMonth() - start.getMonth()) / 12 # Keep in sync with the copy in background-processor ageBrackets = [ {slug: '0-11', max: 11.33} {slug: '11-14', max: 14.33} {slug: '14-18', max: 18.99} {slug: 'open', max: 9001} ] ageToBracket = (age) -> # Convert years to an age bracket return 'open' unless age for bracket in ageBrackets if age < bracket.max return bracket.slug return 'open' bracketToAge = (slug) -> for i in [0...ageBrackets.length] if ageBrackets[i].slug == slug lowerBound = if i == 0 then 0 else ageBrackets[i-1].max higherBound = ageBrackets[i].max return { $gt: lowerBound, $lte: higherBound } CODECOMBAT = 'codecombat' CODECOMBAT_CHINA = 'koudashijie' OZARIA = 'ozaria' OZARIA_CHINA = 'aojiarui' isOldBrowser = () -> if features.china and $.browser return true if not ($.browser.webkit or $.browser.mozilla or $.browser.msedge) majorVersion = $.browser.versionNumber return true if $.browser.mozilla && majorVersion < 25 return true if $.browser.chrome && majorVersion < 72 # forbid some chinese browser return true if $.browser.safari && majorVersion < 6 # 6 might have problems with Aether, or maybe just old minors of 6: https://errorception.com/projects/51a79585ee207206390002a2/errors/547a202e1ead63ba4e4ac9fd return false isCodeCombat = true isOzaria = false arenas = [ {slug: 'blazing-battle' , type: 'regular', start: new Date(2021, 0, 1), end: new Date(2021, 4, 1), levelOriginal: '5fca06dc8b4da8002889dbf1', image: '/file/db/level/5fca06dc8b4da8002889dbf1/Blazing Battle Final cut.jpg'} {slug: 'infinite-inferno' , type: 'championship', start: new Date(2021, 3, 1), end: new Date(2021, 4, 1), levelOriginal: '602cdc204ef0480075fbd954', image: '/file/db/level/602cdc204ef0480075fbd954/InfiniteInferno_Banner_Final.jpg'} {slug: 'mages-might' , type: 'regular', start: new Date(2021, 4, 1), end: new Date(2021, 8, 1), levelOriginal: '6066f956ddfd6f003d1ed6bb', image: '/file/db/level/6066f956ddfd6f003d1ed6bb/Mages\'%20Might%20Banner.jpg'} {slug: 'sorcerers' , type: 'championship', start: new Date(2021, 7, 1), end: new Date(2021, 8, 1), levelOriginal: '609a6ad2e1eb34001a84e7af'} {slug: 'giants-gate' , type: 'regular', start: new Date(2021, 8, 1), end: new Date(2022, 0, 1)} {slug: 'colossus' , type: 'championship', start: new Date(2021, 11, 1), end: new Date(2022, 0, 1)} ] activeArenas = -> daysActiveAfterEnd = regular: 7, championship: 14 (_.clone(a) for a in arenas when a.start <= new Date() < a.end.getTime() + daysActiveAfterEnd[a.type] * 86400 * 1000) module.exports = { activeArenas addressesIncludeAdministrativeRegion ageBrackets ageOfConsent ageToBracket arenas bracketToAge campaignIDs capitalLanguages clone combineAncestralObject countries countryCodeToFlagEmoji countryCodeToName courseAcronyms courseIDs courseLessonSlidesURLs CSCourseIDs createLevelNumberMap extractPlayerCodeTag filterMarkdownCodeLanguages findNextAssessmentForLevel findNextLevel formatDollarValue formatStudentLicenseStatusDate functionCreators getApiClientIdFromEmail getByPath getCourseBundlePrice getCoursePraise getDocumentSearchString getPrepaidCodeAmount getQueryVariable getQueryVariables getSponsoredSubsAmount getUTCDay grayscale hexToHSL hslToHex i18n inEU injectCSS isID isIE isRegionalSubscription isSmokeTestEmail isValidEmail keepDoingUntil kindaEqual needsPractice normalizeFunc objectIdToDate orderedCourseIDs pathToUrl petThangIDs premiumContent replaceText round sortCourses sortCoursesByAcronyms stripIndentation titleize translatejs2cpp usStateCodes userAgent videoLevels yearsSinceMonth CODECOMBAT OZARIA CODECOMBAT_CHINA OZARIA_CHINA isOldBrowser isCodeCombat isOzaria titleize }
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9989874958992004, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-net-listen-exclusive-random-ports.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. noop = -> common = require("../common") assert = require("assert") cluster = require("cluster") net = require("net") if cluster.isMaster worker1 = cluster.fork() worker1.on "message", (port1) -> assert.equal port1, port1 | 0, "first worker could not listen" worker2 = cluster.fork() worker2.on "message", (port2) -> assert.equal port2, port2 | 0, "second worker could not listen" assert.notEqual port1, port2, "ports should not be equal" worker1.kill() worker2.kill() return return else server = net.createServer(noop) server.on "error", (err) -> process.send err.code return server.listen port: 0 exclusive: true , -> process.send server.address().port return
148799
# 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. noop = -> common = require("../common") assert = require("assert") cluster = require("cluster") net = require("net") if cluster.isMaster worker1 = cluster.fork() worker1.on "message", (port1) -> assert.equal port1, port1 | 0, "first worker could not listen" worker2 = cluster.fork() worker2.on "message", (port2) -> assert.equal port2, port2 | 0, "second worker could not listen" assert.notEqual port1, port2, "ports should not be equal" worker1.kill() worker2.kill() return return else server = net.createServer(noop) server.on "error", (err) -> process.send err.code return server.listen port: 0 exclusive: true , -> process.send server.address().port return
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. noop = -> common = require("../common") assert = require("assert") cluster = require("cluster") net = require("net") if cluster.isMaster worker1 = cluster.fork() worker1.on "message", (port1) -> assert.equal port1, port1 | 0, "first worker could not listen" worker2 = cluster.fork() worker2.on "message", (port2) -> assert.equal port2, port2 | 0, "second worker could not listen" assert.notEqual port1, port2, "ports should not be equal" worker1.kill() worker2.kill() return return else server = net.createServer(noop) server.on "error", (err) -> process.send err.code return server.listen port: 0 exclusive: true , -> process.send server.address().port return
[ { "context": "\n\t\t@adding_user_id = \"adding-user-id\"\n\t\t@email = \"joe@sharelatex.com\"\n\t\t@callback = sinon.stub()\n\t\n\tdescribe \"getMembe", "end": 1029, "score": 0.999889075756073, "start": 1011, "tag": "EMAIL", "value": "joe@sharelatex.com" }, { "context": "\n\t\t\t\t@ContactManager.addContact\n\t\t\t\t\t.calledWith(@adding_user_id, @user_id)\n\t\t\t\t\t.should.equal true\n\t\t\t\t\t\n\t\tdescri", "end": 8634, "score": 0.9066661596298218, "start": 8620, "tag": "USERNAME", "value": "adding_user_id" }, { "context": "ger.addContact\n\t\t\t\t\t.calledWith(@adding_user_id, @user_id)\n\t\t\t\t\t.should.equal true\n\t\t\t\t\t\n\t\tdescribe \"as r", "end": 8642, "score": 0.6827938556671143, "start": 8637, "tag": "USERNAME", "value": "user_" }, { "context": "\n\t\t\tbeforeEach ->\n\t\t\t\t@project.collaberator_refs = [@user_id]\n\t\t\t\t@CollaboratorHandler.addUserIdToProject @pro", "end": 9616, "score": 0.9660801291465759, "start": 9607, "tag": "USERNAME", "value": "[@user_id" }, { "context": "oldingAccount = sinon.stub().callsArgWith(1, null, @user = {_id: @user_id})\n\t\t\t@CollaboratorHandler.ad", "end": 9951, "score": 0.6911758184432983, "start": 9951, "tag": "USERNAME", "value": "" }, { "context": "= sinon.stub().callsArgWith(1, null, @user = {_id: @user_id})\n\t\t\t@CollaboratorHandler.addUserIdToProject = si", "end": 9974, "score": 0.9627435207366943, "start": 9966, "tag": "USERNAME", "value": "@user_id" }, { "context": "er.addEmailToProject @project_id, @adding_user_id, (@email = \"Joe@example.com\"), (@privilegeLevel = \"readAnd", "end": 10181, "score": 0.6774107217788696, "start": 10174, "tag": "USERNAME", "value": "(@email" }, { "context": "oProject @project_id, @adding_user_id, (@email = \"Joe@example.com\"), (@privilegeLevel = \"readAndWrite\"), @callback\n", "end": 10200, "score": 0.9998941421508789, "start": 10185, "tag": "EMAIL", "value": "Joe@example.com" }, { "context": "orHandler.getProjectsUserIsCollaboratorOf.withArgs(@user_id, { _id: 1 }).yields(\n\t\t\t\tnull,\n\t\t\t\t[ { _id: \"read", "end": 11380, "score": 0.9626550674438477, "start": 11372, "tag": "USERNAME", "value": "@user_id" }, { "context": "\t\t\t@CollaboratorHandler.removeUserFromAllProjets @user_id, done\n\t\t\n\t\tit \"should remove the user from eac", "end": 11674, "score": 0.5526297092437744, "start": 11670, "tag": "USERNAME", "value": "user" }, { "context": "removeUserFromProject\n\t\t\t\t\t.calledWith(project_id, @user_id)\n\t\t\t\t\t.should.equal true", "end": 11913, "score": 0.882153332233429, "start": 11907, "tag": "USERNAME", "value": "@user_" } ]
test/UnitTests/coffee/Collaborators/CollaboratorsHandlerTests.coffee
bowlofstew/web-sharelatex
0
should = require('chai').should() SandboxedModule = require('sandboxed-module') assert = require('assert') path = require('path') sinon = require('sinon') modulePath = path.join __dirname, "../../../../app/js/Features/Collaborators/CollaboratorsHandler" expect = require("chai").expect Errors = require "../../../../app/js/Features/Errors/Errors.js" describe "CollaboratorsHandler", -> beforeEach -> @CollaboratorHandler = SandboxedModule.require modulePath, requires: "logger-sharelatex": @logger = { log: sinon.stub(), err: sinon.stub() } '../User/UserCreator': @UserCreator = {} '../User/UserGetter': @UserGetter = {} "../Contacts/ContactManager": @ContactManager = {} "../../models/Project": Project: @Project = {} "../Project/ProjectEntityHandler": @ProjectEntityHandler = {} "./CollaboratorsEmailHandler": @CollaboratorsEmailHandler = {} "../Errors/Errors": Errors @project_id = "mock-project-id" @user_id = "mock-user-id" @adding_user_id = "adding-user-id" @email = "joe@sharelatex.com" @callback = sinon.stub() describe "getMemberIdsWithPrivilegeLevels", -> describe "with project", -> beforeEach -> @Project.findOne = sinon.stub() @Project.findOne.withArgs({_id: @project_id}, {owner_ref: 1, collaberator_refs: 1, readOnly_refs: 1}).yields(null, @project = { owner_ref: [ "owner-ref" ] readOnly_refs: [ "read-only-ref-1", "read-only-ref-2" ] collaberator_refs: [ "read-write-ref-1", "read-write-ref-2" ] }) @CollaboratorHandler.getMemberIdsWithPrivilegeLevels @project_id, @callback it "should return an array of member ids with their privilege levels", -> @callback .calledWith(null, [ { id: "owner-ref", privilegeLevel: "owner" } { id: "read-only-ref-1", privilegeLevel: "readOnly" } { id: "read-only-ref-2", privilegeLevel: "readOnly" } { id: "read-write-ref-1", privilegeLevel: "readAndWrite" } { id: "read-write-ref-2", privilegeLevel: "readAndWrite" } ]) .should.equal true describe "with a missing project", -> beforeEach -> @Project.findOne = sinon.stub().yields(null, null) it "should return a NotFoundError", (done) -> @CollaboratorHandler.getMemberIdsWithPrivilegeLevels @project_id, (error) -> error.should.be.instanceof Errors.NotFoundError done() describe "getMemberIds", -> beforeEach -> @CollaboratorHandler.getMemberIdsWithPrivilegeLevels = sinon.stub() @CollaboratorHandler.getMemberIdsWithPrivilegeLevels .withArgs(@project_id) .yields(null, [{id: "member-id-1"}, {id: "member-id-2"}]) @CollaboratorHandler.getMemberIds @project_id, @callback it "should return the ids", -> @callback .calledWith(null, ["member-id-1", "member-id-2"]) .should.equal true describe "getMembersWithPrivilegeLevels", -> beforeEach -> @CollaboratorHandler.getMemberIdsWithPrivilegeLevels = sinon.stub() @CollaboratorHandler.getMemberIdsWithPrivilegeLevels.withArgs(@project_id).yields(null, [ { id: "read-only-ref-1", privilegeLevel: "readOnly" } { id: "read-only-ref-2", privilegeLevel: "readOnly" } { id: "read-write-ref-1", privilegeLevel: "readAndWrite" } { id: "read-write-ref-2", privilegeLevel: "readAndWrite" } { id: "doesnt-exist", privilegeLevel: "readAndWrite" } ]) @UserGetter.getUser = sinon.stub() @UserGetter.getUser.withArgs("read-only-ref-1").yields(null, { _id: "read-only-ref-1" }) @UserGetter.getUser.withArgs("read-only-ref-2").yields(null, { _id: "read-only-ref-2" }) @UserGetter.getUser.withArgs("read-write-ref-1").yields(null, { _id: "read-write-ref-1" }) @UserGetter.getUser.withArgs("read-write-ref-2").yields(null, { _id: "read-write-ref-2" }) @UserGetter.getUser.withArgs("doesnt-exist").yields(null, null) @CollaboratorHandler.getMembersWithPrivilegeLevels @project_id, @callback it "should return an array of members with their privilege levels", -> @callback .calledWith(null, [ { user: { _id: "read-only-ref-1" }, privilegeLevel: "readOnly" } { user: { _id: "read-only-ref-2" }, privilegeLevel: "readOnly" } { user: { _id: "read-write-ref-1" }, privilegeLevel: "readAndWrite" } { user: { _id: "read-write-ref-2" }, privilegeLevel: "readAndWrite" } ]) .should.equal true describe "getMemberIdPrivilegeLevel", -> beforeEach -> @CollaboratorHandler.getMemberIdsWithPrivilegeLevels = sinon.stub() @CollaboratorHandler.getMemberIdsWithPrivilegeLevels .withArgs(@project_id) .yields(null, [ {id: "member-id-1", privilegeLevel: "readAndWrite"} {id: "member-id-2", privilegeLevel: "readOnly"} ]) it "should return the privilege level if it exists", (done) -> @CollaboratorHandler.getMemberIdPrivilegeLevel "member-id-2", @project_id, (error, level) -> expect(level).to.equal "readOnly" done() it "should return false if the member has no privilege level", (done) -> @CollaboratorHandler.getMemberIdPrivilegeLevel "member-id-3", @project_id, (error, level) -> expect(level).to.equal false done() describe "isUserMemberOfProject", -> beforeEach -> @CollaboratorHandler.getMemberIdsWithPrivilegeLevels = sinon.stub() describe "when user is a member of the project", -> beforeEach -> @CollaboratorHandler.getMemberIdsWithPrivilegeLevels.withArgs(@project_id).yields(null, [ { id: "not-the-user", privilegeLevel: "readOnly" } { id: @user_id, privilegeLevel: "readAndWrite" } ]) @CollaboratorHandler.isUserMemberOfProject @user_id, @project_id, @callback it "should return true and the privilegeLevel", -> @callback .calledWith(null, true, "readAndWrite") .should.equal true describe "when user is not a member of the project", -> beforeEach -> @CollaboratorHandler.getMemberIdsWithPrivilegeLevels.withArgs(@project_id).yields(null, [ { id: "not-the-user", privilegeLevel: "readOnly" } ]) @CollaboratorHandler.isUserMemberOfProject @user_id, @project_id, @callback it "should return false", -> @callback .calledWith(null, false, null) .should.equal true describe "getProjectsUserIsCollaboratorOf", -> beforeEach -> @fields = "mock fields" @Project.find = sinon.stub() @Project.find.withArgs({collaberator_refs:@user_id}, @fields).yields(null, ["mock-read-write-project-1", "mock-read-write-project-2"]) @Project.find.withArgs({readOnly_refs:@user_id}, @fields).yields(null, ["mock-read-only-project-1", "mock-read-only-project-2"]) @CollaboratorHandler.getProjectsUserIsCollaboratorOf @user_id, @fields, @callback it "should call the callback with the projects", -> @callback .calledWith(null, ["mock-read-write-project-1", "mock-read-write-project-2"], ["mock-read-only-project-1", "mock-read-only-project-2"]) .should.equal true describe "removeUserFromProject", -> beforeEach -> @Project.update = sinon.stub().callsArg(2) @CollaboratorHandler.removeUserFromProject @project_id, @user_id, @callback it "should remove the user from mongo", -> @Project.update .calledWith({ _id: @project_id }, { "$pull":{collaberator_refs:@user_id, readOnly_refs:@user_id} }) .should.equal true describe "addUserToProject", -> beforeEach -> @Project.update = sinon.stub().callsArg(2) @Project.findOne = sinon.stub().callsArgWith(2, null, @project = {}) @ProjectEntityHandler.flushProjectToThirdPartyDataStore = sinon.stub().callsArg(1) @CollaboratorHandler.addEmailToProject = sinon.stub().callsArgWith(4, null, @user_id) @UserGetter.getUser = sinon.stub().callsArgWith(2, null, @user = { _id: @user_id, email: @email }) @CollaboratorsEmailHandler.notifyUserOfProjectShare = sinon.stub() @ContactManager.addContact = sinon.stub() describe "as readOnly", -> beforeEach -> @CollaboratorHandler.addUserIdToProject @project_id, @adding_user_id, @user_id, "readOnly", @callback it "should add the user to the readOnly_refs", -> @Project.update .calledWith({ _id: @project_id }, { "$addToSet":{ readOnly_refs: @user_id } }) .should.equal true it "should flush the project to the TPDS", -> @ProjectEntityHandler.flushProjectToThirdPartyDataStore .calledWith(@project_id) .should.equal true it "should send an email to the shared-with user", -> @CollaboratorsEmailHandler.notifyUserOfProjectShare .calledWith(@project_id, @email) .should.equal true it "should add the user as a contact for the adding user", -> @ContactManager.addContact .calledWith(@adding_user_id, @user_id) .should.equal true describe "as readAndWrite", -> beforeEach -> @CollaboratorHandler.addUserIdToProject @project_id, @adding_user_id, @user_id, "readAndWrite", @callback it "should add the user to the collaberator_refs", -> @Project.update .calledWith({ _id: @project_id }, { "$addToSet":{ collaberator_refs: @user_id } }) .should.equal true it "should flush the project to the TPDS", -> @ProjectEntityHandler.flushProjectToThirdPartyDataStore .calledWith(@project_id) .should.equal true describe "with invalid privilegeLevel", -> beforeEach -> @CollaboratorHandler.addUserIdToProject @project_id, @adding_user_id, @user_id, "notValid", @callback it "should call the callback with an error", -> @callback.calledWith(new Error()).should.equal true describe "when user already exists as a collaborator", -> beforeEach -> @project.collaberator_refs = [@user_id] @CollaboratorHandler.addUserIdToProject @project_id, @adding_user_id, @user_id, "readAndWrite", @callback it "should not add the user again", -> @Project.update.called.should.equal false describe "addEmailToProject", -> beforeEach -> @UserCreator.getUserOrCreateHoldingAccount = sinon.stub().callsArgWith(1, null, @user = {_id: @user_id}) @CollaboratorHandler.addUserIdToProject = sinon.stub().callsArg(4) describe "with a valid email", -> beforeEach -> @CollaboratorHandler.addEmailToProject @project_id, @adding_user_id, (@email = "Joe@example.com"), (@privilegeLevel = "readAndWrite"), @callback it "should get the user with the lowercased email", -> @UserCreator.getUserOrCreateHoldingAccount .calledWith(@email.toLowerCase()) .should.equal true it "should add the user to the project by id", -> @CollaboratorHandler.addUserIdToProject .calledWith(@project_id, @adding_user_id, @user_id, @privilegeLevel) .should.equal true it "should return the callback with the user_id", -> @callback.calledWith(null, @user_id).should.equal true describe "with an invalid email", -> beforeEach -> @CollaboratorHandler.addEmailToProject @project_id, @adding_user_id, "not-and-email", (@privilegeLevel = "readAndWrite"), @callback it "should call the callback with an error", -> @callback.calledWith(new Error()).should.equal true it "should not add any users to the proejct", -> @CollaboratorHandler.addUserIdToProject.called.should.equal false describe "removeUserFromAllProjects", -> beforeEach (done) -> @CollaboratorHandler.getProjectsUserIsCollaboratorOf = sinon.stub() @CollaboratorHandler.getProjectsUserIsCollaboratorOf.withArgs(@user_id, { _id: 1 }).yields( null, [ { _id: "read-and-write-0" }, { _id: "read-and-write-1" }, null ], [ { _id: "read-only-0" }, { _id: "read-only-1" }, null ] ) @CollaboratorHandler.removeUserFromProject = sinon.stub().yields() @CollaboratorHandler.removeUserFromAllProjets @user_id, done it "should remove the user from each project", -> for project_id in ["read-and-write-0", "read-and-write-1", "read-only-0", "read-only-1"] @CollaboratorHandler.removeUserFromProject .calledWith(project_id, @user_id) .should.equal true
98790
should = require('chai').should() SandboxedModule = require('sandboxed-module') assert = require('assert') path = require('path') sinon = require('sinon') modulePath = path.join __dirname, "../../../../app/js/Features/Collaborators/CollaboratorsHandler" expect = require("chai").expect Errors = require "../../../../app/js/Features/Errors/Errors.js" describe "CollaboratorsHandler", -> beforeEach -> @CollaboratorHandler = SandboxedModule.require modulePath, requires: "logger-sharelatex": @logger = { log: sinon.stub(), err: sinon.stub() } '../User/UserCreator': @UserCreator = {} '../User/UserGetter': @UserGetter = {} "../Contacts/ContactManager": @ContactManager = {} "../../models/Project": Project: @Project = {} "../Project/ProjectEntityHandler": @ProjectEntityHandler = {} "./CollaboratorsEmailHandler": @CollaboratorsEmailHandler = {} "../Errors/Errors": Errors @project_id = "mock-project-id" @user_id = "mock-user-id" @adding_user_id = "adding-user-id" @email = "<EMAIL>" @callback = sinon.stub() describe "getMemberIdsWithPrivilegeLevels", -> describe "with project", -> beforeEach -> @Project.findOne = sinon.stub() @Project.findOne.withArgs({_id: @project_id}, {owner_ref: 1, collaberator_refs: 1, readOnly_refs: 1}).yields(null, @project = { owner_ref: [ "owner-ref" ] readOnly_refs: [ "read-only-ref-1", "read-only-ref-2" ] collaberator_refs: [ "read-write-ref-1", "read-write-ref-2" ] }) @CollaboratorHandler.getMemberIdsWithPrivilegeLevels @project_id, @callback it "should return an array of member ids with their privilege levels", -> @callback .calledWith(null, [ { id: "owner-ref", privilegeLevel: "owner" } { id: "read-only-ref-1", privilegeLevel: "readOnly" } { id: "read-only-ref-2", privilegeLevel: "readOnly" } { id: "read-write-ref-1", privilegeLevel: "readAndWrite" } { id: "read-write-ref-2", privilegeLevel: "readAndWrite" } ]) .should.equal true describe "with a missing project", -> beforeEach -> @Project.findOne = sinon.stub().yields(null, null) it "should return a NotFoundError", (done) -> @CollaboratorHandler.getMemberIdsWithPrivilegeLevels @project_id, (error) -> error.should.be.instanceof Errors.NotFoundError done() describe "getMemberIds", -> beforeEach -> @CollaboratorHandler.getMemberIdsWithPrivilegeLevels = sinon.stub() @CollaboratorHandler.getMemberIdsWithPrivilegeLevels .withArgs(@project_id) .yields(null, [{id: "member-id-1"}, {id: "member-id-2"}]) @CollaboratorHandler.getMemberIds @project_id, @callback it "should return the ids", -> @callback .calledWith(null, ["member-id-1", "member-id-2"]) .should.equal true describe "getMembersWithPrivilegeLevels", -> beforeEach -> @CollaboratorHandler.getMemberIdsWithPrivilegeLevels = sinon.stub() @CollaboratorHandler.getMemberIdsWithPrivilegeLevels.withArgs(@project_id).yields(null, [ { id: "read-only-ref-1", privilegeLevel: "readOnly" } { id: "read-only-ref-2", privilegeLevel: "readOnly" } { id: "read-write-ref-1", privilegeLevel: "readAndWrite" } { id: "read-write-ref-2", privilegeLevel: "readAndWrite" } { id: "doesnt-exist", privilegeLevel: "readAndWrite" } ]) @UserGetter.getUser = sinon.stub() @UserGetter.getUser.withArgs("read-only-ref-1").yields(null, { _id: "read-only-ref-1" }) @UserGetter.getUser.withArgs("read-only-ref-2").yields(null, { _id: "read-only-ref-2" }) @UserGetter.getUser.withArgs("read-write-ref-1").yields(null, { _id: "read-write-ref-1" }) @UserGetter.getUser.withArgs("read-write-ref-2").yields(null, { _id: "read-write-ref-2" }) @UserGetter.getUser.withArgs("doesnt-exist").yields(null, null) @CollaboratorHandler.getMembersWithPrivilegeLevels @project_id, @callback it "should return an array of members with their privilege levels", -> @callback .calledWith(null, [ { user: { _id: "read-only-ref-1" }, privilegeLevel: "readOnly" } { user: { _id: "read-only-ref-2" }, privilegeLevel: "readOnly" } { user: { _id: "read-write-ref-1" }, privilegeLevel: "readAndWrite" } { user: { _id: "read-write-ref-2" }, privilegeLevel: "readAndWrite" } ]) .should.equal true describe "getMemberIdPrivilegeLevel", -> beforeEach -> @CollaboratorHandler.getMemberIdsWithPrivilegeLevels = sinon.stub() @CollaboratorHandler.getMemberIdsWithPrivilegeLevels .withArgs(@project_id) .yields(null, [ {id: "member-id-1", privilegeLevel: "readAndWrite"} {id: "member-id-2", privilegeLevel: "readOnly"} ]) it "should return the privilege level if it exists", (done) -> @CollaboratorHandler.getMemberIdPrivilegeLevel "member-id-2", @project_id, (error, level) -> expect(level).to.equal "readOnly" done() it "should return false if the member has no privilege level", (done) -> @CollaboratorHandler.getMemberIdPrivilegeLevel "member-id-3", @project_id, (error, level) -> expect(level).to.equal false done() describe "isUserMemberOfProject", -> beforeEach -> @CollaboratorHandler.getMemberIdsWithPrivilegeLevels = sinon.stub() describe "when user is a member of the project", -> beforeEach -> @CollaboratorHandler.getMemberIdsWithPrivilegeLevels.withArgs(@project_id).yields(null, [ { id: "not-the-user", privilegeLevel: "readOnly" } { id: @user_id, privilegeLevel: "readAndWrite" } ]) @CollaboratorHandler.isUserMemberOfProject @user_id, @project_id, @callback it "should return true and the privilegeLevel", -> @callback .calledWith(null, true, "readAndWrite") .should.equal true describe "when user is not a member of the project", -> beforeEach -> @CollaboratorHandler.getMemberIdsWithPrivilegeLevels.withArgs(@project_id).yields(null, [ { id: "not-the-user", privilegeLevel: "readOnly" } ]) @CollaboratorHandler.isUserMemberOfProject @user_id, @project_id, @callback it "should return false", -> @callback .calledWith(null, false, null) .should.equal true describe "getProjectsUserIsCollaboratorOf", -> beforeEach -> @fields = "mock fields" @Project.find = sinon.stub() @Project.find.withArgs({collaberator_refs:@user_id}, @fields).yields(null, ["mock-read-write-project-1", "mock-read-write-project-2"]) @Project.find.withArgs({readOnly_refs:@user_id}, @fields).yields(null, ["mock-read-only-project-1", "mock-read-only-project-2"]) @CollaboratorHandler.getProjectsUserIsCollaboratorOf @user_id, @fields, @callback it "should call the callback with the projects", -> @callback .calledWith(null, ["mock-read-write-project-1", "mock-read-write-project-2"], ["mock-read-only-project-1", "mock-read-only-project-2"]) .should.equal true describe "removeUserFromProject", -> beforeEach -> @Project.update = sinon.stub().callsArg(2) @CollaboratorHandler.removeUserFromProject @project_id, @user_id, @callback it "should remove the user from mongo", -> @Project.update .calledWith({ _id: @project_id }, { "$pull":{collaberator_refs:@user_id, readOnly_refs:@user_id} }) .should.equal true describe "addUserToProject", -> beforeEach -> @Project.update = sinon.stub().callsArg(2) @Project.findOne = sinon.stub().callsArgWith(2, null, @project = {}) @ProjectEntityHandler.flushProjectToThirdPartyDataStore = sinon.stub().callsArg(1) @CollaboratorHandler.addEmailToProject = sinon.stub().callsArgWith(4, null, @user_id) @UserGetter.getUser = sinon.stub().callsArgWith(2, null, @user = { _id: @user_id, email: @email }) @CollaboratorsEmailHandler.notifyUserOfProjectShare = sinon.stub() @ContactManager.addContact = sinon.stub() describe "as readOnly", -> beforeEach -> @CollaboratorHandler.addUserIdToProject @project_id, @adding_user_id, @user_id, "readOnly", @callback it "should add the user to the readOnly_refs", -> @Project.update .calledWith({ _id: @project_id }, { "$addToSet":{ readOnly_refs: @user_id } }) .should.equal true it "should flush the project to the TPDS", -> @ProjectEntityHandler.flushProjectToThirdPartyDataStore .calledWith(@project_id) .should.equal true it "should send an email to the shared-with user", -> @CollaboratorsEmailHandler.notifyUserOfProjectShare .calledWith(@project_id, @email) .should.equal true it "should add the user as a contact for the adding user", -> @ContactManager.addContact .calledWith(@adding_user_id, @user_id) .should.equal true describe "as readAndWrite", -> beforeEach -> @CollaboratorHandler.addUserIdToProject @project_id, @adding_user_id, @user_id, "readAndWrite", @callback it "should add the user to the collaberator_refs", -> @Project.update .calledWith({ _id: @project_id }, { "$addToSet":{ collaberator_refs: @user_id } }) .should.equal true it "should flush the project to the TPDS", -> @ProjectEntityHandler.flushProjectToThirdPartyDataStore .calledWith(@project_id) .should.equal true describe "with invalid privilegeLevel", -> beforeEach -> @CollaboratorHandler.addUserIdToProject @project_id, @adding_user_id, @user_id, "notValid", @callback it "should call the callback with an error", -> @callback.calledWith(new Error()).should.equal true describe "when user already exists as a collaborator", -> beforeEach -> @project.collaberator_refs = [@user_id] @CollaboratorHandler.addUserIdToProject @project_id, @adding_user_id, @user_id, "readAndWrite", @callback it "should not add the user again", -> @Project.update.called.should.equal false describe "addEmailToProject", -> beforeEach -> @UserCreator.getUserOrCreateHoldingAccount = sinon.stub().callsArgWith(1, null, @user = {_id: @user_id}) @CollaboratorHandler.addUserIdToProject = sinon.stub().callsArg(4) describe "with a valid email", -> beforeEach -> @CollaboratorHandler.addEmailToProject @project_id, @adding_user_id, (@email = "<EMAIL>"), (@privilegeLevel = "readAndWrite"), @callback it "should get the user with the lowercased email", -> @UserCreator.getUserOrCreateHoldingAccount .calledWith(@email.toLowerCase()) .should.equal true it "should add the user to the project by id", -> @CollaboratorHandler.addUserIdToProject .calledWith(@project_id, @adding_user_id, @user_id, @privilegeLevel) .should.equal true it "should return the callback with the user_id", -> @callback.calledWith(null, @user_id).should.equal true describe "with an invalid email", -> beforeEach -> @CollaboratorHandler.addEmailToProject @project_id, @adding_user_id, "not-and-email", (@privilegeLevel = "readAndWrite"), @callback it "should call the callback with an error", -> @callback.calledWith(new Error()).should.equal true it "should not add any users to the proejct", -> @CollaboratorHandler.addUserIdToProject.called.should.equal false describe "removeUserFromAllProjects", -> beforeEach (done) -> @CollaboratorHandler.getProjectsUserIsCollaboratorOf = sinon.stub() @CollaboratorHandler.getProjectsUserIsCollaboratorOf.withArgs(@user_id, { _id: 1 }).yields( null, [ { _id: "read-and-write-0" }, { _id: "read-and-write-1" }, null ], [ { _id: "read-only-0" }, { _id: "read-only-1" }, null ] ) @CollaboratorHandler.removeUserFromProject = sinon.stub().yields() @CollaboratorHandler.removeUserFromAllProjets @user_id, done it "should remove the user from each project", -> for project_id in ["read-and-write-0", "read-and-write-1", "read-only-0", "read-only-1"] @CollaboratorHandler.removeUserFromProject .calledWith(project_id, @user_id) .should.equal true
true
should = require('chai').should() SandboxedModule = require('sandboxed-module') assert = require('assert') path = require('path') sinon = require('sinon') modulePath = path.join __dirname, "../../../../app/js/Features/Collaborators/CollaboratorsHandler" expect = require("chai").expect Errors = require "../../../../app/js/Features/Errors/Errors.js" describe "CollaboratorsHandler", -> beforeEach -> @CollaboratorHandler = SandboxedModule.require modulePath, requires: "logger-sharelatex": @logger = { log: sinon.stub(), err: sinon.stub() } '../User/UserCreator': @UserCreator = {} '../User/UserGetter': @UserGetter = {} "../Contacts/ContactManager": @ContactManager = {} "../../models/Project": Project: @Project = {} "../Project/ProjectEntityHandler": @ProjectEntityHandler = {} "./CollaboratorsEmailHandler": @CollaboratorsEmailHandler = {} "../Errors/Errors": Errors @project_id = "mock-project-id" @user_id = "mock-user-id" @adding_user_id = "adding-user-id" @email = "PI:EMAIL:<EMAIL>END_PI" @callback = sinon.stub() describe "getMemberIdsWithPrivilegeLevels", -> describe "with project", -> beforeEach -> @Project.findOne = sinon.stub() @Project.findOne.withArgs({_id: @project_id}, {owner_ref: 1, collaberator_refs: 1, readOnly_refs: 1}).yields(null, @project = { owner_ref: [ "owner-ref" ] readOnly_refs: [ "read-only-ref-1", "read-only-ref-2" ] collaberator_refs: [ "read-write-ref-1", "read-write-ref-2" ] }) @CollaboratorHandler.getMemberIdsWithPrivilegeLevels @project_id, @callback it "should return an array of member ids with their privilege levels", -> @callback .calledWith(null, [ { id: "owner-ref", privilegeLevel: "owner" } { id: "read-only-ref-1", privilegeLevel: "readOnly" } { id: "read-only-ref-2", privilegeLevel: "readOnly" } { id: "read-write-ref-1", privilegeLevel: "readAndWrite" } { id: "read-write-ref-2", privilegeLevel: "readAndWrite" } ]) .should.equal true describe "with a missing project", -> beforeEach -> @Project.findOne = sinon.stub().yields(null, null) it "should return a NotFoundError", (done) -> @CollaboratorHandler.getMemberIdsWithPrivilegeLevels @project_id, (error) -> error.should.be.instanceof Errors.NotFoundError done() describe "getMemberIds", -> beforeEach -> @CollaboratorHandler.getMemberIdsWithPrivilegeLevels = sinon.stub() @CollaboratorHandler.getMemberIdsWithPrivilegeLevels .withArgs(@project_id) .yields(null, [{id: "member-id-1"}, {id: "member-id-2"}]) @CollaboratorHandler.getMemberIds @project_id, @callback it "should return the ids", -> @callback .calledWith(null, ["member-id-1", "member-id-2"]) .should.equal true describe "getMembersWithPrivilegeLevels", -> beforeEach -> @CollaboratorHandler.getMemberIdsWithPrivilegeLevels = sinon.stub() @CollaboratorHandler.getMemberIdsWithPrivilegeLevels.withArgs(@project_id).yields(null, [ { id: "read-only-ref-1", privilegeLevel: "readOnly" } { id: "read-only-ref-2", privilegeLevel: "readOnly" } { id: "read-write-ref-1", privilegeLevel: "readAndWrite" } { id: "read-write-ref-2", privilegeLevel: "readAndWrite" } { id: "doesnt-exist", privilegeLevel: "readAndWrite" } ]) @UserGetter.getUser = sinon.stub() @UserGetter.getUser.withArgs("read-only-ref-1").yields(null, { _id: "read-only-ref-1" }) @UserGetter.getUser.withArgs("read-only-ref-2").yields(null, { _id: "read-only-ref-2" }) @UserGetter.getUser.withArgs("read-write-ref-1").yields(null, { _id: "read-write-ref-1" }) @UserGetter.getUser.withArgs("read-write-ref-2").yields(null, { _id: "read-write-ref-2" }) @UserGetter.getUser.withArgs("doesnt-exist").yields(null, null) @CollaboratorHandler.getMembersWithPrivilegeLevels @project_id, @callback it "should return an array of members with their privilege levels", -> @callback .calledWith(null, [ { user: { _id: "read-only-ref-1" }, privilegeLevel: "readOnly" } { user: { _id: "read-only-ref-2" }, privilegeLevel: "readOnly" } { user: { _id: "read-write-ref-1" }, privilegeLevel: "readAndWrite" } { user: { _id: "read-write-ref-2" }, privilegeLevel: "readAndWrite" } ]) .should.equal true describe "getMemberIdPrivilegeLevel", -> beforeEach -> @CollaboratorHandler.getMemberIdsWithPrivilegeLevels = sinon.stub() @CollaboratorHandler.getMemberIdsWithPrivilegeLevels .withArgs(@project_id) .yields(null, [ {id: "member-id-1", privilegeLevel: "readAndWrite"} {id: "member-id-2", privilegeLevel: "readOnly"} ]) it "should return the privilege level if it exists", (done) -> @CollaboratorHandler.getMemberIdPrivilegeLevel "member-id-2", @project_id, (error, level) -> expect(level).to.equal "readOnly" done() it "should return false if the member has no privilege level", (done) -> @CollaboratorHandler.getMemberIdPrivilegeLevel "member-id-3", @project_id, (error, level) -> expect(level).to.equal false done() describe "isUserMemberOfProject", -> beforeEach -> @CollaboratorHandler.getMemberIdsWithPrivilegeLevels = sinon.stub() describe "when user is a member of the project", -> beforeEach -> @CollaboratorHandler.getMemberIdsWithPrivilegeLevels.withArgs(@project_id).yields(null, [ { id: "not-the-user", privilegeLevel: "readOnly" } { id: @user_id, privilegeLevel: "readAndWrite" } ]) @CollaboratorHandler.isUserMemberOfProject @user_id, @project_id, @callback it "should return true and the privilegeLevel", -> @callback .calledWith(null, true, "readAndWrite") .should.equal true describe "when user is not a member of the project", -> beforeEach -> @CollaboratorHandler.getMemberIdsWithPrivilegeLevels.withArgs(@project_id).yields(null, [ { id: "not-the-user", privilegeLevel: "readOnly" } ]) @CollaboratorHandler.isUserMemberOfProject @user_id, @project_id, @callback it "should return false", -> @callback .calledWith(null, false, null) .should.equal true describe "getProjectsUserIsCollaboratorOf", -> beforeEach -> @fields = "mock fields" @Project.find = sinon.stub() @Project.find.withArgs({collaberator_refs:@user_id}, @fields).yields(null, ["mock-read-write-project-1", "mock-read-write-project-2"]) @Project.find.withArgs({readOnly_refs:@user_id}, @fields).yields(null, ["mock-read-only-project-1", "mock-read-only-project-2"]) @CollaboratorHandler.getProjectsUserIsCollaboratorOf @user_id, @fields, @callback it "should call the callback with the projects", -> @callback .calledWith(null, ["mock-read-write-project-1", "mock-read-write-project-2"], ["mock-read-only-project-1", "mock-read-only-project-2"]) .should.equal true describe "removeUserFromProject", -> beforeEach -> @Project.update = sinon.stub().callsArg(2) @CollaboratorHandler.removeUserFromProject @project_id, @user_id, @callback it "should remove the user from mongo", -> @Project.update .calledWith({ _id: @project_id }, { "$pull":{collaberator_refs:@user_id, readOnly_refs:@user_id} }) .should.equal true describe "addUserToProject", -> beforeEach -> @Project.update = sinon.stub().callsArg(2) @Project.findOne = sinon.stub().callsArgWith(2, null, @project = {}) @ProjectEntityHandler.flushProjectToThirdPartyDataStore = sinon.stub().callsArg(1) @CollaboratorHandler.addEmailToProject = sinon.stub().callsArgWith(4, null, @user_id) @UserGetter.getUser = sinon.stub().callsArgWith(2, null, @user = { _id: @user_id, email: @email }) @CollaboratorsEmailHandler.notifyUserOfProjectShare = sinon.stub() @ContactManager.addContact = sinon.stub() describe "as readOnly", -> beforeEach -> @CollaboratorHandler.addUserIdToProject @project_id, @adding_user_id, @user_id, "readOnly", @callback it "should add the user to the readOnly_refs", -> @Project.update .calledWith({ _id: @project_id }, { "$addToSet":{ readOnly_refs: @user_id } }) .should.equal true it "should flush the project to the TPDS", -> @ProjectEntityHandler.flushProjectToThirdPartyDataStore .calledWith(@project_id) .should.equal true it "should send an email to the shared-with user", -> @CollaboratorsEmailHandler.notifyUserOfProjectShare .calledWith(@project_id, @email) .should.equal true it "should add the user as a contact for the adding user", -> @ContactManager.addContact .calledWith(@adding_user_id, @user_id) .should.equal true describe "as readAndWrite", -> beforeEach -> @CollaboratorHandler.addUserIdToProject @project_id, @adding_user_id, @user_id, "readAndWrite", @callback it "should add the user to the collaberator_refs", -> @Project.update .calledWith({ _id: @project_id }, { "$addToSet":{ collaberator_refs: @user_id } }) .should.equal true it "should flush the project to the TPDS", -> @ProjectEntityHandler.flushProjectToThirdPartyDataStore .calledWith(@project_id) .should.equal true describe "with invalid privilegeLevel", -> beforeEach -> @CollaboratorHandler.addUserIdToProject @project_id, @adding_user_id, @user_id, "notValid", @callback it "should call the callback with an error", -> @callback.calledWith(new Error()).should.equal true describe "when user already exists as a collaborator", -> beforeEach -> @project.collaberator_refs = [@user_id] @CollaboratorHandler.addUserIdToProject @project_id, @adding_user_id, @user_id, "readAndWrite", @callback it "should not add the user again", -> @Project.update.called.should.equal false describe "addEmailToProject", -> beforeEach -> @UserCreator.getUserOrCreateHoldingAccount = sinon.stub().callsArgWith(1, null, @user = {_id: @user_id}) @CollaboratorHandler.addUserIdToProject = sinon.stub().callsArg(4) describe "with a valid email", -> beforeEach -> @CollaboratorHandler.addEmailToProject @project_id, @adding_user_id, (@email = "PI:EMAIL:<EMAIL>END_PI"), (@privilegeLevel = "readAndWrite"), @callback it "should get the user with the lowercased email", -> @UserCreator.getUserOrCreateHoldingAccount .calledWith(@email.toLowerCase()) .should.equal true it "should add the user to the project by id", -> @CollaboratorHandler.addUserIdToProject .calledWith(@project_id, @adding_user_id, @user_id, @privilegeLevel) .should.equal true it "should return the callback with the user_id", -> @callback.calledWith(null, @user_id).should.equal true describe "with an invalid email", -> beforeEach -> @CollaboratorHandler.addEmailToProject @project_id, @adding_user_id, "not-and-email", (@privilegeLevel = "readAndWrite"), @callback it "should call the callback with an error", -> @callback.calledWith(new Error()).should.equal true it "should not add any users to the proejct", -> @CollaboratorHandler.addUserIdToProject.called.should.equal false describe "removeUserFromAllProjects", -> beforeEach (done) -> @CollaboratorHandler.getProjectsUserIsCollaboratorOf = sinon.stub() @CollaboratorHandler.getProjectsUserIsCollaboratorOf.withArgs(@user_id, { _id: 1 }).yields( null, [ { _id: "read-and-write-0" }, { _id: "read-and-write-1" }, null ], [ { _id: "read-only-0" }, { _id: "read-only-1" }, null ] ) @CollaboratorHandler.removeUserFromProject = sinon.stub().yields() @CollaboratorHandler.removeUserFromAllProjets @user_id, done it "should remove the user from each project", -> for project_id in ["read-and-write-0", "read-and-write-1", "read-only-0", "read-only-1"] @CollaboratorHandler.removeUserFromProject .calledWith(project_id, @user_id) .should.equal true
[ { "context": ".relationship, relationship_options\n\tfor key in [\"created_at\", \"updated_at\"] when relationship_options[key]\n\t\t", "end": 11465, "score": 0.8955346941947937, "start": 11455, "tag": "KEY", "value": "created_at" }, { "context": "onship_options\n\tfor key in [\"created_at\", \"updated_at\"] when relationship_options[key]\n\t\trelationship_o", "end": 11479, "score": 0.914753794670105, "start": 11477, "tag": "KEY", "value": "at" } ]
src/index.coffee
bigluck/neoogm
0
request = require "request" async = require "async" _ = require "lodash" Q = require "q" # # Globals globals = host: "localhost" port: 7474 secure: false merge: true node: created_at: false updated_at: false relationship: created_at: false updated_at: false models = node: {} relationship: {} options: schema: {} strict: true created_at: false updated_at: false NeoormError = class extends Error constructor: (data) -> @name = "Neoorm#{ if data?.exception? then data?.exception else '' }" @message = if data?.message? then data.message else data @original = data # # Public neoogm = -> neoogm.cypher arguments neoogm.config = (options) -> globals = _.extend {}, globals, options globals.url = "http#{ if globals.secure then 's' else '' }://#{ globals.host or 'localhost' }:#{ globals.port or 7474 }/db/data/cypher" neoogm neoogm.cypher = (options, cb) -> deferred = Q.defer() options = _.extend one: false query: "" params: {} models: [] , if typeof options is "object" options else if options instanceof Array query: options.join " " else query: options options.query = options.query.join " " if options.query instanceof Array options.query += " LIMIT 1" if options.one and not options.query.match /LIMIT\s+([\d+])/ options.params._id = parseInputId options.params._id if options.params?._id? options.params._start = parseInputId options.params._start if options.params?._start? options.params._end = parseInputId options.params._end if options.params?._end? request url: globals.url method: "POST" headers: "Accept": "application/json; charset=UTF-8" "Content-Type": "application/json" "X-Stream": "true" json: query: options.query params: options.params , (err, res, body) -> err = body if res and res?.statusCode isnt 200 if err err = new NeoormError err cb? err return deferred.reject err output_columns = [] model_remaps = [] for name, i in options.models output_columns.push body.columns[i] if name?[0] is "=" model_remaps.push item: body.columns[i] labels: name[1..] else if name is false output_columns.pop() model_remaps.push item: body.columns[i] remove: true data = _.map body.data, (row, row_i) -> # Convert array elements to objects rows = _.transform row, (out, row, col_i) -> entity = if row?.type? then "relationship" else if row?.data? then "node" else false row = switch entity when "relationship" _.extend {}, row.data, _id: parseCypherId row.self _start: parseCypherId row.start _end: parseCypherId row.end _type: row.type when "node" _.extend {}, row.data, _id: parseCypherId row.self else row out[body.columns[col_i]] = if entity and klass = models[entity][options.models?[col_i]] new klass row else row # Remap objects for rule in model_remaps if rule.labels for model in rows[rule.labels] if klass = models.node[model] or klass = models.relationship[model] rows[rule.item] = new klass rows[rule.item] break else if rule.remove is true delete rows[rule.item] # Only one item if output_columns.length and output_columns.length > 1 then rows else rows[output_columns[0]] data = if options.one then data[0] else data cb? null, data deferred.resolve data deferred.promise neoogm.findNodeById = (id, cb) -> neoogm.cypher one: true query: [ "START node = node({id})" "RETURN node, LABELS(node) AS node_labels" ] params: id: id models: [ "=node_labels", false ] , cb neoogm.findRelationshipById = (id, cb) -> neoogm.cypher one: true query: [ "START relationship = relationship({id})" "RETURN relationship, [TYPE(relationship)] AS relationship_type" ] params: id: id models: [ "=relationship_type", false ] , cb neoogm.node = (node_label, node_options=false) -> node_label = node_label.trim() return throw new Error "Node model \"#{ node_label }\" not defined" if not models.node[node_label] and not node_options return models.node[node_label] unless node_options return throw new Error "Node model \"#{ node_label }\" already defined" if models.node[node_label] node_options = _.extend models.options, globals.node, node_options for key in ["created_at", "updated_at"] when node_options[key] node_options[key] = if node_options[key] is true then key else node_options[key] node_options.schema[node_options[key]] = Date.now models.node[node_label] = class constructor: (data={}) -> @[name] = value for name, value of data save: (cb) -> deferred = Q.defer() data = _.extend {}, @toJSON() data[node_options.updated_at] = Date.now() if node_options.updated_at data[node_options.created_at] = Date.now() if node_options.created_at and not @_id? self = @ neoogm.cypher one: true query: if @_id "START n = node({id}) WHERE n:#{ node_label } SET n = {data} RETURN n" else "CREATE (n:#{ node_label } {data}) RETURN n" params: id: @_id data: data models: [ node_label ] , (err, item) -> if err cb? err return deferred.reject err self[key] = value for key, value of item cb? null, self deferred.resolve self deferred.promise remove: (cb) -> deferred = Q.defer() unless @_id err = new NeoormError "Node could not be deleted without a valid id" cb? err return deferred.reject err self = @ neoogm.cypher query: [ "START n = node({id})" "WHERE n:#{ node_label }" "DELETE n" ] params: id: @_id , (err, item) -> if err cb? err return deferred.reject err delete self._id cb? null, self deferred.resolve self deferred.promise # createOutgoing: (type, data, cb) -> # createIncoming: (type, data, cb) -> findOutgoing: (options, cb) -> [options, cb] = [type: options, cb] if typeof options is "string" @findRelates (_.extend {}, options, type: options.type, outgoing: true), cb findIncoming: (options, cb) -> [options, cb] = [type: options, cb] if typeof options is "string" @findRelates (_.extend {}, options, type: options.type, incoming: true), cb findRelates: (options, cb) -> [options, cb] = [type: options, cb] if typeof options is "string" throw new NeoormError "Relationship type not defined" unless options.type (neoogm.relationship options.type).findRelates (_.extend {}, options, model: @), cb getId: -> @_id getLabel: -> node_label toJSON: -> ## FIX ME: validate model everywhere ensureValidModel @, node_options @create: (data, cb) -> [data, cb] = [{}, data] if typeof data is "function" deferred = Q.defer() neoogm.cypher query: [ "CREATE (n:#{ node_label } {data})" "RETURN n" ] params: data: data models: [ node_label ] , (err, items) -> if err cb? err return deferred.reject err cb? err, items deferred.resolve items deferred.promise @update: (options, cb) -> deferred = Q.defer() options = _.extend query: null params: {} data: {} , options if options.query instanceof Array options.query = options.query.join " " else if typeof options.query is "object" options.params[key] = value for key, value of options.query options.query = (" n.#{key} = {#{key}} " for key, value of options.query).join " AND " query_update = (" n.#{key} = {#{key}} " for key, value of options.data).join ", " neoogm.cypher query: [ "MATCH (n:#{ node_label })" if options.query then "WHERE #{ options.query }" else "" "SET #{ query_update }" "RETURN n" ] params: options.params models: [ node_label ] , (err, items) -> if err cb? err return deferred.reject err cb? err, items deferred.resolve items deferred.promise @delete: (options, cb) -> deferred = Q.defer() self = @ async.waterfall [ (cb) -> self.find options, cb (items, cb) -> return cb null, items unless items.length query_where = ("ID(n) = #{ id }" for id in _.pluck items, "_id").join " OR " neoogm.cypher "START n=node(*) WHERE n:User AND (#{ query_where }) DELETE n", (err) -> cb err, items ], (err, items) -> if err cb? err return deferred.reject err cb? err, items deferred.resolve items deferred.promise @findById: (id, cb) -> [id, cb] = [null, id] if typeof id is "function" deferred = Q.defer() unless id? err = new NeoormError "Node id not defined" cb? err return deferred.reject err neoogm.cypher query: [ "START n = node({id})" "WHERE n:#{ node_label }" "RETURN n" ] params: id: id models: [ node_label ] one: true , (err, items) -> if err cb? err return deferred.reject err cb? err, items deferred.resolve items deferred.promise @findByIdAndRemove: (id, cb) -> [id, cb] = [null, id] if typeof id is "function" deferred = Q.defer() unless id? err = new NeoormError "Node id not defined" cb? err return deferred.reject err self = @ async.waterfall [ (cb) -> self.findById id, cb (item, cb) -> item.remove cb ], (err, items) -> if err cb? err return deferred.reject err cb? err, items deferred.resolve items deferred.promise @findByIdAndUpdate: (id, data, cb) -> [data, cb] = [{}, id] if typeof data is "function" deferred = Q.defer() data = _.extend {}, data data[node_options.updated_at] = Date.now() if node_options.updated_at query_update = (" n.#{key} = {#{key}} " for key, value of data).join ", " neoogm.cypher query: [ "START n = node({id})" "WHERE n:#{ node_label }" "SET #{ query_update }" "RETURN n" ] params: _.extend data, id: id models: [ node_label ] one: true , (err, items) -> if err cb? err return deferred.reject err cb? err, items deferred.resolve items deferred.promise @find: (options, cb) -> [options, cb] = [{}, options] if typeof options is "function" deferred = Q.defer() options = _.extend query: null params: {} , options if options.query instanceof Array options.query = options.query.join " " else if typeof options.query is "object" options.params[key] = value for key, value of options.query options.query = (" n.#{key} = {#{key}} " for key, value of options.query).join " AND " neoogm.cypher query: [ "MATCH (n:#{ node_label })" "WHERE #{ options.query }" "RETURN n" ] params: options.params models: [ node_label ] , (err, items) -> if err cb? err return deferred.reject err cb? err, items deferred.resolve items deferred.promise neoogm.relationship = (relationship_type, relationship_options=false) -> relationship_type = relationship_type.trim() return throw new Error "Relationship model \"#{ relationship_type }\" not defined" if not models.relationship[relationship_type] and not relationship_options return models.relationship[relationship_type] unless relationship_options return throw new Error "Relationship model \"#{ relationship_type }\" already defined" if models.relationship[relationship_type] relationship_options = _.extend models.options, globals.relationship, relationship_options for key in ["created_at", "updated_at"] when relationship_options[key] relationship_options[key] = if relationship_options[key] is true then key else relationship_options[key] relationship_options.schema[relationship_options[key]] = Date.now models.relationship[relationship_type] = class constructor: (data={}) -> @[name] = value for name, value of data save: (cb) -> deferred = Q.defer() data = _.extend {}, @toJSON() data[relationship_options.updated_at] = Date.now() if relationship_options.updated_at data[relationship_options.created_at] = Date.now() if relationship_options.created_at and not @_id? unless @_start? err = new NeoormError "Start node not defined" cb? err return deferred.reject err unless @_end? err = new NeoormError "End node not defined" cb? err return deferred.reject err self = @ async.waterfall [ (cb) -> cb null, if self._id then self (item, cb) -> return cb null, item if item # Id not found neoogm.cypher one: true query: [ "START start = node({start}), end = node({end})" "MATCH (start) -[relationship:#{ relationship_type }]-> (end)" "RETURN relationship" ] params: start: self._start end: self._end models: [ relationship_type ] , -> cb? arguments... (item, cb) -> return cb null, item unless item?._id # Relationship already exists data[relationship_options.created_at] = item[relationship_options.created_at] if relationship_options.created_at neoogm.cypher one: true query: [ "START relationship = relationship({id})" "WHERE TYPE(relationship) = {type}" "SET relationship = {data}" "RETURN relationship" ] params: id: item._id type: relationship_type data: data models: [ relationship_type ] , -> cb? arguments... (item, cb) -> return cb null, item if item?._id # Relationship not found neoogm.cypher one: true query: [ "START start = node({start}), end = node({end})" "CREATE (start) -[relationship:#{ relationship_type } {data}]-> (end)" "RETURN relationship" ] params: start: self._start end: self._end data: data models: [ relationship_type ] , -> cb? arguments... ], (err, item) -> if err cb? err return deferred.reject err self[key] = value for key, value of item cb? null, self deferred.resolve self deferred.promise remove: (cb) -> deferred = Q.defer() unless @_id err = new NeoormError "Relationship could not be deleted without a valid id" cb? err return deferred.reject err self = @ neoogm.cypher query: [ "START relationship = relationship({id})" "WHERE TYPE(relationship) = {type}" "DELETE relationship" ] params: id: @_id type: relationship_type , (err, item) -> if err cb? err return deferred.reject err delete self._id delete self._start delete self._end cb? null, self deferred.resolve results deferred.promise getId: -> @_id getType: -> relationship_type getStart: (cb) -> deferred = Q.defer() self = @ async.waterfall [ (cb) -> return cb null, self._start if self._start?._id? neoogm.findNodeById self._start, cb ], (err, item) -> if err cb? err return deferred.reject err self._start = item cb? null, item deferred.resolve item deferred.promise getEnd: (cb) -> deferred = Q.defer() self = @ async.waterfall [ (cb) -> return cb null, self._end if self._end?._id? neoogm.findNodeById self._end, cb ], (err, item) -> if err cb? err return deferred.reject err self._end = item cb? null, item deferred.resolve item deferred.promise toJSON: -> ensureValidModel @, relationship_options @findOutgoing: (options, cb) -> [options, cb] = [{}, options] if typeof options is "function" @findRelates (_.extend {}, options, outgoing: true), cb @findIncoming: (options, cb) -> [options, cb] = [{}, options] if typeof options is "function" @findRelates (_.extend {}, options, incoming: true), cb @findRelates: (options, cb) -> [options, cb] = [{}, options] if typeof options is "function" deferred = Q.defer() options = _.extend model: null outgoing: false incoming: false query: null params: {} , options unless model_label = options.model?.getLabel?() err = new NeoormError "options.model have to be an Neoorm model" cb? err return deferred.reject err unless options.model?.getId?()? err = new NeoormError "options.model is not an database reference" cb? err return deferred.reject err if options.query instanceof Array options.query = options.query.join " " else if typeof options.query is "object" options.params[key] = value for key, value of options.query options.query = (" n.#{key} = {#{key}} " for key, value of options.query).join " AND " neoogm.cypher query: [ "START target = node({id})" "MATCH " "(target:#{ model_label }) #{ if options.incoming and not options.outgoing then '<' else '' }-" " [relationship:#{ relationship_type }] " "-#{ if options.outgoing and not options.incoming then '>' else '' } (end)" if options.query then "WHERE #{ options.query }" else "" "RETURN relationship, end, LABELS(end) AS end_labels" ] params: id: options.model.getId() models: [ relationship_type, "=end_labels", false ] , (err, results) -> if err cb? err return deferred.reject err results = _.map results, (row, row_i) -> row.start = options.model row cb? err, results deferred.resolve results deferred.promise # @create: () -> # @update: () -> # @delete: () -> # # Helpers parseCypherId = (path) -> parseInt (path.match /([\d]+)$/)[1] parseInputId = (data) -> if data?._id? then parseInt data._id else data ensureValidModel = (model, options) -> keys = _.union (key for key of options.schema), (key for key, value of model when model.hasOwnProperty key) _.transform keys, (out, key) -> out[key] = model[key] if model[key]? and key isnt "_id" and (options.strict is false or (options.strict is true and options.schema?[key])) module.exports = neoogm
158804
request = require "request" async = require "async" _ = require "lodash" Q = require "q" # # Globals globals = host: "localhost" port: 7474 secure: false merge: true node: created_at: false updated_at: false relationship: created_at: false updated_at: false models = node: {} relationship: {} options: schema: {} strict: true created_at: false updated_at: false NeoormError = class extends Error constructor: (data) -> @name = "Neoorm#{ if data?.exception? then data?.exception else '' }" @message = if data?.message? then data.message else data @original = data # # Public neoogm = -> neoogm.cypher arguments neoogm.config = (options) -> globals = _.extend {}, globals, options globals.url = "http#{ if globals.secure then 's' else '' }://#{ globals.host or 'localhost' }:#{ globals.port or 7474 }/db/data/cypher" neoogm neoogm.cypher = (options, cb) -> deferred = Q.defer() options = _.extend one: false query: "" params: {} models: [] , if typeof options is "object" options else if options instanceof Array query: options.join " " else query: options options.query = options.query.join " " if options.query instanceof Array options.query += " LIMIT 1" if options.one and not options.query.match /LIMIT\s+([\d+])/ options.params._id = parseInputId options.params._id if options.params?._id? options.params._start = parseInputId options.params._start if options.params?._start? options.params._end = parseInputId options.params._end if options.params?._end? request url: globals.url method: "POST" headers: "Accept": "application/json; charset=UTF-8" "Content-Type": "application/json" "X-Stream": "true" json: query: options.query params: options.params , (err, res, body) -> err = body if res and res?.statusCode isnt 200 if err err = new NeoormError err cb? err return deferred.reject err output_columns = [] model_remaps = [] for name, i in options.models output_columns.push body.columns[i] if name?[0] is "=" model_remaps.push item: body.columns[i] labels: name[1..] else if name is false output_columns.pop() model_remaps.push item: body.columns[i] remove: true data = _.map body.data, (row, row_i) -> # Convert array elements to objects rows = _.transform row, (out, row, col_i) -> entity = if row?.type? then "relationship" else if row?.data? then "node" else false row = switch entity when "relationship" _.extend {}, row.data, _id: parseCypherId row.self _start: parseCypherId row.start _end: parseCypherId row.end _type: row.type when "node" _.extend {}, row.data, _id: parseCypherId row.self else row out[body.columns[col_i]] = if entity and klass = models[entity][options.models?[col_i]] new klass row else row # Remap objects for rule in model_remaps if rule.labels for model in rows[rule.labels] if klass = models.node[model] or klass = models.relationship[model] rows[rule.item] = new klass rows[rule.item] break else if rule.remove is true delete rows[rule.item] # Only one item if output_columns.length and output_columns.length > 1 then rows else rows[output_columns[0]] data = if options.one then data[0] else data cb? null, data deferred.resolve data deferred.promise neoogm.findNodeById = (id, cb) -> neoogm.cypher one: true query: [ "START node = node({id})" "RETURN node, LABELS(node) AS node_labels" ] params: id: id models: [ "=node_labels", false ] , cb neoogm.findRelationshipById = (id, cb) -> neoogm.cypher one: true query: [ "START relationship = relationship({id})" "RETURN relationship, [TYPE(relationship)] AS relationship_type" ] params: id: id models: [ "=relationship_type", false ] , cb neoogm.node = (node_label, node_options=false) -> node_label = node_label.trim() return throw new Error "Node model \"#{ node_label }\" not defined" if not models.node[node_label] and not node_options return models.node[node_label] unless node_options return throw new Error "Node model \"#{ node_label }\" already defined" if models.node[node_label] node_options = _.extend models.options, globals.node, node_options for key in ["created_at", "updated_at"] when node_options[key] node_options[key] = if node_options[key] is true then key else node_options[key] node_options.schema[node_options[key]] = Date.now models.node[node_label] = class constructor: (data={}) -> @[name] = value for name, value of data save: (cb) -> deferred = Q.defer() data = _.extend {}, @toJSON() data[node_options.updated_at] = Date.now() if node_options.updated_at data[node_options.created_at] = Date.now() if node_options.created_at and not @_id? self = @ neoogm.cypher one: true query: if @_id "START n = node({id}) WHERE n:#{ node_label } SET n = {data} RETURN n" else "CREATE (n:#{ node_label } {data}) RETURN n" params: id: @_id data: data models: [ node_label ] , (err, item) -> if err cb? err return deferred.reject err self[key] = value for key, value of item cb? null, self deferred.resolve self deferred.promise remove: (cb) -> deferred = Q.defer() unless @_id err = new NeoormError "Node could not be deleted without a valid id" cb? err return deferred.reject err self = @ neoogm.cypher query: [ "START n = node({id})" "WHERE n:#{ node_label }" "DELETE n" ] params: id: @_id , (err, item) -> if err cb? err return deferred.reject err delete self._id cb? null, self deferred.resolve self deferred.promise # createOutgoing: (type, data, cb) -> # createIncoming: (type, data, cb) -> findOutgoing: (options, cb) -> [options, cb] = [type: options, cb] if typeof options is "string" @findRelates (_.extend {}, options, type: options.type, outgoing: true), cb findIncoming: (options, cb) -> [options, cb] = [type: options, cb] if typeof options is "string" @findRelates (_.extend {}, options, type: options.type, incoming: true), cb findRelates: (options, cb) -> [options, cb] = [type: options, cb] if typeof options is "string" throw new NeoormError "Relationship type not defined" unless options.type (neoogm.relationship options.type).findRelates (_.extend {}, options, model: @), cb getId: -> @_id getLabel: -> node_label toJSON: -> ## FIX ME: validate model everywhere ensureValidModel @, node_options @create: (data, cb) -> [data, cb] = [{}, data] if typeof data is "function" deferred = Q.defer() neoogm.cypher query: [ "CREATE (n:#{ node_label } {data})" "RETURN n" ] params: data: data models: [ node_label ] , (err, items) -> if err cb? err return deferred.reject err cb? err, items deferred.resolve items deferred.promise @update: (options, cb) -> deferred = Q.defer() options = _.extend query: null params: {} data: {} , options if options.query instanceof Array options.query = options.query.join " " else if typeof options.query is "object" options.params[key] = value for key, value of options.query options.query = (" n.#{key} = {#{key}} " for key, value of options.query).join " AND " query_update = (" n.#{key} = {#{key}} " for key, value of options.data).join ", " neoogm.cypher query: [ "MATCH (n:#{ node_label })" if options.query then "WHERE #{ options.query }" else "" "SET #{ query_update }" "RETURN n" ] params: options.params models: [ node_label ] , (err, items) -> if err cb? err return deferred.reject err cb? err, items deferred.resolve items deferred.promise @delete: (options, cb) -> deferred = Q.defer() self = @ async.waterfall [ (cb) -> self.find options, cb (items, cb) -> return cb null, items unless items.length query_where = ("ID(n) = #{ id }" for id in _.pluck items, "_id").join " OR " neoogm.cypher "START n=node(*) WHERE n:User AND (#{ query_where }) DELETE n", (err) -> cb err, items ], (err, items) -> if err cb? err return deferred.reject err cb? err, items deferred.resolve items deferred.promise @findById: (id, cb) -> [id, cb] = [null, id] if typeof id is "function" deferred = Q.defer() unless id? err = new NeoormError "Node id not defined" cb? err return deferred.reject err neoogm.cypher query: [ "START n = node({id})" "WHERE n:#{ node_label }" "RETURN n" ] params: id: id models: [ node_label ] one: true , (err, items) -> if err cb? err return deferred.reject err cb? err, items deferred.resolve items deferred.promise @findByIdAndRemove: (id, cb) -> [id, cb] = [null, id] if typeof id is "function" deferred = Q.defer() unless id? err = new NeoormError "Node id not defined" cb? err return deferred.reject err self = @ async.waterfall [ (cb) -> self.findById id, cb (item, cb) -> item.remove cb ], (err, items) -> if err cb? err return deferred.reject err cb? err, items deferred.resolve items deferred.promise @findByIdAndUpdate: (id, data, cb) -> [data, cb] = [{}, id] if typeof data is "function" deferred = Q.defer() data = _.extend {}, data data[node_options.updated_at] = Date.now() if node_options.updated_at query_update = (" n.#{key} = {#{key}} " for key, value of data).join ", " neoogm.cypher query: [ "START n = node({id})" "WHERE n:#{ node_label }" "SET #{ query_update }" "RETURN n" ] params: _.extend data, id: id models: [ node_label ] one: true , (err, items) -> if err cb? err return deferred.reject err cb? err, items deferred.resolve items deferred.promise @find: (options, cb) -> [options, cb] = [{}, options] if typeof options is "function" deferred = Q.defer() options = _.extend query: null params: {} , options if options.query instanceof Array options.query = options.query.join " " else if typeof options.query is "object" options.params[key] = value for key, value of options.query options.query = (" n.#{key} = {#{key}} " for key, value of options.query).join " AND " neoogm.cypher query: [ "MATCH (n:#{ node_label })" "WHERE #{ options.query }" "RETURN n" ] params: options.params models: [ node_label ] , (err, items) -> if err cb? err return deferred.reject err cb? err, items deferred.resolve items deferred.promise neoogm.relationship = (relationship_type, relationship_options=false) -> relationship_type = relationship_type.trim() return throw new Error "Relationship model \"#{ relationship_type }\" not defined" if not models.relationship[relationship_type] and not relationship_options return models.relationship[relationship_type] unless relationship_options return throw new Error "Relationship model \"#{ relationship_type }\" already defined" if models.relationship[relationship_type] relationship_options = _.extend models.options, globals.relationship, relationship_options for key in ["<KEY>", "updated_<KEY>"] when relationship_options[key] relationship_options[key] = if relationship_options[key] is true then key else relationship_options[key] relationship_options.schema[relationship_options[key]] = Date.now models.relationship[relationship_type] = class constructor: (data={}) -> @[name] = value for name, value of data save: (cb) -> deferred = Q.defer() data = _.extend {}, @toJSON() data[relationship_options.updated_at] = Date.now() if relationship_options.updated_at data[relationship_options.created_at] = Date.now() if relationship_options.created_at and not @_id? unless @_start? err = new NeoormError "Start node not defined" cb? err return deferred.reject err unless @_end? err = new NeoormError "End node not defined" cb? err return deferred.reject err self = @ async.waterfall [ (cb) -> cb null, if self._id then self (item, cb) -> return cb null, item if item # Id not found neoogm.cypher one: true query: [ "START start = node({start}), end = node({end})" "MATCH (start) -[relationship:#{ relationship_type }]-> (end)" "RETURN relationship" ] params: start: self._start end: self._end models: [ relationship_type ] , -> cb? arguments... (item, cb) -> return cb null, item unless item?._id # Relationship already exists data[relationship_options.created_at] = item[relationship_options.created_at] if relationship_options.created_at neoogm.cypher one: true query: [ "START relationship = relationship({id})" "WHERE TYPE(relationship) = {type}" "SET relationship = {data}" "RETURN relationship" ] params: id: item._id type: relationship_type data: data models: [ relationship_type ] , -> cb? arguments... (item, cb) -> return cb null, item if item?._id # Relationship not found neoogm.cypher one: true query: [ "START start = node({start}), end = node({end})" "CREATE (start) -[relationship:#{ relationship_type } {data}]-> (end)" "RETURN relationship" ] params: start: self._start end: self._end data: data models: [ relationship_type ] , -> cb? arguments... ], (err, item) -> if err cb? err return deferred.reject err self[key] = value for key, value of item cb? null, self deferred.resolve self deferred.promise remove: (cb) -> deferred = Q.defer() unless @_id err = new NeoormError "Relationship could not be deleted without a valid id" cb? err return deferred.reject err self = @ neoogm.cypher query: [ "START relationship = relationship({id})" "WHERE TYPE(relationship) = {type}" "DELETE relationship" ] params: id: @_id type: relationship_type , (err, item) -> if err cb? err return deferred.reject err delete self._id delete self._start delete self._end cb? null, self deferred.resolve results deferred.promise getId: -> @_id getType: -> relationship_type getStart: (cb) -> deferred = Q.defer() self = @ async.waterfall [ (cb) -> return cb null, self._start if self._start?._id? neoogm.findNodeById self._start, cb ], (err, item) -> if err cb? err return deferred.reject err self._start = item cb? null, item deferred.resolve item deferred.promise getEnd: (cb) -> deferred = Q.defer() self = @ async.waterfall [ (cb) -> return cb null, self._end if self._end?._id? neoogm.findNodeById self._end, cb ], (err, item) -> if err cb? err return deferred.reject err self._end = item cb? null, item deferred.resolve item deferred.promise toJSON: -> ensureValidModel @, relationship_options @findOutgoing: (options, cb) -> [options, cb] = [{}, options] if typeof options is "function" @findRelates (_.extend {}, options, outgoing: true), cb @findIncoming: (options, cb) -> [options, cb] = [{}, options] if typeof options is "function" @findRelates (_.extend {}, options, incoming: true), cb @findRelates: (options, cb) -> [options, cb] = [{}, options] if typeof options is "function" deferred = Q.defer() options = _.extend model: null outgoing: false incoming: false query: null params: {} , options unless model_label = options.model?.getLabel?() err = new NeoormError "options.model have to be an Neoorm model" cb? err return deferred.reject err unless options.model?.getId?()? err = new NeoormError "options.model is not an database reference" cb? err return deferred.reject err if options.query instanceof Array options.query = options.query.join " " else if typeof options.query is "object" options.params[key] = value for key, value of options.query options.query = (" n.#{key} = {#{key}} " for key, value of options.query).join " AND " neoogm.cypher query: [ "START target = node({id})" "MATCH " "(target:#{ model_label }) #{ if options.incoming and not options.outgoing then '<' else '' }-" " [relationship:#{ relationship_type }] " "-#{ if options.outgoing and not options.incoming then '>' else '' } (end)" if options.query then "WHERE #{ options.query }" else "" "RETURN relationship, end, LABELS(end) AS end_labels" ] params: id: options.model.getId() models: [ relationship_type, "=end_labels", false ] , (err, results) -> if err cb? err return deferred.reject err results = _.map results, (row, row_i) -> row.start = options.model row cb? err, results deferred.resolve results deferred.promise # @create: () -> # @update: () -> # @delete: () -> # # Helpers parseCypherId = (path) -> parseInt (path.match /([\d]+)$/)[1] parseInputId = (data) -> if data?._id? then parseInt data._id else data ensureValidModel = (model, options) -> keys = _.union (key for key of options.schema), (key for key, value of model when model.hasOwnProperty key) _.transform keys, (out, key) -> out[key] = model[key] if model[key]? and key isnt "_id" and (options.strict is false or (options.strict is true and options.schema?[key])) module.exports = neoogm
true
request = require "request" async = require "async" _ = require "lodash" Q = require "q" # # Globals globals = host: "localhost" port: 7474 secure: false merge: true node: created_at: false updated_at: false relationship: created_at: false updated_at: false models = node: {} relationship: {} options: schema: {} strict: true created_at: false updated_at: false NeoormError = class extends Error constructor: (data) -> @name = "Neoorm#{ if data?.exception? then data?.exception else '' }" @message = if data?.message? then data.message else data @original = data # # Public neoogm = -> neoogm.cypher arguments neoogm.config = (options) -> globals = _.extend {}, globals, options globals.url = "http#{ if globals.secure then 's' else '' }://#{ globals.host or 'localhost' }:#{ globals.port or 7474 }/db/data/cypher" neoogm neoogm.cypher = (options, cb) -> deferred = Q.defer() options = _.extend one: false query: "" params: {} models: [] , if typeof options is "object" options else if options instanceof Array query: options.join " " else query: options options.query = options.query.join " " if options.query instanceof Array options.query += " LIMIT 1" if options.one and not options.query.match /LIMIT\s+([\d+])/ options.params._id = parseInputId options.params._id if options.params?._id? options.params._start = parseInputId options.params._start if options.params?._start? options.params._end = parseInputId options.params._end if options.params?._end? request url: globals.url method: "POST" headers: "Accept": "application/json; charset=UTF-8" "Content-Type": "application/json" "X-Stream": "true" json: query: options.query params: options.params , (err, res, body) -> err = body if res and res?.statusCode isnt 200 if err err = new NeoormError err cb? err return deferred.reject err output_columns = [] model_remaps = [] for name, i in options.models output_columns.push body.columns[i] if name?[0] is "=" model_remaps.push item: body.columns[i] labels: name[1..] else if name is false output_columns.pop() model_remaps.push item: body.columns[i] remove: true data = _.map body.data, (row, row_i) -> # Convert array elements to objects rows = _.transform row, (out, row, col_i) -> entity = if row?.type? then "relationship" else if row?.data? then "node" else false row = switch entity when "relationship" _.extend {}, row.data, _id: parseCypherId row.self _start: parseCypherId row.start _end: parseCypherId row.end _type: row.type when "node" _.extend {}, row.data, _id: parseCypherId row.self else row out[body.columns[col_i]] = if entity and klass = models[entity][options.models?[col_i]] new klass row else row # Remap objects for rule in model_remaps if rule.labels for model in rows[rule.labels] if klass = models.node[model] or klass = models.relationship[model] rows[rule.item] = new klass rows[rule.item] break else if rule.remove is true delete rows[rule.item] # Only one item if output_columns.length and output_columns.length > 1 then rows else rows[output_columns[0]] data = if options.one then data[0] else data cb? null, data deferred.resolve data deferred.promise neoogm.findNodeById = (id, cb) -> neoogm.cypher one: true query: [ "START node = node({id})" "RETURN node, LABELS(node) AS node_labels" ] params: id: id models: [ "=node_labels", false ] , cb neoogm.findRelationshipById = (id, cb) -> neoogm.cypher one: true query: [ "START relationship = relationship({id})" "RETURN relationship, [TYPE(relationship)] AS relationship_type" ] params: id: id models: [ "=relationship_type", false ] , cb neoogm.node = (node_label, node_options=false) -> node_label = node_label.trim() return throw new Error "Node model \"#{ node_label }\" not defined" if not models.node[node_label] and not node_options return models.node[node_label] unless node_options return throw new Error "Node model \"#{ node_label }\" already defined" if models.node[node_label] node_options = _.extend models.options, globals.node, node_options for key in ["created_at", "updated_at"] when node_options[key] node_options[key] = if node_options[key] is true then key else node_options[key] node_options.schema[node_options[key]] = Date.now models.node[node_label] = class constructor: (data={}) -> @[name] = value for name, value of data save: (cb) -> deferred = Q.defer() data = _.extend {}, @toJSON() data[node_options.updated_at] = Date.now() if node_options.updated_at data[node_options.created_at] = Date.now() if node_options.created_at and not @_id? self = @ neoogm.cypher one: true query: if @_id "START n = node({id}) WHERE n:#{ node_label } SET n = {data} RETURN n" else "CREATE (n:#{ node_label } {data}) RETURN n" params: id: @_id data: data models: [ node_label ] , (err, item) -> if err cb? err return deferred.reject err self[key] = value for key, value of item cb? null, self deferred.resolve self deferred.promise remove: (cb) -> deferred = Q.defer() unless @_id err = new NeoormError "Node could not be deleted without a valid id" cb? err return deferred.reject err self = @ neoogm.cypher query: [ "START n = node({id})" "WHERE n:#{ node_label }" "DELETE n" ] params: id: @_id , (err, item) -> if err cb? err return deferred.reject err delete self._id cb? null, self deferred.resolve self deferred.promise # createOutgoing: (type, data, cb) -> # createIncoming: (type, data, cb) -> findOutgoing: (options, cb) -> [options, cb] = [type: options, cb] if typeof options is "string" @findRelates (_.extend {}, options, type: options.type, outgoing: true), cb findIncoming: (options, cb) -> [options, cb] = [type: options, cb] if typeof options is "string" @findRelates (_.extend {}, options, type: options.type, incoming: true), cb findRelates: (options, cb) -> [options, cb] = [type: options, cb] if typeof options is "string" throw new NeoormError "Relationship type not defined" unless options.type (neoogm.relationship options.type).findRelates (_.extend {}, options, model: @), cb getId: -> @_id getLabel: -> node_label toJSON: -> ## FIX ME: validate model everywhere ensureValidModel @, node_options @create: (data, cb) -> [data, cb] = [{}, data] if typeof data is "function" deferred = Q.defer() neoogm.cypher query: [ "CREATE (n:#{ node_label } {data})" "RETURN n" ] params: data: data models: [ node_label ] , (err, items) -> if err cb? err return deferred.reject err cb? err, items deferred.resolve items deferred.promise @update: (options, cb) -> deferred = Q.defer() options = _.extend query: null params: {} data: {} , options if options.query instanceof Array options.query = options.query.join " " else if typeof options.query is "object" options.params[key] = value for key, value of options.query options.query = (" n.#{key} = {#{key}} " for key, value of options.query).join " AND " query_update = (" n.#{key} = {#{key}} " for key, value of options.data).join ", " neoogm.cypher query: [ "MATCH (n:#{ node_label })" if options.query then "WHERE #{ options.query }" else "" "SET #{ query_update }" "RETURN n" ] params: options.params models: [ node_label ] , (err, items) -> if err cb? err return deferred.reject err cb? err, items deferred.resolve items deferred.promise @delete: (options, cb) -> deferred = Q.defer() self = @ async.waterfall [ (cb) -> self.find options, cb (items, cb) -> return cb null, items unless items.length query_where = ("ID(n) = #{ id }" for id in _.pluck items, "_id").join " OR " neoogm.cypher "START n=node(*) WHERE n:User AND (#{ query_where }) DELETE n", (err) -> cb err, items ], (err, items) -> if err cb? err return deferred.reject err cb? err, items deferred.resolve items deferred.promise @findById: (id, cb) -> [id, cb] = [null, id] if typeof id is "function" deferred = Q.defer() unless id? err = new NeoormError "Node id not defined" cb? err return deferred.reject err neoogm.cypher query: [ "START n = node({id})" "WHERE n:#{ node_label }" "RETURN n" ] params: id: id models: [ node_label ] one: true , (err, items) -> if err cb? err return deferred.reject err cb? err, items deferred.resolve items deferred.promise @findByIdAndRemove: (id, cb) -> [id, cb] = [null, id] if typeof id is "function" deferred = Q.defer() unless id? err = new NeoormError "Node id not defined" cb? err return deferred.reject err self = @ async.waterfall [ (cb) -> self.findById id, cb (item, cb) -> item.remove cb ], (err, items) -> if err cb? err return deferred.reject err cb? err, items deferred.resolve items deferred.promise @findByIdAndUpdate: (id, data, cb) -> [data, cb] = [{}, id] if typeof data is "function" deferred = Q.defer() data = _.extend {}, data data[node_options.updated_at] = Date.now() if node_options.updated_at query_update = (" n.#{key} = {#{key}} " for key, value of data).join ", " neoogm.cypher query: [ "START n = node({id})" "WHERE n:#{ node_label }" "SET #{ query_update }" "RETURN n" ] params: _.extend data, id: id models: [ node_label ] one: true , (err, items) -> if err cb? err return deferred.reject err cb? err, items deferred.resolve items deferred.promise @find: (options, cb) -> [options, cb] = [{}, options] if typeof options is "function" deferred = Q.defer() options = _.extend query: null params: {} , options if options.query instanceof Array options.query = options.query.join " " else if typeof options.query is "object" options.params[key] = value for key, value of options.query options.query = (" n.#{key} = {#{key}} " for key, value of options.query).join " AND " neoogm.cypher query: [ "MATCH (n:#{ node_label })" "WHERE #{ options.query }" "RETURN n" ] params: options.params models: [ node_label ] , (err, items) -> if err cb? err return deferred.reject err cb? err, items deferred.resolve items deferred.promise neoogm.relationship = (relationship_type, relationship_options=false) -> relationship_type = relationship_type.trim() return throw new Error "Relationship model \"#{ relationship_type }\" not defined" if not models.relationship[relationship_type] and not relationship_options return models.relationship[relationship_type] unless relationship_options return throw new Error "Relationship model \"#{ relationship_type }\" already defined" if models.relationship[relationship_type] relationship_options = _.extend models.options, globals.relationship, relationship_options for key in ["PI:KEY:<KEY>END_PI", "updated_PI:KEY:<KEY>END_PI"] when relationship_options[key] relationship_options[key] = if relationship_options[key] is true then key else relationship_options[key] relationship_options.schema[relationship_options[key]] = Date.now models.relationship[relationship_type] = class constructor: (data={}) -> @[name] = value for name, value of data save: (cb) -> deferred = Q.defer() data = _.extend {}, @toJSON() data[relationship_options.updated_at] = Date.now() if relationship_options.updated_at data[relationship_options.created_at] = Date.now() if relationship_options.created_at and not @_id? unless @_start? err = new NeoormError "Start node not defined" cb? err return deferred.reject err unless @_end? err = new NeoormError "End node not defined" cb? err return deferred.reject err self = @ async.waterfall [ (cb) -> cb null, if self._id then self (item, cb) -> return cb null, item if item # Id not found neoogm.cypher one: true query: [ "START start = node({start}), end = node({end})" "MATCH (start) -[relationship:#{ relationship_type }]-> (end)" "RETURN relationship" ] params: start: self._start end: self._end models: [ relationship_type ] , -> cb? arguments... (item, cb) -> return cb null, item unless item?._id # Relationship already exists data[relationship_options.created_at] = item[relationship_options.created_at] if relationship_options.created_at neoogm.cypher one: true query: [ "START relationship = relationship({id})" "WHERE TYPE(relationship) = {type}" "SET relationship = {data}" "RETURN relationship" ] params: id: item._id type: relationship_type data: data models: [ relationship_type ] , -> cb? arguments... (item, cb) -> return cb null, item if item?._id # Relationship not found neoogm.cypher one: true query: [ "START start = node({start}), end = node({end})" "CREATE (start) -[relationship:#{ relationship_type } {data}]-> (end)" "RETURN relationship" ] params: start: self._start end: self._end data: data models: [ relationship_type ] , -> cb? arguments... ], (err, item) -> if err cb? err return deferred.reject err self[key] = value for key, value of item cb? null, self deferred.resolve self deferred.promise remove: (cb) -> deferred = Q.defer() unless @_id err = new NeoormError "Relationship could not be deleted without a valid id" cb? err return deferred.reject err self = @ neoogm.cypher query: [ "START relationship = relationship({id})" "WHERE TYPE(relationship) = {type}" "DELETE relationship" ] params: id: @_id type: relationship_type , (err, item) -> if err cb? err return deferred.reject err delete self._id delete self._start delete self._end cb? null, self deferred.resolve results deferred.promise getId: -> @_id getType: -> relationship_type getStart: (cb) -> deferred = Q.defer() self = @ async.waterfall [ (cb) -> return cb null, self._start if self._start?._id? neoogm.findNodeById self._start, cb ], (err, item) -> if err cb? err return deferred.reject err self._start = item cb? null, item deferred.resolve item deferred.promise getEnd: (cb) -> deferred = Q.defer() self = @ async.waterfall [ (cb) -> return cb null, self._end if self._end?._id? neoogm.findNodeById self._end, cb ], (err, item) -> if err cb? err return deferred.reject err self._end = item cb? null, item deferred.resolve item deferred.promise toJSON: -> ensureValidModel @, relationship_options @findOutgoing: (options, cb) -> [options, cb] = [{}, options] if typeof options is "function" @findRelates (_.extend {}, options, outgoing: true), cb @findIncoming: (options, cb) -> [options, cb] = [{}, options] if typeof options is "function" @findRelates (_.extend {}, options, incoming: true), cb @findRelates: (options, cb) -> [options, cb] = [{}, options] if typeof options is "function" deferred = Q.defer() options = _.extend model: null outgoing: false incoming: false query: null params: {} , options unless model_label = options.model?.getLabel?() err = new NeoormError "options.model have to be an Neoorm model" cb? err return deferred.reject err unless options.model?.getId?()? err = new NeoormError "options.model is not an database reference" cb? err return deferred.reject err if options.query instanceof Array options.query = options.query.join " " else if typeof options.query is "object" options.params[key] = value for key, value of options.query options.query = (" n.#{key} = {#{key}} " for key, value of options.query).join " AND " neoogm.cypher query: [ "START target = node({id})" "MATCH " "(target:#{ model_label }) #{ if options.incoming and not options.outgoing then '<' else '' }-" " [relationship:#{ relationship_type }] " "-#{ if options.outgoing and not options.incoming then '>' else '' } (end)" if options.query then "WHERE #{ options.query }" else "" "RETURN relationship, end, LABELS(end) AS end_labels" ] params: id: options.model.getId() models: [ relationship_type, "=end_labels", false ] , (err, results) -> if err cb? err return deferred.reject err results = _.map results, (row, row_i) -> row.start = options.model row cb? err, results deferred.resolve results deferred.promise # @create: () -> # @update: () -> # @delete: () -> # # Helpers parseCypherId = (path) -> parseInt (path.match /([\d]+)$/)[1] parseInputId = (data) -> if data?._id? then parseInt data._id else data ensureValidModel = (model, options) -> keys = _.union (key for key of options.schema), (key for key, value of model when model.hasOwnProperty key) _.transform keys, (out, key) -> out[key] = model[key] if model[key]? and key isnt "_id" and (options.strict is false or (options.strict is true and options.schema?[key])) module.exports = neoogm
[ { "context": "r to the game the player is currently in\n name: \"Unnamed\"\n race: null\n team: 0\n isBot: false\n token: n", "end": 602, "score": 0.967689573764801, "start": 595, "tag": "NAME", "value": "Unnamed" }, { "context": "\n @socket = null\n @game = null\n @name = \"Unnamed\"\n @race = null\n @team = 0\n @isBot = fals", "end": 1543, "score": 0.9447908401489258, "start": 1536, "tag": "NAME", "value": "Unnamed" }, { "context": " then callback(err, null)\n @name = user.get('username')\n @log.info \"Calling back with new name\", {", "end": 4799, "score": 0.977266252040863, "start": 4791, "tag": "USERNAME", "value": "username" } ]
gameserver/lib/player.coffee
towerstorm/game
11
### * * This class controls all the player details like their socket and stats * ### netMsg = require 'config/net-messages' config = require 'config/general' gameMsg = require 'config/game-messages' bulkLoad = require("config/bulk-load") minionConfig = bulkLoad("minions") tdb = require('../../database') rs = require 'randomstring' serverConfig = require 'config/gameserver' User = tdb.models.User log = require('logger') _ = require("lodash"); oberr = require("oberr"); class Player id: null socket: null game: null #A pointer to the game the player is currently in name: "Unnamed" race: null team: 0 isBot: false token: null state: config.states.none disconnected: false; currentTick: 0; oldestUnconfirmedTick: 0; #Keep track of the oldest tick was confirmed so we don't send too many ticks in advance (queues them instead) tickSendQueue: {} #We don't want to have more than 10 pending ticks to the player at a time so if they lag they don't get tick spammed. tickConfirmsToCheck: {} #Tick ID's that have yet to be confirmed by the player, resend them until they have been sent. lastConfirmDelays: [] #Number of ticks to confirm for the last 10 ticks so that we can average it out and only send unconfirmed ticks after this much time has passed ping: 0 ready: false loaded: false log: null gameLog: null lastAction: null constructor: () -> @log = log @reset() @state = config.states.init; reset: -> @socket = null @game = null @name = "Unnamed" @race = null @team = 0 @isBot = false @token = null @state = config.states.none @disconnected = false @currentTick = 0 @oldestUnconfirmedTick = 0 @tickSendQueue = {} @tickConfirmsToCheck = {} @lastConfirmDelays = [] @ping = 0 @ready = false @loaded = false ### * Return basic player details in an object ### getDetails: => { @id, @name, @race, @minions } sendDetails: => playerDetails = @getDetails() if @game.get('state') == config.states.begun playerDetails.sync = true @socket.emit netMsg.player.details, playerDetails setState: (state) => @state = state; isLoaded: => return @state == config.states.begun; init: (@id) => @bindFunctions() setSocket: (socket) => if @socket delete @socket @socket = socket; joinGame: (@game) => @log = new (log.Logger)({ transports: log.getCustomTransports('gameserver', [@game.get("code")]) }) @log.info("Player joining game") @disconnected = false; @bindGameSockets(@game); @gameLog = new (log.Logger)({ transports: [new (log.transports.File)({ filename: serverConfig.logDir + '/game-logs-client/' + @game.code + '-' + @id + '.log', timestamp: false})] }) kick: () => if @disconnected return false @socket.emit netMsg.game.kicked syncData: () => @log.info("Sending syncdata to player") currentTick = @game.getCurrentTick() data = {} data.ticks = @game.getTicks() data.settings = @game.get('settings') data.playerId = @id data.players = @game.getPlayers() @log.info("Sending sync data: ", data); @log.info("Sending currnet tick: " + currentTick + " ticks: ", data.ticks); @socket.emit netMsg.game.syncData, currentTick, data setRace: (race) => @race = race return true setMinions: (minions) => @minions = @removeInvalidMinions(_.uniq(minions)) return true removeInvalidMinions: (minions) => return minions.filter((m) => return !!minionConfig[m]) getRace: => return @race setTeam: (team) => if isNaN(team) return false; @team = team return true getTeam: => return @team setIsBot: (isBot) => @isBot = isBot return true setReady: (ready) => @ready = ready return true setLoaded: (loaded) => @loaded = loaded return true # Closes player socket, though currently there is one player object for lobby and one for # each game when you join games. This will need to be fixed in the future when just the one # player object is thrown around with tokens. disconnect: => @log.info("Player " + @id + " is disconnecting") if @socket? @socket.disconnect() @disconnected = true bindFunctions: => if !@socket return false; socket = @socket playerId = @id lobbyPath = "/lobby" #Check if the players username has changed and if so set it to the new value reloadName: (callback) => @log.info("In reload name", {code: @game.code}) User.findById @id, (err, user) => @log.info("In reload name got user: ", user, {code: @game.code}) if err then callback(err, null) @name = user.get('username') @log.info "Calling back with new name", {code: @game.code} callback(null, @name) addConfirmTime: (sendTick, confirmTick) => if @lastConfirmDelays.length > 10 @lastConfirmDelays.splice 0, 1 confirmDelay = confirmTick - sendTick @lastConfirmDelays.push confirmDelay # @log.info "Adding confirm delay of sendTick: ", sendTick, "confirm tick: ", confirmTick, "delay", confirmDelay calculatePing: (averageDelayTime) => if !@game? return false if !averageDelayTime? averageDelayTime = @getResendDelay(); @ping = (averageDelayTime * @game.ts.Timer.constantStep) * 1000 sendPing: => @socket.emit netMsg.player.pingTime, @ping; sendTick: (tick, commandsDone) => if @disconnected return false # @log.info "Sending tick ", tick, " commands: ", commandsDone if serverConfig.addLag lag = Math.round(Math.random()*5000) setTimeout => @socket.emit netMsg.game.tickData, tick, commandsDone, (data) => , lag else @socket.emit netMsg.game.tickData, tick, commandsDone, (data) => checkHash: (tick, hash, callback) => if !@game? return false if @game.getMode() == "TUTORIAL" return callback(JSON.stringify({ok: true})) if @game.gameSnapshotHash[tick]? callbackObject = {ok: false} if hash != @game.gameSnapshotHash[tick] callbackObject.ok = false @game.reportInvalidState(tick) @log.info("Hash Incorrect for player ", @id) else callbackObject.ok = true callback JSON.stringify(callbackObject) canPerformAction: => if @state != config.states.begun #Ignore placing towers when the game hasn't even behun yet. return false if @lastAction #Can't queue more than one action at once return false return true performAction: (type, data) => if !@canPerformAction() return false @lastAction = {type, data} placeTower: (xPos, yPos, towerType) => if (!towerType) then return console.error("User " + @id + " tried to place a tower without a type") @performAction('towers', {xPos, yPos, towerType, ownerId: @id}) upgradeTower: (settings) => @performAction('towerUpgrades', _.merge({}, settings, {ownerId: @id})); sellTower: (settings) => @performAction('towerSales', _.merge({}, settings, {ownerId: @id})); placeMinion: (xPos, yPos, minionType) => @performAction('minions', {xPos, yPos, ownerId: @id, minionType: minionType}); collectGem: (gemId) => @performAction('pickups', {id: gemId}) configure: (details, callback) => callback = callback || -> @log.info("Configuring player " + @id + " with details: " + JSON.stringify(details)) if !details? return callback(new Error("No details passed to configure")); if details.team? && !details.ready @setTeam details.team if details.race? && !@ready if @game.isRaceSelected(details.race, @getTeam()) return callback(new Error("That race is already selected")) if @game.get('state') != config.states.selection return callback(new Error("You cannot change your race now")) @setRace details.race if details.minions? && !@ready if details.minions.length > config.maxMinions return callback(new Error("You cannot select more than " + config.maxMinions + " minions")) @setMinions details.minions if details.isBot? @setIsBot details.isBot if details.ready? && @getRace() @setReady(true) @game.userReady() if details.loaded? @setLoaded details.loaded return callback(); bindGameSockets: (game) => if !@socket return false; @log.info("Binding player sockets") @game = game; @socket.on netMsg.game.configure, (details, callback) => @game.configure details, (success) => if callback? callback(success) @socket.on netMsg.player.log.debug, (message) => @gameLog.info(message) @log.info("Binding to message ", netMsg.player.refresh) @socket.on netMsg.player.refresh, (callback) => @log.info("Got Refresh message") @reloadName (err, newName) => game.broadcastDetails() if callback? callback(!err) ### * Rebinding this for game so the game can resend details * whenever a players details change ### @socket.on netMsg.player.configure, (details, callback) => callback = callback || -> @log.info("Configuring player #{@id} with details: ", details) @configure details, (err, result) => if err then return callback(oberr(err)) game.playerUpdated(@id, details); game.broadcastDetails(); return callback(); @socket.on netMsg.game.addBot, (details, callback) => lagAmount = if !serverConfig.addBotLag then 0 else Math.round(Math.random()*2000) setTimeout => @game.addBot(details, callback); , lagAmount @socket.on netMsg.game.configureBot, (details, callback) => @log.info "Configuring bot #{@id} with details: ", details success = @game.configureBot(@id, details) callback success return success @socket.on netMsg.game.kickPlayer, (playerId) => @log.info "Kicking player of id ", playerId success = @game.kickPlayer(@id, playerId) return success @socket.on netMsg.game.start, (details, callback) => game.startSelection(); callback "{ok: true}" @socket.on netMsg.player.finished, (winningTeam, lastTick) => @game.playerFinished(@id, winningTeam, lastTick) @socket.on netMsg.disconnect, => @disconnected = true game.playerDisconnected @ if game.get('state') == config.states.lobby game.deletePlayer @ @socket.on netMsg.player.loaded, (details, callback) => @log.info("Player #{@id} loaded") @setState config.states.begun game.checkPlayersAreLoaded() @configure {loaded: true}, (success) => game.broadcastDetails(); @socket.on netMsg.game.tickNeeded, (tick) => game.resendTick(tick, @) ### Checks all clients have the same game hash as the server every 100ms ### @socket.on netMsg.game.checkHash, (tick, hash, callback) => @checkHash(tick, hash, callback) @socket.on netMsg.game.placeTower, (xPos, yPos, towerType) => @placeTower(xPos, yPos, towerType) @socket.on netMsg.game.upgradeTower, (settings) => @upgradeTower(settings) @socket.on netMsg.game.sellTower, (settings) => @sellTower(settings) @socket.on netMsg.game.placeMinion, (xPos, yPos, minionType) => @placeMinion(xPos, yPos, minionType) @socket.on netMsg.game.collectGem, (gemId) => @collectGem(gemId) module.exports = Player
13926
### * * This class controls all the player details like their socket and stats * ### netMsg = require 'config/net-messages' config = require 'config/general' gameMsg = require 'config/game-messages' bulkLoad = require("config/bulk-load") minionConfig = bulkLoad("minions") tdb = require('../../database') rs = require 'randomstring' serverConfig = require 'config/gameserver' User = tdb.models.User log = require('logger') _ = require("lodash"); oberr = require("oberr"); class Player id: null socket: null game: null #A pointer to the game the player is currently in name: "<NAME>" race: null team: 0 isBot: false token: null state: config.states.none disconnected: false; currentTick: 0; oldestUnconfirmedTick: 0; #Keep track of the oldest tick was confirmed so we don't send too many ticks in advance (queues them instead) tickSendQueue: {} #We don't want to have more than 10 pending ticks to the player at a time so if they lag they don't get tick spammed. tickConfirmsToCheck: {} #Tick ID's that have yet to be confirmed by the player, resend them until they have been sent. lastConfirmDelays: [] #Number of ticks to confirm for the last 10 ticks so that we can average it out and only send unconfirmed ticks after this much time has passed ping: 0 ready: false loaded: false log: null gameLog: null lastAction: null constructor: () -> @log = log @reset() @state = config.states.init; reset: -> @socket = null @game = null @name = "<NAME>" @race = null @team = 0 @isBot = false @token = null @state = config.states.none @disconnected = false @currentTick = 0 @oldestUnconfirmedTick = 0 @tickSendQueue = {} @tickConfirmsToCheck = {} @lastConfirmDelays = [] @ping = 0 @ready = false @loaded = false ### * Return basic player details in an object ### getDetails: => { @id, @name, @race, @minions } sendDetails: => playerDetails = @getDetails() if @game.get('state') == config.states.begun playerDetails.sync = true @socket.emit netMsg.player.details, playerDetails setState: (state) => @state = state; isLoaded: => return @state == config.states.begun; init: (@id) => @bindFunctions() setSocket: (socket) => if @socket delete @socket @socket = socket; joinGame: (@game) => @log = new (log.Logger)({ transports: log.getCustomTransports('gameserver', [@game.get("code")]) }) @log.info("Player joining game") @disconnected = false; @bindGameSockets(@game); @gameLog = new (log.Logger)({ transports: [new (log.transports.File)({ filename: serverConfig.logDir + '/game-logs-client/' + @game.code + '-' + @id + '.log', timestamp: false})] }) kick: () => if @disconnected return false @socket.emit netMsg.game.kicked syncData: () => @log.info("Sending syncdata to player") currentTick = @game.getCurrentTick() data = {} data.ticks = @game.getTicks() data.settings = @game.get('settings') data.playerId = @id data.players = @game.getPlayers() @log.info("Sending sync data: ", data); @log.info("Sending currnet tick: " + currentTick + " ticks: ", data.ticks); @socket.emit netMsg.game.syncData, currentTick, data setRace: (race) => @race = race return true setMinions: (minions) => @minions = @removeInvalidMinions(_.uniq(minions)) return true removeInvalidMinions: (minions) => return minions.filter((m) => return !!minionConfig[m]) getRace: => return @race setTeam: (team) => if isNaN(team) return false; @team = team return true getTeam: => return @team setIsBot: (isBot) => @isBot = isBot return true setReady: (ready) => @ready = ready return true setLoaded: (loaded) => @loaded = loaded return true # Closes player socket, though currently there is one player object for lobby and one for # each game when you join games. This will need to be fixed in the future when just the one # player object is thrown around with tokens. disconnect: => @log.info("Player " + @id + " is disconnecting") if @socket? @socket.disconnect() @disconnected = true bindFunctions: => if !@socket return false; socket = @socket playerId = @id lobbyPath = "/lobby" #Check if the players username has changed and if so set it to the new value reloadName: (callback) => @log.info("In reload name", {code: @game.code}) User.findById @id, (err, user) => @log.info("In reload name got user: ", user, {code: @game.code}) if err then callback(err, null) @name = user.get('username') @log.info "Calling back with new name", {code: @game.code} callback(null, @name) addConfirmTime: (sendTick, confirmTick) => if @lastConfirmDelays.length > 10 @lastConfirmDelays.splice 0, 1 confirmDelay = confirmTick - sendTick @lastConfirmDelays.push confirmDelay # @log.info "Adding confirm delay of sendTick: ", sendTick, "confirm tick: ", confirmTick, "delay", confirmDelay calculatePing: (averageDelayTime) => if !@game? return false if !averageDelayTime? averageDelayTime = @getResendDelay(); @ping = (averageDelayTime * @game.ts.Timer.constantStep) * 1000 sendPing: => @socket.emit netMsg.player.pingTime, @ping; sendTick: (tick, commandsDone) => if @disconnected return false # @log.info "Sending tick ", tick, " commands: ", commandsDone if serverConfig.addLag lag = Math.round(Math.random()*5000) setTimeout => @socket.emit netMsg.game.tickData, tick, commandsDone, (data) => , lag else @socket.emit netMsg.game.tickData, tick, commandsDone, (data) => checkHash: (tick, hash, callback) => if !@game? return false if @game.getMode() == "TUTORIAL" return callback(JSON.stringify({ok: true})) if @game.gameSnapshotHash[tick]? callbackObject = {ok: false} if hash != @game.gameSnapshotHash[tick] callbackObject.ok = false @game.reportInvalidState(tick) @log.info("Hash Incorrect for player ", @id) else callbackObject.ok = true callback JSON.stringify(callbackObject) canPerformAction: => if @state != config.states.begun #Ignore placing towers when the game hasn't even behun yet. return false if @lastAction #Can't queue more than one action at once return false return true performAction: (type, data) => if !@canPerformAction() return false @lastAction = {type, data} placeTower: (xPos, yPos, towerType) => if (!towerType) then return console.error("User " + @id + " tried to place a tower without a type") @performAction('towers', {xPos, yPos, towerType, ownerId: @id}) upgradeTower: (settings) => @performAction('towerUpgrades', _.merge({}, settings, {ownerId: @id})); sellTower: (settings) => @performAction('towerSales', _.merge({}, settings, {ownerId: @id})); placeMinion: (xPos, yPos, minionType) => @performAction('minions', {xPos, yPos, ownerId: @id, minionType: minionType}); collectGem: (gemId) => @performAction('pickups', {id: gemId}) configure: (details, callback) => callback = callback || -> @log.info("Configuring player " + @id + " with details: " + JSON.stringify(details)) if !details? return callback(new Error("No details passed to configure")); if details.team? && !details.ready @setTeam details.team if details.race? && !@ready if @game.isRaceSelected(details.race, @getTeam()) return callback(new Error("That race is already selected")) if @game.get('state') != config.states.selection return callback(new Error("You cannot change your race now")) @setRace details.race if details.minions? && !@ready if details.minions.length > config.maxMinions return callback(new Error("You cannot select more than " + config.maxMinions + " minions")) @setMinions details.minions if details.isBot? @setIsBot details.isBot if details.ready? && @getRace() @setReady(true) @game.userReady() if details.loaded? @setLoaded details.loaded return callback(); bindGameSockets: (game) => if !@socket return false; @log.info("Binding player sockets") @game = game; @socket.on netMsg.game.configure, (details, callback) => @game.configure details, (success) => if callback? callback(success) @socket.on netMsg.player.log.debug, (message) => @gameLog.info(message) @log.info("Binding to message ", netMsg.player.refresh) @socket.on netMsg.player.refresh, (callback) => @log.info("Got Refresh message") @reloadName (err, newName) => game.broadcastDetails() if callback? callback(!err) ### * Rebinding this for game so the game can resend details * whenever a players details change ### @socket.on netMsg.player.configure, (details, callback) => callback = callback || -> @log.info("Configuring player #{@id} with details: ", details) @configure details, (err, result) => if err then return callback(oberr(err)) game.playerUpdated(@id, details); game.broadcastDetails(); return callback(); @socket.on netMsg.game.addBot, (details, callback) => lagAmount = if !serverConfig.addBotLag then 0 else Math.round(Math.random()*2000) setTimeout => @game.addBot(details, callback); , lagAmount @socket.on netMsg.game.configureBot, (details, callback) => @log.info "Configuring bot #{@id} with details: ", details success = @game.configureBot(@id, details) callback success return success @socket.on netMsg.game.kickPlayer, (playerId) => @log.info "Kicking player of id ", playerId success = @game.kickPlayer(@id, playerId) return success @socket.on netMsg.game.start, (details, callback) => game.startSelection(); callback "{ok: true}" @socket.on netMsg.player.finished, (winningTeam, lastTick) => @game.playerFinished(@id, winningTeam, lastTick) @socket.on netMsg.disconnect, => @disconnected = true game.playerDisconnected @ if game.get('state') == config.states.lobby game.deletePlayer @ @socket.on netMsg.player.loaded, (details, callback) => @log.info("Player #{@id} loaded") @setState config.states.begun game.checkPlayersAreLoaded() @configure {loaded: true}, (success) => game.broadcastDetails(); @socket.on netMsg.game.tickNeeded, (tick) => game.resendTick(tick, @) ### Checks all clients have the same game hash as the server every 100ms ### @socket.on netMsg.game.checkHash, (tick, hash, callback) => @checkHash(tick, hash, callback) @socket.on netMsg.game.placeTower, (xPos, yPos, towerType) => @placeTower(xPos, yPos, towerType) @socket.on netMsg.game.upgradeTower, (settings) => @upgradeTower(settings) @socket.on netMsg.game.sellTower, (settings) => @sellTower(settings) @socket.on netMsg.game.placeMinion, (xPos, yPos, minionType) => @placeMinion(xPos, yPos, minionType) @socket.on netMsg.game.collectGem, (gemId) => @collectGem(gemId) module.exports = Player
true
### * * This class controls all the player details like their socket and stats * ### netMsg = require 'config/net-messages' config = require 'config/general' gameMsg = require 'config/game-messages' bulkLoad = require("config/bulk-load") minionConfig = bulkLoad("minions") tdb = require('../../database') rs = require 'randomstring' serverConfig = require 'config/gameserver' User = tdb.models.User log = require('logger') _ = require("lodash"); oberr = require("oberr"); class Player id: null socket: null game: null #A pointer to the game the player is currently in name: "PI:NAME:<NAME>END_PI" race: null team: 0 isBot: false token: null state: config.states.none disconnected: false; currentTick: 0; oldestUnconfirmedTick: 0; #Keep track of the oldest tick was confirmed so we don't send too many ticks in advance (queues them instead) tickSendQueue: {} #We don't want to have more than 10 pending ticks to the player at a time so if they lag they don't get tick spammed. tickConfirmsToCheck: {} #Tick ID's that have yet to be confirmed by the player, resend them until they have been sent. lastConfirmDelays: [] #Number of ticks to confirm for the last 10 ticks so that we can average it out and only send unconfirmed ticks after this much time has passed ping: 0 ready: false loaded: false log: null gameLog: null lastAction: null constructor: () -> @log = log @reset() @state = config.states.init; reset: -> @socket = null @game = null @name = "PI:NAME:<NAME>END_PI" @race = null @team = 0 @isBot = false @token = null @state = config.states.none @disconnected = false @currentTick = 0 @oldestUnconfirmedTick = 0 @tickSendQueue = {} @tickConfirmsToCheck = {} @lastConfirmDelays = [] @ping = 0 @ready = false @loaded = false ### * Return basic player details in an object ### getDetails: => { @id, @name, @race, @minions } sendDetails: => playerDetails = @getDetails() if @game.get('state') == config.states.begun playerDetails.sync = true @socket.emit netMsg.player.details, playerDetails setState: (state) => @state = state; isLoaded: => return @state == config.states.begun; init: (@id) => @bindFunctions() setSocket: (socket) => if @socket delete @socket @socket = socket; joinGame: (@game) => @log = new (log.Logger)({ transports: log.getCustomTransports('gameserver', [@game.get("code")]) }) @log.info("Player joining game") @disconnected = false; @bindGameSockets(@game); @gameLog = new (log.Logger)({ transports: [new (log.transports.File)({ filename: serverConfig.logDir + '/game-logs-client/' + @game.code + '-' + @id + '.log', timestamp: false})] }) kick: () => if @disconnected return false @socket.emit netMsg.game.kicked syncData: () => @log.info("Sending syncdata to player") currentTick = @game.getCurrentTick() data = {} data.ticks = @game.getTicks() data.settings = @game.get('settings') data.playerId = @id data.players = @game.getPlayers() @log.info("Sending sync data: ", data); @log.info("Sending currnet tick: " + currentTick + " ticks: ", data.ticks); @socket.emit netMsg.game.syncData, currentTick, data setRace: (race) => @race = race return true setMinions: (minions) => @minions = @removeInvalidMinions(_.uniq(minions)) return true removeInvalidMinions: (minions) => return minions.filter((m) => return !!minionConfig[m]) getRace: => return @race setTeam: (team) => if isNaN(team) return false; @team = team return true getTeam: => return @team setIsBot: (isBot) => @isBot = isBot return true setReady: (ready) => @ready = ready return true setLoaded: (loaded) => @loaded = loaded return true # Closes player socket, though currently there is one player object for lobby and one for # each game when you join games. This will need to be fixed in the future when just the one # player object is thrown around with tokens. disconnect: => @log.info("Player " + @id + " is disconnecting") if @socket? @socket.disconnect() @disconnected = true bindFunctions: => if !@socket return false; socket = @socket playerId = @id lobbyPath = "/lobby" #Check if the players username has changed and if so set it to the new value reloadName: (callback) => @log.info("In reload name", {code: @game.code}) User.findById @id, (err, user) => @log.info("In reload name got user: ", user, {code: @game.code}) if err then callback(err, null) @name = user.get('username') @log.info "Calling back with new name", {code: @game.code} callback(null, @name) addConfirmTime: (sendTick, confirmTick) => if @lastConfirmDelays.length > 10 @lastConfirmDelays.splice 0, 1 confirmDelay = confirmTick - sendTick @lastConfirmDelays.push confirmDelay # @log.info "Adding confirm delay of sendTick: ", sendTick, "confirm tick: ", confirmTick, "delay", confirmDelay calculatePing: (averageDelayTime) => if !@game? return false if !averageDelayTime? averageDelayTime = @getResendDelay(); @ping = (averageDelayTime * @game.ts.Timer.constantStep) * 1000 sendPing: => @socket.emit netMsg.player.pingTime, @ping; sendTick: (tick, commandsDone) => if @disconnected return false # @log.info "Sending tick ", tick, " commands: ", commandsDone if serverConfig.addLag lag = Math.round(Math.random()*5000) setTimeout => @socket.emit netMsg.game.tickData, tick, commandsDone, (data) => , lag else @socket.emit netMsg.game.tickData, tick, commandsDone, (data) => checkHash: (tick, hash, callback) => if !@game? return false if @game.getMode() == "TUTORIAL" return callback(JSON.stringify({ok: true})) if @game.gameSnapshotHash[tick]? callbackObject = {ok: false} if hash != @game.gameSnapshotHash[tick] callbackObject.ok = false @game.reportInvalidState(tick) @log.info("Hash Incorrect for player ", @id) else callbackObject.ok = true callback JSON.stringify(callbackObject) canPerformAction: => if @state != config.states.begun #Ignore placing towers when the game hasn't even behun yet. return false if @lastAction #Can't queue more than one action at once return false return true performAction: (type, data) => if !@canPerformAction() return false @lastAction = {type, data} placeTower: (xPos, yPos, towerType) => if (!towerType) then return console.error("User " + @id + " tried to place a tower without a type") @performAction('towers', {xPos, yPos, towerType, ownerId: @id}) upgradeTower: (settings) => @performAction('towerUpgrades', _.merge({}, settings, {ownerId: @id})); sellTower: (settings) => @performAction('towerSales', _.merge({}, settings, {ownerId: @id})); placeMinion: (xPos, yPos, minionType) => @performAction('minions', {xPos, yPos, ownerId: @id, minionType: minionType}); collectGem: (gemId) => @performAction('pickups', {id: gemId}) configure: (details, callback) => callback = callback || -> @log.info("Configuring player " + @id + " with details: " + JSON.stringify(details)) if !details? return callback(new Error("No details passed to configure")); if details.team? && !details.ready @setTeam details.team if details.race? && !@ready if @game.isRaceSelected(details.race, @getTeam()) return callback(new Error("That race is already selected")) if @game.get('state') != config.states.selection return callback(new Error("You cannot change your race now")) @setRace details.race if details.minions? && !@ready if details.minions.length > config.maxMinions return callback(new Error("You cannot select more than " + config.maxMinions + " minions")) @setMinions details.minions if details.isBot? @setIsBot details.isBot if details.ready? && @getRace() @setReady(true) @game.userReady() if details.loaded? @setLoaded details.loaded return callback(); bindGameSockets: (game) => if !@socket return false; @log.info("Binding player sockets") @game = game; @socket.on netMsg.game.configure, (details, callback) => @game.configure details, (success) => if callback? callback(success) @socket.on netMsg.player.log.debug, (message) => @gameLog.info(message) @log.info("Binding to message ", netMsg.player.refresh) @socket.on netMsg.player.refresh, (callback) => @log.info("Got Refresh message") @reloadName (err, newName) => game.broadcastDetails() if callback? callback(!err) ### * Rebinding this for game so the game can resend details * whenever a players details change ### @socket.on netMsg.player.configure, (details, callback) => callback = callback || -> @log.info("Configuring player #{@id} with details: ", details) @configure details, (err, result) => if err then return callback(oberr(err)) game.playerUpdated(@id, details); game.broadcastDetails(); return callback(); @socket.on netMsg.game.addBot, (details, callback) => lagAmount = if !serverConfig.addBotLag then 0 else Math.round(Math.random()*2000) setTimeout => @game.addBot(details, callback); , lagAmount @socket.on netMsg.game.configureBot, (details, callback) => @log.info "Configuring bot #{@id} with details: ", details success = @game.configureBot(@id, details) callback success return success @socket.on netMsg.game.kickPlayer, (playerId) => @log.info "Kicking player of id ", playerId success = @game.kickPlayer(@id, playerId) return success @socket.on netMsg.game.start, (details, callback) => game.startSelection(); callback "{ok: true}" @socket.on netMsg.player.finished, (winningTeam, lastTick) => @game.playerFinished(@id, winningTeam, lastTick) @socket.on netMsg.disconnect, => @disconnected = true game.playerDisconnected @ if game.get('state') == config.states.lobby game.deletePlayer @ @socket.on netMsg.player.loaded, (details, callback) => @log.info("Player #{@id} loaded") @setState config.states.begun game.checkPlayersAreLoaded() @configure {loaded: true}, (success) => game.broadcastDetails(); @socket.on netMsg.game.tickNeeded, (tick) => game.resendTick(tick, @) ### Checks all clients have the same game hash as the server every 100ms ### @socket.on netMsg.game.checkHash, (tick, hash, callback) => @checkHash(tick, hash, callback) @socket.on netMsg.game.placeTower, (xPos, yPos, towerType) => @placeTower(xPos, yPos, towerType) @socket.on netMsg.game.upgradeTower, (settings) => @upgradeTower(settings) @socket.on netMsg.game.sellTower, (settings) => @sellTower(settings) @socket.on netMsg.game.placeMinion, (xPos, yPos, minionType) => @placeMinion(xPos, yPos, minionType) @socket.on netMsg.game.collectGem, (gemId) => @collectGem(gemId) module.exports = Player
[ { "context": "8,\n resource: {resourceType: 'Users', name: 'John Doe'}\n )\n truncateOutcome = schema.fhir_truncat", "end": 1504, "score": 0.9997504949569702, "start": 1496, "tag": "NAME", "value": "John Doe" } ]
test/core/schema_spec.coffee
micabe/fhirbase
0
plv8 = require('../../plpl/src/plv8') schema = require('../../src/core/schema') pg_meta = require('../../src/core/pg_meta') crud = require('../../src/fhir/crud') assert = require('assert') describe "CORE: schema", ()-> it "drop Users storage", ()-> schema.fhir_drop_storage(plv8, resourceType: 'Users') assert.equal(pg_meta.table_exists(plv8, 'users'), false) assert.equal(pg_meta.table_exists(plv8, 'users_history'), false) it "create Users storage and history.users", ()-> schema.fhir_create_storage(plv8, resourceType: 'Users') assert.equal(pg_meta.table_exists(plv8, 'users'), true) assert.equal(pg_meta.table_exists(plv8, 'users_history'), true) it "change Users storage name", ()-> desc = schema.fhir_describe_storage(plv8, resourceType: 'users') assert.equal(desc.name, 'users') it 'describe storage with PostgreSQL reserved name', ()-> desc = schema.fhir_describe_storage(plv8, resourceType: 'Group') assert.equal(desc.name, 'group') it 'return error on create existing Users storage', ()-> schema.fhir_create_storage(plv8, resourceType: 'Users') createOutcome = schema.fhir_create_storage(plv8, resourceType: 'Users') assert.equal(createOutcome.status, 'error') assert.equal(createOutcome.message, 'Table users already exists') it 'truncate Users storage', ()-> schema.fhir_create_storage(plv8, resourceType: 'Users') crud.fhir_create_resource( plv8, resource: {resourceType: 'Users', name: 'John Doe'} ) truncateOutcome = schema.fhir_truncate_storage(plv8, resourceType: 'Users') issue = truncateOutcome.issue[0] assert.equal(issue.severity, 'information') assert.equal(issue.code, 'informational') assert.equal(issue.details.coding[0].code, 'MSG_DELETED_DONE') assert.equal(issue.details.coding[0].display, 'Resource deleted') assert.equal(issue.diagnostics, 'Resource type "Users" has been truncated') it 'truncate unexisting storage', ()-> schema.fhir_drop_storage(plv8, resourceType: 'Users') truncateOutcome = schema.fhir_truncate_storage(plv8, resourceType: 'Users') issue = truncateOutcome.issue[0] assert.equal(issue.severity, 'error') assert.equal(issue.code, 'not-found') assert.equal(issue.details.coding[0].code, 'MSG_UNKNOWN_TYPE') assert.equal( issue.details.coding[0].display, 'Resource Type "Users" not recognised' ) assert.equal( issue.diagnostics, "Resource Type \"Users\" not recognised." + " Try create \"Users\" resource:" + " `SELECT fhir_create_storage('{\"resourceType\": \"Users\"}');`" 'Resource Id "unexistingId" with versionId "unexistingVersionId" does not exist' ) it 'drop all storages', -> schema.fhir_create_storage(plv8, resourceType: 'Patient') assert.equal(pg_meta.table_exists(plv8, 'patient'), true) schema.fhir_drop_all_storages(plv8) assert.equal(pg_meta.table_exists(plv8, 'patient'), false) it 'create all storages', -> this.timeout(60000) # creating all storage takes longer time than default 2000 milliseconds <https://mochajs.org/#timeouts> schema.fhir_drop_all_storages(plv8) assert.equal(pg_meta.table_exists(plv8, 'patient'), false) schema.fhir_create_all_storages(plv8) assert.equal(pg_meta.table_exists(plv8, 'patient'), true)
56330
plv8 = require('../../plpl/src/plv8') schema = require('../../src/core/schema') pg_meta = require('../../src/core/pg_meta') crud = require('../../src/fhir/crud') assert = require('assert') describe "CORE: schema", ()-> it "drop Users storage", ()-> schema.fhir_drop_storage(plv8, resourceType: 'Users') assert.equal(pg_meta.table_exists(plv8, 'users'), false) assert.equal(pg_meta.table_exists(plv8, 'users_history'), false) it "create Users storage and history.users", ()-> schema.fhir_create_storage(plv8, resourceType: 'Users') assert.equal(pg_meta.table_exists(plv8, 'users'), true) assert.equal(pg_meta.table_exists(plv8, 'users_history'), true) it "change Users storage name", ()-> desc = schema.fhir_describe_storage(plv8, resourceType: 'users') assert.equal(desc.name, 'users') it 'describe storage with PostgreSQL reserved name', ()-> desc = schema.fhir_describe_storage(plv8, resourceType: 'Group') assert.equal(desc.name, 'group') it 'return error on create existing Users storage', ()-> schema.fhir_create_storage(plv8, resourceType: 'Users') createOutcome = schema.fhir_create_storage(plv8, resourceType: 'Users') assert.equal(createOutcome.status, 'error') assert.equal(createOutcome.message, 'Table users already exists') it 'truncate Users storage', ()-> schema.fhir_create_storage(plv8, resourceType: 'Users') crud.fhir_create_resource( plv8, resource: {resourceType: 'Users', name: '<NAME>'} ) truncateOutcome = schema.fhir_truncate_storage(plv8, resourceType: 'Users') issue = truncateOutcome.issue[0] assert.equal(issue.severity, 'information') assert.equal(issue.code, 'informational') assert.equal(issue.details.coding[0].code, 'MSG_DELETED_DONE') assert.equal(issue.details.coding[0].display, 'Resource deleted') assert.equal(issue.diagnostics, 'Resource type "Users" has been truncated') it 'truncate unexisting storage', ()-> schema.fhir_drop_storage(plv8, resourceType: 'Users') truncateOutcome = schema.fhir_truncate_storage(plv8, resourceType: 'Users') issue = truncateOutcome.issue[0] assert.equal(issue.severity, 'error') assert.equal(issue.code, 'not-found') assert.equal(issue.details.coding[0].code, 'MSG_UNKNOWN_TYPE') assert.equal( issue.details.coding[0].display, 'Resource Type "Users" not recognised' ) assert.equal( issue.diagnostics, "Resource Type \"Users\" not recognised." + " Try create \"Users\" resource:" + " `SELECT fhir_create_storage('{\"resourceType\": \"Users\"}');`" 'Resource Id "unexistingId" with versionId "unexistingVersionId" does not exist' ) it 'drop all storages', -> schema.fhir_create_storage(plv8, resourceType: 'Patient') assert.equal(pg_meta.table_exists(plv8, 'patient'), true) schema.fhir_drop_all_storages(plv8) assert.equal(pg_meta.table_exists(plv8, 'patient'), false) it 'create all storages', -> this.timeout(60000) # creating all storage takes longer time than default 2000 milliseconds <https://mochajs.org/#timeouts> schema.fhir_drop_all_storages(plv8) assert.equal(pg_meta.table_exists(plv8, 'patient'), false) schema.fhir_create_all_storages(plv8) assert.equal(pg_meta.table_exists(plv8, 'patient'), true)
true
plv8 = require('../../plpl/src/plv8') schema = require('../../src/core/schema') pg_meta = require('../../src/core/pg_meta') crud = require('../../src/fhir/crud') assert = require('assert') describe "CORE: schema", ()-> it "drop Users storage", ()-> schema.fhir_drop_storage(plv8, resourceType: 'Users') assert.equal(pg_meta.table_exists(plv8, 'users'), false) assert.equal(pg_meta.table_exists(plv8, 'users_history'), false) it "create Users storage and history.users", ()-> schema.fhir_create_storage(plv8, resourceType: 'Users') assert.equal(pg_meta.table_exists(plv8, 'users'), true) assert.equal(pg_meta.table_exists(plv8, 'users_history'), true) it "change Users storage name", ()-> desc = schema.fhir_describe_storage(plv8, resourceType: 'users') assert.equal(desc.name, 'users') it 'describe storage with PostgreSQL reserved name', ()-> desc = schema.fhir_describe_storage(plv8, resourceType: 'Group') assert.equal(desc.name, 'group') it 'return error on create existing Users storage', ()-> schema.fhir_create_storage(plv8, resourceType: 'Users') createOutcome = schema.fhir_create_storage(plv8, resourceType: 'Users') assert.equal(createOutcome.status, 'error') assert.equal(createOutcome.message, 'Table users already exists') it 'truncate Users storage', ()-> schema.fhir_create_storage(plv8, resourceType: 'Users') crud.fhir_create_resource( plv8, resource: {resourceType: 'Users', name: 'PI:NAME:<NAME>END_PI'} ) truncateOutcome = schema.fhir_truncate_storage(plv8, resourceType: 'Users') issue = truncateOutcome.issue[0] assert.equal(issue.severity, 'information') assert.equal(issue.code, 'informational') assert.equal(issue.details.coding[0].code, 'MSG_DELETED_DONE') assert.equal(issue.details.coding[0].display, 'Resource deleted') assert.equal(issue.diagnostics, 'Resource type "Users" has been truncated') it 'truncate unexisting storage', ()-> schema.fhir_drop_storage(plv8, resourceType: 'Users') truncateOutcome = schema.fhir_truncate_storage(plv8, resourceType: 'Users') issue = truncateOutcome.issue[0] assert.equal(issue.severity, 'error') assert.equal(issue.code, 'not-found') assert.equal(issue.details.coding[0].code, 'MSG_UNKNOWN_TYPE') assert.equal( issue.details.coding[0].display, 'Resource Type "Users" not recognised' ) assert.equal( issue.diagnostics, "Resource Type \"Users\" not recognised." + " Try create \"Users\" resource:" + " `SELECT fhir_create_storage('{\"resourceType\": \"Users\"}');`" 'Resource Id "unexistingId" with versionId "unexistingVersionId" does not exist' ) it 'drop all storages', -> schema.fhir_create_storage(plv8, resourceType: 'Patient') assert.equal(pg_meta.table_exists(plv8, 'patient'), true) schema.fhir_drop_all_storages(plv8) assert.equal(pg_meta.table_exists(plv8, 'patient'), false) it 'create all storages', -> this.timeout(60000) # creating all storage takes longer time than default 2000 milliseconds <https://mochajs.org/#timeouts> schema.fhir_drop_all_storages(plv8) assert.equal(pg_meta.table_exists(plv8, 'patient'), false) schema.fhir_create_all_storages(plv8) assert.equal(pg_meta.table_exists(plv8, 'patient'), true)
[ { "context": "stName: \"!~\": \"L\")'\ntest 'where(firstName: \"!=\": \"Lance\")'\ntest 'where(firstName: \"!=\": null)'\ntest 'wher", "end": 2891, "score": 0.7668877243995667, "start": 2886, "tag": "NAME", "value": "Lance" } ]
test/config.coffee
ludicast/tower
1
require '../lib/tower' File = require('pathfinder').File # require './secrets' global.chai = require 'chai' global.assert = chai.assert global.expect = chai.expect global.test = it global.sinon = require 'sinon' global.async = require 'async' global.cb = true Tower.root = process.cwd() + "/test/test-app" Tower.publicPath = Tower.root + "/public" Tower.env = "test" Tower.View.loadPaths = ["./test/test-app/app/views"] Tower.request = (method, action, options, callback) -> if typeof options == "function" callback = options options = {} options ||= {} params = _.extend {}, options params.action = action url = "http://example.com/#{action}" location = new Tower.HTTP.Url(url) controller = options.controller || new App.CustomController() delete options.controller request = new Tower.HTTP.Request(url: url, location: location, method: method) response = new Tower.HTTP.Response(url: url, location: location, method: method) request.params = params # extend actual http request to make this fully realistic! #Tower.Application.instance().handle request, response, -> # console.log response.controller controller.call request, response, (error, result) -> callback.call @, @response # redirectTo action: "show" Tower.Controller::redirectTo = (options = {}) -> callback = @callback if typeof options == "string" string = options options = {} if string.match(/[\/:]/) options.path = string else options.action = string if options.action options.path = switch options.action when "show" "show" else options.action params = @params params.id = @resource.get("id") if @resource process.nextTick => if params.hasOwnProperty("id") params = {id: params.id} else params = {} Tower.get options.path, params, callback app = Tower.Application.instance() before (done) -> app.initialize(done) beforeEach (done) -> #Tower.Application.instance().teardown() Tower.root = process.cwd() + "/test/test-app" Tower.publicPath = Tower.root + "/public" Tower.View.engine = "coffee" Tower.View.store().loadPaths = ["test/test-app/app/views"] Tower.Application.instance().initialize -> require "#{Tower.root}/app/controllers/customController" models = File.files("#{Tower.root}/app/models") for model in models require(model) if File.exists(model) controllers = File.files("#{Tower.root}/app/controllers") for controller in controllers require(controller) if File.exists(controller) done() ### test 'where(firstName: "=~": "L")' test 'where(firstName: "$match": "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 'asc("firstName")' test 'desc("firstName")' test 'order(["firstName", "desc"])' test 'limit(10)' test 'paginate(perPage: 20, page: 2)' test 'page(2)' ###
151419
require '../lib/tower' File = require('pathfinder').File # require './secrets' global.chai = require 'chai' global.assert = chai.assert global.expect = chai.expect global.test = it global.sinon = require 'sinon' global.async = require 'async' global.cb = true Tower.root = process.cwd() + "/test/test-app" Tower.publicPath = Tower.root + "/public" Tower.env = "test" Tower.View.loadPaths = ["./test/test-app/app/views"] Tower.request = (method, action, options, callback) -> if typeof options == "function" callback = options options = {} options ||= {} params = _.extend {}, options params.action = action url = "http://example.com/#{action}" location = new Tower.HTTP.Url(url) controller = options.controller || new App.CustomController() delete options.controller request = new Tower.HTTP.Request(url: url, location: location, method: method) response = new Tower.HTTP.Response(url: url, location: location, method: method) request.params = params # extend actual http request to make this fully realistic! #Tower.Application.instance().handle request, response, -> # console.log response.controller controller.call request, response, (error, result) -> callback.call @, @response # redirectTo action: "show" Tower.Controller::redirectTo = (options = {}) -> callback = @callback if typeof options == "string" string = options options = {} if string.match(/[\/:]/) options.path = string else options.action = string if options.action options.path = switch options.action when "show" "show" else options.action params = @params params.id = @resource.get("id") if @resource process.nextTick => if params.hasOwnProperty("id") params = {id: params.id} else params = {} Tower.get options.path, params, callback app = Tower.Application.instance() before (done) -> app.initialize(done) beforeEach (done) -> #Tower.Application.instance().teardown() Tower.root = process.cwd() + "/test/test-app" Tower.publicPath = Tower.root + "/public" Tower.View.engine = "coffee" Tower.View.store().loadPaths = ["test/test-app/app/views"] Tower.Application.instance().initialize -> require "#{Tower.root}/app/controllers/customController" models = File.files("#{Tower.root}/app/models") for model in models require(model) if File.exists(model) controllers = File.files("#{Tower.root}/app/controllers") for controller in controllers require(controller) if File.exists(controller) done() ### test 'where(firstName: "=~": "L")' test 'where(firstName: "$match": "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 'asc("firstName")' test 'desc("firstName")' test 'order(["firstName", "desc"])' test 'limit(10)' test 'paginate(perPage: 20, page: 2)' test 'page(2)' ###
true
require '../lib/tower' File = require('pathfinder').File # require './secrets' global.chai = require 'chai' global.assert = chai.assert global.expect = chai.expect global.test = it global.sinon = require 'sinon' global.async = require 'async' global.cb = true Tower.root = process.cwd() + "/test/test-app" Tower.publicPath = Tower.root + "/public" Tower.env = "test" Tower.View.loadPaths = ["./test/test-app/app/views"] Tower.request = (method, action, options, callback) -> if typeof options == "function" callback = options options = {} options ||= {} params = _.extend {}, options params.action = action url = "http://example.com/#{action}" location = new Tower.HTTP.Url(url) controller = options.controller || new App.CustomController() delete options.controller request = new Tower.HTTP.Request(url: url, location: location, method: method) response = new Tower.HTTP.Response(url: url, location: location, method: method) request.params = params # extend actual http request to make this fully realistic! #Tower.Application.instance().handle request, response, -> # console.log response.controller controller.call request, response, (error, result) -> callback.call @, @response # redirectTo action: "show" Tower.Controller::redirectTo = (options = {}) -> callback = @callback if typeof options == "string" string = options options = {} if string.match(/[\/:]/) options.path = string else options.action = string if options.action options.path = switch options.action when "show" "show" else options.action params = @params params.id = @resource.get("id") if @resource process.nextTick => if params.hasOwnProperty("id") params = {id: params.id} else params = {} Tower.get options.path, params, callback app = Tower.Application.instance() before (done) -> app.initialize(done) beforeEach (done) -> #Tower.Application.instance().teardown() Tower.root = process.cwd() + "/test/test-app" Tower.publicPath = Tower.root + "/public" Tower.View.engine = "coffee" Tower.View.store().loadPaths = ["test/test-app/app/views"] Tower.Application.instance().initialize -> require "#{Tower.root}/app/controllers/customController" models = File.files("#{Tower.root}/app/models") for model in models require(model) if File.exists(model) controllers = File.files("#{Tower.root}/app/controllers") for controller in controllers require(controller) if File.exists(controller) done() ### test 'where(firstName: "=~": "L")' test 'where(firstName: "$match": "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 'asc("firstName")' test 'desc("firstName")' test 'order(["firstName", "desc"])' test 'limit(10)' test 'paginate(perPage: 20, page: 2)' test 'page(2)' ###
[ { "context": ")\n\n client.config.credentials.accessKeyId = 'akid'\n client.config.credentials.secretAccessKey ", "end": 2518, "score": 0.9972755908966064, "start": 2514, "tag": "KEY", "value": "akid" } ]
node_modules/aws-sdk/test/event_listeners.spec.coffee
ellennewellevans/newsScraper
1
# Copyright 2012-2013 Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file 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. helpers = require('./helpers') AWS = helpers.AWS MockClient = helpers.MockClient describe 'AWS.EventListeners', -> oldSetTimeout = setTimeout config = null; client = null; totalWaited = null; delays = [] successHandler = null; errorHandler = null; completeHandler = null retryHandler = null beforeEach -> # Mock the timer manually (jasmine.Clock does not work in node) `setTimeout = jasmine.createSpy('setTimeout');` setTimeout.andCallFake (callback, delay) -> totalWaited += delay delays.push(delay) callback() totalWaited = 0 delays = [] client = new MockClient(maxRetries: 3) client.config.credentials = AWS.util.copy(client.config.credentials) # Helpful handlers successHandler = createSpy('success') errorHandler = createSpy('error') completeHandler = createSpy('complete') retryHandler = createSpy('retry') # Safely tear down setTimeout hack afterEach -> `setTimeout = oldSetTimeout` makeRequest = (callback) -> request = client.makeRequest('mockMethod', foo: 'bar') request.on('retry', retryHandler) request.on('error', errorHandler) request.on('success', successHandler) request.on('complete', completeHandler) if callback request.on 'complete', (resp) -> callback.call(resp, resp.error, resp.data) request.send() else request describe 'validate', -> it 'takes the request object as a parameter', -> request = makeRequest() request.on 'validate', (req) -> expect(req).toBe(request) throw "ERROR" response = request.send() expect(response.error).toEqual("ERROR") it 'sends error event if credentials are not set', -> errorHandler = createSpy() request = makeRequest() request.on('error', errorHandler) client.config.credentials.accessKeyId = null request.send() client.config.credentials.accessKeyId = 'akid' client.config.credentials.secretAccessKey = null request.send() expect(errorHandler).toHaveBeenCalled() AWS.util.arrayEach errorHandler.calls, (call) -> expect(call.args[0] instanceof Error).toBeTruthy() expect(call.args[0].code).toEqual('SigningError') expect(call.args[0].message).toMatch(/Missing credentials in config/) it 'sends error event if region is not set', -> client.config.region = null request = makeRequest(->) call = errorHandler.calls[0] expect(errorHandler).toHaveBeenCalled() expect(call.args[0] instanceof Error).toBeTruthy() expect(call.args[0].code).toEqual('SigningError') expect(call.args[0].message).toMatch(/Missing region in config/) describe 'build', -> it 'takes the request object as a parameter', -> request = makeRequest() request.on 'build', (req) -> expect(req).toBe(request) throw "ERROR" response = request.send() expect(response.error).toEqual("ERROR") describe 'afterBuild', -> beforeEach -> helpers.mockHttpResponse 200, {}, ['DATA'] sendRequest = (body) -> request = makeRequest() request.on('build', (req) -> req.httpRequest.body = body) request.send() request contentLength = (body) -> sendRequest(body).httpRequest.headers['Content-Length'] it 'builds Content-Length in the request headers for string content', -> expect(contentLength('FOOBAR')).toEqual(6) it 'builds Content-Length for string "0"', -> expect(contentLength('0')).toEqual(1) it 'builds Content-Length for utf-8 string body', -> expect(contentLength('tï№')).toEqual(6) it 'builds Content-Length for buffer body', -> expect(contentLength(new Buffer('tï№'))).toEqual(6) it 'builds Content-Length for file body', -> fs = require('fs') file = fs.createReadStream(__filename) fileLen = fs.lstatSync(file.path).size expect(contentLength(file)).toEqual(fileLen) describe 'sign', -> it 'takes the request object as a parameter', -> request = makeRequest() request.on 'sign', (req) -> expect(req).toBe(request) throw "ERROR" response = request.send() expect(response.error).toEqual("ERROR") it 'uses the api.signingName if provided', -> client.api.signingName = 'SIGNING_NAME' spyOn(AWS.Signers.RequestSigner, 'getVersion').andCallFake -> (req, signingName) -> throw signingName request = makeRequest() response = request.send() expect(response.error).toEqual('SIGNING_NAME') delete client.api.signingName it 'uses the api.endpointPrefix if signingName not provided', -> spyOn(AWS.Signers.RequestSigner, 'getVersion').andCallFake -> (req, signingName) -> throw signingName request = makeRequest() response = request.send() expect(response.error).toEqual('mockservice') describe 'httpData', -> beforeEach -> helpers.mockHttpResponse 200, {}, ['FOO', 'BAR', 'BAZ', 'QUX'] it 'emits httpData event on each chunk', -> calls = [] # register httpData event request = makeRequest() request.on('httpData', (chunk) -> calls.push(chunk.toString())) request.send() expect(calls).toEqual(['FOO', 'BAR', 'BAZ', 'QUX']) it 'does not clear default httpData event if another is added', -> request = makeRequest() request.on('httpData', ->) response = request.send() expect(response.httpResponse.body.toString()).toEqual('FOOBARBAZQUX') describe 'retry', -> it 'retries a request with a set maximum retries', -> sendHandler = createSpy('send') client.config.maxRetries = 10 # fail every request with a fake networking error helpers.mockHttpResponse code: 'NetworkingError', message: 'Cannot connect' request = makeRequest() request.on('send', sendHandler) response = request.send() expect(retryHandler).toHaveBeenCalled() expect(errorHandler).toHaveBeenCalled() expect(completeHandler).toHaveBeenCalled() expect(successHandler).not.toHaveBeenCalled() expect(response.retryCount).toEqual(client.config.maxRetries); expect(sendHandler.calls.length).toEqual(client.config.maxRetries + 1) it 'retries with falloff', -> helpers.mockHttpResponse code: 'NetworkingError', message: 'Cannot connect' makeRequest(->) expect(delays).toEqual([30, 60, 120]) it 'retries if status code is >= 500', -> helpers.mockHttpResponse 500, {}, '' makeRequest (err) -> expect(err).toEqual code: 500, message: null, statusCode: 500 retryable: true expect(@retryCount). toEqual(client.config.maxRetries) it 'should not emit error if retried fewer than maxRetries', -> helpers.mockIntermittentFailureResponse 2, 200, {}, 'foo' response = makeRequest(->) expect(totalWaited).toEqual(90) expect(response.retryCount).toBeLessThan(client.config.maxRetries) expect(response.data).toEqual('foo') expect(errorHandler).not.toHaveBeenCalled() describe 'success', -> it 'emits success on a successful response', -> # fail every request with a fake networking error helpers.mockHttpResponse 200, {}, 'Success!' response = makeRequest(->) expect(retryHandler).not.toHaveBeenCalled() expect(errorHandler).not.toHaveBeenCalled() expect(completeHandler).toHaveBeenCalled() expect(successHandler).toHaveBeenCalled() expect(response.retryCount).toEqual(0); describe 'error', -> it 'emits error if error found and should not be retrying', -> # fail every request with a fake networking error helpers.mockHttpResponse 400, {}, '' response = makeRequest(->) expect(retryHandler).not.toHaveBeenCalled() expect(errorHandler).toHaveBeenCalled() expect(completeHandler).toHaveBeenCalled() expect(successHandler).not.toHaveBeenCalled() expect(response.retryCount).toEqual(0); it 'emits error if an error is set in extractError', -> error = code: 'ParseError', message: 'error message' extractDataHandler = createSpy('extractData') helpers.mockHttpResponse 400, {}, '' request = makeRequest() request.on('extractData', extractDataHandler) request.on('extractError', (resp) -> resp.error = error) response = request.send() expect(response.error).toBe(error) expect(extractDataHandler).not.toHaveBeenCalled() expect(retryHandler).not.toHaveBeenCalled() expect(errorHandler).toHaveBeenCalled() expect(completeHandler).toHaveBeenCalled() it 'catches exceptions raised from error event', -> helpers.mockHttpResponse 500, {}, [] request = makeRequest() request.on 'error', -> throw "ERROR" response = request.send() expect(completeHandler).toHaveBeenCalled() expect(response.error).toBe("ERROR")
139149
# Copyright 2012-2013 Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file 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. helpers = require('./helpers') AWS = helpers.AWS MockClient = helpers.MockClient describe 'AWS.EventListeners', -> oldSetTimeout = setTimeout config = null; client = null; totalWaited = null; delays = [] successHandler = null; errorHandler = null; completeHandler = null retryHandler = null beforeEach -> # Mock the timer manually (jasmine.Clock does not work in node) `setTimeout = jasmine.createSpy('setTimeout');` setTimeout.andCallFake (callback, delay) -> totalWaited += delay delays.push(delay) callback() totalWaited = 0 delays = [] client = new MockClient(maxRetries: 3) client.config.credentials = AWS.util.copy(client.config.credentials) # Helpful handlers successHandler = createSpy('success') errorHandler = createSpy('error') completeHandler = createSpy('complete') retryHandler = createSpy('retry') # Safely tear down setTimeout hack afterEach -> `setTimeout = oldSetTimeout` makeRequest = (callback) -> request = client.makeRequest('mockMethod', foo: 'bar') request.on('retry', retryHandler) request.on('error', errorHandler) request.on('success', successHandler) request.on('complete', completeHandler) if callback request.on 'complete', (resp) -> callback.call(resp, resp.error, resp.data) request.send() else request describe 'validate', -> it 'takes the request object as a parameter', -> request = makeRequest() request.on 'validate', (req) -> expect(req).toBe(request) throw "ERROR" response = request.send() expect(response.error).toEqual("ERROR") it 'sends error event if credentials are not set', -> errorHandler = createSpy() request = makeRequest() request.on('error', errorHandler) client.config.credentials.accessKeyId = null request.send() client.config.credentials.accessKeyId = '<KEY>' client.config.credentials.secretAccessKey = null request.send() expect(errorHandler).toHaveBeenCalled() AWS.util.arrayEach errorHandler.calls, (call) -> expect(call.args[0] instanceof Error).toBeTruthy() expect(call.args[0].code).toEqual('SigningError') expect(call.args[0].message).toMatch(/Missing credentials in config/) it 'sends error event if region is not set', -> client.config.region = null request = makeRequest(->) call = errorHandler.calls[0] expect(errorHandler).toHaveBeenCalled() expect(call.args[0] instanceof Error).toBeTruthy() expect(call.args[0].code).toEqual('SigningError') expect(call.args[0].message).toMatch(/Missing region in config/) describe 'build', -> it 'takes the request object as a parameter', -> request = makeRequest() request.on 'build', (req) -> expect(req).toBe(request) throw "ERROR" response = request.send() expect(response.error).toEqual("ERROR") describe 'afterBuild', -> beforeEach -> helpers.mockHttpResponse 200, {}, ['DATA'] sendRequest = (body) -> request = makeRequest() request.on('build', (req) -> req.httpRequest.body = body) request.send() request contentLength = (body) -> sendRequest(body).httpRequest.headers['Content-Length'] it 'builds Content-Length in the request headers for string content', -> expect(contentLength('FOOBAR')).toEqual(6) it 'builds Content-Length for string "0"', -> expect(contentLength('0')).toEqual(1) it 'builds Content-Length for utf-8 string body', -> expect(contentLength('tï№')).toEqual(6) it 'builds Content-Length for buffer body', -> expect(contentLength(new Buffer('tï№'))).toEqual(6) it 'builds Content-Length for file body', -> fs = require('fs') file = fs.createReadStream(__filename) fileLen = fs.lstatSync(file.path).size expect(contentLength(file)).toEqual(fileLen) describe 'sign', -> it 'takes the request object as a parameter', -> request = makeRequest() request.on 'sign', (req) -> expect(req).toBe(request) throw "ERROR" response = request.send() expect(response.error).toEqual("ERROR") it 'uses the api.signingName if provided', -> client.api.signingName = 'SIGNING_NAME' spyOn(AWS.Signers.RequestSigner, 'getVersion').andCallFake -> (req, signingName) -> throw signingName request = makeRequest() response = request.send() expect(response.error).toEqual('SIGNING_NAME') delete client.api.signingName it 'uses the api.endpointPrefix if signingName not provided', -> spyOn(AWS.Signers.RequestSigner, 'getVersion').andCallFake -> (req, signingName) -> throw signingName request = makeRequest() response = request.send() expect(response.error).toEqual('mockservice') describe 'httpData', -> beforeEach -> helpers.mockHttpResponse 200, {}, ['FOO', 'BAR', 'BAZ', 'QUX'] it 'emits httpData event on each chunk', -> calls = [] # register httpData event request = makeRequest() request.on('httpData', (chunk) -> calls.push(chunk.toString())) request.send() expect(calls).toEqual(['FOO', 'BAR', 'BAZ', 'QUX']) it 'does not clear default httpData event if another is added', -> request = makeRequest() request.on('httpData', ->) response = request.send() expect(response.httpResponse.body.toString()).toEqual('FOOBARBAZQUX') describe 'retry', -> it 'retries a request with a set maximum retries', -> sendHandler = createSpy('send') client.config.maxRetries = 10 # fail every request with a fake networking error helpers.mockHttpResponse code: 'NetworkingError', message: 'Cannot connect' request = makeRequest() request.on('send', sendHandler) response = request.send() expect(retryHandler).toHaveBeenCalled() expect(errorHandler).toHaveBeenCalled() expect(completeHandler).toHaveBeenCalled() expect(successHandler).not.toHaveBeenCalled() expect(response.retryCount).toEqual(client.config.maxRetries); expect(sendHandler.calls.length).toEqual(client.config.maxRetries + 1) it 'retries with falloff', -> helpers.mockHttpResponse code: 'NetworkingError', message: 'Cannot connect' makeRequest(->) expect(delays).toEqual([30, 60, 120]) it 'retries if status code is >= 500', -> helpers.mockHttpResponse 500, {}, '' makeRequest (err) -> expect(err).toEqual code: 500, message: null, statusCode: 500 retryable: true expect(@retryCount). toEqual(client.config.maxRetries) it 'should not emit error if retried fewer than maxRetries', -> helpers.mockIntermittentFailureResponse 2, 200, {}, 'foo' response = makeRequest(->) expect(totalWaited).toEqual(90) expect(response.retryCount).toBeLessThan(client.config.maxRetries) expect(response.data).toEqual('foo') expect(errorHandler).not.toHaveBeenCalled() describe 'success', -> it 'emits success on a successful response', -> # fail every request with a fake networking error helpers.mockHttpResponse 200, {}, 'Success!' response = makeRequest(->) expect(retryHandler).not.toHaveBeenCalled() expect(errorHandler).not.toHaveBeenCalled() expect(completeHandler).toHaveBeenCalled() expect(successHandler).toHaveBeenCalled() expect(response.retryCount).toEqual(0); describe 'error', -> it 'emits error if error found and should not be retrying', -> # fail every request with a fake networking error helpers.mockHttpResponse 400, {}, '' response = makeRequest(->) expect(retryHandler).not.toHaveBeenCalled() expect(errorHandler).toHaveBeenCalled() expect(completeHandler).toHaveBeenCalled() expect(successHandler).not.toHaveBeenCalled() expect(response.retryCount).toEqual(0); it 'emits error if an error is set in extractError', -> error = code: 'ParseError', message: 'error message' extractDataHandler = createSpy('extractData') helpers.mockHttpResponse 400, {}, '' request = makeRequest() request.on('extractData', extractDataHandler) request.on('extractError', (resp) -> resp.error = error) response = request.send() expect(response.error).toBe(error) expect(extractDataHandler).not.toHaveBeenCalled() expect(retryHandler).not.toHaveBeenCalled() expect(errorHandler).toHaveBeenCalled() expect(completeHandler).toHaveBeenCalled() it 'catches exceptions raised from error event', -> helpers.mockHttpResponse 500, {}, [] request = makeRequest() request.on 'error', -> throw "ERROR" response = request.send() expect(completeHandler).toHaveBeenCalled() expect(response.error).toBe("ERROR")
true
# Copyright 2012-2013 Amazon.com, Inc. or its affiliates. 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. A copy of # the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file accompanying this file. This file 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. helpers = require('./helpers') AWS = helpers.AWS MockClient = helpers.MockClient describe 'AWS.EventListeners', -> oldSetTimeout = setTimeout config = null; client = null; totalWaited = null; delays = [] successHandler = null; errorHandler = null; completeHandler = null retryHandler = null beforeEach -> # Mock the timer manually (jasmine.Clock does not work in node) `setTimeout = jasmine.createSpy('setTimeout');` setTimeout.andCallFake (callback, delay) -> totalWaited += delay delays.push(delay) callback() totalWaited = 0 delays = [] client = new MockClient(maxRetries: 3) client.config.credentials = AWS.util.copy(client.config.credentials) # Helpful handlers successHandler = createSpy('success') errorHandler = createSpy('error') completeHandler = createSpy('complete') retryHandler = createSpy('retry') # Safely tear down setTimeout hack afterEach -> `setTimeout = oldSetTimeout` makeRequest = (callback) -> request = client.makeRequest('mockMethod', foo: 'bar') request.on('retry', retryHandler) request.on('error', errorHandler) request.on('success', successHandler) request.on('complete', completeHandler) if callback request.on 'complete', (resp) -> callback.call(resp, resp.error, resp.data) request.send() else request describe 'validate', -> it 'takes the request object as a parameter', -> request = makeRequest() request.on 'validate', (req) -> expect(req).toBe(request) throw "ERROR" response = request.send() expect(response.error).toEqual("ERROR") it 'sends error event if credentials are not set', -> errorHandler = createSpy() request = makeRequest() request.on('error', errorHandler) client.config.credentials.accessKeyId = null request.send() client.config.credentials.accessKeyId = 'PI:KEY:<KEY>END_PI' client.config.credentials.secretAccessKey = null request.send() expect(errorHandler).toHaveBeenCalled() AWS.util.arrayEach errorHandler.calls, (call) -> expect(call.args[0] instanceof Error).toBeTruthy() expect(call.args[0].code).toEqual('SigningError') expect(call.args[0].message).toMatch(/Missing credentials in config/) it 'sends error event if region is not set', -> client.config.region = null request = makeRequest(->) call = errorHandler.calls[0] expect(errorHandler).toHaveBeenCalled() expect(call.args[0] instanceof Error).toBeTruthy() expect(call.args[0].code).toEqual('SigningError') expect(call.args[0].message).toMatch(/Missing region in config/) describe 'build', -> it 'takes the request object as a parameter', -> request = makeRequest() request.on 'build', (req) -> expect(req).toBe(request) throw "ERROR" response = request.send() expect(response.error).toEqual("ERROR") describe 'afterBuild', -> beforeEach -> helpers.mockHttpResponse 200, {}, ['DATA'] sendRequest = (body) -> request = makeRequest() request.on('build', (req) -> req.httpRequest.body = body) request.send() request contentLength = (body) -> sendRequest(body).httpRequest.headers['Content-Length'] it 'builds Content-Length in the request headers for string content', -> expect(contentLength('FOOBAR')).toEqual(6) it 'builds Content-Length for string "0"', -> expect(contentLength('0')).toEqual(1) it 'builds Content-Length for utf-8 string body', -> expect(contentLength('tï№')).toEqual(6) it 'builds Content-Length for buffer body', -> expect(contentLength(new Buffer('tï№'))).toEqual(6) it 'builds Content-Length for file body', -> fs = require('fs') file = fs.createReadStream(__filename) fileLen = fs.lstatSync(file.path).size expect(contentLength(file)).toEqual(fileLen) describe 'sign', -> it 'takes the request object as a parameter', -> request = makeRequest() request.on 'sign', (req) -> expect(req).toBe(request) throw "ERROR" response = request.send() expect(response.error).toEqual("ERROR") it 'uses the api.signingName if provided', -> client.api.signingName = 'SIGNING_NAME' spyOn(AWS.Signers.RequestSigner, 'getVersion').andCallFake -> (req, signingName) -> throw signingName request = makeRequest() response = request.send() expect(response.error).toEqual('SIGNING_NAME') delete client.api.signingName it 'uses the api.endpointPrefix if signingName not provided', -> spyOn(AWS.Signers.RequestSigner, 'getVersion').andCallFake -> (req, signingName) -> throw signingName request = makeRequest() response = request.send() expect(response.error).toEqual('mockservice') describe 'httpData', -> beforeEach -> helpers.mockHttpResponse 200, {}, ['FOO', 'BAR', 'BAZ', 'QUX'] it 'emits httpData event on each chunk', -> calls = [] # register httpData event request = makeRequest() request.on('httpData', (chunk) -> calls.push(chunk.toString())) request.send() expect(calls).toEqual(['FOO', 'BAR', 'BAZ', 'QUX']) it 'does not clear default httpData event if another is added', -> request = makeRequest() request.on('httpData', ->) response = request.send() expect(response.httpResponse.body.toString()).toEqual('FOOBARBAZQUX') describe 'retry', -> it 'retries a request with a set maximum retries', -> sendHandler = createSpy('send') client.config.maxRetries = 10 # fail every request with a fake networking error helpers.mockHttpResponse code: 'NetworkingError', message: 'Cannot connect' request = makeRequest() request.on('send', sendHandler) response = request.send() expect(retryHandler).toHaveBeenCalled() expect(errorHandler).toHaveBeenCalled() expect(completeHandler).toHaveBeenCalled() expect(successHandler).not.toHaveBeenCalled() expect(response.retryCount).toEqual(client.config.maxRetries); expect(sendHandler.calls.length).toEqual(client.config.maxRetries + 1) it 'retries with falloff', -> helpers.mockHttpResponse code: 'NetworkingError', message: 'Cannot connect' makeRequest(->) expect(delays).toEqual([30, 60, 120]) it 'retries if status code is >= 500', -> helpers.mockHttpResponse 500, {}, '' makeRequest (err) -> expect(err).toEqual code: 500, message: null, statusCode: 500 retryable: true expect(@retryCount). toEqual(client.config.maxRetries) it 'should not emit error if retried fewer than maxRetries', -> helpers.mockIntermittentFailureResponse 2, 200, {}, 'foo' response = makeRequest(->) expect(totalWaited).toEqual(90) expect(response.retryCount).toBeLessThan(client.config.maxRetries) expect(response.data).toEqual('foo') expect(errorHandler).not.toHaveBeenCalled() describe 'success', -> it 'emits success on a successful response', -> # fail every request with a fake networking error helpers.mockHttpResponse 200, {}, 'Success!' response = makeRequest(->) expect(retryHandler).not.toHaveBeenCalled() expect(errorHandler).not.toHaveBeenCalled() expect(completeHandler).toHaveBeenCalled() expect(successHandler).toHaveBeenCalled() expect(response.retryCount).toEqual(0); describe 'error', -> it 'emits error if error found and should not be retrying', -> # fail every request with a fake networking error helpers.mockHttpResponse 400, {}, '' response = makeRequest(->) expect(retryHandler).not.toHaveBeenCalled() expect(errorHandler).toHaveBeenCalled() expect(completeHandler).toHaveBeenCalled() expect(successHandler).not.toHaveBeenCalled() expect(response.retryCount).toEqual(0); it 'emits error if an error is set in extractError', -> error = code: 'ParseError', message: 'error message' extractDataHandler = createSpy('extractData') helpers.mockHttpResponse 400, {}, '' request = makeRequest() request.on('extractData', extractDataHandler) request.on('extractError', (resp) -> resp.error = error) response = request.send() expect(response.error).toBe(error) expect(extractDataHandler).not.toHaveBeenCalled() expect(retryHandler).not.toHaveBeenCalled() expect(errorHandler).toHaveBeenCalled() expect(completeHandler).toHaveBeenCalled() it 'catches exceptions raised from error event', -> helpers.mockHttpResponse 500, {}, [] request = makeRequest() request.on 'error', -> throw "ERROR" response = request.send() expect(completeHandler).toHaveBeenCalled() expect(response.error).toBe("ERROR")
[ { "context": "uth =\n username: authParts[0]\n password: authParts[1]\n sendImmediately: true\n api\n", "end": 855, "score": 0.9482954740524292, "start": 844, "tag": "PASSWORD", "value": "authParts[1" } ]
lib/generators/app/templates/coffeescript/server/lib/data_adapter.coffee
technicolorenvy/rendr-cli
1
DataAdapter = (options) -> RestAdapter.call this, options RestAdapter = require("rendr/server/data_adapter/rest_adapter") util = require("util") module.exports = DataAdapter util.inherits DataAdapter, RestAdapter ### We have to do a kind of silly thing for our example app; GitHub rate limits requests to its API, but it ups the limit by an order of magnitude if the request is authenticated using HTTP Basic Authentication. We simply override the `apiDefaults` method, tacking on an `auth` property if the `BASIC_AUTH` environment variable is present. ### DataAdapter::apiDefaults = (api) -> basicAuth = undefined authParts = undefined api = RestAdapter::apiDefaults.call(this, api) basicAuth = process.env.BASIC_AUTH if basicAuth? authParts = basicAuth.split(":") api.auth = username: authParts[0] password: authParts[1] sendImmediately: true api
68299
DataAdapter = (options) -> RestAdapter.call this, options RestAdapter = require("rendr/server/data_adapter/rest_adapter") util = require("util") module.exports = DataAdapter util.inherits DataAdapter, RestAdapter ### We have to do a kind of silly thing for our example app; GitHub rate limits requests to its API, but it ups the limit by an order of magnitude if the request is authenticated using HTTP Basic Authentication. We simply override the `apiDefaults` method, tacking on an `auth` property if the `BASIC_AUTH` environment variable is present. ### DataAdapter::apiDefaults = (api) -> basicAuth = undefined authParts = undefined api = RestAdapter::apiDefaults.call(this, api) basicAuth = process.env.BASIC_AUTH if basicAuth? authParts = basicAuth.split(":") api.auth = username: authParts[0] password: <PASSWORD>] sendImmediately: true api
true
DataAdapter = (options) -> RestAdapter.call this, options RestAdapter = require("rendr/server/data_adapter/rest_adapter") util = require("util") module.exports = DataAdapter util.inherits DataAdapter, RestAdapter ### We have to do a kind of silly thing for our example app; GitHub rate limits requests to its API, but it ups the limit by an order of magnitude if the request is authenticated using HTTP Basic Authentication. We simply override the `apiDefaults` method, tacking on an `auth` property if the `BASIC_AUTH` environment variable is present. ### DataAdapter::apiDefaults = (api) -> basicAuth = undefined authParts = undefined api = RestAdapter::apiDefaults.call(this, api) basicAuth = process.env.BASIC_AUTH if basicAuth? authParts = basicAuth.split(":") api.auth = username: authParts[0] password: PI:PASSWORD:<PASSWORD>END_PI] sendImmediately: true api
[ { "context": "# OAuth daemon\r\n# Copyright (C) 2013 Webshell SAS\r\n#\r\n# This program is free software: you", "end": 40, "score": 0.626362144947052, "start": 37, "tag": "NAME", "value": "Web" } ]
src/core/oauth/oauth-response-parser.coffee
makevoid/oauthd
443
# OAuth daemon # Copyright (C) 2013 Webshell SAS # # This program 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 # 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/>. querystring = require 'querystring' zlib = require 'zlib' module.exports = (env) -> check = env.utilities.check class OAuthResponseParser constructor: (response, body, format, tokenType) -> @_response = response @_undecodedBody = body @_format = format || response.headers['content-type'] @_format = @_format.match(/^([^;]+)/)[0] # skip charset etc. @_errorPrefix = 'Error during the \'' + tokenType + '\' step' decode: (callback) -> if @_response.headers['content-encoding'] == 'gzip' zlib.gunzip @_undecodedBody, callback else callback null, @_undecodedBody parse: (callback) -> @decode (e, r) => return callback e if e @_unparsedBody = r.toString() return callback @_setError 'HTTP status code: ' + @_response.statusCode if @_response.statusCode != 200 and not @_unparsedBody return callback @_setError 'Empty response' if not @_unparsedBody parseFunc = @_parse[@_format] if parseFunc @_parseBody parseFunc else @_parseUnknownBody() return callback @error if @error return callback @_setError 'HTTP status code: ' + @_response.statusCode if @_response.statusCode != 200 and @_response.statusCode != 201 return callback null, @ _parse: 'application/json': (d) -> JSON.parse d 'application/x-www-form-urlencoded': (d) -> querystring.parse d _parseUnknownBody: -> for format, parseFunc of @_parse delete @error @_parseBody parseFunc break if not @error @error.message += ' from format ' + @_format if @error return _parseBody: (parseFunc) -> try @body = parseFunc(@_unparsedBody) catch ex return @_setError 'Unable to parse response' @_setError 'Empty response' if not @body? return _setError: (message) -> @error = new check.Error @_errorPrefix + ' (' + message + ')' if typeof @body == 'object' and Object.keys(@body).length @error.body = @body else if @_unparsedBody @error.body = @_unparsedBody return @error OAuthResponseParser
79188
# OAuth daemon # Copyright (C) 2013 <NAME>shell SAS # # This program 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 # 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/>. querystring = require 'querystring' zlib = require 'zlib' module.exports = (env) -> check = env.utilities.check class OAuthResponseParser constructor: (response, body, format, tokenType) -> @_response = response @_undecodedBody = body @_format = format || response.headers['content-type'] @_format = @_format.match(/^([^;]+)/)[0] # skip charset etc. @_errorPrefix = 'Error during the \'' + tokenType + '\' step' decode: (callback) -> if @_response.headers['content-encoding'] == 'gzip' zlib.gunzip @_undecodedBody, callback else callback null, @_undecodedBody parse: (callback) -> @decode (e, r) => return callback e if e @_unparsedBody = r.toString() return callback @_setError 'HTTP status code: ' + @_response.statusCode if @_response.statusCode != 200 and not @_unparsedBody return callback @_setError 'Empty response' if not @_unparsedBody parseFunc = @_parse[@_format] if parseFunc @_parseBody parseFunc else @_parseUnknownBody() return callback @error if @error return callback @_setError 'HTTP status code: ' + @_response.statusCode if @_response.statusCode != 200 and @_response.statusCode != 201 return callback null, @ _parse: 'application/json': (d) -> JSON.parse d 'application/x-www-form-urlencoded': (d) -> querystring.parse d _parseUnknownBody: -> for format, parseFunc of @_parse delete @error @_parseBody parseFunc break if not @error @error.message += ' from format ' + @_format if @error return _parseBody: (parseFunc) -> try @body = parseFunc(@_unparsedBody) catch ex return @_setError 'Unable to parse response' @_setError 'Empty response' if not @body? return _setError: (message) -> @error = new check.Error @_errorPrefix + ' (' + message + ')' if typeof @body == 'object' and Object.keys(@body).length @error.body = @body else if @_unparsedBody @error.body = @_unparsedBody return @error OAuthResponseParser
true
# OAuth daemon # Copyright (C) 2013 PI:NAME:<NAME>END_PIshell SAS # # This program 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 # 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/>. querystring = require 'querystring' zlib = require 'zlib' module.exports = (env) -> check = env.utilities.check class OAuthResponseParser constructor: (response, body, format, tokenType) -> @_response = response @_undecodedBody = body @_format = format || response.headers['content-type'] @_format = @_format.match(/^([^;]+)/)[0] # skip charset etc. @_errorPrefix = 'Error during the \'' + tokenType + '\' step' decode: (callback) -> if @_response.headers['content-encoding'] == 'gzip' zlib.gunzip @_undecodedBody, callback else callback null, @_undecodedBody parse: (callback) -> @decode (e, r) => return callback e if e @_unparsedBody = r.toString() return callback @_setError 'HTTP status code: ' + @_response.statusCode if @_response.statusCode != 200 and not @_unparsedBody return callback @_setError 'Empty response' if not @_unparsedBody parseFunc = @_parse[@_format] if parseFunc @_parseBody parseFunc else @_parseUnknownBody() return callback @error if @error return callback @_setError 'HTTP status code: ' + @_response.statusCode if @_response.statusCode != 200 and @_response.statusCode != 201 return callback null, @ _parse: 'application/json': (d) -> JSON.parse d 'application/x-www-form-urlencoded': (d) -> querystring.parse d _parseUnknownBody: -> for format, parseFunc of @_parse delete @error @_parseBody parseFunc break if not @error @error.message += ' from format ' + @_format if @error return _parseBody: (parseFunc) -> try @body = parseFunc(@_unparsedBody) catch ex return @_setError 'Unable to parse response' @_setError 'Empty response' if not @body? return _setError: (message) -> @error = new check.Error @_errorPrefix + ' (' + message + ')' if typeof @body == 'object' and Object.keys(@body).length @error.body = @body else if @_unparsedBody @error.body = @_unparsedBody return @error OAuthResponseParser
[ { "context": "### Copyright (c) 2015 Magnus Leo. All rights reserved. ###\n\ncollision = {}\nmodule.", "end": 33, "score": 0.9998548626899719, "start": 23, "tag": "NAME", "value": "Magnus Leo" } ]
src/modules/collision.coffee
magnusleo/Leo-Engine
1
### Copyright (c) 2015 Magnus Leo. All rights reserved. ### collision = {} module.exports = collision Line = require('../classes/Line') Rect = require('../classes/Rect') util = require('./util') view = require('./view') collision.actorToLayer = (actor, layer, options) -> o = reposition: false o = util.merge(o, options) collisions = any: false bottom: false top: false left: false right: false friction: 1.0 #TODO: Get data from colliding tiles newPosX = actor.posX newPosY = actor.posY newSpeedX = actor.speedX newSpeedY = actor.speedY startX = actor.posX >> 0 endX = (actor.posX + actor.colW) >> 0 startY = actor.posY >> 0 endY = (actor.posY + actor.colH) >> 0 # Check if overlapping tiles are collidable for y in [startY..endY] for x in [startX..endX] tile = layer.getTile(x, y) if tile > -1 ### +----+ Actor moves from A1 to A2 | A1 | and collides with background tile Bg. | | Actor moves with vector (speedX, speedY) +----+ +----+ The angle between AcBc and the movement vector determines | A2 | if it is a horizontal or vertical collision. | Bc-----+ +--|-Ac | | Bg | +------+ ### if actor.speedX == 0 isHorizontalCollision = false else if actor.speedY == 0 isHorizontalCollision = true else # Get actor's foremost corner in the movement vector # and the backgrounds opposing corner a2Corner = {} bgCorner = {} if actor.speedX > 0 a2Corner.x = actor.posX + actor.colW bgCorner.x = x else a2Corner.x = actor.posX bgCorner.x = x + 1 if actor.speedY > 0 a2Corner.y = actor.posY + actor.colH bgCorner.y = y else a2Corner.y = actor.posY bgCorner.y = y + 1 # Determine by the angle if it is a horizontal or vertical collision movAng = Math.abs(actor.speedY / actor.speedX) colAng = Math.abs((a2Corner.y - bgCorner.y) / (a2Corner.x - bgCorner.x)) if movAng - colAng < 0.01 isHorizontalCollision = true else isHorizontalCollision = false if isHorizontalCollision # Horizontal collisions if actor.speedX > 0 # Going right. Is not an edge if the tile to the left is solid. neighborTile = layer.getTile(x, y, -1, 0) if neighborTile == -1 newPosX = x - actor.colW - 0.01 newSpeedX = 0 collisions.any = true collisions.right = true view.drawOnce {class:Line, x:x, y:y, x2:x, y2:y+1, strokeStyle:'rgba(0,128,0,0.9)'} #Debug else view.drawOnce {class:Line, x:x, y:y, x2:x, y2:y+1, strokeStyle:'rgba(255,64,0,0.6)'} #Debug else # Going left. Is not an edge if the tile to the right is solid. neighborTile = layer.getTile(x, y, 1, 0) if neighborTile == -1 newPosX = x + 1 newSpeedX = 0 collisions.any = true collisions.left = true view.drawOnce {class:Line, x:x+1, y:y, x2:x+1, y2:y+1, strokeStyle:'rgba(0,128,0,0.9)'} #Debug else view.drawOnce {class:Line, x:x+1, y:y, x2:x+1, y2:y+1, strokeStyle:'rgba(255,64,0,0.6)'} #Debug else # Vertical collisions if actor.speedY < 0 # Going up. Is not an edge if the tile upwards is solid. neighborTile = layer.getTile(x, y, 0, 1) if neighborTile == -1 newPosY = y + 1 newSpeedY = 0 collisions.any = true collisions.top = true view.drawOnce {class:Line, x:x, y:y+1, x2:x+1, y2:y+1, strokeStyle:'rgba(0,128,0,0.9)'} #Debug else view.drawOnce {class:Line, x:x, y:y+1, x2:x+1, y2:y+1, strokeStyle:'rgba(255,64,0,0.6)'} #Debug else if actor.speedY > 0 # Going down. Is not an edge if the tile downwards is solid. neighborTile = layer.getTile(x, y, 0, -1) if neighborTile == -1 newPosY = y - actor.colH newSpeedY = 0 collisions.any = true collisions.bottom = true view.drawOnce {class:Line, x:x, y:y, x2:x+1, y2:y, strokeStyle:'rgba(0,128,0,0.9)'} #Debug else view.drawOnce {class:Line, x:x, y:y, x2:x+1, y2:y, strokeStyle:'rgba(255,64,0,0.6)'} #Debug # Debug highlight block if neighborTile == -1 # Collision view.drawOnce {class:Rect, x:x, y:y, w:1, h:1, fillStyle:'rgba(0,255,0,0.6)'} #Debug else # Internal edge; no collision view.drawOnce {class:Rect, x:x, y:y, w:1, h:1, fillStyle:'rgba(255,255,0,0.5)'} #Debug # Apply new position and speed if o.reposition actor.posX = newPosX actor.posY = newPosY actor.speedX = newSpeedX actor.speedY = newSpeedY return collisions
124973
### Copyright (c) 2015 <NAME>. All rights reserved. ### collision = {} module.exports = collision Line = require('../classes/Line') Rect = require('../classes/Rect') util = require('./util') view = require('./view') collision.actorToLayer = (actor, layer, options) -> o = reposition: false o = util.merge(o, options) collisions = any: false bottom: false top: false left: false right: false friction: 1.0 #TODO: Get data from colliding tiles newPosX = actor.posX newPosY = actor.posY newSpeedX = actor.speedX newSpeedY = actor.speedY startX = actor.posX >> 0 endX = (actor.posX + actor.colW) >> 0 startY = actor.posY >> 0 endY = (actor.posY + actor.colH) >> 0 # Check if overlapping tiles are collidable for y in [startY..endY] for x in [startX..endX] tile = layer.getTile(x, y) if tile > -1 ### +----+ Actor moves from A1 to A2 | A1 | and collides with background tile Bg. | | Actor moves with vector (speedX, speedY) +----+ +----+ The angle between AcBc and the movement vector determines | A2 | if it is a horizontal or vertical collision. | Bc-----+ +--|-Ac | | Bg | +------+ ### if actor.speedX == 0 isHorizontalCollision = false else if actor.speedY == 0 isHorizontalCollision = true else # Get actor's foremost corner in the movement vector # and the backgrounds opposing corner a2Corner = {} bgCorner = {} if actor.speedX > 0 a2Corner.x = actor.posX + actor.colW bgCorner.x = x else a2Corner.x = actor.posX bgCorner.x = x + 1 if actor.speedY > 0 a2Corner.y = actor.posY + actor.colH bgCorner.y = y else a2Corner.y = actor.posY bgCorner.y = y + 1 # Determine by the angle if it is a horizontal or vertical collision movAng = Math.abs(actor.speedY / actor.speedX) colAng = Math.abs((a2Corner.y - bgCorner.y) / (a2Corner.x - bgCorner.x)) if movAng - colAng < 0.01 isHorizontalCollision = true else isHorizontalCollision = false if isHorizontalCollision # Horizontal collisions if actor.speedX > 0 # Going right. Is not an edge if the tile to the left is solid. neighborTile = layer.getTile(x, y, -1, 0) if neighborTile == -1 newPosX = x - actor.colW - 0.01 newSpeedX = 0 collisions.any = true collisions.right = true view.drawOnce {class:Line, x:x, y:y, x2:x, y2:y+1, strokeStyle:'rgba(0,128,0,0.9)'} #Debug else view.drawOnce {class:Line, x:x, y:y, x2:x, y2:y+1, strokeStyle:'rgba(255,64,0,0.6)'} #Debug else # Going left. Is not an edge if the tile to the right is solid. neighborTile = layer.getTile(x, y, 1, 0) if neighborTile == -1 newPosX = x + 1 newSpeedX = 0 collisions.any = true collisions.left = true view.drawOnce {class:Line, x:x+1, y:y, x2:x+1, y2:y+1, strokeStyle:'rgba(0,128,0,0.9)'} #Debug else view.drawOnce {class:Line, x:x+1, y:y, x2:x+1, y2:y+1, strokeStyle:'rgba(255,64,0,0.6)'} #Debug else # Vertical collisions if actor.speedY < 0 # Going up. Is not an edge if the tile upwards is solid. neighborTile = layer.getTile(x, y, 0, 1) if neighborTile == -1 newPosY = y + 1 newSpeedY = 0 collisions.any = true collisions.top = true view.drawOnce {class:Line, x:x, y:y+1, x2:x+1, y2:y+1, strokeStyle:'rgba(0,128,0,0.9)'} #Debug else view.drawOnce {class:Line, x:x, y:y+1, x2:x+1, y2:y+1, strokeStyle:'rgba(255,64,0,0.6)'} #Debug else if actor.speedY > 0 # Going down. Is not an edge if the tile downwards is solid. neighborTile = layer.getTile(x, y, 0, -1) if neighborTile == -1 newPosY = y - actor.colH newSpeedY = 0 collisions.any = true collisions.bottom = true view.drawOnce {class:Line, x:x, y:y, x2:x+1, y2:y, strokeStyle:'rgba(0,128,0,0.9)'} #Debug else view.drawOnce {class:Line, x:x, y:y, x2:x+1, y2:y, strokeStyle:'rgba(255,64,0,0.6)'} #Debug # Debug highlight block if neighborTile == -1 # Collision view.drawOnce {class:Rect, x:x, y:y, w:1, h:1, fillStyle:'rgba(0,255,0,0.6)'} #Debug else # Internal edge; no collision view.drawOnce {class:Rect, x:x, y:y, w:1, h:1, fillStyle:'rgba(255,255,0,0.5)'} #Debug # Apply new position and speed if o.reposition actor.posX = newPosX actor.posY = newPosY actor.speedX = newSpeedX actor.speedY = newSpeedY return collisions
true
### Copyright (c) 2015 PI:NAME:<NAME>END_PI. All rights reserved. ### collision = {} module.exports = collision Line = require('../classes/Line') Rect = require('../classes/Rect') util = require('./util') view = require('./view') collision.actorToLayer = (actor, layer, options) -> o = reposition: false o = util.merge(o, options) collisions = any: false bottom: false top: false left: false right: false friction: 1.0 #TODO: Get data from colliding tiles newPosX = actor.posX newPosY = actor.posY newSpeedX = actor.speedX newSpeedY = actor.speedY startX = actor.posX >> 0 endX = (actor.posX + actor.colW) >> 0 startY = actor.posY >> 0 endY = (actor.posY + actor.colH) >> 0 # Check if overlapping tiles are collidable for y in [startY..endY] for x in [startX..endX] tile = layer.getTile(x, y) if tile > -1 ### +----+ Actor moves from A1 to A2 | A1 | and collides with background tile Bg. | | Actor moves with vector (speedX, speedY) +----+ +----+ The angle between AcBc and the movement vector determines | A2 | if it is a horizontal or vertical collision. | Bc-----+ +--|-Ac | | Bg | +------+ ### if actor.speedX == 0 isHorizontalCollision = false else if actor.speedY == 0 isHorizontalCollision = true else # Get actor's foremost corner in the movement vector # and the backgrounds opposing corner a2Corner = {} bgCorner = {} if actor.speedX > 0 a2Corner.x = actor.posX + actor.colW bgCorner.x = x else a2Corner.x = actor.posX bgCorner.x = x + 1 if actor.speedY > 0 a2Corner.y = actor.posY + actor.colH bgCorner.y = y else a2Corner.y = actor.posY bgCorner.y = y + 1 # Determine by the angle if it is a horizontal or vertical collision movAng = Math.abs(actor.speedY / actor.speedX) colAng = Math.abs((a2Corner.y - bgCorner.y) / (a2Corner.x - bgCorner.x)) if movAng - colAng < 0.01 isHorizontalCollision = true else isHorizontalCollision = false if isHorizontalCollision # Horizontal collisions if actor.speedX > 0 # Going right. Is not an edge if the tile to the left is solid. neighborTile = layer.getTile(x, y, -1, 0) if neighborTile == -1 newPosX = x - actor.colW - 0.01 newSpeedX = 0 collisions.any = true collisions.right = true view.drawOnce {class:Line, x:x, y:y, x2:x, y2:y+1, strokeStyle:'rgba(0,128,0,0.9)'} #Debug else view.drawOnce {class:Line, x:x, y:y, x2:x, y2:y+1, strokeStyle:'rgba(255,64,0,0.6)'} #Debug else # Going left. Is not an edge if the tile to the right is solid. neighborTile = layer.getTile(x, y, 1, 0) if neighborTile == -1 newPosX = x + 1 newSpeedX = 0 collisions.any = true collisions.left = true view.drawOnce {class:Line, x:x+1, y:y, x2:x+1, y2:y+1, strokeStyle:'rgba(0,128,0,0.9)'} #Debug else view.drawOnce {class:Line, x:x+1, y:y, x2:x+1, y2:y+1, strokeStyle:'rgba(255,64,0,0.6)'} #Debug else # Vertical collisions if actor.speedY < 0 # Going up. Is not an edge if the tile upwards is solid. neighborTile = layer.getTile(x, y, 0, 1) if neighborTile == -1 newPosY = y + 1 newSpeedY = 0 collisions.any = true collisions.top = true view.drawOnce {class:Line, x:x, y:y+1, x2:x+1, y2:y+1, strokeStyle:'rgba(0,128,0,0.9)'} #Debug else view.drawOnce {class:Line, x:x, y:y+1, x2:x+1, y2:y+1, strokeStyle:'rgba(255,64,0,0.6)'} #Debug else if actor.speedY > 0 # Going down. Is not an edge if the tile downwards is solid. neighborTile = layer.getTile(x, y, 0, -1) if neighborTile == -1 newPosY = y - actor.colH newSpeedY = 0 collisions.any = true collisions.bottom = true view.drawOnce {class:Line, x:x, y:y, x2:x+1, y2:y, strokeStyle:'rgba(0,128,0,0.9)'} #Debug else view.drawOnce {class:Line, x:x, y:y, x2:x+1, y2:y, strokeStyle:'rgba(255,64,0,0.6)'} #Debug # Debug highlight block if neighborTile == -1 # Collision view.drawOnce {class:Rect, x:x, y:y, w:1, h:1, fillStyle:'rgba(0,255,0,0.6)'} #Debug else # Internal edge; no collision view.drawOnce {class:Rect, x:x, y:y, w:1, h:1, fillStyle:'rgba(255,255,0,0.5)'} #Debug # Apply new position and speed if o.reposition actor.posX = newPosX actor.posY = newPosY actor.speedX = newSpeedX actor.speedY = newSpeedY return collisions
[ { "context": "User'\n\nmodule.exports = new User(\n {\n \"_id\": \"teacher1\",\n \"testGroupNumber\": 169,\n \"anonymous\": fa", "end": 81, "score": 0.9923452138900757, "start": 73, "tag": "USERNAME", "value": "teacher1" }, { "context": " \"anonymous\": false,\n \"__v\": 0,\n \"email\": \"teacher1@example.com\",\n \"emails\": {\n \"recruitNotes\": {\n ", "end": 184, "score": 0.9999236464500427, "start": 164, "tag": "EMAIL", "value": "teacher1@example.com" }, { "context": " \"enabled\": false\n }\n },\n \"name\": \"Teacher Teacherson\",\n \"slug\": \"teacher-teacherson\",\n \"points\":", "end": 407, "score": 0.9991095066070557, "start": 389, "tag": "NAME", "value": "Teacher Teacherson" } ]
test/app/fixtures/teacher.coffee
cihatislamdede/codecombat
4,858
User = require 'models/User' module.exports = new User( { "_id": "teacher1", "testGroupNumber": 169, "anonymous": false, "__v": 0, "email": "teacher1@example.com", "emails": { "recruitNotes": { "enabled": true }, "anyNotes": { "enabled": true }, "generalNews": { "enabled": false } }, "name": "Teacher Teacherson", "slug": "teacher-teacherson", "points": 20, "earned": { "gems": 0 }, "referrer": "http://localhost:3000/", "activity": { "login": { "last": "2016-03-07T19:57:05.007Z", "count": 8, "first": "2016-02-26T23:59:15.181Z" } }, "volume": 1, "role": "teacher", "stripe": { "customerID": "cus_80OTFCpv2hArmT" }, "dateCreated": "2016-02-26T23:49:23.696Z" } )
182692
User = require 'models/User' module.exports = new User( { "_id": "teacher1", "testGroupNumber": 169, "anonymous": false, "__v": 0, "email": "<EMAIL>", "emails": { "recruitNotes": { "enabled": true }, "anyNotes": { "enabled": true }, "generalNews": { "enabled": false } }, "name": "<NAME>", "slug": "teacher-teacherson", "points": 20, "earned": { "gems": 0 }, "referrer": "http://localhost:3000/", "activity": { "login": { "last": "2016-03-07T19:57:05.007Z", "count": 8, "first": "2016-02-26T23:59:15.181Z" } }, "volume": 1, "role": "teacher", "stripe": { "customerID": "cus_80OTFCpv2hArmT" }, "dateCreated": "2016-02-26T23:49:23.696Z" } )
true
User = require 'models/User' module.exports = new User( { "_id": "teacher1", "testGroupNumber": 169, "anonymous": false, "__v": 0, "email": "PI:EMAIL:<EMAIL>END_PI", "emails": { "recruitNotes": { "enabled": true }, "anyNotes": { "enabled": true }, "generalNews": { "enabled": false } }, "name": "PI:NAME:<NAME>END_PI", "slug": "teacher-teacherson", "points": 20, "earned": { "gems": 0 }, "referrer": "http://localhost:3000/", "activity": { "login": { "last": "2016-03-07T19:57:05.007Z", "count": 8, "first": "2016-02-26T23:59:15.181Z" } }, "volume": 1, "role": "teacher", "stripe": { "customerID": "cus_80OTFCpv2hArmT" }, "dateCreated": "2016-02-26T23:49:23.696Z" } )
[ { "context": "er : 'Email or username'\n name : 'username'\n }\n {\n type : 'pas", "end": 2923, "score": 0.9992974996566772, "start": 2915, "tag": "USERNAME", "value": "username" }, { "context": "type : 'password'\n placeholder : 'Password'\n name : 'password'\n }\n ", "end": 3013, "score": 0.9928441643714905, "start": 3005, "tag": "PASSWORD", "value": "Password" }, { "context": "placeholder : 'Password'\n name : 'password'\n }\n ]\n buttons : [\n ", "end": 3048, "score": 0.6835718750953674, "start": 3040, "tag": "PASSWORD", "value": "password" } ]
src/lib/widgets/SignUp.coffee
dashersw/spark
1
goog.provide 'spark.widgets.SignUp' goog.require 'spark.core.View' goog.require 'spark.components.Form' class spark.widgets.SignUp extends spark.core.View ###* Ready to use customizable user sign up widget of Spark Framework. @constructor @export @param {Object=} options Class options. @param {*=} data Class data @extends {spark.core.View} ### constructor: (options = {}, data) -> options.withImage ?= options['withImage'] ? yes options.imageUrl or= options['imageUrl'] or 'http://lorempixel.com/460/144/city/4' options.title or= options['title'] or 'Sign Up' options.buttonTitle or= options['buttonTitle'] or 'Sign Up' options.buttonColor or= options['buttonColor'] or 'green' options.callback or= options['callback'] or null options.forgotPasswordCallback or= options['forgotPasswordCallback'] or null options.alreadyRegisteredCallback or= options['alreadyRegisteredCallback'] or null @getCssClass options, 'sign-up-widget' super options, data @createImage_() if options.withImage @createTitle_() @form = new spark.components.Form @getFormOptions_() @appendView @form @createLinks_() ###* Creates form title element. ### createTitle_: -> title = new spark.core.View template : @getOptions().title cssClass : 'title' @appendView title ###* Creates form header image if `withImage` option is set to true. ### createImage_: -> image = new spark.core.View tagName : 'img' attributes : src : @getOptions().imageUrl @appendView image @addClass 'with-image' ###* Creates Forgot Password and Already Registered links. ### createLinks_: -> {forgotPasswordCallback, alreadyRegisteredCallback} = @getOptions() registered = new spark.core.View tagName : 'a' template : 'Already Registered?' cssClass : 'already-registered' attributes : href: '#' events : click : => alreadyRegisteredCallback.call this if alreadyRegisteredCallback @emit 'AlreadyRegisteredLinkClicked' forgotPassword = new spark.core.View tagName : 'a' template : 'Forgot password?' cssClass : 'forgot-password' attributes : href: '#' events : click : => forgotPasswordCallback.call this if forgotPasswordCallback @emit 'ForgotPasswordLinkClicked' @appendView registered @form.getInputsContainer().appendView forgotPassword ###* Returns form options. @private @return {Object} Form options. ### getFormOptions_: -> options = @getOptions() formOptions = inputs : [ { type : 'text' placeholder : 'Email or username' name : 'username' } { type : 'password' placeholder : 'Password' name : 'password' } ] buttons : [ { title : options.buttonTitle cssClass : options.buttonColor callback : => options.callback.call this if options.callback @emit 'SignUpFormPosted' } ] return formOptions ###* Returns form instance. @export @return {spark.components.Form} ### getForm: -> return @form
37235
goog.provide 'spark.widgets.SignUp' goog.require 'spark.core.View' goog.require 'spark.components.Form' class spark.widgets.SignUp extends spark.core.View ###* Ready to use customizable user sign up widget of Spark Framework. @constructor @export @param {Object=} options Class options. @param {*=} data Class data @extends {spark.core.View} ### constructor: (options = {}, data) -> options.withImage ?= options['withImage'] ? yes options.imageUrl or= options['imageUrl'] or 'http://lorempixel.com/460/144/city/4' options.title or= options['title'] or 'Sign Up' options.buttonTitle or= options['buttonTitle'] or 'Sign Up' options.buttonColor or= options['buttonColor'] or 'green' options.callback or= options['callback'] or null options.forgotPasswordCallback or= options['forgotPasswordCallback'] or null options.alreadyRegisteredCallback or= options['alreadyRegisteredCallback'] or null @getCssClass options, 'sign-up-widget' super options, data @createImage_() if options.withImage @createTitle_() @form = new spark.components.Form @getFormOptions_() @appendView @form @createLinks_() ###* Creates form title element. ### createTitle_: -> title = new spark.core.View template : @getOptions().title cssClass : 'title' @appendView title ###* Creates form header image if `withImage` option is set to true. ### createImage_: -> image = new spark.core.View tagName : 'img' attributes : src : @getOptions().imageUrl @appendView image @addClass 'with-image' ###* Creates Forgot Password and Already Registered links. ### createLinks_: -> {forgotPasswordCallback, alreadyRegisteredCallback} = @getOptions() registered = new spark.core.View tagName : 'a' template : 'Already Registered?' cssClass : 'already-registered' attributes : href: '#' events : click : => alreadyRegisteredCallback.call this if alreadyRegisteredCallback @emit 'AlreadyRegisteredLinkClicked' forgotPassword = new spark.core.View tagName : 'a' template : 'Forgot password?' cssClass : 'forgot-password' attributes : href: '#' events : click : => forgotPasswordCallback.call this if forgotPasswordCallback @emit 'ForgotPasswordLinkClicked' @appendView registered @form.getInputsContainer().appendView forgotPassword ###* Returns form options. @private @return {Object} Form options. ### getFormOptions_: -> options = @getOptions() formOptions = inputs : [ { type : 'text' placeholder : 'Email or username' name : 'username' } { type : 'password' placeholder : '<PASSWORD>' name : '<PASSWORD>' } ] buttons : [ { title : options.buttonTitle cssClass : options.buttonColor callback : => options.callback.call this if options.callback @emit 'SignUpFormPosted' } ] return formOptions ###* Returns form instance. @export @return {spark.components.Form} ### getForm: -> return @form
true
goog.provide 'spark.widgets.SignUp' goog.require 'spark.core.View' goog.require 'spark.components.Form' class spark.widgets.SignUp extends spark.core.View ###* Ready to use customizable user sign up widget of Spark Framework. @constructor @export @param {Object=} options Class options. @param {*=} data Class data @extends {spark.core.View} ### constructor: (options = {}, data) -> options.withImage ?= options['withImage'] ? yes options.imageUrl or= options['imageUrl'] or 'http://lorempixel.com/460/144/city/4' options.title or= options['title'] or 'Sign Up' options.buttonTitle or= options['buttonTitle'] or 'Sign Up' options.buttonColor or= options['buttonColor'] or 'green' options.callback or= options['callback'] or null options.forgotPasswordCallback or= options['forgotPasswordCallback'] or null options.alreadyRegisteredCallback or= options['alreadyRegisteredCallback'] or null @getCssClass options, 'sign-up-widget' super options, data @createImage_() if options.withImage @createTitle_() @form = new spark.components.Form @getFormOptions_() @appendView @form @createLinks_() ###* Creates form title element. ### createTitle_: -> title = new spark.core.View template : @getOptions().title cssClass : 'title' @appendView title ###* Creates form header image if `withImage` option is set to true. ### createImage_: -> image = new spark.core.View tagName : 'img' attributes : src : @getOptions().imageUrl @appendView image @addClass 'with-image' ###* Creates Forgot Password and Already Registered links. ### createLinks_: -> {forgotPasswordCallback, alreadyRegisteredCallback} = @getOptions() registered = new spark.core.View tagName : 'a' template : 'Already Registered?' cssClass : 'already-registered' attributes : href: '#' events : click : => alreadyRegisteredCallback.call this if alreadyRegisteredCallback @emit 'AlreadyRegisteredLinkClicked' forgotPassword = new spark.core.View tagName : 'a' template : 'Forgot password?' cssClass : 'forgot-password' attributes : href: '#' events : click : => forgotPasswordCallback.call this if forgotPasswordCallback @emit 'ForgotPasswordLinkClicked' @appendView registered @form.getInputsContainer().appendView forgotPassword ###* Returns form options. @private @return {Object} Form options. ### getFormOptions_: -> options = @getOptions() formOptions = inputs : [ { type : 'text' placeholder : 'Email or username' name : 'username' } { type : 'password' placeholder : 'PI:PASSWORD:<PASSWORD>END_PI' name : 'PI:PASSWORD:<PASSWORD>END_PI' } ] buttons : [ { title : options.buttonTitle cssClass : options.buttonColor callback : => options.callback.call this if options.callback @emit 'SignUpFormPosted' } ] return formOptions ###* Returns form instance. @export @return {spark.components.Form} ### getForm: -> return @form
[ { "context": ") ->\n\t# NB: special Array case http://web.mit.edu/jwalden/www/isArray.html\n\tif Array.isArray(type) then swi", "end": 282, "score": 0.9994259476661682, "start": 275, "tag": "USERNAME", "value": "jwalden" }, { "context": " Object # Object type, e.g.: `{id: Number, name: {firstName: String, lastName: String}}`\n\t\t\treturn false unle", "end": 2052, "score": 0.8218985795974731, "start": 2043, "tag": "NAME", "value": "firstName" }, { "context": "ype, e.g.: `{id: Number, name: {firstName: String, lastName: String}}`\n\t\t\treturn false unless val?.constructo", "end": 2070, "score": 0.5433670878410339, "start": 2062, "tag": "NAME", "value": "lastName" } ]
src/isValid.coffee
laurentpayot/rflow
19
import {isAny, isEmptyObject} from './tools' import typeOf from './typeOf' import Type from './types/Type' # check that a value is of a given type or of any (undefined) type, e.g.: isValid("foo", String) isValid = (type, val) -> # NB: special Array case http://web.mit.edu/jwalden/www/isArray.html if Array.isArray(type) then switch type.length when 0 then Array.isArray(val) and not val.length # empty array: `[]` when 1 then switch when not Array.isArray(val) then false when isAny(type[0]) then true when not Object.values(type).length then val.length is 1 # array of one empty value: sized array `Array(1)` else # typed array type, e.g.: `Array(String)` # optimizing for native types switch t = type[0] # not `f = switch…` to optimize CoffeeScript code generation when Number then f = Number.isFinite # Number.isFinite(NaN) is falsy when String, Boolean, Object then f = (e) -> try e.constructor is t when Array then f = Array.isArray else f = (e) -> isValid(t, e) # unoptimized val.every(f) else # NB: checking two first values instead of `Object.values(type).length` for performance reasons if type[0] is undefined and type[1] is undefined # array of empty values: sized array, e.g.: `Array(1000)`) Array.isArray(val) and val.length is type.length else # union of types, e.g.: `[Object, null]` type.some((t) -> isValid(t, val)) else switch type?.constructor when undefined, String, Number, Boolean # literal type (including ±Infinity and NaN) or undefined or null if Number.isNaN(type) then Number.isNaN(val) else val is type # custom type helpers, constructors of native types (String, Number (excluding ±Infinity), Object…), custom classes when Function then switch when type.rootClass is Type then type().validate(val) # type is a helper, using its default arguments when type is Array then Array.isArray(val) when type is Number then Number.isFinite(val) else val?.constructor is type when Object # Object type, e.g.: `{id: Number, name: {firstName: String, lastName: String}}` return false unless val?.constructor is Object if not isEmptyObject(type) for k, t of type return false unless isValid(t, val[k]) true else isEmptyObject(val) when RegExp then val?.constructor is String and type.test(val) else if type instanceof Type type.validate(val) else prefix = if type.constructor in [Set, Map] then 'the provided Typed' else '' Type.invalid "Type can not be an instance of #{typeOf(type)}. Use #{prefix}#{typeOf(type)} as type instead." export default isValid
188979
import {isAny, isEmptyObject} from './tools' import typeOf from './typeOf' import Type from './types/Type' # check that a value is of a given type or of any (undefined) type, e.g.: isValid("foo", String) isValid = (type, val) -> # NB: special Array case http://web.mit.edu/jwalden/www/isArray.html if Array.isArray(type) then switch type.length when 0 then Array.isArray(val) and not val.length # empty array: `[]` when 1 then switch when not Array.isArray(val) then false when isAny(type[0]) then true when not Object.values(type).length then val.length is 1 # array of one empty value: sized array `Array(1)` else # typed array type, e.g.: `Array(String)` # optimizing for native types switch t = type[0] # not `f = switch…` to optimize CoffeeScript code generation when Number then f = Number.isFinite # Number.isFinite(NaN) is falsy when String, Boolean, Object then f = (e) -> try e.constructor is t when Array then f = Array.isArray else f = (e) -> isValid(t, e) # unoptimized val.every(f) else # NB: checking two first values instead of `Object.values(type).length` for performance reasons if type[0] is undefined and type[1] is undefined # array of empty values: sized array, e.g.: `Array(1000)`) Array.isArray(val) and val.length is type.length else # union of types, e.g.: `[Object, null]` type.some((t) -> isValid(t, val)) else switch type?.constructor when undefined, String, Number, Boolean # literal type (including ±Infinity and NaN) or undefined or null if Number.isNaN(type) then Number.isNaN(val) else val is type # custom type helpers, constructors of native types (String, Number (excluding ±Infinity), Object…), custom classes when Function then switch when type.rootClass is Type then type().validate(val) # type is a helper, using its default arguments when type is Array then Array.isArray(val) when type is Number then Number.isFinite(val) else val?.constructor is type when Object # Object type, e.g.: `{id: Number, name: {<NAME>: String, <NAME>: String}}` return false unless val?.constructor is Object if not isEmptyObject(type) for k, t of type return false unless isValid(t, val[k]) true else isEmptyObject(val) when RegExp then val?.constructor is String and type.test(val) else if type instanceof Type type.validate(val) else prefix = if type.constructor in [Set, Map] then 'the provided Typed' else '' Type.invalid "Type can not be an instance of #{typeOf(type)}. Use #{prefix}#{typeOf(type)} as type instead." export default isValid
true
import {isAny, isEmptyObject} from './tools' import typeOf from './typeOf' import Type from './types/Type' # check that a value is of a given type or of any (undefined) type, e.g.: isValid("foo", String) isValid = (type, val) -> # NB: special Array case http://web.mit.edu/jwalden/www/isArray.html if Array.isArray(type) then switch type.length when 0 then Array.isArray(val) and not val.length # empty array: `[]` when 1 then switch when not Array.isArray(val) then false when isAny(type[0]) then true when not Object.values(type).length then val.length is 1 # array of one empty value: sized array `Array(1)` else # typed array type, e.g.: `Array(String)` # optimizing for native types switch t = type[0] # not `f = switch…` to optimize CoffeeScript code generation when Number then f = Number.isFinite # Number.isFinite(NaN) is falsy when String, Boolean, Object then f = (e) -> try e.constructor is t when Array then f = Array.isArray else f = (e) -> isValid(t, e) # unoptimized val.every(f) else # NB: checking two first values instead of `Object.values(type).length` for performance reasons if type[0] is undefined and type[1] is undefined # array of empty values: sized array, e.g.: `Array(1000)`) Array.isArray(val) and val.length is type.length else # union of types, e.g.: `[Object, null]` type.some((t) -> isValid(t, val)) else switch type?.constructor when undefined, String, Number, Boolean # literal type (including ±Infinity and NaN) or undefined or null if Number.isNaN(type) then Number.isNaN(val) else val is type # custom type helpers, constructors of native types (String, Number (excluding ±Infinity), Object…), custom classes when Function then switch when type.rootClass is Type then type().validate(val) # type is a helper, using its default arguments when type is Array then Array.isArray(val) when type is Number then Number.isFinite(val) else val?.constructor is type when Object # Object type, e.g.: `{id: Number, name: {PI:NAME:<NAME>END_PI: String, PI:NAME:<NAME>END_PI: String}}` return false unless val?.constructor is Object if not isEmptyObject(type) for k, t of type return false unless isValid(t, val[k]) true else isEmptyObject(val) when RegExp then val?.constructor is String and type.test(val) else if type instanceof Type type.validate(val) else prefix = if type.constructor in [Set, Map] then 'the provided Typed' else '' Type.invalid "Type can not be an instance of #{typeOf(type)}. Use #{prefix}#{typeOf(type)} as type instead." export default isValid
[ { "context": "= {\n\t\t\tstripeId: 'cus_HtT1Ke62Z248Bj',\n\t\t\temail: 'victor.cottin+1598277023896@gmail.com',\n\t\t\taddress: {},\n\t\t\tvatCountry: undefined,\n\t\t\tco", "end": 10062, "score": 0.9999143481254578, "start": 10025, "tag": "EMAIL", "value": "victor.cottin+1598277023896@gmail.com" } ]
src/test__ramda-extras.coffee
Cottin/ramda-extras
3
{add, append, dec, empty, evolve, inc, isNil, match, merge, path, prop, reduce, reject, remove, replace, set, type, values, where} = R = require 'ramda' #auto_require: ramda {change, changeM, pickRec, isAffected, diff, toggle, cc, cc_, doto, doto_, $, $_, $$, $$_, superFlip, isNilOrEmpty, PromiseProps, undef, satisfies, reshape} = RE = require 'ramda-extras' #auto_require: ramda-extras [ːb, ːa] = ['b', 'a'] #auto_sugar qq = (f) -> console.log match(/return (.*);/, f.toString())[1], f() qqq = (...args) -> console.log ...args _ = (...xs) -> xs {eq, deepEq, deepEq_, fdeepEq, throws} = require 'testhelp' #auto_require: testhelp {undef, isNilOrEmpty, change, changeM, toggle, isAffected, diff, pickRec, superFlip, doto, doto_, $$, $$_, cc, cc_, PromiseProps, qq, qqq, satisfies, dottedApi, recursiveProxy, reshape} = RE = require './ramda-extras' describe 'isNilOrEmpty', -> it 'simple', -> eq false, isNilOrEmpty(' ') eq true, isNilOrEmpty('') eq false, isNilOrEmpty([1]) eq true, isNilOrEmpty([]) eq false, isNilOrEmpty({a: 1}) eq true, isNilOrEmpty({}) describe 'toggle', -> it 'simple', -> deepEq [1, 2, 3], toggle 3, [1, 2] deepEq [1, 2], toggle(3, [1, 2, 3]) deepEq [3], toggle(3, []) deepEq [3], toggle(3, undefined) describe 'change', -> changeTester = (spec, a, undo, total) -> res = change.meta spec, a, undo, total return [res, undo, total] meta = true # changeTester = (spec, a, total) -> # res = change spec, a # return res # meta = false it 'merge number + empty total', -> res = changeTester {a: 1}, {}, {}, {} if meta then deepEq [{a: 1}, {a: undefined}, {a: 1}], res else deepEq {a: 1}, res it 'remove key + extra key in total', -> res = changeTester {a: undefined}, {a: 1, b: 2}, {}, {c: undefined} deepEq [{b: 2}, {a: 1}, {a: undefined, c: undefined}], res it 'remove key of empty obj + same key in total', -> # {a: 1} {} {} res = changeTester {a: undefined}, {}, {}, {a: undefined} deepEq [{}, {}, {a: undefined}], res # it 'set key + same key in undo', -> # # {a: 1} {} {} # res = changeTester {a: 2, b: 1}, {}, {a: 1}, {a: 0} # deepEq_ [{a: 2, b: 1}, {a: 1}, {a: 2, b: 1}], res it 'set to null', -> res = changeTester {a: null}, {a: 1, b: 2}, {}, {a: 2} deepEq [{a: null, b: 2}, {a: 1}, {a: null}], res it 'function', -> res = changeTester (({a, b}) -> {a: inc(a), b: dec(b), c: 1}), {a: 1, b: 2}, {}, {a: 2, d: 3} deepEq_ [{a: 2, b: 1, c: 1}, {}, {a: 2, d: 3}], res it 'date', -> date1 = new Date res = changeTester {a: date1}, {a: 1, b: 2}, {}, {a: 2} deepEq_ [{a: date1, b: 2}, {a: 1}, {a: date1}], res it 'merge array + same key in total', -> res = changeTester {a: [2, 3]}, {a: [1]}, {}, {a: [5]} deepEq [{a: [2, 3]}, {a: [1]}, {a: [2, 3]}], res it 'evolve if using function', -> res = changeTester {a: inc}, {a: 1}, {}, {} deepEq [{a: 2}, {a: 1}, {a: 2}], res it 'evolve if using function and create key if not there', -> res = changeTester {a: (x) -> if isNil(x) then 1 else inc}, {}, {}, {} deepEq [{a: 1}, {a: undefined}, {a: 1}], res it 'evolve if using function but dont create key on undefined value', -> res = changeTester {a: (x) -> if isNil(x) then undefined else inc}, {b: 2}, {}, {} deepEq [{b: 2}, {}, {}], res it 'undefined in function = "fancy toggle"', -> res = changeTester {a: (x) -> if x then undefined else true}, {b: 2}, {}, {} deepEq [{a: true, b: 2}, {a: undefined}, {a: true}], res res = changeTester {a: (x) -> if x then undefined else true}, {a: true, b: 2}, {}, {} deepEq [{b: 2}, {a: true}, {a: undefined}], res it 'reuses values from spec', -> a = {a: null, b2: 3} delta = {a: [1, 2, 3]} res = changeTester delta, a eq delta.a, res[0].a describe 'nested', -> it 'merge number', -> a = {a: {a1: null, a2: 0}, b2: 3} res = changeTester {a: {a1: 1}}, a, {}, {} eres = {a: {a1: 1, a2: 0}, b2: 3} if meta then deepEq [eres, {a: {a1: null}}, {a: {a1: 1}}], res else deepEq_ eres, res it 'remove key', -> a = {a: {a1: null, a2: 0}, b2: 3} res = changeTester {a: {a1: undefined}}, a, {}, {a: {a1: null, a2: 0}} total = {a: {a1: undefined, a2: 0}} deepEq [{a: {a2: 0}, b2: 3}, {a: {a1: null}}, total], res it 'replace array', -> a = {a: {a1: [1, 2, 3], a2: 0}, b2: 3} res = changeTester {a: {a1: [1, 2, 3, 4]}}, a, {}, {a: {a3: undefined}} deepEq [{a: {a1: [1, 2, 3, 4], a2: 0}, b2: 3}, {a: {a1: [1, 2, 3]}}, {a: {a1: [1, 2, 3, 4], a3: undefined}}], res it 'evolve using function', -> a = {a: {a1: [1, 2, 3], a2: 0}, b2: 3} res = changeTester {a: {a1: append(4)}}, a, {}, {b2: 3} deepEq [{a: {a1: [1, 2, 3, 4], a2: 0}, b2: 3}, {a: {a1: [1, 2, 3]}}, {a: {a1: [1, 2, 3, 4]}, b2: 3}], res it 'evolve using function where there is no key', -> a = {b2: 3} res = changeTester {a: {a1: (x) -> if x then append(4) else [4]}}, a, {}, {b2: 3} deepEq [{a: {a1: [4]}, b2: 3}, {a: undefined}, {a: {a1: [4]}, b2: 3}], res describe 'changeM specifics', -> changeMTester = (spec, a, undo, total) -> res = changeM.meta spec, a, undo, total return [res, undo, total] it 'strict equality', -> a = {a: {a1: {a12: 2}}} res = changeMTester {a: {a1: {a11: 1}}}, a, {}, {a: {a1: {a12: 2}}} deepEq [{a: {a1: {a11: 1, a12: 2}}}, {a: {a1: {a11: undefined}}}, {a: {a1: {a11: 1, a12: 2}}}], res eq true, a == res[0] describe 'isAffected', -> it 'simple', -> eq true, isAffected {a: null}, {a: 1} it 'dep deeper', -> eq true, isAffected {a: {a1: {a11: null}}}, {a: undefined} it 'total deeper', -> eq true, isAffected {a: null}, {a: {a1: {a11: undefined}}} it 'deep false', -> eq false, isAffected {a: {a1: {a11: {a111: null}}}}, {a: {a1: {a11: {a112: undefined}}}} describe 'diff', -> it 'missing', -> res = diff {ab: 1}, {} deepEq {ab: undefined}, res it 'extra', -> res = diff {}, {ab: 1} deepEq {ab: 1}, res it 'changed', -> res = diff {ab: 1}, {ab: 2} deepEq {ab: 2}, res it 'no change value', -> res = diff {ab: true}, {ab: true} deepEq {}, res it 'no change array', -> res = diff {ab: [1, 2]}, {ab: [1, 2]} deepEq {}, res it 'reuses values from b', -> a = {ab: null} b = {ab: [1, 2, 3]} res = diff a, b eq b.ab, res.ab describe 'nested', -> it 'extra empty', -> res = diff {a: null}, {a: {}} deepEq {a: {}}, res it 'missing', -> res = diff {a: {a1: 1}}, {a: {}} deepEq {a: {a1: undefined}}, res it 'extra', -> res = diff {a: {}, b: {b1: 1}}, {a: {a1: 1}, b: {b1: 1}} deepEq {a: {a1: 1}}, res it 'changed', -> a = {a: {a1: 1, a2: 0}, b: {b1: 1}} b = {a: {a1: 2, a2: 0}, b: {b1: 1}} res = diff a, b deepEq {a: {a1: 2}}, res it 'no change', -> a = {a: {a1: 1, a2: 0}, b: {b1: 1}} b = {a: {a1: 1, a2: 0}, b: {b1: 1}} res = diff a, b deepEq {}, res it 'changed to object in b', -> a = {a: {a1: 1, a2: 0}, b: {b1: 1}} b = {a: {a1: {a11: 1}, a2: 0}, b: {b1: 1}} res = diff a, b deepEq {a: {a1: {a11: 1}}}, res it 'changed to object in b from array', -> a = {a: {a1: ['a11', 'a12'], a2: 0}, b: {b1: 1}} b = {a: {a1: {a11: 1}, a2: 0}, b: {b1: 1}} res = diff a, b deepEq {a: {a1: {a11: 1}}}, res it 'reuses values from b', -> a = {a: {a1: 1, a2: 0}, b: {b1: 1}} b = {a: {a1: {a11: 1}, a2: 0}, b: {b1: 1}} res = diff a, b eq b.a.a1, res.a.a1 it 'function', -> throws /diff does not support functions/, -> diff {a: {a1: 1}}, {a: {a1: ->}} it 'RegExp', -> throws /diff does not support RegExps/, -> diff {a: {a1: 1}}, {a: {a1: /a/}} describe 'pickRec', -> it 'shallow', -> res = pickRec ['a', 'b'], {a: 1, b: 2, c: 3} deepEq {a: 1, b: 2}, res it 'two levels', -> res = pickRec ['a.a1', 'b'], {a: {a1: 1, a2: 2}, b: 2, c: 3} deepEq {a: {a1: 1}, b: 2}, res it 'three levels', -> obj = {a: {a1: {a11: 1, a12: 2, a13: 3}, a2: 2}, b: 2, c: 3} res = pickRec ['a.a1.a12', 'a.a1.a13', 'b'], obj deepEq {a: {a1: {a12: 2, a13: 3}}, b: 2}, res it 'missing', -> obj = {a: {a1: {a11: 1, a12: 2}, a2: 2}, b: 2, c: 3} res = pickRec ['a.a1.a12', 'a.a1.a13', 'b'], obj deepEq {a: {a1: {a12: 2}}, b: 2}, res it 'empty', -> obj = {a: {a1: {a11: 1, a12: 2}, a2: 2}, b: 2, c: 3} res = pickRec [], obj deepEq {}, res describe 'superFlip', -> it '2 args', -> deepEq {a: 1}, superFlip(merge)({a: 1}, {a: 2}) it '3 args', -> eq 3, superFlip(reduce)([1,2], 0, add) describe 'doto', -> it 'simple case', -> eq 5, doto(2, add(1), add(2)) it 'with log', -> eq 5, doto_(2, add(1), add(2)) describe 'undef', -> it '1', -> eq undefined, undef(-> 1)() describe 'dotoCompose', -> it 'simple case', -> deepEq [1, 2, 3], $$([1], append(3), append(2)) it 'with log', -> deepEq [1, 2, 3], $$_([1], append(3), append(2)) describe 'PromiseProps', -> # https://stackoverflow.com/a/45286517/416797 reso = (ms) -> new Promise (rs, rj) -> setTimeout (() ->rs(1)), ms reje = (ms) -> new Promise (rs, rj) -> setTimeout (() ->rj(666)), ms it 'simple success', -> res = await PromiseProps({a: reso(10), b: reso(5)}) deepEq {a: 1, b: 1}, res it 'simple reject', -> try res = await PromiseProps({a: reso(10), b: reje(5)}) catch err eq 666, err describe 'cc', -> it 'simple case', -> eq 7, cc( add(1), add(2), 4) it 'with log', -> eq 7, cc_(add(1), add(2), 4) describe 'fliped stuff', -> it 'simple cases', -> eq 'Function', type RE.freduce # describe 'qq', -> # it 'simple cases', -> # eq undefined, qq -> 1 # eq undefined, qqq -> 1 describe 'satisfies', -> sat = satisfies it 'String', -> def = { stripeId〳: String email: String # email address〳: line1: String # address.line1 postal〳: String # address.postal_code city〳: String # address.city region〳: String # address.region vatCountry: String # Always metadata.vatCountry. If using address, also address.country company〳: name: String # name vatNo〳: String # TaxId.value } data = { stripeId: 'cus_HtT1Ke62Z248Bj', email: 'victor.cottin+1598277023896@gmail.com', address: {}, vatCountry: undefined, company: { name: 'We Code Better Nordic AB', vatNo: undefined } } deepEq {a: 1}, sat data, def # deepEq {a: 1}, sat {a: {a1: 1}}, {a: String} # deepEq {}, sat {a: 'a'}, {a: String} # it.only 'String', -> # deepEq {a: 1}, sat {a: 1}, {a: String} # deepEq {}, sat {a: 'a'}, {a: String} it 'Number', -> deepEq {a: ''}, sat {a: ''}, {a: Number} deepEq {}, sat {a: 1}, {a: Number} it 'Boolean', -> deepEq {a: 0}, sat {a: 0}, {a: Boolean} deepEq {}, sat {a: true}, {a: Boolean} it 'Function', -> deepEq {a: 0}, sat {a: 0}, {a: ->} deepEq {}, sat {a: ->}, {a: ->} it 'AsyncFunction', -> deepEq {}, sat {a: -> await 1}, {a: -> 2} throws /not yet support type AsyncFunction/, -> sat {a: 0}, {a: -> await 1} it 'Object', -> deepEq {a: 0}, sat {a: 0}, {a: Object} deepEq {}, sat {a: {}}, {a: Object} it 'Enum', -> deepEq {a: 3}, sat {a: 3}, {a: new Set([1, 2])} deepEq {}, sat {a: 2}, {a: new Set([1, 2])} deepEq {}, sat {}, {a〳: new Set([1, 2])} it 'required 1', -> deepEq {a: 'MISSING'}, sat {b: 1}, {a: Number}, true it 'required 2', -> deepEq {a: 'MISSING', b: 'NOT_IN_SPEC'}, sat {b: 1}, {a: Number}, false it 'required 3', -> deepEq {}, sat {b: 1}, {a〳: Number}, true it 'required 4', -> deepEq {a: 'MISSING'}, sat {}, {a: Number}, false it 'required object', -> deepEq {a: 'MISSING', b: 'NOT_IN_SPEC'}, sat {b: 1}, {a: Object} deepEq {}, sat {a: {}}, {a: Object} it 'optional', -> deepEq {}, sat {b: 1}, {a〳: Number, b: Number} it 'optional with undefined', -> deepEq {}, sat {a: undefined, b: 1}, {a〳: Number, b: Number} describe 'array', -> it 'Null', -> deepEq {a: 'MISSING (null)'}, sat {a: null}, {a: [String]} it 'String', -> deepEq {a: [1]}, sat {a: [1, '']}, {a: [String]} deepEq {}, sat {a: ['', '2']}, {a: [String]} it 'Number', -> deepEq {a: ['']}, sat {a: [1, '']}, {a: [Number]} deepEq {}, sat {a: [1, 2]}, {a: [Number]} it 'Boolean', -> deepEq {a: [1]}, sat {a: [1, true]}, {a: [Boolean]} deepEq {}, sat {a: [true, false]}, {a: [Boolean]} it 'Number or null', -> deepEq {a: [true]}, sat {a: [true, null]}, {a: [Number, null]} deepEq {}, sat {a: [1, null]}, {a: [Number, null]} it 'Object', -> deepEq {a: [{b: 2}]}, sat {a: [{b: '1'}, {b: 2}]}, {a: [{b: String}]} deepEq {}, sat {a: [{b: '1'}, {b: '2'}]}, {a: [{b: String}]} it 'Object extra fields', -> deepEq {a: [{b: 2}]}, sat {a: [{b: '1', c: 1}, {b: 2}]}, {a: [{b: String}]} deepEq {}, sat {a: [{b: '1', c: 1}, {b: '2'}]}, {a: [{b: String}]} it 'Object or null', -> deepEq {a: [{b: true}]}, sat {a: [{b: true}, null]}, {a: [{b: Number}, null]} deepEq {}, sat {a: [{b: 1}, null]}, {a: [{b: Number}, null]} describe 'object', -> it 'String, Number, Boolean', -> deepEq {a: {n: ''}}, sat {a: {s: '', n: '', b: true}}, {a: {s: String, n: Number, b: Boolean}} deepEq {}, sat {a: {s: '', n: 1, b: true}}, {a: {s: String, n: Number, b: Boolean}} describe 'dottedApi', -> it '1', -> fns = dottedApi {a: ['a1', 'a2'], b: ['b1', 'b2'], c: ['c1', 'c2']}, (args) -> {e: 'e1', ...args} res = fns.b2.c2.a1 {d: 'd1'} fdeepEq res, {a: 'a1', b: 'b2', c: 'c2', d: 'd1', e: 'e1'} it 'same value', -> throws /cannot have duplicate value/, -> dottedApi {a: ['a1', 'a2'], b: ['a1', 'b2'], c: ['c1', 'c2']}, (args) -> {e: 'e1', ...args} describe 'recursiveProxy', -> handler = (ref) -> get: (o, prop, path) -> ref.value = path return o[prop] it '1', -> ref = {value: null} proxy = recursiveProxy {a: {a1: {a11: [1, 2, 3]}}, b: 2, c: [{c1: [{c11: 1, c12: 2}]}]}, handler(ref) deepEq [1, 2, 3], proxy.a.a1.a11 deepEq 'a.a1.a11', ref.value proxy.c[0].c1[0].c12 deepEq 'c.c1.c12', ref.value describe 'reshape', -> it '1', -> deepEq {a1: 1}, reshape {a1: ːa}, {a: 1} it '2', -> deepEq {a1: 1, b: 2}, reshape {a1: ːa, ːb}, {a: 1, b: 2} it '3', -> deepEq {a1: {a11: 1, b: 2}, b: 2}, reshape {a1: {a11: ːa, ːb}, ːb}, {a: 1, b: 2}
4127
{add, append, dec, empty, evolve, inc, isNil, match, merge, path, prop, reduce, reject, remove, replace, set, type, values, where} = R = require 'ramda' #auto_require: ramda {change, changeM, pickRec, isAffected, diff, toggle, cc, cc_, doto, doto_, $, $_, $$, $$_, superFlip, isNilOrEmpty, PromiseProps, undef, satisfies, reshape} = RE = require 'ramda-extras' #auto_require: ramda-extras [ːb, ːa] = ['b', 'a'] #auto_sugar qq = (f) -> console.log match(/return (.*);/, f.toString())[1], f() qqq = (...args) -> console.log ...args _ = (...xs) -> xs {eq, deepEq, deepEq_, fdeepEq, throws} = require 'testhelp' #auto_require: testhelp {undef, isNilOrEmpty, change, changeM, toggle, isAffected, diff, pickRec, superFlip, doto, doto_, $$, $$_, cc, cc_, PromiseProps, qq, qqq, satisfies, dottedApi, recursiveProxy, reshape} = RE = require './ramda-extras' describe 'isNilOrEmpty', -> it 'simple', -> eq false, isNilOrEmpty(' ') eq true, isNilOrEmpty('') eq false, isNilOrEmpty([1]) eq true, isNilOrEmpty([]) eq false, isNilOrEmpty({a: 1}) eq true, isNilOrEmpty({}) describe 'toggle', -> it 'simple', -> deepEq [1, 2, 3], toggle 3, [1, 2] deepEq [1, 2], toggle(3, [1, 2, 3]) deepEq [3], toggle(3, []) deepEq [3], toggle(3, undefined) describe 'change', -> changeTester = (spec, a, undo, total) -> res = change.meta spec, a, undo, total return [res, undo, total] meta = true # changeTester = (spec, a, total) -> # res = change spec, a # return res # meta = false it 'merge number + empty total', -> res = changeTester {a: 1}, {}, {}, {} if meta then deepEq [{a: 1}, {a: undefined}, {a: 1}], res else deepEq {a: 1}, res it 'remove key + extra key in total', -> res = changeTester {a: undefined}, {a: 1, b: 2}, {}, {c: undefined} deepEq [{b: 2}, {a: 1}, {a: undefined, c: undefined}], res it 'remove key of empty obj + same key in total', -> # {a: 1} {} {} res = changeTester {a: undefined}, {}, {}, {a: undefined} deepEq [{}, {}, {a: undefined}], res # it 'set key + same key in undo', -> # # {a: 1} {} {} # res = changeTester {a: 2, b: 1}, {}, {a: 1}, {a: 0} # deepEq_ [{a: 2, b: 1}, {a: 1}, {a: 2, b: 1}], res it 'set to null', -> res = changeTester {a: null}, {a: 1, b: 2}, {}, {a: 2} deepEq [{a: null, b: 2}, {a: 1}, {a: null}], res it 'function', -> res = changeTester (({a, b}) -> {a: inc(a), b: dec(b), c: 1}), {a: 1, b: 2}, {}, {a: 2, d: 3} deepEq_ [{a: 2, b: 1, c: 1}, {}, {a: 2, d: 3}], res it 'date', -> date1 = new Date res = changeTester {a: date1}, {a: 1, b: 2}, {}, {a: 2} deepEq_ [{a: date1, b: 2}, {a: 1}, {a: date1}], res it 'merge array + same key in total', -> res = changeTester {a: [2, 3]}, {a: [1]}, {}, {a: [5]} deepEq [{a: [2, 3]}, {a: [1]}, {a: [2, 3]}], res it 'evolve if using function', -> res = changeTester {a: inc}, {a: 1}, {}, {} deepEq [{a: 2}, {a: 1}, {a: 2}], res it 'evolve if using function and create key if not there', -> res = changeTester {a: (x) -> if isNil(x) then 1 else inc}, {}, {}, {} deepEq [{a: 1}, {a: undefined}, {a: 1}], res it 'evolve if using function but dont create key on undefined value', -> res = changeTester {a: (x) -> if isNil(x) then undefined else inc}, {b: 2}, {}, {} deepEq [{b: 2}, {}, {}], res it 'undefined in function = "fancy toggle"', -> res = changeTester {a: (x) -> if x then undefined else true}, {b: 2}, {}, {} deepEq [{a: true, b: 2}, {a: undefined}, {a: true}], res res = changeTester {a: (x) -> if x then undefined else true}, {a: true, b: 2}, {}, {} deepEq [{b: 2}, {a: true}, {a: undefined}], res it 'reuses values from spec', -> a = {a: null, b2: 3} delta = {a: [1, 2, 3]} res = changeTester delta, a eq delta.a, res[0].a describe 'nested', -> it 'merge number', -> a = {a: {a1: null, a2: 0}, b2: 3} res = changeTester {a: {a1: 1}}, a, {}, {} eres = {a: {a1: 1, a2: 0}, b2: 3} if meta then deepEq [eres, {a: {a1: null}}, {a: {a1: 1}}], res else deepEq_ eres, res it 'remove key', -> a = {a: {a1: null, a2: 0}, b2: 3} res = changeTester {a: {a1: undefined}}, a, {}, {a: {a1: null, a2: 0}} total = {a: {a1: undefined, a2: 0}} deepEq [{a: {a2: 0}, b2: 3}, {a: {a1: null}}, total], res it 'replace array', -> a = {a: {a1: [1, 2, 3], a2: 0}, b2: 3} res = changeTester {a: {a1: [1, 2, 3, 4]}}, a, {}, {a: {a3: undefined}} deepEq [{a: {a1: [1, 2, 3, 4], a2: 0}, b2: 3}, {a: {a1: [1, 2, 3]}}, {a: {a1: [1, 2, 3, 4], a3: undefined}}], res it 'evolve using function', -> a = {a: {a1: [1, 2, 3], a2: 0}, b2: 3} res = changeTester {a: {a1: append(4)}}, a, {}, {b2: 3} deepEq [{a: {a1: [1, 2, 3, 4], a2: 0}, b2: 3}, {a: {a1: [1, 2, 3]}}, {a: {a1: [1, 2, 3, 4]}, b2: 3}], res it 'evolve using function where there is no key', -> a = {b2: 3} res = changeTester {a: {a1: (x) -> if x then append(4) else [4]}}, a, {}, {b2: 3} deepEq [{a: {a1: [4]}, b2: 3}, {a: undefined}, {a: {a1: [4]}, b2: 3}], res describe 'changeM specifics', -> changeMTester = (spec, a, undo, total) -> res = changeM.meta spec, a, undo, total return [res, undo, total] it 'strict equality', -> a = {a: {a1: {a12: 2}}} res = changeMTester {a: {a1: {a11: 1}}}, a, {}, {a: {a1: {a12: 2}}} deepEq [{a: {a1: {a11: 1, a12: 2}}}, {a: {a1: {a11: undefined}}}, {a: {a1: {a11: 1, a12: 2}}}], res eq true, a == res[0] describe 'isAffected', -> it 'simple', -> eq true, isAffected {a: null}, {a: 1} it 'dep deeper', -> eq true, isAffected {a: {a1: {a11: null}}}, {a: undefined} it 'total deeper', -> eq true, isAffected {a: null}, {a: {a1: {a11: undefined}}} it 'deep false', -> eq false, isAffected {a: {a1: {a11: {a111: null}}}}, {a: {a1: {a11: {a112: undefined}}}} describe 'diff', -> it 'missing', -> res = diff {ab: 1}, {} deepEq {ab: undefined}, res it 'extra', -> res = diff {}, {ab: 1} deepEq {ab: 1}, res it 'changed', -> res = diff {ab: 1}, {ab: 2} deepEq {ab: 2}, res it 'no change value', -> res = diff {ab: true}, {ab: true} deepEq {}, res it 'no change array', -> res = diff {ab: [1, 2]}, {ab: [1, 2]} deepEq {}, res it 'reuses values from b', -> a = {ab: null} b = {ab: [1, 2, 3]} res = diff a, b eq b.ab, res.ab describe 'nested', -> it 'extra empty', -> res = diff {a: null}, {a: {}} deepEq {a: {}}, res it 'missing', -> res = diff {a: {a1: 1}}, {a: {}} deepEq {a: {a1: undefined}}, res it 'extra', -> res = diff {a: {}, b: {b1: 1}}, {a: {a1: 1}, b: {b1: 1}} deepEq {a: {a1: 1}}, res it 'changed', -> a = {a: {a1: 1, a2: 0}, b: {b1: 1}} b = {a: {a1: 2, a2: 0}, b: {b1: 1}} res = diff a, b deepEq {a: {a1: 2}}, res it 'no change', -> a = {a: {a1: 1, a2: 0}, b: {b1: 1}} b = {a: {a1: 1, a2: 0}, b: {b1: 1}} res = diff a, b deepEq {}, res it 'changed to object in b', -> a = {a: {a1: 1, a2: 0}, b: {b1: 1}} b = {a: {a1: {a11: 1}, a2: 0}, b: {b1: 1}} res = diff a, b deepEq {a: {a1: {a11: 1}}}, res it 'changed to object in b from array', -> a = {a: {a1: ['a11', 'a12'], a2: 0}, b: {b1: 1}} b = {a: {a1: {a11: 1}, a2: 0}, b: {b1: 1}} res = diff a, b deepEq {a: {a1: {a11: 1}}}, res it 'reuses values from b', -> a = {a: {a1: 1, a2: 0}, b: {b1: 1}} b = {a: {a1: {a11: 1}, a2: 0}, b: {b1: 1}} res = diff a, b eq b.a.a1, res.a.a1 it 'function', -> throws /diff does not support functions/, -> diff {a: {a1: 1}}, {a: {a1: ->}} it 'RegExp', -> throws /diff does not support RegExps/, -> diff {a: {a1: 1}}, {a: {a1: /a/}} describe 'pickRec', -> it 'shallow', -> res = pickRec ['a', 'b'], {a: 1, b: 2, c: 3} deepEq {a: 1, b: 2}, res it 'two levels', -> res = pickRec ['a.a1', 'b'], {a: {a1: 1, a2: 2}, b: 2, c: 3} deepEq {a: {a1: 1}, b: 2}, res it 'three levels', -> obj = {a: {a1: {a11: 1, a12: 2, a13: 3}, a2: 2}, b: 2, c: 3} res = pickRec ['a.a1.a12', 'a.a1.a13', 'b'], obj deepEq {a: {a1: {a12: 2, a13: 3}}, b: 2}, res it 'missing', -> obj = {a: {a1: {a11: 1, a12: 2}, a2: 2}, b: 2, c: 3} res = pickRec ['a.a1.a12', 'a.a1.a13', 'b'], obj deepEq {a: {a1: {a12: 2}}, b: 2}, res it 'empty', -> obj = {a: {a1: {a11: 1, a12: 2}, a2: 2}, b: 2, c: 3} res = pickRec [], obj deepEq {}, res describe 'superFlip', -> it '2 args', -> deepEq {a: 1}, superFlip(merge)({a: 1}, {a: 2}) it '3 args', -> eq 3, superFlip(reduce)([1,2], 0, add) describe 'doto', -> it 'simple case', -> eq 5, doto(2, add(1), add(2)) it 'with log', -> eq 5, doto_(2, add(1), add(2)) describe 'undef', -> it '1', -> eq undefined, undef(-> 1)() describe 'dotoCompose', -> it 'simple case', -> deepEq [1, 2, 3], $$([1], append(3), append(2)) it 'with log', -> deepEq [1, 2, 3], $$_([1], append(3), append(2)) describe 'PromiseProps', -> # https://stackoverflow.com/a/45286517/416797 reso = (ms) -> new Promise (rs, rj) -> setTimeout (() ->rs(1)), ms reje = (ms) -> new Promise (rs, rj) -> setTimeout (() ->rj(666)), ms it 'simple success', -> res = await PromiseProps({a: reso(10), b: reso(5)}) deepEq {a: 1, b: 1}, res it 'simple reject', -> try res = await PromiseProps({a: reso(10), b: reje(5)}) catch err eq 666, err describe 'cc', -> it 'simple case', -> eq 7, cc( add(1), add(2), 4) it 'with log', -> eq 7, cc_(add(1), add(2), 4) describe 'fliped stuff', -> it 'simple cases', -> eq 'Function', type RE.freduce # describe 'qq', -> # it 'simple cases', -> # eq undefined, qq -> 1 # eq undefined, qqq -> 1 describe 'satisfies', -> sat = satisfies it 'String', -> def = { stripeId〳: String email: String # email address〳: line1: String # address.line1 postal〳: String # address.postal_code city〳: String # address.city region〳: String # address.region vatCountry: String # Always metadata.vatCountry. If using address, also address.country company〳: name: String # name vatNo〳: String # TaxId.value } data = { stripeId: 'cus_HtT1Ke62Z248Bj', email: '<EMAIL>', address: {}, vatCountry: undefined, company: { name: 'We Code Better Nordic AB', vatNo: undefined } } deepEq {a: 1}, sat data, def # deepEq {a: 1}, sat {a: {a1: 1}}, {a: String} # deepEq {}, sat {a: 'a'}, {a: String} # it.only 'String', -> # deepEq {a: 1}, sat {a: 1}, {a: String} # deepEq {}, sat {a: 'a'}, {a: String} it 'Number', -> deepEq {a: ''}, sat {a: ''}, {a: Number} deepEq {}, sat {a: 1}, {a: Number} it 'Boolean', -> deepEq {a: 0}, sat {a: 0}, {a: Boolean} deepEq {}, sat {a: true}, {a: Boolean} it 'Function', -> deepEq {a: 0}, sat {a: 0}, {a: ->} deepEq {}, sat {a: ->}, {a: ->} it 'AsyncFunction', -> deepEq {}, sat {a: -> await 1}, {a: -> 2} throws /not yet support type AsyncFunction/, -> sat {a: 0}, {a: -> await 1} it 'Object', -> deepEq {a: 0}, sat {a: 0}, {a: Object} deepEq {}, sat {a: {}}, {a: Object} it 'Enum', -> deepEq {a: 3}, sat {a: 3}, {a: new Set([1, 2])} deepEq {}, sat {a: 2}, {a: new Set([1, 2])} deepEq {}, sat {}, {a〳: new Set([1, 2])} it 'required 1', -> deepEq {a: 'MISSING'}, sat {b: 1}, {a: Number}, true it 'required 2', -> deepEq {a: 'MISSING', b: 'NOT_IN_SPEC'}, sat {b: 1}, {a: Number}, false it 'required 3', -> deepEq {}, sat {b: 1}, {a〳: Number}, true it 'required 4', -> deepEq {a: 'MISSING'}, sat {}, {a: Number}, false it 'required object', -> deepEq {a: 'MISSING', b: 'NOT_IN_SPEC'}, sat {b: 1}, {a: Object} deepEq {}, sat {a: {}}, {a: Object} it 'optional', -> deepEq {}, sat {b: 1}, {a〳: Number, b: Number} it 'optional with undefined', -> deepEq {}, sat {a: undefined, b: 1}, {a〳: Number, b: Number} describe 'array', -> it 'Null', -> deepEq {a: 'MISSING (null)'}, sat {a: null}, {a: [String]} it 'String', -> deepEq {a: [1]}, sat {a: [1, '']}, {a: [String]} deepEq {}, sat {a: ['', '2']}, {a: [String]} it 'Number', -> deepEq {a: ['']}, sat {a: [1, '']}, {a: [Number]} deepEq {}, sat {a: [1, 2]}, {a: [Number]} it 'Boolean', -> deepEq {a: [1]}, sat {a: [1, true]}, {a: [Boolean]} deepEq {}, sat {a: [true, false]}, {a: [Boolean]} it 'Number or null', -> deepEq {a: [true]}, sat {a: [true, null]}, {a: [Number, null]} deepEq {}, sat {a: [1, null]}, {a: [Number, null]} it 'Object', -> deepEq {a: [{b: 2}]}, sat {a: [{b: '1'}, {b: 2}]}, {a: [{b: String}]} deepEq {}, sat {a: [{b: '1'}, {b: '2'}]}, {a: [{b: String}]} it 'Object extra fields', -> deepEq {a: [{b: 2}]}, sat {a: [{b: '1', c: 1}, {b: 2}]}, {a: [{b: String}]} deepEq {}, sat {a: [{b: '1', c: 1}, {b: '2'}]}, {a: [{b: String}]} it 'Object or null', -> deepEq {a: [{b: true}]}, sat {a: [{b: true}, null]}, {a: [{b: Number}, null]} deepEq {}, sat {a: [{b: 1}, null]}, {a: [{b: Number}, null]} describe 'object', -> it 'String, Number, Boolean', -> deepEq {a: {n: ''}}, sat {a: {s: '', n: '', b: true}}, {a: {s: String, n: Number, b: Boolean}} deepEq {}, sat {a: {s: '', n: 1, b: true}}, {a: {s: String, n: Number, b: Boolean}} describe 'dottedApi', -> it '1', -> fns = dottedApi {a: ['a1', 'a2'], b: ['b1', 'b2'], c: ['c1', 'c2']}, (args) -> {e: 'e1', ...args} res = fns.b2.c2.a1 {d: 'd1'} fdeepEq res, {a: 'a1', b: 'b2', c: 'c2', d: 'd1', e: 'e1'} it 'same value', -> throws /cannot have duplicate value/, -> dottedApi {a: ['a1', 'a2'], b: ['a1', 'b2'], c: ['c1', 'c2']}, (args) -> {e: 'e1', ...args} describe 'recursiveProxy', -> handler = (ref) -> get: (o, prop, path) -> ref.value = path return o[prop] it '1', -> ref = {value: null} proxy = recursiveProxy {a: {a1: {a11: [1, 2, 3]}}, b: 2, c: [{c1: [{c11: 1, c12: 2}]}]}, handler(ref) deepEq [1, 2, 3], proxy.a.a1.a11 deepEq 'a.a1.a11', ref.value proxy.c[0].c1[0].c12 deepEq 'c.c1.c12', ref.value describe 'reshape', -> it '1', -> deepEq {a1: 1}, reshape {a1: ːa}, {a: 1} it '2', -> deepEq {a1: 1, b: 2}, reshape {a1: ːa, ːb}, {a: 1, b: 2} it '3', -> deepEq {a1: {a11: 1, b: 2}, b: 2}, reshape {a1: {a11: ːa, ːb}, ːb}, {a: 1, b: 2}
true
{add, append, dec, empty, evolve, inc, isNil, match, merge, path, prop, reduce, reject, remove, replace, set, type, values, where} = R = require 'ramda' #auto_require: ramda {change, changeM, pickRec, isAffected, diff, toggle, cc, cc_, doto, doto_, $, $_, $$, $$_, superFlip, isNilOrEmpty, PromiseProps, undef, satisfies, reshape} = RE = require 'ramda-extras' #auto_require: ramda-extras [ːb, ːa] = ['b', 'a'] #auto_sugar qq = (f) -> console.log match(/return (.*);/, f.toString())[1], f() qqq = (...args) -> console.log ...args _ = (...xs) -> xs {eq, deepEq, deepEq_, fdeepEq, throws} = require 'testhelp' #auto_require: testhelp {undef, isNilOrEmpty, change, changeM, toggle, isAffected, diff, pickRec, superFlip, doto, doto_, $$, $$_, cc, cc_, PromiseProps, qq, qqq, satisfies, dottedApi, recursiveProxy, reshape} = RE = require './ramda-extras' describe 'isNilOrEmpty', -> it 'simple', -> eq false, isNilOrEmpty(' ') eq true, isNilOrEmpty('') eq false, isNilOrEmpty([1]) eq true, isNilOrEmpty([]) eq false, isNilOrEmpty({a: 1}) eq true, isNilOrEmpty({}) describe 'toggle', -> it 'simple', -> deepEq [1, 2, 3], toggle 3, [1, 2] deepEq [1, 2], toggle(3, [1, 2, 3]) deepEq [3], toggle(3, []) deepEq [3], toggle(3, undefined) describe 'change', -> changeTester = (spec, a, undo, total) -> res = change.meta spec, a, undo, total return [res, undo, total] meta = true # changeTester = (spec, a, total) -> # res = change spec, a # return res # meta = false it 'merge number + empty total', -> res = changeTester {a: 1}, {}, {}, {} if meta then deepEq [{a: 1}, {a: undefined}, {a: 1}], res else deepEq {a: 1}, res it 'remove key + extra key in total', -> res = changeTester {a: undefined}, {a: 1, b: 2}, {}, {c: undefined} deepEq [{b: 2}, {a: 1}, {a: undefined, c: undefined}], res it 'remove key of empty obj + same key in total', -> # {a: 1} {} {} res = changeTester {a: undefined}, {}, {}, {a: undefined} deepEq [{}, {}, {a: undefined}], res # it 'set key + same key in undo', -> # # {a: 1} {} {} # res = changeTester {a: 2, b: 1}, {}, {a: 1}, {a: 0} # deepEq_ [{a: 2, b: 1}, {a: 1}, {a: 2, b: 1}], res it 'set to null', -> res = changeTester {a: null}, {a: 1, b: 2}, {}, {a: 2} deepEq [{a: null, b: 2}, {a: 1}, {a: null}], res it 'function', -> res = changeTester (({a, b}) -> {a: inc(a), b: dec(b), c: 1}), {a: 1, b: 2}, {}, {a: 2, d: 3} deepEq_ [{a: 2, b: 1, c: 1}, {}, {a: 2, d: 3}], res it 'date', -> date1 = new Date res = changeTester {a: date1}, {a: 1, b: 2}, {}, {a: 2} deepEq_ [{a: date1, b: 2}, {a: 1}, {a: date1}], res it 'merge array + same key in total', -> res = changeTester {a: [2, 3]}, {a: [1]}, {}, {a: [5]} deepEq [{a: [2, 3]}, {a: [1]}, {a: [2, 3]}], res it 'evolve if using function', -> res = changeTester {a: inc}, {a: 1}, {}, {} deepEq [{a: 2}, {a: 1}, {a: 2}], res it 'evolve if using function and create key if not there', -> res = changeTester {a: (x) -> if isNil(x) then 1 else inc}, {}, {}, {} deepEq [{a: 1}, {a: undefined}, {a: 1}], res it 'evolve if using function but dont create key on undefined value', -> res = changeTester {a: (x) -> if isNil(x) then undefined else inc}, {b: 2}, {}, {} deepEq [{b: 2}, {}, {}], res it 'undefined in function = "fancy toggle"', -> res = changeTester {a: (x) -> if x then undefined else true}, {b: 2}, {}, {} deepEq [{a: true, b: 2}, {a: undefined}, {a: true}], res res = changeTester {a: (x) -> if x then undefined else true}, {a: true, b: 2}, {}, {} deepEq [{b: 2}, {a: true}, {a: undefined}], res it 'reuses values from spec', -> a = {a: null, b2: 3} delta = {a: [1, 2, 3]} res = changeTester delta, a eq delta.a, res[0].a describe 'nested', -> it 'merge number', -> a = {a: {a1: null, a2: 0}, b2: 3} res = changeTester {a: {a1: 1}}, a, {}, {} eres = {a: {a1: 1, a2: 0}, b2: 3} if meta then deepEq [eres, {a: {a1: null}}, {a: {a1: 1}}], res else deepEq_ eres, res it 'remove key', -> a = {a: {a1: null, a2: 0}, b2: 3} res = changeTester {a: {a1: undefined}}, a, {}, {a: {a1: null, a2: 0}} total = {a: {a1: undefined, a2: 0}} deepEq [{a: {a2: 0}, b2: 3}, {a: {a1: null}}, total], res it 'replace array', -> a = {a: {a1: [1, 2, 3], a2: 0}, b2: 3} res = changeTester {a: {a1: [1, 2, 3, 4]}}, a, {}, {a: {a3: undefined}} deepEq [{a: {a1: [1, 2, 3, 4], a2: 0}, b2: 3}, {a: {a1: [1, 2, 3]}}, {a: {a1: [1, 2, 3, 4], a3: undefined}}], res it 'evolve using function', -> a = {a: {a1: [1, 2, 3], a2: 0}, b2: 3} res = changeTester {a: {a1: append(4)}}, a, {}, {b2: 3} deepEq [{a: {a1: [1, 2, 3, 4], a2: 0}, b2: 3}, {a: {a1: [1, 2, 3]}}, {a: {a1: [1, 2, 3, 4]}, b2: 3}], res it 'evolve using function where there is no key', -> a = {b2: 3} res = changeTester {a: {a1: (x) -> if x then append(4) else [4]}}, a, {}, {b2: 3} deepEq [{a: {a1: [4]}, b2: 3}, {a: undefined}, {a: {a1: [4]}, b2: 3}], res describe 'changeM specifics', -> changeMTester = (spec, a, undo, total) -> res = changeM.meta spec, a, undo, total return [res, undo, total] it 'strict equality', -> a = {a: {a1: {a12: 2}}} res = changeMTester {a: {a1: {a11: 1}}}, a, {}, {a: {a1: {a12: 2}}} deepEq [{a: {a1: {a11: 1, a12: 2}}}, {a: {a1: {a11: undefined}}}, {a: {a1: {a11: 1, a12: 2}}}], res eq true, a == res[0] describe 'isAffected', -> it 'simple', -> eq true, isAffected {a: null}, {a: 1} it 'dep deeper', -> eq true, isAffected {a: {a1: {a11: null}}}, {a: undefined} it 'total deeper', -> eq true, isAffected {a: null}, {a: {a1: {a11: undefined}}} it 'deep false', -> eq false, isAffected {a: {a1: {a11: {a111: null}}}}, {a: {a1: {a11: {a112: undefined}}}} describe 'diff', -> it 'missing', -> res = diff {ab: 1}, {} deepEq {ab: undefined}, res it 'extra', -> res = diff {}, {ab: 1} deepEq {ab: 1}, res it 'changed', -> res = diff {ab: 1}, {ab: 2} deepEq {ab: 2}, res it 'no change value', -> res = diff {ab: true}, {ab: true} deepEq {}, res it 'no change array', -> res = diff {ab: [1, 2]}, {ab: [1, 2]} deepEq {}, res it 'reuses values from b', -> a = {ab: null} b = {ab: [1, 2, 3]} res = diff a, b eq b.ab, res.ab describe 'nested', -> it 'extra empty', -> res = diff {a: null}, {a: {}} deepEq {a: {}}, res it 'missing', -> res = diff {a: {a1: 1}}, {a: {}} deepEq {a: {a1: undefined}}, res it 'extra', -> res = diff {a: {}, b: {b1: 1}}, {a: {a1: 1}, b: {b1: 1}} deepEq {a: {a1: 1}}, res it 'changed', -> a = {a: {a1: 1, a2: 0}, b: {b1: 1}} b = {a: {a1: 2, a2: 0}, b: {b1: 1}} res = diff a, b deepEq {a: {a1: 2}}, res it 'no change', -> a = {a: {a1: 1, a2: 0}, b: {b1: 1}} b = {a: {a1: 1, a2: 0}, b: {b1: 1}} res = diff a, b deepEq {}, res it 'changed to object in b', -> a = {a: {a1: 1, a2: 0}, b: {b1: 1}} b = {a: {a1: {a11: 1}, a2: 0}, b: {b1: 1}} res = diff a, b deepEq {a: {a1: {a11: 1}}}, res it 'changed to object in b from array', -> a = {a: {a1: ['a11', 'a12'], a2: 0}, b: {b1: 1}} b = {a: {a1: {a11: 1}, a2: 0}, b: {b1: 1}} res = diff a, b deepEq {a: {a1: {a11: 1}}}, res it 'reuses values from b', -> a = {a: {a1: 1, a2: 0}, b: {b1: 1}} b = {a: {a1: {a11: 1}, a2: 0}, b: {b1: 1}} res = diff a, b eq b.a.a1, res.a.a1 it 'function', -> throws /diff does not support functions/, -> diff {a: {a1: 1}}, {a: {a1: ->}} it 'RegExp', -> throws /diff does not support RegExps/, -> diff {a: {a1: 1}}, {a: {a1: /a/}} describe 'pickRec', -> it 'shallow', -> res = pickRec ['a', 'b'], {a: 1, b: 2, c: 3} deepEq {a: 1, b: 2}, res it 'two levels', -> res = pickRec ['a.a1', 'b'], {a: {a1: 1, a2: 2}, b: 2, c: 3} deepEq {a: {a1: 1}, b: 2}, res it 'three levels', -> obj = {a: {a1: {a11: 1, a12: 2, a13: 3}, a2: 2}, b: 2, c: 3} res = pickRec ['a.a1.a12', 'a.a1.a13', 'b'], obj deepEq {a: {a1: {a12: 2, a13: 3}}, b: 2}, res it 'missing', -> obj = {a: {a1: {a11: 1, a12: 2}, a2: 2}, b: 2, c: 3} res = pickRec ['a.a1.a12', 'a.a1.a13', 'b'], obj deepEq {a: {a1: {a12: 2}}, b: 2}, res it 'empty', -> obj = {a: {a1: {a11: 1, a12: 2}, a2: 2}, b: 2, c: 3} res = pickRec [], obj deepEq {}, res describe 'superFlip', -> it '2 args', -> deepEq {a: 1}, superFlip(merge)({a: 1}, {a: 2}) it '3 args', -> eq 3, superFlip(reduce)([1,2], 0, add) describe 'doto', -> it 'simple case', -> eq 5, doto(2, add(1), add(2)) it 'with log', -> eq 5, doto_(2, add(1), add(2)) describe 'undef', -> it '1', -> eq undefined, undef(-> 1)() describe 'dotoCompose', -> it 'simple case', -> deepEq [1, 2, 3], $$([1], append(3), append(2)) it 'with log', -> deepEq [1, 2, 3], $$_([1], append(3), append(2)) describe 'PromiseProps', -> # https://stackoverflow.com/a/45286517/416797 reso = (ms) -> new Promise (rs, rj) -> setTimeout (() ->rs(1)), ms reje = (ms) -> new Promise (rs, rj) -> setTimeout (() ->rj(666)), ms it 'simple success', -> res = await PromiseProps({a: reso(10), b: reso(5)}) deepEq {a: 1, b: 1}, res it 'simple reject', -> try res = await PromiseProps({a: reso(10), b: reje(5)}) catch err eq 666, err describe 'cc', -> it 'simple case', -> eq 7, cc( add(1), add(2), 4) it 'with log', -> eq 7, cc_(add(1), add(2), 4) describe 'fliped stuff', -> it 'simple cases', -> eq 'Function', type RE.freduce # describe 'qq', -> # it 'simple cases', -> # eq undefined, qq -> 1 # eq undefined, qqq -> 1 describe 'satisfies', -> sat = satisfies it 'String', -> def = { stripeId〳: String email: String # email address〳: line1: String # address.line1 postal〳: String # address.postal_code city〳: String # address.city region〳: String # address.region vatCountry: String # Always metadata.vatCountry. If using address, also address.country company〳: name: String # name vatNo〳: String # TaxId.value } data = { stripeId: 'cus_HtT1Ke62Z248Bj', email: 'PI:EMAIL:<EMAIL>END_PI', address: {}, vatCountry: undefined, company: { name: 'We Code Better Nordic AB', vatNo: undefined } } deepEq {a: 1}, sat data, def # deepEq {a: 1}, sat {a: {a1: 1}}, {a: String} # deepEq {}, sat {a: 'a'}, {a: String} # it.only 'String', -> # deepEq {a: 1}, sat {a: 1}, {a: String} # deepEq {}, sat {a: 'a'}, {a: String} it 'Number', -> deepEq {a: ''}, sat {a: ''}, {a: Number} deepEq {}, sat {a: 1}, {a: Number} it 'Boolean', -> deepEq {a: 0}, sat {a: 0}, {a: Boolean} deepEq {}, sat {a: true}, {a: Boolean} it 'Function', -> deepEq {a: 0}, sat {a: 0}, {a: ->} deepEq {}, sat {a: ->}, {a: ->} it 'AsyncFunction', -> deepEq {}, sat {a: -> await 1}, {a: -> 2} throws /not yet support type AsyncFunction/, -> sat {a: 0}, {a: -> await 1} it 'Object', -> deepEq {a: 0}, sat {a: 0}, {a: Object} deepEq {}, sat {a: {}}, {a: Object} it 'Enum', -> deepEq {a: 3}, sat {a: 3}, {a: new Set([1, 2])} deepEq {}, sat {a: 2}, {a: new Set([1, 2])} deepEq {}, sat {}, {a〳: new Set([1, 2])} it 'required 1', -> deepEq {a: 'MISSING'}, sat {b: 1}, {a: Number}, true it 'required 2', -> deepEq {a: 'MISSING', b: 'NOT_IN_SPEC'}, sat {b: 1}, {a: Number}, false it 'required 3', -> deepEq {}, sat {b: 1}, {a〳: Number}, true it 'required 4', -> deepEq {a: 'MISSING'}, sat {}, {a: Number}, false it 'required object', -> deepEq {a: 'MISSING', b: 'NOT_IN_SPEC'}, sat {b: 1}, {a: Object} deepEq {}, sat {a: {}}, {a: Object} it 'optional', -> deepEq {}, sat {b: 1}, {a〳: Number, b: Number} it 'optional with undefined', -> deepEq {}, sat {a: undefined, b: 1}, {a〳: Number, b: Number} describe 'array', -> it 'Null', -> deepEq {a: 'MISSING (null)'}, sat {a: null}, {a: [String]} it 'String', -> deepEq {a: [1]}, sat {a: [1, '']}, {a: [String]} deepEq {}, sat {a: ['', '2']}, {a: [String]} it 'Number', -> deepEq {a: ['']}, sat {a: [1, '']}, {a: [Number]} deepEq {}, sat {a: [1, 2]}, {a: [Number]} it 'Boolean', -> deepEq {a: [1]}, sat {a: [1, true]}, {a: [Boolean]} deepEq {}, sat {a: [true, false]}, {a: [Boolean]} it 'Number or null', -> deepEq {a: [true]}, sat {a: [true, null]}, {a: [Number, null]} deepEq {}, sat {a: [1, null]}, {a: [Number, null]} it 'Object', -> deepEq {a: [{b: 2}]}, sat {a: [{b: '1'}, {b: 2}]}, {a: [{b: String}]} deepEq {}, sat {a: [{b: '1'}, {b: '2'}]}, {a: [{b: String}]} it 'Object extra fields', -> deepEq {a: [{b: 2}]}, sat {a: [{b: '1', c: 1}, {b: 2}]}, {a: [{b: String}]} deepEq {}, sat {a: [{b: '1', c: 1}, {b: '2'}]}, {a: [{b: String}]} it 'Object or null', -> deepEq {a: [{b: true}]}, sat {a: [{b: true}, null]}, {a: [{b: Number}, null]} deepEq {}, sat {a: [{b: 1}, null]}, {a: [{b: Number}, null]} describe 'object', -> it 'String, Number, Boolean', -> deepEq {a: {n: ''}}, sat {a: {s: '', n: '', b: true}}, {a: {s: String, n: Number, b: Boolean}} deepEq {}, sat {a: {s: '', n: 1, b: true}}, {a: {s: String, n: Number, b: Boolean}} describe 'dottedApi', -> it '1', -> fns = dottedApi {a: ['a1', 'a2'], b: ['b1', 'b2'], c: ['c1', 'c2']}, (args) -> {e: 'e1', ...args} res = fns.b2.c2.a1 {d: 'd1'} fdeepEq res, {a: 'a1', b: 'b2', c: 'c2', d: 'd1', e: 'e1'} it 'same value', -> throws /cannot have duplicate value/, -> dottedApi {a: ['a1', 'a2'], b: ['a1', 'b2'], c: ['c1', 'c2']}, (args) -> {e: 'e1', ...args} describe 'recursiveProxy', -> handler = (ref) -> get: (o, prop, path) -> ref.value = path return o[prop] it '1', -> ref = {value: null} proxy = recursiveProxy {a: {a1: {a11: [1, 2, 3]}}, b: 2, c: [{c1: [{c11: 1, c12: 2}]}]}, handler(ref) deepEq [1, 2, 3], proxy.a.a1.a11 deepEq 'a.a1.a11', ref.value proxy.c[0].c1[0].c12 deepEq 'c.c1.c12', ref.value describe 'reshape', -> it '1', -> deepEq {a1: 1}, reshape {a1: ːa}, {a: 1} it '2', -> deepEq {a1: 1, b: 2}, reshape {a1: ːa, ːb}, {a: 1, b: 2} it '3', -> deepEq {a1: {a11: 1, b: 2}, b: 2}, reshape {a1: {a11: ːa, ːb}, ːb}, {a: 1, b: 2}
[ { "context": "damaged as well as when it is spent.\n *\n * @name Archer\n * @physical\n * @dps\n * @hp 70+[level*10]+[con", "end": 420, "score": 0.7735856771469116, "start": 414, "tag": "NAME", "value": "Archer" } ]
src/character/classes/Archer.coffee
sadbear-/IdleLands
0
Class = require "./../base/Class" _ = require "lodash" MessageCreator = require "../../system/MessageCreator" `/** * The Archer is a physical debuff/dps class. Their Focus stat increases critical chance by up to 50%, * and allows access to powerful skills. Focus increases every turn and with use of the Take Aim skill, * and decreases when the Archer is damaged as well as when it is spent. * * @name Archer * @physical * @dps * @hp 70+[level*10]+[con*6] * @mp 30+[level*2]+[int*1] * @special Focus (The Archer builds focus over time, resulting in devastating attacks if unchecked.) * @itemScore agi*1.2 + dex*1.6 + str*0.3 - int * @statPerLevel {str} 2 * @statPerLevel {dex} 4 * @statPerLevel {con} 2 * @statPerLevel {int} 1 * @statPerLevel {wis} 1 * @statPerLevel {agi} 3 * @minDamage 50% * @category Classes * @package Player */` class Archer extends Class baseHp: 70 baseHpPerLevel: 10 baseHpPerCon: 6 baseMp: 30 baseMpPerLevel: 2 baseMpPerInt: 1 baseConPerLevel: 2 baseDexPerLevel: 4 baseAgiPerLevel: 3 baseStrPerLevel: 2 baseIntPerLevel: 1 baseWisPerLevel: 1 itemScore: (player, item) -> item.agi*1.2 + item.dex*1.6 + item.str*0.3 - item.int physicalAttackChance: -> -10 criticalChance: (player) -> 50*player.special.getValue() minDamage: (player) -> player.calc.damage()*0.5 events: {} load: (player) -> super player player.special.maximum = 100 player.special.__current = 0 player.special.name = "Focus" player.on "combat.battle.start", @events.combatStart = -> player.special.toMinimum() player.on "combat.round.start", @events.roundStart = -> player.special.add 10 player.on "combat.self.damaged", @events.hitReceived = -> player.special.sub 7 player.on "combat.ally.flee", @events.allyFled = (fledPlayer) -> return if not fledPlayer.fled fledPlayer.fled = false message = "%casterName dragged %targetName back into combat with a grappling hook arrow!" extra = targetName: fledPlayer.name casterName: player.name newMessage = MessageCreator.doStringReplace message, player, extra player.playerManager.game.currentBattle?.broadcast newMessage unload: (player) -> player.special.maximum = 0 player.special.name = "" player.off "combat.battle.start", @events.combatStart player.off "combat.round.start", @events.roundStart player.off "combat.self.damaged", @events.hitReceived module.exports = exports = Archer
123321
Class = require "./../base/Class" _ = require "lodash" MessageCreator = require "../../system/MessageCreator" `/** * The Archer is a physical debuff/dps class. Their Focus stat increases critical chance by up to 50%, * and allows access to powerful skills. Focus increases every turn and with use of the Take Aim skill, * and decreases when the Archer is damaged as well as when it is spent. * * @name <NAME> * @physical * @dps * @hp 70+[level*10]+[con*6] * @mp 30+[level*2]+[int*1] * @special Focus (The Archer builds focus over time, resulting in devastating attacks if unchecked.) * @itemScore agi*1.2 + dex*1.6 + str*0.3 - int * @statPerLevel {str} 2 * @statPerLevel {dex} 4 * @statPerLevel {con} 2 * @statPerLevel {int} 1 * @statPerLevel {wis} 1 * @statPerLevel {agi} 3 * @minDamage 50% * @category Classes * @package Player */` class Archer extends Class baseHp: 70 baseHpPerLevel: 10 baseHpPerCon: 6 baseMp: 30 baseMpPerLevel: 2 baseMpPerInt: 1 baseConPerLevel: 2 baseDexPerLevel: 4 baseAgiPerLevel: 3 baseStrPerLevel: 2 baseIntPerLevel: 1 baseWisPerLevel: 1 itemScore: (player, item) -> item.agi*1.2 + item.dex*1.6 + item.str*0.3 - item.int physicalAttackChance: -> -10 criticalChance: (player) -> 50*player.special.getValue() minDamage: (player) -> player.calc.damage()*0.5 events: {} load: (player) -> super player player.special.maximum = 100 player.special.__current = 0 player.special.name = "Focus" player.on "combat.battle.start", @events.combatStart = -> player.special.toMinimum() player.on "combat.round.start", @events.roundStart = -> player.special.add 10 player.on "combat.self.damaged", @events.hitReceived = -> player.special.sub 7 player.on "combat.ally.flee", @events.allyFled = (fledPlayer) -> return if not fledPlayer.fled fledPlayer.fled = false message = "%casterName dragged %targetName back into combat with a grappling hook arrow!" extra = targetName: fledPlayer.name casterName: player.name newMessage = MessageCreator.doStringReplace message, player, extra player.playerManager.game.currentBattle?.broadcast newMessage unload: (player) -> player.special.maximum = 0 player.special.name = "" player.off "combat.battle.start", @events.combatStart player.off "combat.round.start", @events.roundStart player.off "combat.self.damaged", @events.hitReceived module.exports = exports = Archer
true
Class = require "./../base/Class" _ = require "lodash" MessageCreator = require "../../system/MessageCreator" `/** * The Archer is a physical debuff/dps class. Their Focus stat increases critical chance by up to 50%, * and allows access to powerful skills. Focus increases every turn and with use of the Take Aim skill, * and decreases when the Archer is damaged as well as when it is spent. * * @name PI:NAME:<NAME>END_PI * @physical * @dps * @hp 70+[level*10]+[con*6] * @mp 30+[level*2]+[int*1] * @special Focus (The Archer builds focus over time, resulting in devastating attacks if unchecked.) * @itemScore agi*1.2 + dex*1.6 + str*0.3 - int * @statPerLevel {str} 2 * @statPerLevel {dex} 4 * @statPerLevel {con} 2 * @statPerLevel {int} 1 * @statPerLevel {wis} 1 * @statPerLevel {agi} 3 * @minDamage 50% * @category Classes * @package Player */` class Archer extends Class baseHp: 70 baseHpPerLevel: 10 baseHpPerCon: 6 baseMp: 30 baseMpPerLevel: 2 baseMpPerInt: 1 baseConPerLevel: 2 baseDexPerLevel: 4 baseAgiPerLevel: 3 baseStrPerLevel: 2 baseIntPerLevel: 1 baseWisPerLevel: 1 itemScore: (player, item) -> item.agi*1.2 + item.dex*1.6 + item.str*0.3 - item.int physicalAttackChance: -> -10 criticalChance: (player) -> 50*player.special.getValue() minDamage: (player) -> player.calc.damage()*0.5 events: {} load: (player) -> super player player.special.maximum = 100 player.special.__current = 0 player.special.name = "Focus" player.on "combat.battle.start", @events.combatStart = -> player.special.toMinimum() player.on "combat.round.start", @events.roundStart = -> player.special.add 10 player.on "combat.self.damaged", @events.hitReceived = -> player.special.sub 7 player.on "combat.ally.flee", @events.allyFled = (fledPlayer) -> return if not fledPlayer.fled fledPlayer.fled = false message = "%casterName dragged %targetName back into combat with a grappling hook arrow!" extra = targetName: fledPlayer.name casterName: player.name newMessage = MessageCreator.doStringReplace message, player, extra player.playerManager.game.currentBattle?.broadcast newMessage unload: (player) -> player.special.maximum = 0 player.special.name = "" player.off "combat.battle.start", @events.combatStart player.off "combat.round.start", @events.roundStart player.off "combat.self.damaged", @events.hitReceived module.exports = exports = Archer
[ { "context": "# @fileoverview Tests for no-alert rule.\n# @author Nicholas C. Zakas\n###\n\n'use strict'\n\n#-----------------------------", "end": 73, "score": 0.9998018145561218, "start": 56, "tag": "NAME", "value": "Nicholas C. Zakas" } ]
src/tests/rules/no-alert.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Tests for no-alert rule. # @author Nicholas C. Zakas ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/no-alert' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-alert', rule, valid: [ 'a[o.k](1)' 'foo.alert(foo)' 'foo.confirm(foo)' 'foo.prompt(foo)' ''' alert = -> alert() ''' ''' -> alert = bar alert() ''' '(alert) -> alert()' ''' alert = -> -> alert() ''' ''' -> alert = -> -> alert() ''' ''' confirm = -> confirm() ''' ''' prompt = -> prompt() ''' 'window[alert]()' '-> @alert()' ''' -> window = bar window.alert() ''' ] invalid: [ code: 'alert(foo)' errors: [ messageId: 'unexpected' data: name: 'alert' type: 'CallExpression' line: 1 column: 1 ] , code: 'window.alert(foo)' errors: [ messageId: 'unexpected' data: name: 'alert' type: 'CallExpression' line: 1 column: 1 ] , code: "window['alert'](foo)" errors: [ messageId: 'unexpected' data: name: 'alert' type: 'CallExpression' line: 1 column: 1 ] , code: 'confirm(foo)' errors: [ messageId: 'unexpected' data: name: 'confirm' type: 'CallExpression' line: 1 column: 1 ] , code: 'window.confirm(foo)' errors: [ messageId: 'unexpected' data: name: 'confirm' type: 'CallExpression' line: 1 column: 1 ] , code: "window['confirm'](foo)" errors: [ messageId: 'unexpected' data: name: 'confirm' type: 'CallExpression' line: 1 column: 1 ] , code: 'prompt(foo)' errors: [ messageId: 'unexpected' data: name: 'prompt' type: 'CallExpression' line: 1 column: 1 ] , code: 'window.prompt(foo)' errors: [ messageId: 'unexpected' data: name: 'prompt' type: 'CallExpression' line: 1 column: 1 ] , code: "window['prompt'](foo)" errors: [ messageId: 'unexpected' data: name: 'prompt' type: 'CallExpression' line: 1 column: 1 ] , code: ''' alert = -> window.alert(foo) ''' errors: [ messageId: 'unexpected' data: name: 'alert' type: 'CallExpression' line: 2 column: 1 ] , code: '(alert) -> window.alert()' errors: [ messageId: 'unexpected' data: name: 'alert' type: 'CallExpression' line: 1 column: 12 ] , code: '-> alert()' errors: [ messageId: 'unexpected' data: name: 'alert' type: 'CallExpression' line: 1 column: 4 ] , code: ''' -> alert = -> alert() ''' errors: [ messageId: 'unexpected' data: name: 'alert' type: 'CallExpression' line: 3 column: 1 ] , # TODO: uncomment if not always parsing as module # , # code: '@alert(foo)' # errors: [ # messageId: 'unexpected' # data: name: 'alert' # type: 'CallExpression' # line: 1 # column: 1 # ] # , # code: "this['alert'](foo)" # errors: [ # messageId: 'unexpected' # data: name: 'alert' # type: 'CallExpression' # line: 1 # column: 1 # ] code: ''' -> window = bar window.alert() window.alert() ''' errors: [ messageId: 'unexpected' data: name: 'alert' type: 'CallExpression' line: 4 column: 1 ] ]
187549
###* # @fileoverview Tests for no-alert rule. # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/no-alert' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-alert', rule, valid: [ 'a[o.k](1)' 'foo.alert(foo)' 'foo.confirm(foo)' 'foo.prompt(foo)' ''' alert = -> alert() ''' ''' -> alert = bar alert() ''' '(alert) -> alert()' ''' alert = -> -> alert() ''' ''' -> alert = -> -> alert() ''' ''' confirm = -> confirm() ''' ''' prompt = -> prompt() ''' 'window[alert]()' '-> @alert()' ''' -> window = bar window.alert() ''' ] invalid: [ code: 'alert(foo)' errors: [ messageId: 'unexpected' data: name: 'alert' type: 'CallExpression' line: 1 column: 1 ] , code: 'window.alert(foo)' errors: [ messageId: 'unexpected' data: name: 'alert' type: 'CallExpression' line: 1 column: 1 ] , code: "window['alert'](foo)" errors: [ messageId: 'unexpected' data: name: 'alert' type: 'CallExpression' line: 1 column: 1 ] , code: 'confirm(foo)' errors: [ messageId: 'unexpected' data: name: 'confirm' type: 'CallExpression' line: 1 column: 1 ] , code: 'window.confirm(foo)' errors: [ messageId: 'unexpected' data: name: 'confirm' type: 'CallExpression' line: 1 column: 1 ] , code: "window['confirm'](foo)" errors: [ messageId: 'unexpected' data: name: 'confirm' type: 'CallExpression' line: 1 column: 1 ] , code: 'prompt(foo)' errors: [ messageId: 'unexpected' data: name: 'prompt' type: 'CallExpression' line: 1 column: 1 ] , code: 'window.prompt(foo)' errors: [ messageId: 'unexpected' data: name: 'prompt' type: 'CallExpression' line: 1 column: 1 ] , code: "window['prompt'](foo)" errors: [ messageId: 'unexpected' data: name: 'prompt' type: 'CallExpression' line: 1 column: 1 ] , code: ''' alert = -> window.alert(foo) ''' errors: [ messageId: 'unexpected' data: name: 'alert' type: 'CallExpression' line: 2 column: 1 ] , code: '(alert) -> window.alert()' errors: [ messageId: 'unexpected' data: name: 'alert' type: 'CallExpression' line: 1 column: 12 ] , code: '-> alert()' errors: [ messageId: 'unexpected' data: name: 'alert' type: 'CallExpression' line: 1 column: 4 ] , code: ''' -> alert = -> alert() ''' errors: [ messageId: 'unexpected' data: name: 'alert' type: 'CallExpression' line: 3 column: 1 ] , # TODO: uncomment if not always parsing as module # , # code: '@alert(foo)' # errors: [ # messageId: 'unexpected' # data: name: 'alert' # type: 'CallExpression' # line: 1 # column: 1 # ] # , # code: "this['alert'](foo)" # errors: [ # messageId: 'unexpected' # data: name: 'alert' # type: 'CallExpression' # line: 1 # column: 1 # ] code: ''' -> window = bar window.alert() window.alert() ''' errors: [ messageId: 'unexpected' data: name: 'alert' type: 'CallExpression' line: 4 column: 1 ] ]
true
###* # @fileoverview Tests for no-alert rule. # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require 'eslint/lib/rules/no-alert' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-alert', rule, valid: [ 'a[o.k](1)' 'foo.alert(foo)' 'foo.confirm(foo)' 'foo.prompt(foo)' ''' alert = -> alert() ''' ''' -> alert = bar alert() ''' '(alert) -> alert()' ''' alert = -> -> alert() ''' ''' -> alert = -> -> alert() ''' ''' confirm = -> confirm() ''' ''' prompt = -> prompt() ''' 'window[alert]()' '-> @alert()' ''' -> window = bar window.alert() ''' ] invalid: [ code: 'alert(foo)' errors: [ messageId: 'unexpected' data: name: 'alert' type: 'CallExpression' line: 1 column: 1 ] , code: 'window.alert(foo)' errors: [ messageId: 'unexpected' data: name: 'alert' type: 'CallExpression' line: 1 column: 1 ] , code: "window['alert'](foo)" errors: [ messageId: 'unexpected' data: name: 'alert' type: 'CallExpression' line: 1 column: 1 ] , code: 'confirm(foo)' errors: [ messageId: 'unexpected' data: name: 'confirm' type: 'CallExpression' line: 1 column: 1 ] , code: 'window.confirm(foo)' errors: [ messageId: 'unexpected' data: name: 'confirm' type: 'CallExpression' line: 1 column: 1 ] , code: "window['confirm'](foo)" errors: [ messageId: 'unexpected' data: name: 'confirm' type: 'CallExpression' line: 1 column: 1 ] , code: 'prompt(foo)' errors: [ messageId: 'unexpected' data: name: 'prompt' type: 'CallExpression' line: 1 column: 1 ] , code: 'window.prompt(foo)' errors: [ messageId: 'unexpected' data: name: 'prompt' type: 'CallExpression' line: 1 column: 1 ] , code: "window['prompt'](foo)" errors: [ messageId: 'unexpected' data: name: 'prompt' type: 'CallExpression' line: 1 column: 1 ] , code: ''' alert = -> window.alert(foo) ''' errors: [ messageId: 'unexpected' data: name: 'alert' type: 'CallExpression' line: 2 column: 1 ] , code: '(alert) -> window.alert()' errors: [ messageId: 'unexpected' data: name: 'alert' type: 'CallExpression' line: 1 column: 12 ] , code: '-> alert()' errors: [ messageId: 'unexpected' data: name: 'alert' type: 'CallExpression' line: 1 column: 4 ] , code: ''' -> alert = -> alert() ''' errors: [ messageId: 'unexpected' data: name: 'alert' type: 'CallExpression' line: 3 column: 1 ] , # TODO: uncomment if not always parsing as module # , # code: '@alert(foo)' # errors: [ # messageId: 'unexpected' # data: name: 'alert' # type: 'CallExpression' # line: 1 # column: 1 # ] # , # code: "this['alert'](foo)" # errors: [ # messageId: 'unexpected' # data: name: 'alert' # type: 'CallExpression' # line: 1 # column: 1 # ] code: ''' -> window = bar window.alert() window.alert() ''' errors: [ messageId: 'unexpected' data: name: 'alert' type: 'CallExpression' line: 4 column: 1 ] ]
[ { "context": "###\n\tAudio output example.\n\tby florin.braghis@gmail.com\n###\n\noflib = require 'lib/of'\noflib._.extend this", "end": 55, "score": 0.999898374080658, "start": 31, "tag": "EMAIL", "value": "florin.braghis@gmail.com" } ]
bin/audioOutputExample.coffee
codeboost/JOpenFrameworks
12
### Audio output example. by florin.braghis@gmail.com ### oflib = require 'lib/of' oflib._.extend this, oflib window = new ofAppGlutWindow ofSetupOpenGL window, 1024, 768, OF_WINDOW g_App = new ofBaseApp class AudioOutputExample constructor: -> @pan = 0 @sampleRate = 44100 @phase = 0 @phaseAdder = 0.0 @phaseAdderTarget = 0.0 @volume = 0.1 @bNoise = false @targetFrequency = 0 @lAudio = [] @rAudio = [] ofSoundStreamSetup 2, 0, g_App, @sampleRate, 256, 4 ofSetFrameRate(60); #this is used for indexing buffers #we call setPtr() with the buffer and then we can do [] on it. @oIndex = new Indexable draw: -> ofSetColor 0x333333 ofRect 100,100,256,200 ofSetColor 0xFFFFFF ofLine 100+i,200,100+i,200+@lAudio[i]*100.0 for i in [0..255] #draw the right: ofSetColor 0x333333 ofRect 600,100,256,200 ofSetColor 0xFFFFFF ofLine 600+i,200,600+i,200+@rAudio[i]*100.0 for i in [0..255] ofSetColor 0x333333 reportString = """volume: (#{@volume}) modify with -/+ keys pan: (#{@pan}) synthesis: #{ if @bNoise then 'noise' else 'sine wave' }""" if (!@bNoise) then reportString+=" (#{@targetFrequency}hz)" ofDrawBitmapString reportString,80,380 #give other threads some time to process yield(25) #collectGarbage() keyPressed: (key) -> c = String.fromCharCode key switch c when "-" @volume -= 0.05 @volume = Math.max @volume, 0 when "+" @volume += 0.05 @volume = Math.min @volume, 1 mouseMoved: (x, y) -> width = ofGetWidth() @pan = x / width height = ofGetHeight() heightPct = (height - y) / height @targetFrequency = 2000.0 * heightPct @phaseAdderTarget = (@targetFrequency / @sampleRate) * TWO_PI mouseDragged: (x, y, button) -> width = ofGetWidth() @pan = x / width mousePressed: -> @bNoise = true mouseReleased: -> @bNoise = false audioRequested: (poutput, bufferSize, nChannels) -> #make buffer indexable; 7 = kFloatArray output = @oIndex.setPtr poutput, bufferSize, 7 leftScale = 1 - @pan rightScale = @pan while @phase > TWO_PI @phase-=TWO_PI if @bNoise for i in [0..bufferSize - 1] @lAudio[i] = output[i * nChannels] = ofRandomf() * @volume * leftScale @rAudio[i] = output[i * nChannels + 1] = ofRandomf() * @volume * rightScale else @phaseAdder = 0.95 * @phaseAdder + 0.05 * @phaseAdderTarget for i in [0..bufferSize - 1] @phase += @phaseAdder sample = Math.sin @phase @lAudio[i] = output[i * nChannels] = sample * @volume * leftScale @rAudio[i] = output[i * nChannels + 1] = sample * @volume * rightScale g_App = _.extend g_App, new AudioOutputExample ofRunApp g_App
180132
### Audio output example. by <EMAIL> ### oflib = require 'lib/of' oflib._.extend this, oflib window = new ofAppGlutWindow ofSetupOpenGL window, 1024, 768, OF_WINDOW g_App = new ofBaseApp class AudioOutputExample constructor: -> @pan = 0 @sampleRate = 44100 @phase = 0 @phaseAdder = 0.0 @phaseAdderTarget = 0.0 @volume = 0.1 @bNoise = false @targetFrequency = 0 @lAudio = [] @rAudio = [] ofSoundStreamSetup 2, 0, g_App, @sampleRate, 256, 4 ofSetFrameRate(60); #this is used for indexing buffers #we call setPtr() with the buffer and then we can do [] on it. @oIndex = new Indexable draw: -> ofSetColor 0x333333 ofRect 100,100,256,200 ofSetColor 0xFFFFFF ofLine 100+i,200,100+i,200+@lAudio[i]*100.0 for i in [0..255] #draw the right: ofSetColor 0x333333 ofRect 600,100,256,200 ofSetColor 0xFFFFFF ofLine 600+i,200,600+i,200+@rAudio[i]*100.0 for i in [0..255] ofSetColor 0x333333 reportString = """volume: (#{@volume}) modify with -/+ keys pan: (#{@pan}) synthesis: #{ if @bNoise then 'noise' else 'sine wave' }""" if (!@bNoise) then reportString+=" (#{@targetFrequency}hz)" ofDrawBitmapString reportString,80,380 #give other threads some time to process yield(25) #collectGarbage() keyPressed: (key) -> c = String.fromCharCode key switch c when "-" @volume -= 0.05 @volume = Math.max @volume, 0 when "+" @volume += 0.05 @volume = Math.min @volume, 1 mouseMoved: (x, y) -> width = ofGetWidth() @pan = x / width height = ofGetHeight() heightPct = (height - y) / height @targetFrequency = 2000.0 * heightPct @phaseAdderTarget = (@targetFrequency / @sampleRate) * TWO_PI mouseDragged: (x, y, button) -> width = ofGetWidth() @pan = x / width mousePressed: -> @bNoise = true mouseReleased: -> @bNoise = false audioRequested: (poutput, bufferSize, nChannels) -> #make buffer indexable; 7 = kFloatArray output = @oIndex.setPtr poutput, bufferSize, 7 leftScale = 1 - @pan rightScale = @pan while @phase > TWO_PI @phase-=TWO_PI if @bNoise for i in [0..bufferSize - 1] @lAudio[i] = output[i * nChannels] = ofRandomf() * @volume * leftScale @rAudio[i] = output[i * nChannels + 1] = ofRandomf() * @volume * rightScale else @phaseAdder = 0.95 * @phaseAdder + 0.05 * @phaseAdderTarget for i in [0..bufferSize - 1] @phase += @phaseAdder sample = Math.sin @phase @lAudio[i] = output[i * nChannels] = sample * @volume * leftScale @rAudio[i] = output[i * nChannels + 1] = sample * @volume * rightScale g_App = _.extend g_App, new AudioOutputExample ofRunApp g_App
true
### Audio output example. by PI:EMAIL:<EMAIL>END_PI ### oflib = require 'lib/of' oflib._.extend this, oflib window = new ofAppGlutWindow ofSetupOpenGL window, 1024, 768, OF_WINDOW g_App = new ofBaseApp class AudioOutputExample constructor: -> @pan = 0 @sampleRate = 44100 @phase = 0 @phaseAdder = 0.0 @phaseAdderTarget = 0.0 @volume = 0.1 @bNoise = false @targetFrequency = 0 @lAudio = [] @rAudio = [] ofSoundStreamSetup 2, 0, g_App, @sampleRate, 256, 4 ofSetFrameRate(60); #this is used for indexing buffers #we call setPtr() with the buffer and then we can do [] on it. @oIndex = new Indexable draw: -> ofSetColor 0x333333 ofRect 100,100,256,200 ofSetColor 0xFFFFFF ofLine 100+i,200,100+i,200+@lAudio[i]*100.0 for i in [0..255] #draw the right: ofSetColor 0x333333 ofRect 600,100,256,200 ofSetColor 0xFFFFFF ofLine 600+i,200,600+i,200+@rAudio[i]*100.0 for i in [0..255] ofSetColor 0x333333 reportString = """volume: (#{@volume}) modify with -/+ keys pan: (#{@pan}) synthesis: #{ if @bNoise then 'noise' else 'sine wave' }""" if (!@bNoise) then reportString+=" (#{@targetFrequency}hz)" ofDrawBitmapString reportString,80,380 #give other threads some time to process yield(25) #collectGarbage() keyPressed: (key) -> c = String.fromCharCode key switch c when "-" @volume -= 0.05 @volume = Math.max @volume, 0 when "+" @volume += 0.05 @volume = Math.min @volume, 1 mouseMoved: (x, y) -> width = ofGetWidth() @pan = x / width height = ofGetHeight() heightPct = (height - y) / height @targetFrequency = 2000.0 * heightPct @phaseAdderTarget = (@targetFrequency / @sampleRate) * TWO_PI mouseDragged: (x, y, button) -> width = ofGetWidth() @pan = x / width mousePressed: -> @bNoise = true mouseReleased: -> @bNoise = false audioRequested: (poutput, bufferSize, nChannels) -> #make buffer indexable; 7 = kFloatArray output = @oIndex.setPtr poutput, bufferSize, 7 leftScale = 1 - @pan rightScale = @pan while @phase > TWO_PI @phase-=TWO_PI if @bNoise for i in [0..bufferSize - 1] @lAudio[i] = output[i * nChannels] = ofRandomf() * @volume * leftScale @rAudio[i] = output[i * nChannels + 1] = ofRandomf() * @volume * rightScale else @phaseAdder = 0.95 * @phaseAdder + 0.05 * @phaseAdderTarget for i in [0..bufferSize - 1] @phase += @phaseAdder sample = Math.sin @phase @lAudio[i] = output[i * nChannels] = sample * @volume * leftScale @rAudio[i] = output[i * nChannels + 1] = sample * @volume * rightScale g_App = _.extend g_App, new AudioOutputExample ofRunApp g_App
[ { "context": "r templates, refer to the FAQ: https://github.com/bevry/docpad/wiki/FAQ\n\n\ttemplateData:\n\t# Specify some s", "end": 450, "score": 0.9976492524147034, "start": 445, "tag": "USERNAME", "value": "bevry" }, { "context": "ite\"\"\"\n\n\t\t# The website author's name\n\t\t\tauthor: \"Your Name\"\n\n\t\t# The website author's email\n\t\t\temail: \"info@", "end": 1152, "score": 0.80571448802948, "start": 1143, "tag": "NAME", "value": "Your Name" }, { "context": " Name\"\n\n\t\t# The website author's email\n\t\t\temail: \"info@karstensminde.dk\"\n\n\t\t# Your company's name\n\t\t\tdata:\n\t\t\t\tsubtitle: ", "end": 1218, "score": 0.9999157786369324, "start": 1197, "tag": "EMAIL", "value": "info@karstensminde.dk" } ]
docpad.coffee
Edifice/karstensminde
0
# The DocPad Configuration File # It is simply a CoffeeScript Object which is parsed by CSON findSubPages = (database, mainPage) -> database.findAllLive({relativeOutDirPath: mainPage, pageOrder: $exists: true }, [ pageOrder: 1, title: 1 ]) docpadConfig = # Template Data # ============= # These are variables that will be accessible via our templates # To access one of these within our templates, refer to the FAQ: https://github.com/bevry/docpad/wiki/FAQ templateData: # Specify some site properties site: # The production url of our website url: "http://www.karstensminde.dk" # Here are some old site urls that you would like to redirect from oldUrls: [] # The default title of our website title: "Karstensminde" # The website description (for SEO) description: """When your website appears in search results in say Google, the text here will be shown underneath your website's title.""" # The website keywords (for SEO) separated by commas keywords: """place, your, website, keywoards, here, keep, them, related, to, the, content, of, your, website""" # The website author's name author: "Your Name" # The website author's email email: "info@karstensminde.dk" # Your company's name data: subtitle: 'Mere end et plejehjem' address1: 'Hans Jensens Vej 1' address2: '6771 Gredstedbro' phone: '75 43 14 64' # Helper Functions # ---------------- # Get the prepared site/document title # Often we would like to specify particular formatting to our page's title # we can apply that formatting here getPreparedTitle: -> # if we have a document title, then we should use that and suffix the site's title onto it if @document.title "#{@document.title} | #{@site.title}" # if our document does not have it's own title, then we should just use the site's title else @site.title # Get the prepared site/document description getPreparedDescription: -> # if we have a document description, then we should use that, otherwise use the site's description @document.description or @site.description # Get the prepared site/document keywords getPreparedKeywords: -> # Merge the document keywords with the site keywords @site.keywords.concat(@document.keywords or []).join(', ') # Collections # =========== # These are special collections that our website makes available to us collections: # For instance, this one will fetch in all documents that have pageOrder set within their meta data pages: (database) -> findSubPages(database, 'pages') # This one, will fetch in all documents that will be outputted to the posts directory posts: (database) -> database.findAllLive({relativeOutDirPath: 'posts'}, [ date: -1 ]) historie: (database) -> findSubPages(database, 'historie') 'praktiske-informationer': (database) -> findSubPages(database, 'praktiske-informationer') aktiviteter: (database) -> findSubPages(database, 'aktiviteter') personale: (database) -> findSubPages(database, 'personale') plugins: cleanurls: static: true # DocPad Events # ============= # Here we can define handlers for events that DocPad fires # You can find a full listing of events on the DocPad Wiki events: # Server Extend # Used to add our own custom routes to the server before the docpad routes are added serverExtend: (opts) -> # Extract the server from the options {server} = opts docpad = @docpad # As we are now running in an event, # ensure we are using the latest copy of the docpad configuraiton # and fetch our urls from it latestConfig = docpad.getConfig() oldUrls = latestConfig.templateData.site.oldUrls or [] newUrl = latestConfig.templateData.site.url # Redirect any requests accessing one of our sites oldUrls to the new site url server.use (req, res, next) -> if req.headers.host in oldUrls res.redirect 301, newUrl + req.url else next() # Export our DocPad Configuration module.exports = docpadConfig
137249
# The DocPad Configuration File # It is simply a CoffeeScript Object which is parsed by CSON findSubPages = (database, mainPage) -> database.findAllLive({relativeOutDirPath: mainPage, pageOrder: $exists: true }, [ pageOrder: 1, title: 1 ]) docpadConfig = # Template Data # ============= # These are variables that will be accessible via our templates # To access one of these within our templates, refer to the FAQ: https://github.com/bevry/docpad/wiki/FAQ templateData: # Specify some site properties site: # The production url of our website url: "http://www.karstensminde.dk" # Here are some old site urls that you would like to redirect from oldUrls: [] # The default title of our website title: "Karstensminde" # The website description (for SEO) description: """When your website appears in search results in say Google, the text here will be shown underneath your website's title.""" # The website keywords (for SEO) separated by commas keywords: """place, your, website, keywoards, here, keep, them, related, to, the, content, of, your, website""" # The website author's name author: "<NAME>" # The website author's email email: "<EMAIL>" # Your company's name data: subtitle: 'Mere end et plejehjem' address1: 'Hans Jensens Vej 1' address2: '6771 Gredstedbro' phone: '75 43 14 64' # Helper Functions # ---------------- # Get the prepared site/document title # Often we would like to specify particular formatting to our page's title # we can apply that formatting here getPreparedTitle: -> # if we have a document title, then we should use that and suffix the site's title onto it if @document.title "#{@document.title} | #{@site.title}" # if our document does not have it's own title, then we should just use the site's title else @site.title # Get the prepared site/document description getPreparedDescription: -> # if we have a document description, then we should use that, otherwise use the site's description @document.description or @site.description # Get the prepared site/document keywords getPreparedKeywords: -> # Merge the document keywords with the site keywords @site.keywords.concat(@document.keywords or []).join(', ') # Collections # =========== # These are special collections that our website makes available to us collections: # For instance, this one will fetch in all documents that have pageOrder set within their meta data pages: (database) -> findSubPages(database, 'pages') # This one, will fetch in all documents that will be outputted to the posts directory posts: (database) -> database.findAllLive({relativeOutDirPath: 'posts'}, [ date: -1 ]) historie: (database) -> findSubPages(database, 'historie') 'praktiske-informationer': (database) -> findSubPages(database, 'praktiske-informationer') aktiviteter: (database) -> findSubPages(database, 'aktiviteter') personale: (database) -> findSubPages(database, 'personale') plugins: cleanurls: static: true # DocPad Events # ============= # Here we can define handlers for events that DocPad fires # You can find a full listing of events on the DocPad Wiki events: # Server Extend # Used to add our own custom routes to the server before the docpad routes are added serverExtend: (opts) -> # Extract the server from the options {server} = opts docpad = @docpad # As we are now running in an event, # ensure we are using the latest copy of the docpad configuraiton # and fetch our urls from it latestConfig = docpad.getConfig() oldUrls = latestConfig.templateData.site.oldUrls or [] newUrl = latestConfig.templateData.site.url # Redirect any requests accessing one of our sites oldUrls to the new site url server.use (req, res, next) -> if req.headers.host in oldUrls res.redirect 301, newUrl + req.url else next() # Export our DocPad Configuration module.exports = docpadConfig
true
# The DocPad Configuration File # It is simply a CoffeeScript Object which is parsed by CSON findSubPages = (database, mainPage) -> database.findAllLive({relativeOutDirPath: mainPage, pageOrder: $exists: true }, [ pageOrder: 1, title: 1 ]) docpadConfig = # Template Data # ============= # These are variables that will be accessible via our templates # To access one of these within our templates, refer to the FAQ: https://github.com/bevry/docpad/wiki/FAQ templateData: # Specify some site properties site: # The production url of our website url: "http://www.karstensminde.dk" # Here are some old site urls that you would like to redirect from oldUrls: [] # The default title of our website title: "Karstensminde" # The website description (for SEO) description: """When your website appears in search results in say Google, the text here will be shown underneath your website's title.""" # The website keywords (for SEO) separated by commas keywords: """place, your, website, keywoards, here, keep, them, related, to, the, content, of, your, website""" # The website author's name author: "PI:NAME:<NAME>END_PI" # The website author's email email: "PI:EMAIL:<EMAIL>END_PI" # Your company's name data: subtitle: 'Mere end et plejehjem' address1: 'Hans Jensens Vej 1' address2: '6771 Gredstedbro' phone: '75 43 14 64' # Helper Functions # ---------------- # Get the prepared site/document title # Often we would like to specify particular formatting to our page's title # we can apply that formatting here getPreparedTitle: -> # if we have a document title, then we should use that and suffix the site's title onto it if @document.title "#{@document.title} | #{@site.title}" # if our document does not have it's own title, then we should just use the site's title else @site.title # Get the prepared site/document description getPreparedDescription: -> # if we have a document description, then we should use that, otherwise use the site's description @document.description or @site.description # Get the prepared site/document keywords getPreparedKeywords: -> # Merge the document keywords with the site keywords @site.keywords.concat(@document.keywords or []).join(', ') # Collections # =========== # These are special collections that our website makes available to us collections: # For instance, this one will fetch in all documents that have pageOrder set within their meta data pages: (database) -> findSubPages(database, 'pages') # This one, will fetch in all documents that will be outputted to the posts directory posts: (database) -> database.findAllLive({relativeOutDirPath: 'posts'}, [ date: -1 ]) historie: (database) -> findSubPages(database, 'historie') 'praktiske-informationer': (database) -> findSubPages(database, 'praktiske-informationer') aktiviteter: (database) -> findSubPages(database, 'aktiviteter') personale: (database) -> findSubPages(database, 'personale') plugins: cleanurls: static: true # DocPad Events # ============= # Here we can define handlers for events that DocPad fires # You can find a full listing of events on the DocPad Wiki events: # Server Extend # Used to add our own custom routes to the server before the docpad routes are added serverExtend: (opts) -> # Extract the server from the options {server} = opts docpad = @docpad # As we are now running in an event, # ensure we are using the latest copy of the docpad configuraiton # and fetch our urls from it latestConfig = docpad.getConfig() oldUrls = latestConfig.templateData.site.oldUrls or [] newUrl = latestConfig.templateData.site.url # Redirect any requests accessing one of our sites oldUrls to the new site url server.use (req, res, next) -> if req.headers.host in oldUrls res.redirect 301, newUrl + req.url else next() # Export our DocPad Configuration module.exports = docpadConfig
[ { "context": "st bucket, \"identity\"\n key = (rest (Key.split \"identity/\")).join \"identity/\"\n\n if Key.match /.*\\/$/\n confi", "end": 2309, "score": 0.7911673188209534, "start": 2292, "tag": "KEY", "value": "identity/\")).join" }, { "context": "y\"\n key = (rest (Key.split \"identity/\")).join \"identity/\"\n\n if Key.match /.*\\/$/\n config.remote.dir", "end": 2321, "score": 0.7055422067642212, "start": 2311, "tag": "KEY", "value": "identity/\"" } ]
src/bucket.coffee
pandastrike/haiku9
10
import {relative, join} from "path" import mime from "mime" import ProgressBar from "progress" import {flow} from "panda-garden" import {first, second, rest, cat, include, toJSON} from "panda-parchment" import {read} from "panda-quill" import {partition} from "panda-river" import {scanLocal, reconcile} from "./local" import {md5, strip, tripleJoin, isTooLarge, gzip, brotli, isCompressible} from "./helpers" establishBucket = (config) -> console.log "establishing bucket..." s3 = config.sundog.S3() {hostnames, cors} = config.environment await s3.bucketTouch first hostnames await s3.bucketSetCORS (first hostnames), cors if cors config addOriginAccess = (config) -> s3 = config.sundog.S3() {get, create} = config.sundog.CloudFront().originAccess name = config.environment.edge.originAccess unless (OAID = await get name) OAID = (await create name).CloudFrontOriginAccessIdentity include config.environment.templateData.cloudfront.primary, originAccessID: OAID.Id name = config.environment.hostnames[0] await s3.bucketSetPolicy name, toJSON Version: "2008-10-17" Statement: [ Effect: "Allow" Principal: CanonicalUser: OAID.S3CanonicalUserId Action: "s3:GetObject" Resource: "arn:aws:s3:::#{name}/*" ] config setupBucket = flow [ establishBucket addOriginAccess ] emptyBucket = (config) -> console.log "emptying buckets" s3 = config.sundog.S3() bucket = config.environment.hostnames[0] await s3.bucketEmpty bucket if await s3.bucketHead bucket config _teardownBucket = (config) -> console.log "bucket teardown" s3 = config.sundog.S3() bucket = config.environment.hostnames[0] await s3.bucketDelete bucket config teardownAccessOriginID = (config) -> console.log "origin access ID teardown" {delete: teardown} = config.sundog.CloudFront().originAccess await teardown config.environment.edge.originAccess config teardownBucket = flow [ emptyBucket _teardownBucket teardownAccessOriginID ] scanBucket = (config) -> console.log "scanning remote files" bucket = first config.environment.hostnames {list} = config.sundog.S3() config.remote = hashes: {}, directories: [] for {Key, ETag} in await list bucket, "identity" key = (rest (Key.split "identity/")).join "identity/" if Key.match /.*\/$/ config.remote.directories.push key else config.remote.hashes[key] = second ETag.split "\"" config setupProgressBar = (config) -> {deletions, uploads} = config.tasks total = deletions.length + uploads.length if total == 0 console.warn "S3 Bucket is already up-to-date." else config.tasks.deletionProgress = new ProgressBar "deleting [:bar] :percent", total: deletions.length width: 40 complete: "=" incomplete: " " config.tasks.uploadProgress = new ProgressBar "uploading [:bar] :percent", total: uploads.length width: 40 complete: "=" incomplete: " " config processDeletions = (config) -> if config.tasks.deletions.length > 0 console.log "deleting old files" {rmBatch} = config.sundog.S3() bucket = config.environment.hostnames[0] for batch from partition 1000, config.tasks.deletions await rmBatch bucket, batch config.tasks.deletionProgress.tick batch.length config _put = (config) -> upload = config.sundog.S3().PUT.buffer bucket = config.environment.hostnames[0] (key, alias) -> path = join config.source, key file = await read path, "buffer" identityKey = join "identity", (alias ? key) gzipKey = join "gzip", (alias ? key) brotliKey = join "brotli", (alias ? key) ContentMD5 = md5 file, "base64" unless ContentType = mime.getType path throw new Error "unknown file type at #{path}" await Promise.all [ upload bucket, identityKey, file, {ContentType, ContentMD5, ContentEncoding: "identity"} do -> if isCompressible file, ContentType buffer = await gzip file encoding = "gzip" hash = md5 buffer, "base64" else buffer = file encoding = "identity" hash = ContentMD5 upload bucket, gzipKey, buffer, {ContentType, ContentMD5: hash, ContentEncoding: encoding} do -> if isCompressible file, ContentType buffer = await brotli file encoding = "br" hash = md5 buffer, "base64" else buffer = file encoding = "identity" hash = ContentMD5 upload bucket, brotliKey, buffer, {ContentType, ContentMD5: hash, ContentEncoding: encoding} ] processUploads = (config) -> if config.tasks.uploads.length > 0 console.log "upserting files" put = _put config for key in config.tasks.uploads if await isTooLarge join config.source, key config.tasks.progress.tick() continue await put key await put key, strip key config.tasks.uploadProgress.tick() config _syncBucket = flow [ setupBucket scanBucket scanLocal reconcile setupProgressBar processDeletions processUploads ] syncBucket = (config) -> if config.source? _syncBucket config else config export {syncBucket, teardownBucket}
133849
import {relative, join} from "path" import mime from "mime" import ProgressBar from "progress" import {flow} from "panda-garden" import {first, second, rest, cat, include, toJSON} from "panda-parchment" import {read} from "panda-quill" import {partition} from "panda-river" import {scanLocal, reconcile} from "./local" import {md5, strip, tripleJoin, isTooLarge, gzip, brotli, isCompressible} from "./helpers" establishBucket = (config) -> console.log "establishing bucket..." s3 = config.sundog.S3() {hostnames, cors} = config.environment await s3.bucketTouch first hostnames await s3.bucketSetCORS (first hostnames), cors if cors config addOriginAccess = (config) -> s3 = config.sundog.S3() {get, create} = config.sundog.CloudFront().originAccess name = config.environment.edge.originAccess unless (OAID = await get name) OAID = (await create name).CloudFrontOriginAccessIdentity include config.environment.templateData.cloudfront.primary, originAccessID: OAID.Id name = config.environment.hostnames[0] await s3.bucketSetPolicy name, toJSON Version: "2008-10-17" Statement: [ Effect: "Allow" Principal: CanonicalUser: OAID.S3CanonicalUserId Action: "s3:GetObject" Resource: "arn:aws:s3:::#{name}/*" ] config setupBucket = flow [ establishBucket addOriginAccess ] emptyBucket = (config) -> console.log "emptying buckets" s3 = config.sundog.S3() bucket = config.environment.hostnames[0] await s3.bucketEmpty bucket if await s3.bucketHead bucket config _teardownBucket = (config) -> console.log "bucket teardown" s3 = config.sundog.S3() bucket = config.environment.hostnames[0] await s3.bucketDelete bucket config teardownAccessOriginID = (config) -> console.log "origin access ID teardown" {delete: teardown} = config.sundog.CloudFront().originAccess await teardown config.environment.edge.originAccess config teardownBucket = flow [ emptyBucket _teardownBucket teardownAccessOriginID ] scanBucket = (config) -> console.log "scanning remote files" bucket = first config.environment.hostnames {list} = config.sundog.S3() config.remote = hashes: {}, directories: [] for {Key, ETag} in await list bucket, "identity" key = (rest (Key.split "<KEY> "<KEY> if Key.match /.*\/$/ config.remote.directories.push key else config.remote.hashes[key] = second ETag.split "\"" config setupProgressBar = (config) -> {deletions, uploads} = config.tasks total = deletions.length + uploads.length if total == 0 console.warn "S3 Bucket is already up-to-date." else config.tasks.deletionProgress = new ProgressBar "deleting [:bar] :percent", total: deletions.length width: 40 complete: "=" incomplete: " " config.tasks.uploadProgress = new ProgressBar "uploading [:bar] :percent", total: uploads.length width: 40 complete: "=" incomplete: " " config processDeletions = (config) -> if config.tasks.deletions.length > 0 console.log "deleting old files" {rmBatch} = config.sundog.S3() bucket = config.environment.hostnames[0] for batch from partition 1000, config.tasks.deletions await rmBatch bucket, batch config.tasks.deletionProgress.tick batch.length config _put = (config) -> upload = config.sundog.S3().PUT.buffer bucket = config.environment.hostnames[0] (key, alias) -> path = join config.source, key file = await read path, "buffer" identityKey = join "identity", (alias ? key) gzipKey = join "gzip", (alias ? key) brotliKey = join "brotli", (alias ? key) ContentMD5 = md5 file, "base64" unless ContentType = mime.getType path throw new Error "unknown file type at #{path}" await Promise.all [ upload bucket, identityKey, file, {ContentType, ContentMD5, ContentEncoding: "identity"} do -> if isCompressible file, ContentType buffer = await gzip file encoding = "gzip" hash = md5 buffer, "base64" else buffer = file encoding = "identity" hash = ContentMD5 upload bucket, gzipKey, buffer, {ContentType, ContentMD5: hash, ContentEncoding: encoding} do -> if isCompressible file, ContentType buffer = await brotli file encoding = "br" hash = md5 buffer, "base64" else buffer = file encoding = "identity" hash = ContentMD5 upload bucket, brotliKey, buffer, {ContentType, ContentMD5: hash, ContentEncoding: encoding} ] processUploads = (config) -> if config.tasks.uploads.length > 0 console.log "upserting files" put = _put config for key in config.tasks.uploads if await isTooLarge join config.source, key config.tasks.progress.tick() continue await put key await put key, strip key config.tasks.uploadProgress.tick() config _syncBucket = flow [ setupBucket scanBucket scanLocal reconcile setupProgressBar processDeletions processUploads ] syncBucket = (config) -> if config.source? _syncBucket config else config export {syncBucket, teardownBucket}
true
import {relative, join} from "path" import mime from "mime" import ProgressBar from "progress" import {flow} from "panda-garden" import {first, second, rest, cat, include, toJSON} from "panda-parchment" import {read} from "panda-quill" import {partition} from "panda-river" import {scanLocal, reconcile} from "./local" import {md5, strip, tripleJoin, isTooLarge, gzip, brotli, isCompressible} from "./helpers" establishBucket = (config) -> console.log "establishing bucket..." s3 = config.sundog.S3() {hostnames, cors} = config.environment await s3.bucketTouch first hostnames await s3.bucketSetCORS (first hostnames), cors if cors config addOriginAccess = (config) -> s3 = config.sundog.S3() {get, create} = config.sundog.CloudFront().originAccess name = config.environment.edge.originAccess unless (OAID = await get name) OAID = (await create name).CloudFrontOriginAccessIdentity include config.environment.templateData.cloudfront.primary, originAccessID: OAID.Id name = config.environment.hostnames[0] await s3.bucketSetPolicy name, toJSON Version: "2008-10-17" Statement: [ Effect: "Allow" Principal: CanonicalUser: OAID.S3CanonicalUserId Action: "s3:GetObject" Resource: "arn:aws:s3:::#{name}/*" ] config setupBucket = flow [ establishBucket addOriginAccess ] emptyBucket = (config) -> console.log "emptying buckets" s3 = config.sundog.S3() bucket = config.environment.hostnames[0] await s3.bucketEmpty bucket if await s3.bucketHead bucket config _teardownBucket = (config) -> console.log "bucket teardown" s3 = config.sundog.S3() bucket = config.environment.hostnames[0] await s3.bucketDelete bucket config teardownAccessOriginID = (config) -> console.log "origin access ID teardown" {delete: teardown} = config.sundog.CloudFront().originAccess await teardown config.environment.edge.originAccess config teardownBucket = flow [ emptyBucket _teardownBucket teardownAccessOriginID ] scanBucket = (config) -> console.log "scanning remote files" bucket = first config.environment.hostnames {list} = config.sundog.S3() config.remote = hashes: {}, directories: [] for {Key, ETag} in await list bucket, "identity" key = (rest (Key.split "PI:KEY:<KEY>END_PI "PI:KEY:<KEY>END_PI if Key.match /.*\/$/ config.remote.directories.push key else config.remote.hashes[key] = second ETag.split "\"" config setupProgressBar = (config) -> {deletions, uploads} = config.tasks total = deletions.length + uploads.length if total == 0 console.warn "S3 Bucket is already up-to-date." else config.tasks.deletionProgress = new ProgressBar "deleting [:bar] :percent", total: deletions.length width: 40 complete: "=" incomplete: " " config.tasks.uploadProgress = new ProgressBar "uploading [:bar] :percent", total: uploads.length width: 40 complete: "=" incomplete: " " config processDeletions = (config) -> if config.tasks.deletions.length > 0 console.log "deleting old files" {rmBatch} = config.sundog.S3() bucket = config.environment.hostnames[0] for batch from partition 1000, config.tasks.deletions await rmBatch bucket, batch config.tasks.deletionProgress.tick batch.length config _put = (config) -> upload = config.sundog.S3().PUT.buffer bucket = config.environment.hostnames[0] (key, alias) -> path = join config.source, key file = await read path, "buffer" identityKey = join "identity", (alias ? key) gzipKey = join "gzip", (alias ? key) brotliKey = join "brotli", (alias ? key) ContentMD5 = md5 file, "base64" unless ContentType = mime.getType path throw new Error "unknown file type at #{path}" await Promise.all [ upload bucket, identityKey, file, {ContentType, ContentMD5, ContentEncoding: "identity"} do -> if isCompressible file, ContentType buffer = await gzip file encoding = "gzip" hash = md5 buffer, "base64" else buffer = file encoding = "identity" hash = ContentMD5 upload bucket, gzipKey, buffer, {ContentType, ContentMD5: hash, ContentEncoding: encoding} do -> if isCompressible file, ContentType buffer = await brotli file encoding = "br" hash = md5 buffer, "base64" else buffer = file encoding = "identity" hash = ContentMD5 upload bucket, brotliKey, buffer, {ContentType, ContentMD5: hash, ContentEncoding: encoding} ] processUploads = (config) -> if config.tasks.uploads.length > 0 console.log "upserting files" put = _put config for key in config.tasks.uploads if await isTooLarge join config.source, key config.tasks.progress.tick() continue await put key await put key, strip key config.tasks.uploadProgress.tick() config _syncBucket = flow [ setupBucket scanBucket scanLocal reconcile setupProgressBar processDeletions processUploads ] syncBucket = (config) -> if config.source? _syncBucket config else config export {syncBucket, teardownBucket}
[ { "context": "er for Zen Photon Garden.\n#\n# Copyright (c) 2013 Micah Elizabeth Scott <micah@scanlime.org>\n#\n# Permission is hereby g", "end": 222, "score": 0.9998753070831299, "start": 201, "tag": "NAME", "value": "Micah Elizabeth Scott" }, { "context": ".\n#\n# Copyright (c) 2013 Micah Elizabeth Scott <micah@scanlime.org>\n#\n# Permission is hereby granted, free of char", "end": 242, "score": 0.9999318718910217, "start": 224, "tag": "EMAIL", "value": "micah@scanlime.org" } ]
example /hqz/queue-watcher.coffee
amane312/photon_generator
0
#!/usr/bin/env coffee # # Watch the results of our rendering queue, and download the finished images. # This file is part of HQZ, the batch renderer for Zen Photon Garden. # # Copyright (c) 2013 Micah Elizabeth Scott <micah@scanlime.org> # # 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. # AWS = require 'aws-sdk' async = require 'async' util = require 'util' fs = require 'fs' log = (msg) -> console.log "[#{ (new Date).toJSON() }] #{msg}" logURL = console.log outputFile = "queue-watcher.log" sqs = new AWS.SQS({ apiVersion: '2012-11-05' }).client s3 = new AWS.S3({ apiVersion: '2006-03-01' }).client fileLog = (msg) -> out = fs.createWriteStream outputFile, {flags: 'a'} out.end msg + '\n' pad = (str, length) -> str = '' + str str = '0' + str while str.length < length return str msgDuration = (msg) -> millis = new Date(msg.FinishTime) - new Date(msg.StartedTime) sec = (millis / 1000) | 0 mins = (sec / 60) | 0 hours = (mins / 60) | 0 return hours + ':' + pad(mins % 60, 2) + ':' + pad(sec % 60, 2) + '.' + pad(millis % 1000, 3) class Watcher constructor: -> @jobs = {} @polling = 0 @pendingDeletions = [] @ident = 0 replaySync: (filename, cb) -> try lines = fs.readFileSync(filename).toString().split('\n') catch error # Okay if this file doesn't exist cb error if error.code != 'ENOENT' return for line in lines if line.length and line[0] == '{' try @handleMessage JSON.parse(line), cb catch error cb error run: (queueName, cb) -> sqs.createQueue QueueName: queueName (error, data) => if error cb error if data @queue = data.QueueUrl log 'Watching for results...' @pollQueue() pollQueue: -> # Handle any pending message deletions at the same rate as our queue polling. if @pendingDeletions.length > 0 batchSize = Math.min 10, @pendingDeletions.length batch = @pendingDeletions.slice 0, batchSize @pendingDeletions = @pendingDeletions.slice batchSize sqs.deleteMessageBatch QueueUrl: @queue Entries: batch (error, data) => if error log error @pendingDeletions = @pendingDeletions.concat batch @polling += 1 sqs.receiveMessage QueueUrl: @queue MaxNumberOfMessages: 10 VisibilityTimeout: 120 WaitTimeSeconds: 10 (error, data) => @polling -= 1 return log error if error if data and data.Messages for m in data.Messages do (m) => cb = (error) => @messageComplete(error, m) try @logAndHandleMessage JSON.parse(m.Body), cb catch error cb error @pollQueue() nextID: () -> @ident += 1 return '' + @ident messageComplete: (error, m) -> return log "Error processing message: " + util.inspect error if error @pendingDeletions.push Id: @nextID() ReceiptHandle: m.ReceiptHandle @pollQueue() if not @polling logAndHandleMessage: (msg, cb) -> fileLog JSON.stringify msg @handleMessage msg, cb resendMessage: (msg, cb) -> # XXX: Kind of a huge hack! sqs.createQueue QueueName: "zenphoton-hqz-render-queue" (error, data) => return cb error if error sqs.sendMessage QueueUrl: data.QueueUrl MessageBody: JSON.stringify msg cb handleMessage: (msg, cb) -> # Use job metadata left for us by queue-submit @jobs[msg.JobKey] = [] if not @jobs[msg.JobKey] job = @jobs[msg.JobKey] index = msg.JobIndex or 0 # Do we have a new URL to show? if msg.State == 'finished' logURL "http://#{ msg.OutputBucket }.s3.amazonaws.com/#{ msg.OutputKey }" # Are we repairing failures? if msg.State == 'failed' and process.argv[2] == '--retry-failed' @resendMessage msg, (error, data) -> return log "Error resending message: " + util.inspect error if error log "Resent message: " + util.inspect msg # Update the state of this render job. Note that messages may arrive out of order, # so 'started' only has an effect if the frame hasn't already taken on a different state. job[index] = msg.State if msg.State != 'started' or !job[index] # Summarize the job state summary = for i in [0 .. job.length - 1] switch job[i] when 'finished' then '#' when 'started' then '.' when 'failed' then '!' else ' ' extra = switch msg.State when 'finished' then " in #{ msgDuration msg }" else '' log "[#{ summary.join '' }] -- #{msg.JobKey} [#{index}] #{msg.State}#{extra}" cb() cb = (error) -> log util.inspect error if error qw = new Watcher qw.replaySync outputFile, cb qw.run "zenphoton-hqz-results"
212580
#!/usr/bin/env coffee # # Watch the results of our rendering queue, and download the finished images. # This file is part of HQZ, the batch renderer for Zen Photon Garden. # # Copyright (c) 2013 <NAME> <<EMAIL>> # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software without # restriction, including without limitation the rights to use, # copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following # conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. # AWS = require 'aws-sdk' async = require 'async' util = require 'util' fs = require 'fs' log = (msg) -> console.log "[#{ (new Date).toJSON() }] #{msg}" logURL = console.log outputFile = "queue-watcher.log" sqs = new AWS.SQS({ apiVersion: '2012-11-05' }).client s3 = new AWS.S3({ apiVersion: '2006-03-01' }).client fileLog = (msg) -> out = fs.createWriteStream outputFile, {flags: 'a'} out.end msg + '\n' pad = (str, length) -> str = '' + str str = '0' + str while str.length < length return str msgDuration = (msg) -> millis = new Date(msg.FinishTime) - new Date(msg.StartedTime) sec = (millis / 1000) | 0 mins = (sec / 60) | 0 hours = (mins / 60) | 0 return hours + ':' + pad(mins % 60, 2) + ':' + pad(sec % 60, 2) + '.' + pad(millis % 1000, 3) class Watcher constructor: -> @jobs = {} @polling = 0 @pendingDeletions = [] @ident = 0 replaySync: (filename, cb) -> try lines = fs.readFileSync(filename).toString().split('\n') catch error # Okay if this file doesn't exist cb error if error.code != 'ENOENT' return for line in lines if line.length and line[0] == '{' try @handleMessage JSON.parse(line), cb catch error cb error run: (queueName, cb) -> sqs.createQueue QueueName: queueName (error, data) => if error cb error if data @queue = data.QueueUrl log 'Watching for results...' @pollQueue() pollQueue: -> # Handle any pending message deletions at the same rate as our queue polling. if @pendingDeletions.length > 0 batchSize = Math.min 10, @pendingDeletions.length batch = @pendingDeletions.slice 0, batchSize @pendingDeletions = @pendingDeletions.slice batchSize sqs.deleteMessageBatch QueueUrl: @queue Entries: batch (error, data) => if error log error @pendingDeletions = @pendingDeletions.concat batch @polling += 1 sqs.receiveMessage QueueUrl: @queue MaxNumberOfMessages: 10 VisibilityTimeout: 120 WaitTimeSeconds: 10 (error, data) => @polling -= 1 return log error if error if data and data.Messages for m in data.Messages do (m) => cb = (error) => @messageComplete(error, m) try @logAndHandleMessage JSON.parse(m.Body), cb catch error cb error @pollQueue() nextID: () -> @ident += 1 return '' + @ident messageComplete: (error, m) -> return log "Error processing message: " + util.inspect error if error @pendingDeletions.push Id: @nextID() ReceiptHandle: m.ReceiptHandle @pollQueue() if not @polling logAndHandleMessage: (msg, cb) -> fileLog JSON.stringify msg @handleMessage msg, cb resendMessage: (msg, cb) -> # XXX: Kind of a huge hack! sqs.createQueue QueueName: "zenphoton-hqz-render-queue" (error, data) => return cb error if error sqs.sendMessage QueueUrl: data.QueueUrl MessageBody: JSON.stringify msg cb handleMessage: (msg, cb) -> # Use job metadata left for us by queue-submit @jobs[msg.JobKey] = [] if not @jobs[msg.JobKey] job = @jobs[msg.JobKey] index = msg.JobIndex or 0 # Do we have a new URL to show? if msg.State == 'finished' logURL "http://#{ msg.OutputBucket }.s3.amazonaws.com/#{ msg.OutputKey }" # Are we repairing failures? if msg.State == 'failed' and process.argv[2] == '--retry-failed' @resendMessage msg, (error, data) -> return log "Error resending message: " + util.inspect error if error log "Resent message: " + util.inspect msg # Update the state of this render job. Note that messages may arrive out of order, # so 'started' only has an effect if the frame hasn't already taken on a different state. job[index] = msg.State if msg.State != 'started' or !job[index] # Summarize the job state summary = for i in [0 .. job.length - 1] switch job[i] when 'finished' then '#' when 'started' then '.' when 'failed' then '!' else ' ' extra = switch msg.State when 'finished' then " in #{ msgDuration msg }" else '' log "[#{ summary.join '' }] -- #{msg.JobKey} [#{index}] #{msg.State}#{extra}" cb() cb = (error) -> log util.inspect error if error qw = new Watcher qw.replaySync outputFile, cb qw.run "zenphoton-hqz-results"
true
#!/usr/bin/env coffee # # Watch the results of our rendering queue, and download the finished images. # This file is part of HQZ, the batch renderer for Zen Photon Garden. # # Copyright (c) 2013 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation # files (the "Software"), to deal in the Software without # restriction, including without limitation the rights to use, # copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following # conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES # OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. # AWS = require 'aws-sdk' async = require 'async' util = require 'util' fs = require 'fs' log = (msg) -> console.log "[#{ (new Date).toJSON() }] #{msg}" logURL = console.log outputFile = "queue-watcher.log" sqs = new AWS.SQS({ apiVersion: '2012-11-05' }).client s3 = new AWS.S3({ apiVersion: '2006-03-01' }).client fileLog = (msg) -> out = fs.createWriteStream outputFile, {flags: 'a'} out.end msg + '\n' pad = (str, length) -> str = '' + str str = '0' + str while str.length < length return str msgDuration = (msg) -> millis = new Date(msg.FinishTime) - new Date(msg.StartedTime) sec = (millis / 1000) | 0 mins = (sec / 60) | 0 hours = (mins / 60) | 0 return hours + ':' + pad(mins % 60, 2) + ':' + pad(sec % 60, 2) + '.' + pad(millis % 1000, 3) class Watcher constructor: -> @jobs = {} @polling = 0 @pendingDeletions = [] @ident = 0 replaySync: (filename, cb) -> try lines = fs.readFileSync(filename).toString().split('\n') catch error # Okay if this file doesn't exist cb error if error.code != 'ENOENT' return for line in lines if line.length and line[0] == '{' try @handleMessage JSON.parse(line), cb catch error cb error run: (queueName, cb) -> sqs.createQueue QueueName: queueName (error, data) => if error cb error if data @queue = data.QueueUrl log 'Watching for results...' @pollQueue() pollQueue: -> # Handle any pending message deletions at the same rate as our queue polling. if @pendingDeletions.length > 0 batchSize = Math.min 10, @pendingDeletions.length batch = @pendingDeletions.slice 0, batchSize @pendingDeletions = @pendingDeletions.slice batchSize sqs.deleteMessageBatch QueueUrl: @queue Entries: batch (error, data) => if error log error @pendingDeletions = @pendingDeletions.concat batch @polling += 1 sqs.receiveMessage QueueUrl: @queue MaxNumberOfMessages: 10 VisibilityTimeout: 120 WaitTimeSeconds: 10 (error, data) => @polling -= 1 return log error if error if data and data.Messages for m in data.Messages do (m) => cb = (error) => @messageComplete(error, m) try @logAndHandleMessage JSON.parse(m.Body), cb catch error cb error @pollQueue() nextID: () -> @ident += 1 return '' + @ident messageComplete: (error, m) -> return log "Error processing message: " + util.inspect error if error @pendingDeletions.push Id: @nextID() ReceiptHandle: m.ReceiptHandle @pollQueue() if not @polling logAndHandleMessage: (msg, cb) -> fileLog JSON.stringify msg @handleMessage msg, cb resendMessage: (msg, cb) -> # XXX: Kind of a huge hack! sqs.createQueue QueueName: "zenphoton-hqz-render-queue" (error, data) => return cb error if error sqs.sendMessage QueueUrl: data.QueueUrl MessageBody: JSON.stringify msg cb handleMessage: (msg, cb) -> # Use job metadata left for us by queue-submit @jobs[msg.JobKey] = [] if not @jobs[msg.JobKey] job = @jobs[msg.JobKey] index = msg.JobIndex or 0 # Do we have a new URL to show? if msg.State == 'finished' logURL "http://#{ msg.OutputBucket }.s3.amazonaws.com/#{ msg.OutputKey }" # Are we repairing failures? if msg.State == 'failed' and process.argv[2] == '--retry-failed' @resendMessage msg, (error, data) -> return log "Error resending message: " + util.inspect error if error log "Resent message: " + util.inspect msg # Update the state of this render job. Note that messages may arrive out of order, # so 'started' only has an effect if the frame hasn't already taken on a different state. job[index] = msg.State if msg.State != 'started' or !job[index] # Summarize the job state summary = for i in [0 .. job.length - 1] switch job[i] when 'finished' then '#' when 'started' then '.' when 'failed' then '!' else ' ' extra = switch msg.State when 'finished' then " in #{ msgDuration msg }" else '' log "[#{ summary.join '' }] -- #{msg.JobKey} [#{index}] #{msg.State}#{extra}" cb() cb = (error) -> log util.inspect error if error qw = new Watcher qw.replaySync outputFile, cb qw.run "zenphoton-hqz-results"
[ { "context": "g 'Inserting user admin'.red\n\t\tconsole.log 'email: admin@admin.com | password: admin'.red\n\n\t\tid = Meteor.users.inser", "end": 195, "score": 0.999920666217804, "start": 180, "tag": "EMAIL", "value": "admin@admin.com" }, { "context": "\n\t\tconsole.log 'email: admin@admin.com | password: admin'.red\n\n\t\tid = Meteor.users.insert\n\t\t\tcreatedAt: ne", "end": 213, "score": 0.999129593372345, "start": 208, "tag": "PASSWORD", "value": "admin" }, { "context": "\t\t\tcreatedAt: new Date\n\t\t\temails: [\n\t\t\t\taddress: 'admin@admin.com'\n\t\t\t\tverified: true\n\t\t\t],\n\t\t\tname: 'Admin'\n\n\t\tAcc", "end": 312, "score": 0.9999192953109741, "start": 297, "tag": "EMAIL", "value": "admin@admin.com" }, { "context": "min@admin.com'\n\t\t\t\tverified: true\n\t\t\t],\n\t\t\tname: 'Admin'\n\n\t\tAccounts.setPassword id, 'admin'\n", "end": 354, "score": 0.8896668553352356, "start": 349, "tag": "NAME", "value": "Admin" }, { "context": "\t],\n\t\t\tname: 'Admin'\n\n\t\tAccounts.setPassword id, 'admin'\n", "end": 390, "score": 0.9909168481826782, "start": 385, "tag": "PASSWORD", "value": "admin" } ]
server/startup/initialData.coffee
halilertekin/Rocket.Chat
0
lineSep = '---------------------------' Meteor.startup -> if not Meteor.users.findOne()? console.log lineSep.red console.log 'Inserting user admin'.red console.log 'email: admin@admin.com | password: admin'.red id = Meteor.users.insert createdAt: new Date emails: [ address: 'admin@admin.com' verified: true ], name: 'Admin' Accounts.setPassword id, 'admin'
39204
lineSep = '---------------------------' Meteor.startup -> if not Meteor.users.findOne()? console.log lineSep.red console.log 'Inserting user admin'.red console.log 'email: <EMAIL> | password: <PASSWORD>'.red id = Meteor.users.insert createdAt: new Date emails: [ address: '<EMAIL>' verified: true ], name: '<NAME>' Accounts.setPassword id, '<PASSWORD>'
true
lineSep = '---------------------------' Meteor.startup -> if not Meteor.users.findOne()? console.log lineSep.red console.log 'Inserting user admin'.red console.log 'email: PI:EMAIL:<EMAIL>END_PI | password: PI:PASSWORD:<PASSWORD>END_PI'.red id = Meteor.users.insert createdAt: new Date emails: [ address: 'PI:EMAIL:<EMAIL>END_PI' verified: true ], name: 'PI:NAME:<NAME>END_PI' Accounts.setPassword id, 'PI:PASSWORD:<PASSWORD>END_PI'
[ { "context": " 'works', ->\n obj = {king: 'queen', prince: 'princess'}\n store.set obj: obj\n expect(store.get", "end": 1151, "score": 0.6481549739837646, "start": 1143, "tag": "NAME", "value": "princess" } ]
spec/store/local_storage_spec.coffee
TheSwanFactory/self-service-kiosk
0
describe 'SwanKiosk.Store.LocalStorage', -> store = new SwanKiosk.Store.LocalStorage beforeEach -> localStorage.clear() describe '#set()', -> it 'sets properly', -> store.set 'key', 'value' expect(localStorage['key']).to.eq 'value' it 'sets many', -> store.set sleigh: 'ride', kiosk: 'monitor' expect(store.get 'sleigh').to.eq 'ride' expect(store.get 'kiosk').to.eq 'monitor' describe '#setMany()', -> it 'works', -> store.setMany key: 'lock', rain: 'deer' expect(localStorage['key']).to.eq 'lock' expect(localStorage['rain']).to.eq 'deer' describe '#get()', -> it 'gets properly', -> localStorage['get'] = 'get' expect(store.get 'get').to.eq 'get' it 'gets many', -> store.set base: 'ball', card: 'collector' expect(store.get ['base', 'card']).to.eql ['ball', 'collector'] describe '#getMany()', -> it 'works', -> store.set 'this', 'that' store.set 'that', 'this' expect(store.get ['this', 'that']).to.eql ['that', 'this'] describe '#getObject()', -> it 'works', -> obj = {king: 'queen', prince: 'princess'} store.set obj: obj expect(store.getObject 'obj').to.eql obj
116780
describe 'SwanKiosk.Store.LocalStorage', -> store = new SwanKiosk.Store.LocalStorage beforeEach -> localStorage.clear() describe '#set()', -> it 'sets properly', -> store.set 'key', 'value' expect(localStorage['key']).to.eq 'value' it 'sets many', -> store.set sleigh: 'ride', kiosk: 'monitor' expect(store.get 'sleigh').to.eq 'ride' expect(store.get 'kiosk').to.eq 'monitor' describe '#setMany()', -> it 'works', -> store.setMany key: 'lock', rain: 'deer' expect(localStorage['key']).to.eq 'lock' expect(localStorage['rain']).to.eq 'deer' describe '#get()', -> it 'gets properly', -> localStorage['get'] = 'get' expect(store.get 'get').to.eq 'get' it 'gets many', -> store.set base: 'ball', card: 'collector' expect(store.get ['base', 'card']).to.eql ['ball', 'collector'] describe '#getMany()', -> it 'works', -> store.set 'this', 'that' store.set 'that', 'this' expect(store.get ['this', 'that']).to.eql ['that', 'this'] describe '#getObject()', -> it 'works', -> obj = {king: 'queen', prince: '<NAME>'} store.set obj: obj expect(store.getObject 'obj').to.eql obj
true
describe 'SwanKiosk.Store.LocalStorage', -> store = new SwanKiosk.Store.LocalStorage beforeEach -> localStorage.clear() describe '#set()', -> it 'sets properly', -> store.set 'key', 'value' expect(localStorage['key']).to.eq 'value' it 'sets many', -> store.set sleigh: 'ride', kiosk: 'monitor' expect(store.get 'sleigh').to.eq 'ride' expect(store.get 'kiosk').to.eq 'monitor' describe '#setMany()', -> it 'works', -> store.setMany key: 'lock', rain: 'deer' expect(localStorage['key']).to.eq 'lock' expect(localStorage['rain']).to.eq 'deer' describe '#get()', -> it 'gets properly', -> localStorage['get'] = 'get' expect(store.get 'get').to.eq 'get' it 'gets many', -> store.set base: 'ball', card: 'collector' expect(store.get ['base', 'card']).to.eql ['ball', 'collector'] describe '#getMany()', -> it 'works', -> store.set 'this', 'that' store.set 'that', 'this' expect(store.get ['this', 'that']).to.eql ['that', 'this'] describe '#getObject()', -> it 'works', -> obj = {king: 'queen', prince: 'PI:NAME:<NAME>END_PI'} store.set obj: obj expect(store.getObject 'obj').to.eql obj
[ { "context": "\n\n failKey = (key) ->\n unless key.match(/^fail[A-Z]/)\n return u.prefixCamelCase(key, 'fail')", "end": 49727, "score": 0.5381043553352356, "start": 49727, "tag": "KEY", "value": "" }, { "context": " failKey = (key) ->\n unless key.match(/^fail[A-Z]/)\n return u.prefixCamelCase(key, 'fail')\n\n ", "end": 49732, "score": 0.6456003189086914, "start": 49730, "tag": "KEY", "value": "Z]" } ]
lib/assets/javascripts/unpoly/fragment.coffee
pfw/unpoly
0
u = up.util e = up.element ###** Fragment API =========== The `up.fragment` module offers a high-level JavaScript API to work with DOM elements. A fragment is an element with some additional properties that are useful in the context of a server-rendered web application: - Fragments are [identified by a CSS selector](/up.fragment.toTarget), like a `.class` or `#id`. - Fragments are usually updated by a [link](/a-up-follow) for [form](/form-up-submits) that targets their selector. When the server renders HTML with a matching element, the fragment is swapped with a new version. - As fragments enter the page they are automatically [compiled](/up.compiler) to activate JavaScript behavior. - Fragment changes may be [animated](/up.motion). - Fragments are placed on a [layer](/up.layer) that is isolated from other layers. Unpoly features will only see or change fragments from the [current layer](/up.layer.current) unless you [explicitly target another layer](/layer-option). - Fragments [know the URL from where they were loaded](/up.source). They can be [reloaded](/up.reload) or [polled periodically](/up-polled). For low-level DOM utilities that complement the browser's native API, see `up.element`. @see up.render @see up.navigate @see up.destroy @see up.reload @see up.fragment.get @see up.hello @module up.fragment ### up.fragment = do -> ###** Configures defaults for fragment updates. @property up.fragment.config @param {Array<string>} [config.mainTargets=['[up-main]', 'main', ':layer']] An array of CSS selectors matching default render targets. When no other render target is given, Unpoly will try to find and replace a main target. When [navigating](/navigation) to a main target, Unpoly will automatically [reset scroll positions](/scroll-option) and [update the browser history](/up.render#options.history). This property is aliased as [`up.layer.config.any.mainTargets`](up.layer.config#config.any.mainTargets). @param {Array<string|RegExp>} [config.badTargetClasses] An array of class names that should be ignored when [deriving a target selector from a fragment](/up.fragment.toTarget). The class names may also be passed as a regular expression. @param {Object} [config.navigateOptions] An object of default options to apply when [navigating](/navigation). @param {boolean} [config.matchAroundOrigin] Whether to match an existing fragment around the triggered link. If set to `false` Unpoly will replace the first fragment matching the given target selector in the link's [layer](/up.layer). @param {Array<string>} [config.autoHistoryTargets] When an updated fragments contain an element matching one of the given CSS selectors, history will be updated with `{ history: 'auto' }`. By default Unpoly will auto-update history when updating a [main target](#config.mainTargets). @param {boolean|string|Function(Element)} [config.autoScroll] How to scroll after updating a fragment with `{ scroll: 'auto' }`. See [scroll option](/scroll-option) for a list of allowed values. The default configuration tries, in this order: - If the URL has a `#hash`, scroll to the hash. - If updating a [main target](/up-main), reset scroll positions. @param {boolean|string|Function(Element)} [config.autoFocus] How to focus when updating a fragment with `{ focus: 'auto' }`. See [focus option](/focus-option) for a list of allowed values. The default configuration tries, in this order: - Focus a `#hash` in the URL. - Focus an `[autofocus]` element in the new fragment. - If focus was lost with the old fragment, focus the new fragment. - If updating a [main target](/up-main), focus the new fragment. @param {boolean} [config.runScripts=false] Whether to execute `<script>` tags in updated fragments. Scripts will load asynchronously, with no guarantee of execution order. If you set this to `true`, mind that the `<body>` element is a default [main target](/up-main). If you are including your global application scripts at the end of your `<body>` for performance reasons, swapping the `<body>` will re-execute these scripts. In that case you must configure a different main target that does not include your application scripts. @stable ### config = new up.Config -> badTargetClasses: [/^up-/] # These defaults will be set to both success and fail options # if { navigate: true } is given. navigateOptions: { focus: 'auto' scroll: 'auto' solo: true # preflight feedback: true # preflight fallback: true history: 'auto' peel: true cache: 'auto' } matchAroundOrigin: true runScripts: false autoHistoryTargets: [':main'] autoFocus: ['hash', 'autofocus', 'main-if-main', 'target-if-lost'] autoScroll: ['hash', 'layer-if-main'] # Users who are not using layers will prefer settings default targets # as up.fragment.config.mainTargets instead of up.layer.config.any.mainTargets. u.delegate config, 'mainTargets', -> up.layer.config.any reset = -> config.reset() ###** Returns the URL the given element was retrieved from. If the given element was never directly updated, but part of a larger fragment update, the closest known source of an ancestor element is returned. \#\#\# Example In the HTML below, the element `#one` was loaded from the URL `/foo`: ```html <div id="one" up-source"/foo"> <div id="two">...</div> </div> ``` We can now ask for the source of an element: ```javascript up.fragment.source('#two') // returns '/foo' ``` @function up.fragment.source @param {Element|string} element The element or CSS selector for which to look up the source URL. @return {string|undefined} @stable ### sourceOf = (element, options = {}) -> element = getSmart(element, options) return e.closestAttr(element, 'up-source') ###** Returns a timestamp for the last modification of the content in the given element. @function up.fragment.time @param {Element} element @return {string} @internal ### timeOf = (element) -> return e.closestAttr(element, 'up-time') || '0' ###** Sets the time when the fragment's underlying data was last changed. This can be used to avoid rendering unchanged HTML when [reloading](/up.reload) a fragment. This saves <b>CPU time</b> and reduces the <b>bandwidth cost</b> for a request/response exchange to **~1 KB**. \#\# Example Let's say we display a list of recent messages. We use the `[up-poll]` attribute to reload the `.messages` fragment every 30 seconds: ```html <div class="messages" up-poll> ... </div> ``` The list is now always up to date. But most of the time there will not be new messages, and we waste resources sending the same unchanged HTML from the server. We can improve this by setting an `[up-time]` attribute and the message list. The attribute value is the time of the most recent message. The time is encoded as the number of seconds since [Unix epoch](https://en.wikipedia.org/wiki/Unix_time). When, for instance, the last message in a list was received from December 24th, 1:51:46 PM UTC, we use the following HTML: ```html <div class="messages" up-time="1608730818" up-poll> ... </div> ``` When reloading Unpoly will echo the `[up-time]` timestamp in an `X-Up-Reload-From-Time` header: ```http X-Up-Reload-From-Time: 1608730818 ``` The server can compare the time from the request with the time of the last data update. If no more recent data is available, the server can render nothing and respond with an [`X-Up-Target: :none`](/X-Up-Target) header. Here is an example with [unpoly-rails](https://unpoly.com/install/rails): ```ruby class MessagesController < ApplicationController def index if up.reload_from_time == current_user.last_message_at up.render_nothing else @messages = current_user.messages.order(time: :desc).to_a render 'index' end end end ``` @selector [up-time] @param {string} up-time The number of seconds between the [Unix epoch](https://en.wikipedia.org/wiki/Unix_time). and the time when the element's underlying data was last changed. @experimental ### ###** Sets this element's source URL for [reloading](/up.reload) and [polling](/up-poll) When an element is reloaded, Unpoly will make a request from the URL that originally brought the element into the DOM. You may use `[up-source]` to use another URL instead. \#\#\# Example Assume an application layout with an unread message counter. You use `[up-poll]` to refresh the counter every 30 seconds. By default this would make a request to the URL that originally brought the counter element into the DOM. To save the server from rendering a lot of unused HTML, you may poll from a different URL like so: <div class="unread-count" up-poll up-source="/unread-count"> 2 new messages </div> @selector [up-source] @param {string} up-source The URL from which to reload this element. @stable ### ###** Replaces elements on the current page with matching elements from a server response or HTML string. The current and new elements must both match the same CSS selector. The selector is either given as `{ target }` option, or a [main target](/up-main) is used as default. See the [fragment placement](/fragment-placement) selector for many examples for how you can target content. This function has many options to enable scrolling, focus, request cancelation and other side effects. These options are all disabled by default and must be opted into one-by-one. To enable defaults that a user would expects for navigation (like clicking a link), pass [`{ navigate: true }`](#options.navigate) or use `up.navigate()` instead. \#\#\# Passing the new fragment The new fragment content can be passed as one of the following options: - [`{ url }`](#options.url) fetches and renders content from the server - [`{ document }`](#options.document) renders content from a given HTML document string or partial document - [`{ fragment }`](#options.fragment) renders content from a given HTML string that only contains the new fragment - [`{ content }`](#options-content) replaces the targeted fragment's inner HTML with the given HTML string \#\#\# Example Let's say your current HTML looks like this: ```html <div class="one">old one</div> <div class="two">old two</div> ``` We now replace the second `<div>` by targeting its CSS class: ```js up.render({ target: '.two', url: '/new' }) ``` The server renders a response for `/new`: ```html <div class="one">new one</div> <div class="two">new two</div> ``` Unpoly looks for the selector `.two` in the response and [implants](/up.extract) it into the current page. The current page now looks like this: ```html <div class="one">old one</div> <div class="two">new two</div> ``` Note how only `.two` has changed. The update for `.one` was discarded, since it didn't match the selector. \#\#\# Events Unpoly will emit events at various stages of the rendering process: - `up:fragment:destroyed` - `up:fragment:loaded` - `up:fragment:inserted` @function up.render @param {string|Element|jQuery|Array<string>} [target] The CSS selector to update. If omitted a [main target](/up-main) will be rendered. You may also pass a DOM element or jQuery element here, in which case a selector will be [inferred from the element attributes](/up.fragment.toTarget). The given element will also be used as [`{ origin }`](#options.origin) for the fragment update. You may also pass an array of selector alternatives. The first selector matching in both old and new content will be used. Instead of passing the target as the first argument, you may also pass it as a [´{ target }`](#options.target) option.. @param {string|Element|jQuery|Array<string>} [options.target] The CSS selector to update. See documentation for the [`target`](#target) parameter. @param {string|boolean} [options.fallback=false] Specifies behavior if the [target selector](/up.render#options.target) is missing from the current page or the server response. If set to a CSS selector string, Unpoly will attempt to replace that selector instead. If set to `true` Unpoly will attempt to replace a [main target](/up-main) instead. If set to `false` Unpoly will immediately reject the render promise. @param {boolean} [options.navigate=false] Whether this fragment update is considered [navigation](/navigation). @param {string} [options.url] The URL to fetch from the server. Instead of making a server request, you may also pass an existing HTML string as [`{ document }`](#options.document), [`{ fragment }`](#options.fragment) or [`{ content }`](#options.content) option. @param {string} [options.method='get'] The HTTP method to use for the request. Common values are `'get'`, `'post'`, `'put'`, `'patch'` and `'delete`'. The value is case insensitive. @param {Object|FormData|string|Array} [options.params] Additional [parameters](/up.Params) that should be sent as the request's [query string](https://en.wikipedia.org/wiki/Query_string) or payload. When making a `GET` request to a URL with a query string, the given `{ params }` will be added to the query parameters. @param {Object} [options.headers={}] An object with additional request headers. Note that Unpoly will by default send a number of custom request headers. E.g. the `X-Up-Target` header includes the targeted CSS selector. See `up.protocol` and `up.network.config.metaKeys` for details. @param {string|Element} [options.fragment] A string of HTML comprising *only* the new fragment. The `{ target }` selector will be derived from the root element in the given HTML: ```js // This will update .foo up.render({ fragment: '<div class=".foo">inner</div>' }) ``` If your HTML string contains other fragments that will not be rendered, use the [`{ document }`](#options.document) option instead. If your HTML string comprises only the new fragment's [inner HTML](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML), consider the [`{ content }`](#options.content) option. @param {string|Element|Document} [options.document] A string of HTML containing the new fragment. The string may contain other HTML, but only the element matching the `{ target }` selector will be extracted and placed into the page. Other elements will be discarded. If your HTML string comprises only the new fragment, consider the [`{ fragment }`](#options.fragment) option instead. With `{ fragment }` you don't need to pass a `{ target }`, since Unpoly can derive it from the root element in the given HTML. If your HTML string comprises only the new fragment's [inner HTML](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML), consider the [`{ content }`](#options.content) option. @param {string} [options.fail='auto'] How to render a server response with an error code. Any HTTP status code other than 2xx is considered an error code. See [handling server errors](/server-errors) for details. @param {boolean|string} [options.history] Whether the browser URL and window title will be updated. If set to `true`, the history will always be updated, using the title and URL from the server response, or from given `{ title }` and `{ location }` options. If set to `'auto'` history will be updated if the `{ target }` matches a selector in `up.fragment.config.autoHistoryTargets`. By default this contains all [main targets](/up-main). If set to `false`, the history will remain unchanged. [Overlays](/up.layer) will only change the browser URL and window title if the overlay has [visible history](/up.layer.historyVisible), even when `{ history: true }` is passed. @param {string} [options.title] An explicit document title to use after rendering. By default the title is extracted from the response's `<title>` tag. You may also pass `{ title: false }` to explicitly prevent the title from being updated. Note that the browser's window title will only be updated it you also pass a [`{ history }`](#options.history) option. @param {string} [options.location] An explicit URL to use after rendering. By default Unpoly will use the `{ url }` or the final URL after the server redirected. You may also pass `{ location: false }` to explicitly prevent the URL from being updated. Note that the browser's URL will only be updated it you also pass a [`{ history }`](#options.history) option. @param {string} [options.transition] The name of an [transition](/up.motion) to morph between the old and few fragment. If you are [prepending or appending content](/fragment-placement#appending-or-prepending-content), use the `{ animation }` option instead. @param {string} [options.animation] The name of an [animation](/up.motion) to reveal a new fragment when [prepending or appending content](/fragment-placement#appending-or-prepending-content). If you are replacing content (the default), use the `{ transition }` option instead. @param {number} [options.duration] The duration of the transition or animation (in millisconds). @param {string} [options.easing] The timing function that accelerates the transition or animation. See [W3C documentation](http://www.w3.org/TR/css3-transitions/#transition-timing-function) for a list of available timing functions. @param {boolean} [options.cache] Whether to read from and write to the [cache](/up.cache). With `{ cache: true }` Unpoly will try to re-use a cached response before connecting to the network. If no cached response exists, Unpoly will make a request and cache the server response. Also see [`up.request({ cache })`](/up.request#options.cache). @param {boolean|string} [options.clearCache] Whether existing [cache](/up.cache) entries will be [cleared](/up.cache.clear) with this request. You may also pass a [URL pattern](/url-patterns) to only clear matching requests. By default a non-GET request will clear the entire cache. Also see [`up.request({ clearCache })`](/up.request#options.clearCache) and `up.network.config.clearCache`. @param {Element|jQuery} [options.origin] The element that triggered the change. When multiple elements in the current page match the `{ target }`, Unpoly will replace an element in the [origin's vicinity](/fragment-placement). The origin's selector will be substituted for `:origin` in a target selector. @param {string|up.Layer|Element} [options.layer='origin current'] The [layer](/up.layer) in which to match and render the fragment. See [layer option](/layer-option) for a list of allowed values. To [open the fragment in a new overlay](/opening-overlays), pass `{ layer: 'new' }`. In this case options for `up.layer.open()` may also be used. @param {boolean} [options.peel] Whether to close overlays obstructing the updated layer when the fragment is updated. This is only relevant when updating a layer that is not the [frontmost layer](/up.layer.front). @param {Object} [options.context] An object that will be merged into the [context](/context) of the current layer once the fragment is rendered. @param {boolean} [options.keep=true] Whether [`[up-keep]`](/up-keep) elements will be preserved in the updated fragment. @param {boolean} [options.hungry=true] Whether [`[up-hungry]`](/up-hungry) elements outside the updated fragment will also be updated. @param {boolean|string|Element|Function} [options.scroll] How to scroll after the new fragment was rendered. See [scroll option](/scroll-option) for a list of allowed values. @param {boolean} [options.saveScroll=true] Whether to save scroll positions before updating the fragment. Saved scroll positions can later be restored with [`{ scroll: 'restore' }`](/scroll-option#restoring-scroll-options). @param {boolean|string|Element|Function} [options.focus] What to focus after the new fragment was rendered. See [focus option](/focus-option) for a list of allowed values. @param {string} [options.confirm] A message the user needs to confirm before fragments are updated. The message will be shown as a [native browser prompt](https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt). If the user does not confirm the render promise will reject and no fragments will be updated. @param {boolean|Element} [options.feedback] Whether to give the [`{ origin }`](#options.origin) element an `.up-active` class while loading and rendering content. May also pass an element which should receive the `.up-active` class. @param {Function(Event)} [options.onLoaded] A callback that will be run when when the server responds with new HTML, but before the HTML is rendered. The callback argument is a preventable `up:fragment:loaded` event. @param {Function()} [options.onFinished] A callback that will be run when all animations have concluded and elements were removed from the DOM tree. @return {Promise<up.RenderResult>} A promise that fulfills when the page has been updated. If the update is animated, the promise will be resolved *before* the existing element was removed from the DOM tree. The old element will be marked with the `.up-destroying` class and removed once the animation finishes. To run code after the old element was removed, pass an `{ onFinished }` callback. The promise will fulfill with an `up.RenderResult` that contains references to the updated fragments and layer. @stable ### render = up.mockable (args...) -> # Convert thrown errors into rejected promises. # Convert non-promise values into a resolved promise. return u.asyncify -> options = parseTargetAndOptions(args) options = up.RenderOptions.preprocess(options) up.browser.assertConfirmed(options) if guardEvent = u.pluckKey(options, 'guardEvent') # Allow guard event handlers to manipulate render options for the default behavior. # # Note that we have removed { guardEvent } from options to not recursively define # guardEvent.renderOptions.guardEvent. This would cause an infinite loop for event # listeners that prevent the default and re-render. guardEvent.renderOptions = options up.event.assertEmitted(guardEvent, { target: options.origin }) up.RenderOptions.assertContentGiven(options) if options.url return renderRemoteContent(options) else return renderLocalContent(options) renderRemoteContent = (options) -> # Rendering a remote URL is an async operation. # We give feedback (.up-active) while the fragment is loading. return up.feedback.aroundForOptions options, -> return new up.Change.FromURL(options).execute() renderLocalContent = (options) -> # When we have a given { url }, the { solo } option is honored by up.request(). # But up.request() is never called when we have local content given as { document }, # { content } or { fragment }. Hence we abort here. up.network.mimicLocalRequest(options) # (1) No need to give feedback as local changes are sync. # (2) Value will be converted to a fulfilled promise by up.util.asyncify() in render(). return new up.Change.FromContent(options).execute() ###** [Navigates](/navigation) to the given URL by updating a major fragment in the current page. `up.navigate()` will mimic a click on a vanilla `<a href>` link to satisfy user expectations regarding scrolling, focus, request cancelation and [many other side effects](/navigation). Instead of calling `up.navigate()` you may also call `up.render({ navigate: true }`) option for the same effect. @function up.navigate @param {string|Element|jQuery} [target] The CSS selector to update. If omitted a [main target](/up-main) will be rendered. You can also pass a DOM element or jQuery element here, in which case a selector will be [inferred from the element attributes](/up.fragment.target). The given element will also be set as the `{ origin }` option. Instead of passing the target as the first argument, you may also pass it as [´{ target }` option](/up.fragment.render#options.target). @param {Object} [options] See options for `up.render()`. @stable ### navigate = up.mockable (args...) -> options = parseTargetAndOptions(args) return render(u.merge(options, navigate: true)) ###** This event is [emitted](/up.emit) when the server responds with the HTML, before the HTML is used to [change a fragment](/up.render). Event listeners may call `event.preventDefault()` on an `up:fragment:loaded` event to prevent any changes to the DOM and browser history. This is useful to detect an entirely different page layout (like a maintenance page or fatal server error) which should be open with a full page load: ```js up.on('up:fragment:loaded', (event) => { let isMaintenancePage = event.response.getHeader('X-Maintenance') if (isMaintenancePage) { // Prevent the fragment update and don't update browser history event.preventDefault() // Make a full page load for the same request. event.request.loadPage() } }) ``` Instead of preventing the update, listeners may also access the `event.renderOptions` object to mutate options to the `up.render()` call that will process the server response. @event up:fragment:loaded @param event.preventDefault() Event listeners may call this method to prevent the fragment change. @param {up.Request} event.request The original request to the server. @param {up.Response} event.response The server response. @param {Object} event.renderOptions Options for the `up.render()` call that will process the server response. @stable ### ###** Elements with an `up-keep` attribute will be persisted during [fragment updates](/up.fragment). The element you're keeping should have an umambiguous class name, ID or `[up-id]` attribute so Unpoly can find its new position within the page update. Emits events [`up:fragment:keep`](/up:fragment:keep) and [`up:fragment:kept`](/up:fragment:kept). \#\#\# Example The following `<audio>` element will be persisted through fragment updates as long as the responses contain an element matching `#player`: ```html <audio id="player" up-keep src="song.mp3"></audio> ``` \#\#\# Controlling if an element will be kept Unpoly will **only** keep an existing element if: - The existing element has an `up-keep` attribute - The response contains an element matching the CSS selector of the existing element - The matching element *also* has an `up-keep` attribute - The [`up:fragment:keep`](/up:fragment:keep) event that is [emitted](/up.emit) on the existing element is not prevented by a event listener. Let's say we want only keep an `<audio>` element as long as it plays the same song (as identified by the tag's `src` attribute). On the client we can achieve this by listening to an `up:keep:fragment` event and preventing it if the `src` attribute of the old and new element differ: up.compiler('audio', function(element) { element.addEventListener('up:fragment:keep', function(event) { if element.getAttribute('src') !== event.newElement.getAttribute('src') { event.preventDefault() } }) }) If we don't want to solve this on the client, we can achieve the same effect on the server. By setting the value of the `up-keep` attribute we can define the CSS selector used for matching elements. <audio up-keep="audio[src='song.mp3']" src="song.mp3"></audio> Now, if a response no longer contains an `<audio src="song.mp3">` tag, the existing element will be destroyed and replaced by a fragment from the response. @selector [up-keep] @param up-on-keep Code to run before an existing element is kept during a page update. The code may use the variables `event` (see `up:fragment:keep`), `this` (the old fragment), `newFragment` and `newData`. @stable ### ###** This event is [emitted](/up.emit) before an existing element is [kept](/up-keep) during a page update. Event listeners can call `event.preventDefault()` on an `up:fragment:keep` event to prevent the element from being persisted. If the event is prevented, the element will be replaced by a fragment from the response. @event up:fragment:keep @param event.preventDefault() Event listeners may call this method to prevent the element from being preserved. @param {Element} event.target The fragment that will be kept. @param {Element} event.newFragment The discarded element. @param {Object} event.newData The value of the [`up-data`](/up-data) attribute of the discarded element, parsed as a JSON object. @stable ### ###** This event is [emitted](/up.emit) when an existing element has been [kept](/up-keep) during a page update. Event listeners can inspect the discarded update through `event.newElement` and `event.newData` and then modify the preserved element when necessary. @event up:fragment:kept @param {Element} event.target The fragment that has been kept. @param {Element} event.newFragment The discarded fragment. @param {Object} event.newData The value of the [`up-data`](/up-data) attribute of the discarded fragment, parsed as a JSON object. @stable ### ###** Compiles a page fragment that has been inserted into the DOM by external code. **As long as you manipulate the DOM using Unpoly, you will never need to call this method.** You only need to use `up.hello()` if the DOM is manipulated without Unpoly' involvement, e.g. by setting the `innerHTML` property or calling jQuery methods like `html`, `insertAfter` or `appendTo`: ```html element = document.createElement('div') element.innerHTML = '... HTML that needs to be activated ...' up.hello(element) ``` This function emits the [`up:fragment:inserted`](/up:fragment:inserted) event. @function up.hello @param {Element|jQuery} target @param {Element|jQuery} [options.origin] @return {Element} The compiled element @stable ### hello = (element, options = {}) -> # If passed a selector, up.fragment.get() will prefer a match on the current layer. element = getSmart(element) # Callers may pass descriptions of child elements that were [kept](/up-keep) # as { options.keepPlans }. For these elements up.hello() emits an event # up:fragment:kept instead of up:fragment:inserted. # # We will also pass an array of kept child elements to up.hello() as { skip } # so they won't be compiled a second time. keepPlans = options.keepPlans || [] skip = keepPlans.map (plan) -> emitFragmentKept(plan) return plan.oldElement up.syntax.compile(element, { skip, layer: options.layer }) emitFragmentInserted(element, options) return element ###** When any page fragment has been [inserted or updated](/up.replace), this event is [emitted](/up.emit) on the fragment. If you're looking to run code when a new fragment matches a selector, use `up.compiler()` instead. \#\#\# Example up.on('up:fragment:inserted', function(event, fragment) { console.log("Looks like we have a new %o!", fragment) }) @event up:fragment:inserted @param {Element} event.target The fragment that has been inserted or updated. @stable ### emitFragmentInserted = (element, options) -> up.emit element, 'up:fragment:inserted', log: ['Inserted fragment %o', element] origin: options.origin emitFragmentKeep = (keepPlan) -> log = ['Keeping fragment %o', keepPlan.oldElement] callback = e.callbackAttr(keepPlan.oldElement, 'up-on-keep', ['newFragment', 'newData']) emitFromKeepPlan(keepPlan, 'up:fragment:keep', { log, callback }) emitFragmentKept = (keepPlan) -> log = ['Kept fragment %o', keepPlan.oldElement] emitFromKeepPlan(keepPlan, 'up:fragment:kept', { log }) emitFromKeepPlan = (keepPlan, eventType, emitDetails) -> keepable = keepPlan.oldElement event = up.event.build(eventType, newFragment: keepPlan.newElement newData: keepPlan.newData ) up.emit(keepable, event, emitDetails) emitFragmentDestroyed = (fragment, options) -> log = options.log ? ['Destroyed fragment %o', fragment] parent = options.parent || document up.emit(parent, 'up:fragment:destroyed', { fragment, parent, log }) isDestroying = (element) -> !!e.closest(element, '.up-destroying') isNotDestroying = (element) -> !isDestroying(element) ###** Returns the first fragment matching the given selector. This function differs from `document.querySelector()` and `up.element.get()`: - This function only selects elements in the [current layer](/up.layer.current). Pass a `{ layer }`option to match elements in other layers. - This function ignores elements that are being [destroyed](/up.destroy) or that are being removed by a [transition](/up.morph). - This function prefers to match elements in the vicinity of a given `{ origin }` element (optional). - This function supports non-standard CSS selectors like `:main` and `:has()`. If no element matches these conditions, `undefined` is returned. \#\#\# Example: Matching a selector in a layer To select the first element with the selector `.foo` on the [current layer](/up.layer.current): let foo = up.fragment.get('.foo') You may also pass a `{ layer }` option to match elements within another layer: let foo = up.fragment.get('.foo', { layer: 'any' }) \#\#\# Example: Matching the descendant of an element To only select in the descendants of an element, pass a root element as the first argument: let container = up.fragment.get('.container') let fooInContainer = up.fragment.get(container, '.foo') \#\#\# Example: Matching around an origin element When processing a user interaction, it is often helpful to match elements around the link that's being clicked or the form field that's being changed. In this case you may pass the triggering element as `{ origin }` element. Assume the following HTML: ```html <div class="element"></div> <div class="element"> <a href="..."></a> </div> ``` When processing an event for the `<a href"...">` you can pass the link element as `{ origin }` to match the closest element in the link's ancestry: ```javascript let link = event.target up.fragment.get('.element') // returns the first .element up.fragment.get('.element', { origin: link }) // returns the second .element ``` When the link's does not have an ancestor matching `.element`, Unpoly will search the entire layer for `.element`. \#\#\# Example: Matching an origin sibling When processing a user interaction, it is often helpful to match elements within the same container as the the link that's being clicked or the form field that's being changed. Assume the following HTML: ```html <div class="element" id="one"> <div class="inner"></div> </div> <div class="element" id="two"> <a href="..."></a> <div class="inner"></div> </div> ``` When processing an event for the `<a href"...">` you can pass the link element as `{ origin }` to match within the link's container: ```javascript let link = event.target up.fragment.get('.element .inner') // returns the first .inner up.fragment.get('.element .inner', { origin: link }) // returns the second .inner ``` Note that when the link's `.element` container does not have a child `.inner`, Unpoly will search the entire layer for `.element .inner`. \#\#\# Similar features - The [`.up-destroying`](/up-destroying) class is assigned to elements during their removal animation. - The [`up.element.get()`](/up.element.get) function simply returns the first element matching a selector without filtering by layer or destruction state. @function up.fragment.get @param {Element|jQuery} [root=document] The root element for the search. Only the root's children will be matched. May be omitted to search through all elements in the `document`. @param {string} selector The selector to match. @param {string} [options.layer='current'] The layer in which to select elements. See `up.layer.get()` for a list of supported layer values. If a root element was passed as first argument, this option is ignored and the root element's layer is searched. @param {string|Element|jQuery} [options.origin] An second element or selector that can be referenced as `&` in the first selector. @return {Element|undefined} The first matching element, or `undefined` if no such element matched. @stable ### getSmart = (args...) -> options = u.extractOptions(args) selector = args.pop() root = args[0] if u.isElementish(selector) # up.fragment.get(root: Element, element: Element, [options]) should just return element. # The given root and options are ignored. We also don't check if it's destroying. # We do use e.get() to unwrap a jQuery collection. return e.get(selector) if root # We don't match around { origin } if we're given a root for the search. return getDumb(root, selector, options) # If we don't have a root element we will use a context-sensitive lookup strategy # that tries to match elements in the vicinity of { origin } before going through # the entire layer. finder = new up.FragmentFinder( selector: selector origin: options.origin layer: options.layer ) return finder.find() getDumb = (args...) -> return getAll(args...)[0] CSS_HAS_SUFFIX_PATTERN = /\:has\(([^\)]+)\)$/ ###** Returns all elements matching the given selector, but ignores elements that are being [destroyed](/up.destroy) or that are being removed by a [transition](/up.morph). By default this function only selects elements in the [current layer](/up.layer.current). Pass a `{ layer }`option to match elements in other layers. See `up.layer.get()` for a list of supported layer values. Returns an empty list if no element matches these conditions. \#\#\# Example To select all elements with the selector `.foo` on the [current layer](/up.layer.current): let foos = up.fragment.all('.foo') You may also pass a `{ layer }` option to match elements within another layer: let foos = up.fragment.all('.foo', { layer: 'any' }) To select in the descendants of an element, pass a root element as the first argument: var container = up.fragment.get('.container') var foosInContainer = up.fragment.all(container, '.foo') \#\#\# Similar features - The [`.up-destroying`](/up-destroying) class is assigned to elements during their removal animation. - The [`up.element.all()`](/up.element.get) function simply returns the all elements matching a selector without further filtering. @function up.fragment.all @param {Element|jQuery} [root=document] The root element for the search. Only the root's children will be matched. May be omitted to search through all elements in the given [layer](#options.layer). @param {string} selector The selector to match. @param {string} [options.layer='current'] The layer in which to select elements. See `up.layer.get()` for a list of supported layer values. If a root element was passed as first argument, this option is ignored and the root element's layer is searched. @param {string|Element|jQuery} [options.origin] An second element or selector that can be referenced as `&` in the first selector: var input = document.querySelector('input.email') up.fragment.get('fieldset:has(&)', { origin: input }) // returns the <fieldset> containing input @return {Element|undefined} The first matching element, or `undefined` if no such element matched. @stable ### getAll = (args...) -> options = u.extractOptions(args) selector = args.pop() root = args[0] # (1) up.fragment.all(rootElement, selector) should find selector within # the descendants of rootElement. # (2) up.fragment.all(selector) should find selector within the current layer. # (3) up.fragment.all(selector, { layer }) should find selector within the given layer(s). selector = parseSelector(selector, root, options) return selector.descendants(root || document) ###** Your target selectors may use this pseudo-selector to replace an element with an descendant matching the given selector. \#\#\# Example `up.render('div:has(span)', { url: '...' })` replaces the first `<div>` elements with at least one `<span>` among its descendants: ```html <div> <span>Will be replaced</span> </div> <div> Will NOT be replaced </div> ``` \#\#\# Compatibility `:has()` is supported by target selectors like `a[up-target]` and `up.render({ target })`. As a [level 4 CSS selector](https://drafts.csswg.org/selectors-4/#relational), `:has()` [has yet to be implemented](https://caniuse.com/#feat=css-has) in native browser functions like [`document.querySelectorAll()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelectorAll). You can also use [`:has()` in jQuery](https://api.jquery.com/has-selector/). @selector :has() @stable ### ###** Returns a list of the given parent's descendants matching the given selector. The list will also include the parent element if it matches the selector itself. @function up.fragment.subtree @param {Element} parent The parent element for the search. @param {string} selector The CSS selector to match. @param {up.Layer|string|Element} [options.layer] @return {NodeList<Element>|Array<Element>} A list of all matching elements. @experimental ### getSubtree = (element, selector, options = {}) -> selector = parseSelector(selector, element, options) return selector.subtree(element) contains = (element, selector) -> getSubtree(element, selector).length > 0 ###** Returns the first element that matches the selector by testing the element itself and traversing up through ancestors in element's layers. `up.fragment.closest()` will only match elements in the same [layer](/up.layer) as the given element. To match ancestors regardless of layers, use `up.element.closest()`. @function up.fragment.closest @param {Element} element The element on which to start the search. @param {string} selector The CSS selector to match. @return {Element|null|undefined} element The matching element. Returns `null` or `undefined` if no element matches in the same layer. @experimental ### closest = (element, selector, options) -> element = e.get(element) selector = parseSelector(selector, element, options) return selector.closest(element) ###** Destroys the given element or selector. All [`up.compiler()`](/up.compiler) destructors, if any, are called. The element is then removed from the DOM. Emits events [`up:fragment:destroyed`](/up:fragment:destroyed). \#\#\# Animating the removal You may animate the element's removal by passing an option like `{ animate: 'fade-out' }`. Unpoly ships with a number of [predefined animations](/up.animate#named-animations) and you may so define [custom animations](/up.animation). If the element's removal is animated, the element will remain in the DOM until after the animation has completed. While the animation is running the element will be given the `.up-destroying` class. The element will also be given the `[aria-hidden]` attribute to remove it from the accessibility tree. Elements that are about to be destroyed (but still animating) are ignored by all functions for fragment lookup: - `up.fragment.all()` - `up.fragment.get()` - `up.fragment.closest()` @function up.destroy @param {string|Element|jQuery} target @param {string|Function(element, options): Promise} [options.animation='none'] The animation to use before the element is removed from the DOM. @param {number} [options.duration] The duration of the animation. See [`up.animate()`](/up.animate). @param {string} [options.easing] The timing function that controls the animation's acceleration. See [`up.animate()`](/up.animate). @param {Function} [options.onFinished] A callback that is run when any animations are finished and the element was removed from the DOM. @return undefined @stable ### destroy = (args...) -> options = parseTargetAndOptions(args) if options.element = getSmart(options.target, options) new up.Change.DestroyFragment(options).execute() return up.migrate.formerlyAsync?('up.destroy()') parseTargetAndOptions = (args) -> options = u.parseArgIntoOptions(args, 'target') if u.isElement(options.target) options.origin ||= options.target options ###** Elements are assigned the `.up-destroying` class before they are [destroyed](/up.destroy) or while they are being removed by a [transition](/up.morph). If the removal is [animated](/up.destroy#animating-the-removal), the class is assigned before the animation starts. Elements that are about to be destroyed (but still animating) are ignored by all functions for fragment lookup: - `up.fragment.all()` - `up.fragment.get()` - `up.fragment.closest()` @selector .up-destroying @stable ### markFragmentAsDestroying = (element) -> element.classList.add('up-destroying') element.setAttribute('aria-hidden', 'true') ###** This event is [emitted](/up.emit) after a page fragment was [destroyed](/up.destroy) and removed from the DOM. If the destruction is animated, this event is emitted after the animation has ended. The event is emitted on the parent element of the fragment that was removed. @event up:fragment:destroyed @param {Element} event.fragment The detached element that has been removed from the DOM. @param {Element} event.parent The former parent element of the fragment that has now been detached from the DOM. @param {Element} event.target The former parent element of the fragment that has now been detached from the DOM. @stable ### ###** Replaces the given element with a fresh copy fetched from the server. By default, reloading is not considered a [user navigation](/navigation) and e.g. will not update the browser location. You may change this with `{ navigate: true }`. \#\#\# Example up.on('new-mail', function() { up.reload('.inbox') }) \#\#\# Controlling the URL that is reloaded Unpoly remembers [the URL from which a fragment was loaded](/up.fragment.source), so you don't usually need to pass a URL when reloading. To reload from another URL, pass a `{ url }` option or set an `[up-source]` attribute on the element or its ancestors. \#\#\# Skipping updates when nothing changed You may use the `[up-time]` attribute to avoid rendering unchanged HTML when reloading a fragment. See `[up-time]` for a detailed example. @function up.reload @param {string|Element|jQuery} [target] The element that should be reloaded. If omitted, an element matching a selector in `up.fragment.config.mainTargets` will be reloaded. @param {Object} [options] See options for `up.render()`. @param {string} [options.url] The URL from which to reload the fragment. This defaults to the URL from which the fragment was originally loaded. @param {string} [options.navigate=false] Whether the reloading constitutes a [user navigation](/navigation). @stable ### reload = (args...) -> options = parseTargetAndOptions(args) options.target ||= ':main' element = getSmart(options.target, options) options.url ?= sourceOf(element) options.headers ||= {} options.headers[up.protocol.headerize('reloadFromTime')] = timeOf(element) return render(options) ###** Fetches this given URL with JavaScript and [replaces](/up.replace) the [current layer](/up.layer.current)'s [main element](/up.fragment.config#config.mainSelectors) with a matching fragment from the server response. \#\#\# Example This would replace the current page with the response for `/users`: up.visit('/users') @function up.visit @param {string} url The URL to visit. @param {Object} [options] See options for `up.render()`. @param {up.Layer|string|number} [options.layer='current'] @stable ### visit = (url, options) -> navigate(u.merge({ url }, options)) successKey = (key) -> return u.unprefixCamelCase(key, 'fail') failKey = (key) -> unless key.match(/^fail[A-Z]/) return u.prefixCamelCase(key, 'fail') ###** Returns a CSS selector that matches the given element as good as possible. To build the selector, the following element properties are used in decreasing order of priority: - The element's `[up-id]` attribute - The element's `[id]` attribute - The element's `[name]` attribute - The element's `[class]` names, ignoring `up.fragment.config.badTargetClasses`. - The element's tag name \#\#\# Example ```js element = up.element.createFromHTML('<span class="klass">...</span>') selector = up.fragment.toTarget(element) // returns '.klass' ``` @function up.fragment.toTarget @param {string|Element|jQuery} The element for which to create a selector. @stable ### toTarget = (element) -> if u.isString(element) return element # In case we're called called with a jQuery collection element = e.get(element) if e.isSingleton(element) return e.elementTagName(element) else if upId = element.getAttribute("up-id") return e.attributeSelector('up-id', upId) else if id = element.getAttribute("id") return e.idSelector(id) else if name = element.getAttribute("name") return e.elementTagName(element) + e.attributeSelector('name', name) else if goodClasses = u.presence(u.filter(element.classList, isGoodClassForTarget)) selector = '' for klass in goodClasses selector += e.classSelector(klass) return selector else return e.elementTagName(element) ###** Sets an unique identifier for this element. This identifier is used by `up.fragment.toSelector()` to create a CSS selector that matches this element precisely. If the element already has other attributes that make a good identifier, like a good `[id]` or `[class]` attribute, it is not necessary to also set `[up-id]`. \#\#\# Example Take this element: <a href="/">Homepage</a> Unpoly cannot generate a good CSS selector for this element: up.fragment.toTarget(element) // returns 'a' We can improve this by assigning an `[up-id]`: <a href="/" up-id="link-to-home">Open user 4</a> The attribute value is used to create a better selector: up.fragment.toTarget(element) // returns '[up-id="link-to-home"]' @selector [up-id] @param up-id A string that uniquely identifies this element. @stable ### isGoodClassForTarget = (klass) -> matchesPattern = (pattern) -> if u.isRegExp(pattern) pattern.test(klass) else pattern == klass return !u.some(config.badTargetClasses, matchesPattern) resolveOriginReference = (target, options = {}) -> origin = options.origin return target.replace /&|:origin\b/, (match) -> if origin return toTarget(origin) else up.fail('Missing { origin } element to resolve "%s" reference (found in %s)', match, target) ###** @internal ### expandTargets = (targets, options = {}) -> layer = options.layer unless layer == 'new' || (layer instanceof up.Layer) up.fail('Must pass an up.Layer as { layer } option, but got %o', layer) # Copy the list since targets might be a jQuery collection, and this does not support shift or push. targets = u.copy(u.wrapList(targets)) expanded = [] while targets.length target = targets.shift() if target == ':main' || target == true mode = if layer == 'new' then options.mode else layer.mode targets.unshift(up.layer.mainTargets(mode)...) else if target == ':layer' # Discard this target for new layers, which don't have a first-swappable-element. # Also don't && the layer check into the `else if` condition above, or it will # be returned as a verbatim string below. unless layer == 'new' || layer.opening targets.unshift layer.getFirstSwappableElement() else if u.isElementish(target) expanded.push toTarget(target) else if u.isString(target) expanded.push resolveOriginReference(target, options) else # @buildPlans() might call us with { target: false } or { target: nil } # In that case we don't add a plan. return u.uniq(expanded) parseSelector = (selector, element, options = {}) -> filters = [] unless options.destroying filters.push(isNotDestroying) # Some up.fragment function center around an element, like closest() or matches(). options.layer ||= element layers = up.layer.getAll(options) if options.layer != 'any' && !(element && e.isDetached(element)) filters.push (match) -> u.some layers, (layer) -> layer.contains(match) expandedTargets = up.fragment.expandTargets(selector, u.merge(options, layer: layers[0])) expandedTargets = expandedTargets.map (target) -> target = target.replace CSS_HAS_SUFFIX_PATTERN, (match, descendantSelector) -> filters.push (element) -> element.querySelector(descendantSelector) return '' return target || '*' return new up.Selector(expandedTargets, filters) hasAutoHistory = (fragment) -> if contains(fragment, config.autoHistoryTargets) true else up.puts('up.render()', "Will not auto-update history because fragment doesn't contain a selector from up.fragment.config.autoHistoryTargets") false ###** A pseudo-selector that matches the layer's main target. Main targets are default render targets. When no other render target is given, Unpoly will try to find and replace a main target. In most app layouts the main target should match the primary content area. The default main targets are: - any element with an `[up-main]` attribute - the HTML5 [`<main>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/main) element - the current layer's [topmost swappable element](/layer) You may configure main target selectors in `up.fragment.config.mainTargets`. \#\#\# Example ```js up.render(':main', { url: '/page2' }) ``` @selector :main @experimental ### ###** Updates this element when no other render target is given. \#\#\# Example Many links simply replace the main content element in your application layout. Unpoly lets you mark this elements as a default target using the `[up-main]` attribute: ```html <body> <div class="layout"> <div class="layout--side"> ... </div> <div class="layout--content" up-main> ... </div> </div> </body> ``` Once a main target is configured, you no longer need `[up-target]` in a link.\ Use `[up-follow]` and the `[up-main]` element will be replaced: ```html <a href="/foo" up-follow>...</a> ``` If you want to update something more specific, you can still use `[up-target]`: ```html <a href="/foo" up-target=".profile">...</a> ``` Instead of assigning `[up-main]` you may also configure an existing selector in `up.fragment.config.mainTargets`: ```js up.fragment.config.mainTargets.push('.layout--content') ``` Overlays can use different main targets --------------------------------------- Overlays often use a different default selector, e.g. to exclude a navigation bar. To define a different main target for an overlay, set the [layer mode](/layer-terminology) as the value of the `[up-main]` attribute: ```html <body> <div class="layout" up-main="root"> <div class="layout--side"> ... </div> <div class="layout--content" up-main="modal"> ... </div> </div> </body> ``` Instead of assigning `[up-main]` you may also configure layer-specific targets in `up.layer.config`: ```js up.layer.config.popup.mainTargets.push('.menu') // for popup overlays up.layer.config.drawer.mainTargets.push('.menu') // for drawer overlays up.layer.config.overlay.mainTargets.push('.layout--content') // for all overlay modes ``` @selector [up-main] @param [up-main] A space-separated list of [layer modes](/layer-terminology) for which to use this main target. Omit the attribute value to define a main target for *all* layer modes. To use a different main target for all overlays (but not the root layer), set `[up-main=overlay]`. @stable ### ###** To make a server request without changing a fragment, use the `:none` selector. \#\#\# Example ```html <a href="/ping" up-target=":none">Ping server</a> ``` @selector :none @experimental ### ###** Your target selectors may use this pseudo-selector to reference the element that triggered the change. The origin element is automatically set to a link that is being [followed](/a-up-follow) or form that is being [submitted](/form-up-submit). When updating fragments programmatically through `up.render()` you may pass an origin element as an `{ origin }` option. Even without using an `:origin` reference, the [origin is considered](/fragment-placement#interaction-origin-is-considered) when matching fragments in the current page. \#\#\# Shorthand Instead of `:origin` you may also use the ampersand character (`&`). You may be familiar with the ampersand from the [Sass](https://sass-lang.com/documentation/file.SASS_REFERENCE.html#parent-selector) CSS preprocessor. @selector :origin @experimental ### ###** Your target selectors may use this pseudo-selector to replace the layer's topmost swappable element. The topmost swappable element is the first child of the layer's container element. For the [root layer](/up.layer.root) it is the `<body>` element. For an overlay it is the target with which the overlay was opened with. In canonical usage the topmost swappable element is often a [main element](/up-main). \#\#\# Example The following will replace the `<body>` element in the root layer, and the topmost swappable element in an overlay: ```js up.render(':layer', { url: '/page2' }) ``` @selector :layer @experimental ### ###** Returns whether the given element matches the given CSS selector. Other than `up.element.matches()` this function supports non-standard selectors like `:main` or `:layer`. @function up.fragment.matches @param {Element} fragment @param {string|Array<string>} selectorOrSelectors @param {string|up.Layer} options.layer The layer for which to match. Pseudo-selectors like `:main` may expand to different selectors in different layers. @param {string|up.Layer} options.mode Required if `{ layer: 'new' }` is passed. @return {boolean} @experimental ### matches = (element, selector, options = {}) -> element = e.get(element) selector = parseSelector(selector, element, options) return selector.matches(element) up.on 'up:app:boot', -> body = document.body body.setAttribute('up-source', up.history.location) hello(body) unless up.browser.canPushState() up.warn('Cannot push history changes. Next fragment update will load in a new page.') up.on 'up:framework:reset', reset u.literal config: config reload: reload destroy: destroy render: render navigate: navigate get: getSmart getDumb: getDumb all: getAll subtree: getSubtree contains: contains closest: closest source: sourceOf hello: hello visit: visit markAsDestroying: markFragmentAsDestroying emitInserted: emitFragmentInserted emitDestroyed: emitFragmentDestroyed emitKeep: emitFragmentKeep emitKept: emitFragmentKept successKey: successKey, failKey: failKey expandTargets: expandTargets toTarget: toTarget matches: matches hasAutoHistory: hasAutoHistory up.replace = up.fragment.replace up.extract = up.fragment.extract up.reload = up.fragment.reload up.destroy = up.fragment.destroy up.render = up.fragment.render up.navigate = up.fragment.navigate up.hello = up.fragment.hello up.visit = up.fragment.visit ###** Returns the current [context](/context). This is aliased as `up.layer.context`. @property up.context @param {Object} context The context object. If no context has been set an empty object is returned. @experimental ### u.delegate up, 'context', -> up.layer.current
179055
u = up.util e = up.element ###** Fragment API =========== The `up.fragment` module offers a high-level JavaScript API to work with DOM elements. A fragment is an element with some additional properties that are useful in the context of a server-rendered web application: - Fragments are [identified by a CSS selector](/up.fragment.toTarget), like a `.class` or `#id`. - Fragments are usually updated by a [link](/a-up-follow) for [form](/form-up-submits) that targets their selector. When the server renders HTML with a matching element, the fragment is swapped with a new version. - As fragments enter the page they are automatically [compiled](/up.compiler) to activate JavaScript behavior. - Fragment changes may be [animated](/up.motion). - Fragments are placed on a [layer](/up.layer) that is isolated from other layers. Unpoly features will only see or change fragments from the [current layer](/up.layer.current) unless you [explicitly target another layer](/layer-option). - Fragments [know the URL from where they were loaded](/up.source). They can be [reloaded](/up.reload) or [polled periodically](/up-polled). For low-level DOM utilities that complement the browser's native API, see `up.element`. @see up.render @see up.navigate @see up.destroy @see up.reload @see up.fragment.get @see up.hello @module up.fragment ### up.fragment = do -> ###** Configures defaults for fragment updates. @property up.fragment.config @param {Array<string>} [config.mainTargets=['[up-main]', 'main', ':layer']] An array of CSS selectors matching default render targets. When no other render target is given, Unpoly will try to find and replace a main target. When [navigating](/navigation) to a main target, Unpoly will automatically [reset scroll positions](/scroll-option) and [update the browser history](/up.render#options.history). This property is aliased as [`up.layer.config.any.mainTargets`](up.layer.config#config.any.mainTargets). @param {Array<string|RegExp>} [config.badTargetClasses] An array of class names that should be ignored when [deriving a target selector from a fragment](/up.fragment.toTarget). The class names may also be passed as a regular expression. @param {Object} [config.navigateOptions] An object of default options to apply when [navigating](/navigation). @param {boolean} [config.matchAroundOrigin] Whether to match an existing fragment around the triggered link. If set to `false` Unpoly will replace the first fragment matching the given target selector in the link's [layer](/up.layer). @param {Array<string>} [config.autoHistoryTargets] When an updated fragments contain an element matching one of the given CSS selectors, history will be updated with `{ history: 'auto' }`. By default Unpoly will auto-update history when updating a [main target](#config.mainTargets). @param {boolean|string|Function(Element)} [config.autoScroll] How to scroll after updating a fragment with `{ scroll: 'auto' }`. See [scroll option](/scroll-option) for a list of allowed values. The default configuration tries, in this order: - If the URL has a `#hash`, scroll to the hash. - If updating a [main target](/up-main), reset scroll positions. @param {boolean|string|Function(Element)} [config.autoFocus] How to focus when updating a fragment with `{ focus: 'auto' }`. See [focus option](/focus-option) for a list of allowed values. The default configuration tries, in this order: - Focus a `#hash` in the URL. - Focus an `[autofocus]` element in the new fragment. - If focus was lost with the old fragment, focus the new fragment. - If updating a [main target](/up-main), focus the new fragment. @param {boolean} [config.runScripts=false] Whether to execute `<script>` tags in updated fragments. Scripts will load asynchronously, with no guarantee of execution order. If you set this to `true`, mind that the `<body>` element is a default [main target](/up-main). If you are including your global application scripts at the end of your `<body>` for performance reasons, swapping the `<body>` will re-execute these scripts. In that case you must configure a different main target that does not include your application scripts. @stable ### config = new up.Config -> badTargetClasses: [/^up-/] # These defaults will be set to both success and fail options # if { navigate: true } is given. navigateOptions: { focus: 'auto' scroll: 'auto' solo: true # preflight feedback: true # preflight fallback: true history: 'auto' peel: true cache: 'auto' } matchAroundOrigin: true runScripts: false autoHistoryTargets: [':main'] autoFocus: ['hash', 'autofocus', 'main-if-main', 'target-if-lost'] autoScroll: ['hash', 'layer-if-main'] # Users who are not using layers will prefer settings default targets # as up.fragment.config.mainTargets instead of up.layer.config.any.mainTargets. u.delegate config, 'mainTargets', -> up.layer.config.any reset = -> config.reset() ###** Returns the URL the given element was retrieved from. If the given element was never directly updated, but part of a larger fragment update, the closest known source of an ancestor element is returned. \#\#\# Example In the HTML below, the element `#one` was loaded from the URL `/foo`: ```html <div id="one" up-source"/foo"> <div id="two">...</div> </div> ``` We can now ask for the source of an element: ```javascript up.fragment.source('#two') // returns '/foo' ``` @function up.fragment.source @param {Element|string} element The element or CSS selector for which to look up the source URL. @return {string|undefined} @stable ### sourceOf = (element, options = {}) -> element = getSmart(element, options) return e.closestAttr(element, 'up-source') ###** Returns a timestamp for the last modification of the content in the given element. @function up.fragment.time @param {Element} element @return {string} @internal ### timeOf = (element) -> return e.closestAttr(element, 'up-time') || '0' ###** Sets the time when the fragment's underlying data was last changed. This can be used to avoid rendering unchanged HTML when [reloading](/up.reload) a fragment. This saves <b>CPU time</b> and reduces the <b>bandwidth cost</b> for a request/response exchange to **~1 KB**. \#\# Example Let's say we display a list of recent messages. We use the `[up-poll]` attribute to reload the `.messages` fragment every 30 seconds: ```html <div class="messages" up-poll> ... </div> ``` The list is now always up to date. But most of the time there will not be new messages, and we waste resources sending the same unchanged HTML from the server. We can improve this by setting an `[up-time]` attribute and the message list. The attribute value is the time of the most recent message. The time is encoded as the number of seconds since [Unix epoch](https://en.wikipedia.org/wiki/Unix_time). When, for instance, the last message in a list was received from December 24th, 1:51:46 PM UTC, we use the following HTML: ```html <div class="messages" up-time="1608730818" up-poll> ... </div> ``` When reloading Unpoly will echo the `[up-time]` timestamp in an `X-Up-Reload-From-Time` header: ```http X-Up-Reload-From-Time: 1608730818 ``` The server can compare the time from the request with the time of the last data update. If no more recent data is available, the server can render nothing and respond with an [`X-Up-Target: :none`](/X-Up-Target) header. Here is an example with [unpoly-rails](https://unpoly.com/install/rails): ```ruby class MessagesController < ApplicationController def index if up.reload_from_time == current_user.last_message_at up.render_nothing else @messages = current_user.messages.order(time: :desc).to_a render 'index' end end end ``` @selector [up-time] @param {string} up-time The number of seconds between the [Unix epoch](https://en.wikipedia.org/wiki/Unix_time). and the time when the element's underlying data was last changed. @experimental ### ###** Sets this element's source URL for [reloading](/up.reload) and [polling](/up-poll) When an element is reloaded, Unpoly will make a request from the URL that originally brought the element into the DOM. You may use `[up-source]` to use another URL instead. \#\#\# Example Assume an application layout with an unread message counter. You use `[up-poll]` to refresh the counter every 30 seconds. By default this would make a request to the URL that originally brought the counter element into the DOM. To save the server from rendering a lot of unused HTML, you may poll from a different URL like so: <div class="unread-count" up-poll up-source="/unread-count"> 2 new messages </div> @selector [up-source] @param {string} up-source The URL from which to reload this element. @stable ### ###** Replaces elements on the current page with matching elements from a server response or HTML string. The current and new elements must both match the same CSS selector. The selector is either given as `{ target }` option, or a [main target](/up-main) is used as default. See the [fragment placement](/fragment-placement) selector for many examples for how you can target content. This function has many options to enable scrolling, focus, request cancelation and other side effects. These options are all disabled by default and must be opted into one-by-one. To enable defaults that a user would expects for navigation (like clicking a link), pass [`{ navigate: true }`](#options.navigate) or use `up.navigate()` instead. \#\#\# Passing the new fragment The new fragment content can be passed as one of the following options: - [`{ url }`](#options.url) fetches and renders content from the server - [`{ document }`](#options.document) renders content from a given HTML document string or partial document - [`{ fragment }`](#options.fragment) renders content from a given HTML string that only contains the new fragment - [`{ content }`](#options-content) replaces the targeted fragment's inner HTML with the given HTML string \#\#\# Example Let's say your current HTML looks like this: ```html <div class="one">old one</div> <div class="two">old two</div> ``` We now replace the second `<div>` by targeting its CSS class: ```js up.render({ target: '.two', url: '/new' }) ``` The server renders a response for `/new`: ```html <div class="one">new one</div> <div class="two">new two</div> ``` Unpoly looks for the selector `.two` in the response and [implants](/up.extract) it into the current page. The current page now looks like this: ```html <div class="one">old one</div> <div class="two">new two</div> ``` Note how only `.two` has changed. The update for `.one` was discarded, since it didn't match the selector. \#\#\# Events Unpoly will emit events at various stages of the rendering process: - `up:fragment:destroyed` - `up:fragment:loaded` - `up:fragment:inserted` @function up.render @param {string|Element|jQuery|Array<string>} [target] The CSS selector to update. If omitted a [main target](/up-main) will be rendered. You may also pass a DOM element or jQuery element here, in which case a selector will be [inferred from the element attributes](/up.fragment.toTarget). The given element will also be used as [`{ origin }`](#options.origin) for the fragment update. You may also pass an array of selector alternatives. The first selector matching in both old and new content will be used. Instead of passing the target as the first argument, you may also pass it as a [´{ target }`](#options.target) option.. @param {string|Element|jQuery|Array<string>} [options.target] The CSS selector to update. See documentation for the [`target`](#target) parameter. @param {string|boolean} [options.fallback=false] Specifies behavior if the [target selector](/up.render#options.target) is missing from the current page or the server response. If set to a CSS selector string, Unpoly will attempt to replace that selector instead. If set to `true` Unpoly will attempt to replace a [main target](/up-main) instead. If set to `false` Unpoly will immediately reject the render promise. @param {boolean} [options.navigate=false] Whether this fragment update is considered [navigation](/navigation). @param {string} [options.url] The URL to fetch from the server. Instead of making a server request, you may also pass an existing HTML string as [`{ document }`](#options.document), [`{ fragment }`](#options.fragment) or [`{ content }`](#options.content) option. @param {string} [options.method='get'] The HTTP method to use for the request. Common values are `'get'`, `'post'`, `'put'`, `'patch'` and `'delete`'. The value is case insensitive. @param {Object|FormData|string|Array} [options.params] Additional [parameters](/up.Params) that should be sent as the request's [query string](https://en.wikipedia.org/wiki/Query_string) or payload. When making a `GET` request to a URL with a query string, the given `{ params }` will be added to the query parameters. @param {Object} [options.headers={}] An object with additional request headers. Note that Unpoly will by default send a number of custom request headers. E.g. the `X-Up-Target` header includes the targeted CSS selector. See `up.protocol` and `up.network.config.metaKeys` for details. @param {string|Element} [options.fragment] A string of HTML comprising *only* the new fragment. The `{ target }` selector will be derived from the root element in the given HTML: ```js // This will update .foo up.render({ fragment: '<div class=".foo">inner</div>' }) ``` If your HTML string contains other fragments that will not be rendered, use the [`{ document }`](#options.document) option instead. If your HTML string comprises only the new fragment's [inner HTML](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML), consider the [`{ content }`](#options.content) option. @param {string|Element|Document} [options.document] A string of HTML containing the new fragment. The string may contain other HTML, but only the element matching the `{ target }` selector will be extracted and placed into the page. Other elements will be discarded. If your HTML string comprises only the new fragment, consider the [`{ fragment }`](#options.fragment) option instead. With `{ fragment }` you don't need to pass a `{ target }`, since Unpoly can derive it from the root element in the given HTML. If your HTML string comprises only the new fragment's [inner HTML](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML), consider the [`{ content }`](#options.content) option. @param {string} [options.fail='auto'] How to render a server response with an error code. Any HTTP status code other than 2xx is considered an error code. See [handling server errors](/server-errors) for details. @param {boolean|string} [options.history] Whether the browser URL and window title will be updated. If set to `true`, the history will always be updated, using the title and URL from the server response, or from given `{ title }` and `{ location }` options. If set to `'auto'` history will be updated if the `{ target }` matches a selector in `up.fragment.config.autoHistoryTargets`. By default this contains all [main targets](/up-main). If set to `false`, the history will remain unchanged. [Overlays](/up.layer) will only change the browser URL and window title if the overlay has [visible history](/up.layer.historyVisible), even when `{ history: true }` is passed. @param {string} [options.title] An explicit document title to use after rendering. By default the title is extracted from the response's `<title>` tag. You may also pass `{ title: false }` to explicitly prevent the title from being updated. Note that the browser's window title will only be updated it you also pass a [`{ history }`](#options.history) option. @param {string} [options.location] An explicit URL to use after rendering. By default Unpoly will use the `{ url }` or the final URL after the server redirected. You may also pass `{ location: false }` to explicitly prevent the URL from being updated. Note that the browser's URL will only be updated it you also pass a [`{ history }`](#options.history) option. @param {string} [options.transition] The name of an [transition](/up.motion) to morph between the old and few fragment. If you are [prepending or appending content](/fragment-placement#appending-or-prepending-content), use the `{ animation }` option instead. @param {string} [options.animation] The name of an [animation](/up.motion) to reveal a new fragment when [prepending or appending content](/fragment-placement#appending-or-prepending-content). If you are replacing content (the default), use the `{ transition }` option instead. @param {number} [options.duration] The duration of the transition or animation (in millisconds). @param {string} [options.easing] The timing function that accelerates the transition or animation. See [W3C documentation](http://www.w3.org/TR/css3-transitions/#transition-timing-function) for a list of available timing functions. @param {boolean} [options.cache] Whether to read from and write to the [cache](/up.cache). With `{ cache: true }` Unpoly will try to re-use a cached response before connecting to the network. If no cached response exists, Unpoly will make a request and cache the server response. Also see [`up.request({ cache })`](/up.request#options.cache). @param {boolean|string} [options.clearCache] Whether existing [cache](/up.cache) entries will be [cleared](/up.cache.clear) with this request. You may also pass a [URL pattern](/url-patterns) to only clear matching requests. By default a non-GET request will clear the entire cache. Also see [`up.request({ clearCache })`](/up.request#options.clearCache) and `up.network.config.clearCache`. @param {Element|jQuery} [options.origin] The element that triggered the change. When multiple elements in the current page match the `{ target }`, Unpoly will replace an element in the [origin's vicinity](/fragment-placement). The origin's selector will be substituted for `:origin` in a target selector. @param {string|up.Layer|Element} [options.layer='origin current'] The [layer](/up.layer) in which to match and render the fragment. See [layer option](/layer-option) for a list of allowed values. To [open the fragment in a new overlay](/opening-overlays), pass `{ layer: 'new' }`. In this case options for `up.layer.open()` may also be used. @param {boolean} [options.peel] Whether to close overlays obstructing the updated layer when the fragment is updated. This is only relevant when updating a layer that is not the [frontmost layer](/up.layer.front). @param {Object} [options.context] An object that will be merged into the [context](/context) of the current layer once the fragment is rendered. @param {boolean} [options.keep=true] Whether [`[up-keep]`](/up-keep) elements will be preserved in the updated fragment. @param {boolean} [options.hungry=true] Whether [`[up-hungry]`](/up-hungry) elements outside the updated fragment will also be updated. @param {boolean|string|Element|Function} [options.scroll] How to scroll after the new fragment was rendered. See [scroll option](/scroll-option) for a list of allowed values. @param {boolean} [options.saveScroll=true] Whether to save scroll positions before updating the fragment. Saved scroll positions can later be restored with [`{ scroll: 'restore' }`](/scroll-option#restoring-scroll-options). @param {boolean|string|Element|Function} [options.focus] What to focus after the new fragment was rendered. See [focus option](/focus-option) for a list of allowed values. @param {string} [options.confirm] A message the user needs to confirm before fragments are updated. The message will be shown as a [native browser prompt](https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt). If the user does not confirm the render promise will reject and no fragments will be updated. @param {boolean|Element} [options.feedback] Whether to give the [`{ origin }`](#options.origin) element an `.up-active` class while loading and rendering content. May also pass an element which should receive the `.up-active` class. @param {Function(Event)} [options.onLoaded] A callback that will be run when when the server responds with new HTML, but before the HTML is rendered. The callback argument is a preventable `up:fragment:loaded` event. @param {Function()} [options.onFinished] A callback that will be run when all animations have concluded and elements were removed from the DOM tree. @return {Promise<up.RenderResult>} A promise that fulfills when the page has been updated. If the update is animated, the promise will be resolved *before* the existing element was removed from the DOM tree. The old element will be marked with the `.up-destroying` class and removed once the animation finishes. To run code after the old element was removed, pass an `{ onFinished }` callback. The promise will fulfill with an `up.RenderResult` that contains references to the updated fragments and layer. @stable ### render = up.mockable (args...) -> # Convert thrown errors into rejected promises. # Convert non-promise values into a resolved promise. return u.asyncify -> options = parseTargetAndOptions(args) options = up.RenderOptions.preprocess(options) up.browser.assertConfirmed(options) if guardEvent = u.pluckKey(options, 'guardEvent') # Allow guard event handlers to manipulate render options for the default behavior. # # Note that we have removed { guardEvent } from options to not recursively define # guardEvent.renderOptions.guardEvent. This would cause an infinite loop for event # listeners that prevent the default and re-render. guardEvent.renderOptions = options up.event.assertEmitted(guardEvent, { target: options.origin }) up.RenderOptions.assertContentGiven(options) if options.url return renderRemoteContent(options) else return renderLocalContent(options) renderRemoteContent = (options) -> # Rendering a remote URL is an async operation. # We give feedback (.up-active) while the fragment is loading. return up.feedback.aroundForOptions options, -> return new up.Change.FromURL(options).execute() renderLocalContent = (options) -> # When we have a given { url }, the { solo } option is honored by up.request(). # But up.request() is never called when we have local content given as { document }, # { content } or { fragment }. Hence we abort here. up.network.mimicLocalRequest(options) # (1) No need to give feedback as local changes are sync. # (2) Value will be converted to a fulfilled promise by up.util.asyncify() in render(). return new up.Change.FromContent(options).execute() ###** [Navigates](/navigation) to the given URL by updating a major fragment in the current page. `up.navigate()` will mimic a click on a vanilla `<a href>` link to satisfy user expectations regarding scrolling, focus, request cancelation and [many other side effects](/navigation). Instead of calling `up.navigate()` you may also call `up.render({ navigate: true }`) option for the same effect. @function up.navigate @param {string|Element|jQuery} [target] The CSS selector to update. If omitted a [main target](/up-main) will be rendered. You can also pass a DOM element or jQuery element here, in which case a selector will be [inferred from the element attributes](/up.fragment.target). The given element will also be set as the `{ origin }` option. Instead of passing the target as the first argument, you may also pass it as [´{ target }` option](/up.fragment.render#options.target). @param {Object} [options] See options for `up.render()`. @stable ### navigate = up.mockable (args...) -> options = parseTargetAndOptions(args) return render(u.merge(options, navigate: true)) ###** This event is [emitted](/up.emit) when the server responds with the HTML, before the HTML is used to [change a fragment](/up.render). Event listeners may call `event.preventDefault()` on an `up:fragment:loaded` event to prevent any changes to the DOM and browser history. This is useful to detect an entirely different page layout (like a maintenance page or fatal server error) which should be open with a full page load: ```js up.on('up:fragment:loaded', (event) => { let isMaintenancePage = event.response.getHeader('X-Maintenance') if (isMaintenancePage) { // Prevent the fragment update and don't update browser history event.preventDefault() // Make a full page load for the same request. event.request.loadPage() } }) ``` Instead of preventing the update, listeners may also access the `event.renderOptions` object to mutate options to the `up.render()` call that will process the server response. @event up:fragment:loaded @param event.preventDefault() Event listeners may call this method to prevent the fragment change. @param {up.Request} event.request The original request to the server. @param {up.Response} event.response The server response. @param {Object} event.renderOptions Options for the `up.render()` call that will process the server response. @stable ### ###** Elements with an `up-keep` attribute will be persisted during [fragment updates](/up.fragment). The element you're keeping should have an umambiguous class name, ID or `[up-id]` attribute so Unpoly can find its new position within the page update. Emits events [`up:fragment:keep`](/up:fragment:keep) and [`up:fragment:kept`](/up:fragment:kept). \#\#\# Example The following `<audio>` element will be persisted through fragment updates as long as the responses contain an element matching `#player`: ```html <audio id="player" up-keep src="song.mp3"></audio> ``` \#\#\# Controlling if an element will be kept Unpoly will **only** keep an existing element if: - The existing element has an `up-keep` attribute - The response contains an element matching the CSS selector of the existing element - The matching element *also* has an `up-keep` attribute - The [`up:fragment:keep`](/up:fragment:keep) event that is [emitted](/up.emit) on the existing element is not prevented by a event listener. Let's say we want only keep an `<audio>` element as long as it plays the same song (as identified by the tag's `src` attribute). On the client we can achieve this by listening to an `up:keep:fragment` event and preventing it if the `src` attribute of the old and new element differ: up.compiler('audio', function(element) { element.addEventListener('up:fragment:keep', function(event) { if element.getAttribute('src') !== event.newElement.getAttribute('src') { event.preventDefault() } }) }) If we don't want to solve this on the client, we can achieve the same effect on the server. By setting the value of the `up-keep` attribute we can define the CSS selector used for matching elements. <audio up-keep="audio[src='song.mp3']" src="song.mp3"></audio> Now, if a response no longer contains an `<audio src="song.mp3">` tag, the existing element will be destroyed and replaced by a fragment from the response. @selector [up-keep] @param up-on-keep Code to run before an existing element is kept during a page update. The code may use the variables `event` (see `up:fragment:keep`), `this` (the old fragment), `newFragment` and `newData`. @stable ### ###** This event is [emitted](/up.emit) before an existing element is [kept](/up-keep) during a page update. Event listeners can call `event.preventDefault()` on an `up:fragment:keep` event to prevent the element from being persisted. If the event is prevented, the element will be replaced by a fragment from the response. @event up:fragment:keep @param event.preventDefault() Event listeners may call this method to prevent the element from being preserved. @param {Element} event.target The fragment that will be kept. @param {Element} event.newFragment The discarded element. @param {Object} event.newData The value of the [`up-data`](/up-data) attribute of the discarded element, parsed as a JSON object. @stable ### ###** This event is [emitted](/up.emit) when an existing element has been [kept](/up-keep) during a page update. Event listeners can inspect the discarded update through `event.newElement` and `event.newData` and then modify the preserved element when necessary. @event up:fragment:kept @param {Element} event.target The fragment that has been kept. @param {Element} event.newFragment The discarded fragment. @param {Object} event.newData The value of the [`up-data`](/up-data) attribute of the discarded fragment, parsed as a JSON object. @stable ### ###** Compiles a page fragment that has been inserted into the DOM by external code. **As long as you manipulate the DOM using Unpoly, you will never need to call this method.** You only need to use `up.hello()` if the DOM is manipulated without Unpoly' involvement, e.g. by setting the `innerHTML` property or calling jQuery methods like `html`, `insertAfter` or `appendTo`: ```html element = document.createElement('div') element.innerHTML = '... HTML that needs to be activated ...' up.hello(element) ``` This function emits the [`up:fragment:inserted`](/up:fragment:inserted) event. @function up.hello @param {Element|jQuery} target @param {Element|jQuery} [options.origin] @return {Element} The compiled element @stable ### hello = (element, options = {}) -> # If passed a selector, up.fragment.get() will prefer a match on the current layer. element = getSmart(element) # Callers may pass descriptions of child elements that were [kept](/up-keep) # as { options.keepPlans }. For these elements up.hello() emits an event # up:fragment:kept instead of up:fragment:inserted. # # We will also pass an array of kept child elements to up.hello() as { skip } # so they won't be compiled a second time. keepPlans = options.keepPlans || [] skip = keepPlans.map (plan) -> emitFragmentKept(plan) return plan.oldElement up.syntax.compile(element, { skip, layer: options.layer }) emitFragmentInserted(element, options) return element ###** When any page fragment has been [inserted or updated](/up.replace), this event is [emitted](/up.emit) on the fragment. If you're looking to run code when a new fragment matches a selector, use `up.compiler()` instead. \#\#\# Example up.on('up:fragment:inserted', function(event, fragment) { console.log("Looks like we have a new %o!", fragment) }) @event up:fragment:inserted @param {Element} event.target The fragment that has been inserted or updated. @stable ### emitFragmentInserted = (element, options) -> up.emit element, 'up:fragment:inserted', log: ['Inserted fragment %o', element] origin: options.origin emitFragmentKeep = (keepPlan) -> log = ['Keeping fragment %o', keepPlan.oldElement] callback = e.callbackAttr(keepPlan.oldElement, 'up-on-keep', ['newFragment', 'newData']) emitFromKeepPlan(keepPlan, 'up:fragment:keep', { log, callback }) emitFragmentKept = (keepPlan) -> log = ['Kept fragment %o', keepPlan.oldElement] emitFromKeepPlan(keepPlan, 'up:fragment:kept', { log }) emitFromKeepPlan = (keepPlan, eventType, emitDetails) -> keepable = keepPlan.oldElement event = up.event.build(eventType, newFragment: keepPlan.newElement newData: keepPlan.newData ) up.emit(keepable, event, emitDetails) emitFragmentDestroyed = (fragment, options) -> log = options.log ? ['Destroyed fragment %o', fragment] parent = options.parent || document up.emit(parent, 'up:fragment:destroyed', { fragment, parent, log }) isDestroying = (element) -> !!e.closest(element, '.up-destroying') isNotDestroying = (element) -> !isDestroying(element) ###** Returns the first fragment matching the given selector. This function differs from `document.querySelector()` and `up.element.get()`: - This function only selects elements in the [current layer](/up.layer.current). Pass a `{ layer }`option to match elements in other layers. - This function ignores elements that are being [destroyed](/up.destroy) or that are being removed by a [transition](/up.morph). - This function prefers to match elements in the vicinity of a given `{ origin }` element (optional). - This function supports non-standard CSS selectors like `:main` and `:has()`. If no element matches these conditions, `undefined` is returned. \#\#\# Example: Matching a selector in a layer To select the first element with the selector `.foo` on the [current layer](/up.layer.current): let foo = up.fragment.get('.foo') You may also pass a `{ layer }` option to match elements within another layer: let foo = up.fragment.get('.foo', { layer: 'any' }) \#\#\# Example: Matching the descendant of an element To only select in the descendants of an element, pass a root element as the first argument: let container = up.fragment.get('.container') let fooInContainer = up.fragment.get(container, '.foo') \#\#\# Example: Matching around an origin element When processing a user interaction, it is often helpful to match elements around the link that's being clicked or the form field that's being changed. In this case you may pass the triggering element as `{ origin }` element. Assume the following HTML: ```html <div class="element"></div> <div class="element"> <a href="..."></a> </div> ``` When processing an event for the `<a href"...">` you can pass the link element as `{ origin }` to match the closest element in the link's ancestry: ```javascript let link = event.target up.fragment.get('.element') // returns the first .element up.fragment.get('.element', { origin: link }) // returns the second .element ``` When the link's does not have an ancestor matching `.element`, Unpoly will search the entire layer for `.element`. \#\#\# Example: Matching an origin sibling When processing a user interaction, it is often helpful to match elements within the same container as the the link that's being clicked or the form field that's being changed. Assume the following HTML: ```html <div class="element" id="one"> <div class="inner"></div> </div> <div class="element" id="two"> <a href="..."></a> <div class="inner"></div> </div> ``` When processing an event for the `<a href"...">` you can pass the link element as `{ origin }` to match within the link's container: ```javascript let link = event.target up.fragment.get('.element .inner') // returns the first .inner up.fragment.get('.element .inner', { origin: link }) // returns the second .inner ``` Note that when the link's `.element` container does not have a child `.inner`, Unpoly will search the entire layer for `.element .inner`. \#\#\# Similar features - The [`.up-destroying`](/up-destroying) class is assigned to elements during their removal animation. - The [`up.element.get()`](/up.element.get) function simply returns the first element matching a selector without filtering by layer or destruction state. @function up.fragment.get @param {Element|jQuery} [root=document] The root element for the search. Only the root's children will be matched. May be omitted to search through all elements in the `document`. @param {string} selector The selector to match. @param {string} [options.layer='current'] The layer in which to select elements. See `up.layer.get()` for a list of supported layer values. If a root element was passed as first argument, this option is ignored and the root element's layer is searched. @param {string|Element|jQuery} [options.origin] An second element or selector that can be referenced as `&` in the first selector. @return {Element|undefined} The first matching element, or `undefined` if no such element matched. @stable ### getSmart = (args...) -> options = u.extractOptions(args) selector = args.pop() root = args[0] if u.isElementish(selector) # up.fragment.get(root: Element, element: Element, [options]) should just return element. # The given root and options are ignored. We also don't check if it's destroying. # We do use e.get() to unwrap a jQuery collection. return e.get(selector) if root # We don't match around { origin } if we're given a root for the search. return getDumb(root, selector, options) # If we don't have a root element we will use a context-sensitive lookup strategy # that tries to match elements in the vicinity of { origin } before going through # the entire layer. finder = new up.FragmentFinder( selector: selector origin: options.origin layer: options.layer ) return finder.find() getDumb = (args...) -> return getAll(args...)[0] CSS_HAS_SUFFIX_PATTERN = /\:has\(([^\)]+)\)$/ ###** Returns all elements matching the given selector, but ignores elements that are being [destroyed](/up.destroy) or that are being removed by a [transition](/up.morph). By default this function only selects elements in the [current layer](/up.layer.current). Pass a `{ layer }`option to match elements in other layers. See `up.layer.get()` for a list of supported layer values. Returns an empty list if no element matches these conditions. \#\#\# Example To select all elements with the selector `.foo` on the [current layer](/up.layer.current): let foos = up.fragment.all('.foo') You may also pass a `{ layer }` option to match elements within another layer: let foos = up.fragment.all('.foo', { layer: 'any' }) To select in the descendants of an element, pass a root element as the first argument: var container = up.fragment.get('.container') var foosInContainer = up.fragment.all(container, '.foo') \#\#\# Similar features - The [`.up-destroying`](/up-destroying) class is assigned to elements during their removal animation. - The [`up.element.all()`](/up.element.get) function simply returns the all elements matching a selector without further filtering. @function up.fragment.all @param {Element|jQuery} [root=document] The root element for the search. Only the root's children will be matched. May be omitted to search through all elements in the given [layer](#options.layer). @param {string} selector The selector to match. @param {string} [options.layer='current'] The layer in which to select elements. See `up.layer.get()` for a list of supported layer values. If a root element was passed as first argument, this option is ignored and the root element's layer is searched. @param {string|Element|jQuery} [options.origin] An second element or selector that can be referenced as `&` in the first selector: var input = document.querySelector('input.email') up.fragment.get('fieldset:has(&)', { origin: input }) // returns the <fieldset> containing input @return {Element|undefined} The first matching element, or `undefined` if no such element matched. @stable ### getAll = (args...) -> options = u.extractOptions(args) selector = args.pop() root = args[0] # (1) up.fragment.all(rootElement, selector) should find selector within # the descendants of rootElement. # (2) up.fragment.all(selector) should find selector within the current layer. # (3) up.fragment.all(selector, { layer }) should find selector within the given layer(s). selector = parseSelector(selector, root, options) return selector.descendants(root || document) ###** Your target selectors may use this pseudo-selector to replace an element with an descendant matching the given selector. \#\#\# Example `up.render('div:has(span)', { url: '...' })` replaces the first `<div>` elements with at least one `<span>` among its descendants: ```html <div> <span>Will be replaced</span> </div> <div> Will NOT be replaced </div> ``` \#\#\# Compatibility `:has()` is supported by target selectors like `a[up-target]` and `up.render({ target })`. As a [level 4 CSS selector](https://drafts.csswg.org/selectors-4/#relational), `:has()` [has yet to be implemented](https://caniuse.com/#feat=css-has) in native browser functions like [`document.querySelectorAll()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelectorAll). You can also use [`:has()` in jQuery](https://api.jquery.com/has-selector/). @selector :has() @stable ### ###** Returns a list of the given parent's descendants matching the given selector. The list will also include the parent element if it matches the selector itself. @function up.fragment.subtree @param {Element} parent The parent element for the search. @param {string} selector The CSS selector to match. @param {up.Layer|string|Element} [options.layer] @return {NodeList<Element>|Array<Element>} A list of all matching elements. @experimental ### getSubtree = (element, selector, options = {}) -> selector = parseSelector(selector, element, options) return selector.subtree(element) contains = (element, selector) -> getSubtree(element, selector).length > 0 ###** Returns the first element that matches the selector by testing the element itself and traversing up through ancestors in element's layers. `up.fragment.closest()` will only match elements in the same [layer](/up.layer) as the given element. To match ancestors regardless of layers, use `up.element.closest()`. @function up.fragment.closest @param {Element} element The element on which to start the search. @param {string} selector The CSS selector to match. @return {Element|null|undefined} element The matching element. Returns `null` or `undefined` if no element matches in the same layer. @experimental ### closest = (element, selector, options) -> element = e.get(element) selector = parseSelector(selector, element, options) return selector.closest(element) ###** Destroys the given element or selector. All [`up.compiler()`](/up.compiler) destructors, if any, are called. The element is then removed from the DOM. Emits events [`up:fragment:destroyed`](/up:fragment:destroyed). \#\#\# Animating the removal You may animate the element's removal by passing an option like `{ animate: 'fade-out' }`. Unpoly ships with a number of [predefined animations](/up.animate#named-animations) and you may so define [custom animations](/up.animation). If the element's removal is animated, the element will remain in the DOM until after the animation has completed. While the animation is running the element will be given the `.up-destroying` class. The element will also be given the `[aria-hidden]` attribute to remove it from the accessibility tree. Elements that are about to be destroyed (but still animating) are ignored by all functions for fragment lookup: - `up.fragment.all()` - `up.fragment.get()` - `up.fragment.closest()` @function up.destroy @param {string|Element|jQuery} target @param {string|Function(element, options): Promise} [options.animation='none'] The animation to use before the element is removed from the DOM. @param {number} [options.duration] The duration of the animation. See [`up.animate()`](/up.animate). @param {string} [options.easing] The timing function that controls the animation's acceleration. See [`up.animate()`](/up.animate). @param {Function} [options.onFinished] A callback that is run when any animations are finished and the element was removed from the DOM. @return undefined @stable ### destroy = (args...) -> options = parseTargetAndOptions(args) if options.element = getSmart(options.target, options) new up.Change.DestroyFragment(options).execute() return up.migrate.formerlyAsync?('up.destroy()') parseTargetAndOptions = (args) -> options = u.parseArgIntoOptions(args, 'target') if u.isElement(options.target) options.origin ||= options.target options ###** Elements are assigned the `.up-destroying` class before they are [destroyed](/up.destroy) or while they are being removed by a [transition](/up.morph). If the removal is [animated](/up.destroy#animating-the-removal), the class is assigned before the animation starts. Elements that are about to be destroyed (but still animating) are ignored by all functions for fragment lookup: - `up.fragment.all()` - `up.fragment.get()` - `up.fragment.closest()` @selector .up-destroying @stable ### markFragmentAsDestroying = (element) -> element.classList.add('up-destroying') element.setAttribute('aria-hidden', 'true') ###** This event is [emitted](/up.emit) after a page fragment was [destroyed](/up.destroy) and removed from the DOM. If the destruction is animated, this event is emitted after the animation has ended. The event is emitted on the parent element of the fragment that was removed. @event up:fragment:destroyed @param {Element} event.fragment The detached element that has been removed from the DOM. @param {Element} event.parent The former parent element of the fragment that has now been detached from the DOM. @param {Element} event.target The former parent element of the fragment that has now been detached from the DOM. @stable ### ###** Replaces the given element with a fresh copy fetched from the server. By default, reloading is not considered a [user navigation](/navigation) and e.g. will not update the browser location. You may change this with `{ navigate: true }`. \#\#\# Example up.on('new-mail', function() { up.reload('.inbox') }) \#\#\# Controlling the URL that is reloaded Unpoly remembers [the URL from which a fragment was loaded](/up.fragment.source), so you don't usually need to pass a URL when reloading. To reload from another URL, pass a `{ url }` option or set an `[up-source]` attribute on the element or its ancestors. \#\#\# Skipping updates when nothing changed You may use the `[up-time]` attribute to avoid rendering unchanged HTML when reloading a fragment. See `[up-time]` for a detailed example. @function up.reload @param {string|Element|jQuery} [target] The element that should be reloaded. If omitted, an element matching a selector in `up.fragment.config.mainTargets` will be reloaded. @param {Object} [options] See options for `up.render()`. @param {string} [options.url] The URL from which to reload the fragment. This defaults to the URL from which the fragment was originally loaded. @param {string} [options.navigate=false] Whether the reloading constitutes a [user navigation](/navigation). @stable ### reload = (args...) -> options = parseTargetAndOptions(args) options.target ||= ':main' element = getSmart(options.target, options) options.url ?= sourceOf(element) options.headers ||= {} options.headers[up.protocol.headerize('reloadFromTime')] = timeOf(element) return render(options) ###** Fetches this given URL with JavaScript and [replaces](/up.replace) the [current layer](/up.layer.current)'s [main element](/up.fragment.config#config.mainSelectors) with a matching fragment from the server response. \#\#\# Example This would replace the current page with the response for `/users`: up.visit('/users') @function up.visit @param {string} url The URL to visit. @param {Object} [options] See options for `up.render()`. @param {up.Layer|string|number} [options.layer='current'] @stable ### visit = (url, options) -> navigate(u.merge({ url }, options)) successKey = (key) -> return u.unprefixCamelCase(key, 'fail') failKey = (key) -> unless key.match(/^fail<KEY>[A-<KEY>/) return u.prefixCamelCase(key, 'fail') ###** Returns a CSS selector that matches the given element as good as possible. To build the selector, the following element properties are used in decreasing order of priority: - The element's `[up-id]` attribute - The element's `[id]` attribute - The element's `[name]` attribute - The element's `[class]` names, ignoring `up.fragment.config.badTargetClasses`. - The element's tag name \#\#\# Example ```js element = up.element.createFromHTML('<span class="klass">...</span>') selector = up.fragment.toTarget(element) // returns '.klass' ``` @function up.fragment.toTarget @param {string|Element|jQuery} The element for which to create a selector. @stable ### toTarget = (element) -> if u.isString(element) return element # In case we're called called with a jQuery collection element = e.get(element) if e.isSingleton(element) return e.elementTagName(element) else if upId = element.getAttribute("up-id") return e.attributeSelector('up-id', upId) else if id = element.getAttribute("id") return e.idSelector(id) else if name = element.getAttribute("name") return e.elementTagName(element) + e.attributeSelector('name', name) else if goodClasses = u.presence(u.filter(element.classList, isGoodClassForTarget)) selector = '' for klass in goodClasses selector += e.classSelector(klass) return selector else return e.elementTagName(element) ###** Sets an unique identifier for this element. This identifier is used by `up.fragment.toSelector()` to create a CSS selector that matches this element precisely. If the element already has other attributes that make a good identifier, like a good `[id]` or `[class]` attribute, it is not necessary to also set `[up-id]`. \#\#\# Example Take this element: <a href="/">Homepage</a> Unpoly cannot generate a good CSS selector for this element: up.fragment.toTarget(element) // returns 'a' We can improve this by assigning an `[up-id]`: <a href="/" up-id="link-to-home">Open user 4</a> The attribute value is used to create a better selector: up.fragment.toTarget(element) // returns '[up-id="link-to-home"]' @selector [up-id] @param up-id A string that uniquely identifies this element. @stable ### isGoodClassForTarget = (klass) -> matchesPattern = (pattern) -> if u.isRegExp(pattern) pattern.test(klass) else pattern == klass return !u.some(config.badTargetClasses, matchesPattern) resolveOriginReference = (target, options = {}) -> origin = options.origin return target.replace /&|:origin\b/, (match) -> if origin return toTarget(origin) else up.fail('Missing { origin } element to resolve "%s" reference (found in %s)', match, target) ###** @internal ### expandTargets = (targets, options = {}) -> layer = options.layer unless layer == 'new' || (layer instanceof up.Layer) up.fail('Must pass an up.Layer as { layer } option, but got %o', layer) # Copy the list since targets might be a jQuery collection, and this does not support shift or push. targets = u.copy(u.wrapList(targets)) expanded = [] while targets.length target = targets.shift() if target == ':main' || target == true mode = if layer == 'new' then options.mode else layer.mode targets.unshift(up.layer.mainTargets(mode)...) else if target == ':layer' # Discard this target for new layers, which don't have a first-swappable-element. # Also don't && the layer check into the `else if` condition above, or it will # be returned as a verbatim string below. unless layer == 'new' || layer.opening targets.unshift layer.getFirstSwappableElement() else if u.isElementish(target) expanded.push toTarget(target) else if u.isString(target) expanded.push resolveOriginReference(target, options) else # @buildPlans() might call us with { target: false } or { target: nil } # In that case we don't add a plan. return u.uniq(expanded) parseSelector = (selector, element, options = {}) -> filters = [] unless options.destroying filters.push(isNotDestroying) # Some up.fragment function center around an element, like closest() or matches(). options.layer ||= element layers = up.layer.getAll(options) if options.layer != 'any' && !(element && e.isDetached(element)) filters.push (match) -> u.some layers, (layer) -> layer.contains(match) expandedTargets = up.fragment.expandTargets(selector, u.merge(options, layer: layers[0])) expandedTargets = expandedTargets.map (target) -> target = target.replace CSS_HAS_SUFFIX_PATTERN, (match, descendantSelector) -> filters.push (element) -> element.querySelector(descendantSelector) return '' return target || '*' return new up.Selector(expandedTargets, filters) hasAutoHistory = (fragment) -> if contains(fragment, config.autoHistoryTargets) true else up.puts('up.render()', "Will not auto-update history because fragment doesn't contain a selector from up.fragment.config.autoHistoryTargets") false ###** A pseudo-selector that matches the layer's main target. Main targets are default render targets. When no other render target is given, Unpoly will try to find and replace a main target. In most app layouts the main target should match the primary content area. The default main targets are: - any element with an `[up-main]` attribute - the HTML5 [`<main>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/main) element - the current layer's [topmost swappable element](/layer) You may configure main target selectors in `up.fragment.config.mainTargets`. \#\#\# Example ```js up.render(':main', { url: '/page2' }) ``` @selector :main @experimental ### ###** Updates this element when no other render target is given. \#\#\# Example Many links simply replace the main content element in your application layout. Unpoly lets you mark this elements as a default target using the `[up-main]` attribute: ```html <body> <div class="layout"> <div class="layout--side"> ... </div> <div class="layout--content" up-main> ... </div> </div> </body> ``` Once a main target is configured, you no longer need `[up-target]` in a link.\ Use `[up-follow]` and the `[up-main]` element will be replaced: ```html <a href="/foo" up-follow>...</a> ``` If you want to update something more specific, you can still use `[up-target]`: ```html <a href="/foo" up-target=".profile">...</a> ``` Instead of assigning `[up-main]` you may also configure an existing selector in `up.fragment.config.mainTargets`: ```js up.fragment.config.mainTargets.push('.layout--content') ``` Overlays can use different main targets --------------------------------------- Overlays often use a different default selector, e.g. to exclude a navigation bar. To define a different main target for an overlay, set the [layer mode](/layer-terminology) as the value of the `[up-main]` attribute: ```html <body> <div class="layout" up-main="root"> <div class="layout--side"> ... </div> <div class="layout--content" up-main="modal"> ... </div> </div> </body> ``` Instead of assigning `[up-main]` you may also configure layer-specific targets in `up.layer.config`: ```js up.layer.config.popup.mainTargets.push('.menu') // for popup overlays up.layer.config.drawer.mainTargets.push('.menu') // for drawer overlays up.layer.config.overlay.mainTargets.push('.layout--content') // for all overlay modes ``` @selector [up-main] @param [up-main] A space-separated list of [layer modes](/layer-terminology) for which to use this main target. Omit the attribute value to define a main target for *all* layer modes. To use a different main target for all overlays (but not the root layer), set `[up-main=overlay]`. @stable ### ###** To make a server request without changing a fragment, use the `:none` selector. \#\#\# Example ```html <a href="/ping" up-target=":none">Ping server</a> ``` @selector :none @experimental ### ###** Your target selectors may use this pseudo-selector to reference the element that triggered the change. The origin element is automatically set to a link that is being [followed](/a-up-follow) or form that is being [submitted](/form-up-submit). When updating fragments programmatically through `up.render()` you may pass an origin element as an `{ origin }` option. Even without using an `:origin` reference, the [origin is considered](/fragment-placement#interaction-origin-is-considered) when matching fragments in the current page. \#\#\# Shorthand Instead of `:origin` you may also use the ampersand character (`&`). You may be familiar with the ampersand from the [Sass](https://sass-lang.com/documentation/file.SASS_REFERENCE.html#parent-selector) CSS preprocessor. @selector :origin @experimental ### ###** Your target selectors may use this pseudo-selector to replace the layer's topmost swappable element. The topmost swappable element is the first child of the layer's container element. For the [root layer](/up.layer.root) it is the `<body>` element. For an overlay it is the target with which the overlay was opened with. In canonical usage the topmost swappable element is often a [main element](/up-main). \#\#\# Example The following will replace the `<body>` element in the root layer, and the topmost swappable element in an overlay: ```js up.render(':layer', { url: '/page2' }) ``` @selector :layer @experimental ### ###** Returns whether the given element matches the given CSS selector. Other than `up.element.matches()` this function supports non-standard selectors like `:main` or `:layer`. @function up.fragment.matches @param {Element} fragment @param {string|Array<string>} selectorOrSelectors @param {string|up.Layer} options.layer The layer for which to match. Pseudo-selectors like `:main` may expand to different selectors in different layers. @param {string|up.Layer} options.mode Required if `{ layer: 'new' }` is passed. @return {boolean} @experimental ### matches = (element, selector, options = {}) -> element = e.get(element) selector = parseSelector(selector, element, options) return selector.matches(element) up.on 'up:app:boot', -> body = document.body body.setAttribute('up-source', up.history.location) hello(body) unless up.browser.canPushState() up.warn('Cannot push history changes. Next fragment update will load in a new page.') up.on 'up:framework:reset', reset u.literal config: config reload: reload destroy: destroy render: render navigate: navigate get: getSmart getDumb: getDumb all: getAll subtree: getSubtree contains: contains closest: closest source: sourceOf hello: hello visit: visit markAsDestroying: markFragmentAsDestroying emitInserted: emitFragmentInserted emitDestroyed: emitFragmentDestroyed emitKeep: emitFragmentKeep emitKept: emitFragmentKept successKey: successKey, failKey: failKey expandTargets: expandTargets toTarget: toTarget matches: matches hasAutoHistory: hasAutoHistory up.replace = up.fragment.replace up.extract = up.fragment.extract up.reload = up.fragment.reload up.destroy = up.fragment.destroy up.render = up.fragment.render up.navigate = up.fragment.navigate up.hello = up.fragment.hello up.visit = up.fragment.visit ###** Returns the current [context](/context). This is aliased as `up.layer.context`. @property up.context @param {Object} context The context object. If no context has been set an empty object is returned. @experimental ### u.delegate up, 'context', -> up.layer.current
true
u = up.util e = up.element ###** Fragment API =========== The `up.fragment` module offers a high-level JavaScript API to work with DOM elements. A fragment is an element with some additional properties that are useful in the context of a server-rendered web application: - Fragments are [identified by a CSS selector](/up.fragment.toTarget), like a `.class` or `#id`. - Fragments are usually updated by a [link](/a-up-follow) for [form](/form-up-submits) that targets their selector. When the server renders HTML with a matching element, the fragment is swapped with a new version. - As fragments enter the page they are automatically [compiled](/up.compiler) to activate JavaScript behavior. - Fragment changes may be [animated](/up.motion). - Fragments are placed on a [layer](/up.layer) that is isolated from other layers. Unpoly features will only see or change fragments from the [current layer](/up.layer.current) unless you [explicitly target another layer](/layer-option). - Fragments [know the URL from where they were loaded](/up.source). They can be [reloaded](/up.reload) or [polled periodically](/up-polled). For low-level DOM utilities that complement the browser's native API, see `up.element`. @see up.render @see up.navigate @see up.destroy @see up.reload @see up.fragment.get @see up.hello @module up.fragment ### up.fragment = do -> ###** Configures defaults for fragment updates. @property up.fragment.config @param {Array<string>} [config.mainTargets=['[up-main]', 'main', ':layer']] An array of CSS selectors matching default render targets. When no other render target is given, Unpoly will try to find and replace a main target. When [navigating](/navigation) to a main target, Unpoly will automatically [reset scroll positions](/scroll-option) and [update the browser history](/up.render#options.history). This property is aliased as [`up.layer.config.any.mainTargets`](up.layer.config#config.any.mainTargets). @param {Array<string|RegExp>} [config.badTargetClasses] An array of class names that should be ignored when [deriving a target selector from a fragment](/up.fragment.toTarget). The class names may also be passed as a regular expression. @param {Object} [config.navigateOptions] An object of default options to apply when [navigating](/navigation). @param {boolean} [config.matchAroundOrigin] Whether to match an existing fragment around the triggered link. If set to `false` Unpoly will replace the first fragment matching the given target selector in the link's [layer](/up.layer). @param {Array<string>} [config.autoHistoryTargets] When an updated fragments contain an element matching one of the given CSS selectors, history will be updated with `{ history: 'auto' }`. By default Unpoly will auto-update history when updating a [main target](#config.mainTargets). @param {boolean|string|Function(Element)} [config.autoScroll] How to scroll after updating a fragment with `{ scroll: 'auto' }`. See [scroll option](/scroll-option) for a list of allowed values. The default configuration tries, in this order: - If the URL has a `#hash`, scroll to the hash. - If updating a [main target](/up-main), reset scroll positions. @param {boolean|string|Function(Element)} [config.autoFocus] How to focus when updating a fragment with `{ focus: 'auto' }`. See [focus option](/focus-option) for a list of allowed values. The default configuration tries, in this order: - Focus a `#hash` in the URL. - Focus an `[autofocus]` element in the new fragment. - If focus was lost with the old fragment, focus the new fragment. - If updating a [main target](/up-main), focus the new fragment. @param {boolean} [config.runScripts=false] Whether to execute `<script>` tags in updated fragments. Scripts will load asynchronously, with no guarantee of execution order. If you set this to `true`, mind that the `<body>` element is a default [main target](/up-main). If you are including your global application scripts at the end of your `<body>` for performance reasons, swapping the `<body>` will re-execute these scripts. In that case you must configure a different main target that does not include your application scripts. @stable ### config = new up.Config -> badTargetClasses: [/^up-/] # These defaults will be set to both success and fail options # if { navigate: true } is given. navigateOptions: { focus: 'auto' scroll: 'auto' solo: true # preflight feedback: true # preflight fallback: true history: 'auto' peel: true cache: 'auto' } matchAroundOrigin: true runScripts: false autoHistoryTargets: [':main'] autoFocus: ['hash', 'autofocus', 'main-if-main', 'target-if-lost'] autoScroll: ['hash', 'layer-if-main'] # Users who are not using layers will prefer settings default targets # as up.fragment.config.mainTargets instead of up.layer.config.any.mainTargets. u.delegate config, 'mainTargets', -> up.layer.config.any reset = -> config.reset() ###** Returns the URL the given element was retrieved from. If the given element was never directly updated, but part of a larger fragment update, the closest known source of an ancestor element is returned. \#\#\# Example In the HTML below, the element `#one` was loaded from the URL `/foo`: ```html <div id="one" up-source"/foo"> <div id="two">...</div> </div> ``` We can now ask for the source of an element: ```javascript up.fragment.source('#two') // returns '/foo' ``` @function up.fragment.source @param {Element|string} element The element or CSS selector for which to look up the source URL. @return {string|undefined} @stable ### sourceOf = (element, options = {}) -> element = getSmart(element, options) return e.closestAttr(element, 'up-source') ###** Returns a timestamp for the last modification of the content in the given element. @function up.fragment.time @param {Element} element @return {string} @internal ### timeOf = (element) -> return e.closestAttr(element, 'up-time') || '0' ###** Sets the time when the fragment's underlying data was last changed. This can be used to avoid rendering unchanged HTML when [reloading](/up.reload) a fragment. This saves <b>CPU time</b> and reduces the <b>bandwidth cost</b> for a request/response exchange to **~1 KB**. \#\# Example Let's say we display a list of recent messages. We use the `[up-poll]` attribute to reload the `.messages` fragment every 30 seconds: ```html <div class="messages" up-poll> ... </div> ``` The list is now always up to date. But most of the time there will not be new messages, and we waste resources sending the same unchanged HTML from the server. We can improve this by setting an `[up-time]` attribute and the message list. The attribute value is the time of the most recent message. The time is encoded as the number of seconds since [Unix epoch](https://en.wikipedia.org/wiki/Unix_time). When, for instance, the last message in a list was received from December 24th, 1:51:46 PM UTC, we use the following HTML: ```html <div class="messages" up-time="1608730818" up-poll> ... </div> ``` When reloading Unpoly will echo the `[up-time]` timestamp in an `X-Up-Reload-From-Time` header: ```http X-Up-Reload-From-Time: 1608730818 ``` The server can compare the time from the request with the time of the last data update. If no more recent data is available, the server can render nothing and respond with an [`X-Up-Target: :none`](/X-Up-Target) header. Here is an example with [unpoly-rails](https://unpoly.com/install/rails): ```ruby class MessagesController < ApplicationController def index if up.reload_from_time == current_user.last_message_at up.render_nothing else @messages = current_user.messages.order(time: :desc).to_a render 'index' end end end ``` @selector [up-time] @param {string} up-time The number of seconds between the [Unix epoch](https://en.wikipedia.org/wiki/Unix_time). and the time when the element's underlying data was last changed. @experimental ### ###** Sets this element's source URL for [reloading](/up.reload) and [polling](/up-poll) When an element is reloaded, Unpoly will make a request from the URL that originally brought the element into the DOM. You may use `[up-source]` to use another URL instead. \#\#\# Example Assume an application layout with an unread message counter. You use `[up-poll]` to refresh the counter every 30 seconds. By default this would make a request to the URL that originally brought the counter element into the DOM. To save the server from rendering a lot of unused HTML, you may poll from a different URL like so: <div class="unread-count" up-poll up-source="/unread-count"> 2 new messages </div> @selector [up-source] @param {string} up-source The URL from which to reload this element. @stable ### ###** Replaces elements on the current page with matching elements from a server response or HTML string. The current and new elements must both match the same CSS selector. The selector is either given as `{ target }` option, or a [main target](/up-main) is used as default. See the [fragment placement](/fragment-placement) selector for many examples for how you can target content. This function has many options to enable scrolling, focus, request cancelation and other side effects. These options are all disabled by default and must be opted into one-by-one. To enable defaults that a user would expects for navigation (like clicking a link), pass [`{ navigate: true }`](#options.navigate) or use `up.navigate()` instead. \#\#\# Passing the new fragment The new fragment content can be passed as one of the following options: - [`{ url }`](#options.url) fetches and renders content from the server - [`{ document }`](#options.document) renders content from a given HTML document string or partial document - [`{ fragment }`](#options.fragment) renders content from a given HTML string that only contains the new fragment - [`{ content }`](#options-content) replaces the targeted fragment's inner HTML with the given HTML string \#\#\# Example Let's say your current HTML looks like this: ```html <div class="one">old one</div> <div class="two">old two</div> ``` We now replace the second `<div>` by targeting its CSS class: ```js up.render({ target: '.two', url: '/new' }) ``` The server renders a response for `/new`: ```html <div class="one">new one</div> <div class="two">new two</div> ``` Unpoly looks for the selector `.two` in the response and [implants](/up.extract) it into the current page. The current page now looks like this: ```html <div class="one">old one</div> <div class="two">new two</div> ``` Note how only `.two` has changed. The update for `.one` was discarded, since it didn't match the selector. \#\#\# Events Unpoly will emit events at various stages of the rendering process: - `up:fragment:destroyed` - `up:fragment:loaded` - `up:fragment:inserted` @function up.render @param {string|Element|jQuery|Array<string>} [target] The CSS selector to update. If omitted a [main target](/up-main) will be rendered. You may also pass a DOM element or jQuery element here, in which case a selector will be [inferred from the element attributes](/up.fragment.toTarget). The given element will also be used as [`{ origin }`](#options.origin) for the fragment update. You may also pass an array of selector alternatives. The first selector matching in both old and new content will be used. Instead of passing the target as the first argument, you may also pass it as a [´{ target }`](#options.target) option.. @param {string|Element|jQuery|Array<string>} [options.target] The CSS selector to update. See documentation for the [`target`](#target) parameter. @param {string|boolean} [options.fallback=false] Specifies behavior if the [target selector](/up.render#options.target) is missing from the current page or the server response. If set to a CSS selector string, Unpoly will attempt to replace that selector instead. If set to `true` Unpoly will attempt to replace a [main target](/up-main) instead. If set to `false` Unpoly will immediately reject the render promise. @param {boolean} [options.navigate=false] Whether this fragment update is considered [navigation](/navigation). @param {string} [options.url] The URL to fetch from the server. Instead of making a server request, you may also pass an existing HTML string as [`{ document }`](#options.document), [`{ fragment }`](#options.fragment) or [`{ content }`](#options.content) option. @param {string} [options.method='get'] The HTTP method to use for the request. Common values are `'get'`, `'post'`, `'put'`, `'patch'` and `'delete`'. The value is case insensitive. @param {Object|FormData|string|Array} [options.params] Additional [parameters](/up.Params) that should be sent as the request's [query string](https://en.wikipedia.org/wiki/Query_string) or payload. When making a `GET` request to a URL with a query string, the given `{ params }` will be added to the query parameters. @param {Object} [options.headers={}] An object with additional request headers. Note that Unpoly will by default send a number of custom request headers. E.g. the `X-Up-Target` header includes the targeted CSS selector. See `up.protocol` and `up.network.config.metaKeys` for details. @param {string|Element} [options.fragment] A string of HTML comprising *only* the new fragment. The `{ target }` selector will be derived from the root element in the given HTML: ```js // This will update .foo up.render({ fragment: '<div class=".foo">inner</div>' }) ``` If your HTML string contains other fragments that will not be rendered, use the [`{ document }`](#options.document) option instead. If your HTML string comprises only the new fragment's [inner HTML](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML), consider the [`{ content }`](#options.content) option. @param {string|Element|Document} [options.document] A string of HTML containing the new fragment. The string may contain other HTML, but only the element matching the `{ target }` selector will be extracted and placed into the page. Other elements will be discarded. If your HTML string comprises only the new fragment, consider the [`{ fragment }`](#options.fragment) option instead. With `{ fragment }` you don't need to pass a `{ target }`, since Unpoly can derive it from the root element in the given HTML. If your HTML string comprises only the new fragment's [inner HTML](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML), consider the [`{ content }`](#options.content) option. @param {string} [options.fail='auto'] How to render a server response with an error code. Any HTTP status code other than 2xx is considered an error code. See [handling server errors](/server-errors) for details. @param {boolean|string} [options.history] Whether the browser URL and window title will be updated. If set to `true`, the history will always be updated, using the title and URL from the server response, or from given `{ title }` and `{ location }` options. If set to `'auto'` history will be updated if the `{ target }` matches a selector in `up.fragment.config.autoHistoryTargets`. By default this contains all [main targets](/up-main). If set to `false`, the history will remain unchanged. [Overlays](/up.layer) will only change the browser URL and window title if the overlay has [visible history](/up.layer.historyVisible), even when `{ history: true }` is passed. @param {string} [options.title] An explicit document title to use after rendering. By default the title is extracted from the response's `<title>` tag. You may also pass `{ title: false }` to explicitly prevent the title from being updated. Note that the browser's window title will only be updated it you also pass a [`{ history }`](#options.history) option. @param {string} [options.location] An explicit URL to use after rendering. By default Unpoly will use the `{ url }` or the final URL after the server redirected. You may also pass `{ location: false }` to explicitly prevent the URL from being updated. Note that the browser's URL will only be updated it you also pass a [`{ history }`](#options.history) option. @param {string} [options.transition] The name of an [transition](/up.motion) to morph between the old and few fragment. If you are [prepending or appending content](/fragment-placement#appending-or-prepending-content), use the `{ animation }` option instead. @param {string} [options.animation] The name of an [animation](/up.motion) to reveal a new fragment when [prepending or appending content](/fragment-placement#appending-or-prepending-content). If you are replacing content (the default), use the `{ transition }` option instead. @param {number} [options.duration] The duration of the transition or animation (in millisconds). @param {string} [options.easing] The timing function that accelerates the transition or animation. See [W3C documentation](http://www.w3.org/TR/css3-transitions/#transition-timing-function) for a list of available timing functions. @param {boolean} [options.cache] Whether to read from and write to the [cache](/up.cache). With `{ cache: true }` Unpoly will try to re-use a cached response before connecting to the network. If no cached response exists, Unpoly will make a request and cache the server response. Also see [`up.request({ cache })`](/up.request#options.cache). @param {boolean|string} [options.clearCache] Whether existing [cache](/up.cache) entries will be [cleared](/up.cache.clear) with this request. You may also pass a [URL pattern](/url-patterns) to only clear matching requests. By default a non-GET request will clear the entire cache. Also see [`up.request({ clearCache })`](/up.request#options.clearCache) and `up.network.config.clearCache`. @param {Element|jQuery} [options.origin] The element that triggered the change. When multiple elements in the current page match the `{ target }`, Unpoly will replace an element in the [origin's vicinity](/fragment-placement). The origin's selector will be substituted for `:origin` in a target selector. @param {string|up.Layer|Element} [options.layer='origin current'] The [layer](/up.layer) in which to match and render the fragment. See [layer option](/layer-option) for a list of allowed values. To [open the fragment in a new overlay](/opening-overlays), pass `{ layer: 'new' }`. In this case options for `up.layer.open()` may also be used. @param {boolean} [options.peel] Whether to close overlays obstructing the updated layer when the fragment is updated. This is only relevant when updating a layer that is not the [frontmost layer](/up.layer.front). @param {Object} [options.context] An object that will be merged into the [context](/context) of the current layer once the fragment is rendered. @param {boolean} [options.keep=true] Whether [`[up-keep]`](/up-keep) elements will be preserved in the updated fragment. @param {boolean} [options.hungry=true] Whether [`[up-hungry]`](/up-hungry) elements outside the updated fragment will also be updated. @param {boolean|string|Element|Function} [options.scroll] How to scroll after the new fragment was rendered. See [scroll option](/scroll-option) for a list of allowed values. @param {boolean} [options.saveScroll=true] Whether to save scroll positions before updating the fragment. Saved scroll positions can later be restored with [`{ scroll: 'restore' }`](/scroll-option#restoring-scroll-options). @param {boolean|string|Element|Function} [options.focus] What to focus after the new fragment was rendered. See [focus option](/focus-option) for a list of allowed values. @param {string} [options.confirm] A message the user needs to confirm before fragments are updated. The message will be shown as a [native browser prompt](https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt). If the user does not confirm the render promise will reject and no fragments will be updated. @param {boolean|Element} [options.feedback] Whether to give the [`{ origin }`](#options.origin) element an `.up-active` class while loading and rendering content. May also pass an element which should receive the `.up-active` class. @param {Function(Event)} [options.onLoaded] A callback that will be run when when the server responds with new HTML, but before the HTML is rendered. The callback argument is a preventable `up:fragment:loaded` event. @param {Function()} [options.onFinished] A callback that will be run when all animations have concluded and elements were removed from the DOM tree. @return {Promise<up.RenderResult>} A promise that fulfills when the page has been updated. If the update is animated, the promise will be resolved *before* the existing element was removed from the DOM tree. The old element will be marked with the `.up-destroying` class and removed once the animation finishes. To run code after the old element was removed, pass an `{ onFinished }` callback. The promise will fulfill with an `up.RenderResult` that contains references to the updated fragments and layer. @stable ### render = up.mockable (args...) -> # Convert thrown errors into rejected promises. # Convert non-promise values into a resolved promise. return u.asyncify -> options = parseTargetAndOptions(args) options = up.RenderOptions.preprocess(options) up.browser.assertConfirmed(options) if guardEvent = u.pluckKey(options, 'guardEvent') # Allow guard event handlers to manipulate render options for the default behavior. # # Note that we have removed { guardEvent } from options to not recursively define # guardEvent.renderOptions.guardEvent. This would cause an infinite loop for event # listeners that prevent the default and re-render. guardEvent.renderOptions = options up.event.assertEmitted(guardEvent, { target: options.origin }) up.RenderOptions.assertContentGiven(options) if options.url return renderRemoteContent(options) else return renderLocalContent(options) renderRemoteContent = (options) -> # Rendering a remote URL is an async operation. # We give feedback (.up-active) while the fragment is loading. return up.feedback.aroundForOptions options, -> return new up.Change.FromURL(options).execute() renderLocalContent = (options) -> # When we have a given { url }, the { solo } option is honored by up.request(). # But up.request() is never called when we have local content given as { document }, # { content } or { fragment }. Hence we abort here. up.network.mimicLocalRequest(options) # (1) No need to give feedback as local changes are sync. # (2) Value will be converted to a fulfilled promise by up.util.asyncify() in render(). return new up.Change.FromContent(options).execute() ###** [Navigates](/navigation) to the given URL by updating a major fragment in the current page. `up.navigate()` will mimic a click on a vanilla `<a href>` link to satisfy user expectations regarding scrolling, focus, request cancelation and [many other side effects](/navigation). Instead of calling `up.navigate()` you may also call `up.render({ navigate: true }`) option for the same effect. @function up.navigate @param {string|Element|jQuery} [target] The CSS selector to update. If omitted a [main target](/up-main) will be rendered. You can also pass a DOM element or jQuery element here, in which case a selector will be [inferred from the element attributes](/up.fragment.target). The given element will also be set as the `{ origin }` option. Instead of passing the target as the first argument, you may also pass it as [´{ target }` option](/up.fragment.render#options.target). @param {Object} [options] See options for `up.render()`. @stable ### navigate = up.mockable (args...) -> options = parseTargetAndOptions(args) return render(u.merge(options, navigate: true)) ###** This event is [emitted](/up.emit) when the server responds with the HTML, before the HTML is used to [change a fragment](/up.render). Event listeners may call `event.preventDefault()` on an `up:fragment:loaded` event to prevent any changes to the DOM and browser history. This is useful to detect an entirely different page layout (like a maintenance page or fatal server error) which should be open with a full page load: ```js up.on('up:fragment:loaded', (event) => { let isMaintenancePage = event.response.getHeader('X-Maintenance') if (isMaintenancePage) { // Prevent the fragment update and don't update browser history event.preventDefault() // Make a full page load for the same request. event.request.loadPage() } }) ``` Instead of preventing the update, listeners may also access the `event.renderOptions` object to mutate options to the `up.render()` call that will process the server response. @event up:fragment:loaded @param event.preventDefault() Event listeners may call this method to prevent the fragment change. @param {up.Request} event.request The original request to the server. @param {up.Response} event.response The server response. @param {Object} event.renderOptions Options for the `up.render()` call that will process the server response. @stable ### ###** Elements with an `up-keep` attribute will be persisted during [fragment updates](/up.fragment). The element you're keeping should have an umambiguous class name, ID or `[up-id]` attribute so Unpoly can find its new position within the page update. Emits events [`up:fragment:keep`](/up:fragment:keep) and [`up:fragment:kept`](/up:fragment:kept). \#\#\# Example The following `<audio>` element will be persisted through fragment updates as long as the responses contain an element matching `#player`: ```html <audio id="player" up-keep src="song.mp3"></audio> ``` \#\#\# Controlling if an element will be kept Unpoly will **only** keep an existing element if: - The existing element has an `up-keep` attribute - The response contains an element matching the CSS selector of the existing element - The matching element *also* has an `up-keep` attribute - The [`up:fragment:keep`](/up:fragment:keep) event that is [emitted](/up.emit) on the existing element is not prevented by a event listener. Let's say we want only keep an `<audio>` element as long as it plays the same song (as identified by the tag's `src` attribute). On the client we can achieve this by listening to an `up:keep:fragment` event and preventing it if the `src` attribute of the old and new element differ: up.compiler('audio', function(element) { element.addEventListener('up:fragment:keep', function(event) { if element.getAttribute('src') !== event.newElement.getAttribute('src') { event.preventDefault() } }) }) If we don't want to solve this on the client, we can achieve the same effect on the server. By setting the value of the `up-keep` attribute we can define the CSS selector used for matching elements. <audio up-keep="audio[src='song.mp3']" src="song.mp3"></audio> Now, if a response no longer contains an `<audio src="song.mp3">` tag, the existing element will be destroyed and replaced by a fragment from the response. @selector [up-keep] @param up-on-keep Code to run before an existing element is kept during a page update. The code may use the variables `event` (see `up:fragment:keep`), `this` (the old fragment), `newFragment` and `newData`. @stable ### ###** This event is [emitted](/up.emit) before an existing element is [kept](/up-keep) during a page update. Event listeners can call `event.preventDefault()` on an `up:fragment:keep` event to prevent the element from being persisted. If the event is prevented, the element will be replaced by a fragment from the response. @event up:fragment:keep @param event.preventDefault() Event listeners may call this method to prevent the element from being preserved. @param {Element} event.target The fragment that will be kept. @param {Element} event.newFragment The discarded element. @param {Object} event.newData The value of the [`up-data`](/up-data) attribute of the discarded element, parsed as a JSON object. @stable ### ###** This event is [emitted](/up.emit) when an existing element has been [kept](/up-keep) during a page update. Event listeners can inspect the discarded update through `event.newElement` and `event.newData` and then modify the preserved element when necessary. @event up:fragment:kept @param {Element} event.target The fragment that has been kept. @param {Element} event.newFragment The discarded fragment. @param {Object} event.newData The value of the [`up-data`](/up-data) attribute of the discarded fragment, parsed as a JSON object. @stable ### ###** Compiles a page fragment that has been inserted into the DOM by external code. **As long as you manipulate the DOM using Unpoly, you will never need to call this method.** You only need to use `up.hello()` if the DOM is manipulated without Unpoly' involvement, e.g. by setting the `innerHTML` property or calling jQuery methods like `html`, `insertAfter` or `appendTo`: ```html element = document.createElement('div') element.innerHTML = '... HTML that needs to be activated ...' up.hello(element) ``` This function emits the [`up:fragment:inserted`](/up:fragment:inserted) event. @function up.hello @param {Element|jQuery} target @param {Element|jQuery} [options.origin] @return {Element} The compiled element @stable ### hello = (element, options = {}) -> # If passed a selector, up.fragment.get() will prefer a match on the current layer. element = getSmart(element) # Callers may pass descriptions of child elements that were [kept](/up-keep) # as { options.keepPlans }. For these elements up.hello() emits an event # up:fragment:kept instead of up:fragment:inserted. # # We will also pass an array of kept child elements to up.hello() as { skip } # so they won't be compiled a second time. keepPlans = options.keepPlans || [] skip = keepPlans.map (plan) -> emitFragmentKept(plan) return plan.oldElement up.syntax.compile(element, { skip, layer: options.layer }) emitFragmentInserted(element, options) return element ###** When any page fragment has been [inserted or updated](/up.replace), this event is [emitted](/up.emit) on the fragment. If you're looking to run code when a new fragment matches a selector, use `up.compiler()` instead. \#\#\# Example up.on('up:fragment:inserted', function(event, fragment) { console.log("Looks like we have a new %o!", fragment) }) @event up:fragment:inserted @param {Element} event.target The fragment that has been inserted or updated. @stable ### emitFragmentInserted = (element, options) -> up.emit element, 'up:fragment:inserted', log: ['Inserted fragment %o', element] origin: options.origin emitFragmentKeep = (keepPlan) -> log = ['Keeping fragment %o', keepPlan.oldElement] callback = e.callbackAttr(keepPlan.oldElement, 'up-on-keep', ['newFragment', 'newData']) emitFromKeepPlan(keepPlan, 'up:fragment:keep', { log, callback }) emitFragmentKept = (keepPlan) -> log = ['Kept fragment %o', keepPlan.oldElement] emitFromKeepPlan(keepPlan, 'up:fragment:kept', { log }) emitFromKeepPlan = (keepPlan, eventType, emitDetails) -> keepable = keepPlan.oldElement event = up.event.build(eventType, newFragment: keepPlan.newElement newData: keepPlan.newData ) up.emit(keepable, event, emitDetails) emitFragmentDestroyed = (fragment, options) -> log = options.log ? ['Destroyed fragment %o', fragment] parent = options.parent || document up.emit(parent, 'up:fragment:destroyed', { fragment, parent, log }) isDestroying = (element) -> !!e.closest(element, '.up-destroying') isNotDestroying = (element) -> !isDestroying(element) ###** Returns the first fragment matching the given selector. This function differs from `document.querySelector()` and `up.element.get()`: - This function only selects elements in the [current layer](/up.layer.current). Pass a `{ layer }`option to match elements in other layers. - This function ignores elements that are being [destroyed](/up.destroy) or that are being removed by a [transition](/up.morph). - This function prefers to match elements in the vicinity of a given `{ origin }` element (optional). - This function supports non-standard CSS selectors like `:main` and `:has()`. If no element matches these conditions, `undefined` is returned. \#\#\# Example: Matching a selector in a layer To select the first element with the selector `.foo` on the [current layer](/up.layer.current): let foo = up.fragment.get('.foo') You may also pass a `{ layer }` option to match elements within another layer: let foo = up.fragment.get('.foo', { layer: 'any' }) \#\#\# Example: Matching the descendant of an element To only select in the descendants of an element, pass a root element as the first argument: let container = up.fragment.get('.container') let fooInContainer = up.fragment.get(container, '.foo') \#\#\# Example: Matching around an origin element When processing a user interaction, it is often helpful to match elements around the link that's being clicked or the form field that's being changed. In this case you may pass the triggering element as `{ origin }` element. Assume the following HTML: ```html <div class="element"></div> <div class="element"> <a href="..."></a> </div> ``` When processing an event for the `<a href"...">` you can pass the link element as `{ origin }` to match the closest element in the link's ancestry: ```javascript let link = event.target up.fragment.get('.element') // returns the first .element up.fragment.get('.element', { origin: link }) // returns the second .element ``` When the link's does not have an ancestor matching `.element`, Unpoly will search the entire layer for `.element`. \#\#\# Example: Matching an origin sibling When processing a user interaction, it is often helpful to match elements within the same container as the the link that's being clicked or the form field that's being changed. Assume the following HTML: ```html <div class="element" id="one"> <div class="inner"></div> </div> <div class="element" id="two"> <a href="..."></a> <div class="inner"></div> </div> ``` When processing an event for the `<a href"...">` you can pass the link element as `{ origin }` to match within the link's container: ```javascript let link = event.target up.fragment.get('.element .inner') // returns the first .inner up.fragment.get('.element .inner', { origin: link }) // returns the second .inner ``` Note that when the link's `.element` container does not have a child `.inner`, Unpoly will search the entire layer for `.element .inner`. \#\#\# Similar features - The [`.up-destroying`](/up-destroying) class is assigned to elements during their removal animation. - The [`up.element.get()`](/up.element.get) function simply returns the first element matching a selector without filtering by layer or destruction state. @function up.fragment.get @param {Element|jQuery} [root=document] The root element for the search. Only the root's children will be matched. May be omitted to search through all elements in the `document`. @param {string} selector The selector to match. @param {string} [options.layer='current'] The layer in which to select elements. See `up.layer.get()` for a list of supported layer values. If a root element was passed as first argument, this option is ignored and the root element's layer is searched. @param {string|Element|jQuery} [options.origin] An second element or selector that can be referenced as `&` in the first selector. @return {Element|undefined} The first matching element, or `undefined` if no such element matched. @stable ### getSmart = (args...) -> options = u.extractOptions(args) selector = args.pop() root = args[0] if u.isElementish(selector) # up.fragment.get(root: Element, element: Element, [options]) should just return element. # The given root and options are ignored. We also don't check if it's destroying. # We do use e.get() to unwrap a jQuery collection. return e.get(selector) if root # We don't match around { origin } if we're given a root for the search. return getDumb(root, selector, options) # If we don't have a root element we will use a context-sensitive lookup strategy # that tries to match elements in the vicinity of { origin } before going through # the entire layer. finder = new up.FragmentFinder( selector: selector origin: options.origin layer: options.layer ) return finder.find() getDumb = (args...) -> return getAll(args...)[0] CSS_HAS_SUFFIX_PATTERN = /\:has\(([^\)]+)\)$/ ###** Returns all elements matching the given selector, but ignores elements that are being [destroyed](/up.destroy) or that are being removed by a [transition](/up.morph). By default this function only selects elements in the [current layer](/up.layer.current). Pass a `{ layer }`option to match elements in other layers. See `up.layer.get()` for a list of supported layer values. Returns an empty list if no element matches these conditions. \#\#\# Example To select all elements with the selector `.foo` on the [current layer](/up.layer.current): let foos = up.fragment.all('.foo') You may also pass a `{ layer }` option to match elements within another layer: let foos = up.fragment.all('.foo', { layer: 'any' }) To select in the descendants of an element, pass a root element as the first argument: var container = up.fragment.get('.container') var foosInContainer = up.fragment.all(container, '.foo') \#\#\# Similar features - The [`.up-destroying`](/up-destroying) class is assigned to elements during their removal animation. - The [`up.element.all()`](/up.element.get) function simply returns the all elements matching a selector without further filtering. @function up.fragment.all @param {Element|jQuery} [root=document] The root element for the search. Only the root's children will be matched. May be omitted to search through all elements in the given [layer](#options.layer). @param {string} selector The selector to match. @param {string} [options.layer='current'] The layer in which to select elements. See `up.layer.get()` for a list of supported layer values. If a root element was passed as first argument, this option is ignored and the root element's layer is searched. @param {string|Element|jQuery} [options.origin] An second element or selector that can be referenced as `&` in the first selector: var input = document.querySelector('input.email') up.fragment.get('fieldset:has(&)', { origin: input }) // returns the <fieldset> containing input @return {Element|undefined} The first matching element, or `undefined` if no such element matched. @stable ### getAll = (args...) -> options = u.extractOptions(args) selector = args.pop() root = args[0] # (1) up.fragment.all(rootElement, selector) should find selector within # the descendants of rootElement. # (2) up.fragment.all(selector) should find selector within the current layer. # (3) up.fragment.all(selector, { layer }) should find selector within the given layer(s). selector = parseSelector(selector, root, options) return selector.descendants(root || document) ###** Your target selectors may use this pseudo-selector to replace an element with an descendant matching the given selector. \#\#\# Example `up.render('div:has(span)', { url: '...' })` replaces the first `<div>` elements with at least one `<span>` among its descendants: ```html <div> <span>Will be replaced</span> </div> <div> Will NOT be replaced </div> ``` \#\#\# Compatibility `:has()` is supported by target selectors like `a[up-target]` and `up.render({ target })`. As a [level 4 CSS selector](https://drafts.csswg.org/selectors-4/#relational), `:has()` [has yet to be implemented](https://caniuse.com/#feat=css-has) in native browser functions like [`document.querySelectorAll()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelectorAll). You can also use [`:has()` in jQuery](https://api.jquery.com/has-selector/). @selector :has() @stable ### ###** Returns a list of the given parent's descendants matching the given selector. The list will also include the parent element if it matches the selector itself. @function up.fragment.subtree @param {Element} parent The parent element for the search. @param {string} selector The CSS selector to match. @param {up.Layer|string|Element} [options.layer] @return {NodeList<Element>|Array<Element>} A list of all matching elements. @experimental ### getSubtree = (element, selector, options = {}) -> selector = parseSelector(selector, element, options) return selector.subtree(element) contains = (element, selector) -> getSubtree(element, selector).length > 0 ###** Returns the first element that matches the selector by testing the element itself and traversing up through ancestors in element's layers. `up.fragment.closest()` will only match elements in the same [layer](/up.layer) as the given element. To match ancestors regardless of layers, use `up.element.closest()`. @function up.fragment.closest @param {Element} element The element on which to start the search. @param {string} selector The CSS selector to match. @return {Element|null|undefined} element The matching element. Returns `null` or `undefined` if no element matches in the same layer. @experimental ### closest = (element, selector, options) -> element = e.get(element) selector = parseSelector(selector, element, options) return selector.closest(element) ###** Destroys the given element or selector. All [`up.compiler()`](/up.compiler) destructors, if any, are called. The element is then removed from the DOM. Emits events [`up:fragment:destroyed`](/up:fragment:destroyed). \#\#\# Animating the removal You may animate the element's removal by passing an option like `{ animate: 'fade-out' }`. Unpoly ships with a number of [predefined animations](/up.animate#named-animations) and you may so define [custom animations](/up.animation). If the element's removal is animated, the element will remain in the DOM until after the animation has completed. While the animation is running the element will be given the `.up-destroying` class. The element will also be given the `[aria-hidden]` attribute to remove it from the accessibility tree. Elements that are about to be destroyed (but still animating) are ignored by all functions for fragment lookup: - `up.fragment.all()` - `up.fragment.get()` - `up.fragment.closest()` @function up.destroy @param {string|Element|jQuery} target @param {string|Function(element, options): Promise} [options.animation='none'] The animation to use before the element is removed from the DOM. @param {number} [options.duration] The duration of the animation. See [`up.animate()`](/up.animate). @param {string} [options.easing] The timing function that controls the animation's acceleration. See [`up.animate()`](/up.animate). @param {Function} [options.onFinished] A callback that is run when any animations are finished and the element was removed from the DOM. @return undefined @stable ### destroy = (args...) -> options = parseTargetAndOptions(args) if options.element = getSmart(options.target, options) new up.Change.DestroyFragment(options).execute() return up.migrate.formerlyAsync?('up.destroy()') parseTargetAndOptions = (args) -> options = u.parseArgIntoOptions(args, 'target') if u.isElement(options.target) options.origin ||= options.target options ###** Elements are assigned the `.up-destroying` class before they are [destroyed](/up.destroy) or while they are being removed by a [transition](/up.morph). If the removal is [animated](/up.destroy#animating-the-removal), the class is assigned before the animation starts. Elements that are about to be destroyed (but still animating) are ignored by all functions for fragment lookup: - `up.fragment.all()` - `up.fragment.get()` - `up.fragment.closest()` @selector .up-destroying @stable ### markFragmentAsDestroying = (element) -> element.classList.add('up-destroying') element.setAttribute('aria-hidden', 'true') ###** This event is [emitted](/up.emit) after a page fragment was [destroyed](/up.destroy) and removed from the DOM. If the destruction is animated, this event is emitted after the animation has ended. The event is emitted on the parent element of the fragment that was removed. @event up:fragment:destroyed @param {Element} event.fragment The detached element that has been removed from the DOM. @param {Element} event.parent The former parent element of the fragment that has now been detached from the DOM. @param {Element} event.target The former parent element of the fragment that has now been detached from the DOM. @stable ### ###** Replaces the given element with a fresh copy fetched from the server. By default, reloading is not considered a [user navigation](/navigation) and e.g. will not update the browser location. You may change this with `{ navigate: true }`. \#\#\# Example up.on('new-mail', function() { up.reload('.inbox') }) \#\#\# Controlling the URL that is reloaded Unpoly remembers [the URL from which a fragment was loaded](/up.fragment.source), so you don't usually need to pass a URL when reloading. To reload from another URL, pass a `{ url }` option or set an `[up-source]` attribute on the element or its ancestors. \#\#\# Skipping updates when nothing changed You may use the `[up-time]` attribute to avoid rendering unchanged HTML when reloading a fragment. See `[up-time]` for a detailed example. @function up.reload @param {string|Element|jQuery} [target] The element that should be reloaded. If omitted, an element matching a selector in `up.fragment.config.mainTargets` will be reloaded. @param {Object} [options] See options for `up.render()`. @param {string} [options.url] The URL from which to reload the fragment. This defaults to the URL from which the fragment was originally loaded. @param {string} [options.navigate=false] Whether the reloading constitutes a [user navigation](/navigation). @stable ### reload = (args...) -> options = parseTargetAndOptions(args) options.target ||= ':main' element = getSmart(options.target, options) options.url ?= sourceOf(element) options.headers ||= {} options.headers[up.protocol.headerize('reloadFromTime')] = timeOf(element) return render(options) ###** Fetches this given URL with JavaScript and [replaces](/up.replace) the [current layer](/up.layer.current)'s [main element](/up.fragment.config#config.mainSelectors) with a matching fragment from the server response. \#\#\# Example This would replace the current page with the response for `/users`: up.visit('/users') @function up.visit @param {string} url The URL to visit. @param {Object} [options] See options for `up.render()`. @param {up.Layer|string|number} [options.layer='current'] @stable ### visit = (url, options) -> navigate(u.merge({ url }, options)) successKey = (key) -> return u.unprefixCamelCase(key, 'fail') failKey = (key) -> unless key.match(/^failPI:KEY:<KEY>END_PI[A-PI:KEY:<KEY>END_PI/) return u.prefixCamelCase(key, 'fail') ###** Returns a CSS selector that matches the given element as good as possible. To build the selector, the following element properties are used in decreasing order of priority: - The element's `[up-id]` attribute - The element's `[id]` attribute - The element's `[name]` attribute - The element's `[class]` names, ignoring `up.fragment.config.badTargetClasses`. - The element's tag name \#\#\# Example ```js element = up.element.createFromHTML('<span class="klass">...</span>') selector = up.fragment.toTarget(element) // returns '.klass' ``` @function up.fragment.toTarget @param {string|Element|jQuery} The element for which to create a selector. @stable ### toTarget = (element) -> if u.isString(element) return element # In case we're called called with a jQuery collection element = e.get(element) if e.isSingleton(element) return e.elementTagName(element) else if upId = element.getAttribute("up-id") return e.attributeSelector('up-id', upId) else if id = element.getAttribute("id") return e.idSelector(id) else if name = element.getAttribute("name") return e.elementTagName(element) + e.attributeSelector('name', name) else if goodClasses = u.presence(u.filter(element.classList, isGoodClassForTarget)) selector = '' for klass in goodClasses selector += e.classSelector(klass) return selector else return e.elementTagName(element) ###** Sets an unique identifier for this element. This identifier is used by `up.fragment.toSelector()` to create a CSS selector that matches this element precisely. If the element already has other attributes that make a good identifier, like a good `[id]` or `[class]` attribute, it is not necessary to also set `[up-id]`. \#\#\# Example Take this element: <a href="/">Homepage</a> Unpoly cannot generate a good CSS selector for this element: up.fragment.toTarget(element) // returns 'a' We can improve this by assigning an `[up-id]`: <a href="/" up-id="link-to-home">Open user 4</a> The attribute value is used to create a better selector: up.fragment.toTarget(element) // returns '[up-id="link-to-home"]' @selector [up-id] @param up-id A string that uniquely identifies this element. @stable ### isGoodClassForTarget = (klass) -> matchesPattern = (pattern) -> if u.isRegExp(pattern) pattern.test(klass) else pattern == klass return !u.some(config.badTargetClasses, matchesPattern) resolveOriginReference = (target, options = {}) -> origin = options.origin return target.replace /&|:origin\b/, (match) -> if origin return toTarget(origin) else up.fail('Missing { origin } element to resolve "%s" reference (found in %s)', match, target) ###** @internal ### expandTargets = (targets, options = {}) -> layer = options.layer unless layer == 'new' || (layer instanceof up.Layer) up.fail('Must pass an up.Layer as { layer } option, but got %o', layer) # Copy the list since targets might be a jQuery collection, and this does not support shift or push. targets = u.copy(u.wrapList(targets)) expanded = [] while targets.length target = targets.shift() if target == ':main' || target == true mode = if layer == 'new' then options.mode else layer.mode targets.unshift(up.layer.mainTargets(mode)...) else if target == ':layer' # Discard this target for new layers, which don't have a first-swappable-element. # Also don't && the layer check into the `else if` condition above, or it will # be returned as a verbatim string below. unless layer == 'new' || layer.opening targets.unshift layer.getFirstSwappableElement() else if u.isElementish(target) expanded.push toTarget(target) else if u.isString(target) expanded.push resolveOriginReference(target, options) else # @buildPlans() might call us with { target: false } or { target: nil } # In that case we don't add a plan. return u.uniq(expanded) parseSelector = (selector, element, options = {}) -> filters = [] unless options.destroying filters.push(isNotDestroying) # Some up.fragment function center around an element, like closest() or matches(). options.layer ||= element layers = up.layer.getAll(options) if options.layer != 'any' && !(element && e.isDetached(element)) filters.push (match) -> u.some layers, (layer) -> layer.contains(match) expandedTargets = up.fragment.expandTargets(selector, u.merge(options, layer: layers[0])) expandedTargets = expandedTargets.map (target) -> target = target.replace CSS_HAS_SUFFIX_PATTERN, (match, descendantSelector) -> filters.push (element) -> element.querySelector(descendantSelector) return '' return target || '*' return new up.Selector(expandedTargets, filters) hasAutoHistory = (fragment) -> if contains(fragment, config.autoHistoryTargets) true else up.puts('up.render()', "Will not auto-update history because fragment doesn't contain a selector from up.fragment.config.autoHistoryTargets") false ###** A pseudo-selector that matches the layer's main target. Main targets are default render targets. When no other render target is given, Unpoly will try to find and replace a main target. In most app layouts the main target should match the primary content area. The default main targets are: - any element with an `[up-main]` attribute - the HTML5 [`<main>`](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/main) element - the current layer's [topmost swappable element](/layer) You may configure main target selectors in `up.fragment.config.mainTargets`. \#\#\# Example ```js up.render(':main', { url: '/page2' }) ``` @selector :main @experimental ### ###** Updates this element when no other render target is given. \#\#\# Example Many links simply replace the main content element in your application layout. Unpoly lets you mark this elements as a default target using the `[up-main]` attribute: ```html <body> <div class="layout"> <div class="layout--side"> ... </div> <div class="layout--content" up-main> ... </div> </div> </body> ``` Once a main target is configured, you no longer need `[up-target]` in a link.\ Use `[up-follow]` and the `[up-main]` element will be replaced: ```html <a href="/foo" up-follow>...</a> ``` If you want to update something more specific, you can still use `[up-target]`: ```html <a href="/foo" up-target=".profile">...</a> ``` Instead of assigning `[up-main]` you may also configure an existing selector in `up.fragment.config.mainTargets`: ```js up.fragment.config.mainTargets.push('.layout--content') ``` Overlays can use different main targets --------------------------------------- Overlays often use a different default selector, e.g. to exclude a navigation bar. To define a different main target for an overlay, set the [layer mode](/layer-terminology) as the value of the `[up-main]` attribute: ```html <body> <div class="layout" up-main="root"> <div class="layout--side"> ... </div> <div class="layout--content" up-main="modal"> ... </div> </div> </body> ``` Instead of assigning `[up-main]` you may also configure layer-specific targets in `up.layer.config`: ```js up.layer.config.popup.mainTargets.push('.menu') // for popup overlays up.layer.config.drawer.mainTargets.push('.menu') // for drawer overlays up.layer.config.overlay.mainTargets.push('.layout--content') // for all overlay modes ``` @selector [up-main] @param [up-main] A space-separated list of [layer modes](/layer-terminology) for which to use this main target. Omit the attribute value to define a main target for *all* layer modes. To use a different main target for all overlays (but not the root layer), set `[up-main=overlay]`. @stable ### ###** To make a server request without changing a fragment, use the `:none` selector. \#\#\# Example ```html <a href="/ping" up-target=":none">Ping server</a> ``` @selector :none @experimental ### ###** Your target selectors may use this pseudo-selector to reference the element that triggered the change. The origin element is automatically set to a link that is being [followed](/a-up-follow) or form that is being [submitted](/form-up-submit). When updating fragments programmatically through `up.render()` you may pass an origin element as an `{ origin }` option. Even without using an `:origin` reference, the [origin is considered](/fragment-placement#interaction-origin-is-considered) when matching fragments in the current page. \#\#\# Shorthand Instead of `:origin` you may also use the ampersand character (`&`). You may be familiar with the ampersand from the [Sass](https://sass-lang.com/documentation/file.SASS_REFERENCE.html#parent-selector) CSS preprocessor. @selector :origin @experimental ### ###** Your target selectors may use this pseudo-selector to replace the layer's topmost swappable element. The topmost swappable element is the first child of the layer's container element. For the [root layer](/up.layer.root) it is the `<body>` element. For an overlay it is the target with which the overlay was opened with. In canonical usage the topmost swappable element is often a [main element](/up-main). \#\#\# Example The following will replace the `<body>` element in the root layer, and the topmost swappable element in an overlay: ```js up.render(':layer', { url: '/page2' }) ``` @selector :layer @experimental ### ###** Returns whether the given element matches the given CSS selector. Other than `up.element.matches()` this function supports non-standard selectors like `:main` or `:layer`. @function up.fragment.matches @param {Element} fragment @param {string|Array<string>} selectorOrSelectors @param {string|up.Layer} options.layer The layer for which to match. Pseudo-selectors like `:main` may expand to different selectors in different layers. @param {string|up.Layer} options.mode Required if `{ layer: 'new' }` is passed. @return {boolean} @experimental ### matches = (element, selector, options = {}) -> element = e.get(element) selector = parseSelector(selector, element, options) return selector.matches(element) up.on 'up:app:boot', -> body = document.body body.setAttribute('up-source', up.history.location) hello(body) unless up.browser.canPushState() up.warn('Cannot push history changes. Next fragment update will load in a new page.') up.on 'up:framework:reset', reset u.literal config: config reload: reload destroy: destroy render: render navigate: navigate get: getSmart getDumb: getDumb all: getAll subtree: getSubtree contains: contains closest: closest source: sourceOf hello: hello visit: visit markAsDestroying: markFragmentAsDestroying emitInserted: emitFragmentInserted emitDestroyed: emitFragmentDestroyed emitKeep: emitFragmentKeep emitKept: emitFragmentKept successKey: successKey, failKey: failKey expandTargets: expandTargets toTarget: toTarget matches: matches hasAutoHistory: hasAutoHistory up.replace = up.fragment.replace up.extract = up.fragment.extract up.reload = up.fragment.reload up.destroy = up.fragment.destroy up.render = up.fragment.render up.navigate = up.fragment.navigate up.hello = up.fragment.hello up.visit = up.fragment.visit ###** Returns the current [context](/context). This is aliased as `up.layer.context`. @property up.context @param {Object} context The context object. If no context has been set an empty object is returned. @experimental ### u.delegate up, 'context', -> up.layer.current
[ { "context": "-----------\n# Copyright IBM Corp. 2014\n# Copyright Patrick Mueller 2015, 2017\n#\n# Licensed under the Apache License,", "end": 6518, "score": 0.9997864961624146, "start": 6503, "tag": "NAME", "value": "Patrick Mueller" } ]
lib-src/cfenv.coffee
smg-bg/node-cfenv
0
# Licensed under the Apache License. See footer for details. fs = require "fs" URL = require "url" pkg = require "../package.json" _ = require "underscore" ports = require "ports" yaml = require "js-yaml" #------------------------------------------------------------------------------- # properties on the cfenv object will be the module exports #------------------------------------------------------------------------------- cfenv = exports #------------------------------------------------------------------------------- cfenv.getAppEnv = (options={}) -> return new AppEnv options #------------------------------------------------------------------------------- class AppEnv #----------------------------------------------------------------------------- constructor: (options = {}) -> @isLocal = not process.env.VCAP_APPLICATION? unless @isLocal try JSON.parse process.env.VCAP_APPLICATION catch @isLocal = true @_getVcapFromFile(options) if @isLocal @app = getApp @, options @services = getServices @, options @name = getName @, options @port = getPort @ @bind = getBind @ @urls = getURLs @, options @url = @urls[0] #----------------------------------------------------------------------------- _getVcapFromFile: (options) -> return if not options?.vcapFile contents = null try contents = fs.readFileSync options.vcapFile, 'utf8' catch err console.log "error reading vcapFile '#{options.vcapFile}': #{err}; ignoring" return vcap = null try vcap = JSON.parse contents catch err console.log "error parsing vcapFile '#{options.vcapFile}': #{err}; ignoring" return options.vcap = vcap #----------------------------------------------------------------------------- toJSON: -> {@app, @services, @isLocal, @name, @port, @bind, @urls, @url} #----------------------------------------------------------------------------- getServices: -> result = {} for type, services of @services for service in services result[service.name] = service return result #----------------------------------------------------------------------------- getService: (spec) -> # set our matching function if _.isRegExp spec matches = (name) -> name.match spec else spec = "#{spec}" matches = (name) -> name is spec services = @getServices() for name, service of services if matches name return service # no matches return null #----------------------------------------------------------------------------- getServiceURL: (spec, replacements={}) -> service = @getService spec credentials = service?.credentials return null unless credentials? replacements = _.clone replacements if replacements.url url = credentials[replacements.url] else url = credentials.url || credentials.uri return null unless url? delete replacements.url return url if _.isEmpty replacements purl = URL.parse url for key, value of replacements if key is "auth" [userid, password] = value purl[key] = "#{credentials[userid]}:#{credentials[password]}" else purl[key] = credentials[value] return URL.format purl #----------------------------------------------------------------------------- getServiceCreds: (spec) -> service = @getService spec return null unless service? return service.credentials || {} #------------------------------------------------------------------------------- getApp = (appEnv, options) -> string = process.env.VCAP_APPLICATION envValue = {} if string? try envValue = JSON.parse string catch e throwError "env var VCAP_APPLICATION is not JSON: /#{string}/" return envValue unless appEnv.isLocal locValue = options?.vcap?.application return locValue if locValue? return envValue #------------------------------------------------------------------------------- getServices = (appEnv, options) -> string = process.env.VCAP_SERVICES envValue = {} if string? try envValue = JSON.parse string catch e throwError "env var VCAP_SERVICES is not JSON: /#{string}/" return envValue unless appEnv.isLocal locValue = options?.vcap?.services return locValue if locValue? return envValue #------------------------------------------------------------------------------- getPort = (appEnv) -> portString = process.env.PORT || process.env.CF_INSTANCE_PORT || process.env.VCAP_APP_PORT || appEnv?.app?.port unless portString? return 3000 unless appEnv.name? portString = "#{ports.getPort appEnv.name}" port = parseInt portString, 10 throwError "invalid PORT value: /#{portString}/" if isNaN port return port #------------------------------------------------------------------------------- getName = (appEnv, options) -> return options.name if options.name? val = appEnv.app?.name return val if val? if fs.existsSync "manifest.yml" yString = fs.readFileSync "manifest.yml", "utf8" yObject = yaml.safeLoad yString, filename: "manifest.yml" yObject = yObject.applications[0] if yObject.applications? return yObject.name if yObject.name? if fs.existsSync "package.json" pString = fs.readFileSync "package.json", "utf8" try pObject = JSON.parse pString catch pObject = null return pObject.name if pObject?.name return null #------------------------------------------------------------------------------- getBind = (appEnv) -> return appEnv.app?.host || "localhost" #------------------------------------------------------------------------------- getURLs = (appEnv, options) -> uris = appEnv.app?.uris if appEnv.isLocal uris = [ "localhost:#{appEnv.port}" ] else unless uris? uris = [ "localhost" ] protocol = options.protocol unless protocol? if appEnv.isLocal protocol = "http:" else protocol = "https:" urls = for uri in uris "#{protocol}//#{uri}" return urls #------------------------------------------------------------------------------- throwError = (message) -> message = "#{pkg.name}: #{message}" console.log "error: #{message}" throw new Error message #------------------------------------------------------------------------------- # Copyright IBM Corp. 2014 # Copyright Patrick Mueller 2015, 2017 # # 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. #-------------------------------------------------------------------------------
124190
# Licensed under the Apache License. See footer for details. fs = require "fs" URL = require "url" pkg = require "../package.json" _ = require "underscore" ports = require "ports" yaml = require "js-yaml" #------------------------------------------------------------------------------- # properties on the cfenv object will be the module exports #------------------------------------------------------------------------------- cfenv = exports #------------------------------------------------------------------------------- cfenv.getAppEnv = (options={}) -> return new AppEnv options #------------------------------------------------------------------------------- class AppEnv #----------------------------------------------------------------------------- constructor: (options = {}) -> @isLocal = not process.env.VCAP_APPLICATION? unless @isLocal try JSON.parse process.env.VCAP_APPLICATION catch @isLocal = true @_getVcapFromFile(options) if @isLocal @app = getApp @, options @services = getServices @, options @name = getName @, options @port = getPort @ @bind = getBind @ @urls = getURLs @, options @url = @urls[0] #----------------------------------------------------------------------------- _getVcapFromFile: (options) -> return if not options?.vcapFile contents = null try contents = fs.readFileSync options.vcapFile, 'utf8' catch err console.log "error reading vcapFile '#{options.vcapFile}': #{err}; ignoring" return vcap = null try vcap = JSON.parse contents catch err console.log "error parsing vcapFile '#{options.vcapFile}': #{err}; ignoring" return options.vcap = vcap #----------------------------------------------------------------------------- toJSON: -> {@app, @services, @isLocal, @name, @port, @bind, @urls, @url} #----------------------------------------------------------------------------- getServices: -> result = {} for type, services of @services for service in services result[service.name] = service return result #----------------------------------------------------------------------------- getService: (spec) -> # set our matching function if _.isRegExp spec matches = (name) -> name.match spec else spec = "#{spec}" matches = (name) -> name is spec services = @getServices() for name, service of services if matches name return service # no matches return null #----------------------------------------------------------------------------- getServiceURL: (spec, replacements={}) -> service = @getService spec credentials = service?.credentials return null unless credentials? replacements = _.clone replacements if replacements.url url = credentials[replacements.url] else url = credentials.url || credentials.uri return null unless url? delete replacements.url return url if _.isEmpty replacements purl = URL.parse url for key, value of replacements if key is "auth" [userid, password] = value purl[key] = "#{credentials[userid]}:#{credentials[password]}" else purl[key] = credentials[value] return URL.format purl #----------------------------------------------------------------------------- getServiceCreds: (spec) -> service = @getService spec return null unless service? return service.credentials || {} #------------------------------------------------------------------------------- getApp = (appEnv, options) -> string = process.env.VCAP_APPLICATION envValue = {} if string? try envValue = JSON.parse string catch e throwError "env var VCAP_APPLICATION is not JSON: /#{string}/" return envValue unless appEnv.isLocal locValue = options?.vcap?.application return locValue if locValue? return envValue #------------------------------------------------------------------------------- getServices = (appEnv, options) -> string = process.env.VCAP_SERVICES envValue = {} if string? try envValue = JSON.parse string catch e throwError "env var VCAP_SERVICES is not JSON: /#{string}/" return envValue unless appEnv.isLocal locValue = options?.vcap?.services return locValue if locValue? return envValue #------------------------------------------------------------------------------- getPort = (appEnv) -> portString = process.env.PORT || process.env.CF_INSTANCE_PORT || process.env.VCAP_APP_PORT || appEnv?.app?.port unless portString? return 3000 unless appEnv.name? portString = "#{ports.getPort appEnv.name}" port = parseInt portString, 10 throwError "invalid PORT value: /#{portString}/" if isNaN port return port #------------------------------------------------------------------------------- getName = (appEnv, options) -> return options.name if options.name? val = appEnv.app?.name return val if val? if fs.existsSync "manifest.yml" yString = fs.readFileSync "manifest.yml", "utf8" yObject = yaml.safeLoad yString, filename: "manifest.yml" yObject = yObject.applications[0] if yObject.applications? return yObject.name if yObject.name? if fs.existsSync "package.json" pString = fs.readFileSync "package.json", "utf8" try pObject = JSON.parse pString catch pObject = null return pObject.name if pObject?.name return null #------------------------------------------------------------------------------- getBind = (appEnv) -> return appEnv.app?.host || "localhost" #------------------------------------------------------------------------------- getURLs = (appEnv, options) -> uris = appEnv.app?.uris if appEnv.isLocal uris = [ "localhost:#{appEnv.port}" ] else unless uris? uris = [ "localhost" ] protocol = options.protocol unless protocol? if appEnv.isLocal protocol = "http:" else protocol = "https:" urls = for uri in uris "#{protocol}//#{uri}" return urls #------------------------------------------------------------------------------- throwError = (message) -> message = "#{pkg.name}: #{message}" console.log "error: #{message}" throw new Error message #------------------------------------------------------------------------------- # Copyright IBM Corp. 2014 # Copyright <NAME> 2015, 2017 # # 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. #-------------------------------------------------------------------------------
true
# Licensed under the Apache License. See footer for details. fs = require "fs" URL = require "url" pkg = require "../package.json" _ = require "underscore" ports = require "ports" yaml = require "js-yaml" #------------------------------------------------------------------------------- # properties on the cfenv object will be the module exports #------------------------------------------------------------------------------- cfenv = exports #------------------------------------------------------------------------------- cfenv.getAppEnv = (options={}) -> return new AppEnv options #------------------------------------------------------------------------------- class AppEnv #----------------------------------------------------------------------------- constructor: (options = {}) -> @isLocal = not process.env.VCAP_APPLICATION? unless @isLocal try JSON.parse process.env.VCAP_APPLICATION catch @isLocal = true @_getVcapFromFile(options) if @isLocal @app = getApp @, options @services = getServices @, options @name = getName @, options @port = getPort @ @bind = getBind @ @urls = getURLs @, options @url = @urls[0] #----------------------------------------------------------------------------- _getVcapFromFile: (options) -> return if not options?.vcapFile contents = null try contents = fs.readFileSync options.vcapFile, 'utf8' catch err console.log "error reading vcapFile '#{options.vcapFile}': #{err}; ignoring" return vcap = null try vcap = JSON.parse contents catch err console.log "error parsing vcapFile '#{options.vcapFile}': #{err}; ignoring" return options.vcap = vcap #----------------------------------------------------------------------------- toJSON: -> {@app, @services, @isLocal, @name, @port, @bind, @urls, @url} #----------------------------------------------------------------------------- getServices: -> result = {} for type, services of @services for service in services result[service.name] = service return result #----------------------------------------------------------------------------- getService: (spec) -> # set our matching function if _.isRegExp spec matches = (name) -> name.match spec else spec = "#{spec}" matches = (name) -> name is spec services = @getServices() for name, service of services if matches name return service # no matches return null #----------------------------------------------------------------------------- getServiceURL: (spec, replacements={}) -> service = @getService spec credentials = service?.credentials return null unless credentials? replacements = _.clone replacements if replacements.url url = credentials[replacements.url] else url = credentials.url || credentials.uri return null unless url? delete replacements.url return url if _.isEmpty replacements purl = URL.parse url for key, value of replacements if key is "auth" [userid, password] = value purl[key] = "#{credentials[userid]}:#{credentials[password]}" else purl[key] = credentials[value] return URL.format purl #----------------------------------------------------------------------------- getServiceCreds: (spec) -> service = @getService spec return null unless service? return service.credentials || {} #------------------------------------------------------------------------------- getApp = (appEnv, options) -> string = process.env.VCAP_APPLICATION envValue = {} if string? try envValue = JSON.parse string catch e throwError "env var VCAP_APPLICATION is not JSON: /#{string}/" return envValue unless appEnv.isLocal locValue = options?.vcap?.application return locValue if locValue? return envValue #------------------------------------------------------------------------------- getServices = (appEnv, options) -> string = process.env.VCAP_SERVICES envValue = {} if string? try envValue = JSON.parse string catch e throwError "env var VCAP_SERVICES is not JSON: /#{string}/" return envValue unless appEnv.isLocal locValue = options?.vcap?.services return locValue if locValue? return envValue #------------------------------------------------------------------------------- getPort = (appEnv) -> portString = process.env.PORT || process.env.CF_INSTANCE_PORT || process.env.VCAP_APP_PORT || appEnv?.app?.port unless portString? return 3000 unless appEnv.name? portString = "#{ports.getPort appEnv.name}" port = parseInt portString, 10 throwError "invalid PORT value: /#{portString}/" if isNaN port return port #------------------------------------------------------------------------------- getName = (appEnv, options) -> return options.name if options.name? val = appEnv.app?.name return val if val? if fs.existsSync "manifest.yml" yString = fs.readFileSync "manifest.yml", "utf8" yObject = yaml.safeLoad yString, filename: "manifest.yml" yObject = yObject.applications[0] if yObject.applications? return yObject.name if yObject.name? if fs.existsSync "package.json" pString = fs.readFileSync "package.json", "utf8" try pObject = JSON.parse pString catch pObject = null return pObject.name if pObject?.name return null #------------------------------------------------------------------------------- getBind = (appEnv) -> return appEnv.app?.host || "localhost" #------------------------------------------------------------------------------- getURLs = (appEnv, options) -> uris = appEnv.app?.uris if appEnv.isLocal uris = [ "localhost:#{appEnv.port}" ] else unless uris? uris = [ "localhost" ] protocol = options.protocol unless protocol? if appEnv.isLocal protocol = "http:" else protocol = "https:" urls = for uri in uris "#{protocol}//#{uri}" return urls #------------------------------------------------------------------------------- throwError = (message) -> message = "#{pkg.name}: #{message}" console.log "error: #{message}" throw new Error message #------------------------------------------------------------------------------- # Copyright IBM Corp. 2014 # Copyright PI:NAME:<NAME>END_PI 2015, 2017 # # 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. #-------------------------------------------------------------------------------
[ { "context": "://webservices.amazon.com/onca/xml?AWSAccessKeyId=AKIAJ7KOQXVZ5KAY36HQ&AssociateTag=tellico-20&ItemId=0124166903&Operati", "end": 828, "score": 0.9997066259384155, "start": 808, "tag": "KEY", "value": "AKIAJ7KOQXVZ5KAY36HQ" } ]
tests-src/domain/services/RequestSigner.coffee
sekko27/node-apa-api
0
Helper = require('wire-context-helper').Helper() APIMeta = require Helper.model('APIMeta') Credential = require Helper.model('Credential') Operations = require Helper.model('Operations') RequestFactory = require Helper.model('RequestFactory') Signer = require Helper.service('RequestSigner') credentialConfiguration = require Helper.path("configs/test-credentials") {assert} = require 'chai' describe 'RequestSigner', -> requestFactory = new RequestFactory(new APIMeta(), new Credential(credentialConfiguration)) signer = new Signer() it 'should sign requests properly', -> request = requestFactory.newInstance(Operations.ITEM_LOOKUP, {ItemId: '0124166903'}, {timestamp: '2014-10-31T13:26:16+01:00'}) assert.equal signer.sign(request), 'http://webservices.amazon.com/onca/xml?AWSAccessKeyId=AKIAJ7KOQXVZ5KAY36HQ&AssociateTag=tellico-20&ItemId=0124166903&Operation=ItemLookup&Service=AWSECommerceService&Timestamp=2014-10-31T13%3A26%3A16%2B01%3A00&Version=2011-08-01&Signature=ddB6fupAIcxKaXxhrkVFMPC0Kxd04TOANpXOvNRncwc%3D'
93642
Helper = require('wire-context-helper').Helper() APIMeta = require Helper.model('APIMeta') Credential = require Helper.model('Credential') Operations = require Helper.model('Operations') RequestFactory = require Helper.model('RequestFactory') Signer = require Helper.service('RequestSigner') credentialConfiguration = require Helper.path("configs/test-credentials") {assert} = require 'chai' describe 'RequestSigner', -> requestFactory = new RequestFactory(new APIMeta(), new Credential(credentialConfiguration)) signer = new Signer() it 'should sign requests properly', -> request = requestFactory.newInstance(Operations.ITEM_LOOKUP, {ItemId: '0124166903'}, {timestamp: '2014-10-31T13:26:16+01:00'}) assert.equal signer.sign(request), 'http://webservices.amazon.com/onca/xml?AWSAccessKeyId=<KEY>&AssociateTag=tellico-20&ItemId=0124166903&Operation=ItemLookup&Service=AWSECommerceService&Timestamp=2014-10-31T13%3A26%3A16%2B01%3A00&Version=2011-08-01&Signature=ddB6fupAIcxKaXxhrkVFMPC0Kxd04TOANpXOvNRncwc%3D'
true
Helper = require('wire-context-helper').Helper() APIMeta = require Helper.model('APIMeta') Credential = require Helper.model('Credential') Operations = require Helper.model('Operations') RequestFactory = require Helper.model('RequestFactory') Signer = require Helper.service('RequestSigner') credentialConfiguration = require Helper.path("configs/test-credentials") {assert} = require 'chai' describe 'RequestSigner', -> requestFactory = new RequestFactory(new APIMeta(), new Credential(credentialConfiguration)) signer = new Signer() it 'should sign requests properly', -> request = requestFactory.newInstance(Operations.ITEM_LOOKUP, {ItemId: '0124166903'}, {timestamp: '2014-10-31T13:26:16+01:00'}) assert.equal signer.sign(request), 'http://webservices.amazon.com/onca/xml?AWSAccessKeyId=PI:KEY:<KEY>END_PI&AssociateTag=tellico-20&ItemId=0124166903&Operation=ItemLookup&Service=AWSECommerceService&Timestamp=2014-10-31T13%3A26%3A16%2B01%3A00&Version=2011-08-01&Signature=ddB6fupAIcxKaXxhrkVFMPC0Kxd04TOANpXOvNRncwc%3D'
[ { "context": "rc', 'https://maps.googleapis.com/maps/api/js?key=AIzaSyApM4iQyAfb0hbmkeXc_zs58aA_Jy0SIac&callback=initMap')\n $head.append($script)\n\n\n ", "end": 568, "score": 0.9996939897537231, "start": 529, "tag": "KEY", "value": "AIzaSyApM4iQyAfb0hbmkeXc_zs58aA_Jy0SIac" } ]
coffee/main.coffee
coreytegeler/la-casita-verde
0
jQuery ($) -> $ -> $palette = $('#palette') window.palette = { light: '#f8f2e1', medium: '#707377', dark: '#2b1010', green: '#33eb74' } if($('#map').length) initMapApi() $('header .hover').mouseenter () -> $('header').addClass('hover') $('header .hover').mouseleave () -> $('header').removeClass('hover') initMapApi = () -> $head = $('head') $script = $('<script defer async></script>') $script.attr('src', 'https://maps.googleapis.com/maps/api/js?key=AIzaSyApM4iQyAfb0hbmkeXc_zs58aA_Jy0SIac&callback=initMap') $head.append($script) window.initMap = () -> mapStyle = new (google.maps.StyledMapType)([ { 'featureType': 'all' 'elementType': 'geometry.fill' 'stylers': [ { 'color': palette.light } ] } { 'featureType': 'all' 'elementType': 'geometry.stroke' 'stylers': [ { 'color': palette.dark } ] } { 'featureType': 'all' 'elementType': 'labels.text.fill' 'stylers': [ { 'color': palette.dark } ] } { 'featureType': 'all' 'elementType': 'labels.text.stroke' 'stylers': [ { 'color': palette.light } ] } { 'featureType': 'road.arterial' 'elementType': 'geometry.fill' 'stylers': [ { 'color': palette.dark } ] } { 'featureType': 'road.local' 'elementType': 'geometry.fill' 'stylers': [ { 'color': palette.dark } ] } { 'featureType': 'road.highway.controlled_access' 'elementType': 'geometry.fill' 'stylers': [ { 'color': palette.dark } ] } { 'featureType': 'transit.line' 'elementType': 'geometry.fill' 'stylers': [ { 'color': palette.dark } ] } { 'featureType': 'transit.line' 'elementType': 'geometry.stroke' 'stylers': [ { 'color': palette.medium } ] } { 'featureType': 'water' 'elementType': 'geometry.fill' 'stylers': [ { 'color': '#b3d1ff' } ] } ]) mapStyleId = 'green' map = undefined location = new (google.maps.LatLng)(40.707776, -73.9663237) map = new (google.maps.Map)(document.getElementById('map'), center: location zoom: 15 scrollwheel: false navigationControl: false mapTypeControl: false scaleControl: false mapTypeId: mapStyleId) map.mapTypes.set mapStyleId, mapStyle map.setMapTypeId mapStyleId marker = new (google.maps.Marker)( position: location title: 'ISCP' map: map icon: url: '/wp-content/themes/la-casita-verde/images/marker.svg' size: new google.maps.Size(70, 70) origin: new google.maps.Point(0, 0) anchor: new google.maps.Point(45, 40) ) google.maps.event.addDomListener window, 'resize', -> google.maps.event.trigger map, 'resize' map.setCenter location return return
1849
jQuery ($) -> $ -> $palette = $('#palette') window.palette = { light: '#f8f2e1', medium: '#707377', dark: '#2b1010', green: '#33eb74' } if($('#map').length) initMapApi() $('header .hover').mouseenter () -> $('header').addClass('hover') $('header .hover').mouseleave () -> $('header').removeClass('hover') initMapApi = () -> $head = $('head') $script = $('<script defer async></script>') $script.attr('src', 'https://maps.googleapis.com/maps/api/js?key=<KEY>&callback=initMap') $head.append($script) window.initMap = () -> mapStyle = new (google.maps.StyledMapType)([ { 'featureType': 'all' 'elementType': 'geometry.fill' 'stylers': [ { 'color': palette.light } ] } { 'featureType': 'all' 'elementType': 'geometry.stroke' 'stylers': [ { 'color': palette.dark } ] } { 'featureType': 'all' 'elementType': 'labels.text.fill' 'stylers': [ { 'color': palette.dark } ] } { 'featureType': 'all' 'elementType': 'labels.text.stroke' 'stylers': [ { 'color': palette.light } ] } { 'featureType': 'road.arterial' 'elementType': 'geometry.fill' 'stylers': [ { 'color': palette.dark } ] } { 'featureType': 'road.local' 'elementType': 'geometry.fill' 'stylers': [ { 'color': palette.dark } ] } { 'featureType': 'road.highway.controlled_access' 'elementType': 'geometry.fill' 'stylers': [ { 'color': palette.dark } ] } { 'featureType': 'transit.line' 'elementType': 'geometry.fill' 'stylers': [ { 'color': palette.dark } ] } { 'featureType': 'transit.line' 'elementType': 'geometry.stroke' 'stylers': [ { 'color': palette.medium } ] } { 'featureType': 'water' 'elementType': 'geometry.fill' 'stylers': [ { 'color': '#b3d1ff' } ] } ]) mapStyleId = 'green' map = undefined location = new (google.maps.LatLng)(40.707776, -73.9663237) map = new (google.maps.Map)(document.getElementById('map'), center: location zoom: 15 scrollwheel: false navigationControl: false mapTypeControl: false scaleControl: false mapTypeId: mapStyleId) map.mapTypes.set mapStyleId, mapStyle map.setMapTypeId mapStyleId marker = new (google.maps.Marker)( position: location title: 'ISCP' map: map icon: url: '/wp-content/themes/la-casita-verde/images/marker.svg' size: new google.maps.Size(70, 70) origin: new google.maps.Point(0, 0) anchor: new google.maps.Point(45, 40) ) google.maps.event.addDomListener window, 'resize', -> google.maps.event.trigger map, 'resize' map.setCenter location return return
true
jQuery ($) -> $ -> $palette = $('#palette') window.palette = { light: '#f8f2e1', medium: '#707377', dark: '#2b1010', green: '#33eb74' } if($('#map').length) initMapApi() $('header .hover').mouseenter () -> $('header').addClass('hover') $('header .hover').mouseleave () -> $('header').removeClass('hover') initMapApi = () -> $head = $('head') $script = $('<script defer async></script>') $script.attr('src', 'https://maps.googleapis.com/maps/api/js?key=PI:KEY:<KEY>END_PI&callback=initMap') $head.append($script) window.initMap = () -> mapStyle = new (google.maps.StyledMapType)([ { 'featureType': 'all' 'elementType': 'geometry.fill' 'stylers': [ { 'color': palette.light } ] } { 'featureType': 'all' 'elementType': 'geometry.stroke' 'stylers': [ { 'color': palette.dark } ] } { 'featureType': 'all' 'elementType': 'labels.text.fill' 'stylers': [ { 'color': palette.dark } ] } { 'featureType': 'all' 'elementType': 'labels.text.stroke' 'stylers': [ { 'color': palette.light } ] } { 'featureType': 'road.arterial' 'elementType': 'geometry.fill' 'stylers': [ { 'color': palette.dark } ] } { 'featureType': 'road.local' 'elementType': 'geometry.fill' 'stylers': [ { 'color': palette.dark } ] } { 'featureType': 'road.highway.controlled_access' 'elementType': 'geometry.fill' 'stylers': [ { 'color': palette.dark } ] } { 'featureType': 'transit.line' 'elementType': 'geometry.fill' 'stylers': [ { 'color': palette.dark } ] } { 'featureType': 'transit.line' 'elementType': 'geometry.stroke' 'stylers': [ { 'color': palette.medium } ] } { 'featureType': 'water' 'elementType': 'geometry.fill' 'stylers': [ { 'color': '#b3d1ff' } ] } ]) mapStyleId = 'green' map = undefined location = new (google.maps.LatLng)(40.707776, -73.9663237) map = new (google.maps.Map)(document.getElementById('map'), center: location zoom: 15 scrollwheel: false navigationControl: false mapTypeControl: false scaleControl: false mapTypeId: mapStyleId) map.mapTypes.set mapStyleId, mapStyle map.setMapTypeId mapStyleId marker = new (google.maps.Marker)( position: location title: 'ISCP' map: map icon: url: '/wp-content/themes/la-casita-verde/images/marker.svg' size: new google.maps.Size(70, 70) origin: new google.maps.Point(0, 0) anchor: new google.maps.Point(45, 40) ) google.maps.event.addDomListener window, 'resize', -> google.maps.event.trigger map, 'resize' map.setCenter location return return
[ { "context": "userId\n # info {\"proto\":\"baidu|otask\",\"token\":\"4421797412868072244_1021458100439220363\",\"updated\":1405307999,\"created\":1405072050}\n s", "end": 630, "score": 0.6650103330612183, "start": 591, "tag": "KEY", "value": "4421797412868072244_1021458100439220363" }, { "context": " message_type: 1,\n msg_keys: JSON.stringify([now]),\n messages: JSON.stringify({\n ", "end": 2082, "score": 0.7680214643478394, "start": 2073, "tag": "KEY", "value": "stringify" } ]
lib/pushservices/baidu.coffee
steedos/opush
0
BCM = require 'baidu-push-sdk' class PushServiceBaidu tokenFormat: /^[0-9_]+$/ validateToken: (token) -> @logger.info "token: " + token if PushServiceBaidu::tokenFormat.test(token) return token.toLowerCase() constructor: (conf, @logger, tokenResolver) -> @logger.verbose "api_key: " + conf.api_key @logger.verbose "secret_key: " + conf.secret_key opt = ak: conf.api_key sk: conf.secret_key @bcm = new BCM(opt) push: (subscriber, subOptions, payload) -> # token的格式: channelId + "_" + userId # info {"proto":"baidu|otask","token":"4421797412868072244_1021458100439220363","updated":1405307999,"created":1405072050} subscriber.get (info) => @logger.info "Baidu push: " + JSON.stringify(info) messageCallback = (err, result) => @logger.verbose "Baidu push message callback: " + err @logger.verbose "Baidu push message callback: " + JSON.stringify(result) notifCallback = (err, result) => @logger.verbose "Baidu push notification callback: " + err @logger.verbose "Baidu push notification callback: " + JSON.stringify(result) ts = info.token.split("_") now = new Date now = now.getTime() + "" # 标题 tle = payload.title.default || "" # 内容 msg = payload.msg.default || "" # 去掉换行符 msg = msg.replace(/\n/g, "") @logger.info "Baidu push title: " + tle @logger.info "Baidu push description: " + msg @logger.info "Baidu push badge: " + payload.badge # 发送推送消息 @bcm.pushMsg({ push_type: 1, device_type: 4, user_id: ts[1], channel_id: ts[0], message_type: 0, msg_keys: JSON.stringify([now]), messages: JSON.stringify({ badge: payload.badge }), }, messageCallback) # 如果内容和标题都存在时,发送通知 if (msg != "" && tle != "") @bcm.pushMsg({ push_type: 1, device_type: 4, user_id: ts[1], channel_id: ts[0], message_type: 1, msg_keys: JSON.stringify([now]), messages: JSON.stringify({ title: tle, description: msg, notification_basic_style: 7, open_type: 2, custom_content: { badge: payload.badge } }) }, notifCallback) exports.PushServiceBaidu = PushServiceBaidu
58583
BCM = require 'baidu-push-sdk' class PushServiceBaidu tokenFormat: /^[0-9_]+$/ validateToken: (token) -> @logger.info "token: " + token if PushServiceBaidu::tokenFormat.test(token) return token.toLowerCase() constructor: (conf, @logger, tokenResolver) -> @logger.verbose "api_key: " + conf.api_key @logger.verbose "secret_key: " + conf.secret_key opt = ak: conf.api_key sk: conf.secret_key @bcm = new BCM(opt) push: (subscriber, subOptions, payload) -> # token的格式: channelId + "_" + userId # info {"proto":"baidu|otask","token":"<KEY>","updated":1405307999,"created":1405072050} subscriber.get (info) => @logger.info "Baidu push: " + JSON.stringify(info) messageCallback = (err, result) => @logger.verbose "Baidu push message callback: " + err @logger.verbose "Baidu push message callback: " + JSON.stringify(result) notifCallback = (err, result) => @logger.verbose "Baidu push notification callback: " + err @logger.verbose "Baidu push notification callback: " + JSON.stringify(result) ts = info.token.split("_") now = new Date now = now.getTime() + "" # 标题 tle = payload.title.default || "" # 内容 msg = payload.msg.default || "" # 去掉换行符 msg = msg.replace(/\n/g, "") @logger.info "Baidu push title: " + tle @logger.info "Baidu push description: " + msg @logger.info "Baidu push badge: " + payload.badge # 发送推送消息 @bcm.pushMsg({ push_type: 1, device_type: 4, user_id: ts[1], channel_id: ts[0], message_type: 0, msg_keys: JSON.stringify([now]), messages: JSON.stringify({ badge: payload.badge }), }, messageCallback) # 如果内容和标题都存在时,发送通知 if (msg != "" && tle != "") @bcm.pushMsg({ push_type: 1, device_type: 4, user_id: ts[1], channel_id: ts[0], message_type: 1, msg_keys: JSON.<KEY>([now]), messages: JSON.stringify({ title: tle, description: msg, notification_basic_style: 7, open_type: 2, custom_content: { badge: payload.badge } }) }, notifCallback) exports.PushServiceBaidu = PushServiceBaidu
true
BCM = require 'baidu-push-sdk' class PushServiceBaidu tokenFormat: /^[0-9_]+$/ validateToken: (token) -> @logger.info "token: " + token if PushServiceBaidu::tokenFormat.test(token) return token.toLowerCase() constructor: (conf, @logger, tokenResolver) -> @logger.verbose "api_key: " + conf.api_key @logger.verbose "secret_key: " + conf.secret_key opt = ak: conf.api_key sk: conf.secret_key @bcm = new BCM(opt) push: (subscriber, subOptions, payload) -> # token的格式: channelId + "_" + userId # info {"proto":"baidu|otask","token":"PI:KEY:<KEY>END_PI","updated":1405307999,"created":1405072050} subscriber.get (info) => @logger.info "Baidu push: " + JSON.stringify(info) messageCallback = (err, result) => @logger.verbose "Baidu push message callback: " + err @logger.verbose "Baidu push message callback: " + JSON.stringify(result) notifCallback = (err, result) => @logger.verbose "Baidu push notification callback: " + err @logger.verbose "Baidu push notification callback: " + JSON.stringify(result) ts = info.token.split("_") now = new Date now = now.getTime() + "" # 标题 tle = payload.title.default || "" # 内容 msg = payload.msg.default || "" # 去掉换行符 msg = msg.replace(/\n/g, "") @logger.info "Baidu push title: " + tle @logger.info "Baidu push description: " + msg @logger.info "Baidu push badge: " + payload.badge # 发送推送消息 @bcm.pushMsg({ push_type: 1, device_type: 4, user_id: ts[1], channel_id: ts[0], message_type: 0, msg_keys: JSON.stringify([now]), messages: JSON.stringify({ badge: payload.badge }), }, messageCallback) # 如果内容和标题都存在时,发送通知 if (msg != "" && tle != "") @bcm.pushMsg({ push_type: 1, device_type: 4, user_id: ts[1], channel_id: ts[0], message_type: 1, msg_keys: JSON.PI:KEY:<KEY>END_PI([now]), messages: JSON.stringify({ title: tle, description: msg, notification_basic_style: 7, open_type: 2, custom_content: { badge: payload.badge } }) }, notifCallback) exports.PushServiceBaidu = PushServiceBaidu
[ { "context": "Fixtures =\n email: \"test@test.test\"\n password: \"password\"\n accountToken: \"6HKYAJCR", "end": 35, "score": 0.9999052286148071, "start": 21, "tag": "EMAIL", "value": "test@test.test" }, { "context": "Fixtures =\n email: \"test@test.test\"\n password: \"password\"\n accountToken: \"6HKYAJCR7XKUGKR6HOHY42BN36GK3RB", "end": 58, "score": 0.9992890357971191, "start": 50, "tag": "PASSWORD", "value": "password" }, { "context": "est.test\"\n password: \"password\"\n accountToken: \"6HKYAJCR7XKUGKR6HOHY42BN36GK3RBLG6VUP3YVQ7UZHTUNLIXA====\"\n\n`export default Fixtures`", "end": 134, "score": 0.9964873194694519, "start": 77, "tag": "KEY", "value": "6HKYAJCR7XKUGKR6HOHY42BN36GK3RBLG6VUP3YVQ7UZHTUNLIXA====\"" } ]
tests/helpers/fixtures.coffee
simwms/simwms-shared
0
Fixtures = email: "test@test.test" password: "password" accountToken: "6HKYAJCR7XKUGKR6HOHY42BN36GK3RBLG6VUP3YVQ7UZHTUNLIXA====" `export default Fixtures`
98243
Fixtures = email: "<EMAIL>" password: "<PASSWORD>" accountToken: "<KEY> `export default Fixtures`
true
Fixtures = email: "PI:EMAIL:<EMAIL>END_PI" password: "PI:PASSWORD:<PASSWORD>END_PI" accountToken: "PI:KEY:<KEY>END_PI `export default Fixtures`
[ { "context": "1\n\n renderStepList: (step, i) ->\n step._key ?= Math.random()\n buttonClasses = classnames\n \"selected\"", "end": 3052, "score": 0.9558928608894348, "start": 3041, "tag": "KEY", "value": "Math.random" }, { "context": " <ProjectModalEditorController\n key={projectModal.id}\n project={@props.project}\n ", "end": 12106, "score": 0.8493293523788452, "start": 12091, "tag": "KEY", "value": "projectModal.id" } ]
app/partials/project-modal-editor.cjsx
tlalka/Panoptes-Front-End
0
React = require 'react' createReactClass = require 'create-react-class' apiClient = require 'panoptes-client/lib/api-client' putFile = require '../lib/put-file' FileButton = require '../components/file-button' {MarkdownEditor, MarkdownHelp} = require 'markdownz' debounce = require 'debounce' DragReorderable = require 'drag-reorderable' classnames = require 'classnames' AutoSave = require '../components/auto-save' handleInputChange = require '../lib/handle-input-change' alert = require('../lib/alert').default confirm = require('../lib/confirm').default ProjectModalStepEditor = createReactClass getDefaultProps: -> step: null media: null onChange: -> console.log 'ProjectModalStepEditor onChange', arguments onMediaSelect: -> console.log 'ProjectModalStepEditor onMediaSelect', arguments onMediaClear: -> console.log 'ProjectModalStepEditor onMediaClear', arguments render: -> <div className="project-modal-step-editor"> <p> {if @props.media? <span> <img className="project-modal-step-editor-media" src={@props.media.src} />{' '} <button type="button" className="minor-button" onClick={@props.onMediaClear}>Clear</button> </span>}{' '} <FileButton className="standard-button" onSelect={@handleMediaChange}>Select media</FileButton> </p> <div> <MarkdownEditor className="full" value={@props.step.content} onChange={@handleContentChange} onHelp={-> alert <MarkdownHelp/>} /> </div> </div> handleMediaChange: (e) -> @props.onMediaSelect e.target.files[0], arguments... handleContentChange: (e) -> @props.onChange 'content', e.target.value, arguments... ProjectModalEditor = createReactClass getDefaultProps: -> projectModal: null media: null kind: null onStepAdd: -> console.log 'ProjectModalEditor onStepAdd', arguments onStepRemove: -> console.log 'ProjectModalEditor onStepRemove', arguments onMediaSelect: -> console.log 'ProjectModalEditor onMediaSelect', arguments onStepChange: -> console.log 'ProjectModalEditor onChange', arguments onStepOrderChange: -> console.log 'ProjectModalEditor onStepOrderChange', arguments getInitialState: -> stepToEdit: 0 onClick: (stepIndex) -> @setState stepToEdit: stepIndex handleStepRemove: (stepToRemove) -> if @props.projectModal.steps.length is 0 stepIndex = null else stepIndex = 0 @setState { stepToEdit: stepIndex }, -> @props.onStepRemove stepToRemove handleStepReorder: (stepsInNewOrder) -> stepReorderedIndex = null for step, index in stepsInNewOrder stepReorderedIndex = index if @props.projectModal.steps[@state.stepToEdit].content is step.content @props.onStepOrderChange stepsInNewOrder @setState stepToEdit: stepReorderedIndex handleStepAdd: -> @props.onStepAdd() @setState stepToEdit: @props.projectModal.steps.length - 1 renderStepList: (step, i) -> step._key ?= Math.random() buttonClasses = classnames "selected": @state.stepToEdit is i "project-modal-step-list-item-button": true <li key={step._key} className="project-modal-step-list-item"> <button type="button" className={buttonClasses} onClick={@onClick.bind null, i}> <span className="project-modal-step-list-item-button-title">Step #{i + 1}</span> </button> <button type="button" className="project-modal-step-list-item-remove-button" title="Remove this step" onClick={@handleStepRemove.bind null, i}> <i className="fa fa-trash-o fa-fw"></i> </button> </li> render: -> <div className="project-modal-editor"> <div className="project-modal-header"> <AutoSave tag="label" resource={@props.projectModal}> <span className="form-label">{@props.kind} #{@props.projectModal.id}</span> <br /> <input type="text" name="display_name" value={@props.projectModal.display_name} className="standard-input full" onChange={handleInputChange.bind @props.projectModal} /> </AutoSave> <p><button className="pill-button" onClick={@props.onProjectModalDelete}>Delete {@props.kind}</button></p> </div> {if @props.projectModal.steps.length is 0 <p>This {@props.kind} has no steps.</p> else <div className="project-modal-step-editor-container"> <DragReorderable tag="ul" className="project-modal-step-list" items={@props.projectModal.steps} render={@renderStepList} onChange={@handleStepReorder} /> <ProjectModalStepEditor step={@props.projectModal.steps[@state.stepToEdit]} media={@props.media?[@props.projectModal.steps[@state.stepToEdit].media]} onMediaSelect={@props.onMediaSelect.bind null, @state.stepToEdit} onMediaClear={@props.onMediaClear.bind null, @state.stepToEdit} onChange={@props.onStepChange.bind null, @state.stepToEdit} /> </div>} <div> <button type="button" onClick={@handleStepAdd}>Add a step</button> </div> </div> ProjectModalEditorController = createReactClass displayName: 'ProjectModalEditorController' getInitialState: -> media: {} getDefaultProps: -> project: null projectModal: null delayBeforeSave: 5000 kind: null onDelete: -> console.log 'ProjectModalEditorController onDelete', arguments componentDidMount: -> @_boundForceUpdate = @forceUpdate.bind this @props.projectModal.listen @_boundForceUpdate @fetchMediaFor(@props.projectModal) componentWillUnmount: -> @props.projectModal.stopListening @_boundForceUpdate fetchMediaFor: (projectModal) -> if projectModal? projectModal.get 'attached_images', {} # Prevent caching. .catch => [] # We get an an error if there're no attached images. .then (mediaResources) => media = {} for mediaResource in mediaResources media[mediaResource.id] = mediaResource @setState {media} else @setState media: {} render: -> <div> <hr /> <ProjectModalEditor projectModal={@props.projectModal} media={@state.media} kind={@props.kind} onStepAdd={@handleStepAdd} onStepRemove={@confirmStepRemove} onMediaSelect={@handleStepMediaChange} onMediaClear={@handleStepMediaClear} onStepChange={@handleStepChange} onStepOrderChange={@handleStepOrderChange} onProjectModalDelete={@confirmProjectModalDelete} /> </div> deleteProjectModal: -> @props.projectModal.delete() .then => @props.onDelete() handleProjectModalDelete: -> if @props.projectModal.steps.length > 0 for step in @props.projectModal.steps # Always pass in first index into step remove, because step deletion changes length # i.e. index 3 will be undefined in an originally 4 item length array after first is deleted # but iterate through the length of the original step array. @handleStepRemove(0) else @deleteProjectModal() confirmProjectModalDelete: -> message = "Are you sure you want to delete this tutorial? This action is irreversible!" successCallback = @handleProjectModalDelete confirm(message, successCallback) handleStepAdd: -> @props.projectModal.steps.push media: '' content: '' @props.projectModal.update 'steps' @props.projectModal.save() confirmStepRemove: (index) -> message = "Are you sure you want to delete this step? This action is irreversible!" confirm(message, () => @handleStepRemove(index)) handleStepRemove: (index) -> @handleStepMediaClear index changes = {} changes["steps.#{index}"] = undefined @props.projectModal.update changes if @props.projectModal.steps.length is 0 @deleteProjectModal() else @props.projectModal.save() handleStepMediaChange: (index, file) -> @handleStepMediaClear index payload = media: content_type: file.type metadata: filename: file.name apiClient.post @props.projectModal._getURL('attached_images'), payload .then (media) => media = [].concat(media)[0] putFile media.src, file, {'Content-Type': file.type} .then => changes = {} changes["steps.#{index}.media"] = media.id @props.projectModal.update changes @props.projectModal.save() .then => @fetchMediaFor @props.projectModal .catch (error) => console.error error handleStepMediaClear: (index) -> @state.media[@props.projectModal.steps[index].media]?.delete() changes = {} changes["steps.#{index}.media"] = undefined @props.projectModal.update changes @props.projectModal.save() handleStepChange: (index, key, value) -> changes = {} changes["steps.#{index}.#{key}"] = value @props.projectModal.update changes @saveProjectModal() handleStepOrderChange: (stepsInNewOrder) -> @props.projectModal.update steps: stepsInNewOrder @saveProjectModal() saveProjectModal: -> unless @_debouncedSaveProjectModal? boundProjectModalSave = @props.projectModal.save.bind @props.projectModal @_debouncedSaveProjectModal = debounce boundProjectModalSave, @props.delayBeforeSave @_debouncedSaveProjectModal arguments... ProjectModalCreator = createReactClass getDefaultProps: -> project: null kind: null onCreate: -> console.log 'ProjectModalCreator onCreate', arguments getInitialState: -> error: null render: -> <div> {if @state.error? <p>{@state.error.toString()}</p>} <p> <button type="button" onClick={@handleCreateClick}>Build a {@props.kind}</button> </p> </div> handleCreateClick: -> projectModalData = steps: [] language: 'en' kind: @props.kind links: project: @props.project.id display_name: "new #{@props.kind} title" @setState error: null apiClient.type('tutorials').create(projectModalData).save() .then (createdProjectModal) => @props.onCreate createdProjectModal .catch (error) => @setState {error} ProjectModalEditorFetcher = createReactClass getDefaultProps: -> project: null kind: null getInitialState: -> loading: false error: null projectModals: null media: {} componentDidMount: -> @_boundForceUpdate = @forceUpdate.bind this @props.project.listen @_boundForceUpdate @fetchProjectModalsFor @props.project componentWillUnmount: -> @props.project.stopListening @_boundForceUpdate componentWillReceiveProps: (nextProps) -> unless nextProps.project is @props.project @props.project.stopListening @_boundForceUpdate nextProps.project.listen @_boundForceUpdate @fetchProjectModalsFor nextProps.project fetchProjectModalsFor: (project) -> @setState loading: true error: null projectModals: null apiClient.type('tutorials').get project_id: project.id .then (projectModals) => filteredProjectModals = if @props.kind is "tutorial" projectModal for projectModal in projectModals when projectModal.kind is @props.kind or projectModal.kind is null else if @props.kind is "mini-course" projectModal for projectModal in projectModals when projectModal.kind is @props.kind @setState {projectModals: filteredProjectModals} .catch (error) => @setState {error} .then => @setState loading: false render: -> if @state.loading <p>Loading...</p> else if @state.error? <p>{@state.error.toString()}</p> else if @state.projectModals? window?.editingProjectModals = @state.projectModals <div> {for projectModal in @state.projectModals <ProjectModalEditorController key={projectModal.id} project={@props.project} projectModal={projectModal} media={@state.media} kind={@props.kind} onDelete={@handleProjectModalCreateOrDelete} />} <hr /> <ProjectModalCreator project={@props.project} kind={@props.kind} onCreate={@handleProjectModalCreateOrDelete} /> </div> else <ProjectModalCreator project={@props.project} kind={@props.kind} onCreate={@handleProjectModalCreateOrDelete} /> handleProjectModalCreateOrDelete: -> @fetchProjectModalsFor @props.project module.exports = ProjectModalEditorFetcher
225702
React = require 'react' createReactClass = require 'create-react-class' apiClient = require 'panoptes-client/lib/api-client' putFile = require '../lib/put-file' FileButton = require '../components/file-button' {MarkdownEditor, MarkdownHelp} = require 'markdownz' debounce = require 'debounce' DragReorderable = require 'drag-reorderable' classnames = require 'classnames' AutoSave = require '../components/auto-save' handleInputChange = require '../lib/handle-input-change' alert = require('../lib/alert').default confirm = require('../lib/confirm').default ProjectModalStepEditor = createReactClass getDefaultProps: -> step: null media: null onChange: -> console.log 'ProjectModalStepEditor onChange', arguments onMediaSelect: -> console.log 'ProjectModalStepEditor onMediaSelect', arguments onMediaClear: -> console.log 'ProjectModalStepEditor onMediaClear', arguments render: -> <div className="project-modal-step-editor"> <p> {if @props.media? <span> <img className="project-modal-step-editor-media" src={@props.media.src} />{' '} <button type="button" className="minor-button" onClick={@props.onMediaClear}>Clear</button> </span>}{' '} <FileButton className="standard-button" onSelect={@handleMediaChange}>Select media</FileButton> </p> <div> <MarkdownEditor className="full" value={@props.step.content} onChange={@handleContentChange} onHelp={-> alert <MarkdownHelp/>} /> </div> </div> handleMediaChange: (e) -> @props.onMediaSelect e.target.files[0], arguments... handleContentChange: (e) -> @props.onChange 'content', e.target.value, arguments... ProjectModalEditor = createReactClass getDefaultProps: -> projectModal: null media: null kind: null onStepAdd: -> console.log 'ProjectModalEditor onStepAdd', arguments onStepRemove: -> console.log 'ProjectModalEditor onStepRemove', arguments onMediaSelect: -> console.log 'ProjectModalEditor onMediaSelect', arguments onStepChange: -> console.log 'ProjectModalEditor onChange', arguments onStepOrderChange: -> console.log 'ProjectModalEditor onStepOrderChange', arguments getInitialState: -> stepToEdit: 0 onClick: (stepIndex) -> @setState stepToEdit: stepIndex handleStepRemove: (stepToRemove) -> if @props.projectModal.steps.length is 0 stepIndex = null else stepIndex = 0 @setState { stepToEdit: stepIndex }, -> @props.onStepRemove stepToRemove handleStepReorder: (stepsInNewOrder) -> stepReorderedIndex = null for step, index in stepsInNewOrder stepReorderedIndex = index if @props.projectModal.steps[@state.stepToEdit].content is step.content @props.onStepOrderChange stepsInNewOrder @setState stepToEdit: stepReorderedIndex handleStepAdd: -> @props.onStepAdd() @setState stepToEdit: @props.projectModal.steps.length - 1 renderStepList: (step, i) -> step._key ?= <KEY>() buttonClasses = classnames "selected": @state.stepToEdit is i "project-modal-step-list-item-button": true <li key={step._key} className="project-modal-step-list-item"> <button type="button" className={buttonClasses} onClick={@onClick.bind null, i}> <span className="project-modal-step-list-item-button-title">Step #{i + 1}</span> </button> <button type="button" className="project-modal-step-list-item-remove-button" title="Remove this step" onClick={@handleStepRemove.bind null, i}> <i className="fa fa-trash-o fa-fw"></i> </button> </li> render: -> <div className="project-modal-editor"> <div className="project-modal-header"> <AutoSave tag="label" resource={@props.projectModal}> <span className="form-label">{@props.kind} #{@props.projectModal.id}</span> <br /> <input type="text" name="display_name" value={@props.projectModal.display_name} className="standard-input full" onChange={handleInputChange.bind @props.projectModal} /> </AutoSave> <p><button className="pill-button" onClick={@props.onProjectModalDelete}>Delete {@props.kind}</button></p> </div> {if @props.projectModal.steps.length is 0 <p>This {@props.kind} has no steps.</p> else <div className="project-modal-step-editor-container"> <DragReorderable tag="ul" className="project-modal-step-list" items={@props.projectModal.steps} render={@renderStepList} onChange={@handleStepReorder} /> <ProjectModalStepEditor step={@props.projectModal.steps[@state.stepToEdit]} media={@props.media?[@props.projectModal.steps[@state.stepToEdit].media]} onMediaSelect={@props.onMediaSelect.bind null, @state.stepToEdit} onMediaClear={@props.onMediaClear.bind null, @state.stepToEdit} onChange={@props.onStepChange.bind null, @state.stepToEdit} /> </div>} <div> <button type="button" onClick={@handleStepAdd}>Add a step</button> </div> </div> ProjectModalEditorController = createReactClass displayName: 'ProjectModalEditorController' getInitialState: -> media: {} getDefaultProps: -> project: null projectModal: null delayBeforeSave: 5000 kind: null onDelete: -> console.log 'ProjectModalEditorController onDelete', arguments componentDidMount: -> @_boundForceUpdate = @forceUpdate.bind this @props.projectModal.listen @_boundForceUpdate @fetchMediaFor(@props.projectModal) componentWillUnmount: -> @props.projectModal.stopListening @_boundForceUpdate fetchMediaFor: (projectModal) -> if projectModal? projectModal.get 'attached_images', {} # Prevent caching. .catch => [] # We get an an error if there're no attached images. .then (mediaResources) => media = {} for mediaResource in mediaResources media[mediaResource.id] = mediaResource @setState {media} else @setState media: {} render: -> <div> <hr /> <ProjectModalEditor projectModal={@props.projectModal} media={@state.media} kind={@props.kind} onStepAdd={@handleStepAdd} onStepRemove={@confirmStepRemove} onMediaSelect={@handleStepMediaChange} onMediaClear={@handleStepMediaClear} onStepChange={@handleStepChange} onStepOrderChange={@handleStepOrderChange} onProjectModalDelete={@confirmProjectModalDelete} /> </div> deleteProjectModal: -> @props.projectModal.delete() .then => @props.onDelete() handleProjectModalDelete: -> if @props.projectModal.steps.length > 0 for step in @props.projectModal.steps # Always pass in first index into step remove, because step deletion changes length # i.e. index 3 will be undefined in an originally 4 item length array after first is deleted # but iterate through the length of the original step array. @handleStepRemove(0) else @deleteProjectModal() confirmProjectModalDelete: -> message = "Are you sure you want to delete this tutorial? This action is irreversible!" successCallback = @handleProjectModalDelete confirm(message, successCallback) handleStepAdd: -> @props.projectModal.steps.push media: '' content: '' @props.projectModal.update 'steps' @props.projectModal.save() confirmStepRemove: (index) -> message = "Are you sure you want to delete this step? This action is irreversible!" confirm(message, () => @handleStepRemove(index)) handleStepRemove: (index) -> @handleStepMediaClear index changes = {} changes["steps.#{index}"] = undefined @props.projectModal.update changes if @props.projectModal.steps.length is 0 @deleteProjectModal() else @props.projectModal.save() handleStepMediaChange: (index, file) -> @handleStepMediaClear index payload = media: content_type: file.type metadata: filename: file.name apiClient.post @props.projectModal._getURL('attached_images'), payload .then (media) => media = [].concat(media)[0] putFile media.src, file, {'Content-Type': file.type} .then => changes = {} changes["steps.#{index}.media"] = media.id @props.projectModal.update changes @props.projectModal.save() .then => @fetchMediaFor @props.projectModal .catch (error) => console.error error handleStepMediaClear: (index) -> @state.media[@props.projectModal.steps[index].media]?.delete() changes = {} changes["steps.#{index}.media"] = undefined @props.projectModal.update changes @props.projectModal.save() handleStepChange: (index, key, value) -> changes = {} changes["steps.#{index}.#{key}"] = value @props.projectModal.update changes @saveProjectModal() handleStepOrderChange: (stepsInNewOrder) -> @props.projectModal.update steps: stepsInNewOrder @saveProjectModal() saveProjectModal: -> unless @_debouncedSaveProjectModal? boundProjectModalSave = @props.projectModal.save.bind @props.projectModal @_debouncedSaveProjectModal = debounce boundProjectModalSave, @props.delayBeforeSave @_debouncedSaveProjectModal arguments... ProjectModalCreator = createReactClass getDefaultProps: -> project: null kind: null onCreate: -> console.log 'ProjectModalCreator onCreate', arguments getInitialState: -> error: null render: -> <div> {if @state.error? <p>{@state.error.toString()}</p>} <p> <button type="button" onClick={@handleCreateClick}>Build a {@props.kind}</button> </p> </div> handleCreateClick: -> projectModalData = steps: [] language: 'en' kind: @props.kind links: project: @props.project.id display_name: "new #{@props.kind} title" @setState error: null apiClient.type('tutorials').create(projectModalData).save() .then (createdProjectModal) => @props.onCreate createdProjectModal .catch (error) => @setState {error} ProjectModalEditorFetcher = createReactClass getDefaultProps: -> project: null kind: null getInitialState: -> loading: false error: null projectModals: null media: {} componentDidMount: -> @_boundForceUpdate = @forceUpdate.bind this @props.project.listen @_boundForceUpdate @fetchProjectModalsFor @props.project componentWillUnmount: -> @props.project.stopListening @_boundForceUpdate componentWillReceiveProps: (nextProps) -> unless nextProps.project is @props.project @props.project.stopListening @_boundForceUpdate nextProps.project.listen @_boundForceUpdate @fetchProjectModalsFor nextProps.project fetchProjectModalsFor: (project) -> @setState loading: true error: null projectModals: null apiClient.type('tutorials').get project_id: project.id .then (projectModals) => filteredProjectModals = if @props.kind is "tutorial" projectModal for projectModal in projectModals when projectModal.kind is @props.kind or projectModal.kind is null else if @props.kind is "mini-course" projectModal for projectModal in projectModals when projectModal.kind is @props.kind @setState {projectModals: filteredProjectModals} .catch (error) => @setState {error} .then => @setState loading: false render: -> if @state.loading <p>Loading...</p> else if @state.error? <p>{@state.error.toString()}</p> else if @state.projectModals? window?.editingProjectModals = @state.projectModals <div> {for projectModal in @state.projectModals <ProjectModalEditorController key={<KEY>} project={@props.project} projectModal={projectModal} media={@state.media} kind={@props.kind} onDelete={@handleProjectModalCreateOrDelete} />} <hr /> <ProjectModalCreator project={@props.project} kind={@props.kind} onCreate={@handleProjectModalCreateOrDelete} /> </div> else <ProjectModalCreator project={@props.project} kind={@props.kind} onCreate={@handleProjectModalCreateOrDelete} /> handleProjectModalCreateOrDelete: -> @fetchProjectModalsFor @props.project module.exports = ProjectModalEditorFetcher
true
React = require 'react' createReactClass = require 'create-react-class' apiClient = require 'panoptes-client/lib/api-client' putFile = require '../lib/put-file' FileButton = require '../components/file-button' {MarkdownEditor, MarkdownHelp} = require 'markdownz' debounce = require 'debounce' DragReorderable = require 'drag-reorderable' classnames = require 'classnames' AutoSave = require '../components/auto-save' handleInputChange = require '../lib/handle-input-change' alert = require('../lib/alert').default confirm = require('../lib/confirm').default ProjectModalStepEditor = createReactClass getDefaultProps: -> step: null media: null onChange: -> console.log 'ProjectModalStepEditor onChange', arguments onMediaSelect: -> console.log 'ProjectModalStepEditor onMediaSelect', arguments onMediaClear: -> console.log 'ProjectModalStepEditor onMediaClear', arguments render: -> <div className="project-modal-step-editor"> <p> {if @props.media? <span> <img className="project-modal-step-editor-media" src={@props.media.src} />{' '} <button type="button" className="minor-button" onClick={@props.onMediaClear}>Clear</button> </span>}{' '} <FileButton className="standard-button" onSelect={@handleMediaChange}>Select media</FileButton> </p> <div> <MarkdownEditor className="full" value={@props.step.content} onChange={@handleContentChange} onHelp={-> alert <MarkdownHelp/>} /> </div> </div> handleMediaChange: (e) -> @props.onMediaSelect e.target.files[0], arguments... handleContentChange: (e) -> @props.onChange 'content', e.target.value, arguments... ProjectModalEditor = createReactClass getDefaultProps: -> projectModal: null media: null kind: null onStepAdd: -> console.log 'ProjectModalEditor onStepAdd', arguments onStepRemove: -> console.log 'ProjectModalEditor onStepRemove', arguments onMediaSelect: -> console.log 'ProjectModalEditor onMediaSelect', arguments onStepChange: -> console.log 'ProjectModalEditor onChange', arguments onStepOrderChange: -> console.log 'ProjectModalEditor onStepOrderChange', arguments getInitialState: -> stepToEdit: 0 onClick: (stepIndex) -> @setState stepToEdit: stepIndex handleStepRemove: (stepToRemove) -> if @props.projectModal.steps.length is 0 stepIndex = null else stepIndex = 0 @setState { stepToEdit: stepIndex }, -> @props.onStepRemove stepToRemove handleStepReorder: (stepsInNewOrder) -> stepReorderedIndex = null for step, index in stepsInNewOrder stepReorderedIndex = index if @props.projectModal.steps[@state.stepToEdit].content is step.content @props.onStepOrderChange stepsInNewOrder @setState stepToEdit: stepReorderedIndex handleStepAdd: -> @props.onStepAdd() @setState stepToEdit: @props.projectModal.steps.length - 1 renderStepList: (step, i) -> step._key ?= PI:KEY:<KEY>END_PI() buttonClasses = classnames "selected": @state.stepToEdit is i "project-modal-step-list-item-button": true <li key={step._key} className="project-modal-step-list-item"> <button type="button" className={buttonClasses} onClick={@onClick.bind null, i}> <span className="project-modal-step-list-item-button-title">Step #{i + 1}</span> </button> <button type="button" className="project-modal-step-list-item-remove-button" title="Remove this step" onClick={@handleStepRemove.bind null, i}> <i className="fa fa-trash-o fa-fw"></i> </button> </li> render: -> <div className="project-modal-editor"> <div className="project-modal-header"> <AutoSave tag="label" resource={@props.projectModal}> <span className="form-label">{@props.kind} #{@props.projectModal.id}</span> <br /> <input type="text" name="display_name" value={@props.projectModal.display_name} className="standard-input full" onChange={handleInputChange.bind @props.projectModal} /> </AutoSave> <p><button className="pill-button" onClick={@props.onProjectModalDelete}>Delete {@props.kind}</button></p> </div> {if @props.projectModal.steps.length is 0 <p>This {@props.kind} has no steps.</p> else <div className="project-modal-step-editor-container"> <DragReorderable tag="ul" className="project-modal-step-list" items={@props.projectModal.steps} render={@renderStepList} onChange={@handleStepReorder} /> <ProjectModalStepEditor step={@props.projectModal.steps[@state.stepToEdit]} media={@props.media?[@props.projectModal.steps[@state.stepToEdit].media]} onMediaSelect={@props.onMediaSelect.bind null, @state.stepToEdit} onMediaClear={@props.onMediaClear.bind null, @state.stepToEdit} onChange={@props.onStepChange.bind null, @state.stepToEdit} /> </div>} <div> <button type="button" onClick={@handleStepAdd}>Add a step</button> </div> </div> ProjectModalEditorController = createReactClass displayName: 'ProjectModalEditorController' getInitialState: -> media: {} getDefaultProps: -> project: null projectModal: null delayBeforeSave: 5000 kind: null onDelete: -> console.log 'ProjectModalEditorController onDelete', arguments componentDidMount: -> @_boundForceUpdate = @forceUpdate.bind this @props.projectModal.listen @_boundForceUpdate @fetchMediaFor(@props.projectModal) componentWillUnmount: -> @props.projectModal.stopListening @_boundForceUpdate fetchMediaFor: (projectModal) -> if projectModal? projectModal.get 'attached_images', {} # Prevent caching. .catch => [] # We get an an error if there're no attached images. .then (mediaResources) => media = {} for mediaResource in mediaResources media[mediaResource.id] = mediaResource @setState {media} else @setState media: {} render: -> <div> <hr /> <ProjectModalEditor projectModal={@props.projectModal} media={@state.media} kind={@props.kind} onStepAdd={@handleStepAdd} onStepRemove={@confirmStepRemove} onMediaSelect={@handleStepMediaChange} onMediaClear={@handleStepMediaClear} onStepChange={@handleStepChange} onStepOrderChange={@handleStepOrderChange} onProjectModalDelete={@confirmProjectModalDelete} /> </div> deleteProjectModal: -> @props.projectModal.delete() .then => @props.onDelete() handleProjectModalDelete: -> if @props.projectModal.steps.length > 0 for step in @props.projectModal.steps # Always pass in first index into step remove, because step deletion changes length # i.e. index 3 will be undefined in an originally 4 item length array after first is deleted # but iterate through the length of the original step array. @handleStepRemove(0) else @deleteProjectModal() confirmProjectModalDelete: -> message = "Are you sure you want to delete this tutorial? This action is irreversible!" successCallback = @handleProjectModalDelete confirm(message, successCallback) handleStepAdd: -> @props.projectModal.steps.push media: '' content: '' @props.projectModal.update 'steps' @props.projectModal.save() confirmStepRemove: (index) -> message = "Are you sure you want to delete this step? This action is irreversible!" confirm(message, () => @handleStepRemove(index)) handleStepRemove: (index) -> @handleStepMediaClear index changes = {} changes["steps.#{index}"] = undefined @props.projectModal.update changes if @props.projectModal.steps.length is 0 @deleteProjectModal() else @props.projectModal.save() handleStepMediaChange: (index, file) -> @handleStepMediaClear index payload = media: content_type: file.type metadata: filename: file.name apiClient.post @props.projectModal._getURL('attached_images'), payload .then (media) => media = [].concat(media)[0] putFile media.src, file, {'Content-Type': file.type} .then => changes = {} changes["steps.#{index}.media"] = media.id @props.projectModal.update changes @props.projectModal.save() .then => @fetchMediaFor @props.projectModal .catch (error) => console.error error handleStepMediaClear: (index) -> @state.media[@props.projectModal.steps[index].media]?.delete() changes = {} changes["steps.#{index}.media"] = undefined @props.projectModal.update changes @props.projectModal.save() handleStepChange: (index, key, value) -> changes = {} changes["steps.#{index}.#{key}"] = value @props.projectModal.update changes @saveProjectModal() handleStepOrderChange: (stepsInNewOrder) -> @props.projectModal.update steps: stepsInNewOrder @saveProjectModal() saveProjectModal: -> unless @_debouncedSaveProjectModal? boundProjectModalSave = @props.projectModal.save.bind @props.projectModal @_debouncedSaveProjectModal = debounce boundProjectModalSave, @props.delayBeforeSave @_debouncedSaveProjectModal arguments... ProjectModalCreator = createReactClass getDefaultProps: -> project: null kind: null onCreate: -> console.log 'ProjectModalCreator onCreate', arguments getInitialState: -> error: null render: -> <div> {if @state.error? <p>{@state.error.toString()}</p>} <p> <button type="button" onClick={@handleCreateClick}>Build a {@props.kind}</button> </p> </div> handleCreateClick: -> projectModalData = steps: [] language: 'en' kind: @props.kind links: project: @props.project.id display_name: "new #{@props.kind} title" @setState error: null apiClient.type('tutorials').create(projectModalData).save() .then (createdProjectModal) => @props.onCreate createdProjectModal .catch (error) => @setState {error} ProjectModalEditorFetcher = createReactClass getDefaultProps: -> project: null kind: null getInitialState: -> loading: false error: null projectModals: null media: {} componentDidMount: -> @_boundForceUpdate = @forceUpdate.bind this @props.project.listen @_boundForceUpdate @fetchProjectModalsFor @props.project componentWillUnmount: -> @props.project.stopListening @_boundForceUpdate componentWillReceiveProps: (nextProps) -> unless nextProps.project is @props.project @props.project.stopListening @_boundForceUpdate nextProps.project.listen @_boundForceUpdate @fetchProjectModalsFor nextProps.project fetchProjectModalsFor: (project) -> @setState loading: true error: null projectModals: null apiClient.type('tutorials').get project_id: project.id .then (projectModals) => filteredProjectModals = if @props.kind is "tutorial" projectModal for projectModal in projectModals when projectModal.kind is @props.kind or projectModal.kind is null else if @props.kind is "mini-course" projectModal for projectModal in projectModals when projectModal.kind is @props.kind @setState {projectModals: filteredProjectModals} .catch (error) => @setState {error} .then => @setState loading: false render: -> if @state.loading <p>Loading...</p> else if @state.error? <p>{@state.error.toString()}</p> else if @state.projectModals? window?.editingProjectModals = @state.projectModals <div> {for projectModal in @state.projectModals <ProjectModalEditorController key={PI:KEY:<KEY>END_PI} project={@props.project} projectModal={projectModal} media={@state.media} kind={@props.kind} onDelete={@handleProjectModalCreateOrDelete} />} <hr /> <ProjectModalCreator project={@props.project} kind={@props.kind} onCreate={@handleProjectModalCreateOrDelete} /> </div> else <ProjectModalCreator project={@props.project} kind={@props.kind} onCreate={@handleProjectModalCreateOrDelete} /> handleProjectModalCreateOrDelete: -> @fetchProjectModalsFor @props.project module.exports = ProjectModalEditorFetcher
[ { "context": " \"id\": \"13\",\n# \"title\": \"желтая\",\n# \"points\": [\n# ", "end": 4498, "score": 0.9928449988365173, "start": 4492, "tag": "NAME", "value": "желтая" }, { "context": " \"id\": \"14\",\n# \"title\": \"серая север\",\n# \"points\": [\n# ", "end": 4754, "score": 0.9919569492340088, "start": 4743, "tag": "NAME", "value": "серая север" }, { "context": " \"id\": \"15\",\n# \"title\": \"серая юг\",\n# \"points\": [\n# ", "end": 5009, "score": 0.9904329776763916, "start": 5001, "tag": "NAME", "value": "серая юг" }, { "context": " \"id\": \"16\",\n# \"title\": \"светло-зеленая\",\n# \"points\": [\n# ", "end": 5295, "score": 0.9724600911140442, "start": 5281, "tag": "NAME", "value": "светло-зеленая" }, { "context": " \"id\": \"17\",\n# \"title\": \"бутовская\",\n# \"points\": [\n# ", "end": 5584, "score": 0.9837687611579895, "start": 5575, "tag": "NAME", "value": "бутовская" }, { "context": " \"id\": \"18\",\n# \"title\": \"каховская\",\n# \"points\": [\n# ", "end": 5841, "score": 0.7155141830444336, "start": 5839, "tag": "NAME", "value": "ка" }, { "context": "\"id\": \"18\",\n# \"title\": \"каховская\",\n# \"points\": [\n# ", "end": 5844, "score": 0.5145367383956909, "start": 5842, "tag": "NAME", "value": "ов" } ]
resources/assets/coffee/services/svgmap.coffee
maxflex/egerep
0
angular.module('Egerep').service 'SvgMap', -> # this.map = new SVGMap # iframeId: 'map', # clicable: true, # places: [], # placesHash: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 180, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211] # groups: [ # { # "id": "1", # "title": "внутри кольца", # "points": [ # 4, 8, 12, 15, 18, 19, 38, 47, 48, 51, 54, 56, 58, 60, 63, 66, 68, 71, 74, 82, 83, 86, 90, 91, 92, 102, 104, 109, 111, 120, 122, 126, 129, 131, 132, 133, 137, 138, 140, 153, 156, 157, 158, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 198, 199 # ] # }, # { # "id": "2", # "title": "красная север", # "points": [ # 55, 106, 124, 145, 154 # ] # }, # { # "id": "3", # "title": "красная юг", # "points": [ # 33, 108, 125, 148, 151, 164, 209, 210 # ] # }, # { # "id": "4", # "title": "зеленая север", # "points": [ # 9, 28, 29, 36, 112, 123 # ] # }, # { # "id": "5", # "title": "зеленая юг", # "points": [ # 2, 39, 44, 46, 50, 53, 88, 152, 197, 202, 204 # ] # }, # { # "id": "6", # "title": "синяя запад", # "points": [ # 32, 59, 62, 75, 76, 77, 93, 121, 127, 186, 203 # ] # }, # { # "id": "7", # "title": "синяя восток", # "points": [ # 13, 42, 94, 95, 119, 161, 163 # ] # }, # { # "id": "8", # "title": "голубая", # "points": [ # 11, 62, 64, 99, 128, 149, 150, 186 # ] # }, # { # "id": "9", # "title": "оранжевая север", # "points": [ # 5, 10, 20, 26, 72, 113, 117 # ] # }, # { # "id": "10", # "title": "оранжевая юг", # "points": [ # 3, 16, 43, 52, 65, 84, 85, 110, 135, 159, 166 # ] # }, # { # "id": "11", # "title": "фиолетовая север", # "points": [ # 14, 87, 100, 103, 130, 141, 142, 162 # ] # }, # { # "id": "12", # "title": "фиолетовая юг", # "points": [ # 30, 35, 57, 61, 107, 115, 134, 205, 206, 211 # ] # }, # { # "id": "13", # "title": "желтая", # "points": [ # 1, 81, 96, 101, 114, 160, 180 # ] # }, # { # "id": "14", # "title": "серая север", # "points": [ # 6, 17, 27, 37, 89, 97, 116, 136 # ] # }, # { # "id": "15", # "title": "серая юг", # "points": [ # 7, 23, 45, 78, 79, 80, 105, 118, 139, 143, 147, 155, 165 # ] # }, # { # "id": "16", # "title": "светло-зеленая", # "points": [ # 21, 31, 41, 49, 53, 57, 67, 70, 98, 101, 107, 114, 200, 201, 202 # ] # }, # { # "id": "17", # "title": "бутовская", # "points": [ # 22, 23, 24, 84, 144, 146, 147, 207, 208 # ] # }, # { # "id": "18", # "title": "каховская", # "points": [ # 25, 45, 46, 118, 197 # ] # } # ] this.show = -> $('#svg-modal').modal('show') return this
215419
angular.module('Egerep').service 'SvgMap', -> # this.map = new SVGMap # iframeId: 'map', # clicable: true, # places: [], # placesHash: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 180, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211] # groups: [ # { # "id": "1", # "title": "внутри кольца", # "points": [ # 4, 8, 12, 15, 18, 19, 38, 47, 48, 51, 54, 56, 58, 60, 63, 66, 68, 71, 74, 82, 83, 86, 90, 91, 92, 102, 104, 109, 111, 120, 122, 126, 129, 131, 132, 133, 137, 138, 140, 153, 156, 157, 158, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 198, 199 # ] # }, # { # "id": "2", # "title": "красная север", # "points": [ # 55, 106, 124, 145, 154 # ] # }, # { # "id": "3", # "title": "красная юг", # "points": [ # 33, 108, 125, 148, 151, 164, 209, 210 # ] # }, # { # "id": "4", # "title": "зеленая север", # "points": [ # 9, 28, 29, 36, 112, 123 # ] # }, # { # "id": "5", # "title": "зеленая юг", # "points": [ # 2, 39, 44, 46, 50, 53, 88, 152, 197, 202, 204 # ] # }, # { # "id": "6", # "title": "синяя запад", # "points": [ # 32, 59, 62, 75, 76, 77, 93, 121, 127, 186, 203 # ] # }, # { # "id": "7", # "title": "синяя восток", # "points": [ # 13, 42, 94, 95, 119, 161, 163 # ] # }, # { # "id": "8", # "title": "голубая", # "points": [ # 11, 62, 64, 99, 128, 149, 150, 186 # ] # }, # { # "id": "9", # "title": "оранжевая север", # "points": [ # 5, 10, 20, 26, 72, 113, 117 # ] # }, # { # "id": "10", # "title": "оранжевая юг", # "points": [ # 3, 16, 43, 52, 65, 84, 85, 110, 135, 159, 166 # ] # }, # { # "id": "11", # "title": "фиолетовая север", # "points": [ # 14, 87, 100, 103, 130, 141, 142, 162 # ] # }, # { # "id": "12", # "title": "фиолетовая юг", # "points": [ # 30, 35, 57, 61, 107, 115, 134, 205, 206, 211 # ] # }, # { # "id": "13", # "title": "<NAME>", # "points": [ # 1, 81, 96, 101, 114, 160, 180 # ] # }, # { # "id": "14", # "title": "<NAME>", # "points": [ # 6, 17, 27, 37, 89, 97, 116, 136 # ] # }, # { # "id": "15", # "title": "<NAME>", # "points": [ # 7, 23, 45, 78, 79, 80, 105, 118, 139, 143, 147, 155, 165 # ] # }, # { # "id": "16", # "title": "<NAME>", # "points": [ # 21, 31, 41, 49, 53, 57, 67, 70, 98, 101, 107, 114, 200, 201, 202 # ] # }, # { # "id": "17", # "title": "<NAME>", # "points": [ # 22, 23, 24, 84, 144, 146, 147, 207, 208 # ] # }, # { # "id": "18", # "title": "<NAME>х<NAME>ская", # "points": [ # 25, 45, 46, 118, 197 # ] # } # ] this.show = -> $('#svg-modal').modal('show') return this
true
angular.module('Egerep').service 'SvgMap', -> # this.map = new SVGMap # iframeId: 'map', # clicable: true, # places: [], # placesHash: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 180, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211] # groups: [ # { # "id": "1", # "title": "внутри кольца", # "points": [ # 4, 8, 12, 15, 18, 19, 38, 47, 48, 51, 54, 56, 58, 60, 63, 66, 68, 71, 74, 82, 83, 86, 90, 91, 92, 102, 104, 109, 111, 120, 122, 126, 129, 131, 132, 133, 137, 138, 140, 153, 156, 157, 158, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 198, 199 # ] # }, # { # "id": "2", # "title": "красная север", # "points": [ # 55, 106, 124, 145, 154 # ] # }, # { # "id": "3", # "title": "красная юг", # "points": [ # 33, 108, 125, 148, 151, 164, 209, 210 # ] # }, # { # "id": "4", # "title": "зеленая север", # "points": [ # 9, 28, 29, 36, 112, 123 # ] # }, # { # "id": "5", # "title": "зеленая юг", # "points": [ # 2, 39, 44, 46, 50, 53, 88, 152, 197, 202, 204 # ] # }, # { # "id": "6", # "title": "синяя запад", # "points": [ # 32, 59, 62, 75, 76, 77, 93, 121, 127, 186, 203 # ] # }, # { # "id": "7", # "title": "синяя восток", # "points": [ # 13, 42, 94, 95, 119, 161, 163 # ] # }, # { # "id": "8", # "title": "голубая", # "points": [ # 11, 62, 64, 99, 128, 149, 150, 186 # ] # }, # { # "id": "9", # "title": "оранжевая север", # "points": [ # 5, 10, 20, 26, 72, 113, 117 # ] # }, # { # "id": "10", # "title": "оранжевая юг", # "points": [ # 3, 16, 43, 52, 65, 84, 85, 110, 135, 159, 166 # ] # }, # { # "id": "11", # "title": "фиолетовая север", # "points": [ # 14, 87, 100, 103, 130, 141, 142, 162 # ] # }, # { # "id": "12", # "title": "фиолетовая юг", # "points": [ # 30, 35, 57, 61, 107, 115, 134, 205, 206, 211 # ] # }, # { # "id": "13", # "title": "PI:NAME:<NAME>END_PI", # "points": [ # 1, 81, 96, 101, 114, 160, 180 # ] # }, # { # "id": "14", # "title": "PI:NAME:<NAME>END_PI", # "points": [ # 6, 17, 27, 37, 89, 97, 116, 136 # ] # }, # { # "id": "15", # "title": "PI:NAME:<NAME>END_PI", # "points": [ # 7, 23, 45, 78, 79, 80, 105, 118, 139, 143, 147, 155, 165 # ] # }, # { # "id": "16", # "title": "PI:NAME:<NAME>END_PI", # "points": [ # 21, 31, 41, 49, 53, 57, 67, 70, 98, 101, 107, 114, 200, 201, 202 # ] # }, # { # "id": "17", # "title": "PI:NAME:<NAME>END_PI", # "points": [ # 22, 23, 24, 84, 144, 146, 147, 207, 208 # ] # }, # { # "id": "18", # "title": "PI:NAME:<NAME>END_PIхPI:NAME:<NAME>END_PIская", # "points": [ # 25, 45, 46, 118, 197 # ] # } # ] this.show = -> $('#svg-modal').modal('show') return this
[ { "context": "\n @joiner1 = factories.makeUser({firstName: 'joiner', lastName: 'one'})\n @joiner2 = factories.ma", "end": 504, "score": 0.8309057354927063, "start": 498, "tag": "NAME", "value": "joiner" }, { "context": "\n @joiner2 = factories.makeUser({firstName: 'joiner', lastName: 'two'})\n @prepaid = factories.ma", "end": 580, "score": 0.8693434000015259, "start": 574, "tag": "NAME", "value": "joiner" }, { "context": "il'))\n # expect(joiners[1]?.firstName).toBe('joiner')\n # expect(joiners[1]?.lastName).toBe('two'", "end": 1530, "score": 0.7578853368759155, "start": 1524, "tag": "NAME", "value": "joiner" }, { "context": "Be('two')\n # expect(joiners[1]?.email).toBe(@joiner2.get('email'))\n # expect(joiners[2]?.firstNam", "end": 1629, "score": 0.8128406405448914, "start": 1622, "tag": "USERNAME", "value": "joiner2" }, { "context": "il'))\n # expect(joiners[2]?.firstName).toBe('joiner')\n # expect(joiners[2]?.lastName).toBe('one'", "end": 1694, "score": 0.8076028823852539, "start": 1688, "tag": "NAME", "value": "joiner" }, { "context": " @joiner3 = factories.makeUser({firstName: 'joiner', lastName: 'three'})\n spyOn(api.prepaids,", "end": 1937, "score": 0.9880229234695435, "start": 1931, "tag": "NAME", "value": "joiner" }, { "context": "ctories.makeUser({firstName: 'joiner', lastName: 'three'})\n spyOn(api.prepaids, 'addJoiner').and.r", "end": 1956, "score": 0.8261951208114624, "start": 1951, "tag": "NAME", "value": "three" }, { "context": "ners\n expect(joiners[1].firstName).toBe('joiner')\n expect(joiners[1].lastName).toBe('thr", "end": 2542, "score": 0.9697278738021851, "start": 2536, "tag": "NAME", "value": "joiner" }, { "context": "w.me = @teacher = factories.makeUser({firstName: 'teacher', lastName: 'one'})\n @joiner1 = factories.make", "end": 2807, "score": 0.9349678158760071, "start": 2800, "tag": "NAME", "value": "teacher" }, { "context": "})\n @joiner1 = factories.makeUser({firstName: 'joiner', lastName: 'one'})\n @joiner2 = factories.make", "end": 2881, "score": 0.9896941781044006, "start": 2875, "tag": "NAME", "value": "joiner" }, { "context": "})\n @joiner2 = factories.makeUser({firstName: 'joiner', lastName: 'two'})\n @prepaid = factories.make", "end": 2955, "score": 0.9840364456176758, "start": 2949, "tag": "NAME", "value": "joiner" }, { "context": "repaid.joiners[0]).toDeepEqual(_.assign({}, _.pick(@joiner1.attributes, 'firstName', 'lastName', 'name', 'email', '_id')", "end": 4072, "score": 0.8795155882835388, "start": 4053, "tag": "USERNAME", "value": "@joiner1.attributes" }, { "context": "ign({}, _.pick(@joiner1.attributes, 'firstName', 'lastName', 'name', 'email', '_id'), {userID: @joiner1.get(", "end": 4096, "score": 0.557227373123169, "start": 4088, "tag": "NAME", "value": "lastName" }, { "context": "', 'lastName', 'name', 'email', '_id'), {userID: @joiner1.get('_id')}))\n expect(storedPrepaid.joiner", "end": 4141, "score": 0.7389641404151917, "start": 4134, "tag": "USERNAME", "value": "joiner1" }, { "context": "repaid.joiners[1]).toDeepEqual(_.assign({}, _.pick(@joiner2.attributes, 'firstName', 'lastName', 'name', 'email', '_id')", "end": 4248, "score": 0.8490152955055237, "start": 4229, "tag": "USERNAME", "value": "@joiner2.attributes" }, { "context": "epEqual(_.assign({}, _.pick(@joiner2.attributes, 'firstName', 'lastName', 'name', 'email', '_id'), {userID: @", "end": 4260, "score": 0.8427382111549377, "start": 4251, "tag": "NAME", "value": "firstName" }, { "context": "ign({}, _.pick(@joiner2.attributes, 'firstName', 'lastName', 'name', 'email', '_id'), {userID: @joiner2.get(", "end": 4272, "score": 0.8760443329811096, "start": 4264, "tag": "NAME", "value": "lastName" } ]
test/app/views/teachers/ShareLicensesModal.spec.coffee
cihatislamdede/codecombat
4,858
ShareLicensesModal = require 'views/teachers/ShareLicensesModal' ShareLicensesStoreModule = require 'views/teachers/ShareLicensesStoreModule' factories = require '../../factories' api = require 'core/api' describe 'ShareLicensesModal', -> afterEach -> @modal?.destroy?() unless @modal?.destroyed describe 'joiner list', -> beforeEach (done) -> window.me = @teacher = factories.makeUser({firstName: 'teacher', lastName: 'one'}) @joiner1 = factories.makeUser({firstName: 'joiner', lastName: 'one'}) @joiner2 = factories.makeUser({firstName: 'joiner', lastName: 'two'}) @prepaid = factories.makePrepaid({ joiners: [{ userID: @joiner1.id }, { userID: @joiner2.id }] }) spyOn(api.prepaids, 'fetchJoiners').and.returnValue Promise.resolve([ _.pick(@joiner1.attributes, '_id', 'name', 'email', 'firstName', 'lastName') _.pick(@joiner2.attributes, '_id', 'name', 'email', 'firstName', 'lastName') ]) @modal = new ShareLicensesModal({ prepaid: @prepaid }) @modal.render() @store = @modal.shareLicensesComponent.$store # TODO How do I wait for VueX to finish updating? _.defer -> done() # xit 'shows a list of joiners in reverse order', -> # joiners = @modal.shareLicensesComponent.prepaid.joiners # expect(joiners[0]?.firstName).toBe('teacher') # expect(joiners[0]?.lastName).toBe('one') # expect(joiners[0]?.email).toBe(@teacher.get('email')) # expect(joiners[1]?.firstName).toBe('joiner') # expect(joiners[1]?.lastName).toBe('two') # expect(joiners[1]?.email).toBe(@joiner2.get('email')) # expect(joiners[2]?.firstName).toBe('joiner') # expect(joiners[2]?.lastName).toBe('one') # expect(joiners[2]?.email).toBe(@joiner1.get('email')) describe 'Add Teacher button', -> beforeEach (done) -> @joiner3 = factories.makeUser({firstName: 'joiner', lastName: 'three'}) spyOn(api.prepaids, 'addJoiner').and.returnValue Promise.resolve(@prepaid.toJSON()) spyOn(api.users, 'getByEmail').and.returnValue Promise.resolve(_.pick(@joiner3.toJSON(), ['_id', 'name', 'email', 'firstName', 'lastName'])) _.defer -> done() it 'can add a joiner', (done) -> @modal.shareLicensesComponent.teacherSearchInput = @joiner3.get('email') @modal.shareLicensesComponent.addTeacher().then => joiners = @modal.shareLicensesComponent.prepaid.joiners expect(joiners[1].firstName).toBe('joiner') expect(joiners[1].lastName).toBe('three') expect(joiners[1].email).toBe(@joiner3.get('email')) done() describe 'ShareLicensesStoreModule', -> beforeEach (done) -> window.me = @teacher = factories.makeUser({firstName: 'teacher', lastName: 'one'}) @joiner1 = factories.makeUser({firstName: 'joiner', lastName: 'one'}) @joiner2 = factories.makeUser({firstName: 'joiner', lastName: 'two'}) @prepaid = factories.makePrepaid({ joiners: [{ userID: @joiner1.id }, { userID: @joiner2.id }] }) @store = require('core/store') @store.registerModule('modal', ShareLicensesStoreModule) @store.commit('modal/clearData') spyOn(api.prepaids, 'fetchJoiners').and.returnValue Promise.resolve([ _.pick(@joiner1.attributes, '_id', 'name', 'email', 'firstName', 'lastName') _.pick(@joiner2.attributes, '_id', 'name', 'email', 'firstName', 'lastName') ]) spyOn(@store, 'commit').and.stub() done() describe 'setJoiners', -> it 'fetches and attaches joiner information', (done) -> @store.dispatch('modal/setPrepaid', @prepaid.attributes) .then => expect(api.prepaids.fetchJoiners).toHaveBeenCalled() expect(ShareLicensesStoreModule.state.error).toBe('') expect(@store.commit).toHaveBeenCalled() storedPrepaid = @store.commit.calls.argsFor(0)[1] expect(storedPrepaid._id).toEqual(@prepaid.attributes._id) expect(storedPrepaid.joiners[0]).toDeepEqual(_.assign({}, _.pick(@joiner1.attributes, 'firstName', 'lastName', 'name', 'email', '_id'), {userID: @joiner1.get('_id')})) expect(storedPrepaid.joiners[1]).toDeepEqual(_.assign({}, _.pick(@joiner2.attributes, 'firstName', 'lastName', 'name', 'email', '_id'), {userID: @joiner2.get('_id')})) done()
150979
ShareLicensesModal = require 'views/teachers/ShareLicensesModal' ShareLicensesStoreModule = require 'views/teachers/ShareLicensesStoreModule' factories = require '../../factories' api = require 'core/api' describe 'ShareLicensesModal', -> afterEach -> @modal?.destroy?() unless @modal?.destroyed describe 'joiner list', -> beforeEach (done) -> window.me = @teacher = factories.makeUser({firstName: 'teacher', lastName: 'one'}) @joiner1 = factories.makeUser({firstName: '<NAME>', lastName: 'one'}) @joiner2 = factories.makeUser({firstName: '<NAME>', lastName: 'two'}) @prepaid = factories.makePrepaid({ joiners: [{ userID: @joiner1.id }, { userID: @joiner2.id }] }) spyOn(api.prepaids, 'fetchJoiners').and.returnValue Promise.resolve([ _.pick(@joiner1.attributes, '_id', 'name', 'email', 'firstName', 'lastName') _.pick(@joiner2.attributes, '_id', 'name', 'email', 'firstName', 'lastName') ]) @modal = new ShareLicensesModal({ prepaid: @prepaid }) @modal.render() @store = @modal.shareLicensesComponent.$store # TODO How do I wait for VueX to finish updating? _.defer -> done() # xit 'shows a list of joiners in reverse order', -> # joiners = @modal.shareLicensesComponent.prepaid.joiners # expect(joiners[0]?.firstName).toBe('teacher') # expect(joiners[0]?.lastName).toBe('one') # expect(joiners[0]?.email).toBe(@teacher.get('email')) # expect(joiners[1]?.firstName).toBe('<NAME>') # expect(joiners[1]?.lastName).toBe('two') # expect(joiners[1]?.email).toBe(@joiner2.get('email')) # expect(joiners[2]?.firstName).toBe('<NAME>') # expect(joiners[2]?.lastName).toBe('one') # expect(joiners[2]?.email).toBe(@joiner1.get('email')) describe 'Add Teacher button', -> beforeEach (done) -> @joiner3 = factories.makeUser({firstName: '<NAME>', lastName: '<NAME>'}) spyOn(api.prepaids, 'addJoiner').and.returnValue Promise.resolve(@prepaid.toJSON()) spyOn(api.users, 'getByEmail').and.returnValue Promise.resolve(_.pick(@joiner3.toJSON(), ['_id', 'name', 'email', 'firstName', 'lastName'])) _.defer -> done() it 'can add a joiner', (done) -> @modal.shareLicensesComponent.teacherSearchInput = @joiner3.get('email') @modal.shareLicensesComponent.addTeacher().then => joiners = @modal.shareLicensesComponent.prepaid.joiners expect(joiners[1].firstName).toBe('<NAME>') expect(joiners[1].lastName).toBe('three') expect(joiners[1].email).toBe(@joiner3.get('email')) done() describe 'ShareLicensesStoreModule', -> beforeEach (done) -> window.me = @teacher = factories.makeUser({firstName: '<NAME>', lastName: 'one'}) @joiner1 = factories.makeUser({firstName: '<NAME>', lastName: 'one'}) @joiner2 = factories.makeUser({firstName: '<NAME>', lastName: 'two'}) @prepaid = factories.makePrepaid({ joiners: [{ userID: @joiner1.id }, { userID: @joiner2.id }] }) @store = require('core/store') @store.registerModule('modal', ShareLicensesStoreModule) @store.commit('modal/clearData') spyOn(api.prepaids, 'fetchJoiners').and.returnValue Promise.resolve([ _.pick(@joiner1.attributes, '_id', 'name', 'email', 'firstName', 'lastName') _.pick(@joiner2.attributes, '_id', 'name', 'email', 'firstName', 'lastName') ]) spyOn(@store, 'commit').and.stub() done() describe 'setJoiners', -> it 'fetches and attaches joiner information', (done) -> @store.dispatch('modal/setPrepaid', @prepaid.attributes) .then => expect(api.prepaids.fetchJoiners).toHaveBeenCalled() expect(ShareLicensesStoreModule.state.error).toBe('') expect(@store.commit).toHaveBeenCalled() storedPrepaid = @store.commit.calls.argsFor(0)[1] expect(storedPrepaid._id).toEqual(@prepaid.attributes._id) expect(storedPrepaid.joiners[0]).toDeepEqual(_.assign({}, _.pick(@joiner1.attributes, 'firstName', '<NAME>', 'name', 'email', '_id'), {userID: @joiner1.get('_id')})) expect(storedPrepaid.joiners[1]).toDeepEqual(_.assign({}, _.pick(@joiner2.attributes, '<NAME>', '<NAME>', 'name', 'email', '_id'), {userID: @joiner2.get('_id')})) done()
true
ShareLicensesModal = require 'views/teachers/ShareLicensesModal' ShareLicensesStoreModule = require 'views/teachers/ShareLicensesStoreModule' factories = require '../../factories' api = require 'core/api' describe 'ShareLicensesModal', -> afterEach -> @modal?.destroy?() unless @modal?.destroyed describe 'joiner list', -> beforeEach (done) -> window.me = @teacher = factories.makeUser({firstName: 'teacher', lastName: 'one'}) @joiner1 = factories.makeUser({firstName: 'PI:NAME:<NAME>END_PI', lastName: 'one'}) @joiner2 = factories.makeUser({firstName: 'PI:NAME:<NAME>END_PI', lastName: 'two'}) @prepaid = factories.makePrepaid({ joiners: [{ userID: @joiner1.id }, { userID: @joiner2.id }] }) spyOn(api.prepaids, 'fetchJoiners').and.returnValue Promise.resolve([ _.pick(@joiner1.attributes, '_id', 'name', 'email', 'firstName', 'lastName') _.pick(@joiner2.attributes, '_id', 'name', 'email', 'firstName', 'lastName') ]) @modal = new ShareLicensesModal({ prepaid: @prepaid }) @modal.render() @store = @modal.shareLicensesComponent.$store # TODO How do I wait for VueX to finish updating? _.defer -> done() # xit 'shows a list of joiners in reverse order', -> # joiners = @modal.shareLicensesComponent.prepaid.joiners # expect(joiners[0]?.firstName).toBe('teacher') # expect(joiners[0]?.lastName).toBe('one') # expect(joiners[0]?.email).toBe(@teacher.get('email')) # expect(joiners[1]?.firstName).toBe('PI:NAME:<NAME>END_PI') # expect(joiners[1]?.lastName).toBe('two') # expect(joiners[1]?.email).toBe(@joiner2.get('email')) # expect(joiners[2]?.firstName).toBe('PI:NAME:<NAME>END_PI') # expect(joiners[2]?.lastName).toBe('one') # expect(joiners[2]?.email).toBe(@joiner1.get('email')) describe 'Add Teacher button', -> beforeEach (done) -> @joiner3 = factories.makeUser({firstName: 'PI:NAME:<NAME>END_PI', lastName: 'PI:NAME:<NAME>END_PI'}) spyOn(api.prepaids, 'addJoiner').and.returnValue Promise.resolve(@prepaid.toJSON()) spyOn(api.users, 'getByEmail').and.returnValue Promise.resolve(_.pick(@joiner3.toJSON(), ['_id', 'name', 'email', 'firstName', 'lastName'])) _.defer -> done() it 'can add a joiner', (done) -> @modal.shareLicensesComponent.teacherSearchInput = @joiner3.get('email') @modal.shareLicensesComponent.addTeacher().then => joiners = @modal.shareLicensesComponent.prepaid.joiners expect(joiners[1].firstName).toBe('PI:NAME:<NAME>END_PI') expect(joiners[1].lastName).toBe('three') expect(joiners[1].email).toBe(@joiner3.get('email')) done() describe 'ShareLicensesStoreModule', -> beforeEach (done) -> window.me = @teacher = factories.makeUser({firstName: 'PI:NAME:<NAME>END_PI', lastName: 'one'}) @joiner1 = factories.makeUser({firstName: 'PI:NAME:<NAME>END_PI', lastName: 'one'}) @joiner2 = factories.makeUser({firstName: 'PI:NAME:<NAME>END_PI', lastName: 'two'}) @prepaid = factories.makePrepaid({ joiners: [{ userID: @joiner1.id }, { userID: @joiner2.id }] }) @store = require('core/store') @store.registerModule('modal', ShareLicensesStoreModule) @store.commit('modal/clearData') spyOn(api.prepaids, 'fetchJoiners').and.returnValue Promise.resolve([ _.pick(@joiner1.attributes, '_id', 'name', 'email', 'firstName', 'lastName') _.pick(@joiner2.attributes, '_id', 'name', 'email', 'firstName', 'lastName') ]) spyOn(@store, 'commit').and.stub() done() describe 'setJoiners', -> it 'fetches and attaches joiner information', (done) -> @store.dispatch('modal/setPrepaid', @prepaid.attributes) .then => expect(api.prepaids.fetchJoiners).toHaveBeenCalled() expect(ShareLicensesStoreModule.state.error).toBe('') expect(@store.commit).toHaveBeenCalled() storedPrepaid = @store.commit.calls.argsFor(0)[1] expect(storedPrepaid._id).toEqual(@prepaid.attributes._id) expect(storedPrepaid.joiners[0]).toDeepEqual(_.assign({}, _.pick(@joiner1.attributes, 'firstName', 'PI:NAME:<NAME>END_PI', 'name', 'email', '_id'), {userID: @joiner1.get('_id')})) expect(storedPrepaid.joiners[1]).toDeepEqual(_.assign({}, _.pick(@joiner2.attributes, 'PI:NAME:<NAME>END_PI', 'PI:NAME:<NAME>END_PI', 'name', 'email', '_id'), {userID: @joiner2.get('_id')})) done()
[ { "context": "terableArray [{\n name: {\n first: 'john'\n last: 'smith'\n }\n }], {fie", "end": 3843, "score": 0.9998010396957397, "start": 3839, "tag": "NAME", "value": "john" }, { "context": " name: {\n first: 'john'\n last: 'smith'\n }\n }], {fields: ['name', 'first']}\n", "end": 3867, "score": 0.9996817708015442, "start": 3862, "tag": "NAME", "value": "smith" } ]
specs/extentions/filterableArray.spec.coffee
aryaroudi/Cyclops
28
describe 'Extentions: filterableArray', -> it 'hangs off the global knockout object', -> expect(ko.filterableArray).toBeDefined() return it 'default properties', -> filterable = ko.filterableArray [] expect(filterable.isFilterableArray).toBeDefined() expect(filterable.query).toBeDefined() expect(filterable.all).toBeDefined() expect(filterable.sortByString).toBeDefined() expect(filterable.sortByStringDesc).toBeDefined() expect(filterable.isSorting).toBeDefined() expect(filterable.clearSort).toBeDefined() expect(filterable.pop).toBeDefined() expect(filterable.push).toBeDefined() expect(filterable.reverse).toBeDefined() expect(filterable.shift).toBeDefined() expect(filterable.sort).toBeDefined() expect(filterable.splice).toBeDefined() expect(filterable.unshift).toBeDefined() expect(filterable.slice).toBeDefined() expect(filterable.replace).toBeDefined() expect(filterable.indexOf).toBeDefined() expect(filterable.destroy).toBeDefined() expect(filterable.destroyAll).toBeDefined() expect(filterable.remove).toBeDefined() expect(filterable.removeAll).toBeDefined() return it 'defaults to filtered array read but has whole array avalible', -> filterable = ko.filterableArray ['one', 'two', 'three'] filterable.query('three') expect(filterable().length).toEqual(1) expect(filterable.all().length).toEqual(3) return it 'uses passed observable for all array', -> initValues = ko.observableArray ['one', 'two', 'three'] filterable = ko.filterableArray initValues expect(filterable.all).toEqual(initValues) return it '[default comparer] uses simple contains for strings', -> filterable = ko.filterableArray ['one', 'two', 'three'] filterable.query('o') expect(filterable().length).toEqual(2) filterable.query('t') expect(filterable().length).toEqual(2) filterable.query('th') expect(filterable().length).toEqual(1) return it '[default comparer] is case insensative for strings', -> filterable = ko.filterableArray ['ONE'] filterable.query('one') expect(filterable().length).toEqual(1) return it '[default comparer] falls back to strict equal, with tostring on item', -> filterable = ko.filterableArray [1,2,3] filterable.query('3') expect(filterable().length).toEqual(1) return it '[default comparer] throws if query is not string', -> filterable = ko.filterableArray [1,2,3] expect(filterable.query(3)).toThrow() return it '[default comparer] object uses field names', -> filterable = ko.filterableArray [{ name: 'the name' description: 'the description' id: 'theId' notUsed: 'not used for search' }] filterable.query('name') expect(filterable().length).toEqual(1) filterable.query('description') expect(filterable().length).toEqual(1) filterable.query('theid') expect(filterable().length).toEqual(1) filterable.query('search') expect(filterable().length).toEqual(0) return it '[default comparer] object unwraps observables', -> filterable = ko.filterableArray [{ name: ko.observable('the name') }] filterable.query('name') expect(filterable().length).toEqual(1) filterable([ko.observable('one'), ko.observable('two')]) filterable.query('on') expect(filterable().length).toEqual(1) return it '[default comparer] fields can be changed', -> filterable = ko.filterableArray [{ notDefault: 'not the default field' }], {fields: ['notDefault']} filterable.query('not the d') expect(filterable().length).toEqual(1) return it '[default comparer] object uses field names', -> filterable = ko.filterableArray [{ name: { first: 'john' last: 'smith' } }], {fields: ['name', 'first']} filterable.query('john') expect(filterable().length).toEqual(1) filterable.query('smith') expect(filterable().length).toEqual(0) return it 'can have the comparer changed', -> filterable = ko.filterableArray ['one', 'two', 'three'], { comparer: (query, item ) -> return true; } filterable.query('o') expect(filterable().length).toEqual(3) filterable.query('two') expect(filterable().length).toEqual(3) return it 'removes last item from all and filtered when pop called', -> filterable = ko.filterableArray ['one', 'two', 'three'] filterable.query('t') expect(filterable.all().length).toEqual(3) expect(filterable().length).toEqual(2) filterable.pop() expect(filterable.all().length).toEqual(2) expect(filterable.all()[1]).toEqual('two') expect(filterable().length).toEqual(1) expect(filterable()[0]).toEqual('two') return it 'returns a reversed array when reverse called', -> filterable = ko.filterableArray ['one', 'two', 'three'] filterable.query('t') expect(filterable()[0]).toEqual('two') expect(filterable()[1]).toEqual('three') filterable.reverse() expect(filterable()[0]).toEqual('three') expect(filterable()[1]).toEqual('two') return it 'returns array including item just pushed at the end', -> filterable = ko.filterableArray ['one', 'two', 'three'] filterable.query('t') expect(filterable().length).toEqual(2) filterable.push('thirty') expect(filterable()[0]).toEqual('two') expect(filterable()[1]).toEqual('three') expect(filterable()[2]).toEqual('thirty') return it 'removes first item from all and filtered when shift called', -> filterable = ko.filterableArray ['two', 'three', 'four'] filterable.query('t') expect(filterable.all().length).toEqual(3) expect(filterable().length).toEqual(2) filterable.shift() expect(filterable.all().length).toEqual(2) expect(filterable.all()[1]).toEqual('four') expect(filterable().length).toEqual(1) expect(filterable()[0]).toEqual('three') return it 'has sort that takes a comparer function order order the array', -> filterable = ko.filterableArray [10, 1, 2.5, 15] filterable.sort( (a, b) -> return a - b ) expect(filterable()[0]).toEqual(1) expect(filterable()[1]).toEqual(2.5) expect(filterable()[2]).toEqual(10) expect(filterable()[3]).toEqual(15) return it 'removes items at index from all and filtered when splice called', -> filterable = ko.filterableArray ['one', 'two', 'three', 'four'] filterable.query('o') #dont remove anything filterable.splice(1,0) expect(filterable().length).toEqual(3) expect(filterable.all().length).toEqual(4) #remove two and three filterable.splice(0,2) expect(filterable().length).toEqual(1) expect(filterable.all().length).toEqual(2) return it 'adds items at index from all and filtered when splice called', -> filterable = ko.filterableArray ['one', 'three', 'four'] filterable.query('o') filterable.splice(0, 0, 'two') expect(filterable().length).toEqual(3) expect(filterable.all().length).toEqual(4) return it 'returns array including item just unshifted at the begining', -> filterable = ko.filterableArray ['one', 'two', 'three'] filterable.query('o') expect(filterable().length).toEqual(2) filterable.unshift('zero') expect(filterable.all()[0]).toEqual('zero') expect(filterable.all()[1]).toEqual('one') expect(filterable.all()[2]).toEqual('two') expect(filterable.all()[3]).toEqual('three') expect(filterable()[0]).toEqual('zero') expect(filterable()[1]).toEqual('one') expect(filterable()[2]).toEqual('two') return it 'sorts by correct property when items are objects', -> filterable = ko.filterableArray [{id: '3'}, {id: '1'}, {id: '5'}] filterable.sortByString('id') expect(filterable()[0].id).toEqual('1') expect(filterable()[1].id).toEqual('3') expect(filterable()[2].id).toEqual('5') return it 'sorts by correct property when items are objects desc version', -> filterable = ko.filterableArray [{id: '3'}, {id: '1'}, {id: '5'}] filterable.sortByStringDesc('id') expect(filterable()[0].id).toEqual('5') expect(filterable()[1].id).toEqual('3') expect(filterable()[2].id).toEqual('1') return it 'sorts even when items are added and removed', -> filterable = ko.filterableArray [{id: '3'}, {id: '1'}, {id: '5'}] filterable.sortByStringDesc('id') filterable.push({id: '6'}) expect(filterable()[0].id).toEqual('6') filterable.shift() expect(filterable()[0].id).toEqual('5') it 'should pass through observableArray function to all', -> filterable = ko.filterableArray [] spyOn filterable.all, 'slice' spyOn filterable.all, 'replace' spyOn filterable.all, 'indexOf' spyOn filterable.all, 'destroy' spyOn filterable.all, 'destroyAll' spyOn filterable.all, 'remove' spyOn filterable.all, 'removeAll' filterable.slice([1]) expect(filterable.all.slice).toHaveBeenCalledWith([1]) filterable.replace('a', 'b') expect(filterable.all.replace).toHaveBeenCalledWith('a', 'b') filterable.indexOf({a:'a'}) expect(filterable.all.indexOf).toHaveBeenCalledWith({a:'a'}) filterable.destroy({}) expect(filterable.all.destroy).toHaveBeenCalledWith({}) filterable.destroyAll([{a:'a'}]) expect(filterable.all.destroyAll).toHaveBeenCalledWith([{a:'a'}]) filterable.remove([{a:'a'}]) expect(filterable.all.remove).toHaveBeenCalledWith([{a:'a'}]) filterable.removeAll([{a:'a'}]) expect(filterable.all.removeAll).toHaveBeenCalledWith([{a:'a'}]) return
192224
describe 'Extentions: filterableArray', -> it 'hangs off the global knockout object', -> expect(ko.filterableArray).toBeDefined() return it 'default properties', -> filterable = ko.filterableArray [] expect(filterable.isFilterableArray).toBeDefined() expect(filterable.query).toBeDefined() expect(filterable.all).toBeDefined() expect(filterable.sortByString).toBeDefined() expect(filterable.sortByStringDesc).toBeDefined() expect(filterable.isSorting).toBeDefined() expect(filterable.clearSort).toBeDefined() expect(filterable.pop).toBeDefined() expect(filterable.push).toBeDefined() expect(filterable.reverse).toBeDefined() expect(filterable.shift).toBeDefined() expect(filterable.sort).toBeDefined() expect(filterable.splice).toBeDefined() expect(filterable.unshift).toBeDefined() expect(filterable.slice).toBeDefined() expect(filterable.replace).toBeDefined() expect(filterable.indexOf).toBeDefined() expect(filterable.destroy).toBeDefined() expect(filterable.destroyAll).toBeDefined() expect(filterable.remove).toBeDefined() expect(filterable.removeAll).toBeDefined() return it 'defaults to filtered array read but has whole array avalible', -> filterable = ko.filterableArray ['one', 'two', 'three'] filterable.query('three') expect(filterable().length).toEqual(1) expect(filterable.all().length).toEqual(3) return it 'uses passed observable for all array', -> initValues = ko.observableArray ['one', 'two', 'three'] filterable = ko.filterableArray initValues expect(filterable.all).toEqual(initValues) return it '[default comparer] uses simple contains for strings', -> filterable = ko.filterableArray ['one', 'two', 'three'] filterable.query('o') expect(filterable().length).toEqual(2) filterable.query('t') expect(filterable().length).toEqual(2) filterable.query('th') expect(filterable().length).toEqual(1) return it '[default comparer] is case insensative for strings', -> filterable = ko.filterableArray ['ONE'] filterable.query('one') expect(filterable().length).toEqual(1) return it '[default comparer] falls back to strict equal, with tostring on item', -> filterable = ko.filterableArray [1,2,3] filterable.query('3') expect(filterable().length).toEqual(1) return it '[default comparer] throws if query is not string', -> filterable = ko.filterableArray [1,2,3] expect(filterable.query(3)).toThrow() return it '[default comparer] object uses field names', -> filterable = ko.filterableArray [{ name: 'the name' description: 'the description' id: 'theId' notUsed: 'not used for search' }] filterable.query('name') expect(filterable().length).toEqual(1) filterable.query('description') expect(filterable().length).toEqual(1) filterable.query('theid') expect(filterable().length).toEqual(1) filterable.query('search') expect(filterable().length).toEqual(0) return it '[default comparer] object unwraps observables', -> filterable = ko.filterableArray [{ name: ko.observable('the name') }] filterable.query('name') expect(filterable().length).toEqual(1) filterable([ko.observable('one'), ko.observable('two')]) filterable.query('on') expect(filterable().length).toEqual(1) return it '[default comparer] fields can be changed', -> filterable = ko.filterableArray [{ notDefault: 'not the default field' }], {fields: ['notDefault']} filterable.query('not the d') expect(filterable().length).toEqual(1) return it '[default comparer] object uses field names', -> filterable = ko.filterableArray [{ name: { first: '<NAME>' last: '<NAME>' } }], {fields: ['name', 'first']} filterable.query('john') expect(filterable().length).toEqual(1) filterable.query('smith') expect(filterable().length).toEqual(0) return it 'can have the comparer changed', -> filterable = ko.filterableArray ['one', 'two', 'three'], { comparer: (query, item ) -> return true; } filterable.query('o') expect(filterable().length).toEqual(3) filterable.query('two') expect(filterable().length).toEqual(3) return it 'removes last item from all and filtered when pop called', -> filterable = ko.filterableArray ['one', 'two', 'three'] filterable.query('t') expect(filterable.all().length).toEqual(3) expect(filterable().length).toEqual(2) filterable.pop() expect(filterable.all().length).toEqual(2) expect(filterable.all()[1]).toEqual('two') expect(filterable().length).toEqual(1) expect(filterable()[0]).toEqual('two') return it 'returns a reversed array when reverse called', -> filterable = ko.filterableArray ['one', 'two', 'three'] filterable.query('t') expect(filterable()[0]).toEqual('two') expect(filterable()[1]).toEqual('three') filterable.reverse() expect(filterable()[0]).toEqual('three') expect(filterable()[1]).toEqual('two') return it 'returns array including item just pushed at the end', -> filterable = ko.filterableArray ['one', 'two', 'three'] filterable.query('t') expect(filterable().length).toEqual(2) filterable.push('thirty') expect(filterable()[0]).toEqual('two') expect(filterable()[1]).toEqual('three') expect(filterable()[2]).toEqual('thirty') return it 'removes first item from all and filtered when shift called', -> filterable = ko.filterableArray ['two', 'three', 'four'] filterable.query('t') expect(filterable.all().length).toEqual(3) expect(filterable().length).toEqual(2) filterable.shift() expect(filterable.all().length).toEqual(2) expect(filterable.all()[1]).toEqual('four') expect(filterable().length).toEqual(1) expect(filterable()[0]).toEqual('three') return it 'has sort that takes a comparer function order order the array', -> filterable = ko.filterableArray [10, 1, 2.5, 15] filterable.sort( (a, b) -> return a - b ) expect(filterable()[0]).toEqual(1) expect(filterable()[1]).toEqual(2.5) expect(filterable()[2]).toEqual(10) expect(filterable()[3]).toEqual(15) return it 'removes items at index from all and filtered when splice called', -> filterable = ko.filterableArray ['one', 'two', 'three', 'four'] filterable.query('o') #dont remove anything filterable.splice(1,0) expect(filterable().length).toEqual(3) expect(filterable.all().length).toEqual(4) #remove two and three filterable.splice(0,2) expect(filterable().length).toEqual(1) expect(filterable.all().length).toEqual(2) return it 'adds items at index from all and filtered when splice called', -> filterable = ko.filterableArray ['one', 'three', 'four'] filterable.query('o') filterable.splice(0, 0, 'two') expect(filterable().length).toEqual(3) expect(filterable.all().length).toEqual(4) return it 'returns array including item just unshifted at the begining', -> filterable = ko.filterableArray ['one', 'two', 'three'] filterable.query('o') expect(filterable().length).toEqual(2) filterable.unshift('zero') expect(filterable.all()[0]).toEqual('zero') expect(filterable.all()[1]).toEqual('one') expect(filterable.all()[2]).toEqual('two') expect(filterable.all()[3]).toEqual('three') expect(filterable()[0]).toEqual('zero') expect(filterable()[1]).toEqual('one') expect(filterable()[2]).toEqual('two') return it 'sorts by correct property when items are objects', -> filterable = ko.filterableArray [{id: '3'}, {id: '1'}, {id: '5'}] filterable.sortByString('id') expect(filterable()[0].id).toEqual('1') expect(filterable()[1].id).toEqual('3') expect(filterable()[2].id).toEqual('5') return it 'sorts by correct property when items are objects desc version', -> filterable = ko.filterableArray [{id: '3'}, {id: '1'}, {id: '5'}] filterable.sortByStringDesc('id') expect(filterable()[0].id).toEqual('5') expect(filterable()[1].id).toEqual('3') expect(filterable()[2].id).toEqual('1') return it 'sorts even when items are added and removed', -> filterable = ko.filterableArray [{id: '3'}, {id: '1'}, {id: '5'}] filterable.sortByStringDesc('id') filterable.push({id: '6'}) expect(filterable()[0].id).toEqual('6') filterable.shift() expect(filterable()[0].id).toEqual('5') it 'should pass through observableArray function to all', -> filterable = ko.filterableArray [] spyOn filterable.all, 'slice' spyOn filterable.all, 'replace' spyOn filterable.all, 'indexOf' spyOn filterable.all, 'destroy' spyOn filterable.all, 'destroyAll' spyOn filterable.all, 'remove' spyOn filterable.all, 'removeAll' filterable.slice([1]) expect(filterable.all.slice).toHaveBeenCalledWith([1]) filterable.replace('a', 'b') expect(filterable.all.replace).toHaveBeenCalledWith('a', 'b') filterable.indexOf({a:'a'}) expect(filterable.all.indexOf).toHaveBeenCalledWith({a:'a'}) filterable.destroy({}) expect(filterable.all.destroy).toHaveBeenCalledWith({}) filterable.destroyAll([{a:'a'}]) expect(filterable.all.destroyAll).toHaveBeenCalledWith([{a:'a'}]) filterable.remove([{a:'a'}]) expect(filterable.all.remove).toHaveBeenCalledWith([{a:'a'}]) filterable.removeAll([{a:'a'}]) expect(filterable.all.removeAll).toHaveBeenCalledWith([{a:'a'}]) return
true
describe 'Extentions: filterableArray', -> it 'hangs off the global knockout object', -> expect(ko.filterableArray).toBeDefined() return it 'default properties', -> filterable = ko.filterableArray [] expect(filterable.isFilterableArray).toBeDefined() expect(filterable.query).toBeDefined() expect(filterable.all).toBeDefined() expect(filterable.sortByString).toBeDefined() expect(filterable.sortByStringDesc).toBeDefined() expect(filterable.isSorting).toBeDefined() expect(filterable.clearSort).toBeDefined() expect(filterable.pop).toBeDefined() expect(filterable.push).toBeDefined() expect(filterable.reverse).toBeDefined() expect(filterable.shift).toBeDefined() expect(filterable.sort).toBeDefined() expect(filterable.splice).toBeDefined() expect(filterable.unshift).toBeDefined() expect(filterable.slice).toBeDefined() expect(filterable.replace).toBeDefined() expect(filterable.indexOf).toBeDefined() expect(filterable.destroy).toBeDefined() expect(filterable.destroyAll).toBeDefined() expect(filterable.remove).toBeDefined() expect(filterable.removeAll).toBeDefined() return it 'defaults to filtered array read but has whole array avalible', -> filterable = ko.filterableArray ['one', 'two', 'three'] filterable.query('three') expect(filterable().length).toEqual(1) expect(filterable.all().length).toEqual(3) return it 'uses passed observable for all array', -> initValues = ko.observableArray ['one', 'two', 'three'] filterable = ko.filterableArray initValues expect(filterable.all).toEqual(initValues) return it '[default comparer] uses simple contains for strings', -> filterable = ko.filterableArray ['one', 'two', 'three'] filterable.query('o') expect(filterable().length).toEqual(2) filterable.query('t') expect(filterable().length).toEqual(2) filterable.query('th') expect(filterable().length).toEqual(1) return it '[default comparer] is case insensative for strings', -> filterable = ko.filterableArray ['ONE'] filterable.query('one') expect(filterable().length).toEqual(1) return it '[default comparer] falls back to strict equal, with tostring on item', -> filterable = ko.filterableArray [1,2,3] filterable.query('3') expect(filterable().length).toEqual(1) return it '[default comparer] throws if query is not string', -> filterable = ko.filterableArray [1,2,3] expect(filterable.query(3)).toThrow() return it '[default comparer] object uses field names', -> filterable = ko.filterableArray [{ name: 'the name' description: 'the description' id: 'theId' notUsed: 'not used for search' }] filterable.query('name') expect(filterable().length).toEqual(1) filterable.query('description') expect(filterable().length).toEqual(1) filterable.query('theid') expect(filterable().length).toEqual(1) filterable.query('search') expect(filterable().length).toEqual(0) return it '[default comparer] object unwraps observables', -> filterable = ko.filterableArray [{ name: ko.observable('the name') }] filterable.query('name') expect(filterable().length).toEqual(1) filterable([ko.observable('one'), ko.observable('two')]) filterable.query('on') expect(filterable().length).toEqual(1) return it '[default comparer] fields can be changed', -> filterable = ko.filterableArray [{ notDefault: 'not the default field' }], {fields: ['notDefault']} filterable.query('not the d') expect(filterable().length).toEqual(1) return it '[default comparer] object uses field names', -> filterable = ko.filterableArray [{ name: { first: 'PI:NAME:<NAME>END_PI' last: 'PI:NAME:<NAME>END_PI' } }], {fields: ['name', 'first']} filterable.query('john') expect(filterable().length).toEqual(1) filterable.query('smith') expect(filterable().length).toEqual(0) return it 'can have the comparer changed', -> filterable = ko.filterableArray ['one', 'two', 'three'], { comparer: (query, item ) -> return true; } filterable.query('o') expect(filterable().length).toEqual(3) filterable.query('two') expect(filterable().length).toEqual(3) return it 'removes last item from all and filtered when pop called', -> filterable = ko.filterableArray ['one', 'two', 'three'] filterable.query('t') expect(filterable.all().length).toEqual(3) expect(filterable().length).toEqual(2) filterable.pop() expect(filterable.all().length).toEqual(2) expect(filterable.all()[1]).toEqual('two') expect(filterable().length).toEqual(1) expect(filterable()[0]).toEqual('two') return it 'returns a reversed array when reverse called', -> filterable = ko.filterableArray ['one', 'two', 'three'] filterable.query('t') expect(filterable()[0]).toEqual('two') expect(filterable()[1]).toEqual('three') filterable.reverse() expect(filterable()[0]).toEqual('three') expect(filterable()[1]).toEqual('two') return it 'returns array including item just pushed at the end', -> filterable = ko.filterableArray ['one', 'two', 'three'] filterable.query('t') expect(filterable().length).toEqual(2) filterable.push('thirty') expect(filterable()[0]).toEqual('two') expect(filterable()[1]).toEqual('three') expect(filterable()[2]).toEqual('thirty') return it 'removes first item from all and filtered when shift called', -> filterable = ko.filterableArray ['two', 'three', 'four'] filterable.query('t') expect(filterable.all().length).toEqual(3) expect(filterable().length).toEqual(2) filterable.shift() expect(filterable.all().length).toEqual(2) expect(filterable.all()[1]).toEqual('four') expect(filterable().length).toEqual(1) expect(filterable()[0]).toEqual('three') return it 'has sort that takes a comparer function order order the array', -> filterable = ko.filterableArray [10, 1, 2.5, 15] filterable.sort( (a, b) -> return a - b ) expect(filterable()[0]).toEqual(1) expect(filterable()[1]).toEqual(2.5) expect(filterable()[2]).toEqual(10) expect(filterable()[3]).toEqual(15) return it 'removes items at index from all and filtered when splice called', -> filterable = ko.filterableArray ['one', 'two', 'three', 'four'] filterable.query('o') #dont remove anything filterable.splice(1,0) expect(filterable().length).toEqual(3) expect(filterable.all().length).toEqual(4) #remove two and three filterable.splice(0,2) expect(filterable().length).toEqual(1) expect(filterable.all().length).toEqual(2) return it 'adds items at index from all and filtered when splice called', -> filterable = ko.filterableArray ['one', 'three', 'four'] filterable.query('o') filterable.splice(0, 0, 'two') expect(filterable().length).toEqual(3) expect(filterable.all().length).toEqual(4) return it 'returns array including item just unshifted at the begining', -> filterable = ko.filterableArray ['one', 'two', 'three'] filterable.query('o') expect(filterable().length).toEqual(2) filterable.unshift('zero') expect(filterable.all()[0]).toEqual('zero') expect(filterable.all()[1]).toEqual('one') expect(filterable.all()[2]).toEqual('two') expect(filterable.all()[3]).toEqual('three') expect(filterable()[0]).toEqual('zero') expect(filterable()[1]).toEqual('one') expect(filterable()[2]).toEqual('two') return it 'sorts by correct property when items are objects', -> filterable = ko.filterableArray [{id: '3'}, {id: '1'}, {id: '5'}] filterable.sortByString('id') expect(filterable()[0].id).toEqual('1') expect(filterable()[1].id).toEqual('3') expect(filterable()[2].id).toEqual('5') return it 'sorts by correct property when items are objects desc version', -> filterable = ko.filterableArray [{id: '3'}, {id: '1'}, {id: '5'}] filterable.sortByStringDesc('id') expect(filterable()[0].id).toEqual('5') expect(filterable()[1].id).toEqual('3') expect(filterable()[2].id).toEqual('1') return it 'sorts even when items are added and removed', -> filterable = ko.filterableArray [{id: '3'}, {id: '1'}, {id: '5'}] filterable.sortByStringDesc('id') filterable.push({id: '6'}) expect(filterable()[0].id).toEqual('6') filterable.shift() expect(filterable()[0].id).toEqual('5') it 'should pass through observableArray function to all', -> filterable = ko.filterableArray [] spyOn filterable.all, 'slice' spyOn filterable.all, 'replace' spyOn filterable.all, 'indexOf' spyOn filterable.all, 'destroy' spyOn filterable.all, 'destroyAll' spyOn filterable.all, 'remove' spyOn filterable.all, 'removeAll' filterable.slice([1]) expect(filterable.all.slice).toHaveBeenCalledWith([1]) filterable.replace('a', 'b') expect(filterable.all.replace).toHaveBeenCalledWith('a', 'b') filterable.indexOf({a:'a'}) expect(filterable.all.indexOf).toHaveBeenCalledWith({a:'a'}) filterable.destroy({}) expect(filterable.all.destroy).toHaveBeenCalledWith({}) filterable.destroyAll([{a:'a'}]) expect(filterable.all.destroyAll).toHaveBeenCalledWith([{a:'a'}]) filterable.remove([{a:'a'}]) expect(filterable.all.remove).toHaveBeenCalledWith([{a:'a'}]) filterable.removeAll([{a:'a'}]) expect(filterable.all.removeAll).toHaveBeenCalledWith([{a:'a'}]) return
[ { "context": "ApplicationController\n # @params \"email\", \"firstName\", \"lastName\"\n # \n # @return [Object]\n pa", "end": 825, "score": 0.9612492918968201, "start": 816, "tag": "NAME", "value": "firstName" }, { "context": "ntroller\n # @params \"email\", \"firstName\", \"lastName\"\n # \n # @return [Object]\n params: ->\n ", "end": 837, "score": 0.9452565908432007, "start": 829, "tag": "NAME", "value": "lastName" } ]
src/tower/controller/params.coffee
vjsingh/tower
1
# @mixin Tower.Controller.Params = ClassMethods: # Define a parameter that should be parsed into criteria for a model query. # # @example # class App.UsersController extends App.ApplicationController # @param "email" # # @param [String] key # @param [Object] options # @option options [String] type # # @return [Tower.HTTP.Param] param: (key, options) -> @params()[key] = Tower.HTTP.Param.create(key, options) # Return all params, or define multiple params at once. # # @example Pass in an object # class App.UsersController extends App.ApplicationController # @params email: "String" # # @example Pass in strings # class App.UsersController extends App.ApplicationController # @params "email", "firstName", "lastName" # # @return [Object] params: -> if arguments.length for arg in arguments if typeof arg == "object" @param(key, value) for key, value of arg else @param(arg) @metadata().params InstanceMethods: # Compile the params defined for this controller into a criteria for querying the database. # # @note The criteria is memoized. # # @return [Tower.Model.Criteria] criteria: -> return @_criteria if @_criteria @_criteria = criteria = new Tower.Model.Criteria parsers = @constructor.params() params = @params for name, parser of parsers if params.hasOwnProperty(name) criteria.where(parser.toCriteria(params[name])) criteria module.exports = Tower.Controller.Params
203983
# @mixin Tower.Controller.Params = ClassMethods: # Define a parameter that should be parsed into criteria for a model query. # # @example # class App.UsersController extends App.ApplicationController # @param "email" # # @param [String] key # @param [Object] options # @option options [String] type # # @return [Tower.HTTP.Param] param: (key, options) -> @params()[key] = Tower.HTTP.Param.create(key, options) # Return all params, or define multiple params at once. # # @example Pass in an object # class App.UsersController extends App.ApplicationController # @params email: "String" # # @example Pass in strings # class App.UsersController extends App.ApplicationController # @params "email", "<NAME>", "<NAME>" # # @return [Object] params: -> if arguments.length for arg in arguments if typeof arg == "object" @param(key, value) for key, value of arg else @param(arg) @metadata().params InstanceMethods: # Compile the params defined for this controller into a criteria for querying the database. # # @note The criteria is memoized. # # @return [Tower.Model.Criteria] criteria: -> return @_criteria if @_criteria @_criteria = criteria = new Tower.Model.Criteria parsers = @constructor.params() params = @params for name, parser of parsers if params.hasOwnProperty(name) criteria.where(parser.toCriteria(params[name])) criteria module.exports = Tower.Controller.Params
true
# @mixin Tower.Controller.Params = ClassMethods: # Define a parameter that should be parsed into criteria for a model query. # # @example # class App.UsersController extends App.ApplicationController # @param "email" # # @param [String] key # @param [Object] options # @option options [String] type # # @return [Tower.HTTP.Param] param: (key, options) -> @params()[key] = Tower.HTTP.Param.create(key, options) # Return all params, or define multiple params at once. # # @example Pass in an object # class App.UsersController extends App.ApplicationController # @params email: "String" # # @example Pass in strings # class App.UsersController extends App.ApplicationController # @params "email", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI" # # @return [Object] params: -> if arguments.length for arg in arguments if typeof arg == "object" @param(key, value) for key, value of arg else @param(arg) @metadata().params InstanceMethods: # Compile the params defined for this controller into a criteria for querying the database. # # @note The criteria is memoized. # # @return [Tower.Model.Criteria] criteria: -> return @_criteria if @_criteria @_criteria = criteria = new Tower.Model.Criteria parsers = @constructor.params() params = @params for name, parser of parsers if params.hasOwnProperty(name) criteria.where(parser.toCriteria(params[name])) criteria module.exports = Tower.Controller.Params
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9987885355949402, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-child-process-fork-exec-path.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. assert = require("assert") cp = require("child_process") fs = require("fs") path = require("path") common = require("../common") msg = test: "this" nodePath = process.execPath copyPath = path.join(common.tmpDir, "node-copy.exe") if process.env.FORK assert process.send assert.equal process.argv[0], copyPath process.send msg process.exit() else try fs.unlinkSync copyPath catch e throw e if e.code isnt "ENOENT" fs.writeFileSync copyPath, fs.readFileSync(nodePath) fs.chmodSync copyPath, "0755" # slow but simple envCopy = JSON.parse(JSON.stringify(process.env)) envCopy.FORK = "true" child = require("child_process").fork(__filename, execPath: copyPath env: envCopy ) child.on "message", common.mustCall((recv) -> assert.deepEqual msg, recv return ) child.on "exit", common.mustCall((code) -> fs.unlinkSync copyPath assert.equal code, 0 return )
81249
# 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. assert = require("assert") cp = require("child_process") fs = require("fs") path = require("path") common = require("../common") msg = test: "this" nodePath = process.execPath copyPath = path.join(common.tmpDir, "node-copy.exe") if process.env.FORK assert process.send assert.equal process.argv[0], copyPath process.send msg process.exit() else try fs.unlinkSync copyPath catch e throw e if e.code isnt "ENOENT" fs.writeFileSync copyPath, fs.readFileSync(nodePath) fs.chmodSync copyPath, "0755" # slow but simple envCopy = JSON.parse(JSON.stringify(process.env)) envCopy.FORK = "true" child = require("child_process").fork(__filename, execPath: copyPath env: envCopy ) child.on "message", common.mustCall((recv) -> assert.deepEqual msg, recv return ) child.on "exit", common.mustCall((code) -> fs.unlinkSync copyPath assert.equal code, 0 return )
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. assert = require("assert") cp = require("child_process") fs = require("fs") path = require("path") common = require("../common") msg = test: "this" nodePath = process.execPath copyPath = path.join(common.tmpDir, "node-copy.exe") if process.env.FORK assert process.send assert.equal process.argv[0], copyPath process.send msg process.exit() else try fs.unlinkSync copyPath catch e throw e if e.code isnt "ENOENT" fs.writeFileSync copyPath, fs.readFileSync(nodePath) fs.chmodSync copyPath, "0755" # slow but simple envCopy = JSON.parse(JSON.stringify(process.env)) envCopy.FORK = "true" child = require("child_process").fork(__filename, execPath: copyPath env: envCopy ) child.on "message", common.mustCall((recv) -> assert.deepEqual msg, recv return ) child.on "exit", common.mustCall((code) -> fs.unlinkSync copyPath assert.equal code, 0 return )
[ { "context": " \"resource\" : {\n \"accountName\" : \"Acme Foo\",\n \"accountNumber\" : accountNumber,\n", "end": 1939, "score": 0.9488396644592285, "start": 1931, "tag": "NAME", "value": "Acme Foo" } ]
src/com/redhat/ascension/rest/taskLogic.coffee
pbathia/ascension
0
fs = require 'fs' logger = require('tracer').colorConsole() settings = require '../settings/settings' prettyjson = require 'prettyjson' _ = require 'lodash' moment = require 'moment' Q = require 'q' #MongoOps = require '../db/MongoOperations' #mongoose = require 'mongoose' #mongooseQ = require('mongoose-q')(mongoose) #ObjectId = mongoose.Types.ObjectId ResourceOpEnum = require '../rules/enums/ResourceOpEnum' TaskActionsEnum = require './enums/taskActionsEnum' TaskStateEnum = require '../rules/enums/TaskStateEnum' TaskTypeEnum = require '../rules/enums/TaskTypeEnum' TaskOpEnum = require '../rules/enums/TaskOpEnum' request = require 'request' UserLogic = require './userLogic' TaskLogic = {} TaskLogic.mockTasks = [] TaskLogic.makeSfId = () -> text = "" possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" i = 0 while i < 18 text += possible.charAt(Math.floor(Math.random() * possible.length)).toUpperCase() i++ text TaskLogic.generateExampleTask = (caseNumber, accountNumber) -> score = Math.floor((Math.random() * 2000) + 1000) createdBySfId = TaskLogic.makeSfId() ownerSfId = TaskLogic.makeSfId() accountSfId = TaskLogic.makeSfId() caseSfId = TaskLogic.makeSfId() taskId = TaskLogic.makeSfId() # sfid is 18 chars long tmp = { "resource" : { "externalModelId" : taskId "closed" : "2014-12-16T12:01:11.000Z", "created" : "2014-10-30T14:55:11.000Z", "createdBy" : { "externalModelId" : createdBySfId }, "lastModified" : "2014-12-16T12:01:11.000Z", "resource" : { "externalModelId" : caseSfId "resource" : { "account" : { "externalModelId" : accountSfId "resource" : { "accountName" : "Acme Foo", "accountNumber" : accountNumber, "hasSRM" : true, "hasTAM" : true, "isActive" : true, "specialHandlingRequired" : true, "strategic" : true, "superRegion" : "NA" }, "resourceReliability" : "Fresh" }, "caseNumber" : caseNumber, "collaborationScore" : score, "created" : "2014-10-30T14:55:11.000Z", "internalPriority" : "1 (Urgent)", "internalStatus" : "Waiting on Owner", "isFTSCase" : false, "isTAMCase" : false, "lastModified" : "2014-12-16T12:01:11.000Z", "owner" : { "externalModelId" : ownerSfId "resourceReliability" : "Fresh" }, "product" : { "externalModelId" : null, "resource" : { "line" : { "externalModelId" : 1462, "resource" : { "name" : "Red Hat Storage Server" }, "resourceReliability" : "Fresh" }, "version" : { "externalModelId" : 17838, "resource" : { "name" : "3.0" }, "resourceReliability" : "Fresh" } }, "resourceReliability" : "Fresh" }, "sbrs" : [ "Filesystem" ], "sbt" : Math.floor((Math.random() * 100) + 1), "severity" : "1 (Urgent)", "status" : "Waiting on Red Hat", "subject" : "Example case", "summary" : "example summary", "tags" : [ "gluster" ] }, "resourceReliability" : "Fresh" }, "resourceOperation" : ResourceOpEnum.TAKE_OWNERSHIP.name, "score" : score, "status" : TaskStateEnum.UNASSIGNED.name, "taskOperation" : TaskOpEnum.NOOP.name, "type" : TaskTypeEnum.CASE.name } } tmp TaskLogic.fetchTasks = (opts) -> if opts?.ssoUsername? and opts?.ssoUsername isnt '' deferred = Q.defer() deferred.resolve TaskLogic.mockTasks return deferred.promise # uql = # where: "SSO is \"#{opts.ssoUsername}\"" # UserLogic.fetchUserUql(uql).then((user) -> # #ownerFindClause = # # 'state': {'$ne': 'closed'} # # '$or': [ # # { 'sbrs': {'$in': user.sbrs} } # # { 'owner.id': user.id } # # ] # # ownerFindClause = # 'owner.id': user.id # 'state': {'$ne': 'closed'} # 'declinedUsers.id': {'$ne': user.id} # # nonOwnerFindClause = # '$and': [ # {'state': {'$ne': 'closed'}} # {'sbrs': {'$in': user.sbrs} } unless user.sbrs is undefined # {'owner.id': {'$ne': user.id }} # {'declinedUsers.id': {'$ne': user.id}} # ] # # logger.debug "Searching mongo with ownerFindClause: #{JSON.stringify(ownerFindClause)}" # logger.debug "Searching mongo with nonOwnerFindClause: #{JSON.stringify(nonOwnerFindClause)}" # # # To force the top 7 owner tasks then other by score I need to sort by owner.id then by score. Or I could # # fetch all owner cases first and add those to the fetched tasks, not sure what is best atm # # # 005A0000002a7XZIAY rmanes # # db.tasks.find({'$or': [{'sbrs': {'$in': ['Kernel']}}, {'owner.id': '005A0000002a7XZIAY '}]}).sort({'owner.id': -1, score: -1}).limit(10) # # db.tasks.find({'owner.id': '005A0000002a7XZIAY '}).sort({'owner.id': -1, score: -1}).limit(10) # # ownerTasksPromise = MongoOps['models']['task'] # .find() # .where(ownerFindClause) # .limit(_.parseInt(opts.limit)) # .sort('-score') # score desc # .execQ() # # nonOwnerTasksPromise = MongoOps['models']['task'] # .find() # .where(nonOwnerFindClause) # .limit(_.parseInt(opts.limit)) # .sort('-score') # score desc # .execQ() # # [ownerTasksPromise, nonOwnerTasksPromise] # ) # #.then((tasks) -> # .spread((ownerTasks, nonOwnerTasks) -> # logger.debug "Discovered: #{ownerTasks.length} owner tasks, and #{nonOwnerTasks.length} non-owner tasks" # finalTasks = [] # # # If more than 7 owner tasks return only the top 7 owned # if ownerTasks.length > 7 # deferred.resolve ownerTasks[0..6] # # Otherwise push the owner tasks then the other tasks so the owner in front, then take the top 7 # else # logger.debug "Discovered: #{ownerTasks.length} owner tasks and #{nonOwnerTasks.length} non-owner tasks." # _.each ownerTasks, (t) -> finalTasks.push t # _.each nonOwnerTasks, (t) -> finalTasks.push t # deferred.resolve finalTasks[0..6] # ) # .catch((err) -> # deferred.reject err # ).done() # return deferred.promise # else # findClause = # 'state': {'$ne': 'closed'} # return MongoOps['models']['task'].find().where(findClause).limit(_.parseInt(opts.limit)).execQ() TaskLogic.fetchTask = (opts) -> deferred = Q.defer() deferred.resolve _.find(TaskLogic.mockTasks, (t) -> t.resource?.resource?.caseNumber is opts.caseNumber) deferred.promise # MongoOps['models']['task'] # .findById(opts['_id']).execQ() # TaskLogic.updateTask = (opts) -> deferred = Q.defer() deferred.resolve undefined deferred.promise # if opts.action is TaskActionsEnum.ASSIGN.name and opts.userInput? # UserLogic.fetchUser(opts).then((user) -> # $set = # $set: # state: TaskStateEnum.ASSIGNED.name # taskOp: TaskOpEnum.COMPLETE_TASK.name # owner: user # # MongoOps['models']['task'].findOneAndUpdate({_id: new ObjectId(opts['_id'])}, $set).execQ() # ) # .then(() -> # deferred.resolve() # ).catch((err) -> # deferred.reject err # ).done() # else if opts.action is TaskActionsEnum.DECLINE.name # UserLogic.fetchUser(opts) # .then((user) -> # $update = # $push: # declinedUsers: # id: user['id'] # sso: user['sso'] # fullName: user['fullName'] # declinedOn: new Date() # logger.debug "Declining the event with #{prettyjson.render $update}" # MongoOps['models']['task'].findOneAndUpdate({_id: new ObjectId(opts['_id'])}, $update).execQ() # ) # .then(-> # deferred.resolve() # ).catch((err) -> # deferred.reject err # ).done() # else if opts.action is TaskActionsEnum.UNASSIGN.name # $set = # $set: # state: TaskStateEnum.UNASSIGNED.name # taskOp: TaskOpEnum.OWN_TASK.name # owner: null # # MongoOps['models']['task'].findOneAndUpdate({_id: new ObjectId(opts['_id'])}, $set).execQ() # .then(-> # deferred.resolve() # ).catch((err) -> # deferred.reject err # ).done() # else if opts.action is TaskActionsEnum.CLOSE.name # $set = # $set: # state: TaskStateEnum.CLOSED.name # taskOp: TaskOpEnum.NOOP.name # closed: new Date() # # MongoOps['models']['task'].findOneAndUpdate({_id: new ObjectId(opts['_id'])}, $set).execQ() # .then(-> # deferred.resolve() # ).catch((err) -> # deferred.reject err # ).done() # else # deferred.reject "#{opts.action} is not a known action" # # deferred.promise module.exports = TaskLogic
214846
fs = require 'fs' logger = require('tracer').colorConsole() settings = require '../settings/settings' prettyjson = require 'prettyjson' _ = require 'lodash' moment = require 'moment' Q = require 'q' #MongoOps = require '../db/MongoOperations' #mongoose = require 'mongoose' #mongooseQ = require('mongoose-q')(mongoose) #ObjectId = mongoose.Types.ObjectId ResourceOpEnum = require '../rules/enums/ResourceOpEnum' TaskActionsEnum = require './enums/taskActionsEnum' TaskStateEnum = require '../rules/enums/TaskStateEnum' TaskTypeEnum = require '../rules/enums/TaskTypeEnum' TaskOpEnum = require '../rules/enums/TaskOpEnum' request = require 'request' UserLogic = require './userLogic' TaskLogic = {} TaskLogic.mockTasks = [] TaskLogic.makeSfId = () -> text = "" possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" i = 0 while i < 18 text += possible.charAt(Math.floor(Math.random() * possible.length)).toUpperCase() i++ text TaskLogic.generateExampleTask = (caseNumber, accountNumber) -> score = Math.floor((Math.random() * 2000) + 1000) createdBySfId = TaskLogic.makeSfId() ownerSfId = TaskLogic.makeSfId() accountSfId = TaskLogic.makeSfId() caseSfId = TaskLogic.makeSfId() taskId = TaskLogic.makeSfId() # sfid is 18 chars long tmp = { "resource" : { "externalModelId" : taskId "closed" : "2014-12-16T12:01:11.000Z", "created" : "2014-10-30T14:55:11.000Z", "createdBy" : { "externalModelId" : createdBySfId }, "lastModified" : "2014-12-16T12:01:11.000Z", "resource" : { "externalModelId" : caseSfId "resource" : { "account" : { "externalModelId" : accountSfId "resource" : { "accountName" : "<NAME>", "accountNumber" : accountNumber, "hasSRM" : true, "hasTAM" : true, "isActive" : true, "specialHandlingRequired" : true, "strategic" : true, "superRegion" : "NA" }, "resourceReliability" : "Fresh" }, "caseNumber" : caseNumber, "collaborationScore" : score, "created" : "2014-10-30T14:55:11.000Z", "internalPriority" : "1 (Urgent)", "internalStatus" : "Waiting on Owner", "isFTSCase" : false, "isTAMCase" : false, "lastModified" : "2014-12-16T12:01:11.000Z", "owner" : { "externalModelId" : ownerSfId "resourceReliability" : "Fresh" }, "product" : { "externalModelId" : null, "resource" : { "line" : { "externalModelId" : 1462, "resource" : { "name" : "Red Hat Storage Server" }, "resourceReliability" : "Fresh" }, "version" : { "externalModelId" : 17838, "resource" : { "name" : "3.0" }, "resourceReliability" : "Fresh" } }, "resourceReliability" : "Fresh" }, "sbrs" : [ "Filesystem" ], "sbt" : Math.floor((Math.random() * 100) + 1), "severity" : "1 (Urgent)", "status" : "Waiting on Red Hat", "subject" : "Example case", "summary" : "example summary", "tags" : [ "gluster" ] }, "resourceReliability" : "Fresh" }, "resourceOperation" : ResourceOpEnum.TAKE_OWNERSHIP.name, "score" : score, "status" : TaskStateEnum.UNASSIGNED.name, "taskOperation" : TaskOpEnum.NOOP.name, "type" : TaskTypeEnum.CASE.name } } tmp TaskLogic.fetchTasks = (opts) -> if opts?.ssoUsername? and opts?.ssoUsername isnt '' deferred = Q.defer() deferred.resolve TaskLogic.mockTasks return deferred.promise # uql = # where: "SSO is \"#{opts.ssoUsername}\"" # UserLogic.fetchUserUql(uql).then((user) -> # #ownerFindClause = # # 'state': {'$ne': 'closed'} # # '$or': [ # # { 'sbrs': {'$in': user.sbrs} } # # { 'owner.id': user.id } # # ] # # ownerFindClause = # 'owner.id': user.id # 'state': {'$ne': 'closed'} # 'declinedUsers.id': {'$ne': user.id} # # nonOwnerFindClause = # '$and': [ # {'state': {'$ne': 'closed'}} # {'sbrs': {'$in': user.sbrs} } unless user.sbrs is undefined # {'owner.id': {'$ne': user.id }} # {'declinedUsers.id': {'$ne': user.id}} # ] # # logger.debug "Searching mongo with ownerFindClause: #{JSON.stringify(ownerFindClause)}" # logger.debug "Searching mongo with nonOwnerFindClause: #{JSON.stringify(nonOwnerFindClause)}" # # # To force the top 7 owner tasks then other by score I need to sort by owner.id then by score. Or I could # # fetch all owner cases first and add those to the fetched tasks, not sure what is best atm # # # 005A0000002a7XZIAY rmanes # # db.tasks.find({'$or': [{'sbrs': {'$in': ['Kernel']}}, {'owner.id': '005A0000002a7XZIAY '}]}).sort({'owner.id': -1, score: -1}).limit(10) # # db.tasks.find({'owner.id': '005A0000002a7XZIAY '}).sort({'owner.id': -1, score: -1}).limit(10) # # ownerTasksPromise = MongoOps['models']['task'] # .find() # .where(ownerFindClause) # .limit(_.parseInt(opts.limit)) # .sort('-score') # score desc # .execQ() # # nonOwnerTasksPromise = MongoOps['models']['task'] # .find() # .where(nonOwnerFindClause) # .limit(_.parseInt(opts.limit)) # .sort('-score') # score desc # .execQ() # # [ownerTasksPromise, nonOwnerTasksPromise] # ) # #.then((tasks) -> # .spread((ownerTasks, nonOwnerTasks) -> # logger.debug "Discovered: #{ownerTasks.length} owner tasks, and #{nonOwnerTasks.length} non-owner tasks" # finalTasks = [] # # # If more than 7 owner tasks return only the top 7 owned # if ownerTasks.length > 7 # deferred.resolve ownerTasks[0..6] # # Otherwise push the owner tasks then the other tasks so the owner in front, then take the top 7 # else # logger.debug "Discovered: #{ownerTasks.length} owner tasks and #{nonOwnerTasks.length} non-owner tasks." # _.each ownerTasks, (t) -> finalTasks.push t # _.each nonOwnerTasks, (t) -> finalTasks.push t # deferred.resolve finalTasks[0..6] # ) # .catch((err) -> # deferred.reject err # ).done() # return deferred.promise # else # findClause = # 'state': {'$ne': 'closed'} # return MongoOps['models']['task'].find().where(findClause).limit(_.parseInt(opts.limit)).execQ() TaskLogic.fetchTask = (opts) -> deferred = Q.defer() deferred.resolve _.find(TaskLogic.mockTasks, (t) -> t.resource?.resource?.caseNumber is opts.caseNumber) deferred.promise # MongoOps['models']['task'] # .findById(opts['_id']).execQ() # TaskLogic.updateTask = (opts) -> deferred = Q.defer() deferred.resolve undefined deferred.promise # if opts.action is TaskActionsEnum.ASSIGN.name and opts.userInput? # UserLogic.fetchUser(opts).then((user) -> # $set = # $set: # state: TaskStateEnum.ASSIGNED.name # taskOp: TaskOpEnum.COMPLETE_TASK.name # owner: user # # MongoOps['models']['task'].findOneAndUpdate({_id: new ObjectId(opts['_id'])}, $set).execQ() # ) # .then(() -> # deferred.resolve() # ).catch((err) -> # deferred.reject err # ).done() # else if opts.action is TaskActionsEnum.DECLINE.name # UserLogic.fetchUser(opts) # .then((user) -> # $update = # $push: # declinedUsers: # id: user['id'] # sso: user['sso'] # fullName: user['fullName'] # declinedOn: new Date() # logger.debug "Declining the event with #{prettyjson.render $update}" # MongoOps['models']['task'].findOneAndUpdate({_id: new ObjectId(opts['_id'])}, $update).execQ() # ) # .then(-> # deferred.resolve() # ).catch((err) -> # deferred.reject err # ).done() # else if opts.action is TaskActionsEnum.UNASSIGN.name # $set = # $set: # state: TaskStateEnum.UNASSIGNED.name # taskOp: TaskOpEnum.OWN_TASK.name # owner: null # # MongoOps['models']['task'].findOneAndUpdate({_id: new ObjectId(opts['_id'])}, $set).execQ() # .then(-> # deferred.resolve() # ).catch((err) -> # deferred.reject err # ).done() # else if opts.action is TaskActionsEnum.CLOSE.name # $set = # $set: # state: TaskStateEnum.CLOSED.name # taskOp: TaskOpEnum.NOOP.name # closed: new Date() # # MongoOps['models']['task'].findOneAndUpdate({_id: new ObjectId(opts['_id'])}, $set).execQ() # .then(-> # deferred.resolve() # ).catch((err) -> # deferred.reject err # ).done() # else # deferred.reject "#{opts.action} is not a known action" # # deferred.promise module.exports = TaskLogic
true
fs = require 'fs' logger = require('tracer').colorConsole() settings = require '../settings/settings' prettyjson = require 'prettyjson' _ = require 'lodash' moment = require 'moment' Q = require 'q' #MongoOps = require '../db/MongoOperations' #mongoose = require 'mongoose' #mongooseQ = require('mongoose-q')(mongoose) #ObjectId = mongoose.Types.ObjectId ResourceOpEnum = require '../rules/enums/ResourceOpEnum' TaskActionsEnum = require './enums/taskActionsEnum' TaskStateEnum = require '../rules/enums/TaskStateEnum' TaskTypeEnum = require '../rules/enums/TaskTypeEnum' TaskOpEnum = require '../rules/enums/TaskOpEnum' request = require 'request' UserLogic = require './userLogic' TaskLogic = {} TaskLogic.mockTasks = [] TaskLogic.makeSfId = () -> text = "" possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" i = 0 while i < 18 text += possible.charAt(Math.floor(Math.random() * possible.length)).toUpperCase() i++ text TaskLogic.generateExampleTask = (caseNumber, accountNumber) -> score = Math.floor((Math.random() * 2000) + 1000) createdBySfId = TaskLogic.makeSfId() ownerSfId = TaskLogic.makeSfId() accountSfId = TaskLogic.makeSfId() caseSfId = TaskLogic.makeSfId() taskId = TaskLogic.makeSfId() # sfid is 18 chars long tmp = { "resource" : { "externalModelId" : taskId "closed" : "2014-12-16T12:01:11.000Z", "created" : "2014-10-30T14:55:11.000Z", "createdBy" : { "externalModelId" : createdBySfId }, "lastModified" : "2014-12-16T12:01:11.000Z", "resource" : { "externalModelId" : caseSfId "resource" : { "account" : { "externalModelId" : accountSfId "resource" : { "accountName" : "PI:NAME:<NAME>END_PI", "accountNumber" : accountNumber, "hasSRM" : true, "hasTAM" : true, "isActive" : true, "specialHandlingRequired" : true, "strategic" : true, "superRegion" : "NA" }, "resourceReliability" : "Fresh" }, "caseNumber" : caseNumber, "collaborationScore" : score, "created" : "2014-10-30T14:55:11.000Z", "internalPriority" : "1 (Urgent)", "internalStatus" : "Waiting on Owner", "isFTSCase" : false, "isTAMCase" : false, "lastModified" : "2014-12-16T12:01:11.000Z", "owner" : { "externalModelId" : ownerSfId "resourceReliability" : "Fresh" }, "product" : { "externalModelId" : null, "resource" : { "line" : { "externalModelId" : 1462, "resource" : { "name" : "Red Hat Storage Server" }, "resourceReliability" : "Fresh" }, "version" : { "externalModelId" : 17838, "resource" : { "name" : "3.0" }, "resourceReliability" : "Fresh" } }, "resourceReliability" : "Fresh" }, "sbrs" : [ "Filesystem" ], "sbt" : Math.floor((Math.random() * 100) + 1), "severity" : "1 (Urgent)", "status" : "Waiting on Red Hat", "subject" : "Example case", "summary" : "example summary", "tags" : [ "gluster" ] }, "resourceReliability" : "Fresh" }, "resourceOperation" : ResourceOpEnum.TAKE_OWNERSHIP.name, "score" : score, "status" : TaskStateEnum.UNASSIGNED.name, "taskOperation" : TaskOpEnum.NOOP.name, "type" : TaskTypeEnum.CASE.name } } tmp TaskLogic.fetchTasks = (opts) -> if opts?.ssoUsername? and opts?.ssoUsername isnt '' deferred = Q.defer() deferred.resolve TaskLogic.mockTasks return deferred.promise # uql = # where: "SSO is \"#{opts.ssoUsername}\"" # UserLogic.fetchUserUql(uql).then((user) -> # #ownerFindClause = # # 'state': {'$ne': 'closed'} # # '$or': [ # # { 'sbrs': {'$in': user.sbrs} } # # { 'owner.id': user.id } # # ] # # ownerFindClause = # 'owner.id': user.id # 'state': {'$ne': 'closed'} # 'declinedUsers.id': {'$ne': user.id} # # nonOwnerFindClause = # '$and': [ # {'state': {'$ne': 'closed'}} # {'sbrs': {'$in': user.sbrs} } unless user.sbrs is undefined # {'owner.id': {'$ne': user.id }} # {'declinedUsers.id': {'$ne': user.id}} # ] # # logger.debug "Searching mongo with ownerFindClause: #{JSON.stringify(ownerFindClause)}" # logger.debug "Searching mongo with nonOwnerFindClause: #{JSON.stringify(nonOwnerFindClause)}" # # # To force the top 7 owner tasks then other by score I need to sort by owner.id then by score. Or I could # # fetch all owner cases first and add those to the fetched tasks, not sure what is best atm # # # 005A0000002a7XZIAY rmanes # # db.tasks.find({'$or': [{'sbrs': {'$in': ['Kernel']}}, {'owner.id': '005A0000002a7XZIAY '}]}).sort({'owner.id': -1, score: -1}).limit(10) # # db.tasks.find({'owner.id': '005A0000002a7XZIAY '}).sort({'owner.id': -1, score: -1}).limit(10) # # ownerTasksPromise = MongoOps['models']['task'] # .find() # .where(ownerFindClause) # .limit(_.parseInt(opts.limit)) # .sort('-score') # score desc # .execQ() # # nonOwnerTasksPromise = MongoOps['models']['task'] # .find() # .where(nonOwnerFindClause) # .limit(_.parseInt(opts.limit)) # .sort('-score') # score desc # .execQ() # # [ownerTasksPromise, nonOwnerTasksPromise] # ) # #.then((tasks) -> # .spread((ownerTasks, nonOwnerTasks) -> # logger.debug "Discovered: #{ownerTasks.length} owner tasks, and #{nonOwnerTasks.length} non-owner tasks" # finalTasks = [] # # # If more than 7 owner tasks return only the top 7 owned # if ownerTasks.length > 7 # deferred.resolve ownerTasks[0..6] # # Otherwise push the owner tasks then the other tasks so the owner in front, then take the top 7 # else # logger.debug "Discovered: #{ownerTasks.length} owner tasks and #{nonOwnerTasks.length} non-owner tasks." # _.each ownerTasks, (t) -> finalTasks.push t # _.each nonOwnerTasks, (t) -> finalTasks.push t # deferred.resolve finalTasks[0..6] # ) # .catch((err) -> # deferred.reject err # ).done() # return deferred.promise # else # findClause = # 'state': {'$ne': 'closed'} # return MongoOps['models']['task'].find().where(findClause).limit(_.parseInt(opts.limit)).execQ() TaskLogic.fetchTask = (opts) -> deferred = Q.defer() deferred.resolve _.find(TaskLogic.mockTasks, (t) -> t.resource?.resource?.caseNumber is opts.caseNumber) deferred.promise # MongoOps['models']['task'] # .findById(opts['_id']).execQ() # TaskLogic.updateTask = (opts) -> deferred = Q.defer() deferred.resolve undefined deferred.promise # if opts.action is TaskActionsEnum.ASSIGN.name and opts.userInput? # UserLogic.fetchUser(opts).then((user) -> # $set = # $set: # state: TaskStateEnum.ASSIGNED.name # taskOp: TaskOpEnum.COMPLETE_TASK.name # owner: user # # MongoOps['models']['task'].findOneAndUpdate({_id: new ObjectId(opts['_id'])}, $set).execQ() # ) # .then(() -> # deferred.resolve() # ).catch((err) -> # deferred.reject err # ).done() # else if opts.action is TaskActionsEnum.DECLINE.name # UserLogic.fetchUser(opts) # .then((user) -> # $update = # $push: # declinedUsers: # id: user['id'] # sso: user['sso'] # fullName: user['fullName'] # declinedOn: new Date() # logger.debug "Declining the event with #{prettyjson.render $update}" # MongoOps['models']['task'].findOneAndUpdate({_id: new ObjectId(opts['_id'])}, $update).execQ() # ) # .then(-> # deferred.resolve() # ).catch((err) -> # deferred.reject err # ).done() # else if opts.action is TaskActionsEnum.UNASSIGN.name # $set = # $set: # state: TaskStateEnum.UNASSIGNED.name # taskOp: TaskOpEnum.OWN_TASK.name # owner: null # # MongoOps['models']['task'].findOneAndUpdate({_id: new ObjectId(opts['_id'])}, $set).execQ() # .then(-> # deferred.resolve() # ).catch((err) -> # deferred.reject err # ).done() # else if opts.action is TaskActionsEnum.CLOSE.name # $set = # $set: # state: TaskStateEnum.CLOSED.name # taskOp: TaskOpEnum.NOOP.name # closed: new Date() # # MongoOps['models']['task'].findOneAndUpdate({_id: new ObjectId(opts['_id'])}, $set).execQ() # .then(-> # deferred.resolve() # ).catch((err) -> # deferred.reject err # ).done() # else # deferred.reject "#{opts.action} is not a known action" # # deferred.promise module.exports = TaskLogic
[ { "context": "ts\n\n sel = {\n owner: ownerName\n name: synchroName\n }\n unless collectionContains(@sync", "end": 5707, "score": 0.6561344265937805, "start": 5704, "tag": "NAME", "value": "syn" }, { "context": "@synchros.update {\n owner: ownerName, name: synchroName\n }, {\n $set: { mtimeMaxProcessed }\n ", "end": 15108, "score": 0.9715652465820312, "start": 15097, "tag": "NAME", "value": "synchroName" }, { "context": "createTree euid, {\n ownerName\n repoName: synchroName\n content: root\n }\n\n # XXX: The s", "end": 15661, "score": 0.5441352128982544, "start": 15658, "tag": "NAME", "value": "syn" }, { "context": "chros.findOne({\n owner: ownerName\n name: synchroName\n })\n return synchro?.op\n\n\ncreateSyn", "end": 20922, "score": 0.779264509677887, "start": 20919, "tag": "NAME", "value": "syn" } ]
packages/nog-sync/nog-sync-store.coffee
nogproject/nog
0
{ check, Match } = require 'meteor/check' { createStagingPrefixTree } = require './nog-sync-merge-lib.coffee' { createEntryCache, createEntryNullCache, } = require './nog-sync-store-cache.js' { createContentCollections createContentStore } = NogContent { ERR_UNKNOWN_USERNAME ERR_UPDATE_SYNCHRO ERR_SYNCHRO_MISSING ERR_SYNCHRO_CONTENT_MISSING ERR_CONTENT_MISSING ERR_CONTENT_CHECKSUM nogthrow } = NogError NULL_SHA1 = '0000000000000000000000000000000000000000' RAW = {transform: false} AA_GET_SYNCHRO_CONTENT = 'nog-sync/get' AA_MODIFY_SYNCHRO_CONTENT = 'nog-sync/modify' AA_CREATE_SYNCHRO = 'nog-sync/create' isDuplicateMongoIdError = (err) -> return err.code == 11000 crypto = require('crypto') sha1_hex = (d) -> crypto.createHash('sha1').update(d, 'utf8').digest('hex') # `decodeMeta()` is identical to nogcontent. # # `verifyEncodedContent()` assumes that the sha verification works for any the # `_idversion`. decodeMeta = (encMeta) -> meta = _.omit encMeta, 'more' for r in encMeta.more ? [] meta[r.key] = r.val meta verifyEncodedContent = (type, content) -> d = _.clone content d.meta = decodeMeta d.meta if d._id != NogContent.contentId(NogContent.stripped(d)) nogthrow ERR_CONTENT_CHECKSUM, {type, sha1: d._id} matchSimpleName = Match.Where (x) -> check x, String if not (x.match /// ^ [a-zA-Z0-9-_]+ $ ///)? throw new Match.Error 'Invalid simple name.' true matchSimpleRelPath = Match.Where (x) -> check x, String if not (x.match /// ^ [a-zA-Z0-9-_]+ ( / [a-zA-Z0-9-_]+ )* $ ///)? throw new Match.Error 'Invalid ref name.' true matchSha1 = Match.Where (x) -> check x, String if not (x.match /^[0-9a-f]{40}$/)? throw new Match.Error 'not a sha1' true # `find().size()` as discussed on SO <http://stackoverflow.com/a/8390458> does # not work with the Meteor Mongo wrapper. Use `findOne()` instead and retrieve # only the id. collectionContains = (coll, sel) -> coll.findOne sel, {fields: {_id: 1}} leafFromRepo = (repo) -> master = repo.refs['branches/master'] cmaster = repo.conflicts?['branches/master'] if cmaster? refs = {} if master? cmaster = cmaster.concat([master]) else cmaster = cmaster.concat([NULL_SHA1]) cmaster.sort() cmaster = _.uniq(cmaster, 1) # 1 == isSorted. conflicts = { 'branches/master': cmaster } else conflicts = {} if master? refs = { 'branches/master': master } else refs = {} name = ['repo', repo.owner, repo.name].join(':') leaf = { name meta: { nog: { name: repo.name, owner: repo.owner, refs, conflicts, } } # XXX Maybe store entries `{type: 'commit', sha1: p[1]}` to prevent gc. entries: [] } _getRawEntriesFromStore = (store, opts) -> { treeShas, objectShas } = opts treeShas = _.unique(treeShas) objectShas = _.unique(objectShas) trees = [] if treeShas.length > 0 store.trees.find({ _id: { $in: treeShas } }, RAW).map (t) => trees.push(t) unless trees.length == treeShas.length nogthrow ERR_CONTENT_MISSING objects = [] if objectShas.length > 0 store.objects.find({ _id: { $in: objectShas } }, RAW).map (o) => objects.push(o) unless objects.length == objectShas.length nogthrow ERR_CONTENT_MISSING return { trees, objects } class SyncStore constructor: (opts) -> { @synchros, @commits, @trees, @objects, @users, @contentStore, @ourPeerName, @checkAccess, @testAccess, @cache } = opts @nRepoPrefixLevels = 2 # Use a ContentStore without access control as the low-level store. Access # control for the low-level store is disabled, since `SyncStore` checks # access for its high-level operation, and access should not be checked # again with a different action. @_syncStore = createContentStore { repos: @synchros commits: @commits trees: @trees objects: @objects users: @users blobs: null deletedRepos: null reposSets: null checkAccess: -> } getRefs: (euid, opts) -> check opts, { ownerName: matchSimpleName synchroName: matchSimpleName } @checkAccess euid, AA_GET_SYNCHRO_CONTENT, opts { ownerName, synchroName } = opts sel = { owner: ownerName, name: synchroName, } fields = { refs: 1 } unless (s = @synchros.findOne(sel, { fields }))? nogthrow ERR_SYNCHRO_MISSING return s.refs updateRef: (euid, opts) -> check opts.synchroName, matchSimpleName # Rely on `_syncStore` to check remaining fields. @checkAccess euid, AA_MODIFY_SYNCHRO_CONTENT, opts opts.repoName = opts.synchroName delete opts.synchroName @_syncStore.updateRef euid, opts createTree: (euid, opts) -> check opts.synchroName, matchSimpleName # Rely on `_syncStore` to check remaining fields. @checkAccess euid, AA_MODIFY_SYNCHRO_CONTENT, opts opts.repoName = opts.synchroName delete opts.synchroName @_syncStore.createTree euid, opts createCommit: (euid, opts) -> check opts.synchroName, matchSimpleName # Rely on `_syncStore` to check remaining fields. @checkAccess euid, AA_MODIFY_SYNCHRO_CONTENT, opts opts.repoName = opts.synchroName delete opts.synchroName @_syncStore.createCommit euid, opts ensureSynchro: (euid, opts) -> check opts, { ownerName: matchSimpleName synchroName: matchSimpleName selector: Match.Optional { repos: Object } } {ownerName, synchroName, selector} = opts selector ?= {repos: {}, users: {}} @checkAccess euid, AA_CREATE_SYNCHRO, opts sel = { owner: ownerName name: synchroName } unless collectionContains(@synchros, sel) @_syncStore.createRepo euid, { repoFullName: [ownerName, synchroName].join('/') } n = @synchros.update sel, {$set: {selector}} unless n == 1 nogthrow ERR_UPDATE_SYNCHRO, { reason: 'Failed to update selector.' } return getPing: (euid, opts) -> check opts, {owner: String} @checkAccess euid, AA_GET_SYNCHRO_CONTENT, opts {owner} = opts unless (s = @synchros.findOne({owner}, {fields: {_ping: 1}}))? return null return s._ping # Functions `*Raw()` use encoded meta as it is stored in Mongo. # # Functions `*RawSudo()` run without access check. They are for code paths # that have already checked access on a higher level. # # Functions `insert*Raw*()` bypass dependency checks. The caller should # use them responsibly in order to preserve invariants: # # - Trees and objects must be deep, that is dependencies must be inserted # first. # # - Commits may be shallow, that is they may be inserted without parents. It # is undefined whether shallow provides any guarantees. The safest # approach, when the synchro code is active, is to assume nothing about # commit ranges. For example, a commit walk should not make assumptions # about the presence of parent commits solely based on the presence of a # commit. It may be safe, though, to assume that all parent commits are # present if a content ref points to a commit. getCommitRaw: (euid, opts) -> check opts, {sha: matchSha1} @checkAccess euid, AA_GET_SYNCHRO_CONTENT, opts {sha} = opts unless (commit = @commits.findOne(sha, RAW))? nogthrow ERR_SYNCHRO_CONTENT_MISSING, {commit: sha} return commit getTreeRaw: (euid, opts) -> check opts, {sha: matchSha1} @checkAccess euid, AA_GET_SYNCHRO_CONTENT, opts {sha} = opts unless (tree = @trees.findOne(sha, RAW))? nogthrow ERR_SYNCHRO_CONTENT_MISSING, {tree: sha} return tree getObjectRaw: (euid, opts) -> check opts, {sha: matchSha1} @checkAccess euid, AA_GET_SYNCHRO_CONTENT, opts {sha} = opts unless (object = @objects.findOne(sha, RAW))? nogthrow ERR_SYNCHRO_CONTENT_MISSING, {object: sha} return object getEntriesRaw: (euid, opts) -> check opts, { treeShas: [matchSha1], objectShas: [matchSha1], } @checkAccess euid, AA_GET_SYNCHRO_CONTENT, opts return _getRawEntriesFromStore this, opts insertCommitRawSudo: (opts) -> { content } = opts verifyEncodedContent 'commit', content try @commits.insert content catch err # Duplicate id indicates that we already had the commit. unless isDuplicateMongoIdError err throw err insertTreeRawSudo: (opts) -> { content } = opts verifyEncodedContent 'tree', content try @trees.insert content catch err # Duplicate id indicates that we already had the tree. unless isDuplicateMongoIdError err throw err insertObjectRawSudo: (opts) -> { content } = opts verifyEncodedContent 'object', content try @objects.insert content catch err # Duplicate id indicates that we already had the object. unless isDuplicateMongoIdError err throw err hasTreeSudo: (opts) -> @_syncStore.hasTreeSudo opts hasObjectSudo: (opts) -> @_syncStore.hasObjectSudo opts getCommitSudo: (opts) -> check opts, { sha: matchSha1 } { sha } = opts if (commit = @cache.get(sha))? return commit unless (commit = @commits.findOne(sha))? nogthrow ERR_SYNCHRO_CONTENT_MISSING, { commit: sha } @cache.add(commit) return commit getTreeSudo: (opts) -> check opts, { sha: matchSha1 } {sha} = opts if (tree = @cache.get(sha))? return tree unless (tree = @trees.findOne(sha))? nogthrow ERR_SYNCHRO_CONTENT_MISSING, { tree: sha } @cache.add(tree) return tree getObjectSudo: (euid, opts) -> check opts, { sha: matchSha1 } {sha} = opts if (object = @cache.get(sha))? return object unless (object = @objects.findOne(sha))? nogthrow ERR_SYNCHRO_CONTENT_MISSING, { object: sha } @cache.add(object) return object # The `getContent*()` calls skip the usual content access checks, such as # `action: 'nog-content/get'` and require synchro access permission instead. # This should be fine for root-like nogsyncbots, which have permission to # access all content. # # We'd need to reconsider if we wanted to extend the synchro design to # ordinary users. getContentCommitRaw: (euid, opts) -> check opts, { sha: matchSha1 } @checkAccess euid, AA_GET_SYNCHRO_CONTENT, opts { sha } = opts unless (commit = @contentStore.commits.findOne(sha, RAW))? nogthrow ERR_CONTENT_MISSING, { commit: sha } return commit getContentTreeRaw: (euid, opts) -> check opts, { sha: matchSha1 } @checkAccess euid, AA_GET_SYNCHRO_CONTENT, opts { sha } = opts unless (tree = @contentStore.trees.findOne(sha, RAW))? nogthrow ERR_CONTENT_MISSING, { tree: sha } return tree getContentObjectRaw: (euid, opts) -> check opts, { sha: matchSha1 } @checkAccess euid, AA_GET_SYNCHRO_CONTENT, opts { sha } = opts unless (object = @contentStore.objects.findOne(sha, RAW))? nogthrow ERR_CONTENT_MISSING, { object: sha } return object getContentEntriesRaw: (euid, opts) -> check opts, { treeShas: [matchSha1], objectShas: [matchSha1], } @checkAccess euid, AA_GET_SYNCHRO_CONTENT, opts return _getRawEntriesFromStore @contentStore, opts insertContentCommitRawSudo: (opts) -> { content } = opts verifyEncodedContent 'commit', content try @contentStore.commits.insert content catch err # Duplicate id indicates that we already had the commit. unless isDuplicateMongoIdError err throw err insertContentTreeRawSudo: (opts) -> { content } = opts verifyEncodedContent 'tree', content try @contentStore.trees.insert content catch err # Duplicate id indicates that we already had the tree. unless isDuplicateMongoIdError err throw err insertContentObjectRawSudo: (opts) -> { content } = opts verifyEncodedContent 'object', content try @contentStore.objects.insert content catch err # Duplicate id indicates that we already had the object. unless isDuplicateMongoIdError err throw err # XXX The meaning of blob placeholders need to be clarified. We will # probably add a notion of a remote blob that is pending transfer. # We should also support storing blobs in multiple caches. insertContentBlobPlaceholderSudo: (opts) -> check opts, { sha: matchSha1 } { sha } = opts blob = { _id: sha, sha1: sha, status: 'placeholder', size: -1, } try @contentStore.blobs.insert blob catch err # Duplicate id indicates that we already had the object. unless isDuplicateMongoIdError err throw err snapshot: (args...) -> @snapshotAnonC args... fullSnapshot: (args...) -> @fullSnapshotAnonC args... snapshotAnonC: (euid, opts) -> check opts, { ownerName: matchSimpleName synchroName: matchSimpleName } @checkAccess euid, AA_MODIFY_SYNCHRO_CONTENT, opts opts = _.extend({ conflictStyle: 'anonymous', strategy: 'incremental' }, opts) @_snapshot(euid, opts) fullSnapshotAnonC: (euid, opts) -> check opts, { ownerName: matchSimpleName synchroName: matchSimpleName } @checkAccess euid, AA_MODIFY_SYNCHRO_CONTENT, opts opts = _.extend({ conflictStyle: 'anonymous', strategy: 'full' }, opts) @_snapshot(euid, opts) _snapshot: (euid, opts) -> {ownerName, synchroName, conflictStyle, strategy} = opts refName = 'branches/master' sel = { owner: ownerName name: synchroName } unless (syn = @synchros.findOne(sel))? nogthrow ERR_SYNCHRO_MISSING old = syn.refs[refName] ? NULL_SHA1 if (op = @getOp({ ownerName, synchroName }))? console.log("[nog-sync] refusing snapshot due to active op #{op.op}.") return { status: 'refused', commit: old } mtimeMaxProcessed = null if strategy == 'incremental' && old != NULL_SHA1 { mtimeMaxProcessed, rootSha } = @_incrSnapshotTree euid, { syn, ownerName, synchroName, baseCommitSha: old } else rootSha = @_fullSnapshotTree euid, { syn, ownerName, synchroName, conflictStyle } # Keep old commit if already up-to-date. unless old == NULL_SHA1 oldc = @_syncStore.getCommit euid, { ownerName repoName: synchroName sha1: old } if oldc.tree == rootSha return {status: 'unchanged', commit: old} commit = { subject: 'Sync snapshot' message: '' parents: (if old != NULL_SHA1 then [old] else []) tree: rootSha } commitId = @_syncStore.createCommit euid, { ownerName repoName: synchroName content: commit } @_syncStore.updateRef euid, { ownerName repoName: synchroName refName old new: commitId } if mtimeMaxProcessed? @synchros.update { owner: ownerName, name: synchroName }, { $set: { mtimeMaxProcessed } } return {status: 'updated', commit: commitId} _fullSnapshotTree: (euid, opts) -> {syn, ownerName, synchroName, conflictStyle} = opts root = { name: 'synchro' entries: [] meta: {} } root.entries.push { type: 'tree' sha1: @_fullReposSnapshotTree euid, { ownerName synchroName conflictStyle selector: syn.selector.repos } } return @_syncStore.createTree euid, { ownerName repoName: synchroName content: root } # XXX: The snapshot code directly uses the content collections without access # control. The security critical part is the definition of the selector. # Whoever controls the selector can control which content is visible in the # snapshot. The approach keeps the overhead for access control low, but it # is riskier than accessing content through the store methods. We should # consider adding a function to `NogContent.Store` that returns a snapshot of # a repo after checking access control. Or we add an access check here in # each map callback. # # XXX Handling of ids needs to be clarified, in particular related to # sharing. The tentative decision is to consider MongoDB ids as local and # use URL-like names in the snapshot. A repo is identified by # "{owner}/{name}". Sharing would refer to a circle by name (not by a # MongoDB id); something like "{owner}/{circle}". Details TBD. # # XXX The snapshot is currently restricted to `master`. We will later # reconsider whether we add support for other branches. # # XXX Sharing is not yet implemented. _fullReposSnapshotTree: (euid, opts) -> {ownerName, synchroName, selector, conflictStyle} = opts snaps = @contentStore.repos.find(selector).map (repo) => leaf = leafFromRepo(repo) treeId = @_syncStore.createTree euid, { ownerName repoName: synchroName content: leaf } return { name: leaf.name, treeId } prefixTree = {} for s in snaps shaid = sha1_hex(s.name) tree = prefixTree for lv in [0...@nRepoPrefixLevels] prefix = shaid[0..(lv * 2 + 1)] tree[prefix] ?= {} tree = tree[prefix] tree[shaid] = s asNogTree = (pfxTree, name) -> prefixes = _.keys(pfxTree) prefixes.sort() return { name, meta: {} entries: for pfx in prefixes child = pfxTree[pfx] if (treeId = child.treeId)? {type: 'tree', sha1: treeId} else asNogTree(child, 'repos:' + pfx) } return @_syncStore.createTree euid, { ownerName repoName: synchroName content: asNogTree(prefixTree, 'repos') } _incrSnapshotTree: (euid, opts) -> {syn, ownerName, synchroName, baseCommitSha } = opts store = { getCommit: (sha) => @getCommitSudo({ sha }) getTree: (sha) => @getTreeSudo({ sha }) } baseCommit = @getCommitSudo({ sha: baseCommitSha }) root = @getTreeSudo({ sha: baseCommit.tree }) root = _.clone(root) delete root._id delete root._idversion reposTreeSha = root.entries[0].sha1 pfxTree = createStagingPrefixTree({ store, rootSha: reposTreeSha }) selector = _.clone(syn.selector.repos) mtimeMaxProcessed = syn.mtimeMaxProcessed ? new Date(0) selector['mtime'] = { $gte: mtimeMaxProcessed } pfxUpsertRepo = (repo) => if (mtime = repo.mtime)? && mtime > mtimeMaxProcessed mtimeMaxProcessed = mtime leaf = leafFromRepo(repo) pfxTree.set(leaf) pfxDelRepo = (repo) => if (mtime = repo.mtime)? && mtime > mtimeMaxProcessed mtimeMaxProcessed = mtime existing = @contentStore.repos.findOne { owner: repo.owner, name: repo.name, } if existing? return leaf = leafFromRepo(repo) pfxTree.del(leaf) @contentStore.repos.find(selector).forEach pfxUpsertRepo @contentStore.deletedRepos.find(selector).forEach pfxDelRepo root.entries = _.clone(root.entries) root.entries[0] = pfxTree.asNogTree() rootSha = @_syncStore.createTree euid, { ownerName repoName: synchroName content: root } return { mtimeMaxProcessed, rootSha } pingSynchro: (euid, opts) -> {ownerName, synchroName, token} = opts @checkAccess euid, AA_MODIFY_SYNCHRO_CONTENT, opts sel = { owner: ownerName name: synchroName } $set = {} $set["_ping.#{ownerName}"] = token @synchros.update sel, {$set} setOp: (opts) -> check opts, { ownerName: matchSimpleName synchroName: matchSimpleName op: String prevOp: Match.Optional(String) } { ownerName, synchroName, prevOp, op } = opts sel = { owner: ownerName name: synchroName } if prevOp == '*' true # Do not check state. else if prevOp? sel['op.op'] = prevOp else sel['op'] = { $exists: false } n = @synchros.update sel, { $set: { 'op.op': op }, $currentDate: { 'op.atime': true }, } return n == 1 clearOp: (opts) -> check opts, { ownerName: matchSimpleName synchroName: matchSimpleName prevOp: String } { ownerName, synchroName, prevOp } = opts sel = { owner: ownerName name: synchroName } if prevOp == '*' true # Do not check state. else if prevOp? sel['op.op'] = prevOp n = @synchros.update sel, { $unset: { op: '' } } return n == 1 getOp: (opts) -> check opts, { ownerName: matchSimpleName synchroName: matchSimpleName } { ownerName, synchroName } = opts synchro = @synchros.findOne({ owner: ownerName name: synchroName }) return synchro?.op createSyncStore = (opts) -> { namespace, caching } = opts nsColl = namespace.coll colls = createContentCollections { names: {repos: "#{nsColl}.synchros"} namespace: {coll: nsColl} } colls.synchros = colls.repos delete colls.repos if caching.maxNElements > 0 cache = createEntryCache({ name: "entryCache-#{nsColl}", maxNElements: caching.maxNElements, maxAge_s: caching.maxAge_s, }) else cache = createEntryNullCache() return new SyncStore _.extend({cache}, colls, opts) module.exports.AA_GET_SYNCHRO_CONTENT = AA_GET_SYNCHRO_CONTENT module.exports.createSyncStore = createSyncStore
48178
{ check, Match } = require 'meteor/check' { createStagingPrefixTree } = require './nog-sync-merge-lib.coffee' { createEntryCache, createEntryNullCache, } = require './nog-sync-store-cache.js' { createContentCollections createContentStore } = NogContent { ERR_UNKNOWN_USERNAME ERR_UPDATE_SYNCHRO ERR_SYNCHRO_MISSING ERR_SYNCHRO_CONTENT_MISSING ERR_CONTENT_MISSING ERR_CONTENT_CHECKSUM nogthrow } = NogError NULL_SHA1 = '0000000000000000000000000000000000000000' RAW = {transform: false} AA_GET_SYNCHRO_CONTENT = 'nog-sync/get' AA_MODIFY_SYNCHRO_CONTENT = 'nog-sync/modify' AA_CREATE_SYNCHRO = 'nog-sync/create' isDuplicateMongoIdError = (err) -> return err.code == 11000 crypto = require('crypto') sha1_hex = (d) -> crypto.createHash('sha1').update(d, 'utf8').digest('hex') # `decodeMeta()` is identical to nogcontent. # # `verifyEncodedContent()` assumes that the sha verification works for any the # `_idversion`. decodeMeta = (encMeta) -> meta = _.omit encMeta, 'more' for r in encMeta.more ? [] meta[r.key] = r.val meta verifyEncodedContent = (type, content) -> d = _.clone content d.meta = decodeMeta d.meta if d._id != NogContent.contentId(NogContent.stripped(d)) nogthrow ERR_CONTENT_CHECKSUM, {type, sha1: d._id} matchSimpleName = Match.Where (x) -> check x, String if not (x.match /// ^ [a-zA-Z0-9-_]+ $ ///)? throw new Match.Error 'Invalid simple name.' true matchSimpleRelPath = Match.Where (x) -> check x, String if not (x.match /// ^ [a-zA-Z0-9-_]+ ( / [a-zA-Z0-9-_]+ )* $ ///)? throw new Match.Error 'Invalid ref name.' true matchSha1 = Match.Where (x) -> check x, String if not (x.match /^[0-9a-f]{40}$/)? throw new Match.Error 'not a sha1' true # `find().size()` as discussed on SO <http://stackoverflow.com/a/8390458> does # not work with the Meteor Mongo wrapper. Use `findOne()` instead and retrieve # only the id. collectionContains = (coll, sel) -> coll.findOne sel, {fields: {_id: 1}} leafFromRepo = (repo) -> master = repo.refs['branches/master'] cmaster = repo.conflicts?['branches/master'] if cmaster? refs = {} if master? cmaster = cmaster.concat([master]) else cmaster = cmaster.concat([NULL_SHA1]) cmaster.sort() cmaster = _.uniq(cmaster, 1) # 1 == isSorted. conflicts = { 'branches/master': cmaster } else conflicts = {} if master? refs = { 'branches/master': master } else refs = {} name = ['repo', repo.owner, repo.name].join(':') leaf = { name meta: { nog: { name: repo.name, owner: repo.owner, refs, conflicts, } } # XXX Maybe store entries `{type: 'commit', sha1: p[1]}` to prevent gc. entries: [] } _getRawEntriesFromStore = (store, opts) -> { treeShas, objectShas } = opts treeShas = _.unique(treeShas) objectShas = _.unique(objectShas) trees = [] if treeShas.length > 0 store.trees.find({ _id: { $in: treeShas } }, RAW).map (t) => trees.push(t) unless trees.length == treeShas.length nogthrow ERR_CONTENT_MISSING objects = [] if objectShas.length > 0 store.objects.find({ _id: { $in: objectShas } }, RAW).map (o) => objects.push(o) unless objects.length == objectShas.length nogthrow ERR_CONTENT_MISSING return { trees, objects } class SyncStore constructor: (opts) -> { @synchros, @commits, @trees, @objects, @users, @contentStore, @ourPeerName, @checkAccess, @testAccess, @cache } = opts @nRepoPrefixLevels = 2 # Use a ContentStore without access control as the low-level store. Access # control for the low-level store is disabled, since `SyncStore` checks # access for its high-level operation, and access should not be checked # again with a different action. @_syncStore = createContentStore { repos: @synchros commits: @commits trees: @trees objects: @objects users: @users blobs: null deletedRepos: null reposSets: null checkAccess: -> } getRefs: (euid, opts) -> check opts, { ownerName: matchSimpleName synchroName: matchSimpleName } @checkAccess euid, AA_GET_SYNCHRO_CONTENT, opts { ownerName, synchroName } = opts sel = { owner: ownerName, name: synchroName, } fields = { refs: 1 } unless (s = @synchros.findOne(sel, { fields }))? nogthrow ERR_SYNCHRO_MISSING return s.refs updateRef: (euid, opts) -> check opts.synchroName, matchSimpleName # Rely on `_syncStore` to check remaining fields. @checkAccess euid, AA_MODIFY_SYNCHRO_CONTENT, opts opts.repoName = opts.synchroName delete opts.synchroName @_syncStore.updateRef euid, opts createTree: (euid, opts) -> check opts.synchroName, matchSimpleName # Rely on `_syncStore` to check remaining fields. @checkAccess euid, AA_MODIFY_SYNCHRO_CONTENT, opts opts.repoName = opts.synchroName delete opts.synchroName @_syncStore.createTree euid, opts createCommit: (euid, opts) -> check opts.synchroName, matchSimpleName # Rely on `_syncStore` to check remaining fields. @checkAccess euid, AA_MODIFY_SYNCHRO_CONTENT, opts opts.repoName = opts.synchroName delete opts.synchroName @_syncStore.createCommit euid, opts ensureSynchro: (euid, opts) -> check opts, { ownerName: matchSimpleName synchroName: matchSimpleName selector: Match.Optional { repos: Object } } {ownerName, synchroName, selector} = opts selector ?= {repos: {}, users: {}} @checkAccess euid, AA_CREATE_SYNCHRO, opts sel = { owner: ownerName name: <NAME>chroName } unless collectionContains(@synchros, sel) @_syncStore.createRepo euid, { repoFullName: [ownerName, synchroName].join('/') } n = @synchros.update sel, {$set: {selector}} unless n == 1 nogthrow ERR_UPDATE_SYNCHRO, { reason: 'Failed to update selector.' } return getPing: (euid, opts) -> check opts, {owner: String} @checkAccess euid, AA_GET_SYNCHRO_CONTENT, opts {owner} = opts unless (s = @synchros.findOne({owner}, {fields: {_ping: 1}}))? return null return s._ping # Functions `*Raw()` use encoded meta as it is stored in Mongo. # # Functions `*RawSudo()` run without access check. They are for code paths # that have already checked access on a higher level. # # Functions `insert*Raw*()` bypass dependency checks. The caller should # use them responsibly in order to preserve invariants: # # - Trees and objects must be deep, that is dependencies must be inserted # first. # # - Commits may be shallow, that is they may be inserted without parents. It # is undefined whether shallow provides any guarantees. The safest # approach, when the synchro code is active, is to assume nothing about # commit ranges. For example, a commit walk should not make assumptions # about the presence of parent commits solely based on the presence of a # commit. It may be safe, though, to assume that all parent commits are # present if a content ref points to a commit. getCommitRaw: (euid, opts) -> check opts, {sha: matchSha1} @checkAccess euid, AA_GET_SYNCHRO_CONTENT, opts {sha} = opts unless (commit = @commits.findOne(sha, RAW))? nogthrow ERR_SYNCHRO_CONTENT_MISSING, {commit: sha} return commit getTreeRaw: (euid, opts) -> check opts, {sha: matchSha1} @checkAccess euid, AA_GET_SYNCHRO_CONTENT, opts {sha} = opts unless (tree = @trees.findOne(sha, RAW))? nogthrow ERR_SYNCHRO_CONTENT_MISSING, {tree: sha} return tree getObjectRaw: (euid, opts) -> check opts, {sha: matchSha1} @checkAccess euid, AA_GET_SYNCHRO_CONTENT, opts {sha} = opts unless (object = @objects.findOne(sha, RAW))? nogthrow ERR_SYNCHRO_CONTENT_MISSING, {object: sha} return object getEntriesRaw: (euid, opts) -> check opts, { treeShas: [matchSha1], objectShas: [matchSha1], } @checkAccess euid, AA_GET_SYNCHRO_CONTENT, opts return _getRawEntriesFromStore this, opts insertCommitRawSudo: (opts) -> { content } = opts verifyEncodedContent 'commit', content try @commits.insert content catch err # Duplicate id indicates that we already had the commit. unless isDuplicateMongoIdError err throw err insertTreeRawSudo: (opts) -> { content } = opts verifyEncodedContent 'tree', content try @trees.insert content catch err # Duplicate id indicates that we already had the tree. unless isDuplicateMongoIdError err throw err insertObjectRawSudo: (opts) -> { content } = opts verifyEncodedContent 'object', content try @objects.insert content catch err # Duplicate id indicates that we already had the object. unless isDuplicateMongoIdError err throw err hasTreeSudo: (opts) -> @_syncStore.hasTreeSudo opts hasObjectSudo: (opts) -> @_syncStore.hasObjectSudo opts getCommitSudo: (opts) -> check opts, { sha: matchSha1 } { sha } = opts if (commit = @cache.get(sha))? return commit unless (commit = @commits.findOne(sha))? nogthrow ERR_SYNCHRO_CONTENT_MISSING, { commit: sha } @cache.add(commit) return commit getTreeSudo: (opts) -> check opts, { sha: matchSha1 } {sha} = opts if (tree = @cache.get(sha))? return tree unless (tree = @trees.findOne(sha))? nogthrow ERR_SYNCHRO_CONTENT_MISSING, { tree: sha } @cache.add(tree) return tree getObjectSudo: (euid, opts) -> check opts, { sha: matchSha1 } {sha} = opts if (object = @cache.get(sha))? return object unless (object = @objects.findOne(sha))? nogthrow ERR_SYNCHRO_CONTENT_MISSING, { object: sha } @cache.add(object) return object # The `getContent*()` calls skip the usual content access checks, such as # `action: 'nog-content/get'` and require synchro access permission instead. # This should be fine for root-like nogsyncbots, which have permission to # access all content. # # We'd need to reconsider if we wanted to extend the synchro design to # ordinary users. getContentCommitRaw: (euid, opts) -> check opts, { sha: matchSha1 } @checkAccess euid, AA_GET_SYNCHRO_CONTENT, opts { sha } = opts unless (commit = @contentStore.commits.findOne(sha, RAW))? nogthrow ERR_CONTENT_MISSING, { commit: sha } return commit getContentTreeRaw: (euid, opts) -> check opts, { sha: matchSha1 } @checkAccess euid, AA_GET_SYNCHRO_CONTENT, opts { sha } = opts unless (tree = @contentStore.trees.findOne(sha, RAW))? nogthrow ERR_CONTENT_MISSING, { tree: sha } return tree getContentObjectRaw: (euid, opts) -> check opts, { sha: matchSha1 } @checkAccess euid, AA_GET_SYNCHRO_CONTENT, opts { sha } = opts unless (object = @contentStore.objects.findOne(sha, RAW))? nogthrow ERR_CONTENT_MISSING, { object: sha } return object getContentEntriesRaw: (euid, opts) -> check opts, { treeShas: [matchSha1], objectShas: [matchSha1], } @checkAccess euid, AA_GET_SYNCHRO_CONTENT, opts return _getRawEntriesFromStore @contentStore, opts insertContentCommitRawSudo: (opts) -> { content } = opts verifyEncodedContent 'commit', content try @contentStore.commits.insert content catch err # Duplicate id indicates that we already had the commit. unless isDuplicateMongoIdError err throw err insertContentTreeRawSudo: (opts) -> { content } = opts verifyEncodedContent 'tree', content try @contentStore.trees.insert content catch err # Duplicate id indicates that we already had the tree. unless isDuplicateMongoIdError err throw err insertContentObjectRawSudo: (opts) -> { content } = opts verifyEncodedContent 'object', content try @contentStore.objects.insert content catch err # Duplicate id indicates that we already had the object. unless isDuplicateMongoIdError err throw err # XXX The meaning of blob placeholders need to be clarified. We will # probably add a notion of a remote blob that is pending transfer. # We should also support storing blobs in multiple caches. insertContentBlobPlaceholderSudo: (opts) -> check opts, { sha: matchSha1 } { sha } = opts blob = { _id: sha, sha1: sha, status: 'placeholder', size: -1, } try @contentStore.blobs.insert blob catch err # Duplicate id indicates that we already had the object. unless isDuplicateMongoIdError err throw err snapshot: (args...) -> @snapshotAnonC args... fullSnapshot: (args...) -> @fullSnapshotAnonC args... snapshotAnonC: (euid, opts) -> check opts, { ownerName: matchSimpleName synchroName: matchSimpleName } @checkAccess euid, AA_MODIFY_SYNCHRO_CONTENT, opts opts = _.extend({ conflictStyle: 'anonymous', strategy: 'incremental' }, opts) @_snapshot(euid, opts) fullSnapshotAnonC: (euid, opts) -> check opts, { ownerName: matchSimpleName synchroName: matchSimpleName } @checkAccess euid, AA_MODIFY_SYNCHRO_CONTENT, opts opts = _.extend({ conflictStyle: 'anonymous', strategy: 'full' }, opts) @_snapshot(euid, opts) _snapshot: (euid, opts) -> {ownerName, synchroName, conflictStyle, strategy} = opts refName = 'branches/master' sel = { owner: ownerName name: synchroName } unless (syn = @synchros.findOne(sel))? nogthrow ERR_SYNCHRO_MISSING old = syn.refs[refName] ? NULL_SHA1 if (op = @getOp({ ownerName, synchroName }))? console.log("[nog-sync] refusing snapshot due to active op #{op.op}.") return { status: 'refused', commit: old } mtimeMaxProcessed = null if strategy == 'incremental' && old != NULL_SHA1 { mtimeMaxProcessed, rootSha } = @_incrSnapshotTree euid, { syn, ownerName, synchroName, baseCommitSha: old } else rootSha = @_fullSnapshotTree euid, { syn, ownerName, synchroName, conflictStyle } # Keep old commit if already up-to-date. unless old == NULL_SHA1 oldc = @_syncStore.getCommit euid, { ownerName repoName: synchroName sha1: old } if oldc.tree == rootSha return {status: 'unchanged', commit: old} commit = { subject: 'Sync snapshot' message: '' parents: (if old != NULL_SHA1 then [old] else []) tree: rootSha } commitId = @_syncStore.createCommit euid, { ownerName repoName: synchroName content: commit } @_syncStore.updateRef euid, { ownerName repoName: synchroName refName old new: commitId } if mtimeMaxProcessed? @synchros.update { owner: ownerName, name: <NAME> }, { $set: { mtimeMaxProcessed } } return {status: 'updated', commit: commitId} _fullSnapshotTree: (euid, opts) -> {syn, ownerName, synchroName, conflictStyle} = opts root = { name: 'synchro' entries: [] meta: {} } root.entries.push { type: 'tree' sha1: @_fullReposSnapshotTree euid, { ownerName synchroName conflictStyle selector: syn.selector.repos } } return @_syncStore.createTree euid, { ownerName repoName: <NAME>chroName content: root } # XXX: The snapshot code directly uses the content collections without access # control. The security critical part is the definition of the selector. # Whoever controls the selector can control which content is visible in the # snapshot. The approach keeps the overhead for access control low, but it # is riskier than accessing content through the store methods. We should # consider adding a function to `NogContent.Store` that returns a snapshot of # a repo after checking access control. Or we add an access check here in # each map callback. # # XXX Handling of ids needs to be clarified, in particular related to # sharing. The tentative decision is to consider MongoDB ids as local and # use URL-like names in the snapshot. A repo is identified by # "{owner}/{name}". Sharing would refer to a circle by name (not by a # MongoDB id); something like "{owner}/{circle}". Details TBD. # # XXX The snapshot is currently restricted to `master`. We will later # reconsider whether we add support for other branches. # # XXX Sharing is not yet implemented. _fullReposSnapshotTree: (euid, opts) -> {ownerName, synchroName, selector, conflictStyle} = opts snaps = @contentStore.repos.find(selector).map (repo) => leaf = leafFromRepo(repo) treeId = @_syncStore.createTree euid, { ownerName repoName: synchroName content: leaf } return { name: leaf.name, treeId } prefixTree = {} for s in snaps shaid = sha1_hex(s.name) tree = prefixTree for lv in [0...@nRepoPrefixLevels] prefix = shaid[0..(lv * 2 + 1)] tree[prefix] ?= {} tree = tree[prefix] tree[shaid] = s asNogTree = (pfxTree, name) -> prefixes = _.keys(pfxTree) prefixes.sort() return { name, meta: {} entries: for pfx in prefixes child = pfxTree[pfx] if (treeId = child.treeId)? {type: 'tree', sha1: treeId} else asNogTree(child, 'repos:' + pfx) } return @_syncStore.createTree euid, { ownerName repoName: synchroName content: asNogTree(prefixTree, 'repos') } _incrSnapshotTree: (euid, opts) -> {syn, ownerName, synchroName, baseCommitSha } = opts store = { getCommit: (sha) => @getCommitSudo({ sha }) getTree: (sha) => @getTreeSudo({ sha }) } baseCommit = @getCommitSudo({ sha: baseCommitSha }) root = @getTreeSudo({ sha: baseCommit.tree }) root = _.clone(root) delete root._id delete root._idversion reposTreeSha = root.entries[0].sha1 pfxTree = createStagingPrefixTree({ store, rootSha: reposTreeSha }) selector = _.clone(syn.selector.repos) mtimeMaxProcessed = syn.mtimeMaxProcessed ? new Date(0) selector['mtime'] = { $gte: mtimeMaxProcessed } pfxUpsertRepo = (repo) => if (mtime = repo.mtime)? && mtime > mtimeMaxProcessed mtimeMaxProcessed = mtime leaf = leafFromRepo(repo) pfxTree.set(leaf) pfxDelRepo = (repo) => if (mtime = repo.mtime)? && mtime > mtimeMaxProcessed mtimeMaxProcessed = mtime existing = @contentStore.repos.findOne { owner: repo.owner, name: repo.name, } if existing? return leaf = leafFromRepo(repo) pfxTree.del(leaf) @contentStore.repos.find(selector).forEach pfxUpsertRepo @contentStore.deletedRepos.find(selector).forEach pfxDelRepo root.entries = _.clone(root.entries) root.entries[0] = pfxTree.asNogTree() rootSha = @_syncStore.createTree euid, { ownerName repoName: synchroName content: root } return { mtimeMaxProcessed, rootSha } pingSynchro: (euid, opts) -> {ownerName, synchroName, token} = opts @checkAccess euid, AA_MODIFY_SYNCHRO_CONTENT, opts sel = { owner: ownerName name: synchroName } $set = {} $set["_ping.#{ownerName}"] = token @synchros.update sel, {$set} setOp: (opts) -> check opts, { ownerName: matchSimpleName synchroName: matchSimpleName op: String prevOp: Match.Optional(String) } { ownerName, synchroName, prevOp, op } = opts sel = { owner: ownerName name: synchroName } if prevOp == '*' true # Do not check state. else if prevOp? sel['op.op'] = prevOp else sel['op'] = { $exists: false } n = @synchros.update sel, { $set: { 'op.op': op }, $currentDate: { 'op.atime': true }, } return n == 1 clearOp: (opts) -> check opts, { ownerName: matchSimpleName synchroName: matchSimpleName prevOp: String } { ownerName, synchroName, prevOp } = opts sel = { owner: ownerName name: synchroName } if prevOp == '*' true # Do not check state. else if prevOp? sel['op.op'] = prevOp n = @synchros.update sel, { $unset: { op: '' } } return n == 1 getOp: (opts) -> check opts, { ownerName: matchSimpleName synchroName: matchSimpleName } { ownerName, synchroName } = opts synchro = @synchros.findOne({ owner: ownerName name: <NAME>chroName }) return synchro?.op createSyncStore = (opts) -> { namespace, caching } = opts nsColl = namespace.coll colls = createContentCollections { names: {repos: "#{nsColl}.synchros"} namespace: {coll: nsColl} } colls.synchros = colls.repos delete colls.repos if caching.maxNElements > 0 cache = createEntryCache({ name: "entryCache-#{nsColl}", maxNElements: caching.maxNElements, maxAge_s: caching.maxAge_s, }) else cache = createEntryNullCache() return new SyncStore _.extend({cache}, colls, opts) module.exports.AA_GET_SYNCHRO_CONTENT = AA_GET_SYNCHRO_CONTENT module.exports.createSyncStore = createSyncStore
true
{ check, Match } = require 'meteor/check' { createStagingPrefixTree } = require './nog-sync-merge-lib.coffee' { createEntryCache, createEntryNullCache, } = require './nog-sync-store-cache.js' { createContentCollections createContentStore } = NogContent { ERR_UNKNOWN_USERNAME ERR_UPDATE_SYNCHRO ERR_SYNCHRO_MISSING ERR_SYNCHRO_CONTENT_MISSING ERR_CONTENT_MISSING ERR_CONTENT_CHECKSUM nogthrow } = NogError NULL_SHA1 = '0000000000000000000000000000000000000000' RAW = {transform: false} AA_GET_SYNCHRO_CONTENT = 'nog-sync/get' AA_MODIFY_SYNCHRO_CONTENT = 'nog-sync/modify' AA_CREATE_SYNCHRO = 'nog-sync/create' isDuplicateMongoIdError = (err) -> return err.code == 11000 crypto = require('crypto') sha1_hex = (d) -> crypto.createHash('sha1').update(d, 'utf8').digest('hex') # `decodeMeta()` is identical to nogcontent. # # `verifyEncodedContent()` assumes that the sha verification works for any the # `_idversion`. decodeMeta = (encMeta) -> meta = _.omit encMeta, 'more' for r in encMeta.more ? [] meta[r.key] = r.val meta verifyEncodedContent = (type, content) -> d = _.clone content d.meta = decodeMeta d.meta if d._id != NogContent.contentId(NogContent.stripped(d)) nogthrow ERR_CONTENT_CHECKSUM, {type, sha1: d._id} matchSimpleName = Match.Where (x) -> check x, String if not (x.match /// ^ [a-zA-Z0-9-_]+ $ ///)? throw new Match.Error 'Invalid simple name.' true matchSimpleRelPath = Match.Where (x) -> check x, String if not (x.match /// ^ [a-zA-Z0-9-_]+ ( / [a-zA-Z0-9-_]+ )* $ ///)? throw new Match.Error 'Invalid ref name.' true matchSha1 = Match.Where (x) -> check x, String if not (x.match /^[0-9a-f]{40}$/)? throw new Match.Error 'not a sha1' true # `find().size()` as discussed on SO <http://stackoverflow.com/a/8390458> does # not work with the Meteor Mongo wrapper. Use `findOne()` instead and retrieve # only the id. collectionContains = (coll, sel) -> coll.findOne sel, {fields: {_id: 1}} leafFromRepo = (repo) -> master = repo.refs['branches/master'] cmaster = repo.conflicts?['branches/master'] if cmaster? refs = {} if master? cmaster = cmaster.concat([master]) else cmaster = cmaster.concat([NULL_SHA1]) cmaster.sort() cmaster = _.uniq(cmaster, 1) # 1 == isSorted. conflicts = { 'branches/master': cmaster } else conflicts = {} if master? refs = { 'branches/master': master } else refs = {} name = ['repo', repo.owner, repo.name].join(':') leaf = { name meta: { nog: { name: repo.name, owner: repo.owner, refs, conflicts, } } # XXX Maybe store entries `{type: 'commit', sha1: p[1]}` to prevent gc. entries: [] } _getRawEntriesFromStore = (store, opts) -> { treeShas, objectShas } = opts treeShas = _.unique(treeShas) objectShas = _.unique(objectShas) trees = [] if treeShas.length > 0 store.trees.find({ _id: { $in: treeShas } }, RAW).map (t) => trees.push(t) unless trees.length == treeShas.length nogthrow ERR_CONTENT_MISSING objects = [] if objectShas.length > 0 store.objects.find({ _id: { $in: objectShas } }, RAW).map (o) => objects.push(o) unless objects.length == objectShas.length nogthrow ERR_CONTENT_MISSING return { trees, objects } class SyncStore constructor: (opts) -> { @synchros, @commits, @trees, @objects, @users, @contentStore, @ourPeerName, @checkAccess, @testAccess, @cache } = opts @nRepoPrefixLevels = 2 # Use a ContentStore without access control as the low-level store. Access # control for the low-level store is disabled, since `SyncStore` checks # access for its high-level operation, and access should not be checked # again with a different action. @_syncStore = createContentStore { repos: @synchros commits: @commits trees: @trees objects: @objects users: @users blobs: null deletedRepos: null reposSets: null checkAccess: -> } getRefs: (euid, opts) -> check opts, { ownerName: matchSimpleName synchroName: matchSimpleName } @checkAccess euid, AA_GET_SYNCHRO_CONTENT, opts { ownerName, synchroName } = opts sel = { owner: ownerName, name: synchroName, } fields = { refs: 1 } unless (s = @synchros.findOne(sel, { fields }))? nogthrow ERR_SYNCHRO_MISSING return s.refs updateRef: (euid, opts) -> check opts.synchroName, matchSimpleName # Rely on `_syncStore` to check remaining fields. @checkAccess euid, AA_MODIFY_SYNCHRO_CONTENT, opts opts.repoName = opts.synchroName delete opts.synchroName @_syncStore.updateRef euid, opts createTree: (euid, opts) -> check opts.synchroName, matchSimpleName # Rely on `_syncStore` to check remaining fields. @checkAccess euid, AA_MODIFY_SYNCHRO_CONTENT, opts opts.repoName = opts.synchroName delete opts.synchroName @_syncStore.createTree euid, opts createCommit: (euid, opts) -> check opts.synchroName, matchSimpleName # Rely on `_syncStore` to check remaining fields. @checkAccess euid, AA_MODIFY_SYNCHRO_CONTENT, opts opts.repoName = opts.synchroName delete opts.synchroName @_syncStore.createCommit euid, opts ensureSynchro: (euid, opts) -> check opts, { ownerName: matchSimpleName synchroName: matchSimpleName selector: Match.Optional { repos: Object } } {ownerName, synchroName, selector} = opts selector ?= {repos: {}, users: {}} @checkAccess euid, AA_CREATE_SYNCHRO, opts sel = { owner: ownerName name: PI:NAME:<NAME>END_PIchroName } unless collectionContains(@synchros, sel) @_syncStore.createRepo euid, { repoFullName: [ownerName, synchroName].join('/') } n = @synchros.update sel, {$set: {selector}} unless n == 1 nogthrow ERR_UPDATE_SYNCHRO, { reason: 'Failed to update selector.' } return getPing: (euid, opts) -> check opts, {owner: String} @checkAccess euid, AA_GET_SYNCHRO_CONTENT, opts {owner} = opts unless (s = @synchros.findOne({owner}, {fields: {_ping: 1}}))? return null return s._ping # Functions `*Raw()` use encoded meta as it is stored in Mongo. # # Functions `*RawSudo()` run without access check. They are for code paths # that have already checked access on a higher level. # # Functions `insert*Raw*()` bypass dependency checks. The caller should # use them responsibly in order to preserve invariants: # # - Trees and objects must be deep, that is dependencies must be inserted # first. # # - Commits may be shallow, that is they may be inserted without parents. It # is undefined whether shallow provides any guarantees. The safest # approach, when the synchro code is active, is to assume nothing about # commit ranges. For example, a commit walk should not make assumptions # about the presence of parent commits solely based on the presence of a # commit. It may be safe, though, to assume that all parent commits are # present if a content ref points to a commit. getCommitRaw: (euid, opts) -> check opts, {sha: matchSha1} @checkAccess euid, AA_GET_SYNCHRO_CONTENT, opts {sha} = opts unless (commit = @commits.findOne(sha, RAW))? nogthrow ERR_SYNCHRO_CONTENT_MISSING, {commit: sha} return commit getTreeRaw: (euid, opts) -> check opts, {sha: matchSha1} @checkAccess euid, AA_GET_SYNCHRO_CONTENT, opts {sha} = opts unless (tree = @trees.findOne(sha, RAW))? nogthrow ERR_SYNCHRO_CONTENT_MISSING, {tree: sha} return tree getObjectRaw: (euid, opts) -> check opts, {sha: matchSha1} @checkAccess euid, AA_GET_SYNCHRO_CONTENT, opts {sha} = opts unless (object = @objects.findOne(sha, RAW))? nogthrow ERR_SYNCHRO_CONTENT_MISSING, {object: sha} return object getEntriesRaw: (euid, opts) -> check opts, { treeShas: [matchSha1], objectShas: [matchSha1], } @checkAccess euid, AA_GET_SYNCHRO_CONTENT, opts return _getRawEntriesFromStore this, opts insertCommitRawSudo: (opts) -> { content } = opts verifyEncodedContent 'commit', content try @commits.insert content catch err # Duplicate id indicates that we already had the commit. unless isDuplicateMongoIdError err throw err insertTreeRawSudo: (opts) -> { content } = opts verifyEncodedContent 'tree', content try @trees.insert content catch err # Duplicate id indicates that we already had the tree. unless isDuplicateMongoIdError err throw err insertObjectRawSudo: (opts) -> { content } = opts verifyEncodedContent 'object', content try @objects.insert content catch err # Duplicate id indicates that we already had the object. unless isDuplicateMongoIdError err throw err hasTreeSudo: (opts) -> @_syncStore.hasTreeSudo opts hasObjectSudo: (opts) -> @_syncStore.hasObjectSudo opts getCommitSudo: (opts) -> check opts, { sha: matchSha1 } { sha } = opts if (commit = @cache.get(sha))? return commit unless (commit = @commits.findOne(sha))? nogthrow ERR_SYNCHRO_CONTENT_MISSING, { commit: sha } @cache.add(commit) return commit getTreeSudo: (opts) -> check opts, { sha: matchSha1 } {sha} = opts if (tree = @cache.get(sha))? return tree unless (tree = @trees.findOne(sha))? nogthrow ERR_SYNCHRO_CONTENT_MISSING, { tree: sha } @cache.add(tree) return tree getObjectSudo: (euid, opts) -> check opts, { sha: matchSha1 } {sha} = opts if (object = @cache.get(sha))? return object unless (object = @objects.findOne(sha))? nogthrow ERR_SYNCHRO_CONTENT_MISSING, { object: sha } @cache.add(object) return object # The `getContent*()` calls skip the usual content access checks, such as # `action: 'nog-content/get'` and require synchro access permission instead. # This should be fine for root-like nogsyncbots, which have permission to # access all content. # # We'd need to reconsider if we wanted to extend the synchro design to # ordinary users. getContentCommitRaw: (euid, opts) -> check opts, { sha: matchSha1 } @checkAccess euid, AA_GET_SYNCHRO_CONTENT, opts { sha } = opts unless (commit = @contentStore.commits.findOne(sha, RAW))? nogthrow ERR_CONTENT_MISSING, { commit: sha } return commit getContentTreeRaw: (euid, opts) -> check opts, { sha: matchSha1 } @checkAccess euid, AA_GET_SYNCHRO_CONTENT, opts { sha } = opts unless (tree = @contentStore.trees.findOne(sha, RAW))? nogthrow ERR_CONTENT_MISSING, { tree: sha } return tree getContentObjectRaw: (euid, opts) -> check opts, { sha: matchSha1 } @checkAccess euid, AA_GET_SYNCHRO_CONTENT, opts { sha } = opts unless (object = @contentStore.objects.findOne(sha, RAW))? nogthrow ERR_CONTENT_MISSING, { object: sha } return object getContentEntriesRaw: (euid, opts) -> check opts, { treeShas: [matchSha1], objectShas: [matchSha1], } @checkAccess euid, AA_GET_SYNCHRO_CONTENT, opts return _getRawEntriesFromStore @contentStore, opts insertContentCommitRawSudo: (opts) -> { content } = opts verifyEncodedContent 'commit', content try @contentStore.commits.insert content catch err # Duplicate id indicates that we already had the commit. unless isDuplicateMongoIdError err throw err insertContentTreeRawSudo: (opts) -> { content } = opts verifyEncodedContent 'tree', content try @contentStore.trees.insert content catch err # Duplicate id indicates that we already had the tree. unless isDuplicateMongoIdError err throw err insertContentObjectRawSudo: (opts) -> { content } = opts verifyEncodedContent 'object', content try @contentStore.objects.insert content catch err # Duplicate id indicates that we already had the object. unless isDuplicateMongoIdError err throw err # XXX The meaning of blob placeholders need to be clarified. We will # probably add a notion of a remote blob that is pending transfer. # We should also support storing blobs in multiple caches. insertContentBlobPlaceholderSudo: (opts) -> check opts, { sha: matchSha1 } { sha } = opts blob = { _id: sha, sha1: sha, status: 'placeholder', size: -1, } try @contentStore.blobs.insert blob catch err # Duplicate id indicates that we already had the object. unless isDuplicateMongoIdError err throw err snapshot: (args...) -> @snapshotAnonC args... fullSnapshot: (args...) -> @fullSnapshotAnonC args... snapshotAnonC: (euid, opts) -> check opts, { ownerName: matchSimpleName synchroName: matchSimpleName } @checkAccess euid, AA_MODIFY_SYNCHRO_CONTENT, opts opts = _.extend({ conflictStyle: 'anonymous', strategy: 'incremental' }, opts) @_snapshot(euid, opts) fullSnapshotAnonC: (euid, opts) -> check opts, { ownerName: matchSimpleName synchroName: matchSimpleName } @checkAccess euid, AA_MODIFY_SYNCHRO_CONTENT, opts opts = _.extend({ conflictStyle: 'anonymous', strategy: 'full' }, opts) @_snapshot(euid, opts) _snapshot: (euid, opts) -> {ownerName, synchroName, conflictStyle, strategy} = opts refName = 'branches/master' sel = { owner: ownerName name: synchroName } unless (syn = @synchros.findOne(sel))? nogthrow ERR_SYNCHRO_MISSING old = syn.refs[refName] ? NULL_SHA1 if (op = @getOp({ ownerName, synchroName }))? console.log("[nog-sync] refusing snapshot due to active op #{op.op}.") return { status: 'refused', commit: old } mtimeMaxProcessed = null if strategy == 'incremental' && old != NULL_SHA1 { mtimeMaxProcessed, rootSha } = @_incrSnapshotTree euid, { syn, ownerName, synchroName, baseCommitSha: old } else rootSha = @_fullSnapshotTree euid, { syn, ownerName, synchroName, conflictStyle } # Keep old commit if already up-to-date. unless old == NULL_SHA1 oldc = @_syncStore.getCommit euid, { ownerName repoName: synchroName sha1: old } if oldc.tree == rootSha return {status: 'unchanged', commit: old} commit = { subject: 'Sync snapshot' message: '' parents: (if old != NULL_SHA1 then [old] else []) tree: rootSha } commitId = @_syncStore.createCommit euid, { ownerName repoName: synchroName content: commit } @_syncStore.updateRef euid, { ownerName repoName: synchroName refName old new: commitId } if mtimeMaxProcessed? @synchros.update { owner: ownerName, name: PI:NAME:<NAME>END_PI }, { $set: { mtimeMaxProcessed } } return {status: 'updated', commit: commitId} _fullSnapshotTree: (euid, opts) -> {syn, ownerName, synchroName, conflictStyle} = opts root = { name: 'synchro' entries: [] meta: {} } root.entries.push { type: 'tree' sha1: @_fullReposSnapshotTree euid, { ownerName synchroName conflictStyle selector: syn.selector.repos } } return @_syncStore.createTree euid, { ownerName repoName: PI:NAME:<NAME>END_PIchroName content: root } # XXX: The snapshot code directly uses the content collections without access # control. The security critical part is the definition of the selector. # Whoever controls the selector can control which content is visible in the # snapshot. The approach keeps the overhead for access control low, but it # is riskier than accessing content through the store methods. We should # consider adding a function to `NogContent.Store` that returns a snapshot of # a repo after checking access control. Or we add an access check here in # each map callback. # # XXX Handling of ids needs to be clarified, in particular related to # sharing. The tentative decision is to consider MongoDB ids as local and # use URL-like names in the snapshot. A repo is identified by # "{owner}/{name}". Sharing would refer to a circle by name (not by a # MongoDB id); something like "{owner}/{circle}". Details TBD. # # XXX The snapshot is currently restricted to `master`. We will later # reconsider whether we add support for other branches. # # XXX Sharing is not yet implemented. _fullReposSnapshotTree: (euid, opts) -> {ownerName, synchroName, selector, conflictStyle} = opts snaps = @contentStore.repos.find(selector).map (repo) => leaf = leafFromRepo(repo) treeId = @_syncStore.createTree euid, { ownerName repoName: synchroName content: leaf } return { name: leaf.name, treeId } prefixTree = {} for s in snaps shaid = sha1_hex(s.name) tree = prefixTree for lv in [0...@nRepoPrefixLevels] prefix = shaid[0..(lv * 2 + 1)] tree[prefix] ?= {} tree = tree[prefix] tree[shaid] = s asNogTree = (pfxTree, name) -> prefixes = _.keys(pfxTree) prefixes.sort() return { name, meta: {} entries: for pfx in prefixes child = pfxTree[pfx] if (treeId = child.treeId)? {type: 'tree', sha1: treeId} else asNogTree(child, 'repos:' + pfx) } return @_syncStore.createTree euid, { ownerName repoName: synchroName content: asNogTree(prefixTree, 'repos') } _incrSnapshotTree: (euid, opts) -> {syn, ownerName, synchroName, baseCommitSha } = opts store = { getCommit: (sha) => @getCommitSudo({ sha }) getTree: (sha) => @getTreeSudo({ sha }) } baseCommit = @getCommitSudo({ sha: baseCommitSha }) root = @getTreeSudo({ sha: baseCommit.tree }) root = _.clone(root) delete root._id delete root._idversion reposTreeSha = root.entries[0].sha1 pfxTree = createStagingPrefixTree({ store, rootSha: reposTreeSha }) selector = _.clone(syn.selector.repos) mtimeMaxProcessed = syn.mtimeMaxProcessed ? new Date(0) selector['mtime'] = { $gte: mtimeMaxProcessed } pfxUpsertRepo = (repo) => if (mtime = repo.mtime)? && mtime > mtimeMaxProcessed mtimeMaxProcessed = mtime leaf = leafFromRepo(repo) pfxTree.set(leaf) pfxDelRepo = (repo) => if (mtime = repo.mtime)? && mtime > mtimeMaxProcessed mtimeMaxProcessed = mtime existing = @contentStore.repos.findOne { owner: repo.owner, name: repo.name, } if existing? return leaf = leafFromRepo(repo) pfxTree.del(leaf) @contentStore.repos.find(selector).forEach pfxUpsertRepo @contentStore.deletedRepos.find(selector).forEach pfxDelRepo root.entries = _.clone(root.entries) root.entries[0] = pfxTree.asNogTree() rootSha = @_syncStore.createTree euid, { ownerName repoName: synchroName content: root } return { mtimeMaxProcessed, rootSha } pingSynchro: (euid, opts) -> {ownerName, synchroName, token} = opts @checkAccess euid, AA_MODIFY_SYNCHRO_CONTENT, opts sel = { owner: ownerName name: synchroName } $set = {} $set["_ping.#{ownerName}"] = token @synchros.update sel, {$set} setOp: (opts) -> check opts, { ownerName: matchSimpleName synchroName: matchSimpleName op: String prevOp: Match.Optional(String) } { ownerName, synchroName, prevOp, op } = opts sel = { owner: ownerName name: synchroName } if prevOp == '*' true # Do not check state. else if prevOp? sel['op.op'] = prevOp else sel['op'] = { $exists: false } n = @synchros.update sel, { $set: { 'op.op': op }, $currentDate: { 'op.atime': true }, } return n == 1 clearOp: (opts) -> check opts, { ownerName: matchSimpleName synchroName: matchSimpleName prevOp: String } { ownerName, synchroName, prevOp } = opts sel = { owner: ownerName name: synchroName } if prevOp == '*' true # Do not check state. else if prevOp? sel['op.op'] = prevOp n = @synchros.update sel, { $unset: { op: '' } } return n == 1 getOp: (opts) -> check opts, { ownerName: matchSimpleName synchroName: matchSimpleName } { ownerName, synchroName } = opts synchro = @synchros.findOne({ owner: ownerName name: PI:NAME:<NAME>END_PIchroName }) return synchro?.op createSyncStore = (opts) -> { namespace, caching } = opts nsColl = namespace.coll colls = createContentCollections { names: {repos: "#{nsColl}.synchros"} namespace: {coll: nsColl} } colls.synchros = colls.repos delete colls.repos if caching.maxNElements > 0 cache = createEntryCache({ name: "entryCache-#{nsColl}", maxNElements: caching.maxNElements, maxAge_s: caching.maxAge_s, }) else cache = createEntryNullCache() return new SyncStore _.extend({cache}, colls, opts) module.exports.AA_GET_SYNCHRO_CONTENT = AA_GET_SYNCHRO_CONTENT module.exports.createSyncStore = createSyncStore
[ { "context": "= $cookies\n @q = $q\n\n updateNew: (firstName, lastName, email, optInEmail) =>\n deferred = @", "end": 197, "score": 0.7465617656707764, "start": 188, "tag": "NAME", "value": "firstName" }, { "context": "\n @q = $q\n\n updateNew: (firstName, lastName, email, optInEmail) =>\n deferred = @q.defer()\n", "end": 207, "score": 0.8090789318084717, "start": 199, "tag": "NAME", "value": "lastName" }, { "context": "@q.defer()\n\n query =\n 'octoblu.firstName': firstName\n 'octoblu.lastName': lastName\n 'octoblu", "end": 306, "score": 0.944227397441864, "start": 297, "tag": "NAME", "value": "firstName" }, { "context": "lu.firstName': firstName\n 'octoblu.lastName': lastName\n 'octoblu.email': email\n 'octoblu.optIn", "end": 341, "score": 0.804231584072113, "start": 333, "tag": "NAME", "value": "lastName" }, { "context": "resolve()\n\n deferred.promise\n\n updateAfter: ({ firstName, lastName, email, optInEmail }) =>\n deferred =", "end": 676, "score": 0.8876475095748901, "start": 667, "tag": "NAME", "value": "firstName" }, { "context": " deferred.promise\n\n updateAfter: ({ firstName, lastName, email, optInEmail }) =>\n deferred = @q.defer(", "end": 686, "score": 0.7886950373649597, "start": 678, "tag": "NAME", "value": "lastName" }, { "context": "@q.defer()\n\n query =\n 'octoblu.firstName': firstName\n 'octoblu.lastName': lastName\n 'octoblu", "end": 787, "score": 0.9684845209121704, "start": 778, "tag": "NAME", "value": "firstName" }, { "context": "lu.firstName': firstName\n 'octoblu.lastName': lastName\n 'octoblu.email': email\n 'octoblu.optIn", "end": 822, "score": 0.8734472990036011, "start": 814, "tag": "NAME", "value": "lastName" } ]
public/angular/services/profile-service.coffee
octoblu/octoblu-frontend
5
class ProfileService constructor: (MeshbluHttpService, $cookies, $q) -> @MeshbluHttpService = MeshbluHttpService @cookies = $cookies @q = $q updateNew: (firstName, lastName, email, optInEmail) => deferred = @q.defer() query = 'octoblu.firstName': firstName 'octoblu.lastName': lastName 'octoblu.email': email 'octoblu.optInEmail': !!optInEmail 'octoblu.termsAcceptedAt': new Date() @MeshbluHttpService.updateDangerously @cookies.meshblu_auth_uuid, { $set: query }, (error) => return deferred.reject(error) if error? deferred.resolve() deferred.promise updateAfter: ({ firstName, lastName, email, optInEmail }) => deferred = @q.defer() query = 'octoblu.firstName': firstName 'octoblu.lastName': lastName 'octoblu.email': email 'octoblu.optInEmail': !!optInEmail @MeshbluHttpService.updateDangerously @cookies.meshblu_auth_uuid, { $set: query }, (error) => return deferred.reject(error) if error? deferred.resolve() deferred.promise angular.module('octobluApp').service 'ProfileService', ProfileService
147924
class ProfileService constructor: (MeshbluHttpService, $cookies, $q) -> @MeshbluHttpService = MeshbluHttpService @cookies = $cookies @q = $q updateNew: (<NAME>, <NAME>, email, optInEmail) => deferred = @q.defer() query = 'octoblu.firstName': <NAME> 'octoblu.lastName': <NAME> 'octoblu.email': email 'octoblu.optInEmail': !!optInEmail 'octoblu.termsAcceptedAt': new Date() @MeshbluHttpService.updateDangerously @cookies.meshblu_auth_uuid, { $set: query }, (error) => return deferred.reject(error) if error? deferred.resolve() deferred.promise updateAfter: ({ <NAME>, <NAME>, email, optInEmail }) => deferred = @q.defer() query = 'octoblu.firstName': <NAME> 'octoblu.lastName': <NAME> 'octoblu.email': email 'octoblu.optInEmail': !!optInEmail @MeshbluHttpService.updateDangerously @cookies.meshblu_auth_uuid, { $set: query }, (error) => return deferred.reject(error) if error? deferred.resolve() deferred.promise angular.module('octobluApp').service 'ProfileService', ProfileService
true
class ProfileService constructor: (MeshbluHttpService, $cookies, $q) -> @MeshbluHttpService = MeshbluHttpService @cookies = $cookies @q = $q updateNew: (PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, email, optInEmail) => deferred = @q.defer() query = 'octoblu.firstName': PI:NAME:<NAME>END_PI 'octoblu.lastName': PI:NAME:<NAME>END_PI 'octoblu.email': email 'octoblu.optInEmail': !!optInEmail 'octoblu.termsAcceptedAt': new Date() @MeshbluHttpService.updateDangerously @cookies.meshblu_auth_uuid, { $set: query }, (error) => return deferred.reject(error) if error? deferred.resolve() deferred.promise updateAfter: ({ PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, email, optInEmail }) => deferred = @q.defer() query = 'octoblu.firstName': PI:NAME:<NAME>END_PI 'octoblu.lastName': PI:NAME:<NAME>END_PI 'octoblu.email': email 'octoblu.optInEmail': !!optInEmail @MeshbluHttpService.updateDangerously @cookies.meshblu_auth_uuid, { $set: query }, (error) => return deferred.reject(error) if error? deferred.resolve() deferred.promise angular.module('octobluApp').service 'ProfileService', ProfileService
[ { "context": "ct! { |k,v| v }\n# @hsh.keys.sort.should == [1,3,5,7,9]\n\n# it \"is equivalent to delete_if if cha", "end": 1819, "score": 0.5549849271774292, "start": 1818, "tag": "KEY", "value": "3" }, { "context": "! { |k,v| v }\n# @hsh.keys.sort.should == [1,3,5,7,9]\n\n# it \"is equivalent to delete_if if chang", "end": 1821, "score": 0.5604076981544495, "start": 1820, "tag": "KEY", "value": "5" }, { "context": "{ |k,v| v }\n# @hsh.keys.sort.should == [1,3,5,7,9]\n\n# it \"is equivalent to delete_if if changes", "end": 1823, "score": 0.5270562171936035, "start": 1822, "tag": "KEY", "value": "7" }, { "context": "|k,v| v }\n# @hsh.keys.sort.should == [1,3,5,7,9]\n\n# it \"is equivalent to delete_if if changes a", "end": 1825, "score": 0.5412359237670898, "start": 1824, "tag": "KEY", "value": "9" } ]
spec/lib/corelib/hash/reject_spec.coffee
hasclass/core-lib
1
describe "Hash#reject", -> it "returns a new hash removing keys for which the block yields true", -> h = R.hashify(1: false, 2: true, 3: false, 4: true) expect( h.reject((k,v) -> v ).keys().sort() ).toEqual R(['1', '3']) xit "is equivalent to hsh.dup.delete_if", -> h = R.hashify(a: 'a', b: 'b', c: 'd') expect( h.reject (k,v) -> k == 'd' ).toEqual (h.dup().delete_if (k, v) -> k == 'd') # all_args_reject = [] # all_args_delete_if = [] # h = R.hashify(1 => 2, 3 => 4) # h.reject { |*args| all_args_reject << args } # h.delete_if { |*args| all_args_delete_if << args } # all_args_reject.should == all_args_delete_if # h = R.hashify(1 => 2) # # dup doesn't copy singleton methods # def h.to_a() end # h.reject { false }.to_a.should == [[1, 2]] xit "returns subclass instance for subclasses", -> # HashSpecs::MyHash[1 => 2, 3 => 4].reject { false }.should be_kind_of(HashSpecs::MyHash) # HashSpecs::MyHash[1 => 2, 3 => 4].reject { true }.should be_kind_of(HashSpecs::MyHash) xit "taints the resulting hash", -> # h = R.hashify(:a => 1).taint # h.reject {false}.tainted?.should == true xit "processes entries with the same order as reject!", -> h = R.hashify(a: 1, b: 2, c: 3, d: 4) # reject_pairs = [] # reject_bang_pairs = [] # h.dup.reject { |*pair| reject_pairs << pair } # h.reject! { |*pair| reject_bang_pairs << pair } # reject_pairs.should == reject_bang_pairs # it_behaves_like(:hash_iteration_no_block, :reject) # describe "Hash#reject!", -> # before(:each) do # @hsh = R.hashify # (1 .. 10).each { |k| @hsh[k] = k.even? } # @empty = R.hashify # it "removes keys from self for which the block yields true", -> # @hsh.reject! { |k,v| v } # @hsh.keys.sort.should == [1,3,5,7,9] # it "is equivalent to delete_if if changes are made", -> # @hsh.reject! { |k,v| v }.should == @hsh.delete_if { |k, v| v } # h = R.hashify(1 => 2, 3 => 4) # all_args_reject = [] # all_args_delete_if = [] # h.dup.reject! { |*args| all_args_reject << args } # h.dup.delete_if { |*args| all_args_delete_if << args } # all_args_reject.should == all_args_delete_if # it "returns nil if no changes were made", -> # R.hashify(:a => 1).reject! { |k,v| v > 1 }.should == nil # it "processes entries with the same order as delete_if", -> # h = R.hashify(:a => 1, :b => 2, :c => 3, :d => 4) # reject_bang_pairs = [] # delete_if_pairs = [] # h.dup.reject! { |*pair| reject_bang_pairs << pair } # h.dup.delete_if { |*pair| delete_if_pairs << pair } # reject_bang_pairs.should == delete_if_pairs # ruby_version_is ""..."1.9", -> # it "raises a TypeError if called on a frozen instance", -> # lambda { HashSpecs.frozen_hash.reject! { false } }.should raise_error(TypeError) # lambda { HashSpecs.empty_frozen_hash.reject! { true } }.should raise_error(TypeError) # ruby_version_is "1.9", -> # it "raises a RuntimeError if called on a frozen instance that is modified", -> # lambda { HashSpecs.empty_frozen_hash.reject! { true } }.should raise_error(RuntimeError) # it "raises a RuntimeError if called on a frozen instance that would not be modified", -> # lambda { HashSpecs.frozen_hash.reject! { false } }.should raise_error(RuntimeError) # ruby_version_is "" ... "1.8.7", -> # it "raises a LocalJumpError when called on a non-empty hash without a block", -> # lambda { @hsh.reject! }.should raise_error(LocalJumpError) # it "does not raise a LocalJumpError when called on an empty hash without a block", -> # @empty.reject!.should == nil # ruby_version_is "1.8.7", -> # it "returns an Enumerator when called on a non-empty hash without a block", -> # @hsh.reject!.should be_an_instance_of(enumerator_class) # it "returns an Enumerator when called on an empty hash without a block", -> # @empty.reject!.should be_an_instance_of(enumerator_class) # end
141007
describe "Hash#reject", -> it "returns a new hash removing keys for which the block yields true", -> h = R.hashify(1: false, 2: true, 3: false, 4: true) expect( h.reject((k,v) -> v ).keys().sort() ).toEqual R(['1', '3']) xit "is equivalent to hsh.dup.delete_if", -> h = R.hashify(a: 'a', b: 'b', c: 'd') expect( h.reject (k,v) -> k == 'd' ).toEqual (h.dup().delete_if (k, v) -> k == 'd') # all_args_reject = [] # all_args_delete_if = [] # h = R.hashify(1 => 2, 3 => 4) # h.reject { |*args| all_args_reject << args } # h.delete_if { |*args| all_args_delete_if << args } # all_args_reject.should == all_args_delete_if # h = R.hashify(1 => 2) # # dup doesn't copy singleton methods # def h.to_a() end # h.reject { false }.to_a.should == [[1, 2]] xit "returns subclass instance for subclasses", -> # HashSpecs::MyHash[1 => 2, 3 => 4].reject { false }.should be_kind_of(HashSpecs::MyHash) # HashSpecs::MyHash[1 => 2, 3 => 4].reject { true }.should be_kind_of(HashSpecs::MyHash) xit "taints the resulting hash", -> # h = R.hashify(:a => 1).taint # h.reject {false}.tainted?.should == true xit "processes entries with the same order as reject!", -> h = R.hashify(a: 1, b: 2, c: 3, d: 4) # reject_pairs = [] # reject_bang_pairs = [] # h.dup.reject { |*pair| reject_pairs << pair } # h.reject! { |*pair| reject_bang_pairs << pair } # reject_pairs.should == reject_bang_pairs # it_behaves_like(:hash_iteration_no_block, :reject) # describe "Hash#reject!", -> # before(:each) do # @hsh = R.hashify # (1 .. 10).each { |k| @hsh[k] = k.even? } # @empty = R.hashify # it "removes keys from self for which the block yields true", -> # @hsh.reject! { |k,v| v } # @hsh.keys.sort.should == [1,<KEY>,<KEY>,<KEY>,<KEY>] # it "is equivalent to delete_if if changes are made", -> # @hsh.reject! { |k,v| v }.should == @hsh.delete_if { |k, v| v } # h = R.hashify(1 => 2, 3 => 4) # all_args_reject = [] # all_args_delete_if = [] # h.dup.reject! { |*args| all_args_reject << args } # h.dup.delete_if { |*args| all_args_delete_if << args } # all_args_reject.should == all_args_delete_if # it "returns nil if no changes were made", -> # R.hashify(:a => 1).reject! { |k,v| v > 1 }.should == nil # it "processes entries with the same order as delete_if", -> # h = R.hashify(:a => 1, :b => 2, :c => 3, :d => 4) # reject_bang_pairs = [] # delete_if_pairs = [] # h.dup.reject! { |*pair| reject_bang_pairs << pair } # h.dup.delete_if { |*pair| delete_if_pairs << pair } # reject_bang_pairs.should == delete_if_pairs # ruby_version_is ""..."1.9", -> # it "raises a TypeError if called on a frozen instance", -> # lambda { HashSpecs.frozen_hash.reject! { false } }.should raise_error(TypeError) # lambda { HashSpecs.empty_frozen_hash.reject! { true } }.should raise_error(TypeError) # ruby_version_is "1.9", -> # it "raises a RuntimeError if called on a frozen instance that is modified", -> # lambda { HashSpecs.empty_frozen_hash.reject! { true } }.should raise_error(RuntimeError) # it "raises a RuntimeError if called on a frozen instance that would not be modified", -> # lambda { HashSpecs.frozen_hash.reject! { false } }.should raise_error(RuntimeError) # ruby_version_is "" ... "1.8.7", -> # it "raises a LocalJumpError when called on a non-empty hash without a block", -> # lambda { @hsh.reject! }.should raise_error(LocalJumpError) # it "does not raise a LocalJumpError when called on an empty hash without a block", -> # @empty.reject!.should == nil # ruby_version_is "1.8.7", -> # it "returns an Enumerator when called on a non-empty hash without a block", -> # @hsh.reject!.should be_an_instance_of(enumerator_class) # it "returns an Enumerator when called on an empty hash without a block", -> # @empty.reject!.should be_an_instance_of(enumerator_class) # end
true
describe "Hash#reject", -> it "returns a new hash removing keys for which the block yields true", -> h = R.hashify(1: false, 2: true, 3: false, 4: true) expect( h.reject((k,v) -> v ).keys().sort() ).toEqual R(['1', '3']) xit "is equivalent to hsh.dup.delete_if", -> h = R.hashify(a: 'a', b: 'b', c: 'd') expect( h.reject (k,v) -> k == 'd' ).toEqual (h.dup().delete_if (k, v) -> k == 'd') # all_args_reject = [] # all_args_delete_if = [] # h = R.hashify(1 => 2, 3 => 4) # h.reject { |*args| all_args_reject << args } # h.delete_if { |*args| all_args_delete_if << args } # all_args_reject.should == all_args_delete_if # h = R.hashify(1 => 2) # # dup doesn't copy singleton methods # def h.to_a() end # h.reject { false }.to_a.should == [[1, 2]] xit "returns subclass instance for subclasses", -> # HashSpecs::MyHash[1 => 2, 3 => 4].reject { false }.should be_kind_of(HashSpecs::MyHash) # HashSpecs::MyHash[1 => 2, 3 => 4].reject { true }.should be_kind_of(HashSpecs::MyHash) xit "taints the resulting hash", -> # h = R.hashify(:a => 1).taint # h.reject {false}.tainted?.should == true xit "processes entries with the same order as reject!", -> h = R.hashify(a: 1, b: 2, c: 3, d: 4) # reject_pairs = [] # reject_bang_pairs = [] # h.dup.reject { |*pair| reject_pairs << pair } # h.reject! { |*pair| reject_bang_pairs << pair } # reject_pairs.should == reject_bang_pairs # it_behaves_like(:hash_iteration_no_block, :reject) # describe "Hash#reject!", -> # before(:each) do # @hsh = R.hashify # (1 .. 10).each { |k| @hsh[k] = k.even? } # @empty = R.hashify # it "removes keys from self for which the block yields true", -> # @hsh.reject! { |k,v| v } # @hsh.keys.sort.should == [1,PI:KEY:<KEY>END_PI,PI:KEY:<KEY>END_PI,PI:KEY:<KEY>END_PI,PI:KEY:<KEY>END_PI] # it "is equivalent to delete_if if changes are made", -> # @hsh.reject! { |k,v| v }.should == @hsh.delete_if { |k, v| v } # h = R.hashify(1 => 2, 3 => 4) # all_args_reject = [] # all_args_delete_if = [] # h.dup.reject! { |*args| all_args_reject << args } # h.dup.delete_if { |*args| all_args_delete_if << args } # all_args_reject.should == all_args_delete_if # it "returns nil if no changes were made", -> # R.hashify(:a => 1).reject! { |k,v| v > 1 }.should == nil # it "processes entries with the same order as delete_if", -> # h = R.hashify(:a => 1, :b => 2, :c => 3, :d => 4) # reject_bang_pairs = [] # delete_if_pairs = [] # h.dup.reject! { |*pair| reject_bang_pairs << pair } # h.dup.delete_if { |*pair| delete_if_pairs << pair } # reject_bang_pairs.should == delete_if_pairs # ruby_version_is ""..."1.9", -> # it "raises a TypeError if called on a frozen instance", -> # lambda { HashSpecs.frozen_hash.reject! { false } }.should raise_error(TypeError) # lambda { HashSpecs.empty_frozen_hash.reject! { true } }.should raise_error(TypeError) # ruby_version_is "1.9", -> # it "raises a RuntimeError if called on a frozen instance that is modified", -> # lambda { HashSpecs.empty_frozen_hash.reject! { true } }.should raise_error(RuntimeError) # it "raises a RuntimeError if called on a frozen instance that would not be modified", -> # lambda { HashSpecs.frozen_hash.reject! { false } }.should raise_error(RuntimeError) # ruby_version_is "" ... "1.8.7", -> # it "raises a LocalJumpError when called on a non-empty hash without a block", -> # lambda { @hsh.reject! }.should raise_error(LocalJumpError) # it "does not raise a LocalJumpError when called on an empty hash without a block", -> # @empty.reject!.should == nil # ruby_version_is "1.8.7", -> # it "returns an Enumerator when called on a non-empty hash without a block", -> # @hsh.reject!.should be_an_instance_of(enumerator_class) # it "returns an Enumerator when called on an empty hash without a block", -> # @empty.reject!.should be_an_instance_of(enumerator_class) # end
[ { "context": "###\n * @author \t\tAbdelhakim RAFIK\n * @version \tv1.0.1\n * @license \tMIT License\n * @", "end": 33, "score": 0.9998911619186401, "start": 17, "tag": "NAME", "value": "Abdelhakim RAFIK" }, { "context": "nse \tMIT License\n * @copyright \tCopyright (c) 2021 Abdelhakim RAFIK\n * @date \t\tMar 2021\n###\n\n{ Router }\t= require 'ex", "end": 129, "score": 0.9998860955238342, "start": 113, "tag": "NAME", "value": "Abdelhakim RAFIK" } ]
src/routes/privateRouter.coffee
AbdelhakimRafik/Pharmalogy-API
0
### * @author Abdelhakim RAFIK * @version v1.0.1 * @license MIT License * @copyright Copyright (c) 2021 Abdelhakim RAFIK * @date Mar 2021 ### { Router } = require 'express' router = do Router authMiddleware = require '../app/middlewares/authMiddleware' userController = require '../app/controllers/userController' # protect router with authentication middleware router.use authMiddleware # export router module.exports = router router.get '/user/:id', userController.getUserById
101203
### * @author <NAME> * @version v1.0.1 * @license MIT License * @copyright Copyright (c) 2021 <NAME> * @date Mar 2021 ### { Router } = require 'express' router = do Router authMiddleware = require '../app/middlewares/authMiddleware' userController = require '../app/controllers/userController' # protect router with authentication middleware router.use authMiddleware # export router module.exports = router router.get '/user/:id', userController.getUserById
true
### * @author PI:NAME:<NAME>END_PI * @version v1.0.1 * @license MIT License * @copyright Copyright (c) 2021 PI:NAME:<NAME>END_PI * @date Mar 2021 ### { Router } = require 'express' router = do Router authMiddleware = require '../app/middlewares/authMiddleware' userController = require '../app/controllers/userController' # protect router with authentication middleware router.use authMiddleware # export router module.exports = router router.get '/user/:id', userController.getUserById
[ { "context": " login: $scope.login\n password: $scope.password\n code: $scope.code\n ", "end": 841, "score": 0.8341336846351624, "start": 826, "tag": "PASSWORD", "value": "$scope.password" }, { "context": ", JSON.stringify({login: $scope.login, password: $scope.password}), { expires: 1 / (24 * 60) * 2, path: '/' })\n ", "end": 1436, "score": 0.9438427090644836, "start": 1422, "tag": "PASSWORD", "value": "scope.password" } ]
resources/assets/coffee/controllers/login.coffee
maxflex/ycms
0
angular .module 'Egecms' .controller 'LoginCtrl', ($scope, $http) -> angular.element(document).ready -> $scope.l = Ladda.create(document.querySelector('#login-submit')) login_data = $.cookie("login_data") if login_data isnt undefined login_data = JSON.parse(login_data) $scope.login = login_data.login $scope.password = login_data.password $scope.sms_verification = true $scope.$apply() #обработка события по enter в форме логина $scope.enter = ($event) -> if $event.keyCode == 13 $scope.checkFields() $scope.goLogin = -> ajaxStart() $http.post 'login', login: $scope.login password: $scope.password code: $scope.code captcha: grecaptcha.getResponse() .then (response) -> grecaptcha.reset() if response.data is true $.removeCookie('login_data') location.reload() else if response.data is 'sms' ajaxEnd() $scope.in_process = false $scope.l.stop() $scope.sms_verification = true $.cookie("login_data", JSON.stringify({login: $scope.login, password: $scope.password}), { expires: 1 / (24 * 60) * 2, path: '/' }) else $scope.in_process = false ajaxEnd() $scope.l.stop() notifyError "Неправильная пара логин-пароль" $scope.checkFields = -> $scope.l.start() $scope.in_process = true if grecaptcha.getResponse() is '' then grecaptcha.execute() else $scope.goLogin()
4774
angular .module 'Egecms' .controller 'LoginCtrl', ($scope, $http) -> angular.element(document).ready -> $scope.l = Ladda.create(document.querySelector('#login-submit')) login_data = $.cookie("login_data") if login_data isnt undefined login_data = JSON.parse(login_data) $scope.login = login_data.login $scope.password = login_data.password $scope.sms_verification = true $scope.$apply() #обработка события по enter в форме логина $scope.enter = ($event) -> if $event.keyCode == 13 $scope.checkFields() $scope.goLogin = -> ajaxStart() $http.post 'login', login: $scope.login password: <PASSWORD> code: $scope.code captcha: grecaptcha.getResponse() .then (response) -> grecaptcha.reset() if response.data is true $.removeCookie('login_data') location.reload() else if response.data is 'sms' ajaxEnd() $scope.in_process = false $scope.l.stop() $scope.sms_verification = true $.cookie("login_data", JSON.stringify({login: $scope.login, password: $<PASSWORD>}), { expires: 1 / (24 * 60) * 2, path: '/' }) else $scope.in_process = false ajaxEnd() $scope.l.stop() notifyError "Неправильная пара логин-пароль" $scope.checkFields = -> $scope.l.start() $scope.in_process = true if grecaptcha.getResponse() is '' then grecaptcha.execute() else $scope.goLogin()
true
angular .module 'Egecms' .controller 'LoginCtrl', ($scope, $http) -> angular.element(document).ready -> $scope.l = Ladda.create(document.querySelector('#login-submit')) login_data = $.cookie("login_data") if login_data isnt undefined login_data = JSON.parse(login_data) $scope.login = login_data.login $scope.password = login_data.password $scope.sms_verification = true $scope.$apply() #обработка события по enter в форме логина $scope.enter = ($event) -> if $event.keyCode == 13 $scope.checkFields() $scope.goLogin = -> ajaxStart() $http.post 'login', login: $scope.login password: PI:PASSWORD:<PASSWORD>END_PI code: $scope.code captcha: grecaptcha.getResponse() .then (response) -> grecaptcha.reset() if response.data is true $.removeCookie('login_data') location.reload() else if response.data is 'sms' ajaxEnd() $scope.in_process = false $scope.l.stop() $scope.sms_verification = true $.cookie("login_data", JSON.stringify({login: $scope.login, password: $PI:PASSWORD:<PASSWORD>END_PI}), { expires: 1 / (24 * 60) * 2, path: '/' }) else $scope.in_process = false ajaxEnd() $scope.l.stop() notifyError "Неправильная пара логин-пароль" $scope.checkFields = -> $scope.l.start() $scope.in_process = true if grecaptcha.getResponse() is '' then grecaptcha.execute() else $scope.goLogin()
[ { "context": "me json file ?\nforceVersionTag = false\ngitUser = \"anodynos\"\ngitPassword = null\nthrow \"No gitPassword set\" if", "end": 1528, "score": 0.9994287490844727, "start": 1520, "tag": "USERNAME", "value": "anodynos" }, { "context": "sionTag = false\ngitUser = \"anodynos\"\ngitPassword = null\nthrow \"No gitPassword set\" if not gitPassword\n\n# ", "end": 1548, "score": 0.974538266658783, "start": 1544, "tag": "PASSWORD", "value": "null" }, { "context": "Ii with {standalone} & streams https://github.com/deepak1556/gulp-browserify/issues/9\nbrowserifyDep = (dep, op", "end": 1681, "score": 0.9996359348297119, "start": 1671, "tag": "USERNAME", "value": "deepak1556" }, { "context": " if _.startsWith foundRepo, 'git://github.com/anodynos/'\n l.ok \"Already bower registered: '#{dep}", "end": 3832, "score": 0.9994262456893921, "start": 3824, "tag": "USERNAME", "value": "anodynos" }, { "context": " r.get(remoteRepoApiUrl dep, {auth: username:gitUser, password:gitPassword}).then(\n (resp)-> ", "end": 4535, "score": 0.9990047216415405, "start": 4528, "tag": "USERNAME", "value": "gitUser" }, { "context": "RepoApiUrl dep, {auth: username:gitUser, password:gitPassword}).then(\n (resp)-> # remote exists\n ", "end": 4557, "score": 0.9971847534179688, "start": 4546, "tag": "PASSWORD", "value": "gitPassword" }, { "context": "b_#{dep}\"},\n {auth: username:gitUser, password:gitPassword}\n ).then ->\n ", "end": 5298, "score": 0.9990363121032715, "start": 5291, "tag": "USERNAME", "value": "gitUser" }, { "context": " {auth: username:gitUser, password:gitPassword}\n ).then ->\n l.ok \"Re", "end": 5320, "score": 0.9989189505577087, "start": 5309, "tag": "PASSWORD", "value": "gitPassword" }, { "context": " git remote add origin https://github.com/anodynos/node2web_#{dep}\n \"\"\", cwd: l", "end": 5636, "score": 0.9994598031044006, "start": 5628, "tag": "USERNAME", "value": "anodynos" }, { "context": " From [node2web](http://github.com/anodynos/node2web) collection,\n should/wi", "end": 6433, "score": 0.9899705052375793, "start": 6425, "tag": "USERNAME", "value": "anodynos" } ]
source/main.coffee
anodynos/node2web
3
### pseudo code: get newest node core modules and forEach: get the local repo updated/cloned/inited if remoteRepoExists if localRepoExists git fetch (with tags) else git clone else git create remote repo if not localRepoExists # first run create local repo dir git init git set remote repo # save latest version if git tags dont have currentVersion save "#{dep}.js" & "#{dep}.min.js" save bower.json save readme.md git add & commit git tag version git push to remote (with tags) register to bower (if not already taken) ### # @todo: Save a `.min.js` also using uglify2 # @todo: Allow overwritting of tag version (with flag) # @todo: refactor into more functions _ = (_B = require 'uberscore')._ _.mixin (require 'underscore.string').exports() l = new _B.Logger 'bower-node-browserify', 1 path = require 'path' os = require 'os' UglifyJS2 = require 'uglify-js' browserify = require 'browserify' # promises When = require 'when' sequence = require('when/sequence') qfs = require("q-io/fs"); nodefn = require("when/node/function") logPromise = require('./logPromise') l wExec = nodefn.lift require("child_process").exec wLogExec = logPromise wExec, 'exec', 'stdout', 'stderr' r = require 'requestify' DEPS = require './DEPS' localRepoPath = (dep)-> "../module_repos/" + if dep then "node2web_#{dep}" else "" # todo: ask in CLI or some json file ? forceVersionTag = false gitUser = "anodynos" gitPassword = null throw "No gitPassword set" if not gitPassword # can't browserify via APIi with {standalone} & streams https://github.com/deepak1556/gulp-browserify/issues/9 browserifyDep = (dep, options)-> options = {standalone: dep} if not options tempDepHeadPath = path.join os.tmpdir(), "#{dep}_head.js" qfs.write(tempDepHeadPath, "module.exports = require('#{dep}');" ).then -> b = browserify tempDepHeadPath nodefn.call(b.bundle.bind(b), options).then (src)-> qfs.remove(tempDepHeadPath).then -> src remoteRepoApiUrl = (dep)-> "https://api.github.com/repos/#{gitUser}/node2web_#{dep}" remoteRepoUrl = (dep, user='', passwd='')-> auth = if user then user + (if passwd then ":#{passwd}" else '') + '@' else '' "https://#{auth}github.com/#{gitUser}/node2web_#{dep}" readJson = (fn)-> qfs.read(fn).then JSON.parse, ->{} git_tagList = (dep)-> wExec('git tag -l', cwd: localRepoPath dep).then (stdout)-> tags = [] for o in stdout when o tags.push tag for tag in o.split('\n') when tag tags git_push = (dep)-> wLogExec("git push #{remoteRepoUrl dep, gitUser, gitPassword} master --tags -f", cwd: localRepoPath dep) git_commitTag = (dep, tag)-> wLogExec(""" git add . git commit -m "browserify version '#{tag}'" git tag #{tag} -f """, cwd: localRepoPath dep) # read version of node, browserify etc cmd_version = (cmd='node')-> wExec("#{cmd} -v").then (stdout)-> _.trim stdout[0].replace '\n', '' # using browserify as API, not CLI getBrowserifyVersion = -> readJson('../node_modules/browserify/package.json').then (pkg)-> pkg.version # @param dep {String} # @resolve false if dep is not bower registered # the repo name if its registered bower_lookup = (dep)-> wExec("bower lookup #{dep}").spread (out)-> if _.startsWith out, 'Package not found.' false else _.trim out[dep.length..].replace('\n', '') bower_register = (dep)-> bower_lookup(dep).then (foundRepo)-> if not foundRepo l.verbose "Registering with bower: '#{dep}' = '#{remoteRepoUrl dep}'" wLogExec("bower register #{dep} #{remoteRepoUrl dep}", cwd: localRepoPath dep).then -> l.ok "Success: bower register #{dep} #{remoteRepoUrl dep}" else if _.startsWith foundRepo, 'git://github.com/anodynos/' l.ok "Already bower registered: '#{dep}' = '#{foundRepo}'" else l.warn "bower registration is taken: '#{dep}' = '#{foundRepo}'" handleDeps = (deps)-> l.log 'deps to handle:', deps getBrowserifyVersion().then (version)-> l.verbose "\nbrowserify (node_modules/browserify/package.json) version = '#{version}'" getDepTask = (dep)-> -> l.verbose "\nHandling dep = '#{dep}'" localRepo = localRepoPath dep qfs.exists(localRepo).then (localRepoExists)-> if localRepoExists then l.ok "local repo '#{localRepo}' exists" else l.warn "local repo '#{localRepo}' NOT exists" r.get(remoteRepoApiUrl dep, {auth: username:gitUser, password:gitPassword}).then( (resp)-> # remote exists l.ok "Remote repo '#{remoteRepoUrl dep}' exists" if localRepoExists wLogExec("git fetch -t", cwd: localRepo) else qfs.makeTree(localRepoPath()).then -> wLogExec("git clone #{remoteRepoUrl dep}", cwd:localRepoPath()) (rej)-> if rej.code isnt '404' l.er err = "Unknown github.com API error", rej throw new Error err else # remote not exists l.warn "Remote repo '#{remoteRepoUrl dep}' NOT exists - creating it" r.post('https://api.github.com/user/repos', { "name":"node2web_#{dep}"}, {auth: username:gitUser, password:gitPassword} ).then -> l.ok "Remote repo '#{remoteRepoUrl dep}' created" if not localRepoExists qfs.makeTree(localRepo).then -> wLogExec(""" git init git remote add origin https://github.com/anodynos/node2web_#{dep} """, cwd: localRepo).then -> l.deb "Local repo '#{localRepo}' created." ).then( -> l.verbose "local & remote repos should both be in sync for '#{dep}'" git_tagList(dep).then (tags)-> if forceVersionTag or (version not in tags) l.verbose "'#{dep}' tag version '#{version}' not exists - Generating & saving '#{dep}.js'." descr = """ '#{dep}' nodejs core module browserify-ied with `--standalone #{dep }`. Should support all module systems (commonjs, AMD & `window.#{dep}`) - check browserify docs.""" header = """ #{descr} From [node2web](http://github.com/anodynos/node2web) collection, should/will be exposed as '#{dep}' to [bower](http://bower.io) for *browser* usage. browserify version: '#{version}', build date '#{new Date}' """ save = (file, content)-> l.verbose "Saving file '#{file = path.join(localRepo, file)}'" qfs.write file, content browserifyDep(dep).then (src)-> crap = '/mnt/tc/DevelopmentProjects/WebStormWorkspace/p/node2web/node_modules/browserify/node_modules/insert-module-globals/node_modules/process/browser.js' src = src.replace new RegExp(crap, 'g'), 'process_browser' pkgInfo = JSON.stringify { name: dep version: version main: "#{dep}.min.js" description: descr keywords: ['nodejs', 'browserify', dep] }, null, ' ' When.all([ save dep + '.js', "/** #{header} \n**/\n#{src}" save dep + '.min.js', """/** '#{dep}' nodejs module minified for AMD, CommonJS & `window.#{dep}`. browserify v#{version} **/ #{(UglifyJS2.minify src, {fromString: true}).code}""" save 'readme.md', header save 'bower.json', pkgInfo save 'package.json', pkgInfo ]).then -> git_commitTag dep, version else l.verbose "Local repo already has a version tag '#{version}' for '#{dep}' - not saving/commiting anything." ).then -> sequence [ git_push, bower_register ], dep sequence(getDepTask dep for dep in deps).catch (err)-> l.er err handleDeps (dep for dep in DEPS.nodeAll when (dep not in DEPS.notSupported) and (dep isnt 'http') )
153045
### pseudo code: get newest node core modules and forEach: get the local repo updated/cloned/inited if remoteRepoExists if localRepoExists git fetch (with tags) else git clone else git create remote repo if not localRepoExists # first run create local repo dir git init git set remote repo # save latest version if git tags dont have currentVersion save "#{dep}.js" & "#{dep}.min.js" save bower.json save readme.md git add & commit git tag version git push to remote (with tags) register to bower (if not already taken) ### # @todo: Save a `.min.js` also using uglify2 # @todo: Allow overwritting of tag version (with flag) # @todo: refactor into more functions _ = (_B = require 'uberscore')._ _.mixin (require 'underscore.string').exports() l = new _B.Logger 'bower-node-browserify', 1 path = require 'path' os = require 'os' UglifyJS2 = require 'uglify-js' browserify = require 'browserify' # promises When = require 'when' sequence = require('when/sequence') qfs = require("q-io/fs"); nodefn = require("when/node/function") logPromise = require('./logPromise') l wExec = nodefn.lift require("child_process").exec wLogExec = logPromise wExec, 'exec', 'stdout', 'stderr' r = require 'requestify' DEPS = require './DEPS' localRepoPath = (dep)-> "../module_repos/" + if dep then "node2web_#{dep}" else "" # todo: ask in CLI or some json file ? forceVersionTag = false gitUser = "anodynos" gitPassword = <PASSWORD> throw "No gitPassword set" if not gitPassword # can't browserify via APIi with {standalone} & streams https://github.com/deepak1556/gulp-browserify/issues/9 browserifyDep = (dep, options)-> options = {standalone: dep} if not options tempDepHeadPath = path.join os.tmpdir(), "#{dep}_head.js" qfs.write(tempDepHeadPath, "module.exports = require('#{dep}');" ).then -> b = browserify tempDepHeadPath nodefn.call(b.bundle.bind(b), options).then (src)-> qfs.remove(tempDepHeadPath).then -> src remoteRepoApiUrl = (dep)-> "https://api.github.com/repos/#{gitUser}/node2web_#{dep}" remoteRepoUrl = (dep, user='', passwd='')-> auth = if user then user + (if passwd then ":#{passwd}" else '') + '@' else '' "https://#{auth}github.com/#{gitUser}/node2web_#{dep}" readJson = (fn)-> qfs.read(fn).then JSON.parse, ->{} git_tagList = (dep)-> wExec('git tag -l', cwd: localRepoPath dep).then (stdout)-> tags = [] for o in stdout when o tags.push tag for tag in o.split('\n') when tag tags git_push = (dep)-> wLogExec("git push #{remoteRepoUrl dep, gitUser, gitPassword} master --tags -f", cwd: localRepoPath dep) git_commitTag = (dep, tag)-> wLogExec(""" git add . git commit -m "browserify version '#{tag}'" git tag #{tag} -f """, cwd: localRepoPath dep) # read version of node, browserify etc cmd_version = (cmd='node')-> wExec("#{cmd} -v").then (stdout)-> _.trim stdout[0].replace '\n', '' # using browserify as API, not CLI getBrowserifyVersion = -> readJson('../node_modules/browserify/package.json').then (pkg)-> pkg.version # @param dep {String} # @resolve false if dep is not bower registered # the repo name if its registered bower_lookup = (dep)-> wExec("bower lookup #{dep}").spread (out)-> if _.startsWith out, 'Package not found.' false else _.trim out[dep.length..].replace('\n', '') bower_register = (dep)-> bower_lookup(dep).then (foundRepo)-> if not foundRepo l.verbose "Registering with bower: '#{dep}' = '#{remoteRepoUrl dep}'" wLogExec("bower register #{dep} #{remoteRepoUrl dep}", cwd: localRepoPath dep).then -> l.ok "Success: bower register #{dep} #{remoteRepoUrl dep}" else if _.startsWith foundRepo, 'git://github.com/anodynos/' l.ok "Already bower registered: '#{dep}' = '#{foundRepo}'" else l.warn "bower registration is taken: '#{dep}' = '#{foundRepo}'" handleDeps = (deps)-> l.log 'deps to handle:', deps getBrowserifyVersion().then (version)-> l.verbose "\nbrowserify (node_modules/browserify/package.json) version = '#{version}'" getDepTask = (dep)-> -> l.verbose "\nHandling dep = '#{dep}'" localRepo = localRepoPath dep qfs.exists(localRepo).then (localRepoExists)-> if localRepoExists then l.ok "local repo '#{localRepo}' exists" else l.warn "local repo '#{localRepo}' NOT exists" r.get(remoteRepoApiUrl dep, {auth: username:gitUser, password:<PASSWORD>}).then( (resp)-> # remote exists l.ok "Remote repo '#{remoteRepoUrl dep}' exists" if localRepoExists wLogExec("git fetch -t", cwd: localRepo) else qfs.makeTree(localRepoPath()).then -> wLogExec("git clone #{remoteRepoUrl dep}", cwd:localRepoPath()) (rej)-> if rej.code isnt '404' l.er err = "Unknown github.com API error", rej throw new Error err else # remote not exists l.warn "Remote repo '#{remoteRepoUrl dep}' NOT exists - creating it" r.post('https://api.github.com/user/repos', { "name":"node2web_#{dep}"}, {auth: username:gitUser, password:<PASSWORD>} ).then -> l.ok "Remote repo '#{remoteRepoUrl dep}' created" if not localRepoExists qfs.makeTree(localRepo).then -> wLogExec(""" git init git remote add origin https://github.com/anodynos/node2web_#{dep} """, cwd: localRepo).then -> l.deb "Local repo '#{localRepo}' created." ).then( -> l.verbose "local & remote repos should both be in sync for '#{dep}'" git_tagList(dep).then (tags)-> if forceVersionTag or (version not in tags) l.verbose "'#{dep}' tag version '#{version}' not exists - Generating & saving '#{dep}.js'." descr = """ '#{dep}' nodejs core module browserify-ied with `--standalone #{dep }`. Should support all module systems (commonjs, AMD & `window.#{dep}`) - check browserify docs.""" header = """ #{descr} From [node2web](http://github.com/anodynos/node2web) collection, should/will be exposed as '#{dep}' to [bower](http://bower.io) for *browser* usage. browserify version: '#{version}', build date '#{new Date}' """ save = (file, content)-> l.verbose "Saving file '#{file = path.join(localRepo, file)}'" qfs.write file, content browserifyDep(dep).then (src)-> crap = '/mnt/tc/DevelopmentProjects/WebStormWorkspace/p/node2web/node_modules/browserify/node_modules/insert-module-globals/node_modules/process/browser.js' src = src.replace new RegExp(crap, 'g'), 'process_browser' pkgInfo = JSON.stringify { name: dep version: version main: "#{dep}.min.js" description: descr keywords: ['nodejs', 'browserify', dep] }, null, ' ' When.all([ save dep + '.js', "/** #{header} \n**/\n#{src}" save dep + '.min.js', """/** '#{dep}' nodejs module minified for AMD, CommonJS & `window.#{dep}`. browserify v#{version} **/ #{(UglifyJS2.minify src, {fromString: true}).code}""" save 'readme.md', header save 'bower.json', pkgInfo save 'package.json', pkgInfo ]).then -> git_commitTag dep, version else l.verbose "Local repo already has a version tag '#{version}' for '#{dep}' - not saving/commiting anything." ).then -> sequence [ git_push, bower_register ], dep sequence(getDepTask dep for dep in deps).catch (err)-> l.er err handleDeps (dep for dep in DEPS.nodeAll when (dep not in DEPS.notSupported) and (dep isnt 'http') )
true
### pseudo code: get newest node core modules and forEach: get the local repo updated/cloned/inited if remoteRepoExists if localRepoExists git fetch (with tags) else git clone else git create remote repo if not localRepoExists # first run create local repo dir git init git set remote repo # save latest version if git tags dont have currentVersion save "#{dep}.js" & "#{dep}.min.js" save bower.json save readme.md git add & commit git tag version git push to remote (with tags) register to bower (if not already taken) ### # @todo: Save a `.min.js` also using uglify2 # @todo: Allow overwritting of tag version (with flag) # @todo: refactor into more functions _ = (_B = require 'uberscore')._ _.mixin (require 'underscore.string').exports() l = new _B.Logger 'bower-node-browserify', 1 path = require 'path' os = require 'os' UglifyJS2 = require 'uglify-js' browserify = require 'browserify' # promises When = require 'when' sequence = require('when/sequence') qfs = require("q-io/fs"); nodefn = require("when/node/function") logPromise = require('./logPromise') l wExec = nodefn.lift require("child_process").exec wLogExec = logPromise wExec, 'exec', 'stdout', 'stderr' r = require 'requestify' DEPS = require './DEPS' localRepoPath = (dep)-> "../module_repos/" + if dep then "node2web_#{dep}" else "" # todo: ask in CLI or some json file ? forceVersionTag = false gitUser = "anodynos" gitPassword = PI:PASSWORD:<PASSWORD>END_PI throw "No gitPassword set" if not gitPassword # can't browserify via APIi with {standalone} & streams https://github.com/deepak1556/gulp-browserify/issues/9 browserifyDep = (dep, options)-> options = {standalone: dep} if not options tempDepHeadPath = path.join os.tmpdir(), "#{dep}_head.js" qfs.write(tempDepHeadPath, "module.exports = require('#{dep}');" ).then -> b = browserify tempDepHeadPath nodefn.call(b.bundle.bind(b), options).then (src)-> qfs.remove(tempDepHeadPath).then -> src remoteRepoApiUrl = (dep)-> "https://api.github.com/repos/#{gitUser}/node2web_#{dep}" remoteRepoUrl = (dep, user='', passwd='')-> auth = if user then user + (if passwd then ":#{passwd}" else '') + '@' else '' "https://#{auth}github.com/#{gitUser}/node2web_#{dep}" readJson = (fn)-> qfs.read(fn).then JSON.parse, ->{} git_tagList = (dep)-> wExec('git tag -l', cwd: localRepoPath dep).then (stdout)-> tags = [] for o in stdout when o tags.push tag for tag in o.split('\n') when tag tags git_push = (dep)-> wLogExec("git push #{remoteRepoUrl dep, gitUser, gitPassword} master --tags -f", cwd: localRepoPath dep) git_commitTag = (dep, tag)-> wLogExec(""" git add . git commit -m "browserify version '#{tag}'" git tag #{tag} -f """, cwd: localRepoPath dep) # read version of node, browserify etc cmd_version = (cmd='node')-> wExec("#{cmd} -v").then (stdout)-> _.trim stdout[0].replace '\n', '' # using browserify as API, not CLI getBrowserifyVersion = -> readJson('../node_modules/browserify/package.json').then (pkg)-> pkg.version # @param dep {String} # @resolve false if dep is not bower registered # the repo name if its registered bower_lookup = (dep)-> wExec("bower lookup #{dep}").spread (out)-> if _.startsWith out, 'Package not found.' false else _.trim out[dep.length..].replace('\n', '') bower_register = (dep)-> bower_lookup(dep).then (foundRepo)-> if not foundRepo l.verbose "Registering with bower: '#{dep}' = '#{remoteRepoUrl dep}'" wLogExec("bower register #{dep} #{remoteRepoUrl dep}", cwd: localRepoPath dep).then -> l.ok "Success: bower register #{dep} #{remoteRepoUrl dep}" else if _.startsWith foundRepo, 'git://github.com/anodynos/' l.ok "Already bower registered: '#{dep}' = '#{foundRepo}'" else l.warn "bower registration is taken: '#{dep}' = '#{foundRepo}'" handleDeps = (deps)-> l.log 'deps to handle:', deps getBrowserifyVersion().then (version)-> l.verbose "\nbrowserify (node_modules/browserify/package.json) version = '#{version}'" getDepTask = (dep)-> -> l.verbose "\nHandling dep = '#{dep}'" localRepo = localRepoPath dep qfs.exists(localRepo).then (localRepoExists)-> if localRepoExists then l.ok "local repo '#{localRepo}' exists" else l.warn "local repo '#{localRepo}' NOT exists" r.get(remoteRepoApiUrl dep, {auth: username:gitUser, password:PI:PASSWORD:<PASSWORD>END_PI}).then( (resp)-> # remote exists l.ok "Remote repo '#{remoteRepoUrl dep}' exists" if localRepoExists wLogExec("git fetch -t", cwd: localRepo) else qfs.makeTree(localRepoPath()).then -> wLogExec("git clone #{remoteRepoUrl dep}", cwd:localRepoPath()) (rej)-> if rej.code isnt '404' l.er err = "Unknown github.com API error", rej throw new Error err else # remote not exists l.warn "Remote repo '#{remoteRepoUrl dep}' NOT exists - creating it" r.post('https://api.github.com/user/repos', { "name":"node2web_#{dep}"}, {auth: username:gitUser, password:PI:PASSWORD:<PASSWORD>END_PI} ).then -> l.ok "Remote repo '#{remoteRepoUrl dep}' created" if not localRepoExists qfs.makeTree(localRepo).then -> wLogExec(""" git init git remote add origin https://github.com/anodynos/node2web_#{dep} """, cwd: localRepo).then -> l.deb "Local repo '#{localRepo}' created." ).then( -> l.verbose "local & remote repos should both be in sync for '#{dep}'" git_tagList(dep).then (tags)-> if forceVersionTag or (version not in tags) l.verbose "'#{dep}' tag version '#{version}' not exists - Generating & saving '#{dep}.js'." descr = """ '#{dep}' nodejs core module browserify-ied with `--standalone #{dep }`. Should support all module systems (commonjs, AMD & `window.#{dep}`) - check browserify docs.""" header = """ #{descr} From [node2web](http://github.com/anodynos/node2web) collection, should/will be exposed as '#{dep}' to [bower](http://bower.io) for *browser* usage. browserify version: '#{version}', build date '#{new Date}' """ save = (file, content)-> l.verbose "Saving file '#{file = path.join(localRepo, file)}'" qfs.write file, content browserifyDep(dep).then (src)-> crap = '/mnt/tc/DevelopmentProjects/WebStormWorkspace/p/node2web/node_modules/browserify/node_modules/insert-module-globals/node_modules/process/browser.js' src = src.replace new RegExp(crap, 'g'), 'process_browser' pkgInfo = JSON.stringify { name: dep version: version main: "#{dep}.min.js" description: descr keywords: ['nodejs', 'browserify', dep] }, null, ' ' When.all([ save dep + '.js', "/** #{header} \n**/\n#{src}" save dep + '.min.js', """/** '#{dep}' nodejs module minified for AMD, CommonJS & `window.#{dep}`. browserify v#{version} **/ #{(UglifyJS2.minify src, {fromString: true}).code}""" save 'readme.md', header save 'bower.json', pkgInfo save 'package.json', pkgInfo ]).then -> git_commitTag dep, version else l.verbose "Local repo already has a version tag '#{version}' for '#{dep}' - not saving/commiting anything." ).then -> sequence [ git_push, bower_register ], dep sequence(getDepTask dep for dep in deps).catch (err)-> l.er err handleDeps (dep for dep in DEPS.nodeAll when (dep not in DEPS.notSupported) and (dep isnt 'http') )
[ { "context": "nit AJAX related extensions\n#\n# Copyright (C) 2011 Nikolay Nemshilov\n#\nForm.include\n remote: false # remotized form ", "end": 86, "score": 0.9998860359191895, "start": 69, "tag": "NAME", "value": "Nikolay Nemshilov" } ]
stl/ajax/src/form.coffee
lovely-io/lovely.io-stl
2
# # The DOM Form unit AJAX related extensions # # Copyright (C) 2011 Nikolay Nemshilov # Form.include remote: false # remotized form marker # # Sends the form via an ajax request # # @param {Object} ajax options # @return {Form} this # send: (options)-> options or= {} options.method = options.method || @_.method || 'post' options.spinner = options.spinner || @first('.spinner') options.params = @ @ajax = new Ajax(@_.action || global.document.location.href, options) @ajax.on 'complete', bind(@enable, @) @ajax.on 'cancel', bind(@enable, @) @ajax.send() setTimeout(bind(@disable, @), 1) # WebKit needs this delay with IFrame requests return @ # # Cancels an ongoing Ajax request initialized by the {#send} methdo # # @return {Form} this # cancelAjax: -> @ajax.cancel() if @ajax instanceof Ajax return @ # # Marks the form to be send via Ajax on submit # # @param {Object} ajax options # @return {Form} this # remotize: (options)-> unless @remote @on 'submit', Form_remote_send, options @remote = true return @ # # Cancels the effect of the {#remotize} mehtod # # @return {Form} this # unremotize: -> if @remote @no 'submit', Form_remote_send @remote = false return @ # # Converts the form values into a query string # # @return {String} a query string # serialize: -> Hash.toQueryString(@values()) # private Form_remote_send = (event, options)-> event.stop() @send(options)
134457
# # The DOM Form unit AJAX related extensions # # Copyright (C) 2011 <NAME> # Form.include remote: false # remotized form marker # # Sends the form via an ajax request # # @param {Object} ajax options # @return {Form} this # send: (options)-> options or= {} options.method = options.method || @_.method || 'post' options.spinner = options.spinner || @first('.spinner') options.params = @ @ajax = new Ajax(@_.action || global.document.location.href, options) @ajax.on 'complete', bind(@enable, @) @ajax.on 'cancel', bind(@enable, @) @ajax.send() setTimeout(bind(@disable, @), 1) # WebKit needs this delay with IFrame requests return @ # # Cancels an ongoing Ajax request initialized by the {#send} methdo # # @return {Form} this # cancelAjax: -> @ajax.cancel() if @ajax instanceof Ajax return @ # # Marks the form to be send via Ajax on submit # # @param {Object} ajax options # @return {Form} this # remotize: (options)-> unless @remote @on 'submit', Form_remote_send, options @remote = true return @ # # Cancels the effect of the {#remotize} mehtod # # @return {Form} this # unremotize: -> if @remote @no 'submit', Form_remote_send @remote = false return @ # # Converts the form values into a query string # # @return {String} a query string # serialize: -> Hash.toQueryString(@values()) # private Form_remote_send = (event, options)-> event.stop() @send(options)
true
# # The DOM Form unit AJAX related extensions # # Copyright (C) 2011 PI:NAME:<NAME>END_PI # Form.include remote: false # remotized form marker # # Sends the form via an ajax request # # @param {Object} ajax options # @return {Form} this # send: (options)-> options or= {} options.method = options.method || @_.method || 'post' options.spinner = options.spinner || @first('.spinner') options.params = @ @ajax = new Ajax(@_.action || global.document.location.href, options) @ajax.on 'complete', bind(@enable, @) @ajax.on 'cancel', bind(@enable, @) @ajax.send() setTimeout(bind(@disable, @), 1) # WebKit needs this delay with IFrame requests return @ # # Cancels an ongoing Ajax request initialized by the {#send} methdo # # @return {Form} this # cancelAjax: -> @ajax.cancel() if @ajax instanceof Ajax return @ # # Marks the form to be send via Ajax on submit # # @param {Object} ajax options # @return {Form} this # remotize: (options)-> unless @remote @on 'submit', Form_remote_send, options @remote = true return @ # # Cancels the effect of the {#remotize} mehtod # # @return {Form} this # unremotize: -> if @remote @no 'submit', Form_remote_send @remote = false return @ # # Converts the form values into a query string # # @return {String} a query string # serialize: -> Hash.toQueryString(@values()) # private Form_remote_send = (event, options)-> event.stop() @send(options)
[ { "context": "Link: @linkState('first_name'), placeholder: \"e.g. Artur\", className: \"form-control\"))\n (di", "end": 3381, "score": 0.9997705221176147, "start": 3376, "tag": "NAME", "value": "Artur" }, { "context": " (input type: \"text\", valueLink: @linkState('username'), placeholder: \"e.g. ArturKing\", className: \"for", "end": 4514, "score": 0.7419672012329102, "start": 4506, "tag": "USERNAME", "value": "username" }, { "context": "ueLink: @linkState('username'), placeholder: \"e.g. ArturKing\", className: \"form-control\"))\n\n (d", "end": 4546, "score": 0.9950328469276428, "start": 4537, "tag": "USERNAME", "value": "ArturKing" } ]
app/assets/javascripts/components/user_profile/header/form.js.coffee
olkeene/knomsy
0
{h3, input, button, div, span, h4, label, img, p, textarea} = React.DOM @UserProfile_Header_Form = React.createFactory React.createClass mixins: [React.addons.LinkedStateMixin, ReactFileinputMixin, AutocompleteMixin] propTypes: user: React.PropTypes.object.isRequired, saveProfile: React.PropTypes.func.isRequired, onClose: React.PropTypes.func.isRequired getInitialState: -> _.omit @props.user, 'about', 'what_do', 'role_list', 'skill_list', 'service_list' componentDidMount: (prevProps, prevState) -> @fileinput 'avatar' @fileinput 'cover' @react_autocomplete 'country_name', 'country_id', url: Routes.countries_data_path(format: 'json', query: 'QUERY') saveProfile: -> params = user: @state delete params.user.coverPreviewEncoded delete params.user.avatarPreviewEncoded # processData: false, # Don't process the files # contentType: false, # Set content type to false as jQuery will tell the server its a query string request resp = @props.saveProfile Object.toFormData(params), {processData: false, contentType: false} if resp.errors @setState errors: resp.errors else @props.onClose(resp) cancel: -> @props.onClose() _get_avatar: -> src = @state.avatarPreviewEncoded || @state.avatar_url if _.isBlank(src) (span className: 'upload_actions', (span style: {fontSize: 30}, className: "input__photo input__photo_circle fa fa-user") (input type: "file", ref: 'avatar', className: 'file-loading')) else (span className: 'upload_actions', (img className: "input__photo input__photo_square", src: src) (input type: "file", ref: 'avatar', className: 'file-loading') (button className: "btn_link btn btn-link", type: "button", onClick: @fileclear.bind(this, 'avatar'), 'Remove')) _get_cover: -> src = @state.coverPreviewEncoded || @state.cover_url if _.isBlank(src) (span className: 'upload_actions', (span style: {fontSize: 30}, className: "input__photo input__photo_circle fa fa-user") (input type: "file", ref: 'cover', className: 'file-loading')) else (span className: 'upload_actions', (img className: "input__photo input__photo_square", src: src) (input type: "file", ref: 'cover', className: 'file-loading') (button className: "btn_link btn btn-link", type: "button", onClick: @fileclear.bind(this, 'cover'), 'Remove')) render: -> errors = if @state.errors (div className: 'alert alert-danger', dangerouslySetInnerHTML: {__html: @state.errors.join('<br />')}) (div className: "profile-card__header_edit", (div className: "profile-card__column_border-bottom", (div className: "container-fluid", (errors) (div className: "col-xs-12 col-md-7 profile-card__column_border-right", (div className: "row", (div className: "col-xs-12 col-md-6", (div className: "form-group", (h4 className: "text-left", 'Photo') @_get_avatar() ) (div className: "form-group", (label className: "input__title", 'First Name'), (input type: "text", valueLink: @linkState('first_name'), placeholder: "e.g. Artur", className: "form-control")) (div className: "form-group", (label className: "input__title", 'Last Name') (input type: "text", valueLink: @linkState('last_name'), placeholder: "e.g. King", className: "form-control")) (div className: "form-group", (label className: "input__title", 'Country') (input type: "text", ref: 'country_name', defaultValue: @state.country_name, placeholder: "e.g. USA", className: "form-control")) (div className: "input", (label className: "input__title", 'Town') (input type: "text", valueLink: @linkState('city'), placeholder: "e.g. San-Francisco", className: "form-control"))) (div className: "col-xs-12 col-md-6", (div className: "form-group", (h4 className: "text-left", 'Cover') @_get_cover() ) (div className: "form-group", (label className: "input__title", 'User Name') (input type: "text", valueLink: @linkState('username'), placeholder: "e.g. ArturKing", className: "form-control")) (div className: "form-group", (label className: "input__title", 'Mini resume') (p style: {display: 'none'}, className: "textarea__subtext pull-right", '25 characters left') (textarea valueLink: @linkState('short_resume'), rows: 4, placeholder: "Your positions, projects and companies, e.g: Founder at Facebook", className: "input__textarea form-control" ))))) (div className: "col-xs-12 col-md-5", (h3 className: "input__main-title", 'Social Networks & Website') (div className: "row", (div className: "col-md-6", (div className: "input", (input type: "text", valueLink: @linkState('gplay_link'), placeholder: "Google Play link", className: "input__link input__link_play-market form-control")) (div className: "input", (input type: "text", valueLink: @linkState('itunes_link'), placeholder: "iTunes link", className: "input__link input__link_itunes form-control")) (div className: "input", (input type: "text", valueLink: @linkState('dribbble_link'), placeholder: "Dribbble link", className: "input__link input__link_dribbble form-control")) (div className: "input", (input type: "text", valueLink: @linkState('fb_link'), placeholder: "Facebook link", className: "input__link input__link_facebook form-control")) (div className: "input", (input type: "text", valueLink: @linkState('gh_link'), placeholder: "GitHub link", className: "input__link input__link_github form-control"))) (div className: "col-md-6", (div className: "input", (input type: "text", valueLink: @linkState('gplus_link'), placeholder: "Google+ link", className: "input__link input__link_google form-control")) (div className: "input", (input type: "text", valueLink: @linkState('linkedin_link'), placeholder: "LinkedIn link", className: "input__link input__link_linkedin form-control")) (div className: "input", (input type: "text", valueLink: @linkState('twitter_link'), placeholder: "Twitter link", className: "input__link input__link_twitter form-control")) (div className: "input", (input type: "text", valueLink: @linkState('youtube_link'), placeholder: "YouTube link", className: "input__link input__link_youtube form-control")) (div className: "input", (input type: "text", valueLink: @linkState('website'), placeholder: "Website link", className: "input__link input__link_website form-control"))))))) (div className: "edit-body__btn-group edit-body__btn-group_center", (button type: "button", className: "btn_save btn btn-success", onClick: @saveProfile, 'Save') (button type: "button", className: "btn_link btn btn-link", onClick: @cancel, 'Cancel')))
99130
{h3, input, button, div, span, h4, label, img, p, textarea} = React.DOM @UserProfile_Header_Form = React.createFactory React.createClass mixins: [React.addons.LinkedStateMixin, ReactFileinputMixin, AutocompleteMixin] propTypes: user: React.PropTypes.object.isRequired, saveProfile: React.PropTypes.func.isRequired, onClose: React.PropTypes.func.isRequired getInitialState: -> _.omit @props.user, 'about', 'what_do', 'role_list', 'skill_list', 'service_list' componentDidMount: (prevProps, prevState) -> @fileinput 'avatar' @fileinput 'cover' @react_autocomplete 'country_name', 'country_id', url: Routes.countries_data_path(format: 'json', query: 'QUERY') saveProfile: -> params = user: @state delete params.user.coverPreviewEncoded delete params.user.avatarPreviewEncoded # processData: false, # Don't process the files # contentType: false, # Set content type to false as jQuery will tell the server its a query string request resp = @props.saveProfile Object.toFormData(params), {processData: false, contentType: false} if resp.errors @setState errors: resp.errors else @props.onClose(resp) cancel: -> @props.onClose() _get_avatar: -> src = @state.avatarPreviewEncoded || @state.avatar_url if _.isBlank(src) (span className: 'upload_actions', (span style: {fontSize: 30}, className: "input__photo input__photo_circle fa fa-user") (input type: "file", ref: 'avatar', className: 'file-loading')) else (span className: 'upload_actions', (img className: "input__photo input__photo_square", src: src) (input type: "file", ref: 'avatar', className: 'file-loading') (button className: "btn_link btn btn-link", type: "button", onClick: @fileclear.bind(this, 'avatar'), 'Remove')) _get_cover: -> src = @state.coverPreviewEncoded || @state.cover_url if _.isBlank(src) (span className: 'upload_actions', (span style: {fontSize: 30}, className: "input__photo input__photo_circle fa fa-user") (input type: "file", ref: 'cover', className: 'file-loading')) else (span className: 'upload_actions', (img className: "input__photo input__photo_square", src: src) (input type: "file", ref: 'cover', className: 'file-loading') (button className: "btn_link btn btn-link", type: "button", onClick: @fileclear.bind(this, 'cover'), 'Remove')) render: -> errors = if @state.errors (div className: 'alert alert-danger', dangerouslySetInnerHTML: {__html: @state.errors.join('<br />')}) (div className: "profile-card__header_edit", (div className: "profile-card__column_border-bottom", (div className: "container-fluid", (errors) (div className: "col-xs-12 col-md-7 profile-card__column_border-right", (div className: "row", (div className: "col-xs-12 col-md-6", (div className: "form-group", (h4 className: "text-left", 'Photo') @_get_avatar() ) (div className: "form-group", (label className: "input__title", 'First Name'), (input type: "text", valueLink: @linkState('first_name'), placeholder: "e.g. <NAME>", className: "form-control")) (div className: "form-group", (label className: "input__title", 'Last Name') (input type: "text", valueLink: @linkState('last_name'), placeholder: "e.g. King", className: "form-control")) (div className: "form-group", (label className: "input__title", 'Country') (input type: "text", ref: 'country_name', defaultValue: @state.country_name, placeholder: "e.g. USA", className: "form-control")) (div className: "input", (label className: "input__title", 'Town') (input type: "text", valueLink: @linkState('city'), placeholder: "e.g. San-Francisco", className: "form-control"))) (div className: "col-xs-12 col-md-6", (div className: "form-group", (h4 className: "text-left", 'Cover') @_get_cover() ) (div className: "form-group", (label className: "input__title", 'User Name') (input type: "text", valueLink: @linkState('username'), placeholder: "e.g. ArturKing", className: "form-control")) (div className: "form-group", (label className: "input__title", 'Mini resume') (p style: {display: 'none'}, className: "textarea__subtext pull-right", '25 characters left') (textarea valueLink: @linkState('short_resume'), rows: 4, placeholder: "Your positions, projects and companies, e.g: Founder at Facebook", className: "input__textarea form-control" ))))) (div className: "col-xs-12 col-md-5", (h3 className: "input__main-title", 'Social Networks & Website') (div className: "row", (div className: "col-md-6", (div className: "input", (input type: "text", valueLink: @linkState('gplay_link'), placeholder: "Google Play link", className: "input__link input__link_play-market form-control")) (div className: "input", (input type: "text", valueLink: @linkState('itunes_link'), placeholder: "iTunes link", className: "input__link input__link_itunes form-control")) (div className: "input", (input type: "text", valueLink: @linkState('dribbble_link'), placeholder: "Dribbble link", className: "input__link input__link_dribbble form-control")) (div className: "input", (input type: "text", valueLink: @linkState('fb_link'), placeholder: "Facebook link", className: "input__link input__link_facebook form-control")) (div className: "input", (input type: "text", valueLink: @linkState('gh_link'), placeholder: "GitHub link", className: "input__link input__link_github form-control"))) (div className: "col-md-6", (div className: "input", (input type: "text", valueLink: @linkState('gplus_link'), placeholder: "Google+ link", className: "input__link input__link_google form-control")) (div className: "input", (input type: "text", valueLink: @linkState('linkedin_link'), placeholder: "LinkedIn link", className: "input__link input__link_linkedin form-control")) (div className: "input", (input type: "text", valueLink: @linkState('twitter_link'), placeholder: "Twitter link", className: "input__link input__link_twitter form-control")) (div className: "input", (input type: "text", valueLink: @linkState('youtube_link'), placeholder: "YouTube link", className: "input__link input__link_youtube form-control")) (div className: "input", (input type: "text", valueLink: @linkState('website'), placeholder: "Website link", className: "input__link input__link_website form-control"))))))) (div className: "edit-body__btn-group edit-body__btn-group_center", (button type: "button", className: "btn_save btn btn-success", onClick: @saveProfile, 'Save') (button type: "button", className: "btn_link btn btn-link", onClick: @cancel, 'Cancel')))
true
{h3, input, button, div, span, h4, label, img, p, textarea} = React.DOM @UserProfile_Header_Form = React.createFactory React.createClass mixins: [React.addons.LinkedStateMixin, ReactFileinputMixin, AutocompleteMixin] propTypes: user: React.PropTypes.object.isRequired, saveProfile: React.PropTypes.func.isRequired, onClose: React.PropTypes.func.isRequired getInitialState: -> _.omit @props.user, 'about', 'what_do', 'role_list', 'skill_list', 'service_list' componentDidMount: (prevProps, prevState) -> @fileinput 'avatar' @fileinput 'cover' @react_autocomplete 'country_name', 'country_id', url: Routes.countries_data_path(format: 'json', query: 'QUERY') saveProfile: -> params = user: @state delete params.user.coverPreviewEncoded delete params.user.avatarPreviewEncoded # processData: false, # Don't process the files # contentType: false, # Set content type to false as jQuery will tell the server its a query string request resp = @props.saveProfile Object.toFormData(params), {processData: false, contentType: false} if resp.errors @setState errors: resp.errors else @props.onClose(resp) cancel: -> @props.onClose() _get_avatar: -> src = @state.avatarPreviewEncoded || @state.avatar_url if _.isBlank(src) (span className: 'upload_actions', (span style: {fontSize: 30}, className: "input__photo input__photo_circle fa fa-user") (input type: "file", ref: 'avatar', className: 'file-loading')) else (span className: 'upload_actions', (img className: "input__photo input__photo_square", src: src) (input type: "file", ref: 'avatar', className: 'file-loading') (button className: "btn_link btn btn-link", type: "button", onClick: @fileclear.bind(this, 'avatar'), 'Remove')) _get_cover: -> src = @state.coverPreviewEncoded || @state.cover_url if _.isBlank(src) (span className: 'upload_actions', (span style: {fontSize: 30}, className: "input__photo input__photo_circle fa fa-user") (input type: "file", ref: 'cover', className: 'file-loading')) else (span className: 'upload_actions', (img className: "input__photo input__photo_square", src: src) (input type: "file", ref: 'cover', className: 'file-loading') (button className: "btn_link btn btn-link", type: "button", onClick: @fileclear.bind(this, 'cover'), 'Remove')) render: -> errors = if @state.errors (div className: 'alert alert-danger', dangerouslySetInnerHTML: {__html: @state.errors.join('<br />')}) (div className: "profile-card__header_edit", (div className: "profile-card__column_border-bottom", (div className: "container-fluid", (errors) (div className: "col-xs-12 col-md-7 profile-card__column_border-right", (div className: "row", (div className: "col-xs-12 col-md-6", (div className: "form-group", (h4 className: "text-left", 'Photo') @_get_avatar() ) (div className: "form-group", (label className: "input__title", 'First Name'), (input type: "text", valueLink: @linkState('first_name'), placeholder: "e.g. PI:NAME:<NAME>END_PI", className: "form-control")) (div className: "form-group", (label className: "input__title", 'Last Name') (input type: "text", valueLink: @linkState('last_name'), placeholder: "e.g. King", className: "form-control")) (div className: "form-group", (label className: "input__title", 'Country') (input type: "text", ref: 'country_name', defaultValue: @state.country_name, placeholder: "e.g. USA", className: "form-control")) (div className: "input", (label className: "input__title", 'Town') (input type: "text", valueLink: @linkState('city'), placeholder: "e.g. San-Francisco", className: "form-control"))) (div className: "col-xs-12 col-md-6", (div className: "form-group", (h4 className: "text-left", 'Cover') @_get_cover() ) (div className: "form-group", (label className: "input__title", 'User Name') (input type: "text", valueLink: @linkState('username'), placeholder: "e.g. ArturKing", className: "form-control")) (div className: "form-group", (label className: "input__title", 'Mini resume') (p style: {display: 'none'}, className: "textarea__subtext pull-right", '25 characters left') (textarea valueLink: @linkState('short_resume'), rows: 4, placeholder: "Your positions, projects and companies, e.g: Founder at Facebook", className: "input__textarea form-control" ))))) (div className: "col-xs-12 col-md-5", (h3 className: "input__main-title", 'Social Networks & Website') (div className: "row", (div className: "col-md-6", (div className: "input", (input type: "text", valueLink: @linkState('gplay_link'), placeholder: "Google Play link", className: "input__link input__link_play-market form-control")) (div className: "input", (input type: "text", valueLink: @linkState('itunes_link'), placeholder: "iTunes link", className: "input__link input__link_itunes form-control")) (div className: "input", (input type: "text", valueLink: @linkState('dribbble_link'), placeholder: "Dribbble link", className: "input__link input__link_dribbble form-control")) (div className: "input", (input type: "text", valueLink: @linkState('fb_link'), placeholder: "Facebook link", className: "input__link input__link_facebook form-control")) (div className: "input", (input type: "text", valueLink: @linkState('gh_link'), placeholder: "GitHub link", className: "input__link input__link_github form-control"))) (div className: "col-md-6", (div className: "input", (input type: "text", valueLink: @linkState('gplus_link'), placeholder: "Google+ link", className: "input__link input__link_google form-control")) (div className: "input", (input type: "text", valueLink: @linkState('linkedin_link'), placeholder: "LinkedIn link", className: "input__link input__link_linkedin form-control")) (div className: "input", (input type: "text", valueLink: @linkState('twitter_link'), placeholder: "Twitter link", className: "input__link input__link_twitter form-control")) (div className: "input", (input type: "text", valueLink: @linkState('youtube_link'), placeholder: "YouTube link", className: "input__link input__link_youtube form-control")) (div className: "input", (input type: "text", valueLink: @linkState('website'), placeholder: "Website link", className: "input__link input__link_website form-control"))))))) (div className: "edit-body__btn-group edit-body__btn-group_center", (button type: "button", className: "btn_save btn btn-success", onClick: @saveProfile, 'Save') (button type: "button", className: "btn_link btn btn-link", onClick: @cancel, 'Cancel')))
[ { "context": "y, 'dave', options).should.eql(getResult([{name: 'Dave', age: '12' }]))\n filterFuzzy(array, 'da", "end": 2433, "score": 0.9996128082275391, "start": 2429, "tag": "NAME", "value": "Dave" }, { "context": "ay, 'dav', options).should.eql(getResult([{name: 'Dave', age: '12' }]))\n filterFuzzy(array, 've", "end": 2530, "score": 0.9996427297592163, "start": 2526, "tag": "NAME", "value": "Dave" }, { "context": "ray, 've', options).should.eql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }, {name", "end": 2626, "score": 0.999660074710846, "start": 2622, "tag": "NAME", "value": "Dave" }, { "context": "ql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }, {name: 'Steve', age: '34' }]))\n ", "end": 2655, "score": 0.9995222091674805, "start": 2650, "tag": "NAME", "value": "Steve" }, { "context": "age: '12' }, {name: 'Steve', age: '12' }, {name: 'Steve', age: '34' }]))\n filterFuzzy(array, 'ao", "end": 2684, "score": 0.9996951222419739, "start": 2679, "tag": "NAME", "value": "Steve" }, { "context": "ray, 'ao', options).should.eql(getResult([{name: 'Alejandro', age: '90' }]))\n filterFuzzy(array, 'ae", "end": 2785, "score": 0.9997503757476807, "start": 2776, "tag": "NAME", "value": "Alejandro" }, { "context": "ray, 'ae', options).should.eql(getResult([{name: 'Alejandro', age: '90' }, {name: 'Dave', age: '12' }, {name:", "end": 2886, "score": 0.999769926071167, "start": 2877, "tag": "NAME", "value": "Alejandro" }, { "context": "tResult([{name: 'Alejandro', age: '90' }, {name: 'Dave', age: '12' }, {name: 'Kate', age: '56' }]))\n ", "end": 2914, "score": 0.9995250701904297, "start": 2910, "tag": "NAME", "value": "Dave" }, { "context": " age: '90' }, {name: 'Dave', age: '12' }, {name: 'Kate', age: '56' }]))\n filterFuzzy(array, '12", "end": 2942, "score": 0.9997541904449463, "start": 2938, "tag": "NAME", "value": "Kate" }, { "context": "ray, '12', options).should.eql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }]))\n ", "end": 3038, "score": 0.9995768070220947, "start": 3034, "tag": "NAME", "value": "Dave" }, { "context": "ql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }]))\n '.()-[]{}\\\\^|$?*+!'.sp", "end": 3067, "score": 0.9993426203727722, "start": 3062, "tag": "NAME", "value": "Steve" }, { "context": "ray, 've', options).should.eql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }, {name", "end": 3776, "score": 0.9994934797286987, "start": 3772, "tag": "NAME", "value": "Dave" }, { "context": "ql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }, {name: 'Steve', age: '34' }]))\n ", "end": 3805, "score": 0.999491810798645, "start": 3800, "tag": "NAME", "value": "Steve" }, { "context": "age: '12' }, {name: 'Steve', age: '12' }, {name: 'Steve', age: '34' }]))\n filterFuzzy(array, 'ao", "end": 3834, "score": 0.999671995639801, "start": 3829, "tag": "NAME", "value": "Steve" }, { "context": "ray, 'ao', options).should.eql(getResult([{name: 'Alejandro', age: '90' }]))\n filterFuzzy(array, 'ae", "end": 3935, "score": 0.9997550249099731, "start": 3926, "tag": "NAME", "value": "Alejandro" }, { "context": "ray, 'ae', options).should.eql(getResult([{name: 'Dave', age: '12' }, {name: 'Kate', age: '56' }]))\n ", "end": 4031, "score": 0.9996991753578186, "start": 4027, "tag": "NAME", "value": "Dave" }, { "context": "ql(getResult([{name: 'Dave', age: '12' }, {name: 'Kate', age: '56' }]))\n filterFuzzy(array, '12", "end": 4059, "score": 0.999717116355896, "start": 4055, "tag": "NAME", "value": "Kate" }, { "context": "ray, '12', options).should.eql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }]))\n\n ", "end": 4155, "score": 0.9996045827865601, "start": 4151, "tag": "NAME", "value": "Dave" }, { "context": "ql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }]))\n\n it 'when not sorting', ", "end": 4184, "score": 0.9996551275253296, "start": 4179, "tag": "NAME", "value": "Steve" }, { "context": "y, 'dave', options).should.eql(getResult([{name: 'Dave', age: '12' }]))\n filterFuzzy(array, 'da", "end": 4473, "score": 0.9993973970413208, "start": 4469, "tag": "NAME", "value": "Dave" }, { "context": "ay, 'dav', options).should.eql(getResult([{name: 'Dave', age: '12' }]))\n filterFuzzy(array, 've", "end": 4570, "score": 0.9992036819458008, "start": 4566, "tag": "NAME", "value": "Dave" }, { "context": "ray, 've', options).should.eql(getResult([{name: 'Steve', age: '34' }, {name: 'Dave', age: '12' }, {name:", "end": 4667, "score": 0.9993735551834106, "start": 4662, "tag": "NAME", "value": "Steve" }, { "context": "l(getResult([{name: 'Steve', age: '34' }, {name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }]))\n ", "end": 4695, "score": 0.9994778633117676, "start": 4691, "tag": "NAME", "value": "Dave" }, { "context": " age: '34' }, {name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }]))\n filterFuzzy(array, 'ao", "end": 4724, "score": 0.9993034601211548, "start": 4719, "tag": "NAME", "value": "Steve" }, { "context": "ray, 'ao', options).should.eql(getResult([{name: 'Alejandro', age: '90' }]))\n filterFuzzy(array, 'ae", "end": 4825, "score": 0.9997023344039917, "start": 4816, "tag": "NAME", "value": "Alejandro" }, { "context": "ray, 'ae', options).should.eql(getResult([{name: 'Kate', age: '56' }, {name: 'Dave', age: '12' }, {name:", "end": 4921, "score": 0.9997462034225464, "start": 4917, "tag": "NAME", "value": "Kate" }, { "context": "ql(getResult([{name: 'Kate', age: '56' }, {name: 'Dave', age: '12' }, {name: 'Alejandro', age: '90' }]))", "end": 4949, "score": 0.9996030330657959, "start": 4945, "tag": "NAME", "value": "Dave" }, { "context": " age: '56' }, {name: 'Dave', age: '12' }, {name: 'Alejandro', age: '90' }]))\n filterFuzzy(array, '12", "end": 4982, "score": 0.9997850060462952, "start": 4973, "tag": "NAME", "value": "Alejandro" }, { "context": "ray, '12', options).should.eql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }]))\n\n\n\n", "end": 5078, "score": 0.9996001720428467, "start": 5074, "tag": "NAME", "value": "Dave" }, { "context": "ql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }]))\n\n\n\n\n describe 'exact should", "end": 5107, "score": 0.9993374347686768, "start": 5102, "tag": "NAME", "value": "Steve" }, { "context": "y, 'dave', options).should.eql(getResult([{name: 'Dave', age: '12' }]))\n filterExact(array, 'da", "end": 5656, "score": 0.9994308948516846, "start": 5652, "tag": "NAME", "value": "Dave" }, { "context": "ray, '12', options).should.eql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }]))\n\n ", "end": 6094, "score": 0.9993983507156372, "start": 6090, "tag": "NAME", "value": "Dave" }, { "context": "ql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }]))\n\n it 'when using case sen", "end": 6123, "score": 0.999332070350647, "start": 6118, "tag": "NAME", "value": "Steve" }, { "context": "ray, '12', options).should.eql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }]))\n\n ", "end": 6822, "score": 0.9992823600769043, "start": 6818, "tag": "NAME", "value": "Dave" }, { "context": "ql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }]))\n\n it 'when not sorting', ", "end": 6851, "score": 0.9994384050369263, "start": 6846, "tag": "NAME", "value": "Steve" }, { "context": "y, 'dave', options).should.eql(getResult([{name: 'Dave', age: '12' }]))\n filterExact(array, 'da", "end": 7247, "score": 0.9992798566818237, "start": 7243, "tag": "NAME", "value": "Dave" }, { "context": "ray, '12', options).should.eql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }]))\n\n\n\n", "end": 7685, "score": 0.9994845390319824, "start": 7681, "tag": "NAME", "value": "Dave" }, { "context": "ql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }]))\n\n\n\n\n describe 'startsWith s", "end": 7714, "score": 0.9995429515838623, "start": 7709, "tag": "NAME", "value": "Steve" }, { "context": "y, 'dave', options).should.eql(getResult([{name: 'Dave', age: '12' }]))\n filterStartsWith(array", "end": 8171, "score": 0.9994490146636963, "start": 8167, "tag": "NAME", "value": "Dave" }, { "context": "ay, 'dav', options).should.eql(getResult([{name: 'Dave', age: '12' }]))\n filterStartsWith(array", "end": 8273, "score": 0.9995021224021912, "start": 8269, "tag": "NAME", "value": "Dave" }, { "context": "ray, '12', options).should.eql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }]))\n\n ", "end": 8676, "score": 0.9993646740913391, "start": 8672, "tag": "NAME", "value": "Dave" }, { "context": "ql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }]))\n\n it 'when using case sen", "end": 8705, "score": 0.9995049834251404, "start": 8700, "tag": "NAME", "value": "Steve" }, { "context": "ray, '12', options).should.eql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }]))\n\n ", "end": 9444, "score": 0.999566912651062, "start": 9440, "tag": "NAME", "value": "Dave" }, { "context": "ql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }]))\n\n it 'when not sorting', ", "end": 9473, "score": 0.9994727969169617, "start": 9468, "tag": "NAME", "value": "Steve" }, { "context": "y, 'dave', options).should.eql(getResult([{name: 'Dave', age: '12' }]))\n filterStartsWith(array", "end": 9772, "score": 0.999305009841919, "start": 9768, "tag": "NAME", "value": "Dave" }, { "context": "ay, 'dav', options).should.eql(getResult([{name: 'Dave', age: '12' }]))\n filterStartsWith(array", "end": 9874, "score": 0.9993590116500854, "start": 9870, "tag": "NAME", "value": "Dave" }, { "context": "ray, '12', options).should.eql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }]))\n\n\n\n", "end": 10277, "score": 0.9993273019790649, "start": 10273, "tag": "NAME", "value": "Dave" }, { "context": "ql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }]))\n\n\n\n\n describe 'contains sho", "end": 10306, "score": 0.9993974566459656, "start": 10301, "tag": "NAME", "value": "Steve" }, { "context": "y, 'dave', options).should.eql(getResult([{name: 'Dave', age: '12' }]))\n filterContains(array, ", "end": 10757, "score": 0.9990338087081909, "start": 10753, "tag": "NAME", "value": "Dave" }, { "context": "ay, 'dav', options).should.eql(getResult([{name: 'Dave', age: '12' }]))\n filterContains(array, ", "end": 10857, "score": 0.9991803169250488, "start": 10853, "tag": "NAME", "value": "Dave" }, { "context": "ray, 've', options).should.eql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }, {name", "end": 10956, "score": 0.9994155168533325, "start": 10952, "tag": "NAME", "value": "Dave" }, { "context": "ql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }, {name: 'Steve', age: '34' }]))\n ", "end": 10985, "score": 0.9991600513458252, "start": 10980, "tag": "NAME", "value": "Steve" }, { "context": "age: '12' }, {name: 'Steve', age: '12' }, {name: 'Steve', age: '34' }]))\n filterContains(array, ", "end": 11014, "score": 0.9994491338729858, "start": 11009, "tag": "NAME", "value": "Steve" }, { "context": "ray, '12', options).should.eql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }]))\n\n ", "end": 11237, "score": 0.9991021156311035, "start": 11233, "tag": "NAME", "value": "Dave" }, { "context": "ql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }]))\n\n it 'when using case sen", "end": 11266, "score": 0.9993922710418701, "start": 11261, "tag": "NAME", "value": "Steve" }, { "context": "ray, 've', options).should.eql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }, {name", "end": 11695, "score": 0.999679446220398, "start": 11691, "tag": "NAME", "value": "Dave" }, { "context": "ql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }, {name: 'Steve', age: '34' }]))\n ", "end": 11724, "score": 0.9997508525848389, "start": 11719, "tag": "NAME", "value": "Steve" }, { "context": "age: '12' }, {name: 'Steve', age: '12' }, {name: 'Steve', age: '34' }]))\n filterContains(array, ", "end": 11753, "score": 0.9997626543045044, "start": 11748, "tag": "NAME", "value": "Steve" }, { "context": "ray, '12', options).should.eql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }]))\n\n ", "end": 11976, "score": 0.999605655670166, "start": 11972, "tag": "NAME", "value": "Dave" }, { "context": "ql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }]))\n\n it 'when not sorting', ", "end": 12005, "score": 0.9997210502624512, "start": 12000, "tag": "NAME", "value": "Steve" }, { "context": "y, 'dave', options).should.eql(getResult([{name: 'Dave', age: '12' }]))\n filterContains(array, ", "end": 12300, "score": 0.9995759725570679, "start": 12296, "tag": "NAME", "value": "Dave" }, { "context": "ay, 'dav', options).should.eql(getResult([{name: 'Dave', age: '12' }]))\n filterContains(array, ", "end": 12400, "score": 0.999610185623169, "start": 12396, "tag": "NAME", "value": "Dave" }, { "context": "ray, 've', options).should.eql(getResult([{name: 'Steve', age: '34' }, {name: 'Dave', age: '12' }, {name:", "end": 12500, "score": 0.9996432065963745, "start": 12495, "tag": "NAME", "value": "Steve" }, { "context": "l(getResult([{name: 'Steve', age: '34' }, {name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }]))\n ", "end": 12528, "score": 0.9996764063835144, "start": 12524, "tag": "NAME", "value": "Dave" }, { "context": " age: '34' }, {name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }]))\n filterContains(array, ", "end": 12557, "score": 0.9996978640556335, "start": 12552, "tag": "NAME", "value": "Steve" }, { "context": "ray, '12', options).should.eql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }]))\n\n\n\n", "end": 12780, "score": 0.9996535778045654, "start": 12776, "tag": "NAME", "value": "Dave" }, { "context": "ql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }]))\n\n\n\n stringArray = [\n 'St", "end": 12809, "score": 0.9997057914733887, "start": 12804, "tag": "NAME", "value": "Steve" }, { "context": "ve', age: '12' }]))\n\n\n\n stringArray = [\n 'Steve 34'\n 'Kate 56'\n 'Dave 12'\n 'Steve 12'", "end": 12865, "score": 0.9905205965042114, "start": 12857, "tag": "NAME", "value": "Steve 34" }, { "context": "))\n\n\n\n stringArray = [\n 'Steve 34'\n 'Kate 56'\n 'Dave 12'\n 'Steve 12'\n 'Bob 78'\n", "end": 12881, "score": 0.9841569066047668, "start": 12874, "tag": "NAME", "value": "Kate 56" }, { "context": "Array = [\n 'Steve 34'\n 'Kate 56'\n 'Dave 12'\n 'Steve 12'\n 'Bob 78'\n 'Alejandro", "end": 12897, "score": 0.9875534176826477, "start": 12890, "tag": "NAME", "value": "Dave 12" }, { "context": "'Steve 34'\n 'Kate 56'\n 'Dave 12'\n 'Steve 12'\n 'Bob 78'\n 'Alejandro 90',\n '.()-", "end": 12914, "score": 0.9046419262886047, "start": 12906, "tag": "NAME", "value": "Steve 12" }, { "context": "'Kate 56'\n 'Dave 12'\n 'Steve 12'\n 'Bob 78'\n 'Alejandro 90',\n '.()-[]{}\\\\^|$?*+! 3", "end": 12929, "score": 0.9465940594673157, "start": 12923, "tag": "NAME", "value": "Bob 78" }, { "context": " 'Dave 12'\n 'Steve 12'\n 'Bob 78'\n 'Alejandro 90',\n '.()-[]{}\\\\^|$?*+! 32'\n ]\n objectAr", "end": 12950, "score": 0.9978839159011841, "start": 12938, "tag": "NAME", "value": "Alejandro 90" }, { "context": "\n ]\n objectArray = [\n {\n name: 'Steve'\n age: '34'\n },{\n name: 'Kate'", "end": 13036, "score": 0.9996734261512756, "start": 13031, "tag": "NAME", "value": "Steve" }, { "context": "Steve'\n age: '34'\n },{\n name: 'Kate'\n age: '56'\n },{\n name: 'Dave'", "end": 13085, "score": 0.9997568726539612, "start": 13081, "tag": "NAME", "value": "Kate" }, { "context": "'Kate'\n age: '56'\n },{\n name: 'Dave'\n age: '12'\n },{\n name: 'Steve", "end": 13134, "score": 0.9997397661209106, "start": 13130, "tag": "NAME", "value": "Dave" }, { "context": "'Dave'\n age: '12'\n },{\n name: 'Steve'\n age: '12'\n },{\n name: 'Bob'\n", "end": 13184, "score": 0.999700665473938, "start": 13179, "tag": "NAME", "value": "Steve" }, { "context": "Steve'\n age: '12'\n },{\n name: 'Bob'\n age: '78'\n },{\n name: 'Aleja", "end": 13232, "score": 0.9998458623886108, "start": 13229, "tag": "NAME", "value": "Bob" }, { "context": " 'Bob'\n age: '78'\n },{\n name: 'Alejandro'\n age: '90'\n }, {\n name: '.()-", "end": 13286, "score": 0.9998214244842529, "start": 13277, "tag": "NAME", "value": "Alejandro" }, { "context": "e: '32'\n }\n ]\n nestedArray = [\n ['Steve', '34']\n ['Kate', '56']\n ['Dave', '12']", "end": 13416, "score": 0.999781608581543, "start": 13411, "tag": "NAME", "value": "Steve" }, { "context": " nestedArray = [\n ['Steve', '34']\n ['Kate', '56']\n ['Dave', '12']\n ['Steve', '12'", "end": 13437, "score": 0.9998484253883362, "start": 13433, "tag": "NAME", "value": "Kate" }, { "context": " ['Steve', '34']\n ['Kate', '56']\n ['Dave', '12']\n ['Steve', '12']\n ['Bob', '78']", "end": 13458, "score": 0.9998345375061035, "start": 13454, "tag": "NAME", "value": "Dave" }, { "context": " ['Kate', '56']\n ['Dave', '12']\n ['Steve', '12']\n ['Bob', '78']\n ['Alejandro', '", "end": 13480, "score": 0.9998157024383545, "start": 13475, "tag": "NAME", "value": "Steve" }, { "context": " ['Dave', '12']\n ['Steve', '12']\n ['Bob', '78']\n ['Alejandro', '90']\n ['.()-[]{", "end": 13500, "score": 0.9998408555984497, "start": 13497, "tag": "NAME", "value": "Bob" }, { "context": "ave', '12']\n ['Steve', '12']\n ['Bob', '78']\n ['Alejandro', '90']\n ['.()-[]{}\\\\^|$", "end": 13506, "score": 0.7296869158744812, "start": 13505, "tag": "NAME", "value": "8" }, { "context": " ['Steve', '12']\n ['Bob', '78']\n ['Alejandro', '90']\n ['.()-[]{}\\\\^|$?*+!', '32']\n ]\n\n", "end": 13526, "score": 0.9997965097427368, "start": 13517, "tag": "NAME", "value": "Alejandro" } ]
src/utils/filter/spec.coffee
p-koscielniak/hexagonjs
61
import { filterExact, filterStartsWith, filterContains, filterExcludes, filterGreater, filterLess, filterFuzzy, filterRegex, filterStringTypes, filterNumberTypes, filterTypes, filter, } from 'utils/filter' export default () -> describe 'filter', -> describe 'regression', -> it 'exports the correct filter object', -> filter.exact.should.equal(filterExact) filter.startsWith.should.equal(filterStartsWith) filter.contains.should.equal(filterContains) filter.excludes.should.equal(filterExcludes) filter.greater.should.equal(filterGreater) filter.less.should.equal(filterLess) filter.fuzzy.should.equal(filterFuzzy) filter.regex.should.equal(filterRegex) filter.stringTypes.should.equal(filterStringTypes) filter.numberTypes.should.equal(filterNumberTypes) filter.types.should.equal(filterTypes) describe 'types', -> describe 'filterStringTypes', -> it 'returns the correct values', -> filterStringTypes().should.eql([ 'contains', 'exact' 'excludes', 'startsWith' 'regex', 'fuzzy', ]) describe 'filterNumberTypes', -> it 'returns the correct values', -> filterNumberTypes().should.eql([ 'exact', 'greater', 'less', ]) describe 'filterTypes', -> it 'returns the correct values', -> filterTypes().should.eql([ 'contains', 'exact' 'greater', 'less', 'excludes', 'startsWith' 'regex', 'fuzzy', ]) runSpecsForSource = (array, options, type) -> getResult = (terms) -> switch type when 'str' terms.map (d) -> d.name + ' ' + d.age when 'arr' terms.map (d) -> [d.name, d.age] when 'obj' terms describe 'fuzzy should return the right results', -> it 'when using default options', -> if type is 'str' options = undefined else options ?= {} options.caseSensitive = false options.sort = true filterFuzzy(array, 'pete', options).should.eql([]) filterFuzzy(array, 'dave', options).should.eql(getResult([{name: 'Dave', age: '12' }])) filterFuzzy(array, 'dav', options).should.eql(getResult([{name: 'Dave', age: '12' }])) filterFuzzy(array, 've', options).should.eql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }, {name: 'Steve', age: '34' }])) filterFuzzy(array, 'ao', options).should.eql(getResult([{name: 'Alejandro', age: '90' }])) filterFuzzy(array, 'ae', options).should.eql(getResult([{name: 'Alejandro', age: '90' }, {name: 'Dave', age: '12' }, {name: 'Kate', age: '56' }])) filterFuzzy(array, '12', options).should.eql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }])) '.()-[]{}\\^|$?*+!'.split().forEach (char) -> filterFuzzy(array, char, options).should.eql(getResult([{name: '.()-[]{}\\^|$?*+!', age: '32' }])) filterFuzzy(array, '.()-[]{}\\^|$?*+!', options).should.eql(getResult([{name: '.()-[]{}\\^|$?*+!', age: '32' }])) it 'when using case sensitivity', -> options ?= {} options.caseSensitive = true options.sort = true filterFuzzy(array, 'pete', options).should.eql([]) filterFuzzy(array, 'dave', options).should.eql([]) filterFuzzy(array, 'dav', options).should.eql([]) filterFuzzy(array, 've', options).should.eql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }, {name: 'Steve', age: '34' }])) filterFuzzy(array, 'ao', options).should.eql(getResult([{name: 'Alejandro', age: '90' }])) filterFuzzy(array, 'ae', options).should.eql(getResult([{name: 'Dave', age: '12' }, {name: 'Kate', age: '56' }])) filterFuzzy(array, '12', options).should.eql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }])) it 'when not sorting', -> options ?= {} options.caseSensitive = false options.sort = false filterFuzzy(array, 'pete', options).should.eql([]) filterFuzzy(array, 'dave', options).should.eql(getResult([{name: 'Dave', age: '12' }])) filterFuzzy(array, 'dav', options).should.eql(getResult([{name: 'Dave', age: '12' }])) filterFuzzy(array, 've', options).should.eql(getResult([{name: 'Steve', age: '34' }, {name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }])) filterFuzzy(array, 'ao', options).should.eql(getResult([{name: 'Alejandro', age: '90' }])) filterFuzzy(array, 'ae', options).should.eql(getResult([{name: 'Kate', age: '56' }, {name: 'Dave', age: '12' }, {name: 'Alejandro', age: '90' }])) filterFuzzy(array, '12', options).should.eql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }])) describe 'exact should return the right results', -> it 'when using default options', -> if type is 'str' options = undefined else options ?= {} options.caseSensitive = false options.sort = true filterExact(array, 'pete', options).should.eql([]) if type is 'str' filterExact(array, 'dave', options).should.eql([]) else filterExact(array, 'dave', options).should.eql(getResult([{name: 'Dave', age: '12' }])) filterExact(array, 'dav', options).should.eql([]) filterExact(array, 've', options).should.eql([]) filterExact(array, 'ao', options).should.eql([]) filterExact(array, 'ae', options).should.eql([]) if type is 'str' filterExact(array, '12', options).should.eql([]) else filterExact(array, '12', options).should.eql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }])) it 'when using case sensitivity', -> options ?= {} options.caseSensitive = true options.sort = true filterExact(array, 'pete', options).should.eql([]) filterExact(array, 'dave', options).should.eql([]) filterExact(array, 'dav', options).should.eql([]) filterExact(array, 've', options).should.eql([]) filterExact(array, 'ao', options).should.eql([]) filterExact(array, 'ae', options).should.eql([]) if type is 'str' filterExact(array, '12', options).should.eql([]) else filterExact(array, '12', options).should.eql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }])) it 'when not sorting', -> options ?= {} options.caseSensitive = false options.sort = false filterExact(array, 'pete', options).should.eql([]) if type is 'str' filterExact(array, 'dave', options).should.eql([]) else filterExact(array, 'dave', options).should.eql(getResult([{name: 'Dave', age: '12' }])) filterExact(array, 'dav', options).should.eql([]) filterExact(array, 've', options).should.eql([]) filterExact(array, 'ao', options).should.eql([]) filterExact(array, 'ae', options).should.eql([]) if type is 'str' filterExact(array, '12', options).should.eql([]) else filterExact(array, '12', options).should.eql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }])) describe 'startsWith should return the right results', -> it 'when using default options', -> if type is 'str' options = undefined else options ?= {} options.caseSensitive = false options.sort = true filterStartsWith(array, 'pete', options).should.eql([]) filterStartsWith(array, 'dave', options).should.eql(getResult([{name: 'Dave', age: '12' }])) filterStartsWith(array, 'dav', options).should.eql(getResult([{name: 'Dave', age: '12' }])) filterStartsWith(array, 've', options).should.eql([]) filterStartsWith(array, 'ao', options).should.eql([]) filterStartsWith(array, 'ae', options).should.eql([]) if type is 'str' filterStartsWith(array, '12', options).should.eql([]) else filterStartsWith(array, '12', options).should.eql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }])) it 'when using case sensitivity', -> options ?= {} options.caseSensitive = true options.sort = true filterStartsWith(array, 'pete', options).should.eql([]) filterStartsWith(array, 'dave', options).should.eql([]) filterStartsWith(array, 'dav', options).should.eql([]) filterStartsWith(array, 've', options).should.eql([]) filterStartsWith(array, 'ao', options).should.eql([]) filterStartsWith(array, 'ae', options).should.eql([]) if type is 'str' filterStartsWith(array, '12', options).should.eql([]) else filterStartsWith(array, '12', options).should.eql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }])) it 'when not sorting', -> options ?= {} options.caseSensitive = false options.sort = false filterStartsWith(array, 'pete', options).should.eql([]) filterStartsWith(array, 'dave', options).should.eql(getResult([{name: 'Dave', age: '12' }])) filterStartsWith(array, 'dav', options).should.eql(getResult([{name: 'Dave', age: '12' }])) filterStartsWith(array, 've', options).should.eql([]) filterStartsWith(array, 'ao', options).should.eql([]) filterStartsWith(array, 'ae', options).should.eql([]) if type is 'str' filterStartsWith(array, '12', options).should.eql([]) else filterStartsWith(array, '12', options).should.eql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }])) describe 'contains should return the right results', -> it 'when using default options', -> if type is 'str' options = undefined else options ?= {} options.caseSensitive = false options.sort = true filterContains(array, 'pete', options).should.eql([]) filterContains(array, 'dave', options).should.eql(getResult([{name: 'Dave', age: '12' }])) filterContains(array, 'dav', options).should.eql(getResult([{name: 'Dave', age: '12' }])) filterContains(array, 've', options).should.eql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }, {name: 'Steve', age: '34' }])) filterContains(array, 'ao', options).should.eql([]) filterContains(array, 'ae', options).should.eql([]) filterContains(array, '12', options).should.eql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }])) it 'when using case sensitivity', -> options ?= {} options.caseSensitive = true options.sort = true filterContains(array, 'pete', options).should.eql([]) filterContains(array, 'dave', options).should.eql([]) filterContains(array, 'dav', options).should.eql([]) filterContains(array, 've', options).should.eql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }, {name: 'Steve', age: '34' }])) filterContains(array, 'ao', options).should.eql([]) filterContains(array, 'ae', options).should.eql([]) filterContains(array, '12', options).should.eql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }])) it 'when not sorting', -> options ?= {} options.caseSensitive = false options.sort = false filterContains(array, 'pete', options).should.eql([]) filterContains(array, 'dave', options).should.eql(getResult([{name: 'Dave', age: '12' }])) filterContains(array, 'dav', options).should.eql(getResult([{name: 'Dave', age: '12' }])) filterContains(array, 've', options).should.eql(getResult([{name: 'Steve', age: '34' }, {name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }])) filterContains(array, 'ao', options).should.eql([]) filterContains(array, 'ae', options).should.eql([]) filterContains(array, '12', options).should.eql(getResult([{name: 'Dave', age: '12' }, {name: 'Steve', age: '12' }])) stringArray = [ 'Steve 34' 'Kate 56' 'Dave 12' 'Steve 12' 'Bob 78' 'Alejandro 90', '.()-[]{}\\^|$?*+! 32' ] objectArray = [ { name: 'Steve' age: '34' },{ name: 'Kate' age: '56' },{ name: 'Dave' age: '12' },{ name: 'Steve' age: '12' },{ name: 'Bob' age: '78' },{ name: 'Alejandro' age: '90' }, { name: '.()-[]{}\\^|$?*+!' age: '32' } ] nestedArray = [ ['Steve', '34'] ['Kate', '56'] ['Dave', '12'] ['Steve', '12'] ['Bob', '78'] ['Alejandro', '90'] ['.()-[]{}\\^|$?*+!', '32'] ] describe 'a string based array using hx.filter', -> runSpecsForSource(stringArray, {}, 'str') describe 'an object based array using hx.filter', -> runSpecsForSource(objectArray, {searchValues: ((d) -> [d.name, d.age])}, 'obj') describe 'a nested array using hx.filter', -> runSpecsForSource(nestedArray, {searchValues: ((d) -> d)}, 'arr')
75234
import { filterExact, filterStartsWith, filterContains, filterExcludes, filterGreater, filterLess, filterFuzzy, filterRegex, filterStringTypes, filterNumberTypes, filterTypes, filter, } from 'utils/filter' export default () -> describe 'filter', -> describe 'regression', -> it 'exports the correct filter object', -> filter.exact.should.equal(filterExact) filter.startsWith.should.equal(filterStartsWith) filter.contains.should.equal(filterContains) filter.excludes.should.equal(filterExcludes) filter.greater.should.equal(filterGreater) filter.less.should.equal(filterLess) filter.fuzzy.should.equal(filterFuzzy) filter.regex.should.equal(filterRegex) filter.stringTypes.should.equal(filterStringTypes) filter.numberTypes.should.equal(filterNumberTypes) filter.types.should.equal(filterTypes) describe 'types', -> describe 'filterStringTypes', -> it 'returns the correct values', -> filterStringTypes().should.eql([ 'contains', 'exact' 'excludes', 'startsWith' 'regex', 'fuzzy', ]) describe 'filterNumberTypes', -> it 'returns the correct values', -> filterNumberTypes().should.eql([ 'exact', 'greater', 'less', ]) describe 'filterTypes', -> it 'returns the correct values', -> filterTypes().should.eql([ 'contains', 'exact' 'greater', 'less', 'excludes', 'startsWith' 'regex', 'fuzzy', ]) runSpecsForSource = (array, options, type) -> getResult = (terms) -> switch type when 'str' terms.map (d) -> d.name + ' ' + d.age when 'arr' terms.map (d) -> [d.name, d.age] when 'obj' terms describe 'fuzzy should return the right results', -> it 'when using default options', -> if type is 'str' options = undefined else options ?= {} options.caseSensitive = false options.sort = true filterFuzzy(array, 'pete', options).should.eql([]) filterFuzzy(array, 'dave', options).should.eql(getResult([{name: '<NAME>', age: '12' }])) filterFuzzy(array, 'dav', options).should.eql(getResult([{name: '<NAME>', age: '12' }])) filterFuzzy(array, 've', options).should.eql(getResult([{name: '<NAME>', age: '12' }, {name: '<NAME>', age: '12' }, {name: '<NAME>', age: '34' }])) filterFuzzy(array, 'ao', options).should.eql(getResult([{name: '<NAME>', age: '90' }])) filterFuzzy(array, 'ae', options).should.eql(getResult([{name: '<NAME>', age: '90' }, {name: '<NAME>', age: '12' }, {name: '<NAME>', age: '56' }])) filterFuzzy(array, '12', options).should.eql(getResult([{name: '<NAME>', age: '12' }, {name: '<NAME>', age: '12' }])) '.()-[]{}\\^|$?*+!'.split().forEach (char) -> filterFuzzy(array, char, options).should.eql(getResult([{name: '.()-[]{}\\^|$?*+!', age: '32' }])) filterFuzzy(array, '.()-[]{}\\^|$?*+!', options).should.eql(getResult([{name: '.()-[]{}\\^|$?*+!', age: '32' }])) it 'when using case sensitivity', -> options ?= {} options.caseSensitive = true options.sort = true filterFuzzy(array, 'pete', options).should.eql([]) filterFuzzy(array, 'dave', options).should.eql([]) filterFuzzy(array, 'dav', options).should.eql([]) filterFuzzy(array, 've', options).should.eql(getResult([{name: '<NAME>', age: '12' }, {name: '<NAME>', age: '12' }, {name: '<NAME>', age: '34' }])) filterFuzzy(array, 'ao', options).should.eql(getResult([{name: '<NAME>', age: '90' }])) filterFuzzy(array, 'ae', options).should.eql(getResult([{name: '<NAME>', age: '12' }, {name: '<NAME>', age: '56' }])) filterFuzzy(array, '12', options).should.eql(getResult([{name: '<NAME>', age: '12' }, {name: '<NAME>', age: '12' }])) it 'when not sorting', -> options ?= {} options.caseSensitive = false options.sort = false filterFuzzy(array, 'pete', options).should.eql([]) filterFuzzy(array, 'dave', options).should.eql(getResult([{name: '<NAME>', age: '12' }])) filterFuzzy(array, 'dav', options).should.eql(getResult([{name: '<NAME>', age: '12' }])) filterFuzzy(array, 've', options).should.eql(getResult([{name: '<NAME>', age: '34' }, {name: '<NAME>', age: '12' }, {name: '<NAME>', age: '12' }])) filterFuzzy(array, 'ao', options).should.eql(getResult([{name: '<NAME>', age: '90' }])) filterFuzzy(array, 'ae', options).should.eql(getResult([{name: '<NAME>', age: '56' }, {name: '<NAME>', age: '12' }, {name: '<NAME>', age: '90' }])) filterFuzzy(array, '12', options).should.eql(getResult([{name: '<NAME>', age: '12' }, {name: '<NAME>', age: '12' }])) describe 'exact should return the right results', -> it 'when using default options', -> if type is 'str' options = undefined else options ?= {} options.caseSensitive = false options.sort = true filterExact(array, 'pete', options).should.eql([]) if type is 'str' filterExact(array, 'dave', options).should.eql([]) else filterExact(array, 'dave', options).should.eql(getResult([{name: '<NAME>', age: '12' }])) filterExact(array, 'dav', options).should.eql([]) filterExact(array, 've', options).should.eql([]) filterExact(array, 'ao', options).should.eql([]) filterExact(array, 'ae', options).should.eql([]) if type is 'str' filterExact(array, '12', options).should.eql([]) else filterExact(array, '12', options).should.eql(getResult([{name: '<NAME>', age: '12' }, {name: '<NAME>', age: '12' }])) it 'when using case sensitivity', -> options ?= {} options.caseSensitive = true options.sort = true filterExact(array, 'pete', options).should.eql([]) filterExact(array, 'dave', options).should.eql([]) filterExact(array, 'dav', options).should.eql([]) filterExact(array, 've', options).should.eql([]) filterExact(array, 'ao', options).should.eql([]) filterExact(array, 'ae', options).should.eql([]) if type is 'str' filterExact(array, '12', options).should.eql([]) else filterExact(array, '12', options).should.eql(getResult([{name: '<NAME>', age: '12' }, {name: '<NAME>', age: '12' }])) it 'when not sorting', -> options ?= {} options.caseSensitive = false options.sort = false filterExact(array, 'pete', options).should.eql([]) if type is 'str' filterExact(array, 'dave', options).should.eql([]) else filterExact(array, 'dave', options).should.eql(getResult([{name: '<NAME>', age: '12' }])) filterExact(array, 'dav', options).should.eql([]) filterExact(array, 've', options).should.eql([]) filterExact(array, 'ao', options).should.eql([]) filterExact(array, 'ae', options).should.eql([]) if type is 'str' filterExact(array, '12', options).should.eql([]) else filterExact(array, '12', options).should.eql(getResult([{name: '<NAME>', age: '12' }, {name: '<NAME>', age: '12' }])) describe 'startsWith should return the right results', -> it 'when using default options', -> if type is 'str' options = undefined else options ?= {} options.caseSensitive = false options.sort = true filterStartsWith(array, 'pete', options).should.eql([]) filterStartsWith(array, 'dave', options).should.eql(getResult([{name: '<NAME>', age: '12' }])) filterStartsWith(array, 'dav', options).should.eql(getResult([{name: '<NAME>', age: '12' }])) filterStartsWith(array, 've', options).should.eql([]) filterStartsWith(array, 'ao', options).should.eql([]) filterStartsWith(array, 'ae', options).should.eql([]) if type is 'str' filterStartsWith(array, '12', options).should.eql([]) else filterStartsWith(array, '12', options).should.eql(getResult([{name: '<NAME>', age: '12' }, {name: '<NAME>', age: '12' }])) it 'when using case sensitivity', -> options ?= {} options.caseSensitive = true options.sort = true filterStartsWith(array, 'pete', options).should.eql([]) filterStartsWith(array, 'dave', options).should.eql([]) filterStartsWith(array, 'dav', options).should.eql([]) filterStartsWith(array, 've', options).should.eql([]) filterStartsWith(array, 'ao', options).should.eql([]) filterStartsWith(array, 'ae', options).should.eql([]) if type is 'str' filterStartsWith(array, '12', options).should.eql([]) else filterStartsWith(array, '12', options).should.eql(getResult([{name: '<NAME>', age: '12' }, {name: '<NAME>', age: '12' }])) it 'when not sorting', -> options ?= {} options.caseSensitive = false options.sort = false filterStartsWith(array, 'pete', options).should.eql([]) filterStartsWith(array, 'dave', options).should.eql(getResult([{name: '<NAME>', age: '12' }])) filterStartsWith(array, 'dav', options).should.eql(getResult([{name: '<NAME>', age: '12' }])) filterStartsWith(array, 've', options).should.eql([]) filterStartsWith(array, 'ao', options).should.eql([]) filterStartsWith(array, 'ae', options).should.eql([]) if type is 'str' filterStartsWith(array, '12', options).should.eql([]) else filterStartsWith(array, '12', options).should.eql(getResult([{name: '<NAME>', age: '12' }, {name: '<NAME>', age: '12' }])) describe 'contains should return the right results', -> it 'when using default options', -> if type is 'str' options = undefined else options ?= {} options.caseSensitive = false options.sort = true filterContains(array, 'pete', options).should.eql([]) filterContains(array, 'dave', options).should.eql(getResult([{name: '<NAME>', age: '12' }])) filterContains(array, 'dav', options).should.eql(getResult([{name: '<NAME>', age: '12' }])) filterContains(array, 've', options).should.eql(getResult([{name: '<NAME>', age: '12' }, {name: '<NAME>', age: '12' }, {name: '<NAME>', age: '34' }])) filterContains(array, 'ao', options).should.eql([]) filterContains(array, 'ae', options).should.eql([]) filterContains(array, '12', options).should.eql(getResult([{name: '<NAME>', age: '12' }, {name: '<NAME>', age: '12' }])) it 'when using case sensitivity', -> options ?= {} options.caseSensitive = true options.sort = true filterContains(array, 'pete', options).should.eql([]) filterContains(array, 'dave', options).should.eql([]) filterContains(array, 'dav', options).should.eql([]) filterContains(array, 've', options).should.eql(getResult([{name: '<NAME>', age: '12' }, {name: '<NAME>', age: '12' }, {name: '<NAME>', age: '34' }])) filterContains(array, 'ao', options).should.eql([]) filterContains(array, 'ae', options).should.eql([]) filterContains(array, '12', options).should.eql(getResult([{name: '<NAME>', age: '12' }, {name: '<NAME>', age: '12' }])) it 'when not sorting', -> options ?= {} options.caseSensitive = false options.sort = false filterContains(array, 'pete', options).should.eql([]) filterContains(array, 'dave', options).should.eql(getResult([{name: '<NAME>', age: '12' }])) filterContains(array, 'dav', options).should.eql(getResult([{name: '<NAME>', age: '12' }])) filterContains(array, 've', options).should.eql(getResult([{name: '<NAME>', age: '34' }, {name: '<NAME>', age: '12' }, {name: '<NAME>', age: '12' }])) filterContains(array, 'ao', options).should.eql([]) filterContains(array, 'ae', options).should.eql([]) filterContains(array, '12', options).should.eql(getResult([{name: '<NAME>', age: '12' }, {name: '<NAME>', age: '12' }])) stringArray = [ '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>' '<NAME>', '.()-[]{}\\^|$?*+! 32' ] objectArray = [ { name: '<NAME>' age: '34' },{ name: '<NAME>' age: '56' },{ name: '<NAME>' age: '12' },{ name: '<NAME>' age: '12' },{ name: '<NAME>' age: '78' },{ name: '<NAME>' age: '90' }, { name: '.()-[]{}\\^|$?*+!' age: '32' } ] nestedArray = [ ['<NAME>', '34'] ['<NAME>', '56'] ['<NAME>', '12'] ['<NAME>', '12'] ['<NAME>', '7<NAME>'] ['<NAME>', '90'] ['.()-[]{}\\^|$?*+!', '32'] ] describe 'a string based array using hx.filter', -> runSpecsForSource(stringArray, {}, 'str') describe 'an object based array using hx.filter', -> runSpecsForSource(objectArray, {searchValues: ((d) -> [d.name, d.age])}, 'obj') describe 'a nested array using hx.filter', -> runSpecsForSource(nestedArray, {searchValues: ((d) -> d)}, 'arr')
true
import { filterExact, filterStartsWith, filterContains, filterExcludes, filterGreater, filterLess, filterFuzzy, filterRegex, filterStringTypes, filterNumberTypes, filterTypes, filter, } from 'utils/filter' export default () -> describe 'filter', -> describe 'regression', -> it 'exports the correct filter object', -> filter.exact.should.equal(filterExact) filter.startsWith.should.equal(filterStartsWith) filter.contains.should.equal(filterContains) filter.excludes.should.equal(filterExcludes) filter.greater.should.equal(filterGreater) filter.less.should.equal(filterLess) filter.fuzzy.should.equal(filterFuzzy) filter.regex.should.equal(filterRegex) filter.stringTypes.should.equal(filterStringTypes) filter.numberTypes.should.equal(filterNumberTypes) filter.types.should.equal(filterTypes) describe 'types', -> describe 'filterStringTypes', -> it 'returns the correct values', -> filterStringTypes().should.eql([ 'contains', 'exact' 'excludes', 'startsWith' 'regex', 'fuzzy', ]) describe 'filterNumberTypes', -> it 'returns the correct values', -> filterNumberTypes().should.eql([ 'exact', 'greater', 'less', ]) describe 'filterTypes', -> it 'returns the correct values', -> filterTypes().should.eql([ 'contains', 'exact' 'greater', 'less', 'excludes', 'startsWith' 'regex', 'fuzzy', ]) runSpecsForSource = (array, options, type) -> getResult = (terms) -> switch type when 'str' terms.map (d) -> d.name + ' ' + d.age when 'arr' terms.map (d) -> [d.name, d.age] when 'obj' terms describe 'fuzzy should return the right results', -> it 'when using default options', -> if type is 'str' options = undefined else options ?= {} options.caseSensitive = false options.sort = true filterFuzzy(array, 'pete', options).should.eql([]) filterFuzzy(array, 'dave', options).should.eql(getResult([{name: 'PI:NAME:<NAME>END_PI', age: '12' }])) filterFuzzy(array, 'dav', options).should.eql(getResult([{name: 'PI:NAME:<NAME>END_PI', age: '12' }])) filterFuzzy(array, 've', options).should.eql(getResult([{name: 'PI:NAME:<NAME>END_PI', age: '12' }, {name: 'PI:NAME:<NAME>END_PI', age: '12' }, {name: 'PI:NAME:<NAME>END_PI', age: '34' }])) filterFuzzy(array, 'ao', options).should.eql(getResult([{name: 'PI:NAME:<NAME>END_PI', age: '90' }])) filterFuzzy(array, 'ae', options).should.eql(getResult([{name: 'PI:NAME:<NAME>END_PI', age: '90' }, {name: 'PI:NAME:<NAME>END_PI', age: '12' }, {name: 'PI:NAME:<NAME>END_PI', age: '56' }])) filterFuzzy(array, '12', options).should.eql(getResult([{name: 'PI:NAME:<NAME>END_PI', age: '12' }, {name: 'PI:NAME:<NAME>END_PI', age: '12' }])) '.()-[]{}\\^|$?*+!'.split().forEach (char) -> filterFuzzy(array, char, options).should.eql(getResult([{name: '.()-[]{}\\^|$?*+!', age: '32' }])) filterFuzzy(array, '.()-[]{}\\^|$?*+!', options).should.eql(getResult([{name: '.()-[]{}\\^|$?*+!', age: '32' }])) it 'when using case sensitivity', -> options ?= {} options.caseSensitive = true options.sort = true filterFuzzy(array, 'pete', options).should.eql([]) filterFuzzy(array, 'dave', options).should.eql([]) filterFuzzy(array, 'dav', options).should.eql([]) filterFuzzy(array, 've', options).should.eql(getResult([{name: 'PI:NAME:<NAME>END_PI', age: '12' }, {name: 'PI:NAME:<NAME>END_PI', age: '12' }, {name: 'PI:NAME:<NAME>END_PI', age: '34' }])) filterFuzzy(array, 'ao', options).should.eql(getResult([{name: 'PI:NAME:<NAME>END_PI', age: '90' }])) filterFuzzy(array, 'ae', options).should.eql(getResult([{name: 'PI:NAME:<NAME>END_PI', age: '12' }, {name: 'PI:NAME:<NAME>END_PI', age: '56' }])) filterFuzzy(array, '12', options).should.eql(getResult([{name: 'PI:NAME:<NAME>END_PI', age: '12' }, {name: 'PI:NAME:<NAME>END_PI', age: '12' }])) it 'when not sorting', -> options ?= {} options.caseSensitive = false options.sort = false filterFuzzy(array, 'pete', options).should.eql([]) filterFuzzy(array, 'dave', options).should.eql(getResult([{name: 'PI:NAME:<NAME>END_PI', age: '12' }])) filterFuzzy(array, 'dav', options).should.eql(getResult([{name: 'PI:NAME:<NAME>END_PI', age: '12' }])) filterFuzzy(array, 've', options).should.eql(getResult([{name: 'PI:NAME:<NAME>END_PI', age: '34' }, {name: 'PI:NAME:<NAME>END_PI', age: '12' }, {name: 'PI:NAME:<NAME>END_PI', age: '12' }])) filterFuzzy(array, 'ao', options).should.eql(getResult([{name: 'PI:NAME:<NAME>END_PI', age: '90' }])) filterFuzzy(array, 'ae', options).should.eql(getResult([{name: 'PI:NAME:<NAME>END_PI', age: '56' }, {name: 'PI:NAME:<NAME>END_PI', age: '12' }, {name: 'PI:NAME:<NAME>END_PI', age: '90' }])) filterFuzzy(array, '12', options).should.eql(getResult([{name: 'PI:NAME:<NAME>END_PI', age: '12' }, {name: 'PI:NAME:<NAME>END_PI', age: '12' }])) describe 'exact should return the right results', -> it 'when using default options', -> if type is 'str' options = undefined else options ?= {} options.caseSensitive = false options.sort = true filterExact(array, 'pete', options).should.eql([]) if type is 'str' filterExact(array, 'dave', options).should.eql([]) else filterExact(array, 'dave', options).should.eql(getResult([{name: 'PI:NAME:<NAME>END_PI', age: '12' }])) filterExact(array, 'dav', options).should.eql([]) filterExact(array, 've', options).should.eql([]) filterExact(array, 'ao', options).should.eql([]) filterExact(array, 'ae', options).should.eql([]) if type is 'str' filterExact(array, '12', options).should.eql([]) else filterExact(array, '12', options).should.eql(getResult([{name: 'PI:NAME:<NAME>END_PI', age: '12' }, {name: 'PI:NAME:<NAME>END_PI', age: '12' }])) it 'when using case sensitivity', -> options ?= {} options.caseSensitive = true options.sort = true filterExact(array, 'pete', options).should.eql([]) filterExact(array, 'dave', options).should.eql([]) filterExact(array, 'dav', options).should.eql([]) filterExact(array, 've', options).should.eql([]) filterExact(array, 'ao', options).should.eql([]) filterExact(array, 'ae', options).should.eql([]) if type is 'str' filterExact(array, '12', options).should.eql([]) else filterExact(array, '12', options).should.eql(getResult([{name: 'PI:NAME:<NAME>END_PI', age: '12' }, {name: 'PI:NAME:<NAME>END_PI', age: '12' }])) it 'when not sorting', -> options ?= {} options.caseSensitive = false options.sort = false filterExact(array, 'pete', options).should.eql([]) if type is 'str' filterExact(array, 'dave', options).should.eql([]) else filterExact(array, 'dave', options).should.eql(getResult([{name: 'PI:NAME:<NAME>END_PI', age: '12' }])) filterExact(array, 'dav', options).should.eql([]) filterExact(array, 've', options).should.eql([]) filterExact(array, 'ao', options).should.eql([]) filterExact(array, 'ae', options).should.eql([]) if type is 'str' filterExact(array, '12', options).should.eql([]) else filterExact(array, '12', options).should.eql(getResult([{name: 'PI:NAME:<NAME>END_PI', age: '12' }, {name: 'PI:NAME:<NAME>END_PI', age: '12' }])) describe 'startsWith should return the right results', -> it 'when using default options', -> if type is 'str' options = undefined else options ?= {} options.caseSensitive = false options.sort = true filterStartsWith(array, 'pete', options).should.eql([]) filterStartsWith(array, 'dave', options).should.eql(getResult([{name: 'PI:NAME:<NAME>END_PI', age: '12' }])) filterStartsWith(array, 'dav', options).should.eql(getResult([{name: 'PI:NAME:<NAME>END_PI', age: '12' }])) filterStartsWith(array, 've', options).should.eql([]) filterStartsWith(array, 'ao', options).should.eql([]) filterStartsWith(array, 'ae', options).should.eql([]) if type is 'str' filterStartsWith(array, '12', options).should.eql([]) else filterStartsWith(array, '12', options).should.eql(getResult([{name: 'PI:NAME:<NAME>END_PI', age: '12' }, {name: 'PI:NAME:<NAME>END_PI', age: '12' }])) it 'when using case sensitivity', -> options ?= {} options.caseSensitive = true options.sort = true filterStartsWith(array, 'pete', options).should.eql([]) filterStartsWith(array, 'dave', options).should.eql([]) filterStartsWith(array, 'dav', options).should.eql([]) filterStartsWith(array, 've', options).should.eql([]) filterStartsWith(array, 'ao', options).should.eql([]) filterStartsWith(array, 'ae', options).should.eql([]) if type is 'str' filterStartsWith(array, '12', options).should.eql([]) else filterStartsWith(array, '12', options).should.eql(getResult([{name: 'PI:NAME:<NAME>END_PI', age: '12' }, {name: 'PI:NAME:<NAME>END_PI', age: '12' }])) it 'when not sorting', -> options ?= {} options.caseSensitive = false options.sort = false filterStartsWith(array, 'pete', options).should.eql([]) filterStartsWith(array, 'dave', options).should.eql(getResult([{name: 'PI:NAME:<NAME>END_PI', age: '12' }])) filterStartsWith(array, 'dav', options).should.eql(getResult([{name: 'PI:NAME:<NAME>END_PI', age: '12' }])) filterStartsWith(array, 've', options).should.eql([]) filterStartsWith(array, 'ao', options).should.eql([]) filterStartsWith(array, 'ae', options).should.eql([]) if type is 'str' filterStartsWith(array, '12', options).should.eql([]) else filterStartsWith(array, '12', options).should.eql(getResult([{name: 'PI:NAME:<NAME>END_PI', age: '12' }, {name: 'PI:NAME:<NAME>END_PI', age: '12' }])) describe 'contains should return the right results', -> it 'when using default options', -> if type is 'str' options = undefined else options ?= {} options.caseSensitive = false options.sort = true filterContains(array, 'pete', options).should.eql([]) filterContains(array, 'dave', options).should.eql(getResult([{name: 'PI:NAME:<NAME>END_PI', age: '12' }])) filterContains(array, 'dav', options).should.eql(getResult([{name: 'PI:NAME:<NAME>END_PI', age: '12' }])) filterContains(array, 've', options).should.eql(getResult([{name: 'PI:NAME:<NAME>END_PI', age: '12' }, {name: 'PI:NAME:<NAME>END_PI', age: '12' }, {name: 'PI:NAME:<NAME>END_PI', age: '34' }])) filterContains(array, 'ao', options).should.eql([]) filterContains(array, 'ae', options).should.eql([]) filterContains(array, '12', options).should.eql(getResult([{name: 'PI:NAME:<NAME>END_PI', age: '12' }, {name: 'PI:NAME:<NAME>END_PI', age: '12' }])) it 'when using case sensitivity', -> options ?= {} options.caseSensitive = true options.sort = true filterContains(array, 'pete', options).should.eql([]) filterContains(array, 'dave', options).should.eql([]) filterContains(array, 'dav', options).should.eql([]) filterContains(array, 've', options).should.eql(getResult([{name: 'PI:NAME:<NAME>END_PI', age: '12' }, {name: 'PI:NAME:<NAME>END_PI', age: '12' }, {name: 'PI:NAME:<NAME>END_PI', age: '34' }])) filterContains(array, 'ao', options).should.eql([]) filterContains(array, 'ae', options).should.eql([]) filterContains(array, '12', options).should.eql(getResult([{name: 'PI:NAME:<NAME>END_PI', age: '12' }, {name: 'PI:NAME:<NAME>END_PI', age: '12' }])) it 'when not sorting', -> options ?= {} options.caseSensitive = false options.sort = false filterContains(array, 'pete', options).should.eql([]) filterContains(array, 'dave', options).should.eql(getResult([{name: 'PI:NAME:<NAME>END_PI', age: '12' }])) filterContains(array, 'dav', options).should.eql(getResult([{name: 'PI:NAME:<NAME>END_PI', age: '12' }])) filterContains(array, 've', options).should.eql(getResult([{name: 'PI:NAME:<NAME>END_PI', age: '34' }, {name: 'PI:NAME:<NAME>END_PI', age: '12' }, {name: 'PI:NAME:<NAME>END_PI', age: '12' }])) filterContains(array, 'ao', options).should.eql([]) filterContains(array, 'ae', options).should.eql([]) filterContains(array, '12', options).should.eql(getResult([{name: 'PI:NAME:<NAME>END_PI', age: '12' }, {name: 'PI:NAME:<NAME>END_PI', age: '12' }])) stringArray = [ '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', '.()-[]{}\\^|$?*+! 32' ] objectArray = [ { name: 'PI:NAME:<NAME>END_PI' age: '34' },{ name: 'PI:NAME:<NAME>END_PI' age: '56' },{ name: 'PI:NAME:<NAME>END_PI' age: '12' },{ name: 'PI:NAME:<NAME>END_PI' age: '12' },{ name: 'PI:NAME:<NAME>END_PI' age: '78' },{ name: 'PI:NAME:<NAME>END_PI' age: '90' }, { name: '.()-[]{}\\^|$?*+!' age: '32' } ] nestedArray = [ ['PI:NAME:<NAME>END_PI', '34'] ['PI:NAME:<NAME>END_PI', '56'] ['PI:NAME:<NAME>END_PI', '12'] ['PI:NAME:<NAME>END_PI', '12'] ['PI:NAME:<NAME>END_PI', '7PI:NAME:<NAME>END_PI'] ['PI:NAME:<NAME>END_PI', '90'] ['.()-[]{}\\^|$?*+!', '32'] ] describe 'a string based array using hx.filter', -> runSpecsForSource(stringArray, {}, 'str') describe 'an object based array using hx.filter', -> runSpecsForSource(objectArray, {searchValues: ((d) -> [d.name, d.age])}, 'obj') describe 'a nested array using hx.filter', -> runSpecsForSource(nestedArray, {searchValues: ((d) -> d)}, 'arr')
[ { "context": "#\n# grunt-colorswap\n# https://github.com/meyer/grunt-colorswap\n#\n# Copyright (c) 2014 Mike Meyer", "end": 46, "score": 0.998649537563324, "start": 41, "tag": "USERNAME", "value": "meyer" }, { "context": "b.com/meyer/grunt-colorswap\n#\n# Copyright (c) 2014 Mike Meyer\n# Licensed under the MIT license.\n#\n\n\"use strict\"", "end": 96, "score": 0.9998744130134583, "start": 86, "tag": "NAME", "value": "Mike Meyer" } ]
tasks/colorswap.coffee
meyer/grunt-colorswap
0
# # grunt-colorswap # https://github.com/meyer/grunt-colorswap # # Copyright (c) 2014 Mike Meyer # Licensed under the MIT license. # "use strict" module.exports = (grunt) -> Chromath = require "chromath" pad = (str, places, padWith=" ") -> (new Array(places+1).join(padWith) + str).slice(-places) multiTask = -> options = @options( # TODO: Probably need to be a bit better about matching weird spaces # TODO: Use block regex format to make this more readable regexes: [ /(rgb\((?:(?:[01]?\d?\d|2[0-4]\d|25[0-5])\,\s*?){2}(?:[01]?\d?\d|2[0-4]\d|25[0-5])\))/gi /(#(?:[\dA-F]{3}){1,2})/gi ] ) @requiresConfig "#{@name}.#{@target}.options.instructions" # Allow for multiple instructions instructionArray = [].concat options.instructions # List of filters to run todoList = [] instructionArray.forEach (instructions) -> # First word == filter name filterName = instructions.toLowerCase().split(" ")[0] try filter = require "./filters/#{filterName}" unless typeof filter.init == "function" throw new Error "missing required method init" if typeof filter.processColour == "function" filter.processColor = filter.processColour unless typeof filter.processColor == "function" throw new Error "missing required method processColor" filter.init instructions grunt.verbose.ok "Loaded filter `#{filterName}` for `#{instructions}`" catch e grunt.log.warn "Can’t load filter `#{filterName}`: #{e}" return todoList.push [filterName, filter] @files.forEach (f, idx) => grunt.verbose.ok "Processing `#{f.src}` (#{idx+1}/#{@files.length})" # Get the text contents of the file fileSource = grunt.file.read f.src grunt.verbose.writeln() originalColors = [] colorObjects = [] # Loop through each regex, see if it matches a valid color options.regexes.forEach (rgx) -> # Loop through regex matches while match = rgx.exec(fileSource) try # Validate the regex match color = new Chromath(match[1]) originalColors.push match[1] colorObjects.push color catch e grunt.log.warn "Regex matched an invalid color string (#{match[1]})" return if originalColors.length == 0 grunt.log.warn "No valid colors were found :C" return # Valid original colors originalColors.forEach (targetString, idx) -> originalColor = colorObjects[idx].toString() grunt.verbose.ok "#{idx+1}/#{originalColors.length} -- #{originalColors[idx]}" # Run each filter todoList.forEach ([filterName, filter]) -> try replacement = filter.processColor(colorObjects[idx]) newTargetString = replacement.toHexString() if originalColor != newTargetString fileSource = fileSource.replace(targetString, newTargetString) grunt.verbose.writeln "#{filterName}: #{originalColor} ---> #{newTargetString}" else grunt.verbose.writeln "#{filterName}: Color unchanged." colorObjects[idx] = replacement targetString = newTargetString catch e grunt.log.warn "Filter `#{options.instructions}` did not run:\n - #{e}" return grunt.verbose.writeln "" grunt.file.write f.dest, fileSource grunt.verbose.ok "File `#{f.dest}` created." grunt.verbose.writeln() return grunt.log.ok "Ran `#{instructionArray.join "`, `"}` on #{@files.length} file#{"s" unless @files.length == 1}" return grunt.registerMultiTask "colorswap", "Manipulate colors in any given file.", multiTask grunt.registerMultiTask "colourswap", "Manipulate colours in any given file.", multiTask return
20409
# # grunt-colorswap # https://github.com/meyer/grunt-colorswap # # Copyright (c) 2014 <NAME> # Licensed under the MIT license. # "use strict" module.exports = (grunt) -> Chromath = require "chromath" pad = (str, places, padWith=" ") -> (new Array(places+1).join(padWith) + str).slice(-places) multiTask = -> options = @options( # TODO: Probably need to be a bit better about matching weird spaces # TODO: Use block regex format to make this more readable regexes: [ /(rgb\((?:(?:[01]?\d?\d|2[0-4]\d|25[0-5])\,\s*?){2}(?:[01]?\d?\d|2[0-4]\d|25[0-5])\))/gi /(#(?:[\dA-F]{3}){1,2})/gi ] ) @requiresConfig "#{@name}.#{@target}.options.instructions" # Allow for multiple instructions instructionArray = [].concat options.instructions # List of filters to run todoList = [] instructionArray.forEach (instructions) -> # First word == filter name filterName = instructions.toLowerCase().split(" ")[0] try filter = require "./filters/#{filterName}" unless typeof filter.init == "function" throw new Error "missing required method init" if typeof filter.processColour == "function" filter.processColor = filter.processColour unless typeof filter.processColor == "function" throw new Error "missing required method processColor" filter.init instructions grunt.verbose.ok "Loaded filter `#{filterName}` for `#{instructions}`" catch e grunt.log.warn "Can’t load filter `#{filterName}`: #{e}" return todoList.push [filterName, filter] @files.forEach (f, idx) => grunt.verbose.ok "Processing `#{f.src}` (#{idx+1}/#{@files.length})" # Get the text contents of the file fileSource = grunt.file.read f.src grunt.verbose.writeln() originalColors = [] colorObjects = [] # Loop through each regex, see if it matches a valid color options.regexes.forEach (rgx) -> # Loop through regex matches while match = rgx.exec(fileSource) try # Validate the regex match color = new Chromath(match[1]) originalColors.push match[1] colorObjects.push color catch e grunt.log.warn "Regex matched an invalid color string (#{match[1]})" return if originalColors.length == 0 grunt.log.warn "No valid colors were found :C" return # Valid original colors originalColors.forEach (targetString, idx) -> originalColor = colorObjects[idx].toString() grunt.verbose.ok "#{idx+1}/#{originalColors.length} -- #{originalColors[idx]}" # Run each filter todoList.forEach ([filterName, filter]) -> try replacement = filter.processColor(colorObjects[idx]) newTargetString = replacement.toHexString() if originalColor != newTargetString fileSource = fileSource.replace(targetString, newTargetString) grunt.verbose.writeln "#{filterName}: #{originalColor} ---> #{newTargetString}" else grunt.verbose.writeln "#{filterName}: Color unchanged." colorObjects[idx] = replacement targetString = newTargetString catch e grunt.log.warn "Filter `#{options.instructions}` did not run:\n - #{e}" return grunt.verbose.writeln "" grunt.file.write f.dest, fileSource grunt.verbose.ok "File `#{f.dest}` created." grunt.verbose.writeln() return grunt.log.ok "Ran `#{instructionArray.join "`, `"}` on #{@files.length} file#{"s" unless @files.length == 1}" return grunt.registerMultiTask "colorswap", "Manipulate colors in any given file.", multiTask grunt.registerMultiTask "colourswap", "Manipulate colours in any given file.", multiTask return
true
# # grunt-colorswap # https://github.com/meyer/grunt-colorswap # # Copyright (c) 2014 PI:NAME:<NAME>END_PI # Licensed under the MIT license. # "use strict" module.exports = (grunt) -> Chromath = require "chromath" pad = (str, places, padWith=" ") -> (new Array(places+1).join(padWith) + str).slice(-places) multiTask = -> options = @options( # TODO: Probably need to be a bit better about matching weird spaces # TODO: Use block regex format to make this more readable regexes: [ /(rgb\((?:(?:[01]?\d?\d|2[0-4]\d|25[0-5])\,\s*?){2}(?:[01]?\d?\d|2[0-4]\d|25[0-5])\))/gi /(#(?:[\dA-F]{3}){1,2})/gi ] ) @requiresConfig "#{@name}.#{@target}.options.instructions" # Allow for multiple instructions instructionArray = [].concat options.instructions # List of filters to run todoList = [] instructionArray.forEach (instructions) -> # First word == filter name filterName = instructions.toLowerCase().split(" ")[0] try filter = require "./filters/#{filterName}" unless typeof filter.init == "function" throw new Error "missing required method init" if typeof filter.processColour == "function" filter.processColor = filter.processColour unless typeof filter.processColor == "function" throw new Error "missing required method processColor" filter.init instructions grunt.verbose.ok "Loaded filter `#{filterName}` for `#{instructions}`" catch e grunt.log.warn "Can’t load filter `#{filterName}`: #{e}" return todoList.push [filterName, filter] @files.forEach (f, idx) => grunt.verbose.ok "Processing `#{f.src}` (#{idx+1}/#{@files.length})" # Get the text contents of the file fileSource = grunt.file.read f.src grunt.verbose.writeln() originalColors = [] colorObjects = [] # Loop through each regex, see if it matches a valid color options.regexes.forEach (rgx) -> # Loop through regex matches while match = rgx.exec(fileSource) try # Validate the regex match color = new Chromath(match[1]) originalColors.push match[1] colorObjects.push color catch e grunt.log.warn "Regex matched an invalid color string (#{match[1]})" return if originalColors.length == 0 grunt.log.warn "No valid colors were found :C" return # Valid original colors originalColors.forEach (targetString, idx) -> originalColor = colorObjects[idx].toString() grunt.verbose.ok "#{idx+1}/#{originalColors.length} -- #{originalColors[idx]}" # Run each filter todoList.forEach ([filterName, filter]) -> try replacement = filter.processColor(colorObjects[idx]) newTargetString = replacement.toHexString() if originalColor != newTargetString fileSource = fileSource.replace(targetString, newTargetString) grunt.verbose.writeln "#{filterName}: #{originalColor} ---> #{newTargetString}" else grunt.verbose.writeln "#{filterName}: Color unchanged." colorObjects[idx] = replacement targetString = newTargetString catch e grunt.log.warn "Filter `#{options.instructions}` did not run:\n - #{e}" return grunt.verbose.writeln "" grunt.file.write f.dest, fileSource grunt.verbose.ok "File `#{f.dest}` created." grunt.verbose.writeln() return grunt.log.ok "Ran `#{instructionArray.join "`, `"}` on #{@files.length} file#{"s" unless @files.length == 1}" return grunt.registerMultiTask "colorswap", "Manipulate colors in any given file.", multiTask grunt.registerMultiTask "colourswap", "Manipulate colours in any given file.", multiTask return
[ { "context": ".emit 'event', 1, 2, 3\n#\n# Copyright (C) 2011-2012 Nikolay Nemshilov\n#\nEvents =\n _listeners: null # this object liste", "end": 295, "score": 0.9998920559883118, "start": 278, "tag": "NAME", "value": "Nikolay Nemshilov" } ]
stl/core/src/events.coffee
lovely-io/lovely.io-stl
2
# # The standard events handling interface mixin # # MyClass = new core.Class # inclunde: core.Events # # my = new MyClass # # my.on 'event', (one, two, three)-> # console.log(one, two, three) # # my.emit 'event', 1, 2, 3 # # Copyright (C) 2011-2012 Nikolay Nemshilov # Events = _listeners: null # this object listeners stash # # Adds event listeners # # object.on 'event', callback # object.on 'event1,event2,event3', callback # object.on event1: callback1, event2: callback2 # object.on 'event', 'methodname'[, arg1, arg2, ..] # # @return {Class} this # on: -> args = Array_slice.call(arguments, 2) events = arguments[0] callback = arguments[1] by_name = false if typeof(callback) is 'string' callback = this[callback] by_name = true listeners = if @_listeners is null then (@_listeners = []) else @_listeners if typeof(events) is 'string' for event in events.split(',') listeners.push e: event # event name c: callback # callback function reference a: args # remaining arguments list n: by_name # a marker if the callback was specified as a method-name else if typeof(events) is 'object' for event of events @on event, events[event] this # # Removes event listeners # # object.no 'event' # object.no 'event1,event2' # object.no callback # object.no 'event', callback # object.no event1: callback1, event2: callback2 # object.no 'event', 'methodname' # # @return {Class} this # no: -> args = Array_slice.call(arguments, 2) events = arguments[0] callback = arguments[1] callback = this[callback] if typeof(callback) is 'string' listeners = if @_listeners is null then (@_listeners = []) else @_listeners switch typeof(events) when 'string' for event in events.split(',') index = 0 while index < listeners.length listeners.splice index--, 1 if listeners[index].e is event and (listeners[index].c is callback or callback is undefined) index++ when 'function' index = 0 while index < listeners.length if listeners[index].c is events listeners.splice index--, 1 index++ when 'object' for event of events @no event, events[event] this # # Checks if this object listens to the events # # object.ones 'event' # object.ones 'event1,event2' # object.ones callback # object.ones 'event', callback # object.ones event1: callback1, event2: callback2 # object.ones 'event', 'methodname' # # __NOTE__: if several event names are specified then it # will check if _any_ of them are satisfied # # @return {boolean} check result # ones: -> result = 0 args = Array_slice.call(arguments, 2) events = arguments[0] callback = arguments[1] callback = this[callback] if typeof(callback) is 'string' listeners = if @_listeners is null then (@_listeners = []) else @_listeners switch typeof(events) when 'string' for event in events.split(',') for entry in listeners result |= entry.e is event and ( entry.c is callback or callback is undefined) when 'function' for entry in listeners result |= entry.c is events when 'object' for event of events result |= @ones event, events[event] result is 1 # converting to boolean after the `|=` operations # # Triggers an event on the object # # object.emit 'event' # object.emit 'event', arg1, arg2, arg3 # # @return {Class} this # emit: -> args = A(arguments) event = args.shift() for entry in this._listeners || [] if entry.e is event entry.c.apply(this, entry.a.concat(args)) this
146205
# # The standard events handling interface mixin # # MyClass = new core.Class # inclunde: core.Events # # my = new MyClass # # my.on 'event', (one, two, three)-> # console.log(one, two, three) # # my.emit 'event', 1, 2, 3 # # Copyright (C) 2011-2012 <NAME> # Events = _listeners: null # this object listeners stash # # Adds event listeners # # object.on 'event', callback # object.on 'event1,event2,event3', callback # object.on event1: callback1, event2: callback2 # object.on 'event', 'methodname'[, arg1, arg2, ..] # # @return {Class} this # on: -> args = Array_slice.call(arguments, 2) events = arguments[0] callback = arguments[1] by_name = false if typeof(callback) is 'string' callback = this[callback] by_name = true listeners = if @_listeners is null then (@_listeners = []) else @_listeners if typeof(events) is 'string' for event in events.split(',') listeners.push e: event # event name c: callback # callback function reference a: args # remaining arguments list n: by_name # a marker if the callback was specified as a method-name else if typeof(events) is 'object' for event of events @on event, events[event] this # # Removes event listeners # # object.no 'event' # object.no 'event1,event2' # object.no callback # object.no 'event', callback # object.no event1: callback1, event2: callback2 # object.no 'event', 'methodname' # # @return {Class} this # no: -> args = Array_slice.call(arguments, 2) events = arguments[0] callback = arguments[1] callback = this[callback] if typeof(callback) is 'string' listeners = if @_listeners is null then (@_listeners = []) else @_listeners switch typeof(events) when 'string' for event in events.split(',') index = 0 while index < listeners.length listeners.splice index--, 1 if listeners[index].e is event and (listeners[index].c is callback or callback is undefined) index++ when 'function' index = 0 while index < listeners.length if listeners[index].c is events listeners.splice index--, 1 index++ when 'object' for event of events @no event, events[event] this # # Checks if this object listens to the events # # object.ones 'event' # object.ones 'event1,event2' # object.ones callback # object.ones 'event', callback # object.ones event1: callback1, event2: callback2 # object.ones 'event', 'methodname' # # __NOTE__: if several event names are specified then it # will check if _any_ of them are satisfied # # @return {boolean} check result # ones: -> result = 0 args = Array_slice.call(arguments, 2) events = arguments[0] callback = arguments[1] callback = this[callback] if typeof(callback) is 'string' listeners = if @_listeners is null then (@_listeners = []) else @_listeners switch typeof(events) when 'string' for event in events.split(',') for entry in listeners result |= entry.e is event and ( entry.c is callback or callback is undefined) when 'function' for entry in listeners result |= entry.c is events when 'object' for event of events result |= @ones event, events[event] result is 1 # converting to boolean after the `|=` operations # # Triggers an event on the object # # object.emit 'event' # object.emit 'event', arg1, arg2, arg3 # # @return {Class} this # emit: -> args = A(arguments) event = args.shift() for entry in this._listeners || [] if entry.e is event entry.c.apply(this, entry.a.concat(args)) this
true
# # The standard events handling interface mixin # # MyClass = new core.Class # inclunde: core.Events # # my = new MyClass # # my.on 'event', (one, two, three)-> # console.log(one, two, three) # # my.emit 'event', 1, 2, 3 # # Copyright (C) 2011-2012 PI:NAME:<NAME>END_PI # Events = _listeners: null # this object listeners stash # # Adds event listeners # # object.on 'event', callback # object.on 'event1,event2,event3', callback # object.on event1: callback1, event2: callback2 # object.on 'event', 'methodname'[, arg1, arg2, ..] # # @return {Class} this # on: -> args = Array_slice.call(arguments, 2) events = arguments[0] callback = arguments[1] by_name = false if typeof(callback) is 'string' callback = this[callback] by_name = true listeners = if @_listeners is null then (@_listeners = []) else @_listeners if typeof(events) is 'string' for event in events.split(',') listeners.push e: event # event name c: callback # callback function reference a: args # remaining arguments list n: by_name # a marker if the callback was specified as a method-name else if typeof(events) is 'object' for event of events @on event, events[event] this # # Removes event listeners # # object.no 'event' # object.no 'event1,event2' # object.no callback # object.no 'event', callback # object.no event1: callback1, event2: callback2 # object.no 'event', 'methodname' # # @return {Class} this # no: -> args = Array_slice.call(arguments, 2) events = arguments[0] callback = arguments[1] callback = this[callback] if typeof(callback) is 'string' listeners = if @_listeners is null then (@_listeners = []) else @_listeners switch typeof(events) when 'string' for event in events.split(',') index = 0 while index < listeners.length listeners.splice index--, 1 if listeners[index].e is event and (listeners[index].c is callback or callback is undefined) index++ when 'function' index = 0 while index < listeners.length if listeners[index].c is events listeners.splice index--, 1 index++ when 'object' for event of events @no event, events[event] this # # Checks if this object listens to the events # # object.ones 'event' # object.ones 'event1,event2' # object.ones callback # object.ones 'event', callback # object.ones event1: callback1, event2: callback2 # object.ones 'event', 'methodname' # # __NOTE__: if several event names are specified then it # will check if _any_ of them are satisfied # # @return {boolean} check result # ones: -> result = 0 args = Array_slice.call(arguments, 2) events = arguments[0] callback = arguments[1] callback = this[callback] if typeof(callback) is 'string' listeners = if @_listeners is null then (@_listeners = []) else @_listeners switch typeof(events) when 'string' for event in events.split(',') for entry in listeners result |= entry.e is event and ( entry.c is callback or callback is undefined) when 'function' for entry in listeners result |= entry.c is events when 'object' for event of events result |= @ones event, events[event] result is 1 # converting to boolean after the `|=` operations # # Triggers an event on the object # # object.emit 'event' # object.emit 'event', arg1, arg2, arg3 # # @return {Class} this # emit: -> args = A(arguments) event = args.shift() for entry in this._listeners || [] if entry.e is event entry.c.apply(this, entry.a.concat(args)) this
[ { "context": "provante = Comprovante.notaFiscal\n\t_fornecedor = 'Multicoisas'\n\t_detalhes = '2x Fones de ouvido Multilaser'\n\n\ti", "end": 335, "score": 0.9546558856964111, "start": 324, "tag": "USERNAME", "value": "Multicoisas" }, { "context": "zar o lançamento de um crédito', ->\n\t\tdetalhes = 'Doação Renan'\n\t\tvalor = 100\n\n\t\tlancamento = _organizador.lanca", "end": 460, "score": 0.9988117218017578, "start": 448, "tag": "NAME", "value": "Doação Renan" } ]
test/unit/models/organizadorTeste.coffee
somosdigix/Digicom
0
should = require('chai').should() Natureza = require '../../../models/natureza' Comprovante = require '../../../models/comprovante' Organizador = require '../../../models/organizador' describe 'Organizador', -> _organizador = new Organizador _mes = 8 _ano = 2014 _comprovante = Comprovante.notaFiscal _fornecedor = 'Multicoisas' _detalhes = '2x Fones de ouvido Multilaser' it 'deve realizar o lançamento de um crédito', -> detalhes = 'Doação Renan' valor = 100 lancamento = _organizador.lancarCredito _mes, _ano, detalhes, valor lancamento.data.getFullYear().should.be.equal _ano lancamento.natureza.should.be.equal Natureza.credito lancamento.detalhes.should.be.equal detalhes lancamento.valor.should.be.equal valor it 'deve realizar o lançamento de um credito subtraindo 1 no mês solicitado', -> numeroDoMesDeAgosto = 7 lancamento = _organizador.lancarCredito _mes, _ano, _detalhes, 123 lancamento.data.getMonth().should.be.equal numeroDoMesDeAgosto it 'deve realizar o lançamento de um crétido com a data sempre marcada para o dia 1', -> lancamento = _organizador.lancarCredito _mes, _ano, _detalhes, 123 lancamento.data.getDate().should.be.equal 1 it 'não deve realizar o lançamento de um crédito sem mes', -> _organizador.lancarCredito.should.throw /Mês deve ser informado/ it 'não deve realizar o lançamento de um crédito sem ano', -> testMethod = -> _organizador.lancarCredito _mes testMethod.should.throw /Ano deve ser informado/ it 'não deve realizar o lançamento de um crédito sem detalhes', -> testMethod = -> _organizador.lancarCredito _mes, _ano testMethod.should.throw /Detalhes devem ser informados/ it 'não deve realizar o lançamento de um crédito sem valor', -> testMethod = -> _organizador.lancarCredito _mes, _ano, 'Detalhes' testMethod.should.throw /Valor deve ser informado/ it 'deve realizar o lançamento de um débito', -> valor = 150.00 lancamento = _organizador.lancarDebito _mes, _ano, _comprovante, _fornecedor, _detalhes, valor lancamento.data.getFullYear().should.be.equal _ano lancamento.natureza.should.be.equal Natureza.debito lancamento.comprovante.should.be.equal _comprovante lancamento.fornecedor.should.be.equal _fornecedor lancamento.detalhes.should.be.equal _detalhes lancamento.valor.should.be.equal valor it 'deve realizar o lançamento de um débito subtraindo um do mês solicitado', -> numeroDoMesDeAgosto = 7 lancamento = _organizador.lancarDebito _mes, _ano, _comprovante, _fornecedor, _detalhes, 123 lancamento.data.getMonth().should.be.equal numeroDoMesDeAgosto it 'deve realizar o lançamento de um débito sempre com a data marcada para o dia 1', -> lancamento = _organizador.lancarDebito _mes, _ano, _comprovante, _fornecedor, _detalhes, 123 lancamento.data.getDate().should.be.equal 1 it 'não deve realizar o lançamento de um débito sem mês', -> _organizador.lancarDebito.should.throw /Mês deve ser informado/ it 'não deve realizar o lançamento de um débito sem ano', -> testMethod = -> _organizador.lancarDebito _mes testMethod.should.throw /Ano deve ser informado/ it 'não deve realizar o lançamento de um débito sem comprovante', -> testMethod = -> _organizador.lancarDebito _mes, _ano testMethod.should.throw /Comprovante deve ser informado/ it 'não deve realizar o lançamento de um débito sem fornecedor', -> testMethod = -> _organizador.lancarDebito _mes, _ano, _comprovante testMethod.should.throw /Fornecedor deve ser informado/ it 'não deve realizar o lançamento de um débito sem valor', -> testMethod = -> _organizador.lancarDebito _mes, _ano, _comprovante, _fornecedor testMethod.should.throw /Valor deve ser informado/
190467
should = require('chai').should() Natureza = require '../../../models/natureza' Comprovante = require '../../../models/comprovante' Organizador = require '../../../models/organizador' describe 'Organizador', -> _organizador = new Organizador _mes = 8 _ano = 2014 _comprovante = Comprovante.notaFiscal _fornecedor = 'Multicoisas' _detalhes = '2x Fones de ouvido Multilaser' it 'deve realizar o lançamento de um crédito', -> detalhes = '<NAME>' valor = 100 lancamento = _organizador.lancarCredito _mes, _ano, detalhes, valor lancamento.data.getFullYear().should.be.equal _ano lancamento.natureza.should.be.equal Natureza.credito lancamento.detalhes.should.be.equal detalhes lancamento.valor.should.be.equal valor it 'deve realizar o lançamento de um credito subtraindo 1 no mês solicitado', -> numeroDoMesDeAgosto = 7 lancamento = _organizador.lancarCredito _mes, _ano, _detalhes, 123 lancamento.data.getMonth().should.be.equal numeroDoMesDeAgosto it 'deve realizar o lançamento de um crétido com a data sempre marcada para o dia 1', -> lancamento = _organizador.lancarCredito _mes, _ano, _detalhes, 123 lancamento.data.getDate().should.be.equal 1 it 'não deve realizar o lançamento de um crédito sem mes', -> _organizador.lancarCredito.should.throw /Mês deve ser informado/ it 'não deve realizar o lançamento de um crédito sem ano', -> testMethod = -> _organizador.lancarCredito _mes testMethod.should.throw /Ano deve ser informado/ it 'não deve realizar o lançamento de um crédito sem detalhes', -> testMethod = -> _organizador.lancarCredito _mes, _ano testMethod.should.throw /Detalhes devem ser informados/ it 'não deve realizar o lançamento de um crédito sem valor', -> testMethod = -> _organizador.lancarCredito _mes, _ano, 'Detalhes' testMethod.should.throw /Valor deve ser informado/ it 'deve realizar o lançamento de um débito', -> valor = 150.00 lancamento = _organizador.lancarDebito _mes, _ano, _comprovante, _fornecedor, _detalhes, valor lancamento.data.getFullYear().should.be.equal _ano lancamento.natureza.should.be.equal Natureza.debito lancamento.comprovante.should.be.equal _comprovante lancamento.fornecedor.should.be.equal _fornecedor lancamento.detalhes.should.be.equal _detalhes lancamento.valor.should.be.equal valor it 'deve realizar o lançamento de um débito subtraindo um do mês solicitado', -> numeroDoMesDeAgosto = 7 lancamento = _organizador.lancarDebito _mes, _ano, _comprovante, _fornecedor, _detalhes, 123 lancamento.data.getMonth().should.be.equal numeroDoMesDeAgosto it 'deve realizar o lançamento de um débito sempre com a data marcada para o dia 1', -> lancamento = _organizador.lancarDebito _mes, _ano, _comprovante, _fornecedor, _detalhes, 123 lancamento.data.getDate().should.be.equal 1 it 'não deve realizar o lançamento de um débito sem mês', -> _organizador.lancarDebito.should.throw /Mês deve ser informado/ it 'não deve realizar o lançamento de um débito sem ano', -> testMethod = -> _organizador.lancarDebito _mes testMethod.should.throw /Ano deve ser informado/ it 'não deve realizar o lançamento de um débito sem comprovante', -> testMethod = -> _organizador.lancarDebito _mes, _ano testMethod.should.throw /Comprovante deve ser informado/ it 'não deve realizar o lançamento de um débito sem fornecedor', -> testMethod = -> _organizador.lancarDebito _mes, _ano, _comprovante testMethod.should.throw /Fornecedor deve ser informado/ it 'não deve realizar o lançamento de um débito sem valor', -> testMethod = -> _organizador.lancarDebito _mes, _ano, _comprovante, _fornecedor testMethod.should.throw /Valor deve ser informado/
true
should = require('chai').should() Natureza = require '../../../models/natureza' Comprovante = require '../../../models/comprovante' Organizador = require '../../../models/organizador' describe 'Organizador', -> _organizador = new Organizador _mes = 8 _ano = 2014 _comprovante = Comprovante.notaFiscal _fornecedor = 'Multicoisas' _detalhes = '2x Fones de ouvido Multilaser' it 'deve realizar o lançamento de um crédito', -> detalhes = 'PI:NAME:<NAME>END_PI' valor = 100 lancamento = _organizador.lancarCredito _mes, _ano, detalhes, valor lancamento.data.getFullYear().should.be.equal _ano lancamento.natureza.should.be.equal Natureza.credito lancamento.detalhes.should.be.equal detalhes lancamento.valor.should.be.equal valor it 'deve realizar o lançamento de um credito subtraindo 1 no mês solicitado', -> numeroDoMesDeAgosto = 7 lancamento = _organizador.lancarCredito _mes, _ano, _detalhes, 123 lancamento.data.getMonth().should.be.equal numeroDoMesDeAgosto it 'deve realizar o lançamento de um crétido com a data sempre marcada para o dia 1', -> lancamento = _organizador.lancarCredito _mes, _ano, _detalhes, 123 lancamento.data.getDate().should.be.equal 1 it 'não deve realizar o lançamento de um crédito sem mes', -> _organizador.lancarCredito.should.throw /Mês deve ser informado/ it 'não deve realizar o lançamento de um crédito sem ano', -> testMethod = -> _organizador.lancarCredito _mes testMethod.should.throw /Ano deve ser informado/ it 'não deve realizar o lançamento de um crédito sem detalhes', -> testMethod = -> _organizador.lancarCredito _mes, _ano testMethod.should.throw /Detalhes devem ser informados/ it 'não deve realizar o lançamento de um crédito sem valor', -> testMethod = -> _organizador.lancarCredito _mes, _ano, 'Detalhes' testMethod.should.throw /Valor deve ser informado/ it 'deve realizar o lançamento de um débito', -> valor = 150.00 lancamento = _organizador.lancarDebito _mes, _ano, _comprovante, _fornecedor, _detalhes, valor lancamento.data.getFullYear().should.be.equal _ano lancamento.natureza.should.be.equal Natureza.debito lancamento.comprovante.should.be.equal _comprovante lancamento.fornecedor.should.be.equal _fornecedor lancamento.detalhes.should.be.equal _detalhes lancamento.valor.should.be.equal valor it 'deve realizar o lançamento de um débito subtraindo um do mês solicitado', -> numeroDoMesDeAgosto = 7 lancamento = _organizador.lancarDebito _mes, _ano, _comprovante, _fornecedor, _detalhes, 123 lancamento.data.getMonth().should.be.equal numeroDoMesDeAgosto it 'deve realizar o lançamento de um débito sempre com a data marcada para o dia 1', -> lancamento = _organizador.lancarDebito _mes, _ano, _comprovante, _fornecedor, _detalhes, 123 lancamento.data.getDate().should.be.equal 1 it 'não deve realizar o lançamento de um débito sem mês', -> _organizador.lancarDebito.should.throw /Mês deve ser informado/ it 'não deve realizar o lançamento de um débito sem ano', -> testMethod = -> _organizador.lancarDebito _mes testMethod.should.throw /Ano deve ser informado/ it 'não deve realizar o lançamento de um débito sem comprovante', -> testMethod = -> _organizador.lancarDebito _mes, _ano testMethod.should.throw /Comprovante deve ser informado/ it 'não deve realizar o lançamento de um débito sem fornecedor', -> testMethod = -> _organizador.lancarDebito _mes, _ano, _comprovante testMethod.should.throw /Fornecedor deve ser informado/ it 'não deve realizar o lançamento de um débito sem valor', -> testMethod = -> _organizador.lancarDebito _mes, _ano, _comprovante, _fornecedor testMethod.should.throw /Valor deve ser informado/
[ { "context": "###\nGulp task bower\n@create 2014-10-07\n@author KoutarouYabe <idolm@ster.pw>\n###\n\nmodule.exports = (gulp, plug", "end": 59, "score": 0.9998900890350342, "start": 47, "tag": "NAME", "value": "KoutarouYabe" }, { "context": "sk bower\n@create 2014-10-07\n@author KoutarouYabe <idolm@ster.pw>\n###\n\nmodule.exports = (gulp, plugins, growl, pat", "end": 74, "score": 0.9999322295188904, "start": 61, "tag": "EMAIL", "value": "idolm@ster.pw" } ]
tasks/config/bower.coffee
moorvin/Sea-Fight
1
### Gulp task bower @create 2014-10-07 @author KoutarouYabe <idolm@ster.pw> ### module.exports = (gulp, plugins, growl, path)-> filter = plugins.filter jsFilter = filter "**/*.js" cssFilter = filter "**/*.css" fontFilter = filter ["**/*.ttf", "**/*.svg", "**/*.eot", "**/*.woff", "**/*.woff2"] gulp.task "bower", -> bowerFiles = plugins.bowerFiles() bowerBasePath = path.resolve __dirname, "../../bower_components/" bowerFiles.push path.resolve bowerBasePath, "modernizr/modernizr.js" bowerFiles.push path.resolve bowerBasePath, "bootstrap/dist/css/bootstrap.min.css" bowerFiles.push path.resolve bowerBasePath, "bootstrap/dist/css/bootstrap-theme.min.css" bowerFiles.push path.resolve bowerBasePath, "bootstrap/dist/fonts/glyphicons-halflings-regular.eot" bowerFiles.push path.resolve bowerBasePath, "bootstrap/dist/fonts/glyphicons-halflings-regular.svg" bowerFiles.push path.resolve bowerBasePath, "bootstrap/dist/fonts/glyphicons-halflings-regular.ttf" bowerFiles.push path.resolve bowerBasePath, "bootstrap/dist/fonts/glyphicons-halflings-regular.woff" bowerFiles.push path.resolve bowerBasePath, "bootstrap/dist/fonts/glyphicons-halflings-regular.woff2" bowerFiles.push path.resolve bowerBasePath, "fontawesome/css/font-awesome.min.css" bowerFiles.push path.resolve bowerBasePath, "fontawesome/fonts/FontAwesome.otf" bowerFiles.push path.resolve bowerBasePath, "fontawesome/fonts/fontawesome-webfont.svg" bowerFiles.push path.resolve bowerBasePath, "fontawesome/fonts/fontawesome-webfont.woff" bowerFiles.push path.resolve bowerBasePath, "fontawesome/fonts/fontawesome-webfont.eot" bowerFiles.push path.resolve bowerBasePath, "fontawesome/fonts/fontawesome-webfont.ttf" bowerFiles.push path.resolve bowerBasePath, "fontawesome/fonts/fontawesome-webfont.woff2" plugins.util.log "---bower including file---" for bf in bowerFiles plugins.util.log path.basename bf plugins.util.log "--------------------------" gulp.src bowerFiles .pipe jsFilter .pipe gulp.dest plugins.config.destPath + "js/lib" .pipe jsFilter.restore() .pipe cssFilter .pipe gulp.dest plugins.config.destPath + "css/lib" .pipe cssFilter.restore() .pipe fontFilter .pipe gulp.dest plugins.config.destPath + "css/fonts"
77973
### Gulp task bower @create 2014-10-07 @author <NAME> <<EMAIL>> ### module.exports = (gulp, plugins, growl, path)-> filter = plugins.filter jsFilter = filter "**/*.js" cssFilter = filter "**/*.css" fontFilter = filter ["**/*.ttf", "**/*.svg", "**/*.eot", "**/*.woff", "**/*.woff2"] gulp.task "bower", -> bowerFiles = plugins.bowerFiles() bowerBasePath = path.resolve __dirname, "../../bower_components/" bowerFiles.push path.resolve bowerBasePath, "modernizr/modernizr.js" bowerFiles.push path.resolve bowerBasePath, "bootstrap/dist/css/bootstrap.min.css" bowerFiles.push path.resolve bowerBasePath, "bootstrap/dist/css/bootstrap-theme.min.css" bowerFiles.push path.resolve bowerBasePath, "bootstrap/dist/fonts/glyphicons-halflings-regular.eot" bowerFiles.push path.resolve bowerBasePath, "bootstrap/dist/fonts/glyphicons-halflings-regular.svg" bowerFiles.push path.resolve bowerBasePath, "bootstrap/dist/fonts/glyphicons-halflings-regular.ttf" bowerFiles.push path.resolve bowerBasePath, "bootstrap/dist/fonts/glyphicons-halflings-regular.woff" bowerFiles.push path.resolve bowerBasePath, "bootstrap/dist/fonts/glyphicons-halflings-regular.woff2" bowerFiles.push path.resolve bowerBasePath, "fontawesome/css/font-awesome.min.css" bowerFiles.push path.resolve bowerBasePath, "fontawesome/fonts/FontAwesome.otf" bowerFiles.push path.resolve bowerBasePath, "fontawesome/fonts/fontawesome-webfont.svg" bowerFiles.push path.resolve bowerBasePath, "fontawesome/fonts/fontawesome-webfont.woff" bowerFiles.push path.resolve bowerBasePath, "fontawesome/fonts/fontawesome-webfont.eot" bowerFiles.push path.resolve bowerBasePath, "fontawesome/fonts/fontawesome-webfont.ttf" bowerFiles.push path.resolve bowerBasePath, "fontawesome/fonts/fontawesome-webfont.woff2" plugins.util.log "---bower including file---" for bf in bowerFiles plugins.util.log path.basename bf plugins.util.log "--------------------------" gulp.src bowerFiles .pipe jsFilter .pipe gulp.dest plugins.config.destPath + "js/lib" .pipe jsFilter.restore() .pipe cssFilter .pipe gulp.dest plugins.config.destPath + "css/lib" .pipe cssFilter.restore() .pipe fontFilter .pipe gulp.dest plugins.config.destPath + "css/fonts"
true
### Gulp task bower @create 2014-10-07 @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ### module.exports = (gulp, plugins, growl, path)-> filter = plugins.filter jsFilter = filter "**/*.js" cssFilter = filter "**/*.css" fontFilter = filter ["**/*.ttf", "**/*.svg", "**/*.eot", "**/*.woff", "**/*.woff2"] gulp.task "bower", -> bowerFiles = plugins.bowerFiles() bowerBasePath = path.resolve __dirname, "../../bower_components/" bowerFiles.push path.resolve bowerBasePath, "modernizr/modernizr.js" bowerFiles.push path.resolve bowerBasePath, "bootstrap/dist/css/bootstrap.min.css" bowerFiles.push path.resolve bowerBasePath, "bootstrap/dist/css/bootstrap-theme.min.css" bowerFiles.push path.resolve bowerBasePath, "bootstrap/dist/fonts/glyphicons-halflings-regular.eot" bowerFiles.push path.resolve bowerBasePath, "bootstrap/dist/fonts/glyphicons-halflings-regular.svg" bowerFiles.push path.resolve bowerBasePath, "bootstrap/dist/fonts/glyphicons-halflings-regular.ttf" bowerFiles.push path.resolve bowerBasePath, "bootstrap/dist/fonts/glyphicons-halflings-regular.woff" bowerFiles.push path.resolve bowerBasePath, "bootstrap/dist/fonts/glyphicons-halflings-regular.woff2" bowerFiles.push path.resolve bowerBasePath, "fontawesome/css/font-awesome.min.css" bowerFiles.push path.resolve bowerBasePath, "fontawesome/fonts/FontAwesome.otf" bowerFiles.push path.resolve bowerBasePath, "fontawesome/fonts/fontawesome-webfont.svg" bowerFiles.push path.resolve bowerBasePath, "fontawesome/fonts/fontawesome-webfont.woff" bowerFiles.push path.resolve bowerBasePath, "fontawesome/fonts/fontawesome-webfont.eot" bowerFiles.push path.resolve bowerBasePath, "fontawesome/fonts/fontawesome-webfont.ttf" bowerFiles.push path.resolve bowerBasePath, "fontawesome/fonts/fontawesome-webfont.woff2" plugins.util.log "---bower including file---" for bf in bowerFiles plugins.util.log path.basename bf plugins.util.log "--------------------------" gulp.src bowerFiles .pipe jsFilter .pipe gulp.dest plugins.config.destPath + "js/lib" .pipe jsFilter.restore() .pipe cssFilter .pipe gulp.dest plugins.config.destPath + "css/lib" .pipe cssFilter.restore() .pipe fontFilter .pipe gulp.dest plugins.config.destPath + "css/fonts"
[ { "context": "y way to connect to the midi controler\n# @author : David Ronai / @Makio64 / makiopolis.com\n#\n\nSignal = require('", "end": 77, "score": 0.9998524188995361, "start": 66, "tag": "NAME", "value": "David Ronai" }, { "context": "ct to the midi controler\n# @author : David Ronai / @Makio64 / makiopolis.com\n#\n\nSignal = require('signals')\n\n", "end": 88, "score": 0.9996159672737122, "start": 80, "tag": "USERNAME", "value": "@Makio64" } ]
src/coffee/makio/audio/Midi.coffee
Makio64/pizzaparty_vj
1
# # Provide easy way to connect to the midi controler # @author : David Ronai / @Makio64 / makiopolis.com # Signal = require('signals') class Midi @onInit = new Signal() @onMessage = new Signal() @XL1 = {in:'-909041163',out:'606894372',type:'xl'} @XL2 = {in:'1764102944',out:'-1845450469',type:'xl'} @PAD = {in:'879598748',out:'-324232190',type:'pad'} @init=()=> @domElement = document.createElement('div') @domElement.className = 'midi' # document.body.appendChild @domElement if(navigator.requestMIDIAccess) navigator.requestMIDIAccess({sysex: false}).then(@onMIDISuccess, @onMIDIFailure) else alert("No MIDI support in your browser.") return @onMIDISuccess=(midiAccess)=> detected = 0 @midi = midiAccess @inputs = [] @outputs = [] @midi.inputs.forEach( ( port, key )=> # console.log('midi in', port.id, port.name) # console.log(port) input = port input.onmidimessage = @onMIDIMessage @inputs.push(input) ) @midi.outputs.forEach( ( port, key )=> # console.log('midi out', port.id, port.name) @outputs.push(port) ) console.log('[MIDI] INIT:',@midi.inputs.size,@midi.outputs.size) @allButton(15,@XL1) @allButton(15,@XL2) @allButton(5,@PAD) @onInit.dispatch() return @onMIDIFailure=(error)=> console.log("No access to MIDI devices or your browser doesn't support WebMIDI API. Please use WebMIDIAPIShim " + error) return @onMIDIMessage=(message)=> data = message.data cmd = data[0] >> 4 channel = data[0] & 0xf type = data[0] & 0xf0 note = data[1] velocity = data[2]/127 id = message.target.id s = '' s += 'cmd: '+cmd+'<br />' s += 'channel: '+channel+'<br />' s += 'type: '+type+'<br />' s += 'note: '+note+'<br />' s += 'velocity: '+velocity+'<br />' @domElement.innerHTML = s console.log("NOTE:",note) @onMessage.dispatch({id:id,data:data,cmd:cmd,channel:channel,type:type,note:note,velocity:velocity}) return # Send message to control midi ( light for example ) @sendMessage=(note,value,id)=> for i in [0...@outputs.length] if(@outputs[i].id!=id.out) continue if(note >= 41 || id.type == 'pad' ) @outputs[i].send( [144,note,value] ) else @outputs[i].send( [240, 0, 32, 41, 2, 17, 120, 0, note, value, 247] ) return @allButton=(value,id)=> if(id.type == 'xl') for i in [0...4] @sendMessage(41+i, value,id) @sendMessage(73+i, value,id) @sendMessage(57+i, value,id) @sendMessage(89+i, value,id) else for x in [1..9] for y in [1..8] @sendMessage(x+y*10, value, id) # if(x<9) # @sendMessage(x+104, value, id) return @greenLed=(note,id)=> # 28 / 60 Midi.sendMessage(note,60,id) return @redLed=(note,id)=> # 13 / 15 if(id.type=='pad') Midi.sendMessage(note,5,id) else Midi.sendMessage(note,15,id) return @yellowLed=(note,id)=> Midi.sendMessage(note,62,id) return @amberLed=(note,id)=> # 29 # console.log(note,id) if(id.type=='pad') Midi.sendMessage(note,1,id) else Midi.sendMessage(note,29,id) return @offLed=(note,id)=> Midi.sendMessage(note,12,id) return module.exports = Midi
54104
# # Provide easy way to connect to the midi controler # @author : <NAME> / @Makio64 / makiopolis.com # Signal = require('signals') class Midi @onInit = new Signal() @onMessage = new Signal() @XL1 = {in:'-909041163',out:'606894372',type:'xl'} @XL2 = {in:'1764102944',out:'-1845450469',type:'xl'} @PAD = {in:'879598748',out:'-324232190',type:'pad'} @init=()=> @domElement = document.createElement('div') @domElement.className = 'midi' # document.body.appendChild @domElement if(navigator.requestMIDIAccess) navigator.requestMIDIAccess({sysex: false}).then(@onMIDISuccess, @onMIDIFailure) else alert("No MIDI support in your browser.") return @onMIDISuccess=(midiAccess)=> detected = 0 @midi = midiAccess @inputs = [] @outputs = [] @midi.inputs.forEach( ( port, key )=> # console.log('midi in', port.id, port.name) # console.log(port) input = port input.onmidimessage = @onMIDIMessage @inputs.push(input) ) @midi.outputs.forEach( ( port, key )=> # console.log('midi out', port.id, port.name) @outputs.push(port) ) console.log('[MIDI] INIT:',@midi.inputs.size,@midi.outputs.size) @allButton(15,@XL1) @allButton(15,@XL2) @allButton(5,@PAD) @onInit.dispatch() return @onMIDIFailure=(error)=> console.log("No access to MIDI devices or your browser doesn't support WebMIDI API. Please use WebMIDIAPIShim " + error) return @onMIDIMessage=(message)=> data = message.data cmd = data[0] >> 4 channel = data[0] & 0xf type = data[0] & 0xf0 note = data[1] velocity = data[2]/127 id = message.target.id s = '' s += 'cmd: '+cmd+'<br />' s += 'channel: '+channel+'<br />' s += 'type: '+type+'<br />' s += 'note: '+note+'<br />' s += 'velocity: '+velocity+'<br />' @domElement.innerHTML = s console.log("NOTE:",note) @onMessage.dispatch({id:id,data:data,cmd:cmd,channel:channel,type:type,note:note,velocity:velocity}) return # Send message to control midi ( light for example ) @sendMessage=(note,value,id)=> for i in [0...@outputs.length] if(@outputs[i].id!=id.out) continue if(note >= 41 || id.type == 'pad' ) @outputs[i].send( [144,note,value] ) else @outputs[i].send( [240, 0, 32, 41, 2, 17, 120, 0, note, value, 247] ) return @allButton=(value,id)=> if(id.type == 'xl') for i in [0...4] @sendMessage(41+i, value,id) @sendMessage(73+i, value,id) @sendMessage(57+i, value,id) @sendMessage(89+i, value,id) else for x in [1..9] for y in [1..8] @sendMessage(x+y*10, value, id) # if(x<9) # @sendMessage(x+104, value, id) return @greenLed=(note,id)=> # 28 / 60 Midi.sendMessage(note,60,id) return @redLed=(note,id)=> # 13 / 15 if(id.type=='pad') Midi.sendMessage(note,5,id) else Midi.sendMessage(note,15,id) return @yellowLed=(note,id)=> Midi.sendMessage(note,62,id) return @amberLed=(note,id)=> # 29 # console.log(note,id) if(id.type=='pad') Midi.sendMessage(note,1,id) else Midi.sendMessage(note,29,id) return @offLed=(note,id)=> Midi.sendMessage(note,12,id) return module.exports = Midi
true
# # Provide easy way to connect to the midi controler # @author : PI:NAME:<NAME>END_PI / @Makio64 / makiopolis.com # Signal = require('signals') class Midi @onInit = new Signal() @onMessage = new Signal() @XL1 = {in:'-909041163',out:'606894372',type:'xl'} @XL2 = {in:'1764102944',out:'-1845450469',type:'xl'} @PAD = {in:'879598748',out:'-324232190',type:'pad'} @init=()=> @domElement = document.createElement('div') @domElement.className = 'midi' # document.body.appendChild @domElement if(navigator.requestMIDIAccess) navigator.requestMIDIAccess({sysex: false}).then(@onMIDISuccess, @onMIDIFailure) else alert("No MIDI support in your browser.") return @onMIDISuccess=(midiAccess)=> detected = 0 @midi = midiAccess @inputs = [] @outputs = [] @midi.inputs.forEach( ( port, key )=> # console.log('midi in', port.id, port.name) # console.log(port) input = port input.onmidimessage = @onMIDIMessage @inputs.push(input) ) @midi.outputs.forEach( ( port, key )=> # console.log('midi out', port.id, port.name) @outputs.push(port) ) console.log('[MIDI] INIT:',@midi.inputs.size,@midi.outputs.size) @allButton(15,@XL1) @allButton(15,@XL2) @allButton(5,@PAD) @onInit.dispatch() return @onMIDIFailure=(error)=> console.log("No access to MIDI devices or your browser doesn't support WebMIDI API. Please use WebMIDIAPIShim " + error) return @onMIDIMessage=(message)=> data = message.data cmd = data[0] >> 4 channel = data[0] & 0xf type = data[0] & 0xf0 note = data[1] velocity = data[2]/127 id = message.target.id s = '' s += 'cmd: '+cmd+'<br />' s += 'channel: '+channel+'<br />' s += 'type: '+type+'<br />' s += 'note: '+note+'<br />' s += 'velocity: '+velocity+'<br />' @domElement.innerHTML = s console.log("NOTE:",note) @onMessage.dispatch({id:id,data:data,cmd:cmd,channel:channel,type:type,note:note,velocity:velocity}) return # Send message to control midi ( light for example ) @sendMessage=(note,value,id)=> for i in [0...@outputs.length] if(@outputs[i].id!=id.out) continue if(note >= 41 || id.type == 'pad' ) @outputs[i].send( [144,note,value] ) else @outputs[i].send( [240, 0, 32, 41, 2, 17, 120, 0, note, value, 247] ) return @allButton=(value,id)=> if(id.type == 'xl') for i in [0...4] @sendMessage(41+i, value,id) @sendMessage(73+i, value,id) @sendMessage(57+i, value,id) @sendMessage(89+i, value,id) else for x in [1..9] for y in [1..8] @sendMessage(x+y*10, value, id) # if(x<9) # @sendMessage(x+104, value, id) return @greenLed=(note,id)=> # 28 / 60 Midi.sendMessage(note,60,id) return @redLed=(note,id)=> # 13 / 15 if(id.type=='pad') Midi.sendMessage(note,5,id) else Midi.sendMessage(note,15,id) return @yellowLed=(note,id)=> Midi.sendMessage(note,62,id) return @amberLed=(note,id)=> # 29 # console.log(note,id) if(id.type=='pad') Midi.sendMessage(note,1,id) else Midi.sendMessage(note,29,id) return @offLed=(note,id)=> Midi.sendMessage(note,12,id) return module.exports = Midi
[ { "context": "ayerData.stats.packStats\n $scope.sortChampKey = 'winRate'\n $scope.reverse = true\n $scope.$watch(\n ->\n", "end": 253, "score": 0.9920707941055298, "start": 246, "tag": "KEY", "value": "winRate" }, { "context": "ame)->\n if urlname is 'flame'\n urlname = 'flameprincess'\n else if urlname is 'princessbubblegum'\n ", "end": 1058, "score": 0.979232132434845, "start": 1045, "tag": "USERNAME", "value": "flameprincess" }, { "context": "urlname = 'flameprincess'\n else if urlname is 'princessbubblegum'\n urlname = 'pb'\n url = \"http://i.cdn.tur", "end": 1101, "score": 0.9972014427185059, "start": 1084, "tag": "USERNAME", "value": "princessbubblegum" }, { "context": "f urlname is 'princessbubblegum'\n urlname = 'pb'\n url = \"http://i.cdn.turner.com/toon/games/ad", "end": 1122, "score": 0.6776943802833557, "start": 1120, "tag": "USERNAME", "value": "pb" } ]
client/app/profile/profile.controller.coffee
johnttan/spicybattle
0
'use strict' angular.module 'spicyPartyApp' .controller 'ProfileCtrl', ($scope, PlayerData) -> $scope.message = 'Hello' $scope.champStats = PlayerData.stats.champStats $scope.packStats = PlayerData.stats.packStats $scope.sortChampKey = 'winRate' $scope.reverse = true $scope.$watch( -> PlayerData.stats , -> $scope.champStats = _.map(PlayerData.stats.champStats, (el, key)-> return {name: key, stats: el} ) $scope.packStats = _.map(PlayerData.stats.packStats, (el, key)-> return {name: key, stats: el} ) _.each($scope.champStats, (el)-> if not Array.isArray(el.stats.belts) el.stats.belts = _.map(el.stats.belts, (el1, key)-> return {name: key, games: el1} ) ) $scope.gamesAnalyzed = PlayerData.stats.gamesAnalyzed ) $scope.$watch( -> PlayerData.tier , -> $scope.tier = PlayerData.tier ) $scope.avatarURL = (urlname)-> if urlname is 'flame' urlname = 'flameprincess' else if urlname is 'princessbubblegum' urlname = 'pb' url = "http://i.cdn.turner.com/toon/games/adventuretime/adventure-time-battle-party/assets/img/champions-icon-" + urlname + ".jpg" return url $scope.changeSortKey = (key)-> if key is $scope.sortChampKey $scope.reverse = !$scope.reverse else $scope.sortChampKey = key $scope.sortChamps = (el)-> if $scope.sortChampKey is 'winRate' if el.stats.wins is 0 return -el.stats.losses else return el.stats.averages.wins else if $scope.sortChampKey is 'wins' or $scope.sortChampKey is 'losses' return el.stats[$scope.sortChampKey] else return el.stats.averages[$scope.sortChampKey] $scope.formatPack = (pack)-> if pack splitUp = pack.split('_') if splitUp[2] return splitUp[1] + ' ' + splitUp[2] else return splitUp[1]
5824
'use strict' angular.module 'spicyPartyApp' .controller 'ProfileCtrl', ($scope, PlayerData) -> $scope.message = 'Hello' $scope.champStats = PlayerData.stats.champStats $scope.packStats = PlayerData.stats.packStats $scope.sortChampKey = '<KEY>' $scope.reverse = true $scope.$watch( -> PlayerData.stats , -> $scope.champStats = _.map(PlayerData.stats.champStats, (el, key)-> return {name: key, stats: el} ) $scope.packStats = _.map(PlayerData.stats.packStats, (el, key)-> return {name: key, stats: el} ) _.each($scope.champStats, (el)-> if not Array.isArray(el.stats.belts) el.stats.belts = _.map(el.stats.belts, (el1, key)-> return {name: key, games: el1} ) ) $scope.gamesAnalyzed = PlayerData.stats.gamesAnalyzed ) $scope.$watch( -> PlayerData.tier , -> $scope.tier = PlayerData.tier ) $scope.avatarURL = (urlname)-> if urlname is 'flame' urlname = 'flameprincess' else if urlname is 'princessbubblegum' urlname = 'pb' url = "http://i.cdn.turner.com/toon/games/adventuretime/adventure-time-battle-party/assets/img/champions-icon-" + urlname + ".jpg" return url $scope.changeSortKey = (key)-> if key is $scope.sortChampKey $scope.reverse = !$scope.reverse else $scope.sortChampKey = key $scope.sortChamps = (el)-> if $scope.sortChampKey is 'winRate' if el.stats.wins is 0 return -el.stats.losses else return el.stats.averages.wins else if $scope.sortChampKey is 'wins' or $scope.sortChampKey is 'losses' return el.stats[$scope.sortChampKey] else return el.stats.averages[$scope.sortChampKey] $scope.formatPack = (pack)-> if pack splitUp = pack.split('_') if splitUp[2] return splitUp[1] + ' ' + splitUp[2] else return splitUp[1]
true
'use strict' angular.module 'spicyPartyApp' .controller 'ProfileCtrl', ($scope, PlayerData) -> $scope.message = 'Hello' $scope.champStats = PlayerData.stats.champStats $scope.packStats = PlayerData.stats.packStats $scope.sortChampKey = 'PI:KEY:<KEY>END_PI' $scope.reverse = true $scope.$watch( -> PlayerData.stats , -> $scope.champStats = _.map(PlayerData.stats.champStats, (el, key)-> return {name: key, stats: el} ) $scope.packStats = _.map(PlayerData.stats.packStats, (el, key)-> return {name: key, stats: el} ) _.each($scope.champStats, (el)-> if not Array.isArray(el.stats.belts) el.stats.belts = _.map(el.stats.belts, (el1, key)-> return {name: key, games: el1} ) ) $scope.gamesAnalyzed = PlayerData.stats.gamesAnalyzed ) $scope.$watch( -> PlayerData.tier , -> $scope.tier = PlayerData.tier ) $scope.avatarURL = (urlname)-> if urlname is 'flame' urlname = 'flameprincess' else if urlname is 'princessbubblegum' urlname = 'pb' url = "http://i.cdn.turner.com/toon/games/adventuretime/adventure-time-battle-party/assets/img/champions-icon-" + urlname + ".jpg" return url $scope.changeSortKey = (key)-> if key is $scope.sortChampKey $scope.reverse = !$scope.reverse else $scope.sortChampKey = key $scope.sortChamps = (el)-> if $scope.sortChampKey is 'winRate' if el.stats.wins is 0 return -el.stats.losses else return el.stats.averages.wins else if $scope.sortChampKey is 'wins' or $scope.sortChampKey is 'losses' return el.stats[$scope.sortChampKey] else return el.stats.averages[$scope.sortChampKey] $scope.formatPack = (pack)-> if pack splitUp = pack.split('_') if splitUp[2] return splitUp[1] + ' ' + splitUp[2] else return splitUp[1]
[ { "context": "nt = {start: {c: 3,r: 0}, end: {c: 4,r: 0}, name:\"Zuchini\", color:\"#008045\"}\n {\n mocks: mocks\n ", "end": 613, "score": 0.9860665798187256, "start": 606, "tag": "NAME", "value": "Zuchini" }, { "context": "et up mocks\n topic.mocks.newText =\"Rosemary\"\n topic.mocks.text.observatory = n", "end": 7130, "score": 0.9985118508338928, "start": 7122, "tag": "NAME", "value": "Rosemary" } ]
test/unit/plantWidget-test.coffee
TheSoftwareGreenhouse/ourSquareFeet
1
vows = require 'vows' assert = require 'assert' ObservatoryModule = require '../../server/public/javascript/observatory.coffee' PlantWidgetModule = require '../../server/public/javascript/ui/plantWidget.coffee' vows.describe('PlantWidget').addBatch({ 'when a new PlantWidget is created': { topic: () -> mocks = {} mocks.layoutEngine = { getLeftForPlantInColumn: () -> 105 columnWidth: 100 plantWidth: 90 getTopForPlantInRow: () -> 105 rowHeight: 100 plantHeight: 90 } mocks.plant = {start: {c: 3,r: 0}, end: {c: 4,r: 0}, name:"Zuchini", color:"#008045"} { mocks: mocks sut: new PlantWidgetModule.PlantWidget(mocks.layoutEngine, mocks.plant) actuals: {} } 'then the plant has a name': (topic) -> assert.isString topic.sut.name 'then the plant has a color': (topic) -> assert.isString topic.sut.color 'then the plant widget has an isAt function': (topic) -> assert.isFunction topic.sut.isAt 'then the plant has a top': (topic) -> assert.isNumber topic.sut.top 'then the plant has a left': (topic) -> assert.isNumber topic.sut.left 'then the plant has a width': (topic) -> assert.isNumber topic.sut.width 'then the plant has a height': (topic) -> assert.isNumber topic.sut.height 'then the widget has a children collection': (topic) -> assert.isObject topic.sut.children 'then the widget has an add close Button method': (topic) -> assert.isFunction topic.sut.addCloseButtonWidget 'then the widget has a subscribe method': (topic) -> assert.isFunction topic.sut.subscribe 'then the widget has a remove method': (topic) -> assert.isFunction topic.sut.remove 'then the widget has a primitives collection': (topic) -> assert.isObject topic.sut.primitives 'then the widget has a addRect function': (topic) -> assert.isFunction topic.sut.addRect 'then the widget has a addText function': (topic) -> assert.isFunction topic.sut.addText 'the the widget has a applyAttributes function': (topic) -> assert.isFunction topic.sut.applyAttributes 'the the widget has a onEditName function': (topic) -> assert.isFunction topic.sut.onEditName 'the the widget has a plant property': (topic) -> assert.isObject topic.sut.plant # test functionality 'then the name is correct': (topic) -> assert.equal topic.sut.name, "Zuchini" 'then the color is correct': (topic) -> assert.equal topic.sut.color, "#008045" 'then the widget is at the plant start and end': (topic) -> assert.isTrue topic.sut.isAt(topic.mocks.plant.start) assert.isTrue topic.sut.isAt(topic.mocks.plant.end) 'then the top is correct': (topic) -> assert.equal topic.sut.top, 105 'then the left is correct': (topic) -> assert.equal topic.sut.left, 105 'then the width is correct': (topic) -> assert.equal topic.sut.width, 190 'then the height is correct': (topic) -> assert.equal topic.sut.height, 90 'then the centre of the row is correct': (topic) -> assert.equal topic.sut.centerRow, 150 'then the centre of the column is correct': (topic) -> assert.equal topic.sut.centerColumn, 200 'then the plant is correct': (topic) -> assert.equal topic.sut.plant, topic.mocks.plant 'and a close button widget is added': { topic: (topic) -> closeButtonWidget = { subscriptions: {} subscribedTo: (eventName) -> @.subscriptions[eventName] != undefined subscribe: (eventName, action) -> @.subscriptions[eventName] = action publish: (eventName) -> @.subscriptions[eventName].call(null) removed: false remove: () -> @.removed = true hidden: false hide: () -> @.hidden = true } topic.mocks.closeButtonWidget = closeButtonWidget topic.sut.addCloseButtonWidget closeButtonWidget topic "then the widget has subscribed to close button widget's click event": (topic) -> assert.isTrue topic.mocks.closeButtonWidget.subscribedTo('click') "then the widget hides the close button widget": (topic) -> assert.isTrue topic.mocks.closeButtonWidget.hidden "and the close button widget is clicked": { topic: (topic) -> topic.actuals.plant = null topic.sut.subscribe "delete", (result) -> topic.actuals.plant = result topic.mocks.closeButtonWidget.publish 'click' topic "then the delete event is raised by the plant": (topic)-> assert.isNotNull topic.actuals.plant } "and a rect is added to the widget": { topic: (topic) -> topic.mocks.rect = { onMouseOver: null onMouseOut: null hover: (over, out) -> @.onMouseOut = out @.onMouseOver = over } topic.sut.addRect topic.mocks.rect topic "then the rect exists in the primitives": (topic) -> assert.equal topic.sut.primitives.rect, topic.mocks.rect "the the hover event is set": (topic) -> assert.isNotNull topic.mocks.rect.onMouseOver assert.isNotNull topic.mocks.rect.onMouseOut "and the text is added to the widget": { topic: (topic) -> topic.mocks.text = { onMouseOver: null onMouseOut: null hover: (over, out) -> @.onMouseOut = out @.onMouseOver = over } topic.sut.addText topic.mocks.text topic "then the text exists in the primitives": (topic) -> assert.equal topic.sut.primitives.text, topic.mocks.text "then the hover event is set": (topic) -> assert.isNotNull topic.mocks.text.onMouseOver assert.isNotNull topic.mocks.text.onMouseOut "and the rect and the text are set with no attributes": { topic: (topic) -> topic.mocks.rect.newAttr = null topic.mocks.rect.attr = (attr) -> @.newAttr = attr topic.mocks.text.newAttr = null topic.mocks.text.attr = (attr) -> @.newAttr = attr topic "and attributes are applied" : { topic: (topic) -> topic.mocks.textAttr = {} topic.mocks.rectAttr = {} topic.sut.applyAttributes { rect: topic.mocks.rectAttr text: topic.mocks.textAttr } topic "then the rect has new attributes": (topic) -> assert.equal topic.mocks.rect.newAttr, topic.mocks.rectAttr "then the text has new attributes": (topic) -> assert.equal topic.mocks.text.newAttr, topic.mocks.textAttr } "and the text raises a changed event": { topic: (topic) -> # set up mocks topic.mocks.newText ="Rosemary" topic.mocks.text.observatory = new ObservatoryModule.Observatory(topic.mocks.text) topic.mocks.text.onChange = (callback) -> topic.mocks.text.observatory.subscribe "changed", callback # prepare actuals topic.actuals.newName = null # subscribe topic.sut.onEditName (newName) -> topic.actuals.newName = newName # publish topic.mocks.text.observatory.publish "changed", topic.mocks.newText topic "then the new name is raised on the EditName event": (topic) -> assert.equal topic.actuals.newName, topic.mocks.newText } } "and the plant widget is removed": { topic: (topic) -> topic.mocks.rect.removed = false topic.mocks.rect.remove = () -> @.removed = true topic.mocks.text.removed = false topic.mocks.text.remove = () -> @.removed = true topic.sut.remove() topic "then the rect is removed": (topic) -> assert.isTrue topic.mocks.rect.removed "then the text is removed": (topic) -> assert.isTrue topic.mocks.text.removed "then the close button is removed": (topic) -> assert.isTrue topic.mocks.closeButtonWidget.removed } } } } } }).export module
107304
vows = require 'vows' assert = require 'assert' ObservatoryModule = require '../../server/public/javascript/observatory.coffee' PlantWidgetModule = require '../../server/public/javascript/ui/plantWidget.coffee' vows.describe('PlantWidget').addBatch({ 'when a new PlantWidget is created': { topic: () -> mocks = {} mocks.layoutEngine = { getLeftForPlantInColumn: () -> 105 columnWidth: 100 plantWidth: 90 getTopForPlantInRow: () -> 105 rowHeight: 100 plantHeight: 90 } mocks.plant = {start: {c: 3,r: 0}, end: {c: 4,r: 0}, name:"<NAME>", color:"#008045"} { mocks: mocks sut: new PlantWidgetModule.PlantWidget(mocks.layoutEngine, mocks.plant) actuals: {} } 'then the plant has a name': (topic) -> assert.isString topic.sut.name 'then the plant has a color': (topic) -> assert.isString topic.sut.color 'then the plant widget has an isAt function': (topic) -> assert.isFunction topic.sut.isAt 'then the plant has a top': (topic) -> assert.isNumber topic.sut.top 'then the plant has a left': (topic) -> assert.isNumber topic.sut.left 'then the plant has a width': (topic) -> assert.isNumber topic.sut.width 'then the plant has a height': (topic) -> assert.isNumber topic.sut.height 'then the widget has a children collection': (topic) -> assert.isObject topic.sut.children 'then the widget has an add close Button method': (topic) -> assert.isFunction topic.sut.addCloseButtonWidget 'then the widget has a subscribe method': (topic) -> assert.isFunction topic.sut.subscribe 'then the widget has a remove method': (topic) -> assert.isFunction topic.sut.remove 'then the widget has a primitives collection': (topic) -> assert.isObject topic.sut.primitives 'then the widget has a addRect function': (topic) -> assert.isFunction topic.sut.addRect 'then the widget has a addText function': (topic) -> assert.isFunction topic.sut.addText 'the the widget has a applyAttributes function': (topic) -> assert.isFunction topic.sut.applyAttributes 'the the widget has a onEditName function': (topic) -> assert.isFunction topic.sut.onEditName 'the the widget has a plant property': (topic) -> assert.isObject topic.sut.plant # test functionality 'then the name is correct': (topic) -> assert.equal topic.sut.name, "Zuchini" 'then the color is correct': (topic) -> assert.equal topic.sut.color, "#008045" 'then the widget is at the plant start and end': (topic) -> assert.isTrue topic.sut.isAt(topic.mocks.plant.start) assert.isTrue topic.sut.isAt(topic.mocks.plant.end) 'then the top is correct': (topic) -> assert.equal topic.sut.top, 105 'then the left is correct': (topic) -> assert.equal topic.sut.left, 105 'then the width is correct': (topic) -> assert.equal topic.sut.width, 190 'then the height is correct': (topic) -> assert.equal topic.sut.height, 90 'then the centre of the row is correct': (topic) -> assert.equal topic.sut.centerRow, 150 'then the centre of the column is correct': (topic) -> assert.equal topic.sut.centerColumn, 200 'then the plant is correct': (topic) -> assert.equal topic.sut.plant, topic.mocks.plant 'and a close button widget is added': { topic: (topic) -> closeButtonWidget = { subscriptions: {} subscribedTo: (eventName) -> @.subscriptions[eventName] != undefined subscribe: (eventName, action) -> @.subscriptions[eventName] = action publish: (eventName) -> @.subscriptions[eventName].call(null) removed: false remove: () -> @.removed = true hidden: false hide: () -> @.hidden = true } topic.mocks.closeButtonWidget = closeButtonWidget topic.sut.addCloseButtonWidget closeButtonWidget topic "then the widget has subscribed to close button widget's click event": (topic) -> assert.isTrue topic.mocks.closeButtonWidget.subscribedTo('click') "then the widget hides the close button widget": (topic) -> assert.isTrue topic.mocks.closeButtonWidget.hidden "and the close button widget is clicked": { topic: (topic) -> topic.actuals.plant = null topic.sut.subscribe "delete", (result) -> topic.actuals.plant = result topic.mocks.closeButtonWidget.publish 'click' topic "then the delete event is raised by the plant": (topic)-> assert.isNotNull topic.actuals.plant } "and a rect is added to the widget": { topic: (topic) -> topic.mocks.rect = { onMouseOver: null onMouseOut: null hover: (over, out) -> @.onMouseOut = out @.onMouseOver = over } topic.sut.addRect topic.mocks.rect topic "then the rect exists in the primitives": (topic) -> assert.equal topic.sut.primitives.rect, topic.mocks.rect "the the hover event is set": (topic) -> assert.isNotNull topic.mocks.rect.onMouseOver assert.isNotNull topic.mocks.rect.onMouseOut "and the text is added to the widget": { topic: (topic) -> topic.mocks.text = { onMouseOver: null onMouseOut: null hover: (over, out) -> @.onMouseOut = out @.onMouseOver = over } topic.sut.addText topic.mocks.text topic "then the text exists in the primitives": (topic) -> assert.equal topic.sut.primitives.text, topic.mocks.text "then the hover event is set": (topic) -> assert.isNotNull topic.mocks.text.onMouseOver assert.isNotNull topic.mocks.text.onMouseOut "and the rect and the text are set with no attributes": { topic: (topic) -> topic.mocks.rect.newAttr = null topic.mocks.rect.attr = (attr) -> @.newAttr = attr topic.mocks.text.newAttr = null topic.mocks.text.attr = (attr) -> @.newAttr = attr topic "and attributes are applied" : { topic: (topic) -> topic.mocks.textAttr = {} topic.mocks.rectAttr = {} topic.sut.applyAttributes { rect: topic.mocks.rectAttr text: topic.mocks.textAttr } topic "then the rect has new attributes": (topic) -> assert.equal topic.mocks.rect.newAttr, topic.mocks.rectAttr "then the text has new attributes": (topic) -> assert.equal topic.mocks.text.newAttr, topic.mocks.textAttr } "and the text raises a changed event": { topic: (topic) -> # set up mocks topic.mocks.newText ="<NAME>" topic.mocks.text.observatory = new ObservatoryModule.Observatory(topic.mocks.text) topic.mocks.text.onChange = (callback) -> topic.mocks.text.observatory.subscribe "changed", callback # prepare actuals topic.actuals.newName = null # subscribe topic.sut.onEditName (newName) -> topic.actuals.newName = newName # publish topic.mocks.text.observatory.publish "changed", topic.mocks.newText topic "then the new name is raised on the EditName event": (topic) -> assert.equal topic.actuals.newName, topic.mocks.newText } } "and the plant widget is removed": { topic: (topic) -> topic.mocks.rect.removed = false topic.mocks.rect.remove = () -> @.removed = true topic.mocks.text.removed = false topic.mocks.text.remove = () -> @.removed = true topic.sut.remove() topic "then the rect is removed": (topic) -> assert.isTrue topic.mocks.rect.removed "then the text is removed": (topic) -> assert.isTrue topic.mocks.text.removed "then the close button is removed": (topic) -> assert.isTrue topic.mocks.closeButtonWidget.removed } } } } } }).export module
true
vows = require 'vows' assert = require 'assert' ObservatoryModule = require '../../server/public/javascript/observatory.coffee' PlantWidgetModule = require '../../server/public/javascript/ui/plantWidget.coffee' vows.describe('PlantWidget').addBatch({ 'when a new PlantWidget is created': { topic: () -> mocks = {} mocks.layoutEngine = { getLeftForPlantInColumn: () -> 105 columnWidth: 100 plantWidth: 90 getTopForPlantInRow: () -> 105 rowHeight: 100 plantHeight: 90 } mocks.plant = {start: {c: 3,r: 0}, end: {c: 4,r: 0}, name:"PI:NAME:<NAME>END_PI", color:"#008045"} { mocks: mocks sut: new PlantWidgetModule.PlantWidget(mocks.layoutEngine, mocks.plant) actuals: {} } 'then the plant has a name': (topic) -> assert.isString topic.sut.name 'then the plant has a color': (topic) -> assert.isString topic.sut.color 'then the plant widget has an isAt function': (topic) -> assert.isFunction topic.sut.isAt 'then the plant has a top': (topic) -> assert.isNumber topic.sut.top 'then the plant has a left': (topic) -> assert.isNumber topic.sut.left 'then the plant has a width': (topic) -> assert.isNumber topic.sut.width 'then the plant has a height': (topic) -> assert.isNumber topic.sut.height 'then the widget has a children collection': (topic) -> assert.isObject topic.sut.children 'then the widget has an add close Button method': (topic) -> assert.isFunction topic.sut.addCloseButtonWidget 'then the widget has a subscribe method': (topic) -> assert.isFunction topic.sut.subscribe 'then the widget has a remove method': (topic) -> assert.isFunction topic.sut.remove 'then the widget has a primitives collection': (topic) -> assert.isObject topic.sut.primitives 'then the widget has a addRect function': (topic) -> assert.isFunction topic.sut.addRect 'then the widget has a addText function': (topic) -> assert.isFunction topic.sut.addText 'the the widget has a applyAttributes function': (topic) -> assert.isFunction topic.sut.applyAttributes 'the the widget has a onEditName function': (topic) -> assert.isFunction topic.sut.onEditName 'the the widget has a plant property': (topic) -> assert.isObject topic.sut.plant # test functionality 'then the name is correct': (topic) -> assert.equal topic.sut.name, "Zuchini" 'then the color is correct': (topic) -> assert.equal topic.sut.color, "#008045" 'then the widget is at the plant start and end': (topic) -> assert.isTrue topic.sut.isAt(topic.mocks.plant.start) assert.isTrue topic.sut.isAt(topic.mocks.plant.end) 'then the top is correct': (topic) -> assert.equal topic.sut.top, 105 'then the left is correct': (topic) -> assert.equal topic.sut.left, 105 'then the width is correct': (topic) -> assert.equal topic.sut.width, 190 'then the height is correct': (topic) -> assert.equal topic.sut.height, 90 'then the centre of the row is correct': (topic) -> assert.equal topic.sut.centerRow, 150 'then the centre of the column is correct': (topic) -> assert.equal topic.sut.centerColumn, 200 'then the plant is correct': (topic) -> assert.equal topic.sut.plant, topic.mocks.plant 'and a close button widget is added': { topic: (topic) -> closeButtonWidget = { subscriptions: {} subscribedTo: (eventName) -> @.subscriptions[eventName] != undefined subscribe: (eventName, action) -> @.subscriptions[eventName] = action publish: (eventName) -> @.subscriptions[eventName].call(null) removed: false remove: () -> @.removed = true hidden: false hide: () -> @.hidden = true } topic.mocks.closeButtonWidget = closeButtonWidget topic.sut.addCloseButtonWidget closeButtonWidget topic "then the widget has subscribed to close button widget's click event": (topic) -> assert.isTrue topic.mocks.closeButtonWidget.subscribedTo('click') "then the widget hides the close button widget": (topic) -> assert.isTrue topic.mocks.closeButtonWidget.hidden "and the close button widget is clicked": { topic: (topic) -> topic.actuals.plant = null topic.sut.subscribe "delete", (result) -> topic.actuals.plant = result topic.mocks.closeButtonWidget.publish 'click' topic "then the delete event is raised by the plant": (topic)-> assert.isNotNull topic.actuals.plant } "and a rect is added to the widget": { topic: (topic) -> topic.mocks.rect = { onMouseOver: null onMouseOut: null hover: (over, out) -> @.onMouseOut = out @.onMouseOver = over } topic.sut.addRect topic.mocks.rect topic "then the rect exists in the primitives": (topic) -> assert.equal topic.sut.primitives.rect, topic.mocks.rect "the the hover event is set": (topic) -> assert.isNotNull topic.mocks.rect.onMouseOver assert.isNotNull topic.mocks.rect.onMouseOut "and the text is added to the widget": { topic: (topic) -> topic.mocks.text = { onMouseOver: null onMouseOut: null hover: (over, out) -> @.onMouseOut = out @.onMouseOver = over } topic.sut.addText topic.mocks.text topic "then the text exists in the primitives": (topic) -> assert.equal topic.sut.primitives.text, topic.mocks.text "then the hover event is set": (topic) -> assert.isNotNull topic.mocks.text.onMouseOver assert.isNotNull topic.mocks.text.onMouseOut "and the rect and the text are set with no attributes": { topic: (topic) -> topic.mocks.rect.newAttr = null topic.mocks.rect.attr = (attr) -> @.newAttr = attr topic.mocks.text.newAttr = null topic.mocks.text.attr = (attr) -> @.newAttr = attr topic "and attributes are applied" : { topic: (topic) -> topic.mocks.textAttr = {} topic.mocks.rectAttr = {} topic.sut.applyAttributes { rect: topic.mocks.rectAttr text: topic.mocks.textAttr } topic "then the rect has new attributes": (topic) -> assert.equal topic.mocks.rect.newAttr, topic.mocks.rectAttr "then the text has new attributes": (topic) -> assert.equal topic.mocks.text.newAttr, topic.mocks.textAttr } "and the text raises a changed event": { topic: (topic) -> # set up mocks topic.mocks.newText ="PI:NAME:<NAME>END_PI" topic.mocks.text.observatory = new ObservatoryModule.Observatory(topic.mocks.text) topic.mocks.text.onChange = (callback) -> topic.mocks.text.observatory.subscribe "changed", callback # prepare actuals topic.actuals.newName = null # subscribe topic.sut.onEditName (newName) -> topic.actuals.newName = newName # publish topic.mocks.text.observatory.publish "changed", topic.mocks.newText topic "then the new name is raised on the EditName event": (topic) -> assert.equal topic.actuals.newName, topic.mocks.newText } } "and the plant widget is removed": { topic: (topic) -> topic.mocks.rect.removed = false topic.mocks.rect.remove = () -> @.removed = true topic.mocks.text.removed = false topic.mocks.text.remove = () -> @.removed = true topic.sut.remove() topic "then the rect is removed": (topic) -> assert.isTrue topic.mocks.rect.removed "then the text is removed": (topic) -> assert.isTrue topic.mocks.text.removed "then the close button is removed": (topic) -> assert.isTrue topic.mocks.closeButtonWidget.removed } } } } } }).export module
[ { "context": "offeeScript:\n# Node : http://github.com/ry/node\n# CoffeeScript : http://github.com/jashken", "end": 72, "score": 0.7964431047439575, "start": 70, "tag": "USERNAME", "value": "ry" }, { "context": ".com/ry/node\n# CoffeeScript : http://github.com/jashkenas/coffee-script\n#\n# In a terminal window:\n# $ cd ", "end": 124, "score": 0.9997246265411377, "start": 115, "tag": "USERNAME", "value": "jashkenas" }, { "context": "c OS X 10.5.8, Node 0.1.26, CoffeeScript 0.5.0\n#\n# Jeremy Ashkenas has included this script in CoffeeScript's exampl", "end": 317, "score": 0.9998471736907959, "start": 302, "tag": "NAME", "value": "Jeremy Ashkenas" }, { "context": "cript's examples directory:\n# http://github.com/jashkenas/coffee-script/blob/master/examples/web_server.cof", "end": 412, "score": 0.9996572732925415, "start": 403, "tag": "USERNAME", "value": "jashkenas" } ]
tools/webserver/node_modules/web_server.coffee
Deepak003/iLearn-ngQuiz
0
# Install Node and CoffeeScript: # Node : http://github.com/ry/node # CoffeeScript : http://github.com/jashkenas/coffee-script # # In a terminal window: # $ cd coffee-script # $ ./bin/node_coffee -r web_server.coffee # # Tested with Mac OS X 10.5.8, Node 0.1.26, CoffeeScript 0.5.0 # # Jeremy Ashkenas has included this script in CoffeeScript's examples directory: # http://github.com/jashkenas/coffee-script/blob/master/examples/web_server.coffee http: require "http" http.createServer( (req, res) -> res.sendHeader 200, {"Content-Type": "text/plain"} res.sendBody "Hello, World!" res.finish() ).listen 8000
217870
# Install Node and CoffeeScript: # Node : http://github.com/ry/node # CoffeeScript : http://github.com/jashkenas/coffee-script # # In a terminal window: # $ cd coffee-script # $ ./bin/node_coffee -r web_server.coffee # # Tested with Mac OS X 10.5.8, Node 0.1.26, CoffeeScript 0.5.0 # # <NAME> has included this script in CoffeeScript's examples directory: # http://github.com/jashkenas/coffee-script/blob/master/examples/web_server.coffee http: require "http" http.createServer( (req, res) -> res.sendHeader 200, {"Content-Type": "text/plain"} res.sendBody "Hello, World!" res.finish() ).listen 8000
true
# Install Node and CoffeeScript: # Node : http://github.com/ry/node # CoffeeScript : http://github.com/jashkenas/coffee-script # # In a terminal window: # $ cd coffee-script # $ ./bin/node_coffee -r web_server.coffee # # Tested with Mac OS X 10.5.8, Node 0.1.26, CoffeeScript 0.5.0 # # PI:NAME:<NAME>END_PI has included this script in CoffeeScript's examples directory: # http://github.com/jashkenas/coffee-script/blob/master/examples/web_server.coffee http: require "http" http.createServer( (req, res) -> res.sendHeader 200, {"Content-Type": "text/plain"} res.sendBody "Hello, World!" res.finish() ).listen 8000
[ { "context": " jQuery Waypoints - v2.0.5\nCopyright (c) 2011-2014 Caleb Troughton\nLicensed under the MIT license.\nhttps://github.co", "end": 98, "score": 0.9998784065246582, "start": 83, "tag": "NAME", "value": "Caleb Troughton" }, { "context": "ensed under the MIT license.\nhttps://github.com/imakewebthings/jquery-waypoints/blob/master/licenses.txt\n###\n((r", "end": 164, "score": 0.5343657732009888, "start": 152, "tag": "USERNAME", "value": "akewebthings" } ]
waypoints/shortcuts/sticky-elements/waypoints-sticky.coffee
sterlingcrispin/privacymap
152
### Sticky Elements Shortcut for jQuery Waypoints - v2.0.5 Copyright (c) 2011-2014 Caleb Troughton Licensed under the MIT license. https://github.com/imakewebthings/jquery-waypoints/blob/master/licenses.txt ### ((root, factory) -> if typeof define is 'function' and define.amd define ['jquery', 'waypoints'], factory else factory root.jQuery ) window, ($) -> # An extension of the waypoint defaults when calling the "sticky" method. # - wrapper: Each sticky element gets wrapped in another element. This # element acts as the actual waypoint and stays in the document flow, # leaving the sticky element to gain/lost fixed positioning freely without # effecting layout. "wrapper" is the HTML for this element. # - stuckClass: The class that is added to the sticky element when the # waypoint is reached. Users should style this class to add fixed # positioning and whatever other styles are necessary for their # particular design. defaults = wrapper: '<div class="sticky-wrapper" />' stuckClass: 'stuck' direction: 'down right' # Internal: Wraps the sticky elements in the sticky wrapper and returns the # wrapper elements. wrap = ($elements, options) -> $elements.wrap options.wrapper $parent = $elements.parent() $parent.data 'isWaypointStickyWrapper', true # .waypoint('sticky', [object]) # The sticky method is a shortcut method for a common UI pattern, sticky # elements. In its most common form, this pattern consists of an item that # is part of the normal document flow until it reaches the top of the # viewport, where it gains a fixed position state. # This shortcut does very little to actually create the sticky state. It only # adds a class to the element when it reaches the appropriate part of the # viewport. It is the job of the user to define the styles for this "stuck" # state in CSS. There are many different ways one could style their sticky # elements, and trying to implement all of them in JS is futile. Everyone's # design is different. # This shortcut does take care of the most common pitfall in previous # versions of Waypoints: Using the sticky element as the waypoint. Fixed # position elements do not work well as waypoints since their position in # the document is constantly changing as the user scrolls (and their # position relative to the viewport never does, which is the whole point of # Waypoints). This shortcut will create a wrapper element around the sticky # element that acts as the actual waypoint, as well as a placeholder for the # waypoint in the document flow, as fixed positioning takes an element out # of flow and would otherwise effect the page layout. Users are recommended # to define any margins on their sticky elements as margins on this # wrapper instead. $.waypoints 'extendFn', 'sticky', (opt) -> options = $.extend {}, $.fn.waypoint.defaults, defaults, opt $wrap = wrap @, options originalHandler = options.handler options.handler = (direction) -> $sticky = $(@).children ':first' shouldBeStuck = options.direction.indexOf(direction) != -1 $sticky.toggleClass options.stuckClass, shouldBeStuck $wrap.height if shouldBeStuck then $sticky.outerHeight() else '' originalHandler.call @, direction if originalHandler? $wrap.waypoint options @data 'stuckClass', options.stuckClass # .waypoint('unsticky') # Undoes everything done within the sticky shortcut by removing the parent # sticky wrapper, destroying the waypoint, and removing any stuck class # that may be applied. $.waypoints 'extendFn', 'unsticky', () -> $parent = @parent() return @ unless $parent.data('isWaypointStickyWrapper') $parent.waypoint 'destroy' @unwrap() @removeClass @data 'stuckClass'
105177
### Sticky Elements Shortcut for jQuery Waypoints - v2.0.5 Copyright (c) 2011-2014 <NAME> Licensed under the MIT license. https://github.com/imakewebthings/jquery-waypoints/blob/master/licenses.txt ### ((root, factory) -> if typeof define is 'function' and define.amd define ['jquery', 'waypoints'], factory else factory root.jQuery ) window, ($) -> # An extension of the waypoint defaults when calling the "sticky" method. # - wrapper: Each sticky element gets wrapped in another element. This # element acts as the actual waypoint and stays in the document flow, # leaving the sticky element to gain/lost fixed positioning freely without # effecting layout. "wrapper" is the HTML for this element. # - stuckClass: The class that is added to the sticky element when the # waypoint is reached. Users should style this class to add fixed # positioning and whatever other styles are necessary for their # particular design. defaults = wrapper: '<div class="sticky-wrapper" />' stuckClass: 'stuck' direction: 'down right' # Internal: Wraps the sticky elements in the sticky wrapper and returns the # wrapper elements. wrap = ($elements, options) -> $elements.wrap options.wrapper $parent = $elements.parent() $parent.data 'isWaypointStickyWrapper', true # .waypoint('sticky', [object]) # The sticky method is a shortcut method for a common UI pattern, sticky # elements. In its most common form, this pattern consists of an item that # is part of the normal document flow until it reaches the top of the # viewport, where it gains a fixed position state. # This shortcut does very little to actually create the sticky state. It only # adds a class to the element when it reaches the appropriate part of the # viewport. It is the job of the user to define the styles for this "stuck" # state in CSS. There are many different ways one could style their sticky # elements, and trying to implement all of them in JS is futile. Everyone's # design is different. # This shortcut does take care of the most common pitfall in previous # versions of Waypoints: Using the sticky element as the waypoint. Fixed # position elements do not work well as waypoints since their position in # the document is constantly changing as the user scrolls (and their # position relative to the viewport never does, which is the whole point of # Waypoints). This shortcut will create a wrapper element around the sticky # element that acts as the actual waypoint, as well as a placeholder for the # waypoint in the document flow, as fixed positioning takes an element out # of flow and would otherwise effect the page layout. Users are recommended # to define any margins on their sticky elements as margins on this # wrapper instead. $.waypoints 'extendFn', 'sticky', (opt) -> options = $.extend {}, $.fn.waypoint.defaults, defaults, opt $wrap = wrap @, options originalHandler = options.handler options.handler = (direction) -> $sticky = $(@).children ':first' shouldBeStuck = options.direction.indexOf(direction) != -1 $sticky.toggleClass options.stuckClass, shouldBeStuck $wrap.height if shouldBeStuck then $sticky.outerHeight() else '' originalHandler.call @, direction if originalHandler? $wrap.waypoint options @data 'stuckClass', options.stuckClass # .waypoint('unsticky') # Undoes everything done within the sticky shortcut by removing the parent # sticky wrapper, destroying the waypoint, and removing any stuck class # that may be applied. $.waypoints 'extendFn', 'unsticky', () -> $parent = @parent() return @ unless $parent.data('isWaypointStickyWrapper') $parent.waypoint 'destroy' @unwrap() @removeClass @data 'stuckClass'
true
### Sticky Elements Shortcut for jQuery Waypoints - v2.0.5 Copyright (c) 2011-2014 PI:NAME:<NAME>END_PI Licensed under the MIT license. https://github.com/imakewebthings/jquery-waypoints/blob/master/licenses.txt ### ((root, factory) -> if typeof define is 'function' and define.amd define ['jquery', 'waypoints'], factory else factory root.jQuery ) window, ($) -> # An extension of the waypoint defaults when calling the "sticky" method. # - wrapper: Each sticky element gets wrapped in another element. This # element acts as the actual waypoint and stays in the document flow, # leaving the sticky element to gain/lost fixed positioning freely without # effecting layout. "wrapper" is the HTML for this element. # - stuckClass: The class that is added to the sticky element when the # waypoint is reached. Users should style this class to add fixed # positioning and whatever other styles are necessary for their # particular design. defaults = wrapper: '<div class="sticky-wrapper" />' stuckClass: 'stuck' direction: 'down right' # Internal: Wraps the sticky elements in the sticky wrapper and returns the # wrapper elements. wrap = ($elements, options) -> $elements.wrap options.wrapper $parent = $elements.parent() $parent.data 'isWaypointStickyWrapper', true # .waypoint('sticky', [object]) # The sticky method is a shortcut method for a common UI pattern, sticky # elements. In its most common form, this pattern consists of an item that # is part of the normal document flow until it reaches the top of the # viewport, where it gains a fixed position state. # This shortcut does very little to actually create the sticky state. It only # adds a class to the element when it reaches the appropriate part of the # viewport. It is the job of the user to define the styles for this "stuck" # state in CSS. There are many different ways one could style their sticky # elements, and trying to implement all of them in JS is futile. Everyone's # design is different. # This shortcut does take care of the most common pitfall in previous # versions of Waypoints: Using the sticky element as the waypoint. Fixed # position elements do not work well as waypoints since their position in # the document is constantly changing as the user scrolls (and their # position relative to the viewport never does, which is the whole point of # Waypoints). This shortcut will create a wrapper element around the sticky # element that acts as the actual waypoint, as well as a placeholder for the # waypoint in the document flow, as fixed positioning takes an element out # of flow and would otherwise effect the page layout. Users are recommended # to define any margins on their sticky elements as margins on this # wrapper instead. $.waypoints 'extendFn', 'sticky', (opt) -> options = $.extend {}, $.fn.waypoint.defaults, defaults, opt $wrap = wrap @, options originalHandler = options.handler options.handler = (direction) -> $sticky = $(@).children ':first' shouldBeStuck = options.direction.indexOf(direction) != -1 $sticky.toggleClass options.stuckClass, shouldBeStuck $wrap.height if shouldBeStuck then $sticky.outerHeight() else '' originalHandler.call @, direction if originalHandler? $wrap.waypoint options @data 'stuckClass', options.stuckClass # .waypoint('unsticky') # Undoes everything done within the sticky shortcut by removing the parent # sticky wrapper, destroying the waypoint, and removing any stuck class # that may be applied. $.waypoints 'extendFn', 'unsticky', () -> $parent = @parent() return @ unless $parent.data('isWaypointStickyWrapper') $parent.waypoint 'destroy' @unwrap() @removeClass @data 'stuckClass'
[ { "context": "CodeFileTypes(newValue)\n\n # configKeyPath = \"#{pkgName}.executionSettings.objectCodeFileType\"\n # if (ob", "end": 5043, "score": 0.867139995098114, "start": 5034, "tag": "KEY", "value": "pkgName}." }, { "context": " # configKeyPath = \"#{pkgName}.executionSettings.objectCodeFileType\"\n # if (objectCodeFileType = atom.config.get(c", "end": 5079, "score": 0.7091010808944702, "start": 5061, "tag": "KEY", "value": "objectCodeFileType" }, { "context": "ectCodeFileType(newValue)\n\n configKeyPath = \"#{pkgName}.executionSettings.executionCommandPatterns\"\n if", "end": 5432, "score": 0.8651933073997498, "start": 5423, "tag": "KEY", "value": "pkgName}." }, { "context": "\n configKeyPath = \"#{pkgName}.executionSettings.executionCommandPatterns\"\n if (executionCommand", "end": 5449, "score": 0.8470246195793152, "start": 5449, "tag": "KEY", "value": "" }, { "context": "h = \"#{pkgName}.executionSettings.executionCommandPatterns\"\n if (executionCommandPatterns = atom.config.g", "end": 5474, "score": 0.6503714919090271, "start": 5466, "tag": "KEY", "value": "Patterns" } ]
lib/main.coffee
lakrme/atom-levels-language-test
2
{Emitter,Disposable} = require('atom') path = require('path') CSON = require('season') # ------------------------------------------------------------------------------ module.exports = ## Language package settings ------------------------------------------------- config: generalSettings: type: 'object' order: 1 properties: levelCodeFileTypes: title: 'Level Code File Type(s)' description: 'A comma-separated list of file type extensions that are associated with this level language. This allows Levels to select the correct language when a file is opened or saved and no other language information is given. It\'s also possible to add a file type that is already associated with another installed grammar (e.g. `rb` for a Ruby-based level language).' type: 'array' default: [] items: type: 'string' executionSettings: type: 'object' order: 2 properties: # objectCodeFileType: # title: 'Object Code File Type' # description: # 'The default file type extension of the back-end programming # language for this level language (e.g. `hs` for a Haskell-based # level language). The object code file type is needed for ' # type: 'string' # default: '' executionCommandPatterns: title: 'Execution Command Pattern(s)' description: 'A comma-separated list of patterns for the commands that will be executed (sequentially) to run your programs. Use the `<filePath>` variable to indicate where to insert the input file for each command. To run a generated executable file, add `./<filePath>` to the end of the list (e.g. `ghc -v0 <filePath>, ./<filePath>` for a Haskell-based level language).' type: 'array' default: [] items: type: 'string' ## Language package activation and deactivation ------------------------------ activate: -> @emitter = new Emitter @pkgDirPath = path.dirname(__dirname) pkgMetadataFilePath = CSON.resolve(path.join(@pkgDirPath,'package')) @pkgMetadata = CSON.readFileSync(pkgMetadataFilePath) @configFilePath = @getConfigFilePath() @executablePath = @getExecutablePath() pkgSubscr = atom.packages.onDidActivatePackage (pkg) => if pkg.name is @pkgMetadata.name @dummyGrammar = pkg.grammars[0] atom.grammars.removeGrammar(@dummyGrammar) @startUsingLevels() if @levelsIsActive @onDidActivateLevels => @startUsingLevels() @onDidDeactivateLevels => @stopUsingLevels() pkgSubscr.dispose() deactivate: -> @languageRegistry.removeLanguage(@language) if @levelsIsActive ## Activation helpers -------------------------------------------------------- getConfigFilePath: -> CSON.resolve(path.join(@pkgDirPath,'language','config')) getExecutablePath: -> executableDirPath = path.join(@pkgDirPath,'language','executable') switch process.platform when 'darwin' then path.join(executableDirPath,'darwin','run') when 'linux' then path.join(executableDirPath,'linux','run') when 'win32' then path.join(executableDirPath,'win32','run.exe') ## Interacting with the Levels package --------------------------------------- onDidActivateLevels: (callback) -> @emitter.on('did-activate-levels',callback) onDidDeactivateLevels: (callback) -> @emitter.on('did-deactivate-levels',callback) consumeLevels: ({@languageRegistry}) -> @levelsIsActive = true @emitter.emit('did-activate-levels') new Disposable => @levelsIsActive = false @emitter.emit('did-deactivate-levels') startUsingLevels: -> unless @language? @language = @languageRegistry.readLanguageSync\ (@configFilePath,@executablePath) @dummyGrammar.name = @language.getGrammarName() @dummyGrammar.scopeName = @language.getScopeName() @dummyGrammar.fileTypes = @language.getLevelCodeFileTypes() @language.setDummyGrammar(@dummyGrammar) @setUpLanguageConfigurationManagement() atom.grammars.addGrammar(@dummyGrammar) @languageRegistry.addLanguage(@language) stopUsingLevels: -> atom.grammars.removeGrammar(@dummyGrammar) ## Language configuration management ----------------------------------------- setUpLanguageConfigurationManagement: -> pkgName = @pkgMetadata.name configKeyPath = "#{pkgName}.generalSettings.levelCodeFileTypes" if (levelCodeFileTypes = atom.config.get(configKeyPath)).length > 0 @language.setLevelCodeFileTypes(levelCodeFileTypes) else atom.config.set(configKeyPath,@language.getLevelCodeFileTypes()) atom.config.onDidChange configKeyPath, ({newValue}) => @language.setLevelCodeFileTypes(newValue) # configKeyPath = "#{pkgName}.executionSettings.objectCodeFileType" # if (objectCodeFileType = atom.config.get(configKeyPath)) # @language.setObjectCodeFileType(objectCodeFileType) # else # atom.config.set(configKeyPath,@language.getObjectCodeFileType()) # atom.config.onDidChange configKeyPath, ({newValue}) => # @language.setObjectCodeFileType(newValue) configKeyPath = "#{pkgName}.executionSettings.executionCommandPatterns" if (executionCommandPatterns = atom.config.get(configKeyPath)) @language.setExecutionCommandPatterns(executionCommandPatterns) else atom.config.set(configKeyPath,@language.getExecutionCommandPatterns()) atom.config.onDidChange configKeyPath, ({newValue}) => @language.setExecutionCommandPatterns(newValue) # ------------------------------------------------------------------------------
185645
{Emitter,Disposable} = require('atom') path = require('path') CSON = require('season') # ------------------------------------------------------------------------------ module.exports = ## Language package settings ------------------------------------------------- config: generalSettings: type: 'object' order: 1 properties: levelCodeFileTypes: title: 'Level Code File Type(s)' description: 'A comma-separated list of file type extensions that are associated with this level language. This allows Levels to select the correct language when a file is opened or saved and no other language information is given. It\'s also possible to add a file type that is already associated with another installed grammar (e.g. `rb` for a Ruby-based level language).' type: 'array' default: [] items: type: 'string' executionSettings: type: 'object' order: 2 properties: # objectCodeFileType: # title: 'Object Code File Type' # description: # 'The default file type extension of the back-end programming # language for this level language (e.g. `hs` for a Haskell-based # level language). The object code file type is needed for ' # type: 'string' # default: '' executionCommandPatterns: title: 'Execution Command Pattern(s)' description: 'A comma-separated list of patterns for the commands that will be executed (sequentially) to run your programs. Use the `<filePath>` variable to indicate where to insert the input file for each command. To run a generated executable file, add `./<filePath>` to the end of the list (e.g. `ghc -v0 <filePath>, ./<filePath>` for a Haskell-based level language).' type: 'array' default: [] items: type: 'string' ## Language package activation and deactivation ------------------------------ activate: -> @emitter = new Emitter @pkgDirPath = path.dirname(__dirname) pkgMetadataFilePath = CSON.resolve(path.join(@pkgDirPath,'package')) @pkgMetadata = CSON.readFileSync(pkgMetadataFilePath) @configFilePath = @getConfigFilePath() @executablePath = @getExecutablePath() pkgSubscr = atom.packages.onDidActivatePackage (pkg) => if pkg.name is @pkgMetadata.name @dummyGrammar = pkg.grammars[0] atom.grammars.removeGrammar(@dummyGrammar) @startUsingLevels() if @levelsIsActive @onDidActivateLevels => @startUsingLevels() @onDidDeactivateLevels => @stopUsingLevels() pkgSubscr.dispose() deactivate: -> @languageRegistry.removeLanguage(@language) if @levelsIsActive ## Activation helpers -------------------------------------------------------- getConfigFilePath: -> CSON.resolve(path.join(@pkgDirPath,'language','config')) getExecutablePath: -> executableDirPath = path.join(@pkgDirPath,'language','executable') switch process.platform when 'darwin' then path.join(executableDirPath,'darwin','run') when 'linux' then path.join(executableDirPath,'linux','run') when 'win32' then path.join(executableDirPath,'win32','run.exe') ## Interacting with the Levels package --------------------------------------- onDidActivateLevels: (callback) -> @emitter.on('did-activate-levels',callback) onDidDeactivateLevels: (callback) -> @emitter.on('did-deactivate-levels',callback) consumeLevels: ({@languageRegistry}) -> @levelsIsActive = true @emitter.emit('did-activate-levels') new Disposable => @levelsIsActive = false @emitter.emit('did-deactivate-levels') startUsingLevels: -> unless @language? @language = @languageRegistry.readLanguageSync\ (@configFilePath,@executablePath) @dummyGrammar.name = @language.getGrammarName() @dummyGrammar.scopeName = @language.getScopeName() @dummyGrammar.fileTypes = @language.getLevelCodeFileTypes() @language.setDummyGrammar(@dummyGrammar) @setUpLanguageConfigurationManagement() atom.grammars.addGrammar(@dummyGrammar) @languageRegistry.addLanguage(@language) stopUsingLevels: -> atom.grammars.removeGrammar(@dummyGrammar) ## Language configuration management ----------------------------------------- setUpLanguageConfigurationManagement: -> pkgName = @pkgMetadata.name configKeyPath = "#{pkgName}.generalSettings.levelCodeFileTypes" if (levelCodeFileTypes = atom.config.get(configKeyPath)).length > 0 @language.setLevelCodeFileTypes(levelCodeFileTypes) else atom.config.set(configKeyPath,@language.getLevelCodeFileTypes()) atom.config.onDidChange configKeyPath, ({newValue}) => @language.setLevelCodeFileTypes(newValue) # configKeyPath = "#{<KEY>executionSettings.<KEY>" # if (objectCodeFileType = atom.config.get(configKeyPath)) # @language.setObjectCodeFileType(objectCodeFileType) # else # atom.config.set(configKeyPath,@language.getObjectCodeFileType()) # atom.config.onDidChange configKeyPath, ({newValue}) => # @language.setObjectCodeFileType(newValue) configKeyPath = "#{<KEY>executionSettings<KEY>.executionCommand<KEY>" if (executionCommandPatterns = atom.config.get(configKeyPath)) @language.setExecutionCommandPatterns(executionCommandPatterns) else atom.config.set(configKeyPath,@language.getExecutionCommandPatterns()) atom.config.onDidChange configKeyPath, ({newValue}) => @language.setExecutionCommandPatterns(newValue) # ------------------------------------------------------------------------------
true
{Emitter,Disposable} = require('atom') path = require('path') CSON = require('season') # ------------------------------------------------------------------------------ module.exports = ## Language package settings ------------------------------------------------- config: generalSettings: type: 'object' order: 1 properties: levelCodeFileTypes: title: 'Level Code File Type(s)' description: 'A comma-separated list of file type extensions that are associated with this level language. This allows Levels to select the correct language when a file is opened or saved and no other language information is given. It\'s also possible to add a file type that is already associated with another installed grammar (e.g. `rb` for a Ruby-based level language).' type: 'array' default: [] items: type: 'string' executionSettings: type: 'object' order: 2 properties: # objectCodeFileType: # title: 'Object Code File Type' # description: # 'The default file type extension of the back-end programming # language for this level language (e.g. `hs` for a Haskell-based # level language). The object code file type is needed for ' # type: 'string' # default: '' executionCommandPatterns: title: 'Execution Command Pattern(s)' description: 'A comma-separated list of patterns for the commands that will be executed (sequentially) to run your programs. Use the `<filePath>` variable to indicate where to insert the input file for each command. To run a generated executable file, add `./<filePath>` to the end of the list (e.g. `ghc -v0 <filePath>, ./<filePath>` for a Haskell-based level language).' type: 'array' default: [] items: type: 'string' ## Language package activation and deactivation ------------------------------ activate: -> @emitter = new Emitter @pkgDirPath = path.dirname(__dirname) pkgMetadataFilePath = CSON.resolve(path.join(@pkgDirPath,'package')) @pkgMetadata = CSON.readFileSync(pkgMetadataFilePath) @configFilePath = @getConfigFilePath() @executablePath = @getExecutablePath() pkgSubscr = atom.packages.onDidActivatePackage (pkg) => if pkg.name is @pkgMetadata.name @dummyGrammar = pkg.grammars[0] atom.grammars.removeGrammar(@dummyGrammar) @startUsingLevels() if @levelsIsActive @onDidActivateLevels => @startUsingLevels() @onDidDeactivateLevels => @stopUsingLevels() pkgSubscr.dispose() deactivate: -> @languageRegistry.removeLanguage(@language) if @levelsIsActive ## Activation helpers -------------------------------------------------------- getConfigFilePath: -> CSON.resolve(path.join(@pkgDirPath,'language','config')) getExecutablePath: -> executableDirPath = path.join(@pkgDirPath,'language','executable') switch process.platform when 'darwin' then path.join(executableDirPath,'darwin','run') when 'linux' then path.join(executableDirPath,'linux','run') when 'win32' then path.join(executableDirPath,'win32','run.exe') ## Interacting with the Levels package --------------------------------------- onDidActivateLevels: (callback) -> @emitter.on('did-activate-levels',callback) onDidDeactivateLevels: (callback) -> @emitter.on('did-deactivate-levels',callback) consumeLevels: ({@languageRegistry}) -> @levelsIsActive = true @emitter.emit('did-activate-levels') new Disposable => @levelsIsActive = false @emitter.emit('did-deactivate-levels') startUsingLevels: -> unless @language? @language = @languageRegistry.readLanguageSync\ (@configFilePath,@executablePath) @dummyGrammar.name = @language.getGrammarName() @dummyGrammar.scopeName = @language.getScopeName() @dummyGrammar.fileTypes = @language.getLevelCodeFileTypes() @language.setDummyGrammar(@dummyGrammar) @setUpLanguageConfigurationManagement() atom.grammars.addGrammar(@dummyGrammar) @languageRegistry.addLanguage(@language) stopUsingLevels: -> atom.grammars.removeGrammar(@dummyGrammar) ## Language configuration management ----------------------------------------- setUpLanguageConfigurationManagement: -> pkgName = @pkgMetadata.name configKeyPath = "#{pkgName}.generalSettings.levelCodeFileTypes" if (levelCodeFileTypes = atom.config.get(configKeyPath)).length > 0 @language.setLevelCodeFileTypes(levelCodeFileTypes) else atom.config.set(configKeyPath,@language.getLevelCodeFileTypes()) atom.config.onDidChange configKeyPath, ({newValue}) => @language.setLevelCodeFileTypes(newValue) # configKeyPath = "#{PI:KEY:<KEY>END_PIexecutionSettings.PI:KEY:<KEY>END_PI" # if (objectCodeFileType = atom.config.get(configKeyPath)) # @language.setObjectCodeFileType(objectCodeFileType) # else # atom.config.set(configKeyPath,@language.getObjectCodeFileType()) # atom.config.onDidChange configKeyPath, ({newValue}) => # @language.setObjectCodeFileType(newValue) configKeyPath = "#{PI:KEY:<KEY>END_PIexecutionSettingsPI:KEY:<KEY>END_PI.executionCommandPI:KEY:<KEY>END_PI" if (executionCommandPatterns = atom.config.get(configKeyPath)) @language.setExecutionCommandPatterns(executionCommandPatterns) else atom.config.set(configKeyPath,@language.getExecutionCommandPatterns()) atom.config.onDidChange configKeyPath, ({newValue}) => @language.setExecutionCommandPatterns(newValue) # ------------------------------------------------------------------------------
[ { "context": "NASA in 2009. It was named after German astronomer Johannes Kepler, who is best known for developing the laws of pla", "end": 207, "score": 0.9994628429412842, "start": 192, "tag": "NAME", "value": "Johannes Kepler" } ]
app/lib/mini-course-content_old.coffee
zooniverse/Planet-Hunters-2
1
content = [ { course_number: 1 material: title: "The Kepler Mission" text: "The Kepler space telescope was launched by NASA in 2009. It was named after German astronomer Johannes Kepler, who is best known for developing the laws of planetary motion in the 17th century. For 4 years it stared at a patch of sky 100 square degrees in area (500 times that of the full Moon) in the constellations Lyra, Cygnus and Draco, looking for the tell-tale dips in brightness caused when a planet passes in front of its host star. It is these brightness measurements you are looking at on Planet Hunters." figure: "./images/mini-course/01-KeplerHR_sm.jpg" figure_credits: "Image courtesy of NASA" } { course_number: 2 material: title: "The First 'People's Planet'" text: "<p>The first confirmed planet discovered by volunteers, like you, on Planet Hunters was PH1b (also known as Kepler-64b). It is a Neptune-sized giant planet with a radius 6 times greater than that of the Earth. The really interesting thing about PH1b is that it’s a circumbinary planet, meaning it orbits around two stars! Those two stars are also in orbit around another binary star system, which makes PH1b the first planet ever discovered in a quadruple star system. Below you can see the original lightcurve seen by volunteers on Planet Hunters. The coloured region shows where separate volunteers marked the dip.</p>" figure: "./images/mini-course/02-ph1fig1.jpg" figure_credits: "Image courtesy of NASA" } { course_number: 3 material: title: "How else can we discover planets? (Part 1)" text: "<p>The transit method is a very simple and effective method for discovering planets, but it is not the only one used by astronomers. Let’s have a look at some of the other methods.</p><p><b>The radial velocity method</b>: As a planet orbits a star its gravitational pull moves the star around. Therefore at some points the star is moving towards us (the observer) and at other it is moving away. We can measure the speed of this movement by looking at the spectrum of light from the star. When moving towards us its light becomes more blue, and when moving away its light becomes more red. The faster the star is moving, the more massive the planet. For example, Jupiter makes our Sun move at 12.7 m/s, whereas the Earth only makes it move at 0.09 m/s.</p>" figure: "./images/mini-course/03-transit.jpg" figure_credits: "Image courtesy of NASA" } { course_number: 4 material: title: "How else can we discover planets? (Part 2)" text: "The radial velocity method has been used to discover the majority of exoplanets to date, however it has one major disadvantage; it cannot be used to determine the angle of the planetary system to our line-of-sight. This means that only a minimum measurement of the star’s speed can be calculated, leading to only a minimum possible value for the mass of the exoplanet." figure: "./images/mini-course/04-doppler.jpg" figure_credits: "Image courtesy of NASA" } ] module.exports = content
177520
content = [ { course_number: 1 material: title: "The Kepler Mission" text: "The Kepler space telescope was launched by NASA in 2009. It was named after German astronomer <NAME>, who is best known for developing the laws of planetary motion in the 17th century. For 4 years it stared at a patch of sky 100 square degrees in area (500 times that of the full Moon) in the constellations Lyra, Cygnus and Draco, looking for the tell-tale dips in brightness caused when a planet passes in front of its host star. It is these brightness measurements you are looking at on Planet Hunters." figure: "./images/mini-course/01-KeplerHR_sm.jpg" figure_credits: "Image courtesy of NASA" } { course_number: 2 material: title: "The First 'People's Planet'" text: "<p>The first confirmed planet discovered by volunteers, like you, on Planet Hunters was PH1b (also known as Kepler-64b). It is a Neptune-sized giant planet with a radius 6 times greater than that of the Earth. The really interesting thing about PH1b is that it’s a circumbinary planet, meaning it orbits around two stars! Those two stars are also in orbit around another binary star system, which makes PH1b the first planet ever discovered in a quadruple star system. Below you can see the original lightcurve seen by volunteers on Planet Hunters. The coloured region shows where separate volunteers marked the dip.</p>" figure: "./images/mini-course/02-ph1fig1.jpg" figure_credits: "Image courtesy of NASA" } { course_number: 3 material: title: "How else can we discover planets? (Part 1)" text: "<p>The transit method is a very simple and effective method for discovering planets, but it is not the only one used by astronomers. Let’s have a look at some of the other methods.</p><p><b>The radial velocity method</b>: As a planet orbits a star its gravitational pull moves the star around. Therefore at some points the star is moving towards us (the observer) and at other it is moving away. We can measure the speed of this movement by looking at the spectrum of light from the star. When moving towards us its light becomes more blue, and when moving away its light becomes more red. The faster the star is moving, the more massive the planet. For example, Jupiter makes our Sun move at 12.7 m/s, whereas the Earth only makes it move at 0.09 m/s.</p>" figure: "./images/mini-course/03-transit.jpg" figure_credits: "Image courtesy of NASA" } { course_number: 4 material: title: "How else can we discover planets? (Part 2)" text: "The radial velocity method has been used to discover the majority of exoplanets to date, however it has one major disadvantage; it cannot be used to determine the angle of the planetary system to our line-of-sight. This means that only a minimum measurement of the star’s speed can be calculated, leading to only a minimum possible value for the mass of the exoplanet." figure: "./images/mini-course/04-doppler.jpg" figure_credits: "Image courtesy of NASA" } ] module.exports = content
true
content = [ { course_number: 1 material: title: "The Kepler Mission" text: "The Kepler space telescope was launched by NASA in 2009. It was named after German astronomer PI:NAME:<NAME>END_PI, who is best known for developing the laws of planetary motion in the 17th century. For 4 years it stared at a patch of sky 100 square degrees in area (500 times that of the full Moon) in the constellations Lyra, Cygnus and Draco, looking for the tell-tale dips in brightness caused when a planet passes in front of its host star. It is these brightness measurements you are looking at on Planet Hunters." figure: "./images/mini-course/01-KeplerHR_sm.jpg" figure_credits: "Image courtesy of NASA" } { course_number: 2 material: title: "The First 'People's Planet'" text: "<p>The first confirmed planet discovered by volunteers, like you, on Planet Hunters was PH1b (also known as Kepler-64b). It is a Neptune-sized giant planet with a radius 6 times greater than that of the Earth. The really interesting thing about PH1b is that it’s a circumbinary planet, meaning it orbits around two stars! Those two stars are also in orbit around another binary star system, which makes PH1b the first planet ever discovered in a quadruple star system. Below you can see the original lightcurve seen by volunteers on Planet Hunters. The coloured region shows where separate volunteers marked the dip.</p>" figure: "./images/mini-course/02-ph1fig1.jpg" figure_credits: "Image courtesy of NASA" } { course_number: 3 material: title: "How else can we discover planets? (Part 1)" text: "<p>The transit method is a very simple and effective method for discovering planets, but it is not the only one used by astronomers. Let’s have a look at some of the other methods.</p><p><b>The radial velocity method</b>: As a planet orbits a star its gravitational pull moves the star around. Therefore at some points the star is moving towards us (the observer) and at other it is moving away. We can measure the speed of this movement by looking at the spectrum of light from the star. When moving towards us its light becomes more blue, and when moving away its light becomes more red. The faster the star is moving, the more massive the planet. For example, Jupiter makes our Sun move at 12.7 m/s, whereas the Earth only makes it move at 0.09 m/s.</p>" figure: "./images/mini-course/03-transit.jpg" figure_credits: "Image courtesy of NASA" } { course_number: 4 material: title: "How else can we discover planets? (Part 2)" text: "The radial velocity method has been used to discover the majority of exoplanets to date, however it has one major disadvantage; it cannot be used to determine the angle of the planetary system to our line-of-sight. This means that only a minimum measurement of the star’s speed can be calculated, leading to only a minimum possible value for the mass of the exoplanet." figure: "./images/mini-course/04-doppler.jpg" figure_credits: "Image courtesy of NASA" } ] module.exports = content
[ { "context": "tps://code.google.com/apis/console/\n clientId = '382467810781.apps.googleusercontent.com'\n\n # The permissions we’re asking for. This is a", "end": 564, "score": 0.7192202806472778, "start": 525, "tag": "KEY", "value": "382467810781.apps.googleusercontent.com" } ]
app/lib/services/google.coffee
Oxicode/brunch-with-chaplin-and-bootstrap
0
mediator = require 'mediator' utils = require 'lib/utils' ServiceProvider = require 'lib/services/service_provider' module.exports = class Google extends ServiceProvider # Client-Side OAuth 2.0 login with Google # https://code.google.com/p/google-api-javascript-client/ # https://code.google.com/p/google-api-javascript-client/wiki/Authentication # Note: This is the ID for an example Google API project. # You might change this to your own project ID. # See https://code.google.com/apis/console/ clientId = '382467810781.apps.googleusercontent.com' # The permissions we’re asking for. This is a space-separated list of URLs. # See https://developers.google.com/accounts/docs/OAuth2Login#scopeparameter # and the individual Google API documentations scopes = 'https://www.googleapis.com/auth/userinfo.profile' name: 'google' load: -> return if @state() is 'resolved' or @loading @loading = true # Register load handler window.googleClientLoaded = @loadHandler # No success callback, there's googleClientLoaded utils.loadLib 'https://apis.google.com/js/client.js?onload=googleClientLoaded', null, @reject loadHandler: => # Remove the global load handler try # IE 8 throws an exception delete window.googleClientLoaded catch error window.googleClientLoaded = undefined # Initialize gapi.auth.init @resolve isLoaded: -> Boolean window.gapi and gapi.auth and gapi.auth.authorize triggerLogin: (loginContext) -> console.log "triggerLogin: #{clientId}, #{scopes}" gapi.auth.authorize client_id: clientId, scope: scopes, immediate: false _(@loginHandler).bind(this, loginContext) loginHandler: (loginContext, authResponse) -> console.log authResponse if authResponse # Publish successful login mediator.publish 'loginSuccessful', {provider: this, loginContext} # Publish the session with extra userinfo @getUserInfo (userInfo) -> data = provider: this accessToken: authResponse.access_token _.extend(data, userInfo) console.log 'serviceProviderSession:', data mediator.publish 'serviceProviderSession', data else mediator.publish 'loginFail', {provider: this, loginContext} getLoginStatus: (callback) -> gapi.auth.authorize { client_id: clientId, scope: scopes, immediate: true }, callback # TODO getUserInfo: (callback) -> request = gapi.client.request path: '/oauth2/v2/userinfo' request.execute callback parsePlusOneButton: (el) -> if window.gapi and gapi.plusone and gapi.plusone.go gapi.plusone.go el else window.___gcfg = parsetags: 'explicit' utils.loadLib 'https://apis.google.com/js/plusone.js', -> try # IE 8 throws an exception delete window.___gcfg catch error window.___gcfg = undefined gapi.plusone.go el
120869
mediator = require 'mediator' utils = require 'lib/utils' ServiceProvider = require 'lib/services/service_provider' module.exports = class Google extends ServiceProvider # Client-Side OAuth 2.0 login with Google # https://code.google.com/p/google-api-javascript-client/ # https://code.google.com/p/google-api-javascript-client/wiki/Authentication # Note: This is the ID for an example Google API project. # You might change this to your own project ID. # See https://code.google.com/apis/console/ clientId = '<KEY>' # The permissions we’re asking for. This is a space-separated list of URLs. # See https://developers.google.com/accounts/docs/OAuth2Login#scopeparameter # and the individual Google API documentations scopes = 'https://www.googleapis.com/auth/userinfo.profile' name: 'google' load: -> return if @state() is 'resolved' or @loading @loading = true # Register load handler window.googleClientLoaded = @loadHandler # No success callback, there's googleClientLoaded utils.loadLib 'https://apis.google.com/js/client.js?onload=googleClientLoaded', null, @reject loadHandler: => # Remove the global load handler try # IE 8 throws an exception delete window.googleClientLoaded catch error window.googleClientLoaded = undefined # Initialize gapi.auth.init @resolve isLoaded: -> Boolean window.gapi and gapi.auth and gapi.auth.authorize triggerLogin: (loginContext) -> console.log "triggerLogin: #{clientId}, #{scopes}" gapi.auth.authorize client_id: clientId, scope: scopes, immediate: false _(@loginHandler).bind(this, loginContext) loginHandler: (loginContext, authResponse) -> console.log authResponse if authResponse # Publish successful login mediator.publish 'loginSuccessful', {provider: this, loginContext} # Publish the session with extra userinfo @getUserInfo (userInfo) -> data = provider: this accessToken: authResponse.access_token _.extend(data, userInfo) console.log 'serviceProviderSession:', data mediator.publish 'serviceProviderSession', data else mediator.publish 'loginFail', {provider: this, loginContext} getLoginStatus: (callback) -> gapi.auth.authorize { client_id: clientId, scope: scopes, immediate: true }, callback # TODO getUserInfo: (callback) -> request = gapi.client.request path: '/oauth2/v2/userinfo' request.execute callback parsePlusOneButton: (el) -> if window.gapi and gapi.plusone and gapi.plusone.go gapi.plusone.go el else window.___gcfg = parsetags: 'explicit' utils.loadLib 'https://apis.google.com/js/plusone.js', -> try # IE 8 throws an exception delete window.___gcfg catch error window.___gcfg = undefined gapi.plusone.go el
true
mediator = require 'mediator' utils = require 'lib/utils' ServiceProvider = require 'lib/services/service_provider' module.exports = class Google extends ServiceProvider # Client-Side OAuth 2.0 login with Google # https://code.google.com/p/google-api-javascript-client/ # https://code.google.com/p/google-api-javascript-client/wiki/Authentication # Note: This is the ID for an example Google API project. # You might change this to your own project ID. # See https://code.google.com/apis/console/ clientId = 'PI:KEY:<KEY>END_PI' # The permissions we’re asking for. This is a space-separated list of URLs. # See https://developers.google.com/accounts/docs/OAuth2Login#scopeparameter # and the individual Google API documentations scopes = 'https://www.googleapis.com/auth/userinfo.profile' name: 'google' load: -> return if @state() is 'resolved' or @loading @loading = true # Register load handler window.googleClientLoaded = @loadHandler # No success callback, there's googleClientLoaded utils.loadLib 'https://apis.google.com/js/client.js?onload=googleClientLoaded', null, @reject loadHandler: => # Remove the global load handler try # IE 8 throws an exception delete window.googleClientLoaded catch error window.googleClientLoaded = undefined # Initialize gapi.auth.init @resolve isLoaded: -> Boolean window.gapi and gapi.auth and gapi.auth.authorize triggerLogin: (loginContext) -> console.log "triggerLogin: #{clientId}, #{scopes}" gapi.auth.authorize client_id: clientId, scope: scopes, immediate: false _(@loginHandler).bind(this, loginContext) loginHandler: (loginContext, authResponse) -> console.log authResponse if authResponse # Publish successful login mediator.publish 'loginSuccessful', {provider: this, loginContext} # Publish the session with extra userinfo @getUserInfo (userInfo) -> data = provider: this accessToken: authResponse.access_token _.extend(data, userInfo) console.log 'serviceProviderSession:', data mediator.publish 'serviceProviderSession', data else mediator.publish 'loginFail', {provider: this, loginContext} getLoginStatus: (callback) -> gapi.auth.authorize { client_id: clientId, scope: scopes, immediate: true }, callback # TODO getUserInfo: (callback) -> request = gapi.client.request path: '/oauth2/v2/userinfo' request.execute callback parsePlusOneButton: (el) -> if window.gapi and gapi.plusone and gapi.plusone.go gapi.plusone.go el else window.___gcfg = parsetags: 'explicit' utils.loadLib 'https://apis.google.com/js/plusone.js', -> try # IE 8 throws an exception delete window.___gcfg catch error window.___gcfg = undefined gapi.plusone.go el
[ { "context": "ORTRAIT_Y, 'noble_portrait'\n noble.heroName = \"Noble\"\n noble.heroText = \"Has mastered the art of th", "end": 677, "score": 0.9837329983711243, "start": 672, "tag": "NAME", "value": "Noble" }, { "context": "ORTRAIT_Y, 'ninja_portrait'\n ninja.heroName = 'Ninja'\n ninja.heroText = \"Shifts between Yin and Yan", "end": 859, "score": 0.90639328956604, "start": 854, "tag": "NAME", "value": "Ninja" }, { "context": "TRAIT_Y, 'wizard_portrait'\n wizard.heroName = 'Wizard'\n wizard.heroText = 'Controls the battle with ", "end": 1028, "score": 0.8971899151802063, "start": 1022, "tag": "NAME", "value": "Wizard" }, { "context": "hor.set 0.5\n kobold = game.add.text 150, 360, \"Kobold\", TEXT_STYLE_SMALLER\n kobold.enemyText = \"A st", "end": 1874, "score": 0.7781400680541992, "start": 1868, "tag": "NAME", "value": "Kobold" } ]
src/state/battle_select.coffee
zekoff/1gam-battle
0
state = {} Popup = require '../ui/popup' TEXT_STYLE = fontSize: 30 fill: 'white' TEXT_STYLE_SMALLER = Object.create(TEXT_STYLE) TEXT_STYLE_SMALLER.fontSize = 24 PORTRAIT_Y = 55 selectedHeroText = null selectedEnemyText = null selectedHero = null selectedEnemy = null popup = null enemyPopup = null state.create = -> selectedHeroText = null selectedEnemyText = null selectedHero = null selectedEnemy = null popup = null enemyPopup = null heroSelectHeading = game.add.text 400, 30, "Select your Hero:", TEXT_STYLE heroSelectHeading.anchor.set 0.5 noble = game.add.image 150, PORTRAIT_Y, 'noble_portrait' noble.heroName = "Noble" noble.heroText = "Has mastered the art of the sword to fight with ripostes and feints." ninja = game.add.image 350, PORTRAIT_Y, 'ninja_portrait' ninja.heroName = 'Ninja' ninja.heroText = "Shifts between Yin and Yang to fuel deadly attacks." wizard = game.add.image 550, PORTRAIT_Y, 'wizard_portrait' wizard.heroName = 'Wizard' wizard.heroText = 'Controls the battle with the right spell for every situation.' for portrait in [noble, ninja, wizard] portrait.inputEnabled = true portrait.scale.set 3 portrait.tint = 0x808080 portrait.events.onInputOver.add -> @tint = 0xffffff popup = new Popup @x - 100, @y + 150 popup.setHeading @heroName popup.setText @heroText , portrait portrait.events.onInputOut.add -> @tint = 0x808080 popup.destroy() , portrait portrait.events.onInputUp.add -> popup?.destroy() selectedHero = @ , portrait enemySelectHeading = game.add.text 400, 330, "Select an Opponent:", TEXT_STYLE enemySelectHeading.anchor.set 0.5 kobold = game.add.text 150, 360, "Kobold", TEXT_STYLE_SMALLER kobold.enemyText = "A strong, stupid opponent from the Eastern caves." naga = game.add.text 380, 360, "Naga", TEXT_STYLE_SMALLER naga.enemyText = "A horrific snake creature that poisons, constricts, and drains health." titan = game.add.text 550, 360, "Titan", TEXT_STYLE_SMALLER titan.enemyText = "Mighty stone being from the mountains that can rend the earth beneath you." for enemyText in [kobold, naga, titan] enemyText.tint = 0x808080 enemyText.inputEnabled = true enemyText.events.onInputOver.add -> @tint = 0xFF8080 enemyPopup = new Popup @x - 100, @y + 20 enemyPopup.setHeading @text enemyPopup.setText @enemyText , enemyText enemyText.events.onInputOut.add -> @tint = 0x808080 enemyPopup.destroy() , enemyText enemyText.events.onInputUp.add -> enemyPopup?.destroy() selectedEnemy = @text , enemyText selectedHeroText = game.add.text 100, 510, "Selected Hero: none", TEXT_STYLE selectedEnemyText = game.add.text 100, 550, "Selected Opponent: none", TEXT_STYLE state.update = -> if selectedHero selectedHeroText?.setText "Selected Hero: #{selectedHero.heroName}" if selectedEnemy selectedEnemyText?.setText "Selected Opponent: #{selectedEnemy}" if selectedHero and selectedEnemy game.selectedHero = selectedHero game.selectedEnemy = selectedEnemy game.state.start 'main' module.exports = state
152768
state = {} Popup = require '../ui/popup' TEXT_STYLE = fontSize: 30 fill: 'white' TEXT_STYLE_SMALLER = Object.create(TEXT_STYLE) TEXT_STYLE_SMALLER.fontSize = 24 PORTRAIT_Y = 55 selectedHeroText = null selectedEnemyText = null selectedHero = null selectedEnemy = null popup = null enemyPopup = null state.create = -> selectedHeroText = null selectedEnemyText = null selectedHero = null selectedEnemy = null popup = null enemyPopup = null heroSelectHeading = game.add.text 400, 30, "Select your Hero:", TEXT_STYLE heroSelectHeading.anchor.set 0.5 noble = game.add.image 150, PORTRAIT_Y, 'noble_portrait' noble.heroName = "<NAME>" noble.heroText = "Has mastered the art of the sword to fight with ripostes and feints." ninja = game.add.image 350, PORTRAIT_Y, 'ninja_portrait' ninja.heroName = '<NAME>' ninja.heroText = "Shifts between Yin and Yang to fuel deadly attacks." wizard = game.add.image 550, PORTRAIT_Y, 'wizard_portrait' wizard.heroName = '<NAME>' wizard.heroText = 'Controls the battle with the right spell for every situation.' for portrait in [noble, ninja, wizard] portrait.inputEnabled = true portrait.scale.set 3 portrait.tint = 0x808080 portrait.events.onInputOver.add -> @tint = 0xffffff popup = new Popup @x - 100, @y + 150 popup.setHeading @heroName popup.setText @heroText , portrait portrait.events.onInputOut.add -> @tint = 0x808080 popup.destroy() , portrait portrait.events.onInputUp.add -> popup?.destroy() selectedHero = @ , portrait enemySelectHeading = game.add.text 400, 330, "Select an Opponent:", TEXT_STYLE enemySelectHeading.anchor.set 0.5 kobold = game.add.text 150, 360, "<NAME>", TEXT_STYLE_SMALLER kobold.enemyText = "A strong, stupid opponent from the Eastern caves." naga = game.add.text 380, 360, "Naga", TEXT_STYLE_SMALLER naga.enemyText = "A horrific snake creature that poisons, constricts, and drains health." titan = game.add.text 550, 360, "Titan", TEXT_STYLE_SMALLER titan.enemyText = "Mighty stone being from the mountains that can rend the earth beneath you." for enemyText in [kobold, naga, titan] enemyText.tint = 0x808080 enemyText.inputEnabled = true enemyText.events.onInputOver.add -> @tint = 0xFF8080 enemyPopup = new Popup @x - 100, @y + 20 enemyPopup.setHeading @text enemyPopup.setText @enemyText , enemyText enemyText.events.onInputOut.add -> @tint = 0x808080 enemyPopup.destroy() , enemyText enemyText.events.onInputUp.add -> enemyPopup?.destroy() selectedEnemy = @text , enemyText selectedHeroText = game.add.text 100, 510, "Selected Hero: none", TEXT_STYLE selectedEnemyText = game.add.text 100, 550, "Selected Opponent: none", TEXT_STYLE state.update = -> if selectedHero selectedHeroText?.setText "Selected Hero: #{selectedHero.heroName}" if selectedEnemy selectedEnemyText?.setText "Selected Opponent: #{selectedEnemy}" if selectedHero and selectedEnemy game.selectedHero = selectedHero game.selectedEnemy = selectedEnemy game.state.start 'main' module.exports = state
true
state = {} Popup = require '../ui/popup' TEXT_STYLE = fontSize: 30 fill: 'white' TEXT_STYLE_SMALLER = Object.create(TEXT_STYLE) TEXT_STYLE_SMALLER.fontSize = 24 PORTRAIT_Y = 55 selectedHeroText = null selectedEnemyText = null selectedHero = null selectedEnemy = null popup = null enemyPopup = null state.create = -> selectedHeroText = null selectedEnemyText = null selectedHero = null selectedEnemy = null popup = null enemyPopup = null heroSelectHeading = game.add.text 400, 30, "Select your Hero:", TEXT_STYLE heroSelectHeading.anchor.set 0.5 noble = game.add.image 150, PORTRAIT_Y, 'noble_portrait' noble.heroName = "PI:NAME:<NAME>END_PI" noble.heroText = "Has mastered the art of the sword to fight with ripostes and feints." ninja = game.add.image 350, PORTRAIT_Y, 'ninja_portrait' ninja.heroName = 'PI:NAME:<NAME>END_PI' ninja.heroText = "Shifts between Yin and Yang to fuel deadly attacks." wizard = game.add.image 550, PORTRAIT_Y, 'wizard_portrait' wizard.heroName = 'PI:NAME:<NAME>END_PI' wizard.heroText = 'Controls the battle with the right spell for every situation.' for portrait in [noble, ninja, wizard] portrait.inputEnabled = true portrait.scale.set 3 portrait.tint = 0x808080 portrait.events.onInputOver.add -> @tint = 0xffffff popup = new Popup @x - 100, @y + 150 popup.setHeading @heroName popup.setText @heroText , portrait portrait.events.onInputOut.add -> @tint = 0x808080 popup.destroy() , portrait portrait.events.onInputUp.add -> popup?.destroy() selectedHero = @ , portrait enemySelectHeading = game.add.text 400, 330, "Select an Opponent:", TEXT_STYLE enemySelectHeading.anchor.set 0.5 kobold = game.add.text 150, 360, "PI:NAME:<NAME>END_PI", TEXT_STYLE_SMALLER kobold.enemyText = "A strong, stupid opponent from the Eastern caves." naga = game.add.text 380, 360, "Naga", TEXT_STYLE_SMALLER naga.enemyText = "A horrific snake creature that poisons, constricts, and drains health." titan = game.add.text 550, 360, "Titan", TEXT_STYLE_SMALLER titan.enemyText = "Mighty stone being from the mountains that can rend the earth beneath you." for enemyText in [kobold, naga, titan] enemyText.tint = 0x808080 enemyText.inputEnabled = true enemyText.events.onInputOver.add -> @tint = 0xFF8080 enemyPopup = new Popup @x - 100, @y + 20 enemyPopup.setHeading @text enemyPopup.setText @enemyText , enemyText enemyText.events.onInputOut.add -> @tint = 0x808080 enemyPopup.destroy() , enemyText enemyText.events.onInputUp.add -> enemyPopup?.destroy() selectedEnemy = @text , enemyText selectedHeroText = game.add.text 100, 510, "Selected Hero: none", TEXT_STYLE selectedEnemyText = game.add.text 100, 550, "Selected Opponent: none", TEXT_STYLE state.update = -> if selectedHero selectedHeroText?.setText "Selected Hero: #{selectedHero.heroName}" if selectedEnemy selectedEnemyText?.setText "Selected Opponent: #{selectedEnemy}" if selectedHero and selectedEnemy game.selectedHero = selectedHero game.selectedEnemy = selectedEnemy game.state.start 'main' module.exports = state
[ { "context": "----------------------------------------\n# Author: Alexander Kravets <alex@slatestudio.com>,\n# Slate Studio (h", "end": 107, "score": 0.9998770952224731, "start": 90, "tag": "NAME", "value": "Alexander Kravets" }, { "context": "--------------------\n# Author: Alexander Kravets <alex@slatestudio.com>,\n# Slate Studio (http://www.slatestudio.", "end": 129, "score": 0.9999297261238098, "start": 109, "tag": "EMAIL", "value": "alex@slatestudio.com" } ]
app/assets/javascripts/loft/asset-item.coffee
slate-studio/loft
0
# ----------------------------------------------------------------------------- # Author: Alexander Kravets <alex@slatestudio.com>, # Slate Studio (http://www.slatestudio.com) # ----------------------------------------------------------------------------- # Loft Asset Item # ----------------------------------------------------------------------------- class @LoftAssetItem extends Item constructor: (@module, @path, @object, @config) -> @$el =$ "<div class='item asset asset-#{ @object.type }' data-id='#{ @object._id }'></div>" @render() # PRIVATE =================================================================== _bind_name_input: -> @$nameInput.on 'blur', (e) => @_update_name_if_changed() @$nameInput.on 'keyup', (e) => if e.keyCode == 13 then $(e.target).blur() if e.keyCode == 27 then @_cancel_name_change() _edit_name: (e) -> @$el.addClass('edit-name') @$nameInput.focus().select() _cancel_name_change: -> @$el.removeClass('edit-name') name = @$title.html() @$nameInput.val(name) _update_name_if_changed: -> @$el.removeClass('edit-name') name = @$nameInput.val() if name == @$title.html() then return @$title.html(name) @config.arrayStore.update @object._id, { '[name]': name }, onSuccess: (object) => onError: (errors) => # process errors # PUBLIC ==================================================================== render: -> @$el.html('').removeClass('item-folder has-subtitle has-thumbnail') @_render_title() @_render_subtitle() # asset icon with link @$link =$ "<a class='asset-icon' href='#{ @object.file.url }' target='_blank'></a>" @$el.prepend(@$link) # thumbnail for images if @object.type == 'image' && @object.grid_item_thumbnail != '' @$thumbnailSmall =$ "<img class='asset-thumbnail-small' src='#{ @object._list_item_thumbnail.small }' />" @$thumbnailMedium =$ "<img class='asset-thumbnail-medium' src='#{ @object._list_item_thumbnail.medium }' />" @$link.append @$thumbnailSmall @$link.append @$thumbnailMedium # checkbox for item selection @$checkbox =$ "<div class='asset-checkbox'></div>" @$checkboxInput =$ "<input type='checkbox' />" @$checkbox.append(@$checkboxInput) @$el.prepend(@$checkbox) # input for assets name name = @$title.text() @$name =$ "<div class='asset-name'></div>" @$nameInput =$ "<input type='text' value='#{ name }' />" @$name.append @$nameInput @$title.before @$name @_bind_name_input() # handler for asset name change on title click @$title.on 'click', (e) => @_edit_name(e)
218384
# ----------------------------------------------------------------------------- # Author: <NAME> <<EMAIL>>, # Slate Studio (http://www.slatestudio.com) # ----------------------------------------------------------------------------- # Loft Asset Item # ----------------------------------------------------------------------------- class @LoftAssetItem extends Item constructor: (@module, @path, @object, @config) -> @$el =$ "<div class='item asset asset-#{ @object.type }' data-id='#{ @object._id }'></div>" @render() # PRIVATE =================================================================== _bind_name_input: -> @$nameInput.on 'blur', (e) => @_update_name_if_changed() @$nameInput.on 'keyup', (e) => if e.keyCode == 13 then $(e.target).blur() if e.keyCode == 27 then @_cancel_name_change() _edit_name: (e) -> @$el.addClass('edit-name') @$nameInput.focus().select() _cancel_name_change: -> @$el.removeClass('edit-name') name = @$title.html() @$nameInput.val(name) _update_name_if_changed: -> @$el.removeClass('edit-name') name = @$nameInput.val() if name == @$title.html() then return @$title.html(name) @config.arrayStore.update @object._id, { '[name]': name }, onSuccess: (object) => onError: (errors) => # process errors # PUBLIC ==================================================================== render: -> @$el.html('').removeClass('item-folder has-subtitle has-thumbnail') @_render_title() @_render_subtitle() # asset icon with link @$link =$ "<a class='asset-icon' href='#{ @object.file.url }' target='_blank'></a>" @$el.prepend(@$link) # thumbnail for images if @object.type == 'image' && @object.grid_item_thumbnail != '' @$thumbnailSmall =$ "<img class='asset-thumbnail-small' src='#{ @object._list_item_thumbnail.small }' />" @$thumbnailMedium =$ "<img class='asset-thumbnail-medium' src='#{ @object._list_item_thumbnail.medium }' />" @$link.append @$thumbnailSmall @$link.append @$thumbnailMedium # checkbox for item selection @$checkbox =$ "<div class='asset-checkbox'></div>" @$checkboxInput =$ "<input type='checkbox' />" @$checkbox.append(@$checkboxInput) @$el.prepend(@$checkbox) # input for assets name name = @$title.text() @$name =$ "<div class='asset-name'></div>" @$nameInput =$ "<input type='text' value='#{ name }' />" @$name.append @$nameInput @$title.before @$name @_bind_name_input() # handler for asset name change on title click @$title.on 'click', (e) => @_edit_name(e)
true
# ----------------------------------------------------------------------------- # Author: PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>, # Slate Studio (http://www.slatestudio.com) # ----------------------------------------------------------------------------- # Loft Asset Item # ----------------------------------------------------------------------------- class @LoftAssetItem extends Item constructor: (@module, @path, @object, @config) -> @$el =$ "<div class='item asset asset-#{ @object.type }' data-id='#{ @object._id }'></div>" @render() # PRIVATE =================================================================== _bind_name_input: -> @$nameInput.on 'blur', (e) => @_update_name_if_changed() @$nameInput.on 'keyup', (e) => if e.keyCode == 13 then $(e.target).blur() if e.keyCode == 27 then @_cancel_name_change() _edit_name: (e) -> @$el.addClass('edit-name') @$nameInput.focus().select() _cancel_name_change: -> @$el.removeClass('edit-name') name = @$title.html() @$nameInput.val(name) _update_name_if_changed: -> @$el.removeClass('edit-name') name = @$nameInput.val() if name == @$title.html() then return @$title.html(name) @config.arrayStore.update @object._id, { '[name]': name }, onSuccess: (object) => onError: (errors) => # process errors # PUBLIC ==================================================================== render: -> @$el.html('').removeClass('item-folder has-subtitle has-thumbnail') @_render_title() @_render_subtitle() # asset icon with link @$link =$ "<a class='asset-icon' href='#{ @object.file.url }' target='_blank'></a>" @$el.prepend(@$link) # thumbnail for images if @object.type == 'image' && @object.grid_item_thumbnail != '' @$thumbnailSmall =$ "<img class='asset-thumbnail-small' src='#{ @object._list_item_thumbnail.small }' />" @$thumbnailMedium =$ "<img class='asset-thumbnail-medium' src='#{ @object._list_item_thumbnail.medium }' />" @$link.append @$thumbnailSmall @$link.append @$thumbnailMedium # checkbox for item selection @$checkbox =$ "<div class='asset-checkbox'></div>" @$checkboxInput =$ "<input type='checkbox' />" @$checkbox.append(@$checkboxInput) @$el.prepend(@$checkbox) # input for assets name name = @$title.text() @$name =$ "<div class='asset-name'></div>" @$nameInput =$ "<input type='text' value='#{ name }' />" @$name.append @$nameInput @$title.before @$name @_bind_name_input() # handler for asset name change on title click @$title.on 'click', (e) => @_edit_name(e)
[ { "context": " a greyhound as a permanent foster\n#\n# Author:\n# Zach Whaley (zachwhaley) <zachbwhaley@gmail.com>\n\ngit = requi", "end": 177, "score": 0.9998334646224976, "start": 166, "tag": "NAME", "value": "Zach Whaley" }, { "context": "s a permanent foster\n#\n# Author:\n# Zach Whaley (zachwhaley) <zachbwhaley@gmail.com>\n\ngit = require '../lib/g", "end": 189, "score": 0.9982151985168457, "start": 179, "tag": "USERNAME", "value": "zachwhaley" }, { "context": " foster\n#\n# Author:\n# Zach Whaley (zachwhaley) <zachbwhaley@gmail.com>\n\ngit = require '../lib/git'\nsite = require '../l", "end": 213, "score": 0.999930202960968, "start": 192, "tag": "EMAIL", "value": "zachbwhaley@gmail.com" } ]
scripts/permafoster.coffee
galtx-centex/roobot
3
# Description: # Label a greyhound as a permanent foster # # Commands: # hubot permafoster <greyhound> - Labels a greyhound as a permanent foster # # Author: # Zach Whaley (zachwhaley) <zachbwhaley@gmail.com> git = require '../lib/git' site = require '../lib/site' util = require '../lib/util' permafoster = (path, greyhound, name, callback) -> site.loadGreyhound path, greyhound, (info, bio) -> if not info? return callback "Sorry, couldn't find #{greyhound} 😕" if info.category is 'deceased' return callback "#{name} has crossed the Rainbow Bridge 😢" if info.category is 'adopted' return callback "#{name} has already been adopted 😝" if info.permafoster is yes return callback "#{name} is already a permanent foster 😞" info.permafoster = yes site.dumpGreyhound path, greyhound, info, bio, callback module.exports = (robot) -> robot.respond /permafoster (.*)/i, (res) -> greyhound = util.slugify res.match[1] name = util.capitalize res.match[1] gitOpts = message: "#{name} Permanent Foster 💜" branch: "permafoster-#{greyhound}" user: name: res.message.user?.real_name email: res.message.user?.email_address res.reply "Labeling #{name} as a Permanent Foster 💜\n" + "Hang on a sec..." git.update permafoster, greyhound, name, gitOpts, (err) -> unless err? res.reply "#{name} labeled as a Permanent Foster 💜" else res.reply err
129204
# Description: # Label a greyhound as a permanent foster # # Commands: # hubot permafoster <greyhound> - Labels a greyhound as a permanent foster # # Author: # <NAME> (zachwhaley) <<EMAIL>> git = require '../lib/git' site = require '../lib/site' util = require '../lib/util' permafoster = (path, greyhound, name, callback) -> site.loadGreyhound path, greyhound, (info, bio) -> if not info? return callback "Sorry, couldn't find #{greyhound} 😕" if info.category is 'deceased' return callback "#{name} has crossed the Rainbow Bridge 😢" if info.category is 'adopted' return callback "#{name} has already been adopted 😝" if info.permafoster is yes return callback "#{name} is already a permanent foster 😞" info.permafoster = yes site.dumpGreyhound path, greyhound, info, bio, callback module.exports = (robot) -> robot.respond /permafoster (.*)/i, (res) -> greyhound = util.slugify res.match[1] name = util.capitalize res.match[1] gitOpts = message: "#{name} Permanent Foster 💜" branch: "permafoster-#{greyhound}" user: name: res.message.user?.real_name email: res.message.user?.email_address res.reply "Labeling #{name} as a Permanent Foster 💜\n" + "Hang on a sec..." git.update permafoster, greyhound, name, gitOpts, (err) -> unless err? res.reply "#{name} labeled as a Permanent Foster 💜" else res.reply err
true
# Description: # Label a greyhound as a permanent foster # # Commands: # hubot permafoster <greyhound> - Labels a greyhound as a permanent foster # # Author: # PI:NAME:<NAME>END_PI (zachwhaley) <PI:EMAIL:<EMAIL>END_PI> git = require '../lib/git' site = require '../lib/site' util = require '../lib/util' permafoster = (path, greyhound, name, callback) -> site.loadGreyhound path, greyhound, (info, bio) -> if not info? return callback "Sorry, couldn't find #{greyhound} 😕" if info.category is 'deceased' return callback "#{name} has crossed the Rainbow Bridge 😢" if info.category is 'adopted' return callback "#{name} has already been adopted 😝" if info.permafoster is yes return callback "#{name} is already a permanent foster 😞" info.permafoster = yes site.dumpGreyhound path, greyhound, info, bio, callback module.exports = (robot) -> robot.respond /permafoster (.*)/i, (res) -> greyhound = util.slugify res.match[1] name = util.capitalize res.match[1] gitOpts = message: "#{name} Permanent Foster 💜" branch: "permafoster-#{greyhound}" user: name: res.message.user?.real_name email: res.message.user?.email_address res.reply "Labeling #{name} as a Permanent Foster 💜\n" + "Hang on a sec..." git.update permafoster, greyhound, name, gitOpts, (err) -> unless err? res.reply "#{name} labeled as a Permanent Foster 💜" else res.reply err