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": "Up: \"Registracija\"\n OR: \"ALI\"\n forgotPassword: \"Pozabljeno geslo?\"\n emailAddress: \"Email naslov\"\n emailResetLink", "end": 140, "score": 0.9737375378608704, "start": 124, "tag": "PASSWORD", "value": "Pozabljeno geslo" }, { "context": "unt: \"Nisi registri...
client/t9n/slovene.coffee
JutoApp/accounts-entry
167
sl = signIn: "Prijava" signin: "se prijavi" signOut: "Odjava" signUp: "Registracija" OR: "ALI" forgotPassword: "Pozabljeno geslo?" emailAddress: "Email naslov" emailResetLink: "Pošlji ponastavitveno povezavo" dontHaveAnAccount: "Nisi registriran(a)?" resetYourPassword: "Ponastavi geslo" updateYourPassword: "Spremeni geslo" password: "Geslo" usernameOrEmail: "Uporabniško ime ali email" email: "Email" ifYouAlreadyHaveAnAccount: "Če si že registriran(a)," signUpWithYourEmailAddress: "Prijava z email naslovom" username: "Uporabniško ime" optional: "Po želji" signupCode: "Prijavna koda" clickAgree: "S klikom na Registracija se strinjaš" privacyPolicy: "z našimi pogoji uporabe" terms: "Pogoji uporabe" sign: "Prijava" configure: "Nastavi" with: "z" createAccount: "Nova registracija" verificationPending: "Confirm your email address" verificationPendingDetails: "A confirmation email has been sent to the email address you provided. Click on the confirmation link in the email to activate your account." and: "in" "Match failed": "Prijava neuspešna" "User not found": "Uporabnik ne obstaja" "Incorrect password": "Napačno geslo" "Email already exists.": "Email že obstaja." "Email is required": "Email je obvezen podatek" error: minChar: "Geslo mora imeti vsaj sedem znakov." pwOneLetter: "V geslu mora biti vsaj ena črka." pwOneDigit: "V geslu mora biti vsaj ena številka." usernameRequired: "Uporabniško ime je obvezen vnos." emailRequired: "Email je obvezen vnos." signupCodeRequired: "Prijavna koda je obvezen vnos." signupCodeIncorrect: "Prijavna koda je napačna." signInRequired: "Za to moraš biti prijavljen(a)." usernameIsEmail: "Uporabniško ime ne more biti email naslov." T9n.map "sl", sl
108310
sl = signIn: "Prijava" signin: "se prijavi" signOut: "Odjava" signUp: "Registracija" OR: "ALI" forgotPassword: "<PASSWORD>?" emailAddress: "Email naslov" emailResetLink: "Pošlji ponastavitveno povezavo" dontHaveAnAccount: "Nisi registriran(a)?" resetYourPassword: "<PASSWORD>" updateYourPassword: "<PASSWORD>" password: "<PASSWORD>" usernameOrEmail: "Uporabniško ime ali email" email: "Email" ifYouAlreadyHaveAnAccount: "Če si že registriran(a)," signUpWithYourEmailAddress: "Prijava z email naslovom" username: "Uporabniško ime" optional: "Po želji" signupCode: "Prijavna koda" clickAgree: "S klikom na Registracija se strinjaš" privacyPolicy: "z našimi pogoji uporabe" terms: "Pogoji uporabe" sign: "Prijava" configure: "Nastavi" with: "z" createAccount: "Nova registracija" verificationPending: "Confirm your email address" verificationPendingDetails: "A confirmation email has been sent to the email address you provided. Click on the confirmation link in the email to activate your account." and: "in" "Match failed": "Prijava neuspešna" "User not found": "Uporabnik ne obstaja" "Incorrect password": "<PASSWORD>" "Email already exists.": "Email že obstaja." "Email is required": "Email je obvezen podatek" error: minChar: "Geslo mora imeti vsaj sedem znakov." pwOneLetter: "V geslu mora biti vsaj ena črka." pwOneDigit: "V geslu mora biti vsaj ena številka." usernameRequired: "Uporabniško ime je obvezen vnos." emailRequired: "Email je obvezen vnos." signupCodeRequired: "Prijavna koda je obvezen vnos." signupCodeIncorrect: "Prijavna koda je napačna." signInRequired: "Za to moraš biti prijavljen(a)." usernameIsEmail: "Uporabniško ime ne more biti email naslov." T9n.map "sl", sl
true
sl = signIn: "Prijava" signin: "se prijavi" signOut: "Odjava" signUp: "Registracija" OR: "ALI" forgotPassword: "PI:PASSWORD:<PASSWORD>END_PI?" emailAddress: "Email naslov" emailResetLink: "Pošlji ponastavitveno povezavo" dontHaveAnAccount: "Nisi registriran(a)?" resetYourPassword: "PI:PASSWORD:<PASSWORD>END_PI" updateYourPassword: "PI:PASSWORD:<PASSWORD>END_PI" password: "PI:PASSWORD:<PASSWORD>END_PI" usernameOrEmail: "Uporabniško ime ali email" email: "Email" ifYouAlreadyHaveAnAccount: "Če si že registriran(a)," signUpWithYourEmailAddress: "Prijava z email naslovom" username: "Uporabniško ime" optional: "Po želji" signupCode: "Prijavna koda" clickAgree: "S klikom na Registracija se strinjaš" privacyPolicy: "z našimi pogoji uporabe" terms: "Pogoji uporabe" sign: "Prijava" configure: "Nastavi" with: "z" createAccount: "Nova registracija" verificationPending: "Confirm your email address" verificationPendingDetails: "A confirmation email has been sent to the email address you provided. Click on the confirmation link in the email to activate your account." and: "in" "Match failed": "Prijava neuspešna" "User not found": "Uporabnik ne obstaja" "Incorrect password": "PI:PASSWORD:<PASSWORD>END_PI" "Email already exists.": "Email že obstaja." "Email is required": "Email je obvezen podatek" error: minChar: "Geslo mora imeti vsaj sedem znakov." pwOneLetter: "V geslu mora biti vsaj ena črka." pwOneDigit: "V geslu mora biti vsaj ena številka." usernameRequired: "Uporabniško ime je obvezen vnos." emailRequired: "Email je obvezen vnos." signupCodeRequired: "Prijavna koda je obvezen vnos." signupCodeIncorrect: "Prijavna koda je napačna." signInRequired: "Za to moraš biti prijavljen(a)." usernameIsEmail: "Uporabniško ime ne more biti email naslov." T9n.map "sl", sl
[ { "context": ">\n req = glacier.listVaults(accountId: 'ABC123')\n req.emit('validate', [req])\n req", "end": 682, "score": 0.830812931060791, "start": 679, "tag": "KEY", "value": "123" } ]
test/services/glacier.spec.coffee
dconnolly/aws-sdk-js
0
helpers = require('../helpers') AWS = helpers.AWS Buffer = AWS.util.Buffer if AWS.util.isNode() describe 'AWS.Glacier', -> glacier = null agentHeader = null if AWS.util.isBrowser() agentHeader = 'X-Amz-User-Agent' else agentHeader = 'User-Agent' beforeEach -> glacier = new AWS.Glacier() describe 'building requests', -> it 'sets accountId to "-" if not set', -> req = glacier.listVaults() req.emit('validate', [req]) req.emit('build', [req]) expect(req.httpRequest.path).to.equal('/-/vaults') it 'will not override accountId if set', -> req = glacier.listVaults(accountId: 'ABC123') req.emit('validate', [req]) req.emit('build', [req]) expect(req.httpRequest.path).to.equal('/ABC123/vaults') it 'computes the SHA 256 checksum header only once', -> spy = helpers.spyOn(AWS.util.crypto, 'sha256').andCallThrough() # Compute checksum of <= 1 megabyte buffer # This will invoke AWS.util.crypto.sha256() only once req = glacier.uploadArchive(vaultName: 'foo', body: 'bar') req.removeAllListeners('sign') req.build() expect(spy.calls.length).to.eql(1) it 'adds linear and tree hash headers to payload requests', -> headers = 'x-amz-glacier-version': '2012-06-01' 'X-Amz-Content-Sha256': 'fcde2b2edba56bf408601fb721fe9b5c338d10ee429ea04fae5511b68fbf8fb9' 'x-amz-sha256-tree-hash': 'fcde2b2edba56bf408601fb721fe9b5c338d10ee429ea04fae5511b68fbf8fb9' 'Content-Length': 3 Host: 'glacier.mock-region.amazonaws.com' headers[agentHeader] = AWS.util.userAgent() req = glacier.uploadArchive(vaultName: 'foo', body: 'bar') req.removeAllListeners('sign') req.build() expect(req.httpRequest.headers).to.eql(headers) describe 'computeChecksums', -> it 'returns correct linear and tree hash for buffer data', -> # compute a 5.5 megabyte chunk of data filled with '0' string (0 byte) # expected values taken from AWS SDK for Ruby data = new Buffer(1024 * 1024 * 5.5) data.fill('0') expected = linearHash: '68aff0c5a91aa0491752bfb96e3fef33eb74953804f6a2f7b708d5bcefa8ff6b', treeHash: '154e26c78fd74d0c2c9b3cc4644191619dc4f2cd539ae2a74d5fd07957a3ee6a' expect(glacier.computeChecksums(data)).to.eql(expected) describe 'initiateJob', -> it 'correctly builds the request', -> helpers.mockHttpResponse 200, {}, '' params = vaultName: 'vault-name' jobParameters: Format: 'foo' Type: 'bar' glacier.initiateJob params, (err, data) -> req = this.request.httpRequest expect(req.path).to.equal('/-/vaults/vault-name/jobs') expect(req.body).to.equal('{"Format":"foo","Type":"bar"}') describe 'uploadArchive', -> it 'passes the body along', -> helpers.mockHttpResponse 200, {}, '' params = vaultName: 'vault-name' body: 'abc' glacier.uploadArchive params, (err, data) -> req = this.request.httpRequest expect(req.method).to.equal('POST') expect(req.path).to.equal('/-/vaults/vault-name/archives') expect(req.body).to.equal('abc')
127598
helpers = require('../helpers') AWS = helpers.AWS Buffer = AWS.util.Buffer if AWS.util.isNode() describe 'AWS.Glacier', -> glacier = null agentHeader = null if AWS.util.isBrowser() agentHeader = 'X-Amz-User-Agent' else agentHeader = 'User-Agent' beforeEach -> glacier = new AWS.Glacier() describe 'building requests', -> it 'sets accountId to "-" if not set', -> req = glacier.listVaults() req.emit('validate', [req]) req.emit('build', [req]) expect(req.httpRequest.path).to.equal('/-/vaults') it 'will not override accountId if set', -> req = glacier.listVaults(accountId: 'ABC<KEY>') req.emit('validate', [req]) req.emit('build', [req]) expect(req.httpRequest.path).to.equal('/ABC123/vaults') it 'computes the SHA 256 checksum header only once', -> spy = helpers.spyOn(AWS.util.crypto, 'sha256').andCallThrough() # Compute checksum of <= 1 megabyte buffer # This will invoke AWS.util.crypto.sha256() only once req = glacier.uploadArchive(vaultName: 'foo', body: 'bar') req.removeAllListeners('sign') req.build() expect(spy.calls.length).to.eql(1) it 'adds linear and tree hash headers to payload requests', -> headers = 'x-amz-glacier-version': '2012-06-01' 'X-Amz-Content-Sha256': 'fcde2b2edba56bf408601fb721fe9b5c338d10ee429ea04fae5511b68fbf8fb9' 'x-amz-sha256-tree-hash': 'fcde2b2edba56bf408601fb721fe9b5c338d10ee429ea04fae5511b68fbf8fb9' 'Content-Length': 3 Host: 'glacier.mock-region.amazonaws.com' headers[agentHeader] = AWS.util.userAgent() req = glacier.uploadArchive(vaultName: 'foo', body: 'bar') req.removeAllListeners('sign') req.build() expect(req.httpRequest.headers).to.eql(headers) describe 'computeChecksums', -> it 'returns correct linear and tree hash for buffer data', -> # compute a 5.5 megabyte chunk of data filled with '0' string (0 byte) # expected values taken from AWS SDK for Ruby data = new Buffer(1024 * 1024 * 5.5) data.fill('0') expected = linearHash: '68aff0c5a91aa0491752bfb96e3fef33eb74953804f6a2f7b708d5bcefa8ff6b', treeHash: '154e26c78fd74d0c2c9b3cc4644191619dc4f2cd539ae2a74d5fd07957a3ee6a' expect(glacier.computeChecksums(data)).to.eql(expected) describe 'initiateJob', -> it 'correctly builds the request', -> helpers.mockHttpResponse 200, {}, '' params = vaultName: 'vault-name' jobParameters: Format: 'foo' Type: 'bar' glacier.initiateJob params, (err, data) -> req = this.request.httpRequest expect(req.path).to.equal('/-/vaults/vault-name/jobs') expect(req.body).to.equal('{"Format":"foo","Type":"bar"}') describe 'uploadArchive', -> it 'passes the body along', -> helpers.mockHttpResponse 200, {}, '' params = vaultName: 'vault-name' body: 'abc' glacier.uploadArchive params, (err, data) -> req = this.request.httpRequest expect(req.method).to.equal('POST') expect(req.path).to.equal('/-/vaults/vault-name/archives') expect(req.body).to.equal('abc')
true
helpers = require('../helpers') AWS = helpers.AWS Buffer = AWS.util.Buffer if AWS.util.isNode() describe 'AWS.Glacier', -> glacier = null agentHeader = null if AWS.util.isBrowser() agentHeader = 'X-Amz-User-Agent' else agentHeader = 'User-Agent' beforeEach -> glacier = new AWS.Glacier() describe 'building requests', -> it 'sets accountId to "-" if not set', -> req = glacier.listVaults() req.emit('validate', [req]) req.emit('build', [req]) expect(req.httpRequest.path).to.equal('/-/vaults') it 'will not override accountId if set', -> req = glacier.listVaults(accountId: 'ABCPI:KEY:<KEY>END_PI') req.emit('validate', [req]) req.emit('build', [req]) expect(req.httpRequest.path).to.equal('/ABC123/vaults') it 'computes the SHA 256 checksum header only once', -> spy = helpers.spyOn(AWS.util.crypto, 'sha256').andCallThrough() # Compute checksum of <= 1 megabyte buffer # This will invoke AWS.util.crypto.sha256() only once req = glacier.uploadArchive(vaultName: 'foo', body: 'bar') req.removeAllListeners('sign') req.build() expect(spy.calls.length).to.eql(1) it 'adds linear and tree hash headers to payload requests', -> headers = 'x-amz-glacier-version': '2012-06-01' 'X-Amz-Content-Sha256': 'fcde2b2edba56bf408601fb721fe9b5c338d10ee429ea04fae5511b68fbf8fb9' 'x-amz-sha256-tree-hash': 'fcde2b2edba56bf408601fb721fe9b5c338d10ee429ea04fae5511b68fbf8fb9' 'Content-Length': 3 Host: 'glacier.mock-region.amazonaws.com' headers[agentHeader] = AWS.util.userAgent() req = glacier.uploadArchive(vaultName: 'foo', body: 'bar') req.removeAllListeners('sign') req.build() expect(req.httpRequest.headers).to.eql(headers) describe 'computeChecksums', -> it 'returns correct linear and tree hash for buffer data', -> # compute a 5.5 megabyte chunk of data filled with '0' string (0 byte) # expected values taken from AWS SDK for Ruby data = new Buffer(1024 * 1024 * 5.5) data.fill('0') expected = linearHash: '68aff0c5a91aa0491752bfb96e3fef33eb74953804f6a2f7b708d5bcefa8ff6b', treeHash: '154e26c78fd74d0c2c9b3cc4644191619dc4f2cd539ae2a74d5fd07957a3ee6a' expect(glacier.computeChecksums(data)).to.eql(expected) describe 'initiateJob', -> it 'correctly builds the request', -> helpers.mockHttpResponse 200, {}, '' params = vaultName: 'vault-name' jobParameters: Format: 'foo' Type: 'bar' glacier.initiateJob params, (err, data) -> req = this.request.httpRequest expect(req.path).to.equal('/-/vaults/vault-name/jobs') expect(req.body).to.equal('{"Format":"foo","Type":"bar"}') describe 'uploadArchive', -> it 'passes the body along', -> helpers.mockHttpResponse 200, {}, '' params = vaultName: 'vault-name' body: 'abc' glacier.uploadArchive params, (err, data) -> req = this.request.httpRequest expect(req.method).to.equal('POST') expect(req.path).to.equal('/-/vaults/vault-name/archives') expect(req.body).to.equal('abc')
[ { "context": "-field input').attr('value')\n data = {username: username, password: pw}\n GG.statemanager.send 'login', ", "end": 829, "score": 0.920866847038269, "start": 821, "tag": "USERNAME", "value": "username" }, { "context": "'value')\n data = {username: username, pass...
app/src/views/views.coffee
concord-consortium/genigames
0
minispade.require 'genigames/views/view-mixins' minispade.require 'genigames/views/drake-view' minispade.require 'genigames/views/meiosis-animation' GG.LoginView = Ember.View.extend templateName: 'login' username: "" password: "" loggingInBinding: 'GG.sessionController.loggingIn' errorBinding: 'GG.sessionController.error' firstTimeBinding: 'GG.sessionController.firstTime' waitingForPreloadBinding: 'GG.sessionController.waitingForPreload' registeredUsernameBinding: 'GG.sessionController.registeredUsername' registrationErrorBinding: 'GG.sessionController.registrationError' registrationErrorMessageBinding: 'GG.sessionController.registrationErrorMessage' login: -> pw = @get('password') @set('password', "") username = $('#username-field input').attr('value') data = {username: username, password: pw} GG.statemanager.send 'login', data showClassWord: -> GG.statemanager.send 'showClassWord' register: -> GG.statemanager.send 'register' GG.LogoutButton = Ember.View.extend tagName: 'div' classNames: 'logout' template: Ember.Handlebars.compile('<div>Logout</div>') click: -> GG.statemanager.transitionTo 'loggingOut' GG.GoToTownButton = Ember.View.extend GG.PointsToolTip, tagName: 'div' classNames: 'goToTown' toolTipText: "Reset task and go back to town" isShowingBreederBinding: 'GG.breedingController.isShowingBreeder2' hidden: (-> not @get('isShowingBreeder') ).property('isShowingBreeder') classNameBindings: ['hidden'] click: -> GG.statemanager.send 'goToTown' GG.GoToWorldButton = Ember.View.extend GG.PointsToolTip, tagName: 'div' classNames: 'goToWorld' toolTipText: "Click to leave the town" click: -> GG.statemanager.send 'goToWorld' GG.BackToTaskListButton = Ember.View.extend tagName: 'div' classNames: 'task-list' template: Ember.Handlebars.compile('<div>Challenge List</div>') click: -> GG.statemanager.transitionTo 'inTaskList' GG.ChooseClassView = Ember.View.extend templateName: 'choose-class' optionsBinding: 'GG.sessionController.classesWithLearners' clazz: null choose: -> GG.statemanager.send 'chooseLearner', @get('clazz') GG.DefineGroupsView = Ember.View.extend tagName: 'div' elementId: 'define-groups' templateName: 'define-groups' groupsBinding: 'GG.groupsController.groups' errorBinding: 'GG.groupsController.error' removeUser: (evt)-> GG.groupsController.removeUser(evt.context) addUser: -> GG.groupsController.addUser() done: -> console.log("done called") GG.groupsController.verifyContent() unless GG.groupsController.get('error') GG.statemanager.send 'definedGroups' GG.WorldView = Ember.View.extend templateName: 'world' contentBinding: 'GG.townsController' GG.WorldTownView = Ember.View.extend classNameBindings: ['icon','location','enabled','completed','locked'] attributeBindings: ['style'] location: "location" icon: (-> @get('content.icon') ).property('content.icon') enabledBinding: 'content.enabled' completedBinding: 'content.completed' locked: (-> @get('content.locked') and not @get('content.enabled') ).property('content.locked', 'content.enabled') style: (-> # width and height are always set to 175x125 regardless of the icon size (image is always centered in this box). width = 175 height = 125 a = 216 # x position of the center of the world (relative to the world div) b = 216 # y position of the center of the world (relative to the world div) r = 216 n = 28 # n is the number to adjust the icon in the world # adjust the radius to be a little bigger because the center of the town icons cannot be in the edge of the world # instead, each town icon image should have the "bottom" exactly at n pixels higher than the bottom of the image r = r + (height/2) r = r - n # calculate the position of the town based on the position # with the center at a,b, r = radius, t = angle: # (a + r cos t, b + r sin t) # add 90 since the equation assumes 0 is on the right of the circle, not top # subtract because the coordinate posRadX = (@get('content.position') + 90) * (Math.PI/180) # subtract for Y since the coordinate system is mirrored on the Y-axis posRadY = (@get('content.position') - 90) * (Math.PI/180) x = Math.round(a + (r * Math.cos(posRadX)) - (width/2)) y = Math.round(b + (r * Math.sin(posRadY)) - (height/2)) return "left: " + x + "px; top: " + y + "px; " + @get('rotation') ).property('content.position') rotation: (-> rot = "rotate(-" + @get('content.position') + "deg); " return "transform: " + rot + "-ms-transform: " + rot + "-webkit-transform: " + rot + "-o-transform: " + rot + "-moz-transform: " + rot ).property('content.position') click: -> GG.statemanager.send 'townSelected', @get('content') GG.BreederView = Ember.View.extend templateName: 'breeder-view' breedTypeBinding: 'GG.breedingController.breedType' isBaselineBinding: 'GG.baselineController.isBaseline' hasObstacleCourseBinding: 'GG.obstacleCourseController.hasObstacleCourse' baseline: (-> if @get('isBaseline') then "baseline" else "game" ).property('isBaseline') meiosisEnabledBinding: 'GG.tasksController.meiosisControlEnabled' showAllTraits: (-> townId = GG.townsController.get("content").indexOf GG.townsController.get "currentTown" return (townId > 1) ).property('GG.townsController.currentTown') GG.TraitSelectionView = Ember.View.extend GG.PointsToolTip, templateName: 'trait-selection' showAllTraits: (-> townId = GG.townsController.get("content").indexOf GG.townsController.get "currentTown" return (townId > 1) ).property('GG.townsController.currentTown') toolTipText: "Use the buttons to keep track of the traits you are breeding for" toolTipConfigTooltip: 'bottomRight' toolTipConfigTip: 'bottomRight' characteristicSelected: (evt) -> elem = evt.currentTarget container = elem.parentElement characteristic = ""+evt.context wasSelected = $(elem).hasClass("selected") $(container).find(".characteristic").removeClass("selected") $(elem).addClass("selected") unless wasSelected GG.logController.logEvent (unless wasSelected then GG.Events.SELECTED_CHARACTERISTIC else GG.Events.DESELECTED_CHARACTERISTIC), trait: container.classList[1] characteristic: characteristic GG.statemanager.send 'selectTrait', characteristic traits: (-> initialTraits = [ {trait: "gender", characteristics: ["male", "female"]} {trait: "wings", characteristics: ["wings", "no-wings"]} {trait: "metallic", characteristics: ["metallic", "non-metallic"]} {trait: "horns", characteristics: ["reverse-horns", "forward-horns"]} {trait: "fire", characteristics: ["no-fire", "fire"]} ] if !@get 'showAllTraits' return initialTraits else return initialTraits.concat [ {trait: "color", characteristics: ["green", "purple", "blue", "red"]} {trait: "spikes", characteristics: ["wide-spikes", "medium-spikes", "narrow-spikes"]} {trait: "tail", characteristics: ["short-tail", "kinked-tail", "long-tail"]} {trait: "armor", characteristics: ["armor", "no-armor"]} ] ).property('showAllTraits') GG.ParentPoolView = Ember.View.extend templateName: 'parent-pool-view' contentBinding: 'controller.content' drakeSelected: (evt) -> drake = evt.context GG.statemanager.send 'parentSelected', drake drakeRemoved: (evt) -> drake = evt.context GG.statemanager.send 'parentRemoved', drake GG.FatherPoolView = GG.ParentPoolView.extend GG.PointsToolTip, controllerBinding: 'GG.fatherPoolController' toolTipText: "Choose from these males for breeding the target drake" toolTipConfigTarget: 'bottomMiddle' toolTipConfigTooltip: 'topLeft' toolTipConfigTip: 'topLeft' GG.MotherPoolView = GG.ParentPoolView.extend GG.PointsToolTip, controllerBinding: 'GG.motherPoolController' toolTipText: "Choose from these females for breeding the target drake" toolTipConfigTarget: 'bottomMiddle' toolTipConfigTooltip: 'topLeft' toolTipConfigTip: 'topLeft' GG.OffspringPoolView = Ember.View.extend drakeSelected: (evt) -> GG.BreedButtonView = Ember.View.extend GG.PointsToolTip, tagName: 'div' toolTipText: (-> tip = "Produce an offspring %@ from the current parents".fmt(Ember.I18n.t('drake')) ).property() costPropertyName: 'extraBreedCycle' motherBinding: 'GG.parentController.selectedMother' fatherBinding: 'GG.parentController.selectedFather' classNameBindings : ['enabled'] inAnimationBinding: 'GG.meiosisController.inAnimation' canBreedDuringAnimationBinding: 'GG.meiosisController.canBreedDuringAnimation' enabled: (-> if !this.get('mother') || !this.get('father') return false else if @get('inAnimation') && !@get('canBreedDuringAnimation') return false else return true ).property('mother', 'father', 'inAnimation', 'canBreedDuringAnimation') click: -> if @get 'enabled' GG.statemanager.send('breedDrake') GG.AlleleView = Ember.View.extend GG.PointsToolTip, classNameBindings: ['defaultClassNames', 'revealable', 'dominant', 'gene', 'species'] defaultClassNames: 'allele' valueBinding: 'content.allele' species: (-> GG.DrakeSpecies.name ).property() hiddenValue: (-> value = @get 'value' value.charAt(0) + "?" ).property('value').cacheable() clickable: true hidden: Ember.computed.not('content.visible') revealable: (-> return @get('hidden') and @get('clickable') ).property('hidden','clickable') dominant: (-> ending = @get('displayValue').slice(-1) if ending is "1" return "dominant" else if ending is "2" return "recessive" else if ending is "3" return "recessive3" else return "" ).property('displayValue') gene: (-> if @get('value')? return BioLogica.Genetics.getGeneOfAllele(GG.DrakeSpecies, @get('value')).name else return '' ).property('value') displayValue: (-> if @get('hidden') then @get('hiddenValue') else @get('value') ).property('value','hidden') forceTooltip: true toolTipText: (-> text = "" if @get('revealable') then text += "Reveal hidden allele.<br/>" if GG.tooltipController.get('show') then text += "The orange circles show you which version, or allele, of a gene is on a particular chromosome. Every gene has different versions. Together, the letter and number in the allele circle show you the version of the gene." text ).property('revealable', 'GG.tooltipController.show') costPropertyName: (-> if @get('revealable') 'alleleRevealed' else null ).property('revealable') GG.ChromoView = Ember.View.extend GG.PointsToolTip, templateName: 'chromosome' content: null chromo: '1' side: 'a' sister: null crossoverSelectable: false selectable: false selected: false hiddenGenesBinding: 'GG.drakeController.hiddenGenes' visibleGenesBinding: 'GG.drakeController.visibleGenes' revealedContentAllelesIdxBinding: 'content.revealedIdx' revealedAlleles: null gametes: null useGamete: false realSide: (-> realSide = '' if ['x2','y','b'].contains(@get('side')) realSide = 'b' else realSide = 'a' realSide += @get('sister') return realSide ).property('sister','side') cellNum: (-> if @get('gametes')? endInfo = @get('gametes').endCellInfo chromo = @get('chromo') chromo = if chromo == "X" or chromo == "Y" then "XY" else chromo cellNum = endInfo[chromo][@get 'realSide'] else cellNum = -1 return cellNum ).property('chromo','realSide','gametes') gamete: (-> if @get('cellNum') != -1 cell = @get('gametes').cells[@get('cellNum')] chromo = @get 'chromo' chromo = if chromo == 'X' or chromo == 'Y' then 'XY' else chromo return cell[chromo] else return null ).property('gametes','chromo','cellNum') visibleGamete: (-> @_filterGamete('gamete',false) ).property('gamete', 'visibleGenes') hiddenGamete: (-> @_filterGamete('gamete',true) ).property('gamete', 'hiddenGenes') _filterGamete: (prop, hidden)-> res = null if @get(prop)?.alleles gamete = @get(prop) genesProp = if hidden then 'hiddenGenes' else 'visibleGenes' genes = @get(genesProp) || [] res = GG.Genetics.filter(gamete.alleles, genes) # Now add or subtract the revealed alleles from the result if gamete.revealed? if hidden res = res.filter (item)-> return !gamete.revealed.contains(item) else res = res.concat(gamete.revealed).uniq().compact() return res biologicaChromoName: (-> chromo = @get 'chromo' return chromo unless chromo is "X" or chromo is "Y" return "XY" ).property('chromo') genes: (-> GG.Genetics.species.chromosomeGeneMap[@get 'biologicaChromoName'] ).property('chromo') visibleAlleles: (-> return @_getAlleles(false) ).property('chromo','content','side','visibleGamete','revealedAlleles','revealedContentAllelesIdx','useGamete') hiddenAlleles: (-> return @_getAlleles(true) ).property('chromo','content','side','hiddenGamete','revealedAlleles','revealedContentAllelesIdx','useGamete') alleles: (-> bioChromo = @get('content.biologicaOrganism').genetics.genotype.chromosomes["1"]["a"] vis = @get('visibleAlleles').map (item)-> {allele: item, visible: true, position: bioChromo.getAllelesPosition(item)} hid = @get('hiddenAlleles').map (item)-> {allele: item, visible: false, position: bioChromo.getAllelesPosition(item)} alleles = vis.concat(hid) alleles = alleles.sort (a,b)=> if a.position > b.position then 1 else -1 return alleles ).property('visibleAlleles','hiddenAlleles') _getAlleles: (hidden)-> gamete = if hidden then 'hiddenGamete' else 'visibleGamete' res = [] if (@get 'content')? or (@get gamete)? if @get('useGamete') && (@get gamete)? res = @get gamete else prop = if hidden then 'content.hiddenGenotype' else 'content.visibleGenotype' fullGeno = @get prop side = @get 'side' if ['x2','y'].contains(side) side = 'b' else if side is 'x1' side = 'a' geno = fullGeno[side] res = GG.Genetics.filter(geno, @get 'genes') return res click: -> if @get('selectable') # toggle selected if @get('selected') @set('selected', false) GG.statemanager.send 'deselectedChromosome', this else @set('selected', true) GG.statemanager.send 'selectedChromosome', this allelesClickableDefault: true allelesClickable: (-> return @get('allelesClickableDefault') and GG.baselineController.get('isNotBaseline') ).property('allelesClickableDefault','GG.baselineController.isNotBaseline') alleleClicked: (event) -> if @get('allelesClickable') allele = event.context if !allele.visible @get('content').markRevealed(@get('side'), allele.allele) GG.reputationController.subtractReputation(GG.actionCostsController.getCost('alleleRevealed'), GG.Events.REVEALED_ALLELE) GG.logController.logEvent GG.Events.REVEALED_ALLELE, allele: allele.allele side: @get('side') drake: { alleles: @get('content.biologicaOrganism.alleles') sex: @get('content.sex') } defaultClass: 'chromosome' chromoName: (-> 'chromo-'+@get('chromo') ).property('chromo','side') right: (-> if @get('chromo') == 'Y' or ['b','y','x2'].contains(@get('side')) then "right" else "left" ).property('chromo','side') parent: (-> if ['a','x1'].contains(@get('side')) then 'mother' else 'father' ).property('chromo','side') sisterClass: (-> if (@get 'sister')? return "sister-" + @get('sister') else return "" ).property('sister') cell: (-> cellNum = @get('cellNum') if cellNum == -1 return '' else return 'cell' + cellNum ).property('cellNum') hidden: false classNames: ['chromosome'] classNameBindings: ['chromoName', 'right', 'parent', 'sisterClass', 'hidden', 'cell', 'selectable', 'selected'] toolTipText: (-> name = @get('biologicaChromoName') sex = @get('content.sex') if name is "XY" if sex "These are the sex chromosomes. Females have two X chromosomes. This is what makes them female." else "These are the sex chromosomes. Males have an X and a Y chromosome. This is what makes them male." else gender = if sex then "female" else "male" "These are the #{gender}'s chromosomes. All drakes have 3 pairs of chromosomes: pair 1, pair 2, and the sex chromosomes. Chromosomes contain genes and are made of DNA and protein." ).property() toolTipConfigTarget: (-> if @get('content.sex') then "topMiddle" else "bottomMiddle" ).property() toolTipConfigTooltip: (-> if @get('content.sex') then "bottomRight" else "topRight" ).property() toolTipConfigTip: (-> if @get('content.sex') then "bottomRight" else "topRight" ).property() GG.ChromosomePanelView = Ember.View.extend templateName: 'chromosome-panel' hiddenBinding: 'controller.hidden' defaultClass: 'chromosome-panel' chromosomeClass: (-> if @get('controller.selected.sex') is GG.FEMALE then 'female-chromosome' else 'male-chromosome' ).property('controller.selected').cacheable() classNameBindings: ['hidden','defaultClass', 'chromosomeClass'] GG.CrossoverPointView = Ember.View.extend tagName: 'div' classNames: ['crossoverPoint','hidden'] classNameBindings: ['gene','species'] allele: null chromoView: null gene: (-> return BioLogica.Genetics.getGeneOfAllele(GG.DrakeSpecies, @get('allele'))?.name ).property('allele') species: (-> GG.DrakeSpecies.name ).property() click: -> GG.statemanager.send 'selectedCrossover', {chromoView: @get('chromoView'), allele: @get('allele')} GG.EggView = Ember.View.extend GG.Animation, tagName: 'div' hidden: Ember.computed.not('GG.breedingController.isBreeding') classNameBindings: ['hidden'] onShow: -> @$().css({backgroundPosition: '0px 0px'}) @animate(properties: {rotate: '0deg'}, delay: 0) @animateSequence sequence: [properties: {rotate: '+=20deg'}, duration: 50, properties: {rotate: '-=20deg'}, duration: 50] delay: 700 repeat: 3 callback: => @$().css({backgroundPosition: '0px -140px'}) GG.OffspringBackButtonView = Ember.View.extend GG.PointsToolTip, tagName: 'div' toolTipText: "Go back and select different parents. This gives you a chance to get different alleles." classNames : 'offspring-buttons-back' click: -> GG.statemanager.send('selectParents') GG.OffspringUseButtonView = Ember.View.extend GG.PointsToolTip, tagName: 'div' toolTipText: (-> "Submit the current %@ as the solution to this task".fmt(Ember.I18n.t('drake')) ).property() classNames : 'offspring-buttons-use' click: -> GG.statemanager.send('submitOffspring') GG.OffspringSaveButtonView = Ember.View.extend GG.PointsToolTip, tagName: 'div' toolTipText: (-> if !GG.breedingController.get 'childSavedToParents' "Use this %@ as a parent".fmt(Ember.I18n.t('drake')) else "Already saved this %@! Press the Back button to select parents.".fmt(Ember.I18n.t('drake')) ).property('GG.breedingController.childSavedToParents') classNames : 'offspring-buttons-save' classNameBindings: ['disabled'] disabled: (-> !GG.powerUpController.hasPowerup("backcrossing") or GG.breedingController.get('childSavedToParents') ).property('GG.breedingController.childSavedToParents') click: -> return if @get 'disabled' @set 'disabled', true GG.statemanager.send('saveOffspring') GG.ValueCounter = Ember.View.extend GG.PointsToolTip, templateName: 'move-counter' classNames: ['value-counter'] toolTipText: "This is the amount you're being offered for breeding the target drake" toolTipConfigTarget: 'topMiddle' toolTipConfigTooltip: 'bottomRight' toolTipConfigTip: 'bottomRight' GG.MoveCounter = Ember.View.extend GG.PointsToolTip, templateName: 'move-counter' classNames: ['cost-counter'] toolTipText: "This tracks how much you have spent to breed, select chromosomes, and do crossovers" GG.MatchGoalCounter = Ember.View.extend templateName: 'match-goal-counter' targetCountBinding: Ember.Binding.oneWay('GG.tasksController.targetCount') classNameBindings: ['hidden','defaultClass'] defaultClass: 'match-goal-counter' hidden: (-> @get('targetCount') <= 1 ).property('targetCount') GG.TownView = Ember.View.extend templateName: 'town' contentBinding: 'GG.tasksController' backgroundBinding: 'GG.townsController.currentTown.background' GG.TaskNPCView = Ember.View.extend tagName : 'div' classNames : ['npc'] classNameBindings : ['npcLocationState','hidden'] attributeBindings : ['style'] hidden: (-> !(@get('content.completed') || @get('content.showInForeground') ) ).property('content.completed', 'content.showInForeground') style: (-> return "" if @get('content.showInForeground') scale = @get('content.npc.scale') || 0.5 layer = @get('content.npc.layer') || 1 flip = @get('content.npc.flip') || false if flip then xModifier = -1 else xModifier = 1 style = "top: " + @get('content.npc.position.y') + "px; left: " + @get('content.npc.position.x') + "px;" style += "z-index: #{layer-1};" for vendor in ["-webkit-", "-moz-", "-ms-", "-o-", ""] style += "#{vendor}transform: scaleX(#{scale * xModifier}) scaleY(#{scale});" style += "#{vendor}transform-origin: 0 0;" return style ).property('content.npc.position.x','content.npc.position.y', 'content.npc.position.scale','content.showInForeground') npcLocationState: (-> if @get('content.showInForeground') then @get('content.foregroundLocation') else "background" ).property('content.showInForeground') npcSelected: (evt) -> GG.statemanager.send 'npcSelected', evt.context replayTask: (evt) -> GG.statemanager.send 'replayTask', evt.context GG.NPCView = Ember.View.extend GG.PointsToolTip, tagName : 'img' classNames : ['character'] attributeBindings : ['src'] srcBinding : 'content.npc.imageURL' GG.NPCQuestionBubbleView = Ember.View.extend GG.Animation, tagName : 'img' classNames : ['bubble'] classNameBindings : ['hidden'] attributeBindings : ['src'] src : '../images/bubble-question.png' hidden : Ember.computed.not('content.showQuestionBubble') onShow: -> @animateSequence sequence: [properties: {top: "-=20px"}, duration: 200, easing: 'easeOutCubic', properties: {top: "+=20px"}, duration: 200, easing: 'easeInCubic'] delay: 200 repeat: 2 mouseEnter: -> # stop(true, true) is necessary so that we don't end up with a slowly enlarging/shrinking image... @$().stop(true, true).animate({width: "+=20px", height: "+=17px", top: "-=10px", left: "-=8px"}, 100, 'easeOutCubic') mouseLeave: -> @$().stop(true, true).animate({width: "-=20px", height: "-=17px", top: "+=10px", left: "+=8px"}, 100, 'easeOutCubic') GG.NPCSpeechBubbleView = Ember.View.extend tagName : 'div' classNames : ['speech-bubble'] classNameBindings : ['hidden'] hidden : Ember.computed.not('content.showSpeechBubble') init : -> @_super() currentText : (-> if @get 'isShowingEndMessage' text = @get 'content.npc.speech.completionText' else if @get 'isShowingThanksMessage' text = "Thanks again!" else if @get 'isShowingFailMessage' text = @get('content.npc.speech.failText') || "That's not the drake I'm looking for!" else text = @get 'content.npc.speech.text' if typeof text == "string" then text else text[0] ).property('content.npc.speech.text', 'isShowingEndMessage', 'isShowingThanksMessage', 'isShowingFailMessage') text : (-> currentText = @get 'currentText' text = currentText.replace("<name>", GG.userController.get('user.first')) text = text.replace(/\[(.*?)\]/g, "") # rm button text return new Handlebars.SafeString(text) ).property('currentText') continueButtonText: "Continue" acceptText: (-> @get('content.npc.speech.accept') || "Sure" ).property('content.npc.speech.accept') declineText: (-> @get('content.npc.speech.decline') || "Maybe later" ).property('content.npc.speech.decline') isShowingEndMessageBinding: 'content.isShowingEndMessage' isShowingThanksMessageBinding: 'content.isShowingThanksMessage' isShowingFailMessageBinding: 'content.isShowingFailMessage' accept: -> GG.statemanager.send 'accept', @get 'content' decline: -> GG.statemanager.send 'decline' replay: -> GG.statemanager.send 'replay', @get 'content' done: -> GG.statemanager.send 'done' GG.NPCHeartBubbleView = Ember.View.extend GG.PointsToolTip, templateName : 'heart-bubble' classNames : ['heart-wrapper'] classNameBindings : ['hidden'] hidden : Ember.computed.not('content.completed') toolTipConfigTarget: 'bottomLeft' toolTipConfigTooltip: 'bottomRight' toolTipConfigTip : 'bottomRight' toolTipText: (-> taskNo = GG.tasksController.indexOf(@get('content')) + 1 tip = "Replay Drake #{taskNo}: #{@get('content.targetDrake')}" if GG.tooltipController.get 'show' tip += ".<br>Hearts show gratitude for a correctly bred drake. If the heart is not completely full, it means you can earn more by trying again and breeding more efficiently." tip ).property('content', 'GG.tooltipController.show') forceTooltip: true updateHeartFill: (-> score = @get('content.reputationEarned') / @get('content.reputationFullScore') height = 53 - (score * 37) # height is from top, min 53px, max 16px height = 16 if height < 16 height = 53 if height > 53 @$('.heart-bubble-empty-wrapper').css({height: height}) ).observes('content.reputationEarned') mouseEnter: -> # stop(true, true) is necessary so that we don't end up with a slowly enlarging/shrinking image... @$('img').stop(true, true).animate({width: "+=4px", height: "+=4px", top: "-=2px", left: "-=2px"}, 100, 'easeOutCubic') mouseLeave: -> @$('img').stop(true, true).animate({width: "-=4px", height: "-=4px", top: "+=2px", left: "+=2px"}, 100, 'easeOutCubic') GG.NPCFinalMessageBubbleView = Ember.View.extend tagName : 'div' text : (-> return new Handlebars.SafeString(GG.townsController.get("currentTown.finalMessage")) ).property('content') classNames : ['speech-bubble'] classNameBindings : ['hidden'] hidden : Ember.computed.not('content.showFinalMessageBubble') isFinalTaskBinding : 'content.finalTask' next: -> GG.statemanager.transitionTo 'inWorld.movingDirectlyToNextTown' world: -> @set 'content.showFinalMessageBubble', false GG.statemanager.transitionTo 'inWorld.townsWaiting' dismissFinalBubble: -> @set 'content.showFinalMessageBubble', false $('.goToWorld').mouseover() setTimeout (-> $('.goToWorld').qtip("hide")), 2500 GG.MeiosisView = Ember.View.extend GG.PointsToolTip, templateName: 'meiosis' tagName: 'div' content: null init: -> @_super() if @get('content')? @contentChanged() contentChanged: (-> GG.meiosisController.set(@get('motherFather') + "View", this) @_createGametes() ).observes('content') classNames: ['meiosis'] classNameBindings: ['motherFather'] motherFather: (-> if @get('content.sex') == GG.MALE then "father" else "mother" ).property('content') gametes: null useGametes: false currentTownBinding: 'GG.townsController.currentTown' crossoverCost: (-> GG.actionCostsController.getCost('crossoverMade') ).property('currentTown') chromosomeSelectedCost: (-> GG.actionCostsController.getCost('chromosomeSelected') ).property('currentTown') selectFirstParent: -> if @get('content.sex') == GG.MALE GG.statemanager.send 'selectFatherMeiosis' else GG.statemanager.send 'selectMotherMeiosis' rerender: -> @_super() setTimeout => @set('useGametes', false) GG.meiosisController.set(@get('motherFather') + "View", _this) , 200 _createGametes: -> meiosisControl = GG.tasksController.get 'currentTask.meiosisControl' doCrossover = if GG.breedingController.get('breedType') == GG.BREED_CONTROLLED and (meiosisControl is "crossover" or meiosisControl is "all") then false else true newGametes = @get('content.biologicaOrganism').createGametesWithCrossInfo(4, doCrossover)[0] @set 'gametes', newGametes return newGametes sistersHidden: true animate: (callback)-> newGametes = @_createGametes() # Transfer revealed status to new gametes... We can't do this earlier # because the meiosis view is created when the user selects the drake # and still has an opportunity to interact and reveal alleles before # the animation starts. revealed = @get('content.revealedAlleles') normalizedSide = (s)-> if ['x','x1','a'].contains(s) return 'a' else if ['y','x2','b'].contains(s) return 'b' for side of revealed alleles = revealed[side] continue if alleles.length == 0 nSide = normalizedSide(side) for i in [0...newGametes.cells.length] gamete = newGametes.cells[i] for c in ["1","2","XY"] chromo = gamete[c] for j in [0...alleles.length] allele = alleles[j] idx = chromo.alleles.indexOf(allele) if idx != -1 and normalizedSide(chromo.allelesWithSides[idx].side) is nSide chromo.revealed ?= [] chromo.revealed.push allele GG.MeiosisAnimation.animate(".meiosis." + @get('motherFather'), this, callback) resetAnimation: ()-> GG.MeiosisAnimation.reset(".meiosis." + @get('motherFather'), this) @set('gametes', null) crossOver: -> newGametes = @get('gametes') # Move the allele circles, then reset them back and set the gametes at the same time cells = newGametes.cells # moves is a data structure that outlines what is moving from where to where # { # "gene": {[to]: [from], [to]: [from], ...} # } moves = {} for own chr,crosses of newGametes.crossInfo continue unless crosses? for c in [0...crosses.length] cross = crosses[c] startingAlleles = cross.crossedAlleles if startingAlleles? for a in [0...startingAlleles.length] sAllele = startingAlleles[a][0] gene = BioLogica.Genetics.getGeneOfAllele(GG.DrakeSpecies, sAllele).name moves[gene] ?= {} end = moves[gene][cross.start_cell] end = cross.start_cell unless end? start = moves[gene][cross.end_cell] start = cross.end_cell unless start? moves[gene][cross.end_cell] = end moves[gene][cross.start_cell] = start @animateMoves moves, => @set('useGametes', true) animateMoves: (moves, callback)-> animationQueue = [] selectorBase = "#" + @get('elementId') scale = GG.MeiosisAnimation.get 'timeScale' for own gene,swaps of moves for own dest,source of swaps sourceSelector = selectorBase + " .cell" + source + " .allele." + gene destSelector = selectorBase + " .cell" + dest + " .allele." + gene s = $(sourceSelector) d = $(destSelector) sOffset = s.offset() dOffset = d.offset() continue unless sOffset? and dOffset? dx = dOffset.left - sOffset.left leftShift = (if dx > 0 then "+=" else "-=") + Math.abs(dx) + "px" animationQueue.push {source: sourceSelector, anim: {left: dx}} # temporarily put alleles on top, so we don't see them sliding under other chromosomes $(selectorBase + " .allele").css({"z-index": 10}) for i in [0...animationQueue.length] anim = animationQueue[i] $(anim.source).animate(anim.anim, GG.MeiosisAnimation.scale(1500), 'easeInOutQuad') setTimeout => callback() Ember.run.next this, => for i in [0...animationQueue.length] anim = animationQueue[i] $(anim.source).css({left: '', top: ''}) # put the alleles back at their default level, so they slide under/over $("#" + @get('elementId') + " .allele").css({"z-index": ''}) , GG.MeiosisAnimation.scale(1550) chromosomeSelectedBinding: 'GG.meiosisController.chromosomeSelected' crossoverSelectedBinding: 'GG.meiosisController.crossoverSelected' doneSelectingCrossoverButtonText: (-> if @get('crossoverSelected') then "Continue" else "Skip" ).property('crossoverSelected') doneSelectingChromatidsButtonText: (-> if @get('chromosomeSelected') then "Continue" else "Skip" ).property('chromosomeSelected') allelesClickable: false crossoverSelectable: false chromosomesSelectable: false selectingChromatids: (callback)-> @set('chromosomesSelectable', true) GG.statemanager.send 'selectingChromatids', {elementId: @get('elementId'), callback: callback} doneSelectingChromatids: -> @set('chromosomesSelectable', false) GG.statemanager.send 'doneSelectingChromatids', this selectingCrossover: (callback)-> @set('crossoverSelectable', true) @set('useGametes', true) GG.statemanager.send 'selectingCrossover', {elementId: @get('elementId'), callback: callback} doneSelectingCrossover: -> @set('crossoverSelectable', false) GG.statemanager.send 'doneSelectingCrossover', this randomGameteNumberOverride: -1 randomGameteNumber: (-> override = @get('randomGameteNumberOverride') if override == -1 return ExtMath.randomInt(4) else return override ).property('gametes', 'randomGameteNumberOverride') chosenSex: (-> if @get('content.sex') == GG.MALE and @get('chosenGamete')? and @get('chosenGamete').XY.side is 'y' then GG.MALE else GG.FEMALE ).property('gametes','randomGameteNumber') chosenGamete: (-> return null unless @get('gametes')? return @get('gametes').cells[@get('randomGameteNumber')] ).property('gametes','randomGameteNumber') chosenGameteAlleles: (-> chosen = @get('chosenGamete') return "" unless chosen? side = if @get('content.sex') == GG.MALE then 'b' else 'a' alleles = "" for c in ['1','2','XY'] chromoAlleles = chosen[c].alleles if chromoAlleles? and chromoAlleles.length > 0 alleles += "," + side + ":" + chromoAlleles.reduce (prev, item) -> return prev + "," + side + ":" + item return alleles.slice(1) ).property('chosenGamete') tooltipTarget: ".tooltip-target-2" toolTipText: (-> if @get('chromosomesSelectable') then return '' gender = if @get('content.sex') is GG.MALE then ["male","sperm"] else ["female","egg"] "This is a special kind of cell in the #{gender[0]} that is about to go through the process called meiosis. In #{gender[0]}s, meiosis makes four #{gender[1]} cells, each with one chromosome from each pair. " ).property('content', 'chromosomesSelectable') toolTipConfigTarget: (-> if @get('content.sex') is GG.MALE then 'bottomRight' else 'topRight' ).property('content') toolTipConfigTooltip: (-> if @get('content.sex') is GG.MALE then 'topLeft' else 'bottomLeft' ).property('content') toolTipConfigTip : (-> if @get('content.sex') is GG.MALE then 'topLeft' else 'bottomLeft' ).property('content') GG.MeiosisSpeedSliderView = Ember.View.extend GG.PointsToolTip, tagName: 'div' elementId: 'meiosis-speed-slider-parent' toolTipText: "Use this slider to speed up or slow down meiosis" toolTipConfigTooltip: 'bottomRight' toolTipConfigTip: 'bottomRight' toolTipConfigTarget: 'topMiddle' updateEnabled: (-> disabled = !GG.powerUpController.hasPowerup("speed control") $('#meiosis-speed-slider').slider("option", "disabled", disabled); ).observes('GG.powerUpController.powerupChanged', 'GG.tasksController.currentTask') didInsertElement: -> # slider can go from -Infinity to 1.9999. # For now, we'll just have 2 values: 0 and 1. # The smaller the slider value, the slower the animation will go. $('#meiosis-speed-slider').slider orientation: 'horizontal' value: (2 - GG.MeiosisAnimation.get('timeScale')) min: 0.5 max: 1.7 step: 0.01 change: (event,ui)-> GG.MeiosisAnimation.set('timeScale', (2 - ui.value)) GG.ObstacleCourseDialogView = Ember.View.extend elementId: 'obstacle-course-dialog' templateName: 'obstacle-course-dialog' tagName: 'div' courseBinding: 'GG.obstacleCourseController.course' obstaclesBinding: 'GG.obstacleCourseController.obstacles' drakeBinding: 'GG.obstacleCourseController.drake' taskReputationBinding: 'GG.reputationController.currentTaskReputation' extraBreedsRepBinding: 'GG.reputationController.extraBreedsRep' meiosisControlRepBinding: 'GG.reputationController.meiosisControlRep' alleleRevealRepBinding: 'GG.reputationController.alleleRevealRep' visibleBinding: 'GG.obstacleCourseController.dialogVisible' taskCompleteBinding: 'GG.obstacleCourseController.taskComplete' currentObstacleBinding: 'GG.obstacleCourseController.currentObstacle' myTotalTimeBinding: 'GG.obstacleCourseController.myTotalTime' opponentTotalTimeBinding: 'GG.obstacleCourseController.opponentTotalTime' nTrainingsBinding: 'GG.cyclesController.cycles' modeBinding: 'GG.obstacleCourseController.mode' trainingPoints: (-> @get('nTrainings') * GG.actionCostsController.getCost('cycleRemainingBonus') ).property('nTrainings') courseCompletionPoints: (-> GG.obstacleCourseController.get('reputationEarned') - @get('trainingPoints') ).property('GG.obstacleCourseController.reputationEarned', 'trainingPoints') isExternalObstacleCourse: (-> @get('mode') == GG.OBSTACLE_COURSE_EXTERNAL ).property('mode') tryAgain: -> # restart task GG.tasksController.restartCurrentTask() continueOn: -> # Go back to town GG.statemanager.transitionTo 'inTown' GG.ObstacleTimeView = Ember.View.extend tagName: 'div' obstacle: null breedsLeftBinding: 'GG.cyclesController.cycles' time: (-> time = GG.obstacleCourseController.calculateTime(@get('obstacle'), false) ).property('obstacle','breedsLeft') GG.ObstacleView = Ember.View.extend tagName: 'div' classNames: ['obstacle'] classNameBindings: ['type', 'after'] attributeBindings : ['style'] after: false skipStyle: false style: (-> if @get 'skipStyle' "" else "top: " + @get('content.positionY') + "px; left: " + @get('content.positionX') + "px;" ).property('content.positionY','content.positionX','skipStyle') typeBinding: "content.obstacle" GG.PasswordField = Ember.TextField.extend type: "password" value: "" loginView: null keyUp: (evt)-> @interpretKeyEvents(evt) if evt.keyCode == 13 and @get('loginView')? @get('loginView').login() GG.BaselineTaskListView = Ember.View.extend tagName: 'div' templateName: 'task-list' taskSelected: (evt) -> GG.statemanager.send 'taskSelected', evt.context GG.townUnlockView = Ember.View.extend templateName: 'town-unlock' contentBinding: 'GG.townsController' costBinding: 'content.nextTownsCost' showPayMessageBinding: 'content.canPayForNextTown' firstTown: (-> @get 'content.firstObject' ).property('content.[]') GG.HelpModeButton = Ember.View.extend GG.PointsToolTip, tagName: 'div' classNames: ['questionmark-button'] classNameBindings: ['active'] activeBinding: 'GG.tooltipController.show' forceTooltip: true toolTipText: "Click to get help by hovering over objects." click: -> GG.statemanager.send 'toggleHelpMode'
131031
minispade.require 'genigames/views/view-mixins' minispade.require 'genigames/views/drake-view' minispade.require 'genigames/views/meiosis-animation' GG.LoginView = Ember.View.extend templateName: 'login' username: "" password: "" loggingInBinding: 'GG.sessionController.loggingIn' errorBinding: 'GG.sessionController.error' firstTimeBinding: 'GG.sessionController.firstTime' waitingForPreloadBinding: 'GG.sessionController.waitingForPreload' registeredUsernameBinding: 'GG.sessionController.registeredUsername' registrationErrorBinding: 'GG.sessionController.registrationError' registrationErrorMessageBinding: 'GG.sessionController.registrationErrorMessage' login: -> pw = @get('password') @set('password', "") username = $('#username-field input').attr('value') data = {username: username, password: <PASSWORD>} GG.statemanager.send 'login', data showClassWord: -> GG.statemanager.send 'showClassWord' register: -> GG.statemanager.send 'register' GG.LogoutButton = Ember.View.extend tagName: 'div' classNames: 'logout' template: Ember.Handlebars.compile('<div>Logout</div>') click: -> GG.statemanager.transitionTo 'loggingOut' GG.GoToTownButton = Ember.View.extend GG.PointsToolTip, tagName: 'div' classNames: 'goToTown' toolTipText: "Reset task and go back to town" isShowingBreederBinding: 'GG.breedingController.isShowingBreeder2' hidden: (-> not @get('isShowingBreeder') ).property('isShowingBreeder') classNameBindings: ['hidden'] click: -> GG.statemanager.send 'goToTown' GG.GoToWorldButton = Ember.View.extend GG.PointsToolTip, tagName: 'div' classNames: 'goToWorld' toolTipText: "Click to leave the town" click: -> GG.statemanager.send 'goToWorld' GG.BackToTaskListButton = Ember.View.extend tagName: 'div' classNames: 'task-list' template: Ember.Handlebars.compile('<div>Challenge List</div>') click: -> GG.statemanager.transitionTo 'inTaskList' GG.ChooseClassView = Ember.View.extend templateName: 'choose-class' optionsBinding: 'GG.sessionController.classesWithLearners' clazz: null choose: -> GG.statemanager.send 'chooseLearner', @get('clazz') GG.DefineGroupsView = Ember.View.extend tagName: 'div' elementId: 'define-groups' templateName: 'define-groups' groupsBinding: 'GG.groupsController.groups' errorBinding: 'GG.groupsController.error' removeUser: (evt)-> GG.groupsController.removeUser(evt.context) addUser: -> GG.groupsController.addUser() done: -> console.log("done called") GG.groupsController.verifyContent() unless GG.groupsController.get('error') GG.statemanager.send 'definedGroups' GG.WorldView = Ember.View.extend templateName: 'world' contentBinding: 'GG.townsController' GG.WorldTownView = Ember.View.extend classNameBindings: ['icon','location','enabled','completed','locked'] attributeBindings: ['style'] location: "location" icon: (-> @get('content.icon') ).property('content.icon') enabledBinding: 'content.enabled' completedBinding: 'content.completed' locked: (-> @get('content.locked') and not @get('content.enabled') ).property('content.locked', 'content.enabled') style: (-> # width and height are always set to 175x125 regardless of the icon size (image is always centered in this box). width = 175 height = 125 a = 216 # x position of the center of the world (relative to the world div) b = 216 # y position of the center of the world (relative to the world div) r = 216 n = 28 # n is the number to adjust the icon in the world # adjust the radius to be a little bigger because the center of the town icons cannot be in the edge of the world # instead, each town icon image should have the "bottom" exactly at n pixels higher than the bottom of the image r = r + (height/2) r = r - n # calculate the position of the town based on the position # with the center at a,b, r = radius, t = angle: # (a + r cos t, b + r sin t) # add 90 since the equation assumes 0 is on the right of the circle, not top # subtract because the coordinate posRadX = (@get('content.position') + 90) * (Math.PI/180) # subtract for Y since the coordinate system is mirrored on the Y-axis posRadY = (@get('content.position') - 90) * (Math.PI/180) x = Math.round(a + (r * Math.cos(posRadX)) - (width/2)) y = Math.round(b + (r * Math.sin(posRadY)) - (height/2)) return "left: " + x + "px; top: " + y + "px; " + @get('rotation') ).property('content.position') rotation: (-> rot = "rotate(-" + @get('content.position') + "deg); " return "transform: " + rot + "-ms-transform: " + rot + "-webkit-transform: " + rot + "-o-transform: " + rot + "-moz-transform: " + rot ).property('content.position') click: -> GG.statemanager.send 'townSelected', @get('content') GG.BreederView = Ember.View.extend templateName: 'breeder-view' breedTypeBinding: 'GG.breedingController.breedType' isBaselineBinding: 'GG.baselineController.isBaseline' hasObstacleCourseBinding: 'GG.obstacleCourseController.hasObstacleCourse' baseline: (-> if @get('isBaseline') then "baseline" else "game" ).property('isBaseline') meiosisEnabledBinding: 'GG.tasksController.meiosisControlEnabled' showAllTraits: (-> townId = GG.townsController.get("content").indexOf GG.townsController.get "currentTown" return (townId > 1) ).property('GG.townsController.currentTown') GG.TraitSelectionView = Ember.View.extend GG.PointsToolTip, templateName: 'trait-selection' showAllTraits: (-> townId = GG.townsController.get("content").indexOf GG.townsController.get "currentTown" return (townId > 1) ).property('GG.townsController.currentTown') toolTipText: "Use the buttons to keep track of the traits you are breeding for" toolTipConfigTooltip: 'bottomRight' toolTipConfigTip: 'bottomRight' characteristicSelected: (evt) -> elem = evt.currentTarget container = elem.parentElement characteristic = ""+evt.context wasSelected = $(elem).hasClass("selected") $(container).find(".characteristic").removeClass("selected") $(elem).addClass("selected") unless wasSelected GG.logController.logEvent (unless wasSelected then GG.Events.SELECTED_CHARACTERISTIC else GG.Events.DESELECTED_CHARACTERISTIC), trait: container.classList[1] characteristic: characteristic GG.statemanager.send 'selectTrait', characteristic traits: (-> initialTraits = [ {trait: "gender", characteristics: ["male", "female"]} {trait: "wings", characteristics: ["wings", "no-wings"]} {trait: "metallic", characteristics: ["metallic", "non-metallic"]} {trait: "horns", characteristics: ["reverse-horns", "forward-horns"]} {trait: "fire", characteristics: ["no-fire", "fire"]} ] if !@get 'showAllTraits' return initialTraits else return initialTraits.concat [ {trait: "color", characteristics: ["green", "purple", "blue", "red"]} {trait: "spikes", characteristics: ["wide-spikes", "medium-spikes", "narrow-spikes"]} {trait: "tail", characteristics: ["short-tail", "kinked-tail", "long-tail"]} {trait: "armor", characteristics: ["armor", "no-armor"]} ] ).property('showAllTraits') GG.ParentPoolView = Ember.View.extend templateName: 'parent-pool-view' contentBinding: 'controller.content' drakeSelected: (evt) -> drake = evt.context GG.statemanager.send 'parentSelected', drake drakeRemoved: (evt) -> drake = evt.context GG.statemanager.send 'parentRemoved', drake GG.FatherPoolView = GG.ParentPoolView.extend GG.PointsToolTip, controllerBinding: 'GG.fatherPoolController' toolTipText: "Choose from these males for breeding the target drake" toolTipConfigTarget: 'bottomMiddle' toolTipConfigTooltip: 'topLeft' toolTipConfigTip: 'topLeft' GG.MotherPoolView = GG.ParentPoolView.extend GG.PointsToolTip, controllerBinding: 'GG.motherPoolController' toolTipText: "Choose from these females for breeding the target drake" toolTipConfigTarget: 'bottomMiddle' toolTipConfigTooltip: 'topLeft' toolTipConfigTip: 'topLeft' GG.OffspringPoolView = Ember.View.extend drakeSelected: (evt) -> GG.BreedButtonView = Ember.View.extend GG.PointsToolTip, tagName: 'div' toolTipText: (-> tip = "Produce an offspring %@ from the current parents".fmt(Ember.I18n.t('drake')) ).property() costPropertyName: 'extraBreedCycle' motherBinding: 'GG.parentController.selectedMother' fatherBinding: 'GG.parentController.selectedFather' classNameBindings : ['enabled'] inAnimationBinding: 'GG.meiosisController.inAnimation' canBreedDuringAnimationBinding: 'GG.meiosisController.canBreedDuringAnimation' enabled: (-> if !this.get('mother') || !this.get('father') return false else if @get('inAnimation') && !@get('canBreedDuringAnimation') return false else return true ).property('mother', 'father', 'inAnimation', 'canBreedDuringAnimation') click: -> if @get 'enabled' GG.statemanager.send('breedDrake') GG.AlleleView = Ember.View.extend GG.PointsToolTip, classNameBindings: ['defaultClassNames', 'revealable', 'dominant', 'gene', 'species'] defaultClassNames: 'allele' valueBinding: 'content.allele' species: (-> GG.DrakeSpecies.name ).property() hiddenValue: (-> value = @get 'value' value.charAt(0) + "?" ).property('value').cacheable() clickable: true hidden: Ember.computed.not('content.visible') revealable: (-> return @get('hidden') and @get('clickable') ).property('hidden','clickable') dominant: (-> ending = @get('displayValue').slice(-1) if ending is "1" return "dominant" else if ending is "2" return "recessive" else if ending is "3" return "recessive3" else return "" ).property('displayValue') gene: (-> if @get('value')? return BioLogica.Genetics.getGeneOfAllele(GG.DrakeSpecies, @get('value')).name else return '' ).property('value') displayValue: (-> if @get('hidden') then @get('hiddenValue') else @get('value') ).property('value','hidden') forceTooltip: true toolTipText: (-> text = "" if @get('revealable') then text += "Reveal hidden allele.<br/>" if GG.tooltipController.get('show') then text += "The orange circles show you which version, or allele, of a gene is on a particular chromosome. Every gene has different versions. Together, the letter and number in the allele circle show you the version of the gene." text ).property('revealable', 'GG.tooltipController.show') costPropertyName: (-> if @get('revealable') 'alleleRevealed' else null ).property('revealable') GG.ChromoView = Ember.View.extend GG.PointsToolTip, templateName: 'chromosome' content: null chromo: '1' side: 'a' sister: null crossoverSelectable: false selectable: false selected: false hiddenGenesBinding: 'GG.drakeController.hiddenGenes' visibleGenesBinding: 'GG.drakeController.visibleGenes' revealedContentAllelesIdxBinding: 'content.revealedIdx' revealedAlleles: null gametes: null useGamete: false realSide: (-> realSide = '' if ['x2','y','b'].contains(@get('side')) realSide = 'b' else realSide = 'a' realSide += @get('sister') return realSide ).property('sister','side') cellNum: (-> if @get('gametes')? endInfo = @get('gametes').endCellInfo chromo = @get('chromo') chromo = if chromo == "X" or chromo == "Y" then "XY" else chromo cellNum = endInfo[chromo][@get 'realSide'] else cellNum = -1 return cellNum ).property('chromo','realSide','gametes') gamete: (-> if @get('cellNum') != -1 cell = @get('gametes').cells[@get('cellNum')] chromo = @get 'chromo' chromo = if chromo == 'X' or chromo == 'Y' then 'XY' else chromo return cell[chromo] else return null ).property('gametes','chromo','cellNum') visibleGamete: (-> @_filterGamete('gamete',false) ).property('gamete', 'visibleGenes') hiddenGamete: (-> @_filterGamete('gamete',true) ).property('gamete', 'hiddenGenes') _filterGamete: (prop, hidden)-> res = null if @get(prop)?.alleles gamete = @get(prop) genesProp = if hidden then 'hiddenGenes' else 'visibleGenes' genes = @get(genesProp) || [] res = GG.Genetics.filter(gamete.alleles, genes) # Now add or subtract the revealed alleles from the result if gamete.revealed? if hidden res = res.filter (item)-> return !gamete.revealed.contains(item) else res = res.concat(gamete.revealed).uniq().compact() return res biologicaChromoName: (-> chromo = @get 'chromo' return chromo unless chromo is "X" or chromo is "Y" return "XY" ).property('chromo') genes: (-> GG.Genetics.species.chromosomeGeneMap[@get 'biologicaChromoName'] ).property('chromo') visibleAlleles: (-> return @_getAlleles(false) ).property('chromo','content','side','visibleGamete','revealedAlleles','revealedContentAllelesIdx','useGamete') hiddenAlleles: (-> return @_getAlleles(true) ).property('chromo','content','side','hiddenGamete','revealedAlleles','revealedContentAllelesIdx','useGamete') alleles: (-> bioChromo = @get('content.biologicaOrganism').genetics.genotype.chromosomes["1"]["a"] vis = @get('visibleAlleles').map (item)-> {allele: item, visible: true, position: bioChromo.getAllelesPosition(item)} hid = @get('hiddenAlleles').map (item)-> {allele: item, visible: false, position: bioChromo.getAllelesPosition(item)} alleles = vis.concat(hid) alleles = alleles.sort (a,b)=> if a.position > b.position then 1 else -1 return alleles ).property('visibleAlleles','hiddenAlleles') _getAlleles: (hidden)-> gamete = if hidden then 'hiddenGamete' else 'visibleGamete' res = [] if (@get 'content')? or (@get gamete)? if @get('useGamete') && (@get gamete)? res = @get gamete else prop = if hidden then 'content.hiddenGenotype' else 'content.visibleGenotype' fullGeno = @get prop side = @get 'side' if ['x2','y'].contains(side) side = 'b' else if side is 'x1' side = 'a' geno = fullGeno[side] res = GG.Genetics.filter(geno, @get 'genes') return res click: -> if @get('selectable') # toggle selected if @get('selected') @set('selected', false) GG.statemanager.send 'deselectedChromosome', this else @set('selected', true) GG.statemanager.send 'selectedChromosome', this allelesClickableDefault: true allelesClickable: (-> return @get('allelesClickableDefault') and GG.baselineController.get('isNotBaseline') ).property('allelesClickableDefault','GG.baselineController.isNotBaseline') alleleClicked: (event) -> if @get('allelesClickable') allele = event.context if !allele.visible @get('content').markRevealed(@get('side'), allele.allele) GG.reputationController.subtractReputation(GG.actionCostsController.getCost('alleleRevealed'), GG.Events.REVEALED_ALLELE) GG.logController.logEvent GG.Events.REVEALED_ALLELE, allele: allele.allele side: @get('side') drake: { alleles: @get('content.biologicaOrganism.alleles') sex: @get('content.sex') } defaultClass: 'chromosome' chromoName: (-> 'chromo-'+@get('chromo') ).property('chromo','side') right: (-> if @get('chromo') == 'Y' or ['b','y','x2'].contains(@get('side')) then "right" else "left" ).property('chromo','side') parent: (-> if ['a','x1'].contains(@get('side')) then 'mother' else 'father' ).property('chromo','side') sisterClass: (-> if (@get 'sister')? return "sister-" + @get('sister') else return "" ).property('sister') cell: (-> cellNum = @get('cellNum') if cellNum == -1 return '' else return 'cell' + cellNum ).property('cellNum') hidden: false classNames: ['chromosome'] classNameBindings: ['chromoName', 'right', 'parent', 'sisterClass', 'hidden', 'cell', 'selectable', 'selected'] toolTipText: (-> name = @get('biologicaChromoName') sex = @get('content.sex') if name is "XY" if sex "These are the sex chromosomes. Females have two X chromosomes. This is what makes them female." else "These are the sex chromosomes. Males have an X and a Y chromosome. This is what makes them male." else gender = if sex then "female" else "male" "These are the #{gender}'s chromosomes. All drakes have 3 pairs of chromosomes: pair 1, pair 2, and the sex chromosomes. Chromosomes contain genes and are made of DNA and protein." ).property() toolTipConfigTarget: (-> if @get('content.sex') then "topMiddle" else "bottomMiddle" ).property() toolTipConfigTooltip: (-> if @get('content.sex') then "bottomRight" else "topRight" ).property() toolTipConfigTip: (-> if @get('content.sex') then "bottomRight" else "topRight" ).property() GG.ChromosomePanelView = Ember.View.extend templateName: 'chromosome-panel' hiddenBinding: 'controller.hidden' defaultClass: 'chromosome-panel' chromosomeClass: (-> if @get('controller.selected.sex') is GG.FEMALE then 'female-chromosome' else 'male-chromosome' ).property('controller.selected').cacheable() classNameBindings: ['hidden','defaultClass', 'chromosomeClass'] GG.CrossoverPointView = Ember.View.extend tagName: 'div' classNames: ['crossoverPoint','hidden'] classNameBindings: ['gene','species'] allele: null chromoView: null gene: (-> return BioLogica.Genetics.getGeneOfAllele(GG.DrakeSpecies, @get('allele'))?.name ).property('allele') species: (-> GG.DrakeSpecies.name ).property() click: -> GG.statemanager.send 'selectedCrossover', {chromoView: @get('chromoView'), allele: @get('allele')} GG.EggView = Ember.View.extend GG.Animation, tagName: 'div' hidden: Ember.computed.not('GG.breedingController.isBreeding') classNameBindings: ['hidden'] onShow: -> @$().css({backgroundPosition: '0px 0px'}) @animate(properties: {rotate: '0deg'}, delay: 0) @animateSequence sequence: [properties: {rotate: '+=20deg'}, duration: 50, properties: {rotate: '-=20deg'}, duration: 50] delay: 700 repeat: 3 callback: => @$().css({backgroundPosition: '0px -140px'}) GG.OffspringBackButtonView = Ember.View.extend GG.PointsToolTip, tagName: 'div' toolTipText: "Go back and select different parents. This gives you a chance to get different alleles." classNames : 'offspring-buttons-back' click: -> GG.statemanager.send('selectParents') GG.OffspringUseButtonView = Ember.View.extend GG.PointsToolTip, tagName: 'div' toolTipText: (-> "Submit the current %@ as the solution to this task".fmt(Ember.I18n.t('drake')) ).property() classNames : 'offspring-buttons-use' click: -> GG.statemanager.send('submitOffspring') GG.OffspringSaveButtonView = Ember.View.extend GG.PointsToolTip, tagName: 'div' toolTipText: (-> if !GG.breedingController.get 'childSavedToParents' "Use this %@ as a parent".fmt(Ember.I18n.t('drake')) else "Already saved this %@! Press the Back button to select parents.".fmt(Ember.I18n.t('drake')) ).property('GG.breedingController.childSavedToParents') classNames : 'offspring-buttons-save' classNameBindings: ['disabled'] disabled: (-> !GG.powerUpController.hasPowerup("backcrossing") or GG.breedingController.get('childSavedToParents') ).property('GG.breedingController.childSavedToParents') click: -> return if @get 'disabled' @set 'disabled', true GG.statemanager.send('saveOffspring') GG.ValueCounter = Ember.View.extend GG.PointsToolTip, templateName: 'move-counter' classNames: ['value-counter'] toolTipText: "This is the amount you're being offered for breeding the target drake" toolTipConfigTarget: 'topMiddle' toolTipConfigTooltip: 'bottomRight' toolTipConfigTip: 'bottomRight' GG.MoveCounter = Ember.View.extend GG.PointsToolTip, templateName: 'move-counter' classNames: ['cost-counter'] toolTipText: "This tracks how much you have spent to breed, select chromosomes, and do crossovers" GG.MatchGoalCounter = Ember.View.extend templateName: 'match-goal-counter' targetCountBinding: Ember.Binding.oneWay('GG.tasksController.targetCount') classNameBindings: ['hidden','defaultClass'] defaultClass: 'match-goal-counter' hidden: (-> @get('targetCount') <= 1 ).property('targetCount') GG.TownView = Ember.View.extend templateName: 'town' contentBinding: 'GG.tasksController' backgroundBinding: 'GG.townsController.currentTown.background' GG.TaskNPCView = Ember.View.extend tagName : 'div' classNames : ['npc'] classNameBindings : ['npcLocationState','hidden'] attributeBindings : ['style'] hidden: (-> !(@get('content.completed') || @get('content.showInForeground') ) ).property('content.completed', 'content.showInForeground') style: (-> return "" if @get('content.showInForeground') scale = @get('content.npc.scale') || 0.5 layer = @get('content.npc.layer') || 1 flip = @get('content.npc.flip') || false if flip then xModifier = -1 else xModifier = 1 style = "top: " + @get('content.npc.position.y') + "px; left: " + @get('content.npc.position.x') + "px;" style += "z-index: #{layer-1};" for vendor in ["-webkit-", "-moz-", "-ms-", "-o-", ""] style += "#{vendor}transform: scaleX(#{scale * xModifier}) scaleY(#{scale});" style += "#{vendor}transform-origin: 0 0;" return style ).property('content.npc.position.x','content.npc.position.y', 'content.npc.position.scale','content.showInForeground') npcLocationState: (-> if @get('content.showInForeground') then @get('content.foregroundLocation') else "background" ).property('content.showInForeground') npcSelected: (evt) -> GG.statemanager.send 'npcSelected', evt.context replayTask: (evt) -> GG.statemanager.send 'replayTask', evt.context GG.NPCView = Ember.View.extend GG.PointsToolTip, tagName : 'img' classNames : ['character'] attributeBindings : ['src'] srcBinding : 'content.npc.imageURL' GG.NPCQuestionBubbleView = Ember.View.extend GG.Animation, tagName : 'img' classNames : ['bubble'] classNameBindings : ['hidden'] attributeBindings : ['src'] src : '../images/bubble-question.png' hidden : Ember.computed.not('content.showQuestionBubble') onShow: -> @animateSequence sequence: [properties: {top: "-=20px"}, duration: 200, easing: 'easeOutCubic', properties: {top: "+=20px"}, duration: 200, easing: 'easeInCubic'] delay: 200 repeat: 2 mouseEnter: -> # stop(true, true) is necessary so that we don't end up with a slowly enlarging/shrinking image... @$().stop(true, true).animate({width: "+=20px", height: "+=17px", top: "-=10px", left: "-=8px"}, 100, 'easeOutCubic') mouseLeave: -> @$().stop(true, true).animate({width: "-=20px", height: "-=17px", top: "+=10px", left: "+=8px"}, 100, 'easeOutCubic') GG.NPCSpeechBubbleView = Ember.View.extend tagName : 'div' classNames : ['speech-bubble'] classNameBindings : ['hidden'] hidden : Ember.computed.not('content.showSpeechBubble') init : -> @_super() currentText : (-> if @get 'isShowingEndMessage' text = @get 'content.npc.speech.completionText' else if @get 'isShowingThanksMessage' text = "Thanks again!" else if @get 'isShowingFailMessage' text = @get('content.npc.speech.failText') || "That's not the drake I'm looking for!" else text = @get 'content.npc.speech.text' if typeof text == "string" then text else text[0] ).property('content.npc.speech.text', 'isShowingEndMessage', 'isShowingThanksMessage', 'isShowingFailMessage') text : (-> currentText = @get 'currentText' text = currentText.replace("<name>", GG.userController.get('user.first')) text = text.replace(/\[(.*?)\]/g, "") # rm button text return new Handlebars.SafeString(text) ).property('currentText') continueButtonText: "Continue" acceptText: (-> @get('content.npc.speech.accept') || "Sure" ).property('content.npc.speech.accept') declineText: (-> @get('content.npc.speech.decline') || "Maybe later" ).property('content.npc.speech.decline') isShowingEndMessageBinding: 'content.isShowingEndMessage' isShowingThanksMessageBinding: 'content.isShowingThanksMessage' isShowingFailMessageBinding: 'content.isShowingFailMessage' accept: -> GG.statemanager.send 'accept', @get 'content' decline: -> GG.statemanager.send 'decline' replay: -> GG.statemanager.send 'replay', @get 'content' done: -> GG.statemanager.send 'done' GG.NPCHeartBubbleView = Ember.View.extend GG.PointsToolTip, templateName : 'heart-bubble' classNames : ['heart-wrapper'] classNameBindings : ['hidden'] hidden : Ember.computed.not('content.completed') toolTipConfigTarget: 'bottomLeft' toolTipConfigTooltip: 'bottomRight' toolTipConfigTip : 'bottomRight' toolTipText: (-> taskNo = GG.tasksController.indexOf(@get('content')) + 1 tip = "Replay Drake #{taskNo}: #{@get('content.targetDrake')}" if GG.tooltipController.get 'show' tip += ".<br>Hearts show gratitude for a correctly bred drake. If the heart is not completely full, it means you can earn more by trying again and breeding more efficiently." tip ).property('content', 'GG.tooltipController.show') forceTooltip: true updateHeartFill: (-> score = @get('content.reputationEarned') / @get('content.reputationFullScore') height = 53 - (score * 37) # height is from top, min 53px, max 16px height = 16 if height < 16 height = 53 if height > 53 @$('.heart-bubble-empty-wrapper').css({height: height}) ).observes('content.reputationEarned') mouseEnter: -> # stop(true, true) is necessary so that we don't end up with a slowly enlarging/shrinking image... @$('img').stop(true, true).animate({width: "+=4px", height: "+=4px", top: "-=2px", left: "-=2px"}, 100, 'easeOutCubic') mouseLeave: -> @$('img').stop(true, true).animate({width: "-=4px", height: "-=4px", top: "+=2px", left: "+=2px"}, 100, 'easeOutCubic') GG.NPCFinalMessageBubbleView = Ember.View.extend tagName : 'div' text : (-> return new Handlebars.SafeString(GG.townsController.get("currentTown.finalMessage")) ).property('content') classNames : ['speech-bubble'] classNameBindings : ['hidden'] hidden : Ember.computed.not('content.showFinalMessageBubble') isFinalTaskBinding : 'content.finalTask' next: -> GG.statemanager.transitionTo 'inWorld.movingDirectlyToNextTown' world: -> @set 'content.showFinalMessageBubble', false GG.statemanager.transitionTo 'inWorld.townsWaiting' dismissFinalBubble: -> @set 'content.showFinalMessageBubble', false $('.goToWorld').mouseover() setTimeout (-> $('.goToWorld').qtip("hide")), 2500 GG.MeiosisView = Ember.View.extend GG.PointsToolTip, templateName: 'meiosis' tagName: 'div' content: null init: -> @_super() if @get('content')? @contentChanged() contentChanged: (-> GG.meiosisController.set(@get('motherFather') + "View", this) @_createGametes() ).observes('content') classNames: ['meiosis'] classNameBindings: ['motherFather'] motherFather: (-> if @get('content.sex') == GG.MALE then "father" else "mother" ).property('content') gametes: null useGametes: false currentTownBinding: 'GG.townsController.currentTown' crossoverCost: (-> GG.actionCostsController.getCost('crossoverMade') ).property('currentTown') chromosomeSelectedCost: (-> GG.actionCostsController.getCost('chromosomeSelected') ).property('currentTown') selectFirstParent: -> if @get('content.sex') == GG.MALE GG.statemanager.send 'selectFatherMeiosis' else GG.statemanager.send 'selectMotherMeiosis' rerender: -> @_super() setTimeout => @set('useGametes', false) GG.meiosisController.set(@get('motherFather') + "View", _this) , 200 _createGametes: -> meiosisControl = GG.tasksController.get 'currentTask.meiosisControl' doCrossover = if GG.breedingController.get('breedType') == GG.BREED_CONTROLLED and (meiosisControl is "crossover" or meiosisControl is "all") then false else true newGametes = @get('content.biologicaOrganism').createGametesWithCrossInfo(4, doCrossover)[0] @set 'gametes', newGametes return newGametes sistersHidden: true animate: (callback)-> newGametes = @_createGametes() # Transfer revealed status to new gametes... We can't do this earlier # because the meiosis view is created when the user selects the drake # and still has an opportunity to interact and reveal alleles before # the animation starts. revealed = @get('content.revealedAlleles') normalizedSide = (s)-> if ['x','x1','a'].contains(s) return 'a' else if ['y','x2','b'].contains(s) return 'b' for side of revealed alleles = revealed[side] continue if alleles.length == 0 nSide = normalizedSide(side) for i in [0...newGametes.cells.length] gamete = newGametes.cells[i] for c in ["1","2","XY"] chromo = gamete[c] for j in [0...alleles.length] allele = alleles[j] idx = chromo.alleles.indexOf(allele) if idx != -1 and normalizedSide(chromo.allelesWithSides[idx].side) is nSide chromo.revealed ?= [] chromo.revealed.push allele GG.MeiosisAnimation.animate(".meiosis." + @get('motherFather'), this, callback) resetAnimation: ()-> GG.MeiosisAnimation.reset(".meiosis." + @get('motherFather'), this) @set('gametes', null) crossOver: -> newGametes = @get('gametes') # Move the allele circles, then reset them back and set the gametes at the same time cells = newGametes.cells # moves is a data structure that outlines what is moving from where to where # { # "gene": {[to]: [from], [to]: [from], ...} # } moves = {} for own chr,crosses of newGametes.crossInfo continue unless crosses? for c in [0...crosses.length] cross = crosses[c] startingAlleles = cross.crossedAlleles if startingAlleles? for a in [0...startingAlleles.length] sAllele = startingAlleles[a][0] gene = BioLogica.Genetics.getGeneOfAllele(GG.DrakeSpecies, sAllele).name moves[gene] ?= {} end = moves[gene][cross.start_cell] end = cross.start_cell unless end? start = moves[gene][cross.end_cell] start = cross.end_cell unless start? moves[gene][cross.end_cell] = end moves[gene][cross.start_cell] = start @animateMoves moves, => @set('useGametes', true) animateMoves: (moves, callback)-> animationQueue = [] selectorBase = "#" + @get('elementId') scale = GG.MeiosisAnimation.get 'timeScale' for own gene,swaps of moves for own dest,source of swaps sourceSelector = selectorBase + " .cell" + source + " .allele." + gene destSelector = selectorBase + " .cell" + dest + " .allele." + gene s = $(sourceSelector) d = $(destSelector) sOffset = s.offset() dOffset = d.offset() continue unless sOffset? and dOffset? dx = dOffset.left - sOffset.left leftShift = (if dx > 0 then "+=" else "-=") + Math.abs(dx) + "px" animationQueue.push {source: sourceSelector, anim: {left: dx}} # temporarily put alleles on top, so we don't see them sliding under other chromosomes $(selectorBase + " .allele").css({"z-index": 10}) for i in [0...animationQueue.length] anim = animationQueue[i] $(anim.source).animate(anim.anim, GG.MeiosisAnimation.scale(1500), 'easeInOutQuad') setTimeout => callback() Ember.run.next this, => for i in [0...animationQueue.length] anim = animationQueue[i] $(anim.source).css({left: '', top: ''}) # put the alleles back at their default level, so they slide under/over $("#" + @get('elementId') + " .allele").css({"z-index": ''}) , GG.MeiosisAnimation.scale(1550) chromosomeSelectedBinding: 'GG.meiosisController.chromosomeSelected' crossoverSelectedBinding: 'GG.meiosisController.crossoverSelected' doneSelectingCrossoverButtonText: (-> if @get('crossoverSelected') then "Continue" else "Skip" ).property('crossoverSelected') doneSelectingChromatidsButtonText: (-> if @get('chromosomeSelected') then "Continue" else "Skip" ).property('chromosomeSelected') allelesClickable: false crossoverSelectable: false chromosomesSelectable: false selectingChromatids: (callback)-> @set('chromosomesSelectable', true) GG.statemanager.send 'selectingChromatids', {elementId: @get('elementId'), callback: callback} doneSelectingChromatids: -> @set('chromosomesSelectable', false) GG.statemanager.send 'doneSelectingChromatids', this selectingCrossover: (callback)-> @set('crossoverSelectable', true) @set('useGametes', true) GG.statemanager.send 'selectingCrossover', {elementId: @get('elementId'), callback: callback} doneSelectingCrossover: -> @set('crossoverSelectable', false) GG.statemanager.send 'doneSelectingCrossover', this randomGameteNumberOverride: -1 randomGameteNumber: (-> override = @get('randomGameteNumberOverride') if override == -1 return ExtMath.randomInt(4) else return override ).property('gametes', 'randomGameteNumberOverride') chosenSex: (-> if @get('content.sex') == GG.MALE and @get('chosenGamete')? and @get('chosenGamete').XY.side is 'y' then GG.MALE else GG.FEMALE ).property('gametes','randomGameteNumber') chosenGamete: (-> return null unless @get('gametes')? return @get('gametes').cells[@get('randomGameteNumber')] ).property('gametes','randomGameteNumber') chosenGameteAlleles: (-> chosen = @get('chosenGamete') return "" unless chosen? side = if @get('content.sex') == GG.MALE then 'b' else 'a' alleles = "" for c in ['1','2','XY'] chromoAlleles = chosen[c].alleles if chromoAlleles? and chromoAlleles.length > 0 alleles += "," + side + ":" + chromoAlleles.reduce (prev, item) -> return prev + "," + side + ":" + item return alleles.slice(1) ).property('chosenGamete') tooltipTarget: ".tooltip-target-2" toolTipText: (-> if @get('chromosomesSelectable') then return '' gender = if @get('content.sex') is GG.MALE then ["male","sperm"] else ["female","egg"] "This is a special kind of cell in the #{gender[0]} that is about to go through the process called meiosis. In #{gender[0]}s, meiosis makes four #{gender[1]} cells, each with one chromosome from each pair. " ).property('content', 'chromosomesSelectable') toolTipConfigTarget: (-> if @get('content.sex') is GG.MALE then 'bottomRight' else 'topRight' ).property('content') toolTipConfigTooltip: (-> if @get('content.sex') is GG.MALE then 'topLeft' else 'bottomLeft' ).property('content') toolTipConfigTip : (-> if @get('content.sex') is GG.MALE then 'topLeft' else 'bottomLeft' ).property('content') GG.MeiosisSpeedSliderView = Ember.View.extend GG.PointsToolTip, tagName: 'div' elementId: 'meiosis-speed-slider-parent' toolTipText: "Use this slider to speed up or slow down meiosis" toolTipConfigTooltip: 'bottomRight' toolTipConfigTip: 'bottomRight' toolTipConfigTarget: 'topMiddle' updateEnabled: (-> disabled = !GG.powerUpController.hasPowerup("speed control") $('#meiosis-speed-slider').slider("option", "disabled", disabled); ).observes('GG.powerUpController.powerupChanged', 'GG.tasksController.currentTask') didInsertElement: -> # slider can go from -Infinity to 1.9999. # For now, we'll just have 2 values: 0 and 1. # The smaller the slider value, the slower the animation will go. $('#meiosis-speed-slider').slider orientation: 'horizontal' value: (2 - GG.MeiosisAnimation.get('timeScale')) min: 0.5 max: 1.7 step: 0.01 change: (event,ui)-> GG.MeiosisAnimation.set('timeScale', (2 - ui.value)) GG.ObstacleCourseDialogView = Ember.View.extend elementId: 'obstacle-course-dialog' templateName: 'obstacle-course-dialog' tagName: 'div' courseBinding: 'GG.obstacleCourseController.course' obstaclesBinding: 'GG.obstacleCourseController.obstacles' drakeBinding: 'GG.obstacleCourseController.drake' taskReputationBinding: 'GG.reputationController.currentTaskReputation' extraBreedsRepBinding: 'GG.reputationController.extraBreedsRep' meiosisControlRepBinding: 'GG.reputationController.meiosisControlRep' alleleRevealRepBinding: 'GG.reputationController.alleleRevealRep' visibleBinding: 'GG.obstacleCourseController.dialogVisible' taskCompleteBinding: 'GG.obstacleCourseController.taskComplete' currentObstacleBinding: 'GG.obstacleCourseController.currentObstacle' myTotalTimeBinding: 'GG.obstacleCourseController.myTotalTime' opponentTotalTimeBinding: 'GG.obstacleCourseController.opponentTotalTime' nTrainingsBinding: 'GG.cyclesController.cycles' modeBinding: 'GG.obstacleCourseController.mode' trainingPoints: (-> @get('nTrainings') * GG.actionCostsController.getCost('cycleRemainingBonus') ).property('nTrainings') courseCompletionPoints: (-> GG.obstacleCourseController.get('reputationEarned') - @get('trainingPoints') ).property('GG.obstacleCourseController.reputationEarned', 'trainingPoints') isExternalObstacleCourse: (-> @get('mode') == GG.OBSTACLE_COURSE_EXTERNAL ).property('mode') tryAgain: -> # restart task GG.tasksController.restartCurrentTask() continueOn: -> # Go back to town GG.statemanager.transitionTo 'inTown' GG.ObstacleTimeView = Ember.View.extend tagName: 'div' obstacle: null breedsLeftBinding: 'GG.cyclesController.cycles' time: (-> time = GG.obstacleCourseController.calculateTime(@get('obstacle'), false) ).property('obstacle','breedsLeft') GG.ObstacleView = Ember.View.extend tagName: 'div' classNames: ['obstacle'] classNameBindings: ['type', 'after'] attributeBindings : ['style'] after: false skipStyle: false style: (-> if @get 'skipStyle' "" else "top: " + @get('content.positionY') + "px; left: " + @get('content.positionX') + "px;" ).property('content.positionY','content.positionX','skipStyle') typeBinding: "content.obstacle" GG.PasswordField = Ember.TextField.extend type: "password" value: "" loginView: null keyUp: (evt)-> @interpretKeyEvents(evt) if evt.keyCode == 13 and @get('loginView')? @get('loginView').login() GG.BaselineTaskListView = Ember.View.extend tagName: 'div' templateName: 'task-list' taskSelected: (evt) -> GG.statemanager.send 'taskSelected', evt.context GG.townUnlockView = Ember.View.extend templateName: 'town-unlock' contentBinding: 'GG.townsController' costBinding: 'content.nextTownsCost' showPayMessageBinding: 'content.canPayForNextTown' firstTown: (-> @get 'content.firstObject' ).property('content.[]') GG.HelpModeButton = Ember.View.extend GG.PointsToolTip, tagName: 'div' classNames: ['questionmark-button'] classNameBindings: ['active'] activeBinding: 'GG.tooltipController.show' forceTooltip: true toolTipText: "Click to get help by hovering over objects." click: -> GG.statemanager.send 'toggleHelpMode'
true
minispade.require 'genigames/views/view-mixins' minispade.require 'genigames/views/drake-view' minispade.require 'genigames/views/meiosis-animation' GG.LoginView = Ember.View.extend templateName: 'login' username: "" password: "" loggingInBinding: 'GG.sessionController.loggingIn' errorBinding: 'GG.sessionController.error' firstTimeBinding: 'GG.sessionController.firstTime' waitingForPreloadBinding: 'GG.sessionController.waitingForPreload' registeredUsernameBinding: 'GG.sessionController.registeredUsername' registrationErrorBinding: 'GG.sessionController.registrationError' registrationErrorMessageBinding: 'GG.sessionController.registrationErrorMessage' login: -> pw = @get('password') @set('password', "") username = $('#username-field input').attr('value') data = {username: username, password: PI:PASSWORD:<PASSWORD>END_PI} GG.statemanager.send 'login', data showClassWord: -> GG.statemanager.send 'showClassWord' register: -> GG.statemanager.send 'register' GG.LogoutButton = Ember.View.extend tagName: 'div' classNames: 'logout' template: Ember.Handlebars.compile('<div>Logout</div>') click: -> GG.statemanager.transitionTo 'loggingOut' GG.GoToTownButton = Ember.View.extend GG.PointsToolTip, tagName: 'div' classNames: 'goToTown' toolTipText: "Reset task and go back to town" isShowingBreederBinding: 'GG.breedingController.isShowingBreeder2' hidden: (-> not @get('isShowingBreeder') ).property('isShowingBreeder') classNameBindings: ['hidden'] click: -> GG.statemanager.send 'goToTown' GG.GoToWorldButton = Ember.View.extend GG.PointsToolTip, tagName: 'div' classNames: 'goToWorld' toolTipText: "Click to leave the town" click: -> GG.statemanager.send 'goToWorld' GG.BackToTaskListButton = Ember.View.extend tagName: 'div' classNames: 'task-list' template: Ember.Handlebars.compile('<div>Challenge List</div>') click: -> GG.statemanager.transitionTo 'inTaskList' GG.ChooseClassView = Ember.View.extend templateName: 'choose-class' optionsBinding: 'GG.sessionController.classesWithLearners' clazz: null choose: -> GG.statemanager.send 'chooseLearner', @get('clazz') GG.DefineGroupsView = Ember.View.extend tagName: 'div' elementId: 'define-groups' templateName: 'define-groups' groupsBinding: 'GG.groupsController.groups' errorBinding: 'GG.groupsController.error' removeUser: (evt)-> GG.groupsController.removeUser(evt.context) addUser: -> GG.groupsController.addUser() done: -> console.log("done called") GG.groupsController.verifyContent() unless GG.groupsController.get('error') GG.statemanager.send 'definedGroups' GG.WorldView = Ember.View.extend templateName: 'world' contentBinding: 'GG.townsController' GG.WorldTownView = Ember.View.extend classNameBindings: ['icon','location','enabled','completed','locked'] attributeBindings: ['style'] location: "location" icon: (-> @get('content.icon') ).property('content.icon') enabledBinding: 'content.enabled' completedBinding: 'content.completed' locked: (-> @get('content.locked') and not @get('content.enabled') ).property('content.locked', 'content.enabled') style: (-> # width and height are always set to 175x125 regardless of the icon size (image is always centered in this box). width = 175 height = 125 a = 216 # x position of the center of the world (relative to the world div) b = 216 # y position of the center of the world (relative to the world div) r = 216 n = 28 # n is the number to adjust the icon in the world # adjust the radius to be a little bigger because the center of the town icons cannot be in the edge of the world # instead, each town icon image should have the "bottom" exactly at n pixels higher than the bottom of the image r = r + (height/2) r = r - n # calculate the position of the town based on the position # with the center at a,b, r = radius, t = angle: # (a + r cos t, b + r sin t) # add 90 since the equation assumes 0 is on the right of the circle, not top # subtract because the coordinate posRadX = (@get('content.position') + 90) * (Math.PI/180) # subtract for Y since the coordinate system is mirrored on the Y-axis posRadY = (@get('content.position') - 90) * (Math.PI/180) x = Math.round(a + (r * Math.cos(posRadX)) - (width/2)) y = Math.round(b + (r * Math.sin(posRadY)) - (height/2)) return "left: " + x + "px; top: " + y + "px; " + @get('rotation') ).property('content.position') rotation: (-> rot = "rotate(-" + @get('content.position') + "deg); " return "transform: " + rot + "-ms-transform: " + rot + "-webkit-transform: " + rot + "-o-transform: " + rot + "-moz-transform: " + rot ).property('content.position') click: -> GG.statemanager.send 'townSelected', @get('content') GG.BreederView = Ember.View.extend templateName: 'breeder-view' breedTypeBinding: 'GG.breedingController.breedType' isBaselineBinding: 'GG.baselineController.isBaseline' hasObstacleCourseBinding: 'GG.obstacleCourseController.hasObstacleCourse' baseline: (-> if @get('isBaseline') then "baseline" else "game" ).property('isBaseline') meiosisEnabledBinding: 'GG.tasksController.meiosisControlEnabled' showAllTraits: (-> townId = GG.townsController.get("content").indexOf GG.townsController.get "currentTown" return (townId > 1) ).property('GG.townsController.currentTown') GG.TraitSelectionView = Ember.View.extend GG.PointsToolTip, templateName: 'trait-selection' showAllTraits: (-> townId = GG.townsController.get("content").indexOf GG.townsController.get "currentTown" return (townId > 1) ).property('GG.townsController.currentTown') toolTipText: "Use the buttons to keep track of the traits you are breeding for" toolTipConfigTooltip: 'bottomRight' toolTipConfigTip: 'bottomRight' characteristicSelected: (evt) -> elem = evt.currentTarget container = elem.parentElement characteristic = ""+evt.context wasSelected = $(elem).hasClass("selected") $(container).find(".characteristic").removeClass("selected") $(elem).addClass("selected") unless wasSelected GG.logController.logEvent (unless wasSelected then GG.Events.SELECTED_CHARACTERISTIC else GG.Events.DESELECTED_CHARACTERISTIC), trait: container.classList[1] characteristic: characteristic GG.statemanager.send 'selectTrait', characteristic traits: (-> initialTraits = [ {trait: "gender", characteristics: ["male", "female"]} {trait: "wings", characteristics: ["wings", "no-wings"]} {trait: "metallic", characteristics: ["metallic", "non-metallic"]} {trait: "horns", characteristics: ["reverse-horns", "forward-horns"]} {trait: "fire", characteristics: ["no-fire", "fire"]} ] if !@get 'showAllTraits' return initialTraits else return initialTraits.concat [ {trait: "color", characteristics: ["green", "purple", "blue", "red"]} {trait: "spikes", characteristics: ["wide-spikes", "medium-spikes", "narrow-spikes"]} {trait: "tail", characteristics: ["short-tail", "kinked-tail", "long-tail"]} {trait: "armor", characteristics: ["armor", "no-armor"]} ] ).property('showAllTraits') GG.ParentPoolView = Ember.View.extend templateName: 'parent-pool-view' contentBinding: 'controller.content' drakeSelected: (evt) -> drake = evt.context GG.statemanager.send 'parentSelected', drake drakeRemoved: (evt) -> drake = evt.context GG.statemanager.send 'parentRemoved', drake GG.FatherPoolView = GG.ParentPoolView.extend GG.PointsToolTip, controllerBinding: 'GG.fatherPoolController' toolTipText: "Choose from these males for breeding the target drake" toolTipConfigTarget: 'bottomMiddle' toolTipConfigTooltip: 'topLeft' toolTipConfigTip: 'topLeft' GG.MotherPoolView = GG.ParentPoolView.extend GG.PointsToolTip, controllerBinding: 'GG.motherPoolController' toolTipText: "Choose from these females for breeding the target drake" toolTipConfigTarget: 'bottomMiddle' toolTipConfigTooltip: 'topLeft' toolTipConfigTip: 'topLeft' GG.OffspringPoolView = Ember.View.extend drakeSelected: (evt) -> GG.BreedButtonView = Ember.View.extend GG.PointsToolTip, tagName: 'div' toolTipText: (-> tip = "Produce an offspring %@ from the current parents".fmt(Ember.I18n.t('drake')) ).property() costPropertyName: 'extraBreedCycle' motherBinding: 'GG.parentController.selectedMother' fatherBinding: 'GG.parentController.selectedFather' classNameBindings : ['enabled'] inAnimationBinding: 'GG.meiosisController.inAnimation' canBreedDuringAnimationBinding: 'GG.meiosisController.canBreedDuringAnimation' enabled: (-> if !this.get('mother') || !this.get('father') return false else if @get('inAnimation') && !@get('canBreedDuringAnimation') return false else return true ).property('mother', 'father', 'inAnimation', 'canBreedDuringAnimation') click: -> if @get 'enabled' GG.statemanager.send('breedDrake') GG.AlleleView = Ember.View.extend GG.PointsToolTip, classNameBindings: ['defaultClassNames', 'revealable', 'dominant', 'gene', 'species'] defaultClassNames: 'allele' valueBinding: 'content.allele' species: (-> GG.DrakeSpecies.name ).property() hiddenValue: (-> value = @get 'value' value.charAt(0) + "?" ).property('value').cacheable() clickable: true hidden: Ember.computed.not('content.visible') revealable: (-> return @get('hidden') and @get('clickable') ).property('hidden','clickable') dominant: (-> ending = @get('displayValue').slice(-1) if ending is "1" return "dominant" else if ending is "2" return "recessive" else if ending is "3" return "recessive3" else return "" ).property('displayValue') gene: (-> if @get('value')? return BioLogica.Genetics.getGeneOfAllele(GG.DrakeSpecies, @get('value')).name else return '' ).property('value') displayValue: (-> if @get('hidden') then @get('hiddenValue') else @get('value') ).property('value','hidden') forceTooltip: true toolTipText: (-> text = "" if @get('revealable') then text += "Reveal hidden allele.<br/>" if GG.tooltipController.get('show') then text += "The orange circles show you which version, or allele, of a gene is on a particular chromosome. Every gene has different versions. Together, the letter and number in the allele circle show you the version of the gene." text ).property('revealable', 'GG.tooltipController.show') costPropertyName: (-> if @get('revealable') 'alleleRevealed' else null ).property('revealable') GG.ChromoView = Ember.View.extend GG.PointsToolTip, templateName: 'chromosome' content: null chromo: '1' side: 'a' sister: null crossoverSelectable: false selectable: false selected: false hiddenGenesBinding: 'GG.drakeController.hiddenGenes' visibleGenesBinding: 'GG.drakeController.visibleGenes' revealedContentAllelesIdxBinding: 'content.revealedIdx' revealedAlleles: null gametes: null useGamete: false realSide: (-> realSide = '' if ['x2','y','b'].contains(@get('side')) realSide = 'b' else realSide = 'a' realSide += @get('sister') return realSide ).property('sister','side') cellNum: (-> if @get('gametes')? endInfo = @get('gametes').endCellInfo chromo = @get('chromo') chromo = if chromo == "X" or chromo == "Y" then "XY" else chromo cellNum = endInfo[chromo][@get 'realSide'] else cellNum = -1 return cellNum ).property('chromo','realSide','gametes') gamete: (-> if @get('cellNum') != -1 cell = @get('gametes').cells[@get('cellNum')] chromo = @get 'chromo' chromo = if chromo == 'X' or chromo == 'Y' then 'XY' else chromo return cell[chromo] else return null ).property('gametes','chromo','cellNum') visibleGamete: (-> @_filterGamete('gamete',false) ).property('gamete', 'visibleGenes') hiddenGamete: (-> @_filterGamete('gamete',true) ).property('gamete', 'hiddenGenes') _filterGamete: (prop, hidden)-> res = null if @get(prop)?.alleles gamete = @get(prop) genesProp = if hidden then 'hiddenGenes' else 'visibleGenes' genes = @get(genesProp) || [] res = GG.Genetics.filter(gamete.alleles, genes) # Now add or subtract the revealed alleles from the result if gamete.revealed? if hidden res = res.filter (item)-> return !gamete.revealed.contains(item) else res = res.concat(gamete.revealed).uniq().compact() return res biologicaChromoName: (-> chromo = @get 'chromo' return chromo unless chromo is "X" or chromo is "Y" return "XY" ).property('chromo') genes: (-> GG.Genetics.species.chromosomeGeneMap[@get 'biologicaChromoName'] ).property('chromo') visibleAlleles: (-> return @_getAlleles(false) ).property('chromo','content','side','visibleGamete','revealedAlleles','revealedContentAllelesIdx','useGamete') hiddenAlleles: (-> return @_getAlleles(true) ).property('chromo','content','side','hiddenGamete','revealedAlleles','revealedContentAllelesIdx','useGamete') alleles: (-> bioChromo = @get('content.biologicaOrganism').genetics.genotype.chromosomes["1"]["a"] vis = @get('visibleAlleles').map (item)-> {allele: item, visible: true, position: bioChromo.getAllelesPosition(item)} hid = @get('hiddenAlleles').map (item)-> {allele: item, visible: false, position: bioChromo.getAllelesPosition(item)} alleles = vis.concat(hid) alleles = alleles.sort (a,b)=> if a.position > b.position then 1 else -1 return alleles ).property('visibleAlleles','hiddenAlleles') _getAlleles: (hidden)-> gamete = if hidden then 'hiddenGamete' else 'visibleGamete' res = [] if (@get 'content')? or (@get gamete)? if @get('useGamete') && (@get gamete)? res = @get gamete else prop = if hidden then 'content.hiddenGenotype' else 'content.visibleGenotype' fullGeno = @get prop side = @get 'side' if ['x2','y'].contains(side) side = 'b' else if side is 'x1' side = 'a' geno = fullGeno[side] res = GG.Genetics.filter(geno, @get 'genes') return res click: -> if @get('selectable') # toggle selected if @get('selected') @set('selected', false) GG.statemanager.send 'deselectedChromosome', this else @set('selected', true) GG.statemanager.send 'selectedChromosome', this allelesClickableDefault: true allelesClickable: (-> return @get('allelesClickableDefault') and GG.baselineController.get('isNotBaseline') ).property('allelesClickableDefault','GG.baselineController.isNotBaseline') alleleClicked: (event) -> if @get('allelesClickable') allele = event.context if !allele.visible @get('content').markRevealed(@get('side'), allele.allele) GG.reputationController.subtractReputation(GG.actionCostsController.getCost('alleleRevealed'), GG.Events.REVEALED_ALLELE) GG.logController.logEvent GG.Events.REVEALED_ALLELE, allele: allele.allele side: @get('side') drake: { alleles: @get('content.biologicaOrganism.alleles') sex: @get('content.sex') } defaultClass: 'chromosome' chromoName: (-> 'chromo-'+@get('chromo') ).property('chromo','side') right: (-> if @get('chromo') == 'Y' or ['b','y','x2'].contains(@get('side')) then "right" else "left" ).property('chromo','side') parent: (-> if ['a','x1'].contains(@get('side')) then 'mother' else 'father' ).property('chromo','side') sisterClass: (-> if (@get 'sister')? return "sister-" + @get('sister') else return "" ).property('sister') cell: (-> cellNum = @get('cellNum') if cellNum == -1 return '' else return 'cell' + cellNum ).property('cellNum') hidden: false classNames: ['chromosome'] classNameBindings: ['chromoName', 'right', 'parent', 'sisterClass', 'hidden', 'cell', 'selectable', 'selected'] toolTipText: (-> name = @get('biologicaChromoName') sex = @get('content.sex') if name is "XY" if sex "These are the sex chromosomes. Females have two X chromosomes. This is what makes them female." else "These are the sex chromosomes. Males have an X and a Y chromosome. This is what makes them male." else gender = if sex then "female" else "male" "These are the #{gender}'s chromosomes. All drakes have 3 pairs of chromosomes: pair 1, pair 2, and the sex chromosomes. Chromosomes contain genes and are made of DNA and protein." ).property() toolTipConfigTarget: (-> if @get('content.sex') then "topMiddle" else "bottomMiddle" ).property() toolTipConfigTooltip: (-> if @get('content.sex') then "bottomRight" else "topRight" ).property() toolTipConfigTip: (-> if @get('content.sex') then "bottomRight" else "topRight" ).property() GG.ChromosomePanelView = Ember.View.extend templateName: 'chromosome-panel' hiddenBinding: 'controller.hidden' defaultClass: 'chromosome-panel' chromosomeClass: (-> if @get('controller.selected.sex') is GG.FEMALE then 'female-chromosome' else 'male-chromosome' ).property('controller.selected').cacheable() classNameBindings: ['hidden','defaultClass', 'chromosomeClass'] GG.CrossoverPointView = Ember.View.extend tagName: 'div' classNames: ['crossoverPoint','hidden'] classNameBindings: ['gene','species'] allele: null chromoView: null gene: (-> return BioLogica.Genetics.getGeneOfAllele(GG.DrakeSpecies, @get('allele'))?.name ).property('allele') species: (-> GG.DrakeSpecies.name ).property() click: -> GG.statemanager.send 'selectedCrossover', {chromoView: @get('chromoView'), allele: @get('allele')} GG.EggView = Ember.View.extend GG.Animation, tagName: 'div' hidden: Ember.computed.not('GG.breedingController.isBreeding') classNameBindings: ['hidden'] onShow: -> @$().css({backgroundPosition: '0px 0px'}) @animate(properties: {rotate: '0deg'}, delay: 0) @animateSequence sequence: [properties: {rotate: '+=20deg'}, duration: 50, properties: {rotate: '-=20deg'}, duration: 50] delay: 700 repeat: 3 callback: => @$().css({backgroundPosition: '0px -140px'}) GG.OffspringBackButtonView = Ember.View.extend GG.PointsToolTip, tagName: 'div' toolTipText: "Go back and select different parents. This gives you a chance to get different alleles." classNames : 'offspring-buttons-back' click: -> GG.statemanager.send('selectParents') GG.OffspringUseButtonView = Ember.View.extend GG.PointsToolTip, tagName: 'div' toolTipText: (-> "Submit the current %@ as the solution to this task".fmt(Ember.I18n.t('drake')) ).property() classNames : 'offspring-buttons-use' click: -> GG.statemanager.send('submitOffspring') GG.OffspringSaveButtonView = Ember.View.extend GG.PointsToolTip, tagName: 'div' toolTipText: (-> if !GG.breedingController.get 'childSavedToParents' "Use this %@ as a parent".fmt(Ember.I18n.t('drake')) else "Already saved this %@! Press the Back button to select parents.".fmt(Ember.I18n.t('drake')) ).property('GG.breedingController.childSavedToParents') classNames : 'offspring-buttons-save' classNameBindings: ['disabled'] disabled: (-> !GG.powerUpController.hasPowerup("backcrossing") or GG.breedingController.get('childSavedToParents') ).property('GG.breedingController.childSavedToParents') click: -> return if @get 'disabled' @set 'disabled', true GG.statemanager.send('saveOffspring') GG.ValueCounter = Ember.View.extend GG.PointsToolTip, templateName: 'move-counter' classNames: ['value-counter'] toolTipText: "This is the amount you're being offered for breeding the target drake" toolTipConfigTarget: 'topMiddle' toolTipConfigTooltip: 'bottomRight' toolTipConfigTip: 'bottomRight' GG.MoveCounter = Ember.View.extend GG.PointsToolTip, templateName: 'move-counter' classNames: ['cost-counter'] toolTipText: "This tracks how much you have spent to breed, select chromosomes, and do crossovers" GG.MatchGoalCounter = Ember.View.extend templateName: 'match-goal-counter' targetCountBinding: Ember.Binding.oneWay('GG.tasksController.targetCount') classNameBindings: ['hidden','defaultClass'] defaultClass: 'match-goal-counter' hidden: (-> @get('targetCount') <= 1 ).property('targetCount') GG.TownView = Ember.View.extend templateName: 'town' contentBinding: 'GG.tasksController' backgroundBinding: 'GG.townsController.currentTown.background' GG.TaskNPCView = Ember.View.extend tagName : 'div' classNames : ['npc'] classNameBindings : ['npcLocationState','hidden'] attributeBindings : ['style'] hidden: (-> !(@get('content.completed') || @get('content.showInForeground') ) ).property('content.completed', 'content.showInForeground') style: (-> return "" if @get('content.showInForeground') scale = @get('content.npc.scale') || 0.5 layer = @get('content.npc.layer') || 1 flip = @get('content.npc.flip') || false if flip then xModifier = -1 else xModifier = 1 style = "top: " + @get('content.npc.position.y') + "px; left: " + @get('content.npc.position.x') + "px;" style += "z-index: #{layer-1};" for vendor in ["-webkit-", "-moz-", "-ms-", "-o-", ""] style += "#{vendor}transform: scaleX(#{scale * xModifier}) scaleY(#{scale});" style += "#{vendor}transform-origin: 0 0;" return style ).property('content.npc.position.x','content.npc.position.y', 'content.npc.position.scale','content.showInForeground') npcLocationState: (-> if @get('content.showInForeground') then @get('content.foregroundLocation') else "background" ).property('content.showInForeground') npcSelected: (evt) -> GG.statemanager.send 'npcSelected', evt.context replayTask: (evt) -> GG.statemanager.send 'replayTask', evt.context GG.NPCView = Ember.View.extend GG.PointsToolTip, tagName : 'img' classNames : ['character'] attributeBindings : ['src'] srcBinding : 'content.npc.imageURL' GG.NPCQuestionBubbleView = Ember.View.extend GG.Animation, tagName : 'img' classNames : ['bubble'] classNameBindings : ['hidden'] attributeBindings : ['src'] src : '../images/bubble-question.png' hidden : Ember.computed.not('content.showQuestionBubble') onShow: -> @animateSequence sequence: [properties: {top: "-=20px"}, duration: 200, easing: 'easeOutCubic', properties: {top: "+=20px"}, duration: 200, easing: 'easeInCubic'] delay: 200 repeat: 2 mouseEnter: -> # stop(true, true) is necessary so that we don't end up with a slowly enlarging/shrinking image... @$().stop(true, true).animate({width: "+=20px", height: "+=17px", top: "-=10px", left: "-=8px"}, 100, 'easeOutCubic') mouseLeave: -> @$().stop(true, true).animate({width: "-=20px", height: "-=17px", top: "+=10px", left: "+=8px"}, 100, 'easeOutCubic') GG.NPCSpeechBubbleView = Ember.View.extend tagName : 'div' classNames : ['speech-bubble'] classNameBindings : ['hidden'] hidden : Ember.computed.not('content.showSpeechBubble') init : -> @_super() currentText : (-> if @get 'isShowingEndMessage' text = @get 'content.npc.speech.completionText' else if @get 'isShowingThanksMessage' text = "Thanks again!" else if @get 'isShowingFailMessage' text = @get('content.npc.speech.failText') || "That's not the drake I'm looking for!" else text = @get 'content.npc.speech.text' if typeof text == "string" then text else text[0] ).property('content.npc.speech.text', 'isShowingEndMessage', 'isShowingThanksMessage', 'isShowingFailMessage') text : (-> currentText = @get 'currentText' text = currentText.replace("<name>", GG.userController.get('user.first')) text = text.replace(/\[(.*?)\]/g, "") # rm button text return new Handlebars.SafeString(text) ).property('currentText') continueButtonText: "Continue" acceptText: (-> @get('content.npc.speech.accept') || "Sure" ).property('content.npc.speech.accept') declineText: (-> @get('content.npc.speech.decline') || "Maybe later" ).property('content.npc.speech.decline') isShowingEndMessageBinding: 'content.isShowingEndMessage' isShowingThanksMessageBinding: 'content.isShowingThanksMessage' isShowingFailMessageBinding: 'content.isShowingFailMessage' accept: -> GG.statemanager.send 'accept', @get 'content' decline: -> GG.statemanager.send 'decline' replay: -> GG.statemanager.send 'replay', @get 'content' done: -> GG.statemanager.send 'done' GG.NPCHeartBubbleView = Ember.View.extend GG.PointsToolTip, templateName : 'heart-bubble' classNames : ['heart-wrapper'] classNameBindings : ['hidden'] hidden : Ember.computed.not('content.completed') toolTipConfigTarget: 'bottomLeft' toolTipConfigTooltip: 'bottomRight' toolTipConfigTip : 'bottomRight' toolTipText: (-> taskNo = GG.tasksController.indexOf(@get('content')) + 1 tip = "Replay Drake #{taskNo}: #{@get('content.targetDrake')}" if GG.tooltipController.get 'show' tip += ".<br>Hearts show gratitude for a correctly bred drake. If the heart is not completely full, it means you can earn more by trying again and breeding more efficiently." tip ).property('content', 'GG.tooltipController.show') forceTooltip: true updateHeartFill: (-> score = @get('content.reputationEarned') / @get('content.reputationFullScore') height = 53 - (score * 37) # height is from top, min 53px, max 16px height = 16 if height < 16 height = 53 if height > 53 @$('.heart-bubble-empty-wrapper').css({height: height}) ).observes('content.reputationEarned') mouseEnter: -> # stop(true, true) is necessary so that we don't end up with a slowly enlarging/shrinking image... @$('img').stop(true, true).animate({width: "+=4px", height: "+=4px", top: "-=2px", left: "-=2px"}, 100, 'easeOutCubic') mouseLeave: -> @$('img').stop(true, true).animate({width: "-=4px", height: "-=4px", top: "+=2px", left: "+=2px"}, 100, 'easeOutCubic') GG.NPCFinalMessageBubbleView = Ember.View.extend tagName : 'div' text : (-> return new Handlebars.SafeString(GG.townsController.get("currentTown.finalMessage")) ).property('content') classNames : ['speech-bubble'] classNameBindings : ['hidden'] hidden : Ember.computed.not('content.showFinalMessageBubble') isFinalTaskBinding : 'content.finalTask' next: -> GG.statemanager.transitionTo 'inWorld.movingDirectlyToNextTown' world: -> @set 'content.showFinalMessageBubble', false GG.statemanager.transitionTo 'inWorld.townsWaiting' dismissFinalBubble: -> @set 'content.showFinalMessageBubble', false $('.goToWorld').mouseover() setTimeout (-> $('.goToWorld').qtip("hide")), 2500 GG.MeiosisView = Ember.View.extend GG.PointsToolTip, templateName: 'meiosis' tagName: 'div' content: null init: -> @_super() if @get('content')? @contentChanged() contentChanged: (-> GG.meiosisController.set(@get('motherFather') + "View", this) @_createGametes() ).observes('content') classNames: ['meiosis'] classNameBindings: ['motherFather'] motherFather: (-> if @get('content.sex') == GG.MALE then "father" else "mother" ).property('content') gametes: null useGametes: false currentTownBinding: 'GG.townsController.currentTown' crossoverCost: (-> GG.actionCostsController.getCost('crossoverMade') ).property('currentTown') chromosomeSelectedCost: (-> GG.actionCostsController.getCost('chromosomeSelected') ).property('currentTown') selectFirstParent: -> if @get('content.sex') == GG.MALE GG.statemanager.send 'selectFatherMeiosis' else GG.statemanager.send 'selectMotherMeiosis' rerender: -> @_super() setTimeout => @set('useGametes', false) GG.meiosisController.set(@get('motherFather') + "View", _this) , 200 _createGametes: -> meiosisControl = GG.tasksController.get 'currentTask.meiosisControl' doCrossover = if GG.breedingController.get('breedType') == GG.BREED_CONTROLLED and (meiosisControl is "crossover" or meiosisControl is "all") then false else true newGametes = @get('content.biologicaOrganism').createGametesWithCrossInfo(4, doCrossover)[0] @set 'gametes', newGametes return newGametes sistersHidden: true animate: (callback)-> newGametes = @_createGametes() # Transfer revealed status to new gametes... We can't do this earlier # because the meiosis view is created when the user selects the drake # and still has an opportunity to interact and reveal alleles before # the animation starts. revealed = @get('content.revealedAlleles') normalizedSide = (s)-> if ['x','x1','a'].contains(s) return 'a' else if ['y','x2','b'].contains(s) return 'b' for side of revealed alleles = revealed[side] continue if alleles.length == 0 nSide = normalizedSide(side) for i in [0...newGametes.cells.length] gamete = newGametes.cells[i] for c in ["1","2","XY"] chromo = gamete[c] for j in [0...alleles.length] allele = alleles[j] idx = chromo.alleles.indexOf(allele) if idx != -1 and normalizedSide(chromo.allelesWithSides[idx].side) is nSide chromo.revealed ?= [] chromo.revealed.push allele GG.MeiosisAnimation.animate(".meiosis." + @get('motherFather'), this, callback) resetAnimation: ()-> GG.MeiosisAnimation.reset(".meiosis." + @get('motherFather'), this) @set('gametes', null) crossOver: -> newGametes = @get('gametes') # Move the allele circles, then reset them back and set the gametes at the same time cells = newGametes.cells # moves is a data structure that outlines what is moving from where to where # { # "gene": {[to]: [from], [to]: [from], ...} # } moves = {} for own chr,crosses of newGametes.crossInfo continue unless crosses? for c in [0...crosses.length] cross = crosses[c] startingAlleles = cross.crossedAlleles if startingAlleles? for a in [0...startingAlleles.length] sAllele = startingAlleles[a][0] gene = BioLogica.Genetics.getGeneOfAllele(GG.DrakeSpecies, sAllele).name moves[gene] ?= {} end = moves[gene][cross.start_cell] end = cross.start_cell unless end? start = moves[gene][cross.end_cell] start = cross.end_cell unless start? moves[gene][cross.end_cell] = end moves[gene][cross.start_cell] = start @animateMoves moves, => @set('useGametes', true) animateMoves: (moves, callback)-> animationQueue = [] selectorBase = "#" + @get('elementId') scale = GG.MeiosisAnimation.get 'timeScale' for own gene,swaps of moves for own dest,source of swaps sourceSelector = selectorBase + " .cell" + source + " .allele." + gene destSelector = selectorBase + " .cell" + dest + " .allele." + gene s = $(sourceSelector) d = $(destSelector) sOffset = s.offset() dOffset = d.offset() continue unless sOffset? and dOffset? dx = dOffset.left - sOffset.left leftShift = (if dx > 0 then "+=" else "-=") + Math.abs(dx) + "px" animationQueue.push {source: sourceSelector, anim: {left: dx}} # temporarily put alleles on top, so we don't see them sliding under other chromosomes $(selectorBase + " .allele").css({"z-index": 10}) for i in [0...animationQueue.length] anim = animationQueue[i] $(anim.source).animate(anim.anim, GG.MeiosisAnimation.scale(1500), 'easeInOutQuad') setTimeout => callback() Ember.run.next this, => for i in [0...animationQueue.length] anim = animationQueue[i] $(anim.source).css({left: '', top: ''}) # put the alleles back at their default level, so they slide under/over $("#" + @get('elementId') + " .allele").css({"z-index": ''}) , GG.MeiosisAnimation.scale(1550) chromosomeSelectedBinding: 'GG.meiosisController.chromosomeSelected' crossoverSelectedBinding: 'GG.meiosisController.crossoverSelected' doneSelectingCrossoverButtonText: (-> if @get('crossoverSelected') then "Continue" else "Skip" ).property('crossoverSelected') doneSelectingChromatidsButtonText: (-> if @get('chromosomeSelected') then "Continue" else "Skip" ).property('chromosomeSelected') allelesClickable: false crossoverSelectable: false chromosomesSelectable: false selectingChromatids: (callback)-> @set('chromosomesSelectable', true) GG.statemanager.send 'selectingChromatids', {elementId: @get('elementId'), callback: callback} doneSelectingChromatids: -> @set('chromosomesSelectable', false) GG.statemanager.send 'doneSelectingChromatids', this selectingCrossover: (callback)-> @set('crossoverSelectable', true) @set('useGametes', true) GG.statemanager.send 'selectingCrossover', {elementId: @get('elementId'), callback: callback} doneSelectingCrossover: -> @set('crossoverSelectable', false) GG.statemanager.send 'doneSelectingCrossover', this randomGameteNumberOverride: -1 randomGameteNumber: (-> override = @get('randomGameteNumberOverride') if override == -1 return ExtMath.randomInt(4) else return override ).property('gametes', 'randomGameteNumberOverride') chosenSex: (-> if @get('content.sex') == GG.MALE and @get('chosenGamete')? and @get('chosenGamete').XY.side is 'y' then GG.MALE else GG.FEMALE ).property('gametes','randomGameteNumber') chosenGamete: (-> return null unless @get('gametes')? return @get('gametes').cells[@get('randomGameteNumber')] ).property('gametes','randomGameteNumber') chosenGameteAlleles: (-> chosen = @get('chosenGamete') return "" unless chosen? side = if @get('content.sex') == GG.MALE then 'b' else 'a' alleles = "" for c in ['1','2','XY'] chromoAlleles = chosen[c].alleles if chromoAlleles? and chromoAlleles.length > 0 alleles += "," + side + ":" + chromoAlleles.reduce (prev, item) -> return prev + "," + side + ":" + item return alleles.slice(1) ).property('chosenGamete') tooltipTarget: ".tooltip-target-2" toolTipText: (-> if @get('chromosomesSelectable') then return '' gender = if @get('content.sex') is GG.MALE then ["male","sperm"] else ["female","egg"] "This is a special kind of cell in the #{gender[0]} that is about to go through the process called meiosis. In #{gender[0]}s, meiosis makes four #{gender[1]} cells, each with one chromosome from each pair. " ).property('content', 'chromosomesSelectable') toolTipConfigTarget: (-> if @get('content.sex') is GG.MALE then 'bottomRight' else 'topRight' ).property('content') toolTipConfigTooltip: (-> if @get('content.sex') is GG.MALE then 'topLeft' else 'bottomLeft' ).property('content') toolTipConfigTip : (-> if @get('content.sex') is GG.MALE then 'topLeft' else 'bottomLeft' ).property('content') GG.MeiosisSpeedSliderView = Ember.View.extend GG.PointsToolTip, tagName: 'div' elementId: 'meiosis-speed-slider-parent' toolTipText: "Use this slider to speed up or slow down meiosis" toolTipConfigTooltip: 'bottomRight' toolTipConfigTip: 'bottomRight' toolTipConfigTarget: 'topMiddle' updateEnabled: (-> disabled = !GG.powerUpController.hasPowerup("speed control") $('#meiosis-speed-slider').slider("option", "disabled", disabled); ).observes('GG.powerUpController.powerupChanged', 'GG.tasksController.currentTask') didInsertElement: -> # slider can go from -Infinity to 1.9999. # For now, we'll just have 2 values: 0 and 1. # The smaller the slider value, the slower the animation will go. $('#meiosis-speed-slider').slider orientation: 'horizontal' value: (2 - GG.MeiosisAnimation.get('timeScale')) min: 0.5 max: 1.7 step: 0.01 change: (event,ui)-> GG.MeiosisAnimation.set('timeScale', (2 - ui.value)) GG.ObstacleCourseDialogView = Ember.View.extend elementId: 'obstacle-course-dialog' templateName: 'obstacle-course-dialog' tagName: 'div' courseBinding: 'GG.obstacleCourseController.course' obstaclesBinding: 'GG.obstacleCourseController.obstacles' drakeBinding: 'GG.obstacleCourseController.drake' taskReputationBinding: 'GG.reputationController.currentTaskReputation' extraBreedsRepBinding: 'GG.reputationController.extraBreedsRep' meiosisControlRepBinding: 'GG.reputationController.meiosisControlRep' alleleRevealRepBinding: 'GG.reputationController.alleleRevealRep' visibleBinding: 'GG.obstacleCourseController.dialogVisible' taskCompleteBinding: 'GG.obstacleCourseController.taskComplete' currentObstacleBinding: 'GG.obstacleCourseController.currentObstacle' myTotalTimeBinding: 'GG.obstacleCourseController.myTotalTime' opponentTotalTimeBinding: 'GG.obstacleCourseController.opponentTotalTime' nTrainingsBinding: 'GG.cyclesController.cycles' modeBinding: 'GG.obstacleCourseController.mode' trainingPoints: (-> @get('nTrainings') * GG.actionCostsController.getCost('cycleRemainingBonus') ).property('nTrainings') courseCompletionPoints: (-> GG.obstacleCourseController.get('reputationEarned') - @get('trainingPoints') ).property('GG.obstacleCourseController.reputationEarned', 'trainingPoints') isExternalObstacleCourse: (-> @get('mode') == GG.OBSTACLE_COURSE_EXTERNAL ).property('mode') tryAgain: -> # restart task GG.tasksController.restartCurrentTask() continueOn: -> # Go back to town GG.statemanager.transitionTo 'inTown' GG.ObstacleTimeView = Ember.View.extend tagName: 'div' obstacle: null breedsLeftBinding: 'GG.cyclesController.cycles' time: (-> time = GG.obstacleCourseController.calculateTime(@get('obstacle'), false) ).property('obstacle','breedsLeft') GG.ObstacleView = Ember.View.extend tagName: 'div' classNames: ['obstacle'] classNameBindings: ['type', 'after'] attributeBindings : ['style'] after: false skipStyle: false style: (-> if @get 'skipStyle' "" else "top: " + @get('content.positionY') + "px; left: " + @get('content.positionX') + "px;" ).property('content.positionY','content.positionX','skipStyle') typeBinding: "content.obstacle" GG.PasswordField = Ember.TextField.extend type: "password" value: "" loginView: null keyUp: (evt)-> @interpretKeyEvents(evt) if evt.keyCode == 13 and @get('loginView')? @get('loginView').login() GG.BaselineTaskListView = Ember.View.extend tagName: 'div' templateName: 'task-list' taskSelected: (evt) -> GG.statemanager.send 'taskSelected', evt.context GG.townUnlockView = Ember.View.extend templateName: 'town-unlock' contentBinding: 'GG.townsController' costBinding: 'content.nextTownsCost' showPayMessageBinding: 'content.canPayForNextTown' firstTown: (-> @get 'content.firstObject' ).property('content.[]') GG.HelpModeButton = Ember.View.extend GG.PointsToolTip, tagName: 'div' classNames: ['questionmark-button'] classNameBindings: ['active'] activeBinding: 'GG.tooltipController.show' forceTooltip: true toolTipText: "Click to get help by hovering over objects." click: -> GG.statemanager.send 'toggleHelpMode'
[ { "context": "ructions: http://minijs.com/plugins/10/alert\n# By: Matthieu Aussaguel, http://www.mynameismatthieu.com, @mattaussaguel\n", "end": 117, "score": 0.9998971819877625, "start": 99, "tag": "NAME", "value": "Matthieu Aussaguel" }, { "context": "tthieu Aussaguel, http://www.m...
static/js/miniAlert.coffee
ferguson/otto
16
# # miniAlert, an alert plugin for jQuery # Instructions: http://minijs.com/plugins/10/alert # By: Matthieu Aussaguel, http://www.mynameismatthieu.com, @mattaussaguel # Version: v1.0 stable # More info: http://minijs.com/ # jQuery -> $.miniAlert = (element, options) -> # default plugin settings @defaults = text: 'x' # close button text content cssClass: 'close' # close button css class position: 'before' # close button position: 'before' or 'after' effect: 'basic' # closing effect: 'basic' or fade' or 'slide' duration: 100 # hide animation duration in milliseconds onLoad: -> # callback called when the close button has been added onHide: -> # callback called when close button is clicked onHidden: -> # callback called when alert message is hidden @state = '' @settings = {} @$element = $ element setState = (@state) -> @getState = -> state @getSetting = (settingKey) -> @settings[settingKey] @callSettingFunction = (functionName, args = [@$element, @$button]) -> @settings[functionName].apply(this, args) removeElement = => @$element.remove() setState 'hidden' @callSettingFunction 'onHidden', [] addButton = => options = { class: @settings.cssClass, text: @settings.text } @$button = $('<button />', options) if @settings.position is 'after' @$button.appendTo @$element else @$button.prependTo @$element bindButtonEvent = => @$button.bind 'click', (e) => e.preventDefault() setState 'hiding' @callSettingFunction 'onHide' if @settings.effect is 'fade' @$element.fadeOut @settings.duration, removeElement else if @settings.effect is 'slide' @$element.slideUp @settings.duration, removeElement else removeElement() init = => setState 'loading' @settings = $.extend({}, @defaults, options) addButton() bindButtonEvent() setState 'loaded' @callSettingFunction 'onLoad' init() this $.fn.miniAlert = (options) -> this.each -> if undefined == ($ this).data('miniAlert') plugin = new $.miniAlert this, options ($ this).data 'miniAlert', plugin
81890
# # miniAlert, an alert plugin for jQuery # Instructions: http://minijs.com/plugins/10/alert # By: <NAME>, http://www.mynameismatthieu.com, @mattaussaguel # Version: v1.0 stable # More info: http://minijs.com/ # jQuery -> $.miniAlert = (element, options) -> # default plugin settings @defaults = text: 'x' # close button text content cssClass: 'close' # close button css class position: 'before' # close button position: 'before' or 'after' effect: 'basic' # closing effect: 'basic' or fade' or 'slide' duration: 100 # hide animation duration in milliseconds onLoad: -> # callback called when the close button has been added onHide: -> # callback called when close button is clicked onHidden: -> # callback called when alert message is hidden @state = '' @settings = {} @$element = $ element setState = (@state) -> @getState = -> state @getSetting = (settingKey) -> @settings[settingKey] @callSettingFunction = (functionName, args = [@$element, @$button]) -> @settings[functionName].apply(this, args) removeElement = => @$element.remove() setState 'hidden' @callSettingFunction 'onHidden', [] addButton = => options = { class: @settings.cssClass, text: @settings.text } @$button = $('<button />', options) if @settings.position is 'after' @$button.appendTo @$element else @$button.prependTo @$element bindButtonEvent = => @$button.bind 'click', (e) => e.preventDefault() setState 'hiding' @callSettingFunction 'onHide' if @settings.effect is 'fade' @$element.fadeOut @settings.duration, removeElement else if @settings.effect is 'slide' @$element.slideUp @settings.duration, removeElement else removeElement() init = => setState 'loading' @settings = $.extend({}, @defaults, options) addButton() bindButtonEvent() setState 'loaded' @callSettingFunction 'onLoad' init() this $.fn.miniAlert = (options) -> this.each -> if undefined == ($ this).data('miniAlert') plugin = new $.miniAlert this, options ($ this).data 'miniAlert', plugin
true
# # miniAlert, an alert plugin for jQuery # Instructions: http://minijs.com/plugins/10/alert # By: PI:NAME:<NAME>END_PI, http://www.mynameismatthieu.com, @mattaussaguel # Version: v1.0 stable # More info: http://minijs.com/ # jQuery -> $.miniAlert = (element, options) -> # default plugin settings @defaults = text: 'x' # close button text content cssClass: 'close' # close button css class position: 'before' # close button position: 'before' or 'after' effect: 'basic' # closing effect: 'basic' or fade' or 'slide' duration: 100 # hide animation duration in milliseconds onLoad: -> # callback called when the close button has been added onHide: -> # callback called when close button is clicked onHidden: -> # callback called when alert message is hidden @state = '' @settings = {} @$element = $ element setState = (@state) -> @getState = -> state @getSetting = (settingKey) -> @settings[settingKey] @callSettingFunction = (functionName, args = [@$element, @$button]) -> @settings[functionName].apply(this, args) removeElement = => @$element.remove() setState 'hidden' @callSettingFunction 'onHidden', [] addButton = => options = { class: @settings.cssClass, text: @settings.text } @$button = $('<button />', options) if @settings.position is 'after' @$button.appendTo @$element else @$button.prependTo @$element bindButtonEvent = => @$button.bind 'click', (e) => e.preventDefault() setState 'hiding' @callSettingFunction 'onHide' if @settings.effect is 'fade' @$element.fadeOut @settings.duration, removeElement else if @settings.effect is 'slide' @$element.slideUp @settings.duration, removeElement else removeElement() init = => setState 'loading' @settings = $.extend({}, @defaults, options) addButton() bindButtonEvent() setState 'loaded' @callSettingFunction 'onLoad' init() this $.fn.miniAlert = (options) -> this.each -> if undefined == ($ this).data('miniAlert') plugin = new $.miniAlert this, options ($ this).data 'miniAlert', plugin
[ { "context": "or.page('50')\n testPaginator.prevText('Bob')\n allText = fixture.selectAll('li').t", "end": 2716, "score": 0.9992820620536804, "start": 2713, "tag": "NAME", "value": "Bob" }, { "context": "ect buttons', ->\n allText.should.eql(['Bob', '...
src/components/paginator/spec.coffee
p-koscielniak/hexagonjs
61
import chai from 'chai' import { select } from 'utils/selection' import { userFacingText } from 'utils/user-facing-text' import { Paginator, paginator, getPageItems } from 'components/paginator' import emit from 'test/utils/fake-event' export default () -> should = chai.should() describe 'paginator', -> describe 'exports', -> it 'the component', -> should.exist(Paginator) it 'the fluid component', -> should.exist(paginator) describe 'user facing text', -> it 'sets paginatorAria', -> userFacingText('paginator', 'paginatorAria').should.equal('Pagination navigation') it 'sets currentPageAria', -> userFacingText('paginator', 'currentPageAria', true).should.equal('Current page, page $page') it 'sets gotoPageAria', -> userFacingText('paginator', 'gotoPageAria', true).should.equal('Goto page $page') it 'sets prevPageAria', -> userFacingText('paginator', 'prevPageAria', true).should.equal('Goto previous page, page $page') it 'sets nextPageAria', -> userFacingText('paginator', 'nextPageAria', true).should.equal('Goto next page, page $page') it 'sets prev', -> userFacingText('paginator', 'prev').should.equal('Prev') it 'sets next', -> userFacingText('paginator', 'next').should.equal('Next') v2Features = { padding: 2, showCentered: true, useAccessibleRendering: true, } fixture = undefined beforeEach -> fixture = select('body').append('div').class('hx-test-paginator') afterEach -> fixture.remove() describe 'Paginator', -> testPaginator = undefined changeSpy = undefined describe 'when creating a paginator with pageCount 100 and currentPage 1', -> allText = undefined selected = undefined beforeEach -> changeSpy = chai.spy() opts = { pageCount: 100, page: 1, v2Features, } testPaginator = new Paginator(fixture, opts) testPaginator.on 'change', changeSpy allText = fixture.selectAll('li').text() selected = fixture.select('.hx-paginator-selected') it 'shows the correct buttons', -> allText.should.eql(['1', '2', '3', '4', '5', '', '100', userFacingText('paginator', 'next')]) it 'has the correct selected item', -> selected.text().should.equal('1') it 'has the correct pageCount', -> testPaginator.pageCount().should.equal(100) it 'has the correct page', -> testPaginator.page().should.equal(1) describe 'and updating the prev text', -> beforeEach -> testPaginator.page('50') testPaginator.prevText('Bob') allText = fixture.selectAll('li').text() it 'shows the correct buttons', -> allText.should.eql(['Bob', '1', '', '48', '49', '50', '51', '52', '', '100', userFacingText('paginator', 'next')]) it 'adds the container class for the previous and next buttons', -> fixture.selectAll('.hx-paginator-prev-next-container').size().should.equal(2) describe 'and updating the next text', -> beforeEach -> testPaginator.page('50') testPaginator.nextText('Bob') allText = fixture.selectAll('li').text() it 'shows the correct buttons', -> allText.should.eql([ userFacingText('paginator', 'prev'), '1', '', '48', '49', '50', '51', '52', '', '100', 'Bob']) it 'adds the container class for the previous and next buttons', -> fixture.selectAll('.hx-paginator-prev-next-container').size().should.equal(2) describe 'and clicking on a page', -> beforeEach -> fixture.select('li:nth-child(4) a').node().click() it 'has the correct page', -> testPaginator.page().should.equal(4) describe 'and clicking next', -> beforeEach -> fixture.select('li:last-child a').node().click() it 'has the correct page', -> testPaginator.page().should.equal(2) describe 'then clicking prev', -> beforeEach -> fixture.select('li:first-child a').node().click() it 'has the correct page', -> testPaginator.page().should.equal(1) describe 'and pressing the left key', -> beforeEach -> emit(fixture.select('nav').node(), 'keydown', { which: 37 }) it 'has the correct page', -> testPaginator.page().should.equal(1) describe 'and pressing the right key', -> beforeEach -> emit(fixture.select('nav').node(), 'keydown', { which: 39 }) it 'has the correct page', -> testPaginator.page().should.equal(2) describe 'then pressing the left key', -> beforeEach -> emit(fixture.select('nav').node(), 'keydown', { which: 37 }) it 'has the correct page', -> testPaginator.page().should.equal(1) describe 'and setting the current page to 100 with the API', -> beforeEach -> testPaginator.page(100) allText = fixture.selectAll('li').text() it 'shows the correct buttons', -> allText.should.eql([userFacingText('paginator', 'prev'), '1', '', '96', '97', '98', '99', '100']) it 'has the correct page', -> testPaginator.page().should.equal(100) describe 'then pressing the right key', -> beforeEach -> emit(fixture.select('nav').node(), 'keydown', { which: 39 }) it 'has the correct page', -> testPaginator.page().should.equal(100) describe 'and setting the current page to undefined with the API', -> beforeEach -> testPaginator.page(undefined) allText = fixture.selectAll('li').text() it 'sets the page to 1', -> testPaginator.page().should.equal(1) it 'shows the correct buttons', -> allText.should.eql(['1', '2', '3', '4', '5', '', '100', userFacingText('paginator', 'next')]) it 'has the correct page', -> testPaginator.page().should.equal(1) describe 'and setting the pageCount to 30 with the API', -> beforeEach -> testPaginator.pageCount(30) allText = fixture.selectAll('li').text() it 'shows the correct buttons', -> allText.should.eql(['1', '2', '3', '4', '5', '', '30', userFacingText('paginator', 'next')]) it 'has the correct page', -> testPaginator.page().should.equal(1) describe 'and setting the pageCount to undefined with the API', -> beforeEach -> testPaginator.pageCount(undefined) allText = fixture.selectAll('li').text() it 'shows the correct buttons', -> allText.should.eql(['1', userFacingText('paginator', 'next')]) it 'has the correct page', -> testPaginator.page().should.equal(1) describe 'then setting the page to 1000', -> beforeEach -> testPaginator.page(1000) allText = fixture.selectAll('li').text() it 'shows the correct buttons', -> allText.should.eql([userFacingText('paginator', 'prev'), '1000', userFacingText('paginator', 'next')]) it 'has the correct page', -> testPaginator.page().should.equal(1000) describe 'and disabling updatePageOnSelect', -> beforeEach -> testPaginator.page(4) testPaginator.updatePageOnSelect(false) describe 'then clicking on a page', -> beforeEach -> fixture.select('li:nth-child(3) a').node().click() it 'has not changed the selected item', -> testPaginator.page().should.equal(4) it 'calls the change function', -> changeSpy.should.have.been.called() it 'calls the change function with the correct value', -> changeSpy.should.have.been.called.with({ cause: 'user', value: 2, selected: 2 }) describe 'then clicking next', -> beforeEach -> fixture.select('li:last-child a').node().click() selected = fixture.select('.hx-paginator-selected') it 'has not changed the selected item', -> testPaginator.page().should.equal(4) it 'calls the change function', -> changeSpy.should.have.been.called() it 'calls the change function with the correct value', -> changeSpy.should.have.been.called.with({ cause: 'user', value: 5, selected: 5 }) describe 'then clicking prev', -> beforeEach -> fixture.select('li:first-child a').node().click() selected = fixture.select('.hx-paginator-selected') it 'has the correct page', -> testPaginator.page().should.equal(4) it 'calls the change function', -> changeSpy.should.have.been.called() it 'calls the change function with the correct value', -> changeSpy.should.have.been.called.with({ cause: 'user', value: 3 selected: 3 }) describe 'paginator', -> describe 'when creating a paginator with pageCount 100 and currentPage 1', -> allText = undefined beforeEach -> opts = { pageCount: 100, currentPage: 1, v2Features, } testPaginator = paginator(opts) allText = testPaginator.selectAll('li').text() it 'shows the correct buttons', -> allText.should.eql(['1', '2', '3', '4', '5', '', '100', userFacingText('paginator', 'next')]) describe 'getPageItems', -> runTest = (expectation, currentPage, pageCount) -> it "page: #{currentPage}, pageCount: #{pageCount} => #{expectation}", -> getPageItems(currentPage, pageCount, 2).join(' ').should.equal(expectation) runTest('1~ 2 3 4 5 ... 100 next', 1, 100) runTest('prev 1 2 3~ 4 5 ... 100 next', 3, 100) runTest('prev 1 ... 13 14 15~ 16 17 ... 100 next', 15, 100) runTest('prev 1 ... 96~ 97 98 99 100 next', 96, 100) runTest('prev 1 ... 96 97 98 99 100~', 100, 100) runTest('1~', undefined, 1) runTest('1~', 1, 1) runTest('1~ 2 next', undefined, 2) runTest('1~ 2 next', 1, 2) runTest('prev 1 2~', 2, 2) runTest('1~ 2 3 next', undefined, 3) runTest('1~ 2 3 next', 1, 3) runTest('prev 1 2~ 3 next', 2, 3) runTest('prev 1 2 3~', 3, 3) runTest('1~ 2 3 4 next', undefined, 4) runTest('1~ 2 3 4 next', 1, 4) runTest('prev 1 2~ 3 4 next', 2, 4) runTest('prev 1 2 3~ 4 next', 3, 4) runTest('prev 1 2 3 4~', 4, 4) runTest('1~ 2 3 4 5 next', undefined, 5) runTest('1~ 2 3 4 5 next', 1, 5) runTest('prev 1 2~ 3 4 5 next', 2, 5) runTest('prev 1 2 3~ 4 5 next', 3, 5) runTest('prev 1 2 3 4~ 5 next', 4, 5) runTest('prev 1 2 3 4 5~', 5, 5) runTest('1~ 2 3 4 5 6 next', undefined, 6) runTest('1~ 2 3 4 5 6 next', 1, 6) runTest('prev 1 2~ 3 4 5 6 next', 2, 6) runTest('prev 1 2 3~ 4 5 6 next', 3, 6) runTest('prev 1 2 3 4~ 5 6 next', 4, 6) runTest('prev 1 2 3 4 5~ 6 next', 5, 6) runTest('prev 1 2 3 4 5 6~', 6, 6) runTest('1~ 2 3 4 5 6 7 next', undefined, 7) runTest('1~ 2 3 4 5 6 7 next', 1, 7) runTest('prev 1 2~ 3 4 5 6 7 next', 2, 7) runTest('prev 1 2 3~ 4 5 6 7 next', 3, 7) runTest('prev 1 2 3 4~ 5 6 7 next', 4, 7) runTest('prev 1 2 3 4 5~ 6 7 next', 5, 7) runTest('prev 1 2 3 4 5 6~ 7 next', 6, 7) runTest('prev 1 2 3 4 5 6 7~', 7, 7) runTest('1~ 2 3 4 5 ... 8 next', undefined, 8) runTest('1~ 2 3 4 5 ... 8 next', 1, 8) runTest('prev 1 2~ 3 4 5 ... 8 next', 2, 8) runTest('prev 1 2 3~ 4 5 ... 8 next', 3, 8) runTest('prev 1 2 3 4~ 5 ... 8 next', 4, 8) runTest('prev 1 ... 4 5~ 6 7 8 next', 5, 8) runTest('prev 1 ... 4 5 6~ 7 8 next', 6, 8) runTest('prev 1 ... 4 5 6 7~ 8 next', 7, 8) runTest('prev 1 ... 4 5 6 7 8~', 8, 8) runTest('1~ 2 3 4 5 ... 9 next', undefined, 9) runTest('1~ 2 3 4 5 ... 9 next', 1, 9) runTest('prev 1 2~ 3 4 5 ... 9 next', 2, 9) runTest('prev 1 2 3~ 4 5 ... 9 next', 3, 9) runTest('prev 1 2 3 4~ 5 ... 9 next', 4, 9) runTest('prev 1 ... 5~ 6 7 8 9 next', 5, 9) runTest('prev 1 ... 5 6~ 7 8 9 next', 6, 9) runTest('prev 1 ... 5 6 7~ 8 9 next', 7, 9) runTest('prev 1 ... 5 6 7 8~ 9 next', 8, 9) runTest('prev 1 ... 5 6 7 8 9~', 9, 9) runTest('1~ 2 3 4 5 ... 10 next', undefined, 10) runTest('1~ 2 3 4 5 ... 10 next', 1, 10) runTest('prev 1 2~ 3 4 5 ... 10 next', 2, 10) runTest('prev 1 2 3~ 4 5 ... 10 next', 3, 10) runTest('prev 1 2 3 4~ 5 ... 10 next', 4, 10) runTest('prev 1 2 3 4 5~ ... 10 next', 5, 10) runTest('prev 1 ... 6~ 7 8 9 10 next', 6, 10) runTest('prev 1 ... 6 7~ 8 9 10 next', 7, 10) runTest('prev 1 ... 6 7 8~ 9 10 next', 8, 10) runTest('prev 1 ... 6 7 8 9~ 10 next', 9, 10) runTest('prev 1 ... 6 7 8 9 10~', 10, 10) runTest('1~ 2 3 4 5 ... 11 next', undefined, 11) runTest('1~ 2 3 4 5 ... 11 next', 1, 11) runTest('prev 1 2~ 3 4 5 ... 11 next', 2, 11) runTest('prev 1 2 3~ 4 5 ... 11 next', 3, 11) runTest('prev 1 2 3 4~ 5 ... 11 next', 4, 11) runTest('prev 1 2 3 4 5~ ... 11 next', 5, 11) runTest('prev 1 ... 4 5 6~ 7 8 ... 11 next', 6, 11) runTest('prev 1 ... 7~ 8 9 10 11 next', 7, 11) runTest('prev 1 ... 7 8~ 9 10 11 next', 8, 11) runTest('prev 1 ... 7 8 9~ 10 11 next', 9, 11) runTest('prev 1 ... 7 8 9 10~ 11 next', 10, 11) runTest('prev 1 ... 7 8 9 10 11~', 11, 11) runTest('1~ next', 1, undefined) runTest('prev 2~ next', 2, undefined) runTest('prev 100~ next', 100, undefined)
37262
import chai from 'chai' import { select } from 'utils/selection' import { userFacingText } from 'utils/user-facing-text' import { Paginator, paginator, getPageItems } from 'components/paginator' import emit from 'test/utils/fake-event' export default () -> should = chai.should() describe 'paginator', -> describe 'exports', -> it 'the component', -> should.exist(Paginator) it 'the fluid component', -> should.exist(paginator) describe 'user facing text', -> it 'sets paginatorAria', -> userFacingText('paginator', 'paginatorAria').should.equal('Pagination navigation') it 'sets currentPageAria', -> userFacingText('paginator', 'currentPageAria', true).should.equal('Current page, page $page') it 'sets gotoPageAria', -> userFacingText('paginator', 'gotoPageAria', true).should.equal('Goto page $page') it 'sets prevPageAria', -> userFacingText('paginator', 'prevPageAria', true).should.equal('Goto previous page, page $page') it 'sets nextPageAria', -> userFacingText('paginator', 'nextPageAria', true).should.equal('Goto next page, page $page') it 'sets prev', -> userFacingText('paginator', 'prev').should.equal('Prev') it 'sets next', -> userFacingText('paginator', 'next').should.equal('Next') v2Features = { padding: 2, showCentered: true, useAccessibleRendering: true, } fixture = undefined beforeEach -> fixture = select('body').append('div').class('hx-test-paginator') afterEach -> fixture.remove() describe 'Paginator', -> testPaginator = undefined changeSpy = undefined describe 'when creating a paginator with pageCount 100 and currentPage 1', -> allText = undefined selected = undefined beforeEach -> changeSpy = chai.spy() opts = { pageCount: 100, page: 1, v2Features, } testPaginator = new Paginator(fixture, opts) testPaginator.on 'change', changeSpy allText = fixture.selectAll('li').text() selected = fixture.select('.hx-paginator-selected') it 'shows the correct buttons', -> allText.should.eql(['1', '2', '3', '4', '5', '', '100', userFacingText('paginator', 'next')]) it 'has the correct selected item', -> selected.text().should.equal('1') it 'has the correct pageCount', -> testPaginator.pageCount().should.equal(100) it 'has the correct page', -> testPaginator.page().should.equal(1) describe 'and updating the prev text', -> beforeEach -> testPaginator.page('50') testPaginator.prevText('<NAME>') allText = fixture.selectAll('li').text() it 'shows the correct buttons', -> allText.should.eql(['<NAME>', '1', '', '48', '49', '50', '51', '52', '', '100', userFacingText('paginator', 'next')]) it 'adds the container class for the previous and next buttons', -> fixture.selectAll('.hx-paginator-prev-next-container').size().should.equal(2) describe 'and updating the next text', -> beforeEach -> testPaginator.page('50') testPaginator.nextText('<NAME>') allText = fixture.selectAll('li').text() it 'shows the correct buttons', -> allText.should.eql([ userFacingText('paginator', 'prev'), '1', '', '48', '49', '50', '51', '52', '', '100', '<NAME>']) it 'adds the container class for the previous and next buttons', -> fixture.selectAll('.hx-paginator-prev-next-container').size().should.equal(2) describe 'and clicking on a page', -> beforeEach -> fixture.select('li:nth-child(4) a').node().click() it 'has the correct page', -> testPaginator.page().should.equal(4) describe 'and clicking next', -> beforeEach -> fixture.select('li:last-child a').node().click() it 'has the correct page', -> testPaginator.page().should.equal(2) describe 'then clicking prev', -> beforeEach -> fixture.select('li:first-child a').node().click() it 'has the correct page', -> testPaginator.page().should.equal(1) describe 'and pressing the left key', -> beforeEach -> emit(fixture.select('nav').node(), 'keydown', { which: 37 }) it 'has the correct page', -> testPaginator.page().should.equal(1) describe 'and pressing the right key', -> beforeEach -> emit(fixture.select('nav').node(), 'keydown', { which: 39 }) it 'has the correct page', -> testPaginator.page().should.equal(2) describe 'then pressing the left key', -> beforeEach -> emit(fixture.select('nav').node(), 'keydown', { which: 37 }) it 'has the correct page', -> testPaginator.page().should.equal(1) describe 'and setting the current page to 100 with the API', -> beforeEach -> testPaginator.page(100) allText = fixture.selectAll('li').text() it 'shows the correct buttons', -> allText.should.eql([userFacingText('paginator', 'prev'), '1', '', '96', '97', '98', '99', '100']) it 'has the correct page', -> testPaginator.page().should.equal(100) describe 'then pressing the right key', -> beforeEach -> emit(fixture.select('nav').node(), 'keydown', { which: 39 }) it 'has the correct page', -> testPaginator.page().should.equal(100) describe 'and setting the current page to undefined with the API', -> beforeEach -> testPaginator.page(undefined) allText = fixture.selectAll('li').text() it 'sets the page to 1', -> testPaginator.page().should.equal(1) it 'shows the correct buttons', -> allText.should.eql(['1', '2', '3', '4', '5', '', '100', userFacingText('paginator', 'next')]) it 'has the correct page', -> testPaginator.page().should.equal(1) describe 'and setting the pageCount to 30 with the API', -> beforeEach -> testPaginator.pageCount(30) allText = fixture.selectAll('li').text() it 'shows the correct buttons', -> allText.should.eql(['1', '2', '3', '4', '5', '', '30', userFacingText('paginator', 'next')]) it 'has the correct page', -> testPaginator.page().should.equal(1) describe 'and setting the pageCount to undefined with the API', -> beforeEach -> testPaginator.pageCount(undefined) allText = fixture.selectAll('li').text() it 'shows the correct buttons', -> allText.should.eql(['1', userFacingText('paginator', 'next')]) it 'has the correct page', -> testPaginator.page().should.equal(1) describe 'then setting the page to 1000', -> beforeEach -> testPaginator.page(1000) allText = fixture.selectAll('li').text() it 'shows the correct buttons', -> allText.should.eql([userFacingText('paginator', 'prev'), '1000', userFacingText('paginator', 'next')]) it 'has the correct page', -> testPaginator.page().should.equal(1000) describe 'and disabling updatePageOnSelect', -> beforeEach -> testPaginator.page(4) testPaginator.updatePageOnSelect(false) describe 'then clicking on a page', -> beforeEach -> fixture.select('li:nth-child(3) a').node().click() it 'has not changed the selected item', -> testPaginator.page().should.equal(4) it 'calls the change function', -> changeSpy.should.have.been.called() it 'calls the change function with the correct value', -> changeSpy.should.have.been.called.with({ cause: 'user', value: 2, selected: 2 }) describe 'then clicking next', -> beforeEach -> fixture.select('li:last-child a').node().click() selected = fixture.select('.hx-paginator-selected') it 'has not changed the selected item', -> testPaginator.page().should.equal(4) it 'calls the change function', -> changeSpy.should.have.been.called() it 'calls the change function with the correct value', -> changeSpy.should.have.been.called.with({ cause: 'user', value: 5, selected: 5 }) describe 'then clicking prev', -> beforeEach -> fixture.select('li:first-child a').node().click() selected = fixture.select('.hx-paginator-selected') it 'has the correct page', -> testPaginator.page().should.equal(4) it 'calls the change function', -> changeSpy.should.have.been.called() it 'calls the change function with the correct value', -> changeSpy.should.have.been.called.with({ cause: 'user', value: 3 selected: 3 }) describe 'paginator', -> describe 'when creating a paginator with pageCount 100 and currentPage 1', -> allText = undefined beforeEach -> opts = { pageCount: 100, currentPage: 1, v2Features, } testPaginator = paginator(opts) allText = testPaginator.selectAll('li').text() it 'shows the correct buttons', -> allText.should.eql(['1', '2', '3', '4', '5', '', '100', userFacingText('paginator', 'next')]) describe 'getPageItems', -> runTest = (expectation, currentPage, pageCount) -> it "page: #{currentPage}, pageCount: #{pageCount} => #{expectation}", -> getPageItems(currentPage, pageCount, 2).join(' ').should.equal(expectation) runTest('1~ 2 3 4 5 ... 100 next', 1, 100) runTest('prev 1 2 3~ 4 5 ... 100 next', 3, 100) runTest('prev 1 ... 13 14 15~ 16 17 ... 100 next', 15, 100) runTest('prev 1 ... 96~ 97 98 99 100 next', 96, 100) runTest('prev 1 ... 96 97 98 99 100~', 100, 100) runTest('1~', undefined, 1) runTest('1~', 1, 1) runTest('1~ 2 next', undefined, 2) runTest('1~ 2 next', 1, 2) runTest('prev 1 2~', 2, 2) runTest('1~ 2 3 next', undefined, 3) runTest('1~ 2 3 next', 1, 3) runTest('prev 1 2~ 3 next', 2, 3) runTest('prev 1 2 3~', 3, 3) runTest('1~ 2 3 4 next', undefined, 4) runTest('1~ 2 3 4 next', 1, 4) runTest('prev 1 2~ 3 4 next', 2, 4) runTest('prev 1 2 3~ 4 next', 3, 4) runTest('prev 1 2 3 4~', 4, 4) runTest('1~ 2 3 4 5 next', undefined, 5) runTest('1~ 2 3 4 5 next', 1, 5) runTest('prev 1 2~ 3 4 5 next', 2, 5) runTest('prev 1 2 3~ 4 5 next', 3, 5) runTest('prev 1 2 3 4~ 5 next', 4, 5) runTest('prev 1 2 3 4 5~', 5, 5) runTest('1~ 2 3 4 5 6 next', undefined, 6) runTest('1~ 2 3 4 5 6 next', 1, 6) runTest('prev 1 2~ 3 4 5 6 next', 2, 6) runTest('prev 1 2 3~ 4 5 6 next', 3, 6) runTest('prev 1 2 3 4~ 5 6 next', 4, 6) runTest('prev 1 2 3 4 5~ 6 next', 5, 6) runTest('prev 1 2 3 4 5 6~', 6, 6) runTest('1~ 2 3 4 5 6 7 next', undefined, 7) runTest('1~ 2 3 4 5 6 7 next', 1, 7) runTest('prev 1 2~ 3 4 5 6 7 next', 2, 7) runTest('prev 1 2 3~ 4 5 6 7 next', 3, 7) runTest('prev 1 2 3 4~ 5 6 7 next', 4, 7) runTest('prev 1 2 3 4 5~ 6 7 next', 5, 7) runTest('prev 1 2 3 4 5 6~ 7 next', 6, 7) runTest('prev 1 2 3 4 5 6 7~', 7, 7) runTest('1~ 2 3 4 5 ... 8 next', undefined, 8) runTest('1~ 2 3 4 5 ... 8 next', 1, 8) runTest('prev 1 2~ 3 4 5 ... 8 next', 2, 8) runTest('prev 1 2 3~ 4 5 ... 8 next', 3, 8) runTest('prev 1 2 3 4~ 5 ... 8 next', 4, 8) runTest('prev 1 ... 4 5~ 6 7 8 next', 5, 8) runTest('prev 1 ... 4 5 6~ 7 8 next', 6, 8) runTest('prev 1 ... 4 5 6 7~ 8 next', 7, 8) runTest('prev 1 ... 4 5 6 7 8~', 8, 8) runTest('1~ 2 3 4 5 ... 9 next', undefined, 9) runTest('1~ 2 3 4 5 ... 9 next', 1, 9) runTest('prev 1 2~ 3 4 5 ... 9 next', 2, 9) runTest('prev 1 2 3~ 4 5 ... 9 next', 3, 9) runTest('prev 1 2 3 4~ 5 ... 9 next', 4, 9) runTest('prev 1 ... 5~ 6 7 8 9 next', 5, 9) runTest('prev 1 ... 5 6~ 7 8 9 next', 6, 9) runTest('prev 1 ... 5 6 7~ 8 9 next', 7, 9) runTest('prev 1 ... 5 6 7 8~ 9 next', 8, 9) runTest('prev 1 ... 5 6 7 8 9~', 9, 9) runTest('1~ 2 3 4 5 ... 10 next', undefined, 10) runTest('1~ 2 3 4 5 ... 10 next', 1, 10) runTest('prev 1 2~ 3 4 5 ... 10 next', 2, 10) runTest('prev 1 2 3~ 4 5 ... 10 next', 3, 10) runTest('prev 1 2 3 4~ 5 ... 10 next', 4, 10) runTest('prev 1 2 3 4 5~ ... 10 next', 5, 10) runTest('prev 1 ... 6~ 7 8 9 10 next', 6, 10) runTest('prev 1 ... 6 7~ 8 9 10 next', 7, 10) runTest('prev 1 ... 6 7 8~ 9 10 next', 8, 10) runTest('prev 1 ... 6 7 8 9~ 10 next', 9, 10) runTest('prev 1 ... 6 7 8 9 10~', 10, 10) runTest('1~ 2 3 4 5 ... 11 next', undefined, 11) runTest('1~ 2 3 4 5 ... 11 next', 1, 11) runTest('prev 1 2~ 3 4 5 ... 11 next', 2, 11) runTest('prev 1 2 3~ 4 5 ... 11 next', 3, 11) runTest('prev 1 2 3 4~ 5 ... 11 next', 4, 11) runTest('prev 1 2 3 4 5~ ... 11 next', 5, 11) runTest('prev 1 ... 4 5 6~ 7 8 ... 11 next', 6, 11) runTest('prev 1 ... 7~ 8 9 10 11 next', 7, 11) runTest('prev 1 ... 7 8~ 9 10 11 next', 8, 11) runTest('prev 1 ... 7 8 9~ 10 11 next', 9, 11) runTest('prev 1 ... 7 8 9 10~ 11 next', 10, 11) runTest('prev 1 ... 7 8 9 10 11~', 11, 11) runTest('1~ next', 1, undefined) runTest('prev 2~ next', 2, undefined) runTest('prev 100~ next', 100, undefined)
true
import chai from 'chai' import { select } from 'utils/selection' import { userFacingText } from 'utils/user-facing-text' import { Paginator, paginator, getPageItems } from 'components/paginator' import emit from 'test/utils/fake-event' export default () -> should = chai.should() describe 'paginator', -> describe 'exports', -> it 'the component', -> should.exist(Paginator) it 'the fluid component', -> should.exist(paginator) describe 'user facing text', -> it 'sets paginatorAria', -> userFacingText('paginator', 'paginatorAria').should.equal('Pagination navigation') it 'sets currentPageAria', -> userFacingText('paginator', 'currentPageAria', true).should.equal('Current page, page $page') it 'sets gotoPageAria', -> userFacingText('paginator', 'gotoPageAria', true).should.equal('Goto page $page') it 'sets prevPageAria', -> userFacingText('paginator', 'prevPageAria', true).should.equal('Goto previous page, page $page') it 'sets nextPageAria', -> userFacingText('paginator', 'nextPageAria', true).should.equal('Goto next page, page $page') it 'sets prev', -> userFacingText('paginator', 'prev').should.equal('Prev') it 'sets next', -> userFacingText('paginator', 'next').should.equal('Next') v2Features = { padding: 2, showCentered: true, useAccessibleRendering: true, } fixture = undefined beforeEach -> fixture = select('body').append('div').class('hx-test-paginator') afterEach -> fixture.remove() describe 'Paginator', -> testPaginator = undefined changeSpy = undefined describe 'when creating a paginator with pageCount 100 and currentPage 1', -> allText = undefined selected = undefined beforeEach -> changeSpy = chai.spy() opts = { pageCount: 100, page: 1, v2Features, } testPaginator = new Paginator(fixture, opts) testPaginator.on 'change', changeSpy allText = fixture.selectAll('li').text() selected = fixture.select('.hx-paginator-selected') it 'shows the correct buttons', -> allText.should.eql(['1', '2', '3', '4', '5', '', '100', userFacingText('paginator', 'next')]) it 'has the correct selected item', -> selected.text().should.equal('1') it 'has the correct pageCount', -> testPaginator.pageCount().should.equal(100) it 'has the correct page', -> testPaginator.page().should.equal(1) describe 'and updating the prev text', -> beforeEach -> testPaginator.page('50') testPaginator.prevText('PI:NAME:<NAME>END_PI') allText = fixture.selectAll('li').text() it 'shows the correct buttons', -> allText.should.eql(['PI:NAME:<NAME>END_PI', '1', '', '48', '49', '50', '51', '52', '', '100', userFacingText('paginator', 'next')]) it 'adds the container class for the previous and next buttons', -> fixture.selectAll('.hx-paginator-prev-next-container').size().should.equal(2) describe 'and updating the next text', -> beforeEach -> testPaginator.page('50') testPaginator.nextText('PI:NAME:<NAME>END_PI') allText = fixture.selectAll('li').text() it 'shows the correct buttons', -> allText.should.eql([ userFacingText('paginator', 'prev'), '1', '', '48', '49', '50', '51', '52', '', '100', 'PI:NAME:<NAME>END_PI']) it 'adds the container class for the previous and next buttons', -> fixture.selectAll('.hx-paginator-prev-next-container').size().should.equal(2) describe 'and clicking on a page', -> beforeEach -> fixture.select('li:nth-child(4) a').node().click() it 'has the correct page', -> testPaginator.page().should.equal(4) describe 'and clicking next', -> beforeEach -> fixture.select('li:last-child a').node().click() it 'has the correct page', -> testPaginator.page().should.equal(2) describe 'then clicking prev', -> beforeEach -> fixture.select('li:first-child a').node().click() it 'has the correct page', -> testPaginator.page().should.equal(1) describe 'and pressing the left key', -> beforeEach -> emit(fixture.select('nav').node(), 'keydown', { which: 37 }) it 'has the correct page', -> testPaginator.page().should.equal(1) describe 'and pressing the right key', -> beforeEach -> emit(fixture.select('nav').node(), 'keydown', { which: 39 }) it 'has the correct page', -> testPaginator.page().should.equal(2) describe 'then pressing the left key', -> beforeEach -> emit(fixture.select('nav').node(), 'keydown', { which: 37 }) it 'has the correct page', -> testPaginator.page().should.equal(1) describe 'and setting the current page to 100 with the API', -> beforeEach -> testPaginator.page(100) allText = fixture.selectAll('li').text() it 'shows the correct buttons', -> allText.should.eql([userFacingText('paginator', 'prev'), '1', '', '96', '97', '98', '99', '100']) it 'has the correct page', -> testPaginator.page().should.equal(100) describe 'then pressing the right key', -> beforeEach -> emit(fixture.select('nav').node(), 'keydown', { which: 39 }) it 'has the correct page', -> testPaginator.page().should.equal(100) describe 'and setting the current page to undefined with the API', -> beforeEach -> testPaginator.page(undefined) allText = fixture.selectAll('li').text() it 'sets the page to 1', -> testPaginator.page().should.equal(1) it 'shows the correct buttons', -> allText.should.eql(['1', '2', '3', '4', '5', '', '100', userFacingText('paginator', 'next')]) it 'has the correct page', -> testPaginator.page().should.equal(1) describe 'and setting the pageCount to 30 with the API', -> beforeEach -> testPaginator.pageCount(30) allText = fixture.selectAll('li').text() it 'shows the correct buttons', -> allText.should.eql(['1', '2', '3', '4', '5', '', '30', userFacingText('paginator', 'next')]) it 'has the correct page', -> testPaginator.page().should.equal(1) describe 'and setting the pageCount to undefined with the API', -> beforeEach -> testPaginator.pageCount(undefined) allText = fixture.selectAll('li').text() it 'shows the correct buttons', -> allText.should.eql(['1', userFacingText('paginator', 'next')]) it 'has the correct page', -> testPaginator.page().should.equal(1) describe 'then setting the page to 1000', -> beforeEach -> testPaginator.page(1000) allText = fixture.selectAll('li').text() it 'shows the correct buttons', -> allText.should.eql([userFacingText('paginator', 'prev'), '1000', userFacingText('paginator', 'next')]) it 'has the correct page', -> testPaginator.page().should.equal(1000) describe 'and disabling updatePageOnSelect', -> beforeEach -> testPaginator.page(4) testPaginator.updatePageOnSelect(false) describe 'then clicking on a page', -> beforeEach -> fixture.select('li:nth-child(3) a').node().click() it 'has not changed the selected item', -> testPaginator.page().should.equal(4) it 'calls the change function', -> changeSpy.should.have.been.called() it 'calls the change function with the correct value', -> changeSpy.should.have.been.called.with({ cause: 'user', value: 2, selected: 2 }) describe 'then clicking next', -> beforeEach -> fixture.select('li:last-child a').node().click() selected = fixture.select('.hx-paginator-selected') it 'has not changed the selected item', -> testPaginator.page().should.equal(4) it 'calls the change function', -> changeSpy.should.have.been.called() it 'calls the change function with the correct value', -> changeSpy.should.have.been.called.with({ cause: 'user', value: 5, selected: 5 }) describe 'then clicking prev', -> beforeEach -> fixture.select('li:first-child a').node().click() selected = fixture.select('.hx-paginator-selected') it 'has the correct page', -> testPaginator.page().should.equal(4) it 'calls the change function', -> changeSpy.should.have.been.called() it 'calls the change function with the correct value', -> changeSpy.should.have.been.called.with({ cause: 'user', value: 3 selected: 3 }) describe 'paginator', -> describe 'when creating a paginator with pageCount 100 and currentPage 1', -> allText = undefined beforeEach -> opts = { pageCount: 100, currentPage: 1, v2Features, } testPaginator = paginator(opts) allText = testPaginator.selectAll('li').text() it 'shows the correct buttons', -> allText.should.eql(['1', '2', '3', '4', '5', '', '100', userFacingText('paginator', 'next')]) describe 'getPageItems', -> runTest = (expectation, currentPage, pageCount) -> it "page: #{currentPage}, pageCount: #{pageCount} => #{expectation}", -> getPageItems(currentPage, pageCount, 2).join(' ').should.equal(expectation) runTest('1~ 2 3 4 5 ... 100 next', 1, 100) runTest('prev 1 2 3~ 4 5 ... 100 next', 3, 100) runTest('prev 1 ... 13 14 15~ 16 17 ... 100 next', 15, 100) runTest('prev 1 ... 96~ 97 98 99 100 next', 96, 100) runTest('prev 1 ... 96 97 98 99 100~', 100, 100) runTest('1~', undefined, 1) runTest('1~', 1, 1) runTest('1~ 2 next', undefined, 2) runTest('1~ 2 next', 1, 2) runTest('prev 1 2~', 2, 2) runTest('1~ 2 3 next', undefined, 3) runTest('1~ 2 3 next', 1, 3) runTest('prev 1 2~ 3 next', 2, 3) runTest('prev 1 2 3~', 3, 3) runTest('1~ 2 3 4 next', undefined, 4) runTest('1~ 2 3 4 next', 1, 4) runTest('prev 1 2~ 3 4 next', 2, 4) runTest('prev 1 2 3~ 4 next', 3, 4) runTest('prev 1 2 3 4~', 4, 4) runTest('1~ 2 3 4 5 next', undefined, 5) runTest('1~ 2 3 4 5 next', 1, 5) runTest('prev 1 2~ 3 4 5 next', 2, 5) runTest('prev 1 2 3~ 4 5 next', 3, 5) runTest('prev 1 2 3 4~ 5 next', 4, 5) runTest('prev 1 2 3 4 5~', 5, 5) runTest('1~ 2 3 4 5 6 next', undefined, 6) runTest('1~ 2 3 4 5 6 next', 1, 6) runTest('prev 1 2~ 3 4 5 6 next', 2, 6) runTest('prev 1 2 3~ 4 5 6 next', 3, 6) runTest('prev 1 2 3 4~ 5 6 next', 4, 6) runTest('prev 1 2 3 4 5~ 6 next', 5, 6) runTest('prev 1 2 3 4 5 6~', 6, 6) runTest('1~ 2 3 4 5 6 7 next', undefined, 7) runTest('1~ 2 3 4 5 6 7 next', 1, 7) runTest('prev 1 2~ 3 4 5 6 7 next', 2, 7) runTest('prev 1 2 3~ 4 5 6 7 next', 3, 7) runTest('prev 1 2 3 4~ 5 6 7 next', 4, 7) runTest('prev 1 2 3 4 5~ 6 7 next', 5, 7) runTest('prev 1 2 3 4 5 6~ 7 next', 6, 7) runTest('prev 1 2 3 4 5 6 7~', 7, 7) runTest('1~ 2 3 4 5 ... 8 next', undefined, 8) runTest('1~ 2 3 4 5 ... 8 next', 1, 8) runTest('prev 1 2~ 3 4 5 ... 8 next', 2, 8) runTest('prev 1 2 3~ 4 5 ... 8 next', 3, 8) runTest('prev 1 2 3 4~ 5 ... 8 next', 4, 8) runTest('prev 1 ... 4 5~ 6 7 8 next', 5, 8) runTest('prev 1 ... 4 5 6~ 7 8 next', 6, 8) runTest('prev 1 ... 4 5 6 7~ 8 next', 7, 8) runTest('prev 1 ... 4 5 6 7 8~', 8, 8) runTest('1~ 2 3 4 5 ... 9 next', undefined, 9) runTest('1~ 2 3 4 5 ... 9 next', 1, 9) runTest('prev 1 2~ 3 4 5 ... 9 next', 2, 9) runTest('prev 1 2 3~ 4 5 ... 9 next', 3, 9) runTest('prev 1 2 3 4~ 5 ... 9 next', 4, 9) runTest('prev 1 ... 5~ 6 7 8 9 next', 5, 9) runTest('prev 1 ... 5 6~ 7 8 9 next', 6, 9) runTest('prev 1 ... 5 6 7~ 8 9 next', 7, 9) runTest('prev 1 ... 5 6 7 8~ 9 next', 8, 9) runTest('prev 1 ... 5 6 7 8 9~', 9, 9) runTest('1~ 2 3 4 5 ... 10 next', undefined, 10) runTest('1~ 2 3 4 5 ... 10 next', 1, 10) runTest('prev 1 2~ 3 4 5 ... 10 next', 2, 10) runTest('prev 1 2 3~ 4 5 ... 10 next', 3, 10) runTest('prev 1 2 3 4~ 5 ... 10 next', 4, 10) runTest('prev 1 2 3 4 5~ ... 10 next', 5, 10) runTest('prev 1 ... 6~ 7 8 9 10 next', 6, 10) runTest('prev 1 ... 6 7~ 8 9 10 next', 7, 10) runTest('prev 1 ... 6 7 8~ 9 10 next', 8, 10) runTest('prev 1 ... 6 7 8 9~ 10 next', 9, 10) runTest('prev 1 ... 6 7 8 9 10~', 10, 10) runTest('1~ 2 3 4 5 ... 11 next', undefined, 11) runTest('1~ 2 3 4 5 ... 11 next', 1, 11) runTest('prev 1 2~ 3 4 5 ... 11 next', 2, 11) runTest('prev 1 2 3~ 4 5 ... 11 next', 3, 11) runTest('prev 1 2 3 4~ 5 ... 11 next', 4, 11) runTest('prev 1 2 3 4 5~ ... 11 next', 5, 11) runTest('prev 1 ... 4 5 6~ 7 8 ... 11 next', 6, 11) runTest('prev 1 ... 7~ 8 9 10 11 next', 7, 11) runTest('prev 1 ... 7 8~ 9 10 11 next', 8, 11) runTest('prev 1 ... 7 8 9~ 10 11 next', 9, 11) runTest('prev 1 ... 7 8 9 10~ 11 next', 10, 11) runTest('prev 1 ... 7 8 9 10 11~', 11, 11) runTest('1~ next', 1, undefined) runTest('prev 2~ next', 2, undefined) runTest('prev 100~ next', 100, undefined)
[ { "context": "###\n@author Louis Stowasser <louisstow@gmail.com>\nLicense: MIT\n###\n{DomBuilde", "end": 27, "score": 0.9998927712440491, "start": 12, "tag": "NAME", "value": "Louis Stowasser" }, { "context": "###\n@author Louis Stowasser <louisstow@gmail.com>\nLicense: MIT\n###\n{Do...
scripts-src/toc.coffee
Kosx-Kosx/js-revca
25
### @author Louis Stowasser <louisstow@gmail.com> License: MIT ### {DomBuilder} = require "./dom_builder" exports.generateTOC = (rootNode, startLevel) -> lastLevel = 0 startLevel = startLevel or 2 #which H# tag to start indexing. dom = new DomBuilder dom.tag "ul" dom.tag "li" #loop every node in rootNode for node, i in rootNode.childNodes #skip nodes that aren't <H#> tags continue if not node.tagName or not /H[0-9]/.test(node.tagName) level = parseInt node.tagName.substr(1), 10 #only parse at the start level continue if level < startLevel #if the <H#> tag has any children, take the text of the first child #else grab the text of the <H#> tag name = node.textContent #skip this node if there is no name continue unless name #create a string that can be used for an anchor hash based #on the name but without dots or spaces hashable = name.replace(/[\.\s]/g, "-") #set the id of the <H#> tag to this hash node.id = hashable #generate the HTML if level is lastLevel dom.end() #li dom.tag("li") else if level < lastLevel lvl = level while lvl < lastLevel dom.end().end() lvl += 1 dom.end().tag("li") else if level > lastLevel lvl = level while lvl < lastLevel dom.tag("ul").tag("li") lvl -= 1 dom.tag("a").CLASS('lvl' + level).a("href", "#" + hashable).text(name).end() lastLevel = level dom.end() dom.finalize()
128522
### @author <NAME> <<EMAIL>> License: MIT ### {DomBuilder} = require "./dom_builder" exports.generateTOC = (rootNode, startLevel) -> lastLevel = 0 startLevel = startLevel or 2 #which H# tag to start indexing. dom = new DomBuilder dom.tag "ul" dom.tag "li" #loop every node in rootNode for node, i in rootNode.childNodes #skip nodes that aren't <H#> tags continue if not node.tagName or not /H[0-9]/.test(node.tagName) level = parseInt node.tagName.substr(1), 10 #only parse at the start level continue if level < startLevel #if the <H#> tag has any children, take the text of the first child #else grab the text of the <H#> tag name = node.textContent #skip this node if there is no name continue unless name #create a string that can be used for an anchor hash based #on the name but without dots or spaces hashable = name.replace(/[\.\s]/g, "-") #set the id of the <H#> tag to this hash node.id = hashable #generate the HTML if level is lastLevel dom.end() #li dom.tag("li") else if level < lastLevel lvl = level while lvl < lastLevel dom.end().end() lvl += 1 dom.end().tag("li") else if level > lastLevel lvl = level while lvl < lastLevel dom.tag("ul").tag("li") lvl -= 1 dom.tag("a").CLASS('lvl' + level).a("href", "#" + hashable).text(name).end() lastLevel = level dom.end() dom.finalize()
true
### @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> License: MIT ### {DomBuilder} = require "./dom_builder" exports.generateTOC = (rootNode, startLevel) -> lastLevel = 0 startLevel = startLevel or 2 #which H# tag to start indexing. dom = new DomBuilder dom.tag "ul" dom.tag "li" #loop every node in rootNode for node, i in rootNode.childNodes #skip nodes that aren't <H#> tags continue if not node.tagName or not /H[0-9]/.test(node.tagName) level = parseInt node.tagName.substr(1), 10 #only parse at the start level continue if level < startLevel #if the <H#> tag has any children, take the text of the first child #else grab the text of the <H#> tag name = node.textContent #skip this node if there is no name continue unless name #create a string that can be used for an anchor hash based #on the name but without dots or spaces hashable = name.replace(/[\.\s]/g, "-") #set the id of the <H#> tag to this hash node.id = hashable #generate the HTML if level is lastLevel dom.end() #li dom.tag("li") else if level < lastLevel lvl = level while lvl < lastLevel dom.end().end() lvl += 1 dom.end().tag("li") else if level > lastLevel lvl = level while lvl < lastLevel dom.tag("ul").tag("li") lvl -= 1 dom.tag("a").CLASS('lvl' + level).a("href", "#" + hashable).text(name).end() lastLevel = level dom.end() dom.finalize()
[ { "context": "_id\").val()\n if teamId?\n pusher = new Pusher(\"b1276f161ff68bbd81e4\")\n channel = pusher.subscribe(\"team_#{teamId}\"", "end": 479, "score": 0.8697342276573181, "start": 459, "tag": "PASSWORD", "value": "b1276f161ff68bbd81e4" } ]
app/assets/javascripts/teams.js.coffee
railsrumble/r13-team-47
0
$ -> push_screenshot = (data) -> $dom = siteDom(data.site_id) $dom.find('.site-thumb').attr('src', data.thumb_url) $dom.find('.site-thumb').removeClass('spinner') push_points = (data) -> $dom = siteDom(data.site_id) $dom.find('.site-points').html(data.points.number_with_delimiter() + ' points') siteDom = (site_id) -> $(".work[data-site-id='#{site_id}']") teamId = $("#team_id").val() if teamId? pusher = new Pusher("b1276f161ff68bbd81e4") channel = pusher.subscribe("team_#{teamId}") channel.bind "push_screenshot", (data) -> console?.log(data) push_screenshot(data) channel.bind "push_points", (data) -> console?.log(data) push_points(data)
124640
$ -> push_screenshot = (data) -> $dom = siteDom(data.site_id) $dom.find('.site-thumb').attr('src', data.thumb_url) $dom.find('.site-thumb').removeClass('spinner') push_points = (data) -> $dom = siteDom(data.site_id) $dom.find('.site-points').html(data.points.number_with_delimiter() + ' points') siteDom = (site_id) -> $(".work[data-site-id='#{site_id}']") teamId = $("#team_id").val() if teamId? pusher = new Pusher("<PASSWORD>") channel = pusher.subscribe("team_#{teamId}") channel.bind "push_screenshot", (data) -> console?.log(data) push_screenshot(data) channel.bind "push_points", (data) -> console?.log(data) push_points(data)
true
$ -> push_screenshot = (data) -> $dom = siteDom(data.site_id) $dom.find('.site-thumb').attr('src', data.thumb_url) $dom.find('.site-thumb').removeClass('spinner') push_points = (data) -> $dom = siteDom(data.site_id) $dom.find('.site-points').html(data.points.number_with_delimiter() + ' points') siteDom = (site_id) -> $(".work[data-site-id='#{site_id}']") teamId = $("#team_id").val() if teamId? pusher = new Pusher("PI:PASSWORD:<PASSWORD>END_PI") channel = pusher.subscribe("team_#{teamId}") channel.bind "push_screenshot", (data) -> console?.log(data) push_screenshot(data) channel.bind "push_points", (data) -> console?.log(data) push_points(data)
[ { "context": "###\n X-Wing Squad Builder 2.0\n Stephen Kim <raithos@gmail.com>\n https://raithos.github.io", "end": 48, "score": 0.999767541885376, "start": 37, "tag": "NAME", "value": "Stephen Kim" }, { "context": "###\n X-Wing Squad Builder 2.0\n Stephen Kim <raithos...
coffeescripts/system/translate.coffee
danrs/xwing
40
### X-Wing Squad Builder 2.0 Stephen Kim <raithos@gmail.com> https://raithos.github.io ### DFL_LANGUAGE = 'English' # default language SHOW_DEBUG_OUT_MISSING_TRANSLATIONS = false builders = [] exportObj = exports ? this # TODO: create a reasonable scope for this (e.g. a translation class), so vars like currentLanguage # and methods like translateToLang are not within exportObj scope # a language change event will only affect the current language, if it has higher priority than # the current languagePriority. # -1: default language # 3: browser setting # 5: default priority (should not be used by now) # 8: parsed from html header (done in backend) # 10: backend setting # 100: manual selection exportObj.languagePriority = -1 # try to set the current language according to the users choice try (()-> # we'll guess language from browser settings - unless a better choice has already been made if exportObj.languagePriority > 3 return exportObj.currentLanguage = DFL_LANGUAGE # some browses just provide a single navigator.language, some provide an array navigator.languages languageCodes = [navigator.language].concat(navigator.languages) for langc in languageCodes # strip stuff like -US from en-US langc = langc.split('-')[0] if langc of exportObj.codeToLanguage # assume that exportObj already exists. If it does not, we don't know which languages YASB supports exportObj.currentLanguage = exportObj.codeToLanguage[langc] # we successfully found a language the user is somewhat happy with. that's cool exportObj.languagePriority = 3 break )() catch all exportObj.currentLanguage = DFL_LANGUAGE # throw all exportObj.loadCards = (language) -> exportObj.cardLoaders[language]() exportObj.translate = (category, what, args...) -> exportObj.translateToLang(exportObj.currentLanguage, category, what, args...) # this method should be somewhat private, and not be called outside this file exportObj.translateToLang = (language, category, what, args...) -> try translation = exportObj.translations[language][category][what] catch all # well, guess something went wrong - most likely some translation did not exist in the # current language. If that isn't the default language, we'll try that next in belows else block # otherwise we just use whatever is the in-code text of the requested translation. # Anyway, we want to keep running, so better catch that exception and keep going... translation = undefined if translation? if translation instanceof Function # pass this function in case we need to do further translation inside the function translation exportObj.translate, args... else translation else if language != DFL_LANGUAGE if SHOW_DEBUG_OUT_MISSING_TRANSLATIONS console.log(language + ' translation for ' + String(what) + ' (category ' + String(category) + ') missing') exportObj.translateToLang DFL_LANGUAGE, category, what, args... else what exportObj.setupTranslationSupport = -> do (builders) -> $(exportObj).on 'xwing:languageChanged', (e, language, priority=5, cb=$.noop) => # check if priority is high enough to do anything if priority == 'reload' # special case - just a reload, no priority change null # check if a better choice than the requested one has already been made else if priority < exportObj.languagePriority return else exportObj.languagePriority = priority exportObj.currentLanguage = language if language of exportObj.translations $('.language-placeholder').text language current_language = "" for builder in builders current_language = builder.language await builder.container.trigger 'xwing:beforeLanguageLoad', defer() if language != current_language exportObj.loadCards language exportObj.translateUIElements() for builder in builders builder.container.trigger 'xwing:afterLanguageLoad', language # Load cards one time basic_cards = exportObj.basicCardData() exportObj.canonicalizeShipNames basic_cards exportObj.ships = basic_cards.ships # Set up the common card data (e.g. stats) exportObj.setupCommonCardData basic_cards # do we need to load dfl as well? Not sure... exportObj.loadCards DFL_LANGUAGE exportObj.loadCards exportObj.currentLanguage $(exportObj).trigger 'xwing:languageChanged', [exportObj.currentLanguage, 'reload'] exportObj.translateUIElements = (context=undefined) -> # translate all UI elements that are marked as translateable for translateableNode in $('.translated', context) translateableNode.innerHTML = (exportObj.translate('ui', translateableNode.getAttribute('defaultText'))) exportObj.setupTranslationUI = (backend) -> for language in Object.keys(exportObj.cardLoaders).sort() li = $ document.createElement 'LI' li.text language do (language, backend) -> li.click (e) -> backend.set('language', language) if backend? # setting a language manually has pretty high priority $(exportObj).trigger 'xwing:languageChanged', [ language, 100 ] $('.language-picker .dropdown-menu').append li exportObj.registerBuilderForTranslation = (builder) -> builders.push(builder) if builder not in builders
152872
### X-Wing Squad Builder 2.0 <NAME> <<EMAIL>> https://raithos.github.io ### DFL_LANGUAGE = 'English' # default language SHOW_DEBUG_OUT_MISSING_TRANSLATIONS = false builders = [] exportObj = exports ? this # TODO: create a reasonable scope for this (e.g. a translation class), so vars like currentLanguage # and methods like translateToLang are not within exportObj scope # a language change event will only affect the current language, if it has higher priority than # the current languagePriority. # -1: default language # 3: browser setting # 5: default priority (should not be used by now) # 8: parsed from html header (done in backend) # 10: backend setting # 100: manual selection exportObj.languagePriority = -1 # try to set the current language according to the users choice try (()-> # we'll guess language from browser settings - unless a better choice has already been made if exportObj.languagePriority > 3 return exportObj.currentLanguage = DFL_LANGUAGE # some browses just provide a single navigator.language, some provide an array navigator.languages languageCodes = [navigator.language].concat(navigator.languages) for langc in languageCodes # strip stuff like -US from en-US langc = langc.split('-')[0] if langc of exportObj.codeToLanguage # assume that exportObj already exists. If it does not, we don't know which languages YASB supports exportObj.currentLanguage = exportObj.codeToLanguage[langc] # we successfully found a language the user is somewhat happy with. that's cool exportObj.languagePriority = 3 break )() catch all exportObj.currentLanguage = DFL_LANGUAGE # throw all exportObj.loadCards = (language) -> exportObj.cardLoaders[language]() exportObj.translate = (category, what, args...) -> exportObj.translateToLang(exportObj.currentLanguage, category, what, args...) # this method should be somewhat private, and not be called outside this file exportObj.translateToLang = (language, category, what, args...) -> try translation = exportObj.translations[language][category][what] catch all # well, guess something went wrong - most likely some translation did not exist in the # current language. If that isn't the default language, we'll try that next in belows else block # otherwise we just use whatever is the in-code text of the requested translation. # Anyway, we want to keep running, so better catch that exception and keep going... translation = undefined if translation? if translation instanceof Function # pass this function in case we need to do further translation inside the function translation exportObj.translate, args... else translation else if language != DFL_LANGUAGE if SHOW_DEBUG_OUT_MISSING_TRANSLATIONS console.log(language + ' translation for ' + String(what) + ' (category ' + String(category) + ') missing') exportObj.translateToLang DFL_LANGUAGE, category, what, args... else what exportObj.setupTranslationSupport = -> do (builders) -> $(exportObj).on 'xwing:languageChanged', (e, language, priority=5, cb=$.noop) => # check if priority is high enough to do anything if priority == 'reload' # special case - just a reload, no priority change null # check if a better choice than the requested one has already been made else if priority < exportObj.languagePriority return else exportObj.languagePriority = priority exportObj.currentLanguage = language if language of exportObj.translations $('.language-placeholder').text language current_language = "" for builder in builders current_language = builder.language await builder.container.trigger 'xwing:beforeLanguageLoad', defer() if language != current_language exportObj.loadCards language exportObj.translateUIElements() for builder in builders builder.container.trigger 'xwing:afterLanguageLoad', language # Load cards one time basic_cards = exportObj.basicCardData() exportObj.canonicalizeShipNames basic_cards exportObj.ships = basic_cards.ships # Set up the common card data (e.g. stats) exportObj.setupCommonCardData basic_cards # do we need to load dfl as well? Not sure... exportObj.loadCards DFL_LANGUAGE exportObj.loadCards exportObj.currentLanguage $(exportObj).trigger 'xwing:languageChanged', [exportObj.currentLanguage, 'reload'] exportObj.translateUIElements = (context=undefined) -> # translate all UI elements that are marked as translateable for translateableNode in $('.translated', context) translateableNode.innerHTML = (exportObj.translate('ui', translateableNode.getAttribute('defaultText'))) exportObj.setupTranslationUI = (backend) -> for language in Object.keys(exportObj.cardLoaders).sort() li = $ document.createElement 'LI' li.text language do (language, backend) -> li.click (e) -> backend.set('language', language) if backend? # setting a language manually has pretty high priority $(exportObj).trigger 'xwing:languageChanged', [ language, 100 ] $('.language-picker .dropdown-menu').append li exportObj.registerBuilderForTranslation = (builder) -> builders.push(builder) if builder not in builders
true
### X-Wing Squad Builder 2.0 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> https://raithos.github.io ### DFL_LANGUAGE = 'English' # default language SHOW_DEBUG_OUT_MISSING_TRANSLATIONS = false builders = [] exportObj = exports ? this # TODO: create a reasonable scope for this (e.g. a translation class), so vars like currentLanguage # and methods like translateToLang are not within exportObj scope # a language change event will only affect the current language, if it has higher priority than # the current languagePriority. # -1: default language # 3: browser setting # 5: default priority (should not be used by now) # 8: parsed from html header (done in backend) # 10: backend setting # 100: manual selection exportObj.languagePriority = -1 # try to set the current language according to the users choice try (()-> # we'll guess language from browser settings - unless a better choice has already been made if exportObj.languagePriority > 3 return exportObj.currentLanguage = DFL_LANGUAGE # some browses just provide a single navigator.language, some provide an array navigator.languages languageCodes = [navigator.language].concat(navigator.languages) for langc in languageCodes # strip stuff like -US from en-US langc = langc.split('-')[0] if langc of exportObj.codeToLanguage # assume that exportObj already exists. If it does not, we don't know which languages YASB supports exportObj.currentLanguage = exportObj.codeToLanguage[langc] # we successfully found a language the user is somewhat happy with. that's cool exportObj.languagePriority = 3 break )() catch all exportObj.currentLanguage = DFL_LANGUAGE # throw all exportObj.loadCards = (language) -> exportObj.cardLoaders[language]() exportObj.translate = (category, what, args...) -> exportObj.translateToLang(exportObj.currentLanguage, category, what, args...) # this method should be somewhat private, and not be called outside this file exportObj.translateToLang = (language, category, what, args...) -> try translation = exportObj.translations[language][category][what] catch all # well, guess something went wrong - most likely some translation did not exist in the # current language. If that isn't the default language, we'll try that next in belows else block # otherwise we just use whatever is the in-code text of the requested translation. # Anyway, we want to keep running, so better catch that exception and keep going... translation = undefined if translation? if translation instanceof Function # pass this function in case we need to do further translation inside the function translation exportObj.translate, args... else translation else if language != DFL_LANGUAGE if SHOW_DEBUG_OUT_MISSING_TRANSLATIONS console.log(language + ' translation for ' + String(what) + ' (category ' + String(category) + ') missing') exportObj.translateToLang DFL_LANGUAGE, category, what, args... else what exportObj.setupTranslationSupport = -> do (builders) -> $(exportObj).on 'xwing:languageChanged', (e, language, priority=5, cb=$.noop) => # check if priority is high enough to do anything if priority == 'reload' # special case - just a reload, no priority change null # check if a better choice than the requested one has already been made else if priority < exportObj.languagePriority return else exportObj.languagePriority = priority exportObj.currentLanguage = language if language of exportObj.translations $('.language-placeholder').text language current_language = "" for builder in builders current_language = builder.language await builder.container.trigger 'xwing:beforeLanguageLoad', defer() if language != current_language exportObj.loadCards language exportObj.translateUIElements() for builder in builders builder.container.trigger 'xwing:afterLanguageLoad', language # Load cards one time basic_cards = exportObj.basicCardData() exportObj.canonicalizeShipNames basic_cards exportObj.ships = basic_cards.ships # Set up the common card data (e.g. stats) exportObj.setupCommonCardData basic_cards # do we need to load dfl as well? Not sure... exportObj.loadCards DFL_LANGUAGE exportObj.loadCards exportObj.currentLanguage $(exportObj).trigger 'xwing:languageChanged', [exportObj.currentLanguage, 'reload'] exportObj.translateUIElements = (context=undefined) -> # translate all UI elements that are marked as translateable for translateableNode in $('.translated', context) translateableNode.innerHTML = (exportObj.translate('ui', translateableNode.getAttribute('defaultText'))) exportObj.setupTranslationUI = (backend) -> for language in Object.keys(exportObj.cardLoaders).sort() li = $ document.createElement 'LI' li.text language do (language, backend) -> li.click (e) -> backend.set('language', language) if backend? # setting a language manually has pretty high priority $(exportObj).trigger 'xwing:languageChanged', [ language, 100 ] $('.language-picker .dropdown-menu').append li exportObj.registerBuilderForTranslation = (builder) -> builders.push(builder) if builder not in builders
[ { "context": "PDFDocument - represents an entire PDF document\nBy Devon Govett\n###\n\nstream = require 'stream'\nfs = require 'fs'\n", "end": 67, "score": 0.9998584985733032, "start": 55, "tag": "NAME", "value": "Devon Govett" } ]
lib/document.coffee
InCaptus/pdfkit
2
### PDFDocument - represents an entire PDF document By Devon Govett ### stream = require 'stream' fs = require 'fs' PDFObject = require './object' PDFReference = require './reference' PDFPage = require './page' class PDFDocument extends stream.Readable constructor: (@options = {}) -> super # PDF version @version = 1.3 # Whether streams should be compressed @compress = @options.compress ? yes @_pageBuffer = [] @_pageBufferStart = 0 # The PDF object store @_offsets = [] @_waiting = 0 @_ended = false @_offset = 0 @_root = @ref Type: 'Catalog' Pages: @ref Type: 'Pages' Count: 0 Kids: [] # The current page @page = null # Initialize mixins @initColor() @initVector() @initFonts() @initText() @initImages() # Initialize the metadata @info = Producer: 'PDFKit' Creator: 'PDFKit' CreationDate: new Date() if @options.info for key, val of @options.info @info[key] = val # Write the header # PDF version @_write "%PDF-#{@version}" # 4 binary chars, as recommended by the spec @_write "%\xFF\xFF\xFF\xFF" # Add the first page if @options.autoFirstPage isnt false @addPage() mixin = (methods) => for name, method of methods this::[name] = method # Load mixins mixin require './mixins/color' mixin require './mixins/vector' mixin require './mixins/fonts' mixin require './mixins/text' mixin require './mixins/images' mixin require './mixins/annotations' addPage: (options = @options) -> # end the current page if needed @flushPages() unless @options.bufferPages # create a page object @page = new PDFPage(this, options) @_pageBuffer.push(@page) # add the page to the object store pages = @_root.data.Pages.data pages.Kids.push @page.dictionary pages.Count++ # reset x and y coordinates @x = @page.margins.left @y = @page.margins.top # flip PDF coordinate system so that the origin is in # the top left rather than the bottom left @_ctm = [1, 0, 0, 1, 0, 0] @transform 1, 0, 0, -1, 0, @page.height return this bufferedPageRange: -> return { start: @_pageBufferStart, count: @_pageBuffer.length } switchToPage: (n) -> unless page = @_pageBuffer[n - @_pageBufferStart] throw new Error "switchToPage(#{n}) out of bounds, current buffer covers pages #{@_pageBufferStart} to #{@_pageBufferStart + @_pageBuffer.length - 1}" @page = page flushPages: -> # this local variable exists so we're future-proof against # reentrant calls to flushPages. pages = @_pageBuffer @_pageBuffer = [] @_pageBufferStart += pages.length for page in pages page.end() return ref: (data) -> ref = new PDFReference(this, @_offsets.length + 1, data) @_offsets.push null # placeholder for this object's offset once it is finalized @_waiting++ return ref _read: -> # do nothing, but this method is required by node _write: (data) -> unless Buffer.isBuffer(data) data = new Buffer(data + '\n', 'binary') @push data @_offset += data.length addContent: (data) -> @page.write data return this _refEnd: (ref) -> @_offsets[ref.id - 1] = ref.offset if --@_waiting is 0 and @_ended @_finalize() @_ended = false write: (filename, fn) -> # print a deprecation warning with a stacktrace err = new Error ' PDFDocument#write is deprecated, and will be removed in a future version of PDFKit. Please pipe the document into a Node stream. ' console.warn err.stack @pipe fs.createWriteStream(filename) @end() @once 'end', fn output: (fn) -> # more difficult to support this. It would involve concatenating all the buffers together throw new Error ' PDFDocument#output is deprecated, and has been removed from PDFKit. Please pipe the document into a Node stream. ' end: -> @flushPages() @_info = @ref() for key, val of @info if typeof val is 'string' val = new String val @_info.data[key] = val @_info.end() for name, font of @_fontFamilies font.embed() @_root.end() @_root.data.Pages.end() if @_waiting is 0 @_finalize() else @_ended = true _finalize: (fn) -> # generate xref xRefOffset = @_offset @_write "xref" @_write "0 #{@_offsets.length + 1}" @_write "0000000000 65535 f " for offset in @_offsets offset = ('0000000000' + offset).slice(-10) @_write offset + ' 00000 n ' # trailer @_write 'trailer' @_write PDFObject.convert Size: @_offsets.length + 1 Root: @_root Info: @_info @_write 'startxref' @_write "#{xRefOffset}" @_write '%%EOF' # end the stream @push null toString: -> "[object PDFDocument]" module.exports = PDFDocument
207085
### PDFDocument - represents an entire PDF document By <NAME> ### stream = require 'stream' fs = require 'fs' PDFObject = require './object' PDFReference = require './reference' PDFPage = require './page' class PDFDocument extends stream.Readable constructor: (@options = {}) -> super # PDF version @version = 1.3 # Whether streams should be compressed @compress = @options.compress ? yes @_pageBuffer = [] @_pageBufferStart = 0 # The PDF object store @_offsets = [] @_waiting = 0 @_ended = false @_offset = 0 @_root = @ref Type: 'Catalog' Pages: @ref Type: 'Pages' Count: 0 Kids: [] # The current page @page = null # Initialize mixins @initColor() @initVector() @initFonts() @initText() @initImages() # Initialize the metadata @info = Producer: 'PDFKit' Creator: 'PDFKit' CreationDate: new Date() if @options.info for key, val of @options.info @info[key] = val # Write the header # PDF version @_write "%PDF-#{@version}" # 4 binary chars, as recommended by the spec @_write "%\xFF\xFF\xFF\xFF" # Add the first page if @options.autoFirstPage isnt false @addPage() mixin = (methods) => for name, method of methods this::[name] = method # Load mixins mixin require './mixins/color' mixin require './mixins/vector' mixin require './mixins/fonts' mixin require './mixins/text' mixin require './mixins/images' mixin require './mixins/annotations' addPage: (options = @options) -> # end the current page if needed @flushPages() unless @options.bufferPages # create a page object @page = new PDFPage(this, options) @_pageBuffer.push(@page) # add the page to the object store pages = @_root.data.Pages.data pages.Kids.push @page.dictionary pages.Count++ # reset x and y coordinates @x = @page.margins.left @y = @page.margins.top # flip PDF coordinate system so that the origin is in # the top left rather than the bottom left @_ctm = [1, 0, 0, 1, 0, 0] @transform 1, 0, 0, -1, 0, @page.height return this bufferedPageRange: -> return { start: @_pageBufferStart, count: @_pageBuffer.length } switchToPage: (n) -> unless page = @_pageBuffer[n - @_pageBufferStart] throw new Error "switchToPage(#{n}) out of bounds, current buffer covers pages #{@_pageBufferStart} to #{@_pageBufferStart + @_pageBuffer.length - 1}" @page = page flushPages: -> # this local variable exists so we're future-proof against # reentrant calls to flushPages. pages = @_pageBuffer @_pageBuffer = [] @_pageBufferStart += pages.length for page in pages page.end() return ref: (data) -> ref = new PDFReference(this, @_offsets.length + 1, data) @_offsets.push null # placeholder for this object's offset once it is finalized @_waiting++ return ref _read: -> # do nothing, but this method is required by node _write: (data) -> unless Buffer.isBuffer(data) data = new Buffer(data + '\n', 'binary') @push data @_offset += data.length addContent: (data) -> @page.write data return this _refEnd: (ref) -> @_offsets[ref.id - 1] = ref.offset if --@_waiting is 0 and @_ended @_finalize() @_ended = false write: (filename, fn) -> # print a deprecation warning with a stacktrace err = new Error ' PDFDocument#write is deprecated, and will be removed in a future version of PDFKit. Please pipe the document into a Node stream. ' console.warn err.stack @pipe fs.createWriteStream(filename) @end() @once 'end', fn output: (fn) -> # more difficult to support this. It would involve concatenating all the buffers together throw new Error ' PDFDocument#output is deprecated, and has been removed from PDFKit. Please pipe the document into a Node stream. ' end: -> @flushPages() @_info = @ref() for key, val of @info if typeof val is 'string' val = new String val @_info.data[key] = val @_info.end() for name, font of @_fontFamilies font.embed() @_root.end() @_root.data.Pages.end() if @_waiting is 0 @_finalize() else @_ended = true _finalize: (fn) -> # generate xref xRefOffset = @_offset @_write "xref" @_write "0 #{@_offsets.length + 1}" @_write "0000000000 65535 f " for offset in @_offsets offset = ('0000000000' + offset).slice(-10) @_write offset + ' 00000 n ' # trailer @_write 'trailer' @_write PDFObject.convert Size: @_offsets.length + 1 Root: @_root Info: @_info @_write 'startxref' @_write "#{xRefOffset}" @_write '%%EOF' # end the stream @push null toString: -> "[object PDFDocument]" module.exports = PDFDocument
true
### PDFDocument - represents an entire PDF document By PI:NAME:<NAME>END_PI ### stream = require 'stream' fs = require 'fs' PDFObject = require './object' PDFReference = require './reference' PDFPage = require './page' class PDFDocument extends stream.Readable constructor: (@options = {}) -> super # PDF version @version = 1.3 # Whether streams should be compressed @compress = @options.compress ? yes @_pageBuffer = [] @_pageBufferStart = 0 # The PDF object store @_offsets = [] @_waiting = 0 @_ended = false @_offset = 0 @_root = @ref Type: 'Catalog' Pages: @ref Type: 'Pages' Count: 0 Kids: [] # The current page @page = null # Initialize mixins @initColor() @initVector() @initFonts() @initText() @initImages() # Initialize the metadata @info = Producer: 'PDFKit' Creator: 'PDFKit' CreationDate: new Date() if @options.info for key, val of @options.info @info[key] = val # Write the header # PDF version @_write "%PDF-#{@version}" # 4 binary chars, as recommended by the spec @_write "%\xFF\xFF\xFF\xFF" # Add the first page if @options.autoFirstPage isnt false @addPage() mixin = (methods) => for name, method of methods this::[name] = method # Load mixins mixin require './mixins/color' mixin require './mixins/vector' mixin require './mixins/fonts' mixin require './mixins/text' mixin require './mixins/images' mixin require './mixins/annotations' addPage: (options = @options) -> # end the current page if needed @flushPages() unless @options.bufferPages # create a page object @page = new PDFPage(this, options) @_pageBuffer.push(@page) # add the page to the object store pages = @_root.data.Pages.data pages.Kids.push @page.dictionary pages.Count++ # reset x and y coordinates @x = @page.margins.left @y = @page.margins.top # flip PDF coordinate system so that the origin is in # the top left rather than the bottom left @_ctm = [1, 0, 0, 1, 0, 0] @transform 1, 0, 0, -1, 0, @page.height return this bufferedPageRange: -> return { start: @_pageBufferStart, count: @_pageBuffer.length } switchToPage: (n) -> unless page = @_pageBuffer[n - @_pageBufferStart] throw new Error "switchToPage(#{n}) out of bounds, current buffer covers pages #{@_pageBufferStart} to #{@_pageBufferStart + @_pageBuffer.length - 1}" @page = page flushPages: -> # this local variable exists so we're future-proof against # reentrant calls to flushPages. pages = @_pageBuffer @_pageBuffer = [] @_pageBufferStart += pages.length for page in pages page.end() return ref: (data) -> ref = new PDFReference(this, @_offsets.length + 1, data) @_offsets.push null # placeholder for this object's offset once it is finalized @_waiting++ return ref _read: -> # do nothing, but this method is required by node _write: (data) -> unless Buffer.isBuffer(data) data = new Buffer(data + '\n', 'binary') @push data @_offset += data.length addContent: (data) -> @page.write data return this _refEnd: (ref) -> @_offsets[ref.id - 1] = ref.offset if --@_waiting is 0 and @_ended @_finalize() @_ended = false write: (filename, fn) -> # print a deprecation warning with a stacktrace err = new Error ' PDFDocument#write is deprecated, and will be removed in a future version of PDFKit. Please pipe the document into a Node stream. ' console.warn err.stack @pipe fs.createWriteStream(filename) @end() @once 'end', fn output: (fn) -> # more difficult to support this. It would involve concatenating all the buffers together throw new Error ' PDFDocument#output is deprecated, and has been removed from PDFKit. Please pipe the document into a Node stream. ' end: -> @flushPages() @_info = @ref() for key, val of @info if typeof val is 'string' val = new String val @_info.data[key] = val @_info.end() for name, font of @_fontFamilies font.embed() @_root.end() @_root.data.Pages.end() if @_waiting is 0 @_finalize() else @_ended = true _finalize: (fn) -> # generate xref xRefOffset = @_offset @_write "xref" @_write "0 #{@_offsets.length + 1}" @_write "0000000000 65535 f " for offset in @_offsets offset = ('0000000000' + offset).slice(-10) @_write offset + ' 00000 n ' # trailer @_write 'trailer' @_write PDFObject.convert Size: @_offsets.length + 1 Root: @_root Info: @_info @_write 'startxref' @_write "#{xRefOffset}" @_write '%%EOF' # end the stream @push null toString: -> "[object PDFDocument]" module.exports = PDFDocument
[ { "context": "\n# Test CSV - Copyright David Worms <open@adaltas.com> (BSD Licensed)\n\nfs = require '", "end": 35, "score": 0.9998494386672974, "start": 24, "tag": "NAME", "value": "David Worms" }, { "context": "\n# Test CSV - Copyright David Worms <open@adaltas.com> (BSD Licensed)\...
test/quotes.coffee
timoxley/node-csv-parser
1
# Test CSV - Copyright David Worms <open@adaltas.com> (BSD Licensed) fs = require 'fs' assert = require 'assert' csv = require '..' module.exports = 'Test regular quotes': -> csv() .fromPath( "#{__dirname}/quotes/regular.in" ) .toPath( "#{__dirname}/quotes/regular.tmp" ) .on 'end', -> assert.equal( fs.readFileSync("#{__dirname}/quotes/regular.out").toString(), fs.readFileSync("#{__dirname}/quotes/regular.tmp").toString() ) fs.unlink "#{__dirname}/quotes/regular.tmp" 'Test quotes with delimiter': -> csv() .fromPath("#{__dirname}/quotes/delimiter.in") .toPath("#{__dirname}/quotes/delimiter.tmp") .on 'end', -> assert.equal( fs.readFileSync("#{__dirname}/quotes/delimiter.out").toString(), fs.readFileSync("#{__dirname}/quotes/delimiter.tmp").toString() ) fs.unlink "#{__dirname}/quotes/delimiter.tmp" 'Test quotes inside field': -> csv() .fromPath( "#{__dirname}/quotes/in_field.in" ) .toPath( "#{__dirname}/quotes/in_field.tmp" ) .on 'end', -> assert.equal( fs.readFileSync("#{__dirname}/quotes/in_field.out").toString(), fs.readFileSync("#{__dirname}/quotes/in_field.tmp").toString() ) fs.unlink "#{__dirname}/quotes/in_field.tmp" 'Test empty value': -> csv() .fromPath "#{__dirname}/quotes/empty_value.in", quote: '"' escape: '"' .toPath("#{__dirname}/quotes/empty_value.tmp") .on 'end', -> assert.equal( fs.readFileSync("#{__dirname}/quotes/empty_value.out").toString(), fs.readFileSync("#{__dirname}/quotes/empty_value.tmp").toString() ) fs.unlink "#{__dirname}/quotes/empty_value.tmp" 'Test quoted quote': -> csv() .fromPath "#{__dirname}/quotes/quoted.in", quote: '"', escape: '"', .toPath("#{__dirname}/quotes/quoted.tmp") .on 'data', (data,index) -> assert.strictEqual(5,data.length) if index is 0 assert.strictEqual('"',data[1]) assert.strictEqual('"ok"',data[4]) .on 'end', -> assert.equal( fs.readFileSync("#{__dirname}/quotes/quoted.out").toString(), fs.readFileSync("#{__dirname}/quotes/quoted.tmp").toString() ) fs.unlink "#{__dirname}/quotes/quoted.tmp" 'Test quoted linebreak': -> csv() .fromPath "#{__dirname}/quotes/linebreak.in", quote: '"', escape: '"' .toPath("#{__dirname}/quotes/linebreak.tmp") .on 'data', (data,index) -> assert.strictEqual(5,data.length) .on 'end', -> assert.equal( fs.readFileSync("#{__dirname}/quotes/linebreak.out").toString(), fs.readFileSync("#{__dirname}/quotes/linebreak.tmp").toString() ) fs.unlink "#{__dirname}/quotes/linebreak.tmp" 'Test unclosed quote': (next) -> n = 0 csv() .fromPath "#{__dirname}/quotes/unclosed.in", quote: '"' escape: '"' .toPath( "#{__dirname}/quotes/unclosed.tmp" ) .on 'end', -> assert.ok false, 'end was raised' .on 'error', -> ++n next -> # finish assert.equal 1, n, 'error was not raised' fs.unlink "#{__dirname}/quotes/unclosed.tmp" 'Test invalid quotes': (next) -> n = 0 csv() .on 'error', (e) -> assert.equal e.message.split(';')[0], 'Invalid closing quote' ++n .fromPath "#{__dirname}/quotes/invalid.in", quote: '"', escape: '"' .toPath( "#{__dirname}/quotes/invalid.tmp" ) .on 'end', -> assert.ok false, 'end was raised' next -> # finish assert.equal 1, n, 'error was not raised' fs.unlink "#{__dirname}/quotes/invalid.tmp" 'Test invalid quotes from string': (next) -> n = 0 csv() .on 'error', (e) -> assert.equal e.message.split(';')[0], 'Invalid closing quote' ++n .from '"",1974,8.8392926E7,""t,""', quote: '"' escape: '"' .toPath( "#{__dirname}/quotes/invalidstring.tmp" ) .on 'end', -> assert.ok false, 'end was raised' next -> # finish assert.equal 1, n fs.unlink "#{__dirname}/quotes/invalidstring.tmp"
145419
# Test CSV - Copyright <NAME> <<EMAIL>> (BSD Licensed) fs = require 'fs' assert = require 'assert' csv = require '..' module.exports = 'Test regular quotes': -> csv() .fromPath( "#{__dirname}/quotes/regular.in" ) .toPath( "#{__dirname}/quotes/regular.tmp" ) .on 'end', -> assert.equal( fs.readFileSync("#{__dirname}/quotes/regular.out").toString(), fs.readFileSync("#{__dirname}/quotes/regular.tmp").toString() ) fs.unlink "#{__dirname}/quotes/regular.tmp" 'Test quotes with delimiter': -> csv() .fromPath("#{__dirname}/quotes/delimiter.in") .toPath("#{__dirname}/quotes/delimiter.tmp") .on 'end', -> assert.equal( fs.readFileSync("#{__dirname}/quotes/delimiter.out").toString(), fs.readFileSync("#{__dirname}/quotes/delimiter.tmp").toString() ) fs.unlink "#{__dirname}/quotes/delimiter.tmp" 'Test quotes inside field': -> csv() .fromPath( "#{__dirname}/quotes/in_field.in" ) .toPath( "#{__dirname}/quotes/in_field.tmp" ) .on 'end', -> assert.equal( fs.readFileSync("#{__dirname}/quotes/in_field.out").toString(), fs.readFileSync("#{__dirname}/quotes/in_field.tmp").toString() ) fs.unlink "#{__dirname}/quotes/in_field.tmp" 'Test empty value': -> csv() .fromPath "#{__dirname}/quotes/empty_value.in", quote: '"' escape: '"' .toPath("#{__dirname}/quotes/empty_value.tmp") .on 'end', -> assert.equal( fs.readFileSync("#{__dirname}/quotes/empty_value.out").toString(), fs.readFileSync("#{__dirname}/quotes/empty_value.tmp").toString() ) fs.unlink "#{__dirname}/quotes/empty_value.tmp" 'Test quoted quote': -> csv() .fromPath "#{__dirname}/quotes/quoted.in", quote: '"', escape: '"', .toPath("#{__dirname}/quotes/quoted.tmp") .on 'data', (data,index) -> assert.strictEqual(5,data.length) if index is 0 assert.strictEqual('"',data[1]) assert.strictEqual('"ok"',data[4]) .on 'end', -> assert.equal( fs.readFileSync("#{__dirname}/quotes/quoted.out").toString(), fs.readFileSync("#{__dirname}/quotes/quoted.tmp").toString() ) fs.unlink "#{__dirname}/quotes/quoted.tmp" 'Test quoted linebreak': -> csv() .fromPath "#{__dirname}/quotes/linebreak.in", quote: '"', escape: '"' .toPath("#{__dirname}/quotes/linebreak.tmp") .on 'data', (data,index) -> assert.strictEqual(5,data.length) .on 'end', -> assert.equal( fs.readFileSync("#{__dirname}/quotes/linebreak.out").toString(), fs.readFileSync("#{__dirname}/quotes/linebreak.tmp").toString() ) fs.unlink "#{__dirname}/quotes/linebreak.tmp" 'Test unclosed quote': (next) -> n = 0 csv() .fromPath "#{__dirname}/quotes/unclosed.in", quote: '"' escape: '"' .toPath( "#{__dirname}/quotes/unclosed.tmp" ) .on 'end', -> assert.ok false, 'end was raised' .on 'error', -> ++n next -> # finish assert.equal 1, n, 'error was not raised' fs.unlink "#{__dirname}/quotes/unclosed.tmp" 'Test invalid quotes': (next) -> n = 0 csv() .on 'error', (e) -> assert.equal e.message.split(';')[0], 'Invalid closing quote' ++n .fromPath "#{__dirname}/quotes/invalid.in", quote: '"', escape: '"' .toPath( "#{__dirname}/quotes/invalid.tmp" ) .on 'end', -> assert.ok false, 'end was raised' next -> # finish assert.equal 1, n, 'error was not raised' fs.unlink "#{__dirname}/quotes/invalid.tmp" 'Test invalid quotes from string': (next) -> n = 0 csv() .on 'error', (e) -> assert.equal e.message.split(';')[0], 'Invalid closing quote' ++n .from '"",1974,8.8392926E7,""t,""', quote: '"' escape: '"' .toPath( "#{__dirname}/quotes/invalidstring.tmp" ) .on 'end', -> assert.ok false, 'end was raised' next -> # finish assert.equal 1, n fs.unlink "#{__dirname}/quotes/invalidstring.tmp"
true
# Test CSV - Copyright PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> (BSD Licensed) fs = require 'fs' assert = require 'assert' csv = require '..' module.exports = 'Test regular quotes': -> csv() .fromPath( "#{__dirname}/quotes/regular.in" ) .toPath( "#{__dirname}/quotes/regular.tmp" ) .on 'end', -> assert.equal( fs.readFileSync("#{__dirname}/quotes/regular.out").toString(), fs.readFileSync("#{__dirname}/quotes/regular.tmp").toString() ) fs.unlink "#{__dirname}/quotes/regular.tmp" 'Test quotes with delimiter': -> csv() .fromPath("#{__dirname}/quotes/delimiter.in") .toPath("#{__dirname}/quotes/delimiter.tmp") .on 'end', -> assert.equal( fs.readFileSync("#{__dirname}/quotes/delimiter.out").toString(), fs.readFileSync("#{__dirname}/quotes/delimiter.tmp").toString() ) fs.unlink "#{__dirname}/quotes/delimiter.tmp" 'Test quotes inside field': -> csv() .fromPath( "#{__dirname}/quotes/in_field.in" ) .toPath( "#{__dirname}/quotes/in_field.tmp" ) .on 'end', -> assert.equal( fs.readFileSync("#{__dirname}/quotes/in_field.out").toString(), fs.readFileSync("#{__dirname}/quotes/in_field.tmp").toString() ) fs.unlink "#{__dirname}/quotes/in_field.tmp" 'Test empty value': -> csv() .fromPath "#{__dirname}/quotes/empty_value.in", quote: '"' escape: '"' .toPath("#{__dirname}/quotes/empty_value.tmp") .on 'end', -> assert.equal( fs.readFileSync("#{__dirname}/quotes/empty_value.out").toString(), fs.readFileSync("#{__dirname}/quotes/empty_value.tmp").toString() ) fs.unlink "#{__dirname}/quotes/empty_value.tmp" 'Test quoted quote': -> csv() .fromPath "#{__dirname}/quotes/quoted.in", quote: '"', escape: '"', .toPath("#{__dirname}/quotes/quoted.tmp") .on 'data', (data,index) -> assert.strictEqual(5,data.length) if index is 0 assert.strictEqual('"',data[1]) assert.strictEqual('"ok"',data[4]) .on 'end', -> assert.equal( fs.readFileSync("#{__dirname}/quotes/quoted.out").toString(), fs.readFileSync("#{__dirname}/quotes/quoted.tmp").toString() ) fs.unlink "#{__dirname}/quotes/quoted.tmp" 'Test quoted linebreak': -> csv() .fromPath "#{__dirname}/quotes/linebreak.in", quote: '"', escape: '"' .toPath("#{__dirname}/quotes/linebreak.tmp") .on 'data', (data,index) -> assert.strictEqual(5,data.length) .on 'end', -> assert.equal( fs.readFileSync("#{__dirname}/quotes/linebreak.out").toString(), fs.readFileSync("#{__dirname}/quotes/linebreak.tmp").toString() ) fs.unlink "#{__dirname}/quotes/linebreak.tmp" 'Test unclosed quote': (next) -> n = 0 csv() .fromPath "#{__dirname}/quotes/unclosed.in", quote: '"' escape: '"' .toPath( "#{__dirname}/quotes/unclosed.tmp" ) .on 'end', -> assert.ok false, 'end was raised' .on 'error', -> ++n next -> # finish assert.equal 1, n, 'error was not raised' fs.unlink "#{__dirname}/quotes/unclosed.tmp" 'Test invalid quotes': (next) -> n = 0 csv() .on 'error', (e) -> assert.equal e.message.split(';')[0], 'Invalid closing quote' ++n .fromPath "#{__dirname}/quotes/invalid.in", quote: '"', escape: '"' .toPath( "#{__dirname}/quotes/invalid.tmp" ) .on 'end', -> assert.ok false, 'end was raised' next -> # finish assert.equal 1, n, 'error was not raised' fs.unlink "#{__dirname}/quotes/invalid.tmp" 'Test invalid quotes from string': (next) -> n = 0 csv() .on 'error', (e) -> assert.equal e.message.split(';')[0], 'Invalid closing quote' ++n .from '"",1974,8.8392926E7,""t,""', quote: '"' escape: '"' .toPath( "#{__dirname}/quotes/invalidstring.tmp" ) .on 'end', -> assert.ok false, 'end was raised' next -> # finish assert.equal 1, n fs.unlink "#{__dirname}/quotes/invalidstring.tmp"
[ { "context": "# Copyright 2015, Christopher Joakim <christopher.joakim@gmail.com>\n\ndescribe 'Speed',", "end": 36, "score": 0.9998871088027954, "start": 18, "tag": "NAME", "value": "Christopher Joakim" }, { "context": "# Copyright 2015, Christopher Joakim <christopher.joakim@gmail.c...
m26-js/test-src/m26_speed_spec.coffee
cjoakim/oss
0
# Copyright 2015, Christopher Joakim <christopher.joakim@gmail.com> describe 'Speed', -> it 'calculates a 2-mile walk, with round numbers', -> d = new Distance(2.0) t = new ElapsedTime('30:00') s = new Speed(d, t) expect(s.mph()).isWithin(0.000001, 4) expect(s.kph()).isWithin(0.000001, 6.437376) expect(s.yph()).isWithin(0.000001, 7040) expect(s.seconds_per_mile()).isWithin(0.000001, 900) expect(s.pace_per_mile()).toBe('15:00') it 'calculates a marathon, with fractional pace_per_mile', -> d = new Distance(26.2) t = new ElapsedTime('03:47:30') s = new Speed(d, t) expect(s.mph()).isWithin(0.000001, 6.90989010989011) expect(s.kph()).isWithin(0.000001, 11.120390189010989) expect(s.yph()).isWithin(0.000001, 12161.4065934066) expect(s.seconds_per_mile()).isWithin(0.000001, 520.992366412214) expect(s.pace_per_mile()).toBe('8:40.99') it 'projected_time using a simple linear formula', -> d1 = new Distance(10.0) t = new ElapsedTime('1:30:00') s = new Speed(d1, t) expect(s.seconds_per_mile()).isWithin(0.000001, 540) expect(s.pace_per_mile()).toBe('9:00') d2 = new Distance(20.0) hhmmss = s.projected_time(d2, 'simple') expect(hhmmss).toBe('03:00:00') it 'projected_time using the exponential riegel formula', -> d1 = new Distance(10.0) t = new ElapsedTime('1:30:00') s = new Speed(d1, t) expect(s.seconds_per_mile()).isWithin(0.000001, 540) expect(s.pace_per_mile()).toBe('9:00') d2 = new Distance(20.0) hhmmss = s.projected_time(d2, 'riegel') expect(hhmmss).toBe('03:07:38') it 'should calculate an age_graded Speed', -> d = new Distance(26.2) t = new ElapsedTime('3:47:30') s1 = new Speed(d, t) a1 = new Age(42.5) a2 = new Age(43.5) a3 = new Age(57.1) expect(s1.mph()).isWithin(0.000001, 6.90989010989011) s2 = s1.age_graded(a1, a2) s3 = s1.age_graded(a1, a3) expect(s2.mph()).isWithin(0.000001, 6.870961151524531) expect(s3.mph()).isWithin(0.000001, 6.341527317752669)
131977
# Copyright 2015, <NAME> <<EMAIL>> describe 'Speed', -> it 'calculates a 2-mile walk, with round numbers', -> d = new Distance(2.0) t = new ElapsedTime('30:00') s = new Speed(d, t) expect(s.mph()).isWithin(0.000001, 4) expect(s.kph()).isWithin(0.000001, 6.437376) expect(s.yph()).isWithin(0.000001, 7040) expect(s.seconds_per_mile()).isWithin(0.000001, 900) expect(s.pace_per_mile()).toBe('15:00') it 'calculates a marathon, with fractional pace_per_mile', -> d = new Distance(26.2) t = new ElapsedTime('03:47:30') s = new Speed(d, t) expect(s.mph()).isWithin(0.000001, 6.90989010989011) expect(s.kph()).isWithin(0.000001, 11.120390189010989) expect(s.yph()).isWithin(0.000001, 12161.4065934066) expect(s.seconds_per_mile()).isWithin(0.000001, 520.992366412214) expect(s.pace_per_mile()).toBe('8:40.99') it 'projected_time using a simple linear formula', -> d1 = new Distance(10.0) t = new ElapsedTime('1:30:00') s = new Speed(d1, t) expect(s.seconds_per_mile()).isWithin(0.000001, 540) expect(s.pace_per_mile()).toBe('9:00') d2 = new Distance(20.0) hhmmss = s.projected_time(d2, 'simple') expect(hhmmss).toBe('03:00:00') it 'projected_time using the exponential riegel formula', -> d1 = new Distance(10.0) t = new ElapsedTime('1:30:00') s = new Speed(d1, t) expect(s.seconds_per_mile()).isWithin(0.000001, 540) expect(s.pace_per_mile()).toBe('9:00') d2 = new Distance(20.0) hhmmss = s.projected_time(d2, 'riegel') expect(hhmmss).toBe('03:07:38') it 'should calculate an age_graded Speed', -> d = new Distance(26.2) t = new ElapsedTime('3:47:30') s1 = new Speed(d, t) a1 = new Age(42.5) a2 = new Age(43.5) a3 = new Age(57.1) expect(s1.mph()).isWithin(0.000001, 6.90989010989011) s2 = s1.age_graded(a1, a2) s3 = s1.age_graded(a1, a3) expect(s2.mph()).isWithin(0.000001, 6.870961151524531) expect(s3.mph()).isWithin(0.000001, 6.341527317752669)
true
# Copyright 2015, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> describe 'Speed', -> it 'calculates a 2-mile walk, with round numbers', -> d = new Distance(2.0) t = new ElapsedTime('30:00') s = new Speed(d, t) expect(s.mph()).isWithin(0.000001, 4) expect(s.kph()).isWithin(0.000001, 6.437376) expect(s.yph()).isWithin(0.000001, 7040) expect(s.seconds_per_mile()).isWithin(0.000001, 900) expect(s.pace_per_mile()).toBe('15:00') it 'calculates a marathon, with fractional pace_per_mile', -> d = new Distance(26.2) t = new ElapsedTime('03:47:30') s = new Speed(d, t) expect(s.mph()).isWithin(0.000001, 6.90989010989011) expect(s.kph()).isWithin(0.000001, 11.120390189010989) expect(s.yph()).isWithin(0.000001, 12161.4065934066) expect(s.seconds_per_mile()).isWithin(0.000001, 520.992366412214) expect(s.pace_per_mile()).toBe('8:40.99') it 'projected_time using a simple linear formula', -> d1 = new Distance(10.0) t = new ElapsedTime('1:30:00') s = new Speed(d1, t) expect(s.seconds_per_mile()).isWithin(0.000001, 540) expect(s.pace_per_mile()).toBe('9:00') d2 = new Distance(20.0) hhmmss = s.projected_time(d2, 'simple') expect(hhmmss).toBe('03:00:00') it 'projected_time using the exponential riegel formula', -> d1 = new Distance(10.0) t = new ElapsedTime('1:30:00') s = new Speed(d1, t) expect(s.seconds_per_mile()).isWithin(0.000001, 540) expect(s.pace_per_mile()).toBe('9:00') d2 = new Distance(20.0) hhmmss = s.projected_time(d2, 'riegel') expect(hhmmss).toBe('03:07:38') it 'should calculate an age_graded Speed', -> d = new Distance(26.2) t = new ElapsedTime('3:47:30') s1 = new Speed(d, t) a1 = new Age(42.5) a2 = new Age(43.5) a3 = new Age(57.1) expect(s1.mph()).isWithin(0.000001, 6.90989010989011) s2 = s1.age_graded(a1, a2) s3 = s1.age_graded(a1, a3) expect(s2.mph()).isWithin(0.000001, 6.870961151524531) expect(s3.mph()).isWithin(0.000001, 6.341527317752669)
[ { "context": " serviceName: 'travis-ci'\n repoToken: 'EPwLMGsbXbKvvVk9hGRSTK0CY2ueNZsEr'\n test:\n options:\n reporter:", "end": 676, "score": 0.9892741441726685, "start": 643, "tag": "KEY", "value": "EPwLMGsbXbKvvVk9hGRSTK0CY2ueNZsEr" } ]
Gruntfile.coffee
chikamichi/jquery.circular
0
module.exports = (grunt) -> grunt.loadNpmTasks('grunt-contrib-coffee') grunt.loadNpmTasks('grunt-contrib-jshint') grunt.loadNpmTasks('grunt-contrib-watch') grunt.loadNpmTasks('grunt-mocha-cov') grunt.initConfig pkg: grunt.file.readJSON('package.json') jshint: options: jshintrc: '.jshintrc' files: ['jquery.circular.js'] coffee: compile: files: 'jquery.circular.js': 'src/circular.coffee' 'build/circular.js': 'src/circular.coffee' mochacov: coverage: options: coveralls: serviceName: 'travis-ci' repoToken: 'EPwLMGsbXbKvvVk9hGRSTK0CY2ueNZsEr' test: options: reporter: 'spec' dots: options: reporter: 'dot' options: compilers: ['coffee:coffee-script'] files: ['test/**/*.coffee'] watch: files: ['src/circular.coffee', 'test/**/*.coffee'] tasks: ['check', 'test'] grunt.registerTask('check', ['coffee', 'jshint']) grunt.registerTask('test', 'mochacov:test') grunt.registerTask('default', 'watch') grunt.registerTask('travis', ['check', 'mochacov:dots'])
43207
module.exports = (grunt) -> grunt.loadNpmTasks('grunt-contrib-coffee') grunt.loadNpmTasks('grunt-contrib-jshint') grunt.loadNpmTasks('grunt-contrib-watch') grunt.loadNpmTasks('grunt-mocha-cov') grunt.initConfig pkg: grunt.file.readJSON('package.json') jshint: options: jshintrc: '.jshintrc' files: ['jquery.circular.js'] coffee: compile: files: 'jquery.circular.js': 'src/circular.coffee' 'build/circular.js': 'src/circular.coffee' mochacov: coverage: options: coveralls: serviceName: 'travis-ci' repoToken: '<KEY>' test: options: reporter: 'spec' dots: options: reporter: 'dot' options: compilers: ['coffee:coffee-script'] files: ['test/**/*.coffee'] watch: files: ['src/circular.coffee', 'test/**/*.coffee'] tasks: ['check', 'test'] grunt.registerTask('check', ['coffee', 'jshint']) grunt.registerTask('test', 'mochacov:test') grunt.registerTask('default', 'watch') grunt.registerTask('travis', ['check', 'mochacov:dots'])
true
module.exports = (grunt) -> grunt.loadNpmTasks('grunt-contrib-coffee') grunt.loadNpmTasks('grunt-contrib-jshint') grunt.loadNpmTasks('grunt-contrib-watch') grunt.loadNpmTasks('grunt-mocha-cov') grunt.initConfig pkg: grunt.file.readJSON('package.json') jshint: options: jshintrc: '.jshintrc' files: ['jquery.circular.js'] coffee: compile: files: 'jquery.circular.js': 'src/circular.coffee' 'build/circular.js': 'src/circular.coffee' mochacov: coverage: options: coveralls: serviceName: 'travis-ci' repoToken: 'PI:KEY:<KEY>END_PI' test: options: reporter: 'spec' dots: options: reporter: 'dot' options: compilers: ['coffee:coffee-script'] files: ['test/**/*.coffee'] watch: files: ['src/circular.coffee', 'test/**/*.coffee'] tasks: ['check', 'test'] grunt.registerTask('check', ['coffee', 'jshint']) grunt.registerTask('test', 'mochacov:test') grunt.registerTask('default', 'watch') grunt.registerTask('travis', ['check', 'mochacov:dots'])
[ { "context": "# Copyright Vladimir Andreev\n\n# Exported objects\n\nexports.Client = require('./", "end": 28, "score": 0.9998622536659241, "start": 12, "tag": "NAME", "value": "Vladimir Andreev" } ]
src/index.coffee
tucan/yamoney
5
# Copyright Vladimir Andreev # Exported objects exports.Client = require('./client')
115118
# Copyright <NAME> # Exported objects exports.Client = require('./client')
true
# Copyright PI:NAME:<NAME>END_PI # Exported objects exports.Client = require('./client')
[ { "context": "ire 'lodash'\nBintray = require '../'\n\nusername = 'username'\napikey = 'apikey'\norganization = 'organization'\n", "end": 92, "score": 0.9994993209838867, "start": 84, "tag": "USERNAME", "value": "username" }, { "context": " = require '../'\n\nusername = 'username'\na...
test/uploadsSpec.coffee
h2non/node-bintray
4
assert = require 'assert' _ = require 'lodash' Bintray = require '../' username = 'username' apikey = 'apikey' organization = 'organization' repository = 'repo' apiBaseUrl = 'http://localhost:8882' client = new Bintray { username: username, apikey: apikey, organization: organization, repository: repository, baseUrl: apiBaseUrl } describe 'Uploads:', -> it 'should register a new package properly', (done) -> client.createPackage({ name: 'my-package' desc: 'My package description' labels: [ 'JavaScript', 'Package' ] licenses: [ 'MIT' ] }) .then (response) -> try assert.equal response.code, 201, 'HTTP status should be 201' done() catch e done e , (error) -> done new Error error.data it 'should creates a new package version', (done) -> client.createPackageVersion('my-package', { name: '1.1.5', release_notes: 'This new version fixes...', release_url: 'https://github.com/user/my-package/RB-1.1.5/README.md', releades: 'ISO8601 (yyyy-MM-ddTHH:mm:ss.SSSZ)' }) .then (response) -> try assert.equal response.code, 201, 'HTTP status should be 201' done() catch e done e , (error) -> done new Error error.data it 'should upload the file properly', (done) -> client.uploadPackage('my-package', '1.1.5', "#{__dirname}/fixtures/my-package.gz", 'packages/my-package/') .then (response) -> try assert.equal response.code, 201, 'HTTP status code should be 201' done() catch e done e , (error) -> done new Error error.data it 'should publish the file properly', (done) -> client.publishPackage('my-package', '1.1.5', true) .then (response) -> try assert.equal response.code, 200, 'HTTP status should be 200' assert.equal response.data.files, 39, 'Discarded files should be 39' done() catch e done e , (error) -> done new Error error.data it 'should remove the package', (done) -> client.deletePackage('my-package') .then (response) -> try assert.equal response.code, 200 done() catch e done e , (error) -> done new Error error.data
26834
assert = require 'assert' _ = require 'lodash' Bintray = require '../' username = 'username' apikey = '<KEY>' organization = 'organization' repository = 'repo' apiBaseUrl = 'http://localhost:8882' client = new Bintray { username: username, apikey: apikey, organization: organization, repository: repository, baseUrl: apiBaseUrl } describe 'Uploads:', -> it 'should register a new package properly', (done) -> client.createPackage({ name: 'my-package' desc: 'My package description' labels: [ 'JavaScript', 'Package' ] licenses: [ 'MIT' ] }) .then (response) -> try assert.equal response.code, 201, 'HTTP status should be 201' done() catch e done e , (error) -> done new Error error.data it 'should creates a new package version', (done) -> client.createPackageVersion('my-package', { name: '1.1.5', release_notes: 'This new version fixes...', release_url: 'https://github.com/user/my-package/RB-1.1.5/README.md', releades: 'ISO8601 (yyyy-MM-ddTHH:mm:ss.SSSZ)' }) .then (response) -> try assert.equal response.code, 201, 'HTTP status should be 201' done() catch e done e , (error) -> done new Error error.data it 'should upload the file properly', (done) -> client.uploadPackage('my-package', '1.1.5', "#{__dirname}/fixtures/my-package.gz", 'packages/my-package/') .then (response) -> try assert.equal response.code, 201, 'HTTP status code should be 201' done() catch e done e , (error) -> done new Error error.data it 'should publish the file properly', (done) -> client.publishPackage('my-package', '1.1.5', true) .then (response) -> try assert.equal response.code, 200, 'HTTP status should be 200' assert.equal response.data.files, 39, 'Discarded files should be 39' done() catch e done e , (error) -> done new Error error.data it 'should remove the package', (done) -> client.deletePackage('my-package') .then (response) -> try assert.equal response.code, 200 done() catch e done e , (error) -> done new Error error.data
true
assert = require 'assert' _ = require 'lodash' Bintray = require '../' username = 'username' apikey = 'PI:KEY:<KEY>END_PI' organization = 'organization' repository = 'repo' apiBaseUrl = 'http://localhost:8882' client = new Bintray { username: username, apikey: apikey, organization: organization, repository: repository, baseUrl: apiBaseUrl } describe 'Uploads:', -> it 'should register a new package properly', (done) -> client.createPackage({ name: 'my-package' desc: 'My package description' labels: [ 'JavaScript', 'Package' ] licenses: [ 'MIT' ] }) .then (response) -> try assert.equal response.code, 201, 'HTTP status should be 201' done() catch e done e , (error) -> done new Error error.data it 'should creates a new package version', (done) -> client.createPackageVersion('my-package', { name: '1.1.5', release_notes: 'This new version fixes...', release_url: 'https://github.com/user/my-package/RB-1.1.5/README.md', releades: 'ISO8601 (yyyy-MM-ddTHH:mm:ss.SSSZ)' }) .then (response) -> try assert.equal response.code, 201, 'HTTP status should be 201' done() catch e done e , (error) -> done new Error error.data it 'should upload the file properly', (done) -> client.uploadPackage('my-package', '1.1.5', "#{__dirname}/fixtures/my-package.gz", 'packages/my-package/') .then (response) -> try assert.equal response.code, 201, 'HTTP status code should be 201' done() catch e done e , (error) -> done new Error error.data it 'should publish the file properly', (done) -> client.publishPackage('my-package', '1.1.5', true) .then (response) -> try assert.equal response.code, 200, 'HTTP status should be 200' assert.equal response.data.files, 39, 'Discarded files should be 39' done() catch e done e , (error) -> done new Error error.data it 'should remove the package', (done) -> client.deletePackage('my-package') .then (response) -> try assert.equal response.code, 200 done() catch e done e , (error) -> done new Error error.data
[ { "context": "\n{merge} = require 'mixme'\nnikita = require '@nikitajs/core'\n{tags, ssh, scratch} = require '../test'\nth", "end": 54, "score": 0.7640132904052734, "start": 49, "tag": "USERNAME", "value": "itajs" }, { "context": "tags.ipa\n\nipa =\n principal: 'admin'\n password: ...
packages/ipa/test/group/index.coffee
chibanemourad/node-nikita
0
{merge} = require 'mixme' nikita = require '@nikitajs/core' {tags, ssh, scratch} = require '../test' they = require('ssh2-they').configure ssh... return unless tags.ipa ipa = principal: 'admin' password: 'admin_pw' referer: 'https://ipa.nikita/ipa' url: 'https://ipa.nikita/ipa/session/json' describe 'ipa.group', -> they 'create a group', ({ssh}) -> nikita ssh: ssh .ipa.group.del ipa, cn: 'group_add' .ipa.group ipa, cn: 'group_add' , (err, {status}) -> status.should.be.true() unless err .ipa.group ipa, cn: 'group_add' , (err, {status}) -> status.should.be.false() unless err .promise() they 'print result such as gidnumber', ({ssh}) -> nikita ssh: ssh .ipa.group.del ipa, cn: 'group_add' .ipa.group ipa, cn: 'group_add' , (err, {status, result}) -> status.should.be.true() unless err result.gidnumber.length.should.eql 1 result = merge result, ipauniqueid: null, gidnumber: null result.should.eql objectclass: [ 'top' 'groupofnames' 'nestedgroup' 'ipausergroup' 'ipaobject' 'posixgroup' ] dn: 'cn=group_add,cn=groups,cn=accounts,dc=nikita' gidnumber: null cn: [ 'group_add' ] ipauniqueid: null .promise() they 'print result even if no modification is performed', ({ssh}) -> nikita ssh: ssh .ipa.group.del ipa, cn: 'group_add' .ipa.group ipa, cn: 'group_add' .ipa.group ipa, cn: 'group_add' , (err, {status, result}) -> status.should.be.false() unless err result.gidnumber.length.should.eql 1 result = merge result, ipauniqueid: null, gidnumber: null result.should.eql dn: 'cn=group_add,cn=groups,cn=accounts,dc=nikita' gidnumber: null cn: [ 'group_add' ] ipauniqueid: null .promise()
74495
{merge} = require 'mixme' nikita = require '@nikitajs/core' {tags, ssh, scratch} = require '../test' they = require('ssh2-they').configure ssh... return unless tags.ipa ipa = principal: 'admin' password: '<PASSWORD>' referer: 'https://ipa.nikita/ipa' url: 'https://ipa.nikita/ipa/session/json' describe 'ipa.group', -> they 'create a group', ({ssh}) -> nikita ssh: ssh .ipa.group.del ipa, cn: 'group_add' .ipa.group ipa, cn: 'group_add' , (err, {status}) -> status.should.be.true() unless err .ipa.group ipa, cn: 'group_add' , (err, {status}) -> status.should.be.false() unless err .promise() they 'print result such as gidnumber', ({ssh}) -> nikita ssh: ssh .ipa.group.del ipa, cn: 'group_add' .ipa.group ipa, cn: 'group_add' , (err, {status, result}) -> status.should.be.true() unless err result.gidnumber.length.should.eql 1 result = merge result, ipauniqueid: null, gidnumber: null result.should.eql objectclass: [ 'top' 'groupofnames' 'nestedgroup' 'ipausergroup' 'ipaobject' 'posixgroup' ] dn: 'cn=group_add,cn=groups,cn=accounts,dc=nikita' gidnumber: null cn: [ 'group_add' ] ipauniqueid: null .promise() they 'print result even if no modification is performed', ({ssh}) -> nikita ssh: ssh .ipa.group.del ipa, cn: 'group_add' .ipa.group ipa, cn: 'group_add' .ipa.group ipa, cn: 'group_add' , (err, {status, result}) -> status.should.be.false() unless err result.gidnumber.length.should.eql 1 result = merge result, ipauniqueid: null, gidnumber: null result.should.eql dn: 'cn=group_add,cn=groups,cn=accounts,dc=nikita' gidnumber: null cn: [ 'group_add' ] ipauniqueid: null .promise()
true
{merge} = require 'mixme' nikita = require '@nikitajs/core' {tags, ssh, scratch} = require '../test' they = require('ssh2-they').configure ssh... return unless tags.ipa ipa = principal: 'admin' password: 'PI:PASSWORD:<PASSWORD>END_PI' referer: 'https://ipa.nikita/ipa' url: 'https://ipa.nikita/ipa/session/json' describe 'ipa.group', -> they 'create a group', ({ssh}) -> nikita ssh: ssh .ipa.group.del ipa, cn: 'group_add' .ipa.group ipa, cn: 'group_add' , (err, {status}) -> status.should.be.true() unless err .ipa.group ipa, cn: 'group_add' , (err, {status}) -> status.should.be.false() unless err .promise() they 'print result such as gidnumber', ({ssh}) -> nikita ssh: ssh .ipa.group.del ipa, cn: 'group_add' .ipa.group ipa, cn: 'group_add' , (err, {status, result}) -> status.should.be.true() unless err result.gidnumber.length.should.eql 1 result = merge result, ipauniqueid: null, gidnumber: null result.should.eql objectclass: [ 'top' 'groupofnames' 'nestedgroup' 'ipausergroup' 'ipaobject' 'posixgroup' ] dn: 'cn=group_add,cn=groups,cn=accounts,dc=nikita' gidnumber: null cn: [ 'group_add' ] ipauniqueid: null .promise() they 'print result even if no modification is performed', ({ssh}) -> nikita ssh: ssh .ipa.group.del ipa, cn: 'group_add' .ipa.group ipa, cn: 'group_add' .ipa.group ipa, cn: 'group_add' , (err, {status, result}) -> status.should.be.false() unless err result.gidnumber.length.should.eql 1 result = merge result, ipauniqueid: null, gidnumber: null result.should.eql dn: 'cn=group_add,cn=groups,cn=accounts,dc=nikita' gidnumber: null cn: [ 'group_add' ] ipauniqueid: null .promise()
[ { "context": "_id}\"\n\t\t\tauth: {user: settings.apis.v1.user, pass: settings.apis.v1.pass }\n\t\t}, (err, res, body) ->\n\t\t\tif err?\n\t\t\t\tlogger.", "end": 4623, "score": 0.7563191652297974, "start": 4602, "tag": "PASSWORD", "value": "settings.apis.v1.pass" } ]
app/coffee/Features/Exports/ExportsHandler.coffee
shyoshyo/web-sharelatex
1
ProjectGetter = require('../Project/ProjectGetter') ProjectHistoryHandler = require('../Project/ProjectHistoryHandler') ProjectLocator = require('../Project/ProjectLocator') ProjectRootDocManager = require('../Project/ProjectRootDocManager') UserGetter = require('../User/UserGetter') logger = require('logger-sharelatex') settings = require 'settings-sharelatex' async = require 'async' request = require 'request' request = request.defaults() settings = require 'settings-sharelatex' module.exports = ExportsHandler = self = exportProject: (export_params, callback=(error, export_data) ->) -> self._buildExport export_params, (err, export_data) -> return callback(err) if err? self._requestExport export_data, (err, export_v1_id) -> return callback(err) if err? export_data.v1_id = export_v1_id # TODO: possibly store the export data in Mongo callback null, export_data _buildExport: (export_params, callback=(err, export_data) ->) -> {project_id, user_id, brand_variation_id, title, description, author, license, show_source} = export_params jobs = project: (cb) -> ProjectGetter.getProject project_id, cb # TODO: when we update async, signature will change from (cb, results) to (results, cb) rootDoc: [ 'project', (cb, results) -> ProjectRootDocManager.ensureRootDocumentIsValid project_id, (error) -> return callback(error) if error? ProjectLocator.findRootDoc {project: results.project, project_id: project_id}, cb ] user: (cb) -> UserGetter.getUser user_id, {first_name: 1, last_name: 1, email: 1, overleaf: 1}, cb historyVersion: (cb) -> ProjectHistoryHandler.ensureHistoryExistsForProject project_id, (error) -> return callback(error) if error? self._requestVersion project_id, cb async.auto jobs, (err, results) -> if err? logger.err err:err, project_id:project_id, user_id:user_id, brand_variation_id:brand_variation_id, "error building project export" return callback(err) {project, rootDoc, user, historyVersion} = results if !rootDoc[1]? err = new Error("cannot export project without root doc") logger.err err:err, project_id: project_id return callback(err) if export_params.first_name && export_params.last_name user.first_name = export_params.first_name user.last_name = export_params.last_name export_data = project: id: project_id rootDocPath: rootDoc[1]?.fileSystem historyId: project.overleaf?.history?.id historyVersion: historyVersion v1ProjectId: project.overleaf?.id metadata: compiler: project.compiler imageName: project.imageName title: title description: description author: author license: license showSource: show_source user: id: user_id firstName: user.first_name lastName: user.last_name email: user.email orcidId: null # until v2 gets ORCID v1UserId: user.overleaf?.id destination: brandVariationId: brand_variation_id options: callbackUrl: null # for now, until we want v1 to call us back callback null, export_data _requestExport: (export_data, callback=(err, export_v1_id) ->) -> request.post { url: "#{settings.apis.v1.url}/api/v1/sharelatex/exports" auth: {user: settings.apis.v1.user, pass: settings.apis.v1.pass } json: export_data }, (err, res, body) -> if err? logger.err err:err, export:export_data, "error making request to v1 export" callback err else if 200 <= res.statusCode < 300 callback null, body.exportId else logger.err export:export_data, "v1 export returned failure; forwarding: #{body}" # pass the v1 error along for the publish modal to handle callback {forwardResponse: body} _requestVersion: (project_id, callback=(err, export_v1_id) ->) -> request.get { url: "#{settings.apis.project_history.url}/project/#{project_id}/version" json: true }, (err, res, body) -> if err? logger.err err:err, project_id:project_id, "error making request to project history" callback err else if res.statusCode >= 200 and res.statusCode < 300 callback null, body.version else err = new Error("project history version returned a failure status code: #{res.statusCode}") logger.err err:err, project_id:project_id, "project history version returned failure status code: #{res.statusCode}" callback err fetchExport: (export_id, callback=(err, export_json) ->) -> request.get { url: "#{settings.apis.v1.url}/api/v1/sharelatex/exports/#{export_id}" auth: {user: settings.apis.v1.user, pass: settings.apis.v1.pass } }, (err, res, body) -> if err? logger.err err:err, export:export_id, "error making request to v1 export" callback err else if 200 <= res.statusCode < 300 callback null, body else err = new Error("v1 export returned a failure status code: #{res.statusCode}") logger.err err:err, export:export_id, "v1 export returned failure status code: #{res.statusCode}" callback err fetchDownload: (export_id, type, callback=(err, file_url) ->) -> request.get { url: "#{settings.apis.v1.url}/api/v1/sharelatex/exports/#{export_id}/#{type}_url" auth: {user: settings.apis.v1.user, pass: settings.apis.v1.pass } }, (err, res, body) -> if err? logger.err err:err, export:export_id, "error making request to v1 export" callback err else if 200 <= res.statusCode < 300 callback null, body else err = new Error("v1 export returned a failure status code: #{res.statusCode}") logger.err err:err, export:export_id, "v1 export zip fetch returned failure status code: #{res.statusCode}" callback err
118787
ProjectGetter = require('../Project/ProjectGetter') ProjectHistoryHandler = require('../Project/ProjectHistoryHandler') ProjectLocator = require('../Project/ProjectLocator') ProjectRootDocManager = require('../Project/ProjectRootDocManager') UserGetter = require('../User/UserGetter') logger = require('logger-sharelatex') settings = require 'settings-sharelatex' async = require 'async' request = require 'request' request = request.defaults() settings = require 'settings-sharelatex' module.exports = ExportsHandler = self = exportProject: (export_params, callback=(error, export_data) ->) -> self._buildExport export_params, (err, export_data) -> return callback(err) if err? self._requestExport export_data, (err, export_v1_id) -> return callback(err) if err? export_data.v1_id = export_v1_id # TODO: possibly store the export data in Mongo callback null, export_data _buildExport: (export_params, callback=(err, export_data) ->) -> {project_id, user_id, brand_variation_id, title, description, author, license, show_source} = export_params jobs = project: (cb) -> ProjectGetter.getProject project_id, cb # TODO: when we update async, signature will change from (cb, results) to (results, cb) rootDoc: [ 'project', (cb, results) -> ProjectRootDocManager.ensureRootDocumentIsValid project_id, (error) -> return callback(error) if error? ProjectLocator.findRootDoc {project: results.project, project_id: project_id}, cb ] user: (cb) -> UserGetter.getUser user_id, {first_name: 1, last_name: 1, email: 1, overleaf: 1}, cb historyVersion: (cb) -> ProjectHistoryHandler.ensureHistoryExistsForProject project_id, (error) -> return callback(error) if error? self._requestVersion project_id, cb async.auto jobs, (err, results) -> if err? logger.err err:err, project_id:project_id, user_id:user_id, brand_variation_id:brand_variation_id, "error building project export" return callback(err) {project, rootDoc, user, historyVersion} = results if !rootDoc[1]? err = new Error("cannot export project without root doc") logger.err err:err, project_id: project_id return callback(err) if export_params.first_name && export_params.last_name user.first_name = export_params.first_name user.last_name = export_params.last_name export_data = project: id: project_id rootDocPath: rootDoc[1]?.fileSystem historyId: project.overleaf?.history?.id historyVersion: historyVersion v1ProjectId: project.overleaf?.id metadata: compiler: project.compiler imageName: project.imageName title: title description: description author: author license: license showSource: show_source user: id: user_id firstName: user.first_name lastName: user.last_name email: user.email orcidId: null # until v2 gets ORCID v1UserId: user.overleaf?.id destination: brandVariationId: brand_variation_id options: callbackUrl: null # for now, until we want v1 to call us back callback null, export_data _requestExport: (export_data, callback=(err, export_v1_id) ->) -> request.post { url: "#{settings.apis.v1.url}/api/v1/sharelatex/exports" auth: {user: settings.apis.v1.user, pass: settings.apis.v1.pass } json: export_data }, (err, res, body) -> if err? logger.err err:err, export:export_data, "error making request to v1 export" callback err else if 200 <= res.statusCode < 300 callback null, body.exportId else logger.err export:export_data, "v1 export returned failure; forwarding: #{body}" # pass the v1 error along for the publish modal to handle callback {forwardResponse: body} _requestVersion: (project_id, callback=(err, export_v1_id) ->) -> request.get { url: "#{settings.apis.project_history.url}/project/#{project_id}/version" json: true }, (err, res, body) -> if err? logger.err err:err, project_id:project_id, "error making request to project history" callback err else if res.statusCode >= 200 and res.statusCode < 300 callback null, body.version else err = new Error("project history version returned a failure status code: #{res.statusCode}") logger.err err:err, project_id:project_id, "project history version returned failure status code: #{res.statusCode}" callback err fetchExport: (export_id, callback=(err, export_json) ->) -> request.get { url: "#{settings.apis.v1.url}/api/v1/sharelatex/exports/#{export_id}" auth: {user: settings.apis.v1.user, pass: <PASSWORD> } }, (err, res, body) -> if err? logger.err err:err, export:export_id, "error making request to v1 export" callback err else if 200 <= res.statusCode < 300 callback null, body else err = new Error("v1 export returned a failure status code: #{res.statusCode}") logger.err err:err, export:export_id, "v1 export returned failure status code: #{res.statusCode}" callback err fetchDownload: (export_id, type, callback=(err, file_url) ->) -> request.get { url: "#{settings.apis.v1.url}/api/v1/sharelatex/exports/#{export_id}/#{type}_url" auth: {user: settings.apis.v1.user, pass: settings.apis.v1.pass } }, (err, res, body) -> if err? logger.err err:err, export:export_id, "error making request to v1 export" callback err else if 200 <= res.statusCode < 300 callback null, body else err = new Error("v1 export returned a failure status code: #{res.statusCode}") logger.err err:err, export:export_id, "v1 export zip fetch returned failure status code: #{res.statusCode}" callback err
true
ProjectGetter = require('../Project/ProjectGetter') ProjectHistoryHandler = require('../Project/ProjectHistoryHandler') ProjectLocator = require('../Project/ProjectLocator') ProjectRootDocManager = require('../Project/ProjectRootDocManager') UserGetter = require('../User/UserGetter') logger = require('logger-sharelatex') settings = require 'settings-sharelatex' async = require 'async' request = require 'request' request = request.defaults() settings = require 'settings-sharelatex' module.exports = ExportsHandler = self = exportProject: (export_params, callback=(error, export_data) ->) -> self._buildExport export_params, (err, export_data) -> return callback(err) if err? self._requestExport export_data, (err, export_v1_id) -> return callback(err) if err? export_data.v1_id = export_v1_id # TODO: possibly store the export data in Mongo callback null, export_data _buildExport: (export_params, callback=(err, export_data) ->) -> {project_id, user_id, brand_variation_id, title, description, author, license, show_source} = export_params jobs = project: (cb) -> ProjectGetter.getProject project_id, cb # TODO: when we update async, signature will change from (cb, results) to (results, cb) rootDoc: [ 'project', (cb, results) -> ProjectRootDocManager.ensureRootDocumentIsValid project_id, (error) -> return callback(error) if error? ProjectLocator.findRootDoc {project: results.project, project_id: project_id}, cb ] user: (cb) -> UserGetter.getUser user_id, {first_name: 1, last_name: 1, email: 1, overleaf: 1}, cb historyVersion: (cb) -> ProjectHistoryHandler.ensureHistoryExistsForProject project_id, (error) -> return callback(error) if error? self._requestVersion project_id, cb async.auto jobs, (err, results) -> if err? logger.err err:err, project_id:project_id, user_id:user_id, brand_variation_id:brand_variation_id, "error building project export" return callback(err) {project, rootDoc, user, historyVersion} = results if !rootDoc[1]? err = new Error("cannot export project without root doc") logger.err err:err, project_id: project_id return callback(err) if export_params.first_name && export_params.last_name user.first_name = export_params.first_name user.last_name = export_params.last_name export_data = project: id: project_id rootDocPath: rootDoc[1]?.fileSystem historyId: project.overleaf?.history?.id historyVersion: historyVersion v1ProjectId: project.overleaf?.id metadata: compiler: project.compiler imageName: project.imageName title: title description: description author: author license: license showSource: show_source user: id: user_id firstName: user.first_name lastName: user.last_name email: user.email orcidId: null # until v2 gets ORCID v1UserId: user.overleaf?.id destination: brandVariationId: brand_variation_id options: callbackUrl: null # for now, until we want v1 to call us back callback null, export_data _requestExport: (export_data, callback=(err, export_v1_id) ->) -> request.post { url: "#{settings.apis.v1.url}/api/v1/sharelatex/exports" auth: {user: settings.apis.v1.user, pass: settings.apis.v1.pass } json: export_data }, (err, res, body) -> if err? logger.err err:err, export:export_data, "error making request to v1 export" callback err else if 200 <= res.statusCode < 300 callback null, body.exportId else logger.err export:export_data, "v1 export returned failure; forwarding: #{body}" # pass the v1 error along for the publish modal to handle callback {forwardResponse: body} _requestVersion: (project_id, callback=(err, export_v1_id) ->) -> request.get { url: "#{settings.apis.project_history.url}/project/#{project_id}/version" json: true }, (err, res, body) -> if err? logger.err err:err, project_id:project_id, "error making request to project history" callback err else if res.statusCode >= 200 and res.statusCode < 300 callback null, body.version else err = new Error("project history version returned a failure status code: #{res.statusCode}") logger.err err:err, project_id:project_id, "project history version returned failure status code: #{res.statusCode}" callback err fetchExport: (export_id, callback=(err, export_json) ->) -> request.get { url: "#{settings.apis.v1.url}/api/v1/sharelatex/exports/#{export_id}" auth: {user: settings.apis.v1.user, pass: PI:PASSWORD:<PASSWORD>END_PI } }, (err, res, body) -> if err? logger.err err:err, export:export_id, "error making request to v1 export" callback err else if 200 <= res.statusCode < 300 callback null, body else err = new Error("v1 export returned a failure status code: #{res.statusCode}") logger.err err:err, export:export_id, "v1 export returned failure status code: #{res.statusCode}" callback err fetchDownload: (export_id, type, callback=(err, file_url) ->) -> request.get { url: "#{settings.apis.v1.url}/api/v1/sharelatex/exports/#{export_id}/#{type}_url" auth: {user: settings.apis.v1.user, pass: settings.apis.v1.pass } }, (err, res, body) -> if err? logger.err err:err, export:export_id, "error making request to v1 export" callback err else if 200 <= res.statusCode < 300 callback null, body else err = new Error("v1 export returned a failure status code: #{res.statusCode}") logger.err err:err, export:export_id, "v1 export zip fetch returned failure status code: #{res.statusCode}" callback err
[ { "context": "module.exports=\n mysql:\n host:'192.168.59.103'\n port:3306\n user:'root'\n password:'root", "end": 49, "score": 0.9997429251670837, "start": 35, "tag": "IP_ADDRESS", "value": "192.168.59.103" }, { "context": ".103'\n port:3306\n user:'root'\n pas...
gulpfile.config.coffee
59naga/sequelize-cheatsheet
2
module.exports= mysql: host:'192.168.59.103' port:3306 user:'root' password:'root' table_name:'edgy_test' charset:'utf8' collate:'utf8_general_ci'
31547
module.exports= mysql: host:'192.168.59.103' port:3306 user:'root' password:'<PASSWORD>' table_name:'edgy_test' charset:'utf8' collate:'utf8_general_ci'
true
module.exports= mysql: host:'192.168.59.103' port:3306 user:'root' password:'PI:PASSWORD:<PASSWORD>END_PI' table_name:'edgy_test' charset:'utf8' collate:'utf8_general_ci'
[ { "context": "# Taken/adapted from deprecated 'wrench' module by Ryan McGrath\ncfs.readdirSyncRecursive = (baseDir) ->\n baseDir", "end": 6071, "score": 0.9995295405387878, "start": 6059, "tag": "NAME", "value": "Ryan McGrath" }, { "context": "# Taken/adapted from deprecated 'wrench...
src/tool/cfs.coffee
joedrago/node-crackers
3
# cracker file system constants = require './constants' fs = require 'fs' path = require 'path' log = require './log' touch = require 'touch' cfs = {} cfs.join = -> result = path.join.apply(null, arguments) # work around stupid lack of symmetry between path.join and split(sep) if arguments.length > 0 and arguments[0] == '' result = "/#{result}" return result cfs.dirExists = (dir) -> if not fs.existsSync(dir) return false stats = fs.statSync(dir) if stats.isDirectory() return true return false cfs.dirTime = (dir) -> dirStats = fs.statSync(dir) return 0 if not dirStats? return Math.floor(dirStats.mtime.getTime() / 1000) cfs.fileExists = (file) -> if not fs.existsSync(file) return false stats = fs.statSync(file) if stats.isFile() return true return false cfs.fileHasBytes = (file) -> if not fs.existsSync(file) return false stats = fs.statSync(file) if stats.isFile() return (stats.size > 0) return false cfs.ensureFileExists = (file) -> if fs.existsSync(file) return touch.sync(file) return cfs.insideDir = (filename, dir) -> if filename.indexOf(dir) == 0 return true return false cfs.findArchive = (dir, comic) -> basename = path.join(dir, comic) if cfs.fileExists("#{basename}.cbr") return "#{comic}.cbr" if cfs.fileExists("#{basename}.cbt") return "#{comic}.cbt" if cfs.fileExists("#{basename}.cbz") return "#{comic}.cbz" return false cfs.findParentContainingFilename = (startDir, filename) -> startDir = path.resolve('.', startDir) dirPieces = startDir.split(path.sep) loop if not dirPieces.length return false testPieces = dirPieces.slice() testPieces.push(filename) testPath = cfs.join.apply(null, testPieces) found = cfs.fileExists(testPath) # log.verbose "checking path #{testPath} (#{found})" if found return cfs.join.apply(null, dirPieces) dirPieces.pop() return false cfs.listDir = (dir) -> return cfs.readdirSyncRecursive(dir) cfs.listImages = (dir) -> list = cfs.readdirSyncRecursive(dir) images = (path.resolve(dir, file) for file in list when file.match(/\.(png|jpg|jpeg|webp|gif)$/i)) return images.sort() cfs.gatherComics = (subDir, rootDir) -> subDir = subDir.replace("#{path.sep}$", "") if not rootDir? rootDir = subDir rootDir = rootDir.replace("#{path.sep}$", "") list = cfs.readdirSyncRecursive(subDir) comicDirs = (path.resolve(subDir, file).replace(/[\/\\]images$/, "") for file in list when file.match(/images$/i)) comics = [] for dir in comicDirs relativeDir = dir.substr(rootDir.length + 1) relativeDir = relativeDir.replace(/\\/g, "/") metadata = cfs.readMetadata(dir) if metadata metadata.dir = dir metadata.relativeDir = relativeDir comics.push metadata return comics cfs.gatherMetadata = (dir) -> mdList = [] fileList = fs.readdirSync(dir).sort() for file in fileList resolvedPath = path.resolve(dir, file) metadata = cfs.readMetadata(resolvedPath) continue if not metadata metadata.path = file mdList.push metadata mdList.sort (a, b) -> #if a.type == b.type if a.path == b.path return 0 if a.path > b.path return 1 return -1 #if a.type > b.type # return 1 #return -1 return mdList cfs.readMetadata = (dir) -> metaFilename = cfs.join(dir, constants.META_FILENAME) if not fs.existsSync(metaFilename) return false rawText = fs.readFileSync(metaFilename) if not rawText return false try metadata = JSON.parse(rawText) catch metadata = false return metadata cfs.touchRoot = (dir) -> rootFilename = cfs.join(dir, constants.ROOT_FILENAME) return if cfs.fileHasBytes(rootFilename) rootinfo = { title: constants.DEFAULT_TITLE progress: "" } json = JSON.stringify(rootinfo, null, 2) fs.writeFileSync rootFilename, json cfs.getRootTitle = (dir) -> rootFilename = cfs.join(dir, constants.ROOT_FILENAME) if cfs.fileHasBytes(rootFilename) try rawJSON = fs.readFileSync(rootFilename) data = JSON.parse(rawJSON) if data.title return data.title catch return constants.DEFAULT_TITLE cfs.getProgressEndpoint = (dir) -> rootFilename = cfs.join(dir, constants.ROOT_FILENAME) if cfs.fileHasBytes(rootFilename) try rawJSON = fs.readFileSync(rootFilename) data = JSON.parse(rawJSON) if data.progress return data.progress catch return "" cfs.writeMetadata = (dir, metadata) -> metaFilename = cfs.join(dir, constants.META_FILENAME) json = JSON.stringify(metadata, null, 2) # log.verbose "writeMetadata (#{dir}): #{JSON.stringify(metadata, null, 2)}" fs.writeFileSync metaFilename, json cfs.removeMetadata = (dir, metadata) -> metaFilename = cfs.join(dir, constants.META_FILENAME) # log.verbose "removeMetadata (#{dir})" fs.unlinkSync metaFilename cfs.copyFile = (src, dst) -> log.verbose "copyFile #{src} -> #{dst}" fs.writeFileSync(dst, fs.readFileSync(src)); cfs.prepareDir = (dir) -> # Ensure the directory exists, and is a directory if not fs.existsSync(dir) fs.mkdirSync(dir) if not fs.existsSync(dir) log.error "Cannot create directory #{dir}, mkdir failed" return false stats = fs.statSync(dir) if not stats.isDirectory() log.error "Cannot create directory #{dir}, file exists (not a dir)" return false return true cfs.prepareComicDir = (dir) -> if not cfs.prepareDir(dir) return false log.verbose "Comic directory prepared: #{dir}" return true cfs.cleanupDir = (dir) -> if fs.existsSync(dir) log.verbose "Cleaning up #{dir}" cfs.rmdirSyncRecursive(dir, true) return cfs.newer = (amINewer, thanThisFile) -> if not fs.existsSync(amINewer) return true if not fs.existsSync(thanThisFile) return true amINewerStats = fs.statSync(amINewer) thanThisFileStats = fs.statSync(thanThisFile) return amINewerStats.mtime > thanThisFileStats.mtime # Taken/adapted from deprecated 'wrench' module by Ryan McGrath cfs.readdirSyncRecursive = (baseDir) -> baseDir = baseDir.replace(/\/$/, '') readdirSyncRecursive = (baseDir) -> files = [] isDir = (fname) -> if fs.existsSync(path.join(baseDir, fname)) return fs.statSync( path.join(baseDir, fname) ).isDirectory() return false prependBaseDir = (fname) -> return path.join(baseDir, fname) curFiles = fs.readdirSync(baseDir) nextDirs = curFiles.filter(isDir) curFiles = curFiles.map(prependBaseDir) files = files.concat(curFiles) while nextDirs.length > 0 files = files.concat( readdirSyncRecursive(path.join(baseDir, nextDirs.shift())) ) return files # convert absolute paths to relative fileList = readdirSyncRecursive(baseDir).map (val) -> return path.relative(baseDir, val) return fileList # Taken/adapted from deprecated 'wrench' module by Ryan McGrath cfs.rmdirSyncRecursive = (dir, failSilent) -> isWindows = !!process.platform.match(/^win/) try files = fs.readdirSync(dir) catch err return if failSilent throw new Error(err.message) # Loop through and delete everything in the sub-tree after checking it for file in files file = path.join(dir, file) currFile = fs.lstatSync(file) if currFile.isDirectory() # Recursive function back to the beginning cfs.rmdirSyncRecursive(file) else if currFile.isSymbolicLink() # Unlink symlinks if isWindows fs.chmodSync(file, 666) # Windows needs this unless joyent/node#3006 is resolved.. fs.unlinkSync(file) else # Assume it's a file - perhaps a try/catch belongs here? if isWindows fs.chmodSync(file, 666) # Windows needs this unless joyent/node#3006 is resolved.. fs.unlinkSync(file) # Now that we know everything in the sub-tree has been deleted, we can delete the main directory. Huzzah for the shopkeep. return fs.rmdirSync(dir) # Taken/adapted from deprecated 'wrench' module by Ryan McGrath cfs.mkdirSyncRecursive = (dir, mode) -> dir = path.normalize(dir) try fs.mkdirSync(dir, mode) catch err if err.code == "ENOENT" slashIdx = dir.lastIndexOf(path.sep) if slashIdx > 0 parentDir = dir.substring(0, slashIdx) cfs.mkdirSyncRecursive(parentDir, mode) cfs.mkdirSyncRecursive(dir, mode) else throw err else if err.code == "EEXIST" return else throw err return # Taken/adapted from deprecated 'wrench' module by Ryan McGrath cfs.chmodSyncRecursive = (sourceDir, filemode) -> files = fs.readdirSync(sourceDir) for file in files currFile = fs.lstatSync(path.join(sourceDir, file)) if currFile.isDirectory() # ...and recursion this thing right on back. cfs.chmodSyncRecursive(path.join(sourceDir, file), filemode) else # At this point, we've hit a file actually worth copying... so copy it on over. fs.chmodSync(path.join(sourceDir, file), filemode) # Finally, chmod the parent directory return fs.chmodSync(sourceDir, filemode) module.exports = cfs
170518
# cracker file system constants = require './constants' fs = require 'fs' path = require 'path' log = require './log' touch = require 'touch' cfs = {} cfs.join = -> result = path.join.apply(null, arguments) # work around stupid lack of symmetry between path.join and split(sep) if arguments.length > 0 and arguments[0] == '' result = "/#{result}" return result cfs.dirExists = (dir) -> if not fs.existsSync(dir) return false stats = fs.statSync(dir) if stats.isDirectory() return true return false cfs.dirTime = (dir) -> dirStats = fs.statSync(dir) return 0 if not dirStats? return Math.floor(dirStats.mtime.getTime() / 1000) cfs.fileExists = (file) -> if not fs.existsSync(file) return false stats = fs.statSync(file) if stats.isFile() return true return false cfs.fileHasBytes = (file) -> if not fs.existsSync(file) return false stats = fs.statSync(file) if stats.isFile() return (stats.size > 0) return false cfs.ensureFileExists = (file) -> if fs.existsSync(file) return touch.sync(file) return cfs.insideDir = (filename, dir) -> if filename.indexOf(dir) == 0 return true return false cfs.findArchive = (dir, comic) -> basename = path.join(dir, comic) if cfs.fileExists("#{basename}.cbr") return "#{comic}.cbr" if cfs.fileExists("#{basename}.cbt") return "#{comic}.cbt" if cfs.fileExists("#{basename}.cbz") return "#{comic}.cbz" return false cfs.findParentContainingFilename = (startDir, filename) -> startDir = path.resolve('.', startDir) dirPieces = startDir.split(path.sep) loop if not dirPieces.length return false testPieces = dirPieces.slice() testPieces.push(filename) testPath = cfs.join.apply(null, testPieces) found = cfs.fileExists(testPath) # log.verbose "checking path #{testPath} (#{found})" if found return cfs.join.apply(null, dirPieces) dirPieces.pop() return false cfs.listDir = (dir) -> return cfs.readdirSyncRecursive(dir) cfs.listImages = (dir) -> list = cfs.readdirSyncRecursive(dir) images = (path.resolve(dir, file) for file in list when file.match(/\.(png|jpg|jpeg|webp|gif)$/i)) return images.sort() cfs.gatherComics = (subDir, rootDir) -> subDir = subDir.replace("#{path.sep}$", "") if not rootDir? rootDir = subDir rootDir = rootDir.replace("#{path.sep}$", "") list = cfs.readdirSyncRecursive(subDir) comicDirs = (path.resolve(subDir, file).replace(/[\/\\]images$/, "") for file in list when file.match(/images$/i)) comics = [] for dir in comicDirs relativeDir = dir.substr(rootDir.length + 1) relativeDir = relativeDir.replace(/\\/g, "/") metadata = cfs.readMetadata(dir) if metadata metadata.dir = dir metadata.relativeDir = relativeDir comics.push metadata return comics cfs.gatherMetadata = (dir) -> mdList = [] fileList = fs.readdirSync(dir).sort() for file in fileList resolvedPath = path.resolve(dir, file) metadata = cfs.readMetadata(resolvedPath) continue if not metadata metadata.path = file mdList.push metadata mdList.sort (a, b) -> #if a.type == b.type if a.path == b.path return 0 if a.path > b.path return 1 return -1 #if a.type > b.type # return 1 #return -1 return mdList cfs.readMetadata = (dir) -> metaFilename = cfs.join(dir, constants.META_FILENAME) if not fs.existsSync(metaFilename) return false rawText = fs.readFileSync(metaFilename) if not rawText return false try metadata = JSON.parse(rawText) catch metadata = false return metadata cfs.touchRoot = (dir) -> rootFilename = cfs.join(dir, constants.ROOT_FILENAME) return if cfs.fileHasBytes(rootFilename) rootinfo = { title: constants.DEFAULT_TITLE progress: "" } json = JSON.stringify(rootinfo, null, 2) fs.writeFileSync rootFilename, json cfs.getRootTitle = (dir) -> rootFilename = cfs.join(dir, constants.ROOT_FILENAME) if cfs.fileHasBytes(rootFilename) try rawJSON = fs.readFileSync(rootFilename) data = JSON.parse(rawJSON) if data.title return data.title catch return constants.DEFAULT_TITLE cfs.getProgressEndpoint = (dir) -> rootFilename = cfs.join(dir, constants.ROOT_FILENAME) if cfs.fileHasBytes(rootFilename) try rawJSON = fs.readFileSync(rootFilename) data = JSON.parse(rawJSON) if data.progress return data.progress catch return "" cfs.writeMetadata = (dir, metadata) -> metaFilename = cfs.join(dir, constants.META_FILENAME) json = JSON.stringify(metadata, null, 2) # log.verbose "writeMetadata (#{dir}): #{JSON.stringify(metadata, null, 2)}" fs.writeFileSync metaFilename, json cfs.removeMetadata = (dir, metadata) -> metaFilename = cfs.join(dir, constants.META_FILENAME) # log.verbose "removeMetadata (#{dir})" fs.unlinkSync metaFilename cfs.copyFile = (src, dst) -> log.verbose "copyFile #{src} -> #{dst}" fs.writeFileSync(dst, fs.readFileSync(src)); cfs.prepareDir = (dir) -> # Ensure the directory exists, and is a directory if not fs.existsSync(dir) fs.mkdirSync(dir) if not fs.existsSync(dir) log.error "Cannot create directory #{dir}, mkdir failed" return false stats = fs.statSync(dir) if not stats.isDirectory() log.error "Cannot create directory #{dir}, file exists (not a dir)" return false return true cfs.prepareComicDir = (dir) -> if not cfs.prepareDir(dir) return false log.verbose "Comic directory prepared: #{dir}" return true cfs.cleanupDir = (dir) -> if fs.existsSync(dir) log.verbose "Cleaning up #{dir}" cfs.rmdirSyncRecursive(dir, true) return cfs.newer = (amINewer, thanThisFile) -> if not fs.existsSync(amINewer) return true if not fs.existsSync(thanThisFile) return true amINewerStats = fs.statSync(amINewer) thanThisFileStats = fs.statSync(thanThisFile) return amINewerStats.mtime > thanThisFileStats.mtime # Taken/adapted from deprecated 'wrench' module by <NAME> cfs.readdirSyncRecursive = (baseDir) -> baseDir = baseDir.replace(/\/$/, '') readdirSyncRecursive = (baseDir) -> files = [] isDir = (fname) -> if fs.existsSync(path.join(baseDir, fname)) return fs.statSync( path.join(baseDir, fname) ).isDirectory() return false prependBaseDir = (fname) -> return path.join(baseDir, fname) curFiles = fs.readdirSync(baseDir) nextDirs = curFiles.filter(isDir) curFiles = curFiles.map(prependBaseDir) files = files.concat(curFiles) while nextDirs.length > 0 files = files.concat( readdirSyncRecursive(path.join(baseDir, nextDirs.shift())) ) return files # convert absolute paths to relative fileList = readdirSyncRecursive(baseDir).map (val) -> return path.relative(baseDir, val) return fileList # Taken/adapted from deprecated 'wrench' module by <NAME> cfs.rmdirSyncRecursive = (dir, failSilent) -> isWindows = !!process.platform.match(/^win/) try files = fs.readdirSync(dir) catch err return if failSilent throw new Error(err.message) # Loop through and delete everything in the sub-tree after checking it for file in files file = path.join(dir, file) currFile = fs.lstatSync(file) if currFile.isDirectory() # Recursive function back to the beginning cfs.rmdirSyncRecursive(file) else if currFile.isSymbolicLink() # Unlink symlinks if isWindows fs.chmodSync(file, 666) # Windows needs this unless joyent/node#3006 is resolved.. fs.unlinkSync(file) else # Assume it's a file - perhaps a try/catch belongs here? if isWindows fs.chmodSync(file, 666) # Windows needs this unless joyent/node#3006 is resolved.. fs.unlinkSync(file) # Now that we know everything in the sub-tree has been deleted, we can delete the main directory. Huzzah for the shopkeep. return fs.rmdirSync(dir) # Taken/adapted from deprecated 'wrench' module by <NAME> cfs.mkdirSyncRecursive = (dir, mode) -> dir = path.normalize(dir) try fs.mkdirSync(dir, mode) catch err if err.code == "ENOENT" slashIdx = dir.lastIndexOf(path.sep) if slashIdx > 0 parentDir = dir.substring(0, slashIdx) cfs.mkdirSyncRecursive(parentDir, mode) cfs.mkdirSyncRecursive(dir, mode) else throw err else if err.code == "EEXIST" return else throw err return # Taken/adapted from deprecated 'wrench' module by <NAME> cfs.chmodSyncRecursive = (sourceDir, filemode) -> files = fs.readdirSync(sourceDir) for file in files currFile = fs.lstatSync(path.join(sourceDir, file)) if currFile.isDirectory() # ...and recursion this thing right on back. cfs.chmodSyncRecursive(path.join(sourceDir, file), filemode) else # At this point, we've hit a file actually worth copying... so copy it on over. fs.chmodSync(path.join(sourceDir, file), filemode) # Finally, chmod the parent directory return fs.chmodSync(sourceDir, filemode) module.exports = cfs
true
# cracker file system constants = require './constants' fs = require 'fs' path = require 'path' log = require './log' touch = require 'touch' cfs = {} cfs.join = -> result = path.join.apply(null, arguments) # work around stupid lack of symmetry between path.join and split(sep) if arguments.length > 0 and arguments[0] == '' result = "/#{result}" return result cfs.dirExists = (dir) -> if not fs.existsSync(dir) return false stats = fs.statSync(dir) if stats.isDirectory() return true return false cfs.dirTime = (dir) -> dirStats = fs.statSync(dir) return 0 if not dirStats? return Math.floor(dirStats.mtime.getTime() / 1000) cfs.fileExists = (file) -> if not fs.existsSync(file) return false stats = fs.statSync(file) if stats.isFile() return true return false cfs.fileHasBytes = (file) -> if not fs.existsSync(file) return false stats = fs.statSync(file) if stats.isFile() return (stats.size > 0) return false cfs.ensureFileExists = (file) -> if fs.existsSync(file) return touch.sync(file) return cfs.insideDir = (filename, dir) -> if filename.indexOf(dir) == 0 return true return false cfs.findArchive = (dir, comic) -> basename = path.join(dir, comic) if cfs.fileExists("#{basename}.cbr") return "#{comic}.cbr" if cfs.fileExists("#{basename}.cbt") return "#{comic}.cbt" if cfs.fileExists("#{basename}.cbz") return "#{comic}.cbz" return false cfs.findParentContainingFilename = (startDir, filename) -> startDir = path.resolve('.', startDir) dirPieces = startDir.split(path.sep) loop if not dirPieces.length return false testPieces = dirPieces.slice() testPieces.push(filename) testPath = cfs.join.apply(null, testPieces) found = cfs.fileExists(testPath) # log.verbose "checking path #{testPath} (#{found})" if found return cfs.join.apply(null, dirPieces) dirPieces.pop() return false cfs.listDir = (dir) -> return cfs.readdirSyncRecursive(dir) cfs.listImages = (dir) -> list = cfs.readdirSyncRecursive(dir) images = (path.resolve(dir, file) for file in list when file.match(/\.(png|jpg|jpeg|webp|gif)$/i)) return images.sort() cfs.gatherComics = (subDir, rootDir) -> subDir = subDir.replace("#{path.sep}$", "") if not rootDir? rootDir = subDir rootDir = rootDir.replace("#{path.sep}$", "") list = cfs.readdirSyncRecursive(subDir) comicDirs = (path.resolve(subDir, file).replace(/[\/\\]images$/, "") for file in list when file.match(/images$/i)) comics = [] for dir in comicDirs relativeDir = dir.substr(rootDir.length + 1) relativeDir = relativeDir.replace(/\\/g, "/") metadata = cfs.readMetadata(dir) if metadata metadata.dir = dir metadata.relativeDir = relativeDir comics.push metadata return comics cfs.gatherMetadata = (dir) -> mdList = [] fileList = fs.readdirSync(dir).sort() for file in fileList resolvedPath = path.resolve(dir, file) metadata = cfs.readMetadata(resolvedPath) continue if not metadata metadata.path = file mdList.push metadata mdList.sort (a, b) -> #if a.type == b.type if a.path == b.path return 0 if a.path > b.path return 1 return -1 #if a.type > b.type # return 1 #return -1 return mdList cfs.readMetadata = (dir) -> metaFilename = cfs.join(dir, constants.META_FILENAME) if not fs.existsSync(metaFilename) return false rawText = fs.readFileSync(metaFilename) if not rawText return false try metadata = JSON.parse(rawText) catch metadata = false return metadata cfs.touchRoot = (dir) -> rootFilename = cfs.join(dir, constants.ROOT_FILENAME) return if cfs.fileHasBytes(rootFilename) rootinfo = { title: constants.DEFAULT_TITLE progress: "" } json = JSON.stringify(rootinfo, null, 2) fs.writeFileSync rootFilename, json cfs.getRootTitle = (dir) -> rootFilename = cfs.join(dir, constants.ROOT_FILENAME) if cfs.fileHasBytes(rootFilename) try rawJSON = fs.readFileSync(rootFilename) data = JSON.parse(rawJSON) if data.title return data.title catch return constants.DEFAULT_TITLE cfs.getProgressEndpoint = (dir) -> rootFilename = cfs.join(dir, constants.ROOT_FILENAME) if cfs.fileHasBytes(rootFilename) try rawJSON = fs.readFileSync(rootFilename) data = JSON.parse(rawJSON) if data.progress return data.progress catch return "" cfs.writeMetadata = (dir, metadata) -> metaFilename = cfs.join(dir, constants.META_FILENAME) json = JSON.stringify(metadata, null, 2) # log.verbose "writeMetadata (#{dir}): #{JSON.stringify(metadata, null, 2)}" fs.writeFileSync metaFilename, json cfs.removeMetadata = (dir, metadata) -> metaFilename = cfs.join(dir, constants.META_FILENAME) # log.verbose "removeMetadata (#{dir})" fs.unlinkSync metaFilename cfs.copyFile = (src, dst) -> log.verbose "copyFile #{src} -> #{dst}" fs.writeFileSync(dst, fs.readFileSync(src)); cfs.prepareDir = (dir) -> # Ensure the directory exists, and is a directory if not fs.existsSync(dir) fs.mkdirSync(dir) if not fs.existsSync(dir) log.error "Cannot create directory #{dir}, mkdir failed" return false stats = fs.statSync(dir) if not stats.isDirectory() log.error "Cannot create directory #{dir}, file exists (not a dir)" return false return true cfs.prepareComicDir = (dir) -> if not cfs.prepareDir(dir) return false log.verbose "Comic directory prepared: #{dir}" return true cfs.cleanupDir = (dir) -> if fs.existsSync(dir) log.verbose "Cleaning up #{dir}" cfs.rmdirSyncRecursive(dir, true) return cfs.newer = (amINewer, thanThisFile) -> if not fs.existsSync(amINewer) return true if not fs.existsSync(thanThisFile) return true amINewerStats = fs.statSync(amINewer) thanThisFileStats = fs.statSync(thanThisFile) return amINewerStats.mtime > thanThisFileStats.mtime # Taken/adapted from deprecated 'wrench' module by PI:NAME:<NAME>END_PI cfs.readdirSyncRecursive = (baseDir) -> baseDir = baseDir.replace(/\/$/, '') readdirSyncRecursive = (baseDir) -> files = [] isDir = (fname) -> if fs.existsSync(path.join(baseDir, fname)) return fs.statSync( path.join(baseDir, fname) ).isDirectory() return false prependBaseDir = (fname) -> return path.join(baseDir, fname) curFiles = fs.readdirSync(baseDir) nextDirs = curFiles.filter(isDir) curFiles = curFiles.map(prependBaseDir) files = files.concat(curFiles) while nextDirs.length > 0 files = files.concat( readdirSyncRecursive(path.join(baseDir, nextDirs.shift())) ) return files # convert absolute paths to relative fileList = readdirSyncRecursive(baseDir).map (val) -> return path.relative(baseDir, val) return fileList # Taken/adapted from deprecated 'wrench' module by PI:NAME:<NAME>END_PI cfs.rmdirSyncRecursive = (dir, failSilent) -> isWindows = !!process.platform.match(/^win/) try files = fs.readdirSync(dir) catch err return if failSilent throw new Error(err.message) # Loop through and delete everything in the sub-tree after checking it for file in files file = path.join(dir, file) currFile = fs.lstatSync(file) if currFile.isDirectory() # Recursive function back to the beginning cfs.rmdirSyncRecursive(file) else if currFile.isSymbolicLink() # Unlink symlinks if isWindows fs.chmodSync(file, 666) # Windows needs this unless joyent/node#3006 is resolved.. fs.unlinkSync(file) else # Assume it's a file - perhaps a try/catch belongs here? if isWindows fs.chmodSync(file, 666) # Windows needs this unless joyent/node#3006 is resolved.. fs.unlinkSync(file) # Now that we know everything in the sub-tree has been deleted, we can delete the main directory. Huzzah for the shopkeep. return fs.rmdirSync(dir) # Taken/adapted from deprecated 'wrench' module by PI:NAME:<NAME>END_PI cfs.mkdirSyncRecursive = (dir, mode) -> dir = path.normalize(dir) try fs.mkdirSync(dir, mode) catch err if err.code == "ENOENT" slashIdx = dir.lastIndexOf(path.sep) if slashIdx > 0 parentDir = dir.substring(0, slashIdx) cfs.mkdirSyncRecursive(parentDir, mode) cfs.mkdirSyncRecursive(dir, mode) else throw err else if err.code == "EEXIST" return else throw err return # Taken/adapted from deprecated 'wrench' module by PI:NAME:<NAME>END_PI cfs.chmodSyncRecursive = (sourceDir, filemode) -> files = fs.readdirSync(sourceDir) for file in files currFile = fs.lstatSync(path.join(sourceDir, file)) if currFile.isDirectory() # ...and recursion this thing right on back. cfs.chmodSyncRecursive(path.join(sourceDir, file), filemode) else # At this point, we've hit a file actually worth copying... so copy it on over. fs.chmodSync(path.join(sourceDir, file), filemode) # Finally, chmod the parent directory return fs.chmodSync(sourceDir, filemode) module.exports = cfs
[ { "context": "one) ->\n fabricate 'authors', [\n { name: 'Alex' }\n { name: 'Molly' }\n {}\n ], (err, ", "end": 482, "score": 0.999828577041626, "start": 478, "tag": "NAME", "value": "Alex" }, { "context": "authors', [\n { name: 'Alex' }\n { name: 'Moll...
src/api/apps/authors/test/integration.test.coffee
craigspaeth/positron
76
_ = require 'underscore' { db, fixtures, fabricate, empty } = require '../../../test/helpers/db' app = require '../../../' request = require 'superagent' { ObjectId } = require 'mongojs' describe 'authors endpoints', -> beforeEach (done) -> empty => fabricate 'users', {}, (err, @user) => @server = app.listen 5000, -> done() afterEach -> @server.close() it 'gets a list of authors', (done) -> fabricate 'authors', [ { name: 'Alex' } { name: 'Molly' } {} ], (err, authors) -> request .get("http://localhost:5000/authors?count=true") .end (err, res) -> res.body.total.should.equal 3 res.body.count.should.equal 3 res.body.results[2].name.should.equal 'Alex' done() it 'gets a list of authors by query', (done) -> fabricate 'authors', [ { name: 'Alex' } { name: 'Molly' } {} ], (err, authors) -> request .get("http://localhost:5000/authors?q=Alex&count=true") .end (err, res) -> res.body.total.should.equal 3 res.body.count.should.equal 1 res.body.results[0].name.should.equal 'Alex' done() it 'gets a single author', (done) -> fabricate 'authors', [ { _id: ObjectId('55356a9deca560a0137aa4b7') name: 'Alex' } ], (err, sections) -> request .get("http://localhost:5000/authors/55356a9deca560a0137aa4b7") .end (err, res) -> res.body.name.should.equal 'Alex' done()
175175
_ = require 'underscore' { db, fixtures, fabricate, empty } = require '../../../test/helpers/db' app = require '../../../' request = require 'superagent' { ObjectId } = require 'mongojs' describe 'authors endpoints', -> beforeEach (done) -> empty => fabricate 'users', {}, (err, @user) => @server = app.listen 5000, -> done() afterEach -> @server.close() it 'gets a list of authors', (done) -> fabricate 'authors', [ { name: '<NAME>' } { name: '<NAME>' } {} ], (err, authors) -> request .get("http://localhost:5000/authors?count=true") .end (err, res) -> res.body.total.should.equal 3 res.body.count.should.equal 3 res.body.results[2].name.should.equal '<NAME>' done() it 'gets a list of authors by query', (done) -> fabricate 'authors', [ { name: '<NAME>' } { name: '<NAME>' } {} ], (err, authors) -> request .get("http://localhost:5000/authors?q=Alex&count=true") .end (err, res) -> res.body.total.should.equal 3 res.body.count.should.equal 1 res.body.results[0].name.should.equal '<NAME>' done() it 'gets a single author', (done) -> fabricate 'authors', [ { _id: ObjectId('55356a9deca560a0137aa4b7') name: '<NAME>' } ], (err, sections) -> request .get("http://localhost:5000/authors/55356a9deca560a0137aa4b7") .end (err, res) -> res.body.name.should.equal '<NAME>' done()
true
_ = require 'underscore' { db, fixtures, fabricate, empty } = require '../../../test/helpers/db' app = require '../../../' request = require 'superagent' { ObjectId } = require 'mongojs' describe 'authors endpoints', -> beforeEach (done) -> empty => fabricate 'users', {}, (err, @user) => @server = app.listen 5000, -> done() afterEach -> @server.close() it 'gets a list of authors', (done) -> fabricate 'authors', [ { name: 'PI:NAME:<NAME>END_PI' } { name: 'PI:NAME:<NAME>END_PI' } {} ], (err, authors) -> request .get("http://localhost:5000/authors?count=true") .end (err, res) -> res.body.total.should.equal 3 res.body.count.should.equal 3 res.body.results[2].name.should.equal 'PI:NAME:<NAME>END_PI' done() it 'gets a list of authors by query', (done) -> fabricate 'authors', [ { name: 'PI:NAME:<NAME>END_PI' } { name: 'PI:NAME:<NAME>END_PI' } {} ], (err, authors) -> request .get("http://localhost:5000/authors?q=Alex&count=true") .end (err, res) -> res.body.total.should.equal 3 res.body.count.should.equal 1 res.body.results[0].name.should.equal 'PI:NAME:<NAME>END_PI' done() it 'gets a single author', (done) -> fabricate 'authors', [ { _id: ObjectId('55356a9deca560a0137aa4b7') name: 'PI:NAME:<NAME>END_PI' } ], (err, sections) -> request .get("http://localhost:5000/authors/55356a9deca560a0137aa4b7") .end (err, res) -> res.body.name.should.equal 'PI:NAME:<NAME>END_PI' done()
[ { "context": " headers = {}\n body = null\n accessKeyId = 'akid'\n secretAccessKey = 'secret'\n sessionToken ", "end": 1087, "score": 0.907167375087738, "start": 1083, "tag": "KEY", "value": "akid" }, { "context": "l\n accessKeyId = 'akid'\n secretAccessKey = 'secr...
node_modules/aws-sdk/test/signers/s3.spec.coffee
Nordstrom/banquo-server
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. AWS = require('../../lib/core') require('../../lib/signers/s3') describe 'AWS.Signers.S3', -> # these can be overriden in tests method = null path = null headers = null body = null date = null virtualHostedBucket = null accessKeyId = null secretAccessKey = null sessionToken = null # reset the overriden variable before each test beforeEach -> method = 'POST' path = '/' virtualHostedBucket = null date = new Date(0) headers = {} body = null accessKeyId = 'akid' secretAccessKey = 'secret' sessionToken = null buildRequest = () -> req = new AWS.HttpRequest('https://s3.amazonaws.com') req.method = method req.path = path req.headers = headers req.body = body req.virtualHostedBucket = virtualHostedBucket req credentials = () -> creds = {} creds.accessKeyId = accessKeyId creds.secretAccessKey = secretAccessKey creds.sessionToken = sessionToken if (sessionToken) creds addAuth = (req) -> signer = new AWS.Signers.S3(req || buildRequest()) signer.addAuthorization(credentials(), date) signer.request stringToSign = (req) -> signer = new AWS.Signers.S3(req || buildRequest()) signer.stringToSign() describe 'addAuthorization', -> it 'sets the date header when not present', -> req = buildRequest() addAuth(req) expect(req.headers['Date']).toEqual(AWS.util.date.rfc822(date)) it 'overwrites Date if present', -> req = buildRequest() req.headers['Date'] = 'date-string' addAuth(req) expect(req.headers['Date']).toEqual(AWS.util.date.rfc822(date)) it 'omits the security token header when session token is blank', -> sessionToken = null req = addAuth() expect(req.headers['x-amz-security-token']).toEqual(undefined) it 'adds a security token header when session token available', -> sessionToken = 'session' req = addAuth() expect(req.headers['x-amz-security-token']).toEqual('session') it 'adds an Authorization header which contains akid and signature', -> creds = { accessKeyId: 'AKID', secretAccessKey: 'secret' } req = buildRequest() signer = new AWS.Signers.S3(req) spyOn(signer, 'stringToSign') signer.stringToSign.andReturn('string-to-sign') signer.addAuthorization(creds, date) expect(req.headers['Authorization']).toEqual('AWS AKID:Gg5WLabTOvH0WMd15wv7lWe4zK0=') it 'properly signs special characters', -> creds = { accessKeyId: 'AKID', secretAccessKey: 'secret' } req = buildRequest() signer = new AWS.Signers.S3(req) spyOn(signer, 'stringToSign') signer.stringToSign.andReturn('!@#$%^&*();\':"{}[],./?`~') signer.addAuthorization(creds, date) expect(req.headers['Authorization']).toEqual('AWS AKID:2E04i7QCa0uZTYtxue9dEqto3dg=') describe 'stringToSign', -> beforeEach -> headers['Date'] = 'DATE-STRING' it 'builds a basic string to sign', -> expect(stringToSign()).toEqual(""" POST DATE-STRING / """) it 'includes content md5 and content type when present', -> headers['Content-Type'] = 'CONTENT-TYPE' headers['Content-MD5'] = 'CONTENT-MD5' expect(stringToSign()).toEqual(""" POST CONTENT-MD5 CONTENT-TYPE DATE-STRING / """) it 'includes the http method, whatever it is', -> method = 'VERB' expect(stringToSign()).toEqual(""" VERB DATE-STRING / """) it 'includes any x-amz- style headers, but not others', -> headers['X-Amz-Abc'] = 'abc' headers['X-Amz-Xyz'] = 'xyz' headers['random-header'] = 'random' expect(stringToSign()).toEqual(""" POST DATE-STRING x-amz-abc:abc x-amz-xyz:xyz / """) it 'includes x-amz- headers that are lower-cased', -> headers['x-amz-Abc'] = 'abc' headers['x-amz-Xyz'] = 'xyz' headers['random-header'] = 'random' expect(stringToSign()).toEqual(""" POST DATE-STRING x-amz-abc:abc x-amz-xyz:xyz / """) it 'sorts headers by their name', -> headers['x-amz-mno'] = 'mno' headers['x-amz-Xyz'] = 'xyz' headers['x-amz-Abc'] = 'abc' expect(stringToSign()).toEqual(""" POST DATE-STRING x-amz-abc:abc x-amz-mno:mno x-amz-xyz:xyz / """) it 'builds a canonical resource from the path', -> path = '/bucket_name/key' expect(stringToSign()).toEqual(""" POST DATE-STRING /bucket_name/key """) it 'appends the bucket to the path when it is part of the hostname', -> path = '/' virtualHostedBucket = 'bucket-name' expect(stringToSign()).toEqual(""" POST DATE-STRING /bucket-name/ """) it 'appends the subresource portion of the path querystring', -> path = '/?acl' virtualHostedBucket = 'bucket-name' expect(stringToSign()).toEqual(""" POST DATE-STRING /bucket-name/?acl """) it 'includes the sub resource value when present', -> path = '/bucket_name/key?versionId=123' expect(stringToSign()).toEqual(""" POST DATE-STRING /bucket_name/key?versionId=123 """) it 'omits non-sub-resource querystring params from the resource string', -> path = '/?versionId=abc&next-marker=xyz' expect(stringToSign()).toEqual(""" POST DATE-STRING /?versionId=abc """) it 'sorts sub resources by name', -> path = '/?logging&acl&website&torrent=123' # made up example expect(stringToSign()).toEqual(""" POST DATE-STRING /?acl&logging&torrent=123&website """) it 'sorts sub resources by name', -> path = '/?logging&acl&website&torrent=123' # made up example expect(stringToSign()).toEqual(""" POST DATE-STRING /?acl&logging&torrent=123&website """) it 'includes the un-decoded query string param for sub resources', -> path = '/?versionId=a%2Bb' # a+b expect(stringToSign()).toEqual(""" POST DATE-STRING /?versionId=a%2Bb """) it 'includes the non-encoded query string get header overrides', -> path = '/?response-content-type=a%2Bb' # a+b expect(stringToSign()).toEqual(""" POST DATE-STRING /?response-content-type=a+b """) it 'omits the date header when not present', -> delete headers['Date'] expect(stringToSign()).toEqual(""" POST / """)
187773
# 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. AWS = require('../../lib/core') require('../../lib/signers/s3') describe 'AWS.Signers.S3', -> # these can be overriden in tests method = null path = null headers = null body = null date = null virtualHostedBucket = null accessKeyId = null secretAccessKey = null sessionToken = null # reset the overriden variable before each test beforeEach -> method = 'POST' path = '/' virtualHostedBucket = null date = new Date(0) headers = {} body = null accessKeyId = '<KEY>' secretAccessKey = '<KEY>' sessionToken = null buildRequest = () -> req = new AWS.HttpRequest('https://s3.amazonaws.com') req.method = method req.path = path req.headers = headers req.body = body req.virtualHostedBucket = virtualHostedBucket req credentials = () -> creds = {} creds.accessKeyId = accessKeyId creds.secretAccessKey = secretAccessKey creds.sessionToken = sessionToken if (sessionToken) creds addAuth = (req) -> signer = new AWS.Signers.S3(req || buildRequest()) signer.addAuthorization(credentials(), date) signer.request stringToSign = (req) -> signer = new AWS.Signers.S3(req || buildRequest()) signer.stringToSign() describe 'addAuthorization', -> it 'sets the date header when not present', -> req = buildRequest() addAuth(req) expect(req.headers['Date']).toEqual(AWS.util.date.rfc822(date)) it 'overwrites Date if present', -> req = buildRequest() req.headers['Date'] = 'date-string' addAuth(req) expect(req.headers['Date']).toEqual(AWS.util.date.rfc822(date)) it 'omits the security token header when session token is blank', -> sessionToken = null req = addAuth() expect(req.headers['x-amz-security-token']).toEqual(undefined) it 'adds a security token header when session token available', -> sessionToken = 'session' req = addAuth() expect(req.headers['x-amz-security-token']).toEqual('session') it 'adds an Authorization header which contains akid and signature', -> creds = { accessKeyId: '<KEY>', secretAccessKey: '<KEY>' } req = buildRequest() signer = new AWS.Signers.S3(req) spyOn(signer, 'stringToSign') signer.stringToSign.andReturn('string-to-sign') signer.addAuthorization(creds, date) expect(req.headers['Authorization']).toEqual('AWS AKID:Gg5WLabTOvH0WMd15wv7lWe4zK0=') it 'properly signs special characters', -> creds = { accessKeyId: '<KEY>', secretAccessKey: '<KEY>' } req = buildRequest() signer = new AWS.Signers.S3(req) spyOn(signer, 'stringToSign') signer.stringToSign.andReturn('!@#$%^&*();\':"{}[],./?`~') signer.addAuthorization(creds, date) expect(req.headers['Authorization']).toEqual('AWS AKID:2E04i7QCa0uZTYtxue9dEqto3dg=') describe 'stringToSign', -> beforeEach -> headers['Date'] = 'DATE-STRING' it 'builds a basic string to sign', -> expect(stringToSign()).toEqual(""" POST DATE-STRING / """) it 'includes content md5 and content type when present', -> headers['Content-Type'] = 'CONTENT-TYPE' headers['Content-MD5'] = 'CONTENT-MD5' expect(stringToSign()).toEqual(""" POST CONTENT-MD5 CONTENT-TYPE DATE-STRING / """) it 'includes the http method, whatever it is', -> method = 'VERB' expect(stringToSign()).toEqual(""" VERB DATE-STRING / """) it 'includes any x-amz- style headers, but not others', -> headers['X-Amz-Abc'] = 'abc' headers['X-Amz-Xyz'] = 'xyz' headers['random-header'] = 'random' expect(stringToSign()).toEqual(""" POST DATE-STRING x-amz-abc:abc x-amz-xyz:xyz / """) it 'includes x-amz- headers that are lower-cased', -> headers['x-amz-Abc'] = 'abc' headers['x-amz-Xyz'] = 'xyz' headers['random-header'] = 'random' expect(stringToSign()).toEqual(""" POST DATE-STRING x-amz-abc:abc x-amz-xyz:xyz / """) it 'sorts headers by their name', -> headers['x-amz-mno'] = 'mno' headers['x-amz-Xyz'] = 'xyz' headers['x-amz-Abc'] = 'abc' expect(stringToSign()).toEqual(""" POST DATE-STRING x-amz-abc:abc x-amz-mno:mno x-amz-xyz:xyz / """) it 'builds a canonical resource from the path', -> path = '/bucket_name/key' expect(stringToSign()).toEqual(""" POST DATE-STRING /bucket_name/key """) it 'appends the bucket to the path when it is part of the hostname', -> path = '/' virtualHostedBucket = 'bucket-name' expect(stringToSign()).toEqual(""" POST DATE-STRING /bucket-name/ """) it 'appends the subresource portion of the path querystring', -> path = '/?acl' virtualHostedBucket = 'bucket-name' expect(stringToSign()).toEqual(""" POST DATE-STRING /bucket-name/?acl """) it 'includes the sub resource value when present', -> path = '/bucket_name/key?versionId=123' expect(stringToSign()).toEqual(""" POST DATE-STRING /bucket_name/key?versionId=123 """) it 'omits non-sub-resource querystring params from the resource string', -> path = '/?versionId=abc&next-marker=xyz' expect(stringToSign()).toEqual(""" POST DATE-STRING /?versionId=abc """) it 'sorts sub resources by name', -> path = '/?logging&acl&website&torrent=123' # made up example expect(stringToSign()).toEqual(""" POST DATE-STRING /?acl&logging&torrent=123&website """) it 'sorts sub resources by name', -> path = '/?logging&acl&website&torrent=123' # made up example expect(stringToSign()).toEqual(""" POST DATE-STRING /?acl&logging&torrent=123&website """) it 'includes the un-decoded query string param for sub resources', -> path = '/?versionId=a%2Bb' # a+b expect(stringToSign()).toEqual(""" POST DATE-STRING /?versionId=a%2Bb """) it 'includes the non-encoded query string get header overrides', -> path = '/?response-content-type=a%2Bb' # a+b expect(stringToSign()).toEqual(""" POST DATE-STRING /?response-content-type=a+b """) it 'omits the date header when not present', -> delete headers['Date'] expect(stringToSign()).toEqual(""" POST / """)
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. AWS = require('../../lib/core') require('../../lib/signers/s3') describe 'AWS.Signers.S3', -> # these can be overriden in tests method = null path = null headers = null body = null date = null virtualHostedBucket = null accessKeyId = null secretAccessKey = null sessionToken = null # reset the overriden variable before each test beforeEach -> method = 'POST' path = '/' virtualHostedBucket = null date = new Date(0) headers = {} body = null accessKeyId = 'PI:KEY:<KEY>END_PI' secretAccessKey = 'PI:KEY:<KEY>END_PI' sessionToken = null buildRequest = () -> req = new AWS.HttpRequest('https://s3.amazonaws.com') req.method = method req.path = path req.headers = headers req.body = body req.virtualHostedBucket = virtualHostedBucket req credentials = () -> creds = {} creds.accessKeyId = accessKeyId creds.secretAccessKey = secretAccessKey creds.sessionToken = sessionToken if (sessionToken) creds addAuth = (req) -> signer = new AWS.Signers.S3(req || buildRequest()) signer.addAuthorization(credentials(), date) signer.request stringToSign = (req) -> signer = new AWS.Signers.S3(req || buildRequest()) signer.stringToSign() describe 'addAuthorization', -> it 'sets the date header when not present', -> req = buildRequest() addAuth(req) expect(req.headers['Date']).toEqual(AWS.util.date.rfc822(date)) it 'overwrites Date if present', -> req = buildRequest() req.headers['Date'] = 'date-string' addAuth(req) expect(req.headers['Date']).toEqual(AWS.util.date.rfc822(date)) it 'omits the security token header when session token is blank', -> sessionToken = null req = addAuth() expect(req.headers['x-amz-security-token']).toEqual(undefined) it 'adds a security token header when session token available', -> sessionToken = 'session' req = addAuth() expect(req.headers['x-amz-security-token']).toEqual('session') it 'adds an Authorization header which contains akid and signature', -> creds = { accessKeyId: 'PI:KEY:<KEY>END_PI', secretAccessKey: 'PI:KEY:<KEY>END_PI' } req = buildRequest() signer = new AWS.Signers.S3(req) spyOn(signer, 'stringToSign') signer.stringToSign.andReturn('string-to-sign') signer.addAuthorization(creds, date) expect(req.headers['Authorization']).toEqual('AWS AKID:Gg5WLabTOvH0WMd15wv7lWe4zK0=') it 'properly signs special characters', -> creds = { accessKeyId: 'PI:KEY:<KEY>END_PI', secretAccessKey: 'PI:KEY:<KEY>END_PI' } req = buildRequest() signer = new AWS.Signers.S3(req) spyOn(signer, 'stringToSign') signer.stringToSign.andReturn('!@#$%^&*();\':"{}[],./?`~') signer.addAuthorization(creds, date) expect(req.headers['Authorization']).toEqual('AWS AKID:2E04i7QCa0uZTYtxue9dEqto3dg=') describe 'stringToSign', -> beforeEach -> headers['Date'] = 'DATE-STRING' it 'builds a basic string to sign', -> expect(stringToSign()).toEqual(""" POST DATE-STRING / """) it 'includes content md5 and content type when present', -> headers['Content-Type'] = 'CONTENT-TYPE' headers['Content-MD5'] = 'CONTENT-MD5' expect(stringToSign()).toEqual(""" POST CONTENT-MD5 CONTENT-TYPE DATE-STRING / """) it 'includes the http method, whatever it is', -> method = 'VERB' expect(stringToSign()).toEqual(""" VERB DATE-STRING / """) it 'includes any x-amz- style headers, but not others', -> headers['X-Amz-Abc'] = 'abc' headers['X-Amz-Xyz'] = 'xyz' headers['random-header'] = 'random' expect(stringToSign()).toEqual(""" POST DATE-STRING x-amz-abc:abc x-amz-xyz:xyz / """) it 'includes x-amz- headers that are lower-cased', -> headers['x-amz-Abc'] = 'abc' headers['x-amz-Xyz'] = 'xyz' headers['random-header'] = 'random' expect(stringToSign()).toEqual(""" POST DATE-STRING x-amz-abc:abc x-amz-xyz:xyz / """) it 'sorts headers by their name', -> headers['x-amz-mno'] = 'mno' headers['x-amz-Xyz'] = 'xyz' headers['x-amz-Abc'] = 'abc' expect(stringToSign()).toEqual(""" POST DATE-STRING x-amz-abc:abc x-amz-mno:mno x-amz-xyz:xyz / """) it 'builds a canonical resource from the path', -> path = '/bucket_name/key' expect(stringToSign()).toEqual(""" POST DATE-STRING /bucket_name/key """) it 'appends the bucket to the path when it is part of the hostname', -> path = '/' virtualHostedBucket = 'bucket-name' expect(stringToSign()).toEqual(""" POST DATE-STRING /bucket-name/ """) it 'appends the subresource portion of the path querystring', -> path = '/?acl' virtualHostedBucket = 'bucket-name' expect(stringToSign()).toEqual(""" POST DATE-STRING /bucket-name/?acl """) it 'includes the sub resource value when present', -> path = '/bucket_name/key?versionId=123' expect(stringToSign()).toEqual(""" POST DATE-STRING /bucket_name/key?versionId=123 """) it 'omits non-sub-resource querystring params from the resource string', -> path = '/?versionId=abc&next-marker=xyz' expect(stringToSign()).toEqual(""" POST DATE-STRING /?versionId=abc """) it 'sorts sub resources by name', -> path = '/?logging&acl&website&torrent=123' # made up example expect(stringToSign()).toEqual(""" POST DATE-STRING /?acl&logging&torrent=123&website """) it 'sorts sub resources by name', -> path = '/?logging&acl&website&torrent=123' # made up example expect(stringToSign()).toEqual(""" POST DATE-STRING /?acl&logging&torrent=123&website """) it 'includes the un-decoded query string param for sub resources', -> path = '/?versionId=a%2Bb' # a+b expect(stringToSign()).toEqual(""" POST DATE-STRING /?versionId=a%2Bb """) it 'includes the non-encoded query string get header overrides', -> path = '/?response-content-type=a%2Bb' # a+b expect(stringToSign()).toEqual(""" POST DATE-STRING /?response-content-type=a+b """) it 'omits the date header when not present', -> delete headers['Date'] expect(stringToSign()).toEqual(""" POST / """)
[ { "context": "man-museum'\n xml.should.containEql '<news:name>Artsy</news:name>'\n xml.should.containEql '2014-09-2", "end": 1917, "score": 0.8999583125114441, "start": 1912, "tag": "NAME", "value": "Artsy" } ]
src/desktop/apps/sitemaps/test/templates.coffee
xtina-starr/force
1
_ = require 'underscore' cheerio = require 'cheerio' path = require 'path' jade = require 'jade' fs = require 'fs' moment = require 'moment' { fabricate } = require 'antigravity' getFullEditorialHref = require("@artsy/reaction/dist/Components/Publishing/Constants").getFullEditorialHref Article = require '../../../models/article' Articles = require '../../../collections/articles' Artwork = require '../../../models/artwork' Section = require '../../../models/section' render = (templateName) -> filename = path.resolve __dirname, "../templates/#{templateName}.jade" jade.compile( fs.readFileSync(filename), { filename: filename } ) describe 'misc sitemap template', -> it 'renders the correct misc URLs', -> xml = render('misc') sd: APP_URL: 'www.artsy.net' xml.should.containEql '<loc>www.artsy.net</loc><priority>1</priority>' xml.should.containEql 'www.artsy.net/about' xml.should.containEql '/press/in-the-media' xml.should.containEql '/press/press-releases' xml.should.containEql '/collect' xml.should.containEql '/log_in' xml.should.containEql '/security' xml.should.containEql '/privacy' xml.should.containEql '/shows' xml.should.containEql '/artists' xml.should.containEql '/categories' xml.should.containEql '/sign_up' xml.should.containEql '/terms' describe 'news sitemap template', -> it 'renders article info', -> articles = [ new Article(fabricate('article', layout: 'standard')) new Article(fabricate('article', layout: 'news', slug: "banksys-half-shredded-painting-will-view-german-museum")) ] xml = render('news')(articles: articles, getFullEditorialHref: getFullEditorialHref) xml.should.containEql '/article/editorial-on-the-heels-of-a-stellar-year' xml.should.containEql '/news/banksys-half-shredded-painting-will-view-german-museum' xml.should.containEql '<news:name>Artsy</news:name>' xml.should.containEql '2014-09-24T23:24:54.000Z' xml.should.containEql 'On The Heels of A Stellar Year in the West, Sterling Ruby Makes His Vivid Mark on Asia'
21884
_ = require 'underscore' cheerio = require 'cheerio' path = require 'path' jade = require 'jade' fs = require 'fs' moment = require 'moment' { fabricate } = require 'antigravity' getFullEditorialHref = require("@artsy/reaction/dist/Components/Publishing/Constants").getFullEditorialHref Article = require '../../../models/article' Articles = require '../../../collections/articles' Artwork = require '../../../models/artwork' Section = require '../../../models/section' render = (templateName) -> filename = path.resolve __dirname, "../templates/#{templateName}.jade" jade.compile( fs.readFileSync(filename), { filename: filename } ) describe 'misc sitemap template', -> it 'renders the correct misc URLs', -> xml = render('misc') sd: APP_URL: 'www.artsy.net' xml.should.containEql '<loc>www.artsy.net</loc><priority>1</priority>' xml.should.containEql 'www.artsy.net/about' xml.should.containEql '/press/in-the-media' xml.should.containEql '/press/press-releases' xml.should.containEql '/collect' xml.should.containEql '/log_in' xml.should.containEql '/security' xml.should.containEql '/privacy' xml.should.containEql '/shows' xml.should.containEql '/artists' xml.should.containEql '/categories' xml.should.containEql '/sign_up' xml.should.containEql '/terms' describe 'news sitemap template', -> it 'renders article info', -> articles = [ new Article(fabricate('article', layout: 'standard')) new Article(fabricate('article', layout: 'news', slug: "banksys-half-shredded-painting-will-view-german-museum")) ] xml = render('news')(articles: articles, getFullEditorialHref: getFullEditorialHref) xml.should.containEql '/article/editorial-on-the-heels-of-a-stellar-year' xml.should.containEql '/news/banksys-half-shredded-painting-will-view-german-museum' xml.should.containEql '<news:name><NAME></news:name>' xml.should.containEql '2014-09-24T23:24:54.000Z' xml.should.containEql 'On The Heels of A Stellar Year in the West, Sterling Ruby Makes His Vivid Mark on Asia'
true
_ = require 'underscore' cheerio = require 'cheerio' path = require 'path' jade = require 'jade' fs = require 'fs' moment = require 'moment' { fabricate } = require 'antigravity' getFullEditorialHref = require("@artsy/reaction/dist/Components/Publishing/Constants").getFullEditorialHref Article = require '../../../models/article' Articles = require '../../../collections/articles' Artwork = require '../../../models/artwork' Section = require '../../../models/section' render = (templateName) -> filename = path.resolve __dirname, "../templates/#{templateName}.jade" jade.compile( fs.readFileSync(filename), { filename: filename } ) describe 'misc sitemap template', -> it 'renders the correct misc URLs', -> xml = render('misc') sd: APP_URL: 'www.artsy.net' xml.should.containEql '<loc>www.artsy.net</loc><priority>1</priority>' xml.should.containEql 'www.artsy.net/about' xml.should.containEql '/press/in-the-media' xml.should.containEql '/press/press-releases' xml.should.containEql '/collect' xml.should.containEql '/log_in' xml.should.containEql '/security' xml.should.containEql '/privacy' xml.should.containEql '/shows' xml.should.containEql '/artists' xml.should.containEql '/categories' xml.should.containEql '/sign_up' xml.should.containEql '/terms' describe 'news sitemap template', -> it 'renders article info', -> articles = [ new Article(fabricate('article', layout: 'standard')) new Article(fabricate('article', layout: 'news', slug: "banksys-half-shredded-painting-will-view-german-museum")) ] xml = render('news')(articles: articles, getFullEditorialHref: getFullEditorialHref) xml.should.containEql '/article/editorial-on-the-heels-of-a-stellar-year' xml.should.containEql '/news/banksys-half-shredded-painting-will-view-german-museum' xml.should.containEql '<news:name>PI:NAME:<NAME>END_PI</news:name>' xml.should.containEql '2014-09-24T23:24:54.000Z' xml.should.containEql 'On The Heels of A Stellar Year in the West, Sterling Ruby Makes His Vivid Mark on Asia'
[ { "context": " region: \"NY\"\n postal_code: '10012'\n name: 'Artsy'\n street: '401 Broadway'\n\ndescribe \"Order\", ->", "end": 325, "score": 0.9996098875999451, "start": 320, "tag": "NAME", "value": "Artsy" }, { "context": "get('partner_location').get('name').should.equal ...
src/desktop/test/models/order.coffee
kanaabe/force
1
_ = require 'underscore' should = require 'should' Backbone = require 'backbone' { fabricate } = require 'antigravity' Order = require '../../models/order.coffee' sinon = require 'sinon' shippingInfo = telephone: '8675309' shipping_address: city: 'New York' region: "NY" postal_code: '10012' name: 'Artsy' street: '401 Broadway' describe "Order", -> beforeEach -> sinon.stub Backbone, 'sync' @order = new Order(fabricate 'order') afterEach -> Backbone.sync.restore() describe '#sellersTerms', -> it "returns links to the sellers terms", -> @order.sellersTerms().should.equal 'http://shipping.conditions.com' describe '#customShippingNote', -> it "returns the shipping notes", -> @order.shippingNote().should.equal "HI I'm a shipping note" it "returns the shipping notes stripped of html", -> @order.set 'line_items', [{shipping_note: '<img>'}] @order.shippingNote().should.equal "&lt;img>" describe '#getLineItemArtworks', -> it "returns artwork models in an order", -> @order.getLineItemArtworks()[0].get('id').should.containEql 'skull' describe '#getLineItemPartners', -> it "returns partner models with locations", -> @order.getLineItemPartners()[0].get('id').should.containEql 'gagosian' @order.getLineItemPartners()[0].get('partner_location').get('name').should.equal 'Eli Ridgway' describe '#formatShippingLocal', -> it "blank if no shipping info", -> @order.formatShippingLocal().should.equal '' it "formatted shipping info", -> @order.set shippingInfo @order.formatShippingLocal().should.equal 'New York, NY 10012' describe '#formatShippingAddress', -> it "blank if no shipping info", -> @order.formatShippingAddress().should.equal '' it "formatted shipping info", -> @order.set shippingInfo @order.formatShippingAddress().should.equal 'Artsy<br />401 Broadway<br />New York, NY 10012' it "formatted shipping info stripped of HTML", -> info = _.clone shippingInfo info.shipping_address.name = "<img>" @order.set info @order.formatShippingAddress().should.equal '&lt;img><br />401 Broadway<br />New York, NY 10012' describe '#fetchPendingOrder', -> it 'constructs the correct url', -> @order.fetchPendingOrder({}) Backbone.sync.args[0][2].url.should.containEql 'api/v1/me/order/pending' describe '#update', -> it 'constructs the correct url', -> @order.update null, success: (order) => order.id.should.equal 'updated' Backbone.sync.args[0][2].url.should.containEql "api/v1/me/order/#{@order.id}" Backbone.sync.args[0][2].success(fabricate 'order', id: 'updated') describe '#resume', -> it 'constructs the correct url', -> @order.resume success: (order) => order.get('state').should.equal 'pending' Backbone.sync.args[0][2].url.should.containEql "api/v1/me/order/#{@order.id}/resume" Backbone.sync.args[0][2].success(fabricate 'order', state: 'pending')
16877
_ = require 'underscore' should = require 'should' Backbone = require 'backbone' { fabricate } = require 'antigravity' Order = require '../../models/order.coffee' sinon = require 'sinon' shippingInfo = telephone: '8675309' shipping_address: city: 'New York' region: "NY" postal_code: '10012' name: '<NAME>' street: '401 Broadway' describe "Order", -> beforeEach -> sinon.stub Backbone, 'sync' @order = new Order(fabricate 'order') afterEach -> Backbone.sync.restore() describe '#sellersTerms', -> it "returns links to the sellers terms", -> @order.sellersTerms().should.equal 'http://shipping.conditions.com' describe '#customShippingNote', -> it "returns the shipping notes", -> @order.shippingNote().should.equal "HI I'm a shipping note" it "returns the shipping notes stripped of html", -> @order.set 'line_items', [{shipping_note: '<img>'}] @order.shippingNote().should.equal "&lt;img>" describe '#getLineItemArtworks', -> it "returns artwork models in an order", -> @order.getLineItemArtworks()[0].get('id').should.containEql 'skull' describe '#getLineItemPartners', -> it "returns partner models with locations", -> @order.getLineItemPartners()[0].get('id').should.containEql 'gagosian' @order.getLineItemPartners()[0].get('partner_location').get('name').should.equal '<NAME>' describe '#formatShippingLocal', -> it "blank if no shipping info", -> @order.formatShippingLocal().should.equal '' it "formatted shipping info", -> @order.set shippingInfo @order.formatShippingLocal().should.equal 'New York, NY 10012' describe '#formatShippingAddress', -> it "blank if no shipping info", -> @order.formatShippingAddress().should.equal '' it "formatted shipping info", -> @order.set shippingInfo @order.formatShippingAddress().should.equal 'Artsy<br />401 Broadway<br />New York, NY 10012' it "formatted shipping info stripped of HTML", -> info = _.clone shippingInfo info.shipping_address.name = "<img>" @order.set info @order.formatShippingAddress().should.equal '&lt;img><br />401 Broadway<br />New York, NY 10012' describe '#fetchPendingOrder', -> it 'constructs the correct url', -> @order.fetchPendingOrder({}) Backbone.sync.args[0][2].url.should.containEql 'api/v1/me/order/pending' describe '#update', -> it 'constructs the correct url', -> @order.update null, success: (order) => order.id.should.equal 'updated' Backbone.sync.args[0][2].url.should.containEql "api/v1/me/order/#{@order.id}" Backbone.sync.args[0][2].success(fabricate 'order', id: 'updated') describe '#resume', -> it 'constructs the correct url', -> @order.resume success: (order) => order.get('state').should.equal 'pending' Backbone.sync.args[0][2].url.should.containEql "api/v1/me/order/#{@order.id}/resume" Backbone.sync.args[0][2].success(fabricate 'order', state: 'pending')
true
_ = require 'underscore' should = require 'should' Backbone = require 'backbone' { fabricate } = require 'antigravity' Order = require '../../models/order.coffee' sinon = require 'sinon' shippingInfo = telephone: '8675309' shipping_address: city: 'New York' region: "NY" postal_code: '10012' name: 'PI:NAME:<NAME>END_PI' street: '401 Broadway' describe "Order", -> beforeEach -> sinon.stub Backbone, 'sync' @order = new Order(fabricate 'order') afterEach -> Backbone.sync.restore() describe '#sellersTerms', -> it "returns links to the sellers terms", -> @order.sellersTerms().should.equal 'http://shipping.conditions.com' describe '#customShippingNote', -> it "returns the shipping notes", -> @order.shippingNote().should.equal "HI I'm a shipping note" it "returns the shipping notes stripped of html", -> @order.set 'line_items', [{shipping_note: '<img>'}] @order.shippingNote().should.equal "&lt;img>" describe '#getLineItemArtworks', -> it "returns artwork models in an order", -> @order.getLineItemArtworks()[0].get('id').should.containEql 'skull' describe '#getLineItemPartners', -> it "returns partner models with locations", -> @order.getLineItemPartners()[0].get('id').should.containEql 'gagosian' @order.getLineItemPartners()[0].get('partner_location').get('name').should.equal 'PI:NAME:<NAME>END_PI' describe '#formatShippingLocal', -> it "blank if no shipping info", -> @order.formatShippingLocal().should.equal '' it "formatted shipping info", -> @order.set shippingInfo @order.formatShippingLocal().should.equal 'New York, NY 10012' describe '#formatShippingAddress', -> it "blank if no shipping info", -> @order.formatShippingAddress().should.equal '' it "formatted shipping info", -> @order.set shippingInfo @order.formatShippingAddress().should.equal 'Artsy<br />401 Broadway<br />New York, NY 10012' it "formatted shipping info stripped of HTML", -> info = _.clone shippingInfo info.shipping_address.name = "<img>" @order.set info @order.formatShippingAddress().should.equal '&lt;img><br />401 Broadway<br />New York, NY 10012' describe '#fetchPendingOrder', -> it 'constructs the correct url', -> @order.fetchPendingOrder({}) Backbone.sync.args[0][2].url.should.containEql 'api/v1/me/order/pending' describe '#update', -> it 'constructs the correct url', -> @order.update null, success: (order) => order.id.should.equal 'updated' Backbone.sync.args[0][2].url.should.containEql "api/v1/me/order/#{@order.id}" Backbone.sync.args[0][2].success(fabricate 'order', id: 'updated') describe '#resume', -> it 'constructs the correct url', -> @order.resume success: (order) => order.get('state').should.equal 'pending' Backbone.sync.args[0][2].url.should.containEql "api/v1/me/order/#{@order.id}/resume" Backbone.sync.args[0][2].success(fabricate 'order', state: 'pending')
[ { "context": " dashboards: [\n id: 1\n user_id: fakeUser.id\n lite_paper_ids: [1]\n ]\n\n c", "end": 179, "score": 0.6428017020225525, "start": 175, "tag": "USERNAME", "value": "fake" }, { "context": "ds: [1]\n ]\n\n collaborators = [\n ...
test/javascripts/integration/commenting_test.js.coffee
johan--/tahi
1
module 'Integration: Commenting', teardown: -> ETahi.reset() setup: -> setupApp(integration: true) dashboard = dashboards: [ id: 1 user_id: fakeUser.id lite_paper_ids: [1] ] collaborators = [ id: "35" full_name: "Aaron Baker" info: "testroles2, collaborator" ] server.respondWith 'GET', "/dashboards", [ 200, {"Content-Type": "application/json"}, JSON.stringify dashboard ] server.respondWith 'PUT', /\/tasks\/\d+/, [ 204, {"Content-Type": "application/json"}, JSON.stringify {} ] test 'A card with more than 5 comments has the show all comments button', -> expect(2) ef = ETahi.Factory r = _.range(10) comments = _.map(r, (n) -> ef.createRecord('Comment', commenter_id: fakeUser.id task: {type: 'Task', id: 1} body: "My comment-#{n}" created_at: new Date().toISOString() )) [paper, task, records...] = ETahi.Setups.paperWithTask('Task' id: 1 title: "Commenting Time" participant_ids: [fakeUser.id] comment_ids: _.pluck(comments, 'id') ) ef = ETahi.Factory paperPayload = ef.createPayload('paper') paperPayload.addRecords(records.concat(paper, task, fakeUser, comments)) server.respondWith 'GET', "/papers/#{paper.id}", [ 200, {"Content-Type": "application/json"}, JSON.stringify paperPayload.toJSON() ] visit("/papers/#{paper.id}/tasks/#{task.id}") andThen -> ok(find('.load-all-comments').length == 1) equal(find('.message-comment').length, 5, 'Only 5 messages displayed') test 'A card with less than 5 comments doesnt have the show all comments button', -> expect(2) ef = ETahi.Factory r = _.range(3) comments = _.map(r, (n) -> ef.createRecord('Comment', commenter_id: fakeUser.id task: {type: 'Task', id: 1} body: "My comment-#{n}" created_at: new Date().toISOString() )) [paper, task, records...] = ETahi.Setups.paperWithTask('Task' id: 1 title: "Commenting Time" participant_ids: [fakeUser.id] comment_ids: _.pluck(comments, 'id') ) ef = ETahi.Factory paperPayload = ef.createPayload('paper') paperPayload.addRecords(records.concat(paper, task, fakeUser, comments)) server.respondWith 'GET', "/papers/#{paper.id}", [ 200, {"Content-Type": "application/json"}, JSON.stringify paperPayload.toJSON() ] visit("/papers/#{paper.id}/tasks/#{task.id}") andThen -> ok(find('.load-all-comments').length == 0) equal(find('.message-comment').length, 3, 'All messages displayed') test 'A message card with a commentLook shows up as unread and updates its commentLook', -> expect(2) ef = ETahi.Factory commenter = ef.createRecord 'User', id: 999 full_name: "Confucius" username: "confucius" email: "confucius@example.com" comment = ef.createRecord('Comment', commenter_id: commenter.id task: {type: 'Task', id: 1} body: "Unread comment" created_at: new Date().toISOString() ) commentLook = ef.createRecord('CommentLook', id: 1) ef.setForeignKey(comment, commentLook, {inverse: 'comment'}) ef.setForeignKey(fakeUser, commentLook, {inverse: 'user'}) comment.comment_look_ids = [commentLook.id] [paper, task, records...] = ETahi.Setups.paperWithTask('Task' title: "Commenting Time" participant_ids: [commenter.id, fakeUser.id] comment_ids: [comment.id] ) paperPayload = ef.createPayload('paper') paperPayload.addRecords(records.concat(paper, task, fakeUser, commenter, comment, commentLook)) server.respondWith 'GET', "/papers/#{paper.id}", [ 200, {"Content-Type": "application/json"}, JSON.stringify paperPayload.toJSON() ] server.respondWith 'PUT', /\/comment_looks\/\d+/, [ 204, {"Content-Type": "application/json"}, JSON.stringify {} ] visit("/papers/#{paper.id}/tasks/#{task.id}") andThen -> ok(_.findWhere(server.requests, {method: "PUT", url: "/comment_looks/1"})) equal(find('.message-comment.unread .comment-body').text(), "Unread comment") test 'Showing all comments shows them.', -> expect(1) ef = ETahi.Factory r = _.range(10) comments = _.map(r, (n) -> ef.createRecord('Comment', commenter_id: fakeUser.id task: {type: 'Task', id: 1} body: "My comment-#{n}" )) [paper, task, records...] = ETahi.Setups.paperWithTask('Task' id: 1 title: "Commenting Time" participant_ids: [fakeUser.id] comment_ids: _.pluck(comments, 'id') ) ef = ETahi.Factory paperPayload = ef.createPayload('paper') paperPayload.addRecords(records.concat(paper, task, fakeUser, comments)) server.respondWith 'GET', "/papers/#{paper.id}", [ 200, {"Content-Type": "application/json"}, JSON.stringify paperPayload.toJSON() ] visit("/papers/#{paper.id}/tasks/#{task.id}") click(".load-all-comments") andThen -> equal(find('.message-comment').length, 10, 'All messages displayed') test 'Unread comments do not stay unread when showing all comments if they were already shown', -> expect(3) ef = ETahi.Factory commenter = ef.createRecord 'User', id: 999 full_name: "Confucius" username: "confucius" email: "confucius@example.com" r = _.range(10) comments = _.map(r, (n) -> ef.createRecord('Comment', commenter_id: commenter.id task: {type: 'Task', id: 1} body: "My comment-#{n}" # These can't all be created at the exact same time created_at: new Date(Date.now() + n).toISOString() )) #make the most recent comment unread recentComment = _.last(comments) recentComment.body = "Unread comment" commentLook = ef.createRecord('CommentLook', id: 1) ef.setForeignKey(recentComment, commentLook, {inverse: 'comment'}) ef.setForeignKey(fakeUser, commentLook, {inverse: 'user'}) recentComment.comment_look_ids = [commentLook.id] [paper, task, records...] = ETahi.Setups.paperWithTask('Task' id: 1 title: "Commenting Time" participant_ids: [commenter.id, fakeUser.id] comment_ids: _.pluck(comments, 'id') ) paperPayload = ef.createPayload('paper') paperPayload.addRecords(records.concat(paper, task, fakeUser, commenter, comments, commentLook)) server.respondWith 'GET', "/papers/#{paper.id}", [ 200, {"Content-Type": "application/json"}, JSON.stringify paperPayload.toJSON() ] server.respondWith 'PUT', /\/comment_looks\/\d+/, [ 204, {"Content-Type": "application/json"}, JSON.stringify {} ] visit("/papers/#{paper.id}/tasks/#{task.id}") andThen -> equal(find('.message-comment.unread .comment-body').text(), 'Unread comment') click(".load-all-comments") andThen -> equal(find('.message-comment.unread').length, 0) equal(find('.message-comment').length, 10, 'All messages displayed')
153440
module 'Integration: Commenting', teardown: -> ETahi.reset() setup: -> setupApp(integration: true) dashboard = dashboards: [ id: 1 user_id: fakeUser.id lite_paper_ids: [1] ] collaborators = [ id: "35" full_name: "<NAME>" info: "testroles2, collaborator" ] server.respondWith 'GET', "/dashboards", [ 200, {"Content-Type": "application/json"}, JSON.stringify dashboard ] server.respondWith 'PUT', /\/tasks\/\d+/, [ 204, {"Content-Type": "application/json"}, JSON.stringify {} ] test 'A card with more than 5 comments has the show all comments button', -> expect(2) ef = ETahi.Factory r = _.range(10) comments = _.map(r, (n) -> ef.createRecord('Comment', commenter_id: fakeUser.id task: {type: 'Task', id: 1} body: "My comment-#{n}" created_at: new Date().toISOString() )) [paper, task, records...] = ETahi.Setups.paperWithTask('Task' id: 1 title: "Commenting Time" participant_ids: [fakeUser.id] comment_ids: _.pluck(comments, 'id') ) ef = ETahi.Factory paperPayload = ef.createPayload('paper') paperPayload.addRecords(records.concat(paper, task, fakeUser, comments)) server.respondWith 'GET', "/papers/#{paper.id}", [ 200, {"Content-Type": "application/json"}, JSON.stringify paperPayload.toJSON() ] visit("/papers/#{paper.id}/tasks/#{task.id}") andThen -> ok(find('.load-all-comments').length == 1) equal(find('.message-comment').length, 5, 'Only 5 messages displayed') test 'A card with less than 5 comments doesnt have the show all comments button', -> expect(2) ef = ETahi.Factory r = _.range(3) comments = _.map(r, (n) -> ef.createRecord('Comment', commenter_id: fakeUser.id task: {type: 'Task', id: 1} body: "My comment-#{n}" created_at: new Date().toISOString() )) [paper, task, records...] = ETahi.Setups.paperWithTask('Task' id: 1 title: "Commenting Time" participant_ids: [fakeUser.id] comment_ids: _.pluck(comments, 'id') ) ef = ETahi.Factory paperPayload = ef.createPayload('paper') paperPayload.addRecords(records.concat(paper, task, fakeUser, comments)) server.respondWith 'GET', "/papers/#{paper.id}", [ 200, {"Content-Type": "application/json"}, JSON.stringify paperPayload.toJSON() ] visit("/papers/#{paper.id}/tasks/#{task.id}") andThen -> ok(find('.load-all-comments').length == 0) equal(find('.message-comment').length, 3, 'All messages displayed') test 'A message card with a commentLook shows up as unread and updates its commentLook', -> expect(2) ef = ETahi.Factory commenter = ef.createRecord 'User', id: 999 full_name: "<NAME>" username: "confucius" email: "<EMAIL>" comment = ef.createRecord('Comment', commenter_id: commenter.id task: {type: 'Task', id: 1} body: "Unread comment" created_at: new Date().toISOString() ) commentLook = ef.createRecord('CommentLook', id: 1) ef.setForeignKey(comment, commentLook, {inverse: 'comment'}) ef.setForeignKey(fakeUser, commentLook, {inverse: 'user'}) comment.comment_look_ids = [commentLook.id] [paper, task, records...] = ETahi.Setups.paperWithTask('Task' title: "Commenting Time" participant_ids: [commenter.id, fakeUser.id] comment_ids: [comment.id] ) paperPayload = ef.createPayload('paper') paperPayload.addRecords(records.concat(paper, task, fakeUser, commenter, comment, commentLook)) server.respondWith 'GET', "/papers/#{paper.id}", [ 200, {"Content-Type": "application/json"}, JSON.stringify paperPayload.toJSON() ] server.respondWith 'PUT', /\/comment_looks\/\d+/, [ 204, {"Content-Type": "application/json"}, JSON.stringify {} ] visit("/papers/#{paper.id}/tasks/#{task.id}") andThen -> ok(_.findWhere(server.requests, {method: "PUT", url: "/comment_looks/1"})) equal(find('.message-comment.unread .comment-body').text(), "Unread comment") test 'Showing all comments shows them.', -> expect(1) ef = ETahi.Factory r = _.range(10) comments = _.map(r, (n) -> ef.createRecord('Comment', commenter_id: fakeUser.id task: {type: 'Task', id: 1} body: "My comment-#{n}" )) [paper, task, records...] = ETahi.Setups.paperWithTask('Task' id: 1 title: "Commenting Time" participant_ids: [fakeUser.id] comment_ids: _.pluck(comments, 'id') ) ef = ETahi.Factory paperPayload = ef.createPayload('paper') paperPayload.addRecords(records.concat(paper, task, fakeUser, comments)) server.respondWith 'GET', "/papers/#{paper.id}", [ 200, {"Content-Type": "application/json"}, JSON.stringify paperPayload.toJSON() ] visit("/papers/#{paper.id}/tasks/#{task.id}") click(".load-all-comments") andThen -> equal(find('.message-comment').length, 10, 'All messages displayed') test 'Unread comments do not stay unread when showing all comments if they were already shown', -> expect(3) ef = ETahi.Factory commenter = ef.createRecord 'User', id: 999 full_name: "<NAME>" username: "confucius" email: "<EMAIL>" r = _.range(10) comments = _.map(r, (n) -> ef.createRecord('Comment', commenter_id: commenter.id task: {type: 'Task', id: 1} body: "My comment-#{n}" # These can't all be created at the exact same time created_at: new Date(Date.now() + n).toISOString() )) #make the most recent comment unread recentComment = _.last(comments) recentComment.body = "Unread comment" commentLook = ef.createRecord('CommentLook', id: 1) ef.setForeignKey(recentComment, commentLook, {inverse: 'comment'}) ef.setForeignKey(fakeUser, commentLook, {inverse: 'user'}) recentComment.comment_look_ids = [commentLook.id] [paper, task, records...] = ETahi.Setups.paperWithTask('Task' id: 1 title: "Commenting Time" participant_ids: [commenter.id, fakeUser.id] comment_ids: _.pluck(comments, 'id') ) paperPayload = ef.createPayload('paper') paperPayload.addRecords(records.concat(paper, task, fakeUser, commenter, comments, commentLook)) server.respondWith 'GET', "/papers/#{paper.id}", [ 200, {"Content-Type": "application/json"}, JSON.stringify paperPayload.toJSON() ] server.respondWith 'PUT', /\/comment_looks\/\d+/, [ 204, {"Content-Type": "application/json"}, JSON.stringify {} ] visit("/papers/#{paper.id}/tasks/#{task.id}") andThen -> equal(find('.message-comment.unread .comment-body').text(), 'Unread comment') click(".load-all-comments") andThen -> equal(find('.message-comment.unread').length, 0) equal(find('.message-comment').length, 10, 'All messages displayed')
true
module 'Integration: Commenting', teardown: -> ETahi.reset() setup: -> setupApp(integration: true) dashboard = dashboards: [ id: 1 user_id: fakeUser.id lite_paper_ids: [1] ] collaborators = [ id: "35" full_name: "PI:NAME:<NAME>END_PI" info: "testroles2, collaborator" ] server.respondWith 'GET', "/dashboards", [ 200, {"Content-Type": "application/json"}, JSON.stringify dashboard ] server.respondWith 'PUT', /\/tasks\/\d+/, [ 204, {"Content-Type": "application/json"}, JSON.stringify {} ] test 'A card with more than 5 comments has the show all comments button', -> expect(2) ef = ETahi.Factory r = _.range(10) comments = _.map(r, (n) -> ef.createRecord('Comment', commenter_id: fakeUser.id task: {type: 'Task', id: 1} body: "My comment-#{n}" created_at: new Date().toISOString() )) [paper, task, records...] = ETahi.Setups.paperWithTask('Task' id: 1 title: "Commenting Time" participant_ids: [fakeUser.id] comment_ids: _.pluck(comments, 'id') ) ef = ETahi.Factory paperPayload = ef.createPayload('paper') paperPayload.addRecords(records.concat(paper, task, fakeUser, comments)) server.respondWith 'GET', "/papers/#{paper.id}", [ 200, {"Content-Type": "application/json"}, JSON.stringify paperPayload.toJSON() ] visit("/papers/#{paper.id}/tasks/#{task.id}") andThen -> ok(find('.load-all-comments').length == 1) equal(find('.message-comment').length, 5, 'Only 5 messages displayed') test 'A card with less than 5 comments doesnt have the show all comments button', -> expect(2) ef = ETahi.Factory r = _.range(3) comments = _.map(r, (n) -> ef.createRecord('Comment', commenter_id: fakeUser.id task: {type: 'Task', id: 1} body: "My comment-#{n}" created_at: new Date().toISOString() )) [paper, task, records...] = ETahi.Setups.paperWithTask('Task' id: 1 title: "Commenting Time" participant_ids: [fakeUser.id] comment_ids: _.pluck(comments, 'id') ) ef = ETahi.Factory paperPayload = ef.createPayload('paper') paperPayload.addRecords(records.concat(paper, task, fakeUser, comments)) server.respondWith 'GET', "/papers/#{paper.id}", [ 200, {"Content-Type": "application/json"}, JSON.stringify paperPayload.toJSON() ] visit("/papers/#{paper.id}/tasks/#{task.id}") andThen -> ok(find('.load-all-comments').length == 0) equal(find('.message-comment').length, 3, 'All messages displayed') test 'A message card with a commentLook shows up as unread and updates its commentLook', -> expect(2) ef = ETahi.Factory commenter = ef.createRecord 'User', id: 999 full_name: "PI:NAME:<NAME>END_PI" username: "confucius" email: "PI:EMAIL:<EMAIL>END_PI" comment = ef.createRecord('Comment', commenter_id: commenter.id task: {type: 'Task', id: 1} body: "Unread comment" created_at: new Date().toISOString() ) commentLook = ef.createRecord('CommentLook', id: 1) ef.setForeignKey(comment, commentLook, {inverse: 'comment'}) ef.setForeignKey(fakeUser, commentLook, {inverse: 'user'}) comment.comment_look_ids = [commentLook.id] [paper, task, records...] = ETahi.Setups.paperWithTask('Task' title: "Commenting Time" participant_ids: [commenter.id, fakeUser.id] comment_ids: [comment.id] ) paperPayload = ef.createPayload('paper') paperPayload.addRecords(records.concat(paper, task, fakeUser, commenter, comment, commentLook)) server.respondWith 'GET', "/papers/#{paper.id}", [ 200, {"Content-Type": "application/json"}, JSON.stringify paperPayload.toJSON() ] server.respondWith 'PUT', /\/comment_looks\/\d+/, [ 204, {"Content-Type": "application/json"}, JSON.stringify {} ] visit("/papers/#{paper.id}/tasks/#{task.id}") andThen -> ok(_.findWhere(server.requests, {method: "PUT", url: "/comment_looks/1"})) equal(find('.message-comment.unread .comment-body').text(), "Unread comment") test 'Showing all comments shows them.', -> expect(1) ef = ETahi.Factory r = _.range(10) comments = _.map(r, (n) -> ef.createRecord('Comment', commenter_id: fakeUser.id task: {type: 'Task', id: 1} body: "My comment-#{n}" )) [paper, task, records...] = ETahi.Setups.paperWithTask('Task' id: 1 title: "Commenting Time" participant_ids: [fakeUser.id] comment_ids: _.pluck(comments, 'id') ) ef = ETahi.Factory paperPayload = ef.createPayload('paper') paperPayload.addRecords(records.concat(paper, task, fakeUser, comments)) server.respondWith 'GET', "/papers/#{paper.id}", [ 200, {"Content-Type": "application/json"}, JSON.stringify paperPayload.toJSON() ] visit("/papers/#{paper.id}/tasks/#{task.id}") click(".load-all-comments") andThen -> equal(find('.message-comment').length, 10, 'All messages displayed') test 'Unread comments do not stay unread when showing all comments if they were already shown', -> expect(3) ef = ETahi.Factory commenter = ef.createRecord 'User', id: 999 full_name: "PI:NAME:<NAME>END_PI" username: "confucius" email: "PI:EMAIL:<EMAIL>END_PI" r = _.range(10) comments = _.map(r, (n) -> ef.createRecord('Comment', commenter_id: commenter.id task: {type: 'Task', id: 1} body: "My comment-#{n}" # These can't all be created at the exact same time created_at: new Date(Date.now() + n).toISOString() )) #make the most recent comment unread recentComment = _.last(comments) recentComment.body = "Unread comment" commentLook = ef.createRecord('CommentLook', id: 1) ef.setForeignKey(recentComment, commentLook, {inverse: 'comment'}) ef.setForeignKey(fakeUser, commentLook, {inverse: 'user'}) recentComment.comment_look_ids = [commentLook.id] [paper, task, records...] = ETahi.Setups.paperWithTask('Task' id: 1 title: "Commenting Time" participant_ids: [commenter.id, fakeUser.id] comment_ids: _.pluck(comments, 'id') ) paperPayload = ef.createPayload('paper') paperPayload.addRecords(records.concat(paper, task, fakeUser, commenter, comments, commentLook)) server.respondWith 'GET', "/papers/#{paper.id}", [ 200, {"Content-Type": "application/json"}, JSON.stringify paperPayload.toJSON() ] server.respondWith 'PUT', /\/comment_looks\/\d+/, [ 204, {"Content-Type": "application/json"}, JSON.stringify {} ] visit("/papers/#{paper.id}/tasks/#{task.id}") andThen -> equal(find('.message-comment.unread .comment-body').text(), 'Unread comment') click(".load-all-comments") andThen -> equal(find('.message-comment.unread').length, 0) equal(find('.message-comment').length, 10, 'All messages displayed')
[ { "context": "###\nCopyright (c) 2002-2013 \"Neo Technology,\"\nNetwork Engine for Objects in Lund AB [http://n", "end": 43, "score": 0.6831578612327576, "start": 33, "tag": "NAME", "value": "Technology" } ]
community/server/src/main/coffeescript/neo4j/webadmin/modules/connectionmonitor/ConnectionMonitor.coffee
baojie/neo4j
1
### Copyright (c) 2002-2013 "Neo Technology," Network Engine for Objects in Lund AB [http://neotechnology.com] This file is part of Neo4j. Neo4j is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ### define( ['./connection_lost' 'lib/amd/jQuery'], (template, $) -> CONNECTION_LOST_EVENT = "web.connection_lost" class ConnectionMonitor visible : false init : (appState) -> @db = appState.getServer() @db.bind CONNECTION_LOST_EVENT, @connectionLost # Empty heartbeat listener, # makes sure we continiously # check if the server is alive. @db.heartbeat.addListener -> # Make sure any images in the connection # lost splash have been pre-loaded, so we # have them in case the server dies. splash = $(template()) $("body").append(splash) setTimeout((-> splash.hide()),0) connectionLost : => if not @visible @visible = true connectionLostSplash = $(template()) $("body").append(connectionLostSplash) hideSplash = => @visible = false connectionLostSplash.fadeOut 200, -> connectionLostSplash.remove() @db.heartbeat.waitForPulse hideSplash )
146004
### Copyright (c) 2002-2013 "Neo <NAME>," Network Engine for Objects in Lund AB [http://neotechnology.com] This file is part of Neo4j. Neo4j is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ### define( ['./connection_lost' 'lib/amd/jQuery'], (template, $) -> CONNECTION_LOST_EVENT = "web.connection_lost" class ConnectionMonitor visible : false init : (appState) -> @db = appState.getServer() @db.bind CONNECTION_LOST_EVENT, @connectionLost # Empty heartbeat listener, # makes sure we continiously # check if the server is alive. @db.heartbeat.addListener -> # Make sure any images in the connection # lost splash have been pre-loaded, so we # have them in case the server dies. splash = $(template()) $("body").append(splash) setTimeout((-> splash.hide()),0) connectionLost : => if not @visible @visible = true connectionLostSplash = $(template()) $("body").append(connectionLostSplash) hideSplash = => @visible = false connectionLostSplash.fadeOut 200, -> connectionLostSplash.remove() @db.heartbeat.waitForPulse hideSplash )
true
### Copyright (c) 2002-2013 "Neo PI:NAME:<NAME>END_PI," Network Engine for Objects in Lund AB [http://neotechnology.com] This file is part of Neo4j. Neo4j is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ### define( ['./connection_lost' 'lib/amd/jQuery'], (template, $) -> CONNECTION_LOST_EVENT = "web.connection_lost" class ConnectionMonitor visible : false init : (appState) -> @db = appState.getServer() @db.bind CONNECTION_LOST_EVENT, @connectionLost # Empty heartbeat listener, # makes sure we continiously # check if the server is alive. @db.heartbeat.addListener -> # Make sure any images in the connection # lost splash have been pre-loaded, so we # have them in case the server dies. splash = $(template()) $("body").append(splash) setTimeout((-> splash.hide()),0) connectionLost : => if not @visible @visible = true connectionLostSplash = $(template()) $("body").append(connectionLostSplash) hideSplash = => @visible = false connectionLostSplash.fadeOut 200, -> connectionLostSplash.remove() @db.heartbeat.waitForPulse hideSplash )
[ { "context": "# Description\n# Philippe is standing on it.\n#\n# Dependencies:\n# \"htmlpars", "end": 26, "score": 0.9989524483680725, "start": 18, "tag": "NAME", "value": "Philippe" }, { "context": "ddest thing, according to Lie Bot\n#\n# Author:\n# 1000hz\n\nhtmlparser = requi...
src/scripts/achewood.coffee
fourkitchens/hubot-scripts
1
# Description # Philippe is standing on it. # # Dependencies: # "htmlparser": "1.7.6" # "soupselect": "0.2.0" # # Configuration: # None # # Commands: # hubot achewood - A random Achewood comic # hubot achewood current - The most recent Achewood comic # hubot achewood <date> - Achewood comic from <date> - mm/dd/yyyy format # hubot saddest thing - The saddest thing, according to Lie Bot # # Author: # 1000hz htmlparser = require "htmlparser" Select = require("soupselect").select module.exports = (robot) -> withDate = (date) -> "http://achewood.com/index.php?date=#{date}" fetchAchewood = (msg, url) -> msg.http(url).get() (err, res, body) -> handler = new htmlparser.DefaultHandler() parser = new htmlparser.Parser(handler) parser.parseComplete(body) img = Select handler.dom, "img.comic" comic = img[0].attribs msg.send "http://achewood.com" + comic.src + "#.png" msg.send comic.title robot.respond /achewood\s?((0[1-9]|1[0-2]).(0[1-9]|[1-2][0-9]|3[0-1]).(20\d{2})$|current)?/i, (msg) -> if msg.match[1] == undefined msg.http("http://www.ohnorobot.com/random.pl?comic=636") .get() (err, res, body) -> fetchAchewood(msg, res.headers['location']) else if msg.match[1] == "current" fetchAchewood(msg, "http://achewood.com") else date = "#{msg.match[2]}#{msg.match[3]}#{msg.match[4]}" fetchAchewood(msg, withDate(date)) robot.respond /.*saddest thing\?*/i, (msg) -> saddest = msg.random ["06022003", "11052001", "09052006", "07302007"] fetchAchewood(msg, withDate(saddest))
68155
# Description # <NAME> is standing on it. # # Dependencies: # "htmlparser": "1.7.6" # "soupselect": "0.2.0" # # Configuration: # None # # Commands: # hubot achewood - A random Achewood comic # hubot achewood current - The most recent Achewood comic # hubot achewood <date> - Achewood comic from <date> - mm/dd/yyyy format # hubot saddest thing - The saddest thing, according to Lie Bot # # Author: # 1000hz htmlparser = require "htmlparser" Select = require("soupselect").select module.exports = (robot) -> withDate = (date) -> "http://achewood.com/index.php?date=#{date}" fetchAchewood = (msg, url) -> msg.http(url).get() (err, res, body) -> handler = new htmlparser.DefaultHandler() parser = new htmlparser.Parser(handler) parser.parseComplete(body) img = Select handler.dom, "img.comic" comic = img[0].attribs msg.send "http://achewood.com" + comic.src + "#.png" msg.send comic.title robot.respond /achewood\s?((0[1-9]|1[0-2]).(0[1-9]|[1-2][0-9]|3[0-1]).(20\d{2})$|current)?/i, (msg) -> if msg.match[1] == undefined msg.http("http://www.ohnorobot.com/random.pl?comic=636") .get() (err, res, body) -> fetchAchewood(msg, res.headers['location']) else if msg.match[1] == "current" fetchAchewood(msg, "http://achewood.com") else date = "#{msg.match[2]}#{msg.match[3]}#{msg.match[4]}" fetchAchewood(msg, withDate(date)) robot.respond /.*saddest thing\?*/i, (msg) -> saddest = msg.random ["06022003", "11052001", "09052006", "07302007"] fetchAchewood(msg, withDate(saddest))
true
# Description # PI:NAME:<NAME>END_PI is standing on it. # # Dependencies: # "htmlparser": "1.7.6" # "soupselect": "0.2.0" # # Configuration: # None # # Commands: # hubot achewood - A random Achewood comic # hubot achewood current - The most recent Achewood comic # hubot achewood <date> - Achewood comic from <date> - mm/dd/yyyy format # hubot saddest thing - The saddest thing, according to Lie Bot # # Author: # 1000hz htmlparser = require "htmlparser" Select = require("soupselect").select module.exports = (robot) -> withDate = (date) -> "http://achewood.com/index.php?date=#{date}" fetchAchewood = (msg, url) -> msg.http(url).get() (err, res, body) -> handler = new htmlparser.DefaultHandler() parser = new htmlparser.Parser(handler) parser.parseComplete(body) img = Select handler.dom, "img.comic" comic = img[0].attribs msg.send "http://achewood.com" + comic.src + "#.png" msg.send comic.title robot.respond /achewood\s?((0[1-9]|1[0-2]).(0[1-9]|[1-2][0-9]|3[0-1]).(20\d{2})$|current)?/i, (msg) -> if msg.match[1] == undefined msg.http("http://www.ohnorobot.com/random.pl?comic=636") .get() (err, res, body) -> fetchAchewood(msg, res.headers['location']) else if msg.match[1] == "current" fetchAchewood(msg, "http://achewood.com") else date = "#{msg.match[2]}#{msg.match[3]}#{msg.match[4]}" fetchAchewood(msg, withDate(date)) robot.respond /.*saddest thing\?*/i, (msg) -> saddest = msg.random ["06022003", "11052001", "09052006", "07302007"] fetchAchewood(msg, withDate(saddest))
[ { "context": "--------------\n# Copyright Joe Drago 2018.\n# Distributed under the Boost Softw", "end": 123, "score": 0.9998249411582947, "start": 114, "tag": "NAME", "value": "Joe Drago" } ]
lib/templates/src/coffee/PixelsView.coffee
TEAMCHINA/colorist
0
# --------------------------------------------------------------------------- # Copyright Joe Drago 2018. # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) # --------------------------------------------------------------------------- React = require 'react' DOM = require 'react-dom' cm = require './colormath' tags = require './tags' utils = require './utils' {el, div, table, tr, td, tbody} = require './tags' TopBar = require './TopBar' ImageRenderer = require './ImageRenderer' InfoPanel = require './InfoPanel' StructArray = require './StructArray' as8Bit = (v, depth) -> return utils.clamp(Math.round(v / ((1 << depth)-1) * 255), 0, 255) class PixelsView extends React.Component @defaultProps: app: null constructor: (props) -> super props @state = x: -1 y: -1 @rawPixels = new StructArray(COLORIST_DATA.raw) setPos: (x, y) -> @setState { x: x, y: y } render: -> elements = [] elements.push el TopBar, { key: "TopBar" app: @props.app } infoPanelWidth = 300 title = "Pixels" image = COLORIST_DATA.visual maxNits = COLORIST_DATA.icc.luminance if @props.name == 'srgb100' title = "sRGB Highlight (100)" image = COLORIST_DATA.srgb100.visual maxNits = 100 else if @props.name == 'srgb300' title = "sRGB Highlight (300)" image = COLORIST_DATA.srgb300.visual maxNits = 300 overbrightScale = COLORIST_DATA.icc.luminance / maxNits elements.push el ImageRenderer, { width: @props.width - infoPanelWidth height: @props.height url: image listener: this } sections = [] horseshoeX = -1 horseshoeY = -1 if (@state.x >= 0) and (@state.y >= 0) pixel = @rawPixels.get(@state.x, @state.y) sections.push { name: "Raw" rows: [ ["R", pixel.r, "", as8Bit(pixel.r, COLORIST_DATA.depth)] ["G", pixel.g, "", as8Bit(pixel.g, COLORIST_DATA.depth)] ["B", pixel.b, "", as8Bit(pixel.b, COLORIST_DATA.depth)] ["A", pixel.a, "", as8Bit(pixel.a, COLORIST_DATA.depth)] ] } # floating point, (inverse) gamma space floatIG = cm.rawToFloat([pixel.r, pixel.g, pixel.b, pixel.a], COLORIST_DATA.depth) # floating point, linear space if(COLORIST_DATA.icc.pq) floatLin = cm.vecPQ_EOTF(floatIG) else floatLin = cm.vecPow(floatIG, COLORIST_DATA.icc.gamma) toXYZ = cm.matDeriveRGBToXYZ(COLORIST_DATA.icc.primaries) XYZ = cm.matEval(toXYZ, floatLin) xyY = cm.convertXYZtoXYY(XYZ, [COLORIST_DATA.icc.primaries[6], COLORIST_DATA.icc.primaries[7]]) pixelLuminance = xyY[2] * COLORIST_DATA.icc.luminance maxPixelLuminance = maxNits * cm.calcMaxY(xyY, COLORIST_DATA.icc.primaries) sections.push { name: "xyY" rows: [ ["x", utils.fr(xyY[0], 4)] ["y", utils.fr(xyY[1], 4)] ["Y", utils.fr(xyY[2], 4)] ["Nits:", utils.fr(pixelLuminance, 2), "/", utils.fr(maxPixelLuminance, 2)] ] } horseshoeX = xyY[0] horseshoeY = xyY[1] if @props.name != 'pixels' overbright = cm.calcOverbright(xyY, overbrightScale, COLORIST_DATA.icc.primaries) outofSRGB = cm.calcOutofSRGB(xyY[0], xyY[1], COLORIST_DATA.icc.primaries) luminancePercentage = 100 * (pixelLuminance / maxPixelLuminance) if luminancePercentage > 100 luminancePercentage = utils.fr(luminancePercentage, 2) + "%" else luminancePercentage = "--" if outofSRGB > 0 outofSRGB = utils.fr(100 * outofSRGB, 2) + "%" else outofSRGB = "--" sections.push { name: "sRGB Overranging (#{maxNits} nits)" rows: [ ["Luminance", luminancePercentage] ["Out Gamut", outofSRGB] ] } elements.push el InfoPanel, { title: title left: @props.width - infoPanelWidth width: infoPanelWidth height: @props.height url: COLORIST_DATA.uri sections: sections usesPixelPos: true x: @state.x y: @state.y horseshoeX: horseshoeX horseshoeY: horseshoeY } return elements module.exports = PixelsView
141578
# --------------------------------------------------------------------------- # Copyright <NAME> 2018. # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) # --------------------------------------------------------------------------- React = require 'react' DOM = require 'react-dom' cm = require './colormath' tags = require './tags' utils = require './utils' {el, div, table, tr, td, tbody} = require './tags' TopBar = require './TopBar' ImageRenderer = require './ImageRenderer' InfoPanel = require './InfoPanel' StructArray = require './StructArray' as8Bit = (v, depth) -> return utils.clamp(Math.round(v / ((1 << depth)-1) * 255), 0, 255) class PixelsView extends React.Component @defaultProps: app: null constructor: (props) -> super props @state = x: -1 y: -1 @rawPixels = new StructArray(COLORIST_DATA.raw) setPos: (x, y) -> @setState { x: x, y: y } render: -> elements = [] elements.push el TopBar, { key: "TopBar" app: @props.app } infoPanelWidth = 300 title = "Pixels" image = COLORIST_DATA.visual maxNits = COLORIST_DATA.icc.luminance if @props.name == 'srgb100' title = "sRGB Highlight (100)" image = COLORIST_DATA.srgb100.visual maxNits = 100 else if @props.name == 'srgb300' title = "sRGB Highlight (300)" image = COLORIST_DATA.srgb300.visual maxNits = 300 overbrightScale = COLORIST_DATA.icc.luminance / maxNits elements.push el ImageRenderer, { width: @props.width - infoPanelWidth height: @props.height url: image listener: this } sections = [] horseshoeX = -1 horseshoeY = -1 if (@state.x >= 0) and (@state.y >= 0) pixel = @rawPixels.get(@state.x, @state.y) sections.push { name: "Raw" rows: [ ["R", pixel.r, "", as8Bit(pixel.r, COLORIST_DATA.depth)] ["G", pixel.g, "", as8Bit(pixel.g, COLORIST_DATA.depth)] ["B", pixel.b, "", as8Bit(pixel.b, COLORIST_DATA.depth)] ["A", pixel.a, "", as8Bit(pixel.a, COLORIST_DATA.depth)] ] } # floating point, (inverse) gamma space floatIG = cm.rawToFloat([pixel.r, pixel.g, pixel.b, pixel.a], COLORIST_DATA.depth) # floating point, linear space if(COLORIST_DATA.icc.pq) floatLin = cm.vecPQ_EOTF(floatIG) else floatLin = cm.vecPow(floatIG, COLORIST_DATA.icc.gamma) toXYZ = cm.matDeriveRGBToXYZ(COLORIST_DATA.icc.primaries) XYZ = cm.matEval(toXYZ, floatLin) xyY = cm.convertXYZtoXYY(XYZ, [COLORIST_DATA.icc.primaries[6], COLORIST_DATA.icc.primaries[7]]) pixelLuminance = xyY[2] * COLORIST_DATA.icc.luminance maxPixelLuminance = maxNits * cm.calcMaxY(xyY, COLORIST_DATA.icc.primaries) sections.push { name: "xyY" rows: [ ["x", utils.fr(xyY[0], 4)] ["y", utils.fr(xyY[1], 4)] ["Y", utils.fr(xyY[2], 4)] ["Nits:", utils.fr(pixelLuminance, 2), "/", utils.fr(maxPixelLuminance, 2)] ] } horseshoeX = xyY[0] horseshoeY = xyY[1] if @props.name != 'pixels' overbright = cm.calcOverbright(xyY, overbrightScale, COLORIST_DATA.icc.primaries) outofSRGB = cm.calcOutofSRGB(xyY[0], xyY[1], COLORIST_DATA.icc.primaries) luminancePercentage = 100 * (pixelLuminance / maxPixelLuminance) if luminancePercentage > 100 luminancePercentage = utils.fr(luminancePercentage, 2) + "%" else luminancePercentage = "--" if outofSRGB > 0 outofSRGB = utils.fr(100 * outofSRGB, 2) + "%" else outofSRGB = "--" sections.push { name: "sRGB Overranging (#{maxNits} nits)" rows: [ ["Luminance", luminancePercentage] ["Out Gamut", outofSRGB] ] } elements.push el InfoPanel, { title: title left: @props.width - infoPanelWidth width: infoPanelWidth height: @props.height url: COLORIST_DATA.uri sections: sections usesPixelPos: true x: @state.x y: @state.y horseshoeX: horseshoeX horseshoeY: horseshoeY } return elements module.exports = PixelsView
true
# --------------------------------------------------------------------------- # Copyright PI:NAME:<NAME>END_PI 2018. # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) # --------------------------------------------------------------------------- React = require 'react' DOM = require 'react-dom' cm = require './colormath' tags = require './tags' utils = require './utils' {el, div, table, tr, td, tbody} = require './tags' TopBar = require './TopBar' ImageRenderer = require './ImageRenderer' InfoPanel = require './InfoPanel' StructArray = require './StructArray' as8Bit = (v, depth) -> return utils.clamp(Math.round(v / ((1 << depth)-1) * 255), 0, 255) class PixelsView extends React.Component @defaultProps: app: null constructor: (props) -> super props @state = x: -1 y: -1 @rawPixels = new StructArray(COLORIST_DATA.raw) setPos: (x, y) -> @setState { x: x, y: y } render: -> elements = [] elements.push el TopBar, { key: "TopBar" app: @props.app } infoPanelWidth = 300 title = "Pixels" image = COLORIST_DATA.visual maxNits = COLORIST_DATA.icc.luminance if @props.name == 'srgb100' title = "sRGB Highlight (100)" image = COLORIST_DATA.srgb100.visual maxNits = 100 else if @props.name == 'srgb300' title = "sRGB Highlight (300)" image = COLORIST_DATA.srgb300.visual maxNits = 300 overbrightScale = COLORIST_DATA.icc.luminance / maxNits elements.push el ImageRenderer, { width: @props.width - infoPanelWidth height: @props.height url: image listener: this } sections = [] horseshoeX = -1 horseshoeY = -1 if (@state.x >= 0) and (@state.y >= 0) pixel = @rawPixels.get(@state.x, @state.y) sections.push { name: "Raw" rows: [ ["R", pixel.r, "", as8Bit(pixel.r, COLORIST_DATA.depth)] ["G", pixel.g, "", as8Bit(pixel.g, COLORIST_DATA.depth)] ["B", pixel.b, "", as8Bit(pixel.b, COLORIST_DATA.depth)] ["A", pixel.a, "", as8Bit(pixel.a, COLORIST_DATA.depth)] ] } # floating point, (inverse) gamma space floatIG = cm.rawToFloat([pixel.r, pixel.g, pixel.b, pixel.a], COLORIST_DATA.depth) # floating point, linear space if(COLORIST_DATA.icc.pq) floatLin = cm.vecPQ_EOTF(floatIG) else floatLin = cm.vecPow(floatIG, COLORIST_DATA.icc.gamma) toXYZ = cm.matDeriveRGBToXYZ(COLORIST_DATA.icc.primaries) XYZ = cm.matEval(toXYZ, floatLin) xyY = cm.convertXYZtoXYY(XYZ, [COLORIST_DATA.icc.primaries[6], COLORIST_DATA.icc.primaries[7]]) pixelLuminance = xyY[2] * COLORIST_DATA.icc.luminance maxPixelLuminance = maxNits * cm.calcMaxY(xyY, COLORIST_DATA.icc.primaries) sections.push { name: "xyY" rows: [ ["x", utils.fr(xyY[0], 4)] ["y", utils.fr(xyY[1], 4)] ["Y", utils.fr(xyY[2], 4)] ["Nits:", utils.fr(pixelLuminance, 2), "/", utils.fr(maxPixelLuminance, 2)] ] } horseshoeX = xyY[0] horseshoeY = xyY[1] if @props.name != 'pixels' overbright = cm.calcOverbright(xyY, overbrightScale, COLORIST_DATA.icc.primaries) outofSRGB = cm.calcOutofSRGB(xyY[0], xyY[1], COLORIST_DATA.icc.primaries) luminancePercentage = 100 * (pixelLuminance / maxPixelLuminance) if luminancePercentage > 100 luminancePercentage = utils.fr(luminancePercentage, 2) + "%" else luminancePercentage = "--" if outofSRGB > 0 outofSRGB = utils.fr(100 * outofSRGB, 2) + "%" else outofSRGB = "--" sections.push { name: "sRGB Overranging (#{maxNits} nits)" rows: [ ["Luminance", luminancePercentage] ["Out Gamut", outofSRGB] ] } elements.push el InfoPanel, { title: title left: @props.width - infoPanelWidth width: infoPanelWidth height: @props.height url: COLORIST_DATA.uri sections: sections usesPixelPos: true x: @state.x y: @state.y horseshoeX: horseshoeX horseshoeY: horseshoeY } return elements module.exports = PixelsView
[ { "context": "led\")\n },\n {\n name: \"2nd\"\n processor: \"reportDone\"\n ", "end": 13297, "score": 0.6828014850616455, "start": 13296, "tag": "NAME", "value": "2" }, { "context": "nt arrays\", ->\n people = [\n { first: ...
client/src/tests/tests.spec.coffee
bcfuchs/RedWire
0
# Get alias for the global scope globals = @ compileExpression = (expression) -> RW.compileExpression(expression, eval) describe "RedWire", -> beforeEach -> @addMatchers toDeeplyEqual: (expected) -> _.isEqual(@actual, expected) toBeEmpty: () -> @actual.length == 0 describe "memory", -> it "can remove value from array", -> a = v: [10..15] b = v: [10, 12, 13, 14, 15] # Missing 11 patches = RW.makePatches(a, b) patchResult = RW.applyPatches(patches, a) expect(patchResult).toDeeplyEqual(b) it "can be patched", -> # Create old data, new data, and the patches between oldData = a: 1 b: b1: true b2: "hi" newData = b: b1: true b2: "there" c: bob: "is cool" # Create the result via patches patches = RW.makePatches(oldData, newData) result = RW.applyPatches(patches, oldData) # The new data and old data should still be valid and different expect(oldData).not.toDeeplyEqual(newData) expect(result).toDeeplyEqual(newData) it "detects conflicting patches", -> # Test changing same attribute oldData = a: b: 1 c: 2 newDataA = a: b: 2 newDataB = a: b: 3 c: 2 patchesA = RW.makePatches(oldData, newDataA, "a") patchesB = RW.makePatches(oldData, newDataB, "b") allPatches = RW.concatenate(patchesA, patchesB) conflicts = RW.detectPatchConflicts(allPatches) expect(conflicts.length).toBe(1) expect(conflicts[0].path).toBe("/a/b") # Test child attribute oldData = a: b: 1 newDataA = a: b: c: 2 newDataB = a: b: 3 patchesA = RW.makePatches(oldData, newDataA, "a") patchesB = RW.makePatches(oldData, newDataB, "b") allPatches = RW.concatenate(patchesA, patchesB) conflicts = RW.detectPatchConflicts(allPatches) expect(conflicts.length).toBe(1) expect(conflicts[0].path).toBe("/a/b") # Test no conflict oldData = a: b: 1 c: 2 newDataA = a: b: 2 c: 2 newDataB = a: b: 1 c: 3 patchesA = RW.makePatches(oldData, newDataA, "a") patchesB = RW.makePatches(oldData, newDataB, "b") allPatches = RW.concatenate(patchesA, patchesB) conflicts = RW.detectPatchConflicts(allPatches) expect(conflicts).toBeEmpty() # Issue #299 it "does not consider parent removal as conflict", -> patches = [ { "remove": "/explosions/0", "path": [ "0" ] }, { "replace": "/explosions/0/frame", "value": 65, "path": [ "1", "0", "0" ] } ] conflicts = RW.detectPatchConflicts(patches) expect(conflicts).toBeEmpty() it "adds to and removes from arrays", -> oldData = a: [1, 2, 3] newDataA = a: [1, 2, 3, 4] newDataB = a: [2, 3] patchesA = RW.makePatches(oldData, newDataA, "a") patchesB = RW.makePatches(oldData, newDataB, "b") allPatches = RW.concatenate(patchesA, patchesB) conflicts = RW.detectPatchConflicts(allPatches) expect(conflicts).toBeEmpty() result = RW.applyPatches(allPatches, oldData) expect(result).toDeeplyEqual({ a: [2, 3, 4] }) it "modifies within arrays", -> oldData = a: [{ b: 1 }, { c: 2 }, { f: 5 }, 6] newDataA = a: [{ b: 1 }, { c: -2 }, { d: 3 }, { e: 4 }, { f: 5 }, 6] newDataB = a: [{ b: -1 }, { c: 2 }, { f: 5 }, -6, { g: 7 }] patchesA = RW.makePatches(oldData, newDataA, "a") patchesB = RW.makePatches(oldData, newDataB, "b") allPatches = RW.concatenate(patchesA, patchesB) conflicts = RW.detectPatchConflicts(allPatches) expect(conflicts).toBeEmpty() result = RW.applyPatches(allPatches, oldData) expect(result).toDeeplyEqual({ a: [{ b: -1 }, { c: -2 }, { d: 3 }, { e: 4 }, { f: 5 }, -6, { g: 7 }] }) describe "stimulateCircuits()", -> it "calls processors", -> isCalled = false processors = doNothing: pinDefs: x: direction: "in" default: compileExpression("1") y: direction: "in" default: compileExpression("'z'") update: (pins, transformers, log) -> isCalled = true expect(pins).toDeeplyEqual x: 2 y: "z" board = processor: "doNothing" pins: in: x: compileExpression("1 + 1") constants = new RW.ChipVisitorConstants circuits: main: new RW.Circuit board: board processors: processors RW.stimulateCircuits(constants) expect(isCalled).toBeTruthy() it "calls children of switches", -> timesCalled = 0 processors = doNothing: pinDefs: {} update: -> timesCalled++ switches = doAll: pinDefs: {} handleSignals: -> timesCalled++ board = switch: "doAll" pins: {} children: [ { processor: "doNothing" pins: {} }, { processor: "doNothing" pins: {} } ] constants = new RW.ChipVisitorConstants circuits: main: new RW.Circuit board: board processors: processors switches: switches RW.stimulateCircuits(constants) expect(timesCalled).toEqual(3) it "returns the path for patches", -> memoryData = a: 0 b: 1 message: null ioData = c: 2 processors = increment: pinDefs: value: direction: "inout" update: (pins, transformers, log) -> pins.value++ log: pinDefs: message: null update: (pins, transformers, log) -> log(RW.logLevels.INFO, pins.message) switches = doAll: pinDefs: {} # Transformers must be compiled this way # TODO: create function that does this work for us transformers = {} transformers.logIt = RW.compileTransformer("log(RW.logLevels.INFO, msg); return msg;", ["msg"], eval)(transformers) board = switch: "doAll" pins: {} children: [ { processor: "increment" pins: in: "value": compileExpression("memory.a") out: "memory.a": compileExpression("pins.value") }, { processor: "increment" pins: in: "value": compileExpression("memory.b") out: "memory.b": compileExpression("pins.value") }, { processor: "increment" pins: in: "value": compileExpression("io.c") out: "io.c": compileExpression("pins.value") }, { processor: "log" pins: in: "message": compileExpression("'hi'") }, { emitter: "memory.message": compileExpression("transformers.logIt('hi')") } ] constants = new RW.ChipVisitorConstants circuits: main: new RW.Circuit board: board processors: processors switches: switches transformers: transformers memoryData: main: memoryData ioData: main: ioData results = RW.stimulateCircuits(constants) mainResults = results.circuitResults.main expect(mainResults.memoryPatches.length).toBe(3) for memoryPatch in mainResults.memoryPatches if memoryPatch.replace is "/a" expect(memoryPatch.path).toDeeplyEqual(["0"]) else if memoryPatch.replace is "/b" expect(memoryPatch.path).toDeeplyEqual(["1"]) else if memoryPatch.replace is "/message" expect(memoryPatch.path).toDeeplyEqual(["4"]) else throw new Error("Memory patch affects wrong attribute") expect(mainResults.ioPatches.length).toBe(1) expect(mainResults.ioPatches[0].path).toDeeplyEqual(["2"]) expect(mainResults.logMessages.length).toBe(2) expect(mainResults.logMessages[0].path).toDeeplyEqual(["3"]) expect(mainResults.logMessages[1].path).toDeeplyEqual(["4"]) it "evaluates pins for processors", -> oldMemory = a: 1 b: 10 c: 20 assets = { image: new Image() } processors = adjustMemory: pinDefs: x: direction: "inout" y: direction: "inout" z: direction: "out" d: default: compileExpression("2") e: {} update: (pins, transformers, log) -> pins.x++ pins.y-- pins.z = 30 expect(pins.d).toBe(2) expect(pins.e).toBe(assets.image) board = processor: "adjustMemory" pins: in: x: compileExpression("memory.a") y: compileExpression("memory.b") e: compileExpression("assets.image") out: "memory.a": compileExpression("pins.x") "memory.b": compileExpression("pins.y") "memory.c": compileExpression("pins.z") constants = new RW.ChipVisitorConstants circuits: main: new RW.Circuit board: board processors: processors memoryData: main: oldMemory assets: assets results = RW.stimulateCircuits(constants) newMemory = RW.applyPatches(results.circuitResults.main.memoryPatches, oldMemory) # The new memory should be changed, but the old one shouldn't be expect(oldMemory.a).toBe(1) expect(oldMemory.b).toBe(10) expect(oldMemory.c).toBe(20) expect(newMemory.a).toBe(2) expect(newMemory.b).toBe(9) expect(newMemory.c).toBe(30) it "sends to memory and io", -> oldMemory = a: a1: 1 b: 10 c: "hi" oldIoData = s: a: -1 board = emitter: "memory.a.a1": compileExpression("2") "memory.b": compileExpression("memory.c") "io.s.a": compileExpression("-5") constants = new RW.ChipVisitorConstants circuits: main: new RW.Circuit board: board memoryData: main: oldMemory ioData: main: oldIoData results = RW.stimulateCircuits(constants) newMemory = RW.applyPatches(results.circuitResults.main.memoryPatches, oldMemory) newIoData = RW.applyPatches(results.circuitResults.main.ioPatches, oldIoData) # The new memory and io should be changed, but the old ones shouldn't be expect(oldMemory.a.a1).toBe(1) expect(oldMemory.b).toBe(10) expect(oldIoData.s.a).toBe(-1) expect(newMemory.a.a1).toBe(2) expect(newMemory.b).toBe("hi") expect(newIoData.s.a).toBe(-5) it "checks and adjusts activation", -> memories = [ { activeChild: 0 child0TimesCalled: 0 child1TimesCalled: 0 } ] switches = nextOnDone: pinDefs: activeChild: direction: "inout" default: compileExpression("0") listActiveChildren: (pins, children, transformers, log) -> expect(children).toDeeplyEqual([0, "2nd"]) return [children[pins.activeChild]] handleSignals: (pins, children, activeChildren, signals, transformers, log) -> expect(children).toDeeplyEqual([0, "2nd"]) if signals[pins.activeChild] == RW.signals.DONE pins.activeChild++ if pins.activeChild >= children.length - 1 return RW.signals.DONE processors = reportDone: pinDefs: timesCalled: direction: "inout" update: (pins, transformers, log) -> pins.timesCalled++ return RW.signals.DONE board = switch: "nextOnDone" pins: in: activeChild: compileExpression("memory.activeChild") out: "memory.activeChild": compileExpression("pins.activeChild") children: [ { processor: "reportDone" pins: in: timesCalled: compileExpression("memory.child0TimesCalled") out: "memory.child0TimesCalled": compileExpression("pins.timesCalled") }, { name: "2nd" processor: "reportDone" pins: in: timesCalled: compileExpression("memory.child1TimesCalled") out: "memory.child1TimesCalled": compileExpression("pins.timesCalled") } ] constants = new RW.ChipVisitorConstants circuits: main: new RW.Circuit board: board processors: processors switches: switches memoryData: main: memories[0] results = RW.stimulateCircuits(constants) memories[1] = RW.applyPatches(results.circuitResults.main.memoryPatches, memories[0]) expect(memories[1].child0TimesCalled).toBe(1) expect(memories[1].child1TimesCalled).toBe(0) expect(memories[1].activeChild).toBe(1) constants = new RW.ChipVisitorConstants circuits: main: new RW.Circuit board: board processors: processors switches: switches memoryData: main: memories[1] results = RW.stimulateCircuits(constants) memories[2] = RW.applyPatches(results.circuitResults.main.memoryPatches, memories[1]) expect(memories[2].child0TimesCalled).toBe(1) expect(memories[2].child1TimesCalled).toBe(1) expect(memories[2].activeChild).toBe(2) it "binds across constant arrays", -> people = [ { first: "bill", last: "bobson" } { first: "joe", last: "johnson" } ] processors = getName: pinDefs: name: direction: "in" index: direction: "in" update: (pins, transformers, log) -> expect(pins.index).toEqual(if pins.name is "bill" then "0" else "1") spyOn(processors.getName, "update").andCallThrough() board = splitter: from: people bindTo: "person" index: "personIndex" children: [ { processor: "getName" pins: in: name: compileExpression("bindings.person.first") index: compileExpression("bindings.personIndex") } ] constants = new RW.ChipVisitorConstants circuits: main: new RW.Circuit board: board processors: processors RW.stimulateCircuits(constants) expect(processors.getName.update).toHaveBeenCalled() it "binds across memory arrays", -> oldMemory = people: [ { first: "bill", last: "bobson" } { first: "joe", last: "johnson" } ] processors = changeName: pinDefs: newName: direction: "in" toChange: direction: "out" index: direction: "in" update: (pins, transformers, log) -> expect(pins.index).toEqual(if pins.newName is "bill" then "0" else "1") pins.toChange = pins.newName board = splitter: from: "memory.people" bindTo: "person" index: "personIndex" children: [ { processor: "changeName" pins: in: newName: compileExpression("bindings.person.first") index: compileExpression("bindings.personIndex") out: "bindings.person.last": compileExpression("pins.toChange") } ] constants = new RW.ChipVisitorConstants circuits: main: new RW.Circuit board: board processors: processors memoryData: main: oldMemory results = RW.stimulateCircuits(constants) newMemory = RW.applyPatches(results.circuitResults.main.memoryPatches, oldMemory) expect(newMemory.people[0].last).toBe("bill") expect(newMemory.people[1].last).toBe("joe") it "binds with where guard", -> oldMemory = people: [ { first: "bill", last: "bobson" } { first: "joe", last: "johnson" } ] processors = getName: pinDefs: lastName: null update: (pins, transformers, log) -> expect(pins.lastName).toEqual("bobson") board = splitter: from: "memory.people" bindTo: "person" where: compileExpression("bindings.person.first == 'bill'") children: [ { processor: "getName" pins: in: lastName: compileExpression("bindings.person.last") } ] spyOn(processors.getName, "update").andCallThrough() constants = new RW.ChipVisitorConstants circuits: main: new RW.Circuit board: board processors: processors memoryData: main: oldMemory results = RW.stimulateCircuits(constants) expect(processors.getName.update).toHaveBeenCalled() it "communicates with io", -> oldIoData = serviceA: a: 1 processors = incrementIoData: pinDefs: service: direction: "inout" update: (pins, transformers, log) -> expect(pins.service.a).toBe(1) pins.service.a++ board = processor: "incrementIoData" pins: in: service: compileExpression("io.serviceA") out: "io.serviceA": compileExpression("pins.service") constants = new RW.ChipVisitorConstants circuits: main: new RW.Circuit board: board processors: processors ioData: main: oldIoData results = RW.stimulateCircuits(constants) newIoData = RW.applyPatches(results.circuitResults.main.ioPatches, oldIoData) expect(newIoData.serviceA.a).toBe(2) it "ignores muted chips", -> timesCalled = 0 processors = doNothing: pinDefs: {} update: -> timesCalled++ switches = doAll: pinDefs: {} board = switch: "doAll" pins: {} children: [ { processor: "doNothing" pins: {} }, { processor: "doNothing" pins: {} muted: true } ] # Only one of these chips should have been called constants = new RW.ChipVisitorConstants circuits: main: new RW.Circuit board: board processors: processors switches: switches RW.stimulateCircuits(constants) expect(timesCalled).toEqual(1) it "handles multiple circuits", -> switches = doAll: pinDefs: {} circuits = main: new RW.Circuit board: switch: "doAll" children: [ { emitter: "memory.a.a1": compileExpression("2") "memory.b": compileExpression("memory.c") "io.s.a": compileExpression("-5") } { circuit: "sub" id: "subId" } ] sub: new RW.Circuit board: emitter: "memory.a": compileExpression("99") "memory.b": compileExpression("memory.c") "io.s.a": compileExpression("100") memoryData = main: a: a1: 1 b: 10 c: "hi" "main.subId": a: 32 b: "hi" c: "bye" ioData = main: s: a: -1 "main.subId": s: a: -1 constants = new RW.ChipVisitorConstants circuits: circuits switches: switches memoryData: memoryData ioData: ioData results = RW.stimulateCircuits(constants) newMemory = {} newIo = {} for name in ["main", "main.subId"] newMemory[name] = RW.applyPatches(results.circuitResults[name].memoryPatches, memoryData[name]) newIo[name] = RW.applyPatches(results.circuitResults[name].ioPatches, ioData[name]) expect(newMemory.main.a.a1).toBe(2) expect(newMemory.main.b).toBe("hi") expect(newIo.main.s.a).toBe(-5) expect(newMemory["main.subId"].a).toBe(99) expect(newMemory["main.subId"].b).toBe("bye") expect(newMemory["main.subId"].c).toBe("bye") expect(newIo["main.subId"].s.a).toBe(100) it "circuits can have pins", -> switches = doAll: pinDefs: {} circuits = main: new RW.Circuit board: switch: "doAll" children: [ { emitter: "memory.a": compileExpression("2") } { circuit: "sub" id: "subId" pins: in: p: compileExpression("10") q: compileExpression("20") out: "memory.b": compileExpression("pins.q") } ] sub: new RW.Circuit pinDefs: p: direction: "in" q: direction: "inout" board: emitter: "memory.a": compileExpression("99") "circuit.q": compileExpression("circuit.p + circuit.q") memoryData = main: a: 0 b: 0 "main.subId": a: 32 constants = new RW.ChipVisitorConstants circuits: circuits switches: switches memoryData: memoryData results = RW.stimulateCircuits(constants) newMemory = {} for name in ["main", "main.subId"] newMemory[name] = RW.applyPatches(results.circuitResults[name].memoryPatches, memoryData[name]) expect(newMemory.main.a).toBe(2) expect(newMemory.main.b).toBe(30) expect(newMemory["main.subId"].a).toBe(99) describe "stepLoop()", -> it "sends output data directly to io", -> io = myService: establishData: jasmine.createSpy() outputIoData = main: myService: a = 1 result = RW.stepLoop io: io outputIoData: outputIoData expect(io.myService.establishData).toHaveBeenCalledWith({ main: 1 }) expect(_.size(result.memoryPatches)).toBe(0) expect(_.size(result.ioPatches)).toBe(0) it "sends io input data to stimulateCircuits()", -> io = myService: establishData: jasmine.createSpy() inputIoData = global: myService: a: 0 main: myService: a: 1 processors = incrementIoData: pinDefs: service: direction: "inout" update: (pins, transformers, log) -> expect(pins.service.a).toBe(1) pins.service.a++ board = processor: "incrementIoData" pins: in: service: compileExpression("io.myService") out: "io.myService": compileExpression("pins.service") result = RW.stepLoop circuits: main: new RW.Circuit board: board processors: processors io: io inputIoData: inputIoData expect(io.myService.establishData).toHaveBeenCalledWith({ main: { a: 2 } }) expect(result.memoryPatches.main).toBeEmpty() expect(result.ioPatches.main.length).toEqual(1) it "gathers io input data, visits chips, uses transformers, and gives output to io", -> io = myService: provideData: -> { main: { a: 1 } } establishData: jasmine.createSpy() spyOn(io.myService, "provideData").andCallThrough() transformers = testTransformer: (arg1, arg2) -> return {_1: arg1, _2: arg2}; processors = incrementIoData: pinDefs: service: direction: "inout" update: (pins, transformers, log) -> expect(transformers.testTransformer(pins.service.a, 2)._1).toBe(1) pins.service.a++ board = processor: "incrementIoData" pins: in: service: compileExpression("io.myService") out: "io.myService": compileExpression("pins.service") result = RW.stepLoop circuits: main: new RW.Circuit board: board processors: processors transformers: transformers io: io expect(io.myService.provideData).toHaveBeenCalledWith() expect(io.myService.establishData).toHaveBeenCalledWith({ main: { a: 2 } }) expect(result.memoryPatches).toDeeplyEqual({ main: [] }) it "rejects conflicting patches", -> # Create old data, new data, and the patches between oldData = a: 0 io = myService: provideData: -> return { main: { a: 0 } } establishData: jasmine.createSpy() switches = group: pinDefs: {} processors = setDataTo: pinDefs: value: null var: direction: "out" update: (pins, transformers, log) -> pins.var = pins.value boardA = switch: "group" children: [ { processor: "setDataTo" pins: in: value: compileExpression("1") out: "memory.a": compileExpression("pins.var") }, { processor: "setDataTo" pins: in: value: compileExpression("2") out: "memory.a": compileExpression("pins.var") } ] results = RW.stepLoop circuits: main: new RW.Circuit board: boardA switches: switches processors: processors memoryData: main: oldData expect(results.errors[0].stage).toBe("patchMemory") boardB = switch: "group" children: [ { processor: "setDataTo" pins: in: value: compileExpression("1") out: "io.myService.a": compileExpression("pins.var") }, { processor: "setDataTo" pins: in: value: compileExpression("2") out: "io.myService.a": compileExpression("pins.var") } ] results = RW.stepLoop circuits: main: new RW.Circuit board: boardB switches: switches processors: processors io: io expect(results.errors[0].stage).toBe("patchIo")
109411
# Get alias for the global scope globals = @ compileExpression = (expression) -> RW.compileExpression(expression, eval) describe "RedWire", -> beforeEach -> @addMatchers toDeeplyEqual: (expected) -> _.isEqual(@actual, expected) toBeEmpty: () -> @actual.length == 0 describe "memory", -> it "can remove value from array", -> a = v: [10..15] b = v: [10, 12, 13, 14, 15] # Missing 11 patches = RW.makePatches(a, b) patchResult = RW.applyPatches(patches, a) expect(patchResult).toDeeplyEqual(b) it "can be patched", -> # Create old data, new data, and the patches between oldData = a: 1 b: b1: true b2: "hi" newData = b: b1: true b2: "there" c: bob: "is cool" # Create the result via patches patches = RW.makePatches(oldData, newData) result = RW.applyPatches(patches, oldData) # The new data and old data should still be valid and different expect(oldData).not.toDeeplyEqual(newData) expect(result).toDeeplyEqual(newData) it "detects conflicting patches", -> # Test changing same attribute oldData = a: b: 1 c: 2 newDataA = a: b: 2 newDataB = a: b: 3 c: 2 patchesA = RW.makePatches(oldData, newDataA, "a") patchesB = RW.makePatches(oldData, newDataB, "b") allPatches = RW.concatenate(patchesA, patchesB) conflicts = RW.detectPatchConflicts(allPatches) expect(conflicts.length).toBe(1) expect(conflicts[0].path).toBe("/a/b") # Test child attribute oldData = a: b: 1 newDataA = a: b: c: 2 newDataB = a: b: 3 patchesA = RW.makePatches(oldData, newDataA, "a") patchesB = RW.makePatches(oldData, newDataB, "b") allPatches = RW.concatenate(patchesA, patchesB) conflicts = RW.detectPatchConflicts(allPatches) expect(conflicts.length).toBe(1) expect(conflicts[0].path).toBe("/a/b") # Test no conflict oldData = a: b: 1 c: 2 newDataA = a: b: 2 c: 2 newDataB = a: b: 1 c: 3 patchesA = RW.makePatches(oldData, newDataA, "a") patchesB = RW.makePatches(oldData, newDataB, "b") allPatches = RW.concatenate(patchesA, patchesB) conflicts = RW.detectPatchConflicts(allPatches) expect(conflicts).toBeEmpty() # Issue #299 it "does not consider parent removal as conflict", -> patches = [ { "remove": "/explosions/0", "path": [ "0" ] }, { "replace": "/explosions/0/frame", "value": 65, "path": [ "1", "0", "0" ] } ] conflicts = RW.detectPatchConflicts(patches) expect(conflicts).toBeEmpty() it "adds to and removes from arrays", -> oldData = a: [1, 2, 3] newDataA = a: [1, 2, 3, 4] newDataB = a: [2, 3] patchesA = RW.makePatches(oldData, newDataA, "a") patchesB = RW.makePatches(oldData, newDataB, "b") allPatches = RW.concatenate(patchesA, patchesB) conflicts = RW.detectPatchConflicts(allPatches) expect(conflicts).toBeEmpty() result = RW.applyPatches(allPatches, oldData) expect(result).toDeeplyEqual({ a: [2, 3, 4] }) it "modifies within arrays", -> oldData = a: [{ b: 1 }, { c: 2 }, { f: 5 }, 6] newDataA = a: [{ b: 1 }, { c: -2 }, { d: 3 }, { e: 4 }, { f: 5 }, 6] newDataB = a: [{ b: -1 }, { c: 2 }, { f: 5 }, -6, { g: 7 }] patchesA = RW.makePatches(oldData, newDataA, "a") patchesB = RW.makePatches(oldData, newDataB, "b") allPatches = RW.concatenate(patchesA, patchesB) conflicts = RW.detectPatchConflicts(allPatches) expect(conflicts).toBeEmpty() result = RW.applyPatches(allPatches, oldData) expect(result).toDeeplyEqual({ a: [{ b: -1 }, { c: -2 }, { d: 3 }, { e: 4 }, { f: 5 }, -6, { g: 7 }] }) describe "stimulateCircuits()", -> it "calls processors", -> isCalled = false processors = doNothing: pinDefs: x: direction: "in" default: compileExpression("1") y: direction: "in" default: compileExpression("'z'") update: (pins, transformers, log) -> isCalled = true expect(pins).toDeeplyEqual x: 2 y: "z" board = processor: "doNothing" pins: in: x: compileExpression("1 + 1") constants = new RW.ChipVisitorConstants circuits: main: new RW.Circuit board: board processors: processors RW.stimulateCircuits(constants) expect(isCalled).toBeTruthy() it "calls children of switches", -> timesCalled = 0 processors = doNothing: pinDefs: {} update: -> timesCalled++ switches = doAll: pinDefs: {} handleSignals: -> timesCalled++ board = switch: "doAll" pins: {} children: [ { processor: "doNothing" pins: {} }, { processor: "doNothing" pins: {} } ] constants = new RW.ChipVisitorConstants circuits: main: new RW.Circuit board: board processors: processors switches: switches RW.stimulateCircuits(constants) expect(timesCalled).toEqual(3) it "returns the path for patches", -> memoryData = a: 0 b: 1 message: null ioData = c: 2 processors = increment: pinDefs: value: direction: "inout" update: (pins, transformers, log) -> pins.value++ log: pinDefs: message: null update: (pins, transformers, log) -> log(RW.logLevels.INFO, pins.message) switches = doAll: pinDefs: {} # Transformers must be compiled this way # TODO: create function that does this work for us transformers = {} transformers.logIt = RW.compileTransformer("log(RW.logLevels.INFO, msg); return msg;", ["msg"], eval)(transformers) board = switch: "doAll" pins: {} children: [ { processor: "increment" pins: in: "value": compileExpression("memory.a") out: "memory.a": compileExpression("pins.value") }, { processor: "increment" pins: in: "value": compileExpression("memory.b") out: "memory.b": compileExpression("pins.value") }, { processor: "increment" pins: in: "value": compileExpression("io.c") out: "io.c": compileExpression("pins.value") }, { processor: "log" pins: in: "message": compileExpression("'hi'") }, { emitter: "memory.message": compileExpression("transformers.logIt('hi')") } ] constants = new RW.ChipVisitorConstants circuits: main: new RW.Circuit board: board processors: processors switches: switches transformers: transformers memoryData: main: memoryData ioData: main: ioData results = RW.stimulateCircuits(constants) mainResults = results.circuitResults.main expect(mainResults.memoryPatches.length).toBe(3) for memoryPatch in mainResults.memoryPatches if memoryPatch.replace is "/a" expect(memoryPatch.path).toDeeplyEqual(["0"]) else if memoryPatch.replace is "/b" expect(memoryPatch.path).toDeeplyEqual(["1"]) else if memoryPatch.replace is "/message" expect(memoryPatch.path).toDeeplyEqual(["4"]) else throw new Error("Memory patch affects wrong attribute") expect(mainResults.ioPatches.length).toBe(1) expect(mainResults.ioPatches[0].path).toDeeplyEqual(["2"]) expect(mainResults.logMessages.length).toBe(2) expect(mainResults.logMessages[0].path).toDeeplyEqual(["3"]) expect(mainResults.logMessages[1].path).toDeeplyEqual(["4"]) it "evaluates pins for processors", -> oldMemory = a: 1 b: 10 c: 20 assets = { image: new Image() } processors = adjustMemory: pinDefs: x: direction: "inout" y: direction: "inout" z: direction: "out" d: default: compileExpression("2") e: {} update: (pins, transformers, log) -> pins.x++ pins.y-- pins.z = 30 expect(pins.d).toBe(2) expect(pins.e).toBe(assets.image) board = processor: "adjustMemory" pins: in: x: compileExpression("memory.a") y: compileExpression("memory.b") e: compileExpression("assets.image") out: "memory.a": compileExpression("pins.x") "memory.b": compileExpression("pins.y") "memory.c": compileExpression("pins.z") constants = new RW.ChipVisitorConstants circuits: main: new RW.Circuit board: board processors: processors memoryData: main: oldMemory assets: assets results = RW.stimulateCircuits(constants) newMemory = RW.applyPatches(results.circuitResults.main.memoryPatches, oldMemory) # The new memory should be changed, but the old one shouldn't be expect(oldMemory.a).toBe(1) expect(oldMemory.b).toBe(10) expect(oldMemory.c).toBe(20) expect(newMemory.a).toBe(2) expect(newMemory.b).toBe(9) expect(newMemory.c).toBe(30) it "sends to memory and io", -> oldMemory = a: a1: 1 b: 10 c: "hi" oldIoData = s: a: -1 board = emitter: "memory.a.a1": compileExpression("2") "memory.b": compileExpression("memory.c") "io.s.a": compileExpression("-5") constants = new RW.ChipVisitorConstants circuits: main: new RW.Circuit board: board memoryData: main: oldMemory ioData: main: oldIoData results = RW.stimulateCircuits(constants) newMemory = RW.applyPatches(results.circuitResults.main.memoryPatches, oldMemory) newIoData = RW.applyPatches(results.circuitResults.main.ioPatches, oldIoData) # The new memory and io should be changed, but the old ones shouldn't be expect(oldMemory.a.a1).toBe(1) expect(oldMemory.b).toBe(10) expect(oldIoData.s.a).toBe(-1) expect(newMemory.a.a1).toBe(2) expect(newMemory.b).toBe("hi") expect(newIoData.s.a).toBe(-5) it "checks and adjusts activation", -> memories = [ { activeChild: 0 child0TimesCalled: 0 child1TimesCalled: 0 } ] switches = nextOnDone: pinDefs: activeChild: direction: "inout" default: compileExpression("0") listActiveChildren: (pins, children, transformers, log) -> expect(children).toDeeplyEqual([0, "2nd"]) return [children[pins.activeChild]] handleSignals: (pins, children, activeChildren, signals, transformers, log) -> expect(children).toDeeplyEqual([0, "2nd"]) if signals[pins.activeChild] == RW.signals.DONE pins.activeChild++ if pins.activeChild >= children.length - 1 return RW.signals.DONE processors = reportDone: pinDefs: timesCalled: direction: "inout" update: (pins, transformers, log) -> pins.timesCalled++ return RW.signals.DONE board = switch: "nextOnDone" pins: in: activeChild: compileExpression("memory.activeChild") out: "memory.activeChild": compileExpression("pins.activeChild") children: [ { processor: "reportDone" pins: in: timesCalled: compileExpression("memory.child0TimesCalled") out: "memory.child0TimesCalled": compileExpression("pins.timesCalled") }, { name: "<NAME>nd" processor: "reportDone" pins: in: timesCalled: compileExpression("memory.child1TimesCalled") out: "memory.child1TimesCalled": compileExpression("pins.timesCalled") } ] constants = new RW.ChipVisitorConstants circuits: main: new RW.Circuit board: board processors: processors switches: switches memoryData: main: memories[0] results = RW.stimulateCircuits(constants) memories[1] = RW.applyPatches(results.circuitResults.main.memoryPatches, memories[0]) expect(memories[1].child0TimesCalled).toBe(1) expect(memories[1].child1TimesCalled).toBe(0) expect(memories[1].activeChild).toBe(1) constants = new RW.ChipVisitorConstants circuits: main: new RW.Circuit board: board processors: processors switches: switches memoryData: main: memories[1] results = RW.stimulateCircuits(constants) memories[2] = RW.applyPatches(results.circuitResults.main.memoryPatches, memories[1]) expect(memories[2].child0TimesCalled).toBe(1) expect(memories[2].child1TimesCalled).toBe(1) expect(memories[2].activeChild).toBe(2) it "binds across constant arrays", -> people = [ { first: "<NAME>", last: "<NAME>" } { first: "<NAME>", last: "<NAME>" } ] processors = getName: pinDefs: name: direction: "in" index: direction: "in" update: (pins, transformers, log) -> expect(pins.index).toEqual(if pins.name is "bill" then "0" else "1") spyOn(processors.getName, "update").andCallThrough() board = splitter: from: people bindTo: "person" index: "personIndex" children: [ { processor: "getName" pins: in: name: compileExpression("bindings.person.first") index: compileExpression("bindings.personIndex") } ] constants = new RW.ChipVisitorConstants circuits: main: new RW.Circuit board: board processors: processors RW.stimulateCircuits(constants) expect(processors.getName.update).toHaveBeenCalled() it "binds across memory arrays", -> oldMemory = people: [ { first: "<NAME>", last: "<NAME>" } { first: "<NAME>", last: "<NAME>" } ] processors = changeName: pinDefs: newName: direction: "in" toChange: direction: "out" index: direction: "in" update: (pins, transformers, log) -> expect(pins.index).toEqual(if pins.newName is "bill" then "0" else "1") pins.toChange = pins.newName board = splitter: from: "memory.people" bindTo: "person" index: "personIndex" children: [ { processor: "changeName" pins: in: newName: compileExpression("bindings.person.first") index: compileExpression("bindings.personIndex") out: "bindings.person.last": compileExpression("pins.toChange") } ] constants = new RW.ChipVisitorConstants circuits: main: new RW.Circuit board: board processors: processors memoryData: main: oldMemory results = RW.stimulateCircuits(constants) newMemory = RW.applyPatches(results.circuitResults.main.memoryPatches, oldMemory) expect(newMemory.people[0].last).toBe("bill") expect(newMemory.people[1].last).toBe("<NAME>") it "binds with where guard", -> oldMemory = people: [ { first: "<NAME>", last: "<NAME>" } { first: "<NAME>", last: "<NAME>" } ] processors = getName: pinDefs: lastName: null update: (pins, transformers, log) -> expect(pins.lastName).toEqual("<NAME>") board = splitter: from: "memory.people" bindTo: "person" where: compileExpression("bindings.person.first == '<NAME>'") children: [ { processor: "getName" pins: in: lastName: compileExpression("bindings.person.last") } ] spyOn(processors.getName, "update").andCallThrough() constants = new RW.ChipVisitorConstants circuits: main: new RW.Circuit board: board processors: processors memoryData: main: oldMemory results = RW.stimulateCircuits(constants) expect(processors.getName.update).toHaveBeenCalled() it "communicates with io", -> oldIoData = serviceA: a: 1 processors = incrementIoData: pinDefs: service: direction: "inout" update: (pins, transformers, log) -> expect(pins.service.a).toBe(1) pins.service.a++ board = processor: "incrementIoData" pins: in: service: compileExpression("io.serviceA") out: "io.serviceA": compileExpression("pins.service") constants = new RW.ChipVisitorConstants circuits: main: new RW.Circuit board: board processors: processors ioData: main: oldIoData results = RW.stimulateCircuits(constants) newIoData = RW.applyPatches(results.circuitResults.main.ioPatches, oldIoData) expect(newIoData.serviceA.a).toBe(2) it "ignores muted chips", -> timesCalled = 0 processors = doNothing: pinDefs: {} update: -> timesCalled++ switches = doAll: pinDefs: {} board = switch: "doAll" pins: {} children: [ { processor: "doNothing" pins: {} }, { processor: "doNothing" pins: {} muted: true } ] # Only one of these chips should have been called constants = new RW.ChipVisitorConstants circuits: main: new RW.Circuit board: board processors: processors switches: switches RW.stimulateCircuits(constants) expect(timesCalled).toEqual(1) it "handles multiple circuits", -> switches = doAll: pinDefs: {} circuits = main: new RW.Circuit board: switch: "doAll" children: [ { emitter: "memory.a.a1": compileExpression("2") "memory.b": compileExpression("memory.c") "io.s.a": compileExpression("-5") } { circuit: "sub" id: "subId" } ] sub: new RW.Circuit board: emitter: "memory.a": compileExpression("99") "memory.b": compileExpression("memory.c") "io.s.a": compileExpression("100") memoryData = main: a: a1: 1 b: 10 c: "hi" "main.subId": a: 32 b: "hi" c: "bye" ioData = main: s: a: -1 "main.subId": s: a: -1 constants = new RW.ChipVisitorConstants circuits: circuits switches: switches memoryData: memoryData ioData: ioData results = RW.stimulateCircuits(constants) newMemory = {} newIo = {} for name in ["main", "main.subId"] newMemory[name] = RW.applyPatches(results.circuitResults[name].memoryPatches, memoryData[name]) newIo[name] = RW.applyPatches(results.circuitResults[name].ioPatches, ioData[name]) expect(newMemory.main.a.a1).toBe(2) expect(newMemory.main.b).toBe("hi") expect(newIo.main.s.a).toBe(-5) expect(newMemory["main.subId"].a).toBe(99) expect(newMemory["main.subId"].b).toBe("bye") expect(newMemory["main.subId"].c).toBe("bye") expect(newIo["main.subId"].s.a).toBe(100) it "circuits can have pins", -> switches = doAll: pinDefs: {} circuits = main: new RW.Circuit board: switch: "doAll" children: [ { emitter: "memory.a": compileExpression("2") } { circuit: "sub" id: "subId" pins: in: p: compileExpression("10") q: compileExpression("20") out: "memory.b": compileExpression("pins.q") } ] sub: new RW.Circuit pinDefs: p: direction: "in" q: direction: "inout" board: emitter: "memory.a": compileExpression("99") "circuit.q": compileExpression("circuit.p + circuit.q") memoryData = main: a: 0 b: 0 "main.subId": a: 32 constants = new RW.ChipVisitorConstants circuits: circuits switches: switches memoryData: memoryData results = RW.stimulateCircuits(constants) newMemory = {} for name in ["main", "main.subId"] newMemory[name] = RW.applyPatches(results.circuitResults[name].memoryPatches, memoryData[name]) expect(newMemory.main.a).toBe(2) expect(newMemory.main.b).toBe(30) expect(newMemory["main.subId"].a).toBe(99) describe "stepLoop()", -> it "sends output data directly to io", -> io = myService: establishData: jasmine.createSpy() outputIoData = main: myService: a = 1 result = RW.stepLoop io: io outputIoData: outputIoData expect(io.myService.establishData).toHaveBeenCalledWith({ main: 1 }) expect(_.size(result.memoryPatches)).toBe(0) expect(_.size(result.ioPatches)).toBe(0) it "sends io input data to stimulateCircuits()", -> io = myService: establishData: jasmine.createSpy() inputIoData = global: myService: a: 0 main: myService: a: 1 processors = incrementIoData: pinDefs: service: direction: "inout" update: (pins, transformers, log) -> expect(pins.service.a).toBe(1) pins.service.a++ board = processor: "incrementIoData" pins: in: service: compileExpression("io.myService") out: "io.myService": compileExpression("pins.service") result = RW.stepLoop circuits: main: new RW.Circuit board: board processors: processors io: io inputIoData: inputIoData expect(io.myService.establishData).toHaveBeenCalledWith({ main: { a: 2 } }) expect(result.memoryPatches.main).toBeEmpty() expect(result.ioPatches.main.length).toEqual(1) it "gathers io input data, visits chips, uses transformers, and gives output to io", -> io = myService: provideData: -> { main: { a: 1 } } establishData: jasmine.createSpy() spyOn(io.myService, "provideData").andCallThrough() transformers = testTransformer: (arg1, arg2) -> return {_1: arg1, _2: arg2}; processors = incrementIoData: pinDefs: service: direction: "inout" update: (pins, transformers, log) -> expect(transformers.testTransformer(pins.service.a, 2)._1).toBe(1) pins.service.a++ board = processor: "incrementIoData" pins: in: service: compileExpression("io.myService") out: "io.myService": compileExpression("pins.service") result = RW.stepLoop circuits: main: new RW.Circuit board: board processors: processors transformers: transformers io: io expect(io.myService.provideData).toHaveBeenCalledWith() expect(io.myService.establishData).toHaveBeenCalledWith({ main: { a: 2 } }) expect(result.memoryPatches).toDeeplyEqual({ main: [] }) it "rejects conflicting patches", -> # Create old data, new data, and the patches between oldData = a: 0 io = myService: provideData: -> return { main: { a: 0 } } establishData: jasmine.createSpy() switches = group: pinDefs: {} processors = setDataTo: pinDefs: value: null var: direction: "out" update: (pins, transformers, log) -> pins.var = pins.value boardA = switch: "group" children: [ { processor: "setDataTo" pins: in: value: compileExpression("1") out: "memory.a": compileExpression("pins.var") }, { processor: "setDataTo" pins: in: value: compileExpression("2") out: "memory.a": compileExpression("pins.var") } ] results = RW.stepLoop circuits: main: new RW.Circuit board: boardA switches: switches processors: processors memoryData: main: oldData expect(results.errors[0].stage).toBe("patchMemory") boardB = switch: "group" children: [ { processor: "setDataTo" pins: in: value: compileExpression("1") out: "io.myService.a": compileExpression("pins.var") }, { processor: "setDataTo" pins: in: value: compileExpression("2") out: "io.myService.a": compileExpression("pins.var") } ] results = RW.stepLoop circuits: main: new RW.Circuit board: boardB switches: switches processors: processors io: io expect(results.errors[0].stage).toBe("patchIo")
true
# Get alias for the global scope globals = @ compileExpression = (expression) -> RW.compileExpression(expression, eval) describe "RedWire", -> beforeEach -> @addMatchers toDeeplyEqual: (expected) -> _.isEqual(@actual, expected) toBeEmpty: () -> @actual.length == 0 describe "memory", -> it "can remove value from array", -> a = v: [10..15] b = v: [10, 12, 13, 14, 15] # Missing 11 patches = RW.makePatches(a, b) patchResult = RW.applyPatches(patches, a) expect(patchResult).toDeeplyEqual(b) it "can be patched", -> # Create old data, new data, and the patches between oldData = a: 1 b: b1: true b2: "hi" newData = b: b1: true b2: "there" c: bob: "is cool" # Create the result via patches patches = RW.makePatches(oldData, newData) result = RW.applyPatches(patches, oldData) # The new data and old data should still be valid and different expect(oldData).not.toDeeplyEqual(newData) expect(result).toDeeplyEqual(newData) it "detects conflicting patches", -> # Test changing same attribute oldData = a: b: 1 c: 2 newDataA = a: b: 2 newDataB = a: b: 3 c: 2 patchesA = RW.makePatches(oldData, newDataA, "a") patchesB = RW.makePatches(oldData, newDataB, "b") allPatches = RW.concatenate(patchesA, patchesB) conflicts = RW.detectPatchConflicts(allPatches) expect(conflicts.length).toBe(1) expect(conflicts[0].path).toBe("/a/b") # Test child attribute oldData = a: b: 1 newDataA = a: b: c: 2 newDataB = a: b: 3 patchesA = RW.makePatches(oldData, newDataA, "a") patchesB = RW.makePatches(oldData, newDataB, "b") allPatches = RW.concatenate(patchesA, patchesB) conflicts = RW.detectPatchConflicts(allPatches) expect(conflicts.length).toBe(1) expect(conflicts[0].path).toBe("/a/b") # Test no conflict oldData = a: b: 1 c: 2 newDataA = a: b: 2 c: 2 newDataB = a: b: 1 c: 3 patchesA = RW.makePatches(oldData, newDataA, "a") patchesB = RW.makePatches(oldData, newDataB, "b") allPatches = RW.concatenate(patchesA, patchesB) conflicts = RW.detectPatchConflicts(allPatches) expect(conflicts).toBeEmpty() # Issue #299 it "does not consider parent removal as conflict", -> patches = [ { "remove": "/explosions/0", "path": [ "0" ] }, { "replace": "/explosions/0/frame", "value": 65, "path": [ "1", "0", "0" ] } ] conflicts = RW.detectPatchConflicts(patches) expect(conflicts).toBeEmpty() it "adds to and removes from arrays", -> oldData = a: [1, 2, 3] newDataA = a: [1, 2, 3, 4] newDataB = a: [2, 3] patchesA = RW.makePatches(oldData, newDataA, "a") patchesB = RW.makePatches(oldData, newDataB, "b") allPatches = RW.concatenate(patchesA, patchesB) conflicts = RW.detectPatchConflicts(allPatches) expect(conflicts).toBeEmpty() result = RW.applyPatches(allPatches, oldData) expect(result).toDeeplyEqual({ a: [2, 3, 4] }) it "modifies within arrays", -> oldData = a: [{ b: 1 }, { c: 2 }, { f: 5 }, 6] newDataA = a: [{ b: 1 }, { c: -2 }, { d: 3 }, { e: 4 }, { f: 5 }, 6] newDataB = a: [{ b: -1 }, { c: 2 }, { f: 5 }, -6, { g: 7 }] patchesA = RW.makePatches(oldData, newDataA, "a") patchesB = RW.makePatches(oldData, newDataB, "b") allPatches = RW.concatenate(patchesA, patchesB) conflicts = RW.detectPatchConflicts(allPatches) expect(conflicts).toBeEmpty() result = RW.applyPatches(allPatches, oldData) expect(result).toDeeplyEqual({ a: [{ b: -1 }, { c: -2 }, { d: 3 }, { e: 4 }, { f: 5 }, -6, { g: 7 }] }) describe "stimulateCircuits()", -> it "calls processors", -> isCalled = false processors = doNothing: pinDefs: x: direction: "in" default: compileExpression("1") y: direction: "in" default: compileExpression("'z'") update: (pins, transformers, log) -> isCalled = true expect(pins).toDeeplyEqual x: 2 y: "z" board = processor: "doNothing" pins: in: x: compileExpression("1 + 1") constants = new RW.ChipVisitorConstants circuits: main: new RW.Circuit board: board processors: processors RW.stimulateCircuits(constants) expect(isCalled).toBeTruthy() it "calls children of switches", -> timesCalled = 0 processors = doNothing: pinDefs: {} update: -> timesCalled++ switches = doAll: pinDefs: {} handleSignals: -> timesCalled++ board = switch: "doAll" pins: {} children: [ { processor: "doNothing" pins: {} }, { processor: "doNothing" pins: {} } ] constants = new RW.ChipVisitorConstants circuits: main: new RW.Circuit board: board processors: processors switches: switches RW.stimulateCircuits(constants) expect(timesCalled).toEqual(3) it "returns the path for patches", -> memoryData = a: 0 b: 1 message: null ioData = c: 2 processors = increment: pinDefs: value: direction: "inout" update: (pins, transformers, log) -> pins.value++ log: pinDefs: message: null update: (pins, transformers, log) -> log(RW.logLevels.INFO, pins.message) switches = doAll: pinDefs: {} # Transformers must be compiled this way # TODO: create function that does this work for us transformers = {} transformers.logIt = RW.compileTransformer("log(RW.logLevels.INFO, msg); return msg;", ["msg"], eval)(transformers) board = switch: "doAll" pins: {} children: [ { processor: "increment" pins: in: "value": compileExpression("memory.a") out: "memory.a": compileExpression("pins.value") }, { processor: "increment" pins: in: "value": compileExpression("memory.b") out: "memory.b": compileExpression("pins.value") }, { processor: "increment" pins: in: "value": compileExpression("io.c") out: "io.c": compileExpression("pins.value") }, { processor: "log" pins: in: "message": compileExpression("'hi'") }, { emitter: "memory.message": compileExpression("transformers.logIt('hi')") } ] constants = new RW.ChipVisitorConstants circuits: main: new RW.Circuit board: board processors: processors switches: switches transformers: transformers memoryData: main: memoryData ioData: main: ioData results = RW.stimulateCircuits(constants) mainResults = results.circuitResults.main expect(mainResults.memoryPatches.length).toBe(3) for memoryPatch in mainResults.memoryPatches if memoryPatch.replace is "/a" expect(memoryPatch.path).toDeeplyEqual(["0"]) else if memoryPatch.replace is "/b" expect(memoryPatch.path).toDeeplyEqual(["1"]) else if memoryPatch.replace is "/message" expect(memoryPatch.path).toDeeplyEqual(["4"]) else throw new Error("Memory patch affects wrong attribute") expect(mainResults.ioPatches.length).toBe(1) expect(mainResults.ioPatches[0].path).toDeeplyEqual(["2"]) expect(mainResults.logMessages.length).toBe(2) expect(mainResults.logMessages[0].path).toDeeplyEqual(["3"]) expect(mainResults.logMessages[1].path).toDeeplyEqual(["4"]) it "evaluates pins for processors", -> oldMemory = a: 1 b: 10 c: 20 assets = { image: new Image() } processors = adjustMemory: pinDefs: x: direction: "inout" y: direction: "inout" z: direction: "out" d: default: compileExpression("2") e: {} update: (pins, transformers, log) -> pins.x++ pins.y-- pins.z = 30 expect(pins.d).toBe(2) expect(pins.e).toBe(assets.image) board = processor: "adjustMemory" pins: in: x: compileExpression("memory.a") y: compileExpression("memory.b") e: compileExpression("assets.image") out: "memory.a": compileExpression("pins.x") "memory.b": compileExpression("pins.y") "memory.c": compileExpression("pins.z") constants = new RW.ChipVisitorConstants circuits: main: new RW.Circuit board: board processors: processors memoryData: main: oldMemory assets: assets results = RW.stimulateCircuits(constants) newMemory = RW.applyPatches(results.circuitResults.main.memoryPatches, oldMemory) # The new memory should be changed, but the old one shouldn't be expect(oldMemory.a).toBe(1) expect(oldMemory.b).toBe(10) expect(oldMemory.c).toBe(20) expect(newMemory.a).toBe(2) expect(newMemory.b).toBe(9) expect(newMemory.c).toBe(30) it "sends to memory and io", -> oldMemory = a: a1: 1 b: 10 c: "hi" oldIoData = s: a: -1 board = emitter: "memory.a.a1": compileExpression("2") "memory.b": compileExpression("memory.c") "io.s.a": compileExpression("-5") constants = new RW.ChipVisitorConstants circuits: main: new RW.Circuit board: board memoryData: main: oldMemory ioData: main: oldIoData results = RW.stimulateCircuits(constants) newMemory = RW.applyPatches(results.circuitResults.main.memoryPatches, oldMemory) newIoData = RW.applyPatches(results.circuitResults.main.ioPatches, oldIoData) # The new memory and io should be changed, but the old ones shouldn't be expect(oldMemory.a.a1).toBe(1) expect(oldMemory.b).toBe(10) expect(oldIoData.s.a).toBe(-1) expect(newMemory.a.a1).toBe(2) expect(newMemory.b).toBe("hi") expect(newIoData.s.a).toBe(-5) it "checks and adjusts activation", -> memories = [ { activeChild: 0 child0TimesCalled: 0 child1TimesCalled: 0 } ] switches = nextOnDone: pinDefs: activeChild: direction: "inout" default: compileExpression("0") listActiveChildren: (pins, children, transformers, log) -> expect(children).toDeeplyEqual([0, "2nd"]) return [children[pins.activeChild]] handleSignals: (pins, children, activeChildren, signals, transformers, log) -> expect(children).toDeeplyEqual([0, "2nd"]) if signals[pins.activeChild] == RW.signals.DONE pins.activeChild++ if pins.activeChild >= children.length - 1 return RW.signals.DONE processors = reportDone: pinDefs: timesCalled: direction: "inout" update: (pins, transformers, log) -> pins.timesCalled++ return RW.signals.DONE board = switch: "nextOnDone" pins: in: activeChild: compileExpression("memory.activeChild") out: "memory.activeChild": compileExpression("pins.activeChild") children: [ { processor: "reportDone" pins: in: timesCalled: compileExpression("memory.child0TimesCalled") out: "memory.child0TimesCalled": compileExpression("pins.timesCalled") }, { name: "PI:NAME:<NAME>END_PInd" processor: "reportDone" pins: in: timesCalled: compileExpression("memory.child1TimesCalled") out: "memory.child1TimesCalled": compileExpression("pins.timesCalled") } ] constants = new RW.ChipVisitorConstants circuits: main: new RW.Circuit board: board processors: processors switches: switches memoryData: main: memories[0] results = RW.stimulateCircuits(constants) memories[1] = RW.applyPatches(results.circuitResults.main.memoryPatches, memories[0]) expect(memories[1].child0TimesCalled).toBe(1) expect(memories[1].child1TimesCalled).toBe(0) expect(memories[1].activeChild).toBe(1) constants = new RW.ChipVisitorConstants circuits: main: new RW.Circuit board: board processors: processors switches: switches memoryData: main: memories[1] results = RW.stimulateCircuits(constants) memories[2] = RW.applyPatches(results.circuitResults.main.memoryPatches, memories[1]) expect(memories[2].child0TimesCalled).toBe(1) expect(memories[2].child1TimesCalled).toBe(1) expect(memories[2].activeChild).toBe(2) it "binds across constant arrays", -> people = [ { first: "PI:NAME:<NAME>END_PI", last: "PI:NAME:<NAME>END_PI" } { first: "PI:NAME:<NAME>END_PI", last: "PI:NAME:<NAME>END_PI" } ] processors = getName: pinDefs: name: direction: "in" index: direction: "in" update: (pins, transformers, log) -> expect(pins.index).toEqual(if pins.name is "bill" then "0" else "1") spyOn(processors.getName, "update").andCallThrough() board = splitter: from: people bindTo: "person" index: "personIndex" children: [ { processor: "getName" pins: in: name: compileExpression("bindings.person.first") index: compileExpression("bindings.personIndex") } ] constants = new RW.ChipVisitorConstants circuits: main: new RW.Circuit board: board processors: processors RW.stimulateCircuits(constants) expect(processors.getName.update).toHaveBeenCalled() it "binds across memory arrays", -> oldMemory = people: [ { first: "PI:NAME:<NAME>END_PI", last: "PI:NAME:<NAME>END_PI" } { first: "PI:NAME:<NAME>END_PI", last: "PI:NAME:<NAME>END_PI" } ] processors = changeName: pinDefs: newName: direction: "in" toChange: direction: "out" index: direction: "in" update: (pins, transformers, log) -> expect(pins.index).toEqual(if pins.newName is "bill" then "0" else "1") pins.toChange = pins.newName board = splitter: from: "memory.people" bindTo: "person" index: "personIndex" children: [ { processor: "changeName" pins: in: newName: compileExpression("bindings.person.first") index: compileExpression("bindings.personIndex") out: "bindings.person.last": compileExpression("pins.toChange") } ] constants = new RW.ChipVisitorConstants circuits: main: new RW.Circuit board: board processors: processors memoryData: main: oldMemory results = RW.stimulateCircuits(constants) newMemory = RW.applyPatches(results.circuitResults.main.memoryPatches, oldMemory) expect(newMemory.people[0].last).toBe("bill") expect(newMemory.people[1].last).toBe("PI:NAME:<NAME>END_PI") it "binds with where guard", -> oldMemory = people: [ { first: "PI:NAME:<NAME>END_PI", last: "PI:NAME:<NAME>END_PI" } { first: "PI:NAME:<NAME>END_PI", last: "PI:NAME:<NAME>END_PI" } ] processors = getName: pinDefs: lastName: null update: (pins, transformers, log) -> expect(pins.lastName).toEqual("PI:NAME:<NAME>END_PI") board = splitter: from: "memory.people" bindTo: "person" where: compileExpression("bindings.person.first == 'PI:NAME:<NAME>END_PI'") children: [ { processor: "getName" pins: in: lastName: compileExpression("bindings.person.last") } ] spyOn(processors.getName, "update").andCallThrough() constants = new RW.ChipVisitorConstants circuits: main: new RW.Circuit board: board processors: processors memoryData: main: oldMemory results = RW.stimulateCircuits(constants) expect(processors.getName.update).toHaveBeenCalled() it "communicates with io", -> oldIoData = serviceA: a: 1 processors = incrementIoData: pinDefs: service: direction: "inout" update: (pins, transformers, log) -> expect(pins.service.a).toBe(1) pins.service.a++ board = processor: "incrementIoData" pins: in: service: compileExpression("io.serviceA") out: "io.serviceA": compileExpression("pins.service") constants = new RW.ChipVisitorConstants circuits: main: new RW.Circuit board: board processors: processors ioData: main: oldIoData results = RW.stimulateCircuits(constants) newIoData = RW.applyPatches(results.circuitResults.main.ioPatches, oldIoData) expect(newIoData.serviceA.a).toBe(2) it "ignores muted chips", -> timesCalled = 0 processors = doNothing: pinDefs: {} update: -> timesCalled++ switches = doAll: pinDefs: {} board = switch: "doAll" pins: {} children: [ { processor: "doNothing" pins: {} }, { processor: "doNothing" pins: {} muted: true } ] # Only one of these chips should have been called constants = new RW.ChipVisitorConstants circuits: main: new RW.Circuit board: board processors: processors switches: switches RW.stimulateCircuits(constants) expect(timesCalled).toEqual(1) it "handles multiple circuits", -> switches = doAll: pinDefs: {} circuits = main: new RW.Circuit board: switch: "doAll" children: [ { emitter: "memory.a.a1": compileExpression("2") "memory.b": compileExpression("memory.c") "io.s.a": compileExpression("-5") } { circuit: "sub" id: "subId" } ] sub: new RW.Circuit board: emitter: "memory.a": compileExpression("99") "memory.b": compileExpression("memory.c") "io.s.a": compileExpression("100") memoryData = main: a: a1: 1 b: 10 c: "hi" "main.subId": a: 32 b: "hi" c: "bye" ioData = main: s: a: -1 "main.subId": s: a: -1 constants = new RW.ChipVisitorConstants circuits: circuits switches: switches memoryData: memoryData ioData: ioData results = RW.stimulateCircuits(constants) newMemory = {} newIo = {} for name in ["main", "main.subId"] newMemory[name] = RW.applyPatches(results.circuitResults[name].memoryPatches, memoryData[name]) newIo[name] = RW.applyPatches(results.circuitResults[name].ioPatches, ioData[name]) expect(newMemory.main.a.a1).toBe(2) expect(newMemory.main.b).toBe("hi") expect(newIo.main.s.a).toBe(-5) expect(newMemory["main.subId"].a).toBe(99) expect(newMemory["main.subId"].b).toBe("bye") expect(newMemory["main.subId"].c).toBe("bye") expect(newIo["main.subId"].s.a).toBe(100) it "circuits can have pins", -> switches = doAll: pinDefs: {} circuits = main: new RW.Circuit board: switch: "doAll" children: [ { emitter: "memory.a": compileExpression("2") } { circuit: "sub" id: "subId" pins: in: p: compileExpression("10") q: compileExpression("20") out: "memory.b": compileExpression("pins.q") } ] sub: new RW.Circuit pinDefs: p: direction: "in" q: direction: "inout" board: emitter: "memory.a": compileExpression("99") "circuit.q": compileExpression("circuit.p + circuit.q") memoryData = main: a: 0 b: 0 "main.subId": a: 32 constants = new RW.ChipVisitorConstants circuits: circuits switches: switches memoryData: memoryData results = RW.stimulateCircuits(constants) newMemory = {} for name in ["main", "main.subId"] newMemory[name] = RW.applyPatches(results.circuitResults[name].memoryPatches, memoryData[name]) expect(newMemory.main.a).toBe(2) expect(newMemory.main.b).toBe(30) expect(newMemory["main.subId"].a).toBe(99) describe "stepLoop()", -> it "sends output data directly to io", -> io = myService: establishData: jasmine.createSpy() outputIoData = main: myService: a = 1 result = RW.stepLoop io: io outputIoData: outputIoData expect(io.myService.establishData).toHaveBeenCalledWith({ main: 1 }) expect(_.size(result.memoryPatches)).toBe(0) expect(_.size(result.ioPatches)).toBe(0) it "sends io input data to stimulateCircuits()", -> io = myService: establishData: jasmine.createSpy() inputIoData = global: myService: a: 0 main: myService: a: 1 processors = incrementIoData: pinDefs: service: direction: "inout" update: (pins, transformers, log) -> expect(pins.service.a).toBe(1) pins.service.a++ board = processor: "incrementIoData" pins: in: service: compileExpression("io.myService") out: "io.myService": compileExpression("pins.service") result = RW.stepLoop circuits: main: new RW.Circuit board: board processors: processors io: io inputIoData: inputIoData expect(io.myService.establishData).toHaveBeenCalledWith({ main: { a: 2 } }) expect(result.memoryPatches.main).toBeEmpty() expect(result.ioPatches.main.length).toEqual(1) it "gathers io input data, visits chips, uses transformers, and gives output to io", -> io = myService: provideData: -> { main: { a: 1 } } establishData: jasmine.createSpy() spyOn(io.myService, "provideData").andCallThrough() transformers = testTransformer: (arg1, arg2) -> return {_1: arg1, _2: arg2}; processors = incrementIoData: pinDefs: service: direction: "inout" update: (pins, transformers, log) -> expect(transformers.testTransformer(pins.service.a, 2)._1).toBe(1) pins.service.a++ board = processor: "incrementIoData" pins: in: service: compileExpression("io.myService") out: "io.myService": compileExpression("pins.service") result = RW.stepLoop circuits: main: new RW.Circuit board: board processors: processors transformers: transformers io: io expect(io.myService.provideData).toHaveBeenCalledWith() expect(io.myService.establishData).toHaveBeenCalledWith({ main: { a: 2 } }) expect(result.memoryPatches).toDeeplyEqual({ main: [] }) it "rejects conflicting patches", -> # Create old data, new data, and the patches between oldData = a: 0 io = myService: provideData: -> return { main: { a: 0 } } establishData: jasmine.createSpy() switches = group: pinDefs: {} processors = setDataTo: pinDefs: value: null var: direction: "out" update: (pins, transformers, log) -> pins.var = pins.value boardA = switch: "group" children: [ { processor: "setDataTo" pins: in: value: compileExpression("1") out: "memory.a": compileExpression("pins.var") }, { processor: "setDataTo" pins: in: value: compileExpression("2") out: "memory.a": compileExpression("pins.var") } ] results = RW.stepLoop circuits: main: new RW.Circuit board: boardA switches: switches processors: processors memoryData: main: oldData expect(results.errors[0].stage).toBe("patchMemory") boardB = switch: "group" children: [ { processor: "setDataTo" pins: in: value: compileExpression("1") out: "io.myService.a": compileExpression("pins.var") }, { processor: "setDataTo" pins: in: value: compileExpression("2") out: "io.myService.a": compileExpression("pins.var") } ] results = RW.stepLoop circuits: main: new RW.Circuit board: boardB switches: switches processors: processors io: io expect(results.errors[0].stage).toBe("patchIo")
[ { "context": "# Copyright 2014, 2015 Simon Lydell\n# X11 (“MIT”) Licensed. (See LICENSE.)\n\n# <http:/", "end": 35, "score": 0.9998506307601929, "start": 23, "tag": "NAME", "value": "Simon Lydell" } ]
gears_babel/node_modules/babel/node_modules/js-tokens/regex.coffee
mandx/gears-babel
0
# Copyright 2014, 2015 Simon Lydell # X11 (“MIT”) Licensed. (See LICENSE.) # <http://es5.github.io/#A.1> # Don’t worry, you don’t need to know CoffeeScript. It is only used for its # readable regex syntax. Everything else is done in JavaScript in index.js. module.exports = /// ( # <string> ([ ' " ]) (?: (?!\2)[^ \\ \r \n \u2028 \u2029 ] | \\(?: \r\n | [\s\S] ) )* (\2)? | ` (?: [^ ` \\ $ ] | \\[\s\S] | \$(?!\{) | \$\{ (?: [^{}] | \{ [^}]* \}? )* \}? )* (`)? ) | ( # <comment> //.* ) | ( # <comment> /\* (?: [^*] | \*(?!/) )* ( \*/ )? ) | ( # <regex> /(?!\*) (?: \[ (?: [^ \] \\ \r \n \u2028 \u2029 ] | \\. )* \] | [^ / \] \\ \r \n \u2028 \u2029 ] | \\. )+ / (?: (?! \s* (?: \b | [ \u0080-\uFFFF $ \\ ' " ~ ( { ] | [ + \- ! ](?!=) | \.?\d ) ) | [ g m i y u ]{1,5} \b (?! [ \u0080-\uFFFF $ \\ ] | \s* (?: [ + \- * % & | ^ < > ! = ? ( { ] | /(?! [ / * ] ) ) ) ) ) | ( # <number> -? (?: 0[xX][ \d a-f A-F ]+ | 0[oO][0-7]+ | 0[bB][01]+ | (?: \d*\.\d+ | \d+\.? # Support one trailing dot for integers only. ) (?: [eE][+-]?\d+ )? ) ) | ( # <name> # See <http://mathiasbynens.be/notes/javascript-identifiers>. (?!\d) (?: (?!\s)[ $ \w \u0080-\uFFFF ] | # Unicode escape sequence. \\u[ \d a-f A-F ]{4} | # ES6 unicode escape sequence. \\u\{[ \d a-f A-F ]{1,6}\} )+ ) | ( # <operator> # Word operators (such as `instanceof`) are matched as <name>s. -- | \+\+ | && | \|\| | => # ES6 function arrow. | \.{3} # ES6 splat. | (?: [ + \- * / % & | ^ ] | <{1,2} | >{1,3} | !=? | ={1,2} )=? | [ ? : ~ ] ) | ( # <punctuation> # A comma can also be an operator, but is matched as <punctuation> only. [ ; , . [ \] ( ) { } ] ) | ( # <whitespace> \s+ ) | ( # <invalid> ^$ # Empty. | [\s\S] # Catch-all rule for anything not matched by the above. ) ///g
172100
# Copyright 2014, 2015 <NAME> # X11 (“MIT”) Licensed. (See LICENSE.) # <http://es5.github.io/#A.1> # Don’t worry, you don’t need to know CoffeeScript. It is only used for its # readable regex syntax. Everything else is done in JavaScript in index.js. module.exports = /// ( # <string> ([ ' " ]) (?: (?!\2)[^ \\ \r \n \u2028 \u2029 ] | \\(?: \r\n | [\s\S] ) )* (\2)? | ` (?: [^ ` \\ $ ] | \\[\s\S] | \$(?!\{) | \$\{ (?: [^{}] | \{ [^}]* \}? )* \}? )* (`)? ) | ( # <comment> //.* ) | ( # <comment> /\* (?: [^*] | \*(?!/) )* ( \*/ )? ) | ( # <regex> /(?!\*) (?: \[ (?: [^ \] \\ \r \n \u2028 \u2029 ] | \\. )* \] | [^ / \] \\ \r \n \u2028 \u2029 ] | \\. )+ / (?: (?! \s* (?: \b | [ \u0080-\uFFFF $ \\ ' " ~ ( { ] | [ + \- ! ](?!=) | \.?\d ) ) | [ g m i y u ]{1,5} \b (?! [ \u0080-\uFFFF $ \\ ] | \s* (?: [ + \- * % & | ^ < > ! = ? ( { ] | /(?! [ / * ] ) ) ) ) ) | ( # <number> -? (?: 0[xX][ \d a-f A-F ]+ | 0[oO][0-7]+ | 0[bB][01]+ | (?: \d*\.\d+ | \d+\.? # Support one trailing dot for integers only. ) (?: [eE][+-]?\d+ )? ) ) | ( # <name> # See <http://mathiasbynens.be/notes/javascript-identifiers>. (?!\d) (?: (?!\s)[ $ \w \u0080-\uFFFF ] | # Unicode escape sequence. \\u[ \d a-f A-F ]{4} | # ES6 unicode escape sequence. \\u\{[ \d a-f A-F ]{1,6}\} )+ ) | ( # <operator> # Word operators (such as `instanceof`) are matched as <name>s. -- | \+\+ | && | \|\| | => # ES6 function arrow. | \.{3} # ES6 splat. | (?: [ + \- * / % & | ^ ] | <{1,2} | >{1,3} | !=? | ={1,2} )=? | [ ? : ~ ] ) | ( # <punctuation> # A comma can also be an operator, but is matched as <punctuation> only. [ ; , . [ \] ( ) { } ] ) | ( # <whitespace> \s+ ) | ( # <invalid> ^$ # Empty. | [\s\S] # Catch-all rule for anything not matched by the above. ) ///g
true
# Copyright 2014, 2015 PI:NAME:<NAME>END_PI # X11 (“MIT”) Licensed. (See LICENSE.) # <http://es5.github.io/#A.1> # Don’t worry, you don’t need to know CoffeeScript. It is only used for its # readable regex syntax. Everything else is done in JavaScript in index.js. module.exports = /// ( # <string> ([ ' " ]) (?: (?!\2)[^ \\ \r \n \u2028 \u2029 ] | \\(?: \r\n | [\s\S] ) )* (\2)? | ` (?: [^ ` \\ $ ] | \\[\s\S] | \$(?!\{) | \$\{ (?: [^{}] | \{ [^}]* \}? )* \}? )* (`)? ) | ( # <comment> //.* ) | ( # <comment> /\* (?: [^*] | \*(?!/) )* ( \*/ )? ) | ( # <regex> /(?!\*) (?: \[ (?: [^ \] \\ \r \n \u2028 \u2029 ] | \\. )* \] | [^ / \] \\ \r \n \u2028 \u2029 ] | \\. )+ / (?: (?! \s* (?: \b | [ \u0080-\uFFFF $ \\ ' " ~ ( { ] | [ + \- ! ](?!=) | \.?\d ) ) | [ g m i y u ]{1,5} \b (?! [ \u0080-\uFFFF $ \\ ] | \s* (?: [ + \- * % & | ^ < > ! = ? ( { ] | /(?! [ / * ] ) ) ) ) ) | ( # <number> -? (?: 0[xX][ \d a-f A-F ]+ | 0[oO][0-7]+ | 0[bB][01]+ | (?: \d*\.\d+ | \d+\.? # Support one trailing dot for integers only. ) (?: [eE][+-]?\d+ )? ) ) | ( # <name> # See <http://mathiasbynens.be/notes/javascript-identifiers>. (?!\d) (?: (?!\s)[ $ \w \u0080-\uFFFF ] | # Unicode escape sequence. \\u[ \d a-f A-F ]{4} | # ES6 unicode escape sequence. \\u\{[ \d a-f A-F ]{1,6}\} )+ ) | ( # <operator> # Word operators (such as `instanceof`) are matched as <name>s. -- | \+\+ | && | \|\| | => # ES6 function arrow. | \.{3} # ES6 splat. | (?: [ + \- * / % & | ^ ] | <{1,2} | >{1,3} | !=? | ={1,2} )=? | [ ? : ~ ] ) | ( # <punctuation> # A comma can also be an operator, but is matched as <punctuation> only. [ ; , . [ \] ( ) { } ] ) | ( # <whitespace> \s+ ) | ( # <invalid> ^$ # Empty. | [\s\S] # Catch-all rule for anything not matched by the above. ) ///g
[ { "context": "ata).set(authentications: authsData)\n keys = ['accessToken', 'authentications'].concat opts.userKeys\n don", "end": 726, "score": 0.9717827439308167, "start": 715, "tag": "KEY", "value": "accessToken" }, { "context": "tications: authsData)\n keys = ['accessTok...
lib/passport/serializers.coffee
craigspaeth/artsy-passport
0
# # Passport.js serialize/deserialize functions that turn user data # into a session. # _ = require 'underscore' opts = require '../options' request = require 'superagent' async = require 'async' module.exports.serialize = (user, done) -> async.parallel [ (cb) -> request .get("#{opts.ARTSY_URL}/api/v1/me") .set('X-Access-Token': user.get 'accessToken').end(cb) (cb) -> request .get("#{opts.ARTSY_URL}/api/v1/me/authentications") .set('X-Access-Token': user.get 'accessToken').end(cb) ], (err, results) -> return done err if err [{ body: userData },{ body: authsData }] = results user.set(userData).set(authentications: authsData) keys = ['accessToken', 'authentications'].concat opts.userKeys done null, user.pick(keys) module.exports.deserialize = (userData, done) -> done null, new opts.CurrentUser(userData)
46454
# # Passport.js serialize/deserialize functions that turn user data # into a session. # _ = require 'underscore' opts = require '../options' request = require 'superagent' async = require 'async' module.exports.serialize = (user, done) -> async.parallel [ (cb) -> request .get("#{opts.ARTSY_URL}/api/v1/me") .set('X-Access-Token': user.get 'accessToken').end(cb) (cb) -> request .get("#{opts.ARTSY_URL}/api/v1/me/authentications") .set('X-Access-Token': user.get 'accessToken').end(cb) ], (err, results) -> return done err if err [{ body: userData },{ body: authsData }] = results user.set(userData).set(authentications: authsData) keys = ['<KEY>', '<KEY>'].concat opts.userKeys done null, user.pick(keys) module.exports.deserialize = (userData, done) -> done null, new opts.CurrentUser(userData)
true
# # Passport.js serialize/deserialize functions that turn user data # into a session. # _ = require 'underscore' opts = require '../options' request = require 'superagent' async = require 'async' module.exports.serialize = (user, done) -> async.parallel [ (cb) -> request .get("#{opts.ARTSY_URL}/api/v1/me") .set('X-Access-Token': user.get 'accessToken').end(cb) (cb) -> request .get("#{opts.ARTSY_URL}/api/v1/me/authentications") .set('X-Access-Token': user.get 'accessToken').end(cb) ], (err, results) -> return done err if err [{ body: userData },{ body: authsData }] = results user.set(userData).set(authentications: authsData) keys = ['PI:KEY:<KEY>END_PI', 'PI:KEY:<KEY>END_PI'].concat opts.userKeys done null, user.pick(keys) module.exports.deserialize = (userData, done) -> done null, new opts.CurrentUser(userData)
[ { "context": "t() is 0\n Accounts.createUser\n username: 'admin'\n password: 'adminpassword'\n profile:\n ", "end": 134, "score": 0.9748339653015137, "start": 129, "tag": "USERNAME", "value": "admin" }, { "context": "eateUser\n username: 'admin'\n password...
server/seed.coffee
biomassives/materialize-meteor-mocha
0
Meteor.startup -> # Seeding with admin account if Meteor.users.find().count() is 0 Accounts.createUser username: 'admin' password: 'adminpassword' profile: roles: ['admin']
64999
Meteor.startup -> # Seeding with admin account if Meteor.users.find().count() is 0 Accounts.createUser username: 'admin' password: '<PASSWORD>' profile: roles: ['admin']
true
Meteor.startup -> # Seeding with admin account if Meteor.users.find().count() is 0 Accounts.createUser username: 'admin' password: 'PI:PASSWORD:<PASSWORD>END_PI' profile: roles: ['admin']
[ { "context": "re is licensed under the MIT License.\n\n Copyright Fedor Indutny, 2011.\n\n Permission is hereby granted, free of c", "end": 126, "score": 0.9996141195297241, "start": 113, "tag": "NAME", "value": "Fedor Indutny" } ]
node_modules/index/lib/index/core/unset.coffee
beshrkayali/monkey-release-action
12
### Unset functionality for Node index module This software is licensed under the MIT License. Copyright Fedor Indutny, 2011. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ### step = require 'step' utils = require '../../index/utils' exports.unset = (key, _callback) -> callback = (err, data) => @releaseLock() process.nextTick -> _callback and _callback err, data storage = @storage sort = @sort if @lock(=> @unset key, _callback) return iterate = (page, callback) -> item_index = utils.search page, sort, key item = page[item_index] if item_index is null # Not found # Even in that case unset should be successfull callback null return if item[2] # Leaf if sort(item[0], key) isnt 0 # Actually key doesn't match # So do nothing callback null return # Delete from leaf and if one will be empty # remove leaf from parent page.splice item_index, 1 if page.length > 0 # If resulting page isn't empty step -> storage.write page, @parallel() , callback return # Notify that item should be removed from parent index callback null, false else # Index page step -> storage.read item[1], @parallel() , (err, page) -> if err throw err iterate page, @parallel() , (err, result) -> if err callback err return if result is false # Delete item from index page page.splice item_index, 1 if page.length <= 1 callback null, page[0][1] return else if storage.isPosition result page[item_index][1] = result else callback null return step -> storage.write page, @parallel() , callback step -> storage.readRoot @parallel() , (err, root) -> if err throw err iterate root, @parallel() , (err, result) -> if err throw err if result is false # Create new root storage.write [], @parallel() else if storage.isPosition(result) # Overwrite old root @parallel() null, result else @parallel() null , (err, position) -> if err throw err if storage.isPosition position storage.writeRoot position, @parallel() else @parallel() null , callback
163797
### Unset functionality for Node index module This software is licensed under the MIT License. Copyright <NAME>, 2011. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ### step = require 'step' utils = require '../../index/utils' exports.unset = (key, _callback) -> callback = (err, data) => @releaseLock() process.nextTick -> _callback and _callback err, data storage = @storage sort = @sort if @lock(=> @unset key, _callback) return iterate = (page, callback) -> item_index = utils.search page, sort, key item = page[item_index] if item_index is null # Not found # Even in that case unset should be successfull callback null return if item[2] # Leaf if sort(item[0], key) isnt 0 # Actually key doesn't match # So do nothing callback null return # Delete from leaf and if one will be empty # remove leaf from parent page.splice item_index, 1 if page.length > 0 # If resulting page isn't empty step -> storage.write page, @parallel() , callback return # Notify that item should be removed from parent index callback null, false else # Index page step -> storage.read item[1], @parallel() , (err, page) -> if err throw err iterate page, @parallel() , (err, result) -> if err callback err return if result is false # Delete item from index page page.splice item_index, 1 if page.length <= 1 callback null, page[0][1] return else if storage.isPosition result page[item_index][1] = result else callback null return step -> storage.write page, @parallel() , callback step -> storage.readRoot @parallel() , (err, root) -> if err throw err iterate root, @parallel() , (err, result) -> if err throw err if result is false # Create new root storage.write [], @parallel() else if storage.isPosition(result) # Overwrite old root @parallel() null, result else @parallel() null , (err, position) -> if err throw err if storage.isPosition position storage.writeRoot position, @parallel() else @parallel() null , callback
true
### Unset functionality for Node index module This software is licensed under the MIT License. Copyright PI:NAME:<NAME>END_PI, 2011. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ### step = require 'step' utils = require '../../index/utils' exports.unset = (key, _callback) -> callback = (err, data) => @releaseLock() process.nextTick -> _callback and _callback err, data storage = @storage sort = @sort if @lock(=> @unset key, _callback) return iterate = (page, callback) -> item_index = utils.search page, sort, key item = page[item_index] if item_index is null # Not found # Even in that case unset should be successfull callback null return if item[2] # Leaf if sort(item[0], key) isnt 0 # Actually key doesn't match # So do nothing callback null return # Delete from leaf and if one will be empty # remove leaf from parent page.splice item_index, 1 if page.length > 0 # If resulting page isn't empty step -> storage.write page, @parallel() , callback return # Notify that item should be removed from parent index callback null, false else # Index page step -> storage.read item[1], @parallel() , (err, page) -> if err throw err iterate page, @parallel() , (err, result) -> if err callback err return if result is false # Delete item from index page page.splice item_index, 1 if page.length <= 1 callback null, page[0][1] return else if storage.isPosition result page[item_index][1] = result else callback null return step -> storage.write page, @parallel() , callback step -> storage.readRoot @parallel() , (err, root) -> if err throw err iterate root, @parallel() , (err, result) -> if err throw err if result is false # Create new root storage.write [], @parallel() else if storage.isPosition(result) # Overwrite old root @parallel() null, result else @parallel() null , (err, position) -> if err throw err if storage.isPosition position storage.writeRoot position, @parallel() else @parallel() null , callback
[ { "context": "###*\n *\n * tast\n * @author vfasky <vfasky@gmail.com>\n###\n'use strict'\n\n{View} = req", "end": 33, "score": 0.999073326587677, "start": 27, "tag": "USERNAME", "value": "vfasky" }, { "context": "###*\n *\n * tast\n * @author vfasky <vfasky@gmail.com>\n###\n'use stri...
example/src/toast.coffee
vfasky/mcore-weui
0
###* * * tast * @author vfasky <vfasky@gmail.com> ### 'use strict' {View} = require 'mcoreapp' weui = require 'mcore-weui' class Toast extends View run: -> @render require('../tpl/toast.html') showSuccess: -> weui.Toast.success.show '完成' false showLoading: -> weui.Toast.loading.show() module.exports = Toast module.exports.viewName = 'toast'
177678
###* * * tast * @author vfasky <<EMAIL>> ### 'use strict' {View} = require 'mcoreapp' weui = require 'mcore-weui' class Toast extends View run: -> @render require('../tpl/toast.html') showSuccess: -> weui.Toast.success.show '完成' false showLoading: -> weui.Toast.loading.show() module.exports = Toast module.exports.viewName = 'toast'
true
###* * * tast * @author vfasky <PI:EMAIL:<EMAIL>END_PI> ### 'use strict' {View} = require 'mcoreapp' weui = require 'mcore-weui' class Toast extends View run: -> @render require('../tpl/toast.html') showSuccess: -> weui.Toast.success.show '完成' false showLoading: -> weui.Toast.loading.show() module.exports = Toast module.exports.viewName = 'toast'
[ { "context": "e case', ->\n\t\t\tres = f mockData, mockState\n\t\t\teq 'Martins Gröna', res[3].name \n\t\tit 'sortBy stars, and correct av", "end": 484, "score": 0.9998952746391296, "start": 471, "tag": "NAME", "value": "Martins Gröna" }, { "context": "e case', ->\n\t\t\tres = f mock...
examples/restaurant-reviewer/src/base/test__lifters.coffee
Cottin/oublie
0
assert = require 'assert' {flip, merge, sortBy} = require 'ramda' #auto_require:ramda {change} = require 'ramda-extras' lifters = require './lifters' mockData = require './mockData' mockState = require './mockState' eq = flip assert.equal deepEq = flip assert.deepStrictEqual throws = (f) -> assert.throws f, Error describe 'lifters', -> describe 'restaurantsSorted', -> {f} = lifters.restaurantsSorted it 'simple case', -> res = f mockData, mockState eq 'Martins Gröna', res[3].name it 'sortBy stars, and correct avg. and color', -> res = f merge(mockData, {ui: {sortBy: 'stars'}}), mockState eq 'La Neta', res[1].name eq 3.7, res[1].stars eq '#6128BC', res[1].color describe 'selectedRestaurant', -> {f} = lifters.selectedRestaurant it 'simple case', -> res = f mockData, mockState eq 'Rolfs Kök', res.name it 'null cases', -> res = f mockData, merge(mockState, {restaurantsSorted: null}) eq null, res res = f change({ui: {selected: undefined}}, mockData), mockState eq null, res describe 'reviewItems', -> {f} = lifters.reviewItems it 'simple case', -> res = f mockData, mockState eq 1, res[1].restaurant expected = {name: 'Martin', initials: 'M', color: '#D78DDA'} deepEq expected, res[1].user
41526
assert = require 'assert' {flip, merge, sortBy} = require 'ramda' #auto_require:ramda {change} = require 'ramda-extras' lifters = require './lifters' mockData = require './mockData' mockState = require './mockState' eq = flip assert.equal deepEq = flip assert.deepStrictEqual throws = (f) -> assert.throws f, Error describe 'lifters', -> describe 'restaurantsSorted', -> {f} = lifters.restaurantsSorted it 'simple case', -> res = f mockData, mockState eq '<NAME>', res[3].name it 'sortBy stars, and correct avg. and color', -> res = f merge(mockData, {ui: {sortBy: 'stars'}}), mockState eq 'La Neta', res[1].name eq 3.7, res[1].stars eq '#6128BC', res[1].color describe 'selectedRestaurant', -> {f} = lifters.selectedRestaurant it 'simple case', -> res = f mockData, mockState eq '<NAME>', res.name it 'null cases', -> res = f mockData, merge(mockState, {restaurantsSorted: null}) eq null, res res = f change({ui: {selected: undefined}}, mockData), mockState eq null, res describe 'reviewItems', -> {f} = lifters.reviewItems it 'simple case', -> res = f mockData, mockState eq 1, res[1].restaurant expected = {name: '<NAME>', initials: 'M', color: '#D78DDA'} deepEq expected, res[1].user
true
assert = require 'assert' {flip, merge, sortBy} = require 'ramda' #auto_require:ramda {change} = require 'ramda-extras' lifters = require './lifters' mockData = require './mockData' mockState = require './mockState' eq = flip assert.equal deepEq = flip assert.deepStrictEqual throws = (f) -> assert.throws f, Error describe 'lifters', -> describe 'restaurantsSorted', -> {f} = lifters.restaurantsSorted it 'simple case', -> res = f mockData, mockState eq 'PI:NAME:<NAME>END_PI', res[3].name it 'sortBy stars, and correct avg. and color', -> res = f merge(mockData, {ui: {sortBy: 'stars'}}), mockState eq 'La Neta', res[1].name eq 3.7, res[1].stars eq '#6128BC', res[1].color describe 'selectedRestaurant', -> {f} = lifters.selectedRestaurant it 'simple case', -> res = f mockData, mockState eq 'PI:NAME:<NAME>END_PI', res.name it 'null cases', -> res = f mockData, merge(mockState, {restaurantsSorted: null}) eq null, res res = f change({ui: {selected: undefined}}, mockData), mockState eq null, res describe 'reviewItems', -> {f} = lifters.reviewItems it 'simple case', -> res = f mockData, mockState eq 1, res[1].restaurant expected = {name: 'PI:NAME:<NAME>END_PI', initials: 'M', color: '#D78DDA'} deepEq expected, res[1].user
[ { "context": " = (robot) ->\n\n songs = [\n 'FINAL COMMANDER by Mizuki Nana ~ https://radio.animebits.moe/player/hash/7c57e48", "end": 76, "score": 0.9997819066047668, "start": 65, "tag": "NAME", "value": "Mizuki Nana" }, { "context": "es.tv/torrents2.php?id=57720',\n 'Extermi...
scripts/symphogay.coffee
WeebHoarder/kana
0
module.exports = (robot) -> songs = [ 'FINAL COMMANDER by Mizuki Nana ~ https://radio.animebits.moe/player/hash/7c57e488c8c1 ~ https://animebytes.tv/torrents2.php?id=57720', 'Exterminate by Mizuki Nana ~ https://radio.animebits.moe/player/hash/b92a0114958e ~ https://animebytes.tv/torrents2.php?id=49119', 'TESTAMENT by Mizuki Nana ~ https://radio.animebits.moe/player/hash/46a2911eb456 ~ https://animebytes.tv/torrents2.php?id=46911', 'Vitalization by Mizuki Nana ~ https://radio.animebits.moe/player/hash/691e1d8a38da ~ https://animebytes.tv/torrents2.php?id=22995', 'Synchrogazer by Mizuki Nana ~ https://radio.animebits.moe/player/hash/8fe559c07363 ~ https://animebytes.tv/torrents2.php?id=13534', 'Vitalization -Aufwachen Form- by Mizuki Nana ~ https://radio.animebits.moe/player/hash/0f8c3c18242d ~ https://animebytes.tv/torrents2.php?id=26608', 'TESTAMENT -Aufwachen Form- by Mizuki Nana ~ https://radio.animebits.moe/player/hash/a1a5c83493f2 ~ https://animebytes.tv/torrents2.php?id=49119', 'Synchrogazer -Aufwachen Form- by Mizuki Nana ~ https://radio.animebits.moe/player/hash/81d7bbbacd42 ~ https://animebytes.tv/torrents2.php?id=16863', 'https://mei.animebytes.tv/D46VG0mwINv.png', 'UNLIMITED BEAT by Mizuki Nana ~ https://radio.animebits.moe/player/hash/18e18823107f ~ https://animebytes.tv/torrents2.php?id=43365', 'METANOIA by Mizuki Nana ~ https://radio.animebits.moe/player/hash/4379a84c66f9 ~ https://animebytes.tv/torrents2.php?id=57062', 'METANOIA -Aufwachen Form- by Mizuki Nana ~ https://radio.animebits.moe/player/hash/3be87f1f3252 ~ https://animebytes.tv/torrents2.php?id=58724&torrentid=429871', 'FINAL COMMANDER -Aufwachen Form- by Mizuki Nana ~ https://radio.animebits.moe/player/hash/9f4ab07bede1 ~ https://animebytes.tv/torrents2.php?id=58724&torrentid=429871', ] robot.hear /^!nana$/i, (msg) -> msg.send songs[Math.floor(Math.random() * songs.length)] robot.hear /^!metanoia$/i, (msg) -> msg.send songs[Math.floor(10 + Math.random() * 2)]
48208
module.exports = (robot) -> songs = [ 'FINAL COMMANDER by <NAME> ~ https://radio.animebits.moe/player/hash/7c57e488c8c1 ~ https://animebytes.tv/torrents2.php?id=57720', 'Exterminate by <NAME> ~ https://radio.animebits.moe/player/hash/b92a0114958e ~ https://animebytes.tv/torrents2.php?id=49119', 'TESTAMENT by <NAME> ~ https://radio.animebits.moe/player/hash/46a2911eb456 ~ https://animebytes.tv/torrents2.php?id=46911', 'Vitalization by <NAME> ~ https://radio.animebits.moe/player/hash/691e1d8a38da ~ https://animebytes.tv/torrents2.php?id=22995', 'Synchrogazer by <NAME> ~ https://radio.animebits.moe/player/hash/8fe559c07363 ~ https://animebytes.tv/torrents2.php?id=13534', 'Vitalization -Aufwachen Form- by <NAME> ~ https://radio.animebits.moe/player/hash/0f8c3c18242d ~ https://animebytes.tv/torrents2.php?id=26608', 'TESTAMENT -Aufwachen Form- by <NAME> ~ https://radio.animebits.moe/player/hash/a1a5c83493f2 ~ https://animebytes.tv/torrents2.php?id=49119', 'Synchrogazer -Aufwachen Form- by <NAME> ~ https://radio.animebits.moe/player/hash/81d7bbbacd42 ~ https://animebytes.tv/torrents2.php?id=16863', 'https://mei.animebytes.tv/D46VG0mwINv.png', 'UNLIMITED BEAT by <NAME> ~ https://radio.animebits.moe/player/hash/18e18823107f ~ https://animebytes.tv/torrents2.php?id=43365', 'METANOIA by <NAME> ~ https://radio.animebits.moe/player/hash/4379a84c66f9 ~ https://animebytes.tv/torrents2.php?id=57062', 'METANOIA -Aufwachen Form- by <NAME> ~ https://radio.animebits.moe/player/hash/3be87f1f3252 ~ https://animebytes.tv/torrents2.php?id=58724&torrentid=429871', 'FINAL COMMANDER -Aufwachen Form- by <NAME> ~ https://radio.animebits.moe/player/hash/9f4ab07bede1 ~ https://animebytes.tv/torrents2.php?id=58724&torrentid=429871', ] robot.hear /^!nana$/i, (msg) -> msg.send songs[Math.floor(Math.random() * songs.length)] robot.hear /^!metanoia$/i, (msg) -> msg.send songs[Math.floor(10 + Math.random() * 2)]
true
module.exports = (robot) -> songs = [ 'FINAL COMMANDER by PI:NAME:<NAME>END_PI ~ https://radio.animebits.moe/player/hash/7c57e488c8c1 ~ https://animebytes.tv/torrents2.php?id=57720', 'Exterminate by PI:NAME:<NAME>END_PI ~ https://radio.animebits.moe/player/hash/b92a0114958e ~ https://animebytes.tv/torrents2.php?id=49119', 'TESTAMENT by PI:NAME:<NAME>END_PI ~ https://radio.animebits.moe/player/hash/46a2911eb456 ~ https://animebytes.tv/torrents2.php?id=46911', 'Vitalization by PI:NAME:<NAME>END_PI ~ https://radio.animebits.moe/player/hash/691e1d8a38da ~ https://animebytes.tv/torrents2.php?id=22995', 'Synchrogazer by PI:NAME:<NAME>END_PI ~ https://radio.animebits.moe/player/hash/8fe559c07363 ~ https://animebytes.tv/torrents2.php?id=13534', 'Vitalization -Aufwachen Form- by PI:NAME:<NAME>END_PI ~ https://radio.animebits.moe/player/hash/0f8c3c18242d ~ https://animebytes.tv/torrents2.php?id=26608', 'TESTAMENT -Aufwachen Form- by PI:NAME:<NAME>END_PI ~ https://radio.animebits.moe/player/hash/a1a5c83493f2 ~ https://animebytes.tv/torrents2.php?id=49119', 'Synchrogazer -Aufwachen Form- by PI:NAME:<NAME>END_PI ~ https://radio.animebits.moe/player/hash/81d7bbbacd42 ~ https://animebytes.tv/torrents2.php?id=16863', 'https://mei.animebytes.tv/D46VG0mwINv.png', 'UNLIMITED BEAT by PI:NAME:<NAME>END_PI ~ https://radio.animebits.moe/player/hash/18e18823107f ~ https://animebytes.tv/torrents2.php?id=43365', 'METANOIA by PI:NAME:<NAME>END_PI ~ https://radio.animebits.moe/player/hash/4379a84c66f9 ~ https://animebytes.tv/torrents2.php?id=57062', 'METANOIA -Aufwachen Form- by PI:NAME:<NAME>END_PI ~ https://radio.animebits.moe/player/hash/3be87f1f3252 ~ https://animebytes.tv/torrents2.php?id=58724&torrentid=429871', 'FINAL COMMANDER -Aufwachen Form- by PI:NAME:<NAME>END_PI ~ https://radio.animebits.moe/player/hash/9f4ab07bede1 ~ https://animebytes.tv/torrents2.php?id=58724&torrentid=429871', ] robot.hear /^!nana$/i, (msg) -> msg.send songs[Math.floor(Math.random() * songs.length)] robot.hear /^!metanoia$/i, (msg) -> msg.send songs[Math.floor(10 + Math.random() * 2)]
[ { "context": "tem in the menu is selected\n#\n# Copyright (C) 2012 Nikolay Nemshilov\n#\nclass Menu extends Element\n extend:\n curren", "end": 253, "score": 0.9998888373374939, "start": 236, "tag": "NAME", "value": "Nikolay Nemshilov" } ]
ui/core/src/menu.coffee
lovely-io/lovely.io-stl
2
# # The drop-down menu unit # # Events: # * `show` when the menu is shown # * `hide` when the menu is hidden # * `pick` when an item in the menu is picked # * `select` when an item in the menu is selected # # Copyright (C) 2012 Nikolay Nemshilov # class Menu extends Element extend: current: null # current menu reference # # Basic constructor # # @param {Object} html options # @return {Menu} this # constructor: (options)-> options = options[0] if options instanceof dom.NodeList options = options._ if options instanceof Element if options && options.nodeType is 1 @$super options else @$super 'nav', options @addClass 'lui-menu' @on 'click', (event)-> if (link = event.find('a')) && link.parent() is @ @emit('pick', link: link) @on 'mouseover', (event)-> if (link = event.find('a')) && link.parent() is @ @emit('select', link: link) @on 'pick', 'hide' # # Shows the menu at the element # # @param {String|HTMLElement|dom.Element|dom.NodeList} element reference # @param {String} menu location 'bottom left', 'top-right' and so on # @return {Menu} this # showAt: (element, location)-> element = dom(element) if typeof(element) is 'string' or element.nodeType is 1 element = element[0] if element instanceof dom.NodeList position = element.position() location or= 'bottom left' if element @style(visibility: 'hidden', display: 'block').insertTo(element, 'after') # adjusting the position for specified location position.y += element.size().y if location.indexOf('bottom') isnt -1 position.x -= (@size().x - element.size().x) if location.indexOf('right') isnt -1 position.y -= @size().y if location.indexOf('top') isnt -1 position.y = 0 if position.y < 0 position.x = 0 if position.x < 0 @position(position).style(visibility: 'visible').show() return @ # # Shows the element and emits the 'show' event # # @return {Menu} this # show: -> Menu.current = @constructor.current = @$super.apply(@, arguments).emit('show') # # Making the menu element to get removed out of the DOM # # @return {Menu} this # hide: -> Menu.current = @constructor.current = null @$super.apply(@, arguments).emit('hide') # # Selects the next link on the menu # # @return {Menu} this # selectNext: (step=1)-> links = @children('a') index = links.indexOf(@currentLink) + step index = links.length - 1 if index > links.length - 1 index = 0 if index < 0 if @currentLink = links[index] @currentLink.radioClass('lui-active') @emit 'select', link: @currentLink return @ # # Selects the previous link on the menu # # @return {Menu} this # selectPrevious: -> @selectNext(-1) # # Picks the currently selected item on the menu # # @return {Menu} this # pickCurrent: -> @emit('pick', link: @currentLink) if @currentLink return @ # # Making all the hanging menus to get closed on menu clicks # $(document).on 'click', (event)-> unless event.find('.lui-menu') or event.find('[data-toggle]') $('.lui-menu').forEach (menu)-> menu.hide() if menu.style('position') is 'absolute' # # Handling keyboard navigation # $(document).on 'keydown', (event)-> if Menu.current isnt null switch event.keyCode when 40 then event.preventDefault(); Menu.current.selectNext() when 38 then event.preventDefault(); Menu.current.selectPrevious() when 13 then event.preventDefault(); Menu.current.pickCurrent() when 27 then Menu.current.hide()
163976
# # The drop-down menu unit # # Events: # * `show` when the menu is shown # * `hide` when the menu is hidden # * `pick` when an item in the menu is picked # * `select` when an item in the menu is selected # # Copyright (C) 2012 <NAME> # class Menu extends Element extend: current: null # current menu reference # # Basic constructor # # @param {Object} html options # @return {Menu} this # constructor: (options)-> options = options[0] if options instanceof dom.NodeList options = options._ if options instanceof Element if options && options.nodeType is 1 @$super options else @$super 'nav', options @addClass 'lui-menu' @on 'click', (event)-> if (link = event.find('a')) && link.parent() is @ @emit('pick', link: link) @on 'mouseover', (event)-> if (link = event.find('a')) && link.parent() is @ @emit('select', link: link) @on 'pick', 'hide' # # Shows the menu at the element # # @param {String|HTMLElement|dom.Element|dom.NodeList} element reference # @param {String} menu location 'bottom left', 'top-right' and so on # @return {Menu} this # showAt: (element, location)-> element = dom(element) if typeof(element) is 'string' or element.nodeType is 1 element = element[0] if element instanceof dom.NodeList position = element.position() location or= 'bottom left' if element @style(visibility: 'hidden', display: 'block').insertTo(element, 'after') # adjusting the position for specified location position.y += element.size().y if location.indexOf('bottom') isnt -1 position.x -= (@size().x - element.size().x) if location.indexOf('right') isnt -1 position.y -= @size().y if location.indexOf('top') isnt -1 position.y = 0 if position.y < 0 position.x = 0 if position.x < 0 @position(position).style(visibility: 'visible').show() return @ # # Shows the element and emits the 'show' event # # @return {Menu} this # show: -> Menu.current = @constructor.current = @$super.apply(@, arguments).emit('show') # # Making the menu element to get removed out of the DOM # # @return {Menu} this # hide: -> Menu.current = @constructor.current = null @$super.apply(@, arguments).emit('hide') # # Selects the next link on the menu # # @return {Menu} this # selectNext: (step=1)-> links = @children('a') index = links.indexOf(@currentLink) + step index = links.length - 1 if index > links.length - 1 index = 0 if index < 0 if @currentLink = links[index] @currentLink.radioClass('lui-active') @emit 'select', link: @currentLink return @ # # Selects the previous link on the menu # # @return {Menu} this # selectPrevious: -> @selectNext(-1) # # Picks the currently selected item on the menu # # @return {Menu} this # pickCurrent: -> @emit('pick', link: @currentLink) if @currentLink return @ # # Making all the hanging menus to get closed on menu clicks # $(document).on 'click', (event)-> unless event.find('.lui-menu') or event.find('[data-toggle]') $('.lui-menu').forEach (menu)-> menu.hide() if menu.style('position') is 'absolute' # # Handling keyboard navigation # $(document).on 'keydown', (event)-> if Menu.current isnt null switch event.keyCode when 40 then event.preventDefault(); Menu.current.selectNext() when 38 then event.preventDefault(); Menu.current.selectPrevious() when 13 then event.preventDefault(); Menu.current.pickCurrent() when 27 then Menu.current.hide()
true
# # The drop-down menu unit # # Events: # * `show` when the menu is shown # * `hide` when the menu is hidden # * `pick` when an item in the menu is picked # * `select` when an item in the menu is selected # # Copyright (C) 2012 PI:NAME:<NAME>END_PI # class Menu extends Element extend: current: null # current menu reference # # Basic constructor # # @param {Object} html options # @return {Menu} this # constructor: (options)-> options = options[0] if options instanceof dom.NodeList options = options._ if options instanceof Element if options && options.nodeType is 1 @$super options else @$super 'nav', options @addClass 'lui-menu' @on 'click', (event)-> if (link = event.find('a')) && link.parent() is @ @emit('pick', link: link) @on 'mouseover', (event)-> if (link = event.find('a')) && link.parent() is @ @emit('select', link: link) @on 'pick', 'hide' # # Shows the menu at the element # # @param {String|HTMLElement|dom.Element|dom.NodeList} element reference # @param {String} menu location 'bottom left', 'top-right' and so on # @return {Menu} this # showAt: (element, location)-> element = dom(element) if typeof(element) is 'string' or element.nodeType is 1 element = element[0] if element instanceof dom.NodeList position = element.position() location or= 'bottom left' if element @style(visibility: 'hidden', display: 'block').insertTo(element, 'after') # adjusting the position for specified location position.y += element.size().y if location.indexOf('bottom') isnt -1 position.x -= (@size().x - element.size().x) if location.indexOf('right') isnt -1 position.y -= @size().y if location.indexOf('top') isnt -1 position.y = 0 if position.y < 0 position.x = 0 if position.x < 0 @position(position).style(visibility: 'visible').show() return @ # # Shows the element and emits the 'show' event # # @return {Menu} this # show: -> Menu.current = @constructor.current = @$super.apply(@, arguments).emit('show') # # Making the menu element to get removed out of the DOM # # @return {Menu} this # hide: -> Menu.current = @constructor.current = null @$super.apply(@, arguments).emit('hide') # # Selects the next link on the menu # # @return {Menu} this # selectNext: (step=1)-> links = @children('a') index = links.indexOf(@currentLink) + step index = links.length - 1 if index > links.length - 1 index = 0 if index < 0 if @currentLink = links[index] @currentLink.radioClass('lui-active') @emit 'select', link: @currentLink return @ # # Selects the previous link on the menu # # @return {Menu} this # selectPrevious: -> @selectNext(-1) # # Picks the currently selected item on the menu # # @return {Menu} this # pickCurrent: -> @emit('pick', link: @currentLink) if @currentLink return @ # # Making all the hanging menus to get closed on menu clicks # $(document).on 'click', (event)-> unless event.find('.lui-menu') or event.find('[data-toggle]') $('.lui-menu').forEach (menu)-> menu.hide() if menu.style('position') is 'absolute' # # Handling keyboard navigation # $(document).on 'keydown', (event)-> if Menu.current isnt null switch event.keyCode when 40 then event.preventDefault(); Menu.current.selectNext() when 38 then event.preventDefault(); Menu.current.selectPrevious() when 13 then event.preventDefault(); Menu.current.pickCurrent() when 27 then Menu.current.hide()
[ { "context": "###\n @author Takahiro INOUE <takahiro.inoue@aist.go.jp>\n @license Songle Wid", "end": 28, "score": 0.999874472618103, "start": 14, "tag": "NAME", "value": "Takahiro INOUE" }, { "context": "###\n @author Takahiro INOUE <takahiro.inoue@aist.go.jp>\n @license Songle ...
extras/src/shared-module.coffee
ongacrest/songle-widget-api-examples
16
### @author Takahiro INOUE <takahiro.inoue@aist.go.jp> @license Songle Widget API Examples Visit http://songle.jp/info/Credit.html OR http://widget.songle.jp/docs/v1 for documentation. Copyright (c) 2015 National Institute of Advanced Industrial Science and Technology (AIST) Distributed under the terms of the MIT license only for non-commercial purposes. http://www.opensource.org/licenses/mit-license.html This notice shall be included in all copies or substantial portions of this Songle Widget API Examples. If you are interested in commercial use of Songle Widget API, please contact "songle-ml@aist.go.jp". ### window.__swExtra__ ?= {} ### @function ### __swExtra__.initializeAllModule = (module) -> __swExtra__.modules ?= [] __swExtra__.modules.push(module) window.onSongleWidgetCreate = (apiKey, songleWidget) -> __swExtra__.initializeCreateModule(songleWidget) window.onSongleWidgetError = (apiKey, songleWidget) -> __swExtra__.initializeErrorModule(songleWidget) window.onSongleWidgetReady = (apiKey, songleWidget) -> __swExtra__.initializeReadyModule(songleWidget) ### @function ### __swExtra__.initializeCreateModule = (songleWidget, options = {}) -> options.force ?= false for module in __swExtra__.modules if !module.__wasCreated__ || options.force module.onCreate && module.onCreate(songleWidget) module.__wasCreated__ = true ### @function ### __swExtra__.initializeErrorModule = (songleWidget, options = {}) -> options.force ?= false for module in __swExtra__.modules if !module.__wasErrored__ || options.force module.onError && module.onError(songleWidget) module.__wasErrored__ = true ### @function ### __swExtra__.initializeReadyModule = (songleWidget, options = {}) -> options.force ?= false for module in __swExtra__.modules if !module.__wasReadied__ || options.force module.onReady && module.onReady(songleWidget) module.__wasReadied__ = true ### @function ### __swExtra__.random = (min, max) -> min ?= 0x00000000 max ?= 0x7fffffff return Math.floor(Math.random() * ((max - min) + 1) + min)
163606
### @author <NAME> <<EMAIL>> @license Songle Widget API Examples Visit http://songle.jp/info/Credit.html OR http://widget.songle.jp/docs/v1 for documentation. Copyright (c) 2015 National Institute of Advanced Industrial Science and Technology (AIST) Distributed under the terms of the MIT license only for non-commercial purposes. http://www.opensource.org/licenses/mit-license.html This notice shall be included in all copies or substantial portions of this Songle Widget API Examples. If you are interested in commercial use of Songle Widget API, please contact "<EMAIL>". ### window.__swExtra__ ?= {} ### @function ### __swExtra__.initializeAllModule = (module) -> __swExtra__.modules ?= [] __swExtra__.modules.push(module) window.onSongleWidgetCreate = (apiKey, songleWidget) -> __swExtra__.initializeCreateModule(songleWidget) window.onSongleWidgetError = (apiKey, songleWidget) -> __swExtra__.initializeErrorModule(songleWidget) window.onSongleWidgetReady = (apiKey, songleWidget) -> __swExtra__.initializeReadyModule(songleWidget) ### @function ### __swExtra__.initializeCreateModule = (songleWidget, options = {}) -> options.force ?= false for module in __swExtra__.modules if !module.__wasCreated__ || options.force module.onCreate && module.onCreate(songleWidget) module.__wasCreated__ = true ### @function ### __swExtra__.initializeErrorModule = (songleWidget, options = {}) -> options.force ?= false for module in __swExtra__.modules if !module.__wasErrored__ || options.force module.onError && module.onError(songleWidget) module.__wasErrored__ = true ### @function ### __swExtra__.initializeReadyModule = (songleWidget, options = {}) -> options.force ?= false for module in __swExtra__.modules if !module.__wasReadied__ || options.force module.onReady && module.onReady(songleWidget) module.__wasReadied__ = true ### @function ### __swExtra__.random = (min, max) -> min ?= 0x00000000 max ?= 0x7fffffff return Math.floor(Math.random() * ((max - min) + 1) + min)
true
### @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> @license Songle Widget API Examples Visit http://songle.jp/info/Credit.html OR http://widget.songle.jp/docs/v1 for documentation. Copyright (c) 2015 National Institute of Advanced Industrial Science and Technology (AIST) Distributed under the terms of the MIT license only for non-commercial purposes. http://www.opensource.org/licenses/mit-license.html This notice shall be included in all copies or substantial portions of this Songle Widget API Examples. If you are interested in commercial use of Songle Widget API, please contact "PI:EMAIL:<EMAIL>END_PI". ### window.__swExtra__ ?= {} ### @function ### __swExtra__.initializeAllModule = (module) -> __swExtra__.modules ?= [] __swExtra__.modules.push(module) window.onSongleWidgetCreate = (apiKey, songleWidget) -> __swExtra__.initializeCreateModule(songleWidget) window.onSongleWidgetError = (apiKey, songleWidget) -> __swExtra__.initializeErrorModule(songleWidget) window.onSongleWidgetReady = (apiKey, songleWidget) -> __swExtra__.initializeReadyModule(songleWidget) ### @function ### __swExtra__.initializeCreateModule = (songleWidget, options = {}) -> options.force ?= false for module in __swExtra__.modules if !module.__wasCreated__ || options.force module.onCreate && module.onCreate(songleWidget) module.__wasCreated__ = true ### @function ### __swExtra__.initializeErrorModule = (songleWidget, options = {}) -> options.force ?= false for module in __swExtra__.modules if !module.__wasErrored__ || options.force module.onError && module.onError(songleWidget) module.__wasErrored__ = true ### @function ### __swExtra__.initializeReadyModule = (songleWidget, options = {}) -> options.force ?= false for module in __swExtra__.modules if !module.__wasReadied__ || options.force module.onReady && module.onReady(songleWidget) module.__wasReadied__ = true ### @function ### __swExtra__.random = (min, max) -> min ?= 0x00000000 max ?= 0x7fffffff return Math.floor(Math.random() * ((max - min) + 1) + min)
[ { "context": " profile: new Profile(fabricate 'profile', name: 'Foobarz', owner_type: 'PartnerGallery') }\n { local", "end": 501, "score": 0.9997522830963135, "start": 494, "tag": "NAME", "value": "Foobarz" }, { "context": "e.sync.args)[2].success fabricate('partner', id: 'foo...
src/mobile/apps/partner_profile/test/routes.coffee
kanaabe/force
1
_ = require 'underscore' { fabricate } = require 'antigravity' sinon = require 'sinon' routes = require '../routes' Profile = require '../../../models/profile' Backbone = require 'backbone' describe 'Profile page', -> beforeEach -> sinon.stub Backbone, 'sync' afterEach -> Backbone.sync.restore() describe '#index', -> it 'renders the index page passing on the profile and featured show', -> routes.index( { profile: new Profile(fabricate 'profile', name: 'Foobarz', owner_type: 'PartnerGallery') } { locals: { sd: {} }, render: renderStub = sinon.stub() } ) _.last(Backbone.sync.args)[2].success fabricate('partner', id: 'foobar1', displayable_shows_count: 1) _.last(Backbone.sync.args)[2].success { results: [] } renderStub.args[0][0].should.equal 'index' renderStub.args[0][1].profile.get('name').should.equal 'Foobarz' describe '#shows', -> it 'renders the shows page passing on the current shows, upcoming shows and past shows', -> Backbone.sync .onCall 0 .yieldsTo 'success', [ fabricate('show', status: 'running', name: 'Foo') ] .returns Promise.resolve [ fabricate('show', status: 'running', name: 'Foo') ] Backbone.sync .onCall 1 .yieldsTo 'success', [ fabricate('show', status: 'upcoming', name: 'Meow') ] .returns Promise.resolve [ fabricate('show', status: 'upcoming', name: 'Meow') ] Backbone.sync .onCall 2 .yieldsTo 'success', [ fabricate('show', status: 'closed', name: 'Bar') ] .returns Promise.resolve [ fabricate('show', status: 'closed', name: 'Bar') ] renderStub = sinon.stub() routes.shows( { profile: new Profile(fabricate 'profile', name: 'Foobarz', owner_type: 'PartnerGallery') } { render: renderStub } ).then -> renderStub.args[0][0].should.equal 'shows_page' renderStub.args[0][1].profile.get('name').should.equal 'Foobarz' renderStub.args[0][1].currentShows.models[0].get('name').should.equal 'Foo' renderStub.args[0][1].currentShows.models[1].get('name').should.equal 'Meow' renderStub.args[0][1].pastShows.models[0].get('name').should.equal 'Bar' describe '#artists', -> it 'renders the artists page by passing on the represented/unrep groups', -> routes.artists( { profile: new Profile(fabricate 'profile', name: 'Foobarz', owner_type: 'PartnerGallery') } { render: renderStub = sinon.stub() } ) Backbone.sync.args[0][2].success [ { artist: fabricate('artist', name: 'Foo'), represented_by: true, image_versions: ['tall'], image_url: '/Foo/bar' } { artist: fabricate('artist', name: 'Bar'), represented_by: false } { artist: fabricate('artist', name: 'Baz'), represented_by: false, published_artworks_count: 1 } ] Backbone.sync.args[0][2].success [] renderStub.args[0][0].should.equal 'artists' renderStub.args[0][1].profile.get('name').should.equal 'Foobarz' renderStub.args[0][1].represented[0].get('name').should.equal 'Foo' renderStub.args[0][1].unrepresented[0].get('name').should.equal 'Baz' describe '#contact', -> it 'renders the contact page by passing on the partner locations groupped by city', -> routes.contact( profile: new Profile fabricate('profile' name: 'Foobarz' owner_type: 'PartnerGallery' owner: fabricate('partner' id: 'foobarz' profile_layout: 'gallery_one')) { render: renderStub = sinon.stub() } ) _.last(Backbone.sync.args)[2].success fabricate('partner', id: 'foobar1', displayable_shows_count: 1) _.last(Backbone.sync.args)[2].success [ fabricate('location', city: 'Zoo York') fabricate('location', city: 'Zoo York') fabricate('location', city: 'Cincinnati') ] renderStub.args[0][0].should.equal 'contact' renderStub.args[0][1].profile.get('name').should.equal 'Foobarz' renderStub.args[0][1].locationGroups['Zoo York'].length.should.equal 2 it 'renders 404 page for non-active partners', -> next = sinon.spy() renderStub = sinon.stub() routes.contact( profile: new Profile fabricate('profile' name: 'Foobarz' owner_type: 'PartnerGallery' owner: fabricate('partner' id: 'foobarz' profile_layout: 'gallery_default')) { render: renderStub } next ) error = next.getCall(0).args[0] error.status.should.equal(404) error.message.should.equal('Not Found') describe '#fetchArtworksAndRender', -> xit 'renders the partner\'s works based on parameters', -> routes.fetchArtworksAndRender( { label: "Works", profile: new Profile(fabricate 'profile', name: 'Foobarz', owner_type: 'PartnerInstitution') } { render: renderStub = sinon.stub() } ) Backbone.sync.args[0][2].success [ [fabricate('artwork')] ] renderStub.args[0][0].should.equal 'contact' renderStub.args[0][1].profile.get('name').should.equal 'Foobarz' renderStub.args[0][1].locationGroups['Zoo York'].length.should.equal 2
217232
_ = require 'underscore' { fabricate } = require 'antigravity' sinon = require 'sinon' routes = require '../routes' Profile = require '../../../models/profile' Backbone = require 'backbone' describe 'Profile page', -> beforeEach -> sinon.stub Backbone, 'sync' afterEach -> Backbone.sync.restore() describe '#index', -> it 'renders the index page passing on the profile and featured show', -> routes.index( { profile: new Profile(fabricate 'profile', name: '<NAME>', owner_type: 'PartnerGallery') } { locals: { sd: {} }, render: renderStub = sinon.stub() } ) _.last(Backbone.sync.args)[2].success fabricate('partner', id: 'foobar1', displayable_shows_count: 1) _.last(Backbone.sync.args)[2].success { results: [] } renderStub.args[0][0].should.equal 'index' renderStub.args[0][1].profile.get('name').should.equal '<NAME>' describe '#shows', -> it 'renders the shows page passing on the current shows, upcoming shows and past shows', -> Backbone.sync .onCall 0 .yieldsTo 'success', [ fabricate('show', status: 'running', name: 'Foo') ] .returns Promise.resolve [ fabricate('show', status: 'running', name: 'Foo') ] Backbone.sync .onCall 1 .yieldsTo 'success', [ fabricate('show', status: 'upcoming', name: 'Meow') ] .returns Promise.resolve [ fabricate('show', status: 'upcoming', name: 'Meow') ] Backbone.sync .onCall 2 .yieldsTo 'success', [ fabricate('show', status: 'closed', name: 'Bar') ] .returns Promise.resolve [ fabricate('show', status: 'closed', name: 'Bar') ] renderStub = sinon.stub() routes.shows( { profile: new Profile(fabricate 'profile', name: '<NAME>', owner_type: 'PartnerGallery') } { render: renderStub } ).then -> renderStub.args[0][0].should.equal 'shows_page' renderStub.args[0][1].profile.get('name').should.equal '<NAME>' renderStub.args[0][1].currentShows.models[0].get('name').should.equal '<NAME>' renderStub.args[0][1].currentShows.models[1].get('name').should.equal '<NAME>' renderStub.args[0][1].pastShows.models[0].get('name').should.equal 'Bar' describe '#artists', -> it 'renders the artists page by passing on the represented/unrep groups', -> routes.artists( { profile: new Profile(fabricate 'profile', name: '<NAME>', owner_type: 'PartnerGallery') } { render: renderStub = sinon.stub() } ) Backbone.sync.args[0][2].success [ { artist: fabricate('artist', name: '<NAME>'), represented_by: true, image_versions: ['tall'], image_url: '/Foo/bar' } { artist: fabricate('artist', name: '<NAME>'), represented_by: false } { artist: fabricate('artist', name: '<NAME>'), represented_by: false, published_artworks_count: 1 } ] Backbone.sync.args[0][2].success [] renderStub.args[0][0].should.equal 'artists' renderStub.args[0][1].profile.get('name').should.equal '<NAME>' renderStub.args[0][1].represented[0].get('name').should.equal '<NAME>' renderStub.args[0][1].unrepresented[0].get('name').should.equal '<NAME>' describe '#contact', -> it 'renders the contact page by passing on the partner locations groupped by city', -> routes.contact( profile: new Profile fabricate('profile' name: '<NAME>' owner_type: 'PartnerGallery' owner: fabricate('partner' id: 'foobarz' profile_layout: 'gallery_one')) { render: renderStub = sinon.stub() } ) _.last(Backbone.sync.args)[2].success fabricate('partner', id: 'foobar1', displayable_shows_count: 1) _.last(Backbone.sync.args)[2].success [ fabricate('location', city: 'Zoo York') fabricate('location', city: 'Zoo York') fabricate('location', city: 'Cincinnati') ] renderStub.args[0][0].should.equal 'contact' renderStub.args[0][1].profile.get('name').should.equal '<NAME>' renderStub.args[0][1].locationGroups['Zoo York'].length.should.equal 2 it 'renders 404 page for non-active partners', -> next = sinon.spy() renderStub = sinon.stub() routes.contact( profile: new Profile fabricate('profile' name: '<NAME>' owner_type: 'PartnerGallery' owner: fabricate('partner' id: 'foobarz' profile_layout: 'gallery_default')) { render: renderStub } next ) error = next.getCall(0).args[0] error.status.should.equal(404) error.message.should.equal('Not Found') describe '#fetchArtworksAndRender', -> xit 'renders the partner\'s works based on parameters', -> routes.fetchArtworksAndRender( { label: "Works", profile: new Profile(fabricate 'profile', name: '<NAME>', owner_type: 'PartnerInstitution') } { render: renderStub = sinon.stub() } ) Backbone.sync.args[0][2].success [ [fabricate('artwork')] ] renderStub.args[0][0].should.equal 'contact' renderStub.args[0][1].profile.get('name').should.equal '<NAME>' renderStub.args[0][1].locationGroups['Zoo York'].length.should.equal 2
true
_ = require 'underscore' { fabricate } = require 'antigravity' sinon = require 'sinon' routes = require '../routes' Profile = require '../../../models/profile' Backbone = require 'backbone' describe 'Profile page', -> beforeEach -> sinon.stub Backbone, 'sync' afterEach -> Backbone.sync.restore() describe '#index', -> it 'renders the index page passing on the profile and featured show', -> routes.index( { profile: new Profile(fabricate 'profile', name: 'PI:NAME:<NAME>END_PI', owner_type: 'PartnerGallery') } { locals: { sd: {} }, render: renderStub = sinon.stub() } ) _.last(Backbone.sync.args)[2].success fabricate('partner', id: 'foobar1', displayable_shows_count: 1) _.last(Backbone.sync.args)[2].success { results: [] } renderStub.args[0][0].should.equal 'index' renderStub.args[0][1].profile.get('name').should.equal 'PI:NAME:<NAME>END_PI' describe '#shows', -> it 'renders the shows page passing on the current shows, upcoming shows and past shows', -> Backbone.sync .onCall 0 .yieldsTo 'success', [ fabricate('show', status: 'running', name: 'Foo') ] .returns Promise.resolve [ fabricate('show', status: 'running', name: 'Foo') ] Backbone.sync .onCall 1 .yieldsTo 'success', [ fabricate('show', status: 'upcoming', name: 'Meow') ] .returns Promise.resolve [ fabricate('show', status: 'upcoming', name: 'Meow') ] Backbone.sync .onCall 2 .yieldsTo 'success', [ fabricate('show', status: 'closed', name: 'Bar') ] .returns Promise.resolve [ fabricate('show', status: 'closed', name: 'Bar') ] renderStub = sinon.stub() routes.shows( { profile: new Profile(fabricate 'profile', name: 'PI:NAME:<NAME>END_PI', owner_type: 'PartnerGallery') } { render: renderStub } ).then -> renderStub.args[0][0].should.equal 'shows_page' renderStub.args[0][1].profile.get('name').should.equal 'PI:NAME:<NAME>END_PI' renderStub.args[0][1].currentShows.models[0].get('name').should.equal 'PI:NAME:<NAME>END_PI' renderStub.args[0][1].currentShows.models[1].get('name').should.equal 'PI:NAME:<NAME>END_PI' renderStub.args[0][1].pastShows.models[0].get('name').should.equal 'Bar' describe '#artists', -> it 'renders the artists page by passing on the represented/unrep groups', -> routes.artists( { profile: new Profile(fabricate 'profile', name: 'PI:NAME:<NAME>END_PI', owner_type: 'PartnerGallery') } { render: renderStub = sinon.stub() } ) Backbone.sync.args[0][2].success [ { artist: fabricate('artist', name: 'PI:NAME:<NAME>END_PI'), represented_by: true, image_versions: ['tall'], image_url: '/Foo/bar' } { artist: fabricate('artist', name: 'PI:NAME:<NAME>END_PI'), represented_by: false } { artist: fabricate('artist', name: 'PI:NAME:<NAME>END_PI'), represented_by: false, published_artworks_count: 1 } ] Backbone.sync.args[0][2].success [] renderStub.args[0][0].should.equal 'artists' renderStub.args[0][1].profile.get('name').should.equal 'PI:NAME:<NAME>END_PI' renderStub.args[0][1].represented[0].get('name').should.equal 'PI:NAME:<NAME>END_PI' renderStub.args[0][1].unrepresented[0].get('name').should.equal 'PI:NAME:<NAME>END_PI' describe '#contact', -> it 'renders the contact page by passing on the partner locations groupped by city', -> routes.contact( profile: new Profile fabricate('profile' name: 'PI:NAME:<NAME>END_PI' owner_type: 'PartnerGallery' owner: fabricate('partner' id: 'foobarz' profile_layout: 'gallery_one')) { render: renderStub = sinon.stub() } ) _.last(Backbone.sync.args)[2].success fabricate('partner', id: 'foobar1', displayable_shows_count: 1) _.last(Backbone.sync.args)[2].success [ fabricate('location', city: 'Zoo York') fabricate('location', city: 'Zoo York') fabricate('location', city: 'Cincinnati') ] renderStub.args[0][0].should.equal 'contact' renderStub.args[0][1].profile.get('name').should.equal 'PI:NAME:<NAME>END_PI' renderStub.args[0][1].locationGroups['Zoo York'].length.should.equal 2 it 'renders 404 page for non-active partners', -> next = sinon.spy() renderStub = sinon.stub() routes.contact( profile: new Profile fabricate('profile' name: 'PI:NAME:<NAME>END_PI' owner_type: 'PartnerGallery' owner: fabricate('partner' id: 'foobarz' profile_layout: 'gallery_default')) { render: renderStub } next ) error = next.getCall(0).args[0] error.status.should.equal(404) error.message.should.equal('Not Found') describe '#fetchArtworksAndRender', -> xit 'renders the partner\'s works based on parameters', -> routes.fetchArtworksAndRender( { label: "Works", profile: new Profile(fabricate 'profile', name: 'PI:NAME:<NAME>END_PI', owner_type: 'PartnerInstitution') } { render: renderStub = sinon.stub() } ) Backbone.sync.args[0][2].success [ [fabricate('artwork')] ] renderStub.args[0][0].should.equal 'contact' renderStub.args[0][1].profile.get('name').should.equal 'PI:NAME:<NAME>END_PI' renderStub.args[0][1].locationGroups['Zoo York'].length.should.equal 2
[ { "context": "............................\n key = guide_0 + guide_1\n unless key of seen\n chrs", "end": 28492, "score": 0.9559110403060913, "start": 28483, "tag": "KEY", "value": "guide_0 +" }, { "context": "............\n key = guide_0...
src/copy-jizuradb-to-Hollerith2-format.coffee
loveencounterflow/jizura
0
############################################################################################################ njs_path = require 'path' njs_fs = require 'fs' join = njs_path.join #........................................................................................................... CND = require 'cnd' rpr = CND.rpr badge = 'JIZURA/copy-jizuradb-to-Hollerith2-format' log = CND.get_logger 'plain', badge info = CND.get_logger 'info', badge whisper = CND.get_logger 'whisper', badge alert = CND.get_logger 'alert', badge debug = CND.get_logger 'debug', badge warn = CND.get_logger 'warn', badge help = CND.get_logger 'help', badge urge = CND.get_logger 'urge', badge echo = CND.echo.bind CND #........................................................................................................... suspend = require 'coffeenode-suspend' step = suspend.step #........................................................................................................... D = require 'pipedreams' $ = D.remit.bind D $async = D.remit_async.bind D #........................................................................................................... HOLLERITH = require 'hollerith' # DEMO = require './demo' KWIC = require 'kwic' IDLX = require 'idlx' XNCHR = require './XNCHR' ƒ = CND.format_number.bind CND #----------------------------------------------------------------------------------------------------------- options = sample: null # sample: [ '國', ] # sample: [ '⿓', '龍', '龍', '邔', '𨙬', '國', '金', '釒', ] # sample: [ '高', ] # sample: [ '𡬜', '國', '𠵓', ] # sample: [ '𡬜', '國', '𠵓', '后', '花', '醒', ] # #----------------------------------------------------------------------------------------------------------- # @$show_progress = ( size ) -> # size ?= 1e3 # count = 0 # return $ ( data, send ) => # count += 1 # echo ƒ count if count % size is 0 # send data #----------------------------------------------------------------------------------------------------------- @$show_progress = ( size ) -> size ?= 1e3 phrase_count = 0 glyph_count = 0 last_glyph = null return D.$observe ( phrase, has_ended ) => unless has_ended phrase_count += 1 echo ƒ phrase_count if phrase_count % size is 0 glyph_count += +1 if ( glyph = phrase[ 0 ] ) isnt last_glyph last_glyph = glyph else help "read #{ƒ phrase_count} phrases for #{ƒ glyph_count} glyphs" help "(#{( phrase_count / glyph_count ).toFixed 2} phrases per glyph)" #----------------------------------------------------------------------------------------------------------- @$keep_small_sample = -> return $ ( key, send ) => return send key unless options[ 'sample' ]? [ glyph, prd, obj, idx, ] = key send key if glyph in options[ 'sample' ] #----------------------------------------------------------------------------------------------------------- @$throw_out_pods = -> return $ ( key, send ) => [ glyph, prd, obj, idx, ] = key send key unless prd is 'pod' #----------------------------------------------------------------------------------------------------------- @$remove_duplicate_kana_readings = -> readings_by_glyph = {} return $ ( key, send ) => [ glyph, prd, obj, idx, ] = key if prd in [ 'reading/hi', ] target = readings_by_glyph[ glyph ]?= [] if obj in target return warn "skipping duplicate reading #{glyph} #{obj}" target.push obj send key #----------------------------------------------------------------------------------------------------------- @$cast_types = ( ds_options ) -> return $ ( [ sbj, prd, obj, idx, ], send ) => type_description = ds_options[ 'schema' ][ prd ] unless type_description? warn "no type description for predicate #{rpr prd}" else switch type = type_description[ 'type' ] when 'int' obj = parseInt obj, 10 when 'text' ### TAINT we have no booleans configured ### if obj is 'true' then obj = true else if obj is 'false' then obj = false send if idx? then [ sbj, prd, obj, idx, ] else [ sbj, prd, obj, ] #----------------------------------------------------------------------------------------------------------- @$collect_lists = -> objs = null sbj_prd = null last_digest = null context_keys = [] has_errors = false #......................................................................................................... return $ ( key, send, end ) => #....................................................................................................... if key? context_keys.push key; context_keys.shift() if context_keys.length > 10 [ sbj, prd, obj, idx, ] = key digest = JSON.stringify [ sbj, prd, ] #..................................................................................................... if digest is last_digest if idx? objs[ idx ] = obj else ### A certain subject/predicate combination can only ever be repeated if an index is present in the key ### alert() alert "erroneous repeated entry; context:" alert context_keys has_errors = true else send [ sbj_prd..., objs, ] if objs? objs = null last_digest = digest if idx? objs = [] objs[ idx ] = obj sbj_prd = [ sbj, prd, ] else send key #....................................................................................................... if end? send [ sbj_prd..., objs, ] if objs? return send.error new Error "there were errors; see alerts above" if has_errors end() #....................................................................................................... return null #----------------------------------------------------------------------------------------------------------- @$compact_lists = -> return $ ( [ sbj, prd, obj, ], send ) => ### Compactify sparse lists so all `undefined` elements are removed; warn about this ### if ( CND.type_of obj ) is 'list' new_obj = ( element for element in obj when element isnt undefined ) if obj.length isnt new_obj.length warn "phrase #{rpr [ sbj, prd, obj, ]} contained undefined elements; compactified" obj = new_obj send [ sbj, prd, obj, ] #----------------------------------------------------------------------------------------------------------- @$add_version_to_kwic_v1 = -> ### mark up all predicates `guide/kwic/*` as `guide/kwic/v1/*` ### return $ ( [ sbj, prd, obj, ], send ) => if prd.startsWith 'guide/kwic/' prd = prd.replace /^guide\/kwic\//, 'guide/kwic/v1/' send [ sbj, prd, obj, ] #----------------------------------------------------------------------------------------------------------- @_long_wrapped_lineups_from_guides = ( guides ) -> ### Extending lineups to accommodate for glyphs with 'overlong' factorials (those with more than 6 factors; these were previously excluded from the gamut in `feed-db.coffee`, line 2135, `@KWIC.$compose_lineup_facets`). ### ### TAINT here be magic numbers ### lineup = guides[ .. ] last_idx = lineup.length - 1 + 6 lineup.push '\u3000' while lineup.length < 19 lineup.unshift '\u3000' while lineup.length < 25 R = [] for idx in [ 6 .. last_idx ] infix = lineup[ idx ] suffix = lineup[ idx + 1 .. idx + 6 ].join '' prefix = lineup[ idx - 6 .. idx - 1 ].join '' R.push [ infix, suffix, prefix, ].join ',' return R # #----------------------------------------------------------------------------------------------------------- # @$add_kwic_v2 = -> # ### see `demo/show_kwic_v2_and_v3_sample` ### # last_glyph = null # long_wrapped_lineups = null # return $ ( [ sbj, prd, obj, ], send ) => # #....................................................................................................... # if prd is 'guide/has/uchr' # last_glyph = sbj # long_wrapped_lineups = @_long_wrapped_lineups_from_guides obj # #....................................................................................................... # return send [ sbj, prd, obj, ] unless prd.startsWith 'guide/kwic/v1/' # #....................................................................................................... # switch prd.replace /^guide\/kwic\/v1\//, '' # when 'lineup/wrapped/infix', 'lineup/wrapped/prefix', 'lineup/wrapped/suffix', 'lineup/wrapped/single' # ### copy to target ### # send [ sbj, prd, obj, ] # when 'sortcode' # [ glyph, _, sortcodes_v1, ] = [ sbj, prd, obj, ] # sortcodes_v2 = [] # #................................................................................................... # ### The difference between KWIC sortcodes of version 1 and version 2 lies in the re-arrangement # of the factor codes and the index codes. In v1, the index codes appeared interspersed with # the factor codes; in v2, the index codes come up front and the index codes come in the latter half # of the sortcode strings. The effect of this rearrangement is that now that all of the indexes # (which indicate the position of each factor in the lineup) are weaker than any of the factor codes, # like sequences of factor codes (and, therefore, factors) will always be grouped together (whereas # in v1, only like factors with like positions appeared together, and often like sequences appeared # with other sequences interspersed where their indexes demanded it so). ### # for sortcode_v1 in sortcodes_v1 # sortrow_v1 = ( x for x in sortcode_v1.split /(........,..),/ when x.length > 0 ) # sortrow_v1 = ( x.split ',' for x in sortrow_v1 ) # sortrow_v2 = [] # sortrow_v2.push sortcode for [ sortcode, _, ] in sortrow_v1 # sortrow_v2.push position for [ _, position, ] in sortrow_v1 # sortcodes_v2.push sortrow_v2.join ',' # #................................................................................................... # unless glyph is last_glyph # return send.error new Error "unexpected mismatch: #{rpr glyph}, #{rpr last_glyph}" # #................................................................................................... # unless long_wrapped_lineups? # return send.error new Error "missing long wrapped lineups for glyph #{rpr glyph}" # #................................................................................................... # unless sortcodes_v2.length is long_wrapped_lineups.length # warn 'sortcodes_v2: ', sortcodes_v2 # warn 'long_wrapped_lineups: ', long_wrapped_lineups # return send.error new Error "length mismatch for glyph #{rpr glyph}" # #................................................................................................... # sortcodes_v1[ idx ] += ";" + lineup for lineup, idx in long_wrapped_lineups # sortcodes_v2[ idx ] += ";" + lineup for lineup, idx in long_wrapped_lineups # send [ glyph, 'guide/kwic/v2/lineup/wrapped/single', long_wrapped_lineups, ] # long_wrapped_lineups = null # #................................................................................................... # send [ glyph, prd, sortcodes_v1, ] # send [ glyph, 'guide/kwic/v2/sortcode', sortcodes_v2, ] # else # send.error new Error "unhandled predicate #{rpr prd}" #----------------------------------------------------------------------------------------------------------- @$add_kwic_v3 = ( factor_infos ) -> ### see `demo/show_kwic_v2_and_v3_sample` ### #......................................................................................................... return $ ( [ sbj, prd, obj, ], send ) => return if prd.startsWith 'guide/kwic/v2/' return send [ sbj, prd, obj, ] unless prd.startsWith 'guide/kwic/v1/' return if prd isnt 'guide/kwic/v1/sortcode' #....................................................................................................... [ glyph, _, [ sortcode_v1, ... ], ] = [ sbj, prd, obj, ] #....................................................................................................... sortrow_v1 = ( x for x in sortcode_v1.split /(........,..),/ when x.length > 0 ) weights = ( x.split ',' for x in sortrow_v1 ) weights.pop() weights = ( sortcode for [ sortcode, _, ] in weights ) weights = ( sortcode for sortcode in weights when sortcode isnt '--------' ) weights = ( ( sortcode.replace /~/g, '-' ) for sortcode in weights ) weights = ( ( sortcode.replace /----/g, 'f---' ) for sortcode in weights ) #....................................................................................................... factors = ( factor_infos[ sortcode ] for sortcode in weights ) factors = ( ( if factor? then factor else '〓' ) for factor in factors ) #....................................................................................................... unless weights.length is factors.length warn glyph, weights, factors, weights.length, factors.length return #....................................................................................................... permutations = KWIC.get_permutations factors, weights send [ glyph, 'guide/kwic/v3/sortcode', permutations, ] #----------------------------------------------------------------------------------------------------------- @$add_kwic_v3_wrapped_lineups = ( factor_infos ) -> prefix_max_length = 3 suffix_max_length = 3 #......................................................................................................... return $ ( [ sbj, prd, obj, ], send ) => send [ sbj, prd, obj, ] return unless prd is 'guide/kwic/v3/sortcode' [ glyph, _, permutations, ] = [ sbj, prd, obj, ] lineups = [] #....................................................................................................... for permutation, idx in permutations [ sortcode, infix, suffix, prefix, ] = permutation suffix = Object.assign [], suffix prefix = Object.assign [], prefix #..................................................................................................... prefix_length = prefix.length suffix_length = suffix.length prefix_delta = prefix_length - prefix_max_length suffix_delta = suffix_length - suffix_max_length prefix_excess_max_length = suffix_max_length - suffix_length suffix_excess_max_length = prefix_max_length - prefix_length prefix_excess = [] suffix_excess = [] prefix_padding = [] suffix_padding = [] #..................................................................................................... if prefix_delta > 0 prefix_excess = prefix.splice 0, prefix_delta if suffix_delta > 0 suffix_excess = suffix.splice suffix.length - suffix_delta, suffix_delta #..................................................................................................... while prefix_excess.length > 0 and prefix_excess.length > prefix_excess_max_length - 1 prefix_excess.pop() while suffix_excess.length > 0 and suffix_excess.length > suffix_excess_max_length - 1 suffix_excess.shift() #..................................................................................................... while prefix_padding.length + suffix_excess.length + prefix.length < prefix_max_length prefix_padding.unshift '\u3000' while suffix_padding.length + prefix_excess.length + suffix.length < suffix_max_length suffix_padding.unshift '\u3000' #..................................................................................................... prefix.splice 0, 0, prefix_padding... prefix.splice 0, 0, suffix_excess... suffix.splice suffix.length, 0, suffix_padding... suffix.splice suffix.length, 0, prefix_excess... #..................................................................................................... prefix = prefix.join '' suffix = suffix.join '' lineups.push [ sortcode, infix, suffix, prefix, ] #....................................................................................................... send [ glyph, 'guide/kwic/v3/sortcode/wrapped-lineups', lineups, ] #----------------------------------------------------------------------------------------------------------- @$add_factor_membership = ( factor_infos ) -> glyphs_by_factors = {} #......................................................................................................... return $ ( phrase, send, end ) => if phrase? send phrase [ glyph, prd, obj, ] = phrase return unless prd is 'guide/has/uchr' for factor in obj continue if factor is glyph ( glyphs_by_factors[ factor ]?= new Set() ).add glyph if end? for factor, glyphs of glyphs_by_factors send [ factor, 'factor/has/glyph/uchr', Array.from glyphs.keys(), ] # glyphs.forEach ( glyph ) => # send [ factor, 'factor/has/glyph/uchr', glyph, ] end() #----------------------------------------------------------------------------------------------------------- ### TAINT code duplication ### @$add_components = -> ### The field `component/uchr` lists all the components that appear as part of a given glyph, collected from all its formulas and down through all recursive steps of component resolution. The resulting lists can, therefore, be quite long and potentially include parts that are present in virtually all glyphs, such as `丿` or `一`. The components listed are unique and appear in no particular order. As an example, the DB contains the folloqing entry: ``` spo|䱴|component/uchr: [ '魚', '恒', '', '灬', '𠂊', '田', '丿', '㇇', '囗', '十', '日', '丨', '冂', '一', '𠃌', '彐', '', '', '丶', '', '忄', '亘', '旦', ] ``` ### ### Immediate Constituents (ICs) ### ics_by_glyph = {} seen_glyphs = new Set() glyph_count = 0 #......................................................................................................... resolve_ics = ( glyph ) => return if seen_glyphs.has glyph seen_glyphs.add glyph if ( entry = ics_by_glyph[ glyph ] )? for ic in Array.from entry.keys() resolve_ics ic if ( sub_entry = ics_by_glyph[ ic ] )? for sub_ic in Array.from sub_entry entry.add sub_ic #......................................................................................................... return $ ( phrase, send, end ) => #....................................................................................................... if phrase? send phrase [ glyph, prd, obj, ] = phrase return unless prd is 'formula' ### TAINT collecting ICs from outer glyphs might aid in resolving more inner glyphs ### return unless XNCHR.is_inner_glyph glyph glyph = XNCHR.as_uchr glyph glyph_count += +1 for formula, formula_idx in obj ics = IDLX.find_all_non_operators formula target = ics_by_glyph[ glyph ]?= new Set() target.add ( XNCHR.as_uchr ic ) for ic in ics #....................................................................................................... if end? resolve_ics glyph for glyph of ics_by_glyph ics_by_glyph[ glyph ] = Array.from entry for glyph, entry of ics_by_glyph for glyph, ics of ics_by_glyph send [ glyph, 'component/uchr', ics, ] end() #....................................................................................................... return null #----------------------------------------------------------------------------------------------------------- ### TAINT code duplication ### @$add_factorial_factors = ( factor_infos ) -> ### Factorial Factors: the factors of factors; used for cross-referencing. E.g. the formula of 鬲 is ⿱𠮛⿵冂&jzr#xe152;; all the components of 鬲 are factors except for 𠮛, which must again be analyzed into 𠮛:⿱一口, leading to the entry 鬲:一口冂&jzr#xe152;. ### factors = new Set() factors.add ( XNCHR.as_uchr factor ) for _, factor of factor_infos # debug '©67157', factors; process.exit 1 ### Immediate Constituents (ICs) ### factors_by_factor = {} seen_glyphs = new Set() factor_count = 0 #......................................................................................................... return $ ( phrase, send, end ) => #....................................................................................................... if phrase? send phrase [ glyph, prd, obj, ] = phrase return unless prd is 'formula' ### TAINT collecting ICs from outer glyphs might aid in resolving more inner glyphs ### return unless XNCHR.is_inner_glyph glyph glyph = XNCHR.as_uchr glyph factor_count += +1 if factors.has glyph entry = factors_by_factor[ glyph ]?= [] for formula, formula_idx in obj ics = IDLX.find_all_non_operators formula entry.push ( ( XNCHR.as_uchr ic ) for ic in ics ) #....................................................................................................... if end? factors_by_factor_json = JSON.stringify factors_by_factor, null, ' ' factors_json = JSON.stringify ( Array.from factors ), null, ' ' ics_route = njs_path.resolve __dirname, '../../jizura-datasources/data/5-derivatives/ics-by-glyphs.json' factors_route = njs_path.resolve __dirname, '../../jizura-datasources/data/5-derivatives/factors.json' warn "write to #{ics_route}" njs_fs.writeFileSync ics_route, factors_by_factor_json warn "write to #{factors_route}" njs_fs.writeFileSync factors_route, factors_json # #..................................................................................................... # for factor in Array.from factors.keys() # unless ( entry = factors_by_factor[ factor ] )? # whisper "no ICs for factor #{factor}" # continue # for ics in entry # for ic in ics # unless factors.has ic # warn "factor #{factor} has non-factorial IC #{ic}" #..................................................................................................... end() #....................................................................................................... return null #----------------------------------------------------------------------------------------------------------- ### TAINT code duplication ### @$add_lineup_back_and_forwards = -> #......................................................................................................... return $ ( phrase, send ) => #....................................................................................................... send phrase [ glyph, prd, obj, ] = phrase return unless prd is 'guide/kwic/v3/sortcode' return unless XNCHR.is_inner_glyph glyph #....................................................................................................... forwards_lineups = [] backwards_lineups = [] #....................................................................................................... for permutation, idx in obj [ sortcode, infix, suffix, prefix, ] = permutation forwards_lineups.push infix + suffix.join '' backwards_lineups.push infix + ( Object.assign [], prefix ).reverse().join '' send [ glyph, 'guide/kwic/lineup/forwards', forwards_lineups, ] send [ glyph, 'guide/kwic/lineup/backwards', backwards_lineups, ] #....................................................................................................... return null #----------------------------------------------------------------------------------------------------------- @$add_sims = -> sims_by_glyph = {} #......................................................................................................... return $ ( phrase, send, end ) => if phrase? send phrase [ source_glyph, prd, target_glyph, ] = phrase return unless prd.startsWith 'sim/' return unless XNCHR.is_inner_glyph source_glyph [ _, tag, ] = prd.match /\/(.+)$/ target = sims_by_glyph[ target_glyph ]?= {} ( target[ tag ]?= [] ).push source_glyph if end? for target_glyph, sims of sims_by_glyph send [ target_glyph, "sims/from", sims, ] # for tag, source_glyphs of sims # send [ target_glyph, "sims/from/#{tag}", source_glyphs, ] end() #----------------------------------------------------------------------------------------------------------- @$add_guide_pairs = ( factor_infos ) -> sortcode_by_factors = {} sortcode_by_factors[ guide_uchr ] = sortcode for sortcode, guide_uchr of factor_infos #......................................................................................................... ### TAINT code duplication ### ### TAIN make configurable / store in options ### home = njs_path.resolve __dirname, '../../jizura-datasources' derivatives_home = njs_path.resolve home, 'data/5-derivatives' derivatives_route = njs_path.resolve derivatives_home, 'guide-pairs.txt' derivatives = njs_fs.createWriteStream derivatives_route, { encoding: 'utf-8', } collector = [] excludes = [ '一', ] help "writing results of `add_guide_pairs` to #{derivatives_route}" derivatives.write """ # generated on #{new Date()} # by #{__filename} \n\n""" #......................................................................................................... get_pairs = ( glyph, guides ) -> ### TAINT allow or eliminate duplicates? use pairs and reversed pairs? ### length = guides.length chrs = [] sortcodes = [] entries = [] seen = {} R = { chrs, entries, } #....................................................................................................... return R if length < 2 #....................................................................................................... for i in [ 0 ... length - 1 ] for j in [ i + 1 ... length ] guide_0 = guides[ i ] guide_1 = guides[ j ] continue if guide_0 in excludes or guide_1 in excludes sortcode_0 = sortcode_by_factors[ guide_0 ] sortcode_1 = sortcode_by_factors[ guide_1 ] sortcode_0 ?= 'zzzzzzzz' sortcode_1 ?= 'zzzzzzzz' # return send.error new Error "unknown guide: #{guide_0}" unless sortcode_0? # return send.error new Error "unknown guide: #{guide_1}" unless sortcode_1? #................................................................................................... key = guide_0 + guide_1 unless key of seen chrs.push key entries.push "#{sortcode_0} #{sortcode_1}\t#{key}\t#{glyph}" seen[ key ] = 1 #................................................................................................... key = guide_1 + guide_0 unless key of seen chrs.push key entries.push "#{sortcode_1} #{sortcode_0}\t#{key}\t#{glyph}" seen[ key ] = 1 #....................................................................................................... return R #......................................................................................................... return $ ( phrase, send, end ) => #....................................................................................................... if phrase? send phrase [ sbj, prd, obj, ] = phrase #..................................................................................................... if prd is 'guide/has/uchr' [ glyph, _, guides, ] = [ sbj, prd, obj, ] if XNCHR.is_inner_glyph glyph { chrs, entries, } = get_pairs glyph, guides # debug '©VrqrO', glyph, chrs # debug '©VrqrO', glyph, entries collector.push entry for entry in entries send [ glyph, 'guide/pair/uchr', chrs, ] send [ glyph, 'guide/pair/entry', entries, ] #....................................................................................................... if end? debug '©70RRX', new Date() whisper "sorting guide pairs..." collector.sort() whisper "done" debug '©70RRX', new Date() whisper "writing guide pairs..." for entry in collector derivatives.write entry + '\n' derivatives.end() whisper "done" debug '©70RRX', new Date() end() # #=========================================================================================================== # find_duplicated_guides = -> # D = require 'pipedreams' # $ = D.remit.bind D # ### TAINT code duplication ### # ### TAIN make configurable / store in options ### # home = njs_path.resolve __dirname, '../../jizura-datasources' # derivatives_home = njs_path.resolve home, 'data/5-derivatives' # # derivatives_route = njs_path.resolve derivatives_home, 'guide-pairs.txt' # input = njs_fs.createReadStream njs_path.resolve derivatives_home, 'guide-pairs.txt' # output = njs_fs.createWriteStream njs_path.resolve derivatives_home, 'guide-pairs-duplicated.txt' # input # .pipe D.$split() # # .pipe D.$parse_csv headers: no # .pipe $ ( line, send ) => send line unless line.length is 0 # .pipe $ ( line, send ) => send line unless line.startsWith '#' # .pipe $ ( line, send ) => send [ line, ( line.split '\t' )... ] # .pipe $ ( [ line, _, guides, glyph, ], send ) => send [ line, glyph, guides, ] # .pipe $ ( fields, send ) => # [ line, glyph, guides, ] = fields # # debug '0912', rpr fields # unless CND.isa_text guides # warn line, fields # send fields # .pipe $ ( [ line, glyph, guides, ], send ) => # send [ line, glyph, ( Array.from guides )... ] # .pipe $ ( fields, send ) => # [ line, glyph, guide_0, guide_1, ] = fields # send fields unless guide_0 is '一' or guide_1 is '一' # .pipe $ ( fields, send ) => # [ line, glyph, guide_0, guide_1, ] = fields # send fields if guide_0 is guide_1 # # .pipe D.$show() # .pipe $ ( [ line, glyph, guide_0, guide_1, ], send ) => send line + '\n' # .pipe output # find_duplicated_guides() #----------------------------------------------------------------------------------------------------------- @v1_split_so_bkey = ( bkey ) -> R = bkey.toString 'utf-8' R = R.split '|' idx_txt = R[ 3 ] R = [ ( R[ 1 ].split ':' )[ 1 ], ( R[ 2 ].split ':' )..., ] R.push ( parseInt idx_txt, 10 ) if idx_txt? and idx_txt.length > 0 for r, idx in R continue unless CND.isa_text r continue unless 'µ' in r R[ idx ] = @v1_unescape r return R #----------------------------------------------------------------------------------------------------------- @v1_$split_so_bkey = -> $ ( bkey, send ) => send @v1_split_so_bkey bkey #----------------------------------------------------------------------------------------------------------- @v1_lte_from_gte = ( gte ) -> R = new Buffer ( last_idx = Buffer.byteLength gte ) + 1 R.write gte R[ last_idx ] = 0xff return R #----------------------------------------------------------------------------------------------------------- @v1_unescape = ( text_esc ) -> matcher = /µ([0-9a-f]{2})/g return text_esc.replace matcher, ( _, cid_hex ) -> return String.fromCharCode parseInt cid_hex, 16 #----------------------------------------------------------------------------------------------------------- @read_factors = ( db, handler ) -> #......................................................................................................... Z = {} #....................................................................................................... gte = 'os|factor/sortcode' lte = @v1_lte_from_gte gte input = db[ '%self' ].createKeyStream { gte, lte, } #....................................................................................................... input .pipe @v1_$split_so_bkey() .pipe D.$observe ( [ sortcode, _, factor, ] ) => Z[ sortcode ] = XNCHR.as_uchr factor .pipe D.$on_end -> handler null, Z #----------------------------------------------------------------------------------------------------------- @copy_jizura_db = -> home = njs_path.resolve __dirname, '../../jizura-datasources' source_route = njs_path.resolve home, 'data/leveldb' target_route = njs_path.resolve home, 'data/leveldb-v2' # ### # # # # # # # # # # # # # # # # # # # # # ### # target_route = '/tmp/leveldb-v2'; alert "using temp DB" # ### # # # # # # # # # # # # # # # # # # # # # ### target_db_size = 1e6 ds_options = require njs_path.resolve home, 'options' source_db = HOLLERITH.new_db source_route target_db = HOLLERITH.new_db target_route, size: target_db_size, create: yes #......................................................................................................... ### TAINT this setting should come from Jizura DB options ### # solids = [ 'guide/kwic/v3/sortcode', ] solids = [] #......................................................................................................... help "using DB at #{source_db[ '%self' ][ 'location' ]}" help "using DB at #{target_db[ '%self' ][ 'location' ]}" #......................................................................................................... step ( resume ) => yield HOLLERITH.clear target_db, resume #......................................................................................................... factor_infos = yield @read_factors source_db, resume # for key, factor of factor_infos # debug key, factor if ( XNCHR.as_uchr factor ) in '羊⺶丷䒑' # process.exit 1 help "read #{( Object.keys factor_infos ).length} entries for factor_infos" #......................................................................................................... # gte = 'so|glyph:中' if ( CND.isa_list sample = options[ 'sample' ] ) and ( sample.length is 1 ) gte = "so|glyph:#{sample[ 0 ]}" else gte = 'so|' lte = @v1_lte_from_gte gte input = source_db[ '%self' ].createKeyStream { gte, lte, } batch_size = 1e4 output = HOLLERITH.$write target_db, { batch: batch_size, solids } #......................................................................................................... help "copying from #{source_route}" help "to #{target_route}" help "reading records with prefix #{rpr gte}" help "writing with batch size #{ƒ batch_size}" #......................................................................................................... input #....................................................................................................... .pipe @v1_$split_so_bkey() .pipe @$show_progress 1e4 .pipe @$keep_small_sample() .pipe @$throw_out_pods() .pipe @$remove_duplicate_kana_readings() .pipe @$cast_types ds_options .pipe @$collect_lists() .pipe @$compact_lists() .pipe @$add_version_to_kwic_v1() # .pipe @$add_kwic_v2() .pipe @$add_kwic_v3 factor_infos .pipe @$add_kwic_v3_wrapped_lineups factor_infos # .pipe @$add_guide_pairs factor_infos .pipe @$add_factor_membership factor_infos .pipe @$add_components() .pipe @$add_lineup_back_and_forwards() .pipe @$add_factorial_factors factor_infos .pipe @$add_sims() # .pipe D.$show() .pipe D.$count ( count ) -> help "kept #{ƒ count} phrases" .pipe D.$stop_time "copy Jizura DB" .pipe output ############################################################################################################ unless module.parent? @copy_jizura_db()
143763
############################################################################################################ njs_path = require 'path' njs_fs = require 'fs' join = njs_path.join #........................................................................................................... CND = require 'cnd' rpr = CND.rpr badge = 'JIZURA/copy-jizuradb-to-Hollerith2-format' log = CND.get_logger 'plain', badge info = CND.get_logger 'info', badge whisper = CND.get_logger 'whisper', badge alert = CND.get_logger 'alert', badge debug = CND.get_logger 'debug', badge warn = CND.get_logger 'warn', badge help = CND.get_logger 'help', badge urge = CND.get_logger 'urge', badge echo = CND.echo.bind CND #........................................................................................................... suspend = require 'coffeenode-suspend' step = suspend.step #........................................................................................................... D = require 'pipedreams' $ = D.remit.bind D $async = D.remit_async.bind D #........................................................................................................... HOLLERITH = require 'hollerith' # DEMO = require './demo' KWIC = require 'kwic' IDLX = require 'idlx' XNCHR = require './XNCHR' ƒ = CND.format_number.bind CND #----------------------------------------------------------------------------------------------------------- options = sample: null # sample: [ '國', ] # sample: [ '⿓', '龍', '龍', '邔', '𨙬', '國', '金', '釒', ] # sample: [ '高', ] # sample: [ '𡬜', '國', '𠵓', ] # sample: [ '𡬜', '國', '𠵓', '后', '花', '醒', ] # #----------------------------------------------------------------------------------------------------------- # @$show_progress = ( size ) -> # size ?= 1e3 # count = 0 # return $ ( data, send ) => # count += 1 # echo ƒ count if count % size is 0 # send data #----------------------------------------------------------------------------------------------------------- @$show_progress = ( size ) -> size ?= 1e3 phrase_count = 0 glyph_count = 0 last_glyph = null return D.$observe ( phrase, has_ended ) => unless has_ended phrase_count += 1 echo ƒ phrase_count if phrase_count % size is 0 glyph_count += +1 if ( glyph = phrase[ 0 ] ) isnt last_glyph last_glyph = glyph else help "read #{ƒ phrase_count} phrases for #{ƒ glyph_count} glyphs" help "(#{( phrase_count / glyph_count ).toFixed 2} phrases per glyph)" #----------------------------------------------------------------------------------------------------------- @$keep_small_sample = -> return $ ( key, send ) => return send key unless options[ 'sample' ]? [ glyph, prd, obj, idx, ] = key send key if glyph in options[ 'sample' ] #----------------------------------------------------------------------------------------------------------- @$throw_out_pods = -> return $ ( key, send ) => [ glyph, prd, obj, idx, ] = key send key unless prd is 'pod' #----------------------------------------------------------------------------------------------------------- @$remove_duplicate_kana_readings = -> readings_by_glyph = {} return $ ( key, send ) => [ glyph, prd, obj, idx, ] = key if prd in [ 'reading/hi', ] target = readings_by_glyph[ glyph ]?= [] if obj in target return warn "skipping duplicate reading #{glyph} #{obj}" target.push obj send key #----------------------------------------------------------------------------------------------------------- @$cast_types = ( ds_options ) -> return $ ( [ sbj, prd, obj, idx, ], send ) => type_description = ds_options[ 'schema' ][ prd ] unless type_description? warn "no type description for predicate #{rpr prd}" else switch type = type_description[ 'type' ] when 'int' obj = parseInt obj, 10 when 'text' ### TAINT we have no booleans configured ### if obj is 'true' then obj = true else if obj is 'false' then obj = false send if idx? then [ sbj, prd, obj, idx, ] else [ sbj, prd, obj, ] #----------------------------------------------------------------------------------------------------------- @$collect_lists = -> objs = null sbj_prd = null last_digest = null context_keys = [] has_errors = false #......................................................................................................... return $ ( key, send, end ) => #....................................................................................................... if key? context_keys.push key; context_keys.shift() if context_keys.length > 10 [ sbj, prd, obj, idx, ] = key digest = JSON.stringify [ sbj, prd, ] #..................................................................................................... if digest is last_digest if idx? objs[ idx ] = obj else ### A certain subject/predicate combination can only ever be repeated if an index is present in the key ### alert() alert "erroneous repeated entry; context:" alert context_keys has_errors = true else send [ sbj_prd..., objs, ] if objs? objs = null last_digest = digest if idx? objs = [] objs[ idx ] = obj sbj_prd = [ sbj, prd, ] else send key #....................................................................................................... if end? send [ sbj_prd..., objs, ] if objs? return send.error new Error "there were errors; see alerts above" if has_errors end() #....................................................................................................... return null #----------------------------------------------------------------------------------------------------------- @$compact_lists = -> return $ ( [ sbj, prd, obj, ], send ) => ### Compactify sparse lists so all `undefined` elements are removed; warn about this ### if ( CND.type_of obj ) is 'list' new_obj = ( element for element in obj when element isnt undefined ) if obj.length isnt new_obj.length warn "phrase #{rpr [ sbj, prd, obj, ]} contained undefined elements; compactified" obj = new_obj send [ sbj, prd, obj, ] #----------------------------------------------------------------------------------------------------------- @$add_version_to_kwic_v1 = -> ### mark up all predicates `guide/kwic/*` as `guide/kwic/v1/*` ### return $ ( [ sbj, prd, obj, ], send ) => if prd.startsWith 'guide/kwic/' prd = prd.replace /^guide\/kwic\//, 'guide/kwic/v1/' send [ sbj, prd, obj, ] #----------------------------------------------------------------------------------------------------------- @_long_wrapped_lineups_from_guides = ( guides ) -> ### Extending lineups to accommodate for glyphs with 'overlong' factorials (those with more than 6 factors; these were previously excluded from the gamut in `feed-db.coffee`, line 2135, `@KWIC.$compose_lineup_facets`). ### ### TAINT here be magic numbers ### lineup = guides[ .. ] last_idx = lineup.length - 1 + 6 lineup.push '\u3000' while lineup.length < 19 lineup.unshift '\u3000' while lineup.length < 25 R = [] for idx in [ 6 .. last_idx ] infix = lineup[ idx ] suffix = lineup[ idx + 1 .. idx + 6 ].join '' prefix = lineup[ idx - 6 .. idx - 1 ].join '' R.push [ infix, suffix, prefix, ].join ',' return R # #----------------------------------------------------------------------------------------------------------- # @$add_kwic_v2 = -> # ### see `demo/show_kwic_v2_and_v3_sample` ### # last_glyph = null # long_wrapped_lineups = null # return $ ( [ sbj, prd, obj, ], send ) => # #....................................................................................................... # if prd is 'guide/has/uchr' # last_glyph = sbj # long_wrapped_lineups = @_long_wrapped_lineups_from_guides obj # #....................................................................................................... # return send [ sbj, prd, obj, ] unless prd.startsWith 'guide/kwic/v1/' # #....................................................................................................... # switch prd.replace /^guide\/kwic\/v1\//, '' # when 'lineup/wrapped/infix', 'lineup/wrapped/prefix', 'lineup/wrapped/suffix', 'lineup/wrapped/single' # ### copy to target ### # send [ sbj, prd, obj, ] # when 'sortcode' # [ glyph, _, sortcodes_v1, ] = [ sbj, prd, obj, ] # sortcodes_v2 = [] # #................................................................................................... # ### The difference between KWIC sortcodes of version 1 and version 2 lies in the re-arrangement # of the factor codes and the index codes. In v1, the index codes appeared interspersed with # the factor codes; in v2, the index codes come up front and the index codes come in the latter half # of the sortcode strings. The effect of this rearrangement is that now that all of the indexes # (which indicate the position of each factor in the lineup) are weaker than any of the factor codes, # like sequences of factor codes (and, therefore, factors) will always be grouped together (whereas # in v1, only like factors with like positions appeared together, and often like sequences appeared # with other sequences interspersed where their indexes demanded it so). ### # for sortcode_v1 in sortcodes_v1 # sortrow_v1 = ( x for x in sortcode_v1.split /(........,..),/ when x.length > 0 ) # sortrow_v1 = ( x.split ',' for x in sortrow_v1 ) # sortrow_v2 = [] # sortrow_v2.push sortcode for [ sortcode, _, ] in sortrow_v1 # sortrow_v2.push position for [ _, position, ] in sortrow_v1 # sortcodes_v2.push sortrow_v2.join ',' # #................................................................................................... # unless glyph is last_glyph # return send.error new Error "unexpected mismatch: #{rpr glyph}, #{rpr last_glyph}" # #................................................................................................... # unless long_wrapped_lineups? # return send.error new Error "missing long wrapped lineups for glyph #{rpr glyph}" # #................................................................................................... # unless sortcodes_v2.length is long_wrapped_lineups.length # warn 'sortcodes_v2: ', sortcodes_v2 # warn 'long_wrapped_lineups: ', long_wrapped_lineups # return send.error new Error "length mismatch for glyph #{rpr glyph}" # #................................................................................................... # sortcodes_v1[ idx ] += ";" + lineup for lineup, idx in long_wrapped_lineups # sortcodes_v2[ idx ] += ";" + lineup for lineup, idx in long_wrapped_lineups # send [ glyph, 'guide/kwic/v2/lineup/wrapped/single', long_wrapped_lineups, ] # long_wrapped_lineups = null # #................................................................................................... # send [ glyph, prd, sortcodes_v1, ] # send [ glyph, 'guide/kwic/v2/sortcode', sortcodes_v2, ] # else # send.error new Error "unhandled predicate #{rpr prd}" #----------------------------------------------------------------------------------------------------------- @$add_kwic_v3 = ( factor_infos ) -> ### see `demo/show_kwic_v2_and_v3_sample` ### #......................................................................................................... return $ ( [ sbj, prd, obj, ], send ) => return if prd.startsWith 'guide/kwic/v2/' return send [ sbj, prd, obj, ] unless prd.startsWith 'guide/kwic/v1/' return if prd isnt 'guide/kwic/v1/sortcode' #....................................................................................................... [ glyph, _, [ sortcode_v1, ... ], ] = [ sbj, prd, obj, ] #....................................................................................................... sortrow_v1 = ( x for x in sortcode_v1.split /(........,..),/ when x.length > 0 ) weights = ( x.split ',' for x in sortrow_v1 ) weights.pop() weights = ( sortcode for [ sortcode, _, ] in weights ) weights = ( sortcode for sortcode in weights when sortcode isnt '--------' ) weights = ( ( sortcode.replace /~/g, '-' ) for sortcode in weights ) weights = ( ( sortcode.replace /----/g, 'f---' ) for sortcode in weights ) #....................................................................................................... factors = ( factor_infos[ sortcode ] for sortcode in weights ) factors = ( ( if factor? then factor else '〓' ) for factor in factors ) #....................................................................................................... unless weights.length is factors.length warn glyph, weights, factors, weights.length, factors.length return #....................................................................................................... permutations = KWIC.get_permutations factors, weights send [ glyph, 'guide/kwic/v3/sortcode', permutations, ] #----------------------------------------------------------------------------------------------------------- @$add_kwic_v3_wrapped_lineups = ( factor_infos ) -> prefix_max_length = 3 suffix_max_length = 3 #......................................................................................................... return $ ( [ sbj, prd, obj, ], send ) => send [ sbj, prd, obj, ] return unless prd is 'guide/kwic/v3/sortcode' [ glyph, _, permutations, ] = [ sbj, prd, obj, ] lineups = [] #....................................................................................................... for permutation, idx in permutations [ sortcode, infix, suffix, prefix, ] = permutation suffix = Object.assign [], suffix prefix = Object.assign [], prefix #..................................................................................................... prefix_length = prefix.length suffix_length = suffix.length prefix_delta = prefix_length - prefix_max_length suffix_delta = suffix_length - suffix_max_length prefix_excess_max_length = suffix_max_length - suffix_length suffix_excess_max_length = prefix_max_length - prefix_length prefix_excess = [] suffix_excess = [] prefix_padding = [] suffix_padding = [] #..................................................................................................... if prefix_delta > 0 prefix_excess = prefix.splice 0, prefix_delta if suffix_delta > 0 suffix_excess = suffix.splice suffix.length - suffix_delta, suffix_delta #..................................................................................................... while prefix_excess.length > 0 and prefix_excess.length > prefix_excess_max_length - 1 prefix_excess.pop() while suffix_excess.length > 0 and suffix_excess.length > suffix_excess_max_length - 1 suffix_excess.shift() #..................................................................................................... while prefix_padding.length + suffix_excess.length + prefix.length < prefix_max_length prefix_padding.unshift '\u3000' while suffix_padding.length + prefix_excess.length + suffix.length < suffix_max_length suffix_padding.unshift '\u3000' #..................................................................................................... prefix.splice 0, 0, prefix_padding... prefix.splice 0, 0, suffix_excess... suffix.splice suffix.length, 0, suffix_padding... suffix.splice suffix.length, 0, prefix_excess... #..................................................................................................... prefix = prefix.join '' suffix = suffix.join '' lineups.push [ sortcode, infix, suffix, prefix, ] #....................................................................................................... send [ glyph, 'guide/kwic/v3/sortcode/wrapped-lineups', lineups, ] #----------------------------------------------------------------------------------------------------------- @$add_factor_membership = ( factor_infos ) -> glyphs_by_factors = {} #......................................................................................................... return $ ( phrase, send, end ) => if phrase? send phrase [ glyph, prd, obj, ] = phrase return unless prd is 'guide/has/uchr' for factor in obj continue if factor is glyph ( glyphs_by_factors[ factor ]?= new Set() ).add glyph if end? for factor, glyphs of glyphs_by_factors send [ factor, 'factor/has/glyph/uchr', Array.from glyphs.keys(), ] # glyphs.forEach ( glyph ) => # send [ factor, 'factor/has/glyph/uchr', glyph, ] end() #----------------------------------------------------------------------------------------------------------- ### TAINT code duplication ### @$add_components = -> ### The field `component/uchr` lists all the components that appear as part of a given glyph, collected from all its formulas and down through all recursive steps of component resolution. The resulting lists can, therefore, be quite long and potentially include parts that are present in virtually all glyphs, such as `丿` or `一`. The components listed are unique and appear in no particular order. As an example, the DB contains the folloqing entry: ``` spo|䱴|component/uchr: [ '魚', '恒', '', '灬', '𠂊', '田', '丿', '㇇', '囗', '十', '日', '丨', '冂', '一', '𠃌', '彐', '', '', '丶', '', '忄', '亘', '旦', ] ``` ### ### Immediate Constituents (ICs) ### ics_by_glyph = {} seen_glyphs = new Set() glyph_count = 0 #......................................................................................................... resolve_ics = ( glyph ) => return if seen_glyphs.has glyph seen_glyphs.add glyph if ( entry = ics_by_glyph[ glyph ] )? for ic in Array.from entry.keys() resolve_ics ic if ( sub_entry = ics_by_glyph[ ic ] )? for sub_ic in Array.from sub_entry entry.add sub_ic #......................................................................................................... return $ ( phrase, send, end ) => #....................................................................................................... if phrase? send phrase [ glyph, prd, obj, ] = phrase return unless prd is 'formula' ### TAINT collecting ICs from outer glyphs might aid in resolving more inner glyphs ### return unless XNCHR.is_inner_glyph glyph glyph = XNCHR.as_uchr glyph glyph_count += +1 for formula, formula_idx in obj ics = IDLX.find_all_non_operators formula target = ics_by_glyph[ glyph ]?= new Set() target.add ( XNCHR.as_uchr ic ) for ic in ics #....................................................................................................... if end? resolve_ics glyph for glyph of ics_by_glyph ics_by_glyph[ glyph ] = Array.from entry for glyph, entry of ics_by_glyph for glyph, ics of ics_by_glyph send [ glyph, 'component/uchr', ics, ] end() #....................................................................................................... return null #----------------------------------------------------------------------------------------------------------- ### TAINT code duplication ### @$add_factorial_factors = ( factor_infos ) -> ### Factorial Factors: the factors of factors; used for cross-referencing. E.g. the formula of 鬲 is ⿱𠮛⿵冂&jzr#xe152;; all the components of 鬲 are factors except for 𠮛, which must again be analyzed into 𠮛:⿱一口, leading to the entry 鬲:一口冂&jzr#xe152;. ### factors = new Set() factors.add ( XNCHR.as_uchr factor ) for _, factor of factor_infos # debug '©67157', factors; process.exit 1 ### Immediate Constituents (ICs) ### factors_by_factor = {} seen_glyphs = new Set() factor_count = 0 #......................................................................................................... return $ ( phrase, send, end ) => #....................................................................................................... if phrase? send phrase [ glyph, prd, obj, ] = phrase return unless prd is 'formula' ### TAINT collecting ICs from outer glyphs might aid in resolving more inner glyphs ### return unless XNCHR.is_inner_glyph glyph glyph = XNCHR.as_uchr glyph factor_count += +1 if factors.has glyph entry = factors_by_factor[ glyph ]?= [] for formula, formula_idx in obj ics = IDLX.find_all_non_operators formula entry.push ( ( XNCHR.as_uchr ic ) for ic in ics ) #....................................................................................................... if end? factors_by_factor_json = JSON.stringify factors_by_factor, null, ' ' factors_json = JSON.stringify ( Array.from factors ), null, ' ' ics_route = njs_path.resolve __dirname, '../../jizura-datasources/data/5-derivatives/ics-by-glyphs.json' factors_route = njs_path.resolve __dirname, '../../jizura-datasources/data/5-derivatives/factors.json' warn "write to #{ics_route}" njs_fs.writeFileSync ics_route, factors_by_factor_json warn "write to #{factors_route}" njs_fs.writeFileSync factors_route, factors_json # #..................................................................................................... # for factor in Array.from factors.keys() # unless ( entry = factors_by_factor[ factor ] )? # whisper "no ICs for factor #{factor}" # continue # for ics in entry # for ic in ics # unless factors.has ic # warn "factor #{factor} has non-factorial IC #{ic}" #..................................................................................................... end() #....................................................................................................... return null #----------------------------------------------------------------------------------------------------------- ### TAINT code duplication ### @$add_lineup_back_and_forwards = -> #......................................................................................................... return $ ( phrase, send ) => #....................................................................................................... send phrase [ glyph, prd, obj, ] = phrase return unless prd is 'guide/kwic/v3/sortcode' return unless XNCHR.is_inner_glyph glyph #....................................................................................................... forwards_lineups = [] backwards_lineups = [] #....................................................................................................... for permutation, idx in obj [ sortcode, infix, suffix, prefix, ] = permutation forwards_lineups.push infix + suffix.join '' backwards_lineups.push infix + ( Object.assign [], prefix ).reverse().join '' send [ glyph, 'guide/kwic/lineup/forwards', forwards_lineups, ] send [ glyph, 'guide/kwic/lineup/backwards', backwards_lineups, ] #....................................................................................................... return null #----------------------------------------------------------------------------------------------------------- @$add_sims = -> sims_by_glyph = {} #......................................................................................................... return $ ( phrase, send, end ) => if phrase? send phrase [ source_glyph, prd, target_glyph, ] = phrase return unless prd.startsWith 'sim/' return unless XNCHR.is_inner_glyph source_glyph [ _, tag, ] = prd.match /\/(.+)$/ target = sims_by_glyph[ target_glyph ]?= {} ( target[ tag ]?= [] ).push source_glyph if end? for target_glyph, sims of sims_by_glyph send [ target_glyph, "sims/from", sims, ] # for tag, source_glyphs of sims # send [ target_glyph, "sims/from/#{tag}", source_glyphs, ] end() #----------------------------------------------------------------------------------------------------------- @$add_guide_pairs = ( factor_infos ) -> sortcode_by_factors = {} sortcode_by_factors[ guide_uchr ] = sortcode for sortcode, guide_uchr of factor_infos #......................................................................................................... ### TAINT code duplication ### ### TAIN make configurable / store in options ### home = njs_path.resolve __dirname, '../../jizura-datasources' derivatives_home = njs_path.resolve home, 'data/5-derivatives' derivatives_route = njs_path.resolve derivatives_home, 'guide-pairs.txt' derivatives = njs_fs.createWriteStream derivatives_route, { encoding: 'utf-8', } collector = [] excludes = [ '一', ] help "writing results of `add_guide_pairs` to #{derivatives_route}" derivatives.write """ # generated on #{new Date()} # by #{__filename} \n\n""" #......................................................................................................... get_pairs = ( glyph, guides ) -> ### TAINT allow or eliminate duplicates? use pairs and reversed pairs? ### length = guides.length chrs = [] sortcodes = [] entries = [] seen = {} R = { chrs, entries, } #....................................................................................................... return R if length < 2 #....................................................................................................... for i in [ 0 ... length - 1 ] for j in [ i + 1 ... length ] guide_0 = guides[ i ] guide_1 = guides[ j ] continue if guide_0 in excludes or guide_1 in excludes sortcode_0 = sortcode_by_factors[ guide_0 ] sortcode_1 = sortcode_by_factors[ guide_1 ] sortcode_0 ?= 'zzzzzzzz' sortcode_1 ?= 'zzzzzzzz' # return send.error new Error "unknown guide: #{guide_0}" unless sortcode_0? # return send.error new Error "unknown guide: #{guide_1}" unless sortcode_1? #................................................................................................... key = <KEY> guide_<KEY> unless key of seen chrs.push key entries.push "#{sortcode_0} #{sortcode_1}\t#{key}\t#{glyph}" seen[ key ] = 1 #................................................................................................... key = <KEY> guide_<KEY> unless key of seen chrs.push key entries.push "#{sortcode_1} #{sortcode_0}\t#{key}\t#{glyph}" seen[ key ] = 1 #....................................................................................................... return R #......................................................................................................... return $ ( phrase, send, end ) => #....................................................................................................... if phrase? send phrase [ sbj, prd, obj, ] = phrase #..................................................................................................... if prd is 'guide/has/uchr' [ glyph, _, guides, ] = [ sbj, prd, obj, ] if XNCHR.is_inner_glyph glyph { chrs, entries, } = get_pairs glyph, guides # debug '©VrqrO', glyph, chrs # debug '©VrqrO', glyph, entries collector.push entry for entry in entries send [ glyph, 'guide/pair/uchr', chrs, ] send [ glyph, 'guide/pair/entry', entries, ] #....................................................................................................... if end? debug '©70RRX', new Date() whisper "sorting guide pairs..." collector.sort() whisper "done" debug '©70RRX', new Date() whisper "writing guide pairs..." for entry in collector derivatives.write entry + '\n' derivatives.end() whisper "done" debug '©70RRX', new Date() end() # #=========================================================================================================== # find_duplicated_guides = -> # D = require 'pipedreams' # $ = D.remit.bind D # ### TAINT code duplication ### # ### TAIN make configurable / store in options ### # home = njs_path.resolve __dirname, '../../jizura-datasources' # derivatives_home = njs_path.resolve home, 'data/5-derivatives' # # derivatives_route = njs_path.resolve derivatives_home, 'guide-pairs.txt' # input = njs_fs.createReadStream njs_path.resolve derivatives_home, 'guide-pairs.txt' # output = njs_fs.createWriteStream njs_path.resolve derivatives_home, 'guide-pairs-duplicated.txt' # input # .pipe D.$split() # # .pipe D.$parse_csv headers: no # .pipe $ ( line, send ) => send line unless line.length is 0 # .pipe $ ( line, send ) => send line unless line.startsWith '#' # .pipe $ ( line, send ) => send [ line, ( line.split '\t' )... ] # .pipe $ ( [ line, _, guides, glyph, ], send ) => send [ line, glyph, guides, ] # .pipe $ ( fields, send ) => # [ line, glyph, guides, ] = fields # # debug '0912', rpr fields # unless CND.isa_text guides # warn line, fields # send fields # .pipe $ ( [ line, glyph, guides, ], send ) => # send [ line, glyph, ( Array.from guides )... ] # .pipe $ ( fields, send ) => # [ line, glyph, guide_0, guide_1, ] = fields # send fields unless guide_0 is '一' or guide_1 is '一' # .pipe $ ( fields, send ) => # [ line, glyph, guide_0, guide_1, ] = fields # send fields if guide_0 is guide_1 # # .pipe D.$show() # .pipe $ ( [ line, glyph, guide_0, guide_1, ], send ) => send line + '\n' # .pipe output # find_duplicated_guides() #----------------------------------------------------------------------------------------------------------- @v1_split_so_bkey = ( bkey ) -> R = bkey.toString 'utf-8' R = R.split '|' idx_txt = R[ 3 ] R = [ ( R[ 1 ].split ':' )[ 1 ], ( R[ 2 ].split ':' )..., ] R.push ( parseInt idx_txt, 10 ) if idx_txt? and idx_txt.length > 0 for r, idx in R continue unless CND.isa_text r continue unless 'µ' in r R[ idx ] = @v1_unescape r return R #----------------------------------------------------------------------------------------------------------- @v1_$split_so_bkey = -> $ ( bkey, send ) => send @v1_split_so_bkey bkey #----------------------------------------------------------------------------------------------------------- @v1_lte_from_gte = ( gte ) -> R = new Buffer ( last_idx = Buffer.byteLength gte ) + 1 R.write gte R[ last_idx ] = 0xff return R #----------------------------------------------------------------------------------------------------------- @v1_unescape = ( text_esc ) -> matcher = /µ([0-9a-f]{2})/g return text_esc.replace matcher, ( _, cid_hex ) -> return String.fromCharCode parseInt cid_hex, 16 #----------------------------------------------------------------------------------------------------------- @read_factors = ( db, handler ) -> #......................................................................................................... Z = {} #....................................................................................................... gte = 'os|factor/sortcode' lte = @v1_lte_from_gte gte input = db[ '%self' ].createKeyStream { gte, lte, } #....................................................................................................... input .pipe @v1_$split_so_bkey() .pipe D.$observe ( [ sortcode, _, factor, ] ) => Z[ sortcode ] = XNCHR.as_uchr factor .pipe D.$on_end -> handler null, Z #----------------------------------------------------------------------------------------------------------- @copy_jizura_db = -> home = njs_path.resolve __dirname, '../../jizura-datasources' source_route = njs_path.resolve home, 'data/leveldb' target_route = njs_path.resolve home, 'data/leveldb-v2' # ### # # # # # # # # # # # # # # # # # # # # # ### # target_route = '/tmp/leveldb-v2'; alert "using temp DB" # ### # # # # # # # # # # # # # # # # # # # # # ### target_db_size = 1e6 ds_options = require njs_path.resolve home, 'options' source_db = HOLLERITH.new_db source_route target_db = HOLLERITH.new_db target_route, size: target_db_size, create: yes #......................................................................................................... ### TAINT this setting should come from Jizura DB options ### # solids = [ 'guide/kwic/v3/sortcode', ] solids = [] #......................................................................................................... help "using DB at #{source_db[ '%self' ][ 'location' ]}" help "using DB at #{target_db[ '%self' ][ 'location' ]}" #......................................................................................................... step ( resume ) => yield HOLLERITH.clear target_db, resume #......................................................................................................... factor_infos = yield @read_factors source_db, resume # for key, factor of factor_infos # debug key, factor if ( XNCHR.as_uchr factor ) in '羊⺶丷䒑' # process.exit 1 help "read #{( Object.keys factor_infos ).length} entries for factor_infos" #......................................................................................................... # gte = 'so|glyph:中' if ( CND.isa_list sample = options[ 'sample' ] ) and ( sample.length is 1 ) gte = "so|glyph:#{sample[ 0 ]}" else gte = 'so|' lte = @v1_lte_from_gte gte input = source_db[ '%self' ].createKeyStream { gte, lte, } batch_size = 1e4 output = HOLLERITH.$write target_db, { batch: batch_size, solids } #......................................................................................................... help "copying from #{source_route}" help "to #{target_route}" help "reading records with prefix #{rpr gte}" help "writing with batch size #{ƒ batch_size}" #......................................................................................................... input #....................................................................................................... .pipe @v1_$split_so_bkey() .pipe @$show_progress 1e4 .pipe @$keep_small_sample() .pipe @$throw_out_pods() .pipe @$remove_duplicate_kana_readings() .pipe @$cast_types ds_options .pipe @$collect_lists() .pipe @$compact_lists() .pipe @$add_version_to_kwic_v1() # .pipe @$add_kwic_v2() .pipe @$add_kwic_v3 factor_infos .pipe @$add_kwic_v3_wrapped_lineups factor_infos # .pipe @$add_guide_pairs factor_infos .pipe @$add_factor_membership factor_infos .pipe @$add_components() .pipe @$add_lineup_back_and_forwards() .pipe @$add_factorial_factors factor_infos .pipe @$add_sims() # .pipe D.$show() .pipe D.$count ( count ) -> help "kept #{ƒ count} phrases" .pipe D.$stop_time "copy Jizura DB" .pipe output ############################################################################################################ unless module.parent? @copy_jizura_db()
true
############################################################################################################ njs_path = require 'path' njs_fs = require 'fs' join = njs_path.join #........................................................................................................... CND = require 'cnd' rpr = CND.rpr badge = 'JIZURA/copy-jizuradb-to-Hollerith2-format' log = CND.get_logger 'plain', badge info = CND.get_logger 'info', badge whisper = CND.get_logger 'whisper', badge alert = CND.get_logger 'alert', badge debug = CND.get_logger 'debug', badge warn = CND.get_logger 'warn', badge help = CND.get_logger 'help', badge urge = CND.get_logger 'urge', badge echo = CND.echo.bind CND #........................................................................................................... suspend = require 'coffeenode-suspend' step = suspend.step #........................................................................................................... D = require 'pipedreams' $ = D.remit.bind D $async = D.remit_async.bind D #........................................................................................................... HOLLERITH = require 'hollerith' # DEMO = require './demo' KWIC = require 'kwic' IDLX = require 'idlx' XNCHR = require './XNCHR' ƒ = CND.format_number.bind CND #----------------------------------------------------------------------------------------------------------- options = sample: null # sample: [ '國', ] # sample: [ '⿓', '龍', '龍', '邔', '𨙬', '國', '金', '釒', ] # sample: [ '高', ] # sample: [ '𡬜', '國', '𠵓', ] # sample: [ '𡬜', '國', '𠵓', '后', '花', '醒', ] # #----------------------------------------------------------------------------------------------------------- # @$show_progress = ( size ) -> # size ?= 1e3 # count = 0 # return $ ( data, send ) => # count += 1 # echo ƒ count if count % size is 0 # send data #----------------------------------------------------------------------------------------------------------- @$show_progress = ( size ) -> size ?= 1e3 phrase_count = 0 glyph_count = 0 last_glyph = null return D.$observe ( phrase, has_ended ) => unless has_ended phrase_count += 1 echo ƒ phrase_count if phrase_count % size is 0 glyph_count += +1 if ( glyph = phrase[ 0 ] ) isnt last_glyph last_glyph = glyph else help "read #{ƒ phrase_count} phrases for #{ƒ glyph_count} glyphs" help "(#{( phrase_count / glyph_count ).toFixed 2} phrases per glyph)" #----------------------------------------------------------------------------------------------------------- @$keep_small_sample = -> return $ ( key, send ) => return send key unless options[ 'sample' ]? [ glyph, prd, obj, idx, ] = key send key if glyph in options[ 'sample' ] #----------------------------------------------------------------------------------------------------------- @$throw_out_pods = -> return $ ( key, send ) => [ glyph, prd, obj, idx, ] = key send key unless prd is 'pod' #----------------------------------------------------------------------------------------------------------- @$remove_duplicate_kana_readings = -> readings_by_glyph = {} return $ ( key, send ) => [ glyph, prd, obj, idx, ] = key if prd in [ 'reading/hi', ] target = readings_by_glyph[ glyph ]?= [] if obj in target return warn "skipping duplicate reading #{glyph} #{obj}" target.push obj send key #----------------------------------------------------------------------------------------------------------- @$cast_types = ( ds_options ) -> return $ ( [ sbj, prd, obj, idx, ], send ) => type_description = ds_options[ 'schema' ][ prd ] unless type_description? warn "no type description for predicate #{rpr prd}" else switch type = type_description[ 'type' ] when 'int' obj = parseInt obj, 10 when 'text' ### TAINT we have no booleans configured ### if obj is 'true' then obj = true else if obj is 'false' then obj = false send if idx? then [ sbj, prd, obj, idx, ] else [ sbj, prd, obj, ] #----------------------------------------------------------------------------------------------------------- @$collect_lists = -> objs = null sbj_prd = null last_digest = null context_keys = [] has_errors = false #......................................................................................................... return $ ( key, send, end ) => #....................................................................................................... if key? context_keys.push key; context_keys.shift() if context_keys.length > 10 [ sbj, prd, obj, idx, ] = key digest = JSON.stringify [ sbj, prd, ] #..................................................................................................... if digest is last_digest if idx? objs[ idx ] = obj else ### A certain subject/predicate combination can only ever be repeated if an index is present in the key ### alert() alert "erroneous repeated entry; context:" alert context_keys has_errors = true else send [ sbj_prd..., objs, ] if objs? objs = null last_digest = digest if idx? objs = [] objs[ idx ] = obj sbj_prd = [ sbj, prd, ] else send key #....................................................................................................... if end? send [ sbj_prd..., objs, ] if objs? return send.error new Error "there were errors; see alerts above" if has_errors end() #....................................................................................................... return null #----------------------------------------------------------------------------------------------------------- @$compact_lists = -> return $ ( [ sbj, prd, obj, ], send ) => ### Compactify sparse lists so all `undefined` elements are removed; warn about this ### if ( CND.type_of obj ) is 'list' new_obj = ( element for element in obj when element isnt undefined ) if obj.length isnt new_obj.length warn "phrase #{rpr [ sbj, prd, obj, ]} contained undefined elements; compactified" obj = new_obj send [ sbj, prd, obj, ] #----------------------------------------------------------------------------------------------------------- @$add_version_to_kwic_v1 = -> ### mark up all predicates `guide/kwic/*` as `guide/kwic/v1/*` ### return $ ( [ sbj, prd, obj, ], send ) => if prd.startsWith 'guide/kwic/' prd = prd.replace /^guide\/kwic\//, 'guide/kwic/v1/' send [ sbj, prd, obj, ] #----------------------------------------------------------------------------------------------------------- @_long_wrapped_lineups_from_guides = ( guides ) -> ### Extending lineups to accommodate for glyphs with 'overlong' factorials (those with more than 6 factors; these were previously excluded from the gamut in `feed-db.coffee`, line 2135, `@KWIC.$compose_lineup_facets`). ### ### TAINT here be magic numbers ### lineup = guides[ .. ] last_idx = lineup.length - 1 + 6 lineup.push '\u3000' while lineup.length < 19 lineup.unshift '\u3000' while lineup.length < 25 R = [] for idx in [ 6 .. last_idx ] infix = lineup[ idx ] suffix = lineup[ idx + 1 .. idx + 6 ].join '' prefix = lineup[ idx - 6 .. idx - 1 ].join '' R.push [ infix, suffix, prefix, ].join ',' return R # #----------------------------------------------------------------------------------------------------------- # @$add_kwic_v2 = -> # ### see `demo/show_kwic_v2_and_v3_sample` ### # last_glyph = null # long_wrapped_lineups = null # return $ ( [ sbj, prd, obj, ], send ) => # #....................................................................................................... # if prd is 'guide/has/uchr' # last_glyph = sbj # long_wrapped_lineups = @_long_wrapped_lineups_from_guides obj # #....................................................................................................... # return send [ sbj, prd, obj, ] unless prd.startsWith 'guide/kwic/v1/' # #....................................................................................................... # switch prd.replace /^guide\/kwic\/v1\//, '' # when 'lineup/wrapped/infix', 'lineup/wrapped/prefix', 'lineup/wrapped/suffix', 'lineup/wrapped/single' # ### copy to target ### # send [ sbj, prd, obj, ] # when 'sortcode' # [ glyph, _, sortcodes_v1, ] = [ sbj, prd, obj, ] # sortcodes_v2 = [] # #................................................................................................... # ### The difference between KWIC sortcodes of version 1 and version 2 lies in the re-arrangement # of the factor codes and the index codes. In v1, the index codes appeared interspersed with # the factor codes; in v2, the index codes come up front and the index codes come in the latter half # of the sortcode strings. The effect of this rearrangement is that now that all of the indexes # (which indicate the position of each factor in the lineup) are weaker than any of the factor codes, # like sequences of factor codes (and, therefore, factors) will always be grouped together (whereas # in v1, only like factors with like positions appeared together, and often like sequences appeared # with other sequences interspersed where their indexes demanded it so). ### # for sortcode_v1 in sortcodes_v1 # sortrow_v1 = ( x for x in sortcode_v1.split /(........,..),/ when x.length > 0 ) # sortrow_v1 = ( x.split ',' for x in sortrow_v1 ) # sortrow_v2 = [] # sortrow_v2.push sortcode for [ sortcode, _, ] in sortrow_v1 # sortrow_v2.push position for [ _, position, ] in sortrow_v1 # sortcodes_v2.push sortrow_v2.join ',' # #................................................................................................... # unless glyph is last_glyph # return send.error new Error "unexpected mismatch: #{rpr glyph}, #{rpr last_glyph}" # #................................................................................................... # unless long_wrapped_lineups? # return send.error new Error "missing long wrapped lineups for glyph #{rpr glyph}" # #................................................................................................... # unless sortcodes_v2.length is long_wrapped_lineups.length # warn 'sortcodes_v2: ', sortcodes_v2 # warn 'long_wrapped_lineups: ', long_wrapped_lineups # return send.error new Error "length mismatch for glyph #{rpr glyph}" # #................................................................................................... # sortcodes_v1[ idx ] += ";" + lineup for lineup, idx in long_wrapped_lineups # sortcodes_v2[ idx ] += ";" + lineup for lineup, idx in long_wrapped_lineups # send [ glyph, 'guide/kwic/v2/lineup/wrapped/single', long_wrapped_lineups, ] # long_wrapped_lineups = null # #................................................................................................... # send [ glyph, prd, sortcodes_v1, ] # send [ glyph, 'guide/kwic/v2/sortcode', sortcodes_v2, ] # else # send.error new Error "unhandled predicate #{rpr prd}" #----------------------------------------------------------------------------------------------------------- @$add_kwic_v3 = ( factor_infos ) -> ### see `demo/show_kwic_v2_and_v3_sample` ### #......................................................................................................... return $ ( [ sbj, prd, obj, ], send ) => return if prd.startsWith 'guide/kwic/v2/' return send [ sbj, prd, obj, ] unless prd.startsWith 'guide/kwic/v1/' return if prd isnt 'guide/kwic/v1/sortcode' #....................................................................................................... [ glyph, _, [ sortcode_v1, ... ], ] = [ sbj, prd, obj, ] #....................................................................................................... sortrow_v1 = ( x for x in sortcode_v1.split /(........,..),/ when x.length > 0 ) weights = ( x.split ',' for x in sortrow_v1 ) weights.pop() weights = ( sortcode for [ sortcode, _, ] in weights ) weights = ( sortcode for sortcode in weights when sortcode isnt '--------' ) weights = ( ( sortcode.replace /~/g, '-' ) for sortcode in weights ) weights = ( ( sortcode.replace /----/g, 'f---' ) for sortcode in weights ) #....................................................................................................... factors = ( factor_infos[ sortcode ] for sortcode in weights ) factors = ( ( if factor? then factor else '〓' ) for factor in factors ) #....................................................................................................... unless weights.length is factors.length warn glyph, weights, factors, weights.length, factors.length return #....................................................................................................... permutations = KWIC.get_permutations factors, weights send [ glyph, 'guide/kwic/v3/sortcode', permutations, ] #----------------------------------------------------------------------------------------------------------- @$add_kwic_v3_wrapped_lineups = ( factor_infos ) -> prefix_max_length = 3 suffix_max_length = 3 #......................................................................................................... return $ ( [ sbj, prd, obj, ], send ) => send [ sbj, prd, obj, ] return unless prd is 'guide/kwic/v3/sortcode' [ glyph, _, permutations, ] = [ sbj, prd, obj, ] lineups = [] #....................................................................................................... for permutation, idx in permutations [ sortcode, infix, suffix, prefix, ] = permutation suffix = Object.assign [], suffix prefix = Object.assign [], prefix #..................................................................................................... prefix_length = prefix.length suffix_length = suffix.length prefix_delta = prefix_length - prefix_max_length suffix_delta = suffix_length - suffix_max_length prefix_excess_max_length = suffix_max_length - suffix_length suffix_excess_max_length = prefix_max_length - prefix_length prefix_excess = [] suffix_excess = [] prefix_padding = [] suffix_padding = [] #..................................................................................................... if prefix_delta > 0 prefix_excess = prefix.splice 0, prefix_delta if suffix_delta > 0 suffix_excess = suffix.splice suffix.length - suffix_delta, suffix_delta #..................................................................................................... while prefix_excess.length > 0 and prefix_excess.length > prefix_excess_max_length - 1 prefix_excess.pop() while suffix_excess.length > 0 and suffix_excess.length > suffix_excess_max_length - 1 suffix_excess.shift() #..................................................................................................... while prefix_padding.length + suffix_excess.length + prefix.length < prefix_max_length prefix_padding.unshift '\u3000' while suffix_padding.length + prefix_excess.length + suffix.length < suffix_max_length suffix_padding.unshift '\u3000' #..................................................................................................... prefix.splice 0, 0, prefix_padding... prefix.splice 0, 0, suffix_excess... suffix.splice suffix.length, 0, suffix_padding... suffix.splice suffix.length, 0, prefix_excess... #..................................................................................................... prefix = prefix.join '' suffix = suffix.join '' lineups.push [ sortcode, infix, suffix, prefix, ] #....................................................................................................... send [ glyph, 'guide/kwic/v3/sortcode/wrapped-lineups', lineups, ] #----------------------------------------------------------------------------------------------------------- @$add_factor_membership = ( factor_infos ) -> glyphs_by_factors = {} #......................................................................................................... return $ ( phrase, send, end ) => if phrase? send phrase [ glyph, prd, obj, ] = phrase return unless prd is 'guide/has/uchr' for factor in obj continue if factor is glyph ( glyphs_by_factors[ factor ]?= new Set() ).add glyph if end? for factor, glyphs of glyphs_by_factors send [ factor, 'factor/has/glyph/uchr', Array.from glyphs.keys(), ] # glyphs.forEach ( glyph ) => # send [ factor, 'factor/has/glyph/uchr', glyph, ] end() #----------------------------------------------------------------------------------------------------------- ### TAINT code duplication ### @$add_components = -> ### The field `component/uchr` lists all the components that appear as part of a given glyph, collected from all its formulas and down through all recursive steps of component resolution. The resulting lists can, therefore, be quite long and potentially include parts that are present in virtually all glyphs, such as `丿` or `一`. The components listed are unique and appear in no particular order. As an example, the DB contains the folloqing entry: ``` spo|䱴|component/uchr: [ '魚', '恒', '', '灬', '𠂊', '田', '丿', '㇇', '囗', '十', '日', '丨', '冂', '一', '𠃌', '彐', '', '', '丶', '', '忄', '亘', '旦', ] ``` ### ### Immediate Constituents (ICs) ### ics_by_glyph = {} seen_glyphs = new Set() glyph_count = 0 #......................................................................................................... resolve_ics = ( glyph ) => return if seen_glyphs.has glyph seen_glyphs.add glyph if ( entry = ics_by_glyph[ glyph ] )? for ic in Array.from entry.keys() resolve_ics ic if ( sub_entry = ics_by_glyph[ ic ] )? for sub_ic in Array.from sub_entry entry.add sub_ic #......................................................................................................... return $ ( phrase, send, end ) => #....................................................................................................... if phrase? send phrase [ glyph, prd, obj, ] = phrase return unless prd is 'formula' ### TAINT collecting ICs from outer glyphs might aid in resolving more inner glyphs ### return unless XNCHR.is_inner_glyph glyph glyph = XNCHR.as_uchr glyph glyph_count += +1 for formula, formula_idx in obj ics = IDLX.find_all_non_operators formula target = ics_by_glyph[ glyph ]?= new Set() target.add ( XNCHR.as_uchr ic ) for ic in ics #....................................................................................................... if end? resolve_ics glyph for glyph of ics_by_glyph ics_by_glyph[ glyph ] = Array.from entry for glyph, entry of ics_by_glyph for glyph, ics of ics_by_glyph send [ glyph, 'component/uchr', ics, ] end() #....................................................................................................... return null #----------------------------------------------------------------------------------------------------------- ### TAINT code duplication ### @$add_factorial_factors = ( factor_infos ) -> ### Factorial Factors: the factors of factors; used for cross-referencing. E.g. the formula of 鬲 is ⿱𠮛⿵冂&jzr#xe152;; all the components of 鬲 are factors except for 𠮛, which must again be analyzed into 𠮛:⿱一口, leading to the entry 鬲:一口冂&jzr#xe152;. ### factors = new Set() factors.add ( XNCHR.as_uchr factor ) for _, factor of factor_infos # debug '©67157', factors; process.exit 1 ### Immediate Constituents (ICs) ### factors_by_factor = {} seen_glyphs = new Set() factor_count = 0 #......................................................................................................... return $ ( phrase, send, end ) => #....................................................................................................... if phrase? send phrase [ glyph, prd, obj, ] = phrase return unless prd is 'formula' ### TAINT collecting ICs from outer glyphs might aid in resolving more inner glyphs ### return unless XNCHR.is_inner_glyph glyph glyph = XNCHR.as_uchr glyph factor_count += +1 if factors.has glyph entry = factors_by_factor[ glyph ]?= [] for formula, formula_idx in obj ics = IDLX.find_all_non_operators formula entry.push ( ( XNCHR.as_uchr ic ) for ic in ics ) #....................................................................................................... if end? factors_by_factor_json = JSON.stringify factors_by_factor, null, ' ' factors_json = JSON.stringify ( Array.from factors ), null, ' ' ics_route = njs_path.resolve __dirname, '../../jizura-datasources/data/5-derivatives/ics-by-glyphs.json' factors_route = njs_path.resolve __dirname, '../../jizura-datasources/data/5-derivatives/factors.json' warn "write to #{ics_route}" njs_fs.writeFileSync ics_route, factors_by_factor_json warn "write to #{factors_route}" njs_fs.writeFileSync factors_route, factors_json # #..................................................................................................... # for factor in Array.from factors.keys() # unless ( entry = factors_by_factor[ factor ] )? # whisper "no ICs for factor #{factor}" # continue # for ics in entry # for ic in ics # unless factors.has ic # warn "factor #{factor} has non-factorial IC #{ic}" #..................................................................................................... end() #....................................................................................................... return null #----------------------------------------------------------------------------------------------------------- ### TAINT code duplication ### @$add_lineup_back_and_forwards = -> #......................................................................................................... return $ ( phrase, send ) => #....................................................................................................... send phrase [ glyph, prd, obj, ] = phrase return unless prd is 'guide/kwic/v3/sortcode' return unless XNCHR.is_inner_glyph glyph #....................................................................................................... forwards_lineups = [] backwards_lineups = [] #....................................................................................................... for permutation, idx in obj [ sortcode, infix, suffix, prefix, ] = permutation forwards_lineups.push infix + suffix.join '' backwards_lineups.push infix + ( Object.assign [], prefix ).reverse().join '' send [ glyph, 'guide/kwic/lineup/forwards', forwards_lineups, ] send [ glyph, 'guide/kwic/lineup/backwards', backwards_lineups, ] #....................................................................................................... return null #----------------------------------------------------------------------------------------------------------- @$add_sims = -> sims_by_glyph = {} #......................................................................................................... return $ ( phrase, send, end ) => if phrase? send phrase [ source_glyph, prd, target_glyph, ] = phrase return unless prd.startsWith 'sim/' return unless XNCHR.is_inner_glyph source_glyph [ _, tag, ] = prd.match /\/(.+)$/ target = sims_by_glyph[ target_glyph ]?= {} ( target[ tag ]?= [] ).push source_glyph if end? for target_glyph, sims of sims_by_glyph send [ target_glyph, "sims/from", sims, ] # for tag, source_glyphs of sims # send [ target_glyph, "sims/from/#{tag}", source_glyphs, ] end() #----------------------------------------------------------------------------------------------------------- @$add_guide_pairs = ( factor_infos ) -> sortcode_by_factors = {} sortcode_by_factors[ guide_uchr ] = sortcode for sortcode, guide_uchr of factor_infos #......................................................................................................... ### TAINT code duplication ### ### TAIN make configurable / store in options ### home = njs_path.resolve __dirname, '../../jizura-datasources' derivatives_home = njs_path.resolve home, 'data/5-derivatives' derivatives_route = njs_path.resolve derivatives_home, 'guide-pairs.txt' derivatives = njs_fs.createWriteStream derivatives_route, { encoding: 'utf-8', } collector = [] excludes = [ '一', ] help "writing results of `add_guide_pairs` to #{derivatives_route}" derivatives.write """ # generated on #{new Date()} # by #{__filename} \n\n""" #......................................................................................................... get_pairs = ( glyph, guides ) -> ### TAINT allow or eliminate duplicates? use pairs and reversed pairs? ### length = guides.length chrs = [] sortcodes = [] entries = [] seen = {} R = { chrs, entries, } #....................................................................................................... return R if length < 2 #....................................................................................................... for i in [ 0 ... length - 1 ] for j in [ i + 1 ... length ] guide_0 = guides[ i ] guide_1 = guides[ j ] continue if guide_0 in excludes or guide_1 in excludes sortcode_0 = sortcode_by_factors[ guide_0 ] sortcode_1 = sortcode_by_factors[ guide_1 ] sortcode_0 ?= 'zzzzzzzz' sortcode_1 ?= 'zzzzzzzz' # return send.error new Error "unknown guide: #{guide_0}" unless sortcode_0? # return send.error new Error "unknown guide: #{guide_1}" unless sortcode_1? #................................................................................................... key = PI:KEY:<KEY>END_PI guide_PI:KEY:<KEY>END_PI unless key of seen chrs.push key entries.push "#{sortcode_0} #{sortcode_1}\t#{key}\t#{glyph}" seen[ key ] = 1 #................................................................................................... key = PI:KEY:<KEY>END_PI guide_PI:KEY:<KEY>END_PI unless key of seen chrs.push key entries.push "#{sortcode_1} #{sortcode_0}\t#{key}\t#{glyph}" seen[ key ] = 1 #....................................................................................................... return R #......................................................................................................... return $ ( phrase, send, end ) => #....................................................................................................... if phrase? send phrase [ sbj, prd, obj, ] = phrase #..................................................................................................... if prd is 'guide/has/uchr' [ glyph, _, guides, ] = [ sbj, prd, obj, ] if XNCHR.is_inner_glyph glyph { chrs, entries, } = get_pairs glyph, guides # debug '©VrqrO', glyph, chrs # debug '©VrqrO', glyph, entries collector.push entry for entry in entries send [ glyph, 'guide/pair/uchr', chrs, ] send [ glyph, 'guide/pair/entry', entries, ] #....................................................................................................... if end? debug '©70RRX', new Date() whisper "sorting guide pairs..." collector.sort() whisper "done" debug '©70RRX', new Date() whisper "writing guide pairs..." for entry in collector derivatives.write entry + '\n' derivatives.end() whisper "done" debug '©70RRX', new Date() end() # #=========================================================================================================== # find_duplicated_guides = -> # D = require 'pipedreams' # $ = D.remit.bind D # ### TAINT code duplication ### # ### TAIN make configurable / store in options ### # home = njs_path.resolve __dirname, '../../jizura-datasources' # derivatives_home = njs_path.resolve home, 'data/5-derivatives' # # derivatives_route = njs_path.resolve derivatives_home, 'guide-pairs.txt' # input = njs_fs.createReadStream njs_path.resolve derivatives_home, 'guide-pairs.txt' # output = njs_fs.createWriteStream njs_path.resolve derivatives_home, 'guide-pairs-duplicated.txt' # input # .pipe D.$split() # # .pipe D.$parse_csv headers: no # .pipe $ ( line, send ) => send line unless line.length is 0 # .pipe $ ( line, send ) => send line unless line.startsWith '#' # .pipe $ ( line, send ) => send [ line, ( line.split '\t' )... ] # .pipe $ ( [ line, _, guides, glyph, ], send ) => send [ line, glyph, guides, ] # .pipe $ ( fields, send ) => # [ line, glyph, guides, ] = fields # # debug '0912', rpr fields # unless CND.isa_text guides # warn line, fields # send fields # .pipe $ ( [ line, glyph, guides, ], send ) => # send [ line, glyph, ( Array.from guides )... ] # .pipe $ ( fields, send ) => # [ line, glyph, guide_0, guide_1, ] = fields # send fields unless guide_0 is '一' or guide_1 is '一' # .pipe $ ( fields, send ) => # [ line, glyph, guide_0, guide_1, ] = fields # send fields if guide_0 is guide_1 # # .pipe D.$show() # .pipe $ ( [ line, glyph, guide_0, guide_1, ], send ) => send line + '\n' # .pipe output # find_duplicated_guides() #----------------------------------------------------------------------------------------------------------- @v1_split_so_bkey = ( bkey ) -> R = bkey.toString 'utf-8' R = R.split '|' idx_txt = R[ 3 ] R = [ ( R[ 1 ].split ':' )[ 1 ], ( R[ 2 ].split ':' )..., ] R.push ( parseInt idx_txt, 10 ) if idx_txt? and idx_txt.length > 0 for r, idx in R continue unless CND.isa_text r continue unless 'µ' in r R[ idx ] = @v1_unescape r return R #----------------------------------------------------------------------------------------------------------- @v1_$split_so_bkey = -> $ ( bkey, send ) => send @v1_split_so_bkey bkey #----------------------------------------------------------------------------------------------------------- @v1_lte_from_gte = ( gte ) -> R = new Buffer ( last_idx = Buffer.byteLength gte ) + 1 R.write gte R[ last_idx ] = 0xff return R #----------------------------------------------------------------------------------------------------------- @v1_unescape = ( text_esc ) -> matcher = /µ([0-9a-f]{2})/g return text_esc.replace matcher, ( _, cid_hex ) -> return String.fromCharCode parseInt cid_hex, 16 #----------------------------------------------------------------------------------------------------------- @read_factors = ( db, handler ) -> #......................................................................................................... Z = {} #....................................................................................................... gte = 'os|factor/sortcode' lte = @v1_lte_from_gte gte input = db[ '%self' ].createKeyStream { gte, lte, } #....................................................................................................... input .pipe @v1_$split_so_bkey() .pipe D.$observe ( [ sortcode, _, factor, ] ) => Z[ sortcode ] = XNCHR.as_uchr factor .pipe D.$on_end -> handler null, Z #----------------------------------------------------------------------------------------------------------- @copy_jizura_db = -> home = njs_path.resolve __dirname, '../../jizura-datasources' source_route = njs_path.resolve home, 'data/leveldb' target_route = njs_path.resolve home, 'data/leveldb-v2' # ### # # # # # # # # # # # # # # # # # # # # # ### # target_route = '/tmp/leveldb-v2'; alert "using temp DB" # ### # # # # # # # # # # # # # # # # # # # # # ### target_db_size = 1e6 ds_options = require njs_path.resolve home, 'options' source_db = HOLLERITH.new_db source_route target_db = HOLLERITH.new_db target_route, size: target_db_size, create: yes #......................................................................................................... ### TAINT this setting should come from Jizura DB options ### # solids = [ 'guide/kwic/v3/sortcode', ] solids = [] #......................................................................................................... help "using DB at #{source_db[ '%self' ][ 'location' ]}" help "using DB at #{target_db[ '%self' ][ 'location' ]}" #......................................................................................................... step ( resume ) => yield HOLLERITH.clear target_db, resume #......................................................................................................... factor_infos = yield @read_factors source_db, resume # for key, factor of factor_infos # debug key, factor if ( XNCHR.as_uchr factor ) in '羊⺶丷䒑' # process.exit 1 help "read #{( Object.keys factor_infos ).length} entries for factor_infos" #......................................................................................................... # gte = 'so|glyph:中' if ( CND.isa_list sample = options[ 'sample' ] ) and ( sample.length is 1 ) gte = "so|glyph:#{sample[ 0 ]}" else gte = 'so|' lte = @v1_lte_from_gte gte input = source_db[ '%self' ].createKeyStream { gte, lte, } batch_size = 1e4 output = HOLLERITH.$write target_db, { batch: batch_size, solids } #......................................................................................................... help "copying from #{source_route}" help "to #{target_route}" help "reading records with prefix #{rpr gte}" help "writing with batch size #{ƒ batch_size}" #......................................................................................................... input #....................................................................................................... .pipe @v1_$split_so_bkey() .pipe @$show_progress 1e4 .pipe @$keep_small_sample() .pipe @$throw_out_pods() .pipe @$remove_duplicate_kana_readings() .pipe @$cast_types ds_options .pipe @$collect_lists() .pipe @$compact_lists() .pipe @$add_version_to_kwic_v1() # .pipe @$add_kwic_v2() .pipe @$add_kwic_v3 factor_infos .pipe @$add_kwic_v3_wrapped_lineups factor_infos # .pipe @$add_guide_pairs factor_infos .pipe @$add_factor_membership factor_infos .pipe @$add_components() .pipe @$add_lineup_back_and_forwards() .pipe @$add_factorial_factors factor_infos .pipe @$add_sims() # .pipe D.$show() .pipe D.$count ( count ) -> help "kept #{ƒ count} phrases" .pipe D.$stop_time "copy Jizura DB" .pipe output ############################################################################################################ unless module.parent? @copy_jizura_db()
[ { "context": "###\n\n Neo4j driver for Node\n\n Copyright 2011 Daniel Gasienica <daniel@gasienica.ch>\n Copyright 2011 Aseem Ki", "end": 67, "score": 0.9998816251754761, "start": 51, "tag": "NAME", "value": "Daniel Gasienica" }, { "context": "er for Node\n\n Copyright 201...
node_modules/neo4j/lib/index.coffee
aranoah/journey-planner
484
### Neo4j driver for Node Copyright 2011 Daniel Gasienica <daniel@gasienica.ch> Copyright 2011 Aseem Kishore <aseem.kishore@gmail.com> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### exports.GraphDatabase = require './GraphDatabase' # XXX serialize functions not used internally right now, but used by outside # clients, e.g. the scrapedb script. TODO formalize these better? util = require './util' exports.serialize = util.serialize exports.deserialize = util.deserialize
149149
### Neo4j driver for Node Copyright 2011 <NAME> <<EMAIL>> Copyright 2011 <NAME> <<EMAIL>> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### exports.GraphDatabase = require './GraphDatabase' # XXX serialize functions not used internally right now, but used by outside # clients, e.g. the scrapedb script. TODO formalize these better? util = require './util' exports.serialize = util.serialize exports.deserialize = util.deserialize
true
### Neo4j driver for Node Copyright 2011 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> Copyright 2011 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ### exports.GraphDatabase = require './GraphDatabase' # XXX serialize functions not used internally right now, but used by outside # clients, e.g. the scrapedb script. TODO formalize these better? util = require './util' exports.serialize = util.serialize exports.deserialize = util.deserialize
[ { "context": " { type: 'object' } }\n }\n }\n data = { name: 'Bob', numbers: [\n {'number':'401-401-1337', 'type'", "end": 206, "score": 0.9996698498725891, "start": 203, "tag": "NAME", "value": "Bob" } ]
test/getters-setters/delete.coffee
lgr7/codecombattreema
66
describe 'TreemaNode.delete', -> schema = { type: 'object', properties: { name: { type: 'string' } numbers: { type: 'array', items: { type: 'object' } } } } data = { name: 'Bob', numbers: [ {'number':'401-401-1337', 'type':'Home'}, {'number':'123-456-7890', 'type':'Work'} ]} treema = TreemaNode.make(null, {data: data, schema: schema}) treema.build() it 'removes objects from an array', -> expect(treema.delete('/numbers/0')).toBeTruthy() numbers = treema.get('/numbers') expect(numbers.length).toBe(1) expect(numbers[0].type).toBe('Work') it 'removes properties from an object', -> expect(treema.delete('/numbers/0/type')).toBeTruthy() expect(treema.get('/numbers').type).toBeUndefined() expect(treema.get('/numbers/type')).toBeUndefined()
160832
describe 'TreemaNode.delete', -> schema = { type: 'object', properties: { name: { type: 'string' } numbers: { type: 'array', items: { type: 'object' } } } } data = { name: '<NAME>', numbers: [ {'number':'401-401-1337', 'type':'Home'}, {'number':'123-456-7890', 'type':'Work'} ]} treema = TreemaNode.make(null, {data: data, schema: schema}) treema.build() it 'removes objects from an array', -> expect(treema.delete('/numbers/0')).toBeTruthy() numbers = treema.get('/numbers') expect(numbers.length).toBe(1) expect(numbers[0].type).toBe('Work') it 'removes properties from an object', -> expect(treema.delete('/numbers/0/type')).toBeTruthy() expect(treema.get('/numbers').type).toBeUndefined() expect(treema.get('/numbers/type')).toBeUndefined()
true
describe 'TreemaNode.delete', -> schema = { type: 'object', properties: { name: { type: 'string' } numbers: { type: 'array', items: { type: 'object' } } } } data = { name: 'PI:NAME:<NAME>END_PI', numbers: [ {'number':'401-401-1337', 'type':'Home'}, {'number':'123-456-7890', 'type':'Work'} ]} treema = TreemaNode.make(null, {data: data, schema: schema}) treema.build() it 'removes objects from an array', -> expect(treema.delete('/numbers/0')).toBeTruthy() numbers = treema.get('/numbers') expect(numbers.length).toBe(1) expect(numbers[0].type).toBe('Work') it 'removes properties from an object', -> expect(treema.delete('/numbers/0/type')).toBeTruthy() expect(treema.get('/numbers').type).toBeUndefined() expect(treema.get('/numbers/type')).toBeUndefined()
[ { "context": "#\n# Copyright (c) 2014 by Lifted Studios. All Rights Reserved.\n#\n\nfs = require 'fs'\n\n{B", "end": 37, "score": 0.6258552670478821, "start": 26, "tag": "NAME", "value": "Lifted Stud" } ]
lib/package-sync.coffee
postcasio/package-sync
0
# # Copyright (c) 2014 by Lifted Studios. All Rights Reserved. # fs = require 'fs' {BufferedProcess} = require 'atom' PackageList = require './package-list' StatusMessage = require './status-message' # Public: Performs the package synchronization. # # ## Events # # This class has no events. module.exports = class PackageSync # Internal: Path to `apm`. apmPath: atom.packages.getApmPath() # Internal: Process object of the current install. currentInstall: null # Internal: Timeout for messages that should be up longer. longMessageTimeout: 15000 # Internal: Status bar message. message: null # Internal: Packages in the process of being installed. packagesToInstall: [] # Internal: Timeout for messages that should be up for only a short time. shortMessageTimeout: 1000 # Internal: Timeout for status bar message. timeout: null # Public: Creates the package list for the user from the list of available packages. createPackageList: -> new PackageList().setPackages() # Public: Opens the package list. openPackageList: -> atom.workspace.open(PackageList.getPackageListPath()) # Public: Installs any packages that are missing from the `packages.cson` configuration file. sync: -> missing = @getMissingPackages() @installPackages(missing) # Internal: Displays a message in the status bar. # # If `timeout` is specified, the message will automatically be cleared in `timeout` milliseconds. # # message - A {String} containing the message to be displayed. # timeout - An optional {Number} specifying the time in milliseconds until the message will be # cleared. displayMessage: (message, timeout) -> clearTimeout(@timeout) if @timeout? if @message? @message.setText(message) else @message = new StatusMessage(message) @setMessageTimeout(timeout) if timeout? # Internal: Execute APM to install the given package. # # pkg - A {String} containing the name of the package to install. executeApm: (pkg) -> @displayMessage("Installing #{pkg}") command = @apmPath args = ['install', pkg] stdout = (output) -> stderr = (output) -> exit = (exitCode) => if exitCode is 0 if @packagesToInstall.length > 0 @displayMessage("#{pkg} installed!", @shortMessageTimeout) else @displayMessage('Package Sync complete!', @longMessageTimeout) else @displayMessage("An error occurred installing #{pkg}", @longMessageTimeout) @currentInstall = null @installPackage() @currentInstall = new BufferedProcess({command, args, stdout, stderr, exit}) # Internal: Gets the list of packages that are missing. # # Returns an {Array} of names of packages that need to be installed. getMissingPackages: -> list = new PackageList() syncPackages = list.getPackages() availablePackages = atom.packages.getAvailablePackageNames() value for value in syncPackages when value not in availablePackages # Internal: Installs the next package in the list. installPackage: -> # Exit if there is already an installation running or if there are no more # packages to install. return if @currentInstall? or @packagesToInstall.length is 0 @executeApm(@packagesToInstall.shift()) # Internal: Installs each of the packages in the given list. # # packages - An {Array} containing the names of packages to install. installPackages: (packages) -> @packagesToInstall.push(packages...) @installPackage() # Internal: Sets a timeout to remove the status bar message. # # timeout - The {Number} of milliseconds until the message should be removed. setMessageTimeout: (timeout) -> clearTimeout(@timeout) if @timeout? @timeout = setTimeout(=> @message.remove() @message = null , timeout)
27352
# # Copyright (c) 2014 by <NAME>ios. All Rights Reserved. # fs = require 'fs' {BufferedProcess} = require 'atom' PackageList = require './package-list' StatusMessage = require './status-message' # Public: Performs the package synchronization. # # ## Events # # This class has no events. module.exports = class PackageSync # Internal: Path to `apm`. apmPath: atom.packages.getApmPath() # Internal: Process object of the current install. currentInstall: null # Internal: Timeout for messages that should be up longer. longMessageTimeout: 15000 # Internal: Status bar message. message: null # Internal: Packages in the process of being installed. packagesToInstall: [] # Internal: Timeout for messages that should be up for only a short time. shortMessageTimeout: 1000 # Internal: Timeout for status bar message. timeout: null # Public: Creates the package list for the user from the list of available packages. createPackageList: -> new PackageList().setPackages() # Public: Opens the package list. openPackageList: -> atom.workspace.open(PackageList.getPackageListPath()) # Public: Installs any packages that are missing from the `packages.cson` configuration file. sync: -> missing = @getMissingPackages() @installPackages(missing) # Internal: Displays a message in the status bar. # # If `timeout` is specified, the message will automatically be cleared in `timeout` milliseconds. # # message - A {String} containing the message to be displayed. # timeout - An optional {Number} specifying the time in milliseconds until the message will be # cleared. displayMessage: (message, timeout) -> clearTimeout(@timeout) if @timeout? if @message? @message.setText(message) else @message = new StatusMessage(message) @setMessageTimeout(timeout) if timeout? # Internal: Execute APM to install the given package. # # pkg - A {String} containing the name of the package to install. executeApm: (pkg) -> @displayMessage("Installing #{pkg}") command = @apmPath args = ['install', pkg] stdout = (output) -> stderr = (output) -> exit = (exitCode) => if exitCode is 0 if @packagesToInstall.length > 0 @displayMessage("#{pkg} installed!", @shortMessageTimeout) else @displayMessage('Package Sync complete!', @longMessageTimeout) else @displayMessage("An error occurred installing #{pkg}", @longMessageTimeout) @currentInstall = null @installPackage() @currentInstall = new BufferedProcess({command, args, stdout, stderr, exit}) # Internal: Gets the list of packages that are missing. # # Returns an {Array} of names of packages that need to be installed. getMissingPackages: -> list = new PackageList() syncPackages = list.getPackages() availablePackages = atom.packages.getAvailablePackageNames() value for value in syncPackages when value not in availablePackages # Internal: Installs the next package in the list. installPackage: -> # Exit if there is already an installation running or if there are no more # packages to install. return if @currentInstall? or @packagesToInstall.length is 0 @executeApm(@packagesToInstall.shift()) # Internal: Installs each of the packages in the given list. # # packages - An {Array} containing the names of packages to install. installPackages: (packages) -> @packagesToInstall.push(packages...) @installPackage() # Internal: Sets a timeout to remove the status bar message. # # timeout - The {Number} of milliseconds until the message should be removed. setMessageTimeout: (timeout) -> clearTimeout(@timeout) if @timeout? @timeout = setTimeout(=> @message.remove() @message = null , timeout)
true
# # Copyright (c) 2014 by PI:NAME:<NAME>END_PIios. All Rights Reserved. # fs = require 'fs' {BufferedProcess} = require 'atom' PackageList = require './package-list' StatusMessage = require './status-message' # Public: Performs the package synchronization. # # ## Events # # This class has no events. module.exports = class PackageSync # Internal: Path to `apm`. apmPath: atom.packages.getApmPath() # Internal: Process object of the current install. currentInstall: null # Internal: Timeout for messages that should be up longer. longMessageTimeout: 15000 # Internal: Status bar message. message: null # Internal: Packages in the process of being installed. packagesToInstall: [] # Internal: Timeout for messages that should be up for only a short time. shortMessageTimeout: 1000 # Internal: Timeout for status bar message. timeout: null # Public: Creates the package list for the user from the list of available packages. createPackageList: -> new PackageList().setPackages() # Public: Opens the package list. openPackageList: -> atom.workspace.open(PackageList.getPackageListPath()) # Public: Installs any packages that are missing from the `packages.cson` configuration file. sync: -> missing = @getMissingPackages() @installPackages(missing) # Internal: Displays a message in the status bar. # # If `timeout` is specified, the message will automatically be cleared in `timeout` milliseconds. # # message - A {String} containing the message to be displayed. # timeout - An optional {Number} specifying the time in milliseconds until the message will be # cleared. displayMessage: (message, timeout) -> clearTimeout(@timeout) if @timeout? if @message? @message.setText(message) else @message = new StatusMessage(message) @setMessageTimeout(timeout) if timeout? # Internal: Execute APM to install the given package. # # pkg - A {String} containing the name of the package to install. executeApm: (pkg) -> @displayMessage("Installing #{pkg}") command = @apmPath args = ['install', pkg] stdout = (output) -> stderr = (output) -> exit = (exitCode) => if exitCode is 0 if @packagesToInstall.length > 0 @displayMessage("#{pkg} installed!", @shortMessageTimeout) else @displayMessage('Package Sync complete!', @longMessageTimeout) else @displayMessage("An error occurred installing #{pkg}", @longMessageTimeout) @currentInstall = null @installPackage() @currentInstall = new BufferedProcess({command, args, stdout, stderr, exit}) # Internal: Gets the list of packages that are missing. # # Returns an {Array} of names of packages that need to be installed. getMissingPackages: -> list = new PackageList() syncPackages = list.getPackages() availablePackages = atom.packages.getAvailablePackageNames() value for value in syncPackages when value not in availablePackages # Internal: Installs the next package in the list. installPackage: -> # Exit if there is already an installation running or if there are no more # packages to install. return if @currentInstall? or @packagesToInstall.length is 0 @executeApm(@packagesToInstall.shift()) # Internal: Installs each of the packages in the given list. # # packages - An {Array} containing the names of packages to install. installPackages: (packages) -> @packagesToInstall.push(packages...) @installPackage() # Internal: Sets a timeout to remove the status bar message. # # timeout - The {Number} of milliseconds until the message should be removed. setMessageTimeout: (timeout) -> clearTimeout(@timeout) if @timeout? @timeout = setTimeout(=> @message.remove() @message = null , timeout)
[ { "context": "s LocalDomain extends DomainBase\n constructor: (@name, @db, @dbStorage, @queue, @tree, @hist, @uidGener", "end": 281, "score": 0.9833381175994873, "start": 277, "tag": "USERNAME", "value": "name" }, { "context": ")\n\n\n saveHistory: (historyEntry, cb) ->\n key = ...
src/local/domain.coffee
tarruda/archdb
5
{ObjectRef, ObjectType, typeOf} = require('../util') {DomainBase, CursorBase, DomainRow} = require('../domain_base') {HistoryRow, HistoryDomainMixin, HistoryCursorMixin, HistoryEntryType} = require('../history_domain') class LocalDomain extends DomainBase constructor: (@name, @db, @dbStorage, @queue, @tree, @hist, @uidGenerator) -> find: (query) -> new LocalCursor(@dbStorage, @queue, @tree, query) setJob: (key, value, cb) -> old = newValue = null; type = typeOf(value) refCb = (err, ref) => set(ref) set = (ref) => newValue = ref @tree.set(key, ref, setCb) setCb = (err, oldValue) => if err then return cb(err, null) if @hist if oldValue if (oldValue instanceof ObjectRef and not oldValue.equals(newValue)) or oldValue != newValue old = oldValue he = [HistoryEntryType.Update, @id, key, oldValue, newValue] else he = [HistoryEntryType.Insert, @id, key, newValue] if he then @saveHistory(he, histCb) else cb(null, newValue) return cb(null, old) histCb = (err) => if err then return cb(err, null) cb(null, old) switch type # small fixed-length values are stored inline when ObjectType.ObjectRef, ObjectType.Boolean, ObjectType.Number set(value) else @dbStorage.saveIndexData(value, refCb) delJob: (key, cb) -> old = null delCb = (err, oldValue) => if err then return cb(err, null) if @hist if oldValue old = oldValue he = [HistoryEntryType.Delete, @id, key, oldValue] return @saveHistory(he, histCb) cb(null, null) histCb = (err) => if err then return cb(err, null) cb(null, old) @tree.del(key, delCb) saveHistory: (historyEntry, cb) -> key = @uidGenerator.generate() @hist.set(key, historyEntry, cb) class LocalCursor extends CursorBase constructor: (@dbStorage, queue, @tree, query) -> super(queue, query) count: -> @tree.getCount() findRangeAsc: (gte, gt, lte, lt, cb) -> limit = null i = skip = 0 nodeCb = (err, next, node) => if err or not next then return cb(err, null, null, null) i++ key = node.getKey() if gt and gt.compareTo(key) >= 0 then return next() if lt and lt.compareTo(key) <= 0 then return next(true) if lte and lte.compareTo(key) < 0 then return next(true) if limit and i > limit + skip then return next(true) if skip < i then return cb(null, next, key.normalize(), node.getValue()) next() if @query limit = @query.$limit skip = @query.$skip or skip @tree.inOrder(gte or gt, nodeCb) findRangeDesc: (gte, gt, lte, lt, cb) -> limit = null i = skip = 0 nodeCb = (err, next, node) => if err or not next then return cb(err, null, null, null) i++ key = node.getKey() if lt and lt.compareTo(key) <= 0 then return next() if gt and gt.compareTo(key) >= 0 then return next(true) if gte and gte.compareTo(key) > 0 then return next(true) if limit and i > limit + skip then return next(true) if skip < i then return cb(null, next, key.normalize(), node.getValue()) next() if @query limit = @query.$limit skip = @query.$skip or skip @tree.revInOrder(lte or lt, nodeCb) fetchKey: (key, cb) -> @tree.get(key, cb) fetchObj: (ref, cb) -> @dbStorage.getIndexData(ref, cb) fetchValue: (key, val, cb) -> rv = new DomainRow(key, null, null) refCb = (err, obj) => if err then return cb(err, null) rv.value = obj cb(null, rv) if val instanceof ObjectRef rv.ref = val return @fetchObj(val, refCb) refCb(null, val) class LocalHistoryDomain extends LocalDomain constructor: (dbStorage, queue, tree, @master) -> super(null, null, dbStorage, queue, tree, null, null) find: (query) -> new LocalHistoryCursor(@dbStorage, @queue, @tree, query, @master) HistoryDomainMixin.merge(this) class LocalHistoryCursor extends LocalCursor constructor: (dbStorage, queue, tree, query, @master) -> super(dbStorage, queue, tree, query) fetchDomainName: (id, cb) -> @master.get(['names', id], cb) HistoryCursorMixin.merge(this) exports.LocalDomain = LocalDomain exports.LocalCursor = LocalCursor exports.LocalHistoryDomain = LocalHistoryDomain exports.LocalHistoryCursor = LocalHistoryCursor
110949
{ObjectRef, ObjectType, typeOf} = require('../util') {DomainBase, CursorBase, DomainRow} = require('../domain_base') {HistoryRow, HistoryDomainMixin, HistoryCursorMixin, HistoryEntryType} = require('../history_domain') class LocalDomain extends DomainBase constructor: (@name, @db, @dbStorage, @queue, @tree, @hist, @uidGenerator) -> find: (query) -> new LocalCursor(@dbStorage, @queue, @tree, query) setJob: (key, value, cb) -> old = newValue = null; type = typeOf(value) refCb = (err, ref) => set(ref) set = (ref) => newValue = ref @tree.set(key, ref, setCb) setCb = (err, oldValue) => if err then return cb(err, null) if @hist if oldValue if (oldValue instanceof ObjectRef and not oldValue.equals(newValue)) or oldValue != newValue old = oldValue he = [HistoryEntryType.Update, @id, key, oldValue, newValue] else he = [HistoryEntryType.Insert, @id, key, newValue] if he then @saveHistory(he, histCb) else cb(null, newValue) return cb(null, old) histCb = (err) => if err then return cb(err, null) cb(null, old) switch type # small fixed-length values are stored inline when ObjectType.ObjectRef, ObjectType.Boolean, ObjectType.Number set(value) else @dbStorage.saveIndexData(value, refCb) delJob: (key, cb) -> old = null delCb = (err, oldValue) => if err then return cb(err, null) if @hist if oldValue old = oldValue he = [HistoryEntryType.Delete, @id, key, oldValue] return @saveHistory(he, histCb) cb(null, null) histCb = (err) => if err then return cb(err, null) cb(null, old) @tree.del(key, delCb) saveHistory: (historyEntry, cb) -> key = <KEY>() @hist.set(key, historyEntry, cb) class LocalCursor extends CursorBase constructor: (@dbStorage, queue, @tree, query) -> super(queue, query) count: -> @tree.getCount() findRangeAsc: (gte, gt, lte, lt, cb) -> limit = null i = skip = 0 nodeCb = (err, next, node) => if err or not next then return cb(err, null, null, null) i++ key = node.getKey() if gt and gt.compareTo(key) >= 0 then return next() if lt and lt.compareTo(key) <= 0 then return next(true) if lte and lte.compareTo(key) < 0 then return next(true) if limit and i > limit + skip then return next(true) if skip < i then return cb(null, next, key.normalize(), node.getValue()) next() if @query limit = @query.$limit skip = @query.$skip or skip @tree.inOrder(gte or gt, nodeCb) findRangeDesc: (gte, gt, lte, lt, cb) -> limit = null i = skip = 0 nodeCb = (err, next, node) => if err or not next then return cb(err, null, null, null) i++ key = node.getKey() if lt and lt.compareTo(key) <= 0 then return next() if gt and gt.compareTo(key) >= 0 then return next(true) if gte and gte.compareTo(key) > 0 then return next(true) if limit and i > limit + skip then return next(true) if skip < i then return cb(null, next, key.normalize(), node.getValue()) next() if @query limit = @query.$limit skip = @query.$skip or skip @tree.revInOrder(lte or lt, nodeCb) fetchKey: (key, cb) -> @tree.get(key, cb) fetchObj: (ref, cb) -> @dbStorage.getIndexData(ref, cb) fetchValue: (key, val, cb) -> rv = new DomainRow(key, null, null) refCb = (err, obj) => if err then return cb(err, null) rv.value = obj cb(null, rv) if val instanceof ObjectRef rv.ref = val return @fetchObj(val, refCb) refCb(null, val) class LocalHistoryDomain extends LocalDomain constructor: (dbStorage, queue, tree, @master) -> super(null, null, dbStorage, queue, tree, null, null) find: (query) -> new LocalHistoryCursor(@dbStorage, @queue, @tree, query, @master) HistoryDomainMixin.merge(this) class LocalHistoryCursor extends LocalCursor constructor: (dbStorage, queue, tree, query, @master) -> super(dbStorage, queue, tree, query) fetchDomainName: (id, cb) -> @master.get(['names', id], cb) HistoryCursorMixin.merge(this) exports.LocalDomain = LocalDomain exports.LocalCursor = LocalCursor exports.LocalHistoryDomain = LocalHistoryDomain exports.LocalHistoryCursor = LocalHistoryCursor
true
{ObjectRef, ObjectType, typeOf} = require('../util') {DomainBase, CursorBase, DomainRow} = require('../domain_base') {HistoryRow, HistoryDomainMixin, HistoryCursorMixin, HistoryEntryType} = require('../history_domain') class LocalDomain extends DomainBase constructor: (@name, @db, @dbStorage, @queue, @tree, @hist, @uidGenerator) -> find: (query) -> new LocalCursor(@dbStorage, @queue, @tree, query) setJob: (key, value, cb) -> old = newValue = null; type = typeOf(value) refCb = (err, ref) => set(ref) set = (ref) => newValue = ref @tree.set(key, ref, setCb) setCb = (err, oldValue) => if err then return cb(err, null) if @hist if oldValue if (oldValue instanceof ObjectRef and not oldValue.equals(newValue)) or oldValue != newValue old = oldValue he = [HistoryEntryType.Update, @id, key, oldValue, newValue] else he = [HistoryEntryType.Insert, @id, key, newValue] if he then @saveHistory(he, histCb) else cb(null, newValue) return cb(null, old) histCb = (err) => if err then return cb(err, null) cb(null, old) switch type # small fixed-length values are stored inline when ObjectType.ObjectRef, ObjectType.Boolean, ObjectType.Number set(value) else @dbStorage.saveIndexData(value, refCb) delJob: (key, cb) -> old = null delCb = (err, oldValue) => if err then return cb(err, null) if @hist if oldValue old = oldValue he = [HistoryEntryType.Delete, @id, key, oldValue] return @saveHistory(he, histCb) cb(null, null) histCb = (err) => if err then return cb(err, null) cb(null, old) @tree.del(key, delCb) saveHistory: (historyEntry, cb) -> key = PI:KEY:<KEY>END_PI() @hist.set(key, historyEntry, cb) class LocalCursor extends CursorBase constructor: (@dbStorage, queue, @tree, query) -> super(queue, query) count: -> @tree.getCount() findRangeAsc: (gte, gt, lte, lt, cb) -> limit = null i = skip = 0 nodeCb = (err, next, node) => if err or not next then return cb(err, null, null, null) i++ key = node.getKey() if gt and gt.compareTo(key) >= 0 then return next() if lt and lt.compareTo(key) <= 0 then return next(true) if lte and lte.compareTo(key) < 0 then return next(true) if limit and i > limit + skip then return next(true) if skip < i then return cb(null, next, key.normalize(), node.getValue()) next() if @query limit = @query.$limit skip = @query.$skip or skip @tree.inOrder(gte or gt, nodeCb) findRangeDesc: (gte, gt, lte, lt, cb) -> limit = null i = skip = 0 nodeCb = (err, next, node) => if err or not next then return cb(err, null, null, null) i++ key = node.getKey() if lt and lt.compareTo(key) <= 0 then return next() if gt and gt.compareTo(key) >= 0 then return next(true) if gte and gte.compareTo(key) > 0 then return next(true) if limit and i > limit + skip then return next(true) if skip < i then return cb(null, next, key.normalize(), node.getValue()) next() if @query limit = @query.$limit skip = @query.$skip or skip @tree.revInOrder(lte or lt, nodeCb) fetchKey: (key, cb) -> @tree.get(key, cb) fetchObj: (ref, cb) -> @dbStorage.getIndexData(ref, cb) fetchValue: (key, val, cb) -> rv = new DomainRow(key, null, null) refCb = (err, obj) => if err then return cb(err, null) rv.value = obj cb(null, rv) if val instanceof ObjectRef rv.ref = val return @fetchObj(val, refCb) refCb(null, val) class LocalHistoryDomain extends LocalDomain constructor: (dbStorage, queue, tree, @master) -> super(null, null, dbStorage, queue, tree, null, null) find: (query) -> new LocalHistoryCursor(@dbStorage, @queue, @tree, query, @master) HistoryDomainMixin.merge(this) class LocalHistoryCursor extends LocalCursor constructor: (dbStorage, queue, tree, query, @master) -> super(dbStorage, queue, tree, query) fetchDomainName: (id, cb) -> @master.get(['names', id], cb) HistoryCursorMixin.merge(this) exports.LocalDomain = LocalDomain exports.LocalCursor = LocalCursor exports.LocalHistoryDomain = LocalHistoryDomain exports.LocalHistoryCursor = LocalHistoryCursor
[ { "context": ": true\n version: 'v1'\n apiKey: '12'\n dateTimeFormat: 'RFC3339'\n th", "end": 2004, "score": 0.9983437061309814, "start": 2002, "tag": "KEY", "value": "12" } ]
test/unit/index.coffee
iofreddy85/simple-fxtrade
13
require('dotenv').load silent: true _ = require 'lodash' {expect} = require 'chai' td = require 'testdouble' contains = td.matchers.contains fx = {} axios = {} disableMocks = -> td.reset() fx = require '../../index' afterEach -> td.reset() describe '--- Unit Tests ---', -> beforeEach -> axios = td.replace 'axios' fx = require '../../index' describe 'main package', -> describe 'module exports', -> it 'should export correctly', -> expect(fx).to.be.ok it 'should be a function', -> expect(_.isFunction fx).to.be.ok it 'should setup the correct defaults', -> expect(fx.options).to.be.eql apiKey: process.env.OANDA_API_KEY live: false version: 'v3' dateTimeFormat: 'RFC3339' throwHttpErrors: true describe '#fx', -> it 'should allow the caller to temporarily set the http method', -> temp = fx 'post' expect(temp.method).to.be.equal 'POST' expect(temp.options).to.be.eql apiKey: process.env.OANDA_API_KEY live: false version: 'v3' dateTimeFormat: 'RFC3339' throwHttpErrors: true describe '#setAccount', -> it 'should set the accountId', -> expect(fx.options.accountId).to.not.be.ok fx.setAccount '12345' expect(fx.options.accountId).to.be.equal '12345' describe '#setDateTimeFormat', -> it 'should set the date time format', -> expect(fx.options.dateTimeFormat).to.be.equal 'RFC3339' fx.setDateTimeFormat 'UNIX' expect(fx.options.dateTimeFormat).to.be.equal 'UNIX' it 'should throw an error when given an invalid format', -> expect(-> fx.setDateTimeFormat 'INVALIDTHING').to.throw 'invalid date time format' describe '#configure', -> it 'should set the api options', -> temp = fx 'get' options = accountId: 234 live: true version: 'v1' apiKey: '12' dateTimeFormat: 'RFC3339' throwHttpErrors: false temp.configure options expect(temp.options).to.be.eql options describe '#endpoint', -> it 'should return the practice api endpoint when not live', -> expect(fx.endpoint()).to.be.equal 'https://api-fxpractice.oanda.com/v3/' it 'should return the trade api endpoint when live', -> temp = fx 'get' temp.configure live: true expect(temp.endpoint()).to.be.equal 'https://api-fxtrade.oanda.com/v3/' it 'should return the practice stream endpoint when not live', -> expect(fx.endpoint '', 'stream').to.be.equal 'https://stream-fxpractice.oanda.com/v3/' it 'should return the trade api endpoint when live', -> temp = fx 'get' temp.configure live: true expect(temp.endpoint '', 'stream').to.be.equal 'https://stream-fxtrade.oanda.com/v3/' it 'should concatenate the route to the url', -> expect(fx.endpoint 'accounts/123').to.be.equal 'https://api-fxpractice.oanda.com/v3/accounts/123' it 'should throw an error when given an invalid mode', -> expect(-> fx.endpoint 'accounts/123', 'invalid').to.throw 'invalid mode' describe '#request', -> it 'should call request-promise respecting the provided url', -> fx.setAccount '1' await fx.request url: 'https://www.google.com' td.verify axios contains url: 'https://www.google.com' it 'should reject as an error when there is no apiKey set', -> temp = fx 'get' temp.configure apiKey: undefined try temp.request 'accounts' expect.fail() catch {message} expect(message).to.match /Api key is not set/ it 'should reject as an error when validating the accountId', -> temp = fx 'get' temp.configure accountId: undefined try temp.request 'accounts' expect.fail() catch {message} expect(message).to.match /Account id must be set for this request/ it 'should use the endpoint to set the correct api url', -> fx.setAccount '123' fx.request {}, 'accounts' td.verify axios contains url: 'https://api-fxpractice.oanda.com/v3/accounts' it 'should strip body and include properties as query parms', -> fx.setAccount '123' fx.request body: 'This is content', since: '2017-01-01', id: 1234, 'accounts' td.verify axios contains data: 'This is content' params: since: '2017-01-01' responseType: 'json' url: 'https://api-fxpractice.oanda.com/v3/accounts' it 'should always pass the authorization header', -> fx.setAccount '123' fx.request {}, 'accounts' td.verify axios contains headers: Authorization: "Bearer #{process.env.OANDA_API_KEY}" describe '#subscribe', -> # Disabled due to the new way we must subscribe it 'should call request passing the expected options', -> fx.setAccount '123' subscription = fx.subscribe {} td.verify axios contains url: 'https://stream-fxpractice.oanda.com/v3/' headers: Authorization: "Bearer #{process.env.OANDA_API_KEY}" params: {} responseType: 'stream' it 'should throw an error for messed up requests', -> disableMocks() url = 'http://brokenurl.town' fx.setAccount '2' try stream = await fx.subscribe {url} expect.fail() catch err expect(err.message).to.match /ENOTFOUND brokenurl\.town/ it 'should return ok without any errors', -> disableMocks() url = 'https://www.google.com' fx.setAccount '2' expect(await fx.subscribe {url, json: false}).to.be.ok
200598
require('dotenv').load silent: true _ = require 'lodash' {expect} = require 'chai' td = require 'testdouble' contains = td.matchers.contains fx = {} axios = {} disableMocks = -> td.reset() fx = require '../../index' afterEach -> td.reset() describe '--- Unit Tests ---', -> beforeEach -> axios = td.replace 'axios' fx = require '../../index' describe 'main package', -> describe 'module exports', -> it 'should export correctly', -> expect(fx).to.be.ok it 'should be a function', -> expect(_.isFunction fx).to.be.ok it 'should setup the correct defaults', -> expect(fx.options).to.be.eql apiKey: process.env.OANDA_API_KEY live: false version: 'v3' dateTimeFormat: 'RFC3339' throwHttpErrors: true describe '#fx', -> it 'should allow the caller to temporarily set the http method', -> temp = fx 'post' expect(temp.method).to.be.equal 'POST' expect(temp.options).to.be.eql apiKey: process.env.OANDA_API_KEY live: false version: 'v3' dateTimeFormat: 'RFC3339' throwHttpErrors: true describe '#setAccount', -> it 'should set the accountId', -> expect(fx.options.accountId).to.not.be.ok fx.setAccount '12345' expect(fx.options.accountId).to.be.equal '12345' describe '#setDateTimeFormat', -> it 'should set the date time format', -> expect(fx.options.dateTimeFormat).to.be.equal 'RFC3339' fx.setDateTimeFormat 'UNIX' expect(fx.options.dateTimeFormat).to.be.equal 'UNIX' it 'should throw an error when given an invalid format', -> expect(-> fx.setDateTimeFormat 'INVALIDTHING').to.throw 'invalid date time format' describe '#configure', -> it 'should set the api options', -> temp = fx 'get' options = accountId: 234 live: true version: 'v1' apiKey: '<KEY>' dateTimeFormat: 'RFC3339' throwHttpErrors: false temp.configure options expect(temp.options).to.be.eql options describe '#endpoint', -> it 'should return the practice api endpoint when not live', -> expect(fx.endpoint()).to.be.equal 'https://api-fxpractice.oanda.com/v3/' it 'should return the trade api endpoint when live', -> temp = fx 'get' temp.configure live: true expect(temp.endpoint()).to.be.equal 'https://api-fxtrade.oanda.com/v3/' it 'should return the practice stream endpoint when not live', -> expect(fx.endpoint '', 'stream').to.be.equal 'https://stream-fxpractice.oanda.com/v3/' it 'should return the trade api endpoint when live', -> temp = fx 'get' temp.configure live: true expect(temp.endpoint '', 'stream').to.be.equal 'https://stream-fxtrade.oanda.com/v3/' it 'should concatenate the route to the url', -> expect(fx.endpoint 'accounts/123').to.be.equal 'https://api-fxpractice.oanda.com/v3/accounts/123' it 'should throw an error when given an invalid mode', -> expect(-> fx.endpoint 'accounts/123', 'invalid').to.throw 'invalid mode' describe '#request', -> it 'should call request-promise respecting the provided url', -> fx.setAccount '1' await fx.request url: 'https://www.google.com' td.verify axios contains url: 'https://www.google.com' it 'should reject as an error when there is no apiKey set', -> temp = fx 'get' temp.configure apiKey: undefined try temp.request 'accounts' expect.fail() catch {message} expect(message).to.match /Api key is not set/ it 'should reject as an error when validating the accountId', -> temp = fx 'get' temp.configure accountId: undefined try temp.request 'accounts' expect.fail() catch {message} expect(message).to.match /Account id must be set for this request/ it 'should use the endpoint to set the correct api url', -> fx.setAccount '123' fx.request {}, 'accounts' td.verify axios contains url: 'https://api-fxpractice.oanda.com/v3/accounts' it 'should strip body and include properties as query parms', -> fx.setAccount '123' fx.request body: 'This is content', since: '2017-01-01', id: 1234, 'accounts' td.verify axios contains data: 'This is content' params: since: '2017-01-01' responseType: 'json' url: 'https://api-fxpractice.oanda.com/v3/accounts' it 'should always pass the authorization header', -> fx.setAccount '123' fx.request {}, 'accounts' td.verify axios contains headers: Authorization: "Bearer #{process.env.OANDA_API_KEY}" describe '#subscribe', -> # Disabled due to the new way we must subscribe it 'should call request passing the expected options', -> fx.setAccount '123' subscription = fx.subscribe {} td.verify axios contains url: 'https://stream-fxpractice.oanda.com/v3/' headers: Authorization: "Bearer #{process.env.OANDA_API_KEY}" params: {} responseType: 'stream' it 'should throw an error for messed up requests', -> disableMocks() url = 'http://brokenurl.town' fx.setAccount '2' try stream = await fx.subscribe {url} expect.fail() catch err expect(err.message).to.match /ENOTFOUND brokenurl\.town/ it 'should return ok without any errors', -> disableMocks() url = 'https://www.google.com' fx.setAccount '2' expect(await fx.subscribe {url, json: false}).to.be.ok
true
require('dotenv').load silent: true _ = require 'lodash' {expect} = require 'chai' td = require 'testdouble' contains = td.matchers.contains fx = {} axios = {} disableMocks = -> td.reset() fx = require '../../index' afterEach -> td.reset() describe '--- Unit Tests ---', -> beforeEach -> axios = td.replace 'axios' fx = require '../../index' describe 'main package', -> describe 'module exports', -> it 'should export correctly', -> expect(fx).to.be.ok it 'should be a function', -> expect(_.isFunction fx).to.be.ok it 'should setup the correct defaults', -> expect(fx.options).to.be.eql apiKey: process.env.OANDA_API_KEY live: false version: 'v3' dateTimeFormat: 'RFC3339' throwHttpErrors: true describe '#fx', -> it 'should allow the caller to temporarily set the http method', -> temp = fx 'post' expect(temp.method).to.be.equal 'POST' expect(temp.options).to.be.eql apiKey: process.env.OANDA_API_KEY live: false version: 'v3' dateTimeFormat: 'RFC3339' throwHttpErrors: true describe '#setAccount', -> it 'should set the accountId', -> expect(fx.options.accountId).to.not.be.ok fx.setAccount '12345' expect(fx.options.accountId).to.be.equal '12345' describe '#setDateTimeFormat', -> it 'should set the date time format', -> expect(fx.options.dateTimeFormat).to.be.equal 'RFC3339' fx.setDateTimeFormat 'UNIX' expect(fx.options.dateTimeFormat).to.be.equal 'UNIX' it 'should throw an error when given an invalid format', -> expect(-> fx.setDateTimeFormat 'INVALIDTHING').to.throw 'invalid date time format' describe '#configure', -> it 'should set the api options', -> temp = fx 'get' options = accountId: 234 live: true version: 'v1' apiKey: 'PI:KEY:<KEY>END_PI' dateTimeFormat: 'RFC3339' throwHttpErrors: false temp.configure options expect(temp.options).to.be.eql options describe '#endpoint', -> it 'should return the practice api endpoint when not live', -> expect(fx.endpoint()).to.be.equal 'https://api-fxpractice.oanda.com/v3/' it 'should return the trade api endpoint when live', -> temp = fx 'get' temp.configure live: true expect(temp.endpoint()).to.be.equal 'https://api-fxtrade.oanda.com/v3/' it 'should return the practice stream endpoint when not live', -> expect(fx.endpoint '', 'stream').to.be.equal 'https://stream-fxpractice.oanda.com/v3/' it 'should return the trade api endpoint when live', -> temp = fx 'get' temp.configure live: true expect(temp.endpoint '', 'stream').to.be.equal 'https://stream-fxtrade.oanda.com/v3/' it 'should concatenate the route to the url', -> expect(fx.endpoint 'accounts/123').to.be.equal 'https://api-fxpractice.oanda.com/v3/accounts/123' it 'should throw an error when given an invalid mode', -> expect(-> fx.endpoint 'accounts/123', 'invalid').to.throw 'invalid mode' describe '#request', -> it 'should call request-promise respecting the provided url', -> fx.setAccount '1' await fx.request url: 'https://www.google.com' td.verify axios contains url: 'https://www.google.com' it 'should reject as an error when there is no apiKey set', -> temp = fx 'get' temp.configure apiKey: undefined try temp.request 'accounts' expect.fail() catch {message} expect(message).to.match /Api key is not set/ it 'should reject as an error when validating the accountId', -> temp = fx 'get' temp.configure accountId: undefined try temp.request 'accounts' expect.fail() catch {message} expect(message).to.match /Account id must be set for this request/ it 'should use the endpoint to set the correct api url', -> fx.setAccount '123' fx.request {}, 'accounts' td.verify axios contains url: 'https://api-fxpractice.oanda.com/v3/accounts' it 'should strip body and include properties as query parms', -> fx.setAccount '123' fx.request body: 'This is content', since: '2017-01-01', id: 1234, 'accounts' td.verify axios contains data: 'This is content' params: since: '2017-01-01' responseType: 'json' url: 'https://api-fxpractice.oanda.com/v3/accounts' it 'should always pass the authorization header', -> fx.setAccount '123' fx.request {}, 'accounts' td.verify axios contains headers: Authorization: "Bearer #{process.env.OANDA_API_KEY}" describe '#subscribe', -> # Disabled due to the new way we must subscribe it 'should call request passing the expected options', -> fx.setAccount '123' subscription = fx.subscribe {} td.verify axios contains url: 'https://stream-fxpractice.oanda.com/v3/' headers: Authorization: "Bearer #{process.env.OANDA_API_KEY}" params: {} responseType: 'stream' it 'should throw an error for messed up requests', -> disableMocks() url = 'http://brokenurl.town' fx.setAccount '2' try stream = await fx.subscribe {url} expect.fail() catch err expect(err.message).to.match /ENOTFOUND brokenurl\.town/ it 'should return ok without any errors', -> disableMocks() url = 'https://www.google.com' fx.setAccount '2' expect(await fx.subscribe {url, json: false}).to.be.ok
[ { "context": " init data\n initData: (data) ->\n if not data[@name()]\n cdata = {}\n data[@name()] =", "end": 259, "score": 0.9217830896377563, "start": 254, "tag": "USERNAME", "value": "@name" }, { "context": "@name()] = cdata\n else\n cdata = d...
src/commons.coffee
programmfabrik/easydb-library
1
# these common classes + methods are used by the plugins, developed by the vzg: gnd, geonames, gn250, gvk, georef, dante, getty, tna_discovery class CustomDataTypeWithCommons extends CustomDataType # init data initData: (data) -> if not data[@name()] cdata = {} data[@name()] = cdata else cdata = data[@name()] if not cdata.url cdata.url = "" cdata renderFieldAsGroup: -> return false renderRowAsBlock: (data, top_level_data, opts) -> false # returns a map for search tokens, containing name and value strings. getQueryFieldBadge: (data) => if data["#{@name()}:unset"] value = $$("text.column.badge.without") else value = data[@name()] name: @nameLocalized() value: value supportsStandard: -> true supportsFacet: -> true getFacet: (opts) -> opts.field = @ new CustomDataTypeCommonFacet(opts) # provide a sort function to sort your data getSortFunction: -> (a, b) => CUI.util.compareIndex(a[@name()]?.conceptName or 'zzz', b[@name()]?.conceptName or 'zzz') # Enable sort hasRenderForSort: -> return true sortExtraOpts: -> return [ { text: "conceptName" value: "conceptName" } { text: "conceptURI" value: "conceptURI" } ] # returns markup to display in expert search renderSearchInput: (data, opts={}) -> search_token = new SearchToken column: @ data: data fields: opts.fields .getInput().DOM getFieldNamesForSearch: -> @getFieldNames() getFieldNamesForSuggest: -> @getFieldNames() getFieldNames: -> field_names = [ @fullName()+".conceptURI" @fullName()+".conceptName" ] field_names # returns a search filter suitable to the search array part # of the request, the data to be search is in data[key] plus # possible additions, which should be stored in key+":<additional>" getSearchFilter: (data, key=@name()) -> if data[key+":unset"] filter = type: "in" fields: [ @fullName()+".conceptName" ] in: [ null ] filter._unnest = true filter._unset_filter = true return filter filter = super(data, key) if filter return filter if CUI.util.isEmpty(data[key]) return val = data[key] [str, phrase] = Search.getPhrase(val) switch data[key+":type"] when "token", "fulltext", undefined filter = type: "match" mode: data[key+":mode"] fields: @getFieldNamesForSearch() string: str phrase: phrase when "field" filter = type: "in" fields: @getFieldNamesForSearch() in: [ str ] filter ####################################################################### # handle editorinput renderEditorInput: (data, top_level_data, opts) -> name = @name() if not data[name] data[name] = { conceptName : '' conceptURI : '' } @__renderEditorInputPopover(data, data[name], opts) ####################################################################### # buttons, which opens and closes popover+menu __renderEditorInputPopover: (data, cdata, opts={}) -> that = @ layout # build layout for editor layout = new CUI.HorizontalLayout class: 'customPluginEditorLayout' center: class: '' right: content: new CUI.Buttonbar buttons: [ new CUI.Button text: '' icon: new CUI.Icon(class: "fa-ellipsis-v") class: 'pluginDirectSelectEditSearch' # show "dots"-menu on click on 3 vertical dots onClick: (e, dotsButton) => dotsButtonMenu = new CUI.Menu class: "customDataTypeCommonsMenu" element : dotsButton menu_items = [ #search text: $$('custom.data.type.commons.controls.search.label') value: 'search' icon_left: new CUI.Icon(class: "fa-search") onClick: (e2, btn2) -> that.showEditPopover(dotsButton, data, cdata, layout, opts) dotsButtonMenu.hide() ] if typeof that.__getAdditionalTooltipInfo == "function" detailinfo = #detailinfo text: $$('custom.data.type.commons.controls.detailinfo.label') value: 'detail' icon_left: new CUI.Icon(class: "fa-info-circle") disabled: that.isEmpty(data, 0, 0) onClick: (eDetailInfo, btnDetailInfo) -> tooltip = new CUI.Tooltip element: btnDetailInfo placement: 'w' markdown: true show_ms: 1000 hide_ms: 200 content: (tooltip) -> if !that.isEmpty(data, 0, 0) # get jskos-details-data encodedURI = encodeURIComponent(cdata.conceptURI) extendedInfo_xhr = { "xhr" : undefined } that.__getAdditionalTooltipInfo(encodedURI, tooltip, extendedInfo_xhr) # loader, until details are xhred new CUI.Label(icon: "spinner", text: $$('custom.data.type.commons.modal.form.popup.loadingstring')) tooltip.show() # hide tooltip + menu on mouseaction CUI.Events.listen type: ["click", "dblclick", "mouseout"] capture: true node: btnDetailInfo only_once: true call: (ev) => dotsButtonMenu.hide() menu_items.push detailinfo uriCall = # call uri text: $$('custom.data.type.commons.controls.calluri.label') value: 'uri' icon_left: new CUI.Icon(class: "fa-external-link") disabled: that.isEmpty(data, 0, 0) || ! CUI.parseLocation(cdata.conceptURI) onClick: -> window.open cdata.conceptURI, "_blank" dotsButtonMenu.hide() menu_items.push uriCall deleteClear = #delete / clear text: $$('custom.data.type.commons.controls.delete.label') value: 'delete' name: 'deleteValueFromDANTEPlugin' class: 'deleteValueFromDANTEPlugin' icon_left: new CUI.Icon(class: "fa-trash") disabled: that.isEmpty(data, 0, 0) onClick: -> cdata = { conceptName : '' conceptURI : '' } data[that.name()] = cdata that.__updateResult(cdata, layout, opts) dotsButtonMenu.hide() menu_items.push deleteClear itemList = items: menu_items dotsButtonMenu._auto_close_after_click = false dotsButtonMenu.setItemList(itemList) dotsButtonMenu.show() ] # other plugins can trigger layout-rebuild by deletion of data-value CUI.Events.registerEvent type: "custom-deleteDataFromPlugin" bubble: false CUI.Events.listen type: "custom-deleteDataFromPlugin" instance: that node: layout call: => cdata = {} data[that.name()] = cdata opts.deleteDataFromPlugin = true that.__updateResult(cdata, layout, opts) @__updateResult(cdata, layout, opts) layout ####################################################################### # show popover and fill it with the form-elements showEditPopover: (btn, data, cdata, layout, opts) -> that = @ suggest_Menu # init xhr-object to abort running xhrs searchsuggest_xhr = { "xhr" : undefined } # set default value for count of suggestions cdata.countOfSuggestions = 50 cdata_form = new CUI.Form class: 'cdtFormWithPadding' data: cdata fields: that.__getEditorFields(cdata) onDataChanged: (data, elem) => @__updateResult(cdata, layout, opts) @__setEditorFieldStatus(cdata, layout) @__updateSuggestionsMenu(cdata, cdata_form, data.searchbarInput, elem, suggest_Menu, searchsuggest_xhr, layout, opts) .start() # init suggestmenu suggest_Menu = new CUI.Menu element: cdata_form.getFieldsByName("searchbarInput")[0] use_element_width_as_min_width: true class: "customDataTypeCommonsMenu" @popover = new CUI.Popover element: btn placement: "wn" class: "commonPlugin_Popover" pane: # titel of popovers header_left: new CUI.Label(text: $$('custom.data.type.commons.popover.choose.label')) content: cdata_form .show() ######################################################################## # check if field is empty isEmpty: (data, top_level_data, opts={}) -> if opts?.mode == "expert" # check input in expert search if typeof data[@name()] == 'object' return CUI.util.isEmpty(data[@name()]?) else return CUI.util.isEmpty(data[@name()]?.trim()) return not data[@name()]?.conceptName ####################################################################### # is called, when record is being saved by user getSaveData: (data, save_data, opts) -> that = @ if opts.demo_data return { conceptName : 'Example' conceptURI : 'https://example.com' } cdata = data[@name()] or data._template?[@name()] switch @getDataStatus(cdata) when "invalid" if opts.copy save_data[@name()] = null else throw new InvalidSaveDataException() when "empty" save_data[@name()] = null when "ok" # if _fulltext is already set, leave it, else set conceptName conceptFulltext = {} if cdata?._fulltext if cdata._fulltext?.string if cdata._fulltext?.string != '' conceptFulltext.string = cdata._fulltext.string if cdata._fulltext?.l10ntext if cdata._fulltext.l10ntext conceptFulltext.l10ntext = cdata._fulltext.l10ntext if cdata._fulltext?.text if cdata._fulltext.text conceptFulltext.text = cdata._fulltext.text else conceptFulltext.text = cdata.conceptName.trim() # if _standard is already set, leave it conceptStandard = {} if cdata?._standard if cdata._standard?.l10ntext if cdata._standard.l10ntext conceptStandard.l10ntext = cdata._standard.l10ntext else # only set .text, if l10ntext is not set (else easydb-error!) if cdata._standard?.text if cdata._standard?.text != '' conceptStandard.text = cdata._standard.text #else # conceptStandard.text = cdata.conceptName.trim() # (else easydb-error!) # save the frontend-language (display-purposes) frontendLanguages = ez5.loca.getLanguage() frontendLanguages = frontendLanguages.split('-') frontendLanguage = frontendLanguages[0] # save the eventually manual chosen label conceptNameChosenByHand = false if cdata?.conceptNameChosenByHand if cdata.conceptNameChosenByHand == true conceptNameChosenByHand = true # build savedata save_data[@name()] = conceptName: cdata.conceptName.trim() conceptURI: cdata.conceptURI.trim() frontendLanguage: frontendLanguage _fulltext: conceptFulltext _standard: conceptStandard # hierarchical ancestors if cdata?.conceptAncestors if cdata.conceptAncestors.length > 0 save_data[@name()]['conceptAncestors'] = cdata.conceptAncestors if cdata?.conceptNameChosenByHand if cdata.conceptNameChosenByHand == true save_data[@name()]['conceptNameChosenByHand'] = true ####################################################################### # update result in Masterform __updateResult: (cdata, layout, opts) -> that = @ if opts.data opts.data[that.name(opts)] = cdata # if field is not empty if cdata?.conceptURI # die uuid einkürzen.. displayURI = cdata.conceptURI if displayURI.length > 20 displayURI = displayURI.replace('http://', '') displayURI = displayURI.replace('https://', '') if displayURI.length > 30 displayURI = displayURI.replace('uri.gbv.de/terminology/', '…/') info = new CUI.VerticalLayout class: 'ez5-info_commonPlugin' top: content: new CUI.Label text: cdata.conceptName multiline: true bottom: content: new CUI.Button name: "outputButtonHref" appearance: "flat" size: "normal" text: displayURI tooltip: markdown: true placement: 'w' content: (tooltip) -> # get jskos-details-data encodedURI = encodeURIComponent(cdata.conceptURI) extendedInfo_xhr = { "xhr" : undefined } if typeof that.__getAdditionalTooltipInfo == "function" that.__getAdditionalTooltipInfo(encodedURI, tooltip, extendedInfo_xhr) # loader, unteil details are xhred new CUI.Label(icon: "spinner", text: $$('custom.data.type.commons.modal.form.popup.loadingstring')) onClick: (evt,button) => window.open cdata.conceptURI, "_blank" layout.replace(info, 'center') layout.addClass('ez5-linked-object-edit') options = class: 'ez5-linked-object-container' layout.__initPane(options, 'center') # if field is empty, display searchfield if ! cdata?.conceptURI suggest_Menu_directInput inputX = new CUI.Input class: "pluginDirectSelectEditInput" undo_and_changed_support: false name: "directSelectInput" content_size: false onKeyup: (input) => # do suggest request and show suggestions searchstring = input.getValueForInput() if typeof that.__updateSuggestionsMenu == "function" @__updateSuggestionsMenu(cdata, 0, searchstring, input, suggest_Menu_directInput, searchsuggest_xhr, layout, opts) # if not called from poolmanagerplugin if ! opts?.callfrompoolmanager inputX.render() # init suggestmenu suggest_Menu_directInput = new CUI.Menu element : inputX use_element_width_as_min_width: true class: "customDataTypeCommonsMenu" # init xhr-object to abort running xhrs searchsuggest_xhr = { "xhr" : undefined } layout.replace(inputX, 'center') layout.removeClass('ez5-linked-object-edit') options = class: '' layout.__initPane(options, 'center') # if deleted from another plugin, do NOT trigger, because that could lead in an endless loop if ! opts.deleteDataFromPlugin # did data change? that.__setEditorFieldStatus(cdata, layout) ####################################################################### # if something in form is in/valid, set this status to masterform __setEditorFieldStatus: (cdata, element) -> switch @getDataStatus(cdata) when "invalid" element.addClass("cui-input-invalid") else element.removeClass("cui-input-invalid") CUI.Events.trigger node: element type: "editor-changed" CUI.Events.trigger node: element type: "data-changed" @ ####################################################################### # renders details-output of record renderDetailOutput: (data, top_level_data, opts) -> @__renderButtonByData(data[@name()]) ####################################################################### # checks the form and returns status getDataStatus: (cdata) -> if (cdata) if cdata.conceptURI and cdata.conceptName # check url for valididy uriCheck = CUI.parseLocation(cdata.conceptURI) nameCheck = if cdata.conceptName then cdata.conceptName.trim() else undefined if uriCheck and nameCheck return "ok" if cdata.conceptURI.trim() == '' and cdata.conceptName.trim() == '' return "empty" return "invalid" return "empty" ####################################################################### # zeige die gewählten Optionen im Datenmodell unter dem Button an #getCustomDataOptionsInDatamodelInfo: (custom_settings) -> # if Object.keys(custom_settings).length == 0 # ['Ohne Optionen'] class CustomDataTypeCommonFacet extends FieldFacet initOpts: -> super() @addOpts field: mandatory: true check: Field requestFacetWithLimit: (obj) -> limit: @getLimit() field: @_field.fullName()+".conceptName" sort: "count" type: "term" getObjects: (key=@name(), data=@data()) -> data[key]?.terms or [] renderObjectText: (object) -> object.term getObjectPath: (obj) -> [obj.term] name: -> @_field.fullName()+".conceptName" requestSearchFilter: (obj) -> bool: "must" fields: [ @_field.fullName()+".conceptName" ] type: "in" in: [ obj.term ]
143452
# these common classes + methods are used by the plugins, developed by the vzg: gnd, geonames, gn250, gvk, georef, dante, getty, tna_discovery class CustomDataTypeWithCommons extends CustomDataType # init data initData: (data) -> if not data[@name()] cdata = {} data[@name()] = cdata else cdata = data[@name()] if not cdata.url cdata.url = "" cdata renderFieldAsGroup: -> return false renderRowAsBlock: (data, top_level_data, opts) -> false # returns a map for search tokens, containing name and value strings. getQueryFieldBadge: (data) => if data["#{@name()}:unset"] value = $$("text.column.badge.without") else value = data[@name()] name: @nameLocalized() value: value supportsStandard: -> true supportsFacet: -> true getFacet: (opts) -> opts.field = @ new CustomDataTypeCommonFacet(opts) # provide a sort function to sort your data getSortFunction: -> (a, b) => CUI.util.compareIndex(a[@name()]?.conceptName or 'zzz', b[@name()]?.conceptName or 'zzz') # Enable sort hasRenderForSort: -> return true sortExtraOpts: -> return [ { text: "conceptName" value: "conceptName" } { text: "conceptURI" value: "conceptURI" } ] # returns markup to display in expert search renderSearchInput: (data, opts={}) -> search_token = new SearchToken column: @ data: data fields: opts.fields .getInput().DOM getFieldNamesForSearch: -> @getFieldNames() getFieldNamesForSuggest: -> @getFieldNames() getFieldNames: -> field_names = [ @fullName()+".conceptURI" @fullName()+".conceptName" ] field_names # returns a search filter suitable to the search array part # of the request, the data to be search is in data[key] plus # possible additions, which should be stored in key+":<additional>" getSearchFilter: (data, key=@name()) -> if data[key+":unset"] filter = type: "in" fields: [ @fullName()+".conceptName" ] in: [ null ] filter._unnest = true filter._unset_filter = true return filter filter = super(data, key) if filter return filter if CUI.util.isEmpty(data[key]) return val = data[key] [str, phrase] = Search.getPhrase(val) switch data[key+":type"] when "token", "fulltext", undefined filter = type: "match" mode: data[key+":mode"] fields: @getFieldNamesForSearch() string: str phrase: phrase when "field" filter = type: "in" fields: @getFieldNamesForSearch() in: [ str ] filter ####################################################################### # handle editorinput renderEditorInput: (data, top_level_data, opts) -> name = @name() if not data[name] data[name] = { conceptName : '' conceptURI : '' } @__renderEditorInputPopover(data, data[name], opts) ####################################################################### # buttons, which opens and closes popover+menu __renderEditorInputPopover: (data, cdata, opts={}) -> that = @ layout # build layout for editor layout = new CUI.HorizontalLayout class: 'customPluginEditorLayout' center: class: '' right: content: new CUI.Buttonbar buttons: [ new CUI.Button text: '' icon: new CUI.Icon(class: "fa-ellipsis-v") class: 'pluginDirectSelectEditSearch' # show "dots"-menu on click on 3 vertical dots onClick: (e, dotsButton) => dotsButtonMenu = new CUI.Menu class: "customDataTypeCommonsMenu" element : dotsButton menu_items = [ #search text: $$('custom.data.type.commons.controls.search.label') value: 'search' icon_left: new CUI.Icon(class: "fa-search") onClick: (e2, btn2) -> that.showEditPopover(dotsButton, data, cdata, layout, opts) dotsButtonMenu.hide() ] if typeof that.__getAdditionalTooltipInfo == "function" detailinfo = #detailinfo text: $$('custom.data.type.commons.controls.detailinfo.label') value: 'detail' icon_left: new CUI.Icon(class: "fa-info-circle") disabled: that.isEmpty(data, 0, 0) onClick: (eDetailInfo, btnDetailInfo) -> tooltip = new CUI.Tooltip element: btnDetailInfo placement: 'w' markdown: true show_ms: 1000 hide_ms: 200 content: (tooltip) -> if !that.isEmpty(data, 0, 0) # get jskos-details-data encodedURI = encodeURIComponent(cdata.conceptURI) extendedInfo_xhr = { "xhr" : undefined } that.__getAdditionalTooltipInfo(encodedURI, tooltip, extendedInfo_xhr) # loader, until details are xhred new CUI.Label(icon: "spinner", text: $$('custom.data.type.commons.modal.form.popup.loadingstring')) tooltip.show() # hide tooltip + menu on mouseaction CUI.Events.listen type: ["click", "dblclick", "mouseout"] capture: true node: btnDetailInfo only_once: true call: (ev) => dotsButtonMenu.hide() menu_items.push detailinfo uriCall = # call uri text: $$('custom.data.type.commons.controls.calluri.label') value: 'uri' icon_left: new CUI.Icon(class: "fa-external-link") disabled: that.isEmpty(data, 0, 0) || ! CUI.parseLocation(cdata.conceptURI) onClick: -> window.open cdata.conceptURI, "_blank" dotsButtonMenu.hide() menu_items.push uriCall deleteClear = #delete / clear text: $$('custom.data.type.commons.controls.delete.label') value: 'delete' name: 'deleteValueFromDANTEPlugin' class: 'deleteValueFromDANTEPlugin' icon_left: new CUI.Icon(class: "fa-trash") disabled: that.isEmpty(data, 0, 0) onClick: -> cdata = { conceptName : '' conceptURI : '' } data[that.name()] = cdata that.__updateResult(cdata, layout, opts) dotsButtonMenu.hide() menu_items.push deleteClear itemList = items: menu_items dotsButtonMenu._auto_close_after_click = false dotsButtonMenu.setItemList(itemList) dotsButtonMenu.show() ] # other plugins can trigger layout-rebuild by deletion of data-value CUI.Events.registerEvent type: "custom-deleteDataFromPlugin" bubble: false CUI.Events.listen type: "custom-deleteDataFromPlugin" instance: that node: layout call: => cdata = {} data[that.name()] = cdata opts.deleteDataFromPlugin = true that.__updateResult(cdata, layout, opts) @__updateResult(cdata, layout, opts) layout ####################################################################### # show popover and fill it with the form-elements showEditPopover: (btn, data, cdata, layout, opts) -> that = @ suggest_Menu # init xhr-object to abort running xhrs searchsuggest_xhr = { "xhr" : undefined } # set default value for count of suggestions cdata.countOfSuggestions = 50 cdata_form = new CUI.Form class: 'cdtFormWithPadding' data: cdata fields: that.__getEditorFields(cdata) onDataChanged: (data, elem) => @__updateResult(cdata, layout, opts) @__setEditorFieldStatus(cdata, layout) @__updateSuggestionsMenu(cdata, cdata_form, data.searchbarInput, elem, suggest_Menu, searchsuggest_xhr, layout, opts) .start() # init suggestmenu suggest_Menu = new CUI.Menu element: cdata_form.getFieldsByName("searchbarInput")[0] use_element_width_as_min_width: true class: "customDataTypeCommonsMenu" @popover = new CUI.Popover element: btn placement: "wn" class: "commonPlugin_Popover" pane: # titel of popovers header_left: new CUI.Label(text: $$('custom.data.type.commons.popover.choose.label')) content: cdata_form .show() ######################################################################## # check if field is empty isEmpty: (data, top_level_data, opts={}) -> if opts?.mode == "expert" # check input in expert search if typeof data[@name()] == 'object' return CUI.util.isEmpty(data[@name()]?) else return CUI.util.isEmpty(data[@name()]?.trim()) return not data[@name()]?.conceptName ####################################################################### # is called, when record is being saved by user getSaveData: (data, save_data, opts) -> that = @ if opts.demo_data return { conceptName : 'Example' conceptURI : 'https://example.com' } cdata = data[@name()] or data._template?[@name()] switch @getDataStatus(cdata) when "invalid" if opts.copy save_data[@name()] = null else throw new InvalidSaveDataException() when "empty" save_data[@name()] = null when "ok" # if _fulltext is already set, leave it, else set conceptName conceptFulltext = {} if cdata?._fulltext if cdata._fulltext?.string if cdata._fulltext?.string != '' conceptFulltext.string = cdata._fulltext.string if cdata._fulltext?.l10ntext if cdata._fulltext.l10ntext conceptFulltext.l10ntext = cdata._fulltext.l10ntext if cdata._fulltext?.text if cdata._fulltext.text conceptFulltext.text = cdata._fulltext.text else conceptFulltext.text = cdata.conceptName.trim() # if _standard is already set, leave it conceptStandard = {} if cdata?._standard if cdata._standard?.l10ntext if cdata._standard.l10ntext conceptStandard.l10ntext = cdata._standard.l10ntext else # only set .text, if l10ntext is not set (else easydb-error!) if cdata._standard?.text if cdata._standard?.text != '' conceptStandard.text = cdata._standard.text #else # conceptStandard.text = cdata.conceptName.trim() # (else easydb-error!) # save the frontend-language (display-purposes) frontendLanguages = ez5.loca.getLanguage() frontendLanguages = frontendLanguages.split('-') frontendLanguage = frontendLanguages[0] # save the eventually manual chosen label conceptNameChosenByHand = false if cdata?.conceptNameChosenByHand if cdata.conceptNameChosenByHand == true conceptNameChosenByHand = true # build savedata save_data[@name()] = conceptName: cdata.conceptName.trim() conceptURI: cdata.conceptURI.trim() frontendLanguage: frontendLanguage _fulltext: conceptFulltext _standard: conceptStandard # hierarchical ancestors if cdata?.conceptAncestors if cdata.conceptAncestors.length > 0 save_data[@name()]['conceptAncestors'] = cdata.conceptAncestors if cdata?.conceptNameChosenByHand if cdata.conceptNameChosenByHand == true save_data[@name()]['conceptNameChosenByHand'] = true ####################################################################### # update result in Masterform __updateResult: (cdata, layout, opts) -> that = @ if opts.data opts.data[that.name(opts)] = cdata # if field is not empty if cdata?.conceptURI # die uuid einkürzen.. displayURI = cdata.conceptURI if displayURI.length > 20 displayURI = displayURI.replace('http://', '') displayURI = displayURI.replace('https://', '') if displayURI.length > 30 displayURI = displayURI.replace('uri.gbv.de/terminology/', '…/') info = new CUI.VerticalLayout class: 'ez5-info_commonPlugin' top: content: new CUI.Label text: cdata.conceptName multiline: true bottom: content: new CUI.Button name: "outputButtonHref" appearance: "flat" size: "normal" text: displayURI tooltip: markdown: true placement: 'w' content: (tooltip) -> # get jskos-details-data encodedURI = encodeURIComponent(cdata.conceptURI) extendedInfo_xhr = { "xhr" : undefined } if typeof that.__getAdditionalTooltipInfo == "function" that.__getAdditionalTooltipInfo(encodedURI, tooltip, extendedInfo_xhr) # loader, unteil details are xhred new CUI.Label(icon: "spinner", text: $$('custom.data.type.commons.modal.form.popup.loadingstring')) onClick: (evt,button) => window.open cdata.conceptURI, "_blank" layout.replace(info, 'center') layout.addClass('ez5-linked-object-edit') options = class: 'ez5-linked-object-container' layout.__initPane(options, 'center') # if field is empty, display searchfield if ! cdata?.conceptURI suggest_Menu_directInput inputX = new CUI.Input class: "pluginDirectSelectEditInput" undo_and_changed_support: false name: "directSelectInput" content_size: false onKeyup: (input) => # do suggest request and show suggestions searchstring = input.getValueForInput() if typeof that.__updateSuggestionsMenu == "function" @__updateSuggestionsMenu(cdata, 0, searchstring, input, suggest_Menu_directInput, searchsuggest_xhr, layout, opts) # if not called from poolmanagerplugin if ! opts?.callfrompoolmanager inputX.render() # init suggestmenu suggest_Menu_directInput = new CUI.Menu element : inputX use_element_width_as_min_width: true class: "customDataTypeCommonsMenu" # init xhr-object to abort running xhrs searchsuggest_xhr = { "xhr" : undefined } layout.replace(inputX, 'center') layout.removeClass('ez5-linked-object-edit') options = class: '' layout.__initPane(options, 'center') # if deleted from another plugin, do NOT trigger, because that could lead in an endless loop if ! opts.deleteDataFromPlugin # did data change? that.__setEditorFieldStatus(cdata, layout) ####################################################################### # if something in form is in/valid, set this status to masterform __setEditorFieldStatus: (cdata, element) -> switch @getDataStatus(cdata) when "invalid" element.addClass("cui-input-invalid") else element.removeClass("cui-input-invalid") CUI.Events.trigger node: element type: "editor-changed" CUI.Events.trigger node: element type: "data-changed" @ ####################################################################### # renders details-output of record renderDetailOutput: (data, top_level_data, opts) -> @__renderButtonByData(data[@name()]) ####################################################################### # checks the form and returns status getDataStatus: (cdata) -> if (cdata) if cdata.conceptURI and cdata.conceptName # check url for valididy uriCheck = CUI.parseLocation(cdata.conceptURI) nameCheck = if cdata.conceptName then cdata.conceptName.trim() else undefined if uriCheck and nameCheck return "ok" if cdata.conceptURI.trim() == '' and cdata.conceptName.trim() == '' return "empty" return "invalid" return "empty" ####################################################################### # zeige die gewählten Optionen im Datenmodell unter dem Button an #getCustomDataOptionsInDatamodelInfo: (custom_settings) -> # if Object.keys(custom_settings).length == 0 # ['<NAME>'] class CustomDataTypeCommonFacet extends FieldFacet initOpts: -> super() @addOpts field: mandatory: true check: Field requestFacetWithLimit: (obj) -> limit: @getLimit() field: @_field.fullName()+".conceptName" sort: "count" type: "term" getObjects: (key=@name(), data=@data()) -> data[key]?.terms or [] renderObjectText: (object) -> object.term getObjectPath: (obj) -> [obj.term] name: -> @_field.fullName()+".conceptName" requestSearchFilter: (obj) -> bool: "must" fields: [ @_field.fullName()+".conceptName" ] type: "in" in: [ obj.term ]
true
# these common classes + methods are used by the plugins, developed by the vzg: gnd, geonames, gn250, gvk, georef, dante, getty, tna_discovery class CustomDataTypeWithCommons extends CustomDataType # init data initData: (data) -> if not data[@name()] cdata = {} data[@name()] = cdata else cdata = data[@name()] if not cdata.url cdata.url = "" cdata renderFieldAsGroup: -> return false renderRowAsBlock: (data, top_level_data, opts) -> false # returns a map for search tokens, containing name and value strings. getQueryFieldBadge: (data) => if data["#{@name()}:unset"] value = $$("text.column.badge.without") else value = data[@name()] name: @nameLocalized() value: value supportsStandard: -> true supportsFacet: -> true getFacet: (opts) -> opts.field = @ new CustomDataTypeCommonFacet(opts) # provide a sort function to sort your data getSortFunction: -> (a, b) => CUI.util.compareIndex(a[@name()]?.conceptName or 'zzz', b[@name()]?.conceptName or 'zzz') # Enable sort hasRenderForSort: -> return true sortExtraOpts: -> return [ { text: "conceptName" value: "conceptName" } { text: "conceptURI" value: "conceptURI" } ] # returns markup to display in expert search renderSearchInput: (data, opts={}) -> search_token = new SearchToken column: @ data: data fields: opts.fields .getInput().DOM getFieldNamesForSearch: -> @getFieldNames() getFieldNamesForSuggest: -> @getFieldNames() getFieldNames: -> field_names = [ @fullName()+".conceptURI" @fullName()+".conceptName" ] field_names # returns a search filter suitable to the search array part # of the request, the data to be search is in data[key] plus # possible additions, which should be stored in key+":<additional>" getSearchFilter: (data, key=@name()) -> if data[key+":unset"] filter = type: "in" fields: [ @fullName()+".conceptName" ] in: [ null ] filter._unnest = true filter._unset_filter = true return filter filter = super(data, key) if filter return filter if CUI.util.isEmpty(data[key]) return val = data[key] [str, phrase] = Search.getPhrase(val) switch data[key+":type"] when "token", "fulltext", undefined filter = type: "match" mode: data[key+":mode"] fields: @getFieldNamesForSearch() string: str phrase: phrase when "field" filter = type: "in" fields: @getFieldNamesForSearch() in: [ str ] filter ####################################################################### # handle editorinput renderEditorInput: (data, top_level_data, opts) -> name = @name() if not data[name] data[name] = { conceptName : '' conceptURI : '' } @__renderEditorInputPopover(data, data[name], opts) ####################################################################### # buttons, which opens and closes popover+menu __renderEditorInputPopover: (data, cdata, opts={}) -> that = @ layout # build layout for editor layout = new CUI.HorizontalLayout class: 'customPluginEditorLayout' center: class: '' right: content: new CUI.Buttonbar buttons: [ new CUI.Button text: '' icon: new CUI.Icon(class: "fa-ellipsis-v") class: 'pluginDirectSelectEditSearch' # show "dots"-menu on click on 3 vertical dots onClick: (e, dotsButton) => dotsButtonMenu = new CUI.Menu class: "customDataTypeCommonsMenu" element : dotsButton menu_items = [ #search text: $$('custom.data.type.commons.controls.search.label') value: 'search' icon_left: new CUI.Icon(class: "fa-search") onClick: (e2, btn2) -> that.showEditPopover(dotsButton, data, cdata, layout, opts) dotsButtonMenu.hide() ] if typeof that.__getAdditionalTooltipInfo == "function" detailinfo = #detailinfo text: $$('custom.data.type.commons.controls.detailinfo.label') value: 'detail' icon_left: new CUI.Icon(class: "fa-info-circle") disabled: that.isEmpty(data, 0, 0) onClick: (eDetailInfo, btnDetailInfo) -> tooltip = new CUI.Tooltip element: btnDetailInfo placement: 'w' markdown: true show_ms: 1000 hide_ms: 200 content: (tooltip) -> if !that.isEmpty(data, 0, 0) # get jskos-details-data encodedURI = encodeURIComponent(cdata.conceptURI) extendedInfo_xhr = { "xhr" : undefined } that.__getAdditionalTooltipInfo(encodedURI, tooltip, extendedInfo_xhr) # loader, until details are xhred new CUI.Label(icon: "spinner", text: $$('custom.data.type.commons.modal.form.popup.loadingstring')) tooltip.show() # hide tooltip + menu on mouseaction CUI.Events.listen type: ["click", "dblclick", "mouseout"] capture: true node: btnDetailInfo only_once: true call: (ev) => dotsButtonMenu.hide() menu_items.push detailinfo uriCall = # call uri text: $$('custom.data.type.commons.controls.calluri.label') value: 'uri' icon_left: new CUI.Icon(class: "fa-external-link") disabled: that.isEmpty(data, 0, 0) || ! CUI.parseLocation(cdata.conceptURI) onClick: -> window.open cdata.conceptURI, "_blank" dotsButtonMenu.hide() menu_items.push uriCall deleteClear = #delete / clear text: $$('custom.data.type.commons.controls.delete.label') value: 'delete' name: 'deleteValueFromDANTEPlugin' class: 'deleteValueFromDANTEPlugin' icon_left: new CUI.Icon(class: "fa-trash") disabled: that.isEmpty(data, 0, 0) onClick: -> cdata = { conceptName : '' conceptURI : '' } data[that.name()] = cdata that.__updateResult(cdata, layout, opts) dotsButtonMenu.hide() menu_items.push deleteClear itemList = items: menu_items dotsButtonMenu._auto_close_after_click = false dotsButtonMenu.setItemList(itemList) dotsButtonMenu.show() ] # other plugins can trigger layout-rebuild by deletion of data-value CUI.Events.registerEvent type: "custom-deleteDataFromPlugin" bubble: false CUI.Events.listen type: "custom-deleteDataFromPlugin" instance: that node: layout call: => cdata = {} data[that.name()] = cdata opts.deleteDataFromPlugin = true that.__updateResult(cdata, layout, opts) @__updateResult(cdata, layout, opts) layout ####################################################################### # show popover and fill it with the form-elements showEditPopover: (btn, data, cdata, layout, opts) -> that = @ suggest_Menu # init xhr-object to abort running xhrs searchsuggest_xhr = { "xhr" : undefined } # set default value for count of suggestions cdata.countOfSuggestions = 50 cdata_form = new CUI.Form class: 'cdtFormWithPadding' data: cdata fields: that.__getEditorFields(cdata) onDataChanged: (data, elem) => @__updateResult(cdata, layout, opts) @__setEditorFieldStatus(cdata, layout) @__updateSuggestionsMenu(cdata, cdata_form, data.searchbarInput, elem, suggest_Menu, searchsuggest_xhr, layout, opts) .start() # init suggestmenu suggest_Menu = new CUI.Menu element: cdata_form.getFieldsByName("searchbarInput")[0] use_element_width_as_min_width: true class: "customDataTypeCommonsMenu" @popover = new CUI.Popover element: btn placement: "wn" class: "commonPlugin_Popover" pane: # titel of popovers header_left: new CUI.Label(text: $$('custom.data.type.commons.popover.choose.label')) content: cdata_form .show() ######################################################################## # check if field is empty isEmpty: (data, top_level_data, opts={}) -> if opts?.mode == "expert" # check input in expert search if typeof data[@name()] == 'object' return CUI.util.isEmpty(data[@name()]?) else return CUI.util.isEmpty(data[@name()]?.trim()) return not data[@name()]?.conceptName ####################################################################### # is called, when record is being saved by user getSaveData: (data, save_data, opts) -> that = @ if opts.demo_data return { conceptName : 'Example' conceptURI : 'https://example.com' } cdata = data[@name()] or data._template?[@name()] switch @getDataStatus(cdata) when "invalid" if opts.copy save_data[@name()] = null else throw new InvalidSaveDataException() when "empty" save_data[@name()] = null when "ok" # if _fulltext is already set, leave it, else set conceptName conceptFulltext = {} if cdata?._fulltext if cdata._fulltext?.string if cdata._fulltext?.string != '' conceptFulltext.string = cdata._fulltext.string if cdata._fulltext?.l10ntext if cdata._fulltext.l10ntext conceptFulltext.l10ntext = cdata._fulltext.l10ntext if cdata._fulltext?.text if cdata._fulltext.text conceptFulltext.text = cdata._fulltext.text else conceptFulltext.text = cdata.conceptName.trim() # if _standard is already set, leave it conceptStandard = {} if cdata?._standard if cdata._standard?.l10ntext if cdata._standard.l10ntext conceptStandard.l10ntext = cdata._standard.l10ntext else # only set .text, if l10ntext is not set (else easydb-error!) if cdata._standard?.text if cdata._standard?.text != '' conceptStandard.text = cdata._standard.text #else # conceptStandard.text = cdata.conceptName.trim() # (else easydb-error!) # save the frontend-language (display-purposes) frontendLanguages = ez5.loca.getLanguage() frontendLanguages = frontendLanguages.split('-') frontendLanguage = frontendLanguages[0] # save the eventually manual chosen label conceptNameChosenByHand = false if cdata?.conceptNameChosenByHand if cdata.conceptNameChosenByHand == true conceptNameChosenByHand = true # build savedata save_data[@name()] = conceptName: cdata.conceptName.trim() conceptURI: cdata.conceptURI.trim() frontendLanguage: frontendLanguage _fulltext: conceptFulltext _standard: conceptStandard # hierarchical ancestors if cdata?.conceptAncestors if cdata.conceptAncestors.length > 0 save_data[@name()]['conceptAncestors'] = cdata.conceptAncestors if cdata?.conceptNameChosenByHand if cdata.conceptNameChosenByHand == true save_data[@name()]['conceptNameChosenByHand'] = true ####################################################################### # update result in Masterform __updateResult: (cdata, layout, opts) -> that = @ if opts.data opts.data[that.name(opts)] = cdata # if field is not empty if cdata?.conceptURI # die uuid einkürzen.. displayURI = cdata.conceptURI if displayURI.length > 20 displayURI = displayURI.replace('http://', '') displayURI = displayURI.replace('https://', '') if displayURI.length > 30 displayURI = displayURI.replace('uri.gbv.de/terminology/', '…/') info = new CUI.VerticalLayout class: 'ez5-info_commonPlugin' top: content: new CUI.Label text: cdata.conceptName multiline: true bottom: content: new CUI.Button name: "outputButtonHref" appearance: "flat" size: "normal" text: displayURI tooltip: markdown: true placement: 'w' content: (tooltip) -> # get jskos-details-data encodedURI = encodeURIComponent(cdata.conceptURI) extendedInfo_xhr = { "xhr" : undefined } if typeof that.__getAdditionalTooltipInfo == "function" that.__getAdditionalTooltipInfo(encodedURI, tooltip, extendedInfo_xhr) # loader, unteil details are xhred new CUI.Label(icon: "spinner", text: $$('custom.data.type.commons.modal.form.popup.loadingstring')) onClick: (evt,button) => window.open cdata.conceptURI, "_blank" layout.replace(info, 'center') layout.addClass('ez5-linked-object-edit') options = class: 'ez5-linked-object-container' layout.__initPane(options, 'center') # if field is empty, display searchfield if ! cdata?.conceptURI suggest_Menu_directInput inputX = new CUI.Input class: "pluginDirectSelectEditInput" undo_and_changed_support: false name: "directSelectInput" content_size: false onKeyup: (input) => # do suggest request and show suggestions searchstring = input.getValueForInput() if typeof that.__updateSuggestionsMenu == "function" @__updateSuggestionsMenu(cdata, 0, searchstring, input, suggest_Menu_directInput, searchsuggest_xhr, layout, opts) # if not called from poolmanagerplugin if ! opts?.callfrompoolmanager inputX.render() # init suggestmenu suggest_Menu_directInput = new CUI.Menu element : inputX use_element_width_as_min_width: true class: "customDataTypeCommonsMenu" # init xhr-object to abort running xhrs searchsuggest_xhr = { "xhr" : undefined } layout.replace(inputX, 'center') layout.removeClass('ez5-linked-object-edit') options = class: '' layout.__initPane(options, 'center') # if deleted from another plugin, do NOT trigger, because that could lead in an endless loop if ! opts.deleteDataFromPlugin # did data change? that.__setEditorFieldStatus(cdata, layout) ####################################################################### # if something in form is in/valid, set this status to masterform __setEditorFieldStatus: (cdata, element) -> switch @getDataStatus(cdata) when "invalid" element.addClass("cui-input-invalid") else element.removeClass("cui-input-invalid") CUI.Events.trigger node: element type: "editor-changed" CUI.Events.trigger node: element type: "data-changed" @ ####################################################################### # renders details-output of record renderDetailOutput: (data, top_level_data, opts) -> @__renderButtonByData(data[@name()]) ####################################################################### # checks the form and returns status getDataStatus: (cdata) -> if (cdata) if cdata.conceptURI and cdata.conceptName # check url for valididy uriCheck = CUI.parseLocation(cdata.conceptURI) nameCheck = if cdata.conceptName then cdata.conceptName.trim() else undefined if uriCheck and nameCheck return "ok" if cdata.conceptURI.trim() == '' and cdata.conceptName.trim() == '' return "empty" return "invalid" return "empty" ####################################################################### # zeige die gewählten Optionen im Datenmodell unter dem Button an #getCustomDataOptionsInDatamodelInfo: (custom_settings) -> # if Object.keys(custom_settings).length == 0 # ['PI:NAME:<NAME>END_PI'] class CustomDataTypeCommonFacet extends FieldFacet initOpts: -> super() @addOpts field: mandatory: true check: Field requestFacetWithLimit: (obj) -> limit: @getLimit() field: @_field.fullName()+".conceptName" sort: "count" type: "term" getObjects: (key=@name(), data=@data()) -> data[key]?.terms or [] renderObjectText: (object) -> object.term getObjectPath: (obj) -> [obj.term] name: -> @_field.fullName()+".conceptName" requestSearchFilter: (obj) -> bool: "must" fields: [ @_field.fullName()+".conceptName" ] type: "in" in: [ obj.term ]
[ { "context": "e cache of <URLs> (comma seprated)\n#\n# Author:\n# Yuki Koya <buty4649@gmail.com>\n\nclient_secret = process.env", "end": 485, "score": 0.9998583793640137, "start": 476, "tag": "NAME", "value": "Yuki Koya" }, { "context": "URLs> (comma seprated)\n#\n# Author:\n# Yu...
src/akamai-cache-purge.coffee
buty4649/hubot-akamai-cache-purge
3
# Description # A hubot script that provides purge edge content # # Configuration: # HUBOT_AKAMAI_CLIENT_TOKEN # HUBOT_AKAMAI_CLIENT_SECRET # HUBOT_AKAMAI_ACCESS_TOKEN # HUBOT_AKAMAI_HOST # # Commands: # hubot akamai purge cache <URLs> - Invalidate cache of <URLs> (comma seprated) # hubot akamai invalidate cache <URLs> - Invalidate cache of <URLs> (comma seprated) # hubot akamai delete cache <URLs> - Delete cache of <URLs> (comma seprated) # # Author: # Yuki Koya <buty4649@gmail.com> client_secret = process.env.HUBOT_AKAMAI_CLIENT_SECRET host = process.env.HUBOT_AKAMAI_HOST access_token = process.env.HUBOT_AKAMAI_ACCESS_TOKEN client_token = process.env.HUBOT_AKAMAI_CLIENT_TOKEN module.exports = (robot) -> EdgeGrid = require 'edgegrid' robot.respond /akamai (purge|invalidate|delete) cache (https?\S+)/i, (res) -> action = if res.match[1] == 'delete' then 'delete' else 'invalidate' urls = res.match[2].split ',' data = JSON.stringify( objects: urls ) eg = new EdgeGrid(client_token, client_secret, access_token, host) eg.auth( path: "/ccu/v3/#{action}/url/production" method: 'POST' headers: 'Content-Type': 'application/json' body: data ) eg.send (err, response, body) -> try data = JSON.parse body catch error res.send "JSON parse error #{body}" return if response.statusCode != 201 message = "Error(#{response.statusCode}): #{data.title}" else message = "Success: estimated time #{data.estimatedSeconds} sec" res.send message
10208
# Description # A hubot script that provides purge edge content # # Configuration: # HUBOT_AKAMAI_CLIENT_TOKEN # HUBOT_AKAMAI_CLIENT_SECRET # HUBOT_AKAMAI_ACCESS_TOKEN # HUBOT_AKAMAI_HOST # # Commands: # hubot akamai purge cache <URLs> - Invalidate cache of <URLs> (comma seprated) # hubot akamai invalidate cache <URLs> - Invalidate cache of <URLs> (comma seprated) # hubot akamai delete cache <URLs> - Delete cache of <URLs> (comma seprated) # # Author: # <NAME> <<EMAIL>> client_secret = process.env.HUBOT_AKAMAI_CLIENT_SECRET host = process.env.HUBOT_AKAMAI_HOST access_token = process.env.HUBOT_AKAMAI_ACCESS_TOKEN client_token = process.env.HUBOT_AKAMAI_CLIENT_TOKEN module.exports = (robot) -> EdgeGrid = require 'edgegrid' robot.respond /akamai (purge|invalidate|delete) cache (https?\S+)/i, (res) -> action = if res.match[1] == 'delete' then 'delete' else 'invalidate' urls = res.match[2].split ',' data = JSON.stringify( objects: urls ) eg = new EdgeGrid(client_token, client_secret, access_token, host) eg.auth( path: "/ccu/v3/#{action}/url/production" method: 'POST' headers: 'Content-Type': 'application/json' body: data ) eg.send (err, response, body) -> try data = JSON.parse body catch error res.send "JSON parse error #{body}" return if response.statusCode != 201 message = "Error(#{response.statusCode}): #{data.title}" else message = "Success: estimated time #{data.estimatedSeconds} sec" res.send message
true
# Description # A hubot script that provides purge edge content # # Configuration: # HUBOT_AKAMAI_CLIENT_TOKEN # HUBOT_AKAMAI_CLIENT_SECRET # HUBOT_AKAMAI_ACCESS_TOKEN # HUBOT_AKAMAI_HOST # # Commands: # hubot akamai purge cache <URLs> - Invalidate cache of <URLs> (comma seprated) # hubot akamai invalidate cache <URLs> - Invalidate cache of <URLs> (comma seprated) # hubot akamai delete cache <URLs> - Delete cache of <URLs> (comma seprated) # # Author: # PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> client_secret = process.env.HUBOT_AKAMAI_CLIENT_SECRET host = process.env.HUBOT_AKAMAI_HOST access_token = process.env.HUBOT_AKAMAI_ACCESS_TOKEN client_token = process.env.HUBOT_AKAMAI_CLIENT_TOKEN module.exports = (robot) -> EdgeGrid = require 'edgegrid' robot.respond /akamai (purge|invalidate|delete) cache (https?\S+)/i, (res) -> action = if res.match[1] == 'delete' then 'delete' else 'invalidate' urls = res.match[2].split ',' data = JSON.stringify( objects: urls ) eg = new EdgeGrid(client_token, client_secret, access_token, host) eg.auth( path: "/ccu/v3/#{action}/url/production" method: 'POST' headers: 'Content-Type': 'application/json' body: data ) eg.send (err, response, body) -> try data = JSON.parse body catch error res.send "JSON parse error #{body}" return if response.statusCode != 201 message = "Error(#{response.statusCode}): #{data.title}" else message = "Success: estimated time #{data.estimatedSeconds} sec" res.send message
[ { "context": "rd</label>\n <input name=\"password\" type=\"password\"/>\n </li>\n </ul>\n <a id=\"login\" ", "end": 4341, "score": 0.9763132929801941, "start": 4333, "tag": "PASSWORD", "value": "password" } ]
www/coffee/templates/jst.coffee
unepwcmc/BlueCarbonMobile
0
window.JST = {} window.JST['area/edit'] = _.template( """ <div class='ios-head'> <a class='back'>Back</a> <h2><%= area.get('title') %></h2> </div> <a id="new-validation" class="btn btn-large">New Validation</a> <ul id='validation-list'></ul> <% if (uploading) { %> <div id='uploading-validations'> <img src="css/images/timerV2.gif"/> Uploading Validations... </div> <% } else if (validationCount > 0) { %> <a id="upload-validations" class="btn"> <span>Upload Validations</span> <img src="css/images/upload.png"/> </a> <% } %> """ ) window.JST['area/add_polygon'] = _.template( """ <div class='ios-head'> <a class='back'>Area</a> <h2>Add Validation</h3> </div> <div id='draw-polygon-notice'> Draw your polygon by tapping on the map </div> <form id="validation-attributes" onSubmit="return false;"> <input type='hidden' name='area_id' value="<%= area.get('id') %>"/> <input type='hidden' name='recorded_at' value="<%= date %>"/> <ul class="fields"> <li> <label>Habitat</label> <select name="habitat"> <option value="">Select a habitat layer</option> <option value="mangrove">Mangrove</option> <option value="seagrass">Seagrass</option> <option value="saltmarsh">Salt Marsh</option> <option value="sabkha">Sabkha</option> <option value="algal_mat">Algal Mat</option> <option value="other">Other</option> </select> </li> <li> <label>Validation Type</label> <select name="action"> <option value="">Select Validation Type</option> <option value="add">Add</option> <option value="delete">Delete</option> </select> </li> <div id='validation-details'> <li class="conditional seagrass mangrove saltmarsh"> <label>Density</label> <select name="density"> <option value="">Unknown</option> <option value="1">Sparse (<20% cover)</option> <option value="2">Moderate (20-50% cover)</option> <option value="3">Dense (50-80% cover)</option> <option value="4">Very dense (>80% cover)</option> </select> </li> <li class="conditional mangrove"> <label>Condition</label> <select name="condition"> <option value="1">Undisturbed / Intact</option> <option value="2">Degraded</option> <option value="3">Restored / Rehabilitating</option> <option value="4">Afforested/ Created</option> <option value="5">Cleared</option> </select> </li> <li class="conditional mangrove"> <label>Age</label> <select name="age"> <option value="">Unknown</option> <option value="1">Natural Mangrove</option> <option value="2">2-10 yrs old</option> <option value="3">10-25 yrs old</option> <option value="4">25-50 yrs old</option> </select> </li> <li class="conditional seagrass"> <label>Species</label> <select name="species"> <option value="">Unknown</option> <option value="Halodule uninervis">Halodule uninervis</option> <option value="Halophila ovalis">Halophila ovalis</option> <option value="Halophila stipulacea">Halophila stipulacea</option> <option value="Mixed species">Mixed species</option> </select> </li> <li> <label>Notes</label> <textarea name="notes"></textarea> </li> </div> </ul> <a id="create-analysis" class="btn btn-large">Save</a> </form> """ ) window.JST['area/login'] = _.template( """ <h3>Please sign in</h3> <div class='error'></div> <form id="login-form" onSubmit="return false;"> <ul class="fields"> <li> <label>Email</label> <input name="email"/> </li> <li> <label>Password</label> <input name="password" type="password"/> </li> </ul> <a id="login" class='btn'>Sign In</a> <img src="css/images/timer.gif" class="loading-spinner" /> </form> """ ) window.JST['area/area_index'] = _.template( """ <div class='ios-head'> <h2>Field Sites</h2> </div> <div id="sync-info"> <span id="sync-status"></span> <a class="sync-areas btn btn-small"> <img src="css/images/sync.png"/> Sync </a> </div> <ul id="area-list"> </ul> """ ) window.JST['area/area'] = _.template( """ <div class='area-attributes'> <h3><%= area.get('title') %></h3> <p> <% var downloadState = area.downloadState(); if (downloadState === 'out of date') { %> Habitat data is out of date <% } else if (downloadState === 'no data') { %> Habitat data not yet downloaded <% } else { %> Data downloaded at: <%= area.lastDownloaded() %> <% } %> </p> </div> <% if (false || downloadState === 'ready') { %> <div class="area-actions start-trip"> <img src="css/images/arrow_forward.png"/> <div>START TRIP</div> </div> <% } else if (downloadState === 'out of date' || downloadState === 'no data') { %> <div class="area-actions download-data"> <img src="css/images/download_icon.png"/> <div>DOWNLOAD</div> </div> <% } else if (downloadState === 'data generating') { %> <div class='area-actions data-generating'> <img src="css/images/timer.gif"/> <div>GENERATING</div> </div> <% } else if (downloadState === 'downloading') { %> <div class='area-actions data-downloading'> <img src="css/images/timer.gif"/> <div>DOWNLOADING</div> </div> <% } %> """ ) window.JST['area/validation'] = _.template( """ <span class="validation-title"> <%= validation.name() %> </span> <img class='delete-validation' src="css/images/trash_can.png"/> <table class="validation-details"> <tr> <th>Habitat</th> <td><%= humanAttributes.habitat %></td> </tr> <tr> <th>Action</th> <td><%= humanAttributes.action %></td> </tr> <% if (typeof humanAttributes.density !== 'undefined') {%> <tr> <th>Density</th> <td><%= humanAttributes.density %></td> </tr> <% } %> <% if (typeof humanAttributes.condition !== 'undefined') {%> <tr> <th>Condition</th> <td><%= humanAttributes.condition %></td> </tr> <% } %> <% if (typeof humanAttributes.age !== 'undefined') {%> <tr> <th>Age</th> <td><%= humanAttributes.age %></td> </tr> <% } %> <% if (typeof humanAttributes.species !== 'undefined') {%> <tr> <th>Species</th> <td><%= humanAttributes.species %></td> </tr> <% } %> <% if (typeof humanAttributes.notes !== 'undefined') {%> <tr> <th>Notes</th> <td><%= humanAttributes.notes %></td> </tr> <% } %> </table> """ )
157517
window.JST = {} window.JST['area/edit'] = _.template( """ <div class='ios-head'> <a class='back'>Back</a> <h2><%= area.get('title') %></h2> </div> <a id="new-validation" class="btn btn-large">New Validation</a> <ul id='validation-list'></ul> <% if (uploading) { %> <div id='uploading-validations'> <img src="css/images/timerV2.gif"/> Uploading Validations... </div> <% } else if (validationCount > 0) { %> <a id="upload-validations" class="btn"> <span>Upload Validations</span> <img src="css/images/upload.png"/> </a> <% } %> """ ) window.JST['area/add_polygon'] = _.template( """ <div class='ios-head'> <a class='back'>Area</a> <h2>Add Validation</h3> </div> <div id='draw-polygon-notice'> Draw your polygon by tapping on the map </div> <form id="validation-attributes" onSubmit="return false;"> <input type='hidden' name='area_id' value="<%= area.get('id') %>"/> <input type='hidden' name='recorded_at' value="<%= date %>"/> <ul class="fields"> <li> <label>Habitat</label> <select name="habitat"> <option value="">Select a habitat layer</option> <option value="mangrove">Mangrove</option> <option value="seagrass">Seagrass</option> <option value="saltmarsh">Salt Marsh</option> <option value="sabkha">Sabkha</option> <option value="algal_mat">Algal Mat</option> <option value="other">Other</option> </select> </li> <li> <label>Validation Type</label> <select name="action"> <option value="">Select Validation Type</option> <option value="add">Add</option> <option value="delete">Delete</option> </select> </li> <div id='validation-details'> <li class="conditional seagrass mangrove saltmarsh"> <label>Density</label> <select name="density"> <option value="">Unknown</option> <option value="1">Sparse (<20% cover)</option> <option value="2">Moderate (20-50% cover)</option> <option value="3">Dense (50-80% cover)</option> <option value="4">Very dense (>80% cover)</option> </select> </li> <li class="conditional mangrove"> <label>Condition</label> <select name="condition"> <option value="1">Undisturbed / Intact</option> <option value="2">Degraded</option> <option value="3">Restored / Rehabilitating</option> <option value="4">Afforested/ Created</option> <option value="5">Cleared</option> </select> </li> <li class="conditional mangrove"> <label>Age</label> <select name="age"> <option value="">Unknown</option> <option value="1">Natural Mangrove</option> <option value="2">2-10 yrs old</option> <option value="3">10-25 yrs old</option> <option value="4">25-50 yrs old</option> </select> </li> <li class="conditional seagrass"> <label>Species</label> <select name="species"> <option value="">Unknown</option> <option value="Halodule uninervis">Halodule uninervis</option> <option value="Halophila ovalis">Halophila ovalis</option> <option value="Halophila stipulacea">Halophila stipulacea</option> <option value="Mixed species">Mixed species</option> </select> </li> <li> <label>Notes</label> <textarea name="notes"></textarea> </li> </div> </ul> <a id="create-analysis" class="btn btn-large">Save</a> </form> """ ) window.JST['area/login'] = _.template( """ <h3>Please sign in</h3> <div class='error'></div> <form id="login-form" onSubmit="return false;"> <ul class="fields"> <li> <label>Email</label> <input name="email"/> </li> <li> <label>Password</label> <input name="password" type="<PASSWORD>"/> </li> </ul> <a id="login" class='btn'>Sign In</a> <img src="css/images/timer.gif" class="loading-spinner" /> </form> """ ) window.JST['area/area_index'] = _.template( """ <div class='ios-head'> <h2>Field Sites</h2> </div> <div id="sync-info"> <span id="sync-status"></span> <a class="sync-areas btn btn-small"> <img src="css/images/sync.png"/> Sync </a> </div> <ul id="area-list"> </ul> """ ) window.JST['area/area'] = _.template( """ <div class='area-attributes'> <h3><%= area.get('title') %></h3> <p> <% var downloadState = area.downloadState(); if (downloadState === 'out of date') { %> Habitat data is out of date <% } else if (downloadState === 'no data') { %> Habitat data not yet downloaded <% } else { %> Data downloaded at: <%= area.lastDownloaded() %> <% } %> </p> </div> <% if (false || downloadState === 'ready') { %> <div class="area-actions start-trip"> <img src="css/images/arrow_forward.png"/> <div>START TRIP</div> </div> <% } else if (downloadState === 'out of date' || downloadState === 'no data') { %> <div class="area-actions download-data"> <img src="css/images/download_icon.png"/> <div>DOWNLOAD</div> </div> <% } else if (downloadState === 'data generating') { %> <div class='area-actions data-generating'> <img src="css/images/timer.gif"/> <div>GENERATING</div> </div> <% } else if (downloadState === 'downloading') { %> <div class='area-actions data-downloading'> <img src="css/images/timer.gif"/> <div>DOWNLOADING</div> </div> <% } %> """ ) window.JST['area/validation'] = _.template( """ <span class="validation-title"> <%= validation.name() %> </span> <img class='delete-validation' src="css/images/trash_can.png"/> <table class="validation-details"> <tr> <th>Habitat</th> <td><%= humanAttributes.habitat %></td> </tr> <tr> <th>Action</th> <td><%= humanAttributes.action %></td> </tr> <% if (typeof humanAttributes.density !== 'undefined') {%> <tr> <th>Density</th> <td><%= humanAttributes.density %></td> </tr> <% } %> <% if (typeof humanAttributes.condition !== 'undefined') {%> <tr> <th>Condition</th> <td><%= humanAttributes.condition %></td> </tr> <% } %> <% if (typeof humanAttributes.age !== 'undefined') {%> <tr> <th>Age</th> <td><%= humanAttributes.age %></td> </tr> <% } %> <% if (typeof humanAttributes.species !== 'undefined') {%> <tr> <th>Species</th> <td><%= humanAttributes.species %></td> </tr> <% } %> <% if (typeof humanAttributes.notes !== 'undefined') {%> <tr> <th>Notes</th> <td><%= humanAttributes.notes %></td> </tr> <% } %> </table> """ )
true
window.JST = {} window.JST['area/edit'] = _.template( """ <div class='ios-head'> <a class='back'>Back</a> <h2><%= area.get('title') %></h2> </div> <a id="new-validation" class="btn btn-large">New Validation</a> <ul id='validation-list'></ul> <% if (uploading) { %> <div id='uploading-validations'> <img src="css/images/timerV2.gif"/> Uploading Validations... </div> <% } else if (validationCount > 0) { %> <a id="upload-validations" class="btn"> <span>Upload Validations</span> <img src="css/images/upload.png"/> </a> <% } %> """ ) window.JST['area/add_polygon'] = _.template( """ <div class='ios-head'> <a class='back'>Area</a> <h2>Add Validation</h3> </div> <div id='draw-polygon-notice'> Draw your polygon by tapping on the map </div> <form id="validation-attributes" onSubmit="return false;"> <input type='hidden' name='area_id' value="<%= area.get('id') %>"/> <input type='hidden' name='recorded_at' value="<%= date %>"/> <ul class="fields"> <li> <label>Habitat</label> <select name="habitat"> <option value="">Select a habitat layer</option> <option value="mangrove">Mangrove</option> <option value="seagrass">Seagrass</option> <option value="saltmarsh">Salt Marsh</option> <option value="sabkha">Sabkha</option> <option value="algal_mat">Algal Mat</option> <option value="other">Other</option> </select> </li> <li> <label>Validation Type</label> <select name="action"> <option value="">Select Validation Type</option> <option value="add">Add</option> <option value="delete">Delete</option> </select> </li> <div id='validation-details'> <li class="conditional seagrass mangrove saltmarsh"> <label>Density</label> <select name="density"> <option value="">Unknown</option> <option value="1">Sparse (<20% cover)</option> <option value="2">Moderate (20-50% cover)</option> <option value="3">Dense (50-80% cover)</option> <option value="4">Very dense (>80% cover)</option> </select> </li> <li class="conditional mangrove"> <label>Condition</label> <select name="condition"> <option value="1">Undisturbed / Intact</option> <option value="2">Degraded</option> <option value="3">Restored / Rehabilitating</option> <option value="4">Afforested/ Created</option> <option value="5">Cleared</option> </select> </li> <li class="conditional mangrove"> <label>Age</label> <select name="age"> <option value="">Unknown</option> <option value="1">Natural Mangrove</option> <option value="2">2-10 yrs old</option> <option value="3">10-25 yrs old</option> <option value="4">25-50 yrs old</option> </select> </li> <li class="conditional seagrass"> <label>Species</label> <select name="species"> <option value="">Unknown</option> <option value="Halodule uninervis">Halodule uninervis</option> <option value="Halophila ovalis">Halophila ovalis</option> <option value="Halophila stipulacea">Halophila stipulacea</option> <option value="Mixed species">Mixed species</option> </select> </li> <li> <label>Notes</label> <textarea name="notes"></textarea> </li> </div> </ul> <a id="create-analysis" class="btn btn-large">Save</a> </form> """ ) window.JST['area/login'] = _.template( """ <h3>Please sign in</h3> <div class='error'></div> <form id="login-form" onSubmit="return false;"> <ul class="fields"> <li> <label>Email</label> <input name="email"/> </li> <li> <label>Password</label> <input name="password" type="PI:PASSWORD:<PASSWORD>END_PI"/> </li> </ul> <a id="login" class='btn'>Sign In</a> <img src="css/images/timer.gif" class="loading-spinner" /> </form> """ ) window.JST['area/area_index'] = _.template( """ <div class='ios-head'> <h2>Field Sites</h2> </div> <div id="sync-info"> <span id="sync-status"></span> <a class="sync-areas btn btn-small"> <img src="css/images/sync.png"/> Sync </a> </div> <ul id="area-list"> </ul> """ ) window.JST['area/area'] = _.template( """ <div class='area-attributes'> <h3><%= area.get('title') %></h3> <p> <% var downloadState = area.downloadState(); if (downloadState === 'out of date') { %> Habitat data is out of date <% } else if (downloadState === 'no data') { %> Habitat data not yet downloaded <% } else { %> Data downloaded at: <%= area.lastDownloaded() %> <% } %> </p> </div> <% if (false || downloadState === 'ready') { %> <div class="area-actions start-trip"> <img src="css/images/arrow_forward.png"/> <div>START TRIP</div> </div> <% } else if (downloadState === 'out of date' || downloadState === 'no data') { %> <div class="area-actions download-data"> <img src="css/images/download_icon.png"/> <div>DOWNLOAD</div> </div> <% } else if (downloadState === 'data generating') { %> <div class='area-actions data-generating'> <img src="css/images/timer.gif"/> <div>GENERATING</div> </div> <% } else if (downloadState === 'downloading') { %> <div class='area-actions data-downloading'> <img src="css/images/timer.gif"/> <div>DOWNLOADING</div> </div> <% } %> """ ) window.JST['area/validation'] = _.template( """ <span class="validation-title"> <%= validation.name() %> </span> <img class='delete-validation' src="css/images/trash_can.png"/> <table class="validation-details"> <tr> <th>Habitat</th> <td><%= humanAttributes.habitat %></td> </tr> <tr> <th>Action</th> <td><%= humanAttributes.action %></td> </tr> <% if (typeof humanAttributes.density !== 'undefined') {%> <tr> <th>Density</th> <td><%= humanAttributes.density %></td> </tr> <% } %> <% if (typeof humanAttributes.condition !== 'undefined') {%> <tr> <th>Condition</th> <td><%= humanAttributes.condition %></td> </tr> <% } %> <% if (typeof humanAttributes.age !== 'undefined') {%> <tr> <th>Age</th> <td><%= humanAttributes.age %></td> </tr> <% } %> <% if (typeof humanAttributes.species !== 'undefined') {%> <tr> <th>Species</th> <td><%= humanAttributes.species %></td> </tr> <% } %> <% if (typeof humanAttributes.notes !== 'undefined') {%> <tr> <th>Notes</th> <td><%= humanAttributes.notes %></td> </tr> <% } %> </table> """ )
[ { "context": "[operation, character.id.name, character.id.number].join('|')\n\n add_applied_op: (applied_ops, operation, ", "end": 1870, "score": 0.6710720062255859, "start": 1866, "tag": "KEY", "value": "join" } ]
src/public/javascripts/lib/utils.coffee
dwetterau/group-edit
1
define ['lib/constants', 'lib/woot'], (constants, woot) -> get_cursor: (element) -> if element.selectionStart return element.selectionStart else if document.selection element.focus() r = document.selection.createRange() if r == null return 0 re = element.createTextRange() rc = re.duplicate() re.moveToBookmark r.getBookmark() rc.setEndPoint 'EndToStart', re return rc.text.length return 0 set_cursor: (element, index) -> if element.createTextRange range = element.createTextRange() range.move 'character', index range.select() else if element.selectionStart? element.focus() element.setSelectionRange index, index else element.focus() get_cursor_state: (element, string) -> cursor_index = this.get_cursor element after_cursor_character = woot.ith_visible string, cursor_index - 1 before_cursor_character = woot.ith_visible string, cursor_index if not after_cursor_character after_cursor_character = string[0] if not before_cursor_character before_cursor_character = string[string.length - 1] cursor_state = character: id: name: '' number: 2 # This is 2 because begin and end character are 0 and 1 visible: false value: '' before_id: before_cursor_character.id after_id: after_cursor_character.id return cursor_state set_cursor_state: (element, string, cursor_state) -> string_index = woot.determine_insert_position( string, cursor_state.character, cursor_state.before_id, cursor_state.after_id) new_index = woot.string_index_to_ith string, string_index this.set_cursor element, new_index + 1 get_op_key: (operation, character) -> return [operation, character.id.name, character.id.number].join('|') add_applied_op: (applied_ops, operation, character) -> key = this.get_op_key operation, character applied_ops[key] = true check_applied_op: (applied_ops, operation, character) -> key = this.get_op_key operation, character return applied_ops[key] send_op: (events_ref, operation, character) -> events_ref.push operation: operation character: character is_bulk: false send_bulk_op: (events_ref, operation, character_list) -> events_ref.push operation: operation character_list: character_list is_bulk: true process_op: (operation_list, string, applied_ops) -> # If no operations to process, return if not operation_list.length return false # Try to execute the operation operation_object = operation_list.pop() result = woot.execute_operation( operation_object.operation, operation_object.character, string) if not result # If we failed to apply the operation, add it back to the front of the list operation_list.unshift operation_object return false else this.add_applied_op applied_ops, operation_object.operation, operation_object.character return true process_bulk_insert: (text, start_index, woot_state) -> insert_characters = [] for c, index in text.split '' woot_character = woot.generate_insert( start_index + index, c, woot_state.participant_name, woot_state.sequence_number, woot_state.string ) this.execute_operation( constants.INSERT_OPERATION, woot_character, woot_state ) # We unshift here so that they get pushed on in reverse and applied # in the correct order (since they are applied through pops) insert_characters.unshift woot_character this.send_bulk_op woot_state.events_ref, constants.INSERT_OPERATION, insert_characters process_bulk_delete: (text, start_index, woot_state) -> delete_characters = [] for c, index in text.split '' delete_characters.push woot.generate_delete start_index + index, woot_state.string for character in delete_characters this.execute_operation constants.DELETE_OPERATION, character, woot_state this.send_bulk_op woot_state.events_ref, constants.DELETE_OPERATION, delete_characters process_diff: (diff_array, woot_state) -> index = 0 for diff_subarray in diff_array type = diff_subarray[0] text = diff_subarray[1] if type == 1 this.process_bulk_insert text, index, woot_state else if type == -1 this.process_bulk_delete text, index, woot_state index -= text.length index += text.length execute_operation: (operation, woot_character, woot_state) -> if operation == constants.DELETE_OPERATION woot.integrate_delete woot_state.string, woot_character else if operation == constants.INSERT_OPERATION woot.integrate_insert woot_state.string, woot_character else throw Error("Unknown operation") this.add_applied_op( woot_state.applied_ops, operation, woot_character) woot_state.sequence_number += 1
220370
define ['lib/constants', 'lib/woot'], (constants, woot) -> get_cursor: (element) -> if element.selectionStart return element.selectionStart else if document.selection element.focus() r = document.selection.createRange() if r == null return 0 re = element.createTextRange() rc = re.duplicate() re.moveToBookmark r.getBookmark() rc.setEndPoint 'EndToStart', re return rc.text.length return 0 set_cursor: (element, index) -> if element.createTextRange range = element.createTextRange() range.move 'character', index range.select() else if element.selectionStart? element.focus() element.setSelectionRange index, index else element.focus() get_cursor_state: (element, string) -> cursor_index = this.get_cursor element after_cursor_character = woot.ith_visible string, cursor_index - 1 before_cursor_character = woot.ith_visible string, cursor_index if not after_cursor_character after_cursor_character = string[0] if not before_cursor_character before_cursor_character = string[string.length - 1] cursor_state = character: id: name: '' number: 2 # This is 2 because begin and end character are 0 and 1 visible: false value: '' before_id: before_cursor_character.id after_id: after_cursor_character.id return cursor_state set_cursor_state: (element, string, cursor_state) -> string_index = woot.determine_insert_position( string, cursor_state.character, cursor_state.before_id, cursor_state.after_id) new_index = woot.string_index_to_ith string, string_index this.set_cursor element, new_index + 1 get_op_key: (operation, character) -> return [operation, character.id.name, character.id.number].<KEY>('|') add_applied_op: (applied_ops, operation, character) -> key = this.get_op_key operation, character applied_ops[key] = true check_applied_op: (applied_ops, operation, character) -> key = this.get_op_key operation, character return applied_ops[key] send_op: (events_ref, operation, character) -> events_ref.push operation: operation character: character is_bulk: false send_bulk_op: (events_ref, operation, character_list) -> events_ref.push operation: operation character_list: character_list is_bulk: true process_op: (operation_list, string, applied_ops) -> # If no operations to process, return if not operation_list.length return false # Try to execute the operation operation_object = operation_list.pop() result = woot.execute_operation( operation_object.operation, operation_object.character, string) if not result # If we failed to apply the operation, add it back to the front of the list operation_list.unshift operation_object return false else this.add_applied_op applied_ops, operation_object.operation, operation_object.character return true process_bulk_insert: (text, start_index, woot_state) -> insert_characters = [] for c, index in text.split '' woot_character = woot.generate_insert( start_index + index, c, woot_state.participant_name, woot_state.sequence_number, woot_state.string ) this.execute_operation( constants.INSERT_OPERATION, woot_character, woot_state ) # We unshift here so that they get pushed on in reverse and applied # in the correct order (since they are applied through pops) insert_characters.unshift woot_character this.send_bulk_op woot_state.events_ref, constants.INSERT_OPERATION, insert_characters process_bulk_delete: (text, start_index, woot_state) -> delete_characters = [] for c, index in text.split '' delete_characters.push woot.generate_delete start_index + index, woot_state.string for character in delete_characters this.execute_operation constants.DELETE_OPERATION, character, woot_state this.send_bulk_op woot_state.events_ref, constants.DELETE_OPERATION, delete_characters process_diff: (diff_array, woot_state) -> index = 0 for diff_subarray in diff_array type = diff_subarray[0] text = diff_subarray[1] if type == 1 this.process_bulk_insert text, index, woot_state else if type == -1 this.process_bulk_delete text, index, woot_state index -= text.length index += text.length execute_operation: (operation, woot_character, woot_state) -> if operation == constants.DELETE_OPERATION woot.integrate_delete woot_state.string, woot_character else if operation == constants.INSERT_OPERATION woot.integrate_insert woot_state.string, woot_character else throw Error("Unknown operation") this.add_applied_op( woot_state.applied_ops, operation, woot_character) woot_state.sequence_number += 1
true
define ['lib/constants', 'lib/woot'], (constants, woot) -> get_cursor: (element) -> if element.selectionStart return element.selectionStart else if document.selection element.focus() r = document.selection.createRange() if r == null return 0 re = element.createTextRange() rc = re.duplicate() re.moveToBookmark r.getBookmark() rc.setEndPoint 'EndToStart', re return rc.text.length return 0 set_cursor: (element, index) -> if element.createTextRange range = element.createTextRange() range.move 'character', index range.select() else if element.selectionStart? element.focus() element.setSelectionRange index, index else element.focus() get_cursor_state: (element, string) -> cursor_index = this.get_cursor element after_cursor_character = woot.ith_visible string, cursor_index - 1 before_cursor_character = woot.ith_visible string, cursor_index if not after_cursor_character after_cursor_character = string[0] if not before_cursor_character before_cursor_character = string[string.length - 1] cursor_state = character: id: name: '' number: 2 # This is 2 because begin and end character are 0 and 1 visible: false value: '' before_id: before_cursor_character.id after_id: after_cursor_character.id return cursor_state set_cursor_state: (element, string, cursor_state) -> string_index = woot.determine_insert_position( string, cursor_state.character, cursor_state.before_id, cursor_state.after_id) new_index = woot.string_index_to_ith string, string_index this.set_cursor element, new_index + 1 get_op_key: (operation, character) -> return [operation, character.id.name, character.id.number].PI:KEY:<KEY>END_PI('|') add_applied_op: (applied_ops, operation, character) -> key = this.get_op_key operation, character applied_ops[key] = true check_applied_op: (applied_ops, operation, character) -> key = this.get_op_key operation, character return applied_ops[key] send_op: (events_ref, operation, character) -> events_ref.push operation: operation character: character is_bulk: false send_bulk_op: (events_ref, operation, character_list) -> events_ref.push operation: operation character_list: character_list is_bulk: true process_op: (operation_list, string, applied_ops) -> # If no operations to process, return if not operation_list.length return false # Try to execute the operation operation_object = operation_list.pop() result = woot.execute_operation( operation_object.operation, operation_object.character, string) if not result # If we failed to apply the operation, add it back to the front of the list operation_list.unshift operation_object return false else this.add_applied_op applied_ops, operation_object.operation, operation_object.character return true process_bulk_insert: (text, start_index, woot_state) -> insert_characters = [] for c, index in text.split '' woot_character = woot.generate_insert( start_index + index, c, woot_state.participant_name, woot_state.sequence_number, woot_state.string ) this.execute_operation( constants.INSERT_OPERATION, woot_character, woot_state ) # We unshift here so that they get pushed on in reverse and applied # in the correct order (since they are applied through pops) insert_characters.unshift woot_character this.send_bulk_op woot_state.events_ref, constants.INSERT_OPERATION, insert_characters process_bulk_delete: (text, start_index, woot_state) -> delete_characters = [] for c, index in text.split '' delete_characters.push woot.generate_delete start_index + index, woot_state.string for character in delete_characters this.execute_operation constants.DELETE_OPERATION, character, woot_state this.send_bulk_op woot_state.events_ref, constants.DELETE_OPERATION, delete_characters process_diff: (diff_array, woot_state) -> index = 0 for diff_subarray in diff_array type = diff_subarray[0] text = diff_subarray[1] if type == 1 this.process_bulk_insert text, index, woot_state else if type == -1 this.process_bulk_delete text, index, woot_state index -= text.length index += text.length execute_operation: (operation, woot_character, woot_state) -> if operation == constants.DELETE_OPERATION woot.integrate_delete woot_state.string, woot_character else if operation == constants.INSERT_OPERATION woot.integrate_insert woot_state.string, woot_character else throw Error("Unknown operation") this.add_applied_op( woot_state.applied_ops, operation, woot_character) woot_state.sequence_number += 1
[ { "context": "env.NODE_ENV = \"test\"\nprocess.env.VANITY_TOKEN = \"secret\"\n\n\nAsync = require(\"async\")\nBrowser = requi", "end": 64, "score": 0.49502813816070557, "start": 58, "tag": "KEY", "value": "secret" } ]
server/test/helper.coffee
assaf/vanity.js
2
process.env.NODE_ENV = "test" process.env.VANITY_TOKEN = "secret" Async = require("async") Browser = require("zombie") Replay = require("replay") server = require("../config/server") redis = require("../config/redis") Activity = require("../models/activity") Helper = # Call this before running each test. setup: (callback)-> redis.keys "#{redis.prefix}.*", (error, keys)-> if error throw error if keys.length == 0 callback() else redis.del keys..., callback # Call this once before running all tests. once: (callback)-> Async.parallel [ (done)-> server.listen(3003, done) ], (error)-> if error throw error else callback() # Call this before each test using ElasticSearch to recreate the index. newIndex: (callback)-> Activity.deleteIndex (error)-> if error throw error else Activity.createIndex (error)-> if error throw error else callback() Browser.site = "localhost:3003" # To capture and record API calls, run with environment variable RECORD=true Replay.fixtures = "#{__dirname}/replay" Replay.networkAccess = false Replay.localhost "localhost" Replay.ignore "mt1.googleapis.com" module.exports = Helper
63134
process.env.NODE_ENV = "test" process.env.VANITY_TOKEN = "<KEY>" Async = require("async") Browser = require("zombie") Replay = require("replay") server = require("../config/server") redis = require("../config/redis") Activity = require("../models/activity") Helper = # Call this before running each test. setup: (callback)-> redis.keys "#{redis.prefix}.*", (error, keys)-> if error throw error if keys.length == 0 callback() else redis.del keys..., callback # Call this once before running all tests. once: (callback)-> Async.parallel [ (done)-> server.listen(3003, done) ], (error)-> if error throw error else callback() # Call this before each test using ElasticSearch to recreate the index. newIndex: (callback)-> Activity.deleteIndex (error)-> if error throw error else Activity.createIndex (error)-> if error throw error else callback() Browser.site = "localhost:3003" # To capture and record API calls, run with environment variable RECORD=true Replay.fixtures = "#{__dirname}/replay" Replay.networkAccess = false Replay.localhost "localhost" Replay.ignore "mt1.googleapis.com" module.exports = Helper
true
process.env.NODE_ENV = "test" process.env.VANITY_TOKEN = "PI:KEY:<KEY>END_PI" Async = require("async") Browser = require("zombie") Replay = require("replay") server = require("../config/server") redis = require("../config/redis") Activity = require("../models/activity") Helper = # Call this before running each test. setup: (callback)-> redis.keys "#{redis.prefix}.*", (error, keys)-> if error throw error if keys.length == 0 callback() else redis.del keys..., callback # Call this once before running all tests. once: (callback)-> Async.parallel [ (done)-> server.listen(3003, done) ], (error)-> if error throw error else callback() # Call this before each test using ElasticSearch to recreate the index. newIndex: (callback)-> Activity.deleteIndex (error)-> if error throw error else Activity.createIndex (error)-> if error throw error else callback() Browser.site = "localhost:3003" # To capture and record API calls, run with environment variable RECORD=true Replay.fixtures = "#{__dirname}/replay" Replay.networkAccess = false Replay.localhost "localhost" Replay.ignore "mt1.googleapis.com" module.exports = Helper
[ { "context": "ttps://api.bufferapp.com/1/user.json?access_token=12345')\n @api.get('/user.json?')\n @get.verify()\n\n", "end": 485, "score": 0.9196006655693054, "start": 480, "tag": "PASSWORD", "value": "12345" }, { "context": ".json?url=http%3A%2F%2Fbufferapp.com&access_token=...
modules/buffer-api/test/buffer-api-spec.coffee
weld-io/social-scheduler
0
API = require '../src/api.coffee' BufferApi = require '../src/buffer-api.coffee' should = require 'should' sinon = require 'sinon' request = require 'request' describe 'API', -> beforeEach -> @api = new API(12345) @get = sinon.mock(request).expects('get') @post = sinon.mock(request).expects('post') it 'appends the access token and prepends the api url to every url accessed through it', -> @get.withArgs('https://api.bufferapp.com/1/user.json?access_token=12345') @api.get('/user.json?') @get.verify() it 'concats the access_token with an ampersand in case there is already a GET param in the url', -> @get.withArgs('https://api.bufferapp.com/1/links/shares.json?url=http%3A%2F%2Fbufferapp.com&access_token=12345') @api.get('/links/shares.json?url=http%3A%2F%2Fbufferapp.com') @get.verify() it 'parses the JSON response from each GET request', (done) -> @get.yields(null, null,'{"shares":47348}') @api.get('http://bufferapi.com', (err, obj) -> (err == null).should.be.ok obj.shares.should.equal(47348) done() ) it 'sends through the callback the error retrieved', (done) -> @get.yields('error!!!', null, null) @api.get('http://bufferapi.com', (err, obj) -> err.should.equal('error!!!') (obj == undefined).should.be.ok done() ) it 'adds the passed parameters to the POST requests', (done) -> parameters = {order: ['12653sa23', '1asd91234', '0w9102d']} @post.yields(null, null, '{"success": true}') @api.post('http://bufferapi.com', parameters, (err, obj) -> obj.success.should.be.true done() ) afterEach -> request.get.restore() request.post.restore() describe 'BufferApi', -> ACCESS_TOKEN = '1' ACCESS_TOKEN_SUFFIX = "access_token=#{ACCESS_TOKEN}" it 'exists', -> @api = new BufferApi(ACCESS_TOKEN) @api.should.not.be.null
84872
API = require '../src/api.coffee' BufferApi = require '../src/buffer-api.coffee' should = require 'should' sinon = require 'sinon' request = require 'request' describe 'API', -> beforeEach -> @api = new API(12345) @get = sinon.mock(request).expects('get') @post = sinon.mock(request).expects('post') it 'appends the access token and prepends the api url to every url accessed through it', -> @get.withArgs('https://api.bufferapp.com/1/user.json?access_token=<PASSWORD>') @api.get('/user.json?') @get.verify() it 'concats the access_token with an ampersand in case there is already a GET param in the url', -> @get.withArgs('https://api.bufferapp.com/1/links/shares.json?url=http%3A%2F%2Fbufferapp.com&access_token=<PASSWORD>') @api.get('/links/shares.json?url=http%3A%2F%2Fbufferapp.com') @get.verify() it 'parses the JSON response from each GET request', (done) -> @get.yields(null, null,'{"shares":47348}') @api.get('http://bufferapi.com', (err, obj) -> (err == null).should.be.ok obj.shares.should.equal(47348) done() ) it 'sends through the callback the error retrieved', (done) -> @get.yields('error!!!', null, null) @api.get('http://bufferapi.com', (err, obj) -> err.should.equal('error!!!') (obj == undefined).should.be.ok done() ) it 'adds the passed parameters to the POST requests', (done) -> parameters = {order: ['12653sa23', '1asd91234', '0w9102d']} @post.yields(null, null, '{"success": true}') @api.post('http://bufferapi.com', parameters, (err, obj) -> obj.success.should.be.true done() ) afterEach -> request.get.restore() request.post.restore() describe 'BufferApi', -> ACCESS_TOKEN = '1' ACCESS_TOKEN_SUFFIX = "access_token=#{ACCESS_TOKEN}" it 'exists', -> @api = new BufferApi(ACCESS_TOKEN) @api.should.not.be.null
true
API = require '../src/api.coffee' BufferApi = require '../src/buffer-api.coffee' should = require 'should' sinon = require 'sinon' request = require 'request' describe 'API', -> beforeEach -> @api = new API(12345) @get = sinon.mock(request).expects('get') @post = sinon.mock(request).expects('post') it 'appends the access token and prepends the api url to every url accessed through it', -> @get.withArgs('https://api.bufferapp.com/1/user.json?access_token=PI:PASSWORD:<PASSWORD>END_PI') @api.get('/user.json?') @get.verify() it 'concats the access_token with an ampersand in case there is already a GET param in the url', -> @get.withArgs('https://api.bufferapp.com/1/links/shares.json?url=http%3A%2F%2Fbufferapp.com&access_token=PI:PASSWORD:<PASSWORD>END_PI') @api.get('/links/shares.json?url=http%3A%2F%2Fbufferapp.com') @get.verify() it 'parses the JSON response from each GET request', (done) -> @get.yields(null, null,'{"shares":47348}') @api.get('http://bufferapi.com', (err, obj) -> (err == null).should.be.ok obj.shares.should.equal(47348) done() ) it 'sends through the callback the error retrieved', (done) -> @get.yields('error!!!', null, null) @api.get('http://bufferapi.com', (err, obj) -> err.should.equal('error!!!') (obj == undefined).should.be.ok done() ) it 'adds the passed parameters to the POST requests', (done) -> parameters = {order: ['12653sa23', '1asd91234', '0w9102d']} @post.yields(null, null, '{"success": true}') @api.post('http://bufferapi.com', parameters, (err, obj) -> obj.success.should.be.true done() ) afterEach -> request.get.restore() request.post.restore() describe 'BufferApi', -> ACCESS_TOKEN = '1' ACCESS_TOKEN_SUFFIX = "access_token=#{ACCESS_TOKEN}" it 'exists', -> @api = new BufferApi(ACCESS_TOKEN) @api.should.not.be.null
[ { "context": "where:\n login: req.body.login\n password: req.body.password\n .then (user) ->\n if not user\n throw new", "end": 885, "score": 0.9989527463912964, "start": 868, "tag": "PASSWORD", "value": "req.body.password" }, { "context": "gin\"/></label>\n <...
src/app.coffee
dgf/e4store-express4-itest
0
# load dependencies express = require 'express' bodyParser = require 'body-parser' multer = require 'multer' cookieParser = require 'cookie-parser' expressSession = require 'express-session' Sequelize = require 'sequelize' Store = require('express-sequelize-session') expressSession.Store # use in-memory SQLite3 database sequelize = new Sequelize 'itest', 'sa', 'secret', dialect: 'sqlite', logging: false store = new Store sequelize # define user table User = sequelize.define 'user', login: type: Sequelize.STRING allowNull: false unique: true password: type: Sequelize.STRING allowNull: false # associate session user User.belongsTo store.Session, foreignKeyConstraint: true # process a login request, reference the session and yield the user login = (req, done) -> User.findOne where: login: req.body.login password: req.body.password .then (user) -> if not user throw new Error 'login failed' else store.Session.findOne where: sid: req.sessionID .then (session) -> if not session # login without session user else # reference session user.setSession session .then (user) -> done null, user .catch (err) -> done err, null # process a logout request logout = (req, done) -> User.findOne where: login: req.session.user .then (user) -> if not user throw new Error 'logout failed' else user.setSession null .then (user) -> done null, user .catch (err) -> done err, null # create and configure express app app = express() app.use bodyParser.json() # for parsing application/json app.use bodyParser.urlencoded extended: true # for parsing application/x-www-form-urlencoded app.use multer() # for parsing multipart/form-data app.use cookieParser() app.use expressSession name: 'sid' secret: 'MyAwesomeAppSessionSecret' store: store resave: false saveUninitialized: true # restrict all requests app.all '*', (req, res, next) -> if req.path in ['/', '/login', '/logout'] next() # always allow access of these resources else # check user session if req.session.user next() # authenticated request else res.sendStatus 401 # unauthorized # public index page with login form app.get '/', (req, res) -> res.send """ <html><head><title>restricted area</title></head><body> <form action="/login" method="POST"> <label>Login <input type="text" name="login"/></label> <label>Password <input type="password" name="password"/></label> <button type="submit">Login</button> </form></body></html> """ # validate login and redirect app.post '/login', (req, res, next) -> login req, (err, user) -> if err? then next err else # re-ref user login req.session.user = user.login res.redirect '/private' # logout and redirect app.get '/logout', (req, res, next) -> logout req, (err) -> if err? then next err else delete req.session.user # de-ref user for safety req.session.destroy -> res.redirect '/' # private content page app.get '/private', (req, res) -> res.send """ <html><head><title>private space</title></head><body> <h1>Welcome #{req.session.user}</h1> <p>nice 2 cu</p> <a href="/logout">Logout</a> </body></html> """ # export database and express app module.exports = (done) -> sequelize.sync force: true .then -> done null, app, Session: store.Session User: User .catch (err) -> done err
126009
# load dependencies express = require 'express' bodyParser = require 'body-parser' multer = require 'multer' cookieParser = require 'cookie-parser' expressSession = require 'express-session' Sequelize = require 'sequelize' Store = require('express-sequelize-session') expressSession.Store # use in-memory SQLite3 database sequelize = new Sequelize 'itest', 'sa', 'secret', dialect: 'sqlite', logging: false store = new Store sequelize # define user table User = sequelize.define 'user', login: type: Sequelize.STRING allowNull: false unique: true password: type: Sequelize.STRING allowNull: false # associate session user User.belongsTo store.Session, foreignKeyConstraint: true # process a login request, reference the session and yield the user login = (req, done) -> User.findOne where: login: req.body.login password: <PASSWORD> .then (user) -> if not user throw new Error 'login failed' else store.Session.findOne where: sid: req.sessionID .then (session) -> if not session # login without session user else # reference session user.setSession session .then (user) -> done null, user .catch (err) -> done err, null # process a logout request logout = (req, done) -> User.findOne where: login: req.session.user .then (user) -> if not user throw new Error 'logout failed' else user.setSession null .then (user) -> done null, user .catch (err) -> done err, null # create and configure express app app = express() app.use bodyParser.json() # for parsing application/json app.use bodyParser.urlencoded extended: true # for parsing application/x-www-form-urlencoded app.use multer() # for parsing multipart/form-data app.use cookieParser() app.use expressSession name: 'sid' secret: 'MyAwesomeAppSessionSecret' store: store resave: false saveUninitialized: true # restrict all requests app.all '*', (req, res, next) -> if req.path in ['/', '/login', '/logout'] next() # always allow access of these resources else # check user session if req.session.user next() # authenticated request else res.sendStatus 401 # unauthorized # public index page with login form app.get '/', (req, res) -> res.send """ <html><head><title>restricted area</title></head><body> <form action="/login" method="POST"> <label>Login <input type="text" name="login"/></label> <label>Password <input type="<PASSWORD>" name="password"/></label> <button type="submit">Login</button> </form></body></html> """ # validate login and redirect app.post '/login', (req, res, next) -> login req, (err, user) -> if err? then next err else # re-ref user login req.session.user = user.login res.redirect '/private' # logout and redirect app.get '/logout', (req, res, next) -> logout req, (err) -> if err? then next err else delete req.session.user # de-ref user for safety req.session.destroy -> res.redirect '/' # private content page app.get '/private', (req, res) -> res.send """ <html><head><title>private space</title></head><body> <h1>Welcome #{req.session.user}</h1> <p>nice 2 cu</p> <a href="/logout">Logout</a> </body></html> """ # export database and express app module.exports = (done) -> sequelize.sync force: true .then -> done null, app, Session: store.Session User: User .catch (err) -> done err
true
# load dependencies express = require 'express' bodyParser = require 'body-parser' multer = require 'multer' cookieParser = require 'cookie-parser' expressSession = require 'express-session' Sequelize = require 'sequelize' Store = require('express-sequelize-session') expressSession.Store # use in-memory SQLite3 database sequelize = new Sequelize 'itest', 'sa', 'secret', dialect: 'sqlite', logging: false store = new Store sequelize # define user table User = sequelize.define 'user', login: type: Sequelize.STRING allowNull: false unique: true password: type: Sequelize.STRING allowNull: false # associate session user User.belongsTo store.Session, foreignKeyConstraint: true # process a login request, reference the session and yield the user login = (req, done) -> User.findOne where: login: req.body.login password: PI:PASSWORD:<PASSWORD>END_PI .then (user) -> if not user throw new Error 'login failed' else store.Session.findOne where: sid: req.sessionID .then (session) -> if not session # login without session user else # reference session user.setSession session .then (user) -> done null, user .catch (err) -> done err, null # process a logout request logout = (req, done) -> User.findOne where: login: req.session.user .then (user) -> if not user throw new Error 'logout failed' else user.setSession null .then (user) -> done null, user .catch (err) -> done err, null # create and configure express app app = express() app.use bodyParser.json() # for parsing application/json app.use bodyParser.urlencoded extended: true # for parsing application/x-www-form-urlencoded app.use multer() # for parsing multipart/form-data app.use cookieParser() app.use expressSession name: 'sid' secret: 'MyAwesomeAppSessionSecret' store: store resave: false saveUninitialized: true # restrict all requests app.all '*', (req, res, next) -> if req.path in ['/', '/login', '/logout'] next() # always allow access of these resources else # check user session if req.session.user next() # authenticated request else res.sendStatus 401 # unauthorized # public index page with login form app.get '/', (req, res) -> res.send """ <html><head><title>restricted area</title></head><body> <form action="/login" method="POST"> <label>Login <input type="text" name="login"/></label> <label>Password <input type="PI:PASSWORD:<PASSWORD>END_PI" name="password"/></label> <button type="submit">Login</button> </form></body></html> """ # validate login and redirect app.post '/login', (req, res, next) -> login req, (err, user) -> if err? then next err else # re-ref user login req.session.user = user.login res.redirect '/private' # logout and redirect app.get '/logout', (req, res, next) -> logout req, (err) -> if err? then next err else delete req.session.user # de-ref user for safety req.session.destroy -> res.redirect '/' # private content page app.get '/private', (req, res) -> res.send """ <html><head><title>private space</title></head><body> <h1>Welcome #{req.session.user}</h1> <p>nice 2 cu</p> <a href="/logout">Logout</a> </body></html> """ # export database and express app module.exports = (done) -> sequelize.sync force: true .then -> done null, app, Session: store.Session User: User .catch (err) -> done err
[ { "context": "ddress=\\\"newAddr\\\" serverPort=\\\"5435\\\" userName=\\\"newUserName\\\" password=\\\"newPass\\\" />\\n</tsRequest>\"\n ", "end": 636, "score": 0.9995229244232178, "start": 625, "tag": "USERNAME", "value": "newUserName" }, { "context": "Port=\\\"5435\\\" userN...
snippets/updatetwbdataconn.cson
cmtoomey/TableauRESTJS
1
'.source.js': 'Update Workbook Data Connections': 'prefix': 'truwdata' 'body': """ //Update Workbook data connections function updateWorkbookConnections() { var settings = { "async": true, "crossDomain": true, "url": url + "sites/" + siteid + "/workbooks/"+workbookID+"/connections/"+connectionID, "method": "PUT", "headers": { "x-tableau-auth": auth }, "data": "<tsRequest>\n\t<connection serverAddress=\"newAddr\" serverPort=\"5435\" userName=\"newUserName\" password=\"newPass\" />\n</tsRequest>" } $.ajax(settings).done(function(response) { console.log(response); }); } """
180971
'.source.js': 'Update Workbook Data Connections': 'prefix': 'truwdata' 'body': """ //Update Workbook data connections function updateWorkbookConnections() { var settings = { "async": true, "crossDomain": true, "url": url + "sites/" + siteid + "/workbooks/"+workbookID+"/connections/"+connectionID, "method": "PUT", "headers": { "x-tableau-auth": auth }, "data": "<tsRequest>\n\t<connection serverAddress=\"newAddr\" serverPort=\"5435\" userName=\"newUserName\" password=\"<PASSWORD>\" />\n</tsRequest>" } $.ajax(settings).done(function(response) { console.log(response); }); } """
true
'.source.js': 'Update Workbook Data Connections': 'prefix': 'truwdata' 'body': """ //Update Workbook data connections function updateWorkbookConnections() { var settings = { "async": true, "crossDomain": true, "url": url + "sites/" + siteid + "/workbooks/"+workbookID+"/connections/"+connectionID, "method": "PUT", "headers": { "x-tableau-auth": auth }, "data": "<tsRequest>\n\t<connection serverAddress=\"newAddr\" serverPort=\"5435\" userName=\"newUserName\" password=\"PI:PASSWORD:<PASSWORD>END_PI\" />\n</tsRequest>" } $.ajax(settings).done(function(response) { console.log(response); }); } """
[ { "context": "scribe 'authentication middleware', ->\n token = '123456'\n userEmail = 'test@example.com'\n accountReques", "end": 191, "score": 0.929323673248291, "start": 185, "tag": "PASSWORD", "value": "123456" }, { "context": "middleware', ->\n token = '123456'\n userEmail =...
spec/middleware/authentication_spec.coffee
RedBulli/LiveSnooker-Server
0
request = require 'supertest' expect = require('chai').expect models = require '../../models' specHelper = require '../spec_helper' describe 'authentication middleware', -> token = '123456' userEmail = 'test@example.com' accountRequest = -> request($app) .get '/account' .set 'x-auth-google-id-token', token leagueGetRequest = (id, token) -> req = request($app).get '/leagues/' + id req.set 'x-auth-google-id-token', token if token req leagueCreateAdminRequest = (id, token) -> req = request($app) .post "/leagues/#{id}/admins" .send UserEmail: 'something@eee.com' req.set 'x-auth-google-id-token', token if token req it 'caches the user data from Google', (done) -> specHelper.mockGoogleTokenRequest(token, userEmail) accountRequest().end -> secondRequestMock = specHelper.mockGoogleTokenRequest(token, userEmail, {status: 400}) accountRequest() .expect -> expect(secondRequestMock.isDone()).to.eql false .expect(200, done) describe 'league privileges', -> userToken = '12345' writeAdminEmail = 'write-admin@example.com' readAdminEmail = 'read-admin@example.com' nonAdminEmail = 'not-admin@example.com' beforeEach -> models.League.create(name: 'Biklu').then (league) => @league = league Promise.all([ models.Admin.create UserEmail: writeAdminEmail LeagueId: league.id write: true models.Admin.create UserEmail: readAdminEmail LeagueId: league.id write: false ]) describe 'when user is not authenticated', -> it "doesn't allow GET", (done) -> leagueGetRequest(@league.id).expect(401, done) it "doesn't allow admin creation", (done) -> leagueCreateAdminRequest(@league.id).expect(401, done) it 'allows GET if league is public', (done) -> @league.set('public', true) @league.save().then => leagueGetRequest(@league.id).expect(200, done) describe 'when the user is not an admin', -> beforeEach -> specHelper.mockGoogleTokenRequest(userToken, nonAdminEmail) it "doesn't allow GET", (done) -> leagueGetRequest(@league.id, userToken).expect(403, done) it "doesn't allow admin creation", (done) -> leagueCreateAdminRequest(@league.id, userToken).expect(403, done) it 'allows GET if league is public', (done) -> @league.set('public', true) @league.save().then => leagueGetRequest(@league.id, userToken).expect(200, done) describe 'when user has admin without write', -> beforeEach -> specHelper.mockGoogleTokenRequest(userToken, readAdminEmail) it "allows GET", (done) -> leagueGetRequest(@league.id, userToken).expect(200, done) it "doesn't allow admin creation", (done) -> leagueCreateAdminRequest(@league.id, userToken).expect(403, done) describe 'when user has write admin', -> beforeEach -> specHelper.mockGoogleTokenRequest(userToken, writeAdminEmail) it "allows GET", (done) -> leagueGetRequest(@league.id, userToken).expect(200, done) it "allows admin creation", (done) -> leagueCreateAdminRequest(@league.id, userToken).expect(201, done)
26670
request = require 'supertest' expect = require('chai').expect models = require '../../models' specHelper = require '../spec_helper' describe 'authentication middleware', -> token = '<PASSWORD>' userEmail = '<EMAIL>' accountRequest = -> request($app) .get '/account' .set 'x-auth-google-id-token', token leagueGetRequest = (id, token) -> req = request($app).get '/leagues/' + id req.set 'x-auth-google-id-token', token if token req leagueCreateAdminRequest = (id, token) -> req = request($app) .post "/leagues/#{id}/admins" .send UserEmail: '<EMAIL>' req.set 'x-auth-google-id-token', token if token req it 'caches the user data from Google', (done) -> specHelper.mockGoogleTokenRequest(token, userEmail) accountRequest().end -> secondRequestMock = specHelper.mockGoogleTokenRequest(token, userEmail, {status: 400}) accountRequest() .expect -> expect(secondRequestMock.isDone()).to.eql false .expect(200, done) describe 'league privileges', -> userToken = '<PASSWORD>' writeAdminEmail = '<EMAIL>' readAdminEmail = '<EMAIL>' nonAdminEmail = '<EMAIL>' beforeEach -> models.League.create(name: 'Biklu').then (league) => @league = league Promise.all([ models.Admin.create UserEmail: writeAdminEmail LeagueId: league.id write: true models.Admin.create UserEmail: readAdminEmail LeagueId: league.id write: false ]) describe 'when user is not authenticated', -> it "doesn't allow GET", (done) -> leagueGetRequest(@league.id).expect(401, done) it "doesn't allow admin creation", (done) -> leagueCreateAdminRequest(@league.id).expect(401, done) it 'allows GET if league is public', (done) -> @league.set('public', true) @league.save().then => leagueGetRequest(@league.id).expect(200, done) describe 'when the user is not an admin', -> beforeEach -> specHelper.mockGoogleTokenRequest(userToken, nonAdminEmail) it "doesn't allow GET", (done) -> leagueGetRequest(@league.id, userToken).expect(403, done) it "doesn't allow admin creation", (done) -> leagueCreateAdminRequest(@league.id, userToken).expect(403, done) it 'allows GET if league is public', (done) -> @league.set('public', true) @league.save().then => leagueGetRequest(@league.id, userToken).expect(200, done) describe 'when user has admin without write', -> beforeEach -> specHelper.mockGoogleTokenRequest(userToken, readAdminEmail) it "allows GET", (done) -> leagueGetRequest(@league.id, userToken).expect(200, done) it "doesn't allow admin creation", (done) -> leagueCreateAdminRequest(@league.id, userToken).expect(403, done) describe 'when user has write admin', -> beforeEach -> specHelper.mockGoogleTokenRequest(userToken, writeAdminEmail) it "allows GET", (done) -> leagueGetRequest(@league.id, userToken).expect(200, done) it "allows admin creation", (done) -> leagueCreateAdminRequest(@league.id, userToken).expect(201, done)
true
request = require 'supertest' expect = require('chai').expect models = require '../../models' specHelper = require '../spec_helper' describe 'authentication middleware', -> token = 'PI:PASSWORD:<PASSWORD>END_PI' userEmail = 'PI:EMAIL:<EMAIL>END_PI' accountRequest = -> request($app) .get '/account' .set 'x-auth-google-id-token', token leagueGetRequest = (id, token) -> req = request($app).get '/leagues/' + id req.set 'x-auth-google-id-token', token if token req leagueCreateAdminRequest = (id, token) -> req = request($app) .post "/leagues/#{id}/admins" .send UserEmail: 'PI:EMAIL:<EMAIL>END_PI' req.set 'x-auth-google-id-token', token if token req it 'caches the user data from Google', (done) -> specHelper.mockGoogleTokenRequest(token, userEmail) accountRequest().end -> secondRequestMock = specHelper.mockGoogleTokenRequest(token, userEmail, {status: 400}) accountRequest() .expect -> expect(secondRequestMock.isDone()).to.eql false .expect(200, done) describe 'league privileges', -> userToken = 'PI:PASSWORD:<PASSWORD>END_PI' writeAdminEmail = 'PI:EMAIL:<EMAIL>END_PI' readAdminEmail = 'PI:EMAIL:<EMAIL>END_PI' nonAdminEmail = 'PI:EMAIL:<EMAIL>END_PI' beforeEach -> models.League.create(name: 'Biklu').then (league) => @league = league Promise.all([ models.Admin.create UserEmail: writeAdminEmail LeagueId: league.id write: true models.Admin.create UserEmail: readAdminEmail LeagueId: league.id write: false ]) describe 'when user is not authenticated', -> it "doesn't allow GET", (done) -> leagueGetRequest(@league.id).expect(401, done) it "doesn't allow admin creation", (done) -> leagueCreateAdminRequest(@league.id).expect(401, done) it 'allows GET if league is public', (done) -> @league.set('public', true) @league.save().then => leagueGetRequest(@league.id).expect(200, done) describe 'when the user is not an admin', -> beforeEach -> specHelper.mockGoogleTokenRequest(userToken, nonAdminEmail) it "doesn't allow GET", (done) -> leagueGetRequest(@league.id, userToken).expect(403, done) it "doesn't allow admin creation", (done) -> leagueCreateAdminRequest(@league.id, userToken).expect(403, done) it 'allows GET if league is public', (done) -> @league.set('public', true) @league.save().then => leagueGetRequest(@league.id, userToken).expect(200, done) describe 'when user has admin without write', -> beforeEach -> specHelper.mockGoogleTokenRequest(userToken, readAdminEmail) it "allows GET", (done) -> leagueGetRequest(@league.id, userToken).expect(200, done) it "doesn't allow admin creation", (done) -> leagueCreateAdminRequest(@league.id, userToken).expect(403, done) describe 'when user has write admin', -> beforeEach -> specHelper.mockGoogleTokenRequest(userToken, writeAdminEmail) it "allows GET", (done) -> leagueGetRequest(@league.id, userToken).expect(200, done) it "allows admin creation", (done) -> leagueCreateAdminRequest(@league.id, userToken).expect(201, done)
[ { "context": "Index = git.Repo.fibers.open(docsDir, 'leisure', 'leisure@textcraft.org').fibers.openAndReadIndex()\n# usingGit = fStat", "end": 3752, "score": 0.9998857975006104, "start": 3731, "tag": "EMAIL", "value": "leisure@textcraft.org" } ]
METEOR-OLD/server/1-git.coffee
zot/Leisure
58
#### # fs-only storage until we get the git connection working again #### root = global.Leisure #git = Meteor.require 'nodegit' fs = Meteor.require 'fs' Fiber = Meteor.require 'fibers' Future = Meteor.require 'fibers/future' path = Meteor.require 'path' docsDir = path.resolve '../../../../../../docs' usingGit = false #currentIndex = null #fRepo = Future.wrap (dir, cb)-> git.Repo.open dir, cb fStat = Future.wrap (name, cb)-> fs.stat name, cb fReadFile = Future.wrap (name, cb)-> fs.readFile name, cb fWriteFile = Future.wrap (name, contents, cb)-> fs.writeFile name, contents, cb docFile = (name)-> "#{docsDir}/#{name}" readFile = (name)-> fReadFile(name).wait() writeFile = (name, contents)-> fWriteFile(name, contents).wait() statFile = (name)-> fStat(name).wait() snapshot = (doc)-> objs = {} text = '' for obj in doc.find().fetch() objs[obj._id] = obj if obj.info then objs.info = obj cur = objs.info.head while cur text += objs[cur].text cur = objs[cur].next storeFile doc.leisure.name, text true storeFile = (name, contents)-> writeFile docFile(name), contents loadFile = (name)-> readFile docFile name hasFile = (name)-> statFile(docFile(name))? #git.Repo.fibers = open: (dir, owner, ownerEmail)->addRepoFibers fRepo(dir).wait(), owner, ownerEmail # #addRepoFibers = (r, owner, ownerEmail)-> # console.log "OWNER: #{owner}, email: #{ownerEmail}" # r.fibers = # owner: owner # ownerEmail: ownerEmail # openIndex: -> addIndexFibers r, Future.wrap((cb)-> r.openIndex cb)().wait() # openAndReadIndex: -> # ind = r.fibers.openIndex() # ind.fibers.read() # referenceOidForName: (name)-> Future.wrap((cb)-> git.Reference.oidForName r, name, cb)().wait() # getCommit: (oid)-> Future.wrap((cb)-> r.getCommit oid, cb)().wait() # getBlob: (oid)-> Future.wrap((cb)-> r.getBlob oid, cb)().wait() # createCommit: (ref, author, committer, msg, treeOid, parents)-> # Future.wrap((cb)-> r.createCommit ref, author, committer, msg, treeOid, parents, cb)().wait() # r # #addIndexFibers = (r, ind)-> # ind.fibers = # repo: r # read: -> # Future.wrap((cb)-> ind.read cb)().wait() # ind # addByPath: (path)-> # Future.wrap((cb)-> ind.addByPath path, cb)().wait() # ind # write: -> # Future.wrap((cb)-> ind.write cb)().wait() # ind # writeTree: -> Future.wrap((cb)-> ind.writeTree cb)().wait() # commit: (ref, msg, author, authorEmail, committer, committerEmail)-> # ind.fibers.write() # treeOid = ind.fibers.writeTree() # headOid = r.fibers.referenceOidForName ref # parent = r.fibers.getCommit headOid # d = new Date() # time = Math.round(d.getTime() / 1000) # zone = d.getTimezoneOffset() # author = git.Signature.create (author ? r.fibers.owner), (authorEmail ? r.fibers.ownerEmail), time, zone # committer = git.Signature.create (committer ? r.fibers.owner), (committerEmail ? r.fibers.ownerEmail), time, zone # r.fibers.createCommit ref, author, committer, msg, treeOid, [parent] # getByPath: (path)-> # i = ind.find path # if i > -1 then r.fibers.getBlob(ind.entry(i).oid()) # ind # #storeFile = (name, contents)-> # if ind = currentIndex # console.log "SNAPSHOT #{name}\n\n#{contents}" # writeFile path.resolve(docsDir, name), contents # ind.fibers.addByPath name # commitOid = ind.fibers.commit 'HEAD', 'snapshot' # console.log "COMMITED SNAPSHOT:", commitOid # true # #loadFile = (name)-> currentIndex?.fibers.read().fibers.getByPath(name).content() # #hasFile = (name)-> currentIndex?.find(name)? # #if (process.env.LEISURE_NO_GIT?.length ? 0) == 0 # try # #currentIndex = git.Repo.fibers.open(docsDir, 'leisure', 'leisure@textcraft.org').fibers.openAndReadIndex() # usingGit = fStat(path.resolve "#{docsDir}/.git")?.isDirectory() # catch err # console.log err.stack root.git = snapshot: snapshot hasFile: hasFile readFile: loadFile hasGit: usingGit
136830
#### # fs-only storage until we get the git connection working again #### root = global.Leisure #git = Meteor.require 'nodegit' fs = Meteor.require 'fs' Fiber = Meteor.require 'fibers' Future = Meteor.require 'fibers/future' path = Meteor.require 'path' docsDir = path.resolve '../../../../../../docs' usingGit = false #currentIndex = null #fRepo = Future.wrap (dir, cb)-> git.Repo.open dir, cb fStat = Future.wrap (name, cb)-> fs.stat name, cb fReadFile = Future.wrap (name, cb)-> fs.readFile name, cb fWriteFile = Future.wrap (name, contents, cb)-> fs.writeFile name, contents, cb docFile = (name)-> "#{docsDir}/#{name}" readFile = (name)-> fReadFile(name).wait() writeFile = (name, contents)-> fWriteFile(name, contents).wait() statFile = (name)-> fStat(name).wait() snapshot = (doc)-> objs = {} text = '' for obj in doc.find().fetch() objs[obj._id] = obj if obj.info then objs.info = obj cur = objs.info.head while cur text += objs[cur].text cur = objs[cur].next storeFile doc.leisure.name, text true storeFile = (name, contents)-> writeFile docFile(name), contents loadFile = (name)-> readFile docFile name hasFile = (name)-> statFile(docFile(name))? #git.Repo.fibers = open: (dir, owner, ownerEmail)->addRepoFibers fRepo(dir).wait(), owner, ownerEmail # #addRepoFibers = (r, owner, ownerEmail)-> # console.log "OWNER: #{owner}, email: #{ownerEmail}" # r.fibers = # owner: owner # ownerEmail: ownerEmail # openIndex: -> addIndexFibers r, Future.wrap((cb)-> r.openIndex cb)().wait() # openAndReadIndex: -> # ind = r.fibers.openIndex() # ind.fibers.read() # referenceOidForName: (name)-> Future.wrap((cb)-> git.Reference.oidForName r, name, cb)().wait() # getCommit: (oid)-> Future.wrap((cb)-> r.getCommit oid, cb)().wait() # getBlob: (oid)-> Future.wrap((cb)-> r.getBlob oid, cb)().wait() # createCommit: (ref, author, committer, msg, treeOid, parents)-> # Future.wrap((cb)-> r.createCommit ref, author, committer, msg, treeOid, parents, cb)().wait() # r # #addIndexFibers = (r, ind)-> # ind.fibers = # repo: r # read: -> # Future.wrap((cb)-> ind.read cb)().wait() # ind # addByPath: (path)-> # Future.wrap((cb)-> ind.addByPath path, cb)().wait() # ind # write: -> # Future.wrap((cb)-> ind.write cb)().wait() # ind # writeTree: -> Future.wrap((cb)-> ind.writeTree cb)().wait() # commit: (ref, msg, author, authorEmail, committer, committerEmail)-> # ind.fibers.write() # treeOid = ind.fibers.writeTree() # headOid = r.fibers.referenceOidForName ref # parent = r.fibers.getCommit headOid # d = new Date() # time = Math.round(d.getTime() / 1000) # zone = d.getTimezoneOffset() # author = git.Signature.create (author ? r.fibers.owner), (authorEmail ? r.fibers.ownerEmail), time, zone # committer = git.Signature.create (committer ? r.fibers.owner), (committerEmail ? r.fibers.ownerEmail), time, zone # r.fibers.createCommit ref, author, committer, msg, treeOid, [parent] # getByPath: (path)-> # i = ind.find path # if i > -1 then r.fibers.getBlob(ind.entry(i).oid()) # ind # #storeFile = (name, contents)-> # if ind = currentIndex # console.log "SNAPSHOT #{name}\n\n#{contents}" # writeFile path.resolve(docsDir, name), contents # ind.fibers.addByPath name # commitOid = ind.fibers.commit 'HEAD', 'snapshot' # console.log "COMMITED SNAPSHOT:", commitOid # true # #loadFile = (name)-> currentIndex?.fibers.read().fibers.getByPath(name).content() # #hasFile = (name)-> currentIndex?.find(name)? # #if (process.env.LEISURE_NO_GIT?.length ? 0) == 0 # try # #currentIndex = git.Repo.fibers.open(docsDir, 'leisure', '<EMAIL>').fibers.openAndReadIndex() # usingGit = fStat(path.resolve "#{docsDir}/.git")?.isDirectory() # catch err # console.log err.stack root.git = snapshot: snapshot hasFile: hasFile readFile: loadFile hasGit: usingGit
true
#### # fs-only storage until we get the git connection working again #### root = global.Leisure #git = Meteor.require 'nodegit' fs = Meteor.require 'fs' Fiber = Meteor.require 'fibers' Future = Meteor.require 'fibers/future' path = Meteor.require 'path' docsDir = path.resolve '../../../../../../docs' usingGit = false #currentIndex = null #fRepo = Future.wrap (dir, cb)-> git.Repo.open dir, cb fStat = Future.wrap (name, cb)-> fs.stat name, cb fReadFile = Future.wrap (name, cb)-> fs.readFile name, cb fWriteFile = Future.wrap (name, contents, cb)-> fs.writeFile name, contents, cb docFile = (name)-> "#{docsDir}/#{name}" readFile = (name)-> fReadFile(name).wait() writeFile = (name, contents)-> fWriteFile(name, contents).wait() statFile = (name)-> fStat(name).wait() snapshot = (doc)-> objs = {} text = '' for obj in doc.find().fetch() objs[obj._id] = obj if obj.info then objs.info = obj cur = objs.info.head while cur text += objs[cur].text cur = objs[cur].next storeFile doc.leisure.name, text true storeFile = (name, contents)-> writeFile docFile(name), contents loadFile = (name)-> readFile docFile name hasFile = (name)-> statFile(docFile(name))? #git.Repo.fibers = open: (dir, owner, ownerEmail)->addRepoFibers fRepo(dir).wait(), owner, ownerEmail # #addRepoFibers = (r, owner, ownerEmail)-> # console.log "OWNER: #{owner}, email: #{ownerEmail}" # r.fibers = # owner: owner # ownerEmail: ownerEmail # openIndex: -> addIndexFibers r, Future.wrap((cb)-> r.openIndex cb)().wait() # openAndReadIndex: -> # ind = r.fibers.openIndex() # ind.fibers.read() # referenceOidForName: (name)-> Future.wrap((cb)-> git.Reference.oidForName r, name, cb)().wait() # getCommit: (oid)-> Future.wrap((cb)-> r.getCommit oid, cb)().wait() # getBlob: (oid)-> Future.wrap((cb)-> r.getBlob oid, cb)().wait() # createCommit: (ref, author, committer, msg, treeOid, parents)-> # Future.wrap((cb)-> r.createCommit ref, author, committer, msg, treeOid, parents, cb)().wait() # r # #addIndexFibers = (r, ind)-> # ind.fibers = # repo: r # read: -> # Future.wrap((cb)-> ind.read cb)().wait() # ind # addByPath: (path)-> # Future.wrap((cb)-> ind.addByPath path, cb)().wait() # ind # write: -> # Future.wrap((cb)-> ind.write cb)().wait() # ind # writeTree: -> Future.wrap((cb)-> ind.writeTree cb)().wait() # commit: (ref, msg, author, authorEmail, committer, committerEmail)-> # ind.fibers.write() # treeOid = ind.fibers.writeTree() # headOid = r.fibers.referenceOidForName ref # parent = r.fibers.getCommit headOid # d = new Date() # time = Math.round(d.getTime() / 1000) # zone = d.getTimezoneOffset() # author = git.Signature.create (author ? r.fibers.owner), (authorEmail ? r.fibers.ownerEmail), time, zone # committer = git.Signature.create (committer ? r.fibers.owner), (committerEmail ? r.fibers.ownerEmail), time, zone # r.fibers.createCommit ref, author, committer, msg, treeOid, [parent] # getByPath: (path)-> # i = ind.find path # if i > -1 then r.fibers.getBlob(ind.entry(i).oid()) # ind # #storeFile = (name, contents)-> # if ind = currentIndex # console.log "SNAPSHOT #{name}\n\n#{contents}" # writeFile path.resolve(docsDir, name), contents # ind.fibers.addByPath name # commitOid = ind.fibers.commit 'HEAD', 'snapshot' # console.log "COMMITED SNAPSHOT:", commitOid # true # #loadFile = (name)-> currentIndex?.fibers.read().fibers.getByPath(name).content() # #hasFile = (name)-> currentIndex?.find(name)? # #if (process.env.LEISURE_NO_GIT?.length ? 0) == 0 # try # #currentIndex = git.Repo.fibers.open(docsDir, 'leisure', 'PI:EMAIL:<EMAIL>END_PI').fibers.openAndReadIndex() # usingGit = fStat(path.resolve "#{docsDir}/.git")?.isDirectory() # catch err # console.log err.stack root.git = snapshot: snapshot hasFile: hasFile readFile: loadFile hasGit: usingGit
[ { "context": "# grunt-react-render\n# https://github.com/alexander/grunt-react-render\n\n# Copyright (c) 2014 AlexMost", "end": 51, "score": 0.9996864795684814, "start": 42, "tag": "USERNAME", "value": "alexander" }, { "context": "alexander/grunt-react-render\n\n# Copyright (c) 2014 ...
src/react_render.coffee
AlexMost/grunt-react-render
1
# grunt-react-render # https://github.com/alexander/grunt-react-render # Copyright (c) 2014 AlexMost # Licensed under the MIT license. {processFile} = require './lib' path = require 'path' module.exports = (grunt) -> defaults = {} grunt.registerMultiTask( 'react_render' 'Grunt plugin for rendering reactjs controls' -> done = @async() options = @options defaults src = options.src dest = if options.dest fname = path.basename src path.join path.resolve(options.dest), fname else src grunt.log.ok "Injecting react components into #{src}" processFile src, dest, (error) -> grunt.log.ok "file #{dest} is ready" grunt.log.subhead 'grunt-react-render done' done() )
88811
# grunt-react-render # https://github.com/alexander/grunt-react-render # Copyright (c) 2014 <NAME> # Licensed under the MIT license. {processFile} = require './lib' path = require 'path' module.exports = (grunt) -> defaults = {} grunt.registerMultiTask( 'react_render' 'Grunt plugin for rendering reactjs controls' -> done = @async() options = @options defaults src = options.src dest = if options.dest fname = path.basename src path.join path.resolve(options.dest), fname else src grunt.log.ok "Injecting react components into #{src}" processFile src, dest, (error) -> grunt.log.ok "file #{dest} is ready" grunt.log.subhead 'grunt-react-render done' done() )
true
# grunt-react-render # https://github.com/alexander/grunt-react-render # Copyright (c) 2014 PI:NAME:<NAME>END_PI # Licensed under the MIT license. {processFile} = require './lib' path = require 'path' module.exports = (grunt) -> defaults = {} grunt.registerMultiTask( 'react_render' 'Grunt plugin for rendering reactjs controls' -> done = @async() options = @options defaults src = options.src dest = if options.dest fname = path.basename src path.join path.resolve(options.dest), fname else src grunt.log.ok "Injecting react components into #{src}" processFile src, dest, (error) -> grunt.log.ok "file #{dest} is ready" grunt.log.subhead 'grunt-react-render done' done() )
[ { "context": "# Try POH\n# author: Leonardone @ NEETSDKASU\n# ==================================", "end": 30, "score": 0.9993153810501099, "start": 20, "tag": "NAME", "value": "Leonardone" } ]
POH8/Yukata/Main.coffee
neetsdkasu/Paiza-POH-MyAnswers
3
# Try POH # author: Leonardone @ NEETSDKASU # =================================================== solve = (mr) -> n = mr.gi() ts = mr.ngss n x = 0 b = 0 c = 0 for [t, s] in ts h = parseInt t if x > 0 df = h - b tx = Math.max x - df, 0 c += x - tx x = tx b = h switch s when 'out' then x += 3 when 'in' then x += 5 if x > 0 df = 24 - b tx = Math.max x - df, 0 c += x - tx x = tx console.log c + 24 # =================================================== (-> buf = '' process.stdin.setEncoding 'utf8' process.stdin.on 'data', (data) -> buf += data.toString() process.stdin.on 'end', () -> lines = buf.split '\n' cur = 0 gs = -> lines[cur++] gi = -> parseInt gs() gss = -> gs().split ' ' gis = -> gss().map (x) -> parseInt x ngt = (n, f) -> f() while n-- ngs = (n) -> ngt n, gs ngi = (n) -> ngt n, gi ngss = (n) -> ngt n, gss ngis = (n) -> ngt n, gis solve "gs": gs, "gi": gi, "gss": gss, "gis": gis, "ngs": ngs, "ngi": ngi, "ngss": ngss, "ngis": ngis )() # ===================================================
52985
# Try POH # author: <NAME> @ NEETSDKASU # =================================================== solve = (mr) -> n = mr.gi() ts = mr.ngss n x = 0 b = 0 c = 0 for [t, s] in ts h = parseInt t if x > 0 df = h - b tx = Math.max x - df, 0 c += x - tx x = tx b = h switch s when 'out' then x += 3 when 'in' then x += 5 if x > 0 df = 24 - b tx = Math.max x - df, 0 c += x - tx x = tx console.log c + 24 # =================================================== (-> buf = '' process.stdin.setEncoding 'utf8' process.stdin.on 'data', (data) -> buf += data.toString() process.stdin.on 'end', () -> lines = buf.split '\n' cur = 0 gs = -> lines[cur++] gi = -> parseInt gs() gss = -> gs().split ' ' gis = -> gss().map (x) -> parseInt x ngt = (n, f) -> f() while n-- ngs = (n) -> ngt n, gs ngi = (n) -> ngt n, gi ngss = (n) -> ngt n, gss ngis = (n) -> ngt n, gis solve "gs": gs, "gi": gi, "gss": gss, "gis": gis, "ngs": ngs, "ngi": ngi, "ngss": ngss, "ngis": ngis )() # ===================================================
true
# Try POH # author: PI:NAME:<NAME>END_PI @ NEETSDKASU # =================================================== solve = (mr) -> n = mr.gi() ts = mr.ngss n x = 0 b = 0 c = 0 for [t, s] in ts h = parseInt t if x > 0 df = h - b tx = Math.max x - df, 0 c += x - tx x = tx b = h switch s when 'out' then x += 3 when 'in' then x += 5 if x > 0 df = 24 - b tx = Math.max x - df, 0 c += x - tx x = tx console.log c + 24 # =================================================== (-> buf = '' process.stdin.setEncoding 'utf8' process.stdin.on 'data', (data) -> buf += data.toString() process.stdin.on 'end', () -> lines = buf.split '\n' cur = 0 gs = -> lines[cur++] gi = -> parseInt gs() gss = -> gs().split ' ' gis = -> gss().map (x) -> parseInt x ngt = (n, f) -> f() while n-- ngs = (n) -> ngt n, gs ngi = (n) -> ngt n, gi ngss = (n) -> ngt n, gss ngis = (n) -> ngt n, gis solve "gs": gs, "gi": gi, "gss": gss, "gis": gis, "ngs": ngs, "ngi": ngi, "ngss": ngss, "ngis": ngis )() # ===================================================
[ { "context": "t-Type', /json/)\n .expect(200, [ { name : \"Euge\" }, { name : \"Bob\" } ], done)\n\n it \"works with", "end": 615, "score": 0.9993278980255127, "start": 611, "tag": "NAME", "value": "Euge" }, { "context": " .expect(200, [ { name : \"Euge\" }, { name : \...
test/server_test.coffee
euge/canned-responses
1
"use strict" request = require 'supertest' canned = require "../" expect = require("chai").expect describe "Actual canned responses", -> server = null before -> server = new canned("#{__dirname}/fixtures/responses.js").server describe "with a match", -> it "adds a default index route handler", (done) -> request(server) .get("/") .expect("Content-Type", /html/) .expect(200, /<html>\s*<body>/, done) it "works with a GET", (done) -> request(server) .get('/people') .expect('Content-Type', /json/) .expect(200, [ { name : "Euge" }, { name : "Bob" } ], done) it "works with a POST", (done) -> request(server) .post('/people') .send(name : "Bob") .expect('Content-Type', /json/) .expect(200, name : "Bob", id : 10, done); it "works with a DELETE", (done) -> request(server) .del('/people/10') .expect('Content-Type', /json/) .expect(200, { }, done) it "works with a PUT", (done) -> request(server) .put('/people/10') .send(name : "NotBob") .expect('Content-Type', /json/) .expect(200, name : "NotBob", id : 10, done); describe "without a match", -> it "should get a 404", (done) -> request(server). get("/not_here"). expect(404, done)
162373
"use strict" request = require 'supertest' canned = require "../" expect = require("chai").expect describe "Actual canned responses", -> server = null before -> server = new canned("#{__dirname}/fixtures/responses.js").server describe "with a match", -> it "adds a default index route handler", (done) -> request(server) .get("/") .expect("Content-Type", /html/) .expect(200, /<html>\s*<body>/, done) it "works with a GET", (done) -> request(server) .get('/people') .expect('Content-Type', /json/) .expect(200, [ { name : "<NAME>" }, { name : "<NAME>" } ], done) it "works with a POST", (done) -> request(server) .post('/people') .send(name : "<NAME>") .expect('Content-Type', /json/) .expect(200, name : "<NAME>", id : 10, done); it "works with a DELETE", (done) -> request(server) .del('/people/10') .expect('Content-Type', /json/) .expect(200, { }, done) it "works with a PUT", (done) -> request(server) .put('/people/10') .send(name : "<NAME>") .expect('Content-Type', /json/) .expect(200, name : "<NAME>", id : 10, done); describe "without a match", -> it "should get a 404", (done) -> request(server). get("/not_here"). expect(404, done)
true
"use strict" request = require 'supertest' canned = require "../" expect = require("chai").expect describe "Actual canned responses", -> server = null before -> server = new canned("#{__dirname}/fixtures/responses.js").server describe "with a match", -> it "adds a default index route handler", (done) -> request(server) .get("/") .expect("Content-Type", /html/) .expect(200, /<html>\s*<body>/, done) it "works with a GET", (done) -> request(server) .get('/people') .expect('Content-Type', /json/) .expect(200, [ { name : "PI:NAME:<NAME>END_PI" }, { name : "PI:NAME:<NAME>END_PI" } ], done) it "works with a POST", (done) -> request(server) .post('/people') .send(name : "PI:NAME:<NAME>END_PI") .expect('Content-Type', /json/) .expect(200, name : "PI:NAME:<NAME>END_PI", id : 10, done); it "works with a DELETE", (done) -> request(server) .del('/people/10') .expect('Content-Type', /json/) .expect(200, { }, done) it "works with a PUT", (done) -> request(server) .put('/people/10') .send(name : "PI:NAME:<NAME>END_PI") .expect('Content-Type', /json/) .expect(200, name : "PI:NAME:<NAME>END_PI", id : 10, done); describe "without a match", -> it "should get a 404", (done) -> request(server). get("/not_here"). expect(404, done)
[ { "context": "ense\": \"MIT\",\n\t\"browsers\": true,\n\t\"author\": \"2018+ Reme Le Hane (reme.lehane@gmail.com) (https://www.remelehane.m", "end": 247, "score": 0.9998967051506042, "start": 235, "tag": "NAME", "value": "Reme Le Hane" }, { "context": "\"browsers\": true,\n\t\"author...
projectz.cson
RemeJuan/hoc-loader
1
{ "title": "React HOC Loader", "name": "react-hoc-loader", "homepage": "https://www.remelehane.me", "description": "HOC (Higher Order Component) Loader for Redux Containers", "license": "MIT", "browsers": true, "author": "2018+ Reme Le Hane (reme.lehane@gmail.com) (https://www.remelehane.me)", "repository": { "type": "git", "url": "https://github.com/RemeJuan/react-hoc-loader.git" }, "bugs": { "url": "https://github.com/RemeJuan/react-hoc-loader/issues" }, "badges": { "list": [ "nodeico", "---", "travisci", "npmversion", "npmdownloads", "githubfollow", "githubstar", "daviddm", ], "config": { "githubUsername": "RemeJuan" } } }
5141
{ "title": "React HOC Loader", "name": "react-hoc-loader", "homepage": "https://www.remelehane.me", "description": "HOC (Higher Order Component) Loader for Redux Containers", "license": "MIT", "browsers": true, "author": "2018+ <NAME> (<EMAIL>) (https://www.remelehane.me)", "repository": { "type": "git", "url": "https://github.com/RemeJuan/react-hoc-loader.git" }, "bugs": { "url": "https://github.com/RemeJuan/react-hoc-loader/issues" }, "badges": { "list": [ "nodeico", "---", "travisci", "npmversion", "npmdownloads", "githubfollow", "githubstar", "daviddm", ], "config": { "githubUsername": "RemeJuan" } } }
true
{ "title": "React HOC Loader", "name": "react-hoc-loader", "homepage": "https://www.remelehane.me", "description": "HOC (Higher Order Component) Loader for Redux Containers", "license": "MIT", "browsers": true, "author": "2018+ PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI) (https://www.remelehane.me)", "repository": { "type": "git", "url": "https://github.com/RemeJuan/react-hoc-loader.git" }, "bugs": { "url": "https://github.com/RemeJuan/react-hoc-loader/issues" }, "badges": { "list": [ "nodeico", "---", "travisci", "npmversion", "npmdownloads", "githubfollow", "githubstar", "daviddm", ], "config": { "githubUsername": "RemeJuan" } } }
[ { "context": "### Copyright (c) 2015 Magnus Leo. All rights reserved. ###\n\ncore = require('../mod", "end": 33, "score": 0.9998577237129211, "start": 23, "tag": "NAME", "value": "Magnus Leo" } ]
src/classes/Layer.coffee
magnusleo/Leo-Engine
1
### Copyright (c) 2015 Magnus Leo. All rights reserved. ### core = require('../modules/core') background = require('../modules/background') layers = require('../modules/layers') view = require('../modules/view') module.exports = class Layer constructor: (properties) -> # Layer::constructor # Defaults @spritesheet = '' # Name of the spritesheet file @chunks = [ chunkOffsetX: 0 chunkOffsetY: 0 colBoxes: [] # [tl1,tr1,bl1,br1, ... tln,trn,bln,brn] tileOffsetX: 0 # Number of tiles offset in X tileOffsetY: 0 # Number of tiles offset in Y tiles:[] # Tile sprite positions [x1,y1, ... xn, yn] -1 is nothing/transparent ] @isLooping = false @parallax = 1.0 # User defined properties for key, val of properties @[key] = val @spriteImg = layers.getImg @spritesheet layer = this @spriteImg.addEventListener 'load', -> if not layer.chunks return for chunk in layer.chunks chunk.redraw() return @layerNumTilesX = 0 for chunk, i in @chunks @chunks[i] = new Chunk(this, chunk) @layerNumTilesX += chunk.tiles.length + chunk.tileOffsetX draw: -> # Layer::draw if @isLooping chunk = @chunks[0] posX = view.posToPx(chunk.tileOffsetX + chunk.chunkOffsetX, 'x', @parallax) multiplier = ((view.cameraPosX / @layerNumTilesX * @parallax) >> 0) - 1 posX += @layerNumTilesX * background.tileSize * multiplier while posX < core.camW for chunk in @chunks posY = view.posToPx(chunk.tileOffsetY + chunk.chunkOffsetY, 'y') chunk.draw(posX, posY) posX += chunk.drawBuffer.width + chunk.tileOffsetXPx else for chunk in @chunks posX = view.posToPx(chunk.tileOffsetX + chunk.chunkOffsetX, 'x', @parallax) posY = view.posToPx(chunk.tileOffsetY + chunk.chunkOffsetY, 'y') chunk.draw(posX, posY) return getTile: (tileX, tileY, offsetX = 0, offsetY = 0) -> # Layer::getTile chunkNo = Math.floor((tileX + offsetX) / @chunks[0].width) if chunkNo < 0 or chunkNo > @chunks.length - 1 return -1 chunk = @chunks[chunkNo] x = tileX - chunk.tileOffsetX + offsetX - chunk.width * chunkNo y = tileY - chunk.tileOffsetY + offsetY if 0 > x > chunk.width or 0 > y > chunk.width return -1 return chunk.tiles[x + y * chunk.width] or -1 setTile: (tileX, tileY, tile) -> # Layer::setTile chunkNo = (tileX / @chunks[0].width) >> 0 chunk = @chunks[chunkNo] chunk.drawBufferDirty = true x = tileX - chunk.tileOffsetX - chunk.width * chunkNo y = tileY - chunk.tileOffsetY chunk.tiles[x + y * chunk.width] = tile serialize: -> # Layer::serialize # Data format: # {type}{length}{data}... data = '' for chunk in @chunks data += String.fromCharCode(core.DATA_TYPES.CHUNK) chunkData = chunk.serialize() data += String.fromCharCode(chunkData.length) + chunkData return data deserialize: (data) -> # Layer::deserialize chunkOffsetX = 0 @chunks.length = 0 t = core.DATA_TYPES i = 0 while i < data.length length = data.charCodeAt(i + 1) switch data.charCodeAt(i) when t.CHUNK #TODO: Store and read chunk metadata numChunks = @chunks.push new Chunk this, width: 30 height: 17 chunkOffsetX: chunkOffsetX chunkOffsetY: 0 tileOffsetX: 0 tileOffsetY: 13 @chunks[numChunks - 1].deserialize(data.substr(i + 2, length)) chunkOffsetX += 30 i += 2 + length class Chunk constructor: (layer, data) -> # Chunk::constructor @tiles = [] for name, datum of data this[name] = datum @layer = layer @drawBuffer = document.createElement 'canvas' @drawBufferCtx = @drawBuffer.getContext '2d' @drawBufferDirty = true @drawBuffer.width = @width * background.tileSize @drawBuffer.height = ((@tiles.length / @width) >> 0) * background.tileSize @tileOffsetXPx = @tileOffsetX * background.tileSize draw: (posX, posY) -> # Chunk::draw # Don't draw chunks out of view if posX < -@drawBuffer.width or posX > core.camW or posY < -@drawBuffer.height or posY > core.camH return if @drawBufferDirty # Redraw chunk @drawBufferCtx.clearRect(0, 0, @drawBuffer.width, @drawBuffer.height) for i in [0..@tiles.length] x = i % @width y = ((i / @width) >> 0) @drawTile @drawBufferCtx, @tiles[i], x * background.tileSize, (y + @chunkOffsetY) * background.tileSize, @drawBufferDirty = false core.frameBufferCtx.drawImage @drawBuffer, 0, # Source X 0, # Source Y @drawBuffer.width, # Source width @drawBuffer.height, # Source height posX, # Destionation X posY, # Destionation Y @drawBuffer.width, # Destination width @drawBuffer.height, # Destination height redraw: -> # Chunk::redraw @drawBufferDirty = true drawTile: (ctx, spriteN, posX, posY) -> # Chunk::drawTile if spriteN == -1 then return tileSize = background.tileSize spriteWidth = 16 spriteX = spriteN % spriteWidth #TODO: Make Sprite class with properties spriteY = (spriteN / spriteWidth) >> 0 #TODO: Make Sprite class with properties ctx.drawImage @layer.spriteImg, spriteX * tileSize, spriteY * tileSize, tileSize, # Source width tileSize, # Source height posX >> 0, posY >> 0, tileSize, # Destination width tileSize, # Destination height serialize: -> # Chunk::serialize data = '' for tile in @tiles data += String.fromCharCode(tile + 1) # +1 to make -1 -> 0. We can't store negative numbers. return data #TODO: Compress consecutive identical tiles deserialize: (data) -> # Chunk::deserialize @drawBufferDirty = true @tiles.length = 0 for i in [0..data.length] @tiles.push data.charCodeAt(i) - 1 # -1 to reverse +1 from Chunk::serialize @drawBuffer.height = ((@tiles.length / @width) >> 0) * background.tileSize
85002
### Copyright (c) 2015 <NAME>. All rights reserved. ### core = require('../modules/core') background = require('../modules/background') layers = require('../modules/layers') view = require('../modules/view') module.exports = class Layer constructor: (properties) -> # Layer::constructor # Defaults @spritesheet = '' # Name of the spritesheet file @chunks = [ chunkOffsetX: 0 chunkOffsetY: 0 colBoxes: [] # [tl1,tr1,bl1,br1, ... tln,trn,bln,brn] tileOffsetX: 0 # Number of tiles offset in X tileOffsetY: 0 # Number of tiles offset in Y tiles:[] # Tile sprite positions [x1,y1, ... xn, yn] -1 is nothing/transparent ] @isLooping = false @parallax = 1.0 # User defined properties for key, val of properties @[key] = val @spriteImg = layers.getImg @spritesheet layer = this @spriteImg.addEventListener 'load', -> if not layer.chunks return for chunk in layer.chunks chunk.redraw() return @layerNumTilesX = 0 for chunk, i in @chunks @chunks[i] = new Chunk(this, chunk) @layerNumTilesX += chunk.tiles.length + chunk.tileOffsetX draw: -> # Layer::draw if @isLooping chunk = @chunks[0] posX = view.posToPx(chunk.tileOffsetX + chunk.chunkOffsetX, 'x', @parallax) multiplier = ((view.cameraPosX / @layerNumTilesX * @parallax) >> 0) - 1 posX += @layerNumTilesX * background.tileSize * multiplier while posX < core.camW for chunk in @chunks posY = view.posToPx(chunk.tileOffsetY + chunk.chunkOffsetY, 'y') chunk.draw(posX, posY) posX += chunk.drawBuffer.width + chunk.tileOffsetXPx else for chunk in @chunks posX = view.posToPx(chunk.tileOffsetX + chunk.chunkOffsetX, 'x', @parallax) posY = view.posToPx(chunk.tileOffsetY + chunk.chunkOffsetY, 'y') chunk.draw(posX, posY) return getTile: (tileX, tileY, offsetX = 0, offsetY = 0) -> # Layer::getTile chunkNo = Math.floor((tileX + offsetX) / @chunks[0].width) if chunkNo < 0 or chunkNo > @chunks.length - 1 return -1 chunk = @chunks[chunkNo] x = tileX - chunk.tileOffsetX + offsetX - chunk.width * chunkNo y = tileY - chunk.tileOffsetY + offsetY if 0 > x > chunk.width or 0 > y > chunk.width return -1 return chunk.tiles[x + y * chunk.width] or -1 setTile: (tileX, tileY, tile) -> # Layer::setTile chunkNo = (tileX / @chunks[0].width) >> 0 chunk = @chunks[chunkNo] chunk.drawBufferDirty = true x = tileX - chunk.tileOffsetX - chunk.width * chunkNo y = tileY - chunk.tileOffsetY chunk.tiles[x + y * chunk.width] = tile serialize: -> # Layer::serialize # Data format: # {type}{length}{data}... data = '' for chunk in @chunks data += String.fromCharCode(core.DATA_TYPES.CHUNK) chunkData = chunk.serialize() data += String.fromCharCode(chunkData.length) + chunkData return data deserialize: (data) -> # Layer::deserialize chunkOffsetX = 0 @chunks.length = 0 t = core.DATA_TYPES i = 0 while i < data.length length = data.charCodeAt(i + 1) switch data.charCodeAt(i) when t.CHUNK #TODO: Store and read chunk metadata numChunks = @chunks.push new Chunk this, width: 30 height: 17 chunkOffsetX: chunkOffsetX chunkOffsetY: 0 tileOffsetX: 0 tileOffsetY: 13 @chunks[numChunks - 1].deserialize(data.substr(i + 2, length)) chunkOffsetX += 30 i += 2 + length class Chunk constructor: (layer, data) -> # Chunk::constructor @tiles = [] for name, datum of data this[name] = datum @layer = layer @drawBuffer = document.createElement 'canvas' @drawBufferCtx = @drawBuffer.getContext '2d' @drawBufferDirty = true @drawBuffer.width = @width * background.tileSize @drawBuffer.height = ((@tiles.length / @width) >> 0) * background.tileSize @tileOffsetXPx = @tileOffsetX * background.tileSize draw: (posX, posY) -> # Chunk::draw # Don't draw chunks out of view if posX < -@drawBuffer.width or posX > core.camW or posY < -@drawBuffer.height or posY > core.camH return if @drawBufferDirty # Redraw chunk @drawBufferCtx.clearRect(0, 0, @drawBuffer.width, @drawBuffer.height) for i in [0..@tiles.length] x = i % @width y = ((i / @width) >> 0) @drawTile @drawBufferCtx, @tiles[i], x * background.tileSize, (y + @chunkOffsetY) * background.tileSize, @drawBufferDirty = false core.frameBufferCtx.drawImage @drawBuffer, 0, # Source X 0, # Source Y @drawBuffer.width, # Source width @drawBuffer.height, # Source height posX, # Destionation X posY, # Destionation Y @drawBuffer.width, # Destination width @drawBuffer.height, # Destination height redraw: -> # Chunk::redraw @drawBufferDirty = true drawTile: (ctx, spriteN, posX, posY) -> # Chunk::drawTile if spriteN == -1 then return tileSize = background.tileSize spriteWidth = 16 spriteX = spriteN % spriteWidth #TODO: Make Sprite class with properties spriteY = (spriteN / spriteWidth) >> 0 #TODO: Make Sprite class with properties ctx.drawImage @layer.spriteImg, spriteX * tileSize, spriteY * tileSize, tileSize, # Source width tileSize, # Source height posX >> 0, posY >> 0, tileSize, # Destination width tileSize, # Destination height serialize: -> # Chunk::serialize data = '' for tile in @tiles data += String.fromCharCode(tile + 1) # +1 to make -1 -> 0. We can't store negative numbers. return data #TODO: Compress consecutive identical tiles deserialize: (data) -> # Chunk::deserialize @drawBufferDirty = true @tiles.length = 0 for i in [0..data.length] @tiles.push data.charCodeAt(i) - 1 # -1 to reverse +1 from Chunk::serialize @drawBuffer.height = ((@tiles.length / @width) >> 0) * background.tileSize
true
### Copyright (c) 2015 PI:NAME:<NAME>END_PI. All rights reserved. ### core = require('../modules/core') background = require('../modules/background') layers = require('../modules/layers') view = require('../modules/view') module.exports = class Layer constructor: (properties) -> # Layer::constructor # Defaults @spritesheet = '' # Name of the spritesheet file @chunks = [ chunkOffsetX: 0 chunkOffsetY: 0 colBoxes: [] # [tl1,tr1,bl1,br1, ... tln,trn,bln,brn] tileOffsetX: 0 # Number of tiles offset in X tileOffsetY: 0 # Number of tiles offset in Y tiles:[] # Tile sprite positions [x1,y1, ... xn, yn] -1 is nothing/transparent ] @isLooping = false @parallax = 1.0 # User defined properties for key, val of properties @[key] = val @spriteImg = layers.getImg @spritesheet layer = this @spriteImg.addEventListener 'load', -> if not layer.chunks return for chunk in layer.chunks chunk.redraw() return @layerNumTilesX = 0 for chunk, i in @chunks @chunks[i] = new Chunk(this, chunk) @layerNumTilesX += chunk.tiles.length + chunk.tileOffsetX draw: -> # Layer::draw if @isLooping chunk = @chunks[0] posX = view.posToPx(chunk.tileOffsetX + chunk.chunkOffsetX, 'x', @parallax) multiplier = ((view.cameraPosX / @layerNumTilesX * @parallax) >> 0) - 1 posX += @layerNumTilesX * background.tileSize * multiplier while posX < core.camW for chunk in @chunks posY = view.posToPx(chunk.tileOffsetY + chunk.chunkOffsetY, 'y') chunk.draw(posX, posY) posX += chunk.drawBuffer.width + chunk.tileOffsetXPx else for chunk in @chunks posX = view.posToPx(chunk.tileOffsetX + chunk.chunkOffsetX, 'x', @parallax) posY = view.posToPx(chunk.tileOffsetY + chunk.chunkOffsetY, 'y') chunk.draw(posX, posY) return getTile: (tileX, tileY, offsetX = 0, offsetY = 0) -> # Layer::getTile chunkNo = Math.floor((tileX + offsetX) / @chunks[0].width) if chunkNo < 0 or chunkNo > @chunks.length - 1 return -1 chunk = @chunks[chunkNo] x = tileX - chunk.tileOffsetX + offsetX - chunk.width * chunkNo y = tileY - chunk.tileOffsetY + offsetY if 0 > x > chunk.width or 0 > y > chunk.width return -1 return chunk.tiles[x + y * chunk.width] or -1 setTile: (tileX, tileY, tile) -> # Layer::setTile chunkNo = (tileX / @chunks[0].width) >> 0 chunk = @chunks[chunkNo] chunk.drawBufferDirty = true x = tileX - chunk.tileOffsetX - chunk.width * chunkNo y = tileY - chunk.tileOffsetY chunk.tiles[x + y * chunk.width] = tile serialize: -> # Layer::serialize # Data format: # {type}{length}{data}... data = '' for chunk in @chunks data += String.fromCharCode(core.DATA_TYPES.CHUNK) chunkData = chunk.serialize() data += String.fromCharCode(chunkData.length) + chunkData return data deserialize: (data) -> # Layer::deserialize chunkOffsetX = 0 @chunks.length = 0 t = core.DATA_TYPES i = 0 while i < data.length length = data.charCodeAt(i + 1) switch data.charCodeAt(i) when t.CHUNK #TODO: Store and read chunk metadata numChunks = @chunks.push new Chunk this, width: 30 height: 17 chunkOffsetX: chunkOffsetX chunkOffsetY: 0 tileOffsetX: 0 tileOffsetY: 13 @chunks[numChunks - 1].deserialize(data.substr(i + 2, length)) chunkOffsetX += 30 i += 2 + length class Chunk constructor: (layer, data) -> # Chunk::constructor @tiles = [] for name, datum of data this[name] = datum @layer = layer @drawBuffer = document.createElement 'canvas' @drawBufferCtx = @drawBuffer.getContext '2d' @drawBufferDirty = true @drawBuffer.width = @width * background.tileSize @drawBuffer.height = ((@tiles.length / @width) >> 0) * background.tileSize @tileOffsetXPx = @tileOffsetX * background.tileSize draw: (posX, posY) -> # Chunk::draw # Don't draw chunks out of view if posX < -@drawBuffer.width or posX > core.camW or posY < -@drawBuffer.height or posY > core.camH return if @drawBufferDirty # Redraw chunk @drawBufferCtx.clearRect(0, 0, @drawBuffer.width, @drawBuffer.height) for i in [0..@tiles.length] x = i % @width y = ((i / @width) >> 0) @drawTile @drawBufferCtx, @tiles[i], x * background.tileSize, (y + @chunkOffsetY) * background.tileSize, @drawBufferDirty = false core.frameBufferCtx.drawImage @drawBuffer, 0, # Source X 0, # Source Y @drawBuffer.width, # Source width @drawBuffer.height, # Source height posX, # Destionation X posY, # Destionation Y @drawBuffer.width, # Destination width @drawBuffer.height, # Destination height redraw: -> # Chunk::redraw @drawBufferDirty = true drawTile: (ctx, spriteN, posX, posY) -> # Chunk::drawTile if spriteN == -1 then return tileSize = background.tileSize spriteWidth = 16 spriteX = spriteN % spriteWidth #TODO: Make Sprite class with properties spriteY = (spriteN / spriteWidth) >> 0 #TODO: Make Sprite class with properties ctx.drawImage @layer.spriteImg, spriteX * tileSize, spriteY * tileSize, tileSize, # Source width tileSize, # Source height posX >> 0, posY >> 0, tileSize, # Destination width tileSize, # Destination height serialize: -> # Chunk::serialize data = '' for tile in @tiles data += String.fromCharCode(tile + 1) # +1 to make -1 -> 0. We can't store negative numbers. return data #TODO: Compress consecutive identical tiles deserialize: (data) -> # Chunk::deserialize @drawBufferDirty = true @tiles.length = 0 for i in [0..data.length] @tiles.push data.charCodeAt(i) - 1 # -1 to reverse +1 from Chunk::serialize @drawBuffer.height = ((@tiles.length / @width) >> 0) * background.tileSize
[ { "context": "y is nested', ->\n @controller.set 'routingKey', 'admin/products'\n @controller.dispatch 'show'\n view = ", "end": 2036, "score": 0.756446897983551, "start": 2031, "tag": "KEY", "value": "admin" } ]
tests/batman/controller/controller_test.coffee
amco/batman
0
helpers = window.viewHelpers oldApp = Batman.currentApp oldHTMLStore = Batman.View.store oldNavigator = Batman.navigator QUnit.module 'Batman.Controller', setup: -> class TestController extends Batman.Controller show: -> Batman.currentApp = Batman(layout: new Batman.View(node: document.createElement('div'))) Batman.View.store.set('foo', "<div>show</div>") Batman.View.store.set('test/show', "<div>show</div>") Batman.View.store.set('products/show', "<div>show</div>") Batman.View.store.set('admin/products/show', "<div>show</div>") Batman.config.cacheViews = true @controller = new TestController @controller.renderCache.reset() Batman.DOM.Yield.reset() teardown: -> Batman.config.cacheViews = false Batman.currentApp = oldApp Batman.navigator = oldNavigator Batman.View.store = oldHTMLStore test 'get(\'routingKey\') should use the prototype level routingKey property', -> class ProductsController extends Batman.Controller routingKey: 'products' equal (new ProductsController).get('routingKey'), 'products' test 'it should render a Batman.View if `view` isn\'t given in the options to render', -> @controller.dispatch('show') equal Batman.currentApp.layout.subviews.length, 1 newView = Batman.currentApp.layout.subviews.get('first') ok newView.isBound test 'it should cache the rendered Batman.View if `view` isn\'t given in the options to render', -> @controller.dispatch('show') view = Batman.currentApp.layout.subviews.get('first') @controller.dispatch('show') equal Batman.currentApp.layout.subviews.get('first')._batmanID(), view._batmanID() test 'it should render a Batman.View subclass with the ControllerAction name on the current app if it exists', -> @controller.dispatch 'show' view = Batman.currentApp.layout.subviews.get('first') equal view.source, 'test/show' test 'it should render a Batman.View subclass with the ControllerAction name if the routing key is nested', -> @controller.set 'routingKey', 'admin/products' @controller.dispatch 'show' view = Batman.currentApp.layout.subviews.get('first') equal view.source, 'admin/products/show' test 'it should cache the rendered Batman.Views if rendered from different action', -> @controller.actionA = -> @render source: 'foo' @controller.actionB = -> @render source: 'foo' @controller.dispatch 'actionA' view = Batman.currentApp.layout.subviews.get('first') @controller.dispatch 'actionB' equal Batman.currentApp.layout.subviews.get('first')._batmanID(), view._batmanID() asyncTest 'it should cache the rendered Batman.Views if rendered from different actions into different yields', -> mainContainer = $('<div>')[0] detailContainer = $('<div>')[0] Batman.DOM.Yield.withName('main').set('containerNode', mainContainer) Batman.DOM.Yield.withName('detail').set('containerNode', detailContainer) @controller.index = -> @render(html: 'foo', into: 'main', source: 'a') @controller.show = -> @index() @render(html: 'bar', into: 'detail', source: 'b') @controller.dispatch 'index' delay => mainView = Batman._data(mainContainer.childNodes[0], 'view') @controller.dispatch 'show' delay -> equal Batman._data(mainContainer.childNodes[0], 'view'), mainView, "The same view was used in the second dispatch" test 'it should render views if given in the options', -> view = new Batman.View @controller.render({view}) equal Batman.currentApp.layout.subviews.get('first'), view test 'it should load the HTML from the default location', -> class TestShowView extends Batman.View Batman.currentApp["TestShowView"] = TestShowView @controller.dispatch('show') equal @controller.currentView.source, 'test/show' test 'it should load the HTML from the override location on the view prototype', -> class TestShowView extends Batman.View source: 'override/source' Batman.currentApp["TestShowView"] = TestShowView @controller.dispatch('show') equal @controller.currentView.source, 'override/source' test 'it should allow setting the default render destination yield', -> view = new Batman.View @controller.defaultRenderYield = 'sidebar' @controller.render({view}) equal Batman.currentApp.layout.subviews.get('first'), view equal Batman.DOM.Yield.withName('sidebar').get('contentView'), view test 'dispatching routes without any actions calls render', -> @controller.test = -> @controller.render = -> ok true, 'render called' @controller.dispatch 'test' test '@render false disables implicit render', 2, -> @controller.test = -> ok true, 'action called' @render false spyOnDuring Batman.DOM, 'replace', (replace) => @controller.dispatch 'test' ok ! replace.called test 'redirecting using @redirect() in an action prevents implicit render', -> Batman.navigator = {redirect: createSpy()} @controller.test = -> @redirect '/' @controller.dispatch 'test' equal Batman.currentApp.layout.subviews.length, 0 ok Batman.navigator.redirect.called test 'redirecting using Batman.redirect in an action prevents implicit render', -> Batman.navigator = {redirect: createSpy()} @controller.test = -> Batman.redirect '/' @controller.dispatch 'test' equal Batman.currentApp.layout.subviews.length, 0 ok Batman.navigator.redirect.called test '@redirect-ing after a dispatch fires no warnings', -> Batman.navigator = {redirect: createSpy()} @controller.test = -> @render false @controller.dispatch 'test' @controller.redirect '/' ok Batman.navigator.redirect.called test 'filters specifying no restrictions should be called on all actions', -> spy = createSpy() class FilterController extends Batman.Controller @beforeAction spy index: -> @render(false) show: -> @render(false) controller = new FilterController controller.dispatch('index') equal spy.callCount, 1 controller.dispatch('show') equal spy.callCount, 2 test 'filters specified with strings should work the same way', -> spy = createSpy() class FilterController extends Batman.Controller @beforeAction 'callSpy' index: -> @render(false) show: -> @render(false) callSpy: -> spy() controller = new FilterController controller.dispatch('index') equal spy.callCount, 1 controller.dispatch('show') equal spy.callCount, 2 test 'filters specified on instances should only work on that instance', -> spy = createSpy() class FilterController extends Batman.Controller index: -> @render(false) controller = new FilterController controller.beforeAction(spy) controller.dispatch('index') equal(spy.callCount, 1) test 'filters specifying only should only be called on those actions', -> spy = createSpy() class FilterController extends Batman.Controller @beforeAction only: 'withBefore', spy withBefore: -> @render false all: -> @render false controller = new FilterController controller.dispatch('withBefore') equal spy.callCount, 1 controller.dispatch('all') equal spy.callCount, 1 test 'filters specified with strings and only (in either order) should only be called on those actions', -> firstSpy = createSpy() secondSpy = createSpy() class FilterController extends Batman.Controller @beforeAction only: 'first', 'callFirstSpy' @beforeAction 'callSecondSpy', only: 'second' first: -> @render(false) second: -> @render(false) callFirstSpy: -> firstSpy() callSecondSpy: -> secondSpy() controller = new FilterController controller.dispatch('first') equal firstSpy.callCount, 1 controller.dispatch('second') equal secondSpy.callCount, 1 test 'filters specifying except should not be called on those actions', -> spy = createSpy() class FilterController extends Batman.Controller @beforeAction {except: 'index'}, spy show: -> @render false index: -> @render false controller = new FilterController controller.dispatch 'show' equal spy.callCount, 1 controller.dispatch 'index' equal spy.callCount, 1 test 'filters specifying options in arrays should apply to all/none of those options', -> spy = createSpy() class FilterController extends Batman.Controller @beforeAction {except: ['index', 'edit']}, spy show: -> @render false index: -> @render false edit: -> @render false controller = new FilterController controller.dispatch 'edit' equal spy.callCount, 0 controller.dispatch 'show' equal spy.callCount, 1 controller.dispatch 'index' equal spy.callCount, 1 test 'redirect() in beforeFilter halts chain and does not call action or render', -> beforeSpy1 = createSpy() beforeSpy2 = createSpy() renderSpy = createSpy() afterSpy = createSpy() class FilterController extends Batman.Controller @beforeAction beforeSpy1 @beforeAction -> @redirect('/') @beforeAction beforeSpy2 @afterAction afterSpy render: renderSpy index: -> @render(false) controller = new FilterController controller.dispatch('index') equal beforeSpy1.callCount, 1 equal beforeSpy2.callCount, 0 equal renderSpy.callCount, 0 equal afterSpy.callCount, 0 test 'actions executed by other actions implicitly render', -> @controller.test = -> @render false @executeAction 'show' @controller.dispatch 'test' view = Batman.currentApp.layout.subviews.get('first') equal view.source, 'test/show', "The action is correctly different inside the inner execution" test 'actions executed by other actions have their filters run', -> beforeSpy = createSpy() afterSpy = createSpy() class TestController extends Batman.Controller @beforeAction {only: 'show'}, beforeSpy @afterAction {only: 'show'}, afterSpy show: -> @render(false) test: -> @render(false) @executeAction('show') @controller = new TestController @controller.dispatch('test') ok beforeSpy.called ok afterSpy.called test 'beforeActions and afterActions are inherited when subclassing controllers', -> beforeSpy1 = createSpy() beforeSpy2 = createSpy() afterSpy1 = createSpy() afterSpy2 = createSpy() class TestParentController extends Batman.Controller @beforeAction beforeSpy1 @beforeAction {only: 'show'}, beforeSpy2 @afterAction afterSpy1 @afterAction {only: 'show'}, afterSpy2 show: -> @render false beforeSpy3 = createSpy() beforeSpy4 = createSpy() afterSpy3 = createSpy() afterSpy4 = createSpy() class TestChildController extends TestParentController @beforeAction beforeSpy3 @beforeAction {only: 'show'}, beforeSpy4 @afterAction afterSpy3 @afterAction {only: 'show'}, afterSpy4 controller = new TestChildController controller.dispatch 'show' equal beforeSpy1.callCount, 1 equal beforeSpy2.callCount, 1 equal beforeSpy3.callCount, 1 equal beforeSpy4.callCount, 1 equal afterSpy1.callCount, 1 equal afterSpy2.callCount, 1 equal afterSpy3.callCount, 1 equal afterSpy4.callCount, 1 test 'afterActions should only fire after renders are complete', -> afterSpy = createSpy() view = new Batman.View class TestController extends Batman.Controller @afterAction {only: 'show'}, afterSpy show: -> @render(view: view) @controller = new TestController view.prevent('viewDidAppear') @controller.dispatch('show') ok !afterSpy.called view.allowAndFire('viewDidAppear') ok afterSpy.called test 'afterActions on outer actions should fire after afterActions on inner actions', -> order = [] class TestController extends Batman.Controller @afterAction {only: 'show'}, -> order.push 1 @afterAction {only: 'test'}, -> order.push 2 show: -> @render(false) test: -> @render(false) @executeAction('show') @controller = new TestController @controller.dispatch('test') deepEqual order, [1, 2] test 'afterActions on outer actions should only fire after inner renders are complete', -> afterSpy = createSpy() view = new Batman.View class TestController extends Batman.Controller @afterAction {only: 'test'}, afterSpy show: -> @render(view: view) test: -> @render false @executeAction 'show' @controller = new TestController view.prevent('viewDidAppear') @controller.dispatch('test') ok !afterSpy.called view.allowAndFire('viewDidAppear') ok afterSpy.called test 'dispatching params with a hash scrolls to that hash', -> @controller.show = -> @render false spyOnDuring Batman.DOM, 'scrollIntoView', (spy) => spy.fixedReturn = true @controller.dispatch 'show', {'#': 'foo'} deepEqual spy.lastCallArguments, ['foo'] test 'dispatching params with a hash does not scroll to that hash if autoScrollToHash is false', -> @controller.autoScrollToHash = false @controller.show = -> @render false spyOnDuring Batman.DOM, 'scrollIntoView', (spy) => spy.fixedReturn = true @controller.dispatch 'show', {'#': 'foo'} ok !spy.called QUnit.module 'Batman.Controller error handling', setup: -> class @CustomError extends Batman.Object class @CustomError2 extends Batman.Object @error = error = new @CustomError @error2 = error2 = new @CustomError2 class @Model extends Batman.Object @load: (callback) -> callback(error, undefined) @load2: (callback) -> callback(error2, undefined) class @TestController extends Batman.Controller _customErrorHandler: (err) -> _customErrorHandler2: (err) -> test 'When wrapping a call with the errorHandler callback, any exception tracked with catchError will be handled by a single handler', 3, -> callbackSpy = createSpy() handlerSpy = createSpy() @TestController::_customErrorHandler = handlerSpy @TestController.catchError @CustomError, with: @TestController::_customErrorHandler namespace = @ controller = new @TestController controller.index = -> namespace.Model.load @errorHandler callbackSpy @render false controller.dispatch('index') equal callbackSpy.callCount, 0 equal handlerSpy.callCount, 1 deepEqual handlerSpy.lastCallArguments, [@error] test 'when wrapping a call with the errorHandler callback, any exception tracked with catchError will be handled by multiple handlers', -> callbackSpy = createSpy() handlerSpy = createSpy() handlerSpy2 = createSpy() @TestController::_customErrorHandler = handlerSpy @TestController::_customErrorHandler2 = handlerSpy2 @TestController.catchError @CustomError, with: [@TestController::_customErrorHandler, @TestController::_customErrorHandler2] namespace = @ controller = new @TestController controller.index = -> namespace.Model.load @errorHandler callbackSpy @render false controller.dispatch('index') equal callbackSpy.callCount, 0 equal handlerSpy.callCount, 1 equal handlerSpy2.callCount, 1 deepEqual handlerSpy.lastCallArguments, [@error] deepEqual handlerSpy2.lastCallArguments, [@error] test 'when wrapping a call with the errorHandler callback, any exception that is not tracked with specific catchError will be re-thrown', -> callbackSpy = createSpy() handlerSpy = createSpy() @TestController::_customErrorHandler = handlerSpy @TestController.catchError @CustomError, with: @TestController::_customErrorHandler @Model.load = (callback) -> callback(new Error, undefined) namespace = @ controller = new @TestController controller.index = -> namespace.Model.load @errorHandler callbackSpy @render false raises -> controller.dispatch('index') , Error equal callbackSpy.callCount, 0 equal handlerSpy.callCount, 0 test 'when wrapping a call with the errorHandler callback, no exception passes result to callback', -> callbackSpy = createSpy() handlerSpy = createSpy() @TestController::_customErrorHandler = handlerSpy @TestController.catchError @CustomError, with: @TestController::_customErrorHandler @Model.load = (callback) -> callback(undefined, [{id: 1}], 'foo') namespace = @ controller = new @TestController controller.index = -> namespace.Model.load @errorHandler callbackSpy @render false controller.dispatch('index') equal handlerSpy.callCount, 0 equal callbackSpy.callCount, 1 deepEqual callbackSpy.lastCallArguments, [[{id: 1}], 'foo'] test 'subclass errors registered with superclass catchError cause the errorHandler callback to fire', -> class ReallyCustomError extends @CustomError callbackSpy = createSpy() handlerSpy = createSpy() error = new ReallyCustomError @TestController::_customErrorHandler = handlerSpy @TestController.catchError @CustomError, with: @TestController::_customErrorHandler @Model.load = (callback) -> callback(error, undefined) namespace = @ controller = new @TestController controller.index = -> namespace.Model.load @errorHandler callbackSpy @render false controller.dispatch('index') equal callbackSpy.callCount, 0 equal handlerSpy.callCount, 1 deepEqual handlerSpy.lastCallArguments, [error] test 'When wrapping a call with the errorHandler callback, parent class handlers are also called', -> callbackSpy = createSpy() handlerSpy = createSpy() handlerSpy2 = createSpy() handlerSpy3 = createSpy() @TestController::_customErrorHandler = handlerSpy @TestController::_customErrorHandler2 = handlerSpy2 @TestController.catchError @CustomError, with: [@TestController::_customErrorHandler, @TestController::_customErrorHandler2] namespace = @ class SubclassController extends @TestController _customErrorHandler3: handlerSpy3 _customErrorHandler2: handlerSpy2 @catchError namespace.CustomError, with: @::_customErrorHandler3 namespace = @ controller = new SubclassController controller.index = -> namespace.Model.load @errorHandler callbackSpy @render false controller.dispatch('index') equal callbackSpy.callCount, 0 equal handlerSpy.callCount, 1 equal handlerSpy2.callCount, 1 equal handlerSpy3.callCount, 1 deepEqual handlerSpy.lastCallArguments, [@error] deepEqual handlerSpy2.lastCallArguments, [@error] deepEqual handlerSpy3.lastCallArguments, [@error] test 'When wrapping multiple calls with errorHandler callback, any successive calls to the errorHandler should be ignored if an error occured on the current frame', -> callbackSpy = createSpy() handlerSpy = createSpy() handlerSpy2 = createSpy() @TestController::_customErrorHandler = handlerSpy @TestController::_customErrorHandler2 = handlerSpy2 @TestController.catchError @CustomError, with: [@TestController::_customErrorHandler] @TestController.catchError @CustomError2, with: [@TestController::_customErrorHandler2] namespace = @ controller = new @TestController controller.index = -> namespace.Model.load @errorHandler callbackSpy namespace.Model.load2 @errorHandler callbackSpy @render false controller.dispatch('index') equal handlerSpy.callCount, 1 equal handlerSpy2.callCount, 0 equal callbackSpy.callCount, 0 deepEqual handlerSpy.lastCallArguments, [@error] test 'When wrapping multiple nested calls with errorHandler callback, nested errors should not be fired if parent errored', -> callbackSpy = createSpy() handlerSpy = createSpy() handlerSpy2 = createSpy() @TestController::_customErrorHandler = handlerSpy @TestController::_customErrorHandler2 = handlerSpy2 @TestController.catchError @CustomError, with: [@TestController::_customErrorHandler] @TestController.catchError @CustomError2, with: [@TestController::_customErrorHandler2] namespace = @ controller = new @TestController controller.index = -> namespace.Model.load @errorHandler -> namespace.Model.load2 @errorHandler callbackSpy ok false # should not be called @render false controller.dispatch('index') equal handlerSpy.callCount, 1 equal handlerSpy2.callCount, 0 equal callbackSpy.callCount, 0 deepEqual handlerSpy.lastCallArguments, [@error] test 'When wrapping multiple nested calls with errorHandler callback, nested errors not be ignored by higher level errors', -> callbackSpy = createSpy() handlerSpy = createSpy() handlerSpy2 = createSpy() @TestController::_customErrorHandler = handlerSpy @TestController::_customErrorHandler2 = handlerSpy2 @TestController.catchError @CustomError, with: [@TestController::_customErrorHandler] @TestController.catchError @CustomError2, with: [@TestController::_customErrorHandler2] namespace = @ @Model.load = (callback) -> callback(undefined, [{id: 1}], 'foo') @Model.load3 = (callback) -> callback(namespace.error, undefined) controller = new @TestController controller.index = -> controllerNamespace = @ namespace.Model.load @errorHandler => ok true namespace.Model.load2 @errorHandler callbackSpy namespace.Model.load3 @errorHandler callbackSpy @render false controller.dispatch('index') equal handlerSpy.callCount, 0 equal handlerSpy2.callCount, 1 equal callbackSpy.callCount, 0 deepEqual handlerSpy2.lastCallArguments, [@error2] test 'Calling handlerError directly with an error should result in the handlers being called', -> handlerSpy = createSpy() handlerSpy2 = createSpy() @TestController::_customErrorHandler = handlerSpy @TestController.catchError @CustomError, with: [@TestController::_customErrorHandler] controller = new @TestController equal controller.handleError(@error), true equal controller.handleError(@error2), false equal handlerSpy.callCount, 1 equal handlerSpy2.callCount, 0 deepEqual handlerSpy.lastCallArguments, [@error]
178491
helpers = window.viewHelpers oldApp = Batman.currentApp oldHTMLStore = Batman.View.store oldNavigator = Batman.navigator QUnit.module 'Batman.Controller', setup: -> class TestController extends Batman.Controller show: -> Batman.currentApp = Batman(layout: new Batman.View(node: document.createElement('div'))) Batman.View.store.set('foo', "<div>show</div>") Batman.View.store.set('test/show', "<div>show</div>") Batman.View.store.set('products/show', "<div>show</div>") Batman.View.store.set('admin/products/show', "<div>show</div>") Batman.config.cacheViews = true @controller = new TestController @controller.renderCache.reset() Batman.DOM.Yield.reset() teardown: -> Batman.config.cacheViews = false Batman.currentApp = oldApp Batman.navigator = oldNavigator Batman.View.store = oldHTMLStore test 'get(\'routingKey\') should use the prototype level routingKey property', -> class ProductsController extends Batman.Controller routingKey: 'products' equal (new ProductsController).get('routingKey'), 'products' test 'it should render a Batman.View if `view` isn\'t given in the options to render', -> @controller.dispatch('show') equal Batman.currentApp.layout.subviews.length, 1 newView = Batman.currentApp.layout.subviews.get('first') ok newView.isBound test 'it should cache the rendered Batman.View if `view` isn\'t given in the options to render', -> @controller.dispatch('show') view = Batman.currentApp.layout.subviews.get('first') @controller.dispatch('show') equal Batman.currentApp.layout.subviews.get('first')._batmanID(), view._batmanID() test 'it should render a Batman.View subclass with the ControllerAction name on the current app if it exists', -> @controller.dispatch 'show' view = Batman.currentApp.layout.subviews.get('first') equal view.source, 'test/show' test 'it should render a Batman.View subclass with the ControllerAction name if the routing key is nested', -> @controller.set 'routingKey', '<KEY>/products' @controller.dispatch 'show' view = Batman.currentApp.layout.subviews.get('first') equal view.source, 'admin/products/show' test 'it should cache the rendered Batman.Views if rendered from different action', -> @controller.actionA = -> @render source: 'foo' @controller.actionB = -> @render source: 'foo' @controller.dispatch 'actionA' view = Batman.currentApp.layout.subviews.get('first') @controller.dispatch 'actionB' equal Batman.currentApp.layout.subviews.get('first')._batmanID(), view._batmanID() asyncTest 'it should cache the rendered Batman.Views if rendered from different actions into different yields', -> mainContainer = $('<div>')[0] detailContainer = $('<div>')[0] Batman.DOM.Yield.withName('main').set('containerNode', mainContainer) Batman.DOM.Yield.withName('detail').set('containerNode', detailContainer) @controller.index = -> @render(html: 'foo', into: 'main', source: 'a') @controller.show = -> @index() @render(html: 'bar', into: 'detail', source: 'b') @controller.dispatch 'index' delay => mainView = Batman._data(mainContainer.childNodes[0], 'view') @controller.dispatch 'show' delay -> equal Batman._data(mainContainer.childNodes[0], 'view'), mainView, "The same view was used in the second dispatch" test 'it should render views if given in the options', -> view = new Batman.View @controller.render({view}) equal Batman.currentApp.layout.subviews.get('first'), view test 'it should load the HTML from the default location', -> class TestShowView extends Batman.View Batman.currentApp["TestShowView"] = TestShowView @controller.dispatch('show') equal @controller.currentView.source, 'test/show' test 'it should load the HTML from the override location on the view prototype', -> class TestShowView extends Batman.View source: 'override/source' Batman.currentApp["TestShowView"] = TestShowView @controller.dispatch('show') equal @controller.currentView.source, 'override/source' test 'it should allow setting the default render destination yield', -> view = new Batman.View @controller.defaultRenderYield = 'sidebar' @controller.render({view}) equal Batman.currentApp.layout.subviews.get('first'), view equal Batman.DOM.Yield.withName('sidebar').get('contentView'), view test 'dispatching routes without any actions calls render', -> @controller.test = -> @controller.render = -> ok true, 'render called' @controller.dispatch 'test' test '@render false disables implicit render', 2, -> @controller.test = -> ok true, 'action called' @render false spyOnDuring Batman.DOM, 'replace', (replace) => @controller.dispatch 'test' ok ! replace.called test 'redirecting using @redirect() in an action prevents implicit render', -> Batman.navigator = {redirect: createSpy()} @controller.test = -> @redirect '/' @controller.dispatch 'test' equal Batman.currentApp.layout.subviews.length, 0 ok Batman.navigator.redirect.called test 'redirecting using Batman.redirect in an action prevents implicit render', -> Batman.navigator = {redirect: createSpy()} @controller.test = -> Batman.redirect '/' @controller.dispatch 'test' equal Batman.currentApp.layout.subviews.length, 0 ok Batman.navigator.redirect.called test '@redirect-ing after a dispatch fires no warnings', -> Batman.navigator = {redirect: createSpy()} @controller.test = -> @render false @controller.dispatch 'test' @controller.redirect '/' ok Batman.navigator.redirect.called test 'filters specifying no restrictions should be called on all actions', -> spy = createSpy() class FilterController extends Batman.Controller @beforeAction spy index: -> @render(false) show: -> @render(false) controller = new FilterController controller.dispatch('index') equal spy.callCount, 1 controller.dispatch('show') equal spy.callCount, 2 test 'filters specified with strings should work the same way', -> spy = createSpy() class FilterController extends Batman.Controller @beforeAction 'callSpy' index: -> @render(false) show: -> @render(false) callSpy: -> spy() controller = new FilterController controller.dispatch('index') equal spy.callCount, 1 controller.dispatch('show') equal spy.callCount, 2 test 'filters specified on instances should only work on that instance', -> spy = createSpy() class FilterController extends Batman.Controller index: -> @render(false) controller = new FilterController controller.beforeAction(spy) controller.dispatch('index') equal(spy.callCount, 1) test 'filters specifying only should only be called on those actions', -> spy = createSpy() class FilterController extends Batman.Controller @beforeAction only: 'withBefore', spy withBefore: -> @render false all: -> @render false controller = new FilterController controller.dispatch('withBefore') equal spy.callCount, 1 controller.dispatch('all') equal spy.callCount, 1 test 'filters specified with strings and only (in either order) should only be called on those actions', -> firstSpy = createSpy() secondSpy = createSpy() class FilterController extends Batman.Controller @beforeAction only: 'first', 'callFirstSpy' @beforeAction 'callSecondSpy', only: 'second' first: -> @render(false) second: -> @render(false) callFirstSpy: -> firstSpy() callSecondSpy: -> secondSpy() controller = new FilterController controller.dispatch('first') equal firstSpy.callCount, 1 controller.dispatch('second') equal secondSpy.callCount, 1 test 'filters specifying except should not be called on those actions', -> spy = createSpy() class FilterController extends Batman.Controller @beforeAction {except: 'index'}, spy show: -> @render false index: -> @render false controller = new FilterController controller.dispatch 'show' equal spy.callCount, 1 controller.dispatch 'index' equal spy.callCount, 1 test 'filters specifying options in arrays should apply to all/none of those options', -> spy = createSpy() class FilterController extends Batman.Controller @beforeAction {except: ['index', 'edit']}, spy show: -> @render false index: -> @render false edit: -> @render false controller = new FilterController controller.dispatch 'edit' equal spy.callCount, 0 controller.dispatch 'show' equal spy.callCount, 1 controller.dispatch 'index' equal spy.callCount, 1 test 'redirect() in beforeFilter halts chain and does not call action or render', -> beforeSpy1 = createSpy() beforeSpy2 = createSpy() renderSpy = createSpy() afterSpy = createSpy() class FilterController extends Batman.Controller @beforeAction beforeSpy1 @beforeAction -> @redirect('/') @beforeAction beforeSpy2 @afterAction afterSpy render: renderSpy index: -> @render(false) controller = new FilterController controller.dispatch('index') equal beforeSpy1.callCount, 1 equal beforeSpy2.callCount, 0 equal renderSpy.callCount, 0 equal afterSpy.callCount, 0 test 'actions executed by other actions implicitly render', -> @controller.test = -> @render false @executeAction 'show' @controller.dispatch 'test' view = Batman.currentApp.layout.subviews.get('first') equal view.source, 'test/show', "The action is correctly different inside the inner execution" test 'actions executed by other actions have their filters run', -> beforeSpy = createSpy() afterSpy = createSpy() class TestController extends Batman.Controller @beforeAction {only: 'show'}, beforeSpy @afterAction {only: 'show'}, afterSpy show: -> @render(false) test: -> @render(false) @executeAction('show') @controller = new TestController @controller.dispatch('test') ok beforeSpy.called ok afterSpy.called test 'beforeActions and afterActions are inherited when subclassing controllers', -> beforeSpy1 = createSpy() beforeSpy2 = createSpy() afterSpy1 = createSpy() afterSpy2 = createSpy() class TestParentController extends Batman.Controller @beforeAction beforeSpy1 @beforeAction {only: 'show'}, beforeSpy2 @afterAction afterSpy1 @afterAction {only: 'show'}, afterSpy2 show: -> @render false beforeSpy3 = createSpy() beforeSpy4 = createSpy() afterSpy3 = createSpy() afterSpy4 = createSpy() class TestChildController extends TestParentController @beforeAction beforeSpy3 @beforeAction {only: 'show'}, beforeSpy4 @afterAction afterSpy3 @afterAction {only: 'show'}, afterSpy4 controller = new TestChildController controller.dispatch 'show' equal beforeSpy1.callCount, 1 equal beforeSpy2.callCount, 1 equal beforeSpy3.callCount, 1 equal beforeSpy4.callCount, 1 equal afterSpy1.callCount, 1 equal afterSpy2.callCount, 1 equal afterSpy3.callCount, 1 equal afterSpy4.callCount, 1 test 'afterActions should only fire after renders are complete', -> afterSpy = createSpy() view = new Batman.View class TestController extends Batman.Controller @afterAction {only: 'show'}, afterSpy show: -> @render(view: view) @controller = new TestController view.prevent('viewDidAppear') @controller.dispatch('show') ok !afterSpy.called view.allowAndFire('viewDidAppear') ok afterSpy.called test 'afterActions on outer actions should fire after afterActions on inner actions', -> order = [] class TestController extends Batman.Controller @afterAction {only: 'show'}, -> order.push 1 @afterAction {only: 'test'}, -> order.push 2 show: -> @render(false) test: -> @render(false) @executeAction('show') @controller = new TestController @controller.dispatch('test') deepEqual order, [1, 2] test 'afterActions on outer actions should only fire after inner renders are complete', -> afterSpy = createSpy() view = new Batman.View class TestController extends Batman.Controller @afterAction {only: 'test'}, afterSpy show: -> @render(view: view) test: -> @render false @executeAction 'show' @controller = new TestController view.prevent('viewDidAppear') @controller.dispatch('test') ok !afterSpy.called view.allowAndFire('viewDidAppear') ok afterSpy.called test 'dispatching params with a hash scrolls to that hash', -> @controller.show = -> @render false spyOnDuring Batman.DOM, 'scrollIntoView', (spy) => spy.fixedReturn = true @controller.dispatch 'show', {'#': 'foo'} deepEqual spy.lastCallArguments, ['foo'] test 'dispatching params with a hash does not scroll to that hash if autoScrollToHash is false', -> @controller.autoScrollToHash = false @controller.show = -> @render false spyOnDuring Batman.DOM, 'scrollIntoView', (spy) => spy.fixedReturn = true @controller.dispatch 'show', {'#': 'foo'} ok !spy.called QUnit.module 'Batman.Controller error handling', setup: -> class @CustomError extends Batman.Object class @CustomError2 extends Batman.Object @error = error = new @CustomError @error2 = error2 = new @CustomError2 class @Model extends Batman.Object @load: (callback) -> callback(error, undefined) @load2: (callback) -> callback(error2, undefined) class @TestController extends Batman.Controller _customErrorHandler: (err) -> _customErrorHandler2: (err) -> test 'When wrapping a call with the errorHandler callback, any exception tracked with catchError will be handled by a single handler', 3, -> callbackSpy = createSpy() handlerSpy = createSpy() @TestController::_customErrorHandler = handlerSpy @TestController.catchError @CustomError, with: @TestController::_customErrorHandler namespace = @ controller = new @TestController controller.index = -> namespace.Model.load @errorHandler callbackSpy @render false controller.dispatch('index') equal callbackSpy.callCount, 0 equal handlerSpy.callCount, 1 deepEqual handlerSpy.lastCallArguments, [@error] test 'when wrapping a call with the errorHandler callback, any exception tracked with catchError will be handled by multiple handlers', -> callbackSpy = createSpy() handlerSpy = createSpy() handlerSpy2 = createSpy() @TestController::_customErrorHandler = handlerSpy @TestController::_customErrorHandler2 = handlerSpy2 @TestController.catchError @CustomError, with: [@TestController::_customErrorHandler, @TestController::_customErrorHandler2] namespace = @ controller = new @TestController controller.index = -> namespace.Model.load @errorHandler callbackSpy @render false controller.dispatch('index') equal callbackSpy.callCount, 0 equal handlerSpy.callCount, 1 equal handlerSpy2.callCount, 1 deepEqual handlerSpy.lastCallArguments, [@error] deepEqual handlerSpy2.lastCallArguments, [@error] test 'when wrapping a call with the errorHandler callback, any exception that is not tracked with specific catchError will be re-thrown', -> callbackSpy = createSpy() handlerSpy = createSpy() @TestController::_customErrorHandler = handlerSpy @TestController.catchError @CustomError, with: @TestController::_customErrorHandler @Model.load = (callback) -> callback(new Error, undefined) namespace = @ controller = new @TestController controller.index = -> namespace.Model.load @errorHandler callbackSpy @render false raises -> controller.dispatch('index') , Error equal callbackSpy.callCount, 0 equal handlerSpy.callCount, 0 test 'when wrapping a call with the errorHandler callback, no exception passes result to callback', -> callbackSpy = createSpy() handlerSpy = createSpy() @TestController::_customErrorHandler = handlerSpy @TestController.catchError @CustomError, with: @TestController::_customErrorHandler @Model.load = (callback) -> callback(undefined, [{id: 1}], 'foo') namespace = @ controller = new @TestController controller.index = -> namespace.Model.load @errorHandler callbackSpy @render false controller.dispatch('index') equal handlerSpy.callCount, 0 equal callbackSpy.callCount, 1 deepEqual callbackSpy.lastCallArguments, [[{id: 1}], 'foo'] test 'subclass errors registered with superclass catchError cause the errorHandler callback to fire', -> class ReallyCustomError extends @CustomError callbackSpy = createSpy() handlerSpy = createSpy() error = new ReallyCustomError @TestController::_customErrorHandler = handlerSpy @TestController.catchError @CustomError, with: @TestController::_customErrorHandler @Model.load = (callback) -> callback(error, undefined) namespace = @ controller = new @TestController controller.index = -> namespace.Model.load @errorHandler callbackSpy @render false controller.dispatch('index') equal callbackSpy.callCount, 0 equal handlerSpy.callCount, 1 deepEqual handlerSpy.lastCallArguments, [error] test 'When wrapping a call with the errorHandler callback, parent class handlers are also called', -> callbackSpy = createSpy() handlerSpy = createSpy() handlerSpy2 = createSpy() handlerSpy3 = createSpy() @TestController::_customErrorHandler = handlerSpy @TestController::_customErrorHandler2 = handlerSpy2 @TestController.catchError @CustomError, with: [@TestController::_customErrorHandler, @TestController::_customErrorHandler2] namespace = @ class SubclassController extends @TestController _customErrorHandler3: handlerSpy3 _customErrorHandler2: handlerSpy2 @catchError namespace.CustomError, with: @::_customErrorHandler3 namespace = @ controller = new SubclassController controller.index = -> namespace.Model.load @errorHandler callbackSpy @render false controller.dispatch('index') equal callbackSpy.callCount, 0 equal handlerSpy.callCount, 1 equal handlerSpy2.callCount, 1 equal handlerSpy3.callCount, 1 deepEqual handlerSpy.lastCallArguments, [@error] deepEqual handlerSpy2.lastCallArguments, [@error] deepEqual handlerSpy3.lastCallArguments, [@error] test 'When wrapping multiple calls with errorHandler callback, any successive calls to the errorHandler should be ignored if an error occured on the current frame', -> callbackSpy = createSpy() handlerSpy = createSpy() handlerSpy2 = createSpy() @TestController::_customErrorHandler = handlerSpy @TestController::_customErrorHandler2 = handlerSpy2 @TestController.catchError @CustomError, with: [@TestController::_customErrorHandler] @TestController.catchError @CustomError2, with: [@TestController::_customErrorHandler2] namespace = @ controller = new @TestController controller.index = -> namespace.Model.load @errorHandler callbackSpy namespace.Model.load2 @errorHandler callbackSpy @render false controller.dispatch('index') equal handlerSpy.callCount, 1 equal handlerSpy2.callCount, 0 equal callbackSpy.callCount, 0 deepEqual handlerSpy.lastCallArguments, [@error] test 'When wrapping multiple nested calls with errorHandler callback, nested errors should not be fired if parent errored', -> callbackSpy = createSpy() handlerSpy = createSpy() handlerSpy2 = createSpy() @TestController::_customErrorHandler = handlerSpy @TestController::_customErrorHandler2 = handlerSpy2 @TestController.catchError @CustomError, with: [@TestController::_customErrorHandler] @TestController.catchError @CustomError2, with: [@TestController::_customErrorHandler2] namespace = @ controller = new @TestController controller.index = -> namespace.Model.load @errorHandler -> namespace.Model.load2 @errorHandler callbackSpy ok false # should not be called @render false controller.dispatch('index') equal handlerSpy.callCount, 1 equal handlerSpy2.callCount, 0 equal callbackSpy.callCount, 0 deepEqual handlerSpy.lastCallArguments, [@error] test 'When wrapping multiple nested calls with errorHandler callback, nested errors not be ignored by higher level errors', -> callbackSpy = createSpy() handlerSpy = createSpy() handlerSpy2 = createSpy() @TestController::_customErrorHandler = handlerSpy @TestController::_customErrorHandler2 = handlerSpy2 @TestController.catchError @CustomError, with: [@TestController::_customErrorHandler] @TestController.catchError @CustomError2, with: [@TestController::_customErrorHandler2] namespace = @ @Model.load = (callback) -> callback(undefined, [{id: 1}], 'foo') @Model.load3 = (callback) -> callback(namespace.error, undefined) controller = new @TestController controller.index = -> controllerNamespace = @ namespace.Model.load @errorHandler => ok true namespace.Model.load2 @errorHandler callbackSpy namespace.Model.load3 @errorHandler callbackSpy @render false controller.dispatch('index') equal handlerSpy.callCount, 0 equal handlerSpy2.callCount, 1 equal callbackSpy.callCount, 0 deepEqual handlerSpy2.lastCallArguments, [@error2] test 'Calling handlerError directly with an error should result in the handlers being called', -> handlerSpy = createSpy() handlerSpy2 = createSpy() @TestController::_customErrorHandler = handlerSpy @TestController.catchError @CustomError, with: [@TestController::_customErrorHandler] controller = new @TestController equal controller.handleError(@error), true equal controller.handleError(@error2), false equal handlerSpy.callCount, 1 equal handlerSpy2.callCount, 0 deepEqual handlerSpy.lastCallArguments, [@error]
true
helpers = window.viewHelpers oldApp = Batman.currentApp oldHTMLStore = Batman.View.store oldNavigator = Batman.navigator QUnit.module 'Batman.Controller', setup: -> class TestController extends Batman.Controller show: -> Batman.currentApp = Batman(layout: new Batman.View(node: document.createElement('div'))) Batman.View.store.set('foo', "<div>show</div>") Batman.View.store.set('test/show', "<div>show</div>") Batman.View.store.set('products/show', "<div>show</div>") Batman.View.store.set('admin/products/show', "<div>show</div>") Batman.config.cacheViews = true @controller = new TestController @controller.renderCache.reset() Batman.DOM.Yield.reset() teardown: -> Batman.config.cacheViews = false Batman.currentApp = oldApp Batman.navigator = oldNavigator Batman.View.store = oldHTMLStore test 'get(\'routingKey\') should use the prototype level routingKey property', -> class ProductsController extends Batman.Controller routingKey: 'products' equal (new ProductsController).get('routingKey'), 'products' test 'it should render a Batman.View if `view` isn\'t given in the options to render', -> @controller.dispatch('show') equal Batman.currentApp.layout.subviews.length, 1 newView = Batman.currentApp.layout.subviews.get('first') ok newView.isBound test 'it should cache the rendered Batman.View if `view` isn\'t given in the options to render', -> @controller.dispatch('show') view = Batman.currentApp.layout.subviews.get('first') @controller.dispatch('show') equal Batman.currentApp.layout.subviews.get('first')._batmanID(), view._batmanID() test 'it should render a Batman.View subclass with the ControllerAction name on the current app if it exists', -> @controller.dispatch 'show' view = Batman.currentApp.layout.subviews.get('first') equal view.source, 'test/show' test 'it should render a Batman.View subclass with the ControllerAction name if the routing key is nested', -> @controller.set 'routingKey', 'PI:KEY:<KEY>END_PI/products' @controller.dispatch 'show' view = Batman.currentApp.layout.subviews.get('first') equal view.source, 'admin/products/show' test 'it should cache the rendered Batman.Views if rendered from different action', -> @controller.actionA = -> @render source: 'foo' @controller.actionB = -> @render source: 'foo' @controller.dispatch 'actionA' view = Batman.currentApp.layout.subviews.get('first') @controller.dispatch 'actionB' equal Batman.currentApp.layout.subviews.get('first')._batmanID(), view._batmanID() asyncTest 'it should cache the rendered Batman.Views if rendered from different actions into different yields', -> mainContainer = $('<div>')[0] detailContainer = $('<div>')[0] Batman.DOM.Yield.withName('main').set('containerNode', mainContainer) Batman.DOM.Yield.withName('detail').set('containerNode', detailContainer) @controller.index = -> @render(html: 'foo', into: 'main', source: 'a') @controller.show = -> @index() @render(html: 'bar', into: 'detail', source: 'b') @controller.dispatch 'index' delay => mainView = Batman._data(mainContainer.childNodes[0], 'view') @controller.dispatch 'show' delay -> equal Batman._data(mainContainer.childNodes[0], 'view'), mainView, "The same view was used in the second dispatch" test 'it should render views if given in the options', -> view = new Batman.View @controller.render({view}) equal Batman.currentApp.layout.subviews.get('first'), view test 'it should load the HTML from the default location', -> class TestShowView extends Batman.View Batman.currentApp["TestShowView"] = TestShowView @controller.dispatch('show') equal @controller.currentView.source, 'test/show' test 'it should load the HTML from the override location on the view prototype', -> class TestShowView extends Batman.View source: 'override/source' Batman.currentApp["TestShowView"] = TestShowView @controller.dispatch('show') equal @controller.currentView.source, 'override/source' test 'it should allow setting the default render destination yield', -> view = new Batman.View @controller.defaultRenderYield = 'sidebar' @controller.render({view}) equal Batman.currentApp.layout.subviews.get('first'), view equal Batman.DOM.Yield.withName('sidebar').get('contentView'), view test 'dispatching routes without any actions calls render', -> @controller.test = -> @controller.render = -> ok true, 'render called' @controller.dispatch 'test' test '@render false disables implicit render', 2, -> @controller.test = -> ok true, 'action called' @render false spyOnDuring Batman.DOM, 'replace', (replace) => @controller.dispatch 'test' ok ! replace.called test 'redirecting using @redirect() in an action prevents implicit render', -> Batman.navigator = {redirect: createSpy()} @controller.test = -> @redirect '/' @controller.dispatch 'test' equal Batman.currentApp.layout.subviews.length, 0 ok Batman.navigator.redirect.called test 'redirecting using Batman.redirect in an action prevents implicit render', -> Batman.navigator = {redirect: createSpy()} @controller.test = -> Batman.redirect '/' @controller.dispatch 'test' equal Batman.currentApp.layout.subviews.length, 0 ok Batman.navigator.redirect.called test '@redirect-ing after a dispatch fires no warnings', -> Batman.navigator = {redirect: createSpy()} @controller.test = -> @render false @controller.dispatch 'test' @controller.redirect '/' ok Batman.navigator.redirect.called test 'filters specifying no restrictions should be called on all actions', -> spy = createSpy() class FilterController extends Batman.Controller @beforeAction spy index: -> @render(false) show: -> @render(false) controller = new FilterController controller.dispatch('index') equal spy.callCount, 1 controller.dispatch('show') equal spy.callCount, 2 test 'filters specified with strings should work the same way', -> spy = createSpy() class FilterController extends Batman.Controller @beforeAction 'callSpy' index: -> @render(false) show: -> @render(false) callSpy: -> spy() controller = new FilterController controller.dispatch('index') equal spy.callCount, 1 controller.dispatch('show') equal spy.callCount, 2 test 'filters specified on instances should only work on that instance', -> spy = createSpy() class FilterController extends Batman.Controller index: -> @render(false) controller = new FilterController controller.beforeAction(spy) controller.dispatch('index') equal(spy.callCount, 1) test 'filters specifying only should only be called on those actions', -> spy = createSpy() class FilterController extends Batman.Controller @beforeAction only: 'withBefore', spy withBefore: -> @render false all: -> @render false controller = new FilterController controller.dispatch('withBefore') equal spy.callCount, 1 controller.dispatch('all') equal spy.callCount, 1 test 'filters specified with strings and only (in either order) should only be called on those actions', -> firstSpy = createSpy() secondSpy = createSpy() class FilterController extends Batman.Controller @beforeAction only: 'first', 'callFirstSpy' @beforeAction 'callSecondSpy', only: 'second' first: -> @render(false) second: -> @render(false) callFirstSpy: -> firstSpy() callSecondSpy: -> secondSpy() controller = new FilterController controller.dispatch('first') equal firstSpy.callCount, 1 controller.dispatch('second') equal secondSpy.callCount, 1 test 'filters specifying except should not be called on those actions', -> spy = createSpy() class FilterController extends Batman.Controller @beforeAction {except: 'index'}, spy show: -> @render false index: -> @render false controller = new FilterController controller.dispatch 'show' equal spy.callCount, 1 controller.dispatch 'index' equal spy.callCount, 1 test 'filters specifying options in arrays should apply to all/none of those options', -> spy = createSpy() class FilterController extends Batman.Controller @beforeAction {except: ['index', 'edit']}, spy show: -> @render false index: -> @render false edit: -> @render false controller = new FilterController controller.dispatch 'edit' equal spy.callCount, 0 controller.dispatch 'show' equal spy.callCount, 1 controller.dispatch 'index' equal spy.callCount, 1 test 'redirect() in beforeFilter halts chain and does not call action or render', -> beforeSpy1 = createSpy() beforeSpy2 = createSpy() renderSpy = createSpy() afterSpy = createSpy() class FilterController extends Batman.Controller @beforeAction beforeSpy1 @beforeAction -> @redirect('/') @beforeAction beforeSpy2 @afterAction afterSpy render: renderSpy index: -> @render(false) controller = new FilterController controller.dispatch('index') equal beforeSpy1.callCount, 1 equal beforeSpy2.callCount, 0 equal renderSpy.callCount, 0 equal afterSpy.callCount, 0 test 'actions executed by other actions implicitly render', -> @controller.test = -> @render false @executeAction 'show' @controller.dispatch 'test' view = Batman.currentApp.layout.subviews.get('first') equal view.source, 'test/show', "The action is correctly different inside the inner execution" test 'actions executed by other actions have their filters run', -> beforeSpy = createSpy() afterSpy = createSpy() class TestController extends Batman.Controller @beforeAction {only: 'show'}, beforeSpy @afterAction {only: 'show'}, afterSpy show: -> @render(false) test: -> @render(false) @executeAction('show') @controller = new TestController @controller.dispatch('test') ok beforeSpy.called ok afterSpy.called test 'beforeActions and afterActions are inherited when subclassing controllers', -> beforeSpy1 = createSpy() beforeSpy2 = createSpy() afterSpy1 = createSpy() afterSpy2 = createSpy() class TestParentController extends Batman.Controller @beforeAction beforeSpy1 @beforeAction {only: 'show'}, beforeSpy2 @afterAction afterSpy1 @afterAction {only: 'show'}, afterSpy2 show: -> @render false beforeSpy3 = createSpy() beforeSpy4 = createSpy() afterSpy3 = createSpy() afterSpy4 = createSpy() class TestChildController extends TestParentController @beforeAction beforeSpy3 @beforeAction {only: 'show'}, beforeSpy4 @afterAction afterSpy3 @afterAction {only: 'show'}, afterSpy4 controller = new TestChildController controller.dispatch 'show' equal beforeSpy1.callCount, 1 equal beforeSpy2.callCount, 1 equal beforeSpy3.callCount, 1 equal beforeSpy4.callCount, 1 equal afterSpy1.callCount, 1 equal afterSpy2.callCount, 1 equal afterSpy3.callCount, 1 equal afterSpy4.callCount, 1 test 'afterActions should only fire after renders are complete', -> afterSpy = createSpy() view = new Batman.View class TestController extends Batman.Controller @afterAction {only: 'show'}, afterSpy show: -> @render(view: view) @controller = new TestController view.prevent('viewDidAppear') @controller.dispatch('show') ok !afterSpy.called view.allowAndFire('viewDidAppear') ok afterSpy.called test 'afterActions on outer actions should fire after afterActions on inner actions', -> order = [] class TestController extends Batman.Controller @afterAction {only: 'show'}, -> order.push 1 @afterAction {only: 'test'}, -> order.push 2 show: -> @render(false) test: -> @render(false) @executeAction('show') @controller = new TestController @controller.dispatch('test') deepEqual order, [1, 2] test 'afterActions on outer actions should only fire after inner renders are complete', -> afterSpy = createSpy() view = new Batman.View class TestController extends Batman.Controller @afterAction {only: 'test'}, afterSpy show: -> @render(view: view) test: -> @render false @executeAction 'show' @controller = new TestController view.prevent('viewDidAppear') @controller.dispatch('test') ok !afterSpy.called view.allowAndFire('viewDidAppear') ok afterSpy.called test 'dispatching params with a hash scrolls to that hash', -> @controller.show = -> @render false spyOnDuring Batman.DOM, 'scrollIntoView', (spy) => spy.fixedReturn = true @controller.dispatch 'show', {'#': 'foo'} deepEqual spy.lastCallArguments, ['foo'] test 'dispatching params with a hash does not scroll to that hash if autoScrollToHash is false', -> @controller.autoScrollToHash = false @controller.show = -> @render false spyOnDuring Batman.DOM, 'scrollIntoView', (spy) => spy.fixedReturn = true @controller.dispatch 'show', {'#': 'foo'} ok !spy.called QUnit.module 'Batman.Controller error handling', setup: -> class @CustomError extends Batman.Object class @CustomError2 extends Batman.Object @error = error = new @CustomError @error2 = error2 = new @CustomError2 class @Model extends Batman.Object @load: (callback) -> callback(error, undefined) @load2: (callback) -> callback(error2, undefined) class @TestController extends Batman.Controller _customErrorHandler: (err) -> _customErrorHandler2: (err) -> test 'When wrapping a call with the errorHandler callback, any exception tracked with catchError will be handled by a single handler', 3, -> callbackSpy = createSpy() handlerSpy = createSpy() @TestController::_customErrorHandler = handlerSpy @TestController.catchError @CustomError, with: @TestController::_customErrorHandler namespace = @ controller = new @TestController controller.index = -> namespace.Model.load @errorHandler callbackSpy @render false controller.dispatch('index') equal callbackSpy.callCount, 0 equal handlerSpy.callCount, 1 deepEqual handlerSpy.lastCallArguments, [@error] test 'when wrapping a call with the errorHandler callback, any exception tracked with catchError will be handled by multiple handlers', -> callbackSpy = createSpy() handlerSpy = createSpy() handlerSpy2 = createSpy() @TestController::_customErrorHandler = handlerSpy @TestController::_customErrorHandler2 = handlerSpy2 @TestController.catchError @CustomError, with: [@TestController::_customErrorHandler, @TestController::_customErrorHandler2] namespace = @ controller = new @TestController controller.index = -> namespace.Model.load @errorHandler callbackSpy @render false controller.dispatch('index') equal callbackSpy.callCount, 0 equal handlerSpy.callCount, 1 equal handlerSpy2.callCount, 1 deepEqual handlerSpy.lastCallArguments, [@error] deepEqual handlerSpy2.lastCallArguments, [@error] test 'when wrapping a call with the errorHandler callback, any exception that is not tracked with specific catchError will be re-thrown', -> callbackSpy = createSpy() handlerSpy = createSpy() @TestController::_customErrorHandler = handlerSpy @TestController.catchError @CustomError, with: @TestController::_customErrorHandler @Model.load = (callback) -> callback(new Error, undefined) namespace = @ controller = new @TestController controller.index = -> namespace.Model.load @errorHandler callbackSpy @render false raises -> controller.dispatch('index') , Error equal callbackSpy.callCount, 0 equal handlerSpy.callCount, 0 test 'when wrapping a call with the errorHandler callback, no exception passes result to callback', -> callbackSpy = createSpy() handlerSpy = createSpy() @TestController::_customErrorHandler = handlerSpy @TestController.catchError @CustomError, with: @TestController::_customErrorHandler @Model.load = (callback) -> callback(undefined, [{id: 1}], 'foo') namespace = @ controller = new @TestController controller.index = -> namespace.Model.load @errorHandler callbackSpy @render false controller.dispatch('index') equal handlerSpy.callCount, 0 equal callbackSpy.callCount, 1 deepEqual callbackSpy.lastCallArguments, [[{id: 1}], 'foo'] test 'subclass errors registered with superclass catchError cause the errorHandler callback to fire', -> class ReallyCustomError extends @CustomError callbackSpy = createSpy() handlerSpy = createSpy() error = new ReallyCustomError @TestController::_customErrorHandler = handlerSpy @TestController.catchError @CustomError, with: @TestController::_customErrorHandler @Model.load = (callback) -> callback(error, undefined) namespace = @ controller = new @TestController controller.index = -> namespace.Model.load @errorHandler callbackSpy @render false controller.dispatch('index') equal callbackSpy.callCount, 0 equal handlerSpy.callCount, 1 deepEqual handlerSpy.lastCallArguments, [error] test 'When wrapping a call with the errorHandler callback, parent class handlers are also called', -> callbackSpy = createSpy() handlerSpy = createSpy() handlerSpy2 = createSpy() handlerSpy3 = createSpy() @TestController::_customErrorHandler = handlerSpy @TestController::_customErrorHandler2 = handlerSpy2 @TestController.catchError @CustomError, with: [@TestController::_customErrorHandler, @TestController::_customErrorHandler2] namespace = @ class SubclassController extends @TestController _customErrorHandler3: handlerSpy3 _customErrorHandler2: handlerSpy2 @catchError namespace.CustomError, with: @::_customErrorHandler3 namespace = @ controller = new SubclassController controller.index = -> namespace.Model.load @errorHandler callbackSpy @render false controller.dispatch('index') equal callbackSpy.callCount, 0 equal handlerSpy.callCount, 1 equal handlerSpy2.callCount, 1 equal handlerSpy3.callCount, 1 deepEqual handlerSpy.lastCallArguments, [@error] deepEqual handlerSpy2.lastCallArguments, [@error] deepEqual handlerSpy3.lastCallArguments, [@error] test 'When wrapping multiple calls with errorHandler callback, any successive calls to the errorHandler should be ignored if an error occured on the current frame', -> callbackSpy = createSpy() handlerSpy = createSpy() handlerSpy2 = createSpy() @TestController::_customErrorHandler = handlerSpy @TestController::_customErrorHandler2 = handlerSpy2 @TestController.catchError @CustomError, with: [@TestController::_customErrorHandler] @TestController.catchError @CustomError2, with: [@TestController::_customErrorHandler2] namespace = @ controller = new @TestController controller.index = -> namespace.Model.load @errorHandler callbackSpy namespace.Model.load2 @errorHandler callbackSpy @render false controller.dispatch('index') equal handlerSpy.callCount, 1 equal handlerSpy2.callCount, 0 equal callbackSpy.callCount, 0 deepEqual handlerSpy.lastCallArguments, [@error] test 'When wrapping multiple nested calls with errorHandler callback, nested errors should not be fired if parent errored', -> callbackSpy = createSpy() handlerSpy = createSpy() handlerSpy2 = createSpy() @TestController::_customErrorHandler = handlerSpy @TestController::_customErrorHandler2 = handlerSpy2 @TestController.catchError @CustomError, with: [@TestController::_customErrorHandler] @TestController.catchError @CustomError2, with: [@TestController::_customErrorHandler2] namespace = @ controller = new @TestController controller.index = -> namespace.Model.load @errorHandler -> namespace.Model.load2 @errorHandler callbackSpy ok false # should not be called @render false controller.dispatch('index') equal handlerSpy.callCount, 1 equal handlerSpy2.callCount, 0 equal callbackSpy.callCount, 0 deepEqual handlerSpy.lastCallArguments, [@error] test 'When wrapping multiple nested calls with errorHandler callback, nested errors not be ignored by higher level errors', -> callbackSpy = createSpy() handlerSpy = createSpy() handlerSpy2 = createSpy() @TestController::_customErrorHandler = handlerSpy @TestController::_customErrorHandler2 = handlerSpy2 @TestController.catchError @CustomError, with: [@TestController::_customErrorHandler] @TestController.catchError @CustomError2, with: [@TestController::_customErrorHandler2] namespace = @ @Model.load = (callback) -> callback(undefined, [{id: 1}], 'foo') @Model.load3 = (callback) -> callback(namespace.error, undefined) controller = new @TestController controller.index = -> controllerNamespace = @ namespace.Model.load @errorHandler => ok true namespace.Model.load2 @errorHandler callbackSpy namespace.Model.load3 @errorHandler callbackSpy @render false controller.dispatch('index') equal handlerSpy.callCount, 0 equal handlerSpy2.callCount, 1 equal callbackSpy.callCount, 0 deepEqual handlerSpy2.lastCallArguments, [@error2] test 'Calling handlerError directly with an error should result in the handlers being called', -> handlerSpy = createSpy() handlerSpy2 = createSpy() @TestController::_customErrorHandler = handlerSpy @TestController.catchError @CustomError, with: [@TestController::_customErrorHandler] controller = new @TestController equal controller.handleError(@error), true equal controller.handleError(@error2), false equal handlerSpy.callCount, 1 equal handlerSpy2.callCount, 0 deepEqual handlerSpy.lastCallArguments, [@error]
[ { "context": "me\n for version in versions\n key = JSON.stringify [ package_name, version, ]\n requir", "end": 5641, "score": 0.9911460280418396, "start": 5637, "tag": "KEY", "value": "JSON" }, { "context": " for version in versions\n key = JSON.stri...
dev/snippets/src/resolve-npm-dependencies.coffee
loveencounterflow/hengist
0
'use strict' ############################################################################################################ CND = require 'cnd' rpr = CND.rpr badge = 'RESOLVE-NPM-DEPS' debug = CND.get_logger 'debug', badge alert = CND.get_logger 'alert', badge whisper = CND.get_logger 'whisper', badge warn = CND.get_logger 'warn', badge help = CND.get_logger 'help', badge urge = CND.get_logger 'urge', badge info = CND.get_logger 'info', badge echo = CND.echo.bind CND #........................................................................................................... PATH = require 'path' # FS = require 'fs' #........................................................................................................... # types = require './types' # { isa # validate # cast # check # declare # declare_check # is_sad # type_of } = types.export() get_tree = require 'npm-logical-tree' #----------------------------------------------------------------------------------------------------------- @get_package_dependencies = ( path ) -> ### Given a `path` to an npm module that should contain a `package.json` and a `package-lock.json` file, return a report of transitive dependencies. The report will be an object with three fields: * **`packages`**—a list of pairs of package names and versions (`[ 'name', '1.1.0', ]`); these are in their installation order, i.e. each versioned package appears earlier than the packages that depend on it. * **`parents`**—an object whose keys are JSON representations os the values of `packages`, so like `'["opentype.js","1.3.3"]'`, and whose values are pairs of package names and versions as above. * **`duplicates`**—An object whose keys are unversioned package names and whose values are lists of versions in no particular order. ### pkg = require PATH.join path, 'package.json' pkgLock = require PATH.join path, 'package-lock.json' tree = get_tree pkg, pkgLock { packages parents } = @_get_package_dependencies tree #......................................................................................................... # Assemble a string `parent@version, parent@version, ...` for each package: for key, value of parents value = [ value..., ] value = ( JSON.parse k for k in value ) parents[ key ] = value #......................................................................................................... # Keep only first appearance of each versioned package in dependency-sorted list: packages = [ ( new Set packages )..., ] packages = ( ( JSON.parse d ) for d in packages ) #......................................................................................................... # Based on the packages list, find dependencies with more than a single version: duplicates = {} for [ name, version, ] in packages ( duplicates[ name ] ?= new Set() ).add version for name, versions of duplicates if versions.size < 2 delete duplicates[ name ] continue duplicates[ name ] = [ versions..., ] #......................................................................................................... return { packages, parents, duplicates, } #----------------------------------------------------------------------------------------------------------- @_get_package_dependencies = ( tree, R = null, seen = null, level = 0 ) -> seen ?= new WeakSet() R ?= { packages: [], parents: {}, } # dent = ' '.repeat level ### verbose ### parent_key = JSON.stringify [ tree.name, tree.version, ] seen.add tree if level > 0 R.packages.unshift parent_key # urge "#{dent}#{parent_key}" ### verbose ### for [ name, sub_tree, ] from tree.dependencies.entries() sub_key = JSON.stringify [ sub_tree.name, sub_tree.version, ] target = R.parents[ sub_key ] ?= new Set() target.add parent_key if seen.has sub_tree R.packages.unshift sub_key # whisper "#{dent}#{sub_key} (circular)" ### verbose ### continue @_get_package_dependencies sub_tree, R, seen, level + 1 return R #----------------------------------------------------------------------------------------------------------- @get_intershop_addon_installation_order = ( path ) -> dependencies = @get_package_dependencies path { packages parents duplicates } = dependencies info packages urge parents info duplicates @_complain_about_duplicates dependencies return ( [ name, version, ] for [ name, version, ] in packages when /^intershop-/.test name ) #----------------------------------------------------------------------------------------------------------- @_complain_about_duplicates = ( dependencies ) -> # Complain about duplicates (only one version of a given InterShop Addon can be installed as they all # write to the same DB): { packages parents duplicates } = dependencies duplicate_names = [] for package_name, versions of duplicates continue unless /^intershop-/.test package_name warn "multiple versions of package #{rpr package_name} detected:" duplicate_names.push package_name for version in versions key = JSON.stringify [ package_name, version, ] required_by = parents[ key ] ? [ [ "UNKNOWN", "UNKNOWN", ], ] required_by = ( "#{p}@#{v}" for [ p, v, ] in required_by ) required_by = required_by.join ', ' warn " version #{version} required_by by #{required_by}" if duplicate_names.length > 0 throw new Error "duplicate versions for packages #{duplicate_names.join ', '} detected; see details above" return null #----------------------------------------------------------------------------------------------------------- @demo = -> # path = PATH.resolve PATH.join __dirname, '../../..' # path = PATH.resolve PATH.join __dirname, '../../../../intershop-intertext' path = PATH.resolve PATH.join __dirname, '../../../../ucdb' debug @get_intershop_addon_installation_order path return null ############################################################################################################ if module is require.main then do => @demo()
71472
'use strict' ############################################################################################################ CND = require 'cnd' rpr = CND.rpr badge = 'RESOLVE-NPM-DEPS' debug = CND.get_logger 'debug', badge alert = CND.get_logger 'alert', badge whisper = CND.get_logger 'whisper', badge warn = CND.get_logger 'warn', badge help = CND.get_logger 'help', badge urge = CND.get_logger 'urge', badge info = CND.get_logger 'info', badge echo = CND.echo.bind CND #........................................................................................................... PATH = require 'path' # FS = require 'fs' #........................................................................................................... # types = require './types' # { isa # validate # cast # check # declare # declare_check # is_sad # type_of } = types.export() get_tree = require 'npm-logical-tree' #----------------------------------------------------------------------------------------------------------- @get_package_dependencies = ( path ) -> ### Given a `path` to an npm module that should contain a `package.json` and a `package-lock.json` file, return a report of transitive dependencies. The report will be an object with three fields: * **`packages`**—a list of pairs of package names and versions (`[ 'name', '1.1.0', ]`); these are in their installation order, i.e. each versioned package appears earlier than the packages that depend on it. * **`parents`**—an object whose keys are JSON representations os the values of `packages`, so like `'["opentype.js","1.3.3"]'`, and whose values are pairs of package names and versions as above. * **`duplicates`**—An object whose keys are unversioned package names and whose values are lists of versions in no particular order. ### pkg = require PATH.join path, 'package.json' pkgLock = require PATH.join path, 'package-lock.json' tree = get_tree pkg, pkgLock { packages parents } = @_get_package_dependencies tree #......................................................................................................... # Assemble a string `parent@version, parent@version, ...` for each package: for key, value of parents value = [ value..., ] value = ( JSON.parse k for k in value ) parents[ key ] = value #......................................................................................................... # Keep only first appearance of each versioned package in dependency-sorted list: packages = [ ( new Set packages )..., ] packages = ( ( JSON.parse d ) for d in packages ) #......................................................................................................... # Based on the packages list, find dependencies with more than a single version: duplicates = {} for [ name, version, ] in packages ( duplicates[ name ] ?= new Set() ).add version for name, versions of duplicates if versions.size < 2 delete duplicates[ name ] continue duplicates[ name ] = [ versions..., ] #......................................................................................................... return { packages, parents, duplicates, } #----------------------------------------------------------------------------------------------------------- @_get_package_dependencies = ( tree, R = null, seen = null, level = 0 ) -> seen ?= new WeakSet() R ?= { packages: [], parents: {}, } # dent = ' '.repeat level ### verbose ### parent_key = JSON.stringify [ tree.name, tree.version, ] seen.add tree if level > 0 R.packages.unshift parent_key # urge "#{dent}#{parent_key}" ### verbose ### for [ name, sub_tree, ] from tree.dependencies.entries() sub_key = JSON.stringify [ sub_tree.name, sub_tree.version, ] target = R.parents[ sub_key ] ?= new Set() target.add parent_key if seen.has sub_tree R.packages.unshift sub_key # whisper "#{dent}#{sub_key} (circular)" ### verbose ### continue @_get_package_dependencies sub_tree, R, seen, level + 1 return R #----------------------------------------------------------------------------------------------------------- @get_intershop_addon_installation_order = ( path ) -> dependencies = @get_package_dependencies path { packages parents duplicates } = dependencies info packages urge parents info duplicates @_complain_about_duplicates dependencies return ( [ name, version, ] for [ name, version, ] in packages when /^intershop-/.test name ) #----------------------------------------------------------------------------------------------------------- @_complain_about_duplicates = ( dependencies ) -> # Complain about duplicates (only one version of a given InterShop Addon can be installed as they all # write to the same DB): { packages parents duplicates } = dependencies duplicate_names = [] for package_name, versions of duplicates continue unless /^intershop-/.test package_name warn "multiple versions of package #{rpr package_name} detected:" duplicate_names.push package_name for version in versions key = <KEY>.<KEY> [ package_<KEY>, version, ] required_by = parents[ key ] ? [ [ "UNKNOWN", "UNKNOWN", ], ] required_by = ( "#{p}@#{v}" for [ p, v, ] in required_by ) required_by = required_by.join ', ' warn " version #{version} required_by by #{required_by}" if duplicate_names.length > 0 throw new Error "duplicate versions for packages #{duplicate_names.join ', '} detected; see details above" return null #----------------------------------------------------------------------------------------------------------- @demo = -> # path = PATH.resolve PATH.join __dirname, '../../..' # path = PATH.resolve PATH.join __dirname, '../../../../intershop-intertext' path = PATH.resolve PATH.join __dirname, '../../../../ucdb' debug @get_intershop_addon_installation_order path return null ############################################################################################################ if module is require.main then do => @demo()
true
'use strict' ############################################################################################################ CND = require 'cnd' rpr = CND.rpr badge = 'RESOLVE-NPM-DEPS' debug = CND.get_logger 'debug', badge alert = CND.get_logger 'alert', badge whisper = CND.get_logger 'whisper', badge warn = CND.get_logger 'warn', badge help = CND.get_logger 'help', badge urge = CND.get_logger 'urge', badge info = CND.get_logger 'info', badge echo = CND.echo.bind CND #........................................................................................................... PATH = require 'path' # FS = require 'fs' #........................................................................................................... # types = require './types' # { isa # validate # cast # check # declare # declare_check # is_sad # type_of } = types.export() get_tree = require 'npm-logical-tree' #----------------------------------------------------------------------------------------------------------- @get_package_dependencies = ( path ) -> ### Given a `path` to an npm module that should contain a `package.json` and a `package-lock.json` file, return a report of transitive dependencies. The report will be an object with three fields: * **`packages`**—a list of pairs of package names and versions (`[ 'name', '1.1.0', ]`); these are in their installation order, i.e. each versioned package appears earlier than the packages that depend on it. * **`parents`**—an object whose keys are JSON representations os the values of `packages`, so like `'["opentype.js","1.3.3"]'`, and whose values are pairs of package names and versions as above. * **`duplicates`**—An object whose keys are unversioned package names and whose values are lists of versions in no particular order. ### pkg = require PATH.join path, 'package.json' pkgLock = require PATH.join path, 'package-lock.json' tree = get_tree pkg, pkgLock { packages parents } = @_get_package_dependencies tree #......................................................................................................... # Assemble a string `parent@version, parent@version, ...` for each package: for key, value of parents value = [ value..., ] value = ( JSON.parse k for k in value ) parents[ key ] = value #......................................................................................................... # Keep only first appearance of each versioned package in dependency-sorted list: packages = [ ( new Set packages )..., ] packages = ( ( JSON.parse d ) for d in packages ) #......................................................................................................... # Based on the packages list, find dependencies with more than a single version: duplicates = {} for [ name, version, ] in packages ( duplicates[ name ] ?= new Set() ).add version for name, versions of duplicates if versions.size < 2 delete duplicates[ name ] continue duplicates[ name ] = [ versions..., ] #......................................................................................................... return { packages, parents, duplicates, } #----------------------------------------------------------------------------------------------------------- @_get_package_dependencies = ( tree, R = null, seen = null, level = 0 ) -> seen ?= new WeakSet() R ?= { packages: [], parents: {}, } # dent = ' '.repeat level ### verbose ### parent_key = JSON.stringify [ tree.name, tree.version, ] seen.add tree if level > 0 R.packages.unshift parent_key # urge "#{dent}#{parent_key}" ### verbose ### for [ name, sub_tree, ] from tree.dependencies.entries() sub_key = JSON.stringify [ sub_tree.name, sub_tree.version, ] target = R.parents[ sub_key ] ?= new Set() target.add parent_key if seen.has sub_tree R.packages.unshift sub_key # whisper "#{dent}#{sub_key} (circular)" ### verbose ### continue @_get_package_dependencies sub_tree, R, seen, level + 1 return R #----------------------------------------------------------------------------------------------------------- @get_intershop_addon_installation_order = ( path ) -> dependencies = @get_package_dependencies path { packages parents duplicates } = dependencies info packages urge parents info duplicates @_complain_about_duplicates dependencies return ( [ name, version, ] for [ name, version, ] in packages when /^intershop-/.test name ) #----------------------------------------------------------------------------------------------------------- @_complain_about_duplicates = ( dependencies ) -> # Complain about duplicates (only one version of a given InterShop Addon can be installed as they all # write to the same DB): { packages parents duplicates } = dependencies duplicate_names = [] for package_name, versions of duplicates continue unless /^intershop-/.test package_name warn "multiple versions of package #{rpr package_name} detected:" duplicate_names.push package_name for version in versions key = PI:KEY:<KEY>END_PI.PI:KEY:<KEY>END_PI [ package_PI:KEY:<KEY>END_PI, version, ] required_by = parents[ key ] ? [ [ "UNKNOWN", "UNKNOWN", ], ] required_by = ( "#{p}@#{v}" for [ p, v, ] in required_by ) required_by = required_by.join ', ' warn " version #{version} required_by by #{required_by}" if duplicate_names.length > 0 throw new Error "duplicate versions for packages #{duplicate_names.join ', '} detected; see details above" return null #----------------------------------------------------------------------------------------------------------- @demo = -> # path = PATH.resolve PATH.join __dirname, '../../..' # path = PATH.resolve PATH.join __dirname, '../../../../intershop-intertext' path = PATH.resolve PATH.join __dirname, '../../../../ucdb' debug @get_intershop_addon_installation_order path return null ############################################################################################################ if module is require.main then do => @demo()
[ { "context": "Length: 4\n \"exception-reporting\":\n userId: \"cf073067-d1e3-42e5-a934-e5630b911f89\"\n \"gcc-make-run\": {}\n \"git-blame\":\n columnWi", "end": 533, "score": 0.8141372203826904, "start": 499, "tag": "PASSWORD", "value": "073067-d1e3-42e5-a934-e5630b911f89" } ]
.atom/config.cson
hill-a/atom-config
0
"*": "atom-beautify": c: configPath: "." default_beautifier: "clang-format" cpp: configPath: "." default_beautifier: "clang-format" "autocomplete-clang": "std c++": "c++11" "clang-format": {} core: disabledPackages: [ "markdown-preview" ] packagesWithKeymapsDisabled: [ "clang-format" ] telemetryConsent: "no" editor: fontSize: 12 preferredLineLength: 140 tabLength: 4 "exception-reporting": userId: "cf073067-d1e3-42e5-a934-e5630b911f89" "gcc-make-run": {} "git-blame": columnWidth: 310 "gpp-compiler": {} "linter-gcc": gccDefaultCFlags: "-c -Wall -fsyntax-only" gccDefaultCppFlags: "-c -Wall -std=c++11 -fsyntax-only" gccIncludePaths: " .,./include" "linter-ui-default": {} "markdown-preview-plus": importPackageStyles: [ "*" ] syntaxThemeName: "one-dark-syntax" useGitHubStyle: true "platformio-ide-terminal": ansiColors: normal: blue: "#0010c3" zBright: brightBlue: "#0000d2" style: fontFamily: "PowerlineSymbols, Monospace" fontSize: "13" theme: "solarized-dark" "vk-terminal": core: {} style: theme: "solarized-dark" toggles: {}
52706
"*": "atom-beautify": c: configPath: "." default_beautifier: "clang-format" cpp: configPath: "." default_beautifier: "clang-format" "autocomplete-clang": "std c++": "c++11" "clang-format": {} core: disabledPackages: [ "markdown-preview" ] packagesWithKeymapsDisabled: [ "clang-format" ] telemetryConsent: "no" editor: fontSize: 12 preferredLineLength: 140 tabLength: 4 "exception-reporting": userId: "cf<PASSWORD>" "gcc-make-run": {} "git-blame": columnWidth: 310 "gpp-compiler": {} "linter-gcc": gccDefaultCFlags: "-c -Wall -fsyntax-only" gccDefaultCppFlags: "-c -Wall -std=c++11 -fsyntax-only" gccIncludePaths: " .,./include" "linter-ui-default": {} "markdown-preview-plus": importPackageStyles: [ "*" ] syntaxThemeName: "one-dark-syntax" useGitHubStyle: true "platformio-ide-terminal": ansiColors: normal: blue: "#0010c3" zBright: brightBlue: "#0000d2" style: fontFamily: "PowerlineSymbols, Monospace" fontSize: "13" theme: "solarized-dark" "vk-terminal": core: {} style: theme: "solarized-dark" toggles: {}
true
"*": "atom-beautify": c: configPath: "." default_beautifier: "clang-format" cpp: configPath: "." default_beautifier: "clang-format" "autocomplete-clang": "std c++": "c++11" "clang-format": {} core: disabledPackages: [ "markdown-preview" ] packagesWithKeymapsDisabled: [ "clang-format" ] telemetryConsent: "no" editor: fontSize: 12 preferredLineLength: 140 tabLength: 4 "exception-reporting": userId: "cfPI:PASSWORD:<PASSWORD>END_PI" "gcc-make-run": {} "git-blame": columnWidth: 310 "gpp-compiler": {} "linter-gcc": gccDefaultCFlags: "-c -Wall -fsyntax-only" gccDefaultCppFlags: "-c -Wall -std=c++11 -fsyntax-only" gccIncludePaths: " .,./include" "linter-ui-default": {} "markdown-preview-plus": importPackageStyles: [ "*" ] syntaxThemeName: "one-dark-syntax" useGitHubStyle: true "platformio-ide-terminal": ansiColors: normal: blue: "#0010c3" zBright: brightBlue: "#0000d2" style: fontFamily: "PowerlineSymbols, Monospace" fontSize: "13" theme: "solarized-dark" "vk-terminal": core: {} style: theme: "solarized-dark" toggles: {}
[ { "context": "'localhost'\n port: port\n username: 'foo@biz.biz'\n password: 'bar'\n }\n\n afterEach (done", "end": 1432, "score": 0.9999135732650757, "start": 1421, "tag": "EMAIL", "value": "foo@biz.biz" }, { "context": " username: 'foo@biz.biz'\n ...
test/streams/exchange-stream-spec.coffee
octoblu/bourse
0
{afterEach, beforeEach, describe, it} = global {expect} = require 'chai' fs = require 'fs' _ = require 'lodash' moment = require 'moment' path = require 'path' enableDestroy = require 'server-destroy' shmock = require 'shmock' sinon = require 'sinon' {PassThrough} = require 'stream' ExchangeStream = require '../../src/streams/exchange-stream' CALENDAR_EVENT = fs.readFileSync path.join(__dirname, '../fixtures/calendarEvent.xml') CALENDAR_EVENT2 = fs.readFileSync path.join(__dirname, '../fixtures/calendarEvent2.xml') CLOSED_EVENT = fs.readFileSync path.join(__dirname, '../fixtures/closedEvent.xml') GET_ITEM_CALENDAR_RESPONSE = fs.readFileSync path.join(__dirname, '../fixtures/getItemCalendarResponse.xml') CHALLENGE = _.trim fs.readFileSync path.join(__dirname, '../fixtures/challenge.b64'), encoding: 'utf8' NEGOTIATE = _.trim fs.readFileSync path.join(__dirname, '../fixtures/negotiate.b64'), encoding: 'utf8' describe 'ExchangeStream', -> beforeEach -> @clock = sinon.useFakeTimers(moment('2016-11-19T12:00:00Z').valueOf()) @server = shmock() enableDestroy @server {port} = @server.address() @request = new PassThrough objectMode: true @sut = new ExchangeStream { request: @request timeout: 200 connectionOptions: protocol: 'http' hostname: 'localhost' port: port username: 'foo@biz.biz' password: 'bar' } afterEach (done) -> @sut.destroy() @server.destroy done @clock.restore() describe 'when the request emits a calendar event', -> beforeEach (done) -> @sut.on 'readable', _.once(done) @server .get '/EWS/Exchange.asmx' .set 'Authorization', NEGOTIATE .reply 401, '', {'WWW-Authenticate': CHALLENGE} @getUser = @server .post '/EWS/Exchange.asmx' .reply 200, GET_ITEM_CALENDAR_RESPONSE @request.write CALENDAR_EVENT it 'should have a calendar event readable', -> event = @sut.read() expect(event).to.deep.equal { timestamp: '2016-11-19T12:00:00Z' } describe 'when the request emits another calendar event', -> beforeEach (done) -> @sut.on 'readable', _.once(done) @server .get '/EWS/Exchange.asmx' .set 'Authorization', NEGOTIATE .reply 401, '', {'WWW-Authenticate': CHALLENGE} @getUser = @server .post '/EWS/Exchange.asmx' .reply 200, GET_ITEM_CALENDAR_RESPONSE @request.write CALENDAR_EVENT2 it 'should have a calendar event readable', -> event = @sut.read() expect(event).to.deep.equal { timestamp: '2016-11-19T12:00:00Z' } describe 'when the request emits a closed event', -> beforeEach (done) -> @timeout 100 @sut.on 'end', done @sut.on 'readable', => @sut.read() @request.write CLOSED_EVENT it 'should close the stream', -> # Getting here is good enough
21771
{afterEach, beforeEach, describe, it} = global {expect} = require 'chai' fs = require 'fs' _ = require 'lodash' moment = require 'moment' path = require 'path' enableDestroy = require 'server-destroy' shmock = require 'shmock' sinon = require 'sinon' {PassThrough} = require 'stream' ExchangeStream = require '../../src/streams/exchange-stream' CALENDAR_EVENT = fs.readFileSync path.join(__dirname, '../fixtures/calendarEvent.xml') CALENDAR_EVENT2 = fs.readFileSync path.join(__dirname, '../fixtures/calendarEvent2.xml') CLOSED_EVENT = fs.readFileSync path.join(__dirname, '../fixtures/closedEvent.xml') GET_ITEM_CALENDAR_RESPONSE = fs.readFileSync path.join(__dirname, '../fixtures/getItemCalendarResponse.xml') CHALLENGE = _.trim fs.readFileSync path.join(__dirname, '../fixtures/challenge.b64'), encoding: 'utf8' NEGOTIATE = _.trim fs.readFileSync path.join(__dirname, '../fixtures/negotiate.b64'), encoding: 'utf8' describe 'ExchangeStream', -> beforeEach -> @clock = sinon.useFakeTimers(moment('2016-11-19T12:00:00Z').valueOf()) @server = shmock() enableDestroy @server {port} = @server.address() @request = new PassThrough objectMode: true @sut = new ExchangeStream { request: @request timeout: 200 connectionOptions: protocol: 'http' hostname: 'localhost' port: port username: '<EMAIL>' password: '<PASSWORD>' } afterEach (done) -> @sut.destroy() @server.destroy done @clock.restore() describe 'when the request emits a calendar event', -> beforeEach (done) -> @sut.on 'readable', _.once(done) @server .get '/EWS/Exchange.asmx' .set 'Authorization', NEGOTIATE .reply 401, '', {'WWW-Authenticate': CHALLENGE} @getUser = @server .post '/EWS/Exchange.asmx' .reply 200, GET_ITEM_CALENDAR_RESPONSE @request.write CALENDAR_EVENT it 'should have a calendar event readable', -> event = @sut.read() expect(event).to.deep.equal { timestamp: '2016-11-19T12:00:00Z' } describe 'when the request emits another calendar event', -> beforeEach (done) -> @sut.on 'readable', _.once(done) @server .get '/EWS/Exchange.asmx' .set 'Authorization', NEGOTIATE .reply 401, '', {'WWW-Authenticate': CHALLENGE} @getUser = @server .post '/EWS/Exchange.asmx' .reply 200, GET_ITEM_CALENDAR_RESPONSE @request.write CALENDAR_EVENT2 it 'should have a calendar event readable', -> event = @sut.read() expect(event).to.deep.equal { timestamp: '2016-11-19T12:00:00Z' } describe 'when the request emits a closed event', -> beforeEach (done) -> @timeout 100 @sut.on 'end', done @sut.on 'readable', => @sut.read() @request.write CLOSED_EVENT it 'should close the stream', -> # Getting here is good enough
true
{afterEach, beforeEach, describe, it} = global {expect} = require 'chai' fs = require 'fs' _ = require 'lodash' moment = require 'moment' path = require 'path' enableDestroy = require 'server-destroy' shmock = require 'shmock' sinon = require 'sinon' {PassThrough} = require 'stream' ExchangeStream = require '../../src/streams/exchange-stream' CALENDAR_EVENT = fs.readFileSync path.join(__dirname, '../fixtures/calendarEvent.xml') CALENDAR_EVENT2 = fs.readFileSync path.join(__dirname, '../fixtures/calendarEvent2.xml') CLOSED_EVENT = fs.readFileSync path.join(__dirname, '../fixtures/closedEvent.xml') GET_ITEM_CALENDAR_RESPONSE = fs.readFileSync path.join(__dirname, '../fixtures/getItemCalendarResponse.xml') CHALLENGE = _.trim fs.readFileSync path.join(__dirname, '../fixtures/challenge.b64'), encoding: 'utf8' NEGOTIATE = _.trim fs.readFileSync path.join(__dirname, '../fixtures/negotiate.b64'), encoding: 'utf8' describe 'ExchangeStream', -> beforeEach -> @clock = sinon.useFakeTimers(moment('2016-11-19T12:00:00Z').valueOf()) @server = shmock() enableDestroy @server {port} = @server.address() @request = new PassThrough objectMode: true @sut = new ExchangeStream { request: @request timeout: 200 connectionOptions: protocol: 'http' hostname: 'localhost' port: port username: 'PI:EMAIL:<EMAIL>END_PI' password: 'PI:PASSWORD:<PASSWORD>END_PI' } afterEach (done) -> @sut.destroy() @server.destroy done @clock.restore() describe 'when the request emits a calendar event', -> beforeEach (done) -> @sut.on 'readable', _.once(done) @server .get '/EWS/Exchange.asmx' .set 'Authorization', NEGOTIATE .reply 401, '', {'WWW-Authenticate': CHALLENGE} @getUser = @server .post '/EWS/Exchange.asmx' .reply 200, GET_ITEM_CALENDAR_RESPONSE @request.write CALENDAR_EVENT it 'should have a calendar event readable', -> event = @sut.read() expect(event).to.deep.equal { timestamp: '2016-11-19T12:00:00Z' } describe 'when the request emits another calendar event', -> beforeEach (done) -> @sut.on 'readable', _.once(done) @server .get '/EWS/Exchange.asmx' .set 'Authorization', NEGOTIATE .reply 401, '', {'WWW-Authenticate': CHALLENGE} @getUser = @server .post '/EWS/Exchange.asmx' .reply 200, GET_ITEM_CALENDAR_RESPONSE @request.write CALENDAR_EVENT2 it 'should have a calendar event readable', -> event = @sut.read() expect(event).to.deep.equal { timestamp: '2016-11-19T12:00:00Z' } describe 'when the request emits a closed event', -> beforeEach (done) -> @timeout 100 @sut.on 'end', done @sut.on 'readable', => @sut.read() @request.write CLOSED_EVENT it 'should close the stream', -> # Getting here is good enough
[ { "context": "EDITING_KEY = \"editingList\"\nSession.setDefault EDITING_KEY, false\n\nTemplate.", "end": 26, "score": 0.9376751184463501, "start": 15, "tag": "KEY", "value": "editingList" } ]
client/templates/lists-show.coffee
mcgwier/workhandle
0
EDITING_KEY = "editingList" Session.setDefault EDITING_KEY, false Template.listsShow.rendered = -> @find(".js-title-nav")._uihooks = insertElement: (node, next) -> $(node).hide().insertBefore(next).fadeIn() removeElement: (node) -> $(node).fadeOut -> @remove() Template.listsShow.helpers editing: -> Session.get EDITING_KEY unfinalizedPosts: -> Todos.find {listId: this._id, finalized: {$ne: true}}, {sort: {createdAt : -1}} finalizedPosts: -> Todos.find {listId: this._id, finalized: true}, {sort: {createdAt : -1}} editList = (list, template) -> Session.set EDITING_KEY, true # force the template to redraw based on the reactive change Tracker.flush() template.$(".js-edit-form input[type=text]").focus() saveList = (list, template) -> Session.set EDITING_KEY, false Lists.update list._id, $set: name: template.$("[name=name]").val() deleteList = (list) -> if Lists.find(domain: Meteor.user().domain).count() is 1 return alert("Mate, you cannot delete the final topic!") message = "Are you sure you want to delete the topic #{list.name} together with all its posts?" if confirm(message) # we must remove each item individually from the client Todos.find(listId: list._id).forEach (todo) -> Todos.remove todo._id Lists.remove list._id Router.go "home" true else false Template.listsShow.events "click .js-cancel": -> Session.set EDITING_KEY, false "keydown input[type=text]": (event) -> # ESC if 27 is event.which event.preventDefault() $(event.target).blur() "blur input[type=text]": (event, template) -> # if we are still editing (we haven't just clicked the cancel button) saveList this, template if Session.get(EDITING_KEY) "submit .js-edit-form": (event, template) -> event.preventDefault() saveList this, template # handle mousedown otherwise the blur handler above will swallow the click # on iOS, we still require the click event so handle both "mousedown .js-cancel, click .js-cancel": (event) -> event.preventDefault() Session.set EDITING_KEY, false "change .list-edit": (event, template) -> if $(event.target).val() is "edit" editList this, template else deleteList this, template if $(event.target).val() is "delete" event.target.selectedIndex = 0 "click .js-edit-list": (event, template) -> editList this, template "click .js-delete-list": (event, template) -> deleteList this, template
131751
EDITING_KEY = "<KEY>" Session.setDefault EDITING_KEY, false Template.listsShow.rendered = -> @find(".js-title-nav")._uihooks = insertElement: (node, next) -> $(node).hide().insertBefore(next).fadeIn() removeElement: (node) -> $(node).fadeOut -> @remove() Template.listsShow.helpers editing: -> Session.get EDITING_KEY unfinalizedPosts: -> Todos.find {listId: this._id, finalized: {$ne: true}}, {sort: {createdAt : -1}} finalizedPosts: -> Todos.find {listId: this._id, finalized: true}, {sort: {createdAt : -1}} editList = (list, template) -> Session.set EDITING_KEY, true # force the template to redraw based on the reactive change Tracker.flush() template.$(".js-edit-form input[type=text]").focus() saveList = (list, template) -> Session.set EDITING_KEY, false Lists.update list._id, $set: name: template.$("[name=name]").val() deleteList = (list) -> if Lists.find(domain: Meteor.user().domain).count() is 1 return alert("Mate, you cannot delete the final topic!") message = "Are you sure you want to delete the topic #{list.name} together with all its posts?" if confirm(message) # we must remove each item individually from the client Todos.find(listId: list._id).forEach (todo) -> Todos.remove todo._id Lists.remove list._id Router.go "home" true else false Template.listsShow.events "click .js-cancel": -> Session.set EDITING_KEY, false "keydown input[type=text]": (event) -> # ESC if 27 is event.which event.preventDefault() $(event.target).blur() "blur input[type=text]": (event, template) -> # if we are still editing (we haven't just clicked the cancel button) saveList this, template if Session.get(EDITING_KEY) "submit .js-edit-form": (event, template) -> event.preventDefault() saveList this, template # handle mousedown otherwise the blur handler above will swallow the click # on iOS, we still require the click event so handle both "mousedown .js-cancel, click .js-cancel": (event) -> event.preventDefault() Session.set EDITING_KEY, false "change .list-edit": (event, template) -> if $(event.target).val() is "edit" editList this, template else deleteList this, template if $(event.target).val() is "delete" event.target.selectedIndex = 0 "click .js-edit-list": (event, template) -> editList this, template "click .js-delete-list": (event, template) -> deleteList this, template
true
EDITING_KEY = "PI:KEY:<KEY>END_PI" Session.setDefault EDITING_KEY, false Template.listsShow.rendered = -> @find(".js-title-nav")._uihooks = insertElement: (node, next) -> $(node).hide().insertBefore(next).fadeIn() removeElement: (node) -> $(node).fadeOut -> @remove() Template.listsShow.helpers editing: -> Session.get EDITING_KEY unfinalizedPosts: -> Todos.find {listId: this._id, finalized: {$ne: true}}, {sort: {createdAt : -1}} finalizedPosts: -> Todos.find {listId: this._id, finalized: true}, {sort: {createdAt : -1}} editList = (list, template) -> Session.set EDITING_KEY, true # force the template to redraw based on the reactive change Tracker.flush() template.$(".js-edit-form input[type=text]").focus() saveList = (list, template) -> Session.set EDITING_KEY, false Lists.update list._id, $set: name: template.$("[name=name]").val() deleteList = (list) -> if Lists.find(domain: Meteor.user().domain).count() is 1 return alert("Mate, you cannot delete the final topic!") message = "Are you sure you want to delete the topic #{list.name} together with all its posts?" if confirm(message) # we must remove each item individually from the client Todos.find(listId: list._id).forEach (todo) -> Todos.remove todo._id Lists.remove list._id Router.go "home" true else false Template.listsShow.events "click .js-cancel": -> Session.set EDITING_KEY, false "keydown input[type=text]": (event) -> # ESC if 27 is event.which event.preventDefault() $(event.target).blur() "blur input[type=text]": (event, template) -> # if we are still editing (we haven't just clicked the cancel button) saveList this, template if Session.get(EDITING_KEY) "submit .js-edit-form": (event, template) -> event.preventDefault() saveList this, template # handle mousedown otherwise the blur handler above will swallow the click # on iOS, we still require the click event so handle both "mousedown .js-cancel, click .js-cancel": (event) -> event.preventDefault() Session.set EDITING_KEY, false "change .list-edit": (event, template) -> if $(event.target).val() is "edit" editList this, template else deleteList this, template if $(event.target).val() is "delete" event.target.selectedIndex = 0 "click .js-edit-list": (event, template) -> editList this, template "click .js-delete-list": (event, template) -> deleteList this, template
[ { "context": " dest: 'app.min.{{hash}}.js'\n key: 'app.js'\n\n dependencies_js:\n src: 'public/ass", "end": 1589, "score": 0.998434841632843, "start": 1583, "tag": "KEY", "value": "app.js" }, { "context": "est: 'dependencies.min.{{hash}}.js'\n key: 'd...
node_modules/nodemon/tmp/express-boilerplate/Gruntfile.coffee
CUBigDataClass/BigThings
8
module.exports = (grunt) -> grunt.initConfig pkg: grunt.file.readJSON('package.json') clean: build: src: 'public/assets' snocketsify: app: src: 'app/client/app.coffee' dest: 'public/assets/app.js' dependencies: src: 'app/client/dependencies.coffee' dest: 'public/assets/dependencies.js' stylus: app: options: compress: false 'include css': true urlfunc: 'embedurl' linenos: true define: '$version': '<%= pkg.version %>' src: 'css/app.styl' dest: 'public/assets/app.css' jade: views: options: pretty: true compileDebug: false client: true namespace: 'app.templates' processName: (file)-> file.replace(/views\/client\/([\w\/]+).jade/gi, '$1') src: 'views/client/**/*.jade' dest: 'public/assets/views.js' cssmin: build: src: 'public/assets/app.css' dest: 'public/assets/app.min.css' uglify: app: src: 'public/assets/app.js' dest: 'public/assets/app.min.js' dependencies: src: 'public/assets/dependencies.js' dest: 'public/assets/dependencies.min.js' views: src: 'public/assets/views.js' dest: 'public/assets/views.min.js' hashify: options: basedir: 'public/assets/' hashmap: 'hashmap.json' app_js: src: 'public/assets/app.min.js' dest: 'app.min.{{hash}}.js' key: 'app.js' dependencies_js: src: 'public/assets/dependencies.min.js' dest: 'dependencies.min.{{hash}}.js' key: 'dependencies.js' views_js: src: 'public/assets/views.min.js' dest: 'views.min.{{hash}}.js' key: 'views.js' app_css: src: 'public/assets/app.min.css' dest: 'app.min.{{hash}}.css' key: 'app.css' compress: build: options: mode: 'gzip' expand: true src: 'public/assets/*.min.*.*' dest: './' # imagemin: # options: # optimizationLevel: 7 # files: # expand: true # src: [ # 'public/images/**/*.jpg' # 'public/images/**/*.jpeg' # 'public/images/**/*.png' # ] # dest: './' watch: options: spawn: false interrupt: true dateFormat: (time) -> grunt.log.writeln("Compiled in #{time}ms @ #{(new Date).toString()} 💪\n") app_js: files: [ 'app/client/**/*.coffee' 'app/shared/**/*.coffee' '!app/client/dependencies.coffee' ] tasks: ['snocketsify:app'] dependencies_js: files: [ 'app/client/dependencies.coffee' 'vendor/**/*.js' 'vendor/**/*.coffee' ] tasks: ['snocketsify:dependencies'] css: files: [ 'css/**/*.styl' 'vendor/**/*.css' 'vendor/**/*.styl' ] tasks: ['stylus'] views: files: [ 'views/client/**/*.jade' 'views/shared/**/*.jade' ] tasks: ['jade'] # images: # files: [ # 'public/images/**/*.jpg' # 'public/images/**/*.jpeg' # 'public/images/**/*.png' # ] # tasks: ['imagemin'] grunt.loadNpmTasks('grunt-contrib-clean') grunt.loadNpmTasks('grunt-snocketsify') grunt.loadNpmTasks('grunt-contrib-stylus') grunt.loadNpmTasks('grunt-contrib-jade') grunt.loadNpmTasks('grunt-contrib-cssmin') grunt.loadNpmTasks('grunt-contrib-uglify') grunt.loadNpmTasks('grunt-hashify') grunt.loadNpmTasks('grunt-contrib-compress') # grunt.loadNpmTasks('grunt-contrib-imagemin') grunt.loadNpmTasks('grunt-contrib-watch') grunt.registerTask('default', [ 'clean' 'snocketsify' 'stylus' 'jade' ]) grunt.registerTask('build', [ 'default' 'cssmin' 'uglify' 'hashify' 'compress' # 'imagemin' # rely on minification during development ])
30756
module.exports = (grunt) -> grunt.initConfig pkg: grunt.file.readJSON('package.json') clean: build: src: 'public/assets' snocketsify: app: src: 'app/client/app.coffee' dest: 'public/assets/app.js' dependencies: src: 'app/client/dependencies.coffee' dest: 'public/assets/dependencies.js' stylus: app: options: compress: false 'include css': true urlfunc: 'embedurl' linenos: true define: '$version': '<%= pkg.version %>' src: 'css/app.styl' dest: 'public/assets/app.css' jade: views: options: pretty: true compileDebug: false client: true namespace: 'app.templates' processName: (file)-> file.replace(/views\/client\/([\w\/]+).jade/gi, '$1') src: 'views/client/**/*.jade' dest: 'public/assets/views.js' cssmin: build: src: 'public/assets/app.css' dest: 'public/assets/app.min.css' uglify: app: src: 'public/assets/app.js' dest: 'public/assets/app.min.js' dependencies: src: 'public/assets/dependencies.js' dest: 'public/assets/dependencies.min.js' views: src: 'public/assets/views.js' dest: 'public/assets/views.min.js' hashify: options: basedir: 'public/assets/' hashmap: 'hashmap.json' app_js: src: 'public/assets/app.min.js' dest: 'app.min.{{hash}}.js' key: '<KEY>' dependencies_js: src: 'public/assets/dependencies.min.js' dest: 'dependencies.min.{{hash}}.js' key: '<KEY>' views_js: src: 'public/assets/views.min.js' dest: 'views.min.{{hash}}.js' key: '<KEY>.<KEY>' app_css: src: 'public/assets/app.min.css' dest: 'app.min.{{hash}}.css' key: '<KEY>' compress: build: options: mode: 'gzip' expand: true src: 'public/assets/*.min.*.*' dest: './' # imagemin: # options: # optimizationLevel: 7 # files: # expand: true # src: [ # 'public/images/**/*.jpg' # 'public/images/**/*.jpeg' # 'public/images/**/*.png' # ] # dest: './' watch: options: spawn: false interrupt: true dateFormat: (time) -> grunt.log.writeln("Compiled in #{time}ms @ #{(new Date).toString()} 💪\n") app_js: files: [ 'app/client/**/*.coffee' 'app/shared/**/*.coffee' '!app/client/dependencies.coffee' ] tasks: ['snocketsify:app'] dependencies_js: files: [ 'app/client/dependencies.coffee' 'vendor/**/*.js' 'vendor/**/*.coffee' ] tasks: ['snocketsify:dependencies'] css: files: [ 'css/**/*.styl' 'vendor/**/*.css' 'vendor/**/*.styl' ] tasks: ['stylus'] views: files: [ 'views/client/**/*.jade' 'views/shared/**/*.jade' ] tasks: ['jade'] # images: # files: [ # 'public/images/**/*.jpg' # 'public/images/**/*.jpeg' # 'public/images/**/*.png' # ] # tasks: ['imagemin'] grunt.loadNpmTasks('grunt-contrib-clean') grunt.loadNpmTasks('grunt-snocketsify') grunt.loadNpmTasks('grunt-contrib-stylus') grunt.loadNpmTasks('grunt-contrib-jade') grunt.loadNpmTasks('grunt-contrib-cssmin') grunt.loadNpmTasks('grunt-contrib-uglify') grunt.loadNpmTasks('grunt-hashify') grunt.loadNpmTasks('grunt-contrib-compress') # grunt.loadNpmTasks('grunt-contrib-imagemin') grunt.loadNpmTasks('grunt-contrib-watch') grunt.registerTask('default', [ 'clean' 'snocketsify' 'stylus' 'jade' ]) grunt.registerTask('build', [ 'default' 'cssmin' 'uglify' 'hashify' 'compress' # 'imagemin' # rely on minification during development ])
true
module.exports = (grunt) -> grunt.initConfig pkg: grunt.file.readJSON('package.json') clean: build: src: 'public/assets' snocketsify: app: src: 'app/client/app.coffee' dest: 'public/assets/app.js' dependencies: src: 'app/client/dependencies.coffee' dest: 'public/assets/dependencies.js' stylus: app: options: compress: false 'include css': true urlfunc: 'embedurl' linenos: true define: '$version': '<%= pkg.version %>' src: 'css/app.styl' dest: 'public/assets/app.css' jade: views: options: pretty: true compileDebug: false client: true namespace: 'app.templates' processName: (file)-> file.replace(/views\/client\/([\w\/]+).jade/gi, '$1') src: 'views/client/**/*.jade' dest: 'public/assets/views.js' cssmin: build: src: 'public/assets/app.css' dest: 'public/assets/app.min.css' uglify: app: src: 'public/assets/app.js' dest: 'public/assets/app.min.js' dependencies: src: 'public/assets/dependencies.js' dest: 'public/assets/dependencies.min.js' views: src: 'public/assets/views.js' dest: 'public/assets/views.min.js' hashify: options: basedir: 'public/assets/' hashmap: 'hashmap.json' app_js: src: 'public/assets/app.min.js' dest: 'app.min.{{hash}}.js' key: 'PI:KEY:<KEY>END_PI' dependencies_js: src: 'public/assets/dependencies.min.js' dest: 'dependencies.min.{{hash}}.js' key: 'PI:KEY:<KEY>END_PI' views_js: src: 'public/assets/views.min.js' dest: 'views.min.{{hash}}.js' key: 'PI:KEY:<KEY>END_PI.PI:KEY:<KEY>END_PI' app_css: src: 'public/assets/app.min.css' dest: 'app.min.{{hash}}.css' key: 'PI:KEY:<KEY>END_PI' compress: build: options: mode: 'gzip' expand: true src: 'public/assets/*.min.*.*' dest: './' # imagemin: # options: # optimizationLevel: 7 # files: # expand: true # src: [ # 'public/images/**/*.jpg' # 'public/images/**/*.jpeg' # 'public/images/**/*.png' # ] # dest: './' watch: options: spawn: false interrupt: true dateFormat: (time) -> grunt.log.writeln("Compiled in #{time}ms @ #{(new Date).toString()} 💪\n") app_js: files: [ 'app/client/**/*.coffee' 'app/shared/**/*.coffee' '!app/client/dependencies.coffee' ] tasks: ['snocketsify:app'] dependencies_js: files: [ 'app/client/dependencies.coffee' 'vendor/**/*.js' 'vendor/**/*.coffee' ] tasks: ['snocketsify:dependencies'] css: files: [ 'css/**/*.styl' 'vendor/**/*.css' 'vendor/**/*.styl' ] tasks: ['stylus'] views: files: [ 'views/client/**/*.jade' 'views/shared/**/*.jade' ] tasks: ['jade'] # images: # files: [ # 'public/images/**/*.jpg' # 'public/images/**/*.jpeg' # 'public/images/**/*.png' # ] # tasks: ['imagemin'] grunt.loadNpmTasks('grunt-contrib-clean') grunt.loadNpmTasks('grunt-snocketsify') grunt.loadNpmTasks('grunt-contrib-stylus') grunt.loadNpmTasks('grunt-contrib-jade') grunt.loadNpmTasks('grunt-contrib-cssmin') grunt.loadNpmTasks('grunt-contrib-uglify') grunt.loadNpmTasks('grunt-hashify') grunt.loadNpmTasks('grunt-contrib-compress') # grunt.loadNpmTasks('grunt-contrib-imagemin') grunt.loadNpmTasks('grunt-contrib-watch') grunt.registerTask('default', [ 'clean' 'snocketsify' 'stylus' 'jade' ]) grunt.registerTask('build', [ 'default' 'cssmin' 'uglify' 'hashify' 'compress' # 'imagemin' # rely on minification during development ])
[ { "context": "ser: process.env.HUBOT_GLIP_EMAIL,\n password: process.env.HUBOT_GLIP_PASSWORD\n })\n\n @client.on 'message', (type, data) =>", "end": 477, "score": 0.9583628177642822, "start": 446, "tag": "PASSWORD", "value": "process.env.HUBOT_GLIP_PASSWORD" } ]
node_modules/hubot-glip/src/adapter.coffee
grokify/glipbot-demos-enterprise
0
try { Adapter, TextMessage, User } = require 'hubot' catch prequire = require('parent-require') { Adapter, TextMessage, User } = prequire 'hubot' GlipClient = require './bot' class GlipAdapter extends Adapter constructor: -> super @robot.logger.info "Constructor" @client = new GlipClient({ host: process.env.HUBOT_GLIP_HOST || 'glip.com', port: 443, user: process.env.HUBOT_GLIP_EMAIL, password: process.env.HUBOT_GLIP_PASSWORD }) @client.on 'message', (type, data) => @robot.logger.info type + ' : ' + JSON.stringify(data, null, 4) if (type == @client.type_ids.TYPE_ID_POST && data.text && !data.deactivated) user = new User data.group_id, room: data.group_id, reply_to: data.group_id, name: 'Group #' + data.group_id message = new TextMessage user, data.text, 'MSG-' + data._id @robot.receive message send: (envelope, strings...) -> @robot.logger.info 'send ' + JSON.stringify(envelope, null, 4) + '\n\n' + strings.join('\n\n') if envelope.message_type == 'image_url' # send image by url for str in strings @client.post_file_from_url envelope.user.reply_to, str, '' else @client.post envelope.user.reply_to, strings.join('\n') reply: (envelope, strings...) -> @robot.logger.info 'reply ' + JSON.stringify(envelope, null, 4) + '\n\n' + strings.join('\n\n') @client.post envelope.user.reply_to, strings.join('\n') run: -> @robot.logger.info "Run" @client.start() @client.on 'started', => @emit "connected" module.exports = GlipAdapter
219006
try { Adapter, TextMessage, User } = require 'hubot' catch prequire = require('parent-require') { Adapter, TextMessage, User } = prequire 'hubot' GlipClient = require './bot' class GlipAdapter extends Adapter constructor: -> super @robot.logger.info "Constructor" @client = new GlipClient({ host: process.env.HUBOT_GLIP_HOST || 'glip.com', port: 443, user: process.env.HUBOT_GLIP_EMAIL, password: <PASSWORD> }) @client.on 'message', (type, data) => @robot.logger.info type + ' : ' + JSON.stringify(data, null, 4) if (type == @client.type_ids.TYPE_ID_POST && data.text && !data.deactivated) user = new User data.group_id, room: data.group_id, reply_to: data.group_id, name: 'Group #' + data.group_id message = new TextMessage user, data.text, 'MSG-' + data._id @robot.receive message send: (envelope, strings...) -> @robot.logger.info 'send ' + JSON.stringify(envelope, null, 4) + '\n\n' + strings.join('\n\n') if envelope.message_type == 'image_url' # send image by url for str in strings @client.post_file_from_url envelope.user.reply_to, str, '' else @client.post envelope.user.reply_to, strings.join('\n') reply: (envelope, strings...) -> @robot.logger.info 'reply ' + JSON.stringify(envelope, null, 4) + '\n\n' + strings.join('\n\n') @client.post envelope.user.reply_to, strings.join('\n') run: -> @robot.logger.info "Run" @client.start() @client.on 'started', => @emit "connected" module.exports = GlipAdapter
true
try { Adapter, TextMessage, User } = require 'hubot' catch prequire = require('parent-require') { Adapter, TextMessage, User } = prequire 'hubot' GlipClient = require './bot' class GlipAdapter extends Adapter constructor: -> super @robot.logger.info "Constructor" @client = new GlipClient({ host: process.env.HUBOT_GLIP_HOST || 'glip.com', port: 443, user: process.env.HUBOT_GLIP_EMAIL, password: PI:PASSWORD:<PASSWORD>END_PI }) @client.on 'message', (type, data) => @robot.logger.info type + ' : ' + JSON.stringify(data, null, 4) if (type == @client.type_ids.TYPE_ID_POST && data.text && !data.deactivated) user = new User data.group_id, room: data.group_id, reply_to: data.group_id, name: 'Group #' + data.group_id message = new TextMessage user, data.text, 'MSG-' + data._id @robot.receive message send: (envelope, strings...) -> @robot.logger.info 'send ' + JSON.stringify(envelope, null, 4) + '\n\n' + strings.join('\n\n') if envelope.message_type == 'image_url' # send image by url for str in strings @client.post_file_from_url envelope.user.reply_to, str, '' else @client.post envelope.user.reply_to, strings.join('\n') reply: (envelope, strings...) -> @robot.logger.info 'reply ' + JSON.stringify(envelope, null, 4) + '\n\n' + strings.join('\n\n') @client.post envelope.user.reply_to, strings.join('\n') run: -> @robot.logger.info "Run" @client.start() @client.on 'started', => @emit "connected" module.exports = GlipAdapter
[ { "context": "EATH_DATE, HANDEDNESS)\n VALUES \n (10, \"Henry McCarty\", \"Billy the Kid\", 10, \"1859.September.17\",\"1881.", "end": 492, "score": 0.9998979568481445, "start": 479, "tag": "NAME", "value": "Henry McCarty" }, { "context": "NESS)\n VALUES \n (10,...
test.coffee
blue-color/nodejsdbc
2
NodeJDBC = require './lib/nodejdbc' _ = require 'lodash' Promise = require 'bluebird' OUTLAW_DDL = ' CREATE TABLE OUTLAW ( ID INT, NAME TEXT, AKA TEXT, GANG INT, BIRTH_DATE DATE, DEATH_DATE DATE, HANDEDNESS INT )' OUTLAW_DML = [ 'INSERT INTO OUTLAW (ID, NAME, AKA, GANG, BIRTH_DATE, DEATH_DATE, HANDEDNESS) VALUES (10, "Henry McCarty", "Billy the Kid", 10, "1859.September.17","1881.July.14",10)', 'INSERT INTO OUTLAW (ID, NAME, AKA, GANG, BIRTH_DATE, DEATH_DATE, HANDEDNESS) VALUES (20, "Josiah Gordon Scurlock", "Doc", 10, "1849.January.11","1929.July.25",20)', 'INSERT INTO OUTLAW (ID, NAME, AKA, GANG, BIRTH_DATE, DEATH_DATE, HANDEDNESS) VALUES (30, "Jesse Woodson James", "Jesse James", 20, "1847.September.05","1882.April.03",20)', 'INSERT INTO OUTLAW (ID, NAME, AKA, GANG, BIRTH_DATE, DEATH_DATE, HANDEDNESS) VALUES (40, "Alexander Franklin James", "Frank", 20, "1843.January.10","1915.February.18",20)', 'INSERT INTO OUTLAW (ID, NAME, AKA, GANG, BIRTH_DATE, DEATH_DATE, HANDEDNESS) VALUES (50,"Harry Alonzo Longabaugh","Sundance Kid",30, "1867.July.17","1908.November.07",30)', 'INSERT INTO OUTLAW (ID, NAME, AKA, GANG, BIRTH_DATE, DEATH_DATE, HANDEDNESS) VALUES (60,"Robert Leroy Parker","Butch Cassidy",30, "1867.July.17","1908.November.07",30)', 'INSERT INTO OUTLAW (ID, NAME, AKA, GANG, BIRTH_DATE, DEATH_DATE, HANDEDNESS) VALUES (70,"John Wesley Hardin","Little Arkansaw",40, "1853.May.26","1895.Agust.19",40)' ] GANG_DDL = ' CREATE TABLE GANG ( ID INT, NAME TEXT, LEADER INT )' GANG_DML = [ 'INSERT INTO GANG (ID,NAME, LEADER) VALUES (10,"Regulators",10)', 'INSERT INTO GANG (ID,NAME, LEADER) VALUES (20,"James-Younger",30)' 'INSERT INTO GANG (ID,NAME, LEADER) VALUES (30,"Wild Bunch",60)', 'INSERT INTO GANG (ID,NAME, LEADER) VALUES (40,"Hardin Gang",70)' ] HANDEDNESS_DDL = ' CREATE TABLE HANDEDNESS ( ID INT, NAME TEXT, DESC TEXT )' HANDEDNESS_DML = [ 'INSERT INTO HANDEDNESS (ID, NAME, DESC) VALUES (10, "Left Handed", "Uses left hand primarily")', 'INSERT INTO HANDEDNESS (ID, NAME, DESC) VALUES (20, "Right Handed", "Uses right hand primarily")', 'INSERT INTO HANDEDNESS (ID, NAME, DESC) VALUES (30, "Mixed Handed", "Uses one or the other hand for different tasks")', 'INSERT INTO HANDEDNESS (ID, NAME, DESC) VALUES (40, "Ambidextrous", "Uses both hands equally.")' ] ddls = [OUTLAW_DDL,GANG_DDL,HANDEDNESS_DDL] dmls = [OUTLAW_DML,GANG_DML,HANDEDNESS_DML] tables = ['OUTLAW','GANG','HANDEDNESS'] config = libs : ['test/lib/sqlite-jdbc-3.8.11.2.jar'] className: 'org.sqlite.JDBC' url: 'jdbc:sqlite:test.db' ### @Method dropClean Drops all _DDL tables. This method throws TableNotFound exception if the tables do not exist in database. @return returns a promise when all the tables are dropped successfully ### dropClean = -> nodejdbc = new NodeJDBC(config) promises = tables.map (table) -> nodejdbc.createStatement().then (statement) -> sql = 'DROP TABLE ' + table console.log "Executing #{sql}" exception = (e) -> console.log "Failed to drop table #{table}" console.log e statement.executeUpdate(sql).catch(exception) close = -> nodejdbc.getConnection().then (connection) -> connection.close() Promise.all(promises).finally(close) ### @Method deleteClean Deletes all the records from the tables in our Outlaw DB. @return returns a promise when all the DELETE statements are fulfilled. @todo We can also return number of records deleted for each statement. ### deleteClean = -> nodejdbc = new NodeJDBC(config) promises = tables.map (table) -> nodejdbc.createStatement().then (statement) -> sql = 'DELETE FROM ' + table console.log "Executing #{sql}" exception = (e) -> console.log "Failed to delete table #{table}" console.log e statement.executeUpdate(sql).catch(exception) # if db is not in AutoCommit mode commit = -> nodejdbc.getConnection().then (connection) -> connection.commit() close = -> nodejdbc.getConnection().then (connection) -> connection.close() Promise.all(promises).finally(close) ### @Method create executes CREATE ddl statements. @return returns a promise when all the CREATE statements are fulfilled. ### create = -> nodejdbc = new NodeJDBC(config) promises = ddls.map (ddl) -> nodejdbc.createStatement().then (statement) -> console.log "Executing \n #{ddl}" exception = (e) -> console.log e statement.executeUpdate(ddl).catch(exception) close = -> nodejdbc.getConnection().then (connection) -> connection.close() Promise.all(promises).then(close) ### @Method load Inserts records to tables. @return returns a promise when all the CREATE statements are fulfilled. ### load = -> nodejdbc = new NodeJDBC(config) promises = _.flatten(dmls).map (dml) -> nodejdbc.createStatement().then (statement) -> console.log "Executing \n #{dml}" exception = (e) -> console.log e statement.executeUpdate(dml).catch(exception) # if db is not in AutoCommit mode commit = -> nodejdbc.getConnection().then (connection) -> connection.commit() close = -> nodejdbc.getConnection().then (connection) -> connection.close() Promise.all(promises).then(close) ### @Method read executes a sample select statement and returns all the records as a json object @return [Object] result all records returned by the sample SQL query ### read = -> sql = 'SELECT NAME,AKA FROM OUTLAW' nodejdbc = new NodeJDBC(config) promise = nodejdbc.createStatement().then (statement) -> statement.executeQuery(sql).then (rs)-> result = [] while rs.next() name = rs.getString('NAME') aka = rs.getString('AKA') result.push {} = name: name aka: aka result promise.then (result) -> nodejdbc.getConnection().then (connection) -> connection.close() result # ------------------------------------------------------- # Drop -> Create -> Insert # dropClean().then(create).then(load) # ------------------------------------------------------- # ------------------------------------------------------- # Drop -> Create -> Insert -> Delete # dropClean().then(create).then(load).then(deleteClean) # ------------------------------------------------------- # ------------------------------------------------------- # Read # read().then (result) -> # console.log result # ------------------------------------------------------- config = libs : ['test/lib/ojdbc7.jar'] className: 'oracle.jdbc.driver.OracleDriver' url: 'jdbc:oracle:thin:@//win:1521/orcl', username: 'demo', password: 'demo' nodejdbc = new NodeJDBC(config) nodejdbc.getConnection().then (connection) -> console.log 'conn is valid', connection.isValid(2) call = '{call demo.pkg_outlaw.prc_flip_coin(?,?,?)}' connection.prepareCall(call).then (statement) -> statement.setString 1, 'Heads' statement.registerOutParameter 2,'VARCHAR' statement.registerOutParameter 3,'VARCHAR' statement.executeUpdate().then ()-> console.log "Result : #{statement.getString 2 }" console.log "Message: #{statement.getString 3 }" connection.close()
216916
NodeJDBC = require './lib/nodejdbc' _ = require 'lodash' Promise = require 'bluebird' OUTLAW_DDL = ' CREATE TABLE OUTLAW ( ID INT, NAME TEXT, AKA TEXT, GANG INT, BIRTH_DATE DATE, DEATH_DATE DATE, HANDEDNESS INT )' OUTLAW_DML = [ 'INSERT INTO OUTLAW (ID, NAME, AKA, GANG, BIRTH_DATE, DEATH_DATE, HANDEDNESS) VALUES (10, "<NAME>", "<NAME>", 10, "1859.September.17","1881.July.14",10)', 'INSERT INTO OUTLAW (ID, NAME, AKA, GANG, BIRTH_DATE, DEATH_DATE, HANDEDNESS) VALUES (20, "<NAME>", "<NAME>", 10, "1849.January.11","1929.July.25",20)', 'INSERT INTO OUTLAW (ID, NAME, AKA, GANG, BIRTH_DATE, DEATH_DATE, HANDEDNESS) VALUES (30, "<NAME>", "<NAME>", 20, "1847.September.05","1882.April.03",20)', 'INSERT INTO OUTLAW (ID, NAME, AKA, GANG, BIRTH_DATE, DEATH_DATE, HANDEDNESS) VALUES (40, "<NAME>", "<NAME>", 20, "1843.January.10","1915.February.18",20)', 'INSERT INTO OUTLAW (ID, NAME, AKA, GANG, BIRTH_DATE, DEATH_DATE, HANDEDNESS) VALUES (50,"<NAME>","Sundance Kid",30, "1867.July.17","1908.November.07",30)', 'INSERT INTO OUTLAW (ID, NAME, AKA, GANG, BIRTH_DATE, DEATH_DATE, HANDEDNESS) VALUES (60,"<NAME>","<NAME>",30, "1867.July.17","1908.November.07",30)', 'INSERT INTO OUTLAW (ID, NAME, AKA, GANG, BIRTH_DATE, DEATH_DATE, HANDEDNESS) VALUES (70,"<NAME>","<NAME>",40, "1853.May.26","1895.Agust.19",40)' ] GANG_DDL = ' CREATE TABLE GANG ( ID INT, NAME TEXT, LEADER INT )' GANG_DML = [ 'INSERT INTO GANG (ID,NAME, LEADER) VALUES (10,"Regulators",10)', 'INSERT INTO GANG (ID,NAME, LEADER) VALUES (20,"<NAME>",30)' 'INSERT INTO GANG (ID,NAME, LEADER) VALUES (30,"Wild Bunch",60)', 'INSERT INTO GANG (ID,NAME, LEADER) VALUES (40,"<NAME>",70)' ] HANDEDNESS_DDL = ' CREATE TABLE HANDEDNESS ( ID INT, NAME TEXT, DESC TEXT )' HANDEDNESS_DML = [ 'INSERT INTO HANDEDNESS (ID, NAME, DESC) VALUES (10, "Left Handed", "Uses left hand primarily")', 'INSERT INTO HANDEDNESS (ID, NAME, DESC) VALUES (20, "Right Handed", "Uses right hand primarily")', 'INSERT INTO HANDEDNESS (ID, NAME, DESC) VALUES (30, "Mixed Handed", "Uses one or the other hand for different tasks")', 'INSERT INTO HANDEDNESS (ID, NAME, DESC) VALUES (40, "Ambidextrous", "Uses both hands equally.")' ] ddls = [OUTLAW_DDL,GANG_DDL,HANDEDNESS_DDL] dmls = [OUTLAW_DML,GANG_DML,HANDEDNESS_DML] tables = ['OUTLAW','GANG','HANDEDNESS'] config = libs : ['test/lib/sqlite-jdbc-3.8.11.2.jar'] className: 'org.sqlite.JDBC' url: 'jdbc:sqlite:test.db' ### @Method dropClean Drops all _DDL tables. This method throws TableNotFound exception if the tables do not exist in database. @return returns a promise when all the tables are dropped successfully ### dropClean = -> nodejdbc = new NodeJDBC(config) promises = tables.map (table) -> nodejdbc.createStatement().then (statement) -> sql = 'DROP TABLE ' + table console.log "Executing #{sql}" exception = (e) -> console.log "Failed to drop table #{table}" console.log e statement.executeUpdate(sql).catch(exception) close = -> nodejdbc.getConnection().then (connection) -> connection.close() Promise.all(promises).finally(close) ### @Method deleteClean Deletes all the records from the tables in our Outlaw DB. @return returns a promise when all the DELETE statements are fulfilled. @todo We can also return number of records deleted for each statement. ### deleteClean = -> nodejdbc = new NodeJDBC(config) promises = tables.map (table) -> nodejdbc.createStatement().then (statement) -> sql = 'DELETE FROM ' + table console.log "Executing #{sql}" exception = (e) -> console.log "Failed to delete table #{table}" console.log e statement.executeUpdate(sql).catch(exception) # if db is not in AutoCommit mode commit = -> nodejdbc.getConnection().then (connection) -> connection.commit() close = -> nodejdbc.getConnection().then (connection) -> connection.close() Promise.all(promises).finally(close) ### @Method create executes CREATE ddl statements. @return returns a promise when all the CREATE statements are fulfilled. ### create = -> nodejdbc = new NodeJDBC(config) promises = ddls.map (ddl) -> nodejdbc.createStatement().then (statement) -> console.log "Executing \n #{ddl}" exception = (e) -> console.log e statement.executeUpdate(ddl).catch(exception) close = -> nodejdbc.getConnection().then (connection) -> connection.close() Promise.all(promises).then(close) ### @Method load Inserts records to tables. @return returns a promise when all the CREATE statements are fulfilled. ### load = -> nodejdbc = new NodeJDBC(config) promises = _.flatten(dmls).map (dml) -> nodejdbc.createStatement().then (statement) -> console.log "Executing \n #{dml}" exception = (e) -> console.log e statement.executeUpdate(dml).catch(exception) # if db is not in AutoCommit mode commit = -> nodejdbc.getConnection().then (connection) -> connection.commit() close = -> nodejdbc.getConnection().then (connection) -> connection.close() Promise.all(promises).then(close) ### @Method read executes a sample select statement and returns all the records as a json object @return [Object] result all records returned by the sample SQL query ### read = -> sql = 'SELECT NAME,AKA FROM OUTLAW' nodejdbc = new NodeJDBC(config) promise = nodejdbc.createStatement().then (statement) -> statement.executeQuery(sql).then (rs)-> result = [] while rs.next() name = rs.getString('NAME') aka = rs.getString('AKA') result.push {} = name: name aka: aka result promise.then (result) -> nodejdbc.getConnection().then (connection) -> connection.close() result # ------------------------------------------------------- # Drop -> Create -> Insert # dropClean().then(create).then(load) # ------------------------------------------------------- # ------------------------------------------------------- # Drop -> Create -> Insert -> Delete # dropClean().then(create).then(load).then(deleteClean) # ------------------------------------------------------- # ------------------------------------------------------- # Read # read().then (result) -> # console.log result # ------------------------------------------------------- config = libs : ['test/lib/ojdbc7.jar'] className: 'oracle.jdbc.driver.OracleDriver' url: 'jdbc:oracle:thin:@//win:1521/orcl', username: 'demo', password: '<PASSWORD>' nodejdbc = new NodeJDBC(config) nodejdbc.getConnection().then (connection) -> console.log 'conn is valid', connection.isValid(2) call = '{call demo.pkg_outlaw.prc_flip_coin(?,?,?)}' connection.prepareCall(call).then (statement) -> statement.setString 1, 'Heads' statement.registerOutParameter 2,'VARCHAR' statement.registerOutParameter 3,'VARCHAR' statement.executeUpdate().then ()-> console.log "Result : #{statement.getString 2 }" console.log "Message: #{statement.getString 3 }" connection.close()
true
NodeJDBC = require './lib/nodejdbc' _ = require 'lodash' Promise = require 'bluebird' OUTLAW_DDL = ' CREATE TABLE OUTLAW ( ID INT, NAME TEXT, AKA TEXT, GANG INT, BIRTH_DATE DATE, DEATH_DATE DATE, HANDEDNESS INT )' OUTLAW_DML = [ 'INSERT INTO OUTLAW (ID, NAME, AKA, GANG, BIRTH_DATE, DEATH_DATE, HANDEDNESS) VALUES (10, "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", 10, "1859.September.17","1881.July.14",10)', 'INSERT INTO OUTLAW (ID, NAME, AKA, GANG, BIRTH_DATE, DEATH_DATE, HANDEDNESS) VALUES (20, "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", 10, "1849.January.11","1929.July.25",20)', 'INSERT INTO OUTLAW (ID, NAME, AKA, GANG, BIRTH_DATE, DEATH_DATE, HANDEDNESS) VALUES (30, "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", 20, "1847.September.05","1882.April.03",20)', 'INSERT INTO OUTLAW (ID, NAME, AKA, GANG, BIRTH_DATE, DEATH_DATE, HANDEDNESS) VALUES (40, "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", 20, "1843.January.10","1915.February.18",20)', 'INSERT INTO OUTLAW (ID, NAME, AKA, GANG, BIRTH_DATE, DEATH_DATE, HANDEDNESS) VALUES (50,"PI:NAME:<NAME>END_PI","Sundance Kid",30, "1867.July.17","1908.November.07",30)', 'INSERT INTO OUTLAW (ID, NAME, AKA, GANG, BIRTH_DATE, DEATH_DATE, HANDEDNESS) VALUES (60,"PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI",30, "1867.July.17","1908.November.07",30)', 'INSERT INTO OUTLAW (ID, NAME, AKA, GANG, BIRTH_DATE, DEATH_DATE, HANDEDNESS) VALUES (70,"PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI",40, "1853.May.26","1895.Agust.19",40)' ] GANG_DDL = ' CREATE TABLE GANG ( ID INT, NAME TEXT, LEADER INT )' GANG_DML = [ 'INSERT INTO GANG (ID,NAME, LEADER) VALUES (10,"Regulators",10)', 'INSERT INTO GANG (ID,NAME, LEADER) VALUES (20,"PI:NAME:<NAME>END_PI",30)' 'INSERT INTO GANG (ID,NAME, LEADER) VALUES (30,"Wild Bunch",60)', 'INSERT INTO GANG (ID,NAME, LEADER) VALUES (40,"PI:NAME:<NAME>END_PI",70)' ] HANDEDNESS_DDL = ' CREATE TABLE HANDEDNESS ( ID INT, NAME TEXT, DESC TEXT )' HANDEDNESS_DML = [ 'INSERT INTO HANDEDNESS (ID, NAME, DESC) VALUES (10, "Left Handed", "Uses left hand primarily")', 'INSERT INTO HANDEDNESS (ID, NAME, DESC) VALUES (20, "Right Handed", "Uses right hand primarily")', 'INSERT INTO HANDEDNESS (ID, NAME, DESC) VALUES (30, "Mixed Handed", "Uses one or the other hand for different tasks")', 'INSERT INTO HANDEDNESS (ID, NAME, DESC) VALUES (40, "Ambidextrous", "Uses both hands equally.")' ] ddls = [OUTLAW_DDL,GANG_DDL,HANDEDNESS_DDL] dmls = [OUTLAW_DML,GANG_DML,HANDEDNESS_DML] tables = ['OUTLAW','GANG','HANDEDNESS'] config = libs : ['test/lib/sqlite-jdbc-3.8.11.2.jar'] className: 'org.sqlite.JDBC' url: 'jdbc:sqlite:test.db' ### @Method dropClean Drops all _DDL tables. This method throws TableNotFound exception if the tables do not exist in database. @return returns a promise when all the tables are dropped successfully ### dropClean = -> nodejdbc = new NodeJDBC(config) promises = tables.map (table) -> nodejdbc.createStatement().then (statement) -> sql = 'DROP TABLE ' + table console.log "Executing #{sql}" exception = (e) -> console.log "Failed to drop table #{table}" console.log e statement.executeUpdate(sql).catch(exception) close = -> nodejdbc.getConnection().then (connection) -> connection.close() Promise.all(promises).finally(close) ### @Method deleteClean Deletes all the records from the tables in our Outlaw DB. @return returns a promise when all the DELETE statements are fulfilled. @todo We can also return number of records deleted for each statement. ### deleteClean = -> nodejdbc = new NodeJDBC(config) promises = tables.map (table) -> nodejdbc.createStatement().then (statement) -> sql = 'DELETE FROM ' + table console.log "Executing #{sql}" exception = (e) -> console.log "Failed to delete table #{table}" console.log e statement.executeUpdate(sql).catch(exception) # if db is not in AutoCommit mode commit = -> nodejdbc.getConnection().then (connection) -> connection.commit() close = -> nodejdbc.getConnection().then (connection) -> connection.close() Promise.all(promises).finally(close) ### @Method create executes CREATE ddl statements. @return returns a promise when all the CREATE statements are fulfilled. ### create = -> nodejdbc = new NodeJDBC(config) promises = ddls.map (ddl) -> nodejdbc.createStatement().then (statement) -> console.log "Executing \n #{ddl}" exception = (e) -> console.log e statement.executeUpdate(ddl).catch(exception) close = -> nodejdbc.getConnection().then (connection) -> connection.close() Promise.all(promises).then(close) ### @Method load Inserts records to tables. @return returns a promise when all the CREATE statements are fulfilled. ### load = -> nodejdbc = new NodeJDBC(config) promises = _.flatten(dmls).map (dml) -> nodejdbc.createStatement().then (statement) -> console.log "Executing \n #{dml}" exception = (e) -> console.log e statement.executeUpdate(dml).catch(exception) # if db is not in AutoCommit mode commit = -> nodejdbc.getConnection().then (connection) -> connection.commit() close = -> nodejdbc.getConnection().then (connection) -> connection.close() Promise.all(promises).then(close) ### @Method read executes a sample select statement and returns all the records as a json object @return [Object] result all records returned by the sample SQL query ### read = -> sql = 'SELECT NAME,AKA FROM OUTLAW' nodejdbc = new NodeJDBC(config) promise = nodejdbc.createStatement().then (statement) -> statement.executeQuery(sql).then (rs)-> result = [] while rs.next() name = rs.getString('NAME') aka = rs.getString('AKA') result.push {} = name: name aka: aka result promise.then (result) -> nodejdbc.getConnection().then (connection) -> connection.close() result # ------------------------------------------------------- # Drop -> Create -> Insert # dropClean().then(create).then(load) # ------------------------------------------------------- # ------------------------------------------------------- # Drop -> Create -> Insert -> Delete # dropClean().then(create).then(load).then(deleteClean) # ------------------------------------------------------- # ------------------------------------------------------- # Read # read().then (result) -> # console.log result # ------------------------------------------------------- config = libs : ['test/lib/ojdbc7.jar'] className: 'oracle.jdbc.driver.OracleDriver' url: 'jdbc:oracle:thin:@//win:1521/orcl', username: 'demo', password: 'PI:PASSWORD:<PASSWORD>END_PI' nodejdbc = new NodeJDBC(config) nodejdbc.getConnection().then (connection) -> console.log 'conn is valid', connection.isValid(2) call = '{call demo.pkg_outlaw.prc_flip_coin(?,?,?)}' connection.prepareCall(call).then (statement) -> statement.setString 1, 'Heads' statement.registerOutParameter 2,'VARCHAR' statement.registerOutParameter 3,'VARCHAR' statement.executeUpdate().then ()-> console.log "Result : #{statement.getString 2 }" console.log "Message: #{statement.getString 3 }" connection.close()
[ { "context": "l\n\n books = [\n Book.create(name: 'foo', date: 1921, age: 51)\n Book.create(name", "end": 2779, "score": 0.9891631007194519, "start": 2776, "tag": "NAME", "value": "foo" }, { "context": "date: 1921, age: 51)\n Book.create(name: 'andy'...
test/unit/ArrayPipeline/core_method_test.coffee
kumavis/ArrayPipeline
0
require '../../test_helper.coffee' describe 'ArrayPipeline', -> describe 'plugin configuration', -> describe '#_initPlugin()', -> it 'should instantiate a plugin from a constant', -> pipeline = Em.ArrayProxy.createWithMixins(Em.ArrayPipelineMixin,{}) pipeline.get('_processors.length').should.equal(0) pipeline._initPlugin(Em.PipePlugin) pipeline.get('_processors.length').should.equal(1) pipeline.get('_processors.firstObject').should.be.instanceof(Em.PipePlugin) it 'should instantiate a plugin from a string', -> pipeline = Em.ArrayProxy.createWithMixins(Em.ArrayPipelineMixin,{}) pipeline.get('_processors.length').should.equal(0) pipeline._initPlugin('Em.PipePlugin') pipeline.get('_processors.length').should.equal(1) pipeline.get('_processors.firstObject').should.be.instanceof(Em.PipePlugin) describe '#_configurePlugins()', -> it 'should create instances of each plugin in the "plugins" array', -> FooPlugin = Em.PipePlugin.extend() pipeline = Em.ArrayProxy.createWithMixins Em.ArrayPipelineMixin, plugins: [FooPlugin, 'Em.PipePlugin'] pipeline.get('_processors.firstObject').should.be.instanceof(FooPlugin) pipeline.get('_processors.lastObject').should.be.instanceof(Em.PipePlugin) describe '#_configureObserverMap()', -> FooPlugin = Em.PipePlugin.extend observes: ['name', 'date'] BarPlugin = Em.PipePlugin.extend observes: ['name', 'age'] it 'should create a map of observable properties -> plugin instances', -> # Setup of the pipeline # We are manually configuring so that _configureObserverMap() isn't called pipeline = Em.ArrayProxy.createWithMixins Em.ArrayPipelineMixin, {} pipeline.set('plugins', [FooPlugin, BarPlugin]) pipeline._initPlugin(FooPlugin) pipeline._initPlugin(BarPlugin) # Run the configureObserverMap method pipeline._configureObserverMap() # Check to see if we get the expected results pipeline.get('_observerMap').get('name').should.be.instanceof(FooPlugin) pipeline.get('_observerMap').get('date').should.be.instanceof(FooPlugin) pipeline.get('_observerMap').get('age').should.be.instanceof(BarPlugin) describe '#_registerObservers()', -> it 'should register a single observer for each observable property', -> FooPlugin = Em.PipePlugin.extend observes: ['name', 'date'] BarPlugin = Em.PipePlugin.extend observes: ['name', 'age'] Book = Em.Object.extend name: null date: null age: null books = [ Book.create(name: 'foo', date: 1921, age: 51) Book.create(name: 'andy', date: 1984, age: 11) ] # Manually creating to avoid out of the box init behavior pipeline = Em.ArrayProxy.createWithMixins(Em.ArrayPipelineMixin, content: books) pipeline.set('plugins', [FooPlugin, BarPlugin]) pipeline._initPlugin(FooPlugin) pipeline._initPlugin(BarPlugin) pipeline._configureObserverMap() # Call our method pipeline._registerObservers() # Test to see that we have name / date observers registered pipeline.get('results').objectAt(0).observersForKey('name').length.should.equal(1) pipeline.get('results').objectAt(0).observersForKey('date').length.should.equal(1) pipeline.get('results').objectAt(0).observersForKey('age').length.should.equal(1) describe '#_processChanges()', -> it 'should trigger _recalculate() on the appropriate PipePlugin', -> ran = [] FooPlugin = Em.PipePlugin.extend observes: ['name', 'date'] _recalculate: -> ran.pushObject('pipe1') BarPlugin = Em.PipePlugin.extend observes: ['name', 'date'] _recalculate: -> ran.pushObject('pipe2') Book = Em.Object.extend name: null date: null books = [ Book.create(name: 'foo', date: 1921, age: 51) Book.create(name: 'andy', date: 1984, age: 11) ] # Create a pipeline to use pipeline = Em.ArrayProxy.createWithMixins Em.ArrayPipelineMixin, content: books plugins: [FooPlugin, BarPlugin] ran.should.deep.equal([]) pipeline.set('firstObject.name', 'barrr') ran.toArray().should.deep.equal(['pipe1', 'pipe2']) describe '#previousResults(plugin)', -> it 'should return back the results from the previous plugin that is passed in', -> Book = Em.Object.extend name: null date: null age: null FooPlugin = Em.PipePlugin.extend process: (inputArr) -> inputArr.map (item) -> return 1 BarPlugin = Em.PipePlugin.extend process: (inputArr) -> inputArr.map (item) -> return 2 books = [ Book.create(name: 'foo', date: 1921, age: 51) Book.create(name: 'andy', date: 1984, age: 11) ] pipeline = Em.ArrayProxy.createWithMixins Em.ArrayPipelineMixin, content: books plugins: [FooPlugin, BarPlugin, BarPlugin] # Trigger a calculation pipeline.get('results') # Do our test lastPlugin = pipeline.get('_processors').objectAt(1) pipeline.previousResults(lastPlugin).should.deep.equal([1,1])
166900
require '../../test_helper.coffee' describe 'ArrayPipeline', -> describe 'plugin configuration', -> describe '#_initPlugin()', -> it 'should instantiate a plugin from a constant', -> pipeline = Em.ArrayProxy.createWithMixins(Em.ArrayPipelineMixin,{}) pipeline.get('_processors.length').should.equal(0) pipeline._initPlugin(Em.PipePlugin) pipeline.get('_processors.length').should.equal(1) pipeline.get('_processors.firstObject').should.be.instanceof(Em.PipePlugin) it 'should instantiate a plugin from a string', -> pipeline = Em.ArrayProxy.createWithMixins(Em.ArrayPipelineMixin,{}) pipeline.get('_processors.length').should.equal(0) pipeline._initPlugin('Em.PipePlugin') pipeline.get('_processors.length').should.equal(1) pipeline.get('_processors.firstObject').should.be.instanceof(Em.PipePlugin) describe '#_configurePlugins()', -> it 'should create instances of each plugin in the "plugins" array', -> FooPlugin = Em.PipePlugin.extend() pipeline = Em.ArrayProxy.createWithMixins Em.ArrayPipelineMixin, plugins: [FooPlugin, 'Em.PipePlugin'] pipeline.get('_processors.firstObject').should.be.instanceof(FooPlugin) pipeline.get('_processors.lastObject').should.be.instanceof(Em.PipePlugin) describe '#_configureObserverMap()', -> FooPlugin = Em.PipePlugin.extend observes: ['name', 'date'] BarPlugin = Em.PipePlugin.extend observes: ['name', 'age'] it 'should create a map of observable properties -> plugin instances', -> # Setup of the pipeline # We are manually configuring so that _configureObserverMap() isn't called pipeline = Em.ArrayProxy.createWithMixins Em.ArrayPipelineMixin, {} pipeline.set('plugins', [FooPlugin, BarPlugin]) pipeline._initPlugin(FooPlugin) pipeline._initPlugin(BarPlugin) # Run the configureObserverMap method pipeline._configureObserverMap() # Check to see if we get the expected results pipeline.get('_observerMap').get('name').should.be.instanceof(FooPlugin) pipeline.get('_observerMap').get('date').should.be.instanceof(FooPlugin) pipeline.get('_observerMap').get('age').should.be.instanceof(BarPlugin) describe '#_registerObservers()', -> it 'should register a single observer for each observable property', -> FooPlugin = Em.PipePlugin.extend observes: ['name', 'date'] BarPlugin = Em.PipePlugin.extend observes: ['name', 'age'] Book = Em.Object.extend name: null date: null age: null books = [ Book.create(name: '<NAME>', date: 1921, age: 51) Book.create(name: '<NAME>', date: 1984, age: 11) ] # Manually creating to avoid out of the box init behavior pipeline = Em.ArrayProxy.createWithMixins(Em.ArrayPipelineMixin, content: books) pipeline.set('plugins', [FooPlugin, BarPlugin]) pipeline._initPlugin(FooPlugin) pipeline._initPlugin(BarPlugin) pipeline._configureObserverMap() # Call our method pipeline._registerObservers() # Test to see that we have name / date observers registered pipeline.get('results').objectAt(0).observersForKey('name').length.should.equal(1) pipeline.get('results').objectAt(0).observersForKey('date').length.should.equal(1) pipeline.get('results').objectAt(0).observersForKey('age').length.should.equal(1) describe '#_processChanges()', -> it 'should trigger _recalculate() on the appropriate PipePlugin', -> ran = [] FooPlugin = Em.PipePlugin.extend observes: ['name', 'date'] _recalculate: -> ran.pushObject('pipe1') BarPlugin = Em.PipePlugin.extend observes: ['name', 'date'] _recalculate: -> ran.pushObject('pipe2') Book = Em.Object.extend name: null date: null books = [ Book.create(name: '<NAME>', date: 1921, age: 51) Book.create(name: '<NAME>', date: 1984, age: 11) ] # Create a pipeline to use pipeline = Em.ArrayProxy.createWithMixins Em.ArrayPipelineMixin, content: books plugins: [FooPlugin, BarPlugin] ran.should.deep.equal([]) pipeline.set('firstObject.name', 'bar<NAME>') ran.toArray().should.deep.equal(['pipe1', 'pipe2']) describe '#previousResults(plugin)', -> it 'should return back the results from the previous plugin that is passed in', -> Book = Em.Object.extend name: null date: null age: null FooPlugin = Em.PipePlugin.extend process: (inputArr) -> inputArr.map (item) -> return 1 BarPlugin = Em.PipePlugin.extend process: (inputArr) -> inputArr.map (item) -> return 2 books = [ Book.create(name: '<NAME>', date: 1921, age: 51) Book.create(name: '<NAME>', date: 1984, age: 11) ] pipeline = Em.ArrayProxy.createWithMixins Em.ArrayPipelineMixin, content: books plugins: [FooPlugin, BarPlugin, BarPlugin] # Trigger a calculation pipeline.get('results') # Do our test lastPlugin = pipeline.get('_processors').objectAt(1) pipeline.previousResults(lastPlugin).should.deep.equal([1,1])
true
require '../../test_helper.coffee' describe 'ArrayPipeline', -> describe 'plugin configuration', -> describe '#_initPlugin()', -> it 'should instantiate a plugin from a constant', -> pipeline = Em.ArrayProxy.createWithMixins(Em.ArrayPipelineMixin,{}) pipeline.get('_processors.length').should.equal(0) pipeline._initPlugin(Em.PipePlugin) pipeline.get('_processors.length').should.equal(1) pipeline.get('_processors.firstObject').should.be.instanceof(Em.PipePlugin) it 'should instantiate a plugin from a string', -> pipeline = Em.ArrayProxy.createWithMixins(Em.ArrayPipelineMixin,{}) pipeline.get('_processors.length').should.equal(0) pipeline._initPlugin('Em.PipePlugin') pipeline.get('_processors.length').should.equal(1) pipeline.get('_processors.firstObject').should.be.instanceof(Em.PipePlugin) describe '#_configurePlugins()', -> it 'should create instances of each plugin in the "plugins" array', -> FooPlugin = Em.PipePlugin.extend() pipeline = Em.ArrayProxy.createWithMixins Em.ArrayPipelineMixin, plugins: [FooPlugin, 'Em.PipePlugin'] pipeline.get('_processors.firstObject').should.be.instanceof(FooPlugin) pipeline.get('_processors.lastObject').should.be.instanceof(Em.PipePlugin) describe '#_configureObserverMap()', -> FooPlugin = Em.PipePlugin.extend observes: ['name', 'date'] BarPlugin = Em.PipePlugin.extend observes: ['name', 'age'] it 'should create a map of observable properties -> plugin instances', -> # Setup of the pipeline # We are manually configuring so that _configureObserverMap() isn't called pipeline = Em.ArrayProxy.createWithMixins Em.ArrayPipelineMixin, {} pipeline.set('plugins', [FooPlugin, BarPlugin]) pipeline._initPlugin(FooPlugin) pipeline._initPlugin(BarPlugin) # Run the configureObserverMap method pipeline._configureObserverMap() # Check to see if we get the expected results pipeline.get('_observerMap').get('name').should.be.instanceof(FooPlugin) pipeline.get('_observerMap').get('date').should.be.instanceof(FooPlugin) pipeline.get('_observerMap').get('age').should.be.instanceof(BarPlugin) describe '#_registerObservers()', -> it 'should register a single observer for each observable property', -> FooPlugin = Em.PipePlugin.extend observes: ['name', 'date'] BarPlugin = Em.PipePlugin.extend observes: ['name', 'age'] Book = Em.Object.extend name: null date: null age: null books = [ Book.create(name: 'PI:NAME:<NAME>END_PI', date: 1921, age: 51) Book.create(name: 'PI:NAME:<NAME>END_PI', date: 1984, age: 11) ] # Manually creating to avoid out of the box init behavior pipeline = Em.ArrayProxy.createWithMixins(Em.ArrayPipelineMixin, content: books) pipeline.set('plugins', [FooPlugin, BarPlugin]) pipeline._initPlugin(FooPlugin) pipeline._initPlugin(BarPlugin) pipeline._configureObserverMap() # Call our method pipeline._registerObservers() # Test to see that we have name / date observers registered pipeline.get('results').objectAt(0).observersForKey('name').length.should.equal(1) pipeline.get('results').objectAt(0).observersForKey('date').length.should.equal(1) pipeline.get('results').objectAt(0).observersForKey('age').length.should.equal(1) describe '#_processChanges()', -> it 'should trigger _recalculate() on the appropriate PipePlugin', -> ran = [] FooPlugin = Em.PipePlugin.extend observes: ['name', 'date'] _recalculate: -> ran.pushObject('pipe1') BarPlugin = Em.PipePlugin.extend observes: ['name', 'date'] _recalculate: -> ran.pushObject('pipe2') Book = Em.Object.extend name: null date: null books = [ Book.create(name: 'PI:NAME:<NAME>END_PI', date: 1921, age: 51) Book.create(name: 'PI:NAME:<NAME>END_PI', date: 1984, age: 11) ] # Create a pipeline to use pipeline = Em.ArrayProxy.createWithMixins Em.ArrayPipelineMixin, content: books plugins: [FooPlugin, BarPlugin] ran.should.deep.equal([]) pipeline.set('firstObject.name', 'barPI:NAME:<NAME>END_PI') ran.toArray().should.deep.equal(['pipe1', 'pipe2']) describe '#previousResults(plugin)', -> it 'should return back the results from the previous plugin that is passed in', -> Book = Em.Object.extend name: null date: null age: null FooPlugin = Em.PipePlugin.extend process: (inputArr) -> inputArr.map (item) -> return 1 BarPlugin = Em.PipePlugin.extend process: (inputArr) -> inputArr.map (item) -> return 2 books = [ Book.create(name: 'PI:NAME:<NAME>END_PI', date: 1921, age: 51) Book.create(name: 'PI:NAME:<NAME>END_PI', date: 1984, age: 11) ] pipeline = Em.ArrayProxy.createWithMixins Em.ArrayPipelineMixin, content: books plugins: [FooPlugin, BarPlugin, BarPlugin] # Trigger a calculation pipeline.get('results') # Do our test lastPlugin = pipeline.get('_processors').objectAt(1) pipeline.previousResults(lastPlugin).should.deep.equal([1,1])
[ { "context": "</p><p>{{job}}</p></div>'\n data = name: 'Fatih', age: 27, job: 'Developer'\n v = new spark.c", "end": 2221, "score": 0.9995608925819397, "start": 2216, "tag": "NAME", "value": "Fatih" }, { "context": " user.lastName}}</div>'\n , user: firstName: 'Fat...
src/tests/core/test_view.coffee
dashersw/spark
1
goog = goog or goog = require: -> goog.require 'spark.core.Object' goog.require 'spark.core.View' goog.require 'spark.utils' describe 'spark.core.View', -> view = null element = null isClicked = null isHovered = null fireEvent = (type, el = element) -> event = document.createEvent 'MouseEvents' event.initEvent type, yes, yes el.dispatchEvent event beforeEach -> isClicked = null isHovered = null options = tagName : 'span' cssClass : 'hello buddy' domId : 'world' template : '<p>Hello World</p>' attributes : type : 'widget' position : 'left' events : click : -> isClicked = yes mouseover : -> isHovered = yes view = new spark.core.View options element = view.getElement() it 'should has default options if no options passed', -> v = new spark.core.View expect(v.getOptions()).not.toBe {} it 'should create a DOM element with passed options', -> expect(element).toBeDefined() expect(element.id).toBe 'world' expect(element.classList.contains('hello')).toBeTruthy() expect(element.firstChild.tagName).toBe 'P' it 'should be appendable to document body', -> # it will throw an error if it couldn't append it to dom # there is no assertion needed document.body.appendChild element it 'should bind events in events object', -> expect(isClicked).toBe null expect(isHovered).toBe null fireEvent 'click' fireEvent 'mouseover' expect(isClicked).toBe yes expect(isHovered).toBe yes it 'should return dom id', -> expect(view.getDomId()).toBe 'world' newView = new spark.core.View expect(newView.getDomId()).toBeNull() describe 'setTemplate', -> it 'should set element template', -> expect(element.firstChild.tagName).toBe 'P' view.setTemplate '<div><span></span></div>' expect(element.firstChild.tagName).toBe 'DIV' expect(element.firstChild.firstChild.tagName).toBe 'SPAN' it 'should render tags in template', -> template = '<div><p>{{name}}</p><p>{{age}}</p><p>{{job}}</p></div>' data = name: 'Fatih', age: 27, job: 'Developer' v = new spark.core.View { template }, data e = v.getElement() first = e.firstChild expect(first.tagName).toBe 'DIV' expect(first.firstChild.tagName).toBe 'P' expect(first.firstChild.innerHTML).toBe 'Fatih' expect(first.lastChild.tagName).toBe 'P' expect(first.lastChild.innerHTML).toBe 'Developer' it 'should render tags in function templates', -> v = new spark.core.View template: -> '<div>Hello {{user.firstName}} {{ user.lastName}}</div>' , user: firstName: 'Fatih', lastName: 'Acet' expect(v.getElement().firstChild.tagName).toBe 'DIV' expect(v.getElement().firstChild.innerHTML).toBe 'Hello Fatih Acet' it 'should have class data in function templates', -> v = new spark.core.View template: (data) -> "<p>Hola #{data.name}</p>" , { name: 'fatih' } expect(v.getElement().firstChild.tagName).toBe 'P' expect(v.getElement().firstChild.innerHTML).toBe 'Hola fatih' it 'should add new class', -> expect(element.classList.contains 'new-class').toBeFalsy() view.addClass 'new-class' expect(element.classList.contains 'new-class').toBeTruthy() it 'should remove a class name', -> expect(element.classList.contains 'hello').toBeTruthy() view.removeClass 'hello' expect(element.classList.contains 'hello').toBeFalsy() it 'should return class list as an array like', -> classList = view.getClassList() expect(classList.length).toBe 3 # view, hello, buddy it 'should return all class names', -> expect(view.getClass()).toBe 'view hello buddy' it 'should update class name', -> expect(element.classList.contains 'new-class-name').toBeFalsy() view.setClass 'new-class-name' expect(element.getAttribute 'class').toBe 'new-class-name' it 'should return true if element has a class name', -> expect(view.hasClass 'class-name').toBeFalsy() expect(view.hasClass 'hello').toBeTruthy() it 'should have disabled attribute when disabled', -> view.disable() expect(view.getAttribute('disabled')).toBe 'disabled' it 'should be disabled if disabled options passed', -> disabledView = new spark.core.View disabled: yes expect(disabledView.getAttribute('disabled')).toBe 'disabled' it 'should disable and enable element', -> view.toggle() expect(view.getAttribute('disabled')).toBe 'disabled' view.toggle() expect(view.getAttribute('disabled')).toBeNull() it 'should has attributes', -> expect(view.getAttribute 'type').toBe 'widget' expect(view.getAttribute 'position').toBe 'left' describe 'appendView', -> button = null child = null innerChild = null it 'should allow appending a new view into this view', -> newOne = new spark.core.View template : '<p>New View</p>' view.appendView newOne child = element.lastChild innerChild = child.firstChild expect(child.tagName).toBe 'DIV' expect(innerChild.tagName).toBe 'P' expect(innerChild.innerHTML).toBe 'New View' it 'should allow appending a new view into a view which is appended a different view', -> newOne = new spark.core.View template : '<p>New View</p>' button = new spark.components.Button title : 'Test Button' cssClass : 'new-button' newOne.appendView button expect(newOne.getElement().lastChild).toBe button.getElement() it 'should throw error if a view already appended into this view', -> newOne = new spark.core.View template : '<p>New View</p>' error = new Error 'This view already appended to target view.' button = new spark.components.Button title : 'Test Button' cssClass : 'new-button' newOne.appendView button expect( -> newOne.appendView button ).toThrow error it 'should throw error when view argument is not an instance of spark.View', -> newOne = new spark.core.View template : '<p>New View</p>' error = new Error 'View should be an instance of spark.core.View' items = [ {}, [], null, undefined, 5, 'some string' ] expect( -> newOne.appendView item).toThrow error for item in items it 'should append element to document body when appendToDocumentBody called', -> myView = new spark.core.View domId: 'myView' expect(document.getElementById('myView')).toBeNull() myView.appendToDocumentBody() expect(document.getElementById('myView')).not.toBeNull() it 'should remove element from document body if it is in the document', -> isRemoved = view.removeFromDocument() expect(isRemoved).toBeFalsy() view.appendToDocumentBody() isRemoved = view.removeFromDocument() expect(isRemoved).toBeTruthy() it 'should emit the event listener when event emitted from object and also DOM event triggered', -> fireEvent 'click' # simulate DOM click expect(isClicked).toBeTruthy() isClicked = null view.emit 'click' expect(isClicked).toBeTruthy() it 'should properly handle overridden once and off', -> state = no callback = -> state = yes view.once 'click', callback view.emit 'click' expect(state).toBeTruthy() state = no view.off 'click', callback view.emit 'click' expect(state).toBeFalsy() describe 'render', -> container = null view = null element = null beforeEach -> container = new spark.core.View view = new spark.core.View element = view.getElement() it 'should render element into another View instance', -> view.render container expect(element.parentNode).toBe container.getElement() it 'should emit ViewHasParent event', -> hasParent = no view.on 'ViewHasParent', -> hasParent = yes expect(hasParent).toBeFalsy() view.render container expect(hasParent).toBeTruthy() it 'should render into document.body', -> view.render document.body expect(element.parentNode).toBe document.body it 'should render element into a dom element', -> view.render container.getElement() expect(element.parentNode).toBe container.getElement() it 'should throw error called with an invalid render target', -> error = new Error 'Render target should be View instance or a DOM element.' expect( -> new spark.core.View renderTo: {} ).toThrow error it 'should call render if renderTo options passed', -> v = new spark.core.View renderTo: container expect(v.getElement().parentNode).toBe container.getElement() it 'should set element width if width passed in options', -> v = new spark.core.View width: 200, renderTo: document.body expect(v.getWidth()).toBe 200 expect(v.getElement().style.width).toBe '200px' it 'should set element height if height passed in options', -> v = new spark.core.View height: 200, renderTo: document.body expect(v.getHeight()).toBe 200 expect(v.getElement().style.height).toBe '200px' it 'should set element width/height after its appended to document', -> v = new spark.core.View width: 1, height: 1, renderTo: document.body expect(v.getWidth()).toBe 1 expect(v.getHeight()).toBe 1 v.setWidth 266 v.setHeight 133 expect(v.getWidth()).toBe 266 expect(v.getHeight()).toBe 133 expect(v.getElement().style.width).toBe '266px' expect(v.getElement().style.height).toBe '133px' describe 'destroy', -> it 'should destroy the view', -> v = new spark.core.View expect(v.isDestroyed()).toBeFalsy() v.destroy() expect(v.isDestroyed()).toBeTruthy() it 'should unlisten the event listeners', -> c = 0 v = new spark.core.View v.on 'click', -> c++ v.on 'custom', -> c++ v.emit 'click' expect(c).toBe 1 v.emit 'custom' expect(c).toBe 2 fireEvent 'click', v.getElement() expect(c).toBe 3 v.destroy() v.emit 'click' v.emit 'custom' fireEvent 'click' expect(c).toBe 3 it 'should remove view from document', -> v = new spark.core.View renderTo: document.body, domId: 'r2d2' expect(document.getElementById('r2d2')).not.toBeNull() v.destroy() expect(document.getElementById('r2d2')).toBeNull() it 'should destroy also children', -> v = new spark.core.View a = new spark.core.View renderTo: v b = new spark.core.View renderTo: v expect(v.children.length).toBe 2 v.destroy() expect(v.children.length).toBe 0 expect(a.isDestroyed()).toBeTruthy() expect(b.isDestroyed()).toBeTruthy()
96700
goog = goog or goog = require: -> goog.require 'spark.core.Object' goog.require 'spark.core.View' goog.require 'spark.utils' describe 'spark.core.View', -> view = null element = null isClicked = null isHovered = null fireEvent = (type, el = element) -> event = document.createEvent 'MouseEvents' event.initEvent type, yes, yes el.dispatchEvent event beforeEach -> isClicked = null isHovered = null options = tagName : 'span' cssClass : 'hello buddy' domId : 'world' template : '<p>Hello World</p>' attributes : type : 'widget' position : 'left' events : click : -> isClicked = yes mouseover : -> isHovered = yes view = new spark.core.View options element = view.getElement() it 'should has default options if no options passed', -> v = new spark.core.View expect(v.getOptions()).not.toBe {} it 'should create a DOM element with passed options', -> expect(element).toBeDefined() expect(element.id).toBe 'world' expect(element.classList.contains('hello')).toBeTruthy() expect(element.firstChild.tagName).toBe 'P' it 'should be appendable to document body', -> # it will throw an error if it couldn't append it to dom # there is no assertion needed document.body.appendChild element it 'should bind events in events object', -> expect(isClicked).toBe null expect(isHovered).toBe null fireEvent 'click' fireEvent 'mouseover' expect(isClicked).toBe yes expect(isHovered).toBe yes it 'should return dom id', -> expect(view.getDomId()).toBe 'world' newView = new spark.core.View expect(newView.getDomId()).toBeNull() describe 'setTemplate', -> it 'should set element template', -> expect(element.firstChild.tagName).toBe 'P' view.setTemplate '<div><span></span></div>' expect(element.firstChild.tagName).toBe 'DIV' expect(element.firstChild.firstChild.tagName).toBe 'SPAN' it 'should render tags in template', -> template = '<div><p>{{name}}</p><p>{{age}}</p><p>{{job}}</p></div>' data = name: '<NAME>', age: 27, job: 'Developer' v = new spark.core.View { template }, data e = v.getElement() first = e.firstChild expect(first.tagName).toBe 'DIV' expect(first.firstChild.tagName).toBe 'P' expect(first.firstChild.innerHTML).toBe 'Fatih' expect(first.lastChild.tagName).toBe 'P' expect(first.lastChild.innerHTML).toBe 'Developer' it 'should render tags in function templates', -> v = new spark.core.View template: -> '<div>Hello {{user.firstName}} {{ user.lastName}}</div>' , user: firstName: '<NAME>', lastName: '<NAME>' expect(v.getElement().firstChild.tagName).toBe 'DIV' expect(v.getElement().firstChild.innerHTML).toBe 'Hello <NAME>' it 'should have class data in function templates', -> v = new spark.core.View template: (data) -> "<p>Hola #{data.name}</p>" , { name: '<NAME>' } expect(v.getElement().firstChild.tagName).toBe 'P' expect(v.getElement().firstChild.innerHTML).toBe 'Hola fat<NAME>' it 'should add new class', -> expect(element.classList.contains 'new-class').toBeFalsy() view.addClass 'new-class' expect(element.classList.contains 'new-class').toBeTruthy() it 'should remove a class name', -> expect(element.classList.contains 'hello').toBeTruthy() view.removeClass 'hello' expect(element.classList.contains 'hello').toBeFalsy() it 'should return class list as an array like', -> classList = view.getClassList() expect(classList.length).toBe 3 # view, hello, buddy it 'should return all class names', -> expect(view.getClass()).toBe 'view hello buddy' it 'should update class name', -> expect(element.classList.contains 'new-class-name').toBeFalsy() view.setClass 'new-class-name' expect(element.getAttribute 'class').toBe 'new-class-name' it 'should return true if element has a class name', -> expect(view.hasClass 'class-name').toBeFalsy() expect(view.hasClass 'hello').toBeTruthy() it 'should have disabled attribute when disabled', -> view.disable() expect(view.getAttribute('disabled')).toBe 'disabled' it 'should be disabled if disabled options passed', -> disabledView = new spark.core.View disabled: yes expect(disabledView.getAttribute('disabled')).toBe 'disabled' it 'should disable and enable element', -> view.toggle() expect(view.getAttribute('disabled')).toBe 'disabled' view.toggle() expect(view.getAttribute('disabled')).toBeNull() it 'should has attributes', -> expect(view.getAttribute 'type').toBe 'widget' expect(view.getAttribute 'position').toBe 'left' describe 'appendView', -> button = null child = null innerChild = null it 'should allow appending a new view into this view', -> newOne = new spark.core.View template : '<p>New View</p>' view.appendView newOne child = element.lastChild innerChild = child.firstChild expect(child.tagName).toBe 'DIV' expect(innerChild.tagName).toBe 'P' expect(innerChild.innerHTML).toBe 'New View' it 'should allow appending a new view into a view which is appended a different view', -> newOne = new spark.core.View template : '<p>New View</p>' button = new spark.components.Button title : 'Test Button' cssClass : 'new-button' newOne.appendView button expect(newOne.getElement().lastChild).toBe button.getElement() it 'should throw error if a view already appended into this view', -> newOne = new spark.core.View template : '<p>New View</p>' error = new Error 'This view already appended to target view.' button = new spark.components.Button title : 'Test Button' cssClass : 'new-button' newOne.appendView button expect( -> newOne.appendView button ).toThrow error it 'should throw error when view argument is not an instance of spark.View', -> newOne = new spark.core.View template : '<p>New View</p>' error = new Error 'View should be an instance of spark.core.View' items = [ {}, [], null, undefined, 5, 'some string' ] expect( -> newOne.appendView item).toThrow error for item in items it 'should append element to document body when appendToDocumentBody called', -> myView = new spark.core.View domId: 'myView' expect(document.getElementById('myView')).toBeNull() myView.appendToDocumentBody() expect(document.getElementById('myView')).not.toBeNull() it 'should remove element from document body if it is in the document', -> isRemoved = view.removeFromDocument() expect(isRemoved).toBeFalsy() view.appendToDocumentBody() isRemoved = view.removeFromDocument() expect(isRemoved).toBeTruthy() it 'should emit the event listener when event emitted from object and also DOM event triggered', -> fireEvent 'click' # simulate DOM click expect(isClicked).toBeTruthy() isClicked = null view.emit 'click' expect(isClicked).toBeTruthy() it 'should properly handle overridden once and off', -> state = no callback = -> state = yes view.once 'click', callback view.emit 'click' expect(state).toBeTruthy() state = no view.off 'click', callback view.emit 'click' expect(state).toBeFalsy() describe 'render', -> container = null view = null element = null beforeEach -> container = new spark.core.View view = new spark.core.View element = view.getElement() it 'should render element into another View instance', -> view.render container expect(element.parentNode).toBe container.getElement() it 'should emit ViewHasParent event', -> hasParent = no view.on 'ViewHasParent', -> hasParent = yes expect(hasParent).toBeFalsy() view.render container expect(hasParent).toBeTruthy() it 'should render into document.body', -> view.render document.body expect(element.parentNode).toBe document.body it 'should render element into a dom element', -> view.render container.getElement() expect(element.parentNode).toBe container.getElement() it 'should throw error called with an invalid render target', -> error = new Error 'Render target should be View instance or a DOM element.' expect( -> new spark.core.View renderTo: {} ).toThrow error it 'should call render if renderTo options passed', -> v = new spark.core.View renderTo: container expect(v.getElement().parentNode).toBe container.getElement() it 'should set element width if width passed in options', -> v = new spark.core.View width: 200, renderTo: document.body expect(v.getWidth()).toBe 200 expect(v.getElement().style.width).toBe '200px' it 'should set element height if height passed in options', -> v = new spark.core.View height: 200, renderTo: document.body expect(v.getHeight()).toBe 200 expect(v.getElement().style.height).toBe '200px' it 'should set element width/height after its appended to document', -> v = new spark.core.View width: 1, height: 1, renderTo: document.body expect(v.getWidth()).toBe 1 expect(v.getHeight()).toBe 1 v.setWidth 266 v.setHeight 133 expect(v.getWidth()).toBe 266 expect(v.getHeight()).toBe 133 expect(v.getElement().style.width).toBe '266px' expect(v.getElement().style.height).toBe '133px' describe 'destroy', -> it 'should destroy the view', -> v = new spark.core.View expect(v.isDestroyed()).toBeFalsy() v.destroy() expect(v.isDestroyed()).toBeTruthy() it 'should unlisten the event listeners', -> c = 0 v = new spark.core.View v.on 'click', -> c++ v.on 'custom', -> c++ v.emit 'click' expect(c).toBe 1 v.emit 'custom' expect(c).toBe 2 fireEvent 'click', v.getElement() expect(c).toBe 3 v.destroy() v.emit 'click' v.emit 'custom' fireEvent 'click' expect(c).toBe 3 it 'should remove view from document', -> v = new spark.core.View renderTo: document.body, domId: 'r2d2' expect(document.getElementById('r2d2')).not.toBeNull() v.destroy() expect(document.getElementById('r2d2')).toBeNull() it 'should destroy also children', -> v = new spark.core.View a = new spark.core.View renderTo: v b = new spark.core.View renderTo: v expect(v.children.length).toBe 2 v.destroy() expect(v.children.length).toBe 0 expect(a.isDestroyed()).toBeTruthy() expect(b.isDestroyed()).toBeTruthy()
true
goog = goog or goog = require: -> goog.require 'spark.core.Object' goog.require 'spark.core.View' goog.require 'spark.utils' describe 'spark.core.View', -> view = null element = null isClicked = null isHovered = null fireEvent = (type, el = element) -> event = document.createEvent 'MouseEvents' event.initEvent type, yes, yes el.dispatchEvent event beforeEach -> isClicked = null isHovered = null options = tagName : 'span' cssClass : 'hello buddy' domId : 'world' template : '<p>Hello World</p>' attributes : type : 'widget' position : 'left' events : click : -> isClicked = yes mouseover : -> isHovered = yes view = new spark.core.View options element = view.getElement() it 'should has default options if no options passed', -> v = new spark.core.View expect(v.getOptions()).not.toBe {} it 'should create a DOM element with passed options', -> expect(element).toBeDefined() expect(element.id).toBe 'world' expect(element.classList.contains('hello')).toBeTruthy() expect(element.firstChild.tagName).toBe 'P' it 'should be appendable to document body', -> # it will throw an error if it couldn't append it to dom # there is no assertion needed document.body.appendChild element it 'should bind events in events object', -> expect(isClicked).toBe null expect(isHovered).toBe null fireEvent 'click' fireEvent 'mouseover' expect(isClicked).toBe yes expect(isHovered).toBe yes it 'should return dom id', -> expect(view.getDomId()).toBe 'world' newView = new spark.core.View expect(newView.getDomId()).toBeNull() describe 'setTemplate', -> it 'should set element template', -> expect(element.firstChild.tagName).toBe 'P' view.setTemplate '<div><span></span></div>' expect(element.firstChild.tagName).toBe 'DIV' expect(element.firstChild.firstChild.tagName).toBe 'SPAN' it 'should render tags in template', -> template = '<div><p>{{name}}</p><p>{{age}}</p><p>{{job}}</p></div>' data = name: 'PI:NAME:<NAME>END_PI', age: 27, job: 'Developer' v = new spark.core.View { template }, data e = v.getElement() first = e.firstChild expect(first.tagName).toBe 'DIV' expect(first.firstChild.tagName).toBe 'P' expect(first.firstChild.innerHTML).toBe 'Fatih' expect(first.lastChild.tagName).toBe 'P' expect(first.lastChild.innerHTML).toBe 'Developer' it 'should render tags in function templates', -> v = new spark.core.View template: -> '<div>Hello {{user.firstName}} {{ user.lastName}}</div>' , user: firstName: 'PI:NAME:<NAME>END_PI', lastName: 'PI:NAME:<NAME>END_PI' expect(v.getElement().firstChild.tagName).toBe 'DIV' expect(v.getElement().firstChild.innerHTML).toBe 'Hello PI:NAME:<NAME>END_PI' it 'should have class data in function templates', -> v = new spark.core.View template: (data) -> "<p>Hola #{data.name}</p>" , { name: 'PI:NAME:<NAME>END_PI' } expect(v.getElement().firstChild.tagName).toBe 'P' expect(v.getElement().firstChild.innerHTML).toBe 'Hola fatPI:NAME:<NAME>END_PI' it 'should add new class', -> expect(element.classList.contains 'new-class').toBeFalsy() view.addClass 'new-class' expect(element.classList.contains 'new-class').toBeTruthy() it 'should remove a class name', -> expect(element.classList.contains 'hello').toBeTruthy() view.removeClass 'hello' expect(element.classList.contains 'hello').toBeFalsy() it 'should return class list as an array like', -> classList = view.getClassList() expect(classList.length).toBe 3 # view, hello, buddy it 'should return all class names', -> expect(view.getClass()).toBe 'view hello buddy' it 'should update class name', -> expect(element.classList.contains 'new-class-name').toBeFalsy() view.setClass 'new-class-name' expect(element.getAttribute 'class').toBe 'new-class-name' it 'should return true if element has a class name', -> expect(view.hasClass 'class-name').toBeFalsy() expect(view.hasClass 'hello').toBeTruthy() it 'should have disabled attribute when disabled', -> view.disable() expect(view.getAttribute('disabled')).toBe 'disabled' it 'should be disabled if disabled options passed', -> disabledView = new spark.core.View disabled: yes expect(disabledView.getAttribute('disabled')).toBe 'disabled' it 'should disable and enable element', -> view.toggle() expect(view.getAttribute('disabled')).toBe 'disabled' view.toggle() expect(view.getAttribute('disabled')).toBeNull() it 'should has attributes', -> expect(view.getAttribute 'type').toBe 'widget' expect(view.getAttribute 'position').toBe 'left' describe 'appendView', -> button = null child = null innerChild = null it 'should allow appending a new view into this view', -> newOne = new spark.core.View template : '<p>New View</p>' view.appendView newOne child = element.lastChild innerChild = child.firstChild expect(child.tagName).toBe 'DIV' expect(innerChild.tagName).toBe 'P' expect(innerChild.innerHTML).toBe 'New View' it 'should allow appending a new view into a view which is appended a different view', -> newOne = new spark.core.View template : '<p>New View</p>' button = new spark.components.Button title : 'Test Button' cssClass : 'new-button' newOne.appendView button expect(newOne.getElement().lastChild).toBe button.getElement() it 'should throw error if a view already appended into this view', -> newOne = new spark.core.View template : '<p>New View</p>' error = new Error 'This view already appended to target view.' button = new spark.components.Button title : 'Test Button' cssClass : 'new-button' newOne.appendView button expect( -> newOne.appendView button ).toThrow error it 'should throw error when view argument is not an instance of spark.View', -> newOne = new spark.core.View template : '<p>New View</p>' error = new Error 'View should be an instance of spark.core.View' items = [ {}, [], null, undefined, 5, 'some string' ] expect( -> newOne.appendView item).toThrow error for item in items it 'should append element to document body when appendToDocumentBody called', -> myView = new spark.core.View domId: 'myView' expect(document.getElementById('myView')).toBeNull() myView.appendToDocumentBody() expect(document.getElementById('myView')).not.toBeNull() it 'should remove element from document body if it is in the document', -> isRemoved = view.removeFromDocument() expect(isRemoved).toBeFalsy() view.appendToDocumentBody() isRemoved = view.removeFromDocument() expect(isRemoved).toBeTruthy() it 'should emit the event listener when event emitted from object and also DOM event triggered', -> fireEvent 'click' # simulate DOM click expect(isClicked).toBeTruthy() isClicked = null view.emit 'click' expect(isClicked).toBeTruthy() it 'should properly handle overridden once and off', -> state = no callback = -> state = yes view.once 'click', callback view.emit 'click' expect(state).toBeTruthy() state = no view.off 'click', callback view.emit 'click' expect(state).toBeFalsy() describe 'render', -> container = null view = null element = null beforeEach -> container = new spark.core.View view = new spark.core.View element = view.getElement() it 'should render element into another View instance', -> view.render container expect(element.parentNode).toBe container.getElement() it 'should emit ViewHasParent event', -> hasParent = no view.on 'ViewHasParent', -> hasParent = yes expect(hasParent).toBeFalsy() view.render container expect(hasParent).toBeTruthy() it 'should render into document.body', -> view.render document.body expect(element.parentNode).toBe document.body it 'should render element into a dom element', -> view.render container.getElement() expect(element.parentNode).toBe container.getElement() it 'should throw error called with an invalid render target', -> error = new Error 'Render target should be View instance or a DOM element.' expect( -> new spark.core.View renderTo: {} ).toThrow error it 'should call render if renderTo options passed', -> v = new spark.core.View renderTo: container expect(v.getElement().parentNode).toBe container.getElement() it 'should set element width if width passed in options', -> v = new spark.core.View width: 200, renderTo: document.body expect(v.getWidth()).toBe 200 expect(v.getElement().style.width).toBe '200px' it 'should set element height if height passed in options', -> v = new spark.core.View height: 200, renderTo: document.body expect(v.getHeight()).toBe 200 expect(v.getElement().style.height).toBe '200px' it 'should set element width/height after its appended to document', -> v = new spark.core.View width: 1, height: 1, renderTo: document.body expect(v.getWidth()).toBe 1 expect(v.getHeight()).toBe 1 v.setWidth 266 v.setHeight 133 expect(v.getWidth()).toBe 266 expect(v.getHeight()).toBe 133 expect(v.getElement().style.width).toBe '266px' expect(v.getElement().style.height).toBe '133px' describe 'destroy', -> it 'should destroy the view', -> v = new spark.core.View expect(v.isDestroyed()).toBeFalsy() v.destroy() expect(v.isDestroyed()).toBeTruthy() it 'should unlisten the event listeners', -> c = 0 v = new spark.core.View v.on 'click', -> c++ v.on 'custom', -> c++ v.emit 'click' expect(c).toBe 1 v.emit 'custom' expect(c).toBe 2 fireEvent 'click', v.getElement() expect(c).toBe 3 v.destroy() v.emit 'click' v.emit 'custom' fireEvent 'click' expect(c).toBe 3 it 'should remove view from document', -> v = new spark.core.View renderTo: document.body, domId: 'r2d2' expect(document.getElementById('r2d2')).not.toBeNull() v.destroy() expect(document.getElementById('r2d2')).toBeNull() it 'should destroy also children', -> v = new spark.core.View a = new spark.core.View renderTo: v b = new spark.core.View renderTo: v expect(v.children.length).toBe 2 v.destroy() expect(v.children.length).toBe 0 expect(a.isDestroyed()).toBeTruthy() expect(b.isDestroyed()).toBeTruthy()
[ { "context": " ${ } }$.\",\n\n html: \"<div class='@{od.markup.content}@'>\"+\n \"<span class=", "end": 8238, "score": 0.5615093111991882, "start": 8238, "tag": "EMAIL", "value": "" }, { "context": "${ } }$.\",\n\n html: \"<div class='@{od.markup.co...
src/odysseus.coffee
playlyfe/odysseus
0
((global, factory) -> # AMD. Register as anonymous module. if typeof define is 'function' and define.amd define ['lodash', 'moment', 'bignumber'], factory # CommonJS. As a node module. else if typeof exports is 'object' module.exports = factory( require('lodash'), require('moment'), require('bignumber.js') ) else global['Odysseus'] = factory( global['_'], global['moment'], global['BigNumber'] ) )(this, (_, moment, BigNumber) -> # Override the templating delimiters to distinguish from HTML tags _.templateSettings.interpolate = /@\{([\s\S]+?)\}@/g _.templateSettings.escape = /\{\{([\s\S]+?)\}\}/g _.templateSettings.evaluate = /\$\{([\s\S]+?)\}\$/g _.templateSettings.variable = 'od' _.templateSettings.imports = { '_': _ # Pass the default lodash object 'moment': moment # Pass moment for time transformations 'ZERO': new BigNumber(0) # Since bigNumber isn't really required, # so just send a big ZERO to enable maths. }; class Odysseus ###* * A map of the default markup tags to be inserted into the rendered HTML * in-case no object is supplied in the constructor * @type {Object} ### @default_markup: { content: "od-content", image: "od-image", actor: "od-actor", target: "od-target", object: "od-object", role_list: "od-role-list", role: "od-role", lane: "od-lane", timestamp: "od-ts" } ###* * A list of all the available templates * @type {Object} ### @stored_templates: { ###* * Activity Templates ### "create": { text: " [{{moment(od.story.timestamp).format('llll')}}] - \ {{ od.story.admin ? '[Admin Event] ' : '' }}\ The '{{ \ od.story.team ? od.story.team.name || od.story.team.id : od.story.process.name || od.story.process.id \ }}' \ {{ od.ctx.isTeam ? 'team' : 'process' }} was created\ ${ if (!od.story.admin) { }$ \ by {{ od.ctx.amActor ? 'you' : od.story.actor.alias || od.story.actor.id}}\ ${ } }$. " html: " <div class='@{od.markup.content}@'>\ The <span class='@{od.markup.object}@'>\ {{od.story.team ? od.story.team.name || od.story.team.id : od.story.process.name || od.story.process.id}}\ </span> {{od.ctx.isTeam ? 'team' : 'process'}} was created\ ${ if (!od.story.admin) { }$ \ by <span class='@{od.markup.actor}@'>\ {{ od.ctx.amActor ? 'you' : od.story.actor.alias || od.story.actor.id }}\ </span>\ ${ } }$.\ ${ if (!!od.story.admin) { }$\ <footer class='@{od.markup.footer}@'>\ <span class='@{od.markup.admin}@'>Admin Event</span>\ </footer>\ ${ } }$\ </div>\ <time class='@{od.markup.timestamp}@' title='On \ {{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>\ {{ts.fromNow()}}</time> " image: '' }, "delete": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{od.ctx.amActor ? 'You' : od.story.actor.alias||od.story.actor.id}} deleted \ the {{od.ctx.isTeam ? 'team' : 'process'}} \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'." html: "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'You' : od.story.actor.alias||od.story.actor.id}}"+ "</span> deleted the {{od.ctx.isTeam ? 'team' : 'process'}} "+ "<span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>" image: '' }, "join": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{ od.story.admin ? '[Admin Event] ' : '' }}\ {{od.ctx.amActor ? 'You' : od.story.actor.alias||od.story.actor.id}} joined \ {{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$ as \ ${ if (od.ctx.isTeam) { }$\ {{_.keys(od.story.roles).join(', ')}}\ ${ } else if (od.ctx.isProcess) { }$\ {{_.reduce(od.story.roles, function(list, role, lane) {\ list.push([\ role + ' in ' + \ (lane === '*' ? 'All lanes' : \ lane === '~' ? 'No lanes' : (lane + ' lane'))\ ]);\ return list;\ }, []).join(', ')}}\ ${ } }$." html: "<div class='@{od.markup.content}@'>\ <span class='@{od.markup.actor}@'>\ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}}\ </span> joined \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ <span class='@{od.markup.object}@'>\ {{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}\ </span>\ ${ } }$ as \ <ul class='@{od.markup.role_list}@'>\ ${ if (od.ctx.isTeam) { }$\ ${ _.forEach(od.story.roles, function(enabled, role) { }$\ <li><span class='@{od.markup.role}@'>{{role}}</span></li>\ ${ }) }$\ ${ } else if (od.ctx.isProcess) { }$\ ${ _.forEach(od.story.roles, function(role, lane) { }$\ <li>\ <span class='@{od.markup.role}@'>{{role}}</span> in \ <span class='@{od.markup.lane}@'>\ {{lane === '*' ? 'All' : lane === '~' ? 'No' : lane}}\ </span> \ {{lane === '*'||lane === '~' ? 'lanes' : 'lane' }}\ </li>\ ${ })}$\ ${ } }$</ul>.\ ${ if (!!od.story.admin) { }$\ <footer class='@{od.markup.footer}@'>\ <span class='@{od.markup.admin}@'>Admin Event</span>\ </footer>\ ${ } }$\ </div>\ <time class='@{od.markup.timestamp}@' title='On \ {{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>\ {{ts.fromNow()}}</time>", image: """ ${ if (od.ctx.isDummy) { }$\ <i class='@{od.markup.dummy_icon}@'></i>\ ${ } else { }$\ <img \ src='{{od.ext.base_url}}/{{od.ctx.amActor ? \ od.ext.profile.id : od.story.actor.id}}'>\ ${ } }$ """ }, "leave": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{od.ctx.amActor ? 'You' : od.story.actor.alias||od.story.actor.id}} left \ {{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$.", html: "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'You' : od.story.actor.alias||od.story.actor.id}}"+ "</span> left "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>" image: '' }, "kick": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{od.ctx.amActor ? 'You' : od.story.actor.alias||od.story.actor.id}} kicked \ {{od.ctx.amPlayer ? 'you' : od.story.player.alias||od.story.player.id}} from \ {{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$.", html: "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'You' : od.story.actor.alias||od.story.actor.id}}"+ "</span> kicked "+ "<span class='@{od.markup.target}@'>"+ "{{od.ctx.amPlayer ? 'you' : od.story.player.alias||od.story.player.id}}"+ "</span> from "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>" image: '' }, "join:request:accept": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{od.ctx.amPlayer ? 'Your' : \ (od.story.player.alias||od.story.player.id) + '\u2019s'}} \ request to join \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$ has been accepted by \ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}}.", html: "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.target}@'>"+ "{{od.ctx.amPlayer ? 'Your' : (od.story.player.alias||od.story.player.id) + '\u2019s'}}"+ "</span> request to join "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$ has been accepted by "+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'you' : od.story.actor.alias||od.story.actor.id}}"+ "</span>."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>" image: '' }, "join:request:reject": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{od.ctx.amPlayer ? 'Your' : \ (od.story.player.alias||od.story.player.id) + '\u2019s'}} \ request to join \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$ has been rejected by \ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}}." html: "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.target}@'>"+ "{{od.ctx.amPlayer ? 'Your' : (od.story.player.alias||od.story.player.id) + '\u2019s'}}"+ "</span> request to join "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$ has been rejected by "+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'you' : od.story.actor.alias||od.story.actor.id}}"+ "</span>."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>" image: '' }, "invite:accept": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}} accepted \ {{od.ctx.amInviter ? 'your' : \ (od.story.inviter.alias||od.story.inviter.id) + '\u2019s'}} \ invitation to join \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id : \ od.story.process.name || od.story.process.id}}'\ ${ } }$ as \ ${ if (od.ctx.isTeam) { }$\ {{_.keys(od.story.roles).join(', ')}}\ ${ } else if (od.ctx.isProcess) { }$\ {{_.reduce(od.story.roles, function(list, role, lane) {\ list.push([\ role + ' in ' + \ (lane === '*' ? 'All lanes' : \ lane === '~' ? 'No lanes' : (lane + ' lane'))\ ]);\ return list;\ }, []).join(', ')}}\ ${ } }$." html: "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'You' : od.story.actor.alias||od.story.actor.id}}"+ "</span> accepted "+ "<span class='@{od.markup.target}@'>"+ "{{od.ctx.amInviter ? 'your' : (od.story.inviter.alias||od.story.inviter.id) + '\u2019s'}}"+ "</span> invitation to join "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$ as "+ "<ul class='@{od.markup.role_list}@'>"+ "${ if (od.ctx.isTeam) { }$"+ "${ _.forEach(od.story.roles, function(enabled, role) { }$"+ "<li><span class='@{od.markup.role}@'>{{role}}</span></li>"+ "${ }) }$"+ "${ } else if (od.ctx.isProcess) { }$"+ "${ _.forEach(od.story.roles, function(role, lane) { }$"+ "<li>"+ "<span class='@{od.markup.role}@'>{{role}}</span> in "+ "<span class='@{od.markup.lane}@'>"+ "{{lane === '*' ? 'All' : lane === '~' ? 'No' : lane}}"+ "</span> {{lane === '*'||lane === '~' ? 'lanes' : 'lane' }}"+ "</li>"+ "${ })}$"+ "${ } }$</ul>."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>" image: '' }, "invite:reject": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}} rejected \ {{od.ctx.amInviter ? 'your' : \ (od.story.inviter.alias||od.story.inviter.id) + '\u2019s'}} \ invitation to join \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id : \ od.story.process.name || od.story.process.id}}'\ ${ } }$ as \ ${ if (od.ctx.isTeam) { }$\ {{_.keys(od.story.roles).join(', ')}}\ ${ } else if (od.ctx.isProcess) { }$\ {{_.reduce(od.story.roles, function(list, role, lane) {\ list.push([\ role + ' in ' + \ (lane === '*' ? 'All lanes' : \ lane === '~' ? 'No lanes' : (lane + ' lane'))\ ]);\ return list;\ }, []).join(', ')}}\ ${ } }$." html: "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'You' : od.story.actor.alias||od.story.actor.id}}"+ "</span> rejected "+ "<span class='@{od.markup.target}@'>"+ "{{od.ctx.amInviter ? 'your' : (od.story.inviter.alias||od.story.inviter.id) + '\u2019s'}}"+ "</span> invitation to join "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$ as "+ "<ul class='@{od.markup.role_list}@'>"+ "${ if (od.ctx.isTeam) { }$"+ "${ _.forEach(od.story.roles, function(enabled, role) { }$"+ "<li><span class='@{od.markup.role}@'>{{role}}</span></li>"+ "${ }) }$"+ "${ } else if (od.ctx.isProcess) { }$"+ "${ _.forEach(od.story.roles, function(role, lane) { }$"+ "<li>"+ "<span class='@{od.markup.role}@'>{{role}}</span> in "+ "<span class='@{od.markup.lane}@'>"+ "{{lane === '*' ? 'All' : lane === '~' ? 'No' : lane}}"+ "</span> {{lane === '*'||lane === '~' ? 'lanes' : 'lane' }}"+ "</li>"+ "${ })}$"+ "${ } }$</ul>."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>" image: '' }, "role:request:accept": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{od.ctx.amPlayer ? 'Your' : \ (od.story.player.alias||od.story.player.id) + '\u2019s'}} \ request for a change of roles in \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$ has been accepted by \ {{od.ctx.amActor ? 'you' : \ od.story.actor.alias||od.story.actor.id}}.\ \n Changes:\ ${ if (od.ctx.isTeam) {\ _.forEach(od.story.changes, function(diff, role) { }$\ \n [{{ !diff.old ? '+' : '-'}}] {{role}}\ ${ }); }$\ ${ } else if (od.ctx.isProcess) {\ _.forEach(od.story.changes, function(diff, lane) {\ if(!!diff['old'] && !!diff['new']) { }$\ \n [+] {{diff['new']}} in {{lane}} lane\ \n [-] {{diff['old']}} in {{lane}} lane\ ${ } else { }$\ \n [{{ !diff.old ? '+' : '-'}}] \ {{diff['new'] || diff['old']}} in \ {{lane === '*' ? 'All lanes' : \ lane === '~' ? 'No lanes' : (lane + ' lane')}}\ ${ }\ });\ } }$" html: "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.target}@'>"+ "{{od.ctx.amPlayer ? 'Your' : (od.story.player.alias||od.story.player.id) + '\u2019s'}}"+ "</span> request for a change of roles in "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$ has been accepted by "+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'you' : od.story.actor.alias||od.story.actor.id}}"+ "</span>."+ "<ul class='@{od.markup.role_list}@ @{od.markup.diff_list}@'>"+ "<li class='@{od.markup.list_header}@'>Changes</li>"+ "${ if (od.ctx.isTeam) {"+ "_.forEach(od.story.changes, function(diff, role) { }$"+ "<li class='@{od.markup[!diff.old ? 'diff_add' : 'diff_rem']}@'>"+ "<span class='@{od.markup.role}@'>{{role}}</span>"+ "</li>"+ "${ }); }$"+ "${ } else if (od.ctx.isProcess) {"+ "_.forEach(od.story.changes, function(diff, lane) {"+ # if both new and old keys exist, the role was changed "if(!!diff['old'] && !!diff['new']) { }$"+ "<li class='@{od.markup.diff_change}@'>"+ "<span class='@{od.markup.role}@ @{od.markup.diff_add}@'>{{diff['new']}}</span> from "+ "<span class='@{od.markup.role}@ @{od.markup.diff_rem}@'>{{diff['old']}}</span> in "+ "<span class='@{od.markup.lane}@'>{{lane}}</span> lane"+ "</li>"+ "${ } else { }$"+ "<li class='@{od.markup[!diff.old ? 'diff_add' : 'diff_rem']}@'>"+ "<span class='@{od.markup.role}@'>{{diff['new'] || diff['old']}}</span> in "+ "<span class='@{od.markup.lane}@'>"+ "{{lane === '*' ? 'All' : lane === '~' ? 'No' : lane}}"+ "</span> {{lane === '*'||lane === '~' ? 'lanes' : 'lane' }}"+ "</li>"+ "${ } }$"+ "${ }); }$"+ "${ } }$"+ "</ul>."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>" image: '' }, "role:request:reject": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{od.ctx.amPlayer ? 'Your' : \ (od.story.player.alias||od.story.player.id) + '\u2019s'}} \ request for a change of roles in \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$ has been rejected by \ {{od.ctx.amActor ? 'you' : \ od.story.actor.alias||od.story.actor.id}}." html: "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.target}@'>"+ "{{od.ctx.amPlayer ? 'Your' : (od.story.player.alias||od.story.player.id) + '\u2019s'}}"+ "</span> request for a change of roles in "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$ has been rejected by "+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'you' : od.story.actor.alias||od.story.actor.id}}"+ "</span>."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>" image: '' }, "role:change": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ ${ if (od.story.admin) { }$\ [Admin Event] \ {{od.ctx.amActor ? 'Your' : \ (od.story.actor.alias||od.story.actor.id)+'\u2019s'}}\ ${ } else { }$\ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}} \ {{od.ctx.amActor ? 'have' : 'has'}} changed\ ${ } }$ roles in \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$\ {{ !!od.story.admin ? ' have been changed' : ''}}.\ \n Changes:\ ${ if (od.ctx.isTeam) {\ _.forEach(od.story.changes, function(diff, role) { }$\ \n [{{ !diff.old ? '+' : '-'}}] {{role}}\ ${ }); }$\ ${ } else if (od.ctx.isProcess) {\ _.forEach(od.story.changes, function(diff, lane) {\ if(!!diff['old'] && !!diff['new']) { }$\ \n [+] {{diff['new']}} in {{lane}} lane\ \n [-] {{diff['old']}} in {{lane}} lane\ ${ } else { }$\ \n [{{ !diff.old ? '+' : '-'}}] \ {{diff['new'] || diff['old']}} in \ {{lane === '*' ? 'All lanes' : \ lane === '~' ? 'No lanes' : (lane + ' lane')}}\ ${ }\ });\ } }$" html: "<div class='@{od.markup.content}@'>\ ${ if (od.story.admin) { }$\ <span class='@{od.markup.target}@'>\ {{od.ctx.amActor ? 'Your' : \ (od.story.actor.alias||od.story.actor.id)+'\u2019s'}}\ </span>\ ${ } else { }$\ <span class='@{od.markup.actor}@'>\ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}}\ </span> \ {{od.ctx.amActor ? 'have' : 'has'}} changed\ ${ } }$ roles in \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ <span class='@{od.markup.object}@'>\ {{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}\ </span>\ ${ } }$\ {{ !!od.story.admin ? ' have been changed' : ''}}.\ <ul class='@{od.markup.role_list}@ @{od.markup.diff_list}@'>\ <li class='@{od.markup.list_header}@'>Changes</li>\ ${ if (od.ctx.isTeam) {\ _.forEach(od.story.changes, function(diff, role) { }$\ <li class='@{od.markup[!diff.old ? 'diff_add' : 'diff_rem']}@'>\ <span class='@{od.markup.role}@'>{{role}}</span>\ </li>\ ${ }); }$\ ${ } else if (od.ctx.isProcess) {\ _.forEach(od.story.changes, function(diff, lane) {\ if(!!diff['old'] && !!diff['new']) { }$\ <li class='@{od.markup.diff_change}@'>\ <span class='@{od.markup.role}@ @{od.markup.diff_add}@'>{{diff['new']}}</span> from \ <span class='@{od.markup.role}@ @{od.markup.diff_rem}@'>{{diff['old']}}</span> in \ <span class='@{od.markup.lane}@'>{{lane}}</span> lane\ </li>\ ${ } else { }$\ <li class='@{od.markup[!diff.old ? 'diff_add' : 'diff_rem']}@'>\ <span class='@{od.markup.role}@'>{{diff['new'] || diff['old']}}</span> in \ <span class='@{od.markup.lane}@'>\ {{lane === '*' ? 'All' : lane === '~' ? 'No' : lane}}\ </span> {{lane === '*'||lane === '~' ? 'lanes' : 'lane' }}\ </li>\ ${ } }$\ ${ }); }$\ ${ } }$\ </ul>.\ ${ if (!!od.story.admin) { }$\ <footer class='@{od.markup.footer}@'>\ <span class='@{od.markup.admin}@'>Admin Event</span>\ </footer>\ ${ } }$\ </div>\ <time class='@{od.markup.timestamp}@' title='On \ {{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>\ {{ts.fromNow()}}</time>" image: '' }, "role:assign": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{ od.story.admin ? '[Admin Event] ' : '' }}\ {{od.ctx.amPlayer ? 'Your' : \ (od.story.player.alias||od.story.player.id) + '\u2019s'}} \ roles in \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$ have been changed\ ${ if (!od.story.admin) { }$ \ by {{od.ctx.amActor ? 'you' : \ od.story.actor.alias||od.story.actor.id}}\ ${ } }$.\ \n Changes:\ ${ if (od.ctx.isTeam) {\ _.forEach(od.story.changes, function(diff, role) { }$\ \n [{{ !diff.old ? '+' : '-'}}] {{role}}\ ${ }); }$\ ${ } else if (od.ctx.isProcess) {\ _.forEach(od.story.changes, function(diff, lane) {\ if(!!diff['old'] && !!diff['new']) { }$\ \n [+] {{diff['new']}} in {{lane}} lane\ \n [-] {{diff['old']}} in {{lane}} lane\ ${ } else { }$\ \n [{{ !diff.old ? '+' : '-'}}] \ {{diff['new'] || diff['old']}} in \ {{lane === '*' ? 'All lanes' : \ lane === '~' ? 'No lanes' : (lane + ' lane')}}\ ${ }\ });\ } }$" html: "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.target}@'>"+ "{{od.ctx.amPlayer ? 'Your' : (od.story.player.alias||od.story.player.id) + '\u2019s'}}"+ "</span> roles in "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$ have been changed"+ "${ if (!od.story.admin) { }$"+ " by <span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'you' : "+ "od.story.actor.alias||od.story.actor.id}}"+ "</span>"+ "${ } }$."+ "<ul class='@{od.markup.role_list}@ @{od.markup.diff_list}@'>"+ "<li class='@{od.markup.list_header}@'>Changes</li>"+ "${ if (od.ctx.isTeam) {"+ "_.forEach(od.story.changes, function(diff, role) { }$"+ "<li class='@{od.markup[!diff.old ? 'diff_add' : 'diff_rem']}@'>"+ "<span class='@{od.markup.role}@'>{{role}}</span>"+ "</li>"+ "${ }); }$"+ "${ } else if (od.ctx.isProcess) {"+ "_.forEach(od.story.changes, function(diff, lane) {"+ # if both new and old keys exist, the role was changed "if(!!diff['old'] && !!diff['new']) { }$"+ "<li class='@{od.markup.diff_change}@'>"+ "<span class='@{od.markup.role}@ @{od.markup.diff_add}@'>{{diff['new']}}</span> from "+ "<span class='@{od.markup.role}@ @{od.markup.diff_rem}@'>{{diff['old']}}</span> in "+ "<span class='@{od.markup.lane}@'>{{lane}}</span> lane"+ "</li>"+ "${ } else { }$"+ "<li class='@{od.markup[!diff.old ? 'diff_add' : 'diff_rem']}@'>"+ "<span class='@{od.markup.role}@'>{{diff['new'] || diff['old']}}</span> in "+ "<span class='@{od.markup.lane}@'>"+ "{{lane === '*' ? 'All' : lane === '~' ? 'No' : lane}}"+ "</span> {{lane === '*'||lane === '~' ? 'lanes' : 'lane' }}"+ "</li>"+ "${ } }$"+ "${ }); }$"+ "${ } }$"+ "</ul>."+ "${ if (!!od.story.admin) { }$\ <footer class='@{od.markup.footer}@'>\ <span class='@{od.markup.admin}@'>Admin Event</span>\ </footer>\ ${ } }$"+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>" image: '' }, "join:request": { text: "${ if(od.story.state === 'PENDING') { }$\ [{{moment(od.story.timestamp).format('llll')}}] - \ ${ if(od.ctx.amActor) { }$\ Your request to join \ ${ } else { }$\ {{od.story.actor.alias||od.story.actor.id}} wants to join \ ${ } }$\ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$ as \ ${ if (od.ctx.isTeam) { }$\ {{_.keys(od.story.roles).join(', ')}}\ ${ } else if (od.ctx.isProcess) { }$\ {{_.reduce(od.story.roles, function(list, role, lane) {\ list.push([\ role + ' in ' + \ (lane === '*' ? 'All lanes' : \ lane === '~' ? 'No lanes' : (lane + ' lane'))\ ]);\ return list;\ }, []).join(', ')}}\ ${ } }$\ {{ od.ctx.amActor ? ' is pending' : '' }}.\ ${ } else if(od.story.state === 'CANCELLED') { }$\ [{{moment(od.story.cancelled_at).format('llll')}}] - \ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}} \ cancelled the request to join \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$.\ ${ } else if(od.story.state === 'ACCEPTED') { }$\ [{{moment(od.story.accepted_at).format('llll')}}] - \ {{od.ctx.amActor ? 'Your' : \ (od.story.actor.alias||od.story.actor.id) + '\u2019s'}} \ request to join \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$ has been accepted by \ {{od.ctx.amMetaActor ? 'you' : \ od.story.accepted_by.alias||od.story.accepted_by.id}}.\ ${ } else if(od.story.state === 'REJECTED') { }$\ [{{moment(od.story.rejected_at).format('llll')}}] - \ {{od.ctx.amActor ? 'Your' : \ (od.story.actor.alias||od.story.actor.id) + '\u2019s'}} \ request to join \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$ has been rejected by \ {{od.ctx.amMetaActor ? 'you' : \ od.story.rejected_by.alias||od.story.rejected_by.id}}.\ ${ } }$" html: "${ if(od.story.state === 'PENDING') { }$"+ "<div class='@{od.markup.content}@'>"+ "${ if(od.ctx.amActor) { }$"+ "<span class='@{od.markup.actor}@'>Your</span> request to join "+ "${ } else { }$"+ "<span class='@{od.markup.actor}@'>"+ "{{od.story.actor.alias||od.story.actor.id}}"+ "</span> wants to join "+ "${ } }$"+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$ as "+ "<ul class='@{od.markup.role_list}@'>"+ "${ if (od.ctx.isTeam) { }$"+ "${ _.forEach(od.story.roles, function(enabled, role) { }$"+ "<li><span class='@{od.markup.role}@'>{{role}}</span></li>"+ "${ }) }$"+ "${ } else if (od.ctx.isProcess) { }$"+ "${ _.forEach(od.story.roles, function(role, lane) { }$"+ "<li>"+ "<span class='@{od.markup.role}@'>{{role}}</span> in "+ "<span class='@{od.markup.lane}@'>"+ "{{lane === '*' ? 'All' : lane === '~' ? 'No' : lane}}"+ "</span> {{lane === '*'||lane === '~' ? 'lanes' : 'lane' }}"+ "</li>"+ "${ })}$"+ "${ } }$</ul>"+ "{{ od.ctx.amActor ? ' is pending' : '' }}."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>"+ "${ } else if(od.story.state === 'CANCELLED') { }$"+ "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'You' : od.story.actor.alias||od.story.actor.id}}"+ "</span>"+ " cancelled the request to join "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.cancelled_at)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>"+ "${ } else if(od.story.state === 'ACCEPTED') { }$"+ "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'Your' : (od.story.actor.alias||od.story.actor.id) + '\u2019s'}}"+ "</span> request to join "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$ has been accepted by "+ "<span class='@{od.markup.target}@'>"+ "{{od.ctx.amMetaActor ? 'you' : "+ "od.story.accepted_by.alias||od.story.accepted_by.id}}"+ "</span>."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.accepted_at)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>"+ "${ } else if(od.story.state === 'REJECTED') { }$"+ "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'Your' : (od.story.actor.alias||od.story.actor.id) + '\u2019s'}}"+ "</span> request to join "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$ has been rejected by "+ "<span class='@{od.markup.target}@'>"+ "{{od.ctx.amMetaActor ? 'you' : "+ "od.story.rejected_by.alias||od.story.rejected_by.id}}"+ "</span>."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.rejected_at)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>"+ "${ } }$" image: '' }, "invite": { text: "${ if(od.story.state === 'PENDING') { }$\ [{{moment(od.story.timestamp).format('llll')}}] - \ ${ if(od.ctx.amActor) { }$\ Your invitation to \ {{od.story.invitee.alias||od.story.invitee.id}} to join \ ${ } else { }$\ {{od.story.actor.alias||od.story.actor.id}} \ invited you to join \ ${ } }$\ the {{od.ctx.isTeam ? 'team' : 'process'}} \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}' as \ ${ if (od.ctx.isTeam) { }$\ {{_.keys(od.story.roles).join(', ')}}\ ${ } else if (od.ctx.isProcess) { }$\ {{_.reduce(od.story.roles, function(list, role, lane) {\ list.push([\ role + ' in ' + \ (lane === '*' ? 'All lanes' : \ lane === '~' ? 'No lanes' : (lane + ' lane'))\ ]);\ return list;\ }, []).join(', ')}}\ ${ } }$\ {{ od.ctx.amActor ? ' is pending' : '' }}.\ ${ } else if(od.story.state === 'CANCELLED') { }$\ [{{moment(od.story.cancelled_at).format('llll')}}] - \ {{od.story.actor.alias||od.story.actor.id}} \ withdrew the invitation to join \ the {{od.ctx.isTeam ? 'team' : 'process'}} \ '{{od.story.team ? od.story.team.name || od.story.team.id : \ od.story.process.name || od.story.process.id}}'.\ ${ } else if(od.story.state === 'ACCEPTED' || \ od.story.state === 'REJECTED') { }$\ [{{moment(od.story.accepted_at||\ od.story.rejected_at).format('llll')}}] - \ {{od.ctx.amInvitee ? 'You' : \ od.story.invitee.alias||od.story.invitee.id}} \ {{od.story.accepted_at ? 'accepted' : 'rejected'}} \ {{od.ctx.amActor ? 'your' : \ (od.story.actor.alias||od.story.actor.id)+'\u2019s'}} \ invitation to join \ the {{od.ctx.isTeam ? 'team' : 'process'}} \ '{{od.story.team ? od.story.team.name || od.story.team.id : \ od.story.process.name || od.story.process.id}}' as \ ${ if (od.ctx.isTeam) { }$\ {{_.keys(od.story.roles).join(', ')}}\ ${ } else if (od.ctx.isProcess) { }$\ {{_.reduce(od.story.roles, function(list, role, lane) {\ list.push([\ role + ' in ' + \ (lane === '*' ? 'All lanes' : \ lane === '~' ? 'No lanes' : (lane + ' lane'))\ ]);\ return list;\ }, []).join(', ')}}\ ${ } }$.\ ${ } }$" html: "${ if(od.story.state === 'PENDING') { }$"+ "<div class='@{od.markup.content}@'>"+ "${ if(od.ctx.amActor) { }$"+ "<span class='@{od.markup.actor}@'>Your</span> invitation to "+ "<span class='@{od.markup.target}@'>{{od.story.invitee.alias||od.story.invitee.id}}</span>"+ " to join "+ "${ } else { }$"+ "<span class='@{od.markup.actor}@'>{{od.story.actor.alias||od.story.actor.id}}</span> "+ "invited <span class='@{od.markup.target}@'>you</span> to join "+ "${ } }$"+ "the {{od.ctx.isTeam ? 'team' : 'process'}}"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ " as "+ "<ul class='@{od.markup.role_list}@'>"+ "${ if (od.ctx.isTeam) { }$"+ "${ _.forEach(od.story.roles, function(enabled, role) { }$"+ "<li><span class='@{od.markup.role}@'>{{role}}</span></li>"+ "${ }) }$"+ "${ } else if (od.ctx.isProcess) { }$"+ "${ _.forEach(od.story.roles, function(role, lane) { }$"+ "<li>"+ "<span class='@{od.markup.role}@'>{{role}}</span> in "+ "<span class='@{od.markup.lane}@'>"+ "{{lane === '*' ? 'All' : lane === '~' ? 'No' : lane}}"+ "</span> {{lane === '*'||lane === '~' ? 'lanes' : 'lane' }}"+ "</li>"+ "${ })}$"+ "${ } }$</ul>"+ "{{ od.ctx.amActor ? ' is pending' : '' }}."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>"+ "${ } else if(od.story.state === 'CANCELLED') { }$"+ "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.actor}@'>"+ "{{od.story.actor.alias||od.story.actor.id}}"+ "</span>"+ " withdrew the invitation to join "+ "the {{od.ctx.isTeam ? 'team' : 'process'}}"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.cancelled_at)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>"+ "${ } else if(od.story.state === 'ACCEPTED' || od.story.state === 'REJECTED') { }$"+ "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.target}@'>"+ "{{od.ctx.amInvitee ? 'You' : \ od.story.invitee.alias||od.story.invitee.id}}"+ "</span> {{od.story.accepted_at ? 'accepted' : 'rejected'}} "+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'your' : \ (od.story.actor.alias||od.story.actor.id)+'\u2019s'}}"+ "</span>"+ " invitation to join "+ "the {{od.ctx.isTeam ? 'team' : 'process'}}"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ " as "+ "<ul class='@{od.markup.role_list}@'>"+ "${ if (od.ctx.isTeam) { }$"+ "${ _.forEach(od.story.roles, function(enabled, role) { }$"+ "<li><span class='@{od.markup.role}@'>{{role}}</span></li>"+ "${ }) }$"+ "${ } else if (od.ctx.isProcess) { }$"+ "${ _.forEach(od.story.roles, function(role, lane) { }$"+ "<li>"+ "<span class='@{od.markup.role}@'>{{role}}</span> in "+ "<span class='@{od.markup.lane}@'>"+ "{{lane === '*' ? 'All' : lane === '~' ? 'No' : lane}}"+ "</span> {{lane === '*'||lane === '~' ? 'lanes' : 'lane' }}"+ "</li>"+ "${ })}$"+ "${ } }$</ul>."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.accepted_at||od.story.rejected_at)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>"+ "${ } }$" image: '' }, "role:request": { text: "${ if(od.story.state === 'PENDING') { }$\ [{{moment(od.story.timestamp).format('llll')}}] - \ ${ if(od.ctx.amActor) { }$\ Your request for change of roles in \ ${ } else { }$\ {{od.story.actor.alias||od.story.actor.id}} \ wants to change roles in \ ${ } }$\ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id : \ od.story.process.name || od.story.process.id}}'\ ${ } }$\ {{ od.ctx.amActor ? ' is pending' : '' }}.\ \n New Roles:\ ${ if (od.ctx.isTeam) { }$\ \n [*] {{_.keys(od.story.roles).join(', ')}}\ ${ } else if (od.ctx.isProcess) {\ _.forEach(od.story.roles, function(role, lane) { }$\ \n [*] {{role}} in \ {{lane === '*' ? 'All' : lane === '~' ? 'No' : lane}} \ {{lane === '*' || lane === '~' ? 'lanes' : 'lane'}}\ ${ });\ } }$\ ${ } else if(od.story.state === 'CANCELLED') { }$\ [{{moment(od.story.cancelled_at).format('llll')}}] - \ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}} \ cancelled the request for change of roles in \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$.\ ${ } else if(od.story.state === 'ACCEPTED') { }$\ [{{moment(od.story.accepted_at).format('llll')}}] - \ {{od.ctx.amActor ? 'Your' : \ (od.story.actor.alias||od.story.actor.id) + '\u2019s'}} \ request for change of roles in \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$ has been accepted by \ {{od.story.accepted_by.alias||od.story.accepted_by.id}}.\ ${ } else if(od.story.state === 'REJECTED') { }$\ [{{moment(od.story.rejected_at).format('llll')}}] - \ {{od.ctx.amActor ? 'Your' : \ (od.story.actor.alias||od.story.actor.id) + '\u2019s'}} \ request for change of roles in \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$ has been rejected by \ {{od.story.rejected_by.alias||od.story.rejected_by.id}}.\ ${ } }$" html: "${ if(od.story.state === 'PENDING') { }$"+ "<div class='@{od.markup.content}@'>"+ "${ if(od.ctx.amActor) { }$"+ "<span class='@{od.markup.actor}@'>Your</span> request for change of roles in "+ "${ } else { }$"+ "<span class='@{od.markup.actor}@'>"+ "{{od.story.actor.alias||od.story.actor.id}}"+ "</span> wants to change roles in "+ "${ } }$"+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$"+ "{{ od.ctx.amActor ? ' is pending' : '' }}."+ "<ul class='@{od.markup.role_list}@'>"+ "<li class='@{od.markup.list_header}@'>New Roles</li>"+ "${ if (od.ctx.isTeam) {"+ "_.forEach(od.story.roles, function(enabled, role) { }$"+ "<li><span class='@{od.markup.role}@'>{{role}}</span></li>"+ "${ })"+ "} else if (od.ctx.isProcess) {"+ "_.forEach(od.story.roles, function(role, lane) { }$"+ "<li>"+ "<span class='@{od.markup.role}@'>{{role}}</span> in "+ "<span class='@{od.markup.lane}@'>"+ "{{lane === '*' ? 'All' : lane === '~' ? 'No' : lane}}"+ "</span> {{lane === '*'||lane === '~' ? 'lanes' : 'lane' }}"+ "</li>"+ "${ });"+ "} }$"+ "</ul>"+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>"+ "${ } else if(od.story.state === 'CANCELLED') { }$"+ "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'You' : od.story.actor.alias||od.story.actor.id}}"+ "</span>"+ " cancelled the request for change of roles in "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.cancelled_at)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>"+ "${ } else if(od.story.state === 'ACCEPTED') { }$"+ "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'Your' : (od.story.actor.alias||od.story.actor.id) + '\u2019s'}}"+ "</span> request for change of roles in "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$ has been accepted by "+ "<span class='@{od.markup.target}@'>"+ "{{od.story.accepted_by.alias||od.story.accepted_by.id}}"+ "</span>."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.accepted_at)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>"+ "${ } else if(od.story.state === 'REJECTED') { }$"+ "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'Your' : (od.story.actor.alias||od.story.actor.id) + '\u2019s'}}"+ "</span> request for change of roles in "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$ has been rejected by "+ "<span class='@{od.markup.target}@'>"+ "{{od.story.rejected_by.alias||od.story.rejected_by.id}}"+ "</span>."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.rejected_at)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>"+ "${ } }$" image: '' }, "progress": { text: "[{{moment(od.story.timestamp).format('llll')}}] - {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}} completed \ '{{od.story.activity.name}}' in \ {{od.ctx.isItem ? 'this' : 'the'}} process\ ${ if(!od.ctx.isItem) { }$ \ '{{od.story.process.name || od.story.process.id}}'\ ${ } }$.\ ${ if (od.story.changes) { }$\ \n Changes:\ ${ } }$\ ${ for (i = 0, \ _ref = (od.story.changes || []), \ len = _ref.length; i < _ref.length; i++) { \ change = _ref[i];\ if(change.metric.type === 'point'||change.metric.type === 'compound') {\ diff = ZERO.plus(change.delta['new'])\ .minus(change.delta['old'] || 0);\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString(); }$\ \n [*] {{diff}} {{change.metric.name}}\ ${ } else if(change.metric.type === 'set') { }$\ \n [>] {{change.metric.name}}\ ${ _.forEach(change.delta, function(delta, item) {\ diff = ZERO.plus(delta['new']).minus(delta['old']||'0');\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString();\ }$\ \n [*] {{diff}} {{item}}\ ${ }); }$\ ${ } else if(change.metric.type === 'state') { }$\ \n [>] {{change.metric.name}}\ \n [+] {{change.delta['new']}}\ \n [-] {{change.delta['old']}}\ ${ }\ } }$" html: """ <div class='@{od.markup.content}@'>\ <span class='@{od.markup.actor}@'>\ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}}\ </span> completed \ <span class='@{od.markup.score_activity}@'>\ {{od.story.activity.name}}\ </span>.\ ${ if(od.story.changes) { }$\ <table class='@{od.markup.score_table}@'>\ ${ }\ for (i = 0, _ref = (od.story.changes || []), len = _ref.length; i < _ref.length; i++) { change = _ref[i];\ if (change.metric.type === 'point'||change.metric.type === 'compound') {\ diff = ZERO.plus(change.delta['new'])\ .minus(change.delta['old'] || 0);\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString();\ }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@'>\ {{diff}}\ </span>\ </td>\ </tr>\ </tbody>\ ${ } else if(change.metric.type === 'set') { }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td colspan='2'>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ </tr>\ </tbody>\ <tbody class='@{od.markup.score_table_body}@'>\ ${ _.forEach(change.delta, function(delta, item) {\ diff = ZERO.plus(delta['new']).minus(delta['old']||'0');\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString();\ }$\ <tr>\ <td>\ <span class='@{od.markup.score_delta_item}@'>\ {{item}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@'>\ {{diff}}\ </span>\ </td>\ </tr>\ ${ }); }$\ </tbody>\ ${ } else if(change.metric.type === 'state') { }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td colspan='2'>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ </tr>\ </tbody>\ <tbody class='@{od.markup.score_table_body}@'>\ <tr>\ <td>\ <span class='@{od.markup.score_delta_value}@ \ @{od.markup.diff_add}@'>{{change.delta['new']}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@ \ @{od.markup.diff_rem}@'>\ {{change.delta['old'] || '--'}}\ </span>\ </td>\ </tr>\ </tbody>\ ${ }\ }\ if(od.story.changes) { }$\ </table>\ ${ }\ if(!od.ctx.isItem) { }$\ <footer class='@{od.markup.footer}@'>\ <span class='@{od.markup.object}@'>\ {{od.story.process.name||od.story.process.id}}\ </span>\ </footer>\ ${ } }$\ </div>\ <time class='@{od.markup.timestamp}@' title='On \ {{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>\ {{ts.fromNow()}}</time> """ image: '' }, "resolution": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}} completed \ '{{od.story.activity.name}}' in \ {{od.ctx.isItem ? 'this' : 'the'}} process\ ${ if(!od.ctx.isItem) { }$ \ '{{od.story.process.name || od.story.process.id}}'\ ${ } }$ and credited \ {{od.ctx.amPlayer ? \ (od.ctx.amActor ? 'yourself' : 'you') : \ od.story.deferred.actor.alias||od.story.deferred.actor.id}} \ for completing '{{od.story.deferred.activity.name}}'.\n \ Changes:\ ${ for (i = 0, _ref = (od.story.deferred.changes || []), len = _ref.length; i < _ref.length; i++) { change = _ref[i];\ if(change.metric.type === 'point'||change.metric.type === 'compound') {\ diff = ZERO.plus(change.delta['new'])\ .minus(change.delta['old'] || 0);\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString()\ }$\ \n [*] {{diff}} {{change.metric.name}}\ ${ } else if(change.metric.type === 'set') { }$\ \n [>] {{change.metric.name}}\ ${ _.forEach(change.delta, function(delta, item) {\ diff = ZERO.plus(delta['new']).minus(delta['old']||'0');\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString()\ }$\ \n [*] {{diff}} {{item}}\ ${ }); }$\ ${ } else if(change.metric.type === 'state') { }$\ \n [>] {{change.metric.name}}\ \n [+] {{change.delta['new']}}\ \n [-] {{change.delta['old']}}\ ${ }\ } }$" html: "<div class='@{od.markup.content}@'>\ <span class='@{od.markup.actor}@'>\ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}}\ </span> completed \ <span class='@{od.markup.score_activity}@'>\ {{od.story.activity.name}}\ </span> and credited \ <span class='@{od.markup.target}@'>\ {{od.ctx.amPlayer ? \ (od.ctx.amActor ? 'yourself' : 'you') : \ od.story.deferred.actor.alias||od.story.deferred.actor.id}}\ </span> for completing \ <span class='@{od.markup.score_activity}@'>\ {{od.story.deferred.activity.name}}\ </span>.\ <table class='@{od.markup.score_table}@'>\ ${ for (i = 0, _ref = (od.story.deferred.changes || []), len = _ref.length; i < _ref.length; i++) { change = _ref[i];\ if(change.metric.type === 'point'||change.metric.type === 'compound') {\ diff = ZERO.plus(change.delta['new'])\ .minus(change.delta['old'] || 0);\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString();\ }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@'>\ {{diff}}\ </span>\ </td>\ </tr>\ </tbody>\ ${ } else if(change.metric.type === 'set') { }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td colspan='2'>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ </tr>\ </tbody>\ <tbody class='@{od.markup.score_table_body}@'>\ ${ _.forEach(change.delta, function(delta, item) {\ diff = ZERO.plus(delta['new'])\ .minus(delta['old']||'0');\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString();\ }$\ <tr>\ <td>\ <span class='@{od.markup.score_delta_item}@'>\ {{item}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@'>\ {{diff}}\ </span>\ </td>\ </tr>\ ${ }); }$\ </tbody>\ ${ } else if(change.metric.type === 'state') { }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td colspan='2'>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ </tr>\ </tbody>\ <tbody class='@{od.markup.score_table_body}@'>\ <tr>\ <td>\ <span class='@{od.markup.score_delta_value}@ \ @{od.markup.diff_add}@'>\ {{change.delta['new']}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@ \ @{od.markup.diff_rem}@'>\ {{change.delta['old']}}\ </span>\ </td>\ </tr>\ </tbody>\ ${ }\ } }$\ </table>\ ${ if(!od.ctx.isItem) { }$\ <footer class='@{od.markup.footer}@'>\ <span class='@{od.markup.object}@'>\ {{od.story.process.name||od.story.process.id}}\ </span>\ </footer>\ ${ } }$\ </div>\ <time class='@{od.markup.timestamp}@' title='On \ {{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>\ {{ts.fromNow()}}</time>" image: '' }, "level": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{od.ctx.amActor ? 'Your' : \ (od.story.actor.alias||od.story.actor.id) + '\u2019s'}} \ ${ change = od.story.changes[0]; }$\ '{{change.metric.name}}' level changed \ ${ if (change.delta['old']) { }$\ from '{{change.delta['old']}}' \ ${ } }$\ to '{{change.delta['new']}}'\ ." html: "<div class='@{od.markup.content}@'>\ <span class='@{od.markup.actor}@'>\ {{od.ctx.amActor ? 'Your' : \ (od.story.actor.alias||od.story.actor.id) + '\u2019s'}}\ </span> \ ${ change = od.story.changes[0]; }$\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}</span> level changed\ ${ if (change.delta['old']) { }$ \ from <span class='@{od.markup.score_delta_value}@ \ @{od.markup.diff_rem}@'>{{change.delta['old']}}\ </span>\ ${ } }$ \ to <span class='@{od.markup.score_delta_value}@ \ @{od.markup.diff_add}@'>{{change.delta['new']}}</span>\ .\ </div>\ <time class='@{od.markup.timestamp}@' title='On \ {{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>\ {{ts.fromNow()}}</time>" image: '' }, "achievement": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{od.ctx.amActor ? 'Congratulations! You' : \ od.story.actor.alias||od.story.actor.id}} \ unlocked an achievement.\n"+ " Changes:"+ "${ for (i = 0, _ref = (od.story.changes || []), len = _ref.length; i < _ref.length; i++) { change = _ref[i]; }$"+ "\n [>] {{change.metric.name}}"+ "${ _.forEach(change.delta, function(delta, item) {"+ "diff = ZERO.plus(delta['new']).minus(delta['old']||'0');"+ "diff = (diff.gt(ZERO) ? '+' : '') + diff.toString();"+ "}$"+ "\n [*] {{diff}} {{item}}"+ "${ }); }$"+ "${ } }$", html: "<div class='@{od.markup.content}@'>"+ "{{od.ctx.amActor ? 'Congratulations! ' : ''}}<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'You' : od.story.actor.alias||od.story.actor.id}}"+ "</span>"+ " unlocked an achievement."+ "<table class='@{od.markup.score_table}@ @{od.markup.achievement_table}@'>"+ "${ for (i = 0, _ref = (od.story.changes || []), len = _ref.length; i < _ref.length; i++) { change = _ref[i]; }$"+ "<tbody class='@{od.markup.score_table_header}@'>"+ "<tr>"+ "<td colspan='2'>"+ "<span class='@{od.markup.score_metric}@'>"+ "{{change.metric.name}}"+ "</span>"+ "</td>"+ "</tr>"+ "</tbody>"+ "<tbody class='@{od.markup.score_table_body}@'>"+ "${ _.forEach(change.delta, function(delta, item) {"+ "diff = ZERO.plus(delta['new']).minus(delta['old']||'0');"+ "diff = (diff.gt(ZERO) ? '+' : '') + diff.toString();"+ "}$"+ "<tr>"+ "<td>"+ "<span class='@{od.markup.score_delta_item}@'>"+ "{{item}}"+ "</span>"+ "</td>"+ "<td>"+ "<span class='@{od.markup.score_delta_value}@'>"+ "{{diff}}"+ "</span>"+ "</td>"+ "</tr>"+ "${ }); }$"+ "</tbody>"+ "${ } }$"+ "</table>"+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>" image: '' }, "score": { text: "[{{moment(od.story.timestamp).format('llll')}}] - {{ od.story.admin ? '[Admin Event] ' : '' }}\ {{od.ctx.amPlayer ? 'Your' : \ (od.story.player.alias||od.story.player.id) + '\u2019s'}} \ scores were changed.\ \n New Scores:\ ${ for (i = 0, _ref = (od.story.changes || []), len = _ref.length; i < _ref.length; i++) { change = _ref[i];\ if(change.metric.type === 'point'||change.metric.type === 'compound') { }$\ \n [*] {{change.delta['new']}} {{change.metric.name}}\ ${ } else if(change.metric.type === 'set') { }$\ \n [>] {{change.metric.name}}\ ${ _.forEach(change.delta, function(delta, item) { }$\ \n [*] {{delta['new']}} {{item}}\ ${ }); }$\ ${ } else if(change.metric.type === 'state') { }$\ \n [*] {{change.metric.name}} - {{change.delta['new']}}\ ${ }\ } }$" html: "<div class='@{od.markup.content}@'>\ <span class='@{od.markup.target}@'>\ {{od.ctx.amPlayer ? 'Your' : \ (od.story.player.alias||od.story.player.id) + '\u2019s'}}\ </span> scores were changed.\ <table class='@{od.markup.score_table}@'>\ ${ for (i = 0, _ref = (od.story.changes || []), len = _ref.length; i < _ref.length; i++) { change = _ref[i];\ if (change.metric.type === 'point'||change.metric.type === 'compound') { }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@'>\ {{change.delta['new']}}\ </span>\ </td>\ </tr>\ </tbody>\ ${ } else if(change.metric.type === 'set') { }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td colspan='2'>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ </tr>\ </tbody>\ <tbody class='@{od.markup.score_table_body}@'>\ ${ _.forEach(change.delta, function(delta, item) { }$\ <tr>\ <td>\ <span class='@{od.markup.score_delta_item}@'>\ {{item}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@'>\ {{delta['new']}}\ </span>\ </td>\ </tr>\ ${ }); }$\ </tbody>\ ${ } else if(change.metric.type === 'state') { }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@'>\ {{change.delta['new']}}\ </span>\ </td>\ </tr>\ </tbody>\ ${ }\ } }$\ </table>\ ${ if (!!od.story.admin) { }$\ <footer class='@{od.markup.footer}@'>\ <span class='@{od.markup.admin}@'>Admin Event</span>\ </footer>\ ${ } }$\ </div>\ <time class='@{od.markup.timestamp}@' title='On \ {{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>\ {{ts.fromNow()}}</time>" image: '' }, "escalation": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{od.story.message}}\ ${ if (!!od.story.completed) { \ var completed = od.story.completed; }$ \ [*] {{od.ctx.amPlayer ? 'You' : \ completed.player.alias||completed.player.id}} completed \ {{completed.trigger.name||completed.trigger.id}}\ \n [{{moment(od.story.timestamp).format('llll')}}]\ ${ } }$" html: "<div class='@{od.markup.content}@\ @{!!od.story.completed?' '+od.markup.escalation_inactive:''}@'>\ {{od.story.message}}\ </div>\ ${ if (!!od.story.completed) { \ var completed = od.story.completed; }$\ <footer class='@{od.markup.footer}@ \ @{od.markup.escalation_footer}@'>\ <span class='@{od.markup.escalation_player}@'> {{od.ctx.amPlayer ? 'You' : \ completed.player.alias||completed.player.id}} completed \ {{completed.trigger.name||completed.trigger.id}} </span>\ <time class='@{od.markup.escalation_timestamp}@ \ @{od.markup.timestamp}@' title='Completed on \ {{(ts = moment(completed.timestamp)).format(\'llll\')}}'>\ {{ts.fromNow()}}</time> </footer>\ ${ } }$\ <time class='@{od.markup.timestamp}@' title='On \ {{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>\ {{ts.fromNow()}}</time>" image: '' }, "action": { text: "[{{moment(od.story.timestamp).format('llll')}}] - {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}} completed \ '{{od.story.action.name}}'.\ ${ if (od.story.changes) { }$\ \n Changes:\ ${ } }$\ ${ for (i = 0, _ref = (od.story.changes || []), len = _ref.length; i < _ref.length; i++) { change = _ref[i];\ if(change.metric.type === 'point'||change.metric.type === 'compound') {\ diff = ZERO.plus(change.delta['new'])\ .minus(change.delta['old'] || 0);\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString(); }$\ \n [*] {{diff}} {{change.metric.name}}\ ${ } else if(change.metric.type === 'set') { }$\ \n [>] {{change.metric.name}}\ ${ _.forEach(change.delta, function(delta, item) {\ diff = ZERO.plus(delta['new']).minus(delta['old']||'0');\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString();\ }$\ \n [*] {{diff}} {{item}}\ ${ }); }$\ ${ } else if(change.metric.type === 'state') { }$\ \n [>] {{change.metric.name}}\ \n [+] {{change.delta['new']}}\ \n [-] {{change.delta['old']}}\ ${ }\ } }$" html: """ <div class='@{od.markup.content}@'>\ <span class='@{od.markup.actor}@'>\ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}}\ </span> completed \ <span class='@{od.markup.score_activity}@'>\ {{od.story.action.name}}\ </span>.\ ${ if(od.story.changes) { }$\ <table class='@{od.markup.score_table}@'>\ ${ } }$\ ${ for (i = 0, _ref = (od.story.changes || []), len = _ref.length; i < _ref.length; i++) { change = _ref[i];\ if (change.metric.type === 'point'||change.metric.type === 'compound') {\ diff = ZERO.plus(change.delta['new'])\ .minus(change.delta['old'] || 0);\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString();\ }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@'>\ {{diff}}\ </span>\ </td>\ </tr>\ </tbody>\ ${ } else if(change.metric.type === 'set') { }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td colspan='2'>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ </tr>\ </tbody>\ <tbody class='@{od.markup.score_table_body}@'>\ ${ _.forEach(change.delta, function(delta, item) {\ diff = ZERO.plus(delta['new'])\ .minus(delta['old']||'0');\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString();\ }$\ <tr>\ <td>\ <span class='@{od.markup.score_delta_item}@'>\ {{item}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@'>\ {{diff}}\ </span>\ </td>\ </tr>\ ${ }); }$\ </tbody>\ ${ } else if(change.metric.type === 'state') { }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td colspan='2'>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ </tr>\ </tbody>\ <tbody class='@{od.markup.score_table_body}@'>\ <tr>\ <td>\ <span class='@{od.markup.score_delta_value}@ \ @{od.markup.diff_add}@'>{{change.delta['new']}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@ \ @{od.markup.diff_rem}@'>\ {{change.delta['old'] || '--'}}\ </span>\ </td>\ </tr>\ </tbody>\ ${ }\ }\ if(od.story.changes) { }$\ </table>\ ${ } }$\ </div>\ <time class='@{od.markup.timestamp}@' title='On \ {{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>\ {{ts.fromNow()}}</time> """ image: '' }, "custom_rule": { text: "[{{moment(od.story.timestamp).format('llll')}}] - {{od.ctx.amActor ? 'You were' : \ (od.story.actor.alias||od.story.actor.id) + ' was'}} awarded \ via '{{od.story.rule.name}}' rule.\ ${ if (od.story.changes) { }$\ \n Changes:\ ${ } }$\ ${ for (i = 0, _ref = (od.story.changes || []), len = _ref.length; i < _ref.length; i++) { change = _ref[i];\ if(change.metric.type === 'point'||change.metric.type === 'compound') {\ diff = ZERO.plus(change.delta['new'])\ .minus(change.delta['old'] || 0);\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString(); }$\ \n [*] {{diff}} {{change.metric.name}}\ ${ } else if(change.metric.type === 'set') { }$\ \n [>] {{change.metric.name}}\ ${ _.forEach(change.delta, function(delta, item) {\ diff = ZERO.plus(delta['new']).minus(delta['old']||'0');\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString();\ }$\ \n [*] {{diff}} {{item}}\ ${ }); }$\ ${ } else if(change.metric.type === 'state') { }$\ \n [>] {{change.metric.name}}\ \n [+] {{change.delta['new']}}\ \n [-] {{change.delta['old']}}\ ${ }\ } }$" html: """ <div class='@{od.markup.content}@'>\ <span class='@{od.markup.actor}@'>\ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}}\ </span> {{od.ctx.amActor ? 'were' : 'was'}} awarded via \ <span class='@{od.markup.score_rule}@'>\ {{od.story.rule.name}}\ </span> rule.\ ${ if(od.story.changes) { }$\ <table class='@{od.markup.score_table}@'>\ ${ } }$\ ${ for (i = 0, _ref = (od.story.changes || []), len = _ref.length; i < _ref.length; i++) { change = _ref[i];\ if (change.metric.type === 'point'||change.metric.type === 'compound') {\ diff = ZERO.plus(change.delta['new'])\ .minus(change.delta['old'] || 0);\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString();\ }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@'>\ {{diff}}\ </span>\ </td>\ </tr>\ </tbody>\ ${ } else if(change.metric.type === 'set') { }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td colspan='2'>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ </tr>\ </tbody>\ <tbody class='@{od.markup.score_table_body}@'>\ ${ _.forEach(change.delta, function(delta, item) {\ diff = ZERO.plus(delta['new'])\ .minus(delta['old']||'0');\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString();\ }$\ <tr>\ <td>\ <span class='@{od.markup.score_delta_item}@'>\ {{item}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@'>\ {{diff}}\ </span>\ </td>\ </tr>\ ${ }); }$\ </tbody>\ ${ } else if(change.metric.type === 'state') { }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td colspan='2'>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ </tr>\ </tbody>\ <tbody class='@{od.markup.score_table_body}@'>\ <tr>\ <td>\ <span class='@{od.markup.score_delta_value}@ \ @{od.markup.diff_add}@'>{{change.delta['new']}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@ \ @{od.markup.diff_rem}@'>\ {{change.delta['old'] || '--'}}\ </span>\ </td>\ </tr>\ </tbody>\ ${ }\ }\ if(od.story.changes) { }$\ </table>\ ${ } }$\ </div>\ <time class='@{od.markup.timestamp}@' title='On \ {{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>\ {{ts.fromNow()}}</time> """ image: '' } } constructor: (options) -> options = options or {} @options = _.defaults options, { markup: Odysseus.default_markup external: {} } buildContext: (story, ext) -> ctx = {} ctx.isDummy = ext.env is 'debug' # Determine whether the current story is for a team or process # to simplify template code. ctx.isItem = ext.context in ['team', 'process'] if story.team? or ext.context is 'team' ctx.isTeam = true else if story.process? or ext.context is 'process' ctx.isProcess = true; # Determine whether the actor is the current player if story.event in [ 'create', 'delete', 'join' 'leave', 'kick', 'join:request', 'join:request:accept', 'join:request:reject', 'invite', 'invite:accept', 'invite:reject', 'role:change', 'role:request', 'role:request:accept', 'role:request:reject', 'role:assign', 'progress', 'level', 'achievement', 'resolution', 'action', 'custom_rule' ] # Determine whether the current player is the actor unless story.actor? and ext.profile?.id isnt story.actor.id ctx.amActor = true # Determine whether the target is the current player if story.event in [ 'kick', 'join:request:accept', 'join:request:reject', 'role:request:accept', 'role:request:reject', 'role:assign' 'score' ] unless story.player? and ext.profile?.id isnt story.player.id ctx.amPlayer = true else if story.event is 'resolution' unless story.deferred.actor? and ext.profile?.id isnt story.deferred.actor.id ctx.amPlayer = true else if story.event in ['invite:accept', 'invite:reject'] unless story.inviter? and ext.profile?.id isnt story.inviter.id ctx.amInviter = true else if story.event is 'invite' unless story.invitee? and ext.profile?.id isnt story.invitee.id ctx.amInvitee = true else if story.event is 'join:request' if story.state is 'ACCEPTED' and ext.profile?.id is story.accepted_by.id or story.state is 'REJECTED' and ext.profile?.id is story.rejected_by.id ctx.amMetaActor = true else if story.event is 'escalation' if story.completed? and ext.profile?.id is story.completed.player.id ctx.amPlayer = true # Finally, return the config object return ctx compile: (evt, type) -> unless (tpl_collection = Odysseus.stored_templates[evt])? throw("The #{evt} event is not supported") unless (tpl = tpl_collection[type])? throw("The #{type} template for #{evt} event cannot be found") _.template tpl toString: (story, external_data = {}) -> unless story? throw 'The story is not available' template = @compile story.event, 'text' context = @buildContext story, external_data template({ story: story ext: external_data ctx: context }) toHTML: (story, external_data = {}, config = {}) -> unless story? throw 'The story is not available' template = @compile story.event, 'html' context = @buildContext story, external_data html = template({ story: story, ext: external_data, ctx: context, markup: @options.markup }) if story.event is 'escalation' html = _.unescape html # The escalation text already comes rendered, # so unescape all HTML tags, etc if config.image is true image = """ <div class='#{@options.markup.image}'>\ #{@getImage(story, external_data)}\ </div> """ html = image + html html getImage: (story, external_data = {}) -> unless story? throw 'The story is not available' unless external_data.base_url? throw 'The base source url is not specified' template = @compile story.event, 'image' context = @buildContext story, external_data template({ story: story, ext: external_data, ctx: context, markup: @options.markup }) Odysseus; )
196058
((global, factory) -> # AMD. Register as anonymous module. if typeof define is 'function' and define.amd define ['lodash', 'moment', 'bignumber'], factory # CommonJS. As a node module. else if typeof exports is 'object' module.exports = factory( require('lodash'), require('moment'), require('bignumber.js') ) else global['Odysseus'] = factory( global['_'], global['moment'], global['BigNumber'] ) )(this, (_, moment, BigNumber) -> # Override the templating delimiters to distinguish from HTML tags _.templateSettings.interpolate = /@\{([\s\S]+?)\}@/g _.templateSettings.escape = /\{\{([\s\S]+?)\}\}/g _.templateSettings.evaluate = /\$\{([\s\S]+?)\}\$/g _.templateSettings.variable = 'od' _.templateSettings.imports = { '_': _ # Pass the default lodash object 'moment': moment # Pass moment for time transformations 'ZERO': new BigNumber(0) # Since bigNumber isn't really required, # so just send a big ZERO to enable maths. }; class Odysseus ###* * A map of the default markup tags to be inserted into the rendered HTML * in-case no object is supplied in the constructor * @type {Object} ### @default_markup: { content: "od-content", image: "od-image", actor: "od-actor", target: "od-target", object: "od-object", role_list: "od-role-list", role: "od-role", lane: "od-lane", timestamp: "od-ts" } ###* * A list of all the available templates * @type {Object} ### @stored_templates: { ###* * Activity Templates ### "create": { text: " [{{moment(od.story.timestamp).format('llll')}}] - \ {{ od.story.admin ? '[Admin Event] ' : '' }}\ The '{{ \ od.story.team ? od.story.team.name || od.story.team.id : od.story.process.name || od.story.process.id \ }}' \ {{ od.ctx.isTeam ? 'team' : 'process' }} was created\ ${ if (!od.story.admin) { }$ \ by {{ od.ctx.amActor ? 'you' : od.story.actor.alias || od.story.actor.id}}\ ${ } }$. " html: " <div class='@{od.markup.content}@'>\ The <span class='@{od.markup.object}@'>\ {{od.story.team ? od.story.team.name || od.story.team.id : od.story.process.name || od.story.process.id}}\ </span> {{od.ctx.isTeam ? 'team' : 'process'}} was created\ ${ if (!od.story.admin) { }$ \ by <span class='@{od.markup.actor}@'>\ {{ od.ctx.amActor ? 'you' : od.story.actor.alias || od.story.actor.id }}\ </span>\ ${ } }$.\ ${ if (!!od.story.admin) { }$\ <footer class='@{od.markup.footer}@'>\ <span class='@{od.markup.admin}@'>Admin Event</span>\ </footer>\ ${ } }$\ </div>\ <time class='@{od.markup.timestamp}@' title='On \ {{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>\ {{ts.fromNow()}}</time> " image: '' }, "delete": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{od.ctx.amActor ? 'You' : od.story.actor.alias||od.story.actor.id}} deleted \ the {{od.ctx.isTeam ? 'team' : 'process'}} \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'." html: "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'You' : od.story.actor.alias||od.story.actor.id}}"+ "</span> deleted the {{od.ctx.isTeam ? 'team' : 'process'}} "+ "<span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>" image: '' }, "join": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{ od.story.admin ? '[Admin Event] ' : '' }}\ {{od.ctx.amActor ? 'You' : od.story.actor.alias||od.story.actor.id}} joined \ {{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$ as \ ${ if (od.ctx.isTeam) { }$\ {{_.keys(od.story.roles).join(', ')}}\ ${ } else if (od.ctx.isProcess) { }$\ {{_.reduce(od.story.roles, function(list, role, lane) {\ list.push([\ role + ' in ' + \ (lane === '*' ? 'All lanes' : \ lane === '~' ? 'No lanes' : (lane + ' lane'))\ ]);\ return list;\ }, []).join(', ')}}\ ${ } }$." html: "<div class='@{od.markup.content}@'>\ <span class='@{od.markup.actor}@'>\ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}}\ </span> joined \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ <span class='@{od.markup.object}@'>\ {{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}\ </span>\ ${ } }$ as \ <ul class='@{od.markup.role_list}@'>\ ${ if (od.ctx.isTeam) { }$\ ${ _.forEach(od.story.roles, function(enabled, role) { }$\ <li><span class='@{od.markup.role}@'>{{role}}</span></li>\ ${ }) }$\ ${ } else if (od.ctx.isProcess) { }$\ ${ _.forEach(od.story.roles, function(role, lane) { }$\ <li>\ <span class='@{od.markup.role}@'>{{role}}</span> in \ <span class='@{od.markup.lane}@'>\ {{lane === '*' ? 'All' : lane === '~' ? 'No' : lane}}\ </span> \ {{lane === '*'||lane === '~' ? 'lanes' : 'lane' }}\ </li>\ ${ })}$\ ${ } }$</ul>.\ ${ if (!!od.story.admin) { }$\ <footer class='@{od.markup.footer}@'>\ <span class='@{od.markup.admin}@'>Admin Event</span>\ </footer>\ ${ } }$\ </div>\ <time class='@{od.markup.timestamp}@' title='On \ {{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>\ {{ts.fromNow()}}</time>", image: """ ${ if (od.ctx.isDummy) { }$\ <i class='@{od.markup.dummy_icon}@'></i>\ ${ } else { }$\ <img \ src='{{od.ext.base_url}}/{{od.ctx.amActor ? \ od.ext.profile.id : od.story.actor.id}}'>\ ${ } }$ """ }, "leave": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{od.ctx.amActor ? 'You' : od.story.actor.alias||od.story.actor.id}} left \ {{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$.", html: "<div class='@{od<EMAIL>.markup<EMAIL>.content}@'>"+ "<span class='@{od.<EMAIL>.actor}@'>"+ "{{od.ctx.amActor ? 'You' : od.story.actor.alias||od.story.actor.id}}"+ "</span> left "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$."+ "</div>"+ "<time class='@{od.<EMAIL>}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>" image: '' }, "kick": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{od.ctx.amActor ? 'You' : od.story.actor.alias||od.story.actor.id}} kicked \ {{od.ctx.amPlayer ? 'you' : od.story.player.alias||od.story.player.id}} from \ {{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$.", html: "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'You' : od.story.actor.alias||od.story.actor.id}}"+ "</span> kicked "+ "<span class='@{od.markup.target}@'>"+ "{{od.ctx.amPlayer ? 'you' : od.story.player.alias||od.story.player.id}}"+ "</span> from "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>" image: '' }, "join:request:accept": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{od.ctx.amPlayer ? 'Your' : \ (od.story.player.alias||od.story.player.id) + '\u2019s'}} \ request to join \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$ has been accepted by \ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}}.", html: "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.target}@'>"+ "{{od.ctx.amPlayer ? 'Your' : (od.story.player.alias||od.story.player.id) + '\u2019s'}}"+ "</span> request to join "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$ has been accepted by "+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'you' : od.story.actor.alias||od.story.actor.id}}"+ "</span>."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>" image: '' }, "join:request:reject": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{od.ctx.amPlayer ? 'Your' : \ (od.story.player.alias||od.story.player.id) + '\u2019s'}} \ request to join \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$ has been rejected by \ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}}." html: "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.target}@'>"+ "{{od.ctx.amPlayer ? 'Your' : (od.story.player.alias||od.story.player.id) + '\u2019s'}}"+ "</span> request to join "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$ has been rejected by "+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'you' : od.story.actor.alias||od.story.actor.id}}"+ "</span>."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>" image: '' }, "invite:accept": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}} accepted \ {{od.ctx.amInviter ? 'your' : \ (od.story.inviter.alias||od.story.inviter.id) + '\u2019s'}} \ invitation to join \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id : \ od.story.process.name || od.story.process.id}}'\ ${ } }$ as \ ${ if (od.ctx.isTeam) { }$\ {{_.keys(od.story.roles).join(', ')}}\ ${ } else if (od.ctx.isProcess) { }$\ {{_.reduce(od.story.roles, function(list, role, lane) {\ list.push([\ role + ' in ' + \ (lane === '*' ? 'All lanes' : \ lane === '~' ? 'No lanes' : (lane + ' lane'))\ ]);\ return list;\ }, []).join(', ')}}\ ${ } }$." html: "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'You' : od.story.actor.alias||od.story.actor.id}}"+ "</span> accepted "+ "<span class='@{od.markup.target}@'>"+ "{{od.ctx.amInviter ? 'your' : (od.story.inviter.alias||od.story.inviter.id) + '\u2019s'}}"+ "</span> invitation to join "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$ as "+ "<ul class='@{od.markup.role_list}@'>"+ "${ if (od.ctx.isTeam) { }$"+ "${ _.forEach(od.story.roles, function(enabled, role) { }$"+ "<li><span class='@{od.markup.role}@'>{{role}}</span></li>"+ "${ }) }$"+ "${ } else if (od.ctx.isProcess) { }$"+ "${ _.forEach(od.story.roles, function(role, lane) { }$"+ "<li>"+ "<span class='@{od.markup.role}@'>{{role}}</span> in "+ "<span class='@{od.markup.lane}@'>"+ "{{lane === '*' ? 'All' : lane === '~' ? 'No' : lane}}"+ "</span> {{lane === '*'||lane === '~' ? 'lanes' : 'lane' }}"+ "</li>"+ "${ })}$"+ "${ } }$</ul>."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>" image: '' }, "invite:reject": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}} rejected \ {{od.ctx.amInviter ? 'your' : \ (od.story.inviter.alias||od.story.inviter.id) + '\u2019s'}} \ invitation to join \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id : \ od.story.process.name || od.story.process.id}}'\ ${ } }$ as \ ${ if (od.ctx.isTeam) { }$\ {{_.keys(od.story.roles).join(', ')}}\ ${ } else if (od.ctx.isProcess) { }$\ {{_.reduce(od.story.roles, function(list, role, lane) {\ list.push([\ role + ' in ' + \ (lane === '*' ? 'All lanes' : \ lane === '~' ? 'No lanes' : (lane + ' lane'))\ ]);\ return list;\ }, []).join(', ')}}\ ${ } }$." html: "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'You' : od.story.actor.alias||od.story.actor.id}}"+ "</span> rejected "+ "<span class='@{od.markup.target}@'>"+ "{{od.ctx.amInviter ? 'your' : (od.story.inviter.alias||od.story.inviter.id) + '\u2019s'}}"+ "</span> invitation to join "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$ as "+ "<ul class='@{od.markup.role_list}@'>"+ "${ if (od.ctx.isTeam) { }$"+ "${ _.forEach(od.story.roles, function(enabled, role) { }$"+ "<li><span class='@{od.markup.role}@'>{{role}}</span></li>"+ "${ }) }$"+ "${ } else if (od.ctx.isProcess) { }$"+ "${ _.forEach(od.story.roles, function(role, lane) { }$"+ "<li>"+ "<span class='@{od.markup.role}@'>{{role}}</span> in "+ "<span class='@{od.markup.lane}@'>"+ "{{lane === '*' ? 'All' : lane === '~' ? 'No' : lane}}"+ "</span> {{lane === '*'||lane === '~' ? 'lanes' : 'lane' }}"+ "</li>"+ "${ })}$"+ "${ } }$</ul>."+ "</div>"+ "<time class='@{<EMAIL>}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>" image: '' }, "role:request:accept": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{od.ctx.amPlayer ? 'Your' : \ (od.story.player.alias||od.story.player.id) + '\u2019s'}} \ request for a change of roles in \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$ has been accepted by \ {{od.ctx.amActor ? 'you' : \ od.story.actor.alias||od.story.actor.id}}.\ \n Changes:\ ${ if (od.ctx.isTeam) {\ _.forEach(od.story.changes, function(diff, role) { }$\ \n [{{ !diff.old ? '+' : '-'}}] {{role}}\ ${ }); }$\ ${ } else if (od.ctx.isProcess) {\ _.forEach(od.story.changes, function(diff, lane) {\ if(!!diff['old'] && !!diff['new']) { }$\ \n [+] {{diff['new']}} in {{lane}} lane\ \n [-] {{diff['old']}} in {{lane}} lane\ ${ } else { }$\ \n [{{ !diff.old ? '+' : '-'}}] \ {{diff['new'] || diff['old']}} in \ {{lane === '*' ? 'All lanes' : \ lane === '~' ? 'No lanes' : (lane + ' lane')}}\ ${ }\ });\ } }$" html: "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.target}@'>"+ "{{od.ctx.amPlayer ? 'Your' : (od.story.player.alias||od.story.player.id) + '\u2019s'}}"+ "</span> request for a change of roles in "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$ has been accepted by "+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'you' : od.story.actor.alias||od.story.actor.id}}"+ "</span>."+ "<ul class='@{od.markup.role_list}@ @{od.markup.diff_list}@'>"+ "<li class='@{od.markup.list_header}@'>Changes</li>"+ "${ if (od.ctx.isTeam) {"+ "_.forEach(od.story.changes, function(diff, role) { }$"+ "<li class='@{od.markup[!diff.old ? 'diff_add' : 'diff_rem']}@'>"+ "<span class='@{od.markup.role}@'>{{role}}</span>"+ "</li>"+ "${ }); }$"+ "${ } else if (od.ctx.isProcess) {"+ "_.forEach(od.story.changes, function(diff, lane) {"+ # if both new and old keys exist, the role was changed "if(!!diff['old'] && !!diff['new']) { }$"+ "<li class='@{od.markup.diff_change}@'>"+ "<span class='@{od.markup.role}@ @{od.markup.diff_add}@'>{{diff['new']}}</span> from "+ "<span class='@{od.markup.role}@ @{od.markup.diff_rem}@'>{{diff['old']}}</span> in "+ "<span class='@{od.markup.lane}@'>{{lane}}</span> lane"+ "</li>"+ "${ } else { }$"+ "<li class='@{od.markup[!diff.old ? 'diff_add' : 'diff_rem']}@'>"+ "<span class='@{od.markup.role}@'>{{diff['new'] || diff['old']}}</span> in "+ "<span class='@{od.markup.lane}@'>"+ "{{lane === '*' ? 'All' : lane === '~' ? 'No' : lane}}"+ "</span> {{lane === '*'||lane === '~' ? 'lanes' : 'lane' }}"+ "</li>"+ "${ } }$"+ "${ }); }$"+ "${ } }$"+ "</ul>."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>" image: '' }, "role:request:reject": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{od.ctx.amPlayer ? 'Your' : \ (od.story.player.alias||od.story.player.id) + '\u2019s'}} \ request for a change of roles in \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$ has been rejected by \ {{od.ctx.amActor ? 'you' : \ od.story.actor.alias||od.story.actor.id}}." html: "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.target}@'>"+ "{{od.ctx.amPlayer ? 'Your' : (od.story.player.alias||od.story.player.id) + '\u2019s'}}"+ "</span> request for a change of roles in "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$ has been rejected by "+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'you' : od.story.actor.alias||od.story.actor.id}}"+ "</span>."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>" image: '' }, "role:change": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ ${ if (od.story.admin) { }$\ [Admin Event] \ {{od.ctx.amActor ? 'Your' : \ (od.story.actor.alias||od.story.actor.id)+'\u2019s'}}\ ${ } else { }$\ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}} \ {{od.ctx.amActor ? 'have' : 'has'}} changed\ ${ } }$ roles in \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$\ {{ !!od.story.admin ? ' have been changed' : ''}}.\ \n Changes:\ ${ if (od.ctx.isTeam) {\ _.forEach(od.story.changes, function(diff, role) { }$\ \n [{{ !diff.old ? '+' : '-'}}] {{role}}\ ${ }); }$\ ${ } else if (od.ctx.isProcess) {\ _.forEach(od.story.changes, function(diff, lane) {\ if(!!diff['old'] && !!diff['new']) { }$\ \n [+] {{diff['new']}} in {{lane}} lane\ \n [-] {{diff['old']}} in {{lane}} lane\ ${ } else { }$\ \n [{{ !diff.old ? '+' : '-'}}] \ {{diff['new'] || diff['old']}} in \ {{lane === '*' ? 'All lanes' : \ lane === '~' ? 'No lanes' : (lane + ' lane')}}\ ${ }\ });\ } }$" html: "<div class='@{od.markup.content}@'>\ ${ if (od.story.admin) { }$\ <span class='@{od.markup.target}@'>\ {{od.ctx.amActor ? 'Your' : \ (od.story.actor.alias||od.story.actor.id)+'\u2019s'}}\ </span>\ ${ } else { }$\ <span class='@{od.markup.actor}@'>\ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}}\ </span> \ {{od.ctx.amActor ? 'have' : 'has'}} changed\ ${ } }$ roles in \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ <span class='@{od.markup.object}@'>\ {{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}\ </span>\ ${ } }$\ {{ !!od.story.admin ? ' have been changed' : ''}}.\ <ul class='@{od.markup.role_list}@ @{od.markup.diff_list}@'>\ <li class='@{od.markup.list_header}@'>Changes</li>\ ${ if (od.ctx.isTeam) {\ _.forEach(od.story.changes, function(diff, role) { }$\ <li class='@{od.markup[!diff.old ? 'diff_add' : 'diff_rem']}@'>\ <span class='@{od.markup.role}@'>{{role}}</span>\ </li>\ ${ }); }$\ ${ } else if (od.ctx.isProcess) {\ _.forEach(od.story.changes, function(diff, lane) {\ if(!!diff['old'] && !!diff['new']) { }$\ <li class='@{od.markup.diff_change}@'>\ <span class='@{od.markup.role}@ @{od.markup.diff_add}@'>{{diff['new']}}</span> from \ <span class='@{od.markup.role}@ @{od.markup.diff_rem}@'>{{diff['old']}}</span> in \ <span class='@{od.markup.lane}@'>{{lane}}</span> lane\ </li>\ ${ } else { }$\ <li class='@{od.markup[!diff.old ? 'diff_add' : 'diff_rem']}@'>\ <span class='@{od.markup.role}@'>{{diff['new'] || diff['old']}}</span> in \ <span class='@{od.markup.lane}@'>\ {{lane === '*' ? 'All' : lane === '~' ? 'No' : lane}}\ </span> {{lane === '*'||lane === '~' ? 'lanes' : 'lane' }}\ </li>\ ${ } }$\ ${ }); }$\ ${ } }$\ </ul>.\ ${ if (!!od.story.admin) { }$\ <footer class='@{od.markup.footer}@'>\ <span class='@{od.markup.admin}@'>Admin Event</span>\ </footer>\ ${ } }$\ </div>\ <time class='@{od.markup.timestamp}@' title='On \ {{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>\ {{ts.fromNow()}}</time>" image: '' }, "role:assign": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{ od.story.admin ? '[Admin Event] ' : '' }}\ {{od.ctx.amPlayer ? 'Your' : \ (od.story.player.alias||od.story.player.id) + '\u2019s'}} \ roles in \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$ have been changed\ ${ if (!od.story.admin) { }$ \ by {{od.ctx.amActor ? 'you' : \ od.story.actor.alias||od.story.actor.id}}\ ${ } }$.\ \n Changes:\ ${ if (od.ctx.isTeam) {\ _.forEach(od.story.changes, function(diff, role) { }$\ \n [{{ !diff.old ? '+' : '-'}}] {{role}}\ ${ }); }$\ ${ } else if (od.ctx.isProcess) {\ _.forEach(od.story.changes, function(diff, lane) {\ if(!!diff['old'] && !!diff['new']) { }$\ \n [+] {{diff['new']}} in {{lane}} lane\ \n [-] {{diff['old']}} in {{lane}} lane\ ${ } else { }$\ \n [{{ !diff.old ? '+' : '-'}}] \ {{diff['new'] || diff['old']}} in \ {{lane === '*' ? 'All lanes' : \ lane === '~' ? 'No lanes' : (lane + ' lane')}}\ ${ }\ });\ } }$" html: "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.target}@'>"+ "{{od.ctx.amPlayer ? 'Your' : (od.story.player.alias||od.story.player.id) + '\u2019s'}}"+ "</span> roles in "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$ have been changed"+ "${ if (!od.story.admin) { }$"+ " by <span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'you' : "+ "od.story.actor.alias||od.story.actor.id}}"+ "</span>"+ "${ } }$."+ "<ul class='@{od.markup.role_list}@ @{od.markup.diff_list}@'>"+ "<li class='@{od.markup.list_header}@'>Changes</li>"+ "${ if (od.ctx.isTeam) {"+ "_.forEach(od.story.changes, function(diff, role) { }$"+ "<li class='@{od.markup[!diff.old ? 'diff_add' : 'diff_rem']}@'>"+ "<span class='@{od.markup.role}@'>{{role}}</span>"+ "</li>"+ "${ }); }$"+ "${ } else if (od.ctx.isProcess) {"+ "_.forEach(od.story.changes, function(diff, lane) {"+ # if both new and old keys exist, the role was changed "if(!!diff['old'] && !!diff['new']) { }$"+ "<li class='@{od.markup.diff_change}@'>"+ "<span class='@{od.markup.role}@ @{od.markup.diff_add}@'>{{diff['new']}}</span> from "+ "<span class='@{od.markup.role}@ @{od.markup.diff_rem}@'>{{diff['old']}}</span> in "+ "<span class='@{od.markup.lane}@'>{{lane}}</span> lane"+ "</li>"+ "${ } else { }$"+ "<li class='@{od.markup[!diff.old ? 'diff_add' : 'diff_rem']}@'>"+ "<span class='@{od.markup.role}@'>{{diff['new'] || diff['old']}}</span> in "+ "<span class='@{od.markup.lane}@'>"+ "{{lane === '*' ? 'All' : lane === '~' ? 'No' : lane}}"+ "</span> {{lane === '*'||lane === '~' ? 'lanes' : 'lane' }}"+ "</li>"+ "${ } }$"+ "${ }); }$"+ "${ } }$"+ "</ul>."+ "${ if (!!od.story.admin) { }$\ <footer class='@{od.markup.footer}@'>\ <span class='@{od.markup.admin}@'>Admin Event</span>\ </footer>\ ${ } }$"+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>" image: '' }, "join:request": { text: "${ if(od.story.state === 'PENDING') { }$\ [{{moment(od.story.timestamp).format('llll')}}] - \ ${ if(od.ctx.amActor) { }$\ Your request to join \ ${ } else { }$\ {{od.story.actor.alias||od.story.actor.id}} wants to join \ ${ } }$\ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$ as \ ${ if (od.ctx.isTeam) { }$\ {{_.keys(od.story.roles).join(', ')}}\ ${ } else if (od.ctx.isProcess) { }$\ {{_.reduce(od.story.roles, function(list, role, lane) {\ list.push([\ role + ' in ' + \ (lane === '*' ? 'All lanes' : \ lane === '~' ? 'No lanes' : (lane + ' lane'))\ ]);\ return list;\ }, []).join(', ')}}\ ${ } }$\ {{ od.ctx.amActor ? ' is pending' : '' }}.\ ${ } else if(od.story.state === 'CANCELLED') { }$\ [{{moment(od.story.cancelled_at).format('llll')}}] - \ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}} \ cancelled the request to join \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$.\ ${ } else if(od.story.state === 'ACCEPTED') { }$\ [{{moment(od.story.accepted_at).format('llll')}}] - \ {{od.ctx.amActor ? 'Your' : \ (od.story.actor.alias||od.story.actor.id) + '\u2019s'}} \ request to join \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$ has been accepted by \ {{od.ctx.amMetaActor ? 'you' : \ od.story.accepted_by.alias||od.story.accepted_by.id}}.\ ${ } else if(od.story.state === 'REJECTED') { }$\ [{{moment(od.story.rejected_at).format('llll')}}] - \ {{od.ctx.amActor ? 'Your' : \ (od.story.actor.alias||od.story.actor.id) + '\u2019s'}} \ request to join \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$ has been rejected by \ {{od.ctx.amMetaActor ? 'you' : \ od.story.rejected_by.alias||od.story.rejected_by.id}}.\ ${ } }$" html: "${ if(od.story.state === 'PENDING') { }$"+ "<div class='@{od.markup.content}@'>"+ "${ if(od.ctx.amActor) { }$"+ "<span class='@{od.markup.actor}@'>Your</span> request to join "+ "${ } else { }$"+ "<span class='@{od.markup.actor}@'>"+ "{{od.story.actor.alias||od.story.actor.id}}"+ "</span> wants to join "+ "${ } }$"+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$ as "+ "<ul class='@{od.markup.role_list}@'>"+ "${ if (od.ctx.isTeam) { }$"+ "${ _.forEach(od.story.roles, function(enabled, role) { }$"+ "<li><span class='@{od.markup.role}@'>{{role}}</span></li>"+ "${ }) }$"+ "${ } else if (od.ctx.isProcess) { }$"+ "${ _.forEach(od.story.roles, function(role, lane) { }$"+ "<li>"+ "<span class='@{od.markup.role}@'>{{role}}</span> in "+ "<span class='@{od.markup.lane}@'>"+ "{{lane === '*' ? 'All' : lane === '~' ? 'No' : lane}}"+ "</span> {{lane === '*'||lane === '~' ? 'lanes' : 'lane' }}"+ "</li>"+ "${ })}$"+ "${ } }$</ul>"+ "{{ od.ctx.amActor ? ' is pending' : '' }}."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>"+ "${ } else if(od.story.state === 'CANCELLED') { }$"+ "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'You' : od.story.actor.alias||od.story.actor.id}}"+ "</span>"+ " cancelled the request to join "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.cancelled_at)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>"+ "${ } else if(od.story.state === 'ACCEPTED') { }$"+ "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'Your' : (od.story.actor.alias||od.story.actor.id) + '\u2019s'}}"+ "</span> request to join "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$ has been accepted by "+ "<span class='@{od.markup.target}@'>"+ "{{od.ctx.amMetaActor ? 'you' : "+ "od.story.accepted_by.alias||od.story.accepted_by.id}}"+ "</span>."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.accepted_at)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>"+ "${ } else if(od.story.state === 'REJECTED') { }$"+ "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'Your' : (od.story.actor.alias||od.story.actor.id) + '\u2019s'}}"+ "</span> request to join "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$ has been rejected by "+ "<span class='@{od.markup.target}@'>"+ "{{od.ctx.amMetaActor ? 'you' : "+ "od.story.rejected_by.alias||od.story.rejected_by.id}}"+ "</span>."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.rejected_at)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>"+ "${ } }$" image: '' }, "invite": { text: "${ if(od.story.state === 'PENDING') { }$\ [{{moment(od.story.timestamp).format('llll')}}] - \ ${ if(od.ctx.amActor) { }$\ Your invitation to \ {{od.story.invitee.alias||od.story.invitee.id}} to join \ ${ } else { }$\ {{od.story.actor.alias||od.story.actor.id}} \ invited you to join \ ${ } }$\ the {{od.ctx.isTeam ? 'team' : 'process'}} \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}' as \ ${ if (od.ctx.isTeam) { }$\ {{_.keys(od.story.roles).join(', ')}}\ ${ } else if (od.ctx.isProcess) { }$\ {{_.reduce(od.story.roles, function(list, role, lane) {\ list.push([\ role + ' in ' + \ (lane === '*' ? 'All lanes' : \ lane === '~' ? 'No lanes' : (lane + ' lane'))\ ]);\ return list;\ }, []).join(', ')}}\ ${ } }$\ {{ od.ctx.amActor ? ' is pending' : '' }}.\ ${ } else if(od.story.state === 'CANCELLED') { }$\ [{{moment(od.story.cancelled_at).format('llll')}}] - \ {{od.story.actor.alias||od.story.actor.id}} \ withdrew the invitation to join \ the {{od.ctx.isTeam ? 'team' : 'process'}} \ '{{od.story.team ? od.story.team.name || od.story.team.id : \ od.story.process.name || od.story.process.id}}'.\ ${ } else if(od.story.state === 'ACCEPTED' || \ od.story.state === 'REJECTED') { }$\ [{{moment(od.story.accepted_at||\ od.story.rejected_at).format('llll')}}] - \ {{od.ctx.amInvitee ? 'You' : \ od.story.invitee.alias||od.story.invitee.id}} \ {{od.story.accepted_at ? 'accepted' : 'rejected'}} \ {{od.ctx.amActor ? 'your' : \ (od.story.actor.alias||od.story.actor.id)+'\u2019s'}} \ invitation to join \ the {{od.ctx.isTeam ? 'team' : 'process'}} \ '{{od.story.team ? od.story.team.name || od.story.team.id : \ od.story.process.name || od.story.process.id}}' as \ ${ if (od.ctx.isTeam) { }$\ {{_.keys(od.story.roles).join(', ')}}\ ${ } else if (od.ctx.isProcess) { }$\ {{_.reduce(od.story.roles, function(list, role, lane) {\ list.push([\ role + ' in ' + \ (lane === '*' ? 'All lanes' : \ lane === '~' ? 'No lanes' : (lane + ' lane'))\ ]);\ return list;\ }, []).join(', ')}}\ ${ } }$.\ ${ } }$" html: "${ if(od.story.state === 'PENDING') { }$"+ "<div class='@{od.markup.content}@'>"+ "${ if(od.ctx.amActor) { }$"+ "<span class='@{od.markup.actor}@'>Your</span> invitation to "+ "<span class='@{od.markup.target}@'>{{od.story.invitee.alias||od.story.invitee.id}}</span>"+ " to join "+ "${ } else { }$"+ "<span class='@{od.markup.actor}@'>{{od.story.actor.alias||od.story.actor.id}}</span> "+ "invited <span class='@{od.markup.target}@'>you</span> to join "+ "${ } }$"+ "the {{od.ctx.isTeam ? 'team' : 'process'}}"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ " as "+ "<ul class='@{od.markup.role_list}@'>"+ "${ if (od.ctx.isTeam) { }$"+ "${ _.forEach(od.story.roles, function(enabled, role) { }$"+ "<li><span class='@{od.markup.role}@'>{{role}}</span></li>"+ "${ }) }$"+ "${ } else if (od.ctx.isProcess) { }$"+ "${ _.forEach(od.story.roles, function(role, lane) { }$"+ "<li>"+ "<span class='@{od.markup.role}@'>{{role}}</span> in "+ "<span class='@{od.markup.lane}@'>"+ "{{lane === '*' ? 'All' : lane === '~' ? 'No' : lane}}"+ "</span> {{lane === '*'||lane === '~' ? 'lanes' : 'lane' }}"+ "</li>"+ "${ })}$"+ "${ } }$</ul>"+ "{{ od.ctx.amActor ? ' is pending' : '' }}."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>"+ "${ } else if(od.story.state === 'CANCELLED') { }$"+ "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.actor}@'>"+ "{{od.story.actor.alias||od.story.actor.id}}"+ "</span>"+ " withdrew the invitation to join "+ "the {{od.ctx.isTeam ? 'team' : 'process'}}"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.cancelled_at)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>"+ "${ } else if(od.story.state === 'ACCEPTED' || od.story.state === 'REJECTED') { }$"+ "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.target}@'>"+ "{{od.ctx.amInvitee ? 'You' : \ od.story.invitee.alias||od.story.invitee.id}}"+ "</span> {{od.story.accepted_at ? 'accepted' : 'rejected'}} "+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'your' : \ (od.story.actor.alias||od.story.actor.id)+'\u2019s'}}"+ "</span>"+ " invitation to join "+ "the {{od.ctx.isTeam ? 'team' : 'process'}}"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ " as "+ "<ul class='@{od.markup.role_list}@'>"+ "${ if (od.ctx.isTeam) { }$"+ "${ _.forEach(od.story.roles, function(enabled, role) { }$"+ "<li><span class='@{od.<EMAIL>.role}@'>{{role}}</span></li>"+ "${ }) }$"+ "${ } else if (od.ctx.isProcess) { }$"+ "${ _.forEach(od.story.roles, function(role, lane) { }$"+ "<li>"+ "<span class='@{od<EMAIL>.markup<EMAIL>.role}@'>{{role}}</span> in "+ "<span class='@{od.markup.lane}@'>"+ "{{lane === '*' ? 'All' : lane === '~' ? 'No' : lane}}"+ "</span> {{lane === '*'||lane === '~' ? 'lanes' : 'lane' }}"+ "</li>"+ "${ })}$"+ "${ } }$</ul>."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.accepted_at||od.story.rejected_at)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>"+ "${ } }$" image: '' }, "role:request": { text: "${ if(od.story.state === 'PENDING') { }$\ [{{moment(od.story.timestamp).format('llll')}}] - \ ${ if(od.ctx.amActor) { }$\ Your request for change of roles in \ ${ } else { }$\ {{od.story.actor.alias||od.story.actor.id}} \ wants to change roles in \ ${ } }$\ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id : \ od.story.process.name || od.story.process.id}}'\ ${ } }$\ {{ od.ctx.amActor ? ' is pending' : '' }}.\ \n New Roles:\ ${ if (od.ctx.isTeam) { }$\ \n [*] {{_.keys(od.story.roles).join(', ')}}\ ${ } else if (od.ctx.isProcess) {\ _.forEach(od.story.roles, function(role, lane) { }$\ \n [*] {{role}} in \ {{lane === '*' ? 'All' : lane === '~' ? 'No' : lane}} \ {{lane === '*' || lane === '~' ? 'lanes' : 'lane'}}\ ${ });\ } }$\ ${ } else if(od.story.state === 'CANCELLED') { }$\ [{{moment(od.story.cancelled_at).format('llll')}}] - \ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}} \ cancelled the request for change of roles in \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$.\ ${ } else if(od.story.state === 'ACCEPTED') { }$\ [{{moment(od.story.accepted_at).format('llll')}}] - \ {{od.ctx.amActor ? 'Your' : \ (od.story.actor.alias||od.story.actor.id) + '\u2019s'}} \ request for change of roles in \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$ has been accepted by \ {{od.story.accepted_by.alias||od.story.accepted_by.id}}.\ ${ } else if(od.story.state === 'REJECTED') { }$\ [{{moment(od.story.rejected_at).format('llll')}}] - \ {{od.ctx.amActor ? 'Your' : \ (od.story.actor.alias||od.story.actor.id) + '\u2019s'}} \ request for change of roles in \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$ has been rejected by \ {{od.story.rejected_by.alias||od.story.rejected_by.id}}.\ ${ } }$" html: "${ if(od.story.state === 'PENDING') { }$"+ "<div class='@{od.markup.content}@'>"+ "${ if(od.ctx.amActor) { }$"+ "<span class='@{od.markup.actor}@'>Your</span> request for change of roles in "+ "${ } else { }$"+ "<span class='@{od.markup.actor}@'>"+ "{{od.story.actor.alias||od.story.actor.id}}"+ "</span> wants to change roles in "+ "${ } }$"+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$"+ "{{ od.ctx.amActor ? ' is pending' : '' }}."+ "<ul class='@{od.markup.role_list}@'>"+ "<li class='@{od.markup.list_header}@'>New Roles</li>"+ "${ if (od.ctx.isTeam) {"+ "_.forEach(od.story.roles, function(enabled, role) { }$"+ "<li><span class='@{od<EMAIL>.markup.role}@'>{{role}}</span></li>"+ "${ })"+ "} else if (od.ctx.isProcess) {"+ "_.forEach(od.story.roles, function(role, lane) { }$"+ "<li>"+ "<span class='@{od.<EMAIL>.role}@'>{{role}}</span> in "+ "<span class='@{od.markup.lane}@'>"+ "{{lane === '*' ? 'All' : lane === '~' ? 'No' : lane}}"+ "</span> {{lane === '*'||lane === '~' ? 'lanes' : 'lane' }}"+ "</li>"+ "${ });"+ "} }$"+ "</ul>"+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>"+ "${ } else if(od.story.state === 'CANCELLED') { }$"+ "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'You' : od.story.actor.alias||od.story.actor.id}}"+ "</span>"+ " cancelled the request for change of roles in "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.cancelled_at)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>"+ "${ } else if(od.story.state === 'ACCEPTED') { }$"+ "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'Your' : (od.story.actor.alias||od.story.actor.id) + '\u2019s'}}"+ "</span> request for change of roles in "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$ has been accepted by "+ "<span class='@{od.markup.target}@'>"+ "{{od.story.accepted_by.alias||od.story.accepted_by.id}}"+ "</span>."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.accepted_at)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>"+ "${ } else if(od.story.state === 'REJECTED') { }$"+ "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'Your' : (od.story.actor.alias||od.story.actor.id) + '\u2019s'}}"+ "</span> request for change of roles in "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$ has been rejected by "+ "<span class='@{od.<EMAIL>}@'>"+ "{{od.story.rejected_by.alias||od.story.rejected_by.id}}"+ "</span>."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.rejected_at)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>"+ "${ } }$" image: '' }, "progress": { text: "[{{moment(od.story.timestamp).format('llll')}}] - {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}} completed \ '{{od.story.activity.name}}' in \ {{od.ctx.isItem ? 'this' : 'the'}} process\ ${ if(!od.ctx.isItem) { }$ \ '{{od.story.process.name || od.story.process.id}}'\ ${ } }$.\ ${ if (od.story.changes) { }$\ \n Changes:\ ${ } }$\ ${ for (i = 0, \ _ref = (od.story.changes || []), \ len = _ref.length; i < _ref.length; i++) { \ change = _ref[i];\ if(change.metric.type === 'point'||change.metric.type === 'compound') {\ diff = ZERO.plus(change.delta['new'])\ .minus(change.delta['old'] || 0);\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString(); }$\ \n [*] {{diff}} {{change.metric.name}}\ ${ } else if(change.metric.type === 'set') { }$\ \n [>] {{change.metric.name}}\ ${ _.forEach(change.delta, function(delta, item) {\ diff = ZERO.plus(delta['new']).minus(delta['old']||'0');\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString();\ }$\ \n [*] {{diff}} {{item}}\ ${ }); }$\ ${ } else if(change.metric.type === 'state') { }$\ \n [>] {{change.metric.name}}\ \n [+] {{change.delta['new']}}\ \n [-] {{change.delta['old']}}\ ${ }\ } }$" html: """ <div class='@{od.markup.content}@'>\ <span class='@{od.markup.actor}@'>\ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}}\ </span> completed \ <span class='@{od.markup.score_activity}@'>\ {{od.story.activity.name}}\ </span>.\ ${ if(od.story.changes) { }$\ <table class='@{od.markup.score_table}@'>\ ${ }\ for (i = 0, _ref = (od.story.changes || []), len = _ref.length; i < _ref.length; i++) { change = _ref[i];\ if (change.metric.type === 'point'||change.metric.type === 'compound') {\ diff = ZERO.plus(change.delta['new'])\ .minus(change.delta['old'] || 0);\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString();\ }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@'>\ {{diff}}\ </span>\ </td>\ </tr>\ </tbody>\ ${ } else if(change.metric.type === 'set') { }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td colspan='2'>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ </tr>\ </tbody>\ <tbody class='@{od.markup.score_table_body}@'>\ ${ _.forEach(change.delta, function(delta, item) {\ diff = ZERO.plus(delta['new']).minus(delta['old']||'0');\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString();\ }$\ <tr>\ <td>\ <span class='@{od.markup.score_delta_item}@'>\ {{item}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@'>\ {{diff}}\ </span>\ </td>\ </tr>\ ${ }); }$\ </tbody>\ ${ } else if(change.metric.type === 'state') { }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td colspan='2'>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ </tr>\ </tbody>\ <tbody class='@{od.markup.score_table_body}@'>\ <tr>\ <td>\ <span class='@{od.markup.score_delta_value}@ \ @{od.markup.diff_add}@'>{{change.delta['new']}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@ \ @{od.markup.diff_rem}@'>\ {{change.delta['old'] || '--'}}\ </span>\ </td>\ </tr>\ </tbody>\ ${ }\ }\ if(od.story.changes) { }$\ </table>\ ${ }\ if(!od.ctx.isItem) { }$\ <footer class='@{od.markup.footer}@'>\ <span class='@{od.markup.object}@'>\ {{od.story.process.name||od.story.process.id}}\ </span>\ </footer>\ ${ } }$\ </div>\ <time class='@{od.markup.timestamp}@' title='On \ {{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>\ {{ts.fromNow()}}</time> """ image: '' }, "resolution": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}} completed \ '{{od.story.activity.name}}' in \ {{od.ctx.isItem ? 'this' : 'the'}} process\ ${ if(!od.ctx.isItem) { }$ \ '{{od.story.process.name || od.story.process.id}}'\ ${ } }$ and credited \ {{od.ctx.amPlayer ? \ (od.ctx.amActor ? 'yourself' : 'you') : \ od.story.deferred.actor.alias||od.story.deferred.actor.id}} \ for completing '{{od.story.deferred.activity.name}}'.\n \ Changes:\ ${ for (i = 0, _ref = (od.story.deferred.changes || []), len = _ref.length; i < _ref.length; i++) { change = _ref[i];\ if(change.metric.type === 'point'||change.metric.type === 'compound') {\ diff = ZERO.plus(change.delta['new'])\ .minus(change.delta['old'] || 0);\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString()\ }$\ \n [*] {{diff}} {{change.metric.name}}\ ${ } else if(change.metric.type === 'set') { }$\ \n [>] {{change.metric.name}}\ ${ _.forEach(change.delta, function(delta, item) {\ diff = ZERO.plus(delta['new']).minus(delta['old']||'0');\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString()\ }$\ \n [*] {{diff}} {{item}}\ ${ }); }$\ ${ } else if(change.metric.type === 'state') { }$\ \n [>] {{change.metric.name}}\ \n [+] {{change.delta['new']}}\ \n [-] {{change.delta['old']}}\ ${ }\ } }$" html: "<div class='@{od.markup.content}@'>\ <span class='@{od.markup.actor}@'>\ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}}\ </span> completed \ <span class='@{od.markup.score_activity}@'>\ {{od.story.activity.name}}\ </span> and credited \ <span class='@{od.markup.target}@'>\ {{od.ctx.amPlayer ? \ (od.ctx.amActor ? 'yourself' : 'you') : \ od.story.deferred.actor.alias||od.story.deferred.actor.id}}\ </span> for completing \ <span class='@{od.markup.score_activity}@'>\ {{od.story.deferred.activity.name}}\ </span>.\ <table class='@{od.markup.score_table}@'>\ ${ for (i = 0, _ref = (od.story.deferred.changes || []), len = _ref.length; i < _ref.length; i++) { change = _ref[i];\ if(change.metric.type === 'point'||change.metric.type === 'compound') {\ diff = ZERO.plus(change.delta['new'])\ .minus(change.delta['old'] || 0);\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString();\ }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@'>\ {{diff}}\ </span>\ </td>\ </tr>\ </tbody>\ ${ } else if(change.metric.type === 'set') { }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td colspan='2'>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ </tr>\ </tbody>\ <tbody class='@{od.markup.score_table_body}@'>\ ${ _.forEach(change.delta, function(delta, item) {\ diff = ZERO.plus(delta['new'])\ .minus(delta['old']||'0');\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString();\ }$\ <tr>\ <td>\ <span class='@{od.markup.score_delta_item}@'>\ {{item}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@'>\ {{diff}}\ </span>\ </td>\ </tr>\ ${ }); }$\ </tbody>\ ${ } else if(change.metric.type === 'state') { }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td colspan='2'>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ </tr>\ </tbody>\ <tbody class='@{od.markup.score_table_body}@'>\ <tr>\ <td>\ <span class='@{od.markup.score_delta_value}@ \ @{od.markup.diff_add}@'>\ {{change.delta['new']}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@ \ @{od.markup.diff_rem}@'>\ {{change.delta['old']}}\ </span>\ </td>\ </tr>\ </tbody>\ ${ }\ } }$\ </table>\ ${ if(!od.ctx.isItem) { }$\ <footer class='@{od.markup.footer}@'>\ <span class='@{od.markup.object}@'>\ {{od.story.process.name||od.story.process.id}}\ </span>\ </footer>\ ${ } }$\ </div>\ <time class='@{od.markup.timestamp}@' title='On \ {{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>\ {{ts.fromNow()}}</time>" image: '' }, "level": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{od.ctx.amActor ? 'Your' : \ (od.story.actor.alias||od.story.actor.id) + '\u2019s'}} \ ${ change = od.story.changes[0]; }$\ '{{change.metric.name}}' level changed \ ${ if (change.delta['old']) { }$\ from '{{change.delta['old']}}' \ ${ } }$\ to '{{change.delta['new']}}'\ ." html: "<div class='@{od.markup.content}@'>\ <span class='@{od.markup.actor}@'>\ {{od.ctx.amActor ? 'Your' : \ (od.story.actor.alias||od.story.actor.id) + '\u2019s'}}\ </span> \ ${ change = od.story.changes[0]; }$\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}</span> level changed\ ${ if (change.delta['old']) { }$ \ from <span class='@{od.markup.score_delta_value}@ \ @{od.markup.diff_rem}@'>{{change.delta['old']}}\ </span>\ ${ } }$ \ to <span class='@{od.markup.score_delta_value}@ \ @{od.markup.diff_add}@'>{{change.delta['new']}}</span>\ .\ </div>\ <time class='@{od.markup.timestamp}@' title='On \ {{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>\ {{ts.fromNow()}}</time>" image: '' }, "achievement": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{od.ctx.amActor ? 'Congratulations! You' : \ od.story.actor.alias||od.story.actor.id}} \ unlocked an achievement.\n"+ " Changes:"+ "${ for (i = 0, _ref = (od.story.changes || []), len = _ref.length; i < _ref.length; i++) { change = _ref[i]; }$"+ "\n [>] {{change.metric.name}}"+ "${ _.forEach(change.delta, function(delta, item) {"+ "diff = ZERO.plus(delta['new']).minus(delta['old']||'0');"+ "diff = (diff.gt(ZERO) ? '+' : '') + diff.toString();"+ "}$"+ "\n [*] {{diff}} {{item}}"+ "${ }); }$"+ "${ } }$", html: "<div class='@{od.markup.content}@'>"+ "{{od.ctx.amActor ? 'Congratulations! ' : ''}}<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'You' : od.story.actor.alias||od.story.actor.id}}"+ "</span>"+ " unlocked an achievement."+ "<table class='@{od.markup.score_table}@ @{od.markup.achievement_table}@'>"+ "${ for (i = 0, _ref = (od.story.changes || []), len = _ref.length; i < _ref.length; i++) { change = _ref[i]; }$"+ "<tbody class='@{od.markup.score_table_header}@'>"+ "<tr>"+ "<td colspan='2'>"+ "<span class='@{od.markup.score_metric}@'>"+ "{{change.metric.name}}"+ "</span>"+ "</td>"+ "</tr>"+ "</tbody>"+ "<tbody class='@{od.markup.score_table_body}@'>"+ "${ _.forEach(change.delta, function(delta, item) {"+ "diff = ZERO.plus(delta['new']).minus(delta['old']||'0');"+ "diff = (diff.gt(ZERO) ? '+' : '') + diff.toString();"+ "}$"+ "<tr>"+ "<td>"+ "<span class='@{od.markup.score_delta_item}@'>"+ "{{item}}"+ "</span>"+ "</td>"+ "<td>"+ "<span class='@{od.markup.score_delta_value}@'>"+ "{{diff}}"+ "</span>"+ "</td>"+ "</tr>"+ "${ }); }$"+ "</tbody>"+ "${ } }$"+ "</table>"+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>" image: '' }, "score": { text: "[{{moment(od.story.timestamp).format('llll')}}] - {{ od.story.admin ? '[Admin Event] ' : '' }}\ {{od.ctx.amPlayer ? 'Your' : \ (od.story.player.alias||od.story.player.id) + '\u2019s'}} \ scores were changed.\ \n New Scores:\ ${ for (i = 0, _ref = (od.story.changes || []), len = _ref.length; i < _ref.length; i++) { change = _ref[i];\ if(change.metric.type === 'point'||change.metric.type === 'compound') { }$\ \n [*] {{change.delta['new']}} {{change.metric.name}}\ ${ } else if(change.metric.type === 'set') { }$\ \n [>] {{change.metric.name}}\ ${ _.forEach(change.delta, function(delta, item) { }$\ \n [*] {{delta['new']}} {{item}}\ ${ }); }$\ ${ } else if(change.metric.type === 'state') { }$\ \n [*] {{change.metric.name}} - {{change.delta['new']}}\ ${ }\ } }$" html: "<div class='@{od.markup.content}@'>\ <span class='@{od.markup.target}@'>\ {{od.ctx.amPlayer ? 'Your' : \ (od.story.player.alias||od.story.player.id) + '\u2019s'}}\ </span> scores were changed.\ <table class='@{od.markup.score_table}@'>\ ${ for (i = 0, _ref = (od.story.changes || []), len = _ref.length; i < _ref.length; i++) { change = _ref[i];\ if (change.metric.type === 'point'||change.metric.type === 'compound') { }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@'>\ {{change.delta['new']}}\ </span>\ </td>\ </tr>\ </tbody>\ ${ } else if(change.metric.type === 'set') { }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td colspan='2'>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ </tr>\ </tbody>\ <tbody class='@{od.markup.score_table_body}@'>\ ${ _.forEach(change.delta, function(delta, item) { }$\ <tr>\ <td>\ <span class='@{od.markup.score_delta_item}@'>\ {{item}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@'>\ {{delta['new']}}\ </span>\ </td>\ </tr>\ ${ }); }$\ </tbody>\ ${ } else if(change.metric.type === 'state') { }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@'>\ {{change.delta['new']}}\ </span>\ </td>\ </tr>\ </tbody>\ ${ }\ } }$\ </table>\ ${ if (!!od.story.admin) { }$\ <footer class='@{od.markup.footer}@'>\ <span class='@{od.markup.admin}@'>Admin Event</span>\ </footer>\ ${ } }$\ </div>\ <time class='@{od.markup.timestamp}@' title='On \ {{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>\ {{ts.fromNow()}}</time>" image: '' }, "escalation": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{od.story.message}}\ ${ if (!!od.story.completed) { \ var completed = od.story.completed; }$ \ [*] {{od.ctx.amPlayer ? 'You' : \ completed.player.alias||completed.player.id}} completed \ {{completed.trigger.name||completed.trigger.id}}\ \n [{{moment(od.story.timestamp).format('llll')}}]\ ${ } }$" html: "<div class='@{od.markup.content}@\ @{!!od.story.completed?' '+od.markup.escalation_inactive:''}@'>\ {{od.story.message}}\ </div>\ ${ if (!!od.story.completed) { \ var completed = od.story.completed; }$\ <footer class='@{od.markup.footer}@ \ @{od.markup.escalation_footer}@'>\ <span class='@{od.markup.escalation_player}@'> {{od.ctx.amPlayer ? 'You' : \ completed.player.alias||completed.player.id}} completed \ {{completed.trigger.name||completed.trigger.id}} </span>\ <time class='@{od.markup.escalation_timestamp}@ \ @{od.markup.timestamp}@' title='Completed on \ {{(ts = moment(completed.timestamp)).format(\'llll\')}}'>\ {{ts.fromNow()}}</time> </footer>\ ${ } }$\ <time class='@{od.markup.timestamp}@' title='On \ {{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>\ {{ts.fromNow()}}</time>" image: '' }, "action": { text: "[{{moment(od.story.timestamp).format('llll')}}] - {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}} completed \ '{{od.story.action.name}}'.\ ${ if (od.story.changes) { }$\ \n Changes:\ ${ } }$\ ${ for (i = 0, _ref = (od.story.changes || []), len = _ref.length; i < _ref.length; i++) { change = _ref[i];\ if(change.metric.type === 'point'||change.metric.type === 'compound') {\ diff = ZERO.plus(change.delta['new'])\ .minus(change.delta['old'] || 0);\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString(); }$\ \n [*] {{diff}} {{change.metric.name}}\ ${ } else if(change.metric.type === 'set') { }$\ \n [>] {{change.metric.name}}\ ${ _.forEach(change.delta, function(delta, item) {\ diff = ZERO.plus(delta['new']).minus(delta['old']||'0');\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString();\ }$\ \n [*] {{diff}} {{item}}\ ${ }); }$\ ${ } else if(change.metric.type === 'state') { }$\ \n [>] {{change.metric.name}}\ \n [+] {{change.delta['new']}}\ \n [-] {{change.delta['old']}}\ ${ }\ } }$" html: """ <div class='@{od.markup.content}@'>\ <span class='@{od.markup.actor}@'>\ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}}\ </span> completed \ <span class='@{od.markup.score_activity}@'>\ {{od.story.action.name}}\ </span>.\ ${ if(od.story.changes) { }$\ <table class='@{od.markup.score_table}@'>\ ${ } }$\ ${ for (i = 0, _ref = (od.story.changes || []), len = _ref.length; i < _ref.length; i++) { change = _ref[i];\ if (change.metric.type === 'point'||change.metric.type === 'compound') {\ diff = ZERO.plus(change.delta['new'])\ .minus(change.delta['old'] || 0);\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString();\ }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@'>\ {{diff}}\ </span>\ </td>\ </tr>\ </tbody>\ ${ } else if(change.metric.type === 'set') { }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td colspan='2'>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ </tr>\ </tbody>\ <tbody class='@{od.markup.score_table_body}@'>\ ${ _.forEach(change.delta, function(delta, item) {\ diff = ZERO.plus(delta['new'])\ .minus(delta['old']||'0');\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString();\ }$\ <tr>\ <td>\ <span class='@{od.markup.score_delta_item}@'>\ {{item}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@'>\ {{diff}}\ </span>\ </td>\ </tr>\ ${ }); }$\ </tbody>\ ${ } else if(change.metric.type === 'state') { }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td colspan='2'>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ </tr>\ </tbody>\ <tbody class='@{od.markup.score_table_body}@'>\ <tr>\ <td>\ <span class='@{od.markup.score_delta_value}@ \ @{od.markup.diff_add}@'>{{change.delta['new']}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@ \ @{od.markup.diff_rem}@'>\ {{change.delta['old'] || '--'}}\ </span>\ </td>\ </tr>\ </tbody>\ ${ }\ }\ if(od.story.changes) { }$\ </table>\ ${ } }$\ </div>\ <time class='@{od.markup.timestamp}@' title='On \ {{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>\ {{ts.fromNow()}}</time> """ image: '' }, "custom_rule": { text: "[{{moment(od.story.timestamp).format('llll')}}] - {{od.ctx.amActor ? 'You were' : \ (od.story.actor.alias||od.story.actor.id) + ' was'}} awarded \ via '{{od.story.rule.name}}' rule.\ ${ if (od.story.changes) { }$\ \n Changes:\ ${ } }$\ ${ for (i = 0, _ref = (od.story.changes || []), len = _ref.length; i < _ref.length; i++) { change = _ref[i];\ if(change.metric.type === 'point'||change.metric.type === 'compound') {\ diff = ZERO.plus(change.delta['new'])\ .minus(change.delta['old'] || 0);\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString(); }$\ \n [*] {{diff}} {{change.metric.name}}\ ${ } else if(change.metric.type === 'set') { }$\ \n [>] {{change.metric.name}}\ ${ _.forEach(change.delta, function(delta, item) {\ diff = ZERO.plus(delta['new']).minus(delta['old']||'0');\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString();\ }$\ \n [*] {{diff}} {{item}}\ ${ }); }$\ ${ } else if(change.metric.type === 'state') { }$\ \n [>] {{change.metric.name}}\ \n [+] {{change.delta['new']}}\ \n [-] {{change.delta['old']}}\ ${ }\ } }$" html: """ <div class='@{od.markup.content}@'>\ <span class='@{od.markup.actor}@'>\ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}}\ </span> {{od.ctx.amActor ? 'were' : 'was'}} awarded via \ <span class='@{od.markup.score_rule}@'>\ {{od.story.rule.name}}\ </span> rule.\ ${ if(od.story.changes) { }$\ <table class='@{od.markup.score_table}@'>\ ${ } }$\ ${ for (i = 0, _ref = (od.story.changes || []), len = _ref.length; i < _ref.length; i++) { change = _ref[i];\ if (change.metric.type === 'point'||change.metric.type === 'compound') {\ diff = ZERO.plus(change.delta['new'])\ .minus(change.delta['old'] || 0);\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString();\ }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@'>\ {{diff}}\ </span>\ </td>\ </tr>\ </tbody>\ ${ } else if(change.metric.type === 'set') { }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td colspan='2'>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ </tr>\ </tbody>\ <tbody class='@{od.markup.score_table_body}@'>\ ${ _.forEach(change.delta, function(delta, item) {\ diff = ZERO.plus(delta['new'])\ .minus(delta['old']||'0');\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString();\ }$\ <tr>\ <td>\ <span class='@{od.markup.score_delta_item}@'>\ {{item}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@'>\ {{diff}}\ </span>\ </td>\ </tr>\ ${ }); }$\ </tbody>\ ${ } else if(change.metric.type === 'state') { }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td colspan='2'>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ </tr>\ </tbody>\ <tbody class='@{od.markup.score_table_body}@'>\ <tr>\ <td>\ <span class='@{od.markup.score_delta_value}@ \ @{od.markup.diff_add}@'>{{change.delta['new']}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@ \ @{od.markup.diff_rem}@'>\ {{change.delta['old'] || '--'}}\ </span>\ </td>\ </tr>\ </tbody>\ ${ }\ }\ if(od.story.changes) { }$\ </table>\ ${ } }$\ </div>\ <time class='@{od.markup.timestamp}@' title='On \ {{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>\ {{ts.fromNow()}}</time> """ image: '' } } constructor: (options) -> options = options or {} @options = _.defaults options, { markup: Odysseus.default_markup external: {} } buildContext: (story, ext) -> ctx = {} ctx.isDummy = ext.env is 'debug' # Determine whether the current story is for a team or process # to simplify template code. ctx.isItem = ext.context in ['team', 'process'] if story.team? or ext.context is 'team' ctx.isTeam = true else if story.process? or ext.context is 'process' ctx.isProcess = true; # Determine whether the actor is the current player if story.event in [ 'create', 'delete', 'join' 'leave', 'kick', 'join:request', 'join:request:accept', 'join:request:reject', 'invite', 'invite:accept', 'invite:reject', 'role:change', 'role:request', 'role:request:accept', 'role:request:reject', 'role:assign', 'progress', 'level', 'achievement', 'resolution', 'action', 'custom_rule' ] # Determine whether the current player is the actor unless story.actor? and ext.profile?.id isnt story.actor.id ctx.amActor = true # Determine whether the target is the current player if story.event in [ 'kick', 'join:request:accept', 'join:request:reject', 'role:request:accept', 'role:request:reject', 'role:assign' 'score' ] unless story.player? and ext.profile?.id isnt story.player.id ctx.amPlayer = true else if story.event is 'resolution' unless story.deferred.actor? and ext.profile?.id isnt story.deferred.actor.id ctx.amPlayer = true else if story.event in ['invite:accept', 'invite:reject'] unless story.inviter? and ext.profile?.id isnt story.inviter.id ctx.amInviter = true else if story.event is 'invite' unless story.invitee? and ext.profile?.id isnt story.invitee.id ctx.amInvitee = true else if story.event is 'join:request' if story.state is 'ACCEPTED' and ext.profile?.id is story.accepted_by.id or story.state is 'REJECTED' and ext.profile?.id is story.rejected_by.id ctx.amMetaActor = true else if story.event is 'escalation' if story.completed? and ext.profile?.id is story.completed.player.id ctx.amPlayer = true # Finally, return the config object return ctx compile: (evt, type) -> unless (tpl_collection = Odysseus.stored_templates[evt])? throw("The #{evt} event is not supported") unless (tpl = tpl_collection[type])? throw("The #{type} template for #{evt} event cannot be found") _.template tpl toString: (story, external_data = {}) -> unless story? throw 'The story is not available' template = @compile story.event, 'text' context = @buildContext story, external_data template({ story: story ext: external_data ctx: context }) toHTML: (story, external_data = {}, config = {}) -> unless story? throw 'The story is not available' template = @compile story.event, 'html' context = @buildContext story, external_data html = template({ story: story, ext: external_data, ctx: context, markup: @options.markup }) if story.event is 'escalation' html = _.unescape html # The escalation text already comes rendered, # so unescape all HTML tags, etc if config.image is true image = """ <div class='#{@options.markup.image}'>\ #{@getImage(story, external_data)}\ </div> """ html = image + html html getImage: (story, external_data = {}) -> unless story? throw 'The story is not available' unless external_data.base_url? throw 'The base source url is not specified' template = @compile story.event, 'image' context = @buildContext story, external_data template({ story: story, ext: external_data, ctx: context, markup: @options.markup }) Odysseus; )
true
((global, factory) -> # AMD. Register as anonymous module. if typeof define is 'function' and define.amd define ['lodash', 'moment', 'bignumber'], factory # CommonJS. As a node module. else if typeof exports is 'object' module.exports = factory( require('lodash'), require('moment'), require('bignumber.js') ) else global['Odysseus'] = factory( global['_'], global['moment'], global['BigNumber'] ) )(this, (_, moment, BigNumber) -> # Override the templating delimiters to distinguish from HTML tags _.templateSettings.interpolate = /@\{([\s\S]+?)\}@/g _.templateSettings.escape = /\{\{([\s\S]+?)\}\}/g _.templateSettings.evaluate = /\$\{([\s\S]+?)\}\$/g _.templateSettings.variable = 'od' _.templateSettings.imports = { '_': _ # Pass the default lodash object 'moment': moment # Pass moment for time transformations 'ZERO': new BigNumber(0) # Since bigNumber isn't really required, # so just send a big ZERO to enable maths. }; class Odysseus ###* * A map of the default markup tags to be inserted into the rendered HTML * in-case no object is supplied in the constructor * @type {Object} ### @default_markup: { content: "od-content", image: "od-image", actor: "od-actor", target: "od-target", object: "od-object", role_list: "od-role-list", role: "od-role", lane: "od-lane", timestamp: "od-ts" } ###* * A list of all the available templates * @type {Object} ### @stored_templates: { ###* * Activity Templates ### "create": { text: " [{{moment(od.story.timestamp).format('llll')}}] - \ {{ od.story.admin ? '[Admin Event] ' : '' }}\ The '{{ \ od.story.team ? od.story.team.name || od.story.team.id : od.story.process.name || od.story.process.id \ }}' \ {{ od.ctx.isTeam ? 'team' : 'process' }} was created\ ${ if (!od.story.admin) { }$ \ by {{ od.ctx.amActor ? 'you' : od.story.actor.alias || od.story.actor.id}}\ ${ } }$. " html: " <div class='@{od.markup.content}@'>\ The <span class='@{od.markup.object}@'>\ {{od.story.team ? od.story.team.name || od.story.team.id : od.story.process.name || od.story.process.id}}\ </span> {{od.ctx.isTeam ? 'team' : 'process'}} was created\ ${ if (!od.story.admin) { }$ \ by <span class='@{od.markup.actor}@'>\ {{ od.ctx.amActor ? 'you' : od.story.actor.alias || od.story.actor.id }}\ </span>\ ${ } }$.\ ${ if (!!od.story.admin) { }$\ <footer class='@{od.markup.footer}@'>\ <span class='@{od.markup.admin}@'>Admin Event</span>\ </footer>\ ${ } }$\ </div>\ <time class='@{od.markup.timestamp}@' title='On \ {{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>\ {{ts.fromNow()}}</time> " image: '' }, "delete": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{od.ctx.amActor ? 'You' : od.story.actor.alias||od.story.actor.id}} deleted \ the {{od.ctx.isTeam ? 'team' : 'process'}} \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'." html: "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'You' : od.story.actor.alias||od.story.actor.id}}"+ "</span> deleted the {{od.ctx.isTeam ? 'team' : 'process'}} "+ "<span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>" image: '' }, "join": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{ od.story.admin ? '[Admin Event] ' : '' }}\ {{od.ctx.amActor ? 'You' : od.story.actor.alias||od.story.actor.id}} joined \ {{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$ as \ ${ if (od.ctx.isTeam) { }$\ {{_.keys(od.story.roles).join(', ')}}\ ${ } else if (od.ctx.isProcess) { }$\ {{_.reduce(od.story.roles, function(list, role, lane) {\ list.push([\ role + ' in ' + \ (lane === '*' ? 'All lanes' : \ lane === '~' ? 'No lanes' : (lane + ' lane'))\ ]);\ return list;\ }, []).join(', ')}}\ ${ } }$." html: "<div class='@{od.markup.content}@'>\ <span class='@{od.markup.actor}@'>\ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}}\ </span> joined \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ <span class='@{od.markup.object}@'>\ {{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}\ </span>\ ${ } }$ as \ <ul class='@{od.markup.role_list}@'>\ ${ if (od.ctx.isTeam) { }$\ ${ _.forEach(od.story.roles, function(enabled, role) { }$\ <li><span class='@{od.markup.role}@'>{{role}}</span></li>\ ${ }) }$\ ${ } else if (od.ctx.isProcess) { }$\ ${ _.forEach(od.story.roles, function(role, lane) { }$\ <li>\ <span class='@{od.markup.role}@'>{{role}}</span> in \ <span class='@{od.markup.lane}@'>\ {{lane === '*' ? 'All' : lane === '~' ? 'No' : lane}}\ </span> \ {{lane === '*'||lane === '~' ? 'lanes' : 'lane' }}\ </li>\ ${ })}$\ ${ } }$</ul>.\ ${ if (!!od.story.admin) { }$\ <footer class='@{od.markup.footer}@'>\ <span class='@{od.markup.admin}@'>Admin Event</span>\ </footer>\ ${ } }$\ </div>\ <time class='@{od.markup.timestamp}@' title='On \ {{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>\ {{ts.fromNow()}}</time>", image: """ ${ if (od.ctx.isDummy) { }$\ <i class='@{od.markup.dummy_icon}@'></i>\ ${ } else { }$\ <img \ src='{{od.ext.base_url}}/{{od.ctx.amActor ? \ od.ext.profile.id : od.story.actor.id}}'>\ ${ } }$ """ }, "leave": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{od.ctx.amActor ? 'You' : od.story.actor.alias||od.story.actor.id}} left \ {{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$.", html: "<div class='@{odPI:EMAIL:<EMAIL>END_PI.markupPI:EMAIL:<EMAIL>END_PI.content}@'>"+ "<span class='@{od.PI:EMAIL:<EMAIL>END_PI.actor}@'>"+ "{{od.ctx.amActor ? 'You' : od.story.actor.alias||od.story.actor.id}}"+ "</span> left "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$."+ "</div>"+ "<time class='@{od.PI:EMAIL:<EMAIL>END_PI}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>" image: '' }, "kick": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{od.ctx.amActor ? 'You' : od.story.actor.alias||od.story.actor.id}} kicked \ {{od.ctx.amPlayer ? 'you' : od.story.player.alias||od.story.player.id}} from \ {{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$.", html: "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'You' : od.story.actor.alias||od.story.actor.id}}"+ "</span> kicked "+ "<span class='@{od.markup.target}@'>"+ "{{od.ctx.amPlayer ? 'you' : od.story.player.alias||od.story.player.id}}"+ "</span> from "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>" image: '' }, "join:request:accept": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{od.ctx.amPlayer ? 'Your' : \ (od.story.player.alias||od.story.player.id) + '\u2019s'}} \ request to join \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$ has been accepted by \ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}}.", html: "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.target}@'>"+ "{{od.ctx.amPlayer ? 'Your' : (od.story.player.alias||od.story.player.id) + '\u2019s'}}"+ "</span> request to join "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$ has been accepted by "+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'you' : od.story.actor.alias||od.story.actor.id}}"+ "</span>."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>" image: '' }, "join:request:reject": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{od.ctx.amPlayer ? 'Your' : \ (od.story.player.alias||od.story.player.id) + '\u2019s'}} \ request to join \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$ has been rejected by \ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}}." html: "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.target}@'>"+ "{{od.ctx.amPlayer ? 'Your' : (od.story.player.alias||od.story.player.id) + '\u2019s'}}"+ "</span> request to join "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$ has been rejected by "+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'you' : od.story.actor.alias||od.story.actor.id}}"+ "</span>."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>" image: '' }, "invite:accept": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}} accepted \ {{od.ctx.amInviter ? 'your' : \ (od.story.inviter.alias||od.story.inviter.id) + '\u2019s'}} \ invitation to join \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id : \ od.story.process.name || od.story.process.id}}'\ ${ } }$ as \ ${ if (od.ctx.isTeam) { }$\ {{_.keys(od.story.roles).join(', ')}}\ ${ } else if (od.ctx.isProcess) { }$\ {{_.reduce(od.story.roles, function(list, role, lane) {\ list.push([\ role + ' in ' + \ (lane === '*' ? 'All lanes' : \ lane === '~' ? 'No lanes' : (lane + ' lane'))\ ]);\ return list;\ }, []).join(', ')}}\ ${ } }$." html: "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'You' : od.story.actor.alias||od.story.actor.id}}"+ "</span> accepted "+ "<span class='@{od.markup.target}@'>"+ "{{od.ctx.amInviter ? 'your' : (od.story.inviter.alias||od.story.inviter.id) + '\u2019s'}}"+ "</span> invitation to join "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$ as "+ "<ul class='@{od.markup.role_list}@'>"+ "${ if (od.ctx.isTeam) { }$"+ "${ _.forEach(od.story.roles, function(enabled, role) { }$"+ "<li><span class='@{od.markup.role}@'>{{role}}</span></li>"+ "${ }) }$"+ "${ } else if (od.ctx.isProcess) { }$"+ "${ _.forEach(od.story.roles, function(role, lane) { }$"+ "<li>"+ "<span class='@{od.markup.role}@'>{{role}}</span> in "+ "<span class='@{od.markup.lane}@'>"+ "{{lane === '*' ? 'All' : lane === '~' ? 'No' : lane}}"+ "</span> {{lane === '*'||lane === '~' ? 'lanes' : 'lane' }}"+ "</li>"+ "${ })}$"+ "${ } }$</ul>."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>" image: '' }, "invite:reject": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}} rejected \ {{od.ctx.amInviter ? 'your' : \ (od.story.inviter.alias||od.story.inviter.id) + '\u2019s'}} \ invitation to join \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id : \ od.story.process.name || od.story.process.id}}'\ ${ } }$ as \ ${ if (od.ctx.isTeam) { }$\ {{_.keys(od.story.roles).join(', ')}}\ ${ } else if (od.ctx.isProcess) { }$\ {{_.reduce(od.story.roles, function(list, role, lane) {\ list.push([\ role + ' in ' + \ (lane === '*' ? 'All lanes' : \ lane === '~' ? 'No lanes' : (lane + ' lane'))\ ]);\ return list;\ }, []).join(', ')}}\ ${ } }$." html: "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'You' : od.story.actor.alias||od.story.actor.id}}"+ "</span> rejected "+ "<span class='@{od.markup.target}@'>"+ "{{od.ctx.amInviter ? 'your' : (od.story.inviter.alias||od.story.inviter.id) + '\u2019s'}}"+ "</span> invitation to join "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$ as "+ "<ul class='@{od.markup.role_list}@'>"+ "${ if (od.ctx.isTeam) { }$"+ "${ _.forEach(od.story.roles, function(enabled, role) { }$"+ "<li><span class='@{od.markup.role}@'>{{role}}</span></li>"+ "${ }) }$"+ "${ } else if (od.ctx.isProcess) { }$"+ "${ _.forEach(od.story.roles, function(role, lane) { }$"+ "<li>"+ "<span class='@{od.markup.role}@'>{{role}}</span> in "+ "<span class='@{od.markup.lane}@'>"+ "{{lane === '*' ? 'All' : lane === '~' ? 'No' : lane}}"+ "</span> {{lane === '*'||lane === '~' ? 'lanes' : 'lane' }}"+ "</li>"+ "${ })}$"+ "${ } }$</ul>."+ "</div>"+ "<time class='@{PI:EMAIL:<EMAIL>END_PI}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>" image: '' }, "role:request:accept": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{od.ctx.amPlayer ? 'Your' : \ (od.story.player.alias||od.story.player.id) + '\u2019s'}} \ request for a change of roles in \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$ has been accepted by \ {{od.ctx.amActor ? 'you' : \ od.story.actor.alias||od.story.actor.id}}.\ \n Changes:\ ${ if (od.ctx.isTeam) {\ _.forEach(od.story.changes, function(diff, role) { }$\ \n [{{ !diff.old ? '+' : '-'}}] {{role}}\ ${ }); }$\ ${ } else if (od.ctx.isProcess) {\ _.forEach(od.story.changes, function(diff, lane) {\ if(!!diff['old'] && !!diff['new']) { }$\ \n [+] {{diff['new']}} in {{lane}} lane\ \n [-] {{diff['old']}} in {{lane}} lane\ ${ } else { }$\ \n [{{ !diff.old ? '+' : '-'}}] \ {{diff['new'] || diff['old']}} in \ {{lane === '*' ? 'All lanes' : \ lane === '~' ? 'No lanes' : (lane + ' lane')}}\ ${ }\ });\ } }$" html: "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.target}@'>"+ "{{od.ctx.amPlayer ? 'Your' : (od.story.player.alias||od.story.player.id) + '\u2019s'}}"+ "</span> request for a change of roles in "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$ has been accepted by "+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'you' : od.story.actor.alias||od.story.actor.id}}"+ "</span>."+ "<ul class='@{od.markup.role_list}@ @{od.markup.diff_list}@'>"+ "<li class='@{od.markup.list_header}@'>Changes</li>"+ "${ if (od.ctx.isTeam) {"+ "_.forEach(od.story.changes, function(diff, role) { }$"+ "<li class='@{od.markup[!diff.old ? 'diff_add' : 'diff_rem']}@'>"+ "<span class='@{od.markup.role}@'>{{role}}</span>"+ "</li>"+ "${ }); }$"+ "${ } else if (od.ctx.isProcess) {"+ "_.forEach(od.story.changes, function(diff, lane) {"+ # if both new and old keys exist, the role was changed "if(!!diff['old'] && !!diff['new']) { }$"+ "<li class='@{od.markup.diff_change}@'>"+ "<span class='@{od.markup.role}@ @{od.markup.diff_add}@'>{{diff['new']}}</span> from "+ "<span class='@{od.markup.role}@ @{od.markup.diff_rem}@'>{{diff['old']}}</span> in "+ "<span class='@{od.markup.lane}@'>{{lane}}</span> lane"+ "</li>"+ "${ } else { }$"+ "<li class='@{od.markup[!diff.old ? 'diff_add' : 'diff_rem']}@'>"+ "<span class='@{od.markup.role}@'>{{diff['new'] || diff['old']}}</span> in "+ "<span class='@{od.markup.lane}@'>"+ "{{lane === '*' ? 'All' : lane === '~' ? 'No' : lane}}"+ "</span> {{lane === '*'||lane === '~' ? 'lanes' : 'lane' }}"+ "</li>"+ "${ } }$"+ "${ }); }$"+ "${ } }$"+ "</ul>."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>" image: '' }, "role:request:reject": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{od.ctx.amPlayer ? 'Your' : \ (od.story.player.alias||od.story.player.id) + '\u2019s'}} \ request for a change of roles in \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$ has been rejected by \ {{od.ctx.amActor ? 'you' : \ od.story.actor.alias||od.story.actor.id}}." html: "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.target}@'>"+ "{{od.ctx.amPlayer ? 'Your' : (od.story.player.alias||od.story.player.id) + '\u2019s'}}"+ "</span> request for a change of roles in "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$ has been rejected by "+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'you' : od.story.actor.alias||od.story.actor.id}}"+ "</span>."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>" image: '' }, "role:change": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ ${ if (od.story.admin) { }$\ [Admin Event] \ {{od.ctx.amActor ? 'Your' : \ (od.story.actor.alias||od.story.actor.id)+'\u2019s'}}\ ${ } else { }$\ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}} \ {{od.ctx.amActor ? 'have' : 'has'}} changed\ ${ } }$ roles in \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$\ {{ !!od.story.admin ? ' have been changed' : ''}}.\ \n Changes:\ ${ if (od.ctx.isTeam) {\ _.forEach(od.story.changes, function(diff, role) { }$\ \n [{{ !diff.old ? '+' : '-'}}] {{role}}\ ${ }); }$\ ${ } else if (od.ctx.isProcess) {\ _.forEach(od.story.changes, function(diff, lane) {\ if(!!diff['old'] && !!diff['new']) { }$\ \n [+] {{diff['new']}} in {{lane}} lane\ \n [-] {{diff['old']}} in {{lane}} lane\ ${ } else { }$\ \n [{{ !diff.old ? '+' : '-'}}] \ {{diff['new'] || diff['old']}} in \ {{lane === '*' ? 'All lanes' : \ lane === '~' ? 'No lanes' : (lane + ' lane')}}\ ${ }\ });\ } }$" html: "<div class='@{od.markup.content}@'>\ ${ if (od.story.admin) { }$\ <span class='@{od.markup.target}@'>\ {{od.ctx.amActor ? 'Your' : \ (od.story.actor.alias||od.story.actor.id)+'\u2019s'}}\ </span>\ ${ } else { }$\ <span class='@{od.markup.actor}@'>\ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}}\ </span> \ {{od.ctx.amActor ? 'have' : 'has'}} changed\ ${ } }$ roles in \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ <span class='@{od.markup.object}@'>\ {{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}\ </span>\ ${ } }$\ {{ !!od.story.admin ? ' have been changed' : ''}}.\ <ul class='@{od.markup.role_list}@ @{od.markup.diff_list}@'>\ <li class='@{od.markup.list_header}@'>Changes</li>\ ${ if (od.ctx.isTeam) {\ _.forEach(od.story.changes, function(diff, role) { }$\ <li class='@{od.markup[!diff.old ? 'diff_add' : 'diff_rem']}@'>\ <span class='@{od.markup.role}@'>{{role}}</span>\ </li>\ ${ }); }$\ ${ } else if (od.ctx.isProcess) {\ _.forEach(od.story.changes, function(diff, lane) {\ if(!!diff['old'] && !!diff['new']) { }$\ <li class='@{od.markup.diff_change}@'>\ <span class='@{od.markup.role}@ @{od.markup.diff_add}@'>{{diff['new']}}</span> from \ <span class='@{od.markup.role}@ @{od.markup.diff_rem}@'>{{diff['old']}}</span> in \ <span class='@{od.markup.lane}@'>{{lane}}</span> lane\ </li>\ ${ } else { }$\ <li class='@{od.markup[!diff.old ? 'diff_add' : 'diff_rem']}@'>\ <span class='@{od.markup.role}@'>{{diff['new'] || diff['old']}}</span> in \ <span class='@{od.markup.lane}@'>\ {{lane === '*' ? 'All' : lane === '~' ? 'No' : lane}}\ </span> {{lane === '*'||lane === '~' ? 'lanes' : 'lane' }}\ </li>\ ${ } }$\ ${ }); }$\ ${ } }$\ </ul>.\ ${ if (!!od.story.admin) { }$\ <footer class='@{od.markup.footer}@'>\ <span class='@{od.markup.admin}@'>Admin Event</span>\ </footer>\ ${ } }$\ </div>\ <time class='@{od.markup.timestamp}@' title='On \ {{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>\ {{ts.fromNow()}}</time>" image: '' }, "role:assign": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{ od.story.admin ? '[Admin Event] ' : '' }}\ {{od.ctx.amPlayer ? 'Your' : \ (od.story.player.alias||od.story.player.id) + '\u2019s'}} \ roles in \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$ have been changed\ ${ if (!od.story.admin) { }$ \ by {{od.ctx.amActor ? 'you' : \ od.story.actor.alias||od.story.actor.id}}\ ${ } }$.\ \n Changes:\ ${ if (od.ctx.isTeam) {\ _.forEach(od.story.changes, function(diff, role) { }$\ \n [{{ !diff.old ? '+' : '-'}}] {{role}}\ ${ }); }$\ ${ } else if (od.ctx.isProcess) {\ _.forEach(od.story.changes, function(diff, lane) {\ if(!!diff['old'] && !!diff['new']) { }$\ \n [+] {{diff['new']}} in {{lane}} lane\ \n [-] {{diff['old']}} in {{lane}} lane\ ${ } else { }$\ \n [{{ !diff.old ? '+' : '-'}}] \ {{diff['new'] || diff['old']}} in \ {{lane === '*' ? 'All lanes' : \ lane === '~' ? 'No lanes' : (lane + ' lane')}}\ ${ }\ });\ } }$" html: "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.target}@'>"+ "{{od.ctx.amPlayer ? 'Your' : (od.story.player.alias||od.story.player.id) + '\u2019s'}}"+ "</span> roles in "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$ have been changed"+ "${ if (!od.story.admin) { }$"+ " by <span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'you' : "+ "od.story.actor.alias||od.story.actor.id}}"+ "</span>"+ "${ } }$."+ "<ul class='@{od.markup.role_list}@ @{od.markup.diff_list}@'>"+ "<li class='@{od.markup.list_header}@'>Changes</li>"+ "${ if (od.ctx.isTeam) {"+ "_.forEach(od.story.changes, function(diff, role) { }$"+ "<li class='@{od.markup[!diff.old ? 'diff_add' : 'diff_rem']}@'>"+ "<span class='@{od.markup.role}@'>{{role}}</span>"+ "</li>"+ "${ }); }$"+ "${ } else if (od.ctx.isProcess) {"+ "_.forEach(od.story.changes, function(diff, lane) {"+ # if both new and old keys exist, the role was changed "if(!!diff['old'] && !!diff['new']) { }$"+ "<li class='@{od.markup.diff_change}@'>"+ "<span class='@{od.markup.role}@ @{od.markup.diff_add}@'>{{diff['new']}}</span> from "+ "<span class='@{od.markup.role}@ @{od.markup.diff_rem}@'>{{diff['old']}}</span> in "+ "<span class='@{od.markup.lane}@'>{{lane}}</span> lane"+ "</li>"+ "${ } else { }$"+ "<li class='@{od.markup[!diff.old ? 'diff_add' : 'diff_rem']}@'>"+ "<span class='@{od.markup.role}@'>{{diff['new'] || diff['old']}}</span> in "+ "<span class='@{od.markup.lane}@'>"+ "{{lane === '*' ? 'All' : lane === '~' ? 'No' : lane}}"+ "</span> {{lane === '*'||lane === '~' ? 'lanes' : 'lane' }}"+ "</li>"+ "${ } }$"+ "${ }); }$"+ "${ } }$"+ "</ul>."+ "${ if (!!od.story.admin) { }$\ <footer class='@{od.markup.footer}@'>\ <span class='@{od.markup.admin}@'>Admin Event</span>\ </footer>\ ${ } }$"+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>" image: '' }, "join:request": { text: "${ if(od.story.state === 'PENDING') { }$\ [{{moment(od.story.timestamp).format('llll')}}] - \ ${ if(od.ctx.amActor) { }$\ Your request to join \ ${ } else { }$\ {{od.story.actor.alias||od.story.actor.id}} wants to join \ ${ } }$\ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$ as \ ${ if (od.ctx.isTeam) { }$\ {{_.keys(od.story.roles).join(', ')}}\ ${ } else if (od.ctx.isProcess) { }$\ {{_.reduce(od.story.roles, function(list, role, lane) {\ list.push([\ role + ' in ' + \ (lane === '*' ? 'All lanes' : \ lane === '~' ? 'No lanes' : (lane + ' lane'))\ ]);\ return list;\ }, []).join(', ')}}\ ${ } }$\ {{ od.ctx.amActor ? ' is pending' : '' }}.\ ${ } else if(od.story.state === 'CANCELLED') { }$\ [{{moment(od.story.cancelled_at).format('llll')}}] - \ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}} \ cancelled the request to join \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$.\ ${ } else if(od.story.state === 'ACCEPTED') { }$\ [{{moment(od.story.accepted_at).format('llll')}}] - \ {{od.ctx.amActor ? 'Your' : \ (od.story.actor.alias||od.story.actor.id) + '\u2019s'}} \ request to join \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$ has been accepted by \ {{od.ctx.amMetaActor ? 'you' : \ od.story.accepted_by.alias||od.story.accepted_by.id}}.\ ${ } else if(od.story.state === 'REJECTED') { }$\ [{{moment(od.story.rejected_at).format('llll')}}] - \ {{od.ctx.amActor ? 'Your' : \ (od.story.actor.alias||od.story.actor.id) + '\u2019s'}} \ request to join \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$ has been rejected by \ {{od.ctx.amMetaActor ? 'you' : \ od.story.rejected_by.alias||od.story.rejected_by.id}}.\ ${ } }$" html: "${ if(od.story.state === 'PENDING') { }$"+ "<div class='@{od.markup.content}@'>"+ "${ if(od.ctx.amActor) { }$"+ "<span class='@{od.markup.actor}@'>Your</span> request to join "+ "${ } else { }$"+ "<span class='@{od.markup.actor}@'>"+ "{{od.story.actor.alias||od.story.actor.id}}"+ "</span> wants to join "+ "${ } }$"+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$ as "+ "<ul class='@{od.markup.role_list}@'>"+ "${ if (od.ctx.isTeam) { }$"+ "${ _.forEach(od.story.roles, function(enabled, role) { }$"+ "<li><span class='@{od.markup.role}@'>{{role}}</span></li>"+ "${ }) }$"+ "${ } else if (od.ctx.isProcess) { }$"+ "${ _.forEach(od.story.roles, function(role, lane) { }$"+ "<li>"+ "<span class='@{od.markup.role}@'>{{role}}</span> in "+ "<span class='@{od.markup.lane}@'>"+ "{{lane === '*' ? 'All' : lane === '~' ? 'No' : lane}}"+ "</span> {{lane === '*'||lane === '~' ? 'lanes' : 'lane' }}"+ "</li>"+ "${ })}$"+ "${ } }$</ul>"+ "{{ od.ctx.amActor ? ' is pending' : '' }}."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>"+ "${ } else if(od.story.state === 'CANCELLED') { }$"+ "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'You' : od.story.actor.alias||od.story.actor.id}}"+ "</span>"+ " cancelled the request to join "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.cancelled_at)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>"+ "${ } else if(od.story.state === 'ACCEPTED') { }$"+ "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'Your' : (od.story.actor.alias||od.story.actor.id) + '\u2019s'}}"+ "</span> request to join "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$ has been accepted by "+ "<span class='@{od.markup.target}@'>"+ "{{od.ctx.amMetaActor ? 'you' : "+ "od.story.accepted_by.alias||od.story.accepted_by.id}}"+ "</span>."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.accepted_at)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>"+ "${ } else if(od.story.state === 'REJECTED') { }$"+ "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'Your' : (od.story.actor.alias||od.story.actor.id) + '\u2019s'}}"+ "</span> request to join "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$ has been rejected by "+ "<span class='@{od.markup.target}@'>"+ "{{od.ctx.amMetaActor ? 'you' : "+ "od.story.rejected_by.alias||od.story.rejected_by.id}}"+ "</span>."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.rejected_at)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>"+ "${ } }$" image: '' }, "invite": { text: "${ if(od.story.state === 'PENDING') { }$\ [{{moment(od.story.timestamp).format('llll')}}] - \ ${ if(od.ctx.amActor) { }$\ Your invitation to \ {{od.story.invitee.alias||od.story.invitee.id}} to join \ ${ } else { }$\ {{od.story.actor.alias||od.story.actor.id}} \ invited you to join \ ${ } }$\ the {{od.ctx.isTeam ? 'team' : 'process'}} \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}' as \ ${ if (od.ctx.isTeam) { }$\ {{_.keys(od.story.roles).join(', ')}}\ ${ } else if (od.ctx.isProcess) { }$\ {{_.reduce(od.story.roles, function(list, role, lane) {\ list.push([\ role + ' in ' + \ (lane === '*' ? 'All lanes' : \ lane === '~' ? 'No lanes' : (lane + ' lane'))\ ]);\ return list;\ }, []).join(', ')}}\ ${ } }$\ {{ od.ctx.amActor ? ' is pending' : '' }}.\ ${ } else if(od.story.state === 'CANCELLED') { }$\ [{{moment(od.story.cancelled_at).format('llll')}}] - \ {{od.story.actor.alias||od.story.actor.id}} \ withdrew the invitation to join \ the {{od.ctx.isTeam ? 'team' : 'process'}} \ '{{od.story.team ? od.story.team.name || od.story.team.id : \ od.story.process.name || od.story.process.id}}'.\ ${ } else if(od.story.state === 'ACCEPTED' || \ od.story.state === 'REJECTED') { }$\ [{{moment(od.story.accepted_at||\ od.story.rejected_at).format('llll')}}] - \ {{od.ctx.amInvitee ? 'You' : \ od.story.invitee.alias||od.story.invitee.id}} \ {{od.story.accepted_at ? 'accepted' : 'rejected'}} \ {{od.ctx.amActor ? 'your' : \ (od.story.actor.alias||od.story.actor.id)+'\u2019s'}} \ invitation to join \ the {{od.ctx.isTeam ? 'team' : 'process'}} \ '{{od.story.team ? od.story.team.name || od.story.team.id : \ od.story.process.name || od.story.process.id}}' as \ ${ if (od.ctx.isTeam) { }$\ {{_.keys(od.story.roles).join(', ')}}\ ${ } else if (od.ctx.isProcess) { }$\ {{_.reduce(od.story.roles, function(list, role, lane) {\ list.push([\ role + ' in ' + \ (lane === '*' ? 'All lanes' : \ lane === '~' ? 'No lanes' : (lane + ' lane'))\ ]);\ return list;\ }, []).join(', ')}}\ ${ } }$.\ ${ } }$" html: "${ if(od.story.state === 'PENDING') { }$"+ "<div class='@{od.markup.content}@'>"+ "${ if(od.ctx.amActor) { }$"+ "<span class='@{od.markup.actor}@'>Your</span> invitation to "+ "<span class='@{od.markup.target}@'>{{od.story.invitee.alias||od.story.invitee.id}}</span>"+ " to join "+ "${ } else { }$"+ "<span class='@{od.markup.actor}@'>{{od.story.actor.alias||od.story.actor.id}}</span> "+ "invited <span class='@{od.markup.target}@'>you</span> to join "+ "${ } }$"+ "the {{od.ctx.isTeam ? 'team' : 'process'}}"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ " as "+ "<ul class='@{od.markup.role_list}@'>"+ "${ if (od.ctx.isTeam) { }$"+ "${ _.forEach(od.story.roles, function(enabled, role) { }$"+ "<li><span class='@{od.markup.role}@'>{{role}}</span></li>"+ "${ }) }$"+ "${ } else if (od.ctx.isProcess) { }$"+ "${ _.forEach(od.story.roles, function(role, lane) { }$"+ "<li>"+ "<span class='@{od.markup.role}@'>{{role}}</span> in "+ "<span class='@{od.markup.lane}@'>"+ "{{lane === '*' ? 'All' : lane === '~' ? 'No' : lane}}"+ "</span> {{lane === '*'||lane === '~' ? 'lanes' : 'lane' }}"+ "</li>"+ "${ })}$"+ "${ } }$</ul>"+ "{{ od.ctx.amActor ? ' is pending' : '' }}."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>"+ "${ } else if(od.story.state === 'CANCELLED') { }$"+ "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.actor}@'>"+ "{{od.story.actor.alias||od.story.actor.id}}"+ "</span>"+ " withdrew the invitation to join "+ "the {{od.ctx.isTeam ? 'team' : 'process'}}"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.cancelled_at)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>"+ "${ } else if(od.story.state === 'ACCEPTED' || od.story.state === 'REJECTED') { }$"+ "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.target}@'>"+ "{{od.ctx.amInvitee ? 'You' : \ od.story.invitee.alias||od.story.invitee.id}}"+ "</span> {{od.story.accepted_at ? 'accepted' : 'rejected'}} "+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'your' : \ (od.story.actor.alias||od.story.actor.id)+'\u2019s'}}"+ "</span>"+ " invitation to join "+ "the {{od.ctx.isTeam ? 'team' : 'process'}}"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ " as "+ "<ul class='@{od.markup.role_list}@'>"+ "${ if (od.ctx.isTeam) { }$"+ "${ _.forEach(od.story.roles, function(enabled, role) { }$"+ "<li><span class='@{od.PI:EMAIL:<EMAIL>END_PI.role}@'>{{role}}</span></li>"+ "${ }) }$"+ "${ } else if (od.ctx.isProcess) { }$"+ "${ _.forEach(od.story.roles, function(role, lane) { }$"+ "<li>"+ "<span class='@{odPI:EMAIL:<EMAIL>END_PI.markupPI:EMAIL:<EMAIL>END_PI.role}@'>{{role}}</span> in "+ "<span class='@{od.markup.lane}@'>"+ "{{lane === '*' ? 'All' : lane === '~' ? 'No' : lane}}"+ "</span> {{lane === '*'||lane === '~' ? 'lanes' : 'lane' }}"+ "</li>"+ "${ })}$"+ "${ } }$</ul>."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.accepted_at||od.story.rejected_at)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>"+ "${ } }$" image: '' }, "role:request": { text: "${ if(od.story.state === 'PENDING') { }$\ [{{moment(od.story.timestamp).format('llll')}}] - \ ${ if(od.ctx.amActor) { }$\ Your request for change of roles in \ ${ } else { }$\ {{od.story.actor.alias||od.story.actor.id}} \ wants to change roles in \ ${ } }$\ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id : \ od.story.process.name || od.story.process.id}}'\ ${ } }$\ {{ od.ctx.amActor ? ' is pending' : '' }}.\ \n New Roles:\ ${ if (od.ctx.isTeam) { }$\ \n [*] {{_.keys(od.story.roles).join(', ')}}\ ${ } else if (od.ctx.isProcess) {\ _.forEach(od.story.roles, function(role, lane) { }$\ \n [*] {{role}} in \ {{lane === '*' ? 'All' : lane === '~' ? 'No' : lane}} \ {{lane === '*' || lane === '~' ? 'lanes' : 'lane'}}\ ${ });\ } }$\ ${ } else if(od.story.state === 'CANCELLED') { }$\ [{{moment(od.story.cancelled_at).format('llll')}}] - \ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}} \ cancelled the request for change of roles in \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$.\ ${ } else if(od.story.state === 'ACCEPTED') { }$\ [{{moment(od.story.accepted_at).format('llll')}}] - \ {{od.ctx.amActor ? 'Your' : \ (od.story.actor.alias||od.story.actor.id) + '\u2019s'}} \ request for change of roles in \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$ has been accepted by \ {{od.story.accepted_by.alias||od.story.accepted_by.id}}.\ ${ } else if(od.story.state === 'REJECTED') { }$\ [{{moment(od.story.rejected_at).format('llll')}}] - \ {{od.ctx.amActor ? 'Your' : \ (od.story.actor.alias||od.story.actor.id) + '\u2019s'}} \ request for change of roles in \ {{od.ctx.isItem ? 'this' : 'the'}} \ {{od.ctx.isTeam ? 'team' : 'process'}}\ ${ if (!od.ctx.isItem) { }$ \ '{{od.story.team ? od.story.team.name || od.story.team.id :\ od.story.process.name || od.story.process.id}}'\ ${ } }$ has been rejected by \ {{od.story.rejected_by.alias||od.story.rejected_by.id}}.\ ${ } }$" html: "${ if(od.story.state === 'PENDING') { }$"+ "<div class='@{od.markup.content}@'>"+ "${ if(od.ctx.amActor) { }$"+ "<span class='@{od.markup.actor}@'>Your</span> request for change of roles in "+ "${ } else { }$"+ "<span class='@{od.markup.actor}@'>"+ "{{od.story.actor.alias||od.story.actor.id}}"+ "</span> wants to change roles in "+ "${ } }$"+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$"+ "{{ od.ctx.amActor ? ' is pending' : '' }}."+ "<ul class='@{od.markup.role_list}@'>"+ "<li class='@{od.markup.list_header}@'>New Roles</li>"+ "${ if (od.ctx.isTeam) {"+ "_.forEach(od.story.roles, function(enabled, role) { }$"+ "<li><span class='@{odPI:EMAIL:<EMAIL>END_PI.markup.role}@'>{{role}}</span></li>"+ "${ })"+ "} else if (od.ctx.isProcess) {"+ "_.forEach(od.story.roles, function(role, lane) { }$"+ "<li>"+ "<span class='@{od.PI:EMAIL:<EMAIL>END_PI.role}@'>{{role}}</span> in "+ "<span class='@{od.markup.lane}@'>"+ "{{lane === '*' ? 'All' : lane === '~' ? 'No' : lane}}"+ "</span> {{lane === '*'||lane === '~' ? 'lanes' : 'lane' }}"+ "</li>"+ "${ });"+ "} }$"+ "</ul>"+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>"+ "${ } else if(od.story.state === 'CANCELLED') { }$"+ "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'You' : od.story.actor.alias||od.story.actor.id}}"+ "</span>"+ " cancelled the request for change of roles in "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.cancelled_at)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>"+ "${ } else if(od.story.state === 'ACCEPTED') { }$"+ "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'Your' : (od.story.actor.alias||od.story.actor.id) + '\u2019s'}}"+ "</span> request for change of roles in "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$ has been accepted by "+ "<span class='@{od.markup.target}@'>"+ "{{od.story.accepted_by.alias||od.story.accepted_by.id}}"+ "</span>."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.accepted_at)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>"+ "${ } else if(od.story.state === 'REJECTED') { }$"+ "<div class='@{od.markup.content}@'>"+ "<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'Your' : (od.story.actor.alias||od.story.actor.id) + '\u2019s'}}"+ "</span> request for change of roles in "+ "{{od.ctx.isItem ? 'this' : 'the'}} {{od.ctx.isTeam ? 'team' : 'process'}}"+ "${ if (!od.ctx.isItem) { }$"+ " <span class='@{od.markup.object}@'>"+ "{{od.story.team ? od.story.team.name || od.story.team.id :"+ "od.story.process.name || od.story.process.id}}"+ "</span>"+ "${ } }$ has been rejected by "+ "<span class='@{od.PI:EMAIL:<EMAIL>END_PI}@'>"+ "{{od.story.rejected_by.alias||od.story.rejected_by.id}}"+ "</span>."+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.rejected_at)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>"+ "${ } }$" image: '' }, "progress": { text: "[{{moment(od.story.timestamp).format('llll')}}] - {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}} completed \ '{{od.story.activity.name}}' in \ {{od.ctx.isItem ? 'this' : 'the'}} process\ ${ if(!od.ctx.isItem) { }$ \ '{{od.story.process.name || od.story.process.id}}'\ ${ } }$.\ ${ if (od.story.changes) { }$\ \n Changes:\ ${ } }$\ ${ for (i = 0, \ _ref = (od.story.changes || []), \ len = _ref.length; i < _ref.length; i++) { \ change = _ref[i];\ if(change.metric.type === 'point'||change.metric.type === 'compound') {\ diff = ZERO.plus(change.delta['new'])\ .minus(change.delta['old'] || 0);\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString(); }$\ \n [*] {{diff}} {{change.metric.name}}\ ${ } else if(change.metric.type === 'set') { }$\ \n [>] {{change.metric.name}}\ ${ _.forEach(change.delta, function(delta, item) {\ diff = ZERO.plus(delta['new']).minus(delta['old']||'0');\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString();\ }$\ \n [*] {{diff}} {{item}}\ ${ }); }$\ ${ } else if(change.metric.type === 'state') { }$\ \n [>] {{change.metric.name}}\ \n [+] {{change.delta['new']}}\ \n [-] {{change.delta['old']}}\ ${ }\ } }$" html: """ <div class='@{od.markup.content}@'>\ <span class='@{od.markup.actor}@'>\ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}}\ </span> completed \ <span class='@{od.markup.score_activity}@'>\ {{od.story.activity.name}}\ </span>.\ ${ if(od.story.changes) { }$\ <table class='@{od.markup.score_table}@'>\ ${ }\ for (i = 0, _ref = (od.story.changes || []), len = _ref.length; i < _ref.length; i++) { change = _ref[i];\ if (change.metric.type === 'point'||change.metric.type === 'compound') {\ diff = ZERO.plus(change.delta['new'])\ .minus(change.delta['old'] || 0);\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString();\ }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@'>\ {{diff}}\ </span>\ </td>\ </tr>\ </tbody>\ ${ } else if(change.metric.type === 'set') { }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td colspan='2'>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ </tr>\ </tbody>\ <tbody class='@{od.markup.score_table_body}@'>\ ${ _.forEach(change.delta, function(delta, item) {\ diff = ZERO.plus(delta['new']).minus(delta['old']||'0');\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString();\ }$\ <tr>\ <td>\ <span class='@{od.markup.score_delta_item}@'>\ {{item}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@'>\ {{diff}}\ </span>\ </td>\ </tr>\ ${ }); }$\ </tbody>\ ${ } else if(change.metric.type === 'state') { }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td colspan='2'>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ </tr>\ </tbody>\ <tbody class='@{od.markup.score_table_body}@'>\ <tr>\ <td>\ <span class='@{od.markup.score_delta_value}@ \ @{od.markup.diff_add}@'>{{change.delta['new']}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@ \ @{od.markup.diff_rem}@'>\ {{change.delta['old'] || '--'}}\ </span>\ </td>\ </tr>\ </tbody>\ ${ }\ }\ if(od.story.changes) { }$\ </table>\ ${ }\ if(!od.ctx.isItem) { }$\ <footer class='@{od.markup.footer}@'>\ <span class='@{od.markup.object}@'>\ {{od.story.process.name||od.story.process.id}}\ </span>\ </footer>\ ${ } }$\ </div>\ <time class='@{od.markup.timestamp}@' title='On \ {{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>\ {{ts.fromNow()}}</time> """ image: '' }, "resolution": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}} completed \ '{{od.story.activity.name}}' in \ {{od.ctx.isItem ? 'this' : 'the'}} process\ ${ if(!od.ctx.isItem) { }$ \ '{{od.story.process.name || od.story.process.id}}'\ ${ } }$ and credited \ {{od.ctx.amPlayer ? \ (od.ctx.amActor ? 'yourself' : 'you') : \ od.story.deferred.actor.alias||od.story.deferred.actor.id}} \ for completing '{{od.story.deferred.activity.name}}'.\n \ Changes:\ ${ for (i = 0, _ref = (od.story.deferred.changes || []), len = _ref.length; i < _ref.length; i++) { change = _ref[i];\ if(change.metric.type === 'point'||change.metric.type === 'compound') {\ diff = ZERO.plus(change.delta['new'])\ .minus(change.delta['old'] || 0);\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString()\ }$\ \n [*] {{diff}} {{change.metric.name}}\ ${ } else if(change.metric.type === 'set') { }$\ \n [>] {{change.metric.name}}\ ${ _.forEach(change.delta, function(delta, item) {\ diff = ZERO.plus(delta['new']).minus(delta['old']||'0');\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString()\ }$\ \n [*] {{diff}} {{item}}\ ${ }); }$\ ${ } else if(change.metric.type === 'state') { }$\ \n [>] {{change.metric.name}}\ \n [+] {{change.delta['new']}}\ \n [-] {{change.delta['old']}}\ ${ }\ } }$" html: "<div class='@{od.markup.content}@'>\ <span class='@{od.markup.actor}@'>\ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}}\ </span> completed \ <span class='@{od.markup.score_activity}@'>\ {{od.story.activity.name}}\ </span> and credited \ <span class='@{od.markup.target}@'>\ {{od.ctx.amPlayer ? \ (od.ctx.amActor ? 'yourself' : 'you') : \ od.story.deferred.actor.alias||od.story.deferred.actor.id}}\ </span> for completing \ <span class='@{od.markup.score_activity}@'>\ {{od.story.deferred.activity.name}}\ </span>.\ <table class='@{od.markup.score_table}@'>\ ${ for (i = 0, _ref = (od.story.deferred.changes || []), len = _ref.length; i < _ref.length; i++) { change = _ref[i];\ if(change.metric.type === 'point'||change.metric.type === 'compound') {\ diff = ZERO.plus(change.delta['new'])\ .minus(change.delta['old'] || 0);\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString();\ }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@'>\ {{diff}}\ </span>\ </td>\ </tr>\ </tbody>\ ${ } else if(change.metric.type === 'set') { }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td colspan='2'>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ </tr>\ </tbody>\ <tbody class='@{od.markup.score_table_body}@'>\ ${ _.forEach(change.delta, function(delta, item) {\ diff = ZERO.plus(delta['new'])\ .minus(delta['old']||'0');\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString();\ }$\ <tr>\ <td>\ <span class='@{od.markup.score_delta_item}@'>\ {{item}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@'>\ {{diff}}\ </span>\ </td>\ </tr>\ ${ }); }$\ </tbody>\ ${ } else if(change.metric.type === 'state') { }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td colspan='2'>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ </tr>\ </tbody>\ <tbody class='@{od.markup.score_table_body}@'>\ <tr>\ <td>\ <span class='@{od.markup.score_delta_value}@ \ @{od.markup.diff_add}@'>\ {{change.delta['new']}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@ \ @{od.markup.diff_rem}@'>\ {{change.delta['old']}}\ </span>\ </td>\ </tr>\ </tbody>\ ${ }\ } }$\ </table>\ ${ if(!od.ctx.isItem) { }$\ <footer class='@{od.markup.footer}@'>\ <span class='@{od.markup.object}@'>\ {{od.story.process.name||od.story.process.id}}\ </span>\ </footer>\ ${ } }$\ </div>\ <time class='@{od.markup.timestamp}@' title='On \ {{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>\ {{ts.fromNow()}}</time>" image: '' }, "level": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{od.ctx.amActor ? 'Your' : \ (od.story.actor.alias||od.story.actor.id) + '\u2019s'}} \ ${ change = od.story.changes[0]; }$\ '{{change.metric.name}}' level changed \ ${ if (change.delta['old']) { }$\ from '{{change.delta['old']}}' \ ${ } }$\ to '{{change.delta['new']}}'\ ." html: "<div class='@{od.markup.content}@'>\ <span class='@{od.markup.actor}@'>\ {{od.ctx.amActor ? 'Your' : \ (od.story.actor.alias||od.story.actor.id) + '\u2019s'}}\ </span> \ ${ change = od.story.changes[0]; }$\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}</span> level changed\ ${ if (change.delta['old']) { }$ \ from <span class='@{od.markup.score_delta_value}@ \ @{od.markup.diff_rem}@'>{{change.delta['old']}}\ </span>\ ${ } }$ \ to <span class='@{od.markup.score_delta_value}@ \ @{od.markup.diff_add}@'>{{change.delta['new']}}</span>\ .\ </div>\ <time class='@{od.markup.timestamp}@' title='On \ {{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>\ {{ts.fromNow()}}</time>" image: '' }, "achievement": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{od.ctx.amActor ? 'Congratulations! You' : \ od.story.actor.alias||od.story.actor.id}} \ unlocked an achievement.\n"+ " Changes:"+ "${ for (i = 0, _ref = (od.story.changes || []), len = _ref.length; i < _ref.length; i++) { change = _ref[i]; }$"+ "\n [>] {{change.metric.name}}"+ "${ _.forEach(change.delta, function(delta, item) {"+ "diff = ZERO.plus(delta['new']).minus(delta['old']||'0');"+ "diff = (diff.gt(ZERO) ? '+' : '') + diff.toString();"+ "}$"+ "\n [*] {{diff}} {{item}}"+ "${ }); }$"+ "${ } }$", html: "<div class='@{od.markup.content}@'>"+ "{{od.ctx.amActor ? 'Congratulations! ' : ''}}<span class='@{od.markup.actor}@'>"+ "{{od.ctx.amActor ? 'You' : od.story.actor.alias||od.story.actor.id}}"+ "</span>"+ " unlocked an achievement."+ "<table class='@{od.markup.score_table}@ @{od.markup.achievement_table}@'>"+ "${ for (i = 0, _ref = (od.story.changes || []), len = _ref.length; i < _ref.length; i++) { change = _ref[i]; }$"+ "<tbody class='@{od.markup.score_table_header}@'>"+ "<tr>"+ "<td colspan='2'>"+ "<span class='@{od.markup.score_metric}@'>"+ "{{change.metric.name}}"+ "</span>"+ "</td>"+ "</tr>"+ "</tbody>"+ "<tbody class='@{od.markup.score_table_body}@'>"+ "${ _.forEach(change.delta, function(delta, item) {"+ "diff = ZERO.plus(delta['new']).minus(delta['old']||'0');"+ "diff = (diff.gt(ZERO) ? '+' : '') + diff.toString();"+ "}$"+ "<tr>"+ "<td>"+ "<span class='@{od.markup.score_delta_item}@'>"+ "{{item}}"+ "</span>"+ "</td>"+ "<td>"+ "<span class='@{od.markup.score_delta_value}@'>"+ "{{diff}}"+ "</span>"+ "</td>"+ "</tr>"+ "${ }); }$"+ "</tbody>"+ "${ } }$"+ "</table>"+ "</div>"+ "<time class='@{od.markup.timestamp}@' title='On "+ "{{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>"+ "{{ts.fromNow()}}</time>" image: '' }, "score": { text: "[{{moment(od.story.timestamp).format('llll')}}] - {{ od.story.admin ? '[Admin Event] ' : '' }}\ {{od.ctx.amPlayer ? 'Your' : \ (od.story.player.alias||od.story.player.id) + '\u2019s'}} \ scores were changed.\ \n New Scores:\ ${ for (i = 0, _ref = (od.story.changes || []), len = _ref.length; i < _ref.length; i++) { change = _ref[i];\ if(change.metric.type === 'point'||change.metric.type === 'compound') { }$\ \n [*] {{change.delta['new']}} {{change.metric.name}}\ ${ } else if(change.metric.type === 'set') { }$\ \n [>] {{change.metric.name}}\ ${ _.forEach(change.delta, function(delta, item) { }$\ \n [*] {{delta['new']}} {{item}}\ ${ }); }$\ ${ } else if(change.metric.type === 'state') { }$\ \n [*] {{change.metric.name}} - {{change.delta['new']}}\ ${ }\ } }$" html: "<div class='@{od.markup.content}@'>\ <span class='@{od.markup.target}@'>\ {{od.ctx.amPlayer ? 'Your' : \ (od.story.player.alias||od.story.player.id) + '\u2019s'}}\ </span> scores were changed.\ <table class='@{od.markup.score_table}@'>\ ${ for (i = 0, _ref = (od.story.changes || []), len = _ref.length; i < _ref.length; i++) { change = _ref[i];\ if (change.metric.type === 'point'||change.metric.type === 'compound') { }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@'>\ {{change.delta['new']}}\ </span>\ </td>\ </tr>\ </tbody>\ ${ } else if(change.metric.type === 'set') { }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td colspan='2'>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ </tr>\ </tbody>\ <tbody class='@{od.markup.score_table_body}@'>\ ${ _.forEach(change.delta, function(delta, item) { }$\ <tr>\ <td>\ <span class='@{od.markup.score_delta_item}@'>\ {{item}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@'>\ {{delta['new']}}\ </span>\ </td>\ </tr>\ ${ }); }$\ </tbody>\ ${ } else if(change.metric.type === 'state') { }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@'>\ {{change.delta['new']}}\ </span>\ </td>\ </tr>\ </tbody>\ ${ }\ } }$\ </table>\ ${ if (!!od.story.admin) { }$\ <footer class='@{od.markup.footer}@'>\ <span class='@{od.markup.admin}@'>Admin Event</span>\ </footer>\ ${ } }$\ </div>\ <time class='@{od.markup.timestamp}@' title='On \ {{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>\ {{ts.fromNow()}}</time>" image: '' }, "escalation": { text: "[{{moment(od.story.timestamp).format('llll')}}] - \ {{od.story.message}}\ ${ if (!!od.story.completed) { \ var completed = od.story.completed; }$ \ [*] {{od.ctx.amPlayer ? 'You' : \ completed.player.alias||completed.player.id}} completed \ {{completed.trigger.name||completed.trigger.id}}\ \n [{{moment(od.story.timestamp).format('llll')}}]\ ${ } }$" html: "<div class='@{od.markup.content}@\ @{!!od.story.completed?' '+od.markup.escalation_inactive:''}@'>\ {{od.story.message}}\ </div>\ ${ if (!!od.story.completed) { \ var completed = od.story.completed; }$\ <footer class='@{od.markup.footer}@ \ @{od.markup.escalation_footer}@'>\ <span class='@{od.markup.escalation_player}@'> {{od.ctx.amPlayer ? 'You' : \ completed.player.alias||completed.player.id}} completed \ {{completed.trigger.name||completed.trigger.id}} </span>\ <time class='@{od.markup.escalation_timestamp}@ \ @{od.markup.timestamp}@' title='Completed on \ {{(ts = moment(completed.timestamp)).format(\'llll\')}}'>\ {{ts.fromNow()}}</time> </footer>\ ${ } }$\ <time class='@{od.markup.timestamp}@' title='On \ {{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>\ {{ts.fromNow()}}</time>" image: '' }, "action": { text: "[{{moment(od.story.timestamp).format('llll')}}] - {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}} completed \ '{{od.story.action.name}}'.\ ${ if (od.story.changes) { }$\ \n Changes:\ ${ } }$\ ${ for (i = 0, _ref = (od.story.changes || []), len = _ref.length; i < _ref.length; i++) { change = _ref[i];\ if(change.metric.type === 'point'||change.metric.type === 'compound') {\ diff = ZERO.plus(change.delta['new'])\ .minus(change.delta['old'] || 0);\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString(); }$\ \n [*] {{diff}} {{change.metric.name}}\ ${ } else if(change.metric.type === 'set') { }$\ \n [>] {{change.metric.name}}\ ${ _.forEach(change.delta, function(delta, item) {\ diff = ZERO.plus(delta['new']).minus(delta['old']||'0');\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString();\ }$\ \n [*] {{diff}} {{item}}\ ${ }); }$\ ${ } else if(change.metric.type === 'state') { }$\ \n [>] {{change.metric.name}}\ \n [+] {{change.delta['new']}}\ \n [-] {{change.delta['old']}}\ ${ }\ } }$" html: """ <div class='@{od.markup.content}@'>\ <span class='@{od.markup.actor}@'>\ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}}\ </span> completed \ <span class='@{od.markup.score_activity}@'>\ {{od.story.action.name}}\ </span>.\ ${ if(od.story.changes) { }$\ <table class='@{od.markup.score_table}@'>\ ${ } }$\ ${ for (i = 0, _ref = (od.story.changes || []), len = _ref.length; i < _ref.length; i++) { change = _ref[i];\ if (change.metric.type === 'point'||change.metric.type === 'compound') {\ diff = ZERO.plus(change.delta['new'])\ .minus(change.delta['old'] || 0);\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString();\ }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@'>\ {{diff}}\ </span>\ </td>\ </tr>\ </tbody>\ ${ } else if(change.metric.type === 'set') { }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td colspan='2'>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ </tr>\ </tbody>\ <tbody class='@{od.markup.score_table_body}@'>\ ${ _.forEach(change.delta, function(delta, item) {\ diff = ZERO.plus(delta['new'])\ .minus(delta['old']||'0');\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString();\ }$\ <tr>\ <td>\ <span class='@{od.markup.score_delta_item}@'>\ {{item}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@'>\ {{diff}}\ </span>\ </td>\ </tr>\ ${ }); }$\ </tbody>\ ${ } else if(change.metric.type === 'state') { }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td colspan='2'>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ </tr>\ </tbody>\ <tbody class='@{od.markup.score_table_body}@'>\ <tr>\ <td>\ <span class='@{od.markup.score_delta_value}@ \ @{od.markup.diff_add}@'>{{change.delta['new']}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@ \ @{od.markup.diff_rem}@'>\ {{change.delta['old'] || '--'}}\ </span>\ </td>\ </tr>\ </tbody>\ ${ }\ }\ if(od.story.changes) { }$\ </table>\ ${ } }$\ </div>\ <time class='@{od.markup.timestamp}@' title='On \ {{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>\ {{ts.fromNow()}}</time> """ image: '' }, "custom_rule": { text: "[{{moment(od.story.timestamp).format('llll')}}] - {{od.ctx.amActor ? 'You were' : \ (od.story.actor.alias||od.story.actor.id) + ' was'}} awarded \ via '{{od.story.rule.name}}' rule.\ ${ if (od.story.changes) { }$\ \n Changes:\ ${ } }$\ ${ for (i = 0, _ref = (od.story.changes || []), len = _ref.length; i < _ref.length; i++) { change = _ref[i];\ if(change.metric.type === 'point'||change.metric.type === 'compound') {\ diff = ZERO.plus(change.delta['new'])\ .minus(change.delta['old'] || 0);\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString(); }$\ \n [*] {{diff}} {{change.metric.name}}\ ${ } else if(change.metric.type === 'set') { }$\ \n [>] {{change.metric.name}}\ ${ _.forEach(change.delta, function(delta, item) {\ diff = ZERO.plus(delta['new']).minus(delta['old']||'0');\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString();\ }$\ \n [*] {{diff}} {{item}}\ ${ }); }$\ ${ } else if(change.metric.type === 'state') { }$\ \n [>] {{change.metric.name}}\ \n [+] {{change.delta['new']}}\ \n [-] {{change.delta['old']}}\ ${ }\ } }$" html: """ <div class='@{od.markup.content}@'>\ <span class='@{od.markup.actor}@'>\ {{od.ctx.amActor ? 'You' : \ od.story.actor.alias||od.story.actor.id}}\ </span> {{od.ctx.amActor ? 'were' : 'was'}} awarded via \ <span class='@{od.markup.score_rule}@'>\ {{od.story.rule.name}}\ </span> rule.\ ${ if(od.story.changes) { }$\ <table class='@{od.markup.score_table}@'>\ ${ } }$\ ${ for (i = 0, _ref = (od.story.changes || []), len = _ref.length; i < _ref.length; i++) { change = _ref[i];\ if (change.metric.type === 'point'||change.metric.type === 'compound') {\ diff = ZERO.plus(change.delta['new'])\ .minus(change.delta['old'] || 0);\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString();\ }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@'>\ {{diff}}\ </span>\ </td>\ </tr>\ </tbody>\ ${ } else if(change.metric.type === 'set') { }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td colspan='2'>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ </tr>\ </tbody>\ <tbody class='@{od.markup.score_table_body}@'>\ ${ _.forEach(change.delta, function(delta, item) {\ diff = ZERO.plus(delta['new'])\ .minus(delta['old']||'0');\ diff = (diff.gt(ZERO) ? '+' : '') + diff.toString();\ }$\ <tr>\ <td>\ <span class='@{od.markup.score_delta_item}@'>\ {{item}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@'>\ {{diff}}\ </span>\ </td>\ </tr>\ ${ }); }$\ </tbody>\ ${ } else if(change.metric.type === 'state') { }$\ <tbody class='@{od.markup.score_table_header}@'>\ <tr>\ <td colspan='2'>\ <span class='@{od.markup.score_metric}@'>\ {{change.metric.name}}\ </span>\ </td>\ </tr>\ </tbody>\ <tbody class='@{od.markup.score_table_body}@'>\ <tr>\ <td>\ <span class='@{od.markup.score_delta_value}@ \ @{od.markup.diff_add}@'>{{change.delta['new']}}\ </span>\ </td>\ <td>\ <span class='@{od.markup.score_delta_value}@ \ @{od.markup.diff_rem}@'>\ {{change.delta['old'] || '--'}}\ </span>\ </td>\ </tr>\ </tbody>\ ${ }\ }\ if(od.story.changes) { }$\ </table>\ ${ } }$\ </div>\ <time class='@{od.markup.timestamp}@' title='On \ {{(ts = moment(od.story.timestamp)).format(\'llll\')}}'>\ {{ts.fromNow()}}</time> """ image: '' } } constructor: (options) -> options = options or {} @options = _.defaults options, { markup: Odysseus.default_markup external: {} } buildContext: (story, ext) -> ctx = {} ctx.isDummy = ext.env is 'debug' # Determine whether the current story is for a team or process # to simplify template code. ctx.isItem = ext.context in ['team', 'process'] if story.team? or ext.context is 'team' ctx.isTeam = true else if story.process? or ext.context is 'process' ctx.isProcess = true; # Determine whether the actor is the current player if story.event in [ 'create', 'delete', 'join' 'leave', 'kick', 'join:request', 'join:request:accept', 'join:request:reject', 'invite', 'invite:accept', 'invite:reject', 'role:change', 'role:request', 'role:request:accept', 'role:request:reject', 'role:assign', 'progress', 'level', 'achievement', 'resolution', 'action', 'custom_rule' ] # Determine whether the current player is the actor unless story.actor? and ext.profile?.id isnt story.actor.id ctx.amActor = true # Determine whether the target is the current player if story.event in [ 'kick', 'join:request:accept', 'join:request:reject', 'role:request:accept', 'role:request:reject', 'role:assign' 'score' ] unless story.player? and ext.profile?.id isnt story.player.id ctx.amPlayer = true else if story.event is 'resolution' unless story.deferred.actor? and ext.profile?.id isnt story.deferred.actor.id ctx.amPlayer = true else if story.event in ['invite:accept', 'invite:reject'] unless story.inviter? and ext.profile?.id isnt story.inviter.id ctx.amInviter = true else if story.event is 'invite' unless story.invitee? and ext.profile?.id isnt story.invitee.id ctx.amInvitee = true else if story.event is 'join:request' if story.state is 'ACCEPTED' and ext.profile?.id is story.accepted_by.id or story.state is 'REJECTED' and ext.profile?.id is story.rejected_by.id ctx.amMetaActor = true else if story.event is 'escalation' if story.completed? and ext.profile?.id is story.completed.player.id ctx.amPlayer = true # Finally, return the config object return ctx compile: (evt, type) -> unless (tpl_collection = Odysseus.stored_templates[evt])? throw("The #{evt} event is not supported") unless (tpl = tpl_collection[type])? throw("The #{type} template for #{evt} event cannot be found") _.template tpl toString: (story, external_data = {}) -> unless story? throw 'The story is not available' template = @compile story.event, 'text' context = @buildContext story, external_data template({ story: story ext: external_data ctx: context }) toHTML: (story, external_data = {}, config = {}) -> unless story? throw 'The story is not available' template = @compile story.event, 'html' context = @buildContext story, external_data html = template({ story: story, ext: external_data, ctx: context, markup: @options.markup }) if story.event is 'escalation' html = _.unescape html # The escalation text already comes rendered, # so unescape all HTML tags, etc if config.image is true image = """ <div class='#{@options.markup.image}'>\ #{@getImage(story, external_data)}\ </div> """ html = image + html html getImage: (story, external_data = {}) -> unless story? throw 'The story is not available' unless external_data.base_url? throw 'The base source url is not specified' template = @compile story.event, 'image' context = @buildContext story, external_data template({ story: story, ext: external_data, ctx: context, markup: @options.markup }) Odysseus; )
[ { "context": " ret\n }\n {\n name:\"黒い村\"\n minNumber:6\n rule:(number)->\n", "end": 13610, "score": 0.6280943751335144, "start": 13607, "tag": "NAME", "value": "黒い村" }, { "context": " ret\n }\n {\n nam...
client/code/shared/game.coffee
h3zjp/jinro
0
Shared= game:exports # 身代わりセーフティありのときの除外役職一覧 exports.SAFETY_EXCLUDED_JOBS = SAFETY_EXCLUDED_JOBS = ["QueenSpectator","Spy2","Poisoner","Cat","Cupid","BloodyMary","Noble", "Lover", "Twin","Hunter","MadHunter","Idol","SnowLover","Raven","LunaticLover","HooliganGuard","HooliganAttacker","SantaClaus","Oni"] # ------ 役職一覧 # 基本役職 exports.jobs=["Human","Werewolf","Diviner","Psychic","Madman","Guard","Couple","Fox", # ミラーズホロウの人狼 "Hunter","Cupid", # 特殊役職? "Poisoner","BigWolf","TinyFox","Cat", # るる鯖で見つけた役職 "Fanatic","Immoral" # 特殊役職2 "Devil","Stalker","WhisperingMad","Dog", # 桃栗基本特殊役職 "Bat","Noble","Slave","Magician","Spy","WolfDiviner", # 桃栗期間限定役職 "Fugitive","Merchant","QueenSpectator","MadWolf","Liar","Spy2","Copier", # 究極の人狼の役職 "ToughGuy","Cursed","ApprenticeSeer","Diseased","Spellcaster","Lycan","Priest","Prince","PI","Sorcerer", "Doppleganger","CultLeader","Vampire","LoneWolf","Witch","Oldman","Tanner","OccultMania","WolfCub","Thief", "Hoodlum","TroubleMaker","FrankensteinsMonster", "BloodyMary", # うそつき人狼の役職 "Dictator","SeersMama","Trapper","WolfBoy","King", # Twitter人狼の役職 "Counselor","Miko","GreedyWolf","FascinatingWolf","SolitudeWolf","ToughWolf","ThreateningWolf", # dat人狼 "Sleepwalker", # 人狼物語 "CurseWolf", # 人狼議事 "Trickster", # 人狼物語(瓜科国) "MadCouple", # 人狼物語(薔薇の下国) "NightRabbit", # 人狼物語(深海国) "Fate","QueenOfNight","CynthiaWolf","Saint", # 人狼物語(三日月国) "Tarzan", # 天国系の役職 "Lover", # 人狼天国 "ObstructiveMad", # 人狼天国 "WanderingGuard", # 錠前天国 "BadLady", # 蒼汁天国、人狼天国 # ねじれ天国 "Bomber","Blasphemy","Ushinotokimairi","DualPersonality","GachaAddicted", "Gambler","Faker","NetherWolf", # 人狼式 "Emma","EyesWolf","TongueWolf","Oracle","Hitokotonushinokami", "SealWolf","Oni", # えけけ鯖 "MadHunter","Ascetic" # 人狼パーティー "TinyGhost","Ninja","Twin","Dracula","VampireClan" # その他 "RedHood","Baker","XianFox","LunaticLover" # 人狼放浪記 "MadDog","CraftyWolf","Pumpkin","MadScientist","SpiritPossessed","Forensic" # 牢獄の悪夢 "PsychoKiller","Cosplayer", # 人狼NET "Satori", # わんないと人狼 "Phantom", # 月夜の人狼 "DrawGirl","CautiousWolf","SnowLover","Raven","Samurai", # 月夜の人狼(闇夜の人狼) "DarkClown", # 人狼HOUSE "Hypnotist", # 人狼ジャッジメント "BlackCat","Amanojaku", # 人狼 SUPER DX(幻冬舎) "Illusionist", # 魔法都市の人狼 "Elementaler", # 24時間耐久人狼 "IntuitionWolf", # 絶対的人狼 "AbsoluteWolf", #人狼村池袋本店 "DarkWolf", # オリジナル "SantaClaus","Reindeer", "Pyrotechnist","Patissiere","Shishimai","Idol","LurkingMad", "DecoyWolf","Hooligan","HomeComer","DragonKnight","Poet","Sacrifice", "Synesthete","Streamer","RemoteWorker","Disguised" ] # 隠されていて自分で入れることができない役職 exports.hiddenJobs = [ "Light", "Neet", "MinionSelector", "QuantumPlayer", "HolyMarked", "Lorelei", # 宇宙人狼 "SpaceWerewolfCrew", "SpaceWerewolfImposter", "SpaceWerewolfObserver","SpaceWerewolfGuard","SpaceWerewolfSabotage" ] # 人外 exports.nonhumans=["Werewolf","Fox","BigWolf","TinyFox","WolfDiviner","MadWolf","Devil","Vampire","LoneWolf","WolfCub","GreedyWolf","FascinatingWolf","SolitudeWolf","ToughWolf","ThreateningWolf","CautiousWolf","CraftyWolf","EyesWolf","TongueWolf","XianFox","DecoyWolf","Dracula","AbsoluteWolf","NightRabbit","CurseWolf","IntuitionWolf","Lorelei","SealWolf","CynthiaWolf","Trickster","NetherWolf","DarkWolf","SpaceWerewolfImposter"] # 黒が出る人 exports.blacks=["Werewolf","WolfDiviner","MadWolf","Lycan","LoneWolf","WolfCub","Dog","GreedyWolf","FascinatingWolf","SolitudeWolf","ToughWolf","ThreateningWolf","MadDog","CraftyWolf","Cosplayer","EyesWolf","TongueWolf","DecoyWolf","AbsoluteWolf","CurseWolf","IntuitionWolf","SealWolf","CynthiaWolf","NetherWolf","DarkWolf","SpaceWerewolfImposter"] # チームたち exports.teams=teams= Human:["Human","Diviner","Psychic","Guard","Couple","Poisoner","ToughGuy","Noble","Slave","Magician","Fugitive","Merchant","QueenSpectator","MadWolf","Liar","Light","Cursed","ApprenticeSeer","Diseased","Spellcaster","Lycan","Priest","Prince","PI","Cat","Witch","Oldman","OccultMania","Dog","Dictator","SeersMama","Trapper","RedHood","Counselor","Miko","HolyMarked","WanderingGuard","TroubleMaker","FrankensteinsMonster","BloodyMary","King","SantaClaus","Phantom","DrawGirl","Pyrotechnist","Baker","SpiritPossessed","GotChocolate","Forensic","Cosplayer","TinyGhost","Ninja","Twin","Hunter","Emma","Idol","HomeComer","Illusionist","DragonKnight","Samurai","Elementaler","Poet","Sacrifice","Oracle","GachaAddicted","Fate","Synesthete","Reindeer","Streamer","Tarzan","Hitokotonushinokami","RemoteWorker","Gambler","Sleepwalker","Disguised","Saint","SpaceWerewolfCrew","SpaceWerewolfObserver","SpaceWerewolfGuard"] Werewolf:["Werewolf","Madman","BigWolf","Fanatic","Spy","WolfDiviner","Spy2","Sorcerer","LoneWolf","MinionSelector","WolfCub","WhisperingMad","WolfBoy","GreedyWolf","FascinatingWolf","SolitudeWolf","ToughWolf","ThreateningWolf","ObstructiveMad","PsychoKiller","CautiousWolf","Bomber","Ushinotokimairi","MadDog","Hypnotist","CraftyWolf","Pumpkin","MadScientist","MadHunter","MadCouple","EyesWolf","TongueWolf","BlackCat","LurkingMad","DecoyWolf","Satori","AbsoluteWolf","QueenOfNight","CurseWolf","IntuitionWolf","Faker","SealWolf","CynthiaWolf","NetherWolf","DarkWolf","SpaceWerewolfImposter"] Fox:["Fox","TinyFox","Immoral","Blasphemy","XianFox","NightRabbit","Trickster"] Devil:["Devil"] Friend:["Cupid","Lover","BadLady","Patissiere","SnowLover","LunaticLover"] Vampire:["Vampire","Dracula","VampireClan"] Cult:["CultLeader"] Raven:["Raven","Ascetic"] Hooligan:["Hooligan", "HooliganAttacker"] Lorelei:["Lorelei"] Others:["Bat","Stalker","Doppleganger","Copier","Tanner","Thief","Hoodlum","QuantumPlayer","Shishimai","HooliganGuard","Amanojaku","DarkClown","DualPersonality","Oni"], Neet:["Neet"] # カテゴリ分け(一部闇鍋でつかうぞ!) exports.categories= Human: teams.Human.filter((x)-> not (x in ["GotChocolate", "Phantom", "OccultMania", "Cursed", "BloodyMary","Listener","SpaceWerewolfCrew","SpaceWerewolfObserver","SpaceWerewolfGuard"])) Werewolf:["Werewolf","BigWolf","WolfDiviner","LoneWolf","WolfCub","GreedyWolf","FascinatingWolf","SolitudeWolf","ToughWolf","ThreateningWolf","CautiousWolf","CraftyWolf","EyesWolf","TongueWolf","DecoyWolf","AbsoluteWolf","CurseWolf","IntuitionWolf","SealWolf","CynthiaWolf","NetherWolf","DarkWolf"] Madman:["Madman","Fanatic","Spy","Spy2","Sorcerer","WhisperingMad","WolfBoy","ObstructiveMad","PsychoKiller","Bomber","Ushinotokimairi","MadDog","Hypnotist","Pumpkin","MadScientist","MadHunter","MadCouple","BlackCat","LurkingMad","Satori","QueenOfNight","Faker"] Fox:["Fox","TinyFox","XianFox","NightRabbit","Trickster"] Immoral:["Immoral","Blasphemy"] # sort by teams (恋人陣営、単独陣営、その他、変化系その他、変化系村人陣営) Others:["Cupid","Lover","BadLady","Patissiere","SnowLover","LunaticLover","Devil","CultLeader","Vampire","Dracula","VampireClan","Raven","Ascetic","Hooligan","Lorelei","Bat","Tanner","Hoodlum","Shishimai","Amanojaku","DarkClown","Oni"] Switching:["Stalker","Copier","Doppleganger","DualPersonality","OccultMania","Cursed","BloodyMary","Phantom","Thief"] # Special category for "no category" None:[ "Neet", "SpaceWerewolfCrew","SpaceWerewolfImposter","SpaceWerewolfObserver","SpaceWerewolfGuard","SpaceWerewolfSabotage" ] # 配列版のカテゴリリスト exports.categoryList = Object.keys(exports.categories) .map (key)-> { id: key roles: exports.categories[key] } # ガチャデータ(課金者用) exports.gachaData = 1: ["Human", "Couple", "Noble", "Slave", "Liar", "Lycan", "Oldman", "TinyGhost", "Twin", "Sleepwalker", "Disguised"] 2: ["Diviner", "Psychic", "Guard", "Magician", "ToughGuy", "ApprenticeSeer", "Diseased", "Dog", "SeersMama", "DrawGirl", "Cosplayer","Reindeer", "Tarzan", "RemoteWorker" ] 3: ["Fugitive", "Cursed", "Spellcaster", "Prince", "PI", "OccultMania", "RedHood", "WanderingGuard", "Phantom", "Pyrotechnist", "Forensic", "Ninja", "Emma", "HomeComer", "Samurai", "Sacrifice", "Oracle", "Poet", "GachaAddicted","Hitokotonushinokami","Gambler","Saint"] 4: ["Poisoner", "Merchant", "MadWolf", "Light", "Cat", "Witch", "Dictator", "Miko", "HolyMarked", "TroubleMaker", "FrankensteinsMonster", "SantaClaus", "Baker", "SpiritPossessed", "Hunter", "Idol", "Elementaler","Fate", "Synesthete", "Streamer"] 5: ["QueenSpectator", "Priest", "Trapper", "Counselor", "BloodyMary", "King", "Illusionist", "DragonKnight"] 6: ["Neet", "Helper", "Watching"] # 役職ルールたち 役職人数一覧を返す(Humanは向こうで補完) normal1=(number)-> ret={} #狼 ret.Werewolf=1 if number>=8 ret.Werewolf++ if number>=13 ret.Werewolf++ if number>=20 ret.Werewolf++ if number>=25 ret.Werewolf++ if number>=30 ret.Werewolf++ ret.Diviner=1 #占い if number>=22 ret.Diviner++ if number>=8 ret.Psychic=1 #霊能 if number>=6 ret.Madman=1 #狂人 ret.Guard=1 #狩人 if 18 <= number <= 19 || number >= 23 ret.Madman++ if number>=20 ret.Guard++ if number>=13 ret.Couple=2 #共有 if number>=18 ret.Couple++ if number>=11 ret.Fox=1 #狐 if number>=19 ret.Fox++ ret normal2=(number)-> ret={} # 人狼 ret.Werewolf=1 if number>=8 ret.Werewolf++ if number>=16 ret.Werewolf++ if number>=20 ret.Werewolf++ if number>=25 ret.Werewolf++ if number>=29 ret.Werewolf++ ret.Diviner=1 #占い師 if number>=8 ret.Psychic=1 #霊能者 if number>=10 ret.Madman=1 #狂人 if number>=28 ret.Madman++ if number>=11 ret.Guard=1 #狩人 if number>=13 ret.Couple=2 #共有者 if number>=28 ret.Couple++ if number>=15 ret.Fox=1 #狐 ret exports.normal1 = normal1 exports.jobrules=[ { name:"普通配役" rule:[ { name:"普通1" minNumber:4 rule:normal1 } { name:"普通2" minNumber:4 rule:normal2 } { name:"普通3" minNumber:4 rule:(number)-> ret=normal1 number ret.Fox ?= 0 ret.Fox++ if number<10 && ret.Werewolf>1 ret.Werewolf-- ret } ] } { name:"特殊役職配役" rule:[ { name:"恋人" rule:(number)-> ret=normal1 number if ret.Fox>0 #NaNかも ret.Fox-- ret.Cupid ?= 0 ret.Cupid++ ret } { name:"背徳者" rule:(number)-> ret=normal1 number if ret.Fox>0 ret.Immoral?=0 ret.Immoral+=1 ret } { name:"埋毒者あり" rule:(number)-> ret=normal1 number ret.Poisoner=1 ret.Werewolf++ ret } { name:"猫又あり" rule:(number)-> ret=normal1 number ret.Cat=1 ret.Werewolf++ ret } { name:"囁き狂人" rule:(number)-> ret=normal1 number if ret.Madman>0 ret.WhisperingMad=1 ret.Madman-- ret } ] } { name:"桃栗配役" rule:[ { name:"こうもり" rule:(number)-> ret=normal1 number ret.Bat=1 if number>=10 ret.Bat++ if number>=16 ret.Bat++ ret } { name:"貴族奴隷" rule:(number)-> ret=normal1 number ret.Noble=1 ret.Slave=1 if ret.Couple>=2 # 共有者ポジション ret.Couple=0 if number>=14 ret.Slave++ if number>=20 ret.Slave++ if number>=23 ret.Noble++ ret } { name:"魔術師" rule:(number)-> ret=normal1 number ret.Magician=1 ret } { name:"スパイ" rule:(number)-> ret=normal1 number ret.Spy=1 if number<10 && ret.Madman>0 ret.Madman-- ret } { name:"人狼占い" rule:(number)-> ret=normal1 number ret.Werewolf-- ret.WolfDiviner=1 if number>=7 ret.Fox++ ret } { name:"商人" rule:(number)-> ret=normal1 number ret.Merchant=1 ret } ] } { name:"テーマ配役" rule:[ { name:"変化村" minNumber:6 rule:(number)-> ret={} ret.Werewolf=1 ret.Diviner=1 ret.Guard=1 ret.Madman=1 ret.Copier=1 if number>=8 ret.OccultMania=1 if number>=9 ret.Werewolf++ if number>=10 ret.Psychic=1 if number>=11 ret.Doppleganger=1 if number>=13 ret.Counselor=1 ret.FascinatingWolf=1 if number>=15 ret.ApprenticeSeer=1 if number>=16 ret.Cursed=1 if number>=17 ret.Cupid=1 if number>=18 ret.Sorcerer=1 if number>=19 ret.ThreateningWolf=1 if number>=20 ret.Copier++ if number>=21 ret.Fanatic=1 if number>=22 ret.Werewolf-- ret.WolfDiviner=1 ret.Copier++ if number>=24 ret.Diviner++ if number>=26 ret.BigWolf=1 if number>=28 ret.Fox=1 ret.Immoral=1 ret } { name:"黒い村" minNumber:6 rule:(number)-> ret={} # 狼憑き ret.Lycan=1 if number>=10 ret.Lycan++ if number>=14 ret.Lycan++ if number==20 ret.Lycan-- if number>=22 ret.Lycan++ if number>=16 ret.Cursed=1 if number>=28 ret.Cursed++ ret.Diviner=1 if number>=20 ret.Diviner++ if number>=12 ret.ApprenticeSeer=1 if number>=16 ret.SeersMama=1 if number>=9 ret.Psychic=1 if number>=18 ret.Psychic++ ret.Guard=1 if number>=14 ret.Couple=2 if number>=24 ret.Couple++ if number>=13 ret.Fugitive=1 if number>=26 ret.Merchant=1 if number>=27 ret.Dog=1 ret.Werewolf=1 if number>=13 ret.Werewolf++ if number>=9 ret.WolfDiviner=1 if number>=23 ret.WolfDiviner++ if number>=19 ret.SolitudeWolf=1 ret.Madman=1 if number>=7 ret.Madman-- ret.WolfBoy=1 if number>=17 ret.WolfBoy++ if number>=29 ret.WolfBoy++ if number>=20 ret.Stalker=1 if number>=30 ret.Stalker++ if number>=25 ret.Copier=1 ret } { name:"女王村" minNumber:10 suggestedOption: scapegoat:"no" rule:(number)-> ret={} ret.Diviner=1 if number>=25 ret.Diviner++ if number>=11 ret.ApprenticeSeer=1 ret.Psychic=1 ret.Guard=1 ret.Trapper=1 ret.Priest=1 if number>=12 ret.Merchant=1 if number>=18 ret.Merchant++ ret.QueenSpectator=1 if number>=14 ret.Prince=1 if number>=21 ret.Prince++ if number>=15 ret.Dictator=1 if number>=17 ret.Dictator++ if number>=26 ret.Couple=2 ret.Werewolf=1 ret.Werewolf?=0 ret.Werewolf++ ret.WolfDiviner=1 if number>=19 ret.WolfDiviner++ if number>=13 ret.WolfCub=1 if number>=16 ret.ToughWolf=1 ret.WhisperingMad=1 if number>=23 ret.Sorcerer=1 if number>=28 ret.Tanner=1 ret } ] } { name:"その他" rule:[ { name:"狂った世界" rule:(number)-> ret={} count=3 ret.Werewolf=1 ret.Diviner=1 ret.Guard=1 # 人狼 if number>=9 ret.Werewolf++ count++ if number>=14 ret.Werewolf++ count++ if number>=19 ret.Werewolf++ count++ if number>=24 ret.Werewolf++ count++ # 占い師 if number>=12 ret.Diviner++ count++ if number>=20 ret.Diviner++ count++ # 妖術師 if number>=8 ret.Sorcerer=1 count++ if number>=23 ret.Sorcerer++ count++ # 霊能者 if number>=16 ret.Psychic=1 count++ # 狂信者 if number>=17 ret.Fanatic=1 count++ # 独裁者 if number>=7 ret.Dictator=1 count++ if number>=9 ret.Dictator++ count++ if number>=14 ret.Dictator++ count++ # 埋毒者 if number>=22 ret.Poisoner=1 count++ # 魔女 if number>=18 ret.Witch=1 count++ ret.Madman=number-count #残り全部狂人 ret } { name:"六つ巴人狼" rule:(number)-> ret={} ret.Diviner=1 ret.Psychic=1 ret.Guard=1 ret.Madman=1 ret.Werewolf=2 ret.Fox=1 ret.Devil=1 ret.Cupid=1 ret.Copier=1 if number>=14 ret.Priest=1 ret.Doppleganger=1 if number>=16 ret.Stalker=1 ret.Bat=1 if number>=18 ret.Werewolf++ if number>=20 ret.ApprenticeSeer=1 ret.Fox++ if number>=23 ret.Vampire=1 if number>=25 ret.Werewolf++ if number>=27 ret.WolfDiviner=1 ret.Werewolf-- ret.Immoral=1 if number>=29 ret.Noble=1 ret.Slave=1 if number>=30 ret.Werewolf-- ret.LoneWolf=1 if number>=35 ret.Werewolf++ if number>=36 ret.Fox++ if number>=38 ret.Vampire++ ret }, { name: "spaceWerewolf" rule:(number)-> ret = {} ret.SpaceWerewolfImposter = 1 if number >= 7 ret.SpaceWerewolfImposter++ if number >= 13 ret.SpaceWerewolfImposter++ if number >= 20 ret.SpaceWerewolfImposter++ ret.SpaceWerewolfObserver = 1 if number >= 6 ret.SpaceWerewolfGuard = 1 ret.SpaceWerewolfSabotage = 1 count = ret.SpaceWerewolfImposter + ret.SpaceWerewolfObserver + ret.SpaceWerewolfGuard + ret.SpaceWerewolfSabotage ret.SpaceWerewolfCrew = number - count ret } ] } ] # ルールオブジェクトを得る getruleobj=(name)-> # オブジェクトから探す if name=="特殊ルール.量子人狼" # 特殊だ! return { name:"量子人狼" rule:null suggestedNight:{ max:60 } } names= name.split "." obj=Shared.game.jobrules for branch in names #.区切りでオブジェクト名 ruleobj=obj.filter((x)->x.name==branch)[0] unless ruleobj # そんな配役は見つからない return if "function"==typeof ruleobj.rule # 目当てのものを見つけた return ruleobj obj=ruleobj.rule null # ルール関数を得る exports.getrulefunc=(name)-> if name=="内部利用.量子人狼" # 量子人狼のときは return (number)-> ret={} #狼 ret.Werewolf=1 if number>=8 ret.Werewolf++ if number>=13 ret.Werewolf++ if number>=20 ret.Werewolf++ if number>=25 ret.Werewolf++ if number>=30 ret.Werewolf++ ret.Diviner=1 #占い ret # ほかはオブジェクトから探す ruleobj = getruleobj name return ruleobj?.rule # 職の情報 exports.getjobobj = (job)-> for name,team of Shared.game.jobinfo if team[job]? return team[job] return null # make team color map from jobinfo exports.makeTeamColors = -> result = {} for team, obj of Shared.game.jobinfo result[team] = obj.color result # jobinfo.name can now be removed exports.jobinfo= Human: color:"#00CC00" Human: color:"#dddddd" Diviner: color:"#00b3ff" Psychic: color:"#bb00ff" Guard: color:"#969ad4" Couple: color:"#ffffab" Poisoner: color:"#853c24" Noble: color:"#ffff00" Slave: color:"#1417d9" Magician: color:"#f03eba" Fugitive: color:"#e8b279" Merchant: color:"#e06781" QueenSpectator: color:"#faeebe" Liar: color:"#a3e4e6" Light: color:"#2d158c" MadWolf: color:"#847430" ToughGuy: color:"#ff5900" Cursed: color:"#bda3bf" ApprenticeSeer: color:"#bfecff" Diseased: color:"#b35b98" Spellcaster: color:"#4b4f7d" Lycan: color:"#7d5f5f" Priest: color:"#fff94a" Prince: color:"#e5ff00" PI: color:"#573670" Cat: color:"#9200C7" Witch: color:"#9200C7" Oldman: color:"#ede4b9" OccultMania: color:"#edda8c" Dog: color:"#d4a152" Dictator: color:"#ff0000" SeersMama: color:"#ff9500" Trapper: color:"#b58500" RedHood: color:"#ff2200" Counselor: color:"#ff94d9" Miko: color:"#f5b8ca" HolyMarked: color:"#c4e8ff" WanderingGuard: color:"#16bf0d" TroubleMaker: color:"#64b82c" FrankensteinsMonster: color:"#4d3a03" BloodyMary: color:"#ee0000" King: color:"#fcdd28" SantaClaus: color:"#ff0000" Phantom: color:"#f3f3f3" DrawGirl: color:"#ffc796" Pyrotechnist: color:"#ff6a19" Baker: color:"#fad587" SpiritPossessed: color:"#a196d1" Forensic: color:"#d4e9fc" Cosplayer: color:"#69652b" TinyGhost: color:"#999999" Ninja: color:"#1f136d" Twin: color:"#dbfcff" Hunter: color:"#d11f1f" Emma: color:"#dd2211" Idol: color:"#ffcc55" HomeComer: color:"#bbeeee" Illusionist: color:"#ddaaee" DragonKnight: color:"#ef8b26" Samurai: color:"#000d80" Elementaler: color:"#46f17f" Poet: color:"#f1a0a2" Sacrifice: color:"#573f2b" Oracle: color:"#77c8ed" GachaAddicted: color:"#edb232" Fate: color:"#062a66" Synesthete: color:"#ffb6c1" Reindeer: color:"#917663" Streamer: color:"#c4302b" Listener: color:"#eefeff" Tarzan: color:"#b3925a" Hitokotonushinokami: color:"#e6e397" RemoteWorker: color:"#0e71eb" Gambler: color:"#edbd80" Sleepwalker: color:"#46ba32" Disguised: color:"#f1a502" Saint: color:"#ffdb1a" SpaceWerewolfCrew: color:"#4de837" SpaceWerewolfObserver: color:"#e651b4" SpaceWerewolfGuard: color:"#ef7d0d" Werewolf: color:"#DD0000" Werewolf: color:"#220000" Madman: color:"#ffbb00" BigWolf: color:"#660000" Spy: color:"#ad5d28" WolfDiviner: color:"#5b0080" Spy2: color:"#d3b959" Fanatic: color:"#94782b" Sorcerer: color:"#b91be0" LoneWolf: color:"#222222" MinionSelector: color:"#ffffff" WolfCub: color:"#662233" WhisperingMad: color:"#ccab52" WolfBoy: color:"#5b2266" GreedyWolf: color:"#910052" FascinatingWolf: color:"#f200c2" SolitudeWolf: color:"#a13f3f" ToughWolf: color:"#c47f35" ThreateningWolf: color:"#9e6f00" ObstructiveMad: color:"#d95e38" PsychoKiller: color:"#1ee37d" CautiousWolf: color:"#5c3716" Bomber: color:"#cda764" Ushinotokimairi: color:"#c9563c" MadDog: color:"#c21f1f" Hypnotist: color:"#e01bs9" CraftyWolf: color:"#4a03ad" Pumpkin: color:"#ffb042" MadScientist: color:"#14e051" MadHunter: color:"#511e0f" MadCouple: color:"#f2d5bc" EyesWolf: color:"#000a75" TongueWolf: color:"#912d5b" BlackCat: color:"#38004c" LurkingMad: color:"#937930" DecoyWolf: color:"#cc8f2e" Satori: color:"#f9cad9" AbsoluteWolf: color:"#ff7f50" QueenOfNight: color:"#f7f8f0" CurseWolf: color:"#484366" IntuitionWolf: color:"#fcac07" Faker: color:"#8a7458" SealWolf: color:"#333366" CynthiaWolf: color:"#dc143c" NetherWolf: color:"#2f0000" DarkWolf: color:"#1f0000" SpaceWerewolfImposter: color:"#1c30b1" SpaceWerewolfSabotage: color:"#918977" Fox: color:"#934293" Fox: color:"#934293" TinyFox: color:"#dd81f0" Immoral: color:"#5c2f5c" Blasphemy: color:"#802060" XianFox: color:"#edd5ed" NightRabbit: color:"#202f55" Trickster: color:"#27dcce" Friend: color:"#ffb5e5" Cupid: color:"#ffb5e5" Lover: color:"#ffcfee" BadLady: color:"#cf0085" Patissiere: color:"#ab5f30" SnowLover: color:"#f6ceff" LunaticLover: color:"#b30000" Devil: color:"#735f9e" Devil: color:"#735f9e" Vampire: color:"#8f00bf" Vampire: color:"#8f00bf" Dracula: color:"#2d00b7" VampireClan: color:"#c77ed0" Cult: color: "#b09d87" CultLeader: color:"#b09d87" Raven: color: "#444466" Raven: color: "#444466" Ascetic: color:"#435066" Hooligan: color: "#f39800" Hooligan: color: "#ff5900" Lorelei: color: "#b51b70" Lorelei: color: "#b51b70" Others: color:"#cccccc" Bat: color:"#000066" Stalker: color:"#ad6628" Doppleganger: color:"#bbbbbb" Copier: color:"#ffffff" Tanner: color:"#ede4b9" Thief: color:"#a4a4a4" Hoodlum: color:"#88002d" QuantumPlayer: color:"#eeeeee" Shishimai: color:"#2c8c3e" Amanojaku: color:"#b09ca8" DarkClown: color:"#444434" DualPersonality: color:"#9db699" Oni: color:"#d14545" Neet: color:"#aaaaaa" Neet: color:"#aaaaaa" # TODO temporal new version exports.new_rules=[ # 闇鍋関係 { type: 'group' label: id: 'yaminabe_option' visible: (rule)-> # 闇鍋モードのみ (rule.casting ? rule.jobrule) in ["特殊ルール.闇鍋","特殊ルール.一部闇鍋","特殊ルール.エンドレス闇鍋"] items: [ { type: 'item' value: type: 'select' id: 'yaminabe_safety' defaultValue: 'low' values:[ "supersuper" "super" "high" "middle" "lowlow" "low" "none" "reverse" ] } ] } # 配役表示 { type: 'group' label: id: 'show_roles_option' visible: (rule, isEditor)-> if !isEditor && rule.rules.get('yaminabe_hidejobs') != 'team' # ルール表示時で配役がチームのみの設定でない場合は隠す return false return true if isAllJobsMode(rule) if isEditor && rule.rules.get('yaminabe_hidejobs') != 'team' return false for job in ["Vampire","Devil","CultLeader"] if rule.jobNumbers[job]>0 return true return false items: [ { type: 'item' value: type: 'checkbox' id: 'hide_singleton_teams' defaultChecked: false value: 'on' } ] } # 標準ルール { type: 'group' label: id: 'normal_rules' visible:->true items: [ { type: 'item' value: type: 'checkbox' id: 'decider' defaultChecked: false value: '1' } { type: 'item' value: type:"checkbox" id:"authority" defaultChecked: false value:"1" } { type: 'item' value: type:"checkbox" id:"deathnote" defaultChecked: false value:"1" } { type: 'item' value: type:"checkbox" id:"wolfminion" defaultChecked: false value:"1" } { type: 'item' value: type:"checkbox" id:"drunk" defaultChecked: false value:"1" } { type: 'item' value: type:"separator" } { type: 'item' value: type:"select" id:"scapegoat" defaultValue: 'on' values: [ "on" "off" "no" ] } { type: 'item' value: type:"separator" } { type: 'item' value: type:"time" id: 'day' defaultValue: 330 disabled:(rule)-> rule.rules.get('dynamic_day_time') == 'on' } { type: 'item' value: type:"time" id: 'night' defaultValue: 150 } { type: 'item' value: type:"time" id: 'remain' defaultValue: 120 minValue: 60 } { type: 'item' value: type:"time" id: 'voting' defaultValue: 0 } { type: 'item' value: type:"separator" } { type: 'item' value: type:"checkbox" id:"dynamic_day_time" defaultChecked: false value:"on" } { type: 'item' value: type:"integer" id:"dynamic_day_time_factor" defaultValue: 30 minValue: 10 step: 5 value:"on" disabled:(rule)-> rule.rules.get('dynamic_day_time') != 'on' getstr:(t, value)-> { value: if !value t('rules:common.none') else value + t('rules:common.seconds') } } { type: 'item' value: type:"separator" } { type: 'item' value: type:"checkbox" id:"will" defaultChecked: true value:"die" } { type: 'item' value: type:"select" id:"heavenview" defaultValue: 'norevive' values:[ "view" "norevive" # ""なのは歴史的経緯 "" ] } { type: 'item' value: type:"checkbox" id:"votemyself" value:"ok" } { type: 'item' value: type:"checkbox" id:"voteresult" value:"hide" } { type: 'item' value: type:"hidden" id:"waitingnight" value: "wait" } { type: 'item' value: type:"select" id:"safety" defaultValue: 'full' values:[ "full" "no" "free" ] getOptionStr: (t, value)-> { label: t("rules:rule.safety.labels.#{value}") description: t("rules:rule.safety.descriptions.#{value}", { safety_excluded_jobs: SAFETY_EXCLUDED_JOBS.map((job)-> t("roles:jobname.#{job}")).join("、") }) } } { type: 'item' value: type:"separator" } { type: 'item' value: type:"checkbox" id:"noticebitten" value:"notice" } { type: 'item' value: type:"checkbox" id:"GMpsychic" value:"on" } { type: 'item' value: type:"integer" id:"silentrule" defaultValue: 0 minValue: 0 getstr:(t, value)-> { value: if !value t('rules:common.none') else value + t('rules:common.seconds') } } { type: 'item' value: type:"select" id:"runoff" defaultValue: 'no' values:[ "no" "revote" "yes" ] } { type: 'item' value: type:"select" id:"drawvote" defaultValue: 'revote' values:[ "revote" "random" "none" "all" ] } { type: 'item' value: type: "separator" } { # 名前がyaminabeなのは歴史的経緯 type: 'item' value: type:"select" id:"yaminabe_hidejobs" defaultValue: '' values:[ # ""なのは歴史的経緯 "" "team" "2" ] } { type: 'item' value: type:"checkbox" id:"losemode" value:"on" } { type: 'item' value: type:"checkbox" id:"rolerequest" value:"on" } { type: 'item' value: type:"checkbox" id:"chemical" value:"on" } ] } # 人狼系 { type: 'group' label: id: "werewolf" visible: (rule)-> return true if isAllJobsMode rule for job in exports.categories.Werewolf if rule.jobNumbers[job]>0 return true return false items:[ { type: 'item' value: type:"checkbox" id:"wolfsound" defaultChecked: true value:"aloud" } { type: 'item' value: type:"checkbox" id:"wolfattack" value:"ok" } ] } # 占い系 { type: 'group' label: id: 'diviner' visible:(rule)-> return true if isAllJobsMode rule for job in ["Diviner","ApprenticeSeer","WolfDiviner","TinyFox"] if rule.jobNumbers[job]>0 return true return false items:[ { type: 'item' value: type:"select" id:"divineresult" defaultValue: 'sunrise' values:[ "immediate" "sunrise" ] } { type: 'item' value: type:"select" id:"firstnightdivine" defaultValue: 'manual' values:[ "auto" "manual" ] } ] } # 霊能 { type: 'group' label: id: 'psychic' visible:(rule)-> return true if isAllJobsMode rule return rule.jobNumbers.Psychic>0 items:[ { type: 'item' value: type:"select" id:"psychicresult" defaultValue: 'sunrise' values:[ "sunset" "sunrise" ] } ] } # 共有者 { type: 'group' label: id: 'couple' visible:(rule)-> return true if isAllJobsMode rule return rule.jobNumbers.Couple>0 || rule.jobNumbers.MadCouple>0 items:[ { type: 'item' value: type:"checkbox" id:"couplesound" value:"aloud" } ] } # 護衛役職 { type: 'group' label: id: 'guard' visible:(rule)-> return true if isAllJobsMode rule for job in ["Guard","Trapper","WanderingGuard","Cosplayer"] if rule.jobNumbers[job]>0 return true return false items:[ { type: 'item' value: type:"checkbox" id:"guardmyself" value:"ok" } { type: 'item' value: type:"checkbox" id:"gjmessage" value:"on" } { type: 'item' value: type:"select" id:"consecutiveguard" defaultValue: 'yes' values:[ "yes" "no" ] } ] } # 妖狐 { type: 'group' label: id: "fox" visible:(rule)-> return true if isAllJobsMode rule return rule.jobNumbers.Fox>0 items:[ { type: 'item' value: type:"checkbox" id:"deadfox" value:"obvious" } ] } # ハンター { type: 'group' label: id: 'hunter' visible:(rule)-> return true if isAllJobsMode rule return rule.jobNumbers.Hunter > 0 || rule.jobNumbers.MadHunter > 0 items:[ { type: 'item' value: type: "select" id:"hunter_lastattack" defaultValue: 'yes' values:[ "yes" "no" ] } ] } # 埋毒者、猫又 { type: 'group' label: id: 'poison' visible:(rule)-> return true if isAllJobsMode rule return rule.jobNumbers.Poisoner>0 || rule.jobNumbers.Cat>0 items:[ { type: 'item' value: type: "select" id: "poisonwolf" defaultValue: 'selector' values:[ "selector" "" ] } ] } # 恋人 { type: 'group' label: id: 'lover' visible:(rule)-> return true if isAllJobsMode rule for job in ["Cupid","Lover","BadLady","Patissiere"] if rule.jobNumbers[job]>0 return true return false items:[ { type: 'item' value: type:"select" id:"friendsjudge" defaultValue: 'alive' values:[ "alive" "ruin" ] } { type: 'item' value: type:"checkbox" id:"friendssplit" defaultChecked: true value:"split" } ] } # 量子人狼 { type: 'group' label: id: 'quantum' visible:(rule)->rule.casting=="特殊ルール.量子人狼" items:[ { type: 'item' value: type:"select" id:"quantumwerewolf_table" defaultValue: 'open' values:[ "open" "anonymous" ] } { type: 'item' value: type:"checkbox" id:"quantumwerewolf_dead" value:"no" } { type: 'item' value: type:"checkbox" id:"quantumwerewolf_diviner" value:"on" } { type: 'item' value: type:"checkbox" id:"quantumwerewolf_firstattack" value:"on" } ] } ] # 情報表示(makejobinfoで付加するやつ) exports.jobinfos=[ { name:"supporting" } { name:"wolves" } { name:"vampires" } { name:"peers" } { name:"madpeers" } { name:"foxes" } { name:"nobles" } { name:"queens" } { name:"spy2s" } { name:"friends" } { name:"stalking" } { name:"cultmembers" } { name:"dogOwner" } { name:"quantumwerewolf_number" } { name:"watchingfireworks", } { name:"twins" } { name:"myfans" } { name:"fanof" } { name:"ravens" } { name:"hooligans" } { name:"loreleis" } { name:"bonds" } ] # 全ての役職が現れる可能性があるモードかどうか isAllJobsMode=(rule)-> if (rule.casting ? rule.jobrule) in ["特殊ルール.闇鍋","特殊ルール.一部闇鍋","特殊ルール.エンドレス闇鍋", "特殊ルール.easyYaminabe"] return true if rule.rules.get("yaminabe_hidejobs") != "" # 役職が隠されている場合もtrue return true return false
139898
Shared= game:exports # 身代わりセーフティありのときの除外役職一覧 exports.SAFETY_EXCLUDED_JOBS = SAFETY_EXCLUDED_JOBS = ["QueenSpectator","Spy2","Poisoner","Cat","Cupid","BloodyMary","Noble", "Lover", "Twin","Hunter","MadHunter","Idol","SnowLover","Raven","LunaticLover","HooliganGuard","HooliganAttacker","SantaClaus","Oni"] # ------ 役職一覧 # 基本役職 exports.jobs=["Human","Werewolf","Diviner","Psychic","Madman","Guard","Couple","Fox", # ミラーズホロウの人狼 "Hunter","Cupid", # 特殊役職? "Poisoner","BigWolf","TinyFox","Cat", # るる鯖で見つけた役職 "Fanatic","Immoral" # 特殊役職2 "Devil","Stalker","WhisperingMad","Dog", # 桃栗基本特殊役職 "Bat","Noble","Slave","Magician","Spy","WolfDiviner", # 桃栗期間限定役職 "Fugitive","Merchant","QueenSpectator","MadWolf","Liar","Spy2","Copier", # 究極の人狼の役職 "ToughGuy","Cursed","ApprenticeSeer","Diseased","Spellcaster","Lycan","Priest","Prince","PI","Sorcerer", "Doppleganger","CultLeader","Vampire","LoneWolf","Witch","Oldman","Tanner","OccultMania","WolfCub","Thief", "Hoodlum","TroubleMaker","FrankensteinsMonster", "BloodyMary", # うそつき人狼の役職 "Dictator","SeersMama","Trapper","WolfBoy","King", # Twitter人狼の役職 "Counselor","Miko","GreedyWolf","FascinatingWolf","SolitudeWolf","ToughWolf","ThreateningWolf", # dat人狼 "Sleepwalker", # 人狼物語 "CurseWolf", # 人狼議事 "Trickster", # 人狼物語(瓜科国) "MadCouple", # 人狼物語(薔薇の下国) "NightRabbit", # 人狼物語(深海国) "Fate","QueenOfNight","CynthiaWolf","Saint", # 人狼物語(三日月国) "Tarzan", # 天国系の役職 "Lover", # 人狼天国 "ObstructiveMad", # 人狼天国 "WanderingGuard", # 錠前天国 "BadLady", # 蒼汁天国、人狼天国 # ねじれ天国 "Bomber","Blasphemy","Ushinotokimairi","DualPersonality","GachaAddicted", "Gambler","Faker","NetherWolf", # 人狼式 "Emma","EyesWolf","TongueWolf","Oracle","Hitokotonushinokami", "SealWolf","Oni", # えけけ鯖 "MadHunter","Ascetic" # 人狼パーティー "TinyGhost","Ninja","Twin","Dracula","VampireClan" # その他 "RedHood","Baker","XianFox","LunaticLover" # 人狼放浪記 "MadDog","CraftyWolf","Pumpkin","MadScientist","SpiritPossessed","Forensic" # 牢獄の悪夢 "PsychoKiller","Cosplayer", # 人狼NET "Satori", # わんないと人狼 "Phantom", # 月夜の人狼 "DrawGirl","CautiousWolf","SnowLover","Raven","Samurai", # 月夜の人狼(闇夜の人狼) "DarkClown", # 人狼HOUSE "Hypnotist", # 人狼ジャッジメント "BlackCat","Amanojaku", # 人狼 SUPER DX(幻冬舎) "Illusionist", # 魔法都市の人狼 "Elementaler", # 24時間耐久人狼 "IntuitionWolf", # 絶対的人狼 "AbsoluteWolf", #人狼村池袋本店 "DarkWolf", # オリジナル "SantaClaus","Reindeer", "Pyrotechnist","Patissiere","Shishimai","Idol","LurkingMad", "DecoyWolf","Hooligan","HomeComer","DragonKnight","Poet","Sacrifice", "Synesthete","Streamer","RemoteWorker","Disguised" ] # 隠されていて自分で入れることができない役職 exports.hiddenJobs = [ "Light", "Neet", "MinionSelector", "QuantumPlayer", "HolyMarked", "Lorelei", # 宇宙人狼 "SpaceWerewolfCrew", "SpaceWerewolfImposter", "SpaceWerewolfObserver","SpaceWerewolfGuard","SpaceWerewolfSabotage" ] # 人外 exports.nonhumans=["Werewolf","Fox","BigWolf","TinyFox","WolfDiviner","MadWolf","Devil","Vampire","LoneWolf","WolfCub","GreedyWolf","FascinatingWolf","SolitudeWolf","ToughWolf","ThreateningWolf","CautiousWolf","CraftyWolf","EyesWolf","TongueWolf","XianFox","DecoyWolf","Dracula","AbsoluteWolf","NightRabbit","CurseWolf","IntuitionWolf","Lorelei","SealWolf","CynthiaWolf","Trickster","NetherWolf","DarkWolf","SpaceWerewolfImposter"] # 黒が出る人 exports.blacks=["Werewolf","WolfDiviner","MadWolf","Lycan","LoneWolf","WolfCub","Dog","GreedyWolf","FascinatingWolf","SolitudeWolf","ToughWolf","ThreateningWolf","MadDog","CraftyWolf","Cosplayer","EyesWolf","TongueWolf","DecoyWolf","AbsoluteWolf","CurseWolf","IntuitionWolf","SealWolf","CynthiaWolf","NetherWolf","DarkWolf","SpaceWerewolfImposter"] # チームたち exports.teams=teams= Human:["Human","Diviner","Psychic","Guard","Couple","Poisoner","ToughGuy","Noble","Slave","Magician","Fugitive","Merchant","QueenSpectator","MadWolf","Liar","Light","Cursed","ApprenticeSeer","Diseased","Spellcaster","Lycan","Priest","Prince","PI","Cat","Witch","Oldman","OccultMania","Dog","Dictator","SeersMama","Trapper","RedHood","Counselor","Miko","HolyMarked","WanderingGuard","TroubleMaker","FrankensteinsMonster","BloodyMary","King","SantaClaus","Phantom","DrawGirl","Pyrotechnist","Baker","SpiritPossessed","GotChocolate","Forensic","Cosplayer","TinyGhost","Ninja","Twin","Hunter","Emma","Idol","HomeComer","Illusionist","DragonKnight","Samurai","Elementaler","Poet","Sacrifice","Oracle","GachaAddicted","Fate","Synesthete","Reindeer","Streamer","Tarzan","Hitokotonushinokami","RemoteWorker","Gambler","Sleepwalker","Disguised","Saint","SpaceWerewolfCrew","SpaceWerewolfObserver","SpaceWerewolfGuard"] Werewolf:["Werewolf","Madman","BigWolf","Fanatic","Spy","WolfDiviner","Spy2","Sorcerer","LoneWolf","MinionSelector","WolfCub","WhisperingMad","WolfBoy","GreedyWolf","FascinatingWolf","SolitudeWolf","ToughWolf","ThreateningWolf","ObstructiveMad","PsychoKiller","CautiousWolf","Bomber","Ushinotokimairi","MadDog","Hypnotist","CraftyWolf","Pumpkin","MadScientist","MadHunter","MadCouple","EyesWolf","TongueWolf","BlackCat","LurkingMad","DecoyWolf","Satori","AbsoluteWolf","QueenOfNight","CurseWolf","IntuitionWolf","Faker","SealWolf","CynthiaWolf","NetherWolf","DarkWolf","SpaceWerewolfImposter"] Fox:["Fox","TinyFox","Immoral","Blasphemy","XianFox","NightRabbit","Trickster"] Devil:["Devil"] Friend:["Cupid","Lover","BadLady","Patissiere","SnowLover","LunaticLover"] Vampire:["Vampire","Dracula","VampireClan"] Cult:["CultLeader"] Raven:["Raven","Ascetic"] Hooligan:["Hooligan", "HooliganAttacker"] Lorelei:["Lorelei"] Others:["Bat","Stalker","Doppleganger","Copier","Tanner","Thief","Hoodlum","QuantumPlayer","Shishimai","HooliganGuard","Amanojaku","DarkClown","DualPersonality","Oni"], Neet:["Neet"] # カテゴリ分け(一部闇鍋でつかうぞ!) exports.categories= Human: teams.Human.filter((x)-> not (x in ["GotChocolate", "Phantom", "OccultMania", "Cursed", "BloodyMary","Listener","SpaceWerewolfCrew","SpaceWerewolfObserver","SpaceWerewolfGuard"])) Werewolf:["Werewolf","BigWolf","WolfDiviner","LoneWolf","WolfCub","GreedyWolf","FascinatingWolf","SolitudeWolf","ToughWolf","ThreateningWolf","CautiousWolf","CraftyWolf","EyesWolf","TongueWolf","DecoyWolf","AbsoluteWolf","CurseWolf","IntuitionWolf","SealWolf","CynthiaWolf","NetherWolf","DarkWolf"] Madman:["Madman","Fanatic","Spy","Spy2","Sorcerer","WhisperingMad","WolfBoy","ObstructiveMad","PsychoKiller","Bomber","Ushinotokimairi","MadDog","Hypnotist","Pumpkin","MadScientist","MadHunter","MadCouple","BlackCat","LurkingMad","Satori","QueenOfNight","Faker"] Fox:["Fox","TinyFox","XianFox","NightRabbit","Trickster"] Immoral:["Immoral","Blasphemy"] # sort by teams (恋人陣営、単独陣営、その他、変化系その他、変化系村人陣営) Others:["Cupid","Lover","BadLady","Patissiere","SnowLover","LunaticLover","Devil","CultLeader","Vampire","Dracula","VampireClan","Raven","Ascetic","Hooligan","Lorelei","Bat","Tanner","Hoodlum","Shishimai","Amanojaku","DarkClown","Oni"] Switching:["Stalker","Copier","Doppleganger","DualPersonality","OccultMania","Cursed","BloodyMary","Phantom","Thief"] # Special category for "no category" None:[ "Neet", "SpaceWerewolfCrew","SpaceWerewolfImposter","SpaceWerewolfObserver","SpaceWerewolfGuard","SpaceWerewolfSabotage" ] # 配列版のカテゴリリスト exports.categoryList = Object.keys(exports.categories) .map (key)-> { id: key roles: exports.categories[key] } # ガチャデータ(課金者用) exports.gachaData = 1: ["Human", "Couple", "Noble", "Slave", "Liar", "Lycan", "Oldman", "TinyGhost", "Twin", "Sleepwalker", "Disguised"] 2: ["Diviner", "Psychic", "Guard", "Magician", "ToughGuy", "ApprenticeSeer", "Diseased", "Dog", "SeersMama", "DrawGirl", "Cosplayer","Reindeer", "Tarzan", "RemoteWorker" ] 3: ["Fugitive", "Cursed", "Spellcaster", "Prince", "PI", "OccultMania", "RedHood", "WanderingGuard", "Phantom", "Pyrotechnist", "Forensic", "Ninja", "Emma", "HomeComer", "Samurai", "Sacrifice", "Oracle", "Poet", "GachaAddicted","Hitokotonushinokami","Gambler","Saint"] 4: ["Poisoner", "Merchant", "MadWolf", "Light", "Cat", "Witch", "Dictator", "Miko", "HolyMarked", "TroubleMaker", "FrankensteinsMonster", "SantaClaus", "Baker", "SpiritPossessed", "Hunter", "Idol", "Elementaler","Fate", "Synesthete", "Streamer"] 5: ["QueenSpectator", "Priest", "Trapper", "Counselor", "BloodyMary", "King", "Illusionist", "DragonKnight"] 6: ["Neet", "Helper", "Watching"] # 役職ルールたち 役職人数一覧を返す(Humanは向こうで補完) normal1=(number)-> ret={} #狼 ret.Werewolf=1 if number>=8 ret.Werewolf++ if number>=13 ret.Werewolf++ if number>=20 ret.Werewolf++ if number>=25 ret.Werewolf++ if number>=30 ret.Werewolf++ ret.Diviner=1 #占い if number>=22 ret.Diviner++ if number>=8 ret.Psychic=1 #霊能 if number>=6 ret.Madman=1 #狂人 ret.Guard=1 #狩人 if 18 <= number <= 19 || number >= 23 ret.Madman++ if number>=20 ret.Guard++ if number>=13 ret.Couple=2 #共有 if number>=18 ret.Couple++ if number>=11 ret.Fox=1 #狐 if number>=19 ret.Fox++ ret normal2=(number)-> ret={} # 人狼 ret.Werewolf=1 if number>=8 ret.Werewolf++ if number>=16 ret.Werewolf++ if number>=20 ret.Werewolf++ if number>=25 ret.Werewolf++ if number>=29 ret.Werewolf++ ret.Diviner=1 #占い師 if number>=8 ret.Psychic=1 #霊能者 if number>=10 ret.Madman=1 #狂人 if number>=28 ret.Madman++ if number>=11 ret.Guard=1 #狩人 if number>=13 ret.Couple=2 #共有者 if number>=28 ret.Couple++ if number>=15 ret.Fox=1 #狐 ret exports.normal1 = normal1 exports.jobrules=[ { name:"普通配役" rule:[ { name:"普通1" minNumber:4 rule:normal1 } { name:"普通2" minNumber:4 rule:normal2 } { name:"普通3" minNumber:4 rule:(number)-> ret=normal1 number ret.Fox ?= 0 ret.Fox++ if number<10 && ret.Werewolf>1 ret.Werewolf-- ret } ] } { name:"特殊役職配役" rule:[ { name:"恋人" rule:(number)-> ret=normal1 number if ret.Fox>0 #NaNかも ret.Fox-- ret.Cupid ?= 0 ret.Cupid++ ret } { name:"背徳者" rule:(number)-> ret=normal1 number if ret.Fox>0 ret.Immoral?=0 ret.Immoral+=1 ret } { name:"埋毒者あり" rule:(number)-> ret=normal1 number ret.Poisoner=1 ret.Werewolf++ ret } { name:"猫又あり" rule:(number)-> ret=normal1 number ret.Cat=1 ret.Werewolf++ ret } { name:"囁き狂人" rule:(number)-> ret=normal1 number if ret.Madman>0 ret.WhisperingMad=1 ret.Madman-- ret } ] } { name:"桃栗配役" rule:[ { name:"こうもり" rule:(number)-> ret=normal1 number ret.Bat=1 if number>=10 ret.Bat++ if number>=16 ret.Bat++ ret } { name:"貴族奴隷" rule:(number)-> ret=normal1 number ret.Noble=1 ret.Slave=1 if ret.Couple>=2 # 共有者ポジション ret.Couple=0 if number>=14 ret.Slave++ if number>=20 ret.Slave++ if number>=23 ret.Noble++ ret } { name:"魔術師" rule:(number)-> ret=normal1 number ret.Magician=1 ret } { name:"スパイ" rule:(number)-> ret=normal1 number ret.Spy=1 if number<10 && ret.Madman>0 ret.Madman-- ret } { name:"人狼占い" rule:(number)-> ret=normal1 number ret.Werewolf-- ret.WolfDiviner=1 if number>=7 ret.Fox++ ret } { name:"商人" rule:(number)-> ret=normal1 number ret.Merchant=1 ret } ] } { name:"テーマ配役" rule:[ { name:"変化村" minNumber:6 rule:(number)-> ret={} ret.Werewolf=1 ret.Diviner=1 ret.Guard=1 ret.Madman=1 ret.Copier=1 if number>=8 ret.OccultMania=1 if number>=9 ret.Werewolf++ if number>=10 ret.Psychic=1 if number>=11 ret.Doppleganger=1 if number>=13 ret.Counselor=1 ret.FascinatingWolf=1 if number>=15 ret.ApprenticeSeer=1 if number>=16 ret.Cursed=1 if number>=17 ret.Cupid=1 if number>=18 ret.Sorcerer=1 if number>=19 ret.ThreateningWolf=1 if number>=20 ret.Copier++ if number>=21 ret.Fanatic=1 if number>=22 ret.Werewolf-- ret.WolfDiviner=1 ret.Copier++ if number>=24 ret.Diviner++ if number>=26 ret.BigWolf=1 if number>=28 ret.Fox=1 ret.Immoral=1 ret } { name:"<NAME>" minNumber:6 rule:(number)-> ret={} # 狼憑き ret.Lycan=1 if number>=10 ret.Lycan++ if number>=14 ret.Lycan++ if number==20 ret.Lycan-- if number>=22 ret.Lycan++ if number>=16 ret.Cursed=1 if number>=28 ret.Cursed++ ret.Diviner=1 if number>=20 ret.Diviner++ if number>=12 ret.ApprenticeSeer=1 if number>=16 ret.SeersMama=1 if number>=9 ret.Psychic=1 if number>=18 ret.Psychic++ ret.Guard=1 if number>=14 ret.Couple=2 if number>=24 ret.Couple++ if number>=13 ret.Fugitive=1 if number>=26 ret.Merchant=1 if number>=27 ret.Dog=1 ret.Werewolf=1 if number>=13 ret.Werewolf++ if number>=9 ret.WolfDiviner=1 if number>=23 ret.WolfDiviner++ if number>=19 ret.SolitudeWolf=1 ret.Madman=1 if number>=7 ret.Madman-- ret.WolfBoy=1 if number>=17 ret.WolfBoy++ if number>=29 ret.WolfBoy++ if number>=20 ret.Stalker=1 if number>=30 ret.Stalker++ if number>=25 ret.Copier=1 ret } { name:"<NAME>" minNumber:10 suggestedOption: scapegoat:"no" rule:(number)-> ret={} ret.Diviner=1 if number>=25 ret.Diviner++ if number>=11 ret.ApprenticeSeer=1 ret.Psychic=1 ret.Guard=1 ret.Trapper=1 ret.Priest=1 if number>=12 ret.Merchant=1 if number>=18 ret.Merchant++ ret.QueenSpectator=1 if number>=14 ret.Prince=1 if number>=21 ret.Prince++ if number>=15 ret.Dictator=1 if number>=17 ret.Dictator++ if number>=26 ret.Couple=2 ret.Werewolf=1 ret.Werewolf?=0 ret.Werewolf++ ret.WolfDiviner=1 if number>=19 ret.WolfDiviner++ if number>=13 ret.WolfCub=1 if number>=16 ret.ToughWolf=1 ret.WhisperingMad=1 if number>=23 ret.Sorcerer=1 if number>=28 ret.Tanner=1 ret } ] } { name:"その他" rule:[ { name:"狂った世界" rule:(number)-> ret={} count=3 ret.Werewolf=1 ret.Diviner=1 ret.Guard=1 # 人狼 if number>=9 ret.Werewolf++ count++ if number>=14 ret.Werewolf++ count++ if number>=19 ret.Werewolf++ count++ if number>=24 ret.Werewolf++ count++ # 占い師 if number>=12 ret.Diviner++ count++ if number>=20 ret.Diviner++ count++ # 妖術師 if number>=8 ret.Sorcerer=1 count++ if number>=23 ret.Sorcerer++ count++ # 霊能者 if number>=16 ret.Psychic=1 count++ # 狂信者 if number>=17 ret.Fanatic=1 count++ # 独裁者 if number>=7 ret.Dictator=1 count++ if number>=9 ret.Dictator++ count++ if number>=14 ret.Dictator++ count++ # 埋毒者 if number>=22 ret.Poisoner=1 count++ # 魔女 if number>=18 ret.Witch=1 count++ ret.Madman=number-count #残り全部狂人 ret } { name:"六つ巴人狼" rule:(number)-> ret={} ret.Diviner=1 ret.Psychic=1 ret.Guard=1 ret.Madman=1 ret.Werewolf=2 ret.Fox=1 ret.Devil=1 ret.Cupid=1 ret.Copier=1 if number>=14 ret.Priest=1 ret.Doppleganger=1 if number>=16 ret.Stalker=1 ret.Bat=1 if number>=18 ret.Werewolf++ if number>=20 ret.ApprenticeSeer=1 ret.Fox++ if number>=23 ret.Vampire=1 if number>=25 ret.Werewolf++ if number>=27 ret.WolfDiviner=1 ret.Werewolf-- ret.Immoral=1 if number>=29 ret.Noble=1 ret.Slave=1 if number>=30 ret.Werewolf-- ret.LoneWolf=1 if number>=35 ret.Werewolf++ if number>=36 ret.Fox++ if number>=38 ret.Vampire++ ret }, { name: "spaceWerewolf" rule:(number)-> ret = {} ret.SpaceWerewolfImposter = 1 if number >= 7 ret.SpaceWerewolfImposter++ if number >= 13 ret.SpaceWerewolfImposter++ if number >= 20 ret.SpaceWerewolfImposter++ ret.SpaceWerewolfObserver = 1 if number >= 6 ret.SpaceWerewolfGuard = 1 ret.SpaceWerewolfSabotage = 1 count = ret.SpaceWerewolfImposter + ret.SpaceWerewolfObserver + ret.SpaceWerewolfGuard + ret.SpaceWerewolfSabotage ret.SpaceWerewolfCrew = number - count ret } ] } ] # ルールオブジェクトを得る getruleobj=(name)-> # オブジェクトから探す if name=="特殊ルール.量子人狼" # 特殊だ! return { name:"量子人狼" rule:null suggestedNight:{ max:60 } } names= name.split "." obj=Shared.game.jobrules for branch in names #.区切りでオブジェクト名 ruleobj=obj.filter((x)->x.name==branch)[0] unless ruleobj # そんな配役は見つからない return if "function"==typeof ruleobj.rule # 目当てのものを見つけた return ruleobj obj=ruleobj.rule null # ルール関数を得る exports.getrulefunc=(name)-> if name=="内部利用.量子人狼" # 量子人狼のときは return (number)-> ret={} #狼 ret.Werewolf=1 if number>=8 ret.Werewolf++ if number>=13 ret.Werewolf++ if number>=20 ret.Werewolf++ if number>=25 ret.Werewolf++ if number>=30 ret.Werewolf++ ret.Diviner=1 #占い ret # ほかはオブジェクトから探す ruleobj = getruleobj name return ruleobj?.rule # 職の情報 exports.getjobobj = (job)-> for name,team of Shared.game.jobinfo if team[job]? return team[job] return null # make team color map from jobinfo exports.makeTeamColors = -> result = {} for team, obj of Shared.game.jobinfo result[team] = obj.color result # jobinfo.name can now be removed exports.jobinfo= Human: color:"#00CC00" Human: color:"#dddddd" Diviner: color:"#00b3ff" Psychic: color:"#bb00ff" Guard: color:"#969ad4" Couple: color:"#ffffab" Poisoner: color:"#853c24" Noble: color:"#ffff00" Slave: color:"#1417d9" Magician: color:"#f03eba" Fugitive: color:"#e8b279" Merchant: color:"#e06781" QueenSpectator: color:"#faeebe" Liar: color:"#a3e4e6" Light: color:"#2d158c" MadWolf: color:"#847430" ToughGuy: color:"#ff5900" Cursed: color:"#bda3bf" ApprenticeSeer: color:"#bfecff" Diseased: color:"#b35b98" Spellcaster: color:"#4b4f7d" Lycan: color:"#7d5f5f" Priest: color:"#fff94a" Prince: color:"#e5ff00" PI: color:"#573670" Cat: color:"#9200C7" Witch: color:"#9200C7" Oldman: color:"#ede4b9" OccultMania: color:"#edda8c" Dog: color:"#d4a152" Dictator: color:"#ff0000" SeersMama: color:"#ff9500" Trapper: color:"#b58500" RedHood: color:"#ff2200" Counselor: color:"#ff94d9" Miko: color:"#f5b8ca" HolyMarked: color:"#c4e8ff" WanderingGuard: color:"#16bf0d" TroubleMaker: color:"#64b82c" FrankensteinsMonster: color:"#4d3a03" BloodyMary: color:"#ee0000" King: color:"#fcdd28" SantaClaus: color:"#ff0000" Phantom: color:"#f3f3f3" DrawGirl: color:"#ffc796" Pyrotechnist: color:"#ff6a19" Baker: color:"#fad587" SpiritPossessed: color:"#a196d1" Forensic: color:"#d4e9fc" Cosplayer: color:"#69652b" TinyGhost: color:"#999999" Ninja: color:"#1f136d" Twin: color:"#dbfcff" Hunter: color:"#d11f1f" Emma: color:"#dd2211" Idol: color:"#ffcc55" HomeComer: color:"#bbeeee" Illusionist: color:"#ddaaee" DragonKnight: color:"#ef8b26" Samurai: color:"#000d80" Elementaler: color:"#46f17f" Poet: color:"#f1a0a2" Sacrifice: color:"#573f2b" Oracle: color:"#77c8ed" GachaAddicted: color:"#edb232" Fate: color:"#062a66" Synesthete: color:"#ffb6c1" Reindeer: color:"#917663" Streamer: color:"#c4302b" Listener: color:"#eefeff" Tarzan: color:"#b3925a" Hitokotonushinokami: color:"#e6e397" RemoteWorker: color:"#0e71eb" Gambler: color:"#edbd80" Sleepwalker: color:"#46ba32" Disguised: color:"#f1a502" Saint: color:"#ffdb1a" SpaceWerewolfCrew: color:"#4de837" SpaceWerewolfObserver: color:"#e651b4" SpaceWerewolfGuard: color:"#ef7d0d" Werewolf: color:"#DD0000" Werewolf: color:"#220000" Madman: color:"#ffbb00" BigWolf: color:"#660000" Spy: color:"#ad5d28" WolfDiviner: color:"#5b0080" Spy2: color:"#d3b959" Fanatic: color:"#94782b" Sorcerer: color:"#b91be0" LoneWolf: color:"#222222" MinionSelector: color:"#ffffff" WolfCub: color:"#662233" WhisperingMad: color:"#ccab52" WolfBoy: color:"#5b2266" GreedyWolf: color:"#910052" FascinatingWolf: color:"#f200c2" SolitudeWolf: color:"#a13f3f" ToughWolf: color:"#c47f35" ThreateningWolf: color:"#9e6f00" ObstructiveMad: color:"#d95e3<PASSWORD>" PsychoKiller: color:"#1ee37d" CautiousWolf: color:"#5c3716" Bomber: color:"#cda764" Ushinotokimairi: color:"#c9563c" MadDog: color:"#c21f1f" Hypnotist: color:"#e01bs9" CraftyWolf: color:"#4a03ad" Pumpkin: color:"#ffb042" MadScientist: color:"#14e051" MadHunter: color:"#511e0f" MadCouple: color:"#f2d5bc" EyesWolf: color:"#000a75" TongueWolf: color:"#912d5b" BlackCat: color:"#38004c" LurkingMad: color:"#937930" DecoyWolf: color:"#cc8f2e" Satori: color:"#f9cad9" AbsoluteWolf: color:"#ff7f50" QueenOfNight: color:"#f7f8f0" CurseWolf: color:"#484366" IntuitionWolf: color:"#fcac07" Faker: color:"#8a7458" SealWolf: color:"#333366" CynthiaWolf: color:"#dc143c" NetherWolf: color:"#2f0000" DarkWolf: color:"#1f0000" SpaceWerewolfImposter: color:"#1c30b1" SpaceWerewolfSabotage: color:"#918977" Fox: color:"#934293" Fox: color:"#934293" TinyFox: color:"#dd81f0" Immoral: color:"#5c2f5c" Blasphemy: color:"#802060" XianFox: color:"#edd5ed" NightRabbit: color:"#202f55" Trickster: color:"#27dcce" Friend: color:"#ffb5e5" Cupid: color:"#ffb5e5" Lover: color:"#ffcfee" BadLady: color:"#cf0085" Patissiere: color:"#ab5f30" SnowLover: color:"#f6ceff" LunaticLover: color:"#b30000" Devil: color:"#735f9e" Devil: color:"#735f9e" Vampire: color:"#8f00bf" Vampire: color:"#8f00bf" Dracula: color:"#2d00b7" VampireClan: color:"#c77ed0" Cult: color: "#b09d87" CultLeader: color:"#b09d87" Raven: color: "#444466" Raven: color: "#444466" Ascetic: color:"#435066" Hooligan: color: "#f39800" Hooligan: color: "#ff5900" Lorelei: color: "#b51b70" Lorelei: color: "#b51b70" Others: color:"#cccccc" Bat: color:"#000066" Stalker: color:"#ad6628" Doppleganger: color:"#bbbbbb" Copier: color:"#ffffff" Tanner: color:"#ede4b9" Thief: color:"#a4a4a4" Hoodlum: color:"#88002d" QuantumPlayer: color:"#eeeeee" Shishimai: color:"#2c8c3e" Amanojaku: color:"#b09ca8" DarkClown: color:"#444434" DualPersonality: color:"#9db699" Oni: color:"#d14545" Neet: color:"#aaaaaa" Neet: color:"#aaaaaa" # TODO temporal new version exports.new_rules=[ # 闇鍋関係 { type: 'group' label: id: 'yaminabe_option' visible: (rule)-> # 闇鍋モードのみ (rule.casting ? rule.jobrule) in ["特殊ルール.闇鍋","特殊ルール.一部闇鍋","特殊ルール.エンドレス闇鍋"] items: [ { type: 'item' value: type: 'select' id: 'yaminabe_safety' defaultValue: 'low' values:[ "supersuper" "super" "high" "middle" "lowlow" "low" "none" "reverse" ] } ] } # 配役表示 { type: 'group' label: id: 'show_roles_option' visible: (rule, isEditor)-> if !isEditor && rule.rules.get('yaminabe_hidejobs') != 'team' # ルール表示時で配役がチームのみの設定でない場合は隠す return false return true if isAllJobsMode(rule) if isEditor && rule.rules.get('yaminabe_hidejobs') != 'team' return false for job in ["Vampire","Devil","CultLeader"] if rule.jobNumbers[job]>0 return true return false items: [ { type: 'item' value: type: 'checkbox' id: 'hide_singleton_teams' defaultChecked: false value: 'on' } ] } # 標準ルール { type: 'group' label: id: 'normal_rules' visible:->true items: [ { type: 'item' value: type: 'checkbox' id: 'decider' defaultChecked: false value: '1' } { type: 'item' value: type:"checkbox" id:"authority" defaultChecked: false value:"1" } { type: 'item' value: type:"checkbox" id:"deathnote" defaultChecked: false value:"1" } { type: 'item' value: type:"checkbox" id:"wolfminion" defaultChecked: false value:"1" } { type: 'item' value: type:"checkbox" id:"drunk" defaultChecked: false value:"1" } { type: 'item' value: type:"separator" } { type: 'item' value: type:"select" id:"scapegoat" defaultValue: 'on' values: [ "on" "off" "no" ] } { type: 'item' value: type:"separator" } { type: 'item' value: type:"time" id: 'day' defaultValue: 330 disabled:(rule)-> rule.rules.get('dynamic_day_time') == 'on' } { type: 'item' value: type:"time" id: 'night' defaultValue: 150 } { type: 'item' value: type:"time" id: 'remain' defaultValue: 120 minValue: 60 } { type: 'item' value: type:"time" id: 'voting' defaultValue: 0 } { type: 'item' value: type:"separator" } { type: 'item' value: type:"checkbox" id:"dynamic_day_time" defaultChecked: false value:"on" } { type: 'item' value: type:"integer" id:"dynamic_day_time_factor" defaultValue: 30 minValue: 10 step: 5 value:"on" disabled:(rule)-> rule.rules.get('dynamic_day_time') != 'on' getstr:(t, value)-> { value: if !value t('rules:common.none') else value + t('rules:common.seconds') } } { type: 'item' value: type:"separator" } { type: 'item' value: type:"checkbox" id:"will" defaultChecked: true value:"die" } { type: 'item' value: type:"select" id:"heavenview" defaultValue: 'norevive' values:[ "view" "norevive" # ""なのは歴史的経緯 "" ] } { type: 'item' value: type:"checkbox" id:"votemyself" value:"ok" } { type: 'item' value: type:"checkbox" id:"voteresult" value:"hide" } { type: 'item' value: type:"hidden" id:"waitingnight" value: "wait" } { type: 'item' value: type:"select" id:"safety" defaultValue: 'full' values:[ "full" "no" "free" ] getOptionStr: (t, value)-> { label: t("rules:rule.safety.labels.#{value}") description: t("rules:rule.safety.descriptions.#{value}", { safety_excluded_jobs: SAFETY_EXCLUDED_JOBS.map((job)-> t("roles:jobname.#{job}")).join("、") }) } } { type: 'item' value: type:"separator" } { type: 'item' value: type:"checkbox" id:"noticebitten" value:"notice" } { type: 'item' value: type:"checkbox" id:"GMpsychic" value:"on" } { type: 'item' value: type:"integer" id:"silentrule" defaultValue: 0 minValue: 0 getstr:(t, value)-> { value: if !value t('rules:common.none') else value + t('rules:common.seconds') } } { type: 'item' value: type:"select" id:"runoff" defaultValue: 'no' values:[ "no" "revote" "yes" ] } { type: 'item' value: type:"select" id:"drawvote" defaultValue: 'revote' values:[ "revote" "random" "none" "all" ] } { type: 'item' value: type: "separator" } { # 名前がyaminabeなのは歴史的経緯 type: 'item' value: type:"select" id:"yaminabe_hidejobs" defaultValue: '' values:[ # ""なのは歴史的経緯 "" "team" "2" ] } { type: 'item' value: type:"checkbox" id:"losemode" value:"on" } { type: 'item' value: type:"checkbox" id:"rolerequest" value:"on" } { type: 'item' value: type:"checkbox" id:"chemical" value:"on" } ] } # 人狼系 { type: 'group' label: id: "werewolf" visible: (rule)-> return true if isAllJobsMode rule for job in exports.categories.Werewolf if rule.jobNumbers[job]>0 return true return false items:[ { type: 'item' value: type:"checkbox" id:"wolfsound" defaultChecked: true value:"aloud" } { type: 'item' value: type:"checkbox" id:"wolfattack" value:"ok" } ] } # 占い系 { type: 'group' label: id: 'diviner' visible:(rule)-> return true if isAllJobsMode rule for job in ["Diviner","ApprenticeSeer","WolfDiviner","TinyFox"] if rule.jobNumbers[job]>0 return true return false items:[ { type: 'item' value: type:"select" id:"divineresult" defaultValue: 'sunrise' values:[ "immediate" "sunrise" ] } { type: 'item' value: type:"select" id:"firstnightdivine" defaultValue: 'manual' values:[ "auto" "manual" ] } ] } # 霊能 { type: 'group' label: id: 'psychic' visible:(rule)-> return true if isAllJobsMode rule return rule.jobNumbers.Psychic>0 items:[ { type: 'item' value: type:"select" id:"psychicresult" defaultValue: 'sunrise' values:[ "sunset" "sunrise" ] } ] } # 共有者 { type: 'group' label: id: 'couple' visible:(rule)-> return true if isAllJobsMode rule return rule.jobNumbers.Couple>0 || rule.jobNumbers.MadCouple>0 items:[ { type: 'item' value: type:"checkbox" id:"couplesound" value:"aloud" } ] } # 護衛役職 { type: 'group' label: id: 'guard' visible:(rule)-> return true if isAllJobsMode rule for job in ["Guard","Trapper","WanderingGuard","Cosplayer"] if rule.jobNumbers[job]>0 return true return false items:[ { type: 'item' value: type:"checkbox" id:"guardmyself" value:"ok" } { type: 'item' value: type:"checkbox" id:"gjmessage" value:"on" } { type: 'item' value: type:"select" id:"consecutiveguard" defaultValue: 'yes' values:[ "yes" "no" ] } ] } # 妖狐 { type: 'group' label: id: "fox" visible:(rule)-> return true if isAllJobsMode rule return rule.jobNumbers.Fox>0 items:[ { type: 'item' value: type:"checkbox" id:"deadfox" value:"obvious" } ] } # ハンター { type: 'group' label: id: 'hunter' visible:(rule)-> return true if isAllJobsMode rule return rule.jobNumbers.Hunter > 0 || rule.jobNumbers.MadHunter > 0 items:[ { type: 'item' value: type: "select" id:"hunter_lastattack" defaultValue: 'yes' values:[ "yes" "no" ] } ] } # 埋毒者、猫又 { type: 'group' label: id: 'poison' visible:(rule)-> return true if isAllJobsMode rule return rule.jobNumbers.Poisoner>0 || rule.jobNumbers.Cat>0 items:[ { type: 'item' value: type: "select" id: "poisonwolf" defaultValue: 'selector' values:[ "selector" "" ] } ] } # 恋人 { type: 'group' label: id: 'lover' visible:(rule)-> return true if isAllJobsMode rule for job in ["Cupid","Lover","BadLady","Patissiere"] if rule.jobNumbers[job]>0 return true return false items:[ { type: 'item' value: type:"select" id:"friendsjudge" defaultValue: 'alive' values:[ "alive" "ruin" ] } { type: 'item' value: type:"checkbox" id:"friendssplit" defaultChecked: true value:"split" } ] } # 量子人狼 { type: 'group' label: id: 'quantum' visible:(rule)->rule.casting=="特殊ルール.量子人狼" items:[ { type: 'item' value: type:"select" id:"quantumwerewolf_table" defaultValue: 'open' values:[ "open" "anonymous" ] } { type: 'item' value: type:"checkbox" id:"quantumwerewolf_dead" value:"no" } { type: 'item' value: type:"checkbox" id:"quantumwerewolf_diviner" value:"on" } { type: 'item' value: type:"checkbox" id:"quantumwerewolf_firstattack" value:"on" } ] } ] # 情報表示(makejobinfoで付加するやつ) exports.jobinfos=[ { name:"supporting" } { name:"wolves" } { name:"vampires" } { name:"peers" } { name:"madpeers" } { name:"<NAME>" } { name:"<NAME>" } { name:"<NAME>" } { name:"<NAME>2s" } { name:"friends" } { name:"stalking" } { name:"cultmembers" } { name:"dogOwner" } { name:"quantumwerewolf_number" } { name:"watchingfireworks", } { name:"twins" } { name:"myfans" } { name:"<NAME>" } { name:"<NAME>" } { name:"<NAME>" } { name:"<NAME>" } { name:"<NAME>" } ] # 全ての役職が現れる可能性があるモードかどうか isAllJobsMode=(rule)-> if (rule.casting ? rule.jobrule) in ["特殊ルール.闇鍋","特殊ルール.一部闇鍋","特殊ルール.エンドレス闇鍋", "特殊ルール.easyYaminabe"] return true if rule.rules.get("yaminabe_hidejobs") != "" # 役職が隠されている場合もtrue return true return false
true
Shared= game:exports # 身代わりセーフティありのときの除外役職一覧 exports.SAFETY_EXCLUDED_JOBS = SAFETY_EXCLUDED_JOBS = ["QueenSpectator","Spy2","Poisoner","Cat","Cupid","BloodyMary","Noble", "Lover", "Twin","Hunter","MadHunter","Idol","SnowLover","Raven","LunaticLover","HooliganGuard","HooliganAttacker","SantaClaus","Oni"] # ------ 役職一覧 # 基本役職 exports.jobs=["Human","Werewolf","Diviner","Psychic","Madman","Guard","Couple","Fox", # ミラーズホロウの人狼 "Hunter","Cupid", # 特殊役職? "Poisoner","BigWolf","TinyFox","Cat", # るる鯖で見つけた役職 "Fanatic","Immoral" # 特殊役職2 "Devil","Stalker","WhisperingMad","Dog", # 桃栗基本特殊役職 "Bat","Noble","Slave","Magician","Spy","WolfDiviner", # 桃栗期間限定役職 "Fugitive","Merchant","QueenSpectator","MadWolf","Liar","Spy2","Copier", # 究極の人狼の役職 "ToughGuy","Cursed","ApprenticeSeer","Diseased","Spellcaster","Lycan","Priest","Prince","PI","Sorcerer", "Doppleganger","CultLeader","Vampire","LoneWolf","Witch","Oldman","Tanner","OccultMania","WolfCub","Thief", "Hoodlum","TroubleMaker","FrankensteinsMonster", "BloodyMary", # うそつき人狼の役職 "Dictator","SeersMama","Trapper","WolfBoy","King", # Twitter人狼の役職 "Counselor","Miko","GreedyWolf","FascinatingWolf","SolitudeWolf","ToughWolf","ThreateningWolf", # dat人狼 "Sleepwalker", # 人狼物語 "CurseWolf", # 人狼議事 "Trickster", # 人狼物語(瓜科国) "MadCouple", # 人狼物語(薔薇の下国) "NightRabbit", # 人狼物語(深海国) "Fate","QueenOfNight","CynthiaWolf","Saint", # 人狼物語(三日月国) "Tarzan", # 天国系の役職 "Lover", # 人狼天国 "ObstructiveMad", # 人狼天国 "WanderingGuard", # 錠前天国 "BadLady", # 蒼汁天国、人狼天国 # ねじれ天国 "Bomber","Blasphemy","Ushinotokimairi","DualPersonality","GachaAddicted", "Gambler","Faker","NetherWolf", # 人狼式 "Emma","EyesWolf","TongueWolf","Oracle","Hitokotonushinokami", "SealWolf","Oni", # えけけ鯖 "MadHunter","Ascetic" # 人狼パーティー "TinyGhost","Ninja","Twin","Dracula","VampireClan" # その他 "RedHood","Baker","XianFox","LunaticLover" # 人狼放浪記 "MadDog","CraftyWolf","Pumpkin","MadScientist","SpiritPossessed","Forensic" # 牢獄の悪夢 "PsychoKiller","Cosplayer", # 人狼NET "Satori", # わんないと人狼 "Phantom", # 月夜の人狼 "DrawGirl","CautiousWolf","SnowLover","Raven","Samurai", # 月夜の人狼(闇夜の人狼) "DarkClown", # 人狼HOUSE "Hypnotist", # 人狼ジャッジメント "BlackCat","Amanojaku", # 人狼 SUPER DX(幻冬舎) "Illusionist", # 魔法都市の人狼 "Elementaler", # 24時間耐久人狼 "IntuitionWolf", # 絶対的人狼 "AbsoluteWolf", #人狼村池袋本店 "DarkWolf", # オリジナル "SantaClaus","Reindeer", "Pyrotechnist","Patissiere","Shishimai","Idol","LurkingMad", "DecoyWolf","Hooligan","HomeComer","DragonKnight","Poet","Sacrifice", "Synesthete","Streamer","RemoteWorker","Disguised" ] # 隠されていて自分で入れることができない役職 exports.hiddenJobs = [ "Light", "Neet", "MinionSelector", "QuantumPlayer", "HolyMarked", "Lorelei", # 宇宙人狼 "SpaceWerewolfCrew", "SpaceWerewolfImposter", "SpaceWerewolfObserver","SpaceWerewolfGuard","SpaceWerewolfSabotage" ] # 人外 exports.nonhumans=["Werewolf","Fox","BigWolf","TinyFox","WolfDiviner","MadWolf","Devil","Vampire","LoneWolf","WolfCub","GreedyWolf","FascinatingWolf","SolitudeWolf","ToughWolf","ThreateningWolf","CautiousWolf","CraftyWolf","EyesWolf","TongueWolf","XianFox","DecoyWolf","Dracula","AbsoluteWolf","NightRabbit","CurseWolf","IntuitionWolf","Lorelei","SealWolf","CynthiaWolf","Trickster","NetherWolf","DarkWolf","SpaceWerewolfImposter"] # 黒が出る人 exports.blacks=["Werewolf","WolfDiviner","MadWolf","Lycan","LoneWolf","WolfCub","Dog","GreedyWolf","FascinatingWolf","SolitudeWolf","ToughWolf","ThreateningWolf","MadDog","CraftyWolf","Cosplayer","EyesWolf","TongueWolf","DecoyWolf","AbsoluteWolf","CurseWolf","IntuitionWolf","SealWolf","CynthiaWolf","NetherWolf","DarkWolf","SpaceWerewolfImposter"] # チームたち exports.teams=teams= Human:["Human","Diviner","Psychic","Guard","Couple","Poisoner","ToughGuy","Noble","Slave","Magician","Fugitive","Merchant","QueenSpectator","MadWolf","Liar","Light","Cursed","ApprenticeSeer","Diseased","Spellcaster","Lycan","Priest","Prince","PI","Cat","Witch","Oldman","OccultMania","Dog","Dictator","SeersMama","Trapper","RedHood","Counselor","Miko","HolyMarked","WanderingGuard","TroubleMaker","FrankensteinsMonster","BloodyMary","King","SantaClaus","Phantom","DrawGirl","Pyrotechnist","Baker","SpiritPossessed","GotChocolate","Forensic","Cosplayer","TinyGhost","Ninja","Twin","Hunter","Emma","Idol","HomeComer","Illusionist","DragonKnight","Samurai","Elementaler","Poet","Sacrifice","Oracle","GachaAddicted","Fate","Synesthete","Reindeer","Streamer","Tarzan","Hitokotonushinokami","RemoteWorker","Gambler","Sleepwalker","Disguised","Saint","SpaceWerewolfCrew","SpaceWerewolfObserver","SpaceWerewolfGuard"] Werewolf:["Werewolf","Madman","BigWolf","Fanatic","Spy","WolfDiviner","Spy2","Sorcerer","LoneWolf","MinionSelector","WolfCub","WhisperingMad","WolfBoy","GreedyWolf","FascinatingWolf","SolitudeWolf","ToughWolf","ThreateningWolf","ObstructiveMad","PsychoKiller","CautiousWolf","Bomber","Ushinotokimairi","MadDog","Hypnotist","CraftyWolf","Pumpkin","MadScientist","MadHunter","MadCouple","EyesWolf","TongueWolf","BlackCat","LurkingMad","DecoyWolf","Satori","AbsoluteWolf","QueenOfNight","CurseWolf","IntuitionWolf","Faker","SealWolf","CynthiaWolf","NetherWolf","DarkWolf","SpaceWerewolfImposter"] Fox:["Fox","TinyFox","Immoral","Blasphemy","XianFox","NightRabbit","Trickster"] Devil:["Devil"] Friend:["Cupid","Lover","BadLady","Patissiere","SnowLover","LunaticLover"] Vampire:["Vampire","Dracula","VampireClan"] Cult:["CultLeader"] Raven:["Raven","Ascetic"] Hooligan:["Hooligan", "HooliganAttacker"] Lorelei:["Lorelei"] Others:["Bat","Stalker","Doppleganger","Copier","Tanner","Thief","Hoodlum","QuantumPlayer","Shishimai","HooliganGuard","Amanojaku","DarkClown","DualPersonality","Oni"], Neet:["Neet"] # カテゴリ分け(一部闇鍋でつかうぞ!) exports.categories= Human: teams.Human.filter((x)-> not (x in ["GotChocolate", "Phantom", "OccultMania", "Cursed", "BloodyMary","Listener","SpaceWerewolfCrew","SpaceWerewolfObserver","SpaceWerewolfGuard"])) Werewolf:["Werewolf","BigWolf","WolfDiviner","LoneWolf","WolfCub","GreedyWolf","FascinatingWolf","SolitudeWolf","ToughWolf","ThreateningWolf","CautiousWolf","CraftyWolf","EyesWolf","TongueWolf","DecoyWolf","AbsoluteWolf","CurseWolf","IntuitionWolf","SealWolf","CynthiaWolf","NetherWolf","DarkWolf"] Madman:["Madman","Fanatic","Spy","Spy2","Sorcerer","WhisperingMad","WolfBoy","ObstructiveMad","PsychoKiller","Bomber","Ushinotokimairi","MadDog","Hypnotist","Pumpkin","MadScientist","MadHunter","MadCouple","BlackCat","LurkingMad","Satori","QueenOfNight","Faker"] Fox:["Fox","TinyFox","XianFox","NightRabbit","Trickster"] Immoral:["Immoral","Blasphemy"] # sort by teams (恋人陣営、単独陣営、その他、変化系その他、変化系村人陣営) Others:["Cupid","Lover","BadLady","Patissiere","SnowLover","LunaticLover","Devil","CultLeader","Vampire","Dracula","VampireClan","Raven","Ascetic","Hooligan","Lorelei","Bat","Tanner","Hoodlum","Shishimai","Amanojaku","DarkClown","Oni"] Switching:["Stalker","Copier","Doppleganger","DualPersonality","OccultMania","Cursed","BloodyMary","Phantom","Thief"] # Special category for "no category" None:[ "Neet", "SpaceWerewolfCrew","SpaceWerewolfImposter","SpaceWerewolfObserver","SpaceWerewolfGuard","SpaceWerewolfSabotage" ] # 配列版のカテゴリリスト exports.categoryList = Object.keys(exports.categories) .map (key)-> { id: key roles: exports.categories[key] } # ガチャデータ(課金者用) exports.gachaData = 1: ["Human", "Couple", "Noble", "Slave", "Liar", "Lycan", "Oldman", "TinyGhost", "Twin", "Sleepwalker", "Disguised"] 2: ["Diviner", "Psychic", "Guard", "Magician", "ToughGuy", "ApprenticeSeer", "Diseased", "Dog", "SeersMama", "DrawGirl", "Cosplayer","Reindeer", "Tarzan", "RemoteWorker" ] 3: ["Fugitive", "Cursed", "Spellcaster", "Prince", "PI", "OccultMania", "RedHood", "WanderingGuard", "Phantom", "Pyrotechnist", "Forensic", "Ninja", "Emma", "HomeComer", "Samurai", "Sacrifice", "Oracle", "Poet", "GachaAddicted","Hitokotonushinokami","Gambler","Saint"] 4: ["Poisoner", "Merchant", "MadWolf", "Light", "Cat", "Witch", "Dictator", "Miko", "HolyMarked", "TroubleMaker", "FrankensteinsMonster", "SantaClaus", "Baker", "SpiritPossessed", "Hunter", "Idol", "Elementaler","Fate", "Synesthete", "Streamer"] 5: ["QueenSpectator", "Priest", "Trapper", "Counselor", "BloodyMary", "King", "Illusionist", "DragonKnight"] 6: ["Neet", "Helper", "Watching"] # 役職ルールたち 役職人数一覧を返す(Humanは向こうで補完) normal1=(number)-> ret={} #狼 ret.Werewolf=1 if number>=8 ret.Werewolf++ if number>=13 ret.Werewolf++ if number>=20 ret.Werewolf++ if number>=25 ret.Werewolf++ if number>=30 ret.Werewolf++ ret.Diviner=1 #占い if number>=22 ret.Diviner++ if number>=8 ret.Psychic=1 #霊能 if number>=6 ret.Madman=1 #狂人 ret.Guard=1 #狩人 if 18 <= number <= 19 || number >= 23 ret.Madman++ if number>=20 ret.Guard++ if number>=13 ret.Couple=2 #共有 if number>=18 ret.Couple++ if number>=11 ret.Fox=1 #狐 if number>=19 ret.Fox++ ret normal2=(number)-> ret={} # 人狼 ret.Werewolf=1 if number>=8 ret.Werewolf++ if number>=16 ret.Werewolf++ if number>=20 ret.Werewolf++ if number>=25 ret.Werewolf++ if number>=29 ret.Werewolf++ ret.Diviner=1 #占い師 if number>=8 ret.Psychic=1 #霊能者 if number>=10 ret.Madman=1 #狂人 if number>=28 ret.Madman++ if number>=11 ret.Guard=1 #狩人 if number>=13 ret.Couple=2 #共有者 if number>=28 ret.Couple++ if number>=15 ret.Fox=1 #狐 ret exports.normal1 = normal1 exports.jobrules=[ { name:"普通配役" rule:[ { name:"普通1" minNumber:4 rule:normal1 } { name:"普通2" minNumber:4 rule:normal2 } { name:"普通3" minNumber:4 rule:(number)-> ret=normal1 number ret.Fox ?= 0 ret.Fox++ if number<10 && ret.Werewolf>1 ret.Werewolf-- ret } ] } { name:"特殊役職配役" rule:[ { name:"恋人" rule:(number)-> ret=normal1 number if ret.Fox>0 #NaNかも ret.Fox-- ret.Cupid ?= 0 ret.Cupid++ ret } { name:"背徳者" rule:(number)-> ret=normal1 number if ret.Fox>0 ret.Immoral?=0 ret.Immoral+=1 ret } { name:"埋毒者あり" rule:(number)-> ret=normal1 number ret.Poisoner=1 ret.Werewolf++ ret } { name:"猫又あり" rule:(number)-> ret=normal1 number ret.Cat=1 ret.Werewolf++ ret } { name:"囁き狂人" rule:(number)-> ret=normal1 number if ret.Madman>0 ret.WhisperingMad=1 ret.Madman-- ret } ] } { name:"桃栗配役" rule:[ { name:"こうもり" rule:(number)-> ret=normal1 number ret.Bat=1 if number>=10 ret.Bat++ if number>=16 ret.Bat++ ret } { name:"貴族奴隷" rule:(number)-> ret=normal1 number ret.Noble=1 ret.Slave=1 if ret.Couple>=2 # 共有者ポジション ret.Couple=0 if number>=14 ret.Slave++ if number>=20 ret.Slave++ if number>=23 ret.Noble++ ret } { name:"魔術師" rule:(number)-> ret=normal1 number ret.Magician=1 ret } { name:"スパイ" rule:(number)-> ret=normal1 number ret.Spy=1 if number<10 && ret.Madman>0 ret.Madman-- ret } { name:"人狼占い" rule:(number)-> ret=normal1 number ret.Werewolf-- ret.WolfDiviner=1 if number>=7 ret.Fox++ ret } { name:"商人" rule:(number)-> ret=normal1 number ret.Merchant=1 ret } ] } { name:"テーマ配役" rule:[ { name:"変化村" minNumber:6 rule:(number)-> ret={} ret.Werewolf=1 ret.Diviner=1 ret.Guard=1 ret.Madman=1 ret.Copier=1 if number>=8 ret.OccultMania=1 if number>=9 ret.Werewolf++ if number>=10 ret.Psychic=1 if number>=11 ret.Doppleganger=1 if number>=13 ret.Counselor=1 ret.FascinatingWolf=1 if number>=15 ret.ApprenticeSeer=1 if number>=16 ret.Cursed=1 if number>=17 ret.Cupid=1 if number>=18 ret.Sorcerer=1 if number>=19 ret.ThreateningWolf=1 if number>=20 ret.Copier++ if number>=21 ret.Fanatic=1 if number>=22 ret.Werewolf-- ret.WolfDiviner=1 ret.Copier++ if number>=24 ret.Diviner++ if number>=26 ret.BigWolf=1 if number>=28 ret.Fox=1 ret.Immoral=1 ret } { name:"PI:NAME:<NAME>END_PI" minNumber:6 rule:(number)-> ret={} # 狼憑き ret.Lycan=1 if number>=10 ret.Lycan++ if number>=14 ret.Lycan++ if number==20 ret.Lycan-- if number>=22 ret.Lycan++ if number>=16 ret.Cursed=1 if number>=28 ret.Cursed++ ret.Diviner=1 if number>=20 ret.Diviner++ if number>=12 ret.ApprenticeSeer=1 if number>=16 ret.SeersMama=1 if number>=9 ret.Psychic=1 if number>=18 ret.Psychic++ ret.Guard=1 if number>=14 ret.Couple=2 if number>=24 ret.Couple++ if number>=13 ret.Fugitive=1 if number>=26 ret.Merchant=1 if number>=27 ret.Dog=1 ret.Werewolf=1 if number>=13 ret.Werewolf++ if number>=9 ret.WolfDiviner=1 if number>=23 ret.WolfDiviner++ if number>=19 ret.SolitudeWolf=1 ret.Madman=1 if number>=7 ret.Madman-- ret.WolfBoy=1 if number>=17 ret.WolfBoy++ if number>=29 ret.WolfBoy++ if number>=20 ret.Stalker=1 if number>=30 ret.Stalker++ if number>=25 ret.Copier=1 ret } { name:"PI:NAME:<NAME>END_PI" minNumber:10 suggestedOption: scapegoat:"no" rule:(number)-> ret={} ret.Diviner=1 if number>=25 ret.Diviner++ if number>=11 ret.ApprenticeSeer=1 ret.Psychic=1 ret.Guard=1 ret.Trapper=1 ret.Priest=1 if number>=12 ret.Merchant=1 if number>=18 ret.Merchant++ ret.QueenSpectator=1 if number>=14 ret.Prince=1 if number>=21 ret.Prince++ if number>=15 ret.Dictator=1 if number>=17 ret.Dictator++ if number>=26 ret.Couple=2 ret.Werewolf=1 ret.Werewolf?=0 ret.Werewolf++ ret.WolfDiviner=1 if number>=19 ret.WolfDiviner++ if number>=13 ret.WolfCub=1 if number>=16 ret.ToughWolf=1 ret.WhisperingMad=1 if number>=23 ret.Sorcerer=1 if number>=28 ret.Tanner=1 ret } ] } { name:"その他" rule:[ { name:"狂った世界" rule:(number)-> ret={} count=3 ret.Werewolf=1 ret.Diviner=1 ret.Guard=1 # 人狼 if number>=9 ret.Werewolf++ count++ if number>=14 ret.Werewolf++ count++ if number>=19 ret.Werewolf++ count++ if number>=24 ret.Werewolf++ count++ # 占い師 if number>=12 ret.Diviner++ count++ if number>=20 ret.Diviner++ count++ # 妖術師 if number>=8 ret.Sorcerer=1 count++ if number>=23 ret.Sorcerer++ count++ # 霊能者 if number>=16 ret.Psychic=1 count++ # 狂信者 if number>=17 ret.Fanatic=1 count++ # 独裁者 if number>=7 ret.Dictator=1 count++ if number>=9 ret.Dictator++ count++ if number>=14 ret.Dictator++ count++ # 埋毒者 if number>=22 ret.Poisoner=1 count++ # 魔女 if number>=18 ret.Witch=1 count++ ret.Madman=number-count #残り全部狂人 ret } { name:"六つ巴人狼" rule:(number)-> ret={} ret.Diviner=1 ret.Psychic=1 ret.Guard=1 ret.Madman=1 ret.Werewolf=2 ret.Fox=1 ret.Devil=1 ret.Cupid=1 ret.Copier=1 if number>=14 ret.Priest=1 ret.Doppleganger=1 if number>=16 ret.Stalker=1 ret.Bat=1 if number>=18 ret.Werewolf++ if number>=20 ret.ApprenticeSeer=1 ret.Fox++ if number>=23 ret.Vampire=1 if number>=25 ret.Werewolf++ if number>=27 ret.WolfDiviner=1 ret.Werewolf-- ret.Immoral=1 if number>=29 ret.Noble=1 ret.Slave=1 if number>=30 ret.Werewolf-- ret.LoneWolf=1 if number>=35 ret.Werewolf++ if number>=36 ret.Fox++ if number>=38 ret.Vampire++ ret }, { name: "spaceWerewolf" rule:(number)-> ret = {} ret.SpaceWerewolfImposter = 1 if number >= 7 ret.SpaceWerewolfImposter++ if number >= 13 ret.SpaceWerewolfImposter++ if number >= 20 ret.SpaceWerewolfImposter++ ret.SpaceWerewolfObserver = 1 if number >= 6 ret.SpaceWerewolfGuard = 1 ret.SpaceWerewolfSabotage = 1 count = ret.SpaceWerewolfImposter + ret.SpaceWerewolfObserver + ret.SpaceWerewolfGuard + ret.SpaceWerewolfSabotage ret.SpaceWerewolfCrew = number - count ret } ] } ] # ルールオブジェクトを得る getruleobj=(name)-> # オブジェクトから探す if name=="特殊ルール.量子人狼" # 特殊だ! return { name:"量子人狼" rule:null suggestedNight:{ max:60 } } names= name.split "." obj=Shared.game.jobrules for branch in names #.区切りでオブジェクト名 ruleobj=obj.filter((x)->x.name==branch)[0] unless ruleobj # そんな配役は見つからない return if "function"==typeof ruleobj.rule # 目当てのものを見つけた return ruleobj obj=ruleobj.rule null # ルール関数を得る exports.getrulefunc=(name)-> if name=="内部利用.量子人狼" # 量子人狼のときは return (number)-> ret={} #狼 ret.Werewolf=1 if number>=8 ret.Werewolf++ if number>=13 ret.Werewolf++ if number>=20 ret.Werewolf++ if number>=25 ret.Werewolf++ if number>=30 ret.Werewolf++ ret.Diviner=1 #占い ret # ほかはオブジェクトから探す ruleobj = getruleobj name return ruleobj?.rule # 職の情報 exports.getjobobj = (job)-> for name,team of Shared.game.jobinfo if team[job]? return team[job] return null # make team color map from jobinfo exports.makeTeamColors = -> result = {} for team, obj of Shared.game.jobinfo result[team] = obj.color result # jobinfo.name can now be removed exports.jobinfo= Human: color:"#00CC00" Human: color:"#dddddd" Diviner: color:"#00b3ff" Psychic: color:"#bb00ff" Guard: color:"#969ad4" Couple: color:"#ffffab" Poisoner: color:"#853c24" Noble: color:"#ffff00" Slave: color:"#1417d9" Magician: color:"#f03eba" Fugitive: color:"#e8b279" Merchant: color:"#e06781" QueenSpectator: color:"#faeebe" Liar: color:"#a3e4e6" Light: color:"#2d158c" MadWolf: color:"#847430" ToughGuy: color:"#ff5900" Cursed: color:"#bda3bf" ApprenticeSeer: color:"#bfecff" Diseased: color:"#b35b98" Spellcaster: color:"#4b4f7d" Lycan: color:"#7d5f5f" Priest: color:"#fff94a" Prince: color:"#e5ff00" PI: color:"#573670" Cat: color:"#9200C7" Witch: color:"#9200C7" Oldman: color:"#ede4b9" OccultMania: color:"#edda8c" Dog: color:"#d4a152" Dictator: color:"#ff0000" SeersMama: color:"#ff9500" Trapper: color:"#b58500" RedHood: color:"#ff2200" Counselor: color:"#ff94d9" Miko: color:"#f5b8ca" HolyMarked: color:"#c4e8ff" WanderingGuard: color:"#16bf0d" TroubleMaker: color:"#64b82c" FrankensteinsMonster: color:"#4d3a03" BloodyMary: color:"#ee0000" King: color:"#fcdd28" SantaClaus: color:"#ff0000" Phantom: color:"#f3f3f3" DrawGirl: color:"#ffc796" Pyrotechnist: color:"#ff6a19" Baker: color:"#fad587" SpiritPossessed: color:"#a196d1" Forensic: color:"#d4e9fc" Cosplayer: color:"#69652b" TinyGhost: color:"#999999" Ninja: color:"#1f136d" Twin: color:"#dbfcff" Hunter: color:"#d11f1f" Emma: color:"#dd2211" Idol: color:"#ffcc55" HomeComer: color:"#bbeeee" Illusionist: color:"#ddaaee" DragonKnight: color:"#ef8b26" Samurai: color:"#000d80" Elementaler: color:"#46f17f" Poet: color:"#f1a0a2" Sacrifice: color:"#573f2b" Oracle: color:"#77c8ed" GachaAddicted: color:"#edb232" Fate: color:"#062a66" Synesthete: color:"#ffb6c1" Reindeer: color:"#917663" Streamer: color:"#c4302b" Listener: color:"#eefeff" Tarzan: color:"#b3925a" Hitokotonushinokami: color:"#e6e397" RemoteWorker: color:"#0e71eb" Gambler: color:"#edbd80" Sleepwalker: color:"#46ba32" Disguised: color:"#f1a502" Saint: color:"#ffdb1a" SpaceWerewolfCrew: color:"#4de837" SpaceWerewolfObserver: color:"#e651b4" SpaceWerewolfGuard: color:"#ef7d0d" Werewolf: color:"#DD0000" Werewolf: color:"#220000" Madman: color:"#ffbb00" BigWolf: color:"#660000" Spy: color:"#ad5d28" WolfDiviner: color:"#5b0080" Spy2: color:"#d3b959" Fanatic: color:"#94782b" Sorcerer: color:"#b91be0" LoneWolf: color:"#222222" MinionSelector: color:"#ffffff" WolfCub: color:"#662233" WhisperingMad: color:"#ccab52" WolfBoy: color:"#5b2266" GreedyWolf: color:"#910052" FascinatingWolf: color:"#f200c2" SolitudeWolf: color:"#a13f3f" ToughWolf: color:"#c47f35" ThreateningWolf: color:"#9e6f00" ObstructiveMad: color:"#d95e3PI:PASSWORD:<PASSWORD>END_PI" PsychoKiller: color:"#1ee37d" CautiousWolf: color:"#5c3716" Bomber: color:"#cda764" Ushinotokimairi: color:"#c9563c" MadDog: color:"#c21f1f" Hypnotist: color:"#e01bs9" CraftyWolf: color:"#4a03ad" Pumpkin: color:"#ffb042" MadScientist: color:"#14e051" MadHunter: color:"#511e0f" MadCouple: color:"#f2d5bc" EyesWolf: color:"#000a75" TongueWolf: color:"#912d5b" BlackCat: color:"#38004c" LurkingMad: color:"#937930" DecoyWolf: color:"#cc8f2e" Satori: color:"#f9cad9" AbsoluteWolf: color:"#ff7f50" QueenOfNight: color:"#f7f8f0" CurseWolf: color:"#484366" IntuitionWolf: color:"#fcac07" Faker: color:"#8a7458" SealWolf: color:"#333366" CynthiaWolf: color:"#dc143c" NetherWolf: color:"#2f0000" DarkWolf: color:"#1f0000" SpaceWerewolfImposter: color:"#1c30b1" SpaceWerewolfSabotage: color:"#918977" Fox: color:"#934293" Fox: color:"#934293" TinyFox: color:"#dd81f0" Immoral: color:"#5c2f5c" Blasphemy: color:"#802060" XianFox: color:"#edd5ed" NightRabbit: color:"#202f55" Trickster: color:"#27dcce" Friend: color:"#ffb5e5" Cupid: color:"#ffb5e5" Lover: color:"#ffcfee" BadLady: color:"#cf0085" Patissiere: color:"#ab5f30" SnowLover: color:"#f6ceff" LunaticLover: color:"#b30000" Devil: color:"#735f9e" Devil: color:"#735f9e" Vampire: color:"#8f00bf" Vampire: color:"#8f00bf" Dracula: color:"#2d00b7" VampireClan: color:"#c77ed0" Cult: color: "#b09d87" CultLeader: color:"#b09d87" Raven: color: "#444466" Raven: color: "#444466" Ascetic: color:"#435066" Hooligan: color: "#f39800" Hooligan: color: "#ff5900" Lorelei: color: "#b51b70" Lorelei: color: "#b51b70" Others: color:"#cccccc" Bat: color:"#000066" Stalker: color:"#ad6628" Doppleganger: color:"#bbbbbb" Copier: color:"#ffffff" Tanner: color:"#ede4b9" Thief: color:"#a4a4a4" Hoodlum: color:"#88002d" QuantumPlayer: color:"#eeeeee" Shishimai: color:"#2c8c3e" Amanojaku: color:"#b09ca8" DarkClown: color:"#444434" DualPersonality: color:"#9db699" Oni: color:"#d14545" Neet: color:"#aaaaaa" Neet: color:"#aaaaaa" # TODO temporal new version exports.new_rules=[ # 闇鍋関係 { type: 'group' label: id: 'yaminabe_option' visible: (rule)-> # 闇鍋モードのみ (rule.casting ? rule.jobrule) in ["特殊ルール.闇鍋","特殊ルール.一部闇鍋","特殊ルール.エンドレス闇鍋"] items: [ { type: 'item' value: type: 'select' id: 'yaminabe_safety' defaultValue: 'low' values:[ "supersuper" "super" "high" "middle" "lowlow" "low" "none" "reverse" ] } ] } # 配役表示 { type: 'group' label: id: 'show_roles_option' visible: (rule, isEditor)-> if !isEditor && rule.rules.get('yaminabe_hidejobs') != 'team' # ルール表示時で配役がチームのみの設定でない場合は隠す return false return true if isAllJobsMode(rule) if isEditor && rule.rules.get('yaminabe_hidejobs') != 'team' return false for job in ["Vampire","Devil","CultLeader"] if rule.jobNumbers[job]>0 return true return false items: [ { type: 'item' value: type: 'checkbox' id: 'hide_singleton_teams' defaultChecked: false value: 'on' } ] } # 標準ルール { type: 'group' label: id: 'normal_rules' visible:->true items: [ { type: 'item' value: type: 'checkbox' id: 'decider' defaultChecked: false value: '1' } { type: 'item' value: type:"checkbox" id:"authority" defaultChecked: false value:"1" } { type: 'item' value: type:"checkbox" id:"deathnote" defaultChecked: false value:"1" } { type: 'item' value: type:"checkbox" id:"wolfminion" defaultChecked: false value:"1" } { type: 'item' value: type:"checkbox" id:"drunk" defaultChecked: false value:"1" } { type: 'item' value: type:"separator" } { type: 'item' value: type:"select" id:"scapegoat" defaultValue: 'on' values: [ "on" "off" "no" ] } { type: 'item' value: type:"separator" } { type: 'item' value: type:"time" id: 'day' defaultValue: 330 disabled:(rule)-> rule.rules.get('dynamic_day_time') == 'on' } { type: 'item' value: type:"time" id: 'night' defaultValue: 150 } { type: 'item' value: type:"time" id: 'remain' defaultValue: 120 minValue: 60 } { type: 'item' value: type:"time" id: 'voting' defaultValue: 0 } { type: 'item' value: type:"separator" } { type: 'item' value: type:"checkbox" id:"dynamic_day_time" defaultChecked: false value:"on" } { type: 'item' value: type:"integer" id:"dynamic_day_time_factor" defaultValue: 30 minValue: 10 step: 5 value:"on" disabled:(rule)-> rule.rules.get('dynamic_day_time') != 'on' getstr:(t, value)-> { value: if !value t('rules:common.none') else value + t('rules:common.seconds') } } { type: 'item' value: type:"separator" } { type: 'item' value: type:"checkbox" id:"will" defaultChecked: true value:"die" } { type: 'item' value: type:"select" id:"heavenview" defaultValue: 'norevive' values:[ "view" "norevive" # ""なのは歴史的経緯 "" ] } { type: 'item' value: type:"checkbox" id:"votemyself" value:"ok" } { type: 'item' value: type:"checkbox" id:"voteresult" value:"hide" } { type: 'item' value: type:"hidden" id:"waitingnight" value: "wait" } { type: 'item' value: type:"select" id:"safety" defaultValue: 'full' values:[ "full" "no" "free" ] getOptionStr: (t, value)-> { label: t("rules:rule.safety.labels.#{value}") description: t("rules:rule.safety.descriptions.#{value}", { safety_excluded_jobs: SAFETY_EXCLUDED_JOBS.map((job)-> t("roles:jobname.#{job}")).join("、") }) } } { type: 'item' value: type:"separator" } { type: 'item' value: type:"checkbox" id:"noticebitten" value:"notice" } { type: 'item' value: type:"checkbox" id:"GMpsychic" value:"on" } { type: 'item' value: type:"integer" id:"silentrule" defaultValue: 0 minValue: 0 getstr:(t, value)-> { value: if !value t('rules:common.none') else value + t('rules:common.seconds') } } { type: 'item' value: type:"select" id:"runoff" defaultValue: 'no' values:[ "no" "revote" "yes" ] } { type: 'item' value: type:"select" id:"drawvote" defaultValue: 'revote' values:[ "revote" "random" "none" "all" ] } { type: 'item' value: type: "separator" } { # 名前がyaminabeなのは歴史的経緯 type: 'item' value: type:"select" id:"yaminabe_hidejobs" defaultValue: '' values:[ # ""なのは歴史的経緯 "" "team" "2" ] } { type: 'item' value: type:"checkbox" id:"losemode" value:"on" } { type: 'item' value: type:"checkbox" id:"rolerequest" value:"on" } { type: 'item' value: type:"checkbox" id:"chemical" value:"on" } ] } # 人狼系 { type: 'group' label: id: "werewolf" visible: (rule)-> return true if isAllJobsMode rule for job in exports.categories.Werewolf if rule.jobNumbers[job]>0 return true return false items:[ { type: 'item' value: type:"checkbox" id:"wolfsound" defaultChecked: true value:"aloud" } { type: 'item' value: type:"checkbox" id:"wolfattack" value:"ok" } ] } # 占い系 { type: 'group' label: id: 'diviner' visible:(rule)-> return true if isAllJobsMode rule for job in ["Diviner","ApprenticeSeer","WolfDiviner","TinyFox"] if rule.jobNumbers[job]>0 return true return false items:[ { type: 'item' value: type:"select" id:"divineresult" defaultValue: 'sunrise' values:[ "immediate" "sunrise" ] } { type: 'item' value: type:"select" id:"firstnightdivine" defaultValue: 'manual' values:[ "auto" "manual" ] } ] } # 霊能 { type: 'group' label: id: 'psychic' visible:(rule)-> return true if isAllJobsMode rule return rule.jobNumbers.Psychic>0 items:[ { type: 'item' value: type:"select" id:"psychicresult" defaultValue: 'sunrise' values:[ "sunset" "sunrise" ] } ] } # 共有者 { type: 'group' label: id: 'couple' visible:(rule)-> return true if isAllJobsMode rule return rule.jobNumbers.Couple>0 || rule.jobNumbers.MadCouple>0 items:[ { type: 'item' value: type:"checkbox" id:"couplesound" value:"aloud" } ] } # 護衛役職 { type: 'group' label: id: 'guard' visible:(rule)-> return true if isAllJobsMode rule for job in ["Guard","Trapper","WanderingGuard","Cosplayer"] if rule.jobNumbers[job]>0 return true return false items:[ { type: 'item' value: type:"checkbox" id:"guardmyself" value:"ok" } { type: 'item' value: type:"checkbox" id:"gjmessage" value:"on" } { type: 'item' value: type:"select" id:"consecutiveguard" defaultValue: 'yes' values:[ "yes" "no" ] } ] } # 妖狐 { type: 'group' label: id: "fox" visible:(rule)-> return true if isAllJobsMode rule return rule.jobNumbers.Fox>0 items:[ { type: 'item' value: type:"checkbox" id:"deadfox" value:"obvious" } ] } # ハンター { type: 'group' label: id: 'hunter' visible:(rule)-> return true if isAllJobsMode rule return rule.jobNumbers.Hunter > 0 || rule.jobNumbers.MadHunter > 0 items:[ { type: 'item' value: type: "select" id:"hunter_lastattack" defaultValue: 'yes' values:[ "yes" "no" ] } ] } # 埋毒者、猫又 { type: 'group' label: id: 'poison' visible:(rule)-> return true if isAllJobsMode rule return rule.jobNumbers.Poisoner>0 || rule.jobNumbers.Cat>0 items:[ { type: 'item' value: type: "select" id: "poisonwolf" defaultValue: 'selector' values:[ "selector" "" ] } ] } # 恋人 { type: 'group' label: id: 'lover' visible:(rule)-> return true if isAllJobsMode rule for job in ["Cupid","Lover","BadLady","Patissiere"] if rule.jobNumbers[job]>0 return true return false items:[ { type: 'item' value: type:"select" id:"friendsjudge" defaultValue: 'alive' values:[ "alive" "ruin" ] } { type: 'item' value: type:"checkbox" id:"friendssplit" defaultChecked: true value:"split" } ] } # 量子人狼 { type: 'group' label: id: 'quantum' visible:(rule)->rule.casting=="特殊ルール.量子人狼" items:[ { type: 'item' value: type:"select" id:"quantumwerewolf_table" defaultValue: 'open' values:[ "open" "anonymous" ] } { type: 'item' value: type:"checkbox" id:"quantumwerewolf_dead" value:"no" } { type: 'item' value: type:"checkbox" id:"quantumwerewolf_diviner" value:"on" } { type: 'item' value: type:"checkbox" id:"quantumwerewolf_firstattack" value:"on" } ] } ] # 情報表示(makejobinfoで付加するやつ) exports.jobinfos=[ { name:"supporting" } { name:"wolves" } { name:"vampires" } { name:"peers" } { name:"madpeers" } { name:"PI:NAME:<NAME>END_PI" } { name:"PI:NAME:<NAME>END_PI" } { name:"PI:NAME:<NAME>END_PI" } { name:"PI:NAME:<NAME>END_PI2s" } { name:"friends" } { name:"stalking" } { name:"cultmembers" } { name:"dogOwner" } { name:"quantumwerewolf_number" } { name:"watchingfireworks", } { name:"twins" } { name:"myfans" } { name:"PI:NAME:<NAME>END_PI" } { name:"PI:NAME:<NAME>END_PI" } { name:"PI:NAME:<NAME>END_PI" } { name:"PI:NAME:<NAME>END_PI" } { name:"PI:NAME:<NAME>END_PI" } ] # 全ての役職が現れる可能性があるモードかどうか isAllJobsMode=(rule)-> if (rule.casting ? rule.jobrule) in ["特殊ルール.闇鍋","特殊ルール.一部闇鍋","特殊ルール.エンドレス闇鍋", "特殊ルール.easyYaminabe"] return true if rule.rules.get("yaminabe_hidejobs") != "" # 役職が隠されている場合もtrue return true return false
[ { "context": "articipant.email || \"#{Math.random().toString(36)}@provider.com\"\n\n <li className=\"list-group-item\">\n ", "end": 245, "score": 0.9364737272262573, "start": 232, "tag": "EMAIL", "value": "@provider.com" } ]
app/assets/javascripts/quiz_app/components/participant_status.js.coffee
sgwiseco/livequiz
56
@ParticipantStatus = React.createClass( render: -> status_classes = classNames('c-info', 'fa', 'fa-circle', this.props.participant.status) gravatar_email = this.props.participant.email || "#{Math.random().toString(36)}@provider.com" <li className="list-group-item"> <div className="col-xs-12 col-sm-4"> <img src={gravatarUrl(gravatar_email, 200)} alt="{this.props.participant.name}" className="img-responsive img-circle" /> </div> <div className="col-xs-12 col-sm-7"> <span className="c-name">{this.props.participant.name}</span><br/> <span className={ status_classes } data-toggle="tooltip" title={this.props.participant.status}></span> <span className="visible-xs"> <br/></span> <span className="fa fa-envelope-o c-info" data-toggle="tooltip" title={this.props.participant.email}></span> <span className="visible-xs"><br/></span> </div> <div className="clearfix"></div> </li> )
402
@ParticipantStatus = React.createClass( render: -> status_classes = classNames('c-info', 'fa', 'fa-circle', this.props.participant.status) gravatar_email = this.props.participant.email || "#{Math.random().toString(36)}<EMAIL>" <li className="list-group-item"> <div className="col-xs-12 col-sm-4"> <img src={gravatarUrl(gravatar_email, 200)} alt="{this.props.participant.name}" className="img-responsive img-circle" /> </div> <div className="col-xs-12 col-sm-7"> <span className="c-name">{this.props.participant.name}</span><br/> <span className={ status_classes } data-toggle="tooltip" title={this.props.participant.status}></span> <span className="visible-xs"> <br/></span> <span className="fa fa-envelope-o c-info" data-toggle="tooltip" title={this.props.participant.email}></span> <span className="visible-xs"><br/></span> </div> <div className="clearfix"></div> </li> )
true
@ParticipantStatus = React.createClass( render: -> status_classes = classNames('c-info', 'fa', 'fa-circle', this.props.participant.status) gravatar_email = this.props.participant.email || "#{Math.random().toString(36)}PI:EMAIL:<EMAIL>END_PI" <li className="list-group-item"> <div className="col-xs-12 col-sm-4"> <img src={gravatarUrl(gravatar_email, 200)} alt="{this.props.participant.name}" className="img-responsive img-circle" /> </div> <div className="col-xs-12 col-sm-7"> <span className="c-name">{this.props.participant.name}</span><br/> <span className={ status_classes } data-toggle="tooltip" title={this.props.participant.status}></span> <span className="visible-xs"> <br/></span> <span className="fa fa-envelope-o c-info" data-toggle="tooltip" title={this.props.participant.email}></span> <span className="visible-xs"><br/></span> </div> <div className="clearfix"></div> </li> )
[ { "context": "ptions.metrics.gameVersionId\n player: playerId\n userTime: userTime\n\n if ", "end": 31169, "score": 0.7003540992736816, "start": 31163, "tag": "NAME", "value": "player" }, { "context": "ptions.metrics.gameVersionId\n pla...
client/src/app/io.coffee
bcfuchs/RedWire
0
# Get alias for the global scope globals = @ # All will be in the "RW" namespace RW = globals.RW ? {} globals.RW = RW RW.io = {} # Define keyboard input io RW.io.keyboard = meta: visual: false factory: (options) -> eventNamespace = _.uniqueId('keyboard') keysDown = {} $(options.elementSelector).on "keydown.#{eventNamespace} keyup.#{eventNamespace} focusout.#{eventNamespace}", (event) -> # Don't handle events on HTML controls if event.target.tagName in ["INPUT", "BUTTON", "LABEL", "TEXTAREA"] then return true event.preventDefault() # jQuery standardizes the keycode into http://api.jquery.com/event.which/ switch event.type when 'keydown' then keysDown[event.which] = true when 'keyup' then delete keysDown[event.which] when 'focusout' then keysDown = {} # Lost focus, so will not receive keyup events else throw new Error('Unexpected event type') return true return { provideData: -> global: keysDown: keysDown establishData: -> # NOOP. Input io does not take data # Remove all event handlers destroy: -> $(options.elementSelector).off(".#{eventNamespace}") } # Define mouse input/output io RW.io.mouse = meta: visual: false factory: (options) -> eventNamespace = _.uniqueId('mouse') mouse = down: false position: [0, 0] cursor: null lastMouse = RW.cloneData(mouse) # This disables selection, which allows the cursor to change in Chrome $(options.elementSelector).on("selectstart.#{eventNamespace}", -> false) $(options.elementSelector).on "mousedown.#{eventNamespace} mouseup.#{eventNamespace} mousemove.#{eventNamespace} mouseleave.#{eventNamespace}", (event) -> switch event.type when 'mousedown' then mouse.down = true when 'mouseup' then mouse.down = false when 'mousemove' # Get position relative to canvas. # Based on http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/ rect = event.target.getBoundingClientRect() target = $(event.target) mouse.position = [ Math.floor((event.clientX - rect.left) * options.size[0] / rect.width) Math.floor((event.clientY - rect.top) * options.size[1] / rect.height) ] return true # Otherwise mouse click may not "complete" in Chrome return { provideData: -> # Calculate justDown and justUp in terms of previous data info = down: mouse.down position: mouse.position cursor: mouse.cursor justDown: mouse.down and not lastMouse.down justUp: not mouse.down and lastMouse.down lastMouse = RW.cloneData(mouse) return { global: info } establishData: (data) -> # TODO: how to handle contention for cursor across circuits? cursor = "" for circuitId, circuitData of data cursor = circuitData.cursor || cursor $(options.elementSelector).css("cursor", cursor) # Remove all event handlers destroy: -> $(options.elementSelector).off(".#{eventNamespace}") } # Define canvas output io RW.io.canvas = meta: visual: true factory: (options) -> CANVAS_CSS = "position: absolute; left: 0px; top: 0px; pointer-events: none;" makeLayerId = (circuitId, layerName) -> "#{circuitId}.#{layerName}" deconstructLayerId = (layerId) -> layerId.split(".") createLayers = -> # Convert layers to ordered createdLayers = {} for { circuitId, name, depth } in options.layers layerId = makeLayerId(circuitId, name) layer = $("<canvas id='canvasLayer-#{layerId}' class='gameCanvas' width='#{options.size[0]}' height='#{options.size[1]}' style='z-index: #{depth}; #{CANVAS_CSS}' />") $(options.elementSelector).append(layer) createdLayers[layerId] = layer return createdLayers # Default orderForShape = (shape) -> return shape.order || 0 shapeSorter = (a, b) -> return orderForShape(a) - orderForShape(b) interpretStyle = (style, ctx) -> if _.isString(style) then return style if not _.isObject(style) then throw new Error('Style must be string or object') switch style.type when 'radialGradient' grad = ctx.createRadialGradient(style.start.position[0], style.start.position[1], style.start.radius, style.end.position[0], style.end.position[1], style.end.radius) for colorStop in style.colorStops grad.addColorStop(colorStop.position, colorStop.color) return grad when 'linearGradient' grad = ctx.createLinearGradient(style.startPosition[0], style.startPosition[1], style.endPosition[0], style.endPosition[1]) for colorStop in style.colorStops grad.addColorStop(colorStop.position, colorStop.color) return grad else throw new Error('Unknown or missing style type') handleTransformations = (shape, ctx) -> # Not sure this is done in the right order if shape.translation? ctx.translate(shape.translation[0], shape.translation[1]) if not shape.position? then shape.position = [0, 0] if shape.rotation? then ctx.rotate(shape.rotation * Math.PI / 180) # Convert to radians if shape.scale? if _.isArray(shape.scale) then ctx.scale(shape.scale[0], shape.scale[1]) else if _.isNumber(shape.scale) then ctx.scale(shape.scale, shape.scale) else throw new Error('Scale argument must be number or array') drawShape = (shape, ctx, assets) -> # TODO: verify that arguments are of the correct type (the canvas API will not complain, just misfunction!) ctx.save() handleTransformations(shape, ctx) if shape.composition then ctx.globalCompositeOperation = shape.composition if shape.alpha then ctx.globalAlpha = shape.alpha switch shape.type when 'rectangle' # Fill in defaults if "fillStyle" not of shape and "strokeStyle" not of shape then shape.fillStyle = "#cf0404" _.defaults shape, size: [100, 100] position: [100, 100] if shape.fillStyle ctx.fillStyle = interpretStyle(shape.fillStyle, ctx) ctx.fillRect(shape.position[0], shape.position[1], shape.size[0], shape.size[1]) if shape.strokeStyle ctx.strokeStyle = interpretStyle(shape.strokeStyle, ctx) if shape.lineWidth then ctx.lineWidth = shape.lineWidth ctx.strokeRect(shape.position[0], shape.position[1], shape.size[0], shape.size[1]) when 'image' if shape.asset not of assets then throw new Error("Cannot find asset '#{shape.asset}' for shape '#{JSON.stringify(shape)}'") # Fill in defaults if "position" not of shape then shape.position = [100, 100] img = assets[shape.asset] size = if shape.size # Clamp size to image size [Math.min(shape.size[0], img.naturalWidth), Math.min(shape.size[1], img.naturalHeight)] else [img.naturalWidth, img.naturalHeight] offset = shape.offset || [0, 0] try # drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh) ctx.drawImage(img, offset[0], offset[1], size[0], size[1], shape.position[0], shape.position[1], size[0], size[1]) catch error throw new Error("Error drawing image shape #{JSON.stringify(shape)}: #{RW.formatStackTrace(error)}") when 'text' # Fill in defaults if "fillStyle" not of shape and "strokeStyle" not of shape then shape.fillStyle = "#cf0404" _.defaults shape, position: [200, 200] text: "RedWire" font: "40px Courier New" align: "left" text = _.isString(shape.text) && shape.text || JSON.stringify(shape.text) ctx.font = shape.font ctx.textAlign = shape.align if shape.fillStyle ctx.fillStyle = interpretStyle(shape.fillStyle, ctx) ctx.fillText(text, shape.position[0], shape.position[1]) if shape.strokeStyle ctx.strokeStyle = interpretStyle(shape.strokeStyle, ctx) ctx.strokeText(text, shape.position[0], shape.position[1]) when 'path' # Fill in defaults if "fillStyle" not of shape and "strokeStyle" not of shape then shape.strokeStyle = "#cf0404" _.defaults shape, points: [ [200, 200], [400, 200], [300, 100] ] lineWidth: 10 ctx.beginPath() ctx.moveTo(shape.points[0][0], shape.points[0][1]) for point in shape.points[1..] then ctx.lineTo(point[0], point[1]) if shape.fillStyle ctx.fillStyle = interpretStyle(shape.fillStyle, ctx) ctx.fill() if shape.strokeStyle ctx.strokeStyle = interpretStyle(shape.strokeStyle, ctx) if shape.lineWidth then ctx.lineWidth = shape.lineWidth if shape.lineCap then ctx.lineCap = shape.lineCap if shape.lineJoin then ctx.lineJoin = shape.lineJoin if shape.miterLimit then ctx.miterLimit = shape.miterLimit ctx.stroke() when 'circle' # Fill in defaults if "fillStyle" not of shape and "strokeStyle" not of shape then shape.fillStyle = "#cf0404" _.defaults shape, position: [300, 300] radius: 50 ctx.beginPath(); ctx.moveTo(shape.position[0], shape.position[1]) ctx.arc(shape.position[0], shape.position[1], shape.radius, 0, 2 * Math.PI) if shape.fillStyle ctx.fillStyle = interpretStyle(shape.fillStyle, ctx) ctx.fill() if shape.strokeStyle ctx.strokeStyle = interpretStyle(shape.strokeStyle, ctx) if shape.lineWidth then ctx.lineWidth = shape.lineWidth ctx.stroke() else throw new Error('Unknown or missing shape type') ctx.restore() layers = createLayers() return { provideData: -> # Return a global size, as well as an empty object of shapes for each layer per circuit data = global: size: options.size for circuitMeta in options.circuitMetas data[circuitMeta.id] = size: options.size for layer in options.layers data[layer.circuitId][layer.name] = [] return data establishData: (data) -> # Clear layers for layerId, canvas of layers canvas[0].getContext('2d').clearRect(0, 0, options.size[0], options.size[1]) # For each layer, sort shapes and then draw them for circuitId, circuitData of data circuitType = _.findWhere(options.circuitMetas, { id: circuitId })?.type if not circuitType? then continue # Recorded data with circuits can trip us up for layerName, shapeArray of circuitData when layerName isnt "size" layerId = makeLayerId(circuitId, layerName) if layerId not of layers then throw new Error("Invalid layer '#{layerName}' in circuit '#{circuitId}'") shapeArray.sort(shapeSorter) ctx = layers[layerId][0].getContext('2d') for shape in shapeArray then drawShape(shape, ctx, options.assets) return null # avoid accumulating results destroy: -> for layerId, canvas of layers then canvas.remove() } # Define html input io RW.io.html = meta: visual: true factory: (options) -> state = RW.mapToObject _.pluck(options.circuitMetas, "id"), -> templates: {} layers: {} views: {} callbacks: {} codeTemplateId = (circuitId, templateName) -> return "#{circuitId}.#{templateName}" decodeTemplateId = (templateId) -> templateId.split(".") rivets.configure handler: (target, event, binding) -> # binding.view.models.data will give the id of the template [circuitId, templateName] = decodeTemplateId(binding.view.models.data) state[circuitId].templates[templateName].values[binding.keypath] = true adapter: subscribe: (templateId, keypath, callback) -> # console.log("subscribe called with ", arguments) [circuitId, templateName] = decodeTemplateId(templateId) state[circuitId].callbacks[templateName][keypath] = callback unsubscribe: (templateId, keypath, callback) -> # console.log("unsubscribe called with ", arguments) [circuitId, templateName] = decodeTemplateId(templateId) delete state[circuitId].callbacks[templateName][keypath] read: (templateId, keypath) -> # console.log("read called with ", arguments) [circuitId, templateName] = decodeTemplateId(templateId) return state[circuitId].templates[templateName].values[keypath] publish: (templateId, keypath, value) -> # console.log("publish called with ", arguments) [circuitId, templateName] = decodeTemplateId(templateId) state[circuitId].templates[templateName].values[keypath] = value return { provideData: -> result = RW.mapToObject _.pluck(options.circuitMetas, "id"), (circuitId) -> state[circuitId].templates result.global = {} return result establishData: (data) -> for circuitId, circuitData of data # circuitData are in the template of { templateName: { asset: "", initialValues: { ... } values: { name: value, ... }, ... }, ...} existingTemplates = _.keys(state[circuitId].templates) newTemplates = _.keys(circuitData) # Remove all templates that are no longer to be shown for templateName in _.difference(existingTemplates, newTemplates) delete state[circuitId].templates[templateName] state[circuitId].layers[templateName].remove() delete state[circuitId].layers[templateName] state[circuitId].views[templateName].unbind() delete state[circuitId].views[templateName] delete state[circuitId].callbacks[templateName] # Add new templates for templateName in _.difference(newTemplates, existingTemplates) # Create template templateHtml = options.assets[circuitData[templateName].asset] # TODO: create all layers before hand? layerOptions = _.findWhere(options.layers, { circuitId: circuitId, name: templateName }) # Find out what the depth is layer = _.findWhere options.layers, "circuitId": circuitId "name": templateName if not layer then throw new Error("Invalid HTML layer '#{templateName}' in circuit '#{circuitId}'") outerWrapper = $("<div id='html-#{circuitId}-#{templateName}' style='position: absolute; z-index: #{layer.depth}; pointer-events: none; width: #{options.size[0]}px; height: #{options.size[1]}px'/>") outerWrapper.append(templateHtml) $(options.elementSelector).append(outerWrapper) state[circuitId].layers[templateName] = outerWrapper # Copy over template data to state state[circuitId].templates[templateName] = circuitData[templateName] # Setup initial values if available state[circuitId].templates[templateName].values = _.defaults({}, circuitData[templateName].values, circuitData[templateName].initialValues) # Bind to the template name state[circuitId].callbacks[templateName] = { } # Will be filled by calls to adapter.subscribe() state[circuitId].views[templateName] = rivets.bind(outerWrapper[0], { data: codeTemplateId(circuitId, templateName) }) # Update existing templates with new circuitData for templateName in _.intersection(newTemplates, existingTemplates) # Start with current values newValues = RW.cloneData(state[circuitId].templates[templateName].values) # Overwrite old state with new if circuitData[templateName].values? newValues = circuitData[templateName].values # Overwrite only selected properties with new values if circuitData[templateName].overwriteValues? _.extend(newValues, circuitData[templateName].overwriteValues) # TODO: call individual binders instead of syncronizing the whole model? # for key in _.union(_.keys(circuitData[templateName].values), _.keys(templates[templateName].values) if not _.isEqual(newValues, state[circuitId].templates[templateName].values) # Overwrite values in the state with those established state[circuitId].templates[templateName].values = newValues state[circuitId].views[templateName].sync() # Reset all event bindings to false for templateName, view of state[circuitId].views for binding in view.bindings if binding.type.indexOf("on-") == 0 state[circuitId].templates[templateName].values[binding.keypath] = false return null # Remove all event handlers destroy: -> for circuitId, circuitState of state for templateName, view of circuitState.views view.unbind() for templateName, layer of circuitState.layers layer.remove() } # Define time io, that provides the current time in ms RW.io.time = meta: visual: false factory: (options) -> provideData: -> global: Date.now() establishData: -> # NOP destroy: -> # NOP # The HTTP io makes AJAX requests RW.io.http = meta: visual: false factory: (options) -> state = RW.mapToObject _.pluck(options.circuitMetas, "id"), -> requests: {} responses: {} io = provideData: -> _.extend({}, state, global: { requests: {}, responses: {} }) establishData: (ioData) -> # Expecting a format like { requests: { id: { method:, url:, data:, cache:, contentType: }, ... }, { responses: { id: { code:, data: }, ... } for circuitId in _.pluck(options.circuitMetas, "id") # Create new requests for requestName in _.difference(_.keys(ioData[circuitId].requests), _.keys(state[circuitId].requests)) do (requestName) -> jqXhr = $.ajax url: ioData[circuitId].requests[requestName].url type: ioData[circuitId].requests[requestName].method ? "GET" cache: ioData[circuitId].requests[requestName].cache ? true data: ioData[circuitId].requests[requestName].data contentType: ioData[circuitId].requests[requestName].contentType jqXhr.done (data, textStatus) -> state[circuitId].responses[requestName] = status: textStatus data: data jqXhr.fail (__, textStatus, errorThrown) -> state[circuitId].responses[requestName] = status: textStatus error: errorThrown delete state[circuitId].requests[requestName] # Remove deleted responses for requestName in _.difference(_.keys(state[circuitId].responses), _.keys(ioData[circuitId].responses)) delete state[circuitId].responses[requestName] return state destroy: () -> # NOP return io # Define chart output io RW.io.charts = meta: visual: true factory: (options) -> capitalizeFirstLetter = (str) -> str[0].toUpperCase() + str.slice(1) makeLayerId = (circuitId, layerName) -> "#{circuitId}.#{layerName}" deconstructLayerId = (layerId) -> layerId.split(".") createLayers = -> # Convert layers to ordered createdLayers = {} for { circuitId, name, depth } in options.layers layerId = makeLayerId(circuitId, name) # Create a canvas element canvasProps = "id='chartLayer-#{layerId}' class='chartCanvas' tabIndex=0" canvasCss = "z-index: #{depth}; position: absolute;" canvas = $("<canvas #{canvasProps} style='#{canvasCss}' />") $(options.elementSelector).append(canvas) createdLayers[layerId] = canvas return createdLayers clearLayer = (circuitId, layerName) -> layer = layers[makeLayerId(circuitId, layerName)] context = layer[0].getContext("2d") context.clearRect(0, 0, layer[0].width, layer[0].height) removeChart = (circuitId, layerName) -> clearLayer(circuitId, layerName) delete charts[circuitId][layerName] # Format { circuitId: { name: { canvas:, data: }}} charts = RW.mapToObject(_.pluck(options.circuitMetas, "id"), -> {}) layers = createLayers() return { provideData: -> data = global: {} for circuitMeta in options.circuitMetas data[circuitMeta.id] = {} for layer in options.layers data[layer.circuitId][layer.name] = null return data establishData: (ioData) -> for circuitId, circuitData of ioData circuitType = _.findWhere(options.circuitMetas, { id: circuitId })?.type if not circuitType? then continue # Recorded data with circuits can trip us up # Remove unused charts for layerName in _.difference(_.keys(charts[circuitId]), _.keys(circuitData)) removeChart(circuitId, chartName) # Create and update charts for layerName, chartData of circuitData layerId = makeLayerId(circuitId, layerName) if layerId not of layers then throw new Error("Invalid layer '#{layerName}' in circuit '#{circuitId}'") # Expecting chartData like { size:, position:, data:, options: }} # If the chart already exists... if layerName of charts[circuitId] #... and has the same data, don't bother redrawing it if _.isEqual(charts[circuitId][layerName].data, chartData) then continue # Otherwise remove it. else removeChart(circuitId, layerName) # If the chart is empty or null, remove it if not chartData then continue # Check it's a valid chart type chartType = chartData.type || "Line" if chartType not of Chart.types throw new Error("Unknown chart type: '#{chartData.type}'") # Define options displayOptions = size: chartData.size ? options.size position: chartData.position ? [0, 0] chartOptions = _.defaults chartData.options ? {}, animation: false showTooltips: false # Retrieve the existing canvas layer, then set its position and size layer = layers[layerId] layer.prop width: displayOptions.size[0] height: displayOptions.size[1] layer.css left: "#{displayOptions.position[0]}px" top: "#{displayOptions.position[1]}px" # Create a new Chart object chart = new Chart(layer[0].getContext("2d")) # Call the correct method on it chart[capitalizeFirstLetter(chartType)](chartData.data, chartOptions) # Store it charts[circuitId][layerName] = chart: chart data: chartData return null destroy: -> for circuitId, circuitCharts of charts for layerName, chart of circuitCharts then clearLayer(circuitId, layerName) $(".chartCanvas").remove() return null } # Define audio output io RW.io.sound = meta: audio: true factory: (options) -> makeChannelId = (circuitId, channelName) -> "#{circuitId}.#{channelName}" deconstructLayerId = (channelId) -> channelId.split(".") stopPlayingSounds = -> for id, source of playingSourceNodes source.stop() # Returns a unique id of the sound clip in playingSourceNodes connectAndPlayBuffer = (buffer, shouldLoop = false) -> # Create source node source = RW.audioContext.createBufferSource() source.buffer = buffer source.connect(RW.lineOut.destination) source.loop = shouldLoop # Keep track of what sounds are playing id = _.uniqueId() source.onended = -> delete playingSourceNodes[id] playingSourceNodes[id] = source # Play immediately source.start(0) return id playingMusic = {} # maps asset names to AudioBufferSourceNode objects playingSourceNodes = {} inPlaySequence = false return { enterPlaySequence: -> inPlaySequence = true # startup playing music for channelId, playingMusicData of playingMusic if playingMusicData.channelData.asset then connectAndPlayBuffer(options.assets[playingMusicData.channelData.asset], true) leavePlaySequence: -> stopPlayingSounds() inPlaySequence = false provideData: -> global: { } establishData: (data) -> # Only play sounds in "play" mode if not inPlaySequence then return for circuitId, circuitData of data circuitType = _.findWhere(options.circuitMetas, { id: circuitId }).type for channelName, channelData of circuitData channelMeta = _.findWhere(options.channels, { circuitId: circuitId, name: channelName }) if not channelMeta? then throw new Error("Cannot find channel '#{channelName}' for circuit '#{circuitId}'") switch channelMeta.type when "clip" for sound in channelData if sound.asset not of options.assets throw new Error("Cannot find asset '#{sound.asset}' for circuit '#{circuitId}'") connectAndPlayBuffer(options.assets[sound.asset]) when "music" # Channel data should be like { asset: "qsdf" } or null channelId = makeChannelId(circuitId, channelName) if _.isEqual(playingMusic[channelId]?.channelData, channelData) then continue # Stop music if its playing # TODO: handle volume changes of same music if playingMusic[channelId] playingSourceNodes[playingMusic[channelId].id].stop() # Play new music if channelData if channelData.asset not of options.assets throw new Error("Cannot find asset '#{channelData.asset}' for circuit '#{circuitId}'") # TODO: handle crossfading sourceId = connectAndPlayBuffer(options.assets[channelData.asset], true) playingMusic[channelId] = channelData: channelData id: sourceId when "fx" for sound in channelData _.defaults sound, fx: ["square",0.0000,0.4000,0.0000,0.3200,0.0000,0.2780,20.0000,496.0000,2400.0000,0.4640,0.0000,0.0000,0.0100,0.0003,0.0000,0.0000,0.0000,0.0235,0.0000,0.0000,0.0000,0.0000,1.0000,0.0000,0.0000,0.0000,0.0000] buffer = WebAudiox.getBufferFromJsfx(RW.audioContext, sound.fx) connectAndPlayBuffer(buffer) else throw new Error("Unknown channel type '#{channelMeta.type}'") return null # avoid accumulating results destroy: -> stopPlayingSounds() } # A RedMetrics IO service to send game analytics data RW.io.metrics = meta: visual: false factory: (options) -> SNAPSHOT_FRAME_DELAY = 60 # Only record a snapshot every 60 frames eventQueue = [] snapshotQueue = [] timerId = null playerId = null playerInfo = {} # Current state of player snapshotFrameCounter = 0 ## Number of frames since last snapshot configIsValid = -> options.metrics and options.metrics.gameVersionId and options.metrics.host sendResults = -> sendEvents() sendSnapshots() sendEvents = -> if eventQueue.length is 0 then return # Send AJAX request jqXhr = $.ajax url: options.metrics.host + "/v1/event/" type: "POST" data: JSON.stringify(eventQueue) processData: false contentType: "application/json" # Clear queue eventQueue = [] sendSnapshots = -> if snapshotQueue.length is 0 then return # Send AJAX request jqXhr = $.ajax url: options.metrics.host + "/v1/snapshot/" type: "POST" data: JSON.stringify(snapshotQueue) processData: false contentType: "application/json" # Clear queue snapshotQueue = [] io = enterPlaySequence: -> if not configIsValid() then return # Reset snapshot counter so that it will be sent on the first frame snapshotFrameCounter = SNAPSHOT_FRAME_DELAY # Create player jqXhr = $.ajax url: options.metrics.host + "/v1/player/" type: "POST" data: "{}" processData: false contentType: "application/json" jqXhr.done (data, textStatus) -> playerId = data.id # Start sending events timerId = window.setInterval(sendResults, 5000) jqXhr.fail (__, textStatus, errorThrown) -> throw new Error("Cannot create player: #{errorThrown}") leavePlaySequence: -> # If metrics session was not created then ignore if not playerId then return # Send last data before stopping sendResults() # Stop sending events window.clearInterval(timerId) playerId = null provideData: -> global: events: [] player: playerInfo establishData: (ioData, additionalData) -> # Only send data in play sequence if not playerId then return # Contains updated playerInfo if necessary newPlayerInfo = null userTime = new Date().toISOString() # Expecting a format like { player: {}, events: [ type: "", section: [], coordinates: [], customData: }, ... ] } for circuitId in _.pluck(options.circuitMetas, "id") # Collate all data into the events queue (disregard individual circuits) # Set game version and player IDs on events for event in ioData[circuitId].events # If event section is array, change it to a dot.separated string if event.section and _.isArray(event.section) event.section = event.section.join(".") eventQueue.push _.extend event, gameVersion: options.metrics.gameVersionId player: playerId userTime: userTime if snapshotFrameCounter++ >= SNAPSHOT_FRAME_DELAY # Reset snapshot counter snapshotFrameCounter = 0 # Send input memory and input IO data as snapshots snapshotQueue.push gameVersion: options.metrics.gameVersionId player: playerId userTime: userTime customData: inputIo: additionalData.inputIoData memory: additionalData.memoryData # Update player info if not _.isEqual(ioData[circuitId].player, playerInfo) newPlayerInfo = ioData[circuitId].player # Update player info if necessary if newPlayerInfo jqXhr = $.ajax url: options.metrics.host + "/v1/player/" + playerId type: "PUT" data: JSON.stringify(newPlayerInfo) processData: false contentType: "application/json" playerInfo = newPlayerInfo return null # avoid accumulating results destroy: -> # NOP return io # The location buffer provides information about the URL and its different parts RW.io.location = meta: visual: false factory: (options) -> provideData: -> global: options.locationInfo establishData: -> # NOP destroy: -> # NOP # Gives access to the Movuino RW.io.movuino = meta: visual: false factory: (options) -> # Connect to the serial port via a web socket (using MisterS) state = connected: false a: [0, 0, 0] g: [0, 0, 0] # TODO: check for errors # TODO: make host and port configurable ws = new WebSocket("ws://localhost:53141/") ws.onopen = -> ws.send("l") state.connected = true ws.onmessage = (event) -> # Expecting data like "l 6360 -8796 -16152 -371 218 -147" tokens = event.data.split(" ") state.a = _.map(tokens[1..3], parseFloat) state.g = _.map(tokens[4..6], parseFloat) return { provideData: -> return global: state establishData: -> # NOP destroy: -> try if not ws or ws.readyState != WebSocket.OPEN then return null ws.send("q") ws.close() catch e console.log("Error closing Mouvino web socket", e) } # Gives access to mobile data # but maybe we can inject this from mobiler... RW.io.mobilemover = meta: visual: false factory: (options) -> # Connect to the serial port via a web socket -- ws_server.js for now # but eventually socket.io keysDown = {} state = connected: false move: false moves = ['u','d','l','r'] # get ip and port of ws from js file written on startup ws_ip = window.mobiler_qr_ip port = window.mobiler_qr_port ws = new WebSocket("ws://"+ ws_ip + ":" + port,'echo-protocol') ws.onopen = -> state.connected = true ws.onmessage = (event) -> # for now, wipe this on each new message keysDown = {} data = JSON.parse(event.data); # hide the qr code # parent.$("#"+data.id).hide(); # TODO add per game filter from vendor js key = data.msg console.log(key); # test by just emitting a keydown event # needs a debounce arrow = $.Event('keydown'); kill = $.Event('keyup'); # jQuery uses which not keyCode arrow.which = key kill.which = key interval = 50 selector = '#gameContent' killme = () -> $(selector).trigger(kill) $(selector).trigger(arrow) setTimeout(killme,interval) keysDown[key] = true return { # what do we need to return here? # keyboard returns a keysDowns object of form {38:true,40:false,...} # we can return that. provideData: -> global: keysDown: keysDown establishData: -> # NOP destroy: -> try if not ws or ws.readyState != WebSocket.OPEN then return null ws.send("q") ws.close() catch e console.log("Error closing Mobilemovr web socket", e) }
157479
# Get alias for the global scope globals = @ # All will be in the "RW" namespace RW = globals.RW ? {} globals.RW = RW RW.io = {} # Define keyboard input io RW.io.keyboard = meta: visual: false factory: (options) -> eventNamespace = _.uniqueId('keyboard') keysDown = {} $(options.elementSelector).on "keydown.#{eventNamespace} keyup.#{eventNamespace} focusout.#{eventNamespace}", (event) -> # Don't handle events on HTML controls if event.target.tagName in ["INPUT", "BUTTON", "LABEL", "TEXTAREA"] then return true event.preventDefault() # jQuery standardizes the keycode into http://api.jquery.com/event.which/ switch event.type when 'keydown' then keysDown[event.which] = true when 'keyup' then delete keysDown[event.which] when 'focusout' then keysDown = {} # Lost focus, so will not receive keyup events else throw new Error('Unexpected event type') return true return { provideData: -> global: keysDown: keysDown establishData: -> # NOOP. Input io does not take data # Remove all event handlers destroy: -> $(options.elementSelector).off(".#{eventNamespace}") } # Define mouse input/output io RW.io.mouse = meta: visual: false factory: (options) -> eventNamespace = _.uniqueId('mouse') mouse = down: false position: [0, 0] cursor: null lastMouse = RW.cloneData(mouse) # This disables selection, which allows the cursor to change in Chrome $(options.elementSelector).on("selectstart.#{eventNamespace}", -> false) $(options.elementSelector).on "mousedown.#{eventNamespace} mouseup.#{eventNamespace} mousemove.#{eventNamespace} mouseleave.#{eventNamespace}", (event) -> switch event.type when 'mousedown' then mouse.down = true when 'mouseup' then mouse.down = false when 'mousemove' # Get position relative to canvas. # Based on http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/ rect = event.target.getBoundingClientRect() target = $(event.target) mouse.position = [ Math.floor((event.clientX - rect.left) * options.size[0] / rect.width) Math.floor((event.clientY - rect.top) * options.size[1] / rect.height) ] return true # Otherwise mouse click may not "complete" in Chrome return { provideData: -> # Calculate justDown and justUp in terms of previous data info = down: mouse.down position: mouse.position cursor: mouse.cursor justDown: mouse.down and not lastMouse.down justUp: not mouse.down and lastMouse.down lastMouse = RW.cloneData(mouse) return { global: info } establishData: (data) -> # TODO: how to handle contention for cursor across circuits? cursor = "" for circuitId, circuitData of data cursor = circuitData.cursor || cursor $(options.elementSelector).css("cursor", cursor) # Remove all event handlers destroy: -> $(options.elementSelector).off(".#{eventNamespace}") } # Define canvas output io RW.io.canvas = meta: visual: true factory: (options) -> CANVAS_CSS = "position: absolute; left: 0px; top: 0px; pointer-events: none;" makeLayerId = (circuitId, layerName) -> "#{circuitId}.#{layerName}" deconstructLayerId = (layerId) -> layerId.split(".") createLayers = -> # Convert layers to ordered createdLayers = {} for { circuitId, name, depth } in options.layers layerId = makeLayerId(circuitId, name) layer = $("<canvas id='canvasLayer-#{layerId}' class='gameCanvas' width='#{options.size[0]}' height='#{options.size[1]}' style='z-index: #{depth}; #{CANVAS_CSS}' />") $(options.elementSelector).append(layer) createdLayers[layerId] = layer return createdLayers # Default orderForShape = (shape) -> return shape.order || 0 shapeSorter = (a, b) -> return orderForShape(a) - orderForShape(b) interpretStyle = (style, ctx) -> if _.isString(style) then return style if not _.isObject(style) then throw new Error('Style must be string or object') switch style.type when 'radialGradient' grad = ctx.createRadialGradient(style.start.position[0], style.start.position[1], style.start.radius, style.end.position[0], style.end.position[1], style.end.radius) for colorStop in style.colorStops grad.addColorStop(colorStop.position, colorStop.color) return grad when 'linearGradient' grad = ctx.createLinearGradient(style.startPosition[0], style.startPosition[1], style.endPosition[0], style.endPosition[1]) for colorStop in style.colorStops grad.addColorStop(colorStop.position, colorStop.color) return grad else throw new Error('Unknown or missing style type') handleTransformations = (shape, ctx) -> # Not sure this is done in the right order if shape.translation? ctx.translate(shape.translation[0], shape.translation[1]) if not shape.position? then shape.position = [0, 0] if shape.rotation? then ctx.rotate(shape.rotation * Math.PI / 180) # Convert to radians if shape.scale? if _.isArray(shape.scale) then ctx.scale(shape.scale[0], shape.scale[1]) else if _.isNumber(shape.scale) then ctx.scale(shape.scale, shape.scale) else throw new Error('Scale argument must be number or array') drawShape = (shape, ctx, assets) -> # TODO: verify that arguments are of the correct type (the canvas API will not complain, just misfunction!) ctx.save() handleTransformations(shape, ctx) if shape.composition then ctx.globalCompositeOperation = shape.composition if shape.alpha then ctx.globalAlpha = shape.alpha switch shape.type when 'rectangle' # Fill in defaults if "fillStyle" not of shape and "strokeStyle" not of shape then shape.fillStyle = "#cf0404" _.defaults shape, size: [100, 100] position: [100, 100] if shape.fillStyle ctx.fillStyle = interpretStyle(shape.fillStyle, ctx) ctx.fillRect(shape.position[0], shape.position[1], shape.size[0], shape.size[1]) if shape.strokeStyle ctx.strokeStyle = interpretStyle(shape.strokeStyle, ctx) if shape.lineWidth then ctx.lineWidth = shape.lineWidth ctx.strokeRect(shape.position[0], shape.position[1], shape.size[0], shape.size[1]) when 'image' if shape.asset not of assets then throw new Error("Cannot find asset '#{shape.asset}' for shape '#{JSON.stringify(shape)}'") # Fill in defaults if "position" not of shape then shape.position = [100, 100] img = assets[shape.asset] size = if shape.size # Clamp size to image size [Math.min(shape.size[0], img.naturalWidth), Math.min(shape.size[1], img.naturalHeight)] else [img.naturalWidth, img.naturalHeight] offset = shape.offset || [0, 0] try # drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh) ctx.drawImage(img, offset[0], offset[1], size[0], size[1], shape.position[0], shape.position[1], size[0], size[1]) catch error throw new Error("Error drawing image shape #{JSON.stringify(shape)}: #{RW.formatStackTrace(error)}") when 'text' # Fill in defaults if "fillStyle" not of shape and "strokeStyle" not of shape then shape.fillStyle = "#cf0404" _.defaults shape, position: [200, 200] text: "RedWire" font: "40px Courier New" align: "left" text = _.isString(shape.text) && shape.text || JSON.stringify(shape.text) ctx.font = shape.font ctx.textAlign = shape.align if shape.fillStyle ctx.fillStyle = interpretStyle(shape.fillStyle, ctx) ctx.fillText(text, shape.position[0], shape.position[1]) if shape.strokeStyle ctx.strokeStyle = interpretStyle(shape.strokeStyle, ctx) ctx.strokeText(text, shape.position[0], shape.position[1]) when 'path' # Fill in defaults if "fillStyle" not of shape and "strokeStyle" not of shape then shape.strokeStyle = "#cf0404" _.defaults shape, points: [ [200, 200], [400, 200], [300, 100] ] lineWidth: 10 ctx.beginPath() ctx.moveTo(shape.points[0][0], shape.points[0][1]) for point in shape.points[1..] then ctx.lineTo(point[0], point[1]) if shape.fillStyle ctx.fillStyle = interpretStyle(shape.fillStyle, ctx) ctx.fill() if shape.strokeStyle ctx.strokeStyle = interpretStyle(shape.strokeStyle, ctx) if shape.lineWidth then ctx.lineWidth = shape.lineWidth if shape.lineCap then ctx.lineCap = shape.lineCap if shape.lineJoin then ctx.lineJoin = shape.lineJoin if shape.miterLimit then ctx.miterLimit = shape.miterLimit ctx.stroke() when 'circle' # Fill in defaults if "fillStyle" not of shape and "strokeStyle" not of shape then shape.fillStyle = "#cf0404" _.defaults shape, position: [300, 300] radius: 50 ctx.beginPath(); ctx.moveTo(shape.position[0], shape.position[1]) ctx.arc(shape.position[0], shape.position[1], shape.radius, 0, 2 * Math.PI) if shape.fillStyle ctx.fillStyle = interpretStyle(shape.fillStyle, ctx) ctx.fill() if shape.strokeStyle ctx.strokeStyle = interpretStyle(shape.strokeStyle, ctx) if shape.lineWidth then ctx.lineWidth = shape.lineWidth ctx.stroke() else throw new Error('Unknown or missing shape type') ctx.restore() layers = createLayers() return { provideData: -> # Return a global size, as well as an empty object of shapes for each layer per circuit data = global: size: options.size for circuitMeta in options.circuitMetas data[circuitMeta.id] = size: options.size for layer in options.layers data[layer.circuitId][layer.name] = [] return data establishData: (data) -> # Clear layers for layerId, canvas of layers canvas[0].getContext('2d').clearRect(0, 0, options.size[0], options.size[1]) # For each layer, sort shapes and then draw them for circuitId, circuitData of data circuitType = _.findWhere(options.circuitMetas, { id: circuitId })?.type if not circuitType? then continue # Recorded data with circuits can trip us up for layerName, shapeArray of circuitData when layerName isnt "size" layerId = makeLayerId(circuitId, layerName) if layerId not of layers then throw new Error("Invalid layer '#{layerName}' in circuit '#{circuitId}'") shapeArray.sort(shapeSorter) ctx = layers[layerId][0].getContext('2d') for shape in shapeArray then drawShape(shape, ctx, options.assets) return null # avoid accumulating results destroy: -> for layerId, canvas of layers then canvas.remove() } # Define html input io RW.io.html = meta: visual: true factory: (options) -> state = RW.mapToObject _.pluck(options.circuitMetas, "id"), -> templates: {} layers: {} views: {} callbacks: {} codeTemplateId = (circuitId, templateName) -> return "#{circuitId}.#{templateName}" decodeTemplateId = (templateId) -> templateId.split(".") rivets.configure handler: (target, event, binding) -> # binding.view.models.data will give the id of the template [circuitId, templateName] = decodeTemplateId(binding.view.models.data) state[circuitId].templates[templateName].values[binding.keypath] = true adapter: subscribe: (templateId, keypath, callback) -> # console.log("subscribe called with ", arguments) [circuitId, templateName] = decodeTemplateId(templateId) state[circuitId].callbacks[templateName][keypath] = callback unsubscribe: (templateId, keypath, callback) -> # console.log("unsubscribe called with ", arguments) [circuitId, templateName] = decodeTemplateId(templateId) delete state[circuitId].callbacks[templateName][keypath] read: (templateId, keypath) -> # console.log("read called with ", arguments) [circuitId, templateName] = decodeTemplateId(templateId) return state[circuitId].templates[templateName].values[keypath] publish: (templateId, keypath, value) -> # console.log("publish called with ", arguments) [circuitId, templateName] = decodeTemplateId(templateId) state[circuitId].templates[templateName].values[keypath] = value return { provideData: -> result = RW.mapToObject _.pluck(options.circuitMetas, "id"), (circuitId) -> state[circuitId].templates result.global = {} return result establishData: (data) -> for circuitId, circuitData of data # circuitData are in the template of { templateName: { asset: "", initialValues: { ... } values: { name: value, ... }, ... }, ...} existingTemplates = _.keys(state[circuitId].templates) newTemplates = _.keys(circuitData) # Remove all templates that are no longer to be shown for templateName in _.difference(existingTemplates, newTemplates) delete state[circuitId].templates[templateName] state[circuitId].layers[templateName].remove() delete state[circuitId].layers[templateName] state[circuitId].views[templateName].unbind() delete state[circuitId].views[templateName] delete state[circuitId].callbacks[templateName] # Add new templates for templateName in _.difference(newTemplates, existingTemplates) # Create template templateHtml = options.assets[circuitData[templateName].asset] # TODO: create all layers before hand? layerOptions = _.findWhere(options.layers, { circuitId: circuitId, name: templateName }) # Find out what the depth is layer = _.findWhere options.layers, "circuitId": circuitId "name": templateName if not layer then throw new Error("Invalid HTML layer '#{templateName}' in circuit '#{circuitId}'") outerWrapper = $("<div id='html-#{circuitId}-#{templateName}' style='position: absolute; z-index: #{layer.depth}; pointer-events: none; width: #{options.size[0]}px; height: #{options.size[1]}px'/>") outerWrapper.append(templateHtml) $(options.elementSelector).append(outerWrapper) state[circuitId].layers[templateName] = outerWrapper # Copy over template data to state state[circuitId].templates[templateName] = circuitData[templateName] # Setup initial values if available state[circuitId].templates[templateName].values = _.defaults({}, circuitData[templateName].values, circuitData[templateName].initialValues) # Bind to the template name state[circuitId].callbacks[templateName] = { } # Will be filled by calls to adapter.subscribe() state[circuitId].views[templateName] = rivets.bind(outerWrapper[0], { data: codeTemplateId(circuitId, templateName) }) # Update existing templates with new circuitData for templateName in _.intersection(newTemplates, existingTemplates) # Start with current values newValues = RW.cloneData(state[circuitId].templates[templateName].values) # Overwrite old state with new if circuitData[templateName].values? newValues = circuitData[templateName].values # Overwrite only selected properties with new values if circuitData[templateName].overwriteValues? _.extend(newValues, circuitData[templateName].overwriteValues) # TODO: call individual binders instead of syncronizing the whole model? # for key in _.union(_.keys(circuitData[templateName].values), _.keys(templates[templateName].values) if not _.isEqual(newValues, state[circuitId].templates[templateName].values) # Overwrite values in the state with those established state[circuitId].templates[templateName].values = newValues state[circuitId].views[templateName].sync() # Reset all event bindings to false for templateName, view of state[circuitId].views for binding in view.bindings if binding.type.indexOf("on-") == 0 state[circuitId].templates[templateName].values[binding.keypath] = false return null # Remove all event handlers destroy: -> for circuitId, circuitState of state for templateName, view of circuitState.views view.unbind() for templateName, layer of circuitState.layers layer.remove() } # Define time io, that provides the current time in ms RW.io.time = meta: visual: false factory: (options) -> provideData: -> global: Date.now() establishData: -> # NOP destroy: -> # NOP # The HTTP io makes AJAX requests RW.io.http = meta: visual: false factory: (options) -> state = RW.mapToObject _.pluck(options.circuitMetas, "id"), -> requests: {} responses: {} io = provideData: -> _.extend({}, state, global: { requests: {}, responses: {} }) establishData: (ioData) -> # Expecting a format like { requests: { id: { method:, url:, data:, cache:, contentType: }, ... }, { responses: { id: { code:, data: }, ... } for circuitId in _.pluck(options.circuitMetas, "id") # Create new requests for requestName in _.difference(_.keys(ioData[circuitId].requests), _.keys(state[circuitId].requests)) do (requestName) -> jqXhr = $.ajax url: ioData[circuitId].requests[requestName].url type: ioData[circuitId].requests[requestName].method ? "GET" cache: ioData[circuitId].requests[requestName].cache ? true data: ioData[circuitId].requests[requestName].data contentType: ioData[circuitId].requests[requestName].contentType jqXhr.done (data, textStatus) -> state[circuitId].responses[requestName] = status: textStatus data: data jqXhr.fail (__, textStatus, errorThrown) -> state[circuitId].responses[requestName] = status: textStatus error: errorThrown delete state[circuitId].requests[requestName] # Remove deleted responses for requestName in _.difference(_.keys(state[circuitId].responses), _.keys(ioData[circuitId].responses)) delete state[circuitId].responses[requestName] return state destroy: () -> # NOP return io # Define chart output io RW.io.charts = meta: visual: true factory: (options) -> capitalizeFirstLetter = (str) -> str[0].toUpperCase() + str.slice(1) makeLayerId = (circuitId, layerName) -> "#{circuitId}.#{layerName}" deconstructLayerId = (layerId) -> layerId.split(".") createLayers = -> # Convert layers to ordered createdLayers = {} for { circuitId, name, depth } in options.layers layerId = makeLayerId(circuitId, name) # Create a canvas element canvasProps = "id='chartLayer-#{layerId}' class='chartCanvas' tabIndex=0" canvasCss = "z-index: #{depth}; position: absolute;" canvas = $("<canvas #{canvasProps} style='#{canvasCss}' />") $(options.elementSelector).append(canvas) createdLayers[layerId] = canvas return createdLayers clearLayer = (circuitId, layerName) -> layer = layers[makeLayerId(circuitId, layerName)] context = layer[0].getContext("2d") context.clearRect(0, 0, layer[0].width, layer[0].height) removeChart = (circuitId, layerName) -> clearLayer(circuitId, layerName) delete charts[circuitId][layerName] # Format { circuitId: { name: { canvas:, data: }}} charts = RW.mapToObject(_.pluck(options.circuitMetas, "id"), -> {}) layers = createLayers() return { provideData: -> data = global: {} for circuitMeta in options.circuitMetas data[circuitMeta.id] = {} for layer in options.layers data[layer.circuitId][layer.name] = null return data establishData: (ioData) -> for circuitId, circuitData of ioData circuitType = _.findWhere(options.circuitMetas, { id: circuitId })?.type if not circuitType? then continue # Recorded data with circuits can trip us up # Remove unused charts for layerName in _.difference(_.keys(charts[circuitId]), _.keys(circuitData)) removeChart(circuitId, chartName) # Create and update charts for layerName, chartData of circuitData layerId = makeLayerId(circuitId, layerName) if layerId not of layers then throw new Error("Invalid layer '#{layerName}' in circuit '#{circuitId}'") # Expecting chartData like { size:, position:, data:, options: }} # If the chart already exists... if layerName of charts[circuitId] #... and has the same data, don't bother redrawing it if _.isEqual(charts[circuitId][layerName].data, chartData) then continue # Otherwise remove it. else removeChart(circuitId, layerName) # If the chart is empty or null, remove it if not chartData then continue # Check it's a valid chart type chartType = chartData.type || "Line" if chartType not of Chart.types throw new Error("Unknown chart type: '#{chartData.type}'") # Define options displayOptions = size: chartData.size ? options.size position: chartData.position ? [0, 0] chartOptions = _.defaults chartData.options ? {}, animation: false showTooltips: false # Retrieve the existing canvas layer, then set its position and size layer = layers[layerId] layer.prop width: displayOptions.size[0] height: displayOptions.size[1] layer.css left: "#{displayOptions.position[0]}px" top: "#{displayOptions.position[1]}px" # Create a new Chart object chart = new Chart(layer[0].getContext("2d")) # Call the correct method on it chart[capitalizeFirstLetter(chartType)](chartData.data, chartOptions) # Store it charts[circuitId][layerName] = chart: chart data: chartData return null destroy: -> for circuitId, circuitCharts of charts for layerName, chart of circuitCharts then clearLayer(circuitId, layerName) $(".chartCanvas").remove() return null } # Define audio output io RW.io.sound = meta: audio: true factory: (options) -> makeChannelId = (circuitId, channelName) -> "#{circuitId}.#{channelName}" deconstructLayerId = (channelId) -> channelId.split(".") stopPlayingSounds = -> for id, source of playingSourceNodes source.stop() # Returns a unique id of the sound clip in playingSourceNodes connectAndPlayBuffer = (buffer, shouldLoop = false) -> # Create source node source = RW.audioContext.createBufferSource() source.buffer = buffer source.connect(RW.lineOut.destination) source.loop = shouldLoop # Keep track of what sounds are playing id = _.uniqueId() source.onended = -> delete playingSourceNodes[id] playingSourceNodes[id] = source # Play immediately source.start(0) return id playingMusic = {} # maps asset names to AudioBufferSourceNode objects playingSourceNodes = {} inPlaySequence = false return { enterPlaySequence: -> inPlaySequence = true # startup playing music for channelId, playingMusicData of playingMusic if playingMusicData.channelData.asset then connectAndPlayBuffer(options.assets[playingMusicData.channelData.asset], true) leavePlaySequence: -> stopPlayingSounds() inPlaySequence = false provideData: -> global: { } establishData: (data) -> # Only play sounds in "play" mode if not inPlaySequence then return for circuitId, circuitData of data circuitType = _.findWhere(options.circuitMetas, { id: circuitId }).type for channelName, channelData of circuitData channelMeta = _.findWhere(options.channels, { circuitId: circuitId, name: channelName }) if not channelMeta? then throw new Error("Cannot find channel '#{channelName}' for circuit '#{circuitId}'") switch channelMeta.type when "clip" for sound in channelData if sound.asset not of options.assets throw new Error("Cannot find asset '#{sound.asset}' for circuit '#{circuitId}'") connectAndPlayBuffer(options.assets[sound.asset]) when "music" # Channel data should be like { asset: "qsdf" } or null channelId = makeChannelId(circuitId, channelName) if _.isEqual(playingMusic[channelId]?.channelData, channelData) then continue # Stop music if its playing # TODO: handle volume changes of same music if playingMusic[channelId] playingSourceNodes[playingMusic[channelId].id].stop() # Play new music if channelData if channelData.asset not of options.assets throw new Error("Cannot find asset '#{channelData.asset}' for circuit '#{circuitId}'") # TODO: handle crossfading sourceId = connectAndPlayBuffer(options.assets[channelData.asset], true) playingMusic[channelId] = channelData: channelData id: sourceId when "fx" for sound in channelData _.defaults sound, fx: ["square",0.0000,0.4000,0.0000,0.3200,0.0000,0.2780,20.0000,496.0000,2400.0000,0.4640,0.0000,0.0000,0.0100,0.0003,0.0000,0.0000,0.0000,0.0235,0.0000,0.0000,0.0000,0.0000,1.0000,0.0000,0.0000,0.0000,0.0000] buffer = WebAudiox.getBufferFromJsfx(RW.audioContext, sound.fx) connectAndPlayBuffer(buffer) else throw new Error("Unknown channel type '#{channelMeta.type}'") return null # avoid accumulating results destroy: -> stopPlayingSounds() } # A RedMetrics IO service to send game analytics data RW.io.metrics = meta: visual: false factory: (options) -> SNAPSHOT_FRAME_DELAY = 60 # Only record a snapshot every 60 frames eventQueue = [] snapshotQueue = [] timerId = null playerId = null playerInfo = {} # Current state of player snapshotFrameCounter = 0 ## Number of frames since last snapshot configIsValid = -> options.metrics and options.metrics.gameVersionId and options.metrics.host sendResults = -> sendEvents() sendSnapshots() sendEvents = -> if eventQueue.length is 0 then return # Send AJAX request jqXhr = $.ajax url: options.metrics.host + "/v1/event/" type: "POST" data: JSON.stringify(eventQueue) processData: false contentType: "application/json" # Clear queue eventQueue = [] sendSnapshots = -> if snapshotQueue.length is 0 then return # Send AJAX request jqXhr = $.ajax url: options.metrics.host + "/v1/snapshot/" type: "POST" data: JSON.stringify(snapshotQueue) processData: false contentType: "application/json" # Clear queue snapshotQueue = [] io = enterPlaySequence: -> if not configIsValid() then return # Reset snapshot counter so that it will be sent on the first frame snapshotFrameCounter = SNAPSHOT_FRAME_DELAY # Create player jqXhr = $.ajax url: options.metrics.host + "/v1/player/" type: "POST" data: "{}" processData: false contentType: "application/json" jqXhr.done (data, textStatus) -> playerId = data.id # Start sending events timerId = window.setInterval(sendResults, 5000) jqXhr.fail (__, textStatus, errorThrown) -> throw new Error("Cannot create player: #{errorThrown}") leavePlaySequence: -> # If metrics session was not created then ignore if not playerId then return # Send last data before stopping sendResults() # Stop sending events window.clearInterval(timerId) playerId = null provideData: -> global: events: [] player: playerInfo establishData: (ioData, additionalData) -> # Only send data in play sequence if not playerId then return # Contains updated playerInfo if necessary newPlayerInfo = null userTime = new Date().toISOString() # Expecting a format like { player: {}, events: [ type: "", section: [], coordinates: [], customData: }, ... ] } for circuitId in _.pluck(options.circuitMetas, "id") # Collate all data into the events queue (disregard individual circuits) # Set game version and player IDs on events for event in ioData[circuitId].events # If event section is array, change it to a dot.separated string if event.section and _.isArray(event.section) event.section = event.section.join(".") eventQueue.push _.extend event, gameVersion: options.metrics.gameVersionId player: <NAME>Id userTime: userTime if snapshotFrameCounter++ >= SNAPSHOT_FRAME_DELAY # Reset snapshot counter snapshotFrameCounter = 0 # Send input memory and input IO data as snapshots snapshotQueue.push gameVersion: options.metrics.gameVersionId player: <NAME>Id userTime: userTime customData: inputIo: additionalData.inputIoData memory: additionalData.memoryData # Update player info if not _.isEqual(ioData[circuitId].player, playerInfo) newPlayerInfo = ioData[circuitId].player # Update player info if necessary if newPlayerInfo jqXhr = $.ajax url: options.metrics.host + "/v1/player/" + playerId type: "PUT" data: JSON.stringify(newPlayerInfo) processData: false contentType: "application/json" playerInfo = newPlayerInfo return null # avoid accumulating results destroy: -> # NOP return io # The location buffer provides information about the URL and its different parts RW.io.location = meta: visual: false factory: (options) -> provideData: -> global: options.locationInfo establishData: -> # NOP destroy: -> # NOP # Gives access to the Movuino RW.io.movuino = meta: visual: false factory: (options) -> # Connect to the serial port via a web socket (using MisterS) state = connected: false a: [0, 0, 0] g: [0, 0, 0] # TODO: check for errors # TODO: make host and port configurable ws = new WebSocket("ws://localhost:53141/") ws.onopen = -> ws.send("l") state.connected = true ws.onmessage = (event) -> # Expecting data like "l 6360 -8796 -16152 -371 218 -147" tokens = event.data.split(" ") state.a = _.map(tokens[1..3], parseFloat) state.g = _.map(tokens[4..6], parseFloat) return { provideData: -> return global: state establishData: -> # NOP destroy: -> try if not ws or ws.readyState != WebSocket.OPEN then return null ws.send("q") ws.close() catch e console.log("Error closing Mouvino web socket", e) } # Gives access to mobile data # but maybe we can inject this from mobiler... RW.io.mobilemover = meta: visual: false factory: (options) -> # Connect to the serial port via a web socket -- ws_server.js for now # but eventually socket.io keysDown = {} state = connected: false move: false moves = ['u','d','l','r'] # get ip and port of ws from js file written on startup ws_ip = window.mobiler_qr_ip port = window.mobiler_qr_port ws = new WebSocket("ws://"+ ws_ip + ":" + port,'echo-protocol') ws.onopen = -> state.connected = true ws.onmessage = (event) -> # for now, wipe this on each new message keysDown = {} data = JSON.parse(event.data); # hide the qr code # parent.$("#"+data.id).hide(); # TODO add per game filter from vendor js key = data.msg console.log(key); # test by just emitting a keydown event # needs a debounce arrow = $.Event('keydown'); kill = $.Event('keyup'); # jQuery uses which not keyCode arrow.which = key kill.which = key interval = 50 selector = '#gameContent' killme = () -> $(selector).trigger(kill) $(selector).trigger(arrow) setTimeout(killme,interval) keysDown[key] = true return { # what do we need to return here? # keyboard returns a keysDowns object of form {38:true,40:false,...} # we can return that. provideData: -> global: keysDown: keysDown establishData: -> # NOP destroy: -> try if not ws or ws.readyState != WebSocket.OPEN then return null ws.send("q") ws.close() catch e console.log("Error closing Mobilemovr web socket", e) }
true
# Get alias for the global scope globals = @ # All will be in the "RW" namespace RW = globals.RW ? {} globals.RW = RW RW.io = {} # Define keyboard input io RW.io.keyboard = meta: visual: false factory: (options) -> eventNamespace = _.uniqueId('keyboard') keysDown = {} $(options.elementSelector).on "keydown.#{eventNamespace} keyup.#{eventNamespace} focusout.#{eventNamespace}", (event) -> # Don't handle events on HTML controls if event.target.tagName in ["INPUT", "BUTTON", "LABEL", "TEXTAREA"] then return true event.preventDefault() # jQuery standardizes the keycode into http://api.jquery.com/event.which/ switch event.type when 'keydown' then keysDown[event.which] = true when 'keyup' then delete keysDown[event.which] when 'focusout' then keysDown = {} # Lost focus, so will not receive keyup events else throw new Error('Unexpected event type') return true return { provideData: -> global: keysDown: keysDown establishData: -> # NOOP. Input io does not take data # Remove all event handlers destroy: -> $(options.elementSelector).off(".#{eventNamespace}") } # Define mouse input/output io RW.io.mouse = meta: visual: false factory: (options) -> eventNamespace = _.uniqueId('mouse') mouse = down: false position: [0, 0] cursor: null lastMouse = RW.cloneData(mouse) # This disables selection, which allows the cursor to change in Chrome $(options.elementSelector).on("selectstart.#{eventNamespace}", -> false) $(options.elementSelector).on "mousedown.#{eventNamespace} mouseup.#{eventNamespace} mousemove.#{eventNamespace} mouseleave.#{eventNamespace}", (event) -> switch event.type when 'mousedown' then mouse.down = true when 'mouseup' then mouse.down = false when 'mousemove' # Get position relative to canvas. # Based on http://www.html5canvastutorials.com/advanced/html5-canvas-mouse-coordinates/ rect = event.target.getBoundingClientRect() target = $(event.target) mouse.position = [ Math.floor((event.clientX - rect.left) * options.size[0] / rect.width) Math.floor((event.clientY - rect.top) * options.size[1] / rect.height) ] return true # Otherwise mouse click may not "complete" in Chrome return { provideData: -> # Calculate justDown and justUp in terms of previous data info = down: mouse.down position: mouse.position cursor: mouse.cursor justDown: mouse.down and not lastMouse.down justUp: not mouse.down and lastMouse.down lastMouse = RW.cloneData(mouse) return { global: info } establishData: (data) -> # TODO: how to handle contention for cursor across circuits? cursor = "" for circuitId, circuitData of data cursor = circuitData.cursor || cursor $(options.elementSelector).css("cursor", cursor) # Remove all event handlers destroy: -> $(options.elementSelector).off(".#{eventNamespace}") } # Define canvas output io RW.io.canvas = meta: visual: true factory: (options) -> CANVAS_CSS = "position: absolute; left: 0px; top: 0px; pointer-events: none;" makeLayerId = (circuitId, layerName) -> "#{circuitId}.#{layerName}" deconstructLayerId = (layerId) -> layerId.split(".") createLayers = -> # Convert layers to ordered createdLayers = {} for { circuitId, name, depth } in options.layers layerId = makeLayerId(circuitId, name) layer = $("<canvas id='canvasLayer-#{layerId}' class='gameCanvas' width='#{options.size[0]}' height='#{options.size[1]}' style='z-index: #{depth}; #{CANVAS_CSS}' />") $(options.elementSelector).append(layer) createdLayers[layerId] = layer return createdLayers # Default orderForShape = (shape) -> return shape.order || 0 shapeSorter = (a, b) -> return orderForShape(a) - orderForShape(b) interpretStyle = (style, ctx) -> if _.isString(style) then return style if not _.isObject(style) then throw new Error('Style must be string or object') switch style.type when 'radialGradient' grad = ctx.createRadialGradient(style.start.position[0], style.start.position[1], style.start.radius, style.end.position[0], style.end.position[1], style.end.radius) for colorStop in style.colorStops grad.addColorStop(colorStop.position, colorStop.color) return grad when 'linearGradient' grad = ctx.createLinearGradient(style.startPosition[0], style.startPosition[1], style.endPosition[0], style.endPosition[1]) for colorStop in style.colorStops grad.addColorStop(colorStop.position, colorStop.color) return grad else throw new Error('Unknown or missing style type') handleTransformations = (shape, ctx) -> # Not sure this is done in the right order if shape.translation? ctx.translate(shape.translation[0], shape.translation[1]) if not shape.position? then shape.position = [0, 0] if shape.rotation? then ctx.rotate(shape.rotation * Math.PI / 180) # Convert to radians if shape.scale? if _.isArray(shape.scale) then ctx.scale(shape.scale[0], shape.scale[1]) else if _.isNumber(shape.scale) then ctx.scale(shape.scale, shape.scale) else throw new Error('Scale argument must be number or array') drawShape = (shape, ctx, assets) -> # TODO: verify that arguments are of the correct type (the canvas API will not complain, just misfunction!) ctx.save() handleTransformations(shape, ctx) if shape.composition then ctx.globalCompositeOperation = shape.composition if shape.alpha then ctx.globalAlpha = shape.alpha switch shape.type when 'rectangle' # Fill in defaults if "fillStyle" not of shape and "strokeStyle" not of shape then shape.fillStyle = "#cf0404" _.defaults shape, size: [100, 100] position: [100, 100] if shape.fillStyle ctx.fillStyle = interpretStyle(shape.fillStyle, ctx) ctx.fillRect(shape.position[0], shape.position[1], shape.size[0], shape.size[1]) if shape.strokeStyle ctx.strokeStyle = interpretStyle(shape.strokeStyle, ctx) if shape.lineWidth then ctx.lineWidth = shape.lineWidth ctx.strokeRect(shape.position[0], shape.position[1], shape.size[0], shape.size[1]) when 'image' if shape.asset not of assets then throw new Error("Cannot find asset '#{shape.asset}' for shape '#{JSON.stringify(shape)}'") # Fill in defaults if "position" not of shape then shape.position = [100, 100] img = assets[shape.asset] size = if shape.size # Clamp size to image size [Math.min(shape.size[0], img.naturalWidth), Math.min(shape.size[1], img.naturalHeight)] else [img.naturalWidth, img.naturalHeight] offset = shape.offset || [0, 0] try # drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh) ctx.drawImage(img, offset[0], offset[1], size[0], size[1], shape.position[0], shape.position[1], size[0], size[1]) catch error throw new Error("Error drawing image shape #{JSON.stringify(shape)}: #{RW.formatStackTrace(error)}") when 'text' # Fill in defaults if "fillStyle" not of shape and "strokeStyle" not of shape then shape.fillStyle = "#cf0404" _.defaults shape, position: [200, 200] text: "RedWire" font: "40px Courier New" align: "left" text = _.isString(shape.text) && shape.text || JSON.stringify(shape.text) ctx.font = shape.font ctx.textAlign = shape.align if shape.fillStyle ctx.fillStyle = interpretStyle(shape.fillStyle, ctx) ctx.fillText(text, shape.position[0], shape.position[1]) if shape.strokeStyle ctx.strokeStyle = interpretStyle(shape.strokeStyle, ctx) ctx.strokeText(text, shape.position[0], shape.position[1]) when 'path' # Fill in defaults if "fillStyle" not of shape and "strokeStyle" not of shape then shape.strokeStyle = "#cf0404" _.defaults shape, points: [ [200, 200], [400, 200], [300, 100] ] lineWidth: 10 ctx.beginPath() ctx.moveTo(shape.points[0][0], shape.points[0][1]) for point in shape.points[1..] then ctx.lineTo(point[0], point[1]) if shape.fillStyle ctx.fillStyle = interpretStyle(shape.fillStyle, ctx) ctx.fill() if shape.strokeStyle ctx.strokeStyle = interpretStyle(shape.strokeStyle, ctx) if shape.lineWidth then ctx.lineWidth = shape.lineWidth if shape.lineCap then ctx.lineCap = shape.lineCap if shape.lineJoin then ctx.lineJoin = shape.lineJoin if shape.miterLimit then ctx.miterLimit = shape.miterLimit ctx.stroke() when 'circle' # Fill in defaults if "fillStyle" not of shape and "strokeStyle" not of shape then shape.fillStyle = "#cf0404" _.defaults shape, position: [300, 300] radius: 50 ctx.beginPath(); ctx.moveTo(shape.position[0], shape.position[1]) ctx.arc(shape.position[0], shape.position[1], shape.radius, 0, 2 * Math.PI) if shape.fillStyle ctx.fillStyle = interpretStyle(shape.fillStyle, ctx) ctx.fill() if shape.strokeStyle ctx.strokeStyle = interpretStyle(shape.strokeStyle, ctx) if shape.lineWidth then ctx.lineWidth = shape.lineWidth ctx.stroke() else throw new Error('Unknown or missing shape type') ctx.restore() layers = createLayers() return { provideData: -> # Return a global size, as well as an empty object of shapes for each layer per circuit data = global: size: options.size for circuitMeta in options.circuitMetas data[circuitMeta.id] = size: options.size for layer in options.layers data[layer.circuitId][layer.name] = [] return data establishData: (data) -> # Clear layers for layerId, canvas of layers canvas[0].getContext('2d').clearRect(0, 0, options.size[0], options.size[1]) # For each layer, sort shapes and then draw them for circuitId, circuitData of data circuitType = _.findWhere(options.circuitMetas, { id: circuitId })?.type if not circuitType? then continue # Recorded data with circuits can trip us up for layerName, shapeArray of circuitData when layerName isnt "size" layerId = makeLayerId(circuitId, layerName) if layerId not of layers then throw new Error("Invalid layer '#{layerName}' in circuit '#{circuitId}'") shapeArray.sort(shapeSorter) ctx = layers[layerId][0].getContext('2d') for shape in shapeArray then drawShape(shape, ctx, options.assets) return null # avoid accumulating results destroy: -> for layerId, canvas of layers then canvas.remove() } # Define html input io RW.io.html = meta: visual: true factory: (options) -> state = RW.mapToObject _.pluck(options.circuitMetas, "id"), -> templates: {} layers: {} views: {} callbacks: {} codeTemplateId = (circuitId, templateName) -> return "#{circuitId}.#{templateName}" decodeTemplateId = (templateId) -> templateId.split(".") rivets.configure handler: (target, event, binding) -> # binding.view.models.data will give the id of the template [circuitId, templateName] = decodeTemplateId(binding.view.models.data) state[circuitId].templates[templateName].values[binding.keypath] = true adapter: subscribe: (templateId, keypath, callback) -> # console.log("subscribe called with ", arguments) [circuitId, templateName] = decodeTemplateId(templateId) state[circuitId].callbacks[templateName][keypath] = callback unsubscribe: (templateId, keypath, callback) -> # console.log("unsubscribe called with ", arguments) [circuitId, templateName] = decodeTemplateId(templateId) delete state[circuitId].callbacks[templateName][keypath] read: (templateId, keypath) -> # console.log("read called with ", arguments) [circuitId, templateName] = decodeTemplateId(templateId) return state[circuitId].templates[templateName].values[keypath] publish: (templateId, keypath, value) -> # console.log("publish called with ", arguments) [circuitId, templateName] = decodeTemplateId(templateId) state[circuitId].templates[templateName].values[keypath] = value return { provideData: -> result = RW.mapToObject _.pluck(options.circuitMetas, "id"), (circuitId) -> state[circuitId].templates result.global = {} return result establishData: (data) -> for circuitId, circuitData of data # circuitData are in the template of { templateName: { asset: "", initialValues: { ... } values: { name: value, ... }, ... }, ...} existingTemplates = _.keys(state[circuitId].templates) newTemplates = _.keys(circuitData) # Remove all templates that are no longer to be shown for templateName in _.difference(existingTemplates, newTemplates) delete state[circuitId].templates[templateName] state[circuitId].layers[templateName].remove() delete state[circuitId].layers[templateName] state[circuitId].views[templateName].unbind() delete state[circuitId].views[templateName] delete state[circuitId].callbacks[templateName] # Add new templates for templateName in _.difference(newTemplates, existingTemplates) # Create template templateHtml = options.assets[circuitData[templateName].asset] # TODO: create all layers before hand? layerOptions = _.findWhere(options.layers, { circuitId: circuitId, name: templateName }) # Find out what the depth is layer = _.findWhere options.layers, "circuitId": circuitId "name": templateName if not layer then throw new Error("Invalid HTML layer '#{templateName}' in circuit '#{circuitId}'") outerWrapper = $("<div id='html-#{circuitId}-#{templateName}' style='position: absolute; z-index: #{layer.depth}; pointer-events: none; width: #{options.size[0]}px; height: #{options.size[1]}px'/>") outerWrapper.append(templateHtml) $(options.elementSelector).append(outerWrapper) state[circuitId].layers[templateName] = outerWrapper # Copy over template data to state state[circuitId].templates[templateName] = circuitData[templateName] # Setup initial values if available state[circuitId].templates[templateName].values = _.defaults({}, circuitData[templateName].values, circuitData[templateName].initialValues) # Bind to the template name state[circuitId].callbacks[templateName] = { } # Will be filled by calls to adapter.subscribe() state[circuitId].views[templateName] = rivets.bind(outerWrapper[0], { data: codeTemplateId(circuitId, templateName) }) # Update existing templates with new circuitData for templateName in _.intersection(newTemplates, existingTemplates) # Start with current values newValues = RW.cloneData(state[circuitId].templates[templateName].values) # Overwrite old state with new if circuitData[templateName].values? newValues = circuitData[templateName].values # Overwrite only selected properties with new values if circuitData[templateName].overwriteValues? _.extend(newValues, circuitData[templateName].overwriteValues) # TODO: call individual binders instead of syncronizing the whole model? # for key in _.union(_.keys(circuitData[templateName].values), _.keys(templates[templateName].values) if not _.isEqual(newValues, state[circuitId].templates[templateName].values) # Overwrite values in the state with those established state[circuitId].templates[templateName].values = newValues state[circuitId].views[templateName].sync() # Reset all event bindings to false for templateName, view of state[circuitId].views for binding in view.bindings if binding.type.indexOf("on-") == 0 state[circuitId].templates[templateName].values[binding.keypath] = false return null # Remove all event handlers destroy: -> for circuitId, circuitState of state for templateName, view of circuitState.views view.unbind() for templateName, layer of circuitState.layers layer.remove() } # Define time io, that provides the current time in ms RW.io.time = meta: visual: false factory: (options) -> provideData: -> global: Date.now() establishData: -> # NOP destroy: -> # NOP # The HTTP io makes AJAX requests RW.io.http = meta: visual: false factory: (options) -> state = RW.mapToObject _.pluck(options.circuitMetas, "id"), -> requests: {} responses: {} io = provideData: -> _.extend({}, state, global: { requests: {}, responses: {} }) establishData: (ioData) -> # Expecting a format like { requests: { id: { method:, url:, data:, cache:, contentType: }, ... }, { responses: { id: { code:, data: }, ... } for circuitId in _.pluck(options.circuitMetas, "id") # Create new requests for requestName in _.difference(_.keys(ioData[circuitId].requests), _.keys(state[circuitId].requests)) do (requestName) -> jqXhr = $.ajax url: ioData[circuitId].requests[requestName].url type: ioData[circuitId].requests[requestName].method ? "GET" cache: ioData[circuitId].requests[requestName].cache ? true data: ioData[circuitId].requests[requestName].data contentType: ioData[circuitId].requests[requestName].contentType jqXhr.done (data, textStatus) -> state[circuitId].responses[requestName] = status: textStatus data: data jqXhr.fail (__, textStatus, errorThrown) -> state[circuitId].responses[requestName] = status: textStatus error: errorThrown delete state[circuitId].requests[requestName] # Remove deleted responses for requestName in _.difference(_.keys(state[circuitId].responses), _.keys(ioData[circuitId].responses)) delete state[circuitId].responses[requestName] return state destroy: () -> # NOP return io # Define chart output io RW.io.charts = meta: visual: true factory: (options) -> capitalizeFirstLetter = (str) -> str[0].toUpperCase() + str.slice(1) makeLayerId = (circuitId, layerName) -> "#{circuitId}.#{layerName}" deconstructLayerId = (layerId) -> layerId.split(".") createLayers = -> # Convert layers to ordered createdLayers = {} for { circuitId, name, depth } in options.layers layerId = makeLayerId(circuitId, name) # Create a canvas element canvasProps = "id='chartLayer-#{layerId}' class='chartCanvas' tabIndex=0" canvasCss = "z-index: #{depth}; position: absolute;" canvas = $("<canvas #{canvasProps} style='#{canvasCss}' />") $(options.elementSelector).append(canvas) createdLayers[layerId] = canvas return createdLayers clearLayer = (circuitId, layerName) -> layer = layers[makeLayerId(circuitId, layerName)] context = layer[0].getContext("2d") context.clearRect(0, 0, layer[0].width, layer[0].height) removeChart = (circuitId, layerName) -> clearLayer(circuitId, layerName) delete charts[circuitId][layerName] # Format { circuitId: { name: { canvas:, data: }}} charts = RW.mapToObject(_.pluck(options.circuitMetas, "id"), -> {}) layers = createLayers() return { provideData: -> data = global: {} for circuitMeta in options.circuitMetas data[circuitMeta.id] = {} for layer in options.layers data[layer.circuitId][layer.name] = null return data establishData: (ioData) -> for circuitId, circuitData of ioData circuitType = _.findWhere(options.circuitMetas, { id: circuitId })?.type if not circuitType? then continue # Recorded data with circuits can trip us up # Remove unused charts for layerName in _.difference(_.keys(charts[circuitId]), _.keys(circuitData)) removeChart(circuitId, chartName) # Create and update charts for layerName, chartData of circuitData layerId = makeLayerId(circuitId, layerName) if layerId not of layers then throw new Error("Invalid layer '#{layerName}' in circuit '#{circuitId}'") # Expecting chartData like { size:, position:, data:, options: }} # If the chart already exists... if layerName of charts[circuitId] #... and has the same data, don't bother redrawing it if _.isEqual(charts[circuitId][layerName].data, chartData) then continue # Otherwise remove it. else removeChart(circuitId, layerName) # If the chart is empty or null, remove it if not chartData then continue # Check it's a valid chart type chartType = chartData.type || "Line" if chartType not of Chart.types throw new Error("Unknown chart type: '#{chartData.type}'") # Define options displayOptions = size: chartData.size ? options.size position: chartData.position ? [0, 0] chartOptions = _.defaults chartData.options ? {}, animation: false showTooltips: false # Retrieve the existing canvas layer, then set its position and size layer = layers[layerId] layer.prop width: displayOptions.size[0] height: displayOptions.size[1] layer.css left: "#{displayOptions.position[0]}px" top: "#{displayOptions.position[1]}px" # Create a new Chart object chart = new Chart(layer[0].getContext("2d")) # Call the correct method on it chart[capitalizeFirstLetter(chartType)](chartData.data, chartOptions) # Store it charts[circuitId][layerName] = chart: chart data: chartData return null destroy: -> for circuitId, circuitCharts of charts for layerName, chart of circuitCharts then clearLayer(circuitId, layerName) $(".chartCanvas").remove() return null } # Define audio output io RW.io.sound = meta: audio: true factory: (options) -> makeChannelId = (circuitId, channelName) -> "#{circuitId}.#{channelName}" deconstructLayerId = (channelId) -> channelId.split(".") stopPlayingSounds = -> for id, source of playingSourceNodes source.stop() # Returns a unique id of the sound clip in playingSourceNodes connectAndPlayBuffer = (buffer, shouldLoop = false) -> # Create source node source = RW.audioContext.createBufferSource() source.buffer = buffer source.connect(RW.lineOut.destination) source.loop = shouldLoop # Keep track of what sounds are playing id = _.uniqueId() source.onended = -> delete playingSourceNodes[id] playingSourceNodes[id] = source # Play immediately source.start(0) return id playingMusic = {} # maps asset names to AudioBufferSourceNode objects playingSourceNodes = {} inPlaySequence = false return { enterPlaySequence: -> inPlaySequence = true # startup playing music for channelId, playingMusicData of playingMusic if playingMusicData.channelData.asset then connectAndPlayBuffer(options.assets[playingMusicData.channelData.asset], true) leavePlaySequence: -> stopPlayingSounds() inPlaySequence = false provideData: -> global: { } establishData: (data) -> # Only play sounds in "play" mode if not inPlaySequence then return for circuitId, circuitData of data circuitType = _.findWhere(options.circuitMetas, { id: circuitId }).type for channelName, channelData of circuitData channelMeta = _.findWhere(options.channels, { circuitId: circuitId, name: channelName }) if not channelMeta? then throw new Error("Cannot find channel '#{channelName}' for circuit '#{circuitId}'") switch channelMeta.type when "clip" for sound in channelData if sound.asset not of options.assets throw new Error("Cannot find asset '#{sound.asset}' for circuit '#{circuitId}'") connectAndPlayBuffer(options.assets[sound.asset]) when "music" # Channel data should be like { asset: "qsdf" } or null channelId = makeChannelId(circuitId, channelName) if _.isEqual(playingMusic[channelId]?.channelData, channelData) then continue # Stop music if its playing # TODO: handle volume changes of same music if playingMusic[channelId] playingSourceNodes[playingMusic[channelId].id].stop() # Play new music if channelData if channelData.asset not of options.assets throw new Error("Cannot find asset '#{channelData.asset}' for circuit '#{circuitId}'") # TODO: handle crossfading sourceId = connectAndPlayBuffer(options.assets[channelData.asset], true) playingMusic[channelId] = channelData: channelData id: sourceId when "fx" for sound in channelData _.defaults sound, fx: ["square",0.0000,0.4000,0.0000,0.3200,0.0000,0.2780,20.0000,496.0000,2400.0000,0.4640,0.0000,0.0000,0.0100,0.0003,0.0000,0.0000,0.0000,0.0235,0.0000,0.0000,0.0000,0.0000,1.0000,0.0000,0.0000,0.0000,0.0000] buffer = WebAudiox.getBufferFromJsfx(RW.audioContext, sound.fx) connectAndPlayBuffer(buffer) else throw new Error("Unknown channel type '#{channelMeta.type}'") return null # avoid accumulating results destroy: -> stopPlayingSounds() } # A RedMetrics IO service to send game analytics data RW.io.metrics = meta: visual: false factory: (options) -> SNAPSHOT_FRAME_DELAY = 60 # Only record a snapshot every 60 frames eventQueue = [] snapshotQueue = [] timerId = null playerId = null playerInfo = {} # Current state of player snapshotFrameCounter = 0 ## Number of frames since last snapshot configIsValid = -> options.metrics and options.metrics.gameVersionId and options.metrics.host sendResults = -> sendEvents() sendSnapshots() sendEvents = -> if eventQueue.length is 0 then return # Send AJAX request jqXhr = $.ajax url: options.metrics.host + "/v1/event/" type: "POST" data: JSON.stringify(eventQueue) processData: false contentType: "application/json" # Clear queue eventQueue = [] sendSnapshots = -> if snapshotQueue.length is 0 then return # Send AJAX request jqXhr = $.ajax url: options.metrics.host + "/v1/snapshot/" type: "POST" data: JSON.stringify(snapshotQueue) processData: false contentType: "application/json" # Clear queue snapshotQueue = [] io = enterPlaySequence: -> if not configIsValid() then return # Reset snapshot counter so that it will be sent on the first frame snapshotFrameCounter = SNAPSHOT_FRAME_DELAY # Create player jqXhr = $.ajax url: options.metrics.host + "/v1/player/" type: "POST" data: "{}" processData: false contentType: "application/json" jqXhr.done (data, textStatus) -> playerId = data.id # Start sending events timerId = window.setInterval(sendResults, 5000) jqXhr.fail (__, textStatus, errorThrown) -> throw new Error("Cannot create player: #{errorThrown}") leavePlaySequence: -> # If metrics session was not created then ignore if not playerId then return # Send last data before stopping sendResults() # Stop sending events window.clearInterval(timerId) playerId = null provideData: -> global: events: [] player: playerInfo establishData: (ioData, additionalData) -> # Only send data in play sequence if not playerId then return # Contains updated playerInfo if necessary newPlayerInfo = null userTime = new Date().toISOString() # Expecting a format like { player: {}, events: [ type: "", section: [], coordinates: [], customData: }, ... ] } for circuitId in _.pluck(options.circuitMetas, "id") # Collate all data into the events queue (disregard individual circuits) # Set game version and player IDs on events for event in ioData[circuitId].events # If event section is array, change it to a dot.separated string if event.section and _.isArray(event.section) event.section = event.section.join(".") eventQueue.push _.extend event, gameVersion: options.metrics.gameVersionId player: PI:NAME:<NAME>END_PIId userTime: userTime if snapshotFrameCounter++ >= SNAPSHOT_FRAME_DELAY # Reset snapshot counter snapshotFrameCounter = 0 # Send input memory and input IO data as snapshots snapshotQueue.push gameVersion: options.metrics.gameVersionId player: PI:NAME:<NAME>END_PIId userTime: userTime customData: inputIo: additionalData.inputIoData memory: additionalData.memoryData # Update player info if not _.isEqual(ioData[circuitId].player, playerInfo) newPlayerInfo = ioData[circuitId].player # Update player info if necessary if newPlayerInfo jqXhr = $.ajax url: options.metrics.host + "/v1/player/" + playerId type: "PUT" data: JSON.stringify(newPlayerInfo) processData: false contentType: "application/json" playerInfo = newPlayerInfo return null # avoid accumulating results destroy: -> # NOP return io # The location buffer provides information about the URL and its different parts RW.io.location = meta: visual: false factory: (options) -> provideData: -> global: options.locationInfo establishData: -> # NOP destroy: -> # NOP # Gives access to the Movuino RW.io.movuino = meta: visual: false factory: (options) -> # Connect to the serial port via a web socket (using MisterS) state = connected: false a: [0, 0, 0] g: [0, 0, 0] # TODO: check for errors # TODO: make host and port configurable ws = new WebSocket("ws://localhost:53141/") ws.onopen = -> ws.send("l") state.connected = true ws.onmessage = (event) -> # Expecting data like "l 6360 -8796 -16152 -371 218 -147" tokens = event.data.split(" ") state.a = _.map(tokens[1..3], parseFloat) state.g = _.map(tokens[4..6], parseFloat) return { provideData: -> return global: state establishData: -> # NOP destroy: -> try if not ws or ws.readyState != WebSocket.OPEN then return null ws.send("q") ws.close() catch e console.log("Error closing Mouvino web socket", e) } # Gives access to mobile data # but maybe we can inject this from mobiler... RW.io.mobilemover = meta: visual: false factory: (options) -> # Connect to the serial port via a web socket -- ws_server.js for now # but eventually socket.io keysDown = {} state = connected: false move: false moves = ['u','d','l','r'] # get ip and port of ws from js file written on startup ws_ip = window.mobiler_qr_ip port = window.mobiler_qr_port ws = new WebSocket("ws://"+ ws_ip + ":" + port,'echo-protocol') ws.onopen = -> state.connected = true ws.onmessage = (event) -> # for now, wipe this on each new message keysDown = {} data = JSON.parse(event.data); # hide the qr code # parent.$("#"+data.id).hide(); # TODO add per game filter from vendor js key = data.msg console.log(key); # test by just emitting a keydown event # needs a debounce arrow = $.Event('keydown'); kill = $.Event('keyup'); # jQuery uses which not keyCode arrow.which = key kill.which = key interval = 50 selector = '#gameContent' killme = () -> $(selector).trigger(kill) $(selector).trigger(arrow) setTimeout(killme,interval) keysDown[key] = true return { # what do we need to return here? # keyboard returns a keysDowns object of form {38:true,40:false,...} # we can return that. provideData: -> global: keysDown: keysDown establishData: -> # NOP destroy: -> try if not ws or ws.readyState != WebSocket.OPEN then return null ws.send("q") ws.close() catch e console.log("Error closing Mobilemovr web socket", e) }
[ { "context": "ime Completions converted from https://github.com/Southclaw/pawn-sublime-language\n# Converter created by Rena", "end": 106, "score": 0.9995107054710388, "start": 97, "tag": "USERNAME", "value": "Southclaw" }, { "context": "hclaw/pawn-sublime-language\n# Converter creat...
snippets/sscanf2.cson
Wuzi/language-pawn
4
# sscanf2 snippets for Atom converted from Sublime Completions converted from https://github.com/Southclaw/pawn-sublime-language # Converter created by Renato "Hii" Garcia # Repo: https://github.com/Renato-Garcia/sublime-completions-to-atom-snippets '.source.pwn, .source.inc': 'sscanf': 'prefix': 'sscanf' 'body': 'sscanf(${1:const data[]}, ${2:const format[]}, ${3:...})' 'unformat': 'prefix': 'unformat' 'body': 'unformat(${1:const data[]}, ${2:const format[]}, ${3:...})'
142979
# sscanf2 snippets for Atom converted from Sublime Completions converted from https://github.com/Southclaw/pawn-sublime-language # Converter created by <NAME> "<NAME> # Repo: https://github.com/Renato-Garcia/sublime-completions-to-atom-snippets '.source.pwn, .source.inc': 'sscanf': 'prefix': 'sscanf' 'body': 'sscanf(${1:const data[]}, ${2:const format[]}, ${3:...})' 'unformat': 'prefix': 'unformat' 'body': 'unformat(${1:const data[]}, ${2:const format[]}, ${3:...})'
true
# sscanf2 snippets for Atom converted from Sublime Completions converted from https://github.com/Southclaw/pawn-sublime-language # Converter created by PI:NAME:<NAME>END_PI "PI:NAME:<NAME>END_PI # Repo: https://github.com/Renato-Garcia/sublime-completions-to-atom-snippets '.source.pwn, .source.inc': 'sscanf': 'prefix': 'sscanf' 'body': 'sscanf(${1:const data[]}, ${2:const format[]}, ${3:...})' 'unformat': 'prefix': 'unformat' 'body': 'unformat(${1:const data[]}, ${2:const format[]}, ${3:...})'
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9987964034080505, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-http-destroyed-socket-write2.coffee
lxe/io.coffee
0
# Copyright Joyent, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") # Verify that ECONNRESET is raised when writing to a http request # where the server has ended the socket. http = require("http") net = require("net") server = http.createServer((req, res) -> setImmediate -> res.destroy() return return ) server.listen common.PORT, -> write = -> if ++writes is 128 clearTimeout timer req.end() test() else timer = setImmediate(write) req.write "hello" return # This is the expected case # On windows this sometimes manifests as ECONNABORTED test = -> return if closed server.close() closed = true console.error "bad happened", req.output, req.outputEncodings if req.output.length or req.outputEncodings.length assert.equal req.output.length, 0 assert.equal req.outputEncodings, 0 assert gotError assert not sawData assert not sawEnd console.log "ok" return req = http.request( port: common.PORT path: "/" method: "POST" ) timer = setImmediate(write) writes = 0 gotError = false sawData = false sawEnd = false req.on "error", (er) -> assert not gotError gotError = true switch er.code when "ECONNRESET", "ECONNABORTED" else assert.strictEqual er.code, "ECONNRESET", "Writing to a torn down client should RESET or ABORT" clearTimeout timer console.log "ECONNRESET was raised after %d writes", writes test() return req.on "response", (res) -> res.on "data", (chunk) -> console.error "saw data: " + chunk sawData = true return res.on "end", -> console.error "saw end" sawEnd = true return return closed = false return
66969
# Copyright <NAME>, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") # Verify that ECONNRESET is raised when writing to a http request # where the server has ended the socket. http = require("http") net = require("net") server = http.createServer((req, res) -> setImmediate -> res.destroy() return return ) server.listen common.PORT, -> write = -> if ++writes is 128 clearTimeout timer req.end() test() else timer = setImmediate(write) req.write "hello" return # This is the expected case # On windows this sometimes manifests as ECONNABORTED test = -> return if closed server.close() closed = true console.error "bad happened", req.output, req.outputEncodings if req.output.length or req.outputEncodings.length assert.equal req.output.length, 0 assert.equal req.outputEncodings, 0 assert gotError assert not sawData assert not sawEnd console.log "ok" return req = http.request( port: common.PORT path: "/" method: "POST" ) timer = setImmediate(write) writes = 0 gotError = false sawData = false sawEnd = false req.on "error", (er) -> assert not gotError gotError = true switch er.code when "ECONNRESET", "ECONNABORTED" else assert.strictEqual er.code, "ECONNRESET", "Writing to a torn down client should RESET or ABORT" clearTimeout timer console.log "ECONNRESET was raised after %d writes", writes test() return req.on "response", (res) -> res.on "data", (chunk) -> console.error "saw data: " + chunk sawData = true return res.on "end", -> console.error "saw end" sawEnd = true return return closed = false return
true
# Copyright PI:NAME:<NAME>END_PI, Inc. and other Node contributors. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. common = require("../common") assert = require("assert") # Verify that ECONNRESET is raised when writing to a http request # where the server has ended the socket. http = require("http") net = require("net") server = http.createServer((req, res) -> setImmediate -> res.destroy() return return ) server.listen common.PORT, -> write = -> if ++writes is 128 clearTimeout timer req.end() test() else timer = setImmediate(write) req.write "hello" return # This is the expected case # On windows this sometimes manifests as ECONNABORTED test = -> return if closed server.close() closed = true console.error "bad happened", req.output, req.outputEncodings if req.output.length or req.outputEncodings.length assert.equal req.output.length, 0 assert.equal req.outputEncodings, 0 assert gotError assert not sawData assert not sawEnd console.log "ok" return req = http.request( port: common.PORT path: "/" method: "POST" ) timer = setImmediate(write) writes = 0 gotError = false sawData = false sawEnd = false req.on "error", (er) -> assert not gotError gotError = true switch er.code when "ECONNRESET", "ECONNABORTED" else assert.strictEqual er.code, "ECONNRESET", "Writing to a torn down client should RESET or ABORT" clearTimeout timer console.log "ECONNRESET was raised after %d writes", writes test() return req.on "response", (res) -> res.on "data", (chunk) -> console.error "saw data: " + chunk sawData = true return res.on "end", -> console.error "saw end" sawEnd = true return return closed = false return
[ { "context": "sed under the MIT License\nDate: 11-08-2015\nAuthor: Julio Cesar Fausto\nSource: https://github.com/jcfausto/jcfausto-com-", "end": 110, "score": 0.9998677372932434, "start": 92, "tag": "NAME", "value": "Julio Cesar Fausto" }, { "context": "or: Julio Cesar Fausto\nSourc...
app/assets/javascripts/components/achievement_list.js.jsx.coffee
jcfausto/jcfausto-rails-website
1
### AchievementList React Component Released under the MIT License Date: 11-08-2015 Author: Julio Cesar Fausto Source: https://github.com/jcfausto/jcfausto-com-rails ### @AchievementList = React.createClass getInitialState: -> achievement_items: this.props.achievements render: -> `<section> <h3><span>Some Achievements This Year</span></h3> <ul className="achievements"> {this.state.achievement_items.map( function(achievement, index){ return (<AchievementItem key={index} when={achievement.when} what={achievement.what} />) }, this) } </ul> </section>`
67343
### AchievementList React Component Released under the MIT License Date: 11-08-2015 Author: <NAME> Source: https://github.com/jcfausto/jcfausto-com-rails ### @AchievementList = React.createClass getInitialState: -> achievement_items: this.props.achievements render: -> `<section> <h3><span>Some Achievements This Year</span></h3> <ul className="achievements"> {this.state.achievement_items.map( function(achievement, index){ return (<AchievementItem key={index} when={achievement.when} what={achievement.what} />) }, this) } </ul> </section>`
true
### AchievementList React Component Released under the MIT License Date: 11-08-2015 Author: PI:NAME:<NAME>END_PI Source: https://github.com/jcfausto/jcfausto-com-rails ### @AchievementList = React.createClass getInitialState: -> achievement_items: this.props.achievements render: -> `<section> <h3><span>Some Achievements This Year</span></h3> <ul className="achievements"> {this.state.achievement_items.map( function(achievement, index){ return (<AchievementItem key={index} when={achievement.when} what={achievement.what} />) }, this) } </ul> </section>`
[ { "context": "lude the key in case the user doesn't have it.\n \"03E146CDAF8136680AD566912A32340CEC8C9492\" : \"\"\"\n-----BEGIN PGP PUBLIC KEY BLOCK-----\nVers", "end": 186, "score": 0.5850181579589844, "start": 146, "tag": "KEY", "value": "03E146CDAF8136680AD566912A32340CEC8C9492" }, ...
src/keys.iced
AngelKey/Angelkey.nodeclient
151
exports.lookup = # The Merkle Signing key that's in use by default by the server. # Include the key in case the user doesn't have it. "03E146CDAF8136680AD566912A32340CEC8C9492" : """ -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v1.4.14 (GNU/Linux) mQINBFNby/YBEACqCgoh3ia0AEd798qPkMHPUbRyEjuFOW4BkOw7auvaKJKL+vJz Ub1bgBDEEYwQYz/43JJymW7HuEb9Xg83DKnpVS3RlqSugcD/gRf0lwObEbTLWS4i sUBWx7h2cWjqqnDEQjdGE+HGRtzoYIvGwyDQlddrfOdgDIzvS9fjj4qgvNag2ktJ uZrH4psfEWsKaEKURBxuT48FxhhIJgo/OktB5hOEHAW/cAlXXCquykkCZq1uFKBP DNGBm7ZQOcAE/phoCeAh3hW3yYIX1XTeV8gBZ2o5RNVBJxBMOKiWDyVorHDCG+SK kV5xTw6ZzhKdShoqnXxJtQQ6CyPPOd9ypMJuf7Tc4/lPZYAXOLwEeeeNTEW7DblM JY0Xdy+KReesjewOBmNHGdgYCye6cWUKdi5NKg9VCuGR8v8FnjFLWrZyhgS84zia 8kL8L+7SBpyCxBe2NyXlTNESqyrplttmfJxrrmgI6518ptSYtHB1BHFoBkBngKtk OvBQEVzsR/ZSb5rQfsgR5JmiCp4UvdpTh6DmfQFSoDG9qp4oxMa3hyVqVAa3C/rY xrc4bBzifVwwlRl8J7WecsSxHVBeivFk96lF8Vk0DyKcEzAI2AvCXTM2OtAedD2y 6mGTPywvqxSnaGktUVLkgvUD3fBBMvezV1CzSWqSljqyvJMzHzkP4sGOKQARAQAB tDJLZXliYXNlLmlvIE1lcmtsZSBTaWduaW5nICh2MSkgPG1lcmtsZUBrZXliYXNl LmlvPokCOAQTAQIAIgUCU1vL9gIbAwYLCQgHAwIGFQgCCQoLBBYCAwECHgECF4AA CgkQKjI0DOyMlJJ6fA//cgw2t65CCtpSrCngtFf0k2/CNCjcP1sAidNySkOmLSuS vxifzee5I52w/Hr3hJ6j3E1/u+FJ8CaOjaKaPsNje8z8TUWVZCjBPyC7XM6+fFfC tWdMrI0kKAGfziKcxYij/WQOVDSKMvnvmnpzeYfMXKpuU2OQwgFvqfV19DHeSBKO cbL1MVM0eTnrfCgVq1RJNoLiTK3MF/YMb/1CWW2U3LRIiHptU4jyBDUwPSHeujVw CI2UeNIAcb26EcXWmagAcjPbmMsKq4drtZ5b1iG2adQYGaLMrURxaUJdCrn4gO47 bYfK2L8U4zDUuhf9rLbAHUEes4am4foVoJJegU3gjAeaVlOZFL9y7pcxnar0DNvb gWIEmAxUbeOQbTojj8LyJIWzqAySdmgWuJPU4BS6nHHdmAl4lYhbBP93fCKYMqbT T+JAE0TwD2uyk7HJm6hhb3X7NoyQBHC5/Dbfv+WvtuKYOYIKe2scoWb5JqcY8nx8 WGG8XrPSOMTO8Ga4d62PdrmXA2ZNbJXw+i6DxqSSkJYORKU34Mda/3nP7UaZ0/5e 8lVb0xKEMn0yT8zvv0s6q4d365KB9Lju+OwU86Pi+XjPZ6ehqcGNF3Cg1AzavJpW 23rCrlL4c+/hB28du+X4V9q30bI1mYlot3ik2LDpLV92LOa3+nhMhPC0v7jiOQiJ AhwEEAECAAYFAlNb4ScACgkQR0hOUGVtFsf90g//QcWrJC3Q9BKjiDBgIRTe5cbI Jynfk34W1X7pMecnJYOutIvwM5CbCp052uYeVps/KjScwziEVV2f6nnsKE76mxRO yWQhiXY2RRoc6gI4toX4qWpe3BiH6UFS1t2B9YkJLI21vcc4KBAFg9Gv26Wsm3c9 gbUWf0gppoZvqPFb1AqpblBSj/gB7Y7De8seirJOIt6g5lBEH+O2458Ugfwyhk7j ZGZnzH1doFwMYZ7uuF6gNHANHNJ17dd8rS8aBRohJ0LFFKV0GI5wkvUc/VTrO5lw s9zAGwbvGlpA4hICbFAbUGCP+MCH/FXs2pfEIvAR6cmPHOEDYqSN9tYI1/kESRr2 4JES1QuiZpsW4F70JW+a9OADDjfgnmMh7XnPUS+wzMvkoszNySaBJjooq9NBk2gk kJSoNIsulKjaQFa61YKH8jimARqLlp0Gloe1ZmzQBd6EDpMBJ1UgFjQstEg/8a5f 8/FUTPt+IPzzIr8dv9krVLqRLGb0yjlERWJ6KFUsrWiM+W+mvlIsW/czJ9bsbBXA nZpdyLeRnpmPQ9lgR/r1CALOo0KMwj1FwAKHYhaVDIbrQIVIPHbkz0DuSFPFsQMX G1kYKi1qlKhRDeLDxTtY++KCCX8Myh/Kubc7RroI54hmP++yS/eQ8c/YsDtp93j5 G5wb2w5FAkTwoA2ysm6JAhwEEAECAAYFAlNb4W0ACgkQYFKyrTGmYxx+Cw//VQlZ asdxMMNAAzVRfSnKZIUyQoclffg1fMgXOPV7VEFXndeX0q73xAZ7xOczAGJupPPW j6pNdrBe57yWhvUp5lmJUVpB4hbzzmHXsuQNJ7iyrZpjK/Y2urzBDTDYOuRmyeG7 93f1C3wHoamUeWW811O5F6nqlzCQAVhubR7c9kRYZSzmoP0YlwZd2uHxq7MjPtlz 2WSmmRQCLq97p65S8wHZaJoJY6B50WH9x/0BYbZgRFN4GnuPOY6VBK1xWhfPRAR3 aJqhhjyDBvJYGiZaoZHeCdKwUrLIJA5P3hanX6+I4VBO1m/NvReQAMav6DVrLs/z ESN2ohNmkli1WUxEpDVDTX8YelxwTY/YVbbzIonhRwK7X6w0QBSmTRgItlJumc7O QoKm6H5yrDe58QFzDpG8NWUsKcFIcYSgNCpCVB1vHNHJ65LwH64nrseF4ZlZn/cO Xktf6UqN0V0qFK5WDBsOqc8MVz34rQdPeJ0UcXtSn35i5qi2X4JriffzSks8i4j6 soGOXP6E/gtoeVc5T4OYPIryUudnQTgu/idDCHymYvCdJx2tVNTSJJJ+xo5w+XaD ew60ML1TVk9NZXVuvZgC3ohyubtahkJQEoakqAJPErSKlA1kWT2JTbprpv6g3Ymn PlAr8dU96L9DiaxgJX7JY6D+uByhB41G5JB4D6SJAhwEEAECAAYFAlNb4YEACgkQ Y4R7S4OTDwyQxw/9EKghNHyTDjhwm+0NcsdLO7NRhM0O29Fa1nBfsmoB2SmDwBjR 6LR8JAqBFAz287+Awg0XIQemxAmtrgr9jK998qllwD6vR0cQAbTTNiT3tQ9DefOo fkXlq2oQM4M5nxjeM7CO1Crkfo7bnRzZR3f+YJSx5sruYih6in4NDoBhaZDGLHxq uWJr0pAGOfdNWzNtRpFV6H8s72mlVp17+2xS5dDtWjLBMkOiIjpxv9XcRgTkP1K+ SYZjRQc+3J9H/0zxMQKNGPdZygQlIyBQEpK5nqLgaUMs0yqgGORUZLmNRZw/Wf5z meaglW9y6vC2FbkQDHqLjqGb7J4N3JNpGKNrLFKoiCcuv2KqNf0ZdCCDdYPRxMAl byDNXWkD0/j6n+P6pub9+irr1ChEuL82Cnoz49Y+ZztI0aYhZde6robTwhi4MNsk t38ZwbHNbhAI6tD/YMDIwsFOJ7YYTMVksxeHj6+5CqXq7TJoGuMMweAbM8jSw8F0 4vfy0I7QeSWx+elZY0WPpemUiEzIm3Cz0kNinOZSH03OKl9+l7B2uLkWLgnw2PLb LvXrZ9kZQ2hl4iCnOzZLHgCiFT1AHMqOIQe/Kw/aFKiXF4rUU3XIYIo7NHTIn0Xg AO+zTA48eXe2pjvi5oA5AsnFN5W2Egf85BMyVRQCGPzzP1tpDlxX5Rfq3by5Ag0E U1vL9gEQALepCHnG2SPqTJF3NMpKNKXhFvFafuweDO/RUR97vaQte6m5wj5kNsRR 8Nnl4DBhGcZ+N2PT+ANqkaJ3Dj8xnaJX7rVCN5atNV9w+gNI1c21NlTE6hp70pzQ c7krvHoLqV5bZqKnMFEh5sQe0LkjWrxMhG6peE8Rk8jtpUIiBXoR3rXMU0Ndxmrf +b/VbIYhyipd4wNoE1hCwGHEJOdcWkLoo27v9G4oKH597SnhEOjC+kSd6dohMUFK YqUyrxcb1/wHbtIKX4vYG3hGobL+IUSN33YP6iO4ObgUvOl/CerGvKbFPpkrVaLU RoIxUOd4tPSBMx5nksK3Vve/PDMvnm4eWbhWfFzliv9pl4L57MKgY5TOwFA8yd/y Sx7MT3xtZLMPe99v7eFepEJohZoarxBiTOukT7TFQAwzheCHmqWjW0C6BZIw/9QJ R+Pj0WJmPktXE7xauZ1pRlhtP/mnsu+YNvkwv03dDd0iMWLpP3pBJLq3llh68w8F AK22ppJiB8QUvBs2sSCw4BGio2BpND1dTx/IXlEZeM4Wsid6pRHqqxm5i9Sb9w2M KvRJXUiFKa1ViFSYeMEG/NDwJ8GyEA40w9fEW10eDZ41DwxWV9fk7gvBfpX32zGO cW9AFO3qYl4bX8vbrc2ePRsozZ6wkt0O3z2pvUg2oXBz1AUsexuDABEBAAGJAh8E GAECAAkFAlNby/YCGwwACgkQKjI0DOyMlJJ57w//VI9cwZKl3h8czdY9VpUc83Ai uy/ZqJj5XGbQypbYMW4akzLVv0bsjjPKCUhMOdJUbA7vxVd78RUZ05HMJboVlKNE eDHR67Eh3M6yf4yFc7jtkL/24LdSFnB6TN2+9PitLVLTMonmfMBeooMG+9qwdppn /3e6iM7qJffq5ycW67F0Mf8oKq57cRKcu/xaHrscKEvBw9xFepEB8jrrUVw5pBQo QxLnvXHLUgal28RhFyB1WSGr1ls6c7iP5+sFpDIEflMqePQNUt4VfEsFFJ8Es7NG fFatzGGjR2vj+RlL2WcO6SvOe85YJZBGsmy8LXW63Vr4YYpBv/PcgN6btLw9EDIh h2kvVl9Er0FOI61gCIL197Igbp6pO3+b2evU/UZGZa2EPaGRcl6K9zGFvHFnWLTH Wu1sZl2/HnWjgXiVuRJ6lo8mnR4Dft8rcusYLFaR7s8xcySpkKn8YGS7pOvDzkhA 5nruu/71Zlf+jIqO76Kj9El1Pnvtycf5kaZbZIpUT6VHikDA60zJ62E4FGoszOWJ 5i1DXRR723mdcDPpn45s/gdYx3x2JLaU33b0waHBtSBMXYnZU6YsA2cVThDMYFg6 8B3mEPdCTAV/FZoC6HSUCmn2a+xVZIfXV4jVa1Lm2Rnya7vFTcGqQtICZf+KELN4 g6+R8KxR+jJttVV0mq65Ag0EU1vMPAEQAOQtgB6kb/uj05nagloSloZh8BYhtRB9 laPh+xKKPNEbUaUEbwincA7uoHzD0/W45KU6dAFwhyr8Pf5I3MuqQYAU+/L0jFvo bSf5c9F4T+5yrDhqWAx3igIWD3b+tSQ4+VbypTbo85b34IM0dGDeYkCTu29udAG1 xX6BJyWpgH9DTzOYvPx21mOziflu3fKyZa80b6c7uLd4QvPIOtLtNc5ommJkAdid NmuPYQiIUVSx1hpT8XZ0r3WE6YLPLqkbdg+ZRRVztOvstdr3xUtmPchRtNoRpk4Q T16XchRQ5jkqpDQvXUAdIOQfQ/M2oPqiFzZHDoUC/Ay/yaxOgQZRevq3JUIY3ZZE EW6IY8TJ/H7FpIKn5WK/b2ETbWVCwWL0fikUKPc4gBizX4ToUT1a+gV8CLp94ZqW Jru4jClpbe/T7lQVlXRsBzn/PK4a8bnb0iZGDcETNfHQ7x4MhkftVlpwVR23i8d7 9LWZc6sYBU8xDPT9w8PrBp6Bqu1QsuYVVZJZ4WQ2v3IcjeebDxSyLgRHnfpFG+D5 e9BuDc10Mvqe4vqwiKTVfCTRtUpPy3mg5m+gnkIIC2hVJQyyhrDk27o5uJauRg2e a/duZliKsv0VLEw+6Gla32dH9CW89HJv5XU8TaGHse2m1Ijywpe/4ffmN5cxYmPd 0O3YtTwZ20F3ABEBAAGJBEQEGAECAA8FAlNbzDwCGwIFCRLMAwACKQkQKjI0DOyM lJLBXSAEGQECAAYFAlNbzDwACgkQ9DgDo0namdXNqxAA4dYHugrFqiddTmo9N6GJ vDUaVztD2jHCZRVgjrWEE9pLZ68NgOauqTuifhgunY4VGl8cTcKBSn2AFrDVca1f 9LtXExMBnOfjaucXqrIqYtoVRofO63FBe6dVLxTsEVj+XprCgeL6BJeIOC2uD850 Crzlv4BRVxW+YvTd63GtjwLR/T7bHZPfzvDRZdwFSuOdx0qqalC5pIeOV/bOzLEM 0Vg4J4vFBy/YntGwrkhCgIzSb+J55TRIIWgMOQbD2j4mRnzdviRUr+72dtMBqK01 D7jPft4SASf09+2qyDcrcUzf6qPFCyaSfvx9/4ECdU6wSnnlogo/AhjXN8lyi5qe uliGhGfCNE6A7VunWfbJj4JSD7iGPYeDYgyGHQPJQSJ5MRtmw0px1lvHy4ZisoxY y0ZREDchtVlk60u6GqBYgINSaGURcG/WdZ4HfHbML16fk7HlLEDeu9SXJBS1m/RT K+W9daIHVFDtfoWFOMj5XCMUdSyIH2mczhRph9X7wLo1/hwu7UG2yv4KXXYzpNYU LptBMamfm6DACnbzhr9AKE4pzyu7Eslvrx4FQWp7Jmqc96Aj8VcCzrIMqmV9KhEU 4yPlN9uSsSarkhjH30TjZCBWbWbxoiqmyHXDOTd7EXrMaqZ7c6AB9l5frgxiWzva 9gp14qaE06lViIqj6XDa0NxciA//a/uIyQYiko1dlVd/f2lEGh1OUSibgeNmnLks oGtbqZCHiuWNHXBAnCSRzUFL3xNz96Neht+H2joftl401/7AZiKahJQFbpZKYaX6 V82vU3KX0Ef0kpNLlr57orLoGQo/k/y02LvVV7QJHK9JmEeYzkKBBRuao7L7T1O4 SZGgr44VEhF8MHywECOdAP9dTtXBrP0k1e0JtU6ZfS71qEiYC18hfpwM9D0+8PoI e7Zb1O7X7XyyTbBw+646iLximlxNP6NSO1jnvkjs0tsKq6z+7hHB1MrtVuErJtrf yKLwPqR0NYfglY5MZuasZ4+twL7ZwJUfgq+3toJMK+q2A7wL55Mouzre9QAlXOCP FH7g8+G74RPmJwTqDzLR4Wb5i7rZEJnlPkgjOcaoRuMGB/+u9gKcF73k32113yJJ WvpKVI+XtcPGgvSTJXIQ/XdOcvweQfUIfKVXC6bcYZm4k2MacRDek7OsHOopxs+B I++qRDlyW3gvOA2A2ayXDBWDJzceLUjNu4fZxg+mcp/SrpqHEppeAnyQzffZMjNm 1g/LzfRY8PsQruOjnI6zhaqz1UPF5JuGx5ZM9lEzcRgCcrsJxVo2npG6lZ4kK4tP 9HwyrYwLiUXPhwaPMh5OLfe4TTCdzr8D//sQUwIYyDDqSLOcqa+kq/vL6AXsXFpF r+ovOrU= =DSgN -----END PGP PUBLIC KEY BLOCK----- """
60762
exports.lookup = # The Merkle Signing key that's in use by default by the server. # Include the key in case the user doesn't have it. "<KEY>" : """ -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v1.4.14 (GNU/Linux) <KEY> t3<KEY> -----END PGP PUBLIC KEY BLOCK----- """
true
exports.lookup = # The Merkle Signing key that's in use by default by the server. # Include the key in case the user doesn't have it. "PI:KEY:<KEY>END_PI" : """ -----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v1.4.14 (GNU/Linux) PI:KEY:<KEY>END_PI t3PI:KEY:<KEY>END_PI -----END PGP PUBLIC KEY BLOCK----- """
[ { "context": "clientID: '123-456-789',\n# clientSecret: 'shhh-its-a-secret'\n# callbackURL: 'https://www.example.net/", "end": 1558, "score": 0.9942877292633057, "start": 1541, "tag": "KEY", "value": "shhh-its-a-secret" } ]
src/strategy.coffee
trevorwang/passport-teambition
0
###* # Module dependencies. ### util = require('util') OAuth2Strategy = require('passport-oauth2') Profile = require('./profile') InternalOAuthError = require('passport-oauth2').InternalOAuthError ###* # Inherit from `OAuth2Strategy`. ### ###* # `Strategy` constructor. # # The teambition authentication strategy authenticates requests by delegating to # teambition using the OAuth 2.0 protocol. # # Applications must supply a `verify` callback which accepts an `accessToken`, # `refreshToken` and service-specific `profile`, and then calls the `done` # callback supplying a `user`, which should be set to `false` if the # credentials are not valid. If an exception occured, `err` should be set. # # Options: # - `clientID` your teambition application's Client ID # - `clientSecret` your teambition application's Client Secret # - `callbackURL` URL to which teambition will redirect the user after granting authorization # - `scope` array of permission scopes to request. valid scopes include: # 'user', 'public_repo', 'repo', 'gist', or none. # (see http://developer.teambition.com/v3/oauth/#scopes for more info) # — `userAgent` All API requests MUST include a valid User Agent string. # e.g: domain name of your application. # (see http://developer.teambition.com/v3/#user-agent-required for more info) # # Examples: # # passport.use(new teambitionStrategy({ # clientID: '123-456-789', # clientSecret: 'shhh-its-a-secret' # callbackURL: 'https://www.example.net/auth/teambition/callback', # userAgent: 'myapp.com' # }, # function(accessToken, refreshToken, profile, done) { # User.findOrCreate(..., function (err, user) { # done(err, user); # }); # } # )); # # @param {Object} options # @param {Function} verify # @api public ### Strategy = (options, verify) -> options = options or {} options.authorizationURL = options.authorizationURL or 'https://account.teambition.com/oauth2/authorize' options.tokenURL = options.tokenURL or 'https://account.teambition.com/oauth2/access_token' options.scopeSeparator = options.scopeSeparator or ',' options.customHeaders = options.customHeaders or {} if !options.customHeaders['User-Agent'] options.customHeaders['User-Agent'] = options.userAgent or 'passport-teambition' OAuth2Strategy.call this, options, verify @name = 'teambition' @_userProfileURL = options.userProfileURL or 'https://api.teambition.com/users/me' @_oauth2.useAuthorizationHeaderforGET true @_oauth2._authMethod = 'OAuth2' return util.inherits Strategy, OAuth2Strategy ###* # Retrieve user profile from teambition. # # This function constructs a normalized profile, with the following properties: # # - `provider` always set to `teambition` # - `id` the user's teambition ID # - `username` the user's teambition username # - `displayName` the user's full name # - `profileUrl` the URL of the profile for the user on teambition # - `emails` the user's email addresses # # @param {String} accessToken # @param {Function} done # @api protected ### Strategy::userProfile = (accessToken, done) -> @_oauth2.get @_userProfileURL, accessToken, (err, body, res) -> json = undefined if err return done(new InternalOAuthError('Failed to fetch user profile', err)) try json = JSON.parse(body) catch ex return done(new Error('Failed to parse user profile')) profile = Profile.parse(json) profile.provider = 'teambition' profile._raw = body profile._json = json done null, profile return return ###* # Expose `Strategy`. ### module.exports = Strategy
35011
###* # Module dependencies. ### util = require('util') OAuth2Strategy = require('passport-oauth2') Profile = require('./profile') InternalOAuthError = require('passport-oauth2').InternalOAuthError ###* # Inherit from `OAuth2Strategy`. ### ###* # `Strategy` constructor. # # The teambition authentication strategy authenticates requests by delegating to # teambition using the OAuth 2.0 protocol. # # Applications must supply a `verify` callback which accepts an `accessToken`, # `refreshToken` and service-specific `profile`, and then calls the `done` # callback supplying a `user`, which should be set to `false` if the # credentials are not valid. If an exception occured, `err` should be set. # # Options: # - `clientID` your teambition application's Client ID # - `clientSecret` your teambition application's Client Secret # - `callbackURL` URL to which teambition will redirect the user after granting authorization # - `scope` array of permission scopes to request. valid scopes include: # 'user', 'public_repo', 'repo', 'gist', or none. # (see http://developer.teambition.com/v3/oauth/#scopes for more info) # — `userAgent` All API requests MUST include a valid User Agent string. # e.g: domain name of your application. # (see http://developer.teambition.com/v3/#user-agent-required for more info) # # Examples: # # passport.use(new teambitionStrategy({ # clientID: '123-456-789', # clientSecret: '<KEY>' # callbackURL: 'https://www.example.net/auth/teambition/callback', # userAgent: 'myapp.com' # }, # function(accessToken, refreshToken, profile, done) { # User.findOrCreate(..., function (err, user) { # done(err, user); # }); # } # )); # # @param {Object} options # @param {Function} verify # @api public ### Strategy = (options, verify) -> options = options or {} options.authorizationURL = options.authorizationURL or 'https://account.teambition.com/oauth2/authorize' options.tokenURL = options.tokenURL or 'https://account.teambition.com/oauth2/access_token' options.scopeSeparator = options.scopeSeparator or ',' options.customHeaders = options.customHeaders or {} if !options.customHeaders['User-Agent'] options.customHeaders['User-Agent'] = options.userAgent or 'passport-teambition' OAuth2Strategy.call this, options, verify @name = 'teambition' @_userProfileURL = options.userProfileURL or 'https://api.teambition.com/users/me' @_oauth2.useAuthorizationHeaderforGET true @_oauth2._authMethod = 'OAuth2' return util.inherits Strategy, OAuth2Strategy ###* # Retrieve user profile from teambition. # # This function constructs a normalized profile, with the following properties: # # - `provider` always set to `teambition` # - `id` the user's teambition ID # - `username` the user's teambition username # - `displayName` the user's full name # - `profileUrl` the URL of the profile for the user on teambition # - `emails` the user's email addresses # # @param {String} accessToken # @param {Function} done # @api protected ### Strategy::userProfile = (accessToken, done) -> @_oauth2.get @_userProfileURL, accessToken, (err, body, res) -> json = undefined if err return done(new InternalOAuthError('Failed to fetch user profile', err)) try json = JSON.parse(body) catch ex return done(new Error('Failed to parse user profile')) profile = Profile.parse(json) profile.provider = 'teambition' profile._raw = body profile._json = json done null, profile return return ###* # Expose `Strategy`. ### module.exports = Strategy
true
###* # Module dependencies. ### util = require('util') OAuth2Strategy = require('passport-oauth2') Profile = require('./profile') InternalOAuthError = require('passport-oauth2').InternalOAuthError ###* # Inherit from `OAuth2Strategy`. ### ###* # `Strategy` constructor. # # The teambition authentication strategy authenticates requests by delegating to # teambition using the OAuth 2.0 protocol. # # Applications must supply a `verify` callback which accepts an `accessToken`, # `refreshToken` and service-specific `profile`, and then calls the `done` # callback supplying a `user`, which should be set to `false` if the # credentials are not valid. If an exception occured, `err` should be set. # # Options: # - `clientID` your teambition application's Client ID # - `clientSecret` your teambition application's Client Secret # - `callbackURL` URL to which teambition will redirect the user after granting authorization # - `scope` array of permission scopes to request. valid scopes include: # 'user', 'public_repo', 'repo', 'gist', or none. # (see http://developer.teambition.com/v3/oauth/#scopes for more info) # — `userAgent` All API requests MUST include a valid User Agent string. # e.g: domain name of your application. # (see http://developer.teambition.com/v3/#user-agent-required for more info) # # Examples: # # passport.use(new teambitionStrategy({ # clientID: '123-456-789', # clientSecret: 'PI:KEY:<KEY>END_PI' # callbackURL: 'https://www.example.net/auth/teambition/callback', # userAgent: 'myapp.com' # }, # function(accessToken, refreshToken, profile, done) { # User.findOrCreate(..., function (err, user) { # done(err, user); # }); # } # )); # # @param {Object} options # @param {Function} verify # @api public ### Strategy = (options, verify) -> options = options or {} options.authorizationURL = options.authorizationURL or 'https://account.teambition.com/oauth2/authorize' options.tokenURL = options.tokenURL or 'https://account.teambition.com/oauth2/access_token' options.scopeSeparator = options.scopeSeparator or ',' options.customHeaders = options.customHeaders or {} if !options.customHeaders['User-Agent'] options.customHeaders['User-Agent'] = options.userAgent or 'passport-teambition' OAuth2Strategy.call this, options, verify @name = 'teambition' @_userProfileURL = options.userProfileURL or 'https://api.teambition.com/users/me' @_oauth2.useAuthorizationHeaderforGET true @_oauth2._authMethod = 'OAuth2' return util.inherits Strategy, OAuth2Strategy ###* # Retrieve user profile from teambition. # # This function constructs a normalized profile, with the following properties: # # - `provider` always set to `teambition` # - `id` the user's teambition ID # - `username` the user's teambition username # - `displayName` the user's full name # - `profileUrl` the URL of the profile for the user on teambition # - `emails` the user's email addresses # # @param {String} accessToken # @param {Function} done # @api protected ### Strategy::userProfile = (accessToken, done) -> @_oauth2.get @_userProfileURL, accessToken, (err, body, res) -> json = undefined if err return done(new InternalOAuthError('Failed to fetch user profile', err)) try json = JSON.parse(body) catch ex return done(new Error('Failed to parse user profile')) profile = Profile.parse(json) profile.provider = 'teambition' profile._raw = body profile._json = json done null, profile return return ###* # Expose `Strategy`. ### module.exports = Strategy
[ { "context": "# Toolbar.coffee\n# Tomasz (Tomek) Zemla\n# tomek@datacratic.com\n\n# Application", "end": 25, "score": 0.9989516735076904, "start": 19, "tag": "NAME", "value": "Tomasz" }, { "context": "# Toolbar.coffee\n# Tomasz (Tomek) Zemla\n# tomek@datacratic.com\n\n# Application t...
src/Toolbar.coffee
SachithDassanayaka/sachithdassanayaka.github.io
0
# Toolbar.coffee # Tomasz (Tomek) Zemla # tomek@datacratic.com # Application top of the window menu toolbar. Utility = require('./Utility.coffee') Panel = require('./Panel.coffee') Palette = require('./Palette.coffee') class Toolbar extends Panel # E V E N T S @EVENT_MENU : "EVENT_MENU" @EVENT_INFO : "EVENT_INFO" @EVENT_PERSPECTIVE : "EVENT_PERSPECTIVE" @EVENT_ORTHOGRAPHIC : "EVENT_ORTHOGRAPHIC" @EVENT_DUAL : "EVENT_DUAL" @EVENT_RESET : "EVENT_RESET" @EVENT_CLEAR : "EVENT_CLEAR" @EVENT_BOX : "EVENT_BOX" @EVENT_VIEWPORT : "EVENT_VIEWPORT" @EVENT_SELECT : "EVENT_SELECT" @EVENT_VIEW_TOP : "EVENT_VIEW_TOP" @EVENT_VIEW_FRONT : "EVENT_VIEW_FRONT" @EVENT_VIEW_SIDE : "EVENT_VIEW_SIDE" @EVENT_SPIN_LEFT : "EVENT_SPIN_LEFT" @EVENT_SPIN_STOP : "EVENT_SPIN_STOP" @EVENT_SPIN_RIGHT : "EVENT_SPIN_RIGHT" @EVENT_ANIMATE : "EVENT_ANIMATE" # M E M B E R S dispatcher : null # map of IDs and event handlers # C O N S T R U C T O R constructor : (id) -> super(id) @createDispatcher() for item in @dispatcher $(item.id).click({ type : item.type }, @onClick) document.addEventListener('keydown', @onKeyDown, false) @initialize() # E V E N T H A N D L E R S # Called when key pressed. onKeyDown : (event) => # console.log event.keyCode + " : " + event.shiftKey modifier = Utility.NO_KEY # default if event.shiftKey then modifier = Utility.SHIFT_KEY for item in @dispatcher if (item.key is event.keyCode) and (item.modifier is modifier) then @notify(item.type) onClick : (event) => @notify(event.data.type) # M E T H O D S # Create centralized event registration and dispatch map createDispatcher : => # NOTE key == 0 means no shortcut assigned @dispatcher = [ { id : "#menuButton", key : 77, modifier : Utility.NO_KEY, type : Toolbar.EVENT_MENU }, { id : "#infoButton", key : 73, modifier : Utility.NO_KEY, type : Toolbar.EVENT_INFO }, { id : "#perspectiveButton", key : 80, modifier : Utility.NO_KEY, type : Toolbar.EVENT_PERSPECTIVE }, { id : "#orthographicButton", key : 79, modifier : Utility.NO_KEY, type : Toolbar.EVENT_ORTHOGRAPHIC }, { id : "#dualButton", key : 68, modifier : Utility.NO_KEY, type : Toolbar.EVENT_DUAL }, { id : "#resetButton", key : 82, modifier : Utility.NO_KEY, type : Toolbar.EVENT_RESET }, { id : "#clearButton", key : 67, modifier : Utility.NO_KEY, type : Toolbar.EVENT_CLEAR }, { id : "#boxButton", key : 66, modifier : Utility.NO_KEY, type : Toolbar.EVENT_BOX }, { id : "#viewportButton", key : 86, modifier : Utility.NO_KEY, type : Toolbar.EVENT_VIEWPORT }, { id : "#selectButton", key : 83, modifier : Utility.NO_KEY, type : Toolbar.EVENT_SELECT }, { id : "#viewTopButton", key : 49, modifier : Utility.NO_KEY, type : Toolbar.EVENT_VIEW_TOP }, { id : "#viewFrontButton", key : 50, modifier : Utility.NO_KEY, type : Toolbar.EVENT_VIEW_FRONT }, { id : "#viewSideButton", key : 51, modifier : Utility.NO_KEY, type : Toolbar.EVENT_VIEW_SIDE }, { id : "#spinLeftButton", key : 37, modifier : Utility.NO_KEY, type : Toolbar.EVENT_SPIN_LEFT }, { id : "#spinStopButton", key : 32, modifier : Utility.NO_KEY, type : Toolbar.EVENT_SPIN_STOP }, { id : "#spinRightButton", key : 39, modifier : Utility.NO_KEY, type : Toolbar.EVENT_SPIN_RIGHT }, { id : "#animateButton", key : 65, modifier : Utility.NO_KEY, type : Toolbar.EVENT_ANIMATE }, ] initialize : => @setButtonSelected("#menuButton", true) @setButtonSelected("#infoButton", true) @setButtonSelected("#perspectiveButton", false) @setButtonSelected("#orthographicButton", false) @setButtonSelected("#dualButton", true) @setButtonSelected("#boxButton", true) @setButtonSelected("#viewportButton", true) @setButtonSelected("#selectButton", false) @setButtonSelected("#viewTopButton", true) @setButtonSelected("#viewFrontButton", false) @setButtonSelected("#viewSideButton", false) @setButtonSelected("#spinLeftButton", false) @setButtonSelected("#spinStopButton", true) @setButtonSelected("#spinRightButton", false) @setButtonSelected("#animateButton", false) setButtonSelected : (id, selected) => color = Palette.BUTTON.getStyle() if selected then color = Palette.BUTTON_SELECTED.getStyle() $(id).css('color', color) blinkButton : (id) => @setButtonSelected(id, true) window.setTimeout(@unblinkButton, 200, id) unblinkButton : (id) => console.log "Toolbar.unblinkButton " + id @setButtonSelected(id, false) setMenuButtonSelected : (selected) => @setButtonSelected("#menuButton", selected) setInfoButtonSelected : (selected) => @setButtonSelected("#infoButton", selected) setCameraButtonSelected : (selected1, selected2, selected3) => @setButtonSelected("#perspectiveButton", selected1) @setButtonSelected("#orthographicButton", selected2) @setButtonSelected("#dualButton", selected3) blinkResetButton : => @blinkButton("#resetButton") blinkClearButton : => @blinkButton("#clearButton") setBoxButtonSelected : (selected) => @setButtonSelected("#boxButton", selected) setViewportButtonSelected : (selected) => @setButtonSelected("#viewportButton", selected) setSelectButtonSelected : (selected) => @setButtonSelected("#selectButton", selected) setViewButtonSelected : (selected1, selected2, selected3) => @setButtonSelected("#viewTopButton", selected1) @setButtonSelected("#viewFrontButton", selected2) @setButtonSelected("#viewSideButton", selected3) setSpinButtonSelected : (selected1, selected2, selected3) => @setButtonSelected("#spinLeftButton", selected1) @setButtonSelected("#spinStopButton", selected2) @setButtonSelected("#spinRightButton", selected3) setAnimateButtonSelected : (selected) => @setButtonSelected("#animateButton", selected) module.exports = Toolbar
3642
# Toolbar.coffee # <NAME> (<NAME> # <EMAIL> # Application top of the window menu toolbar. Utility = require('./Utility.coffee') Panel = require('./Panel.coffee') Palette = require('./Palette.coffee') class Toolbar extends Panel # E V E N T S @EVENT_MENU : "EVENT_MENU" @EVENT_INFO : "EVENT_INFO" @EVENT_PERSPECTIVE : "EVENT_PERSPECTIVE" @EVENT_ORTHOGRAPHIC : "EVENT_ORTHOGRAPHIC" @EVENT_DUAL : "EVENT_DUAL" @EVENT_RESET : "EVENT_RESET" @EVENT_CLEAR : "EVENT_CLEAR" @EVENT_BOX : "EVENT_BOX" @EVENT_VIEWPORT : "EVENT_VIEWPORT" @EVENT_SELECT : "EVENT_SELECT" @EVENT_VIEW_TOP : "EVENT_VIEW_TOP" @EVENT_VIEW_FRONT : "EVENT_VIEW_FRONT" @EVENT_VIEW_SIDE : "EVENT_VIEW_SIDE" @EVENT_SPIN_LEFT : "EVENT_SPIN_LEFT" @EVENT_SPIN_STOP : "EVENT_SPIN_STOP" @EVENT_SPIN_RIGHT : "EVENT_SPIN_RIGHT" @EVENT_ANIMATE : "EVENT_ANIMATE" # M E M B E R S dispatcher : null # map of IDs and event handlers # C O N S T R U C T O R constructor : (id) -> super(id) @createDispatcher() for item in @dispatcher $(item.id).click({ type : item.type }, @onClick) document.addEventListener('keydown', @onKeyDown, false) @initialize() # E V E N T H A N D L E R S # Called when key pressed. onKeyDown : (event) => # console.log event.keyCode + " : " + event.shiftKey modifier = Utility.NO_KEY # default if event.shiftKey then modifier = Utility.SHIFT_KEY for item in @dispatcher if (item.key is event.keyCode) and (item.modifier is modifier) then @notify(item.type) onClick : (event) => @notify(event.data.type) # M E T H O D S # Create centralized event registration and dispatch map createDispatcher : => # NOTE key == 0 means no shortcut assigned @dispatcher = [ { id : "#menuButton", key : 77, modifier : Utility.NO_KEY, type : Toolbar.EVENT_MENU }, { id : "#infoButton", key : 73, modifier : Utility.NO_KEY, type : Toolbar.EVENT_INFO }, { id : "#perspectiveButton", key : 80, modifier : Utility.NO_KEY, type : Toolbar.EVENT_PERSPECTIVE }, { id : "#orthographicButton", key : 79, modifier : Utility.NO_KEY, type : Toolbar.EVENT_ORTHOGRAPHIC }, { id : "#dualButton", key : 68, modifier : Utility.NO_KEY, type : Toolbar.EVENT_DUAL }, { id : "#resetButton", key : 82, modifier : Utility.NO_KEY, type : Toolbar.EVENT_RESET }, { id : "#clearButton", key : 67, modifier : Utility.NO_KEY, type : Toolbar.EVENT_CLEAR }, { id : "#boxButton", key : 66, modifier : Utility.NO_KEY, type : Toolbar.EVENT_BOX }, { id : "#viewportButton", key : 86, modifier : Utility.NO_KEY, type : Toolbar.EVENT_VIEWPORT }, { id : "#selectButton", key : 83, modifier : Utility.NO_KEY, type : Toolbar.EVENT_SELECT }, { id : "#viewTopButton", key : 49, modifier : Utility.NO_KEY, type : Toolbar.EVENT_VIEW_TOP }, { id : "#viewFrontButton", key : 50, modifier : Utility.NO_KEY, type : Toolbar.EVENT_VIEW_FRONT }, { id : "#viewSideButton", key : 51, modifier : Utility.NO_KEY, type : Toolbar.EVENT_VIEW_SIDE }, { id : "#spinLeftButton", key : 37, modifier : Utility.NO_KEY, type : Toolbar.EVENT_SPIN_LEFT }, { id : "#spinStopButton", key : 32, modifier : Utility.NO_KEY, type : Toolbar.EVENT_SPIN_STOP }, { id : "#spinRightButton", key : 39, modifier : Utility.NO_KEY, type : Toolbar.EVENT_SPIN_RIGHT }, { id : "#animateButton", key : 65, modifier : Utility.NO_KEY, type : Toolbar.EVENT_ANIMATE }, ] initialize : => @setButtonSelected("#menuButton", true) @setButtonSelected("#infoButton", true) @setButtonSelected("#perspectiveButton", false) @setButtonSelected("#orthographicButton", false) @setButtonSelected("#dualButton", true) @setButtonSelected("#boxButton", true) @setButtonSelected("#viewportButton", true) @setButtonSelected("#selectButton", false) @setButtonSelected("#viewTopButton", true) @setButtonSelected("#viewFrontButton", false) @setButtonSelected("#viewSideButton", false) @setButtonSelected("#spinLeftButton", false) @setButtonSelected("#spinStopButton", true) @setButtonSelected("#spinRightButton", false) @setButtonSelected("#animateButton", false) setButtonSelected : (id, selected) => color = Palette.BUTTON.getStyle() if selected then color = Palette.BUTTON_SELECTED.getStyle() $(id).css('color', color) blinkButton : (id) => @setButtonSelected(id, true) window.setTimeout(@unblinkButton, 200, id) unblinkButton : (id) => console.log "Toolbar.unblinkButton " + id @setButtonSelected(id, false) setMenuButtonSelected : (selected) => @setButtonSelected("#menuButton", selected) setInfoButtonSelected : (selected) => @setButtonSelected("#infoButton", selected) setCameraButtonSelected : (selected1, selected2, selected3) => @setButtonSelected("#perspectiveButton", selected1) @setButtonSelected("#orthographicButton", selected2) @setButtonSelected("#dualButton", selected3) blinkResetButton : => @blinkButton("#resetButton") blinkClearButton : => @blinkButton("#clearButton") setBoxButtonSelected : (selected) => @setButtonSelected("#boxButton", selected) setViewportButtonSelected : (selected) => @setButtonSelected("#viewportButton", selected) setSelectButtonSelected : (selected) => @setButtonSelected("#selectButton", selected) setViewButtonSelected : (selected1, selected2, selected3) => @setButtonSelected("#viewTopButton", selected1) @setButtonSelected("#viewFrontButton", selected2) @setButtonSelected("#viewSideButton", selected3) setSpinButtonSelected : (selected1, selected2, selected3) => @setButtonSelected("#spinLeftButton", selected1) @setButtonSelected("#spinStopButton", selected2) @setButtonSelected("#spinRightButton", selected3) setAnimateButtonSelected : (selected) => @setButtonSelected("#animateButton", selected) module.exports = Toolbar
true
# Toolbar.coffee # PI:NAME:<NAME>END_PI (PI:NAME:<NAME>END_PI # PI:EMAIL:<EMAIL>END_PI # Application top of the window menu toolbar. Utility = require('./Utility.coffee') Panel = require('./Panel.coffee') Palette = require('./Palette.coffee') class Toolbar extends Panel # E V E N T S @EVENT_MENU : "EVENT_MENU" @EVENT_INFO : "EVENT_INFO" @EVENT_PERSPECTIVE : "EVENT_PERSPECTIVE" @EVENT_ORTHOGRAPHIC : "EVENT_ORTHOGRAPHIC" @EVENT_DUAL : "EVENT_DUAL" @EVENT_RESET : "EVENT_RESET" @EVENT_CLEAR : "EVENT_CLEAR" @EVENT_BOX : "EVENT_BOX" @EVENT_VIEWPORT : "EVENT_VIEWPORT" @EVENT_SELECT : "EVENT_SELECT" @EVENT_VIEW_TOP : "EVENT_VIEW_TOP" @EVENT_VIEW_FRONT : "EVENT_VIEW_FRONT" @EVENT_VIEW_SIDE : "EVENT_VIEW_SIDE" @EVENT_SPIN_LEFT : "EVENT_SPIN_LEFT" @EVENT_SPIN_STOP : "EVENT_SPIN_STOP" @EVENT_SPIN_RIGHT : "EVENT_SPIN_RIGHT" @EVENT_ANIMATE : "EVENT_ANIMATE" # M E M B E R S dispatcher : null # map of IDs and event handlers # C O N S T R U C T O R constructor : (id) -> super(id) @createDispatcher() for item in @dispatcher $(item.id).click({ type : item.type }, @onClick) document.addEventListener('keydown', @onKeyDown, false) @initialize() # E V E N T H A N D L E R S # Called when key pressed. onKeyDown : (event) => # console.log event.keyCode + " : " + event.shiftKey modifier = Utility.NO_KEY # default if event.shiftKey then modifier = Utility.SHIFT_KEY for item in @dispatcher if (item.key is event.keyCode) and (item.modifier is modifier) then @notify(item.type) onClick : (event) => @notify(event.data.type) # M E T H O D S # Create centralized event registration and dispatch map createDispatcher : => # NOTE key == 0 means no shortcut assigned @dispatcher = [ { id : "#menuButton", key : 77, modifier : Utility.NO_KEY, type : Toolbar.EVENT_MENU }, { id : "#infoButton", key : 73, modifier : Utility.NO_KEY, type : Toolbar.EVENT_INFO }, { id : "#perspectiveButton", key : 80, modifier : Utility.NO_KEY, type : Toolbar.EVENT_PERSPECTIVE }, { id : "#orthographicButton", key : 79, modifier : Utility.NO_KEY, type : Toolbar.EVENT_ORTHOGRAPHIC }, { id : "#dualButton", key : 68, modifier : Utility.NO_KEY, type : Toolbar.EVENT_DUAL }, { id : "#resetButton", key : 82, modifier : Utility.NO_KEY, type : Toolbar.EVENT_RESET }, { id : "#clearButton", key : 67, modifier : Utility.NO_KEY, type : Toolbar.EVENT_CLEAR }, { id : "#boxButton", key : 66, modifier : Utility.NO_KEY, type : Toolbar.EVENT_BOX }, { id : "#viewportButton", key : 86, modifier : Utility.NO_KEY, type : Toolbar.EVENT_VIEWPORT }, { id : "#selectButton", key : 83, modifier : Utility.NO_KEY, type : Toolbar.EVENT_SELECT }, { id : "#viewTopButton", key : 49, modifier : Utility.NO_KEY, type : Toolbar.EVENT_VIEW_TOP }, { id : "#viewFrontButton", key : 50, modifier : Utility.NO_KEY, type : Toolbar.EVENT_VIEW_FRONT }, { id : "#viewSideButton", key : 51, modifier : Utility.NO_KEY, type : Toolbar.EVENT_VIEW_SIDE }, { id : "#spinLeftButton", key : 37, modifier : Utility.NO_KEY, type : Toolbar.EVENT_SPIN_LEFT }, { id : "#spinStopButton", key : 32, modifier : Utility.NO_KEY, type : Toolbar.EVENT_SPIN_STOP }, { id : "#spinRightButton", key : 39, modifier : Utility.NO_KEY, type : Toolbar.EVENT_SPIN_RIGHT }, { id : "#animateButton", key : 65, modifier : Utility.NO_KEY, type : Toolbar.EVENT_ANIMATE }, ] initialize : => @setButtonSelected("#menuButton", true) @setButtonSelected("#infoButton", true) @setButtonSelected("#perspectiveButton", false) @setButtonSelected("#orthographicButton", false) @setButtonSelected("#dualButton", true) @setButtonSelected("#boxButton", true) @setButtonSelected("#viewportButton", true) @setButtonSelected("#selectButton", false) @setButtonSelected("#viewTopButton", true) @setButtonSelected("#viewFrontButton", false) @setButtonSelected("#viewSideButton", false) @setButtonSelected("#spinLeftButton", false) @setButtonSelected("#spinStopButton", true) @setButtonSelected("#spinRightButton", false) @setButtonSelected("#animateButton", false) setButtonSelected : (id, selected) => color = Palette.BUTTON.getStyle() if selected then color = Palette.BUTTON_SELECTED.getStyle() $(id).css('color', color) blinkButton : (id) => @setButtonSelected(id, true) window.setTimeout(@unblinkButton, 200, id) unblinkButton : (id) => console.log "Toolbar.unblinkButton " + id @setButtonSelected(id, false) setMenuButtonSelected : (selected) => @setButtonSelected("#menuButton", selected) setInfoButtonSelected : (selected) => @setButtonSelected("#infoButton", selected) setCameraButtonSelected : (selected1, selected2, selected3) => @setButtonSelected("#perspectiveButton", selected1) @setButtonSelected("#orthographicButton", selected2) @setButtonSelected("#dualButton", selected3) blinkResetButton : => @blinkButton("#resetButton") blinkClearButton : => @blinkButton("#clearButton") setBoxButtonSelected : (selected) => @setButtonSelected("#boxButton", selected) setViewportButtonSelected : (selected) => @setButtonSelected("#viewportButton", selected) setSelectButtonSelected : (selected) => @setButtonSelected("#selectButton", selected) setViewButtonSelected : (selected1, selected2, selected3) => @setButtonSelected("#viewTopButton", selected1) @setButtonSelected("#viewFrontButton", selected2) @setButtonSelected("#viewSideButton", selected3) setSpinButtonSelected : (selected1, selected2, selected3) => @setButtonSelected("#spinLeftButton", selected1) @setButtonSelected("#spinStopButton", selected2) @setButtonSelected("#spinRightButton", selected3) setAnimateButtonSelected : (selected) => @setButtonSelected("#animateButton", selected) module.exports = Toolbar
[ { "context": "###\n# ExifReader 1.0.1\n# http://github.com/mattiasw/exifreader\n# Copyright (C) 2011 Mattias Wallande", "end": 51, "score": 0.8891206383705139, "start": 43, "tag": "USERNAME", "value": "mattiasw" }, { "context": "thub.com/mattiasw/exifreader\n# Copyright (C) 2011 Ma...
studio/node_modules/exif-component/spec/ExifReader.spec.coffee
sajustsmile/twitter-blockchain
3
### # ExifReader 1.0.1 # http://github.com/mattiasw/exifreader # Copyright (C) 2011 Mattias Wallander <mattias@wallander.eu> # Licensed under the GNU Lesser General Public License version 3 or later # See license text at http://www.gnu.org/licenses/lgpl.txt ### ExifReader = require '../src/ExifReader.coffee' ExifReader = ExifReader.ExifReader # Node.js doesn't have DataView. class DataView constructor: (@_data) -> @byteLength = @_data.length getUint8: (offset) -> @_data.readUInt8 offset getUint16: (offset, littleEndian) -> if littleEndian? and littleEndian @_data.readUInt16LE offset else @_data.readUInt16BE offset getUint32: (offset, littleEndian) -> if littleEndian? and littleEndian @_data.readUInt32LE offset else @_data.readUInt32BE offset getInt32: (offset, littleEndian) -> if littleEndian? and littleEndian @_data.readInt32LE offset else @_data.readInt32BE offset describe 'ExifReader', -> getArrayBuffer = (data) -> buffer = new Buffer(data.length) for i in [0...data.length] buffer[i] = data.charCodeAt i buffer getDataView = (data) -> dataView = new DataView getArrayBuffer(data) beforeEach -> @exif = new ExifReader @exif._tags = {} @exif._littleEndian = false @exif._tiffHeaderOffset = 0 it 'should fail for too short data buffer', -> exif = @exif exif._dataView = getDataView '\x00' expect(-> exif._checkImageHeader()).toThrow(new Error 'Invalid image format') it 'should accept well-formed header of JPEG image data', -> @exif._dataView = getDataView '\xff\xd8\xff\xe100Exif\x00\x00' @exif._checkImageHeader() it 'should fail for invalid image format', -> exif = @exif exif._dataView = getDataView '------------' expect(-> exif._checkImageHeader()).toThrow(new Error 'Invalid image format') it 'should fail when no Exif identifier for APP1', -> exif = @exif exif._dataView = getDataView '\xff\xd8\xff\xe1--------' expect(-> exif._checkImageHeader()).toThrow(new Error 'No Exif data') it 'should handle APP2 markers', -> @exif._dataView = getDataView '\xff\xd8\xff\xe0\x00\x07JFIF\x00\xff\xe2\x00\x07XXXX\x00\xff\xe0\x00\x07JFXX\x00\xff\xe1\x47\x11Exif\x00\x00' @exif._checkImageHeader() expect(@exif._tiffHeaderOffset).toEqual 39 it 'should handle JFIF APP0 markers', -> @exif._dataView = getDataView '\xff\xd8\xff\xe0\x00\x07JFIF\x00\xff\xe1\x47\x11Exif\x00\x00' @exif._checkImageHeader() expect(@exif._tiffHeaderOffset).toEqual 21 it 'should handle JFXX APP0 markers', -> @exif._dataView = getDataView '\xff\xd8\xff\xe0\x00\x07JFIF\x00\xff\xe0\x00\x07JFXX\x00\xff\xe1\x47\x11Exif\x00\x00' @exif._checkImageHeader() expect(@exif._tiffHeaderOffset).toEqual 30 it 'should handle unknown high ID APP markers', -> @exif._dataView = getDataView '\xff\xd8\xff\xea\x00\x07XXXX\x00\xff\xe1\x47\x11Exif\x00\x00' @exif._checkImageHeader() expect(@exif._tiffHeaderOffset).toEqual 21 it 'should handle reversed order of JFIF-Exif hybrid', -> @exif._dataView = getDataView '\xff\xd8\xff\xe1\x00\x08Exif\x00\x00\xff\xe0\x00\x07JFIF\x00' @exif._checkImageHeader() expect(@exif._tiffHeaderOffset).toEqual 12 it 'should fail gracefully for faulty APP markers', -> exif = @exif exif._dataView = getDataView '\xff\xd8\xfe\xdc\x00\x6fJFIF\x65\x01\x01\x01\x00\x48' expect(-> exif._checkImageHeader() exif._setByteOrder() ).toThrow(new Error 'No Exif data') it 'should find byte order data', -> @exif._dataView = getDataView '\xff\xd8\xff\xe100Exif\x00\x00\x49\x49' @exif._checkImageHeader() @exif._setByteOrder() expect(@exif._littleEndian).toBeTruthy() it 'should set correct byte order for litte endian data', -> @exif._dataView = getDataView '\x49\x49' @exif._setByteOrder() expect(@exif._littleEndian).toBeTruthy() it 'should set correct byte order for big endian data', -> @exif._dataView = getDataView '\x4d\x4d' @exif._setByteOrder() expect(@exif._littleEndian).toBeFalsy() it 'should not allow illegal byte order value', -> exif = @exif exif._dataView = getDataView '\x00\x00' expect(-> exif._setByteOrder()).toThrow(new Error 'Illegal byte order value. Faulty image.') it 'should correctly read offset of 0th IFD for little endian data', -> @exif._dataView = getDataView '\x49\x49\x00\x2a\x08\x00\x00\x00' @exif._setByteOrder() expect(@exif._getIfdOffset(0)).toEqual 8 it 'should correctly read offset of 0th IFD for big endian data', -> @exif._dataView = getDataView '\x4d\x4d\x00\x2a\x00\x00\x00\x08' @exif._setByteOrder() expect(@exif._getIfdOffset(0)).toEqual 8 it 'should be able to read a byte', -> @exif._dataView = getDataView '\x42' expect(@exif._getByteAt(0)).toEqual 0x42 it 'should be able to read an ASCII text', -> @exif._dataView = getDataView 'String\x00' expect(@exif._getAsciiAt(0)).toEqual 'S'.charCodeAt(0) it 'should be able to read a little endian short', -> @exif._dataView = getDataView '\x11\x47' @exif._littleEndian = true expect(@exif._getShortAt(0)).toEqual 0x4711 it 'should be able to read a big endian short', -> @exif._dataView = getDataView '\x47\x11' @exif._littleEndian = false expect(@exif._getShortAt(0)).toEqual 0x4711 it 'should be able to read a little endian long', -> @exif._dataView = getDataView '\x45\x44\x43\x42' @exif._littleEndian = true expect(@exif._getLongAt(0)).toEqual 0x42434445 it 'should be able to read a big endian long', -> @exif._dataView = getDataView '\x42\x43\x44\x45' @exif._littleEndian = false expect(@exif._getLongAt(0)).toEqual 0x42434445 it 'should be able to read a little endian rational', -> @exif._dataView = getDataView '\x45\x44\x43\x42\x49\x48\x47\x46' @exif._littleEndian = true expect(@exif._getRationalAt(0)).toEqual 0x42434445/0x46474849 it 'should be able to read a big endian rational', -> @exif._dataView = getDataView '\x42\x43\x44\x45\x46\x47\x48\x49' @exif._littleEndian = false expect(@exif._getRationalAt(0)).toEqual 0x42434445/0x46474849 it 'should be able to read an undefined', -> @exif._dataView = getDataView '\x42' expect(@exif._getUndefinedAt(0)).toEqual 0x42 it 'should be able to read a little endian slong', -> @exif._dataView = getDataView '\xbe\xff\xff\xff' @exif._littleEndian = true expect(@exif._getSlongAt(0)).toEqual -0x42 it 'should be able to read a big endian slong', -> @exif._dataView = getDataView '\xff\xff\xff\xbe' @exif._littleEndian = false expect(@exif._getSlongAt(0)).toEqual -0x42 it 'should be able to read a little endian srational', -> @exif._dataView = getDataView '\xbe\xff\xff\xff\x49\x48\x47\x46' @exif._littleEndian = true expect(@exif._getSrationalAt(0)).toEqual -0x42/0x46474849 it 'should be able to read a big endian srational', -> @exif._dataView = getDataView '\xff\xff\xff\xbe\x46\x47\x48\x49' @exif._littleEndian = false expect(@exif._getSrationalAt(0)).toEqual -0x42/0x46474849 it 'should be able to get ASCII value', -> expect(@exif._getAsciiValue(['S'.charCodeAt(0), 't'.charCodeAt(0), 'r'.charCodeAt(0), 'i'.charCodeAt(0), 'n'.charCodeAt(0), 'g'.charCodeAt(0), 0x00]).join('')).toEqual 'String\x00' it 'should be able to get IFD offset', -> @exif._dataView = getDataView '\x00\x00\x00\x00\x00\x2a\x47\x11\x48\x12' @exif._tiffHeaderOffset = 2 expect(@exif._getIfdOffset()).toEqual @exif._tiffHeaderOffset + 0x47114812 it 'should be able to read a one-field IFD', -> # field count + field @exif._dataView = getDataView '\x00\x01' + '\x47\x11\x00\x01\x00\x00\x00\x01\x42\x00\x00\x00' @exif._tagNames['0th'][0x4711] = 'MyExifTag' @exif._readIfd '0th', 0 expect(@exif.getTagDescription('MyExifTag')).toEqual 0x42 it 'should be able to read a multi-field IFD', -> # field count + 1st field + 2nd field @exif._dataView = getDataView('\x00\x02' + '\x47\x11\x00\x01\x00\x00\x00\x01\x42\x00\x00\x00' + '\x47\x12\x00\x01\x00\x00\x00\x01\x43\x00\x00\x00') @exif._tagNames['0th'][0x4711] = 'MyExifTag0' @exif._tagNames['0th'][0x4712] = 'MyExifTag1' @exif._readIfd '0th', 0 expect(@exif.getTagDescription('MyExifTag0')).toEqual 0x42 expect(@exif.getTagDescription('MyExifTag1')).toEqual 0x43 it 'should be able to read short ASCII tag', -> @exif._tagNames['0th'][0x4711] = 'MyAsciiTag' @exif._dataView = getDataView '\x47\x11\x00\x02\x00\x00\x00\x04\x41\x42\x43\x00' expect(@exif._readTag('0th', 0).description).toEqual 'ABC' it 'should be able to read long ASCII tag', -> @exif._tagNames['0th'][0x4711] = 'MyAsciiTag' @exif._dataView = getDataView '\x47\x11\x00\x02\x00\x00\x00\x06\x00\x00\x00\x0c\x41\x42\x43\x44\x45\x00' expect(@exif._readTag('0th', 0).description).toEqual 'ABCDE' it 'should return undefined value for undefined tag names', -> exif = @exif expect(exif.getTagValue('MyUndefinedTagName')).toBeUndefined() it 'should return undefined description for undefined tag names', -> exif = @exif expect(exif.getTagDescription('MyUndefinedTagName')).toBeUndefined() # Parsing tag descriptions. getOrientationView = (o) -> getDataView('\x01\x12\x00\x03\x00\x00\x00\x01\x00' + o + '\x00\x00') it 'should report correct description for Orientation', -> @exif._dataView = getOrientationView '\x01' expect(@exif._readTag('0th', 0).description).toEqual 'top-left' @exif._dataView = getOrientationView '\x02' expect(@exif._readTag('0th', 0).description).toEqual 'top-right' @exif._dataView = getOrientationView '\x03' expect(@exif._readTag('0th', 0).description).toEqual 'bottom-right' @exif._dataView = getOrientationView '\x04' expect(@exif._readTag('0th', 0).description).toEqual 'bottom-left' @exif._dataView = getOrientationView '\x05' expect(@exif._readTag('0th', 0).description).toEqual 'left-top' @exif._dataView = getOrientationView '\x06' expect(@exif._readTag('0th', 0).description).toEqual 'right-top' @exif._dataView = getOrientationView '\x07' expect(@exif._readTag('0th', 0).description).toEqual 'right-bottom' @exif._dataView = getOrientationView '\x08' expect(@exif._readTag('0th', 0).description).toEqual 'left-bottom' it 'should report correct description for YCbCrPositioning', -> @exif._dataView = getDataView '\x02\x13\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('0th', 0).description).toEqual 'centered' @exif._dataView = getDataView '\x02\x13\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('0th', 0).description).toEqual 'co-sited' it 'should report correct description for ResolutionUnit', -> @exif._dataView = getDataView '\x01\x28\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('0th', 0).description).toEqual 'inches' @exif._dataView = getDataView '\x01\x28\x00\x03\x00\x00\x00\x01\x00\x03\x00\x00' expect(@exif._readTag('0th', 0).description).toEqual 'centimeters' it 'should report correct description for Copyright', -> # A NULL B NULL @exif._dataView = getDataView '\x82\x98\x00\x02\x00\x00\x00\x04\x41\x00\x42\x00' expect(@exif._readTag('0th', 0).description).toEqual 'A; B' it 'should report correct description for ExifVersion', -> @exif._dataView = getDataView '\x90\x00\x00\x07\x00\x00\x00\x04\x30\x32\x32\x30' expect(@exif._readTag('exif', 0).description).toEqual '0220' it 'should report correct description for FlashpixVersion', -> @exif._dataView = getDataView '\xa0\x00\x00\x07\x00\x00\x00\x04\x30\x31\x30\x30' expect(@exif._readTag('exif', 0).description).toEqual '0100' it 'should report correct description for ColorSpace', -> @exif._dataView = getDataView '\xa0\x01\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'sRGB' @exif._dataView = getDataView '\xa0\x01\x00\x03\x00\x00\x00\x01\xff\xff\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Uncalibrated' it 'should report correct description for ComponentsConfiguration', -> @exif._dataView = getDataView '\x91\x01\x00\x07\x00\x00\x00\x04\x34\x35\x36\x30' expect(@exif._readTag('exif', 0).description).toEqual 'RGB' @exif._dataView = getDataView '\x91\x01\x00\x07\x00\x00\x00\x04\x31\x32\x33\x30' expect(@exif._readTag('exif', 0).description).toEqual 'YCbCr' it 'should report correct text for ASCII UserComment', -> @exif._dataView = getDataView '\x92\x86\x00\x07\x00\x00\x00\x0b\x00\x00\x00\x0cASCII\x00\x00\x00ABC' expect(@exif._readTag('exif', 0).description).toEqual 'ABC' it 'should report correct character code for UserComment', -> @exif._dataView = getDataView '\x92\x86\x00\x07\x00\x00\x00\x08\x00\x00\x00\x0cJIS\x00\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual '[JIS encoded text]' @exif._dataView = getDataView '\x92\x86\x00\x07\x00\x00\x00\x08\x00\x00\x00\x0cUNICODE\x00' expect(@exif._readTag('exif', 0).description).toEqual '[Unicode encoded text]' @exif._dataView = getDataView '\x92\x86\x00\x07\x00\x00\x00\x08\x00\x00\x00\x0c\x00\x00\x00\x00\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual '[Undefined encoding]' it 'should report correct description for ExposureProgram', -> @exif._dataView = getDataView '\x88\x22\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Undefined' @exif._dataView = getDataView '\x88\x22\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Manual' @exif._dataView = getDataView '\x88\x22\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Normal program' @exif._dataView = getDataView '\x88\x22\x00\x03\x00\x00\x00\x01\x00\x03\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Aperture priority' @exif._dataView = getDataView '\x88\x22\x00\x03\x00\x00\x00\x01\x00\x04\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Shutter priority' @exif._dataView = getDataView '\x88\x22\x00\x03\x00\x00\x00\x01\x00\x05\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Creative program' @exif._dataView = getDataView '\x88\x22\x00\x03\x00\x00\x00\x01\x00\x06\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Action program' @exif._dataView = getDataView '\x88\x22\x00\x03\x00\x00\x00\x01\x00\x07\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Portrait mode' @exif._dataView = getDataView '\x88\x22\x00\x03\x00\x00\x00\x01\x00\x08\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Landscape mode' @exif._dataView = getDataView '\x88\x22\x00\x03\x00\x00\x00\x01\x00\x09\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Unknown' it 'should report correct description for MeteringMode', -> @exif._dataView = getDataView '\x92\x07\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Average' @exif._dataView = getDataView '\x92\x07\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'CenterWeightedAverage' @exif._dataView = getDataView '\x92\x07\x00\x03\x00\x00\x00\x01\x00\x03\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Spot' @exif._dataView = getDataView '\x92\x07\x00\x03\x00\x00\x00\x01\x00\x04\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'MultiSpot' @exif._dataView = getDataView '\x92\x07\x00\x03\x00\x00\x00\x01\x00\x05\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Pattern' @exif._dataView = getDataView '\x92\x07\x00\x03\x00\x00\x00\x01\x00\x06\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Partial' @exif._dataView = getDataView '\x92\x07\x00\x03\x00\x00\x00\x01\x00\xff\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Other' @exif._dataView = getDataView '\x92\x07\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Unknown' it 'should report correct description for LightSource', -> @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Daylight' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Fluorescent' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x03\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Tungsten (incandescent light)' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x04\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x09\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Fine weather' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x0a\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Cloudy weather' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x0b\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Shade' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x0c\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Daylight fluorescent (D 5700 – 7100K)' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x0d\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Day white fluorescent (N 4600 – 5400K)' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x0e\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Cool white fluorescent (W 3900 – 4500K)' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x0f\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'White fluorescent (WW 3200 – 3700K)' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x11\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Standard light A' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x12\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Standard light B' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x13\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Standard light C' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x14\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'D55' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x15\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'D65' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x16\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'D75' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x17\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'D50' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x18\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'ISO studio tungsten' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\xff\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Other light source' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Unknown' it 'should report correct description for Flash', -> @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash did not fire' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x05\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Strobe return light not detected' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x07\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Strobe return light detected' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x09\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, compulsory flash mode' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x0d\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, compulsory flash mode, return light not detected' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x0f\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, compulsory flash mode, return light detected' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x10\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash did not fire, compulsory flash mode' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x18\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash did not fire, auto mode' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x19\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, auto mode' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x1d\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, auto mode, return light not detected' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x1f\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, auto mode, return light detected' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x20\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'No flash function' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x41\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, red-eye reduction mode' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x45\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, red-eye reduction mode, return light not detected' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x47\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, red-eye reduction mode, return light detected' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x49\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, compulsory flash mode, red-eye reduction mode' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x4d\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x4f\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, compulsory flash mode, red-eye reduction mode, return light detected' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x59\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, auto mode, red-eye reduction mode' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x5d\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, auto mode, return light not detected, red-eye reduction mode' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x5f\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, auto mode, return light detected, red-eye reduction mode' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x60\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Unknown' it 'should report correct description for SubjectArea', -> @exif._dataView = getDataView '\x92\x14\x00\x03\x00\x00\x00\x02\x47\x11\x48\x12' expect(@exif._readTag('exif', 0).description).toEqual 'Location; X: 18193, Y: 18450' @exif._dataView = getDataView '\x92\x14\x00\x03\x00\x00\x00\x03\x00\x00\x00\x0c\x47\x11\x48\x12\x00\x42' expect(@exif._readTag('exif', 0).description).toEqual 'Circle; X: 18193, Y: 18450, diameter: 66' @exif._dataView = getDataView '\x92\x14\x00\x03\x00\x00\x00\x04\x00\x00\x00\x0c\x47\x11\x48\x12\x00\x42\x00\x43' expect(@exif._readTag('exif', 0).description).toEqual 'Rectangle; X: 18193, Y: 18450, width: 66, height: 67' it 'should report correct description for FocalPlaneResolutionUnit', -> @exif._dataView = getDataView '\xa2\x10\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'inches' @exif._dataView = getDataView '\xa2\x10\x00\x03\x00\x00\x00\x01\x00\x03\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'centimeters' it 'should report correct description for SubjectLocation', -> @exif._dataView = getDataView '\xa2\x14\x00\x03\x00\x00\x00\x02\x47\x11\x48\x12' expect(@exif._readTag('exif', 0).description).toEqual 'X: 18193, Y: 18450' it 'should report correct description for SensingMethod', -> @exif._dataView = getDataView '\xa2\x17\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Undefined' @exif._dataView = getDataView '\xa2\x17\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'One-chip color area sensor' @exif._dataView = getDataView '\xa2\x17\x00\x03\x00\x00\x00\x01\x00\x03\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Two-chip color area sensor' @exif._dataView = getDataView '\xa2\x17\x00\x03\x00\x00\x00\x01\x00\x04\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Three-chip color area sensor' @exif._dataView = getDataView '\xa2\x17\x00\x03\x00\x00\x00\x01\x00\x05\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Color sequential area sensor' @exif._dataView = getDataView '\xa2\x17\x00\x03\x00\x00\x00\x01\x00\x07\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Trilinear sensor' @exif._dataView = getDataView '\xa2\x17\x00\x03\x00\x00\x00\x01\x00\x08\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Color sequential linear sensor' it 'should report correct description for FileSource', -> @exif._dataView = getDataView '\xa3\x00\x00\x07\x00\x00\x00\x01\x03\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'DSC' it 'should report correct description for SceneType', -> @exif._dataView = getDataView '\xa3\x01\x00\x07\x00\x00\x00\x01\x01\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'A directly photographed image' it 'should report correct description for CustomRendered', -> @exif._dataView = getDataView '\xa4\x01\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Normal process' @exif._dataView = getDataView '\xa4\x01\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Custom process' it 'should report correct description for ExposureMode', -> @exif._dataView = getDataView '\xa4\x02\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Auto exposure' @exif._dataView = getDataView '\xa4\x02\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Manual exposure' @exif._dataView = getDataView '\xa4\x02\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Auto bracket' it 'should report correct description for WhiteBalance', -> @exif._dataView = getDataView '\xa4\x03\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Auto white balance' @exif._dataView = getDataView '\xa4\x03\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Manual white balance' it 'should report correct description for DigitalZoomRatio', -> @exif._dataView = getDataView '\xa4\x04\x00\x05\x00\x00\x00\x01\x00\x00\x00\x0c\x00\x00\x00\x00\x00\x00\x00\x42' expect(@exif._readTag('exif', 0).description).toEqual 'Digital zoom was not used' @exif._dataView = getDataView '\xa4\x04\x00\x05\x00\x00\x00\x01\x00\x00\x00\x0c\x00\x00\x47\x11\x00\x00\x00\x42' expect(@exif._readTag('exif', 0).description).toBeCloseTo(275.6515, 4) it 'should report correct description for FocalLengthIn35mmFilm', -> @exif._dataView = getDataView '\xa4\x05\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Unknown' @exif._dataView = getDataView '\xa4\x05\x00\x03\x00\x00\x00\x01\x00\x42\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 0x42 it 'should report correct description for SceneCaptureType', -> @exif._dataView = getDataView '\xa4\x06\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Standard' @exif._dataView = getDataView '\xa4\x06\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Landscape' @exif._dataView = getDataView '\xa4\x06\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Portrait' @exif._dataView = getDataView '\xa4\x06\x00\x03\x00\x00\x00\x01\x00\x03\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Night scene' it 'should report correct description for GainControl', -> @exif._dataView = getDataView '\xa4\x07\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'None' @exif._dataView = getDataView '\xa4\x07\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Low gain up' @exif._dataView = getDataView '\xa4\x07\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'High gain up' @exif._dataView = getDataView '\xa4\x07\x00\x03\x00\x00\x00\x01\x00\x03\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Low gain down' @exif._dataView = getDataView '\xa4\x07\x00\x03\x00\x00\x00\x01\x00\x04\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'High gain down' it 'should report correct description for Contrast', -> @exif._dataView = getDataView '\xa4\x08\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Normal' @exif._dataView = getDataView '\xa4\x08\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Soft' @exif._dataView = getDataView '\xa4\x08\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Hard' it 'should report correct description for Saturation', -> @exif._dataView = getDataView '\xa4\x09\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Normal' @exif._dataView = getDataView '\xa4\x09\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Low saturation' @exif._dataView = getDataView '\xa4\x09\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'High saturation' it 'should report correct description for Sharpness', -> @exif._dataView = getDataView '\xa4\x0a\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Normal' @exif._dataView = getDataView '\xa4\x0a\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Soft' @exif._dataView = getDataView '\xa4\x0a\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Hard' it 'should report correct description for SubjectDistanceRange', -> @exif._dataView = getDataView '\xa4\x0c\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Unknown' @exif._dataView = getDataView '\xa4\x0c\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Macro' @exif._dataView = getDataView '\xa4\x0c\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Close view' @exif._dataView = getDataView '\xa4\x0c\x00\x03\x00\x00\x00\x01\x00\x03\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Distant view' it 'should report correct description for GPSVersionID', -> @exif._dataView = getDataView '\x00\x00\x00\x01\x00\x00\x00\x04\x02\x02\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Version 2.2' it 'should report correct description for GPSLatitudeRef', -> @exif._dataView = getDataView '\x00\x01\x00\x02\x00\x00\x00\x02N\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'North latitude' @exif._dataView = getDataView '\x00\x01\x00\x02\x00\x00\x00\x02S\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'South latitude' it 'should report correct description for GPSLatitude', -> # 37.231969, 115.811119 (37° 13' 55.0878", 115° 48' 40.0284") @exif._dataView = getDataView '\x00\x02\x00\x05\x00\x00\x00\x03\x00\x00\x00\x0c' + '\x00\x00\x00\x25\x00\x00\x00\x01' + '\x00\x00\x00\x0d\x00\x00\x00\x01' + '\x00\x08\x67\xde\x00\x00\x27\x10' expect(@exif._readTag('gps', 0).description).toBeCloseTo(37.231969, 6) it 'should report correct description for GPSLongitudeRef', -> @exif._dataView = getDataView '\x00\x03\x00\x02\x00\x00\x00\x02E\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'East longitude' @exif._dataView = getDataView '\x00\x03\x00\x02\x00\x00\x00\x02W\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'West longitude' it 'should report correct description for GPSLongitude', -> # 37.231969, 115.811119 (37° 13' 55.0878", 115° 48' 40.0284") @exif._dataView = getDataView '\x00\x04\x00\x05\x00\x00\x00\x03\x00\x00\x00\x0c' + '\x00\x00\x00\x73\x00\x00\x00\x01' + '\x00\x00\x00\x30\x00\x00\x00\x01' + '\x00\x06\x1b\x9c\x00\x00\x27\x10' expect(@exif._readTag('gps', 0).description).toBeCloseTo(115.811119, 6) it 'should report correct description for GPSAltitudeRef', -> @exif._dataView = getDataView '\x00\x05\x00\x01\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Sea level' @exif._dataView = getDataView '\x00\x05\x00\x01\x00\x00\x00\x01\x01\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Sea level reference (negative value)' it 'should report correct description for GPSAltitude', -> @exif._dataView = getDataView '\x00\x06\x00\x05\x00\x00\x00\x01\x00\x00\x00\x0c' + '\x00\x00\x00\x2a\x00\x00\x00\x01' expect(@exif._readTag('gps', 0).description).toEqual '42 m' it 'should report correct description for GPSTimeStamp', -> @exif._dataView = getDataView '\x00\x07\x00\x05\x00\x00\x00\x03\x00\x00\x00\x0c' + '\x00\x00\x00\x06\x00\x00\x00\x01' + '\x00\x00\x00\x07\x00\x00\x00\x01' + '\x00\x00\x0c\xb0\x00\x00\x00\x64' expect(@exif._readTag('gps', 0).description).toEqual '06:07:32.48' @exif._dataView = getDataView '\x00\x07\x00\x05\x00\x00\x00\x03\x00\x00\x00\x0c' + '\x00\x00\x00\x06\x00\x00\x00\x01' + '\x00\x00\x00\x00\x00\x00\x00\x01' + '\x00\x00\x0c\xb0\x00\x00\x00\x64' expect(@exif._readTag('gps', 0).description).toEqual '06:00:32.48' it 'should report correct description for GPSStatus', -> @exif._dataView = getDataView '\x00\x09\x00\x02\x00\x00\x00\x02A\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Measurement in progress' @exif._dataView = getDataView '\x00\x09\x00\x02\x00\x00\x00\x02V\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Measurement Interoperability' it 'should report correct description for GPSMeasureMode', -> @exif._dataView = getDataView '\x00\x0a\x00\x02\x00\x00\x00\x022\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual '2-dimensional measurement' @exif._dataView = getDataView '\x00\x0a\x00\x02\x00\x00\x00\x023\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual '3-dimensional measurement' it 'should report correct description for GPSSpeedRef', -> @exif._dataView = getDataView '\x00\x0c\x00\x02\x00\x00\x00\x02K\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Kilometers per hour' @exif._dataView = getDataView '\x00\x0c\x00\x02\x00\x00\x00\x02M\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Miles per hour' @exif._dataView = getDataView '\x00\x0c\x00\x02\x00\x00\x00\x02N\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Knots' it 'should report correct description for GPSTrackRef', -> @exif._dataView = getDataView '\x00\x0e\x00\x02\x00\x00\x00\x02T\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'True direction' @exif._dataView = getDataView '\x00\x0e\x00\x02\x00\x00\x00\x02M\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Magnetic direction' it 'should report correct description for GPSImgDirectionRef', -> @exif._dataView = getDataView '\x00\x10\x00\x02\x00\x00\x00\x02T\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'True direction' @exif._dataView = getDataView '\x00\x10\x00\x02\x00\x00\x00\x02M\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Magnetic direction' it 'should report correct description for GPSDestLatitudeRef', -> @exif._dataView = getDataView '\x00\x13\x00\x02\x00\x00\x00\x02N\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'North latitude' @exif._dataView = getDataView '\x00\x13\x00\x02\x00\x00\x00\x02S\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'South latitude' it 'should report correct description for GPSDestLatitude', -> # 37.231969, 115.811119 (37° 13' 55.0878", 115° 48' 40.0284") @exif._dataView = getDataView '\x00\x14\x00\x05\x00\x00\x00\x03\x00\x00\x00\x0c' + '\x00\x00\x00\x25\x00\x00\x00\x01' + '\x00\x00\x00\x0d\x00\x00\x00\x01' + '\x00\x08\x67\xde\x00\x00\x27\x10' expect(@exif._readTag('gps', 0).description).toBeCloseTo(37.231969, 6) it 'should report correct description for GPSDestLongitudeRef', -> @exif._dataView = getDataView '\x00\x15\x00\x02\x00\x00\x00\x02E\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'East longitude' @exif._dataView = getDataView '\x00\x15\x00\x02\x00\x00\x00\x02W\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'West longitude' it 'should report correct description for GPSDestLongitude', -> # 37.231969, 115.811119 (37° 13' 55.0878", 115° 48' 40.0284") @exif._dataView = getDataView '\x00\x16\x00\x05\x00\x00\x00\x03\x00\x00\x00\x0c' + '\x00\x00\x00\x73\x00\x00\x00\x01' + '\x00\x00\x00\x30\x00\x00\x00\x01' + '\x00\x06\x1b\x9c\x00\x00\x27\x10' expect(@exif._readTag('gps', 0).description).toBeCloseTo(115.811119, 6) it 'should report correct description for GPSDestBearingRef', -> @exif._dataView = getDataView '\x00\x17\x00\x02\x00\x00\x00\x02T\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'True direction' @exif._dataView = getDataView '\x00\x0e\x00\x02\x00\x00\x00\x02M\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Magnetic direction' it 'should report correct description for GPSDestDistanceRef', -> @exif._dataView = getDataView '\x00\x19\x00\x02\x00\x00\x00\x02K\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Kilometers' @exif._dataView = getDataView '\x00\x19\x00\x02\x00\x00\x00\x02M\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Miles' @exif._dataView = getDataView '\x00\x19\x00\x02\x00\x00\x00\x02N\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Knots' it 'should report correct description for GPSDifferential', -> @exif._dataView = getDataView '\x00\x1e\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Measurement without differential correction' @exif._dataView = getDataView '\x00\x1e\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Differential correction applied' it 'should report correct text for ASCII GPSProcessingMethod', -> @exif._dataView = getDataView '\x00\x1b\x00\x07\x00\x00\x00\x0b\x00\x00\x00\x0cASCII\x00\x00\x00ABC' expect(@exif._readTag('gps', 0).description).toEqual 'ABC' it 'should report correct character code for GPSProcessingMethod', -> @exif._dataView = getDataView '\x00\x1b\x00\x07\x00\x00\x00\x08\x00\x00\x00\x0cJIS\x00\x00\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual '[JIS encoded text]' @exif._dataView = getDataView '\x00\x1b\x00\x07\x00\x00\x00\x08\x00\x00\x00\x0cUNICODE\x00' expect(@exif._readTag('gps', 0).description).toEqual '[Unicode encoded text]' @exif._dataView = getDataView '\x00\x1b\x00\x07\x00\x00\x00\x08\x00\x00\x00\x0c\x00\x00\x00\x00\x00\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual '[Undefined encoding]' it 'should report correct text for ASCII GPSAreaInformation', -> @exif._dataView = getDataView '\x00\x1c\x00\x07\x00\x00\x00\x0b\x00\x00\x00\x0cASCII\x00\x00\x00ABC' expect(@exif._readTag('gps', 0).description).toEqual 'ABC' it 'should report correct character code for GPSAreaInformation', -> @exif._dataView = getDataView '\x00\x1c\x00\x07\x00\x00\x00\x08\x00\x00\x00\x0cJIS\x00\x00\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual '[JIS encoded text]' @exif._dataView = getDataView '\x00\x1c\x00\x07\x00\x00\x00\x08\x00\x00\x00\x0cUNICODE\x00' expect(@exif._readTag('gps', 0).description).toEqual '[Unicode encoded text]' @exif._dataView = getDataView '\x00\x1c\x00\x07\x00\x00\x00\x08\x00\x00\x00\x0c\x00\x00\x00\x00\x00\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual '[Undefined encoding]'
218733
### # ExifReader 1.0.1 # http://github.com/mattiasw/exifreader # Copyright (C) 2011 <NAME> <<EMAIL>> # Licensed under the GNU Lesser General Public License version 3 or later # See license text at http://www.gnu.org/licenses/lgpl.txt ### ExifReader = require '../src/ExifReader.coffee' ExifReader = ExifReader.ExifReader # Node.js doesn't have DataView. class DataView constructor: (@_data) -> @byteLength = @_data.length getUint8: (offset) -> @_data.readUInt8 offset getUint16: (offset, littleEndian) -> if littleEndian? and littleEndian @_data.readUInt16LE offset else @_data.readUInt16BE offset getUint32: (offset, littleEndian) -> if littleEndian? and littleEndian @_data.readUInt32LE offset else @_data.readUInt32BE offset getInt32: (offset, littleEndian) -> if littleEndian? and littleEndian @_data.readInt32LE offset else @_data.readInt32BE offset describe 'ExifReader', -> getArrayBuffer = (data) -> buffer = new Buffer(data.length) for i in [0...data.length] buffer[i] = data.charCodeAt i buffer getDataView = (data) -> dataView = new DataView getArrayBuffer(data) beforeEach -> @exif = new ExifReader @exif._tags = {} @exif._littleEndian = false @exif._tiffHeaderOffset = 0 it 'should fail for too short data buffer', -> exif = @exif exif._dataView = getDataView '\x00' expect(-> exif._checkImageHeader()).toThrow(new Error 'Invalid image format') it 'should accept well-formed header of JPEG image data', -> @exif._dataView = getDataView '\xff\xd8\xff\xe100Exif\x00\x00' @exif._checkImageHeader() it 'should fail for invalid image format', -> exif = @exif exif._dataView = getDataView '------------' expect(-> exif._checkImageHeader()).toThrow(new Error 'Invalid image format') it 'should fail when no Exif identifier for APP1', -> exif = @exif exif._dataView = getDataView '\xff\xd8\xff\xe1--------' expect(-> exif._checkImageHeader()).toThrow(new Error 'No Exif data') it 'should handle APP2 markers', -> @exif._dataView = getDataView '\xff\xd8\xff\xe0\x00\x07JFIF\x00\xff\xe2\x00\x07XXXX\x00\xff\xe0\x00\x07JFXX\x00\xff\xe1\x47\x11Exif\x00\x00' @exif._checkImageHeader() expect(@exif._tiffHeaderOffset).toEqual 39 it 'should handle JFIF APP0 markers', -> @exif._dataView = getDataView '\xff\xd8\xff\xe0\x00\x07JFIF\x00\xff\xe1\x47\x11Exif\x00\x00' @exif._checkImageHeader() expect(@exif._tiffHeaderOffset).toEqual 21 it 'should handle JFXX APP0 markers', -> @exif._dataView = getDataView '\xff\xd8\xff\xe0\x00\x07JFIF\x00\xff\xe0\x00\x07JFXX\x00\xff\xe1\x47\x11Exif\x00\x00' @exif._checkImageHeader() expect(@exif._tiffHeaderOffset).toEqual 30 it 'should handle unknown high ID APP markers', -> @exif._dataView = getDataView '\xff\xd8\xff\xea\x00\x07XXXX\x00\xff\xe1\x47\x11Exif\x00\x00' @exif._checkImageHeader() expect(@exif._tiffHeaderOffset).toEqual 21 it 'should handle reversed order of JFIF-Exif hybrid', -> @exif._dataView = getDataView '\xff\xd8\xff\xe1\x00\x08Exif\x00\x00\xff\xe0\x00\x07JFIF\x00' @exif._checkImageHeader() expect(@exif._tiffHeaderOffset).toEqual 12 it 'should fail gracefully for faulty APP markers', -> exif = @exif exif._dataView = getDataView '\xff\xd8\xfe\xdc\x00\x6fJFIF\x65\x01\x01\x01\x00\x48' expect(-> exif._checkImageHeader() exif._setByteOrder() ).toThrow(new Error 'No Exif data') it 'should find byte order data', -> @exif._dataView = getDataView '\xff\xd8\xff\xe100Exif\x00\x00\x49\x49' @exif._checkImageHeader() @exif._setByteOrder() expect(@exif._littleEndian).toBeTruthy() it 'should set correct byte order for litte endian data', -> @exif._dataView = getDataView '\x49\x49' @exif._setByteOrder() expect(@exif._littleEndian).toBeTruthy() it 'should set correct byte order for big endian data', -> @exif._dataView = getDataView '\x4d\x4d' @exif._setByteOrder() expect(@exif._littleEndian).toBeFalsy() it 'should not allow illegal byte order value', -> exif = @exif exif._dataView = getDataView '\x00\x00' expect(-> exif._setByteOrder()).toThrow(new Error 'Illegal byte order value. Faulty image.') it 'should correctly read offset of 0th IFD for little endian data', -> @exif._dataView = getDataView '\x49\x49\x00\x2a\x08\x00\x00\x00' @exif._setByteOrder() expect(@exif._getIfdOffset(0)).toEqual 8 it 'should correctly read offset of 0th IFD for big endian data', -> @exif._dataView = getDataView '\x4d\x4d\x00\x2a\x00\x00\x00\x08' @exif._setByteOrder() expect(@exif._getIfdOffset(0)).toEqual 8 it 'should be able to read a byte', -> @exif._dataView = getDataView '\x42' expect(@exif._getByteAt(0)).toEqual 0x42 it 'should be able to read an ASCII text', -> @exif._dataView = getDataView 'String\x00' expect(@exif._getAsciiAt(0)).toEqual 'S'.charCodeAt(0) it 'should be able to read a little endian short', -> @exif._dataView = getDataView '\x11\x47' @exif._littleEndian = true expect(@exif._getShortAt(0)).toEqual 0x4711 it 'should be able to read a big endian short', -> @exif._dataView = getDataView '\x47\x11' @exif._littleEndian = false expect(@exif._getShortAt(0)).toEqual 0x4711 it 'should be able to read a little endian long', -> @exif._dataView = getDataView '\x45\x44\x43\x42' @exif._littleEndian = true expect(@exif._getLongAt(0)).toEqual 0x42434445 it 'should be able to read a big endian long', -> @exif._dataView = getDataView '\x42\x43\x44\x45' @exif._littleEndian = false expect(@exif._getLongAt(0)).toEqual 0x42434445 it 'should be able to read a little endian rational', -> @exif._dataView = getDataView '\x45\x44\x43\x42\x49\x48\x47\x46' @exif._littleEndian = true expect(@exif._getRationalAt(0)).toEqual 0x42434445/0x46474849 it 'should be able to read a big endian rational', -> @exif._dataView = getDataView '\x42\x43\x44\x45\x46\x47\x48\x49' @exif._littleEndian = false expect(@exif._getRationalAt(0)).toEqual 0x42434445/0x46474849 it 'should be able to read an undefined', -> @exif._dataView = getDataView '\x42' expect(@exif._getUndefinedAt(0)).toEqual 0x42 it 'should be able to read a little endian slong', -> @exif._dataView = getDataView '\xbe\xff\xff\xff' @exif._littleEndian = true expect(@exif._getSlongAt(0)).toEqual -0x42 it 'should be able to read a big endian slong', -> @exif._dataView = getDataView '\xff\xff\xff\xbe' @exif._littleEndian = false expect(@exif._getSlongAt(0)).toEqual -0x42 it 'should be able to read a little endian srational', -> @exif._dataView = getDataView '\xbe\xff\xff\xff\x49\x48\x47\x46' @exif._littleEndian = true expect(@exif._getSrationalAt(0)).toEqual -0x42/0x46474849 it 'should be able to read a big endian srational', -> @exif._dataView = getDataView '\xff\xff\xff\xbe\x46\x47\x48\x49' @exif._littleEndian = false expect(@exif._getSrationalAt(0)).toEqual -0x42/0x46474849 it 'should be able to get ASCII value', -> expect(@exif._getAsciiValue(['S'.charCodeAt(0), 't'.charCodeAt(0), 'r'.charCodeAt(0), 'i'.charCodeAt(0), 'n'.charCodeAt(0), 'g'.charCodeAt(0), 0x00]).join('')).toEqual 'String\x00' it 'should be able to get IFD offset', -> @exif._dataView = getDataView '\x00\x00\x00\x00\x00\x2a\x47\x11\x48\x12' @exif._tiffHeaderOffset = 2 expect(@exif._getIfdOffset()).toEqual @exif._tiffHeaderOffset + 0x47114812 it 'should be able to read a one-field IFD', -> # field count + field @exif._dataView = getDataView '\x00\x01' + '\x47\x11\x00\x01\x00\x00\x00\x01\x42\x00\x00\x00' @exif._tagNames['0th'][0x4711] = 'MyExifTag' @exif._readIfd '0th', 0 expect(@exif.getTagDescription('MyExifTag')).toEqual 0x42 it 'should be able to read a multi-field IFD', -> # field count + 1st field + 2nd field @exif._dataView = getDataView('\x00\x02' + '\x47\x11\x00\x01\x00\x00\x00\x01\x42\x00\x00\x00' + '\x47\x12\x00\x01\x00\x00\x00\x01\x43\x00\x00\x00') @exif._tagNames['0th'][0x4711] = 'MyExifTag0' @exif._tagNames['0th'][0x4712] = 'MyExifTag1' @exif._readIfd '0th', 0 expect(@exif.getTagDescription('MyExifTag0')).toEqual 0x42 expect(@exif.getTagDescription('MyExifTag1')).toEqual 0x43 it 'should be able to read short ASCII tag', -> @exif._tagNames['0th'][0x4711] = 'MyAsciiTag' @exif._dataView = getDataView '\x47\x11\x00\x02\x00\x00\x00\x04\x41\x42\x43\x00' expect(@exif._readTag('0th', 0).description).toEqual 'ABC' it 'should be able to read long ASCII tag', -> @exif._tagNames['0th'][0x4711] = 'MyAsciiTag' @exif._dataView = getDataView '\x47\x11\x00\x02\x00\x00\x00\x06\x00\x00\x00\x0c\x41\x42\x43\x44\x45\x00' expect(@exif._readTag('0th', 0).description).toEqual 'ABCDE' it 'should return undefined value for undefined tag names', -> exif = @exif expect(exif.getTagValue('MyUndefinedTagName')).toBeUndefined() it 'should return undefined description for undefined tag names', -> exif = @exif expect(exif.getTagDescription('MyUndefinedTagName')).toBeUndefined() # Parsing tag descriptions. getOrientationView = (o) -> getDataView('\x01\x12\x00\x03\x00\x00\x00\x01\x00' + o + '\x00\x00') it 'should report correct description for Orientation', -> @exif._dataView = getOrientationView '\x01' expect(@exif._readTag('0th', 0).description).toEqual 'top-left' @exif._dataView = getOrientationView '\x02' expect(@exif._readTag('0th', 0).description).toEqual 'top-right' @exif._dataView = getOrientationView '\x03' expect(@exif._readTag('0th', 0).description).toEqual 'bottom-right' @exif._dataView = getOrientationView '\x04' expect(@exif._readTag('0th', 0).description).toEqual 'bottom-left' @exif._dataView = getOrientationView '\x05' expect(@exif._readTag('0th', 0).description).toEqual 'left-top' @exif._dataView = getOrientationView '\x06' expect(@exif._readTag('0th', 0).description).toEqual 'right-top' @exif._dataView = getOrientationView '\x07' expect(@exif._readTag('0th', 0).description).toEqual 'right-bottom' @exif._dataView = getOrientationView '\x08' expect(@exif._readTag('0th', 0).description).toEqual 'left-bottom' it 'should report correct description for YCbCrPositioning', -> @exif._dataView = getDataView '\x02\x13\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('0th', 0).description).toEqual 'centered' @exif._dataView = getDataView '\x02\x13\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('0th', 0).description).toEqual 'co-sited' it 'should report correct description for ResolutionUnit', -> @exif._dataView = getDataView '\x01\x28\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('0th', 0).description).toEqual 'inches' @exif._dataView = getDataView '\x01\x28\x00\x03\x00\x00\x00\x01\x00\x03\x00\x00' expect(@exif._readTag('0th', 0).description).toEqual 'centimeters' it 'should report correct description for Copyright', -> # A NULL B NULL @exif._dataView = getDataView '\x82\x98\x00\x02\x00\x00\x00\x04\x41\x00\x42\x00' expect(@exif._readTag('0th', 0).description).toEqual 'A; B' it 'should report correct description for ExifVersion', -> @exif._dataView = getDataView '\x90\x00\x00\x07\x00\x00\x00\x04\x30\x32\x32\x30' expect(@exif._readTag('exif', 0).description).toEqual '0220' it 'should report correct description for FlashpixVersion', -> @exif._dataView = getDataView '\xa0\x00\x00\x07\x00\x00\x00\x04\x30\x31\x30\x30' expect(@exif._readTag('exif', 0).description).toEqual '0100' it 'should report correct description for ColorSpace', -> @exif._dataView = getDataView '\xa0\x01\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'sRGB' @exif._dataView = getDataView '\xa0\x01\x00\x03\x00\x00\x00\x01\xff\xff\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Uncalibrated' it 'should report correct description for ComponentsConfiguration', -> @exif._dataView = getDataView '\x91\x01\x00\x07\x00\x00\x00\x04\x34\x35\x36\x30' expect(@exif._readTag('exif', 0).description).toEqual 'RGB' @exif._dataView = getDataView '\x91\x01\x00\x07\x00\x00\x00\x04\x31\x32\x33\x30' expect(@exif._readTag('exif', 0).description).toEqual 'YCbCr' it 'should report correct text for ASCII UserComment', -> @exif._dataView = getDataView '\x92\x86\x00\x07\x00\x00\x00\x0b\x00\x00\x00\x0cASCII\x00\x00\x00ABC' expect(@exif._readTag('exif', 0).description).toEqual 'ABC' it 'should report correct character code for UserComment', -> @exif._dataView = getDataView '\x92\x86\x00\x07\x00\x00\x00\x08\x00\x00\x00\x0cJIS\x00\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual '[JIS encoded text]' @exif._dataView = getDataView '\x92\x86\x00\x07\x00\x00\x00\x08\x00\x00\x00\x0cUNICODE\x00' expect(@exif._readTag('exif', 0).description).toEqual '[Unicode encoded text]' @exif._dataView = getDataView '\x92\x86\x00\x07\x00\x00\x00\x08\x00\x00\x00\x0c\x00\x00\x00\x00\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual '[Undefined encoding]' it 'should report correct description for ExposureProgram', -> @exif._dataView = getDataView '\x88\x22\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Undefined' @exif._dataView = getDataView '\x88\x22\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Manual' @exif._dataView = getDataView '\x88\x22\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Normal program' @exif._dataView = getDataView '\x88\x22\x00\x03\x00\x00\x00\x01\x00\x03\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Aperture priority' @exif._dataView = getDataView '\x88\x22\x00\x03\x00\x00\x00\x01\x00\x04\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Shutter priority' @exif._dataView = getDataView '\x88\x22\x00\x03\x00\x00\x00\x01\x00\x05\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Creative program' @exif._dataView = getDataView '\x88\x22\x00\x03\x00\x00\x00\x01\x00\x06\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Action program' @exif._dataView = getDataView '\x88\x22\x00\x03\x00\x00\x00\x01\x00\x07\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Portrait mode' @exif._dataView = getDataView '\x88\x22\x00\x03\x00\x00\x00\x01\x00\x08\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Landscape mode' @exif._dataView = getDataView '\x88\x22\x00\x03\x00\x00\x00\x01\x00\x09\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Unknown' it 'should report correct description for MeteringMode', -> @exif._dataView = getDataView '\x92\x07\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Average' @exif._dataView = getDataView '\x92\x07\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'CenterWeightedAverage' @exif._dataView = getDataView '\x92\x07\x00\x03\x00\x00\x00\x01\x00\x03\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Spot' @exif._dataView = getDataView '\x92\x07\x00\x03\x00\x00\x00\x01\x00\x04\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'MultiSpot' @exif._dataView = getDataView '\x92\x07\x00\x03\x00\x00\x00\x01\x00\x05\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Pattern' @exif._dataView = getDataView '\x92\x07\x00\x03\x00\x00\x00\x01\x00\x06\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Partial' @exif._dataView = getDataView '\x92\x07\x00\x03\x00\x00\x00\x01\x00\xff\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Other' @exif._dataView = getDataView '\x92\x07\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Unknown' it 'should report correct description for LightSource', -> @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Daylight' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Fluorescent' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x03\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Tungsten (incandescent light)' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x04\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x09\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Fine weather' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x0a\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Cloudy weather' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x0b\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Shade' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x0c\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Daylight fluorescent (D 5700 – 7100K)' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x0d\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Day white fluorescent (N 4600 – 5400K)' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x0e\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Cool white fluorescent (W 3900 – 4500K)' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x0f\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'White fluorescent (WW 3200 – 3700K)' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x11\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Standard light A' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x12\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Standard light B' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x13\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Standard light C' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x14\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'D55' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x15\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'D65' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x16\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'D75' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x17\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'D50' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x18\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'ISO studio tungsten' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\xff\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Other light source' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Unknown' it 'should report correct description for Flash', -> @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash did not fire' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x05\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Strobe return light not detected' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x07\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Strobe return light detected' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x09\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, compulsory flash mode' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x0d\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, compulsory flash mode, return light not detected' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x0f\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, compulsory flash mode, return light detected' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x10\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash did not fire, compulsory flash mode' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x18\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash did not fire, auto mode' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x19\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, auto mode' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x1d\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, auto mode, return light not detected' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x1f\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, auto mode, return light detected' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x20\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'No flash function' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x41\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, red-eye reduction mode' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x45\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, red-eye reduction mode, return light not detected' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x47\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, red-eye reduction mode, return light detected' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x49\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, compulsory flash mode, red-eye reduction mode' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x4d\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x4f\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, compulsory flash mode, red-eye reduction mode, return light detected' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x59\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, auto mode, red-eye reduction mode' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x5d\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, auto mode, return light not detected, red-eye reduction mode' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x5f\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, auto mode, return light detected, red-eye reduction mode' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x60\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Unknown' it 'should report correct description for SubjectArea', -> @exif._dataView = getDataView '\x92\x14\x00\x03\x00\x00\x00\x02\x47\x11\x48\x12' expect(@exif._readTag('exif', 0).description).toEqual 'Location; X: 18193, Y: 18450' @exif._dataView = getDataView '\x92\x14\x00\x03\x00\x00\x00\x03\x00\x00\x00\x0c\x47\x11\x48\x12\x00\x42' expect(@exif._readTag('exif', 0).description).toEqual 'Circle; X: 18193, Y: 18450, diameter: 66' @exif._dataView = getDataView '\x92\x14\x00\x03\x00\x00\x00\x04\x00\x00\x00\x0c\x47\x11\x48\x12\x00\x42\x00\x43' expect(@exif._readTag('exif', 0).description).toEqual 'Rectangle; X: 18193, Y: 18450, width: 66, height: 67' it 'should report correct description for FocalPlaneResolutionUnit', -> @exif._dataView = getDataView '\xa2\x10\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'inches' @exif._dataView = getDataView '\xa2\x10\x00\x03\x00\x00\x00\x01\x00\x03\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'centimeters' it 'should report correct description for SubjectLocation', -> @exif._dataView = getDataView '\xa2\x14\x00\x03\x00\x00\x00\x02\x47\x11\x48\x12' expect(@exif._readTag('exif', 0).description).toEqual 'X: 18193, Y: 18450' it 'should report correct description for SensingMethod', -> @exif._dataView = getDataView '\xa2\x17\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Undefined' @exif._dataView = getDataView '\xa2\x17\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'One-chip color area sensor' @exif._dataView = getDataView '\xa2\x17\x00\x03\x00\x00\x00\x01\x00\x03\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Two-chip color area sensor' @exif._dataView = getDataView '\xa2\x17\x00\x03\x00\x00\x00\x01\x00\x04\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Three-chip color area sensor' @exif._dataView = getDataView '\xa2\x17\x00\x03\x00\x00\x00\x01\x00\x05\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Color sequential area sensor' @exif._dataView = getDataView '\xa2\x17\x00\x03\x00\x00\x00\x01\x00\x07\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Trilinear sensor' @exif._dataView = getDataView '\xa2\x17\x00\x03\x00\x00\x00\x01\x00\x08\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Color sequential linear sensor' it 'should report correct description for FileSource', -> @exif._dataView = getDataView '\xa3\x00\x00\x07\x00\x00\x00\x01\x03\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'DSC' it 'should report correct description for SceneType', -> @exif._dataView = getDataView '\xa3\x01\x00\x07\x00\x00\x00\x01\x01\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'A directly photographed image' it 'should report correct description for CustomRendered', -> @exif._dataView = getDataView '\xa4\x01\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Normal process' @exif._dataView = getDataView '\xa4\x01\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Custom process' it 'should report correct description for ExposureMode', -> @exif._dataView = getDataView '\xa4\x02\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Auto exposure' @exif._dataView = getDataView '\xa4\x02\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Manual exposure' @exif._dataView = getDataView '\xa4\x02\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Auto bracket' it 'should report correct description for WhiteBalance', -> @exif._dataView = getDataView '\xa4\x03\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Auto white balance' @exif._dataView = getDataView '\xa4\x03\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Manual white balance' it 'should report correct description for DigitalZoomRatio', -> @exif._dataView = getDataView '\xa4\x04\x00\x05\x00\x00\x00\x01\x00\x00\x00\x0c\x00\x00\x00\x00\x00\x00\x00\x42' expect(@exif._readTag('exif', 0).description).toEqual 'Digital zoom was not used' @exif._dataView = getDataView '\xa4\x04\x00\x05\x00\x00\x00\x01\x00\x00\x00\x0c\x00\x00\x47\x11\x00\x00\x00\x42' expect(@exif._readTag('exif', 0).description).toBeCloseTo(275.6515, 4) it 'should report correct description for FocalLengthIn35mmFilm', -> @exif._dataView = getDataView '\xa4\x05\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Unknown' @exif._dataView = getDataView '\xa4\x05\x00\x03\x00\x00\x00\x01\x00\x42\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 0x42 it 'should report correct description for SceneCaptureType', -> @exif._dataView = getDataView '\xa4\x06\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Standard' @exif._dataView = getDataView '\xa4\x06\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Landscape' @exif._dataView = getDataView '\xa4\x06\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Portrait' @exif._dataView = getDataView '\xa4\x06\x00\x03\x00\x00\x00\x01\x00\x03\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Night scene' it 'should report correct description for GainControl', -> @exif._dataView = getDataView '\xa4\x07\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'None' @exif._dataView = getDataView '\xa4\x07\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Low gain up' @exif._dataView = getDataView '\xa4\x07\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'High gain up' @exif._dataView = getDataView '\xa4\x07\x00\x03\x00\x00\x00\x01\x00\x03\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Low gain down' @exif._dataView = getDataView '\xa4\x07\x00\x03\x00\x00\x00\x01\x00\x04\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'High gain down' it 'should report correct description for Contrast', -> @exif._dataView = getDataView '\xa4\x08\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Normal' @exif._dataView = getDataView '\xa4\x08\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Soft' @exif._dataView = getDataView '\xa4\x08\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Hard' it 'should report correct description for Saturation', -> @exif._dataView = getDataView '\xa4\x09\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Normal' @exif._dataView = getDataView '\xa4\x09\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Low saturation' @exif._dataView = getDataView '\xa4\x09\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'High saturation' it 'should report correct description for Sharpness', -> @exif._dataView = getDataView '\xa4\x0a\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Normal' @exif._dataView = getDataView '\xa4\x0a\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Soft' @exif._dataView = getDataView '\xa4\x0a\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Hard' it 'should report correct description for SubjectDistanceRange', -> @exif._dataView = getDataView '\xa4\x0c\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Unknown' @exif._dataView = getDataView '\xa4\x0c\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Macro' @exif._dataView = getDataView '\xa4\x0c\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Close view' @exif._dataView = getDataView '\xa4\x0c\x00\x03\x00\x00\x00\x01\x00\x03\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Distant view' it 'should report correct description for GPSVersionID', -> @exif._dataView = getDataView '\x00\x00\x00\x01\x00\x00\x00\x04\x02\x02\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Version 2.2' it 'should report correct description for GPSLatitudeRef', -> @exif._dataView = getDataView '\x00\x01\x00\x02\x00\x00\x00\x02N\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'North latitude' @exif._dataView = getDataView '\x00\x01\x00\x02\x00\x00\x00\x02S\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'South latitude' it 'should report correct description for GPSLatitude', -> # 37.231969, 115.811119 (37° 13' 55.0878", 115° 48' 40.0284") @exif._dataView = getDataView '\x00\x02\x00\x05\x00\x00\x00\x03\x00\x00\x00\x0c' + '\x00\x00\x00\x25\x00\x00\x00\x01' + '\x00\x00\x00\x0d\x00\x00\x00\x01' + '\x00\x08\x67\xde\x00\x00\x27\x10' expect(@exif._readTag('gps', 0).description).toBeCloseTo(37.231969, 6) it 'should report correct description for GPSLongitudeRef', -> @exif._dataView = getDataView '\x00\x03\x00\x02\x00\x00\x00\x02E\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'East longitude' @exif._dataView = getDataView '\x00\x03\x00\x02\x00\x00\x00\x02W\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'West longitude' it 'should report correct description for GPSLongitude', -> # 37.231969, 115.811119 (37° 13' 55.0878", 115° 48' 40.0284") @exif._dataView = getDataView '\x00\x04\x00\x05\x00\x00\x00\x03\x00\x00\x00\x0c' + '\x00\x00\x00\x73\x00\x00\x00\x01' + '\x00\x00\x00\x30\x00\x00\x00\x01' + '\x00\x06\x1b\x9c\x00\x00\x27\x10' expect(@exif._readTag('gps', 0).description).toBeCloseTo(115.811119, 6) it 'should report correct description for GPSAltitudeRef', -> @exif._dataView = getDataView '\x00\x05\x00\x01\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Sea level' @exif._dataView = getDataView '\x00\x05\x00\x01\x00\x00\x00\x01\x01\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Sea level reference (negative value)' it 'should report correct description for GPSAltitude', -> @exif._dataView = getDataView '\x00\x06\x00\x05\x00\x00\x00\x01\x00\x00\x00\x0c' + '\x00\x00\x00\x2a\x00\x00\x00\x01' expect(@exif._readTag('gps', 0).description).toEqual '42 m' it 'should report correct description for GPSTimeStamp', -> @exif._dataView = getDataView '\x00\x07\x00\x05\x00\x00\x00\x03\x00\x00\x00\x0c' + '\x00\x00\x00\x06\x00\x00\x00\x01' + '\x00\x00\x00\x07\x00\x00\x00\x01' + '\x00\x00\x0c\xb0\x00\x00\x00\x64' expect(@exif._readTag('gps', 0).description).toEqual '06:07:32.48' @exif._dataView = getDataView '\x00\x07\x00\x05\x00\x00\x00\x03\x00\x00\x00\x0c' + '\x00\x00\x00\x06\x00\x00\x00\x01' + '\x00\x00\x00\x00\x00\x00\x00\x01' + '\x00\x00\x0c\xb0\x00\x00\x00\x64' expect(@exif._readTag('gps', 0).description).toEqual '06:00:32.48' it 'should report correct description for GPSStatus', -> @exif._dataView = getDataView '\x00\x09\x00\x02\x00\x00\x00\x02A\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Measurement in progress' @exif._dataView = getDataView '\x00\x09\x00\x02\x00\x00\x00\x02V\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Measurement Interoperability' it 'should report correct description for GPSMeasureMode', -> @exif._dataView = getDataView '\x00\x0a\x00\x02\x00\x00\x00\x022\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual '2-dimensional measurement' @exif._dataView = getDataView '\x00\x0a\x00\x02\x00\x00\x00\x023\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual '3-dimensional measurement' it 'should report correct description for GPSSpeedRef', -> @exif._dataView = getDataView '\x00\x0c\x00\x02\x00\x00\x00\x02K\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Kilometers per hour' @exif._dataView = getDataView '\x00\x0c\x00\x02\x00\x00\x00\x02M\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Miles per hour' @exif._dataView = getDataView '\x00\x0c\x00\x02\x00\x00\x00\x02N\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Knots' it 'should report correct description for GPSTrackRef', -> @exif._dataView = getDataView '\x00\x0e\x00\x02\x00\x00\x00\x02T\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'True direction' @exif._dataView = getDataView '\x00\x0e\x00\x02\x00\x00\x00\x02M\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Magnetic direction' it 'should report correct description for GPSImgDirectionRef', -> @exif._dataView = getDataView '\x00\x10\x00\x02\x00\x00\x00\x02T\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'True direction' @exif._dataView = getDataView '\x00\x10\x00\x02\x00\x00\x00\x02M\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Magnetic direction' it 'should report correct description for GPSDestLatitudeRef', -> @exif._dataView = getDataView '\x00\x13\x00\x02\x00\x00\x00\x02N\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'North latitude' @exif._dataView = getDataView '\x00\x13\x00\x02\x00\x00\x00\x02S\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'South latitude' it 'should report correct description for GPSDestLatitude', -> # 37.231969, 115.811119 (37° 13' 55.0878", 115° 48' 40.0284") @exif._dataView = getDataView '\x00\x14\x00\x05\x00\x00\x00\x03\x00\x00\x00\x0c' + '\x00\x00\x00\x25\x00\x00\x00\x01' + '\x00\x00\x00\x0d\x00\x00\x00\x01' + '\x00\x08\x67\xde\x00\x00\x27\x10' expect(@exif._readTag('gps', 0).description).toBeCloseTo(37.231969, 6) it 'should report correct description for GPSDestLongitudeRef', -> @exif._dataView = getDataView '\x00\x15\x00\x02\x00\x00\x00\x02E\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'East longitude' @exif._dataView = getDataView '\x00\x15\x00\x02\x00\x00\x00\x02W\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'West longitude' it 'should report correct description for GPSDestLongitude', -> # 37.231969, 115.811119 (37° 13' 55.0878", 115° 48' 40.0284") @exif._dataView = getDataView '\x00\x16\x00\x05\x00\x00\x00\x03\x00\x00\x00\x0c' + '\x00\x00\x00\x73\x00\x00\x00\x01' + '\x00\x00\x00\x30\x00\x00\x00\x01' + '\x00\x06\x1b\x9c\x00\x00\x27\x10' expect(@exif._readTag('gps', 0).description).toBeCloseTo(115.811119, 6) it 'should report correct description for GPSDestBearingRef', -> @exif._dataView = getDataView '\x00\x17\x00\x02\x00\x00\x00\x02T\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'True direction' @exif._dataView = getDataView '\x00\x0e\x00\x02\x00\x00\x00\x02M\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Magnetic direction' it 'should report correct description for GPSDestDistanceRef', -> @exif._dataView = getDataView '\x00\x19\x00\x02\x00\x00\x00\x02K\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Kilometers' @exif._dataView = getDataView '\x00\x19\x00\x02\x00\x00\x00\x02M\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Miles' @exif._dataView = getDataView '\x00\x19\x00\x02\x00\x00\x00\x02N\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Knots' it 'should report correct description for GPSDifferential', -> @exif._dataView = getDataView '\x00\x1e\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Measurement without differential correction' @exif._dataView = getDataView '\x00\x1e\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Differential correction applied' it 'should report correct text for ASCII GPSProcessingMethod', -> @exif._dataView = getDataView '\x00\x1b\x00\x07\x00\x00\x00\x0b\x00\x00\x00\x0cASCII\x00\x00\x00ABC' expect(@exif._readTag('gps', 0).description).toEqual 'ABC' it 'should report correct character code for GPSProcessingMethod', -> @exif._dataView = getDataView '\x00\x1b\x00\x07\x00\x00\x00\x08\x00\x00\x00\x0cJIS\x00\x00\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual '[JIS encoded text]' @exif._dataView = getDataView '\x00\x1b\x00\x07\x00\x00\x00\x08\x00\x00\x00\x0cUNICODE\x00' expect(@exif._readTag('gps', 0).description).toEqual '[Unicode encoded text]' @exif._dataView = getDataView '\x00\x1b\x00\x07\x00\x00\x00\x08\x00\x00\x00\x0c\x00\x00\x00\x00\x00\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual '[Undefined encoding]' it 'should report correct text for ASCII GPSAreaInformation', -> @exif._dataView = getDataView '\x00\x1c\x00\x07\x00\x00\x00\x0b\x00\x00\x00\x0cASCII\x00\x00\x00ABC' expect(@exif._readTag('gps', 0).description).toEqual 'ABC' it 'should report correct character code for GPSAreaInformation', -> @exif._dataView = getDataView '\x00\x1c\x00\x07\x00\x00\x00\x08\x00\x00\x00\x0cJIS\x00\x00\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual '[JIS encoded text]' @exif._dataView = getDataView '\x00\x1c\x00\x07\x00\x00\x00\x08\x00\x00\x00\x0cUNICODE\x00' expect(@exif._readTag('gps', 0).description).toEqual '[Unicode encoded text]' @exif._dataView = getDataView '\x00\x1c\x00\x07\x00\x00\x00\x08\x00\x00\x00\x0c\x00\x00\x00\x00\x00\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual '[Undefined encoding]'
true
### # ExifReader 1.0.1 # http://github.com/mattiasw/exifreader # Copyright (C) 2011 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # Licensed under the GNU Lesser General Public License version 3 or later # See license text at http://www.gnu.org/licenses/lgpl.txt ### ExifReader = require '../src/ExifReader.coffee' ExifReader = ExifReader.ExifReader # Node.js doesn't have DataView. class DataView constructor: (@_data) -> @byteLength = @_data.length getUint8: (offset) -> @_data.readUInt8 offset getUint16: (offset, littleEndian) -> if littleEndian? and littleEndian @_data.readUInt16LE offset else @_data.readUInt16BE offset getUint32: (offset, littleEndian) -> if littleEndian? and littleEndian @_data.readUInt32LE offset else @_data.readUInt32BE offset getInt32: (offset, littleEndian) -> if littleEndian? and littleEndian @_data.readInt32LE offset else @_data.readInt32BE offset describe 'ExifReader', -> getArrayBuffer = (data) -> buffer = new Buffer(data.length) for i in [0...data.length] buffer[i] = data.charCodeAt i buffer getDataView = (data) -> dataView = new DataView getArrayBuffer(data) beforeEach -> @exif = new ExifReader @exif._tags = {} @exif._littleEndian = false @exif._tiffHeaderOffset = 0 it 'should fail for too short data buffer', -> exif = @exif exif._dataView = getDataView '\x00' expect(-> exif._checkImageHeader()).toThrow(new Error 'Invalid image format') it 'should accept well-formed header of JPEG image data', -> @exif._dataView = getDataView '\xff\xd8\xff\xe100Exif\x00\x00' @exif._checkImageHeader() it 'should fail for invalid image format', -> exif = @exif exif._dataView = getDataView '------------' expect(-> exif._checkImageHeader()).toThrow(new Error 'Invalid image format') it 'should fail when no Exif identifier for APP1', -> exif = @exif exif._dataView = getDataView '\xff\xd8\xff\xe1--------' expect(-> exif._checkImageHeader()).toThrow(new Error 'No Exif data') it 'should handle APP2 markers', -> @exif._dataView = getDataView '\xff\xd8\xff\xe0\x00\x07JFIF\x00\xff\xe2\x00\x07XXXX\x00\xff\xe0\x00\x07JFXX\x00\xff\xe1\x47\x11Exif\x00\x00' @exif._checkImageHeader() expect(@exif._tiffHeaderOffset).toEqual 39 it 'should handle JFIF APP0 markers', -> @exif._dataView = getDataView '\xff\xd8\xff\xe0\x00\x07JFIF\x00\xff\xe1\x47\x11Exif\x00\x00' @exif._checkImageHeader() expect(@exif._tiffHeaderOffset).toEqual 21 it 'should handle JFXX APP0 markers', -> @exif._dataView = getDataView '\xff\xd8\xff\xe0\x00\x07JFIF\x00\xff\xe0\x00\x07JFXX\x00\xff\xe1\x47\x11Exif\x00\x00' @exif._checkImageHeader() expect(@exif._tiffHeaderOffset).toEqual 30 it 'should handle unknown high ID APP markers', -> @exif._dataView = getDataView '\xff\xd8\xff\xea\x00\x07XXXX\x00\xff\xe1\x47\x11Exif\x00\x00' @exif._checkImageHeader() expect(@exif._tiffHeaderOffset).toEqual 21 it 'should handle reversed order of JFIF-Exif hybrid', -> @exif._dataView = getDataView '\xff\xd8\xff\xe1\x00\x08Exif\x00\x00\xff\xe0\x00\x07JFIF\x00' @exif._checkImageHeader() expect(@exif._tiffHeaderOffset).toEqual 12 it 'should fail gracefully for faulty APP markers', -> exif = @exif exif._dataView = getDataView '\xff\xd8\xfe\xdc\x00\x6fJFIF\x65\x01\x01\x01\x00\x48' expect(-> exif._checkImageHeader() exif._setByteOrder() ).toThrow(new Error 'No Exif data') it 'should find byte order data', -> @exif._dataView = getDataView '\xff\xd8\xff\xe100Exif\x00\x00\x49\x49' @exif._checkImageHeader() @exif._setByteOrder() expect(@exif._littleEndian).toBeTruthy() it 'should set correct byte order for litte endian data', -> @exif._dataView = getDataView '\x49\x49' @exif._setByteOrder() expect(@exif._littleEndian).toBeTruthy() it 'should set correct byte order for big endian data', -> @exif._dataView = getDataView '\x4d\x4d' @exif._setByteOrder() expect(@exif._littleEndian).toBeFalsy() it 'should not allow illegal byte order value', -> exif = @exif exif._dataView = getDataView '\x00\x00' expect(-> exif._setByteOrder()).toThrow(new Error 'Illegal byte order value. Faulty image.') it 'should correctly read offset of 0th IFD for little endian data', -> @exif._dataView = getDataView '\x49\x49\x00\x2a\x08\x00\x00\x00' @exif._setByteOrder() expect(@exif._getIfdOffset(0)).toEqual 8 it 'should correctly read offset of 0th IFD for big endian data', -> @exif._dataView = getDataView '\x4d\x4d\x00\x2a\x00\x00\x00\x08' @exif._setByteOrder() expect(@exif._getIfdOffset(0)).toEqual 8 it 'should be able to read a byte', -> @exif._dataView = getDataView '\x42' expect(@exif._getByteAt(0)).toEqual 0x42 it 'should be able to read an ASCII text', -> @exif._dataView = getDataView 'String\x00' expect(@exif._getAsciiAt(0)).toEqual 'S'.charCodeAt(0) it 'should be able to read a little endian short', -> @exif._dataView = getDataView '\x11\x47' @exif._littleEndian = true expect(@exif._getShortAt(0)).toEqual 0x4711 it 'should be able to read a big endian short', -> @exif._dataView = getDataView '\x47\x11' @exif._littleEndian = false expect(@exif._getShortAt(0)).toEqual 0x4711 it 'should be able to read a little endian long', -> @exif._dataView = getDataView '\x45\x44\x43\x42' @exif._littleEndian = true expect(@exif._getLongAt(0)).toEqual 0x42434445 it 'should be able to read a big endian long', -> @exif._dataView = getDataView '\x42\x43\x44\x45' @exif._littleEndian = false expect(@exif._getLongAt(0)).toEqual 0x42434445 it 'should be able to read a little endian rational', -> @exif._dataView = getDataView '\x45\x44\x43\x42\x49\x48\x47\x46' @exif._littleEndian = true expect(@exif._getRationalAt(0)).toEqual 0x42434445/0x46474849 it 'should be able to read a big endian rational', -> @exif._dataView = getDataView '\x42\x43\x44\x45\x46\x47\x48\x49' @exif._littleEndian = false expect(@exif._getRationalAt(0)).toEqual 0x42434445/0x46474849 it 'should be able to read an undefined', -> @exif._dataView = getDataView '\x42' expect(@exif._getUndefinedAt(0)).toEqual 0x42 it 'should be able to read a little endian slong', -> @exif._dataView = getDataView '\xbe\xff\xff\xff' @exif._littleEndian = true expect(@exif._getSlongAt(0)).toEqual -0x42 it 'should be able to read a big endian slong', -> @exif._dataView = getDataView '\xff\xff\xff\xbe' @exif._littleEndian = false expect(@exif._getSlongAt(0)).toEqual -0x42 it 'should be able to read a little endian srational', -> @exif._dataView = getDataView '\xbe\xff\xff\xff\x49\x48\x47\x46' @exif._littleEndian = true expect(@exif._getSrationalAt(0)).toEqual -0x42/0x46474849 it 'should be able to read a big endian srational', -> @exif._dataView = getDataView '\xff\xff\xff\xbe\x46\x47\x48\x49' @exif._littleEndian = false expect(@exif._getSrationalAt(0)).toEqual -0x42/0x46474849 it 'should be able to get ASCII value', -> expect(@exif._getAsciiValue(['S'.charCodeAt(0), 't'.charCodeAt(0), 'r'.charCodeAt(0), 'i'.charCodeAt(0), 'n'.charCodeAt(0), 'g'.charCodeAt(0), 0x00]).join('')).toEqual 'String\x00' it 'should be able to get IFD offset', -> @exif._dataView = getDataView '\x00\x00\x00\x00\x00\x2a\x47\x11\x48\x12' @exif._tiffHeaderOffset = 2 expect(@exif._getIfdOffset()).toEqual @exif._tiffHeaderOffset + 0x47114812 it 'should be able to read a one-field IFD', -> # field count + field @exif._dataView = getDataView '\x00\x01' + '\x47\x11\x00\x01\x00\x00\x00\x01\x42\x00\x00\x00' @exif._tagNames['0th'][0x4711] = 'MyExifTag' @exif._readIfd '0th', 0 expect(@exif.getTagDescription('MyExifTag')).toEqual 0x42 it 'should be able to read a multi-field IFD', -> # field count + 1st field + 2nd field @exif._dataView = getDataView('\x00\x02' + '\x47\x11\x00\x01\x00\x00\x00\x01\x42\x00\x00\x00' + '\x47\x12\x00\x01\x00\x00\x00\x01\x43\x00\x00\x00') @exif._tagNames['0th'][0x4711] = 'MyExifTag0' @exif._tagNames['0th'][0x4712] = 'MyExifTag1' @exif._readIfd '0th', 0 expect(@exif.getTagDescription('MyExifTag0')).toEqual 0x42 expect(@exif.getTagDescription('MyExifTag1')).toEqual 0x43 it 'should be able to read short ASCII tag', -> @exif._tagNames['0th'][0x4711] = 'MyAsciiTag' @exif._dataView = getDataView '\x47\x11\x00\x02\x00\x00\x00\x04\x41\x42\x43\x00' expect(@exif._readTag('0th', 0).description).toEqual 'ABC' it 'should be able to read long ASCII tag', -> @exif._tagNames['0th'][0x4711] = 'MyAsciiTag' @exif._dataView = getDataView '\x47\x11\x00\x02\x00\x00\x00\x06\x00\x00\x00\x0c\x41\x42\x43\x44\x45\x00' expect(@exif._readTag('0th', 0).description).toEqual 'ABCDE' it 'should return undefined value for undefined tag names', -> exif = @exif expect(exif.getTagValue('MyUndefinedTagName')).toBeUndefined() it 'should return undefined description for undefined tag names', -> exif = @exif expect(exif.getTagDescription('MyUndefinedTagName')).toBeUndefined() # Parsing tag descriptions. getOrientationView = (o) -> getDataView('\x01\x12\x00\x03\x00\x00\x00\x01\x00' + o + '\x00\x00') it 'should report correct description for Orientation', -> @exif._dataView = getOrientationView '\x01' expect(@exif._readTag('0th', 0).description).toEqual 'top-left' @exif._dataView = getOrientationView '\x02' expect(@exif._readTag('0th', 0).description).toEqual 'top-right' @exif._dataView = getOrientationView '\x03' expect(@exif._readTag('0th', 0).description).toEqual 'bottom-right' @exif._dataView = getOrientationView '\x04' expect(@exif._readTag('0th', 0).description).toEqual 'bottom-left' @exif._dataView = getOrientationView '\x05' expect(@exif._readTag('0th', 0).description).toEqual 'left-top' @exif._dataView = getOrientationView '\x06' expect(@exif._readTag('0th', 0).description).toEqual 'right-top' @exif._dataView = getOrientationView '\x07' expect(@exif._readTag('0th', 0).description).toEqual 'right-bottom' @exif._dataView = getOrientationView '\x08' expect(@exif._readTag('0th', 0).description).toEqual 'left-bottom' it 'should report correct description for YCbCrPositioning', -> @exif._dataView = getDataView '\x02\x13\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('0th', 0).description).toEqual 'centered' @exif._dataView = getDataView '\x02\x13\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('0th', 0).description).toEqual 'co-sited' it 'should report correct description for ResolutionUnit', -> @exif._dataView = getDataView '\x01\x28\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('0th', 0).description).toEqual 'inches' @exif._dataView = getDataView '\x01\x28\x00\x03\x00\x00\x00\x01\x00\x03\x00\x00' expect(@exif._readTag('0th', 0).description).toEqual 'centimeters' it 'should report correct description for Copyright', -> # A NULL B NULL @exif._dataView = getDataView '\x82\x98\x00\x02\x00\x00\x00\x04\x41\x00\x42\x00' expect(@exif._readTag('0th', 0).description).toEqual 'A; B' it 'should report correct description for ExifVersion', -> @exif._dataView = getDataView '\x90\x00\x00\x07\x00\x00\x00\x04\x30\x32\x32\x30' expect(@exif._readTag('exif', 0).description).toEqual '0220' it 'should report correct description for FlashpixVersion', -> @exif._dataView = getDataView '\xa0\x00\x00\x07\x00\x00\x00\x04\x30\x31\x30\x30' expect(@exif._readTag('exif', 0).description).toEqual '0100' it 'should report correct description for ColorSpace', -> @exif._dataView = getDataView '\xa0\x01\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'sRGB' @exif._dataView = getDataView '\xa0\x01\x00\x03\x00\x00\x00\x01\xff\xff\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Uncalibrated' it 'should report correct description for ComponentsConfiguration', -> @exif._dataView = getDataView '\x91\x01\x00\x07\x00\x00\x00\x04\x34\x35\x36\x30' expect(@exif._readTag('exif', 0).description).toEqual 'RGB' @exif._dataView = getDataView '\x91\x01\x00\x07\x00\x00\x00\x04\x31\x32\x33\x30' expect(@exif._readTag('exif', 0).description).toEqual 'YCbCr' it 'should report correct text for ASCII UserComment', -> @exif._dataView = getDataView '\x92\x86\x00\x07\x00\x00\x00\x0b\x00\x00\x00\x0cASCII\x00\x00\x00ABC' expect(@exif._readTag('exif', 0).description).toEqual 'ABC' it 'should report correct character code for UserComment', -> @exif._dataView = getDataView '\x92\x86\x00\x07\x00\x00\x00\x08\x00\x00\x00\x0cJIS\x00\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual '[JIS encoded text]' @exif._dataView = getDataView '\x92\x86\x00\x07\x00\x00\x00\x08\x00\x00\x00\x0cUNICODE\x00' expect(@exif._readTag('exif', 0).description).toEqual '[Unicode encoded text]' @exif._dataView = getDataView '\x92\x86\x00\x07\x00\x00\x00\x08\x00\x00\x00\x0c\x00\x00\x00\x00\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual '[Undefined encoding]' it 'should report correct description for ExposureProgram', -> @exif._dataView = getDataView '\x88\x22\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Undefined' @exif._dataView = getDataView '\x88\x22\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Manual' @exif._dataView = getDataView '\x88\x22\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Normal program' @exif._dataView = getDataView '\x88\x22\x00\x03\x00\x00\x00\x01\x00\x03\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Aperture priority' @exif._dataView = getDataView '\x88\x22\x00\x03\x00\x00\x00\x01\x00\x04\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Shutter priority' @exif._dataView = getDataView '\x88\x22\x00\x03\x00\x00\x00\x01\x00\x05\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Creative program' @exif._dataView = getDataView '\x88\x22\x00\x03\x00\x00\x00\x01\x00\x06\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Action program' @exif._dataView = getDataView '\x88\x22\x00\x03\x00\x00\x00\x01\x00\x07\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Portrait mode' @exif._dataView = getDataView '\x88\x22\x00\x03\x00\x00\x00\x01\x00\x08\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Landscape mode' @exif._dataView = getDataView '\x88\x22\x00\x03\x00\x00\x00\x01\x00\x09\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Unknown' it 'should report correct description for MeteringMode', -> @exif._dataView = getDataView '\x92\x07\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Average' @exif._dataView = getDataView '\x92\x07\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'CenterWeightedAverage' @exif._dataView = getDataView '\x92\x07\x00\x03\x00\x00\x00\x01\x00\x03\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Spot' @exif._dataView = getDataView '\x92\x07\x00\x03\x00\x00\x00\x01\x00\x04\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'MultiSpot' @exif._dataView = getDataView '\x92\x07\x00\x03\x00\x00\x00\x01\x00\x05\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Pattern' @exif._dataView = getDataView '\x92\x07\x00\x03\x00\x00\x00\x01\x00\x06\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Partial' @exif._dataView = getDataView '\x92\x07\x00\x03\x00\x00\x00\x01\x00\xff\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Other' @exif._dataView = getDataView '\x92\x07\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Unknown' it 'should report correct description for LightSource', -> @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Daylight' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Fluorescent' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x03\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Tungsten (incandescent light)' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x04\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x09\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Fine weather' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x0a\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Cloudy weather' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x0b\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Shade' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x0c\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Daylight fluorescent (D 5700 – 7100K)' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x0d\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Day white fluorescent (N 4600 – 5400K)' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x0e\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Cool white fluorescent (W 3900 – 4500K)' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x0f\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'White fluorescent (WW 3200 – 3700K)' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x11\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Standard light A' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x12\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Standard light B' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x13\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Standard light C' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x14\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'D55' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x15\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'D65' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x16\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'D75' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x17\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'D50' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x18\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'ISO studio tungsten' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\xff\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Other light source' @exif._dataView = getDataView '\x92\x08\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Unknown' it 'should report correct description for Flash', -> @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash did not fire' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x05\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Strobe return light not detected' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x07\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Strobe return light detected' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x09\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, compulsory flash mode' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x0d\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, compulsory flash mode, return light not detected' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x0f\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, compulsory flash mode, return light detected' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x10\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash did not fire, compulsory flash mode' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x18\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash did not fire, auto mode' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x19\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, auto mode' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x1d\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, auto mode, return light not detected' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x1f\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, auto mode, return light detected' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x20\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'No flash function' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x41\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, red-eye reduction mode' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x45\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, red-eye reduction mode, return light not detected' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x47\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, red-eye reduction mode, return light detected' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x49\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, compulsory flash mode, red-eye reduction mode' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x4d\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x4f\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, compulsory flash mode, red-eye reduction mode, return light detected' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x59\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, auto mode, red-eye reduction mode' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x5d\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, auto mode, return light not detected, red-eye reduction mode' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x5f\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Flash fired, auto mode, return light detected, red-eye reduction mode' @exif._dataView = getDataView '\x92\x09\x00\x03\x00\x00\x00\x01\x00\x60\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Unknown' it 'should report correct description for SubjectArea', -> @exif._dataView = getDataView '\x92\x14\x00\x03\x00\x00\x00\x02\x47\x11\x48\x12' expect(@exif._readTag('exif', 0).description).toEqual 'Location; X: 18193, Y: 18450' @exif._dataView = getDataView '\x92\x14\x00\x03\x00\x00\x00\x03\x00\x00\x00\x0c\x47\x11\x48\x12\x00\x42' expect(@exif._readTag('exif', 0).description).toEqual 'Circle; X: 18193, Y: 18450, diameter: 66' @exif._dataView = getDataView '\x92\x14\x00\x03\x00\x00\x00\x04\x00\x00\x00\x0c\x47\x11\x48\x12\x00\x42\x00\x43' expect(@exif._readTag('exif', 0).description).toEqual 'Rectangle; X: 18193, Y: 18450, width: 66, height: 67' it 'should report correct description for FocalPlaneResolutionUnit', -> @exif._dataView = getDataView '\xa2\x10\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'inches' @exif._dataView = getDataView '\xa2\x10\x00\x03\x00\x00\x00\x01\x00\x03\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'centimeters' it 'should report correct description for SubjectLocation', -> @exif._dataView = getDataView '\xa2\x14\x00\x03\x00\x00\x00\x02\x47\x11\x48\x12' expect(@exif._readTag('exif', 0).description).toEqual 'X: 18193, Y: 18450' it 'should report correct description for SensingMethod', -> @exif._dataView = getDataView '\xa2\x17\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Undefined' @exif._dataView = getDataView '\xa2\x17\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'One-chip color area sensor' @exif._dataView = getDataView '\xa2\x17\x00\x03\x00\x00\x00\x01\x00\x03\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Two-chip color area sensor' @exif._dataView = getDataView '\xa2\x17\x00\x03\x00\x00\x00\x01\x00\x04\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Three-chip color area sensor' @exif._dataView = getDataView '\xa2\x17\x00\x03\x00\x00\x00\x01\x00\x05\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Color sequential area sensor' @exif._dataView = getDataView '\xa2\x17\x00\x03\x00\x00\x00\x01\x00\x07\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Trilinear sensor' @exif._dataView = getDataView '\xa2\x17\x00\x03\x00\x00\x00\x01\x00\x08\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Color sequential linear sensor' it 'should report correct description for FileSource', -> @exif._dataView = getDataView '\xa3\x00\x00\x07\x00\x00\x00\x01\x03\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'DSC' it 'should report correct description for SceneType', -> @exif._dataView = getDataView '\xa3\x01\x00\x07\x00\x00\x00\x01\x01\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'A directly photographed image' it 'should report correct description for CustomRendered', -> @exif._dataView = getDataView '\xa4\x01\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Normal process' @exif._dataView = getDataView '\xa4\x01\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Custom process' it 'should report correct description for ExposureMode', -> @exif._dataView = getDataView '\xa4\x02\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Auto exposure' @exif._dataView = getDataView '\xa4\x02\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Manual exposure' @exif._dataView = getDataView '\xa4\x02\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Auto bracket' it 'should report correct description for WhiteBalance', -> @exif._dataView = getDataView '\xa4\x03\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Auto white balance' @exif._dataView = getDataView '\xa4\x03\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Manual white balance' it 'should report correct description for DigitalZoomRatio', -> @exif._dataView = getDataView '\xa4\x04\x00\x05\x00\x00\x00\x01\x00\x00\x00\x0c\x00\x00\x00\x00\x00\x00\x00\x42' expect(@exif._readTag('exif', 0).description).toEqual 'Digital zoom was not used' @exif._dataView = getDataView '\xa4\x04\x00\x05\x00\x00\x00\x01\x00\x00\x00\x0c\x00\x00\x47\x11\x00\x00\x00\x42' expect(@exif._readTag('exif', 0).description).toBeCloseTo(275.6515, 4) it 'should report correct description for FocalLengthIn35mmFilm', -> @exif._dataView = getDataView '\xa4\x05\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Unknown' @exif._dataView = getDataView '\xa4\x05\x00\x03\x00\x00\x00\x01\x00\x42\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 0x42 it 'should report correct description for SceneCaptureType', -> @exif._dataView = getDataView '\xa4\x06\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Standard' @exif._dataView = getDataView '\xa4\x06\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Landscape' @exif._dataView = getDataView '\xa4\x06\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Portrait' @exif._dataView = getDataView '\xa4\x06\x00\x03\x00\x00\x00\x01\x00\x03\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Night scene' it 'should report correct description for GainControl', -> @exif._dataView = getDataView '\xa4\x07\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'None' @exif._dataView = getDataView '\xa4\x07\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Low gain up' @exif._dataView = getDataView '\xa4\x07\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'High gain up' @exif._dataView = getDataView '\xa4\x07\x00\x03\x00\x00\x00\x01\x00\x03\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Low gain down' @exif._dataView = getDataView '\xa4\x07\x00\x03\x00\x00\x00\x01\x00\x04\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'High gain down' it 'should report correct description for Contrast', -> @exif._dataView = getDataView '\xa4\x08\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Normal' @exif._dataView = getDataView '\xa4\x08\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Soft' @exif._dataView = getDataView '\xa4\x08\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Hard' it 'should report correct description for Saturation', -> @exif._dataView = getDataView '\xa4\x09\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Normal' @exif._dataView = getDataView '\xa4\x09\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Low saturation' @exif._dataView = getDataView '\xa4\x09\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'High saturation' it 'should report correct description for Sharpness', -> @exif._dataView = getDataView '\xa4\x0a\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Normal' @exif._dataView = getDataView '\xa4\x0a\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Soft' @exif._dataView = getDataView '\xa4\x0a\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Hard' it 'should report correct description for SubjectDistanceRange', -> @exif._dataView = getDataView '\xa4\x0c\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Unknown' @exif._dataView = getDataView '\xa4\x0c\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Macro' @exif._dataView = getDataView '\xa4\x0c\x00\x03\x00\x00\x00\x01\x00\x02\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Close view' @exif._dataView = getDataView '\xa4\x0c\x00\x03\x00\x00\x00\x01\x00\x03\x00\x00' expect(@exif._readTag('exif', 0).description).toEqual 'Distant view' it 'should report correct description for GPSVersionID', -> @exif._dataView = getDataView '\x00\x00\x00\x01\x00\x00\x00\x04\x02\x02\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Version 2.2' it 'should report correct description for GPSLatitudeRef', -> @exif._dataView = getDataView '\x00\x01\x00\x02\x00\x00\x00\x02N\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'North latitude' @exif._dataView = getDataView '\x00\x01\x00\x02\x00\x00\x00\x02S\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'South latitude' it 'should report correct description for GPSLatitude', -> # 37.231969, 115.811119 (37° 13' 55.0878", 115° 48' 40.0284") @exif._dataView = getDataView '\x00\x02\x00\x05\x00\x00\x00\x03\x00\x00\x00\x0c' + '\x00\x00\x00\x25\x00\x00\x00\x01' + '\x00\x00\x00\x0d\x00\x00\x00\x01' + '\x00\x08\x67\xde\x00\x00\x27\x10' expect(@exif._readTag('gps', 0).description).toBeCloseTo(37.231969, 6) it 'should report correct description for GPSLongitudeRef', -> @exif._dataView = getDataView '\x00\x03\x00\x02\x00\x00\x00\x02E\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'East longitude' @exif._dataView = getDataView '\x00\x03\x00\x02\x00\x00\x00\x02W\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'West longitude' it 'should report correct description for GPSLongitude', -> # 37.231969, 115.811119 (37° 13' 55.0878", 115° 48' 40.0284") @exif._dataView = getDataView '\x00\x04\x00\x05\x00\x00\x00\x03\x00\x00\x00\x0c' + '\x00\x00\x00\x73\x00\x00\x00\x01' + '\x00\x00\x00\x30\x00\x00\x00\x01' + '\x00\x06\x1b\x9c\x00\x00\x27\x10' expect(@exif._readTag('gps', 0).description).toBeCloseTo(115.811119, 6) it 'should report correct description for GPSAltitudeRef', -> @exif._dataView = getDataView '\x00\x05\x00\x01\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Sea level' @exif._dataView = getDataView '\x00\x05\x00\x01\x00\x00\x00\x01\x01\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Sea level reference (negative value)' it 'should report correct description for GPSAltitude', -> @exif._dataView = getDataView '\x00\x06\x00\x05\x00\x00\x00\x01\x00\x00\x00\x0c' + '\x00\x00\x00\x2a\x00\x00\x00\x01' expect(@exif._readTag('gps', 0).description).toEqual '42 m' it 'should report correct description for GPSTimeStamp', -> @exif._dataView = getDataView '\x00\x07\x00\x05\x00\x00\x00\x03\x00\x00\x00\x0c' + '\x00\x00\x00\x06\x00\x00\x00\x01' + '\x00\x00\x00\x07\x00\x00\x00\x01' + '\x00\x00\x0c\xb0\x00\x00\x00\x64' expect(@exif._readTag('gps', 0).description).toEqual '06:07:32.48' @exif._dataView = getDataView '\x00\x07\x00\x05\x00\x00\x00\x03\x00\x00\x00\x0c' + '\x00\x00\x00\x06\x00\x00\x00\x01' + '\x00\x00\x00\x00\x00\x00\x00\x01' + '\x00\x00\x0c\xb0\x00\x00\x00\x64' expect(@exif._readTag('gps', 0).description).toEqual '06:00:32.48' it 'should report correct description for GPSStatus', -> @exif._dataView = getDataView '\x00\x09\x00\x02\x00\x00\x00\x02A\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Measurement in progress' @exif._dataView = getDataView '\x00\x09\x00\x02\x00\x00\x00\x02V\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Measurement Interoperability' it 'should report correct description for GPSMeasureMode', -> @exif._dataView = getDataView '\x00\x0a\x00\x02\x00\x00\x00\x022\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual '2-dimensional measurement' @exif._dataView = getDataView '\x00\x0a\x00\x02\x00\x00\x00\x023\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual '3-dimensional measurement' it 'should report correct description for GPSSpeedRef', -> @exif._dataView = getDataView '\x00\x0c\x00\x02\x00\x00\x00\x02K\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Kilometers per hour' @exif._dataView = getDataView '\x00\x0c\x00\x02\x00\x00\x00\x02M\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Miles per hour' @exif._dataView = getDataView '\x00\x0c\x00\x02\x00\x00\x00\x02N\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Knots' it 'should report correct description for GPSTrackRef', -> @exif._dataView = getDataView '\x00\x0e\x00\x02\x00\x00\x00\x02T\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'True direction' @exif._dataView = getDataView '\x00\x0e\x00\x02\x00\x00\x00\x02M\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Magnetic direction' it 'should report correct description for GPSImgDirectionRef', -> @exif._dataView = getDataView '\x00\x10\x00\x02\x00\x00\x00\x02T\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'True direction' @exif._dataView = getDataView '\x00\x10\x00\x02\x00\x00\x00\x02M\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Magnetic direction' it 'should report correct description for GPSDestLatitudeRef', -> @exif._dataView = getDataView '\x00\x13\x00\x02\x00\x00\x00\x02N\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'North latitude' @exif._dataView = getDataView '\x00\x13\x00\x02\x00\x00\x00\x02S\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'South latitude' it 'should report correct description for GPSDestLatitude', -> # 37.231969, 115.811119 (37° 13' 55.0878", 115° 48' 40.0284") @exif._dataView = getDataView '\x00\x14\x00\x05\x00\x00\x00\x03\x00\x00\x00\x0c' + '\x00\x00\x00\x25\x00\x00\x00\x01' + '\x00\x00\x00\x0d\x00\x00\x00\x01' + '\x00\x08\x67\xde\x00\x00\x27\x10' expect(@exif._readTag('gps', 0).description).toBeCloseTo(37.231969, 6) it 'should report correct description for GPSDestLongitudeRef', -> @exif._dataView = getDataView '\x00\x15\x00\x02\x00\x00\x00\x02E\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'East longitude' @exif._dataView = getDataView '\x00\x15\x00\x02\x00\x00\x00\x02W\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'West longitude' it 'should report correct description for GPSDestLongitude', -> # 37.231969, 115.811119 (37° 13' 55.0878", 115° 48' 40.0284") @exif._dataView = getDataView '\x00\x16\x00\x05\x00\x00\x00\x03\x00\x00\x00\x0c' + '\x00\x00\x00\x73\x00\x00\x00\x01' + '\x00\x00\x00\x30\x00\x00\x00\x01' + '\x00\x06\x1b\x9c\x00\x00\x27\x10' expect(@exif._readTag('gps', 0).description).toBeCloseTo(115.811119, 6) it 'should report correct description for GPSDestBearingRef', -> @exif._dataView = getDataView '\x00\x17\x00\x02\x00\x00\x00\x02T\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'True direction' @exif._dataView = getDataView '\x00\x0e\x00\x02\x00\x00\x00\x02M\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Magnetic direction' it 'should report correct description for GPSDestDistanceRef', -> @exif._dataView = getDataView '\x00\x19\x00\x02\x00\x00\x00\x02K\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Kilometers' @exif._dataView = getDataView '\x00\x19\x00\x02\x00\x00\x00\x02M\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Miles' @exif._dataView = getDataView '\x00\x19\x00\x02\x00\x00\x00\x02N\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Knots' it 'should report correct description for GPSDifferential', -> @exif._dataView = getDataView '\x00\x1e\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Measurement without differential correction' @exif._dataView = getDataView '\x00\x1e\x00\x03\x00\x00\x00\x01\x00\x01\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual 'Differential correction applied' it 'should report correct text for ASCII GPSProcessingMethod', -> @exif._dataView = getDataView '\x00\x1b\x00\x07\x00\x00\x00\x0b\x00\x00\x00\x0cASCII\x00\x00\x00ABC' expect(@exif._readTag('gps', 0).description).toEqual 'ABC' it 'should report correct character code for GPSProcessingMethod', -> @exif._dataView = getDataView '\x00\x1b\x00\x07\x00\x00\x00\x08\x00\x00\x00\x0cJIS\x00\x00\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual '[JIS encoded text]' @exif._dataView = getDataView '\x00\x1b\x00\x07\x00\x00\x00\x08\x00\x00\x00\x0cUNICODE\x00' expect(@exif._readTag('gps', 0).description).toEqual '[Unicode encoded text]' @exif._dataView = getDataView '\x00\x1b\x00\x07\x00\x00\x00\x08\x00\x00\x00\x0c\x00\x00\x00\x00\x00\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual '[Undefined encoding]' it 'should report correct text for ASCII GPSAreaInformation', -> @exif._dataView = getDataView '\x00\x1c\x00\x07\x00\x00\x00\x0b\x00\x00\x00\x0cASCII\x00\x00\x00ABC' expect(@exif._readTag('gps', 0).description).toEqual 'ABC' it 'should report correct character code for GPSAreaInformation', -> @exif._dataView = getDataView '\x00\x1c\x00\x07\x00\x00\x00\x08\x00\x00\x00\x0cJIS\x00\x00\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual '[JIS encoded text]' @exif._dataView = getDataView '\x00\x1c\x00\x07\x00\x00\x00\x08\x00\x00\x00\x0cUNICODE\x00' expect(@exif._readTag('gps', 0).description).toEqual '[Unicode encoded text]' @exif._dataView = getDataView '\x00\x1c\x00\x07\x00\x00\x00\x08\x00\x00\x00\x0c\x00\x00\x00\x00\x00\x00\x00\x00' expect(@exif._readTag('gps', 0).description).toEqual '[Undefined encoding]'
[ { "context": "ableView - table base data manage class\n# Coded by Hajime Oh-yake 2013.09.10\n#*************************************", "end": 113, "score": 0.999890148639679, "start": 99, "tag": "NAME", "value": "Hajime Oh-yake" }, { "context": "ze.width, @_rowHeight))\n @_titl...
JSKit/04_JSTableView.coffee
digitarhythm/codeJS
0
#***************************************** # JSTableView - table base data manage class # Coded by Hajime Oh-yake 2013.09.10 #***************************************** class JSTableView extends JSView constructor:(frame)-> if (!frame?) frame = getBounds() super(frame) @_rowHeight = 32 @_clipToBounds = true @_bgColor = JSColor("white") @_scroll = true @_titlebarColor = JSColor("#d0d8e0") @_titleColor = JSColor("black") @_title = "Title Bar" @_titleBar = undefined @_tableView = undefined @delegate = null @dataSource = null @childlist = [] @bounds = getBounds() setRowHeight:(@_rowHeight)-> destructor:-> super() addTableView:-> # 各セクションに含まれるデータの数を取得する(デリゲートメソッドが無い場合はデータの数は初期値(0)) if (typeof @dataSource.numberOfRowsInSection == 'function') @_dataNum = @dataSource.numberOfRowsInSection() else @_dataNum = 0 # セクションの数を取得する(デリゲートメソッドが無い場合は初期値(1)のまま) if (typeof @dataSource.numberOfSectionsInTableView == 'function') @_sectionNum = @dataSource.numberOfSectionsInTableView() else @_sectionNum = 1 @_tableView.setScroll(true) # 各セルの内容を返すデリゲートメソッドを呼ぶ diff_y = @_rowHeight @_parent.bringSubviewToFront(@_self) for i in [0...@_dataNum] # 各セルの高さを取得して設定する if (typeof @delegate.heightForRowAtIndexPath == 'function') cellHeight = @delegate.heightForRowAtIndexPath(i) else cellHeight = @_rowHeight cell = @dataSource.cellForRowAtIndexPath(i) cell._cellnum = i cell.delegate = @delegate cell._tableview = @ @childlist.push(cell) cell.setFrame(JSRectMake(1, diff_y, @_frame.size.width - 4, cellHeight)) @_tableView.addSubview(cell) diff_y += cellHeight+1 reloadData:-> if (@_tableView?) for obj in @childlist obj.removeFromSuperview() @addTableView() selectRowAtIndexPath:(num)-> if (@_tableView?) for obj, i in @childlist if (i == num) obj.setBackgroundColor(JSColor("#87cefa")) deselectRowAtIndexPath:-> if (@_tableView?) for obj in @childlist obj.setBackgroundColor(JSColor('clearColor')) viewDidAppear:-> super() if (!@_tableView?) if (!@_titleBar?) @_titleBar = new JSLabel(JSRectMake(0, 0, @_frame.size.width, @_rowHeight)) @_titleBar.setText(@_title) @_titleBar.setTextAlignment("JSTextAlignmentLeft") @_titleBar.setTextSize(11) @_titleBar.setBackgroundColor(@_titlebarColor) @_titleBar.setTextColor(@_titleColor) @_titleBar.setAlpha(0.9) frm = JSRectMake(0, 0, @_frame.size.width, @_frame.size.height) @_tableView = new JSScrollView(frm) @_tableView.setBackgroundColor(@_bgColor) @_tableView.setAlpha(@_alpha) @_tableView.setCornerRadius(@_cornerRadius) @_tableView.setBorderColor(@_borderColor) @_tableView.setBorderWidth(@_borderWidth) @_self.addSubview(@_tableView) @addTableView() @_self.addSubview(@_titleBar)
48585
#***************************************** # JSTableView - table base data manage class # Coded by <NAME> 2013.09.10 #***************************************** class JSTableView extends JSView constructor:(frame)-> if (!frame?) frame = getBounds() super(frame) @_rowHeight = 32 @_clipToBounds = true @_bgColor = JSColor("white") @_scroll = true @_titlebarColor = JSColor("#d0d8e0") @_titleColor = JSColor("black") @_title = "Title Bar" @_titleBar = undefined @_tableView = undefined @delegate = null @dataSource = null @childlist = [] @bounds = getBounds() setRowHeight:(@_rowHeight)-> destructor:-> super() addTableView:-> # 各セクションに含まれるデータの数を取得する(デリゲートメソッドが無い場合はデータの数は初期値(0)) if (typeof @dataSource.numberOfRowsInSection == 'function') @_dataNum = @dataSource.numberOfRowsInSection() else @_dataNum = 0 # セクションの数を取得する(デリゲートメソッドが無い場合は初期値(1)のまま) if (typeof @dataSource.numberOfSectionsInTableView == 'function') @_sectionNum = @dataSource.numberOfSectionsInTableView() else @_sectionNum = 1 @_tableView.setScroll(true) # 各セルの内容を返すデリゲートメソッドを呼ぶ diff_y = @_rowHeight @_parent.bringSubviewToFront(@_self) for i in [0...@_dataNum] # 各セルの高さを取得して設定する if (typeof @delegate.heightForRowAtIndexPath == 'function') cellHeight = @delegate.heightForRowAtIndexPath(i) else cellHeight = @_rowHeight cell = @dataSource.cellForRowAtIndexPath(i) cell._cellnum = i cell.delegate = @delegate cell._tableview = @ @childlist.push(cell) cell.setFrame(JSRectMake(1, diff_y, @_frame.size.width - 4, cellHeight)) @_tableView.addSubview(cell) diff_y += cellHeight+1 reloadData:-> if (@_tableView?) for obj in @childlist obj.removeFromSuperview() @addTableView() selectRowAtIndexPath:(num)-> if (@_tableView?) for obj, i in @childlist if (i == num) obj.setBackgroundColor(JSColor("#87cefa")) deselectRowAtIndexPath:-> if (@_tableView?) for obj in @childlist obj.setBackgroundColor(JSColor('clearColor')) viewDidAppear:-> super() if (!@_tableView?) if (!@_titleBar?) @_titleBar = new JSLabel(JSRectMake(0, 0, @_frame.size.width, @_rowHeight)) @_titleBar.setText(@_title) @_titleBar.setTextAlignment("JSTextAlignmentLeft") @_titleBar.setTextSize(11) @_titleBar.setBackgroundColor(@_titlebarColor) @_titleBar.setTextColor(@_titleColor) @_titleBar.setAlpha(0.9) frm = JSRectMake(0, 0, @_frame.size.width, @_frame.size.height) @_tableView = new JSScrollView(frm) @_tableView.setBackgroundColor(@_bgColor) @_tableView.setAlpha(@_alpha) @_tableView.setCornerRadius(@_cornerRadius) @_tableView.setBorderColor(@_borderColor) @_tableView.setBorderWidth(@_borderWidth) @_self.addSubview(@_tableView) @addTableView() @_self.addSubview(@_titleBar)
true
#***************************************** # JSTableView - table base data manage class # Coded by PI:NAME:<NAME>END_PI 2013.09.10 #***************************************** class JSTableView extends JSView constructor:(frame)-> if (!frame?) frame = getBounds() super(frame) @_rowHeight = 32 @_clipToBounds = true @_bgColor = JSColor("white") @_scroll = true @_titlebarColor = JSColor("#d0d8e0") @_titleColor = JSColor("black") @_title = "Title Bar" @_titleBar = undefined @_tableView = undefined @delegate = null @dataSource = null @childlist = [] @bounds = getBounds() setRowHeight:(@_rowHeight)-> destructor:-> super() addTableView:-> # 各セクションに含まれるデータの数を取得する(デリゲートメソッドが無い場合はデータの数は初期値(0)) if (typeof @dataSource.numberOfRowsInSection == 'function') @_dataNum = @dataSource.numberOfRowsInSection() else @_dataNum = 0 # セクションの数を取得する(デリゲートメソッドが無い場合は初期値(1)のまま) if (typeof @dataSource.numberOfSectionsInTableView == 'function') @_sectionNum = @dataSource.numberOfSectionsInTableView() else @_sectionNum = 1 @_tableView.setScroll(true) # 各セルの内容を返すデリゲートメソッドを呼ぶ diff_y = @_rowHeight @_parent.bringSubviewToFront(@_self) for i in [0...@_dataNum] # 各セルの高さを取得して設定する if (typeof @delegate.heightForRowAtIndexPath == 'function') cellHeight = @delegate.heightForRowAtIndexPath(i) else cellHeight = @_rowHeight cell = @dataSource.cellForRowAtIndexPath(i) cell._cellnum = i cell.delegate = @delegate cell._tableview = @ @childlist.push(cell) cell.setFrame(JSRectMake(1, diff_y, @_frame.size.width - 4, cellHeight)) @_tableView.addSubview(cell) diff_y += cellHeight+1 reloadData:-> if (@_tableView?) for obj in @childlist obj.removeFromSuperview() @addTableView() selectRowAtIndexPath:(num)-> if (@_tableView?) for obj, i in @childlist if (i == num) obj.setBackgroundColor(JSColor("#87cefa")) deselectRowAtIndexPath:-> if (@_tableView?) for obj in @childlist obj.setBackgroundColor(JSColor('clearColor')) viewDidAppear:-> super() if (!@_tableView?) if (!@_titleBar?) @_titleBar = new JSLabel(JSRectMake(0, 0, @_frame.size.width, @_rowHeight)) @_titleBar.setText(@_title) @_titleBar.setTextAlignment("JSTextAlignmentLeft") @_titleBar.setTextSize(11) @_titleBar.setBackgroundColor(@_titlebarColor) @_titleBar.setTextColor(@_titleColor) @_titleBar.setAlpha(0.9) frm = JSRectMake(0, 0, @_frame.size.width, @_frame.size.height) @_tableView = new JSScrollView(frm) @_tableView.setBackgroundColor(@_bgColor) @_tableView.setAlpha(@_alpha) @_tableView.setCornerRadius(@_cornerRadius) @_tableView.setBorderColor(@_borderColor) @_tableView.setBorderWidth(@_borderWidth) @_self.addSubview(@_tableView) @addTableView() @_self.addSubview(@_titleBar)
[ { "context": "\"2016\",\n \"first_name\":\"CFN\",\n \"last_name\":\"CLN\",\n", "end": 768, "score": 0.9997838139533997, "start": 765, "tag": "NAME", "value": "CFN" }, { "context": "\":\"CFN\",\n \"last_n...
models/account/fixture/get_creditcard.coffee
signonsridhar/sridhar_hbs
0
define(['can_fixture'], (can)-> can.fixture('GET /bss/account?action=getcreditcard',(req, res)-> return { "response":{ "service":"getcreditcard", "response_code":100, "execution_time":856, "timestamp":"2013-11-25T18:56:03+0000", "response_data":{ "creditcards":[ { "creditcardid":"2", "address1":"295 n bernado ave", "city":"mountain view", "country":"US", "expiration_month":"3", "expiration_year":"2016", "first_name":"CFN", "last_name":"CLN", "number":"XXXX-1111", "zip_code":"94043", "state":"CA", "card_type":"Visa", "primary":true } ] }, "version":"1.0" } } ) )
143705
define(['can_fixture'], (can)-> can.fixture('GET /bss/account?action=getcreditcard',(req, res)-> return { "response":{ "service":"getcreditcard", "response_code":100, "execution_time":856, "timestamp":"2013-11-25T18:56:03+0000", "response_data":{ "creditcards":[ { "creditcardid":"2", "address1":"295 n bernado ave", "city":"mountain view", "country":"US", "expiration_month":"3", "expiration_year":"2016", "first_name":"<NAME>", "last_name":"<NAME>", "number":"XXXX-1111", "zip_code":"94043", "state":"CA", "card_type":"Visa", "primary":true } ] }, "version":"1.0" } } ) )
true
define(['can_fixture'], (can)-> can.fixture('GET /bss/account?action=getcreditcard',(req, res)-> return { "response":{ "service":"getcreditcard", "response_code":100, "execution_time":856, "timestamp":"2013-11-25T18:56:03+0000", "response_data":{ "creditcards":[ { "creditcardid":"2", "address1":"295 n bernado ave", "city":"mountain view", "country":"US", "expiration_month":"3", "expiration_year":"2016", "first_name":"PI:NAME:<NAME>END_PI", "last_name":"PI:NAME:<NAME>END_PI", "number":"XXXX-1111", "zip_code":"94043", "state":"CA", "card_type":"Visa", "primary":true } ] }, "version":"1.0" } } ) )
[ { "context": "asset/upload\"\n params: {id: id, name: name, dataModel: $scope.currentDataModel?.id, filename", "end": 3774, "score": 0.7320658564567566, "start": 3770, "tag": "NAME", "value": "name" } ]
ModelCatalogueCorePluginTestApp/grails-app/assets/javascripts/modelcatalogue/core/ui/states/dataModel/resource/xmlEditor/xmlEditorCtrl.coffee
passionfruit18/ModelCataloguePlugin
0
angular.module('modelcatalogue.core.ui.states.dataModel.resource.xmlEditor.xmlEditorCtrl', ['ui.ace', 'ngFileSaver', 'modelcatalogue.core.ui.states.dataModel.resource.xmlEditor.xsltTransformer', 'mc.util.ui.actions']) .controller('modelcatalogue.core.ui.states.dataModel.resource.xmlEditor.xmlEditorCtrl', [ '$log', '$scope', '$stateParams', '$state', '$timeout', 'element', 'applicationTitle', '$http', 'catalogue', 'security', 'FileSaver', 'Blob', 'xsltTransformer', 'actionRoleAccess', ($log, $scope, $stateParams, $state, $timeout, element, applicationTitle, $http, catalogue, security, FileSaver, Blob, xsltTransformer, actionRoleAccess) -> $scope.actionRoleAccess = actionRoleAccess applicationTitle "Xml Editor for #{element.getLabel()}" $scope.element = element $scope.transformationInProgress = false transform = (newValues) -> xml = newValues[0] xslt = newValues[1] return unless xml and xslt $log.debug("transformation started", {xml: xml, xslt: xslt}) $timeout( -> $scope.transformationInProgress = true , 500 ) xsltTransformer.transformXml(xml, xslt) .then (result) -> $scope.xsd = result $log.debug("transformation succeeded with result", {xsd: result}) .catch (error) -> $scope.xsd = error.message $log.debug("transformation failed with error", error) .finally () -> $timeout( -> $scope.transformationInProgress = false , 500 ) $http.get("#{element.internalModelCatalogueId}?format=xml&full=true&repetitive=true").then (resp) -> $scope.xml = resp.data $http.get("#{security.contextPath}#{catalogue.getDefaultXslt(element.elementType) ? catalogue.getDefaultXslt('catalogueElement')}").then (resp) -> $scope.xslt = resp.data $scope.download = (name, text, mimeType = 'text/xml;charset=utf-8') -> FileSaver.saveAs(new Blob([text], type: mimeType), name) $scope.$watchGroup ['xml', 'xslt'], transform ]) .config(['actionsProvider', 'actionRoleRegister', 'actionClass', (actionsProvider, actionRoleRegister, actionClass) -> Action = actionClass actionsProvider.registerActionInRole 'load-xslt', actionRoleRegister.ROLE_XMLEDITOR_XSLT_ACTION, [ '$log', '$scope','messages', ($log, $scope, messages) -> Action.createStandardAction( position: null label: 'Load XSLT' icon: 'fa fa-file-code-o' type: null action: -> messages .prompt("Select Stylesheet", "Select stylesheet to be loaded", type: 'catalogue-element', resource: 'asset', contentType: 'text/xsl') .then (asset) -> $scope.xsltAsset = asset $log.debug("loaded asset", asset) return asset.execute('content') .then (resp) -> $scope.xslt = resp ) ] actionsProvider.registerActionInRole 'save-xslt', actionRoleRegister.ROLE_XMLEDITOR_XSLT_ACTION, [ '$log', '$scope','messages', 'Upload', 'modelCatalogueApiRoot', 'enhance', ($log, $scope, messages, Upload, modelCatalogueApiRoot, enhance) -> Action.createStandardAction( position: null label: 'Save Stylesheet' icon: 'fa fa-save' type: null action: -> messages .prompt("Save Stylesheet", "Asset name", type: 'catalogue-element', resource: 'asset', contentType: 'text/xsl', allowString: true, value: $scope.xsltAsset) .then (asset) -> if angular.isString(asset) name = asset else id = asset.id name = asset.name $scope.upload = Upload.upload({ url: "#{modelCatalogueApiRoot}/asset/upload" params: {id: id, name: name, dataModel: $scope.currentDataModel?.id, filename: "#{name}.xsl"} data: {asset: new Blob([$scope.xslt], {type: 'text/xsl'})} }).progress((evt) -> $scope.progress = parseInt(100.0 * evt.loaded / evt.total) ).success((result) -> $scope.xsltAsset = enhance(result) $log.debug("asset saved", result) messages.success "Asset was successfully saved." ).catch( (reason) -> $log.error("asset was not saved", reason) messages.error "Could not save asset. #{reason}" ) ) ] actionsProvider.registerActionInRole 'save-xsd', actionRoleRegister.ROLE_XMLEDITOR_XSD_ACTION, [ '$log', '$scope','messages', 'Upload', 'modelCatalogueApiRoot', 'enhance', ($log, $scope, messages, Upload, modelCatalogueApiRoot, enhance) -> Action.createStandardAction( position: null label: 'Save Schema' icon: 'fa fa-save' type: null action: -> messages .prompt("Save Schema", "Asset name", type: 'catalogue-element', resource: 'asset', contentType: 'text/xml', allowString: true, value: $scope.xsdAsset) .then (asset) -> if angular.isString(asset) name = asset else id = asset.id name = asset.name $scope.upload = Upload.upload({ url: "#{modelCatalogueApiRoot}/asset/upload" params: {id: id, name: name, dataModel: $scope.currentDataModel?.id, filename: "#{name}.xsd"} data: {asset: new Blob([$scope.xsd], {type: 'text/xml'})} }).progress((evt) -> $scope.progress = parseInt(100.0 * evt.loaded / evt.total) ).success((result) -> $scope.xsdAsset = enhance(result) $log.debug("asset saved", result) messages.success "Asset was successfuly saved." ).catch( (reason) -> $log.error("asset was not saved", reason) messages.error "Could not save asset. #{reason}" ) ) ] actionsProvider.registerActionInRole 'load-xslt', actionRoleRegister.ROLE_XMLEDITOR_XSD_ACTION, [ '$scope', ($scope) -> Action.createStandardAction( position: null label: 'Download Result' icon: 'fa fa-download' type: null action: -> $scope.download('Result.xsd', $scope.xsd) ) ] ])
156109
angular.module('modelcatalogue.core.ui.states.dataModel.resource.xmlEditor.xmlEditorCtrl', ['ui.ace', 'ngFileSaver', 'modelcatalogue.core.ui.states.dataModel.resource.xmlEditor.xsltTransformer', 'mc.util.ui.actions']) .controller('modelcatalogue.core.ui.states.dataModel.resource.xmlEditor.xmlEditorCtrl', [ '$log', '$scope', '$stateParams', '$state', '$timeout', 'element', 'applicationTitle', '$http', 'catalogue', 'security', 'FileSaver', 'Blob', 'xsltTransformer', 'actionRoleAccess', ($log, $scope, $stateParams, $state, $timeout, element, applicationTitle, $http, catalogue, security, FileSaver, Blob, xsltTransformer, actionRoleAccess) -> $scope.actionRoleAccess = actionRoleAccess applicationTitle "Xml Editor for #{element.getLabel()}" $scope.element = element $scope.transformationInProgress = false transform = (newValues) -> xml = newValues[0] xslt = newValues[1] return unless xml and xslt $log.debug("transformation started", {xml: xml, xslt: xslt}) $timeout( -> $scope.transformationInProgress = true , 500 ) xsltTransformer.transformXml(xml, xslt) .then (result) -> $scope.xsd = result $log.debug("transformation succeeded with result", {xsd: result}) .catch (error) -> $scope.xsd = error.message $log.debug("transformation failed with error", error) .finally () -> $timeout( -> $scope.transformationInProgress = false , 500 ) $http.get("#{element.internalModelCatalogueId}?format=xml&full=true&repetitive=true").then (resp) -> $scope.xml = resp.data $http.get("#{security.contextPath}#{catalogue.getDefaultXslt(element.elementType) ? catalogue.getDefaultXslt('catalogueElement')}").then (resp) -> $scope.xslt = resp.data $scope.download = (name, text, mimeType = 'text/xml;charset=utf-8') -> FileSaver.saveAs(new Blob([text], type: mimeType), name) $scope.$watchGroup ['xml', 'xslt'], transform ]) .config(['actionsProvider', 'actionRoleRegister', 'actionClass', (actionsProvider, actionRoleRegister, actionClass) -> Action = actionClass actionsProvider.registerActionInRole 'load-xslt', actionRoleRegister.ROLE_XMLEDITOR_XSLT_ACTION, [ '$log', '$scope','messages', ($log, $scope, messages) -> Action.createStandardAction( position: null label: 'Load XSLT' icon: 'fa fa-file-code-o' type: null action: -> messages .prompt("Select Stylesheet", "Select stylesheet to be loaded", type: 'catalogue-element', resource: 'asset', contentType: 'text/xsl') .then (asset) -> $scope.xsltAsset = asset $log.debug("loaded asset", asset) return asset.execute('content') .then (resp) -> $scope.xslt = resp ) ] actionsProvider.registerActionInRole 'save-xslt', actionRoleRegister.ROLE_XMLEDITOR_XSLT_ACTION, [ '$log', '$scope','messages', 'Upload', 'modelCatalogueApiRoot', 'enhance', ($log, $scope, messages, Upload, modelCatalogueApiRoot, enhance) -> Action.createStandardAction( position: null label: 'Save Stylesheet' icon: 'fa fa-save' type: null action: -> messages .prompt("Save Stylesheet", "Asset name", type: 'catalogue-element', resource: 'asset', contentType: 'text/xsl', allowString: true, value: $scope.xsltAsset) .then (asset) -> if angular.isString(asset) name = asset else id = asset.id name = asset.name $scope.upload = Upload.upload({ url: "#{modelCatalogueApiRoot}/asset/upload" params: {id: id, name: <NAME>, dataModel: $scope.currentDataModel?.id, filename: "#{name}.xsl"} data: {asset: new Blob([$scope.xslt], {type: 'text/xsl'})} }).progress((evt) -> $scope.progress = parseInt(100.0 * evt.loaded / evt.total) ).success((result) -> $scope.xsltAsset = enhance(result) $log.debug("asset saved", result) messages.success "Asset was successfully saved." ).catch( (reason) -> $log.error("asset was not saved", reason) messages.error "Could not save asset. #{reason}" ) ) ] actionsProvider.registerActionInRole 'save-xsd', actionRoleRegister.ROLE_XMLEDITOR_XSD_ACTION, [ '$log', '$scope','messages', 'Upload', 'modelCatalogueApiRoot', 'enhance', ($log, $scope, messages, Upload, modelCatalogueApiRoot, enhance) -> Action.createStandardAction( position: null label: 'Save Schema' icon: 'fa fa-save' type: null action: -> messages .prompt("Save Schema", "Asset name", type: 'catalogue-element', resource: 'asset', contentType: 'text/xml', allowString: true, value: $scope.xsdAsset) .then (asset) -> if angular.isString(asset) name = asset else id = asset.id name = asset.name $scope.upload = Upload.upload({ url: "#{modelCatalogueApiRoot}/asset/upload" params: {id: id, name: name, dataModel: $scope.currentDataModel?.id, filename: "#{name}.xsd"} data: {asset: new Blob([$scope.xsd], {type: 'text/xml'})} }).progress((evt) -> $scope.progress = parseInt(100.0 * evt.loaded / evt.total) ).success((result) -> $scope.xsdAsset = enhance(result) $log.debug("asset saved", result) messages.success "Asset was successfuly saved." ).catch( (reason) -> $log.error("asset was not saved", reason) messages.error "Could not save asset. #{reason}" ) ) ] actionsProvider.registerActionInRole 'load-xslt', actionRoleRegister.ROLE_XMLEDITOR_XSD_ACTION, [ '$scope', ($scope) -> Action.createStandardAction( position: null label: 'Download Result' icon: 'fa fa-download' type: null action: -> $scope.download('Result.xsd', $scope.xsd) ) ] ])
true
angular.module('modelcatalogue.core.ui.states.dataModel.resource.xmlEditor.xmlEditorCtrl', ['ui.ace', 'ngFileSaver', 'modelcatalogue.core.ui.states.dataModel.resource.xmlEditor.xsltTransformer', 'mc.util.ui.actions']) .controller('modelcatalogue.core.ui.states.dataModel.resource.xmlEditor.xmlEditorCtrl', [ '$log', '$scope', '$stateParams', '$state', '$timeout', 'element', 'applicationTitle', '$http', 'catalogue', 'security', 'FileSaver', 'Blob', 'xsltTransformer', 'actionRoleAccess', ($log, $scope, $stateParams, $state, $timeout, element, applicationTitle, $http, catalogue, security, FileSaver, Blob, xsltTransformer, actionRoleAccess) -> $scope.actionRoleAccess = actionRoleAccess applicationTitle "Xml Editor for #{element.getLabel()}" $scope.element = element $scope.transformationInProgress = false transform = (newValues) -> xml = newValues[0] xslt = newValues[1] return unless xml and xslt $log.debug("transformation started", {xml: xml, xslt: xslt}) $timeout( -> $scope.transformationInProgress = true , 500 ) xsltTransformer.transformXml(xml, xslt) .then (result) -> $scope.xsd = result $log.debug("transformation succeeded with result", {xsd: result}) .catch (error) -> $scope.xsd = error.message $log.debug("transformation failed with error", error) .finally () -> $timeout( -> $scope.transformationInProgress = false , 500 ) $http.get("#{element.internalModelCatalogueId}?format=xml&full=true&repetitive=true").then (resp) -> $scope.xml = resp.data $http.get("#{security.contextPath}#{catalogue.getDefaultXslt(element.elementType) ? catalogue.getDefaultXslt('catalogueElement')}").then (resp) -> $scope.xslt = resp.data $scope.download = (name, text, mimeType = 'text/xml;charset=utf-8') -> FileSaver.saveAs(new Blob([text], type: mimeType), name) $scope.$watchGroup ['xml', 'xslt'], transform ]) .config(['actionsProvider', 'actionRoleRegister', 'actionClass', (actionsProvider, actionRoleRegister, actionClass) -> Action = actionClass actionsProvider.registerActionInRole 'load-xslt', actionRoleRegister.ROLE_XMLEDITOR_XSLT_ACTION, [ '$log', '$scope','messages', ($log, $scope, messages) -> Action.createStandardAction( position: null label: 'Load XSLT' icon: 'fa fa-file-code-o' type: null action: -> messages .prompt("Select Stylesheet", "Select stylesheet to be loaded", type: 'catalogue-element', resource: 'asset', contentType: 'text/xsl') .then (asset) -> $scope.xsltAsset = asset $log.debug("loaded asset", asset) return asset.execute('content') .then (resp) -> $scope.xslt = resp ) ] actionsProvider.registerActionInRole 'save-xslt', actionRoleRegister.ROLE_XMLEDITOR_XSLT_ACTION, [ '$log', '$scope','messages', 'Upload', 'modelCatalogueApiRoot', 'enhance', ($log, $scope, messages, Upload, modelCatalogueApiRoot, enhance) -> Action.createStandardAction( position: null label: 'Save Stylesheet' icon: 'fa fa-save' type: null action: -> messages .prompt("Save Stylesheet", "Asset name", type: 'catalogue-element', resource: 'asset', contentType: 'text/xsl', allowString: true, value: $scope.xsltAsset) .then (asset) -> if angular.isString(asset) name = asset else id = asset.id name = asset.name $scope.upload = Upload.upload({ url: "#{modelCatalogueApiRoot}/asset/upload" params: {id: id, name: PI:NAME:<NAME>END_PI, dataModel: $scope.currentDataModel?.id, filename: "#{name}.xsl"} data: {asset: new Blob([$scope.xslt], {type: 'text/xsl'})} }).progress((evt) -> $scope.progress = parseInt(100.0 * evt.loaded / evt.total) ).success((result) -> $scope.xsltAsset = enhance(result) $log.debug("asset saved", result) messages.success "Asset was successfully saved." ).catch( (reason) -> $log.error("asset was not saved", reason) messages.error "Could not save asset. #{reason}" ) ) ] actionsProvider.registerActionInRole 'save-xsd', actionRoleRegister.ROLE_XMLEDITOR_XSD_ACTION, [ '$log', '$scope','messages', 'Upload', 'modelCatalogueApiRoot', 'enhance', ($log, $scope, messages, Upload, modelCatalogueApiRoot, enhance) -> Action.createStandardAction( position: null label: 'Save Schema' icon: 'fa fa-save' type: null action: -> messages .prompt("Save Schema", "Asset name", type: 'catalogue-element', resource: 'asset', contentType: 'text/xml', allowString: true, value: $scope.xsdAsset) .then (asset) -> if angular.isString(asset) name = asset else id = asset.id name = asset.name $scope.upload = Upload.upload({ url: "#{modelCatalogueApiRoot}/asset/upload" params: {id: id, name: name, dataModel: $scope.currentDataModel?.id, filename: "#{name}.xsd"} data: {asset: new Blob([$scope.xsd], {type: 'text/xml'})} }).progress((evt) -> $scope.progress = parseInt(100.0 * evt.loaded / evt.total) ).success((result) -> $scope.xsdAsset = enhance(result) $log.debug("asset saved", result) messages.success "Asset was successfuly saved." ).catch( (reason) -> $log.error("asset was not saved", reason) messages.error "Could not save asset. #{reason}" ) ) ] actionsProvider.registerActionInRole 'load-xslt', actionRoleRegister.ROLE_XMLEDITOR_XSD_ACTION, [ '$scope', ($scope) -> Action.createStandardAction( position: null label: 'Download Result' icon: 'fa fa-download' type: null action: -> $scope.download('Result.xsd', $scope.xsd) ) ] ])
[ { "context": "yName: ->\n @get('name') or @gravatarName() or \"Anoner\"\n\n lang: ->\n @get('preferredLanguage') or \"en", "end": 1113, "score": 0.4822728931903839, "start": 1107, "tag": "NAME", "value": "Anoner" } ]
app/models/User.coffee
vyz1194/codecombat
1
GRAVATAR_URL = 'https://www.gravatar.com/' cache = {} CocoModel = require('./CocoModel') module.exports = class User extends CocoModel @className: "User" urlRoot: "/db/user" initialize: -> super() @on 'change:emailHash', -> @gravatarProfile = null @loadGravatarProfile() isAdmin: -> permissions = @attributes['permissions'] or [] return 'admin' in permissions gravatarAvatarURL: -> avatar_url = GRAVATAR_URL + 'avatar/' return avatar_url if not @emailHash return avatar_url + @emailHash loadGravatarProfile: -> emailHash = @get('emailHash') return if not emailHash functionName = 'gotProfile'+emailHash profileUrl = "#{GRAVATAR_URL}#{emailHash}.json?callback=#{functionName}" script = $("<script src='#{profileUrl}' type='text/javascript'></script>") $('head').append(script) window[functionName] = (profile) => @gravatarProfile = profile @trigger('change', @) func = => @gravatarProfile = null unless @gravatarProfile setTimeout(func, 1000) displayName: -> @get('name') or @gravatarName() or "Anoner" lang: -> @get('preferredLanguage') or "en-US" gravatarName: -> @gravatarProfile?.entry[0]?.name?.formatted or '' gravatarPhotoURLs: -> photos = @gravatarProfile?.entry[0]?.photos return if not photos (photo.value for photo in photos) getPhotoURL: -> photoURL = @get('photoURL') validURLs = @gravatarPhotoURLs() return @gravatarAvatarURL() unless validURLs and validURLs.length return validURLs[0] unless photoURL in validURLs return photoURL @getByID = (id, properties, force) -> {me} = require('lib/auth') return me if me.id is id user = cache[id] or new module.exports({_id:id}) if force or not cache[id] user.loading = true user.fetch( success: -> user.loading = false Backbone.Mediator.publish('user:fetched') user.loadGravatarProfile() ) cache[id] = user user
112496
GRAVATAR_URL = 'https://www.gravatar.com/' cache = {} CocoModel = require('./CocoModel') module.exports = class User extends CocoModel @className: "User" urlRoot: "/db/user" initialize: -> super() @on 'change:emailHash', -> @gravatarProfile = null @loadGravatarProfile() isAdmin: -> permissions = @attributes['permissions'] or [] return 'admin' in permissions gravatarAvatarURL: -> avatar_url = GRAVATAR_URL + 'avatar/' return avatar_url if not @emailHash return avatar_url + @emailHash loadGravatarProfile: -> emailHash = @get('emailHash') return if not emailHash functionName = 'gotProfile'+emailHash profileUrl = "#{GRAVATAR_URL}#{emailHash}.json?callback=#{functionName}" script = $("<script src='#{profileUrl}' type='text/javascript'></script>") $('head').append(script) window[functionName] = (profile) => @gravatarProfile = profile @trigger('change', @) func = => @gravatarProfile = null unless @gravatarProfile setTimeout(func, 1000) displayName: -> @get('name') or @gravatarName() or "<NAME>" lang: -> @get('preferredLanguage') or "en-US" gravatarName: -> @gravatarProfile?.entry[0]?.name?.formatted or '' gravatarPhotoURLs: -> photos = @gravatarProfile?.entry[0]?.photos return if not photos (photo.value for photo in photos) getPhotoURL: -> photoURL = @get('photoURL') validURLs = @gravatarPhotoURLs() return @gravatarAvatarURL() unless validURLs and validURLs.length return validURLs[0] unless photoURL in validURLs return photoURL @getByID = (id, properties, force) -> {me} = require('lib/auth') return me if me.id is id user = cache[id] or new module.exports({_id:id}) if force or not cache[id] user.loading = true user.fetch( success: -> user.loading = false Backbone.Mediator.publish('user:fetched') user.loadGravatarProfile() ) cache[id] = user user
true
GRAVATAR_URL = 'https://www.gravatar.com/' cache = {} CocoModel = require('./CocoModel') module.exports = class User extends CocoModel @className: "User" urlRoot: "/db/user" initialize: -> super() @on 'change:emailHash', -> @gravatarProfile = null @loadGravatarProfile() isAdmin: -> permissions = @attributes['permissions'] or [] return 'admin' in permissions gravatarAvatarURL: -> avatar_url = GRAVATAR_URL + 'avatar/' return avatar_url if not @emailHash return avatar_url + @emailHash loadGravatarProfile: -> emailHash = @get('emailHash') return if not emailHash functionName = 'gotProfile'+emailHash profileUrl = "#{GRAVATAR_URL}#{emailHash}.json?callback=#{functionName}" script = $("<script src='#{profileUrl}' type='text/javascript'></script>") $('head').append(script) window[functionName] = (profile) => @gravatarProfile = profile @trigger('change', @) func = => @gravatarProfile = null unless @gravatarProfile setTimeout(func, 1000) displayName: -> @get('name') or @gravatarName() or "PI:NAME:<NAME>END_PI" lang: -> @get('preferredLanguage') or "en-US" gravatarName: -> @gravatarProfile?.entry[0]?.name?.formatted or '' gravatarPhotoURLs: -> photos = @gravatarProfile?.entry[0]?.photos return if not photos (photo.value for photo in photos) getPhotoURL: -> photoURL = @get('photoURL') validURLs = @gravatarPhotoURLs() return @gravatarAvatarURL() unless validURLs and validURLs.length return validURLs[0] unless photoURL in validURLs return photoURL @getByID = (id, properties, force) -> {me} = require('lib/auth') return me if me.id is id user = cache[id] or new module.exports({_id:id}) if force or not cache[id] user.loading = true user.fetch( success: -> user.loading = false Backbone.Mediator.publish('user:fetched') user.loadGravatarProfile() ) cache[id] = user user
[ { "context": " of non-negative integers into k ranges\n# Based on Óscar López implementation in Python (http://stacko", "end": 94, "score": 0.7169627547264099, "start": 93, "tag": "NAME", "value": "Ó" }, { "context": "f non-negative integers into k ranges\n# Based on Óscar López impl...
linear_partition.coffee
ael-r-d-m/linear-partition
35
# Linear partition # Partitions a sequence of non-negative integers into k ranges # Based on Óscar López implementation in Python (http://stackoverflow.com/a/7942946) # Also see http://www8.cs.umu.se/kurser/TDBAfl/VT06/algorithms/BOOK/BOOK2/NODE45.HTM # Dependencies: UnderscoreJS (http://www.underscorejs.org) # Example: linear_partition([9,2,6,3,8,5,8,1,7,3,4], 3) => [[9,2,6,3],[8,5,8],[1,7,3,4]] linear_partition = (seq, k) => n = seq.length return [] if k <= 0 return seq.map((x) -> [x]) if k > n table = (0 for x in [0...k] for y in [0...n]) solution = (0 for x in [0...k-1] for y in [0...n-1]) table[i][0] = seq[i] + (if i then table[i-1][0] else 0) for i in [0...n] table[0][j] = seq[0] for j in [0...k] for i in [1...n] for j in [1...k] m = _.min(([_.max([table[x][j-1], table[i][0]-table[x][0]]), x] for x in [0...i]), (o) -> o[0]) table[i][j] = m[0] solution[i-1][j-1] = m[1] n = n-1 k = k-2 ans = [] while k >= 0 ans = [seq[i] for i in [(solution[n-1][k]+1)...n+1]].concat ans n = solution[n-1][k] k = k-1 [seq[i] for i in [0...n+1]].concat ans
187352
# Linear partition # Partitions a sequence of non-negative integers into k ranges # Based on <NAME> <NAME>ar López implementation in Python (http://stackoverflow.com/a/7942946) # Also see http://www8.cs.umu.se/kurser/TDBAfl/VT06/algorithms/BOOK/BOOK2/NODE45.HTM # Dependencies: UnderscoreJS (http://www.underscorejs.org) # Example: linear_partition([9,2,6,3,8,5,8,1,7,3,4], 3) => [[9,2,6,3],[8,5,8],[1,7,3,4]] linear_partition = (seq, k) => n = seq.length return [] if k <= 0 return seq.map((x) -> [x]) if k > n table = (0 for x in [0...k] for y in [0...n]) solution = (0 for x in [0...k-1] for y in [0...n-1]) table[i][0] = seq[i] + (if i then table[i-1][0] else 0) for i in [0...n] table[0][j] = seq[0] for j in [0...k] for i in [1...n] for j in [1...k] m = _.min(([_.max([table[x][j-1], table[i][0]-table[x][0]]), x] for x in [0...i]), (o) -> o[0]) table[i][j] = m[0] solution[i-1][j-1] = m[1] n = n-1 k = k-2 ans = [] while k >= 0 ans = [seq[i] for i in [(solution[n-1][k]+1)...n+1]].concat ans n = solution[n-1][k] k = k-1 [seq[i] for i in [0...n+1]].concat ans
true
# Linear partition # Partitions a sequence of non-negative integers into k ranges # Based on PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PIar López implementation in Python (http://stackoverflow.com/a/7942946) # Also see http://www8.cs.umu.se/kurser/TDBAfl/VT06/algorithms/BOOK/BOOK2/NODE45.HTM # Dependencies: UnderscoreJS (http://www.underscorejs.org) # Example: linear_partition([9,2,6,3,8,5,8,1,7,3,4], 3) => [[9,2,6,3],[8,5,8],[1,7,3,4]] linear_partition = (seq, k) => n = seq.length return [] if k <= 0 return seq.map((x) -> [x]) if k > n table = (0 for x in [0...k] for y in [0...n]) solution = (0 for x in [0...k-1] for y in [0...n-1]) table[i][0] = seq[i] + (if i then table[i-1][0] else 0) for i in [0...n] table[0][j] = seq[0] for j in [0...k] for i in [1...n] for j in [1...k] m = _.min(([_.max([table[x][j-1], table[i][0]-table[x][0]]), x] for x in [0...i]), (o) -> o[0]) table[i][j] = m[0] solution[i-1][j-1] = m[1] n = n-1 k = k-2 ans = [] while k >= 0 ans = [seq[i] for i in [(solution[n-1][k]+1)...n+1]].concat ans n = solution[n-1][k] k = k-1 [seq[i] for i in [0...n+1]].concat ans
[ { "context": "ormation, please see the LICENSE file\n\n@author Bryan Conrad <bkconrad@gmail.com>\n@copyright 2016 Bryan Conra", "end": 156, "score": 0.9998879432678223, "start": 144, "tag": "NAME", "value": "Bryan Conrad" }, { "context": "e see the LICENSE file\n\n@author Br...
src/ScreepsStatsd.coffee
michal-franc/screeps-grafana
0
### hopsoft\screeps-statsd Licensed under the MIT license For full copyright and license information, please see the LICENSE file @author Bryan Conrad <bkconrad@gmail.com> @copyright 2016 Bryan Conrad @link https://github.com/hopsoft/docker-graphite-statsd @license http://choosealicense.com/licenses/MIT MIT License ### rp = require 'request-promise' zlib = require 'zlib' StatsD = require 'node-statsd' lodash = require 'lodash' shards = (process.env.SCREEPS_SHARD || '').split(',') resources = [ 'energy','power','H','O','U','K','L','Z','X','G', 'OH','ZK','UL','UH','UO','KH','KO','LH','LO','ZH', 'ZO','GH','GO','UH2O','UHO2','KH2O','KHO2','LH2O','LHO2','ZH2O', 'ZHO2','GH2O','GHO2','XUH2O','XUHO2','XKH2O','XKHO2','XLH2O','XLHO2','XZH2O', 'XZHO2','XGH2O','XGHO2','ops','silicon','metal','biomass','mist','utrium_bar','lemergium_bar', 'zynthium_bar','keanium_bar','ghodium_melt','oxidant','reductant','purifier','battery','composite','crystal','liquid', 'wire','switch','transistor','microchip','circuit','device','cell','phlegm','tissue','muscle', 'organoid','organism','alloy','tube','fixtures','frame','hydraulics','machine','condensate','concentrate', 'extract','spirit','emanation','essence', ] class ScreepsStatsd run: ( string ) -> rp.defaults jar: true @counter = 0 @token = "" @succes = false @client = new StatsD host: process.env.GRAPHITE_PORT_8125_UDP_ADDR console.log "will fetch data for", shards @loop() setInterval @loop, 15000 loop: () => if(!@token || !@succes) @signin() return @getStats() if(@counter % 5 == 0) @getMarket() @counter++ signin: () => console.log "New login request - " + new Date() options = uri: 'https://screeps.com/api/auth/signin' json: true method: 'POST' body: email: process.env.SCREEPS_EMAIL password: process.env.SCREEPS_PASSWORD rp(options) .then (x) => @token = x.token console.log "Fetched auth data" @succes = true .catch (e) => console.log e getStats: () => console.log("getting stats") shards.forEach (shard) => @succes = false options = uri: 'https://screeps.com/api/user/memory' method: 'GET' json: true resolveWithFullResponse: true headers: "X-Token": @token qs: path: 'stats' shard: shard rp(options) .then (x) => return unless x.body.ok && x.body.data @succes = true # Memory is returned in base64 encoded blob gzData = x.body.data.split('gz:')[1] data = JSON.parse zlib.gunzipSync(new Buffer(gzData, 'base64')).toString() @report(data, shard + '.') .catch (e) => console.log "failed getting stats", @counter, shard getMarket: () => # rotate the array resources.push(resources.shift()) resource = resources[0] console.log "getting market data", resource shards.forEach (shard) => @succes = false options = uri: 'https://screeps.com/api/game/market/orders' method: 'GET' json: true resolveWithFullResponse: true headers: "X-Token": @token qs: resourceType: resource shard: shard rp(options) .then (x) => return unless x.body.ok && x.body.list @succes = true orders = x.body.list sellOrders = orders.filter (o) => return o.type == 'sell' sellOrders = lodash.sortBy sellOrders, 'price' minSell = sellOrders[0]; if (minSell) @client.gauge([shard, 'market', resource, 'min', 'sell'].join('.'), minSell.price); buyOrders = orders.filter (o) => return o.type == 'buy' buyOrders = lodash.sortBy buyOrders, 'price' buyOrders.reverse() maxBuy = buyOrders[0]; if (maxBuy) @client.gauge([shard, 'market', resource, 'max', 'buy'].join('.'), maxBuy.price); .catch (e) => console.log "failed getting market data", @counter, shard, resource report: (data, prefix) => for k,v of data if typeof v is 'object' @report(v, prefix+k+'.') else @client.gauge prefix+k, v module.exports = ScreepsStatsd
117869
### hopsoft\screeps-statsd Licensed under the MIT license For full copyright and license information, please see the LICENSE file @author <NAME> <<EMAIL>> @copyright 2016 <NAME> @link https://github.com/hopsoft/docker-graphite-statsd @license http://choosealicense.com/licenses/MIT MIT License ### rp = require 'request-promise' zlib = require 'zlib' StatsD = require 'node-statsd' lodash = require 'lodash' shards = (process.env.SCREEPS_SHARD || '').split(',') resources = [ 'energy','power','H','O','U','K','L','Z','X','G', 'OH','ZK','UL','UH','UO','KH','KO','LH','LO','ZH', 'ZO','GH','GO','UH2O','UHO2','KH2O','KHO2','LH2O','LHO2','ZH2O', 'ZHO2','GH2O','GHO2','XUH2O','XUHO2','XKH2O','XKHO2','XLH2O','XLHO2','XZH2O', 'XZHO2','XGH2O','XGHO2','ops','silicon','metal','biomass','mist','utrium_bar','lemergium_bar', 'zynthium_bar','keanium_bar','ghodium_melt','oxidant','reductant','purifier','battery','composite','crystal','liquid', 'wire','switch','transistor','microchip','circuit','device','cell','phlegm','tissue','muscle', 'organoid','organism','alloy','tube','fixtures','frame','hydraulics','machine','condensate','concentrate', 'extract','spirit','emanation','essence', ] class ScreepsStatsd run: ( string ) -> rp.defaults jar: true @counter = 0 @token = "" @succes = false @client = new StatsD host: process.env.GRAPHITE_PORT_8125_UDP_ADDR console.log "will fetch data for", shards @loop() setInterval @loop, 15000 loop: () => if(!@token || !@succes) @signin() return @getStats() if(@counter % 5 == 0) @getMarket() @counter++ signin: () => console.log "New login request - " + new Date() options = uri: 'https://screeps.com/api/auth/signin' json: true method: 'POST' body: email: process.env.SCREEPS_EMAIL password: <PASSWORD> rp(options) .then (x) => @token = x.token console.log "Fetched auth data" @succes = true .catch (e) => console.log e getStats: () => console.log("getting stats") shards.forEach (shard) => @succes = false options = uri: 'https://screeps.com/api/user/memory' method: 'GET' json: true resolveWithFullResponse: true headers: "X-Token": @token qs: path: 'stats' shard: shard rp(options) .then (x) => return unless x.body.ok && x.body.data @succes = true # Memory is returned in base64 encoded blob gzData = x.body.data.split('gz:')[1] data = JSON.parse zlib.gunzipSync(new Buffer(gzData, 'base64')).toString() @report(data, shard + '.') .catch (e) => console.log "failed getting stats", @counter, shard getMarket: () => # rotate the array resources.push(resources.shift()) resource = resources[0] console.log "getting market data", resource shards.forEach (shard) => @succes = false options = uri: 'https://screeps.com/api/game/market/orders' method: 'GET' json: true resolveWithFullResponse: true headers: "X-Token": @token qs: resourceType: resource shard: shard rp(options) .then (x) => return unless x.body.ok && x.body.list @succes = true orders = x.body.list sellOrders = orders.filter (o) => return o.type == 'sell' sellOrders = lodash.sortBy sellOrders, 'price' minSell = sellOrders[0]; if (minSell) @client.gauge([shard, 'market', resource, 'min', 'sell'].join('.'), minSell.price); buyOrders = orders.filter (o) => return o.type == 'buy' buyOrders = lodash.sortBy buyOrders, 'price' buyOrders.reverse() maxBuy = buyOrders[0]; if (maxBuy) @client.gauge([shard, 'market', resource, 'max', 'buy'].join('.'), maxBuy.price); .catch (e) => console.log "failed getting market data", @counter, shard, resource report: (data, prefix) => for k,v of data if typeof v is 'object' @report(v, prefix+k+'.') else @client.gauge prefix+k, v module.exports = ScreepsStatsd
true
### hopsoft\screeps-statsd Licensed under the MIT license For full copyright and license information, please see the LICENSE file @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> @copyright 2016 PI:NAME:<NAME>END_PI @link https://github.com/hopsoft/docker-graphite-statsd @license http://choosealicense.com/licenses/MIT MIT License ### rp = require 'request-promise' zlib = require 'zlib' StatsD = require 'node-statsd' lodash = require 'lodash' shards = (process.env.SCREEPS_SHARD || '').split(',') resources = [ 'energy','power','H','O','U','K','L','Z','X','G', 'OH','ZK','UL','UH','UO','KH','KO','LH','LO','ZH', 'ZO','GH','GO','UH2O','UHO2','KH2O','KHO2','LH2O','LHO2','ZH2O', 'ZHO2','GH2O','GHO2','XUH2O','XUHO2','XKH2O','XKHO2','XLH2O','XLHO2','XZH2O', 'XZHO2','XGH2O','XGHO2','ops','silicon','metal','biomass','mist','utrium_bar','lemergium_bar', 'zynthium_bar','keanium_bar','ghodium_melt','oxidant','reductant','purifier','battery','composite','crystal','liquid', 'wire','switch','transistor','microchip','circuit','device','cell','phlegm','tissue','muscle', 'organoid','organism','alloy','tube','fixtures','frame','hydraulics','machine','condensate','concentrate', 'extract','spirit','emanation','essence', ] class ScreepsStatsd run: ( string ) -> rp.defaults jar: true @counter = 0 @token = "" @succes = false @client = new StatsD host: process.env.GRAPHITE_PORT_8125_UDP_ADDR console.log "will fetch data for", shards @loop() setInterval @loop, 15000 loop: () => if(!@token || !@succes) @signin() return @getStats() if(@counter % 5 == 0) @getMarket() @counter++ signin: () => console.log "New login request - " + new Date() options = uri: 'https://screeps.com/api/auth/signin' json: true method: 'POST' body: email: process.env.SCREEPS_EMAIL password: PI:PASSWORD:<PASSWORD>END_PI rp(options) .then (x) => @token = x.token console.log "Fetched auth data" @succes = true .catch (e) => console.log e getStats: () => console.log("getting stats") shards.forEach (shard) => @succes = false options = uri: 'https://screeps.com/api/user/memory' method: 'GET' json: true resolveWithFullResponse: true headers: "X-Token": @token qs: path: 'stats' shard: shard rp(options) .then (x) => return unless x.body.ok && x.body.data @succes = true # Memory is returned in base64 encoded blob gzData = x.body.data.split('gz:')[1] data = JSON.parse zlib.gunzipSync(new Buffer(gzData, 'base64')).toString() @report(data, shard + '.') .catch (e) => console.log "failed getting stats", @counter, shard getMarket: () => # rotate the array resources.push(resources.shift()) resource = resources[0] console.log "getting market data", resource shards.forEach (shard) => @succes = false options = uri: 'https://screeps.com/api/game/market/orders' method: 'GET' json: true resolveWithFullResponse: true headers: "X-Token": @token qs: resourceType: resource shard: shard rp(options) .then (x) => return unless x.body.ok && x.body.list @succes = true orders = x.body.list sellOrders = orders.filter (o) => return o.type == 'sell' sellOrders = lodash.sortBy sellOrders, 'price' minSell = sellOrders[0]; if (minSell) @client.gauge([shard, 'market', resource, 'min', 'sell'].join('.'), minSell.price); buyOrders = orders.filter (o) => return o.type == 'buy' buyOrders = lodash.sortBy buyOrders, 'price' buyOrders.reverse() maxBuy = buyOrders[0]; if (maxBuy) @client.gauge([shard, 'market', resource, 'max', 'buy'].join('.'), maxBuy.price); .catch (e) => console.log "failed getting market data", @counter, shard, resource report: (data, prefix) => for k,v of data if typeof v is 'object' @report(v, prefix+k+'.') else @client.gauge prefix+k, v module.exports = ScreepsStatsd
[ { "context": "# Description:\n# Zach Holman hates weasel words. Frick.\n#\n# Dependencies:\n# ", "end": 30, "score": 0.9950648546218872, "start": 19, "tag": "NAME", "value": "Zach Holman" }, { "context": "figuration:\n# None\n#\n# Commands:\n# frick - Let Zach Holman tell you...
src/scripts/frick.coffee
Reelhouse/hubot-scripts
1,450
# Description: # Zach Holman hates weasel words. Frick. # # Dependencies: # None # # Configuration: # None # # Commands: # frick - Let Zach Holman tell you what word to use instead of "frick" # # Authors: # lmarburger module.exports = (robot) -> robot.hear /frick/i, (msg) -> msg.send 'https://twitter.com/holman/status/296703339696111617'
142985
# Description: # <NAME> hates weasel words. Frick. # # Dependencies: # None # # Configuration: # None # # Commands: # frick - Let <NAME> tell you what word to use instead of "frick" # # Authors: # lmarburger module.exports = (robot) -> robot.hear /frick/i, (msg) -> msg.send 'https://twitter.com/holman/status/296703339696111617'
true
# Description: # PI:NAME:<NAME>END_PI hates weasel words. Frick. # # Dependencies: # None # # Configuration: # None # # Commands: # frick - Let PI:NAME:<NAME>END_PI tell you what word to use instead of "frick" # # Authors: # lmarburger module.exports = (robot) -> robot.hear /frick/i, (msg) -> msg.send 'https://twitter.com/holman/status/296703339696111617'
[ { "context": "reful--with quotations, you can damn anything.”\\n― André Malraux\",nil,nil,nil,nil,nil,WorldMorph.preferencesAndSet", "end": 12577, "score": 0.9998844861984253, "start": 12564, "tag": "NAME", "value": "André Malraux" } ]
src/basic-widgets/menu-system/MenusHelper.coffee
intensifier/Fizzygum
110
# All "actions" functions for all accessory menu items should belong # in here. Also helps so we don't pollute moprhs with a varying number # of helper functions, which is problematic for visual diffing # on inspectors (the number of methods keeps changing). class MenusHelper @augmentWith DeepCopierMixin popUpDevToolsMenu: (morphOpeningThePopUp, widgetThisMenuIsAbout) -> menu = new MenuMorph morphOpeningThePopUp, false, @, true, true, "Dev Tools" menu.addMenuItem "inspect", true, widgetThisMenuIsAbout, "inspect2", "open a window\non all properties" menu.addMenuItem "console", true, widgetThisMenuIsAbout, "createConsole", "console" menu.popUpAtHand() # »>> this part is excluded from the fizzygum homepage build createFridgeMagnets: -> fmm = new FridgeMagnetsMorph wm = new WindowWdgt nil, nil, fmm wm.setExtent new Point 570, 400 wm.fullRawMoveTo world.hand.position() wm.fullRawMoveWithin world world.add wm createReconfigurablePaint: -> reconfPaint = new ReconfigurablePaintWdgt wm = new WindowWdgt nil, nil, reconfPaint wm.setExtent new Point 460, 400 wm.fullRawMoveTo world.hand.position() wm.fullRawMoveWithin world world.add wm createSimpleSlideWdgt: -> simpleSlide = new SimpleSlideWdgt wm = new WindowWdgt nil, nil, simpleSlide wm.setExtent new Point 460, 400 wm.fullRawMoveTo world.hand.position() wm.fullRawMoveWithin world world.add wm createSimpleButton: -> world.create new SimpleRectangularButtonMorph true, @, nil, new IconMorph(nil) createSwitchButtonMorph: -> button1 = new SimpleRectangularButtonMorph true, @, nil, new IconMorph(nil) button2 = new SimpleRectangularButtonMorph true, @, nil, new StringMorph2 "Hello World! ⎲ƒ⎳⎷ ⎸⎹ " world.create new SwitchButtonMorph [button1, button2] createNewClippingBoxMorph: -> world.create new ClippingBoxMorph makeSlidersButtonsStatesBright: -> world.forAllChildrenBottomToTop (child) -> if child instanceof SliderButtonMorph child.pressColor = Color.LIME child.highlightColor = Color.BLUE child.normalColor = Color.BLACK # Icons -------------------------------------------------------------- makeIconWithText: -> world.create new WidgetHolderWithCaptionWdgt "hey there", new BrushIconMorph makeEmptyIconWithText: -> world.create new WidgetHolderWithCaptionWdgt "hey there" makeFolderWindow: (a,b,c,d,e) -> world.create new FolderWindowWdgt nil,nil,nil,nil, @ makeBouncingParticle: -> world.create new BouncerWdgt createDestroyIconMorph: -> world.create new DestroyIconMorph createUnderCarpetIconMorph: -> world.create new UnderCarpetIconMorph createUncollapsedStateIconMorph: -> world.create new UncollapsedStateIconMorph createCollapsedStateIconMorph: -> world.create new CollapsedStateIconMorph createCloseIconButtonMorph: -> world.create new CloseIconButtonMorph createScratchAreaIconMorph: -> world.create new ScratchAreaIconMorph createFloraIconMorph: -> world.create new FloraIconMorph createScooterIconMorph: -> world.create new ScooterIconMorph createHeartIconMorph: -> world.create new HeartIconMorph createPencil1IconMorph: -> world.create new PencilIconMorph createPencil2IconMorph: -> world.create new Pencil2IconMorph createBrushIconMorph: -> world.create new BrushIconMorph createToothpasteIconMorph: -> world.create new ToothpasteIconMorph createEraserIconMorph: -> world.create new EraserIconMorph createTrashcanIconWdgt: -> world.create new TrashcanIconWdgt createShortcutArrowIconWdgt: -> world.create new ShortcutArrowIconWdgt createRasterPicIconWdgt: -> world.create new RasterPicIconWdgt createPaintBucketIconWdgt: -> world.create new PaintBucketIconWdgt createObjectIconWdgt: -> world.create new ObjectIconWdgt createFolderIconWdgt: -> world.create new FolderIconWdgt createBasementIconWdgt: -> world.create new BasementIconWdgt createWidgetIconWdgt: -> world.create new WidgetIconWdgt makeGenericReferenceIcon: -> world.create new GenericShortcutIconWdgt makeGenericObjectIcon: -> world.create new GenericObjectIconWdgt # this part is excluded from the fizzygum homepage build <<« basementIconAndText: -> world.add new BasementOpenerWdgt # »>> this part is excluded from the fizzygum homepage build newScriptWindow: -> scriptWdgt = new ScriptWdgt wm = new WindowWdgt nil, nil, scriptWdgt wm.setExtent new Point 460, 400 wm.fullRawMoveTo world.hand.position().subtract new Point 50, 100 wm.fullRawMoveWithin world world.add wm # this part is excluded from the fizzygum homepage build <<« # ------------------------------------------------------------------------ launchFizzyPaint: -> wm = new WindowWdgt nil, nil, new ReconfigurablePaintWdgt wm.setExtent new Point 460, 400 wm.fullRawMoveTo new Point 174, 114 wm.fullRawMoveWithin world world.add wm ReconfigurablePaintInfoWdgt.createNextTo wm createFizzyPaintLauncher: -> fizzyPaintLauncher = new IconicDesktopSystemWindowedAppLauncherWdgt "Draw", new PaintBucketIconWdgt, @, "launchFizzyPaint" # this "add" is going to try to position the reference # in some smart way (i.e. according to a grid) world.add fizzyPaintLauncher fizzyPaintLauncher.setExtent new Point 75, 75 fizzyPaintLauncher.fullChanged() # ------------------------------------------------------------------------ launchSimpleDocument: -> wm = new WindowWdgt nil, nil, new SimpleDocumentWdgt wm.setExtent new Point 370, 395 wm.fullRawMoveTo new Point 170, 88 wm.fullRawMoveWithin world world.add wm SimpleDocumentInfoWdgt.createNextTo wm createSimpleDocumentLauncher: -> simpleDocumentLauncher = new IconicDesktopSystemWindowedAppLauncherWdgt "Docs Maker", new TypewriterIconWdgt, @, "launchSimpleDocument" # this "add" is going to try to position the reference # in some smart way (i.e. according to a grid) world.add simpleDocumentLauncher simpleDocumentLauncher.setExtent new Point 75, 75 simpleDocumentLauncher.fullChanged() # ------------------------------------------------------------------------ launchSimpleSlide: -> wm = new WindowWdgt nil, nil, new SimpleSlideWdgt wm.setExtent new Point 460, 400 wm.fullRawMoveTo new Point 168, 134 wm.fullRawMoveWithin world world.add wm SimpleSlideInfoWdgt.createNextTo wm createSimpleSlideLauncher: -> simpleSlideLauncher = new IconicDesktopSystemWindowedAppLauncherWdgt "Slides Maker", new SimpleSlideIconWdgt, @, "launchSimpleSlide" # this "add" is going to try to position the reference # in some smart way (i.e. according to a grid) world.add simpleSlideLauncher simpleSlideLauncher.setExtent new Point 75, 75 simpleSlideLauncher.fullChanged() # ------------------------------------------------------------------------ launchDashboards: -> reconfPaint = new DashboardsWdgt wm = new WindowWdgt nil, nil, reconfPaint wm.setExtent new Point 460, 400 wm.fullRawMoveTo world.hand.position() wm.fullRawMoveWithin world world.add wm DashboardsInfoWdgt.createNextTo wm createDashboardsLauncher: -> simpleDashboardsLauncher = new IconicDesktopSystemWindowedAppLauncherWdgt "Dashboards", new DashboardsIconWdgt, @, "launchDashboards" # this "add" is going to try to position the reference # in some smart way (i.e. according to a grid) world.add simpleDashboardsLauncher simpleDashboardsLauncher.setExtent new Point 75, 75 simpleDashboardsLauncher.fullChanged() # ------------------------------------------------------------------------ launchPatchProgramming: -> patchProgramming = new PatchProgrammingWdgt wm = new WindowWdgt nil, nil, patchProgramming wm.setExtent new Point 460, 400 wm.fullRawMoveTo world.hand.position() wm.fullRawMoveWithin world world.add wm PatchProgrammingInfoWdgt.createNextTo wm createPatchProgrammingLauncher: -> patchProgrammingLauncher = new IconicDesktopSystemWindowedAppLauncherWdgt "Patch progr.", new PatchProgrammingIconWdgt, @, "launchPatchProgramming" # this "add" is going to try to position the reference # in some smart way (i.e. according to a grid) world.add patchProgrammingLauncher patchProgrammingLauncher.setExtent new Point 75, 75 patchProgrammingLauncher.fullChanged() # ------------------------------------------------------------------------ launchGenericPanel: -> genericPanel = new StretchableEditableWdgt wm = new WindowWdgt nil, nil, genericPanel wm.setExtent new Point 460, 400 wm.fullRawMoveTo world.hand.position() wm.fullRawMoveWithin world world.add wm GenericPanelInfoWdgt.createNextTo wm createGenericPanelLauncher: -> genericPanelLauncher = new IconicDesktopSystemWindowedAppLauncherWdgt "Generic panel", new GenericPanelIconWdgt, @, "launchGenericPanel" # this "add" is going to try to position the reference # in some smart way (i.e. according to a grid) world.add genericPanelLauncher genericPanelLauncher.setExtent new Point 75, 75 genericPanelLauncher.fullChanged() # ------------------------------------------------------------------------ launchToolbars: -> # tools ------------------------------- toolsPanel = new ScrollPanelWdgt new ToolPanelWdgt toolsPanel.addMany [ new TextToolbarCreatorButtonWdgt new UsefulTextSnippetsToolbarCreatorButtonWdgt new SlidesToolbarCreatorButtonWdgt new PlotsToolbarCreatorButtonWdgt new PatchProgrammingComponentsToolbarCreatorButtonWdgt new WindowsToolbarCreatorButtonWdgt ] toolsPanel.disableDragsDropsAndEditing() wm = new WindowWdgt nil, nil, toolsPanel wm.setExtent new Point 60, 261 wm.fullRawMoveTo new Point 170, 170 wm.fullRawMoveWithin world world.add wm ToolbarsInfoWdgt.createNextTo wm createToolbarsOpener: -> toolbarsOpenerLauncher = new IconicDesktopSystemWindowedAppLauncherWdgt "Super Toolbar", new ToolbarsIconWdgt, @, "launchToolbars" toolbarsOpenerLauncher.toolTipMessage = "a toolbar to rule them all" # this "add" is going to try to position the reference # in some smart way (i.e. according to a grid) world.add toolbarsOpenerLauncher toolbarsOpenerLauncher.setExtent new Point 75, 75 toolbarsOpenerLauncher.fullChanged() # ------------------------------------------------------------------------ createNewTemplatesWindow: -> sdspw = new SimpleDocumentScrollPanelWdgt sdspw.rawSetExtent new Point 365, 335 startingContent = new SimplePlainTextWdgt( "Simply drag the items below into your document",nil,nil,nil,nil,nil,WorldMorph.preferencesAndSettings.editableItemBackgroundColor, 1) startingContent.alignCenter() startingContent.setFontSize 18 startingContent.isEditable = true startingContent.enableSelecting() sdspw.setContents startingContent, 5 startingContent = new ArrowSIconWdgt startingContent.rawSetExtent new Point 25, 25 sdspw.add startingContent startingContent.layoutSpecDetails.setAlignmentToCenter() sdspw.addDivider() startingContent = new SimplePlainTextWdgt( "Title",nil,nil,nil,nil,nil,WorldMorph.preferencesAndSettings.editableItemBackgroundColor, 1) startingContent.alignCenter() startingContent.setFontName nil, nil, startingContent.georgiaFontStack startingContent.setFontSize 48 startingContent.isEditable = true startingContent.enableSelecting() sdspw.add startingContent startingContent = new SimplePlainTextWdgt( "Section X",nil,nil,nil,nil,nil,WorldMorph.preferencesAndSettings.editableItemBackgroundColor, 1) startingContent.toggleWeight() startingContent.isEditable = true startingContent.enableSelecting() startingContent.setFontSize 28 sdspw.add startingContent startingContent = new SimplePlainTextWdgt( "Section X.X",nil,nil,nil,nil,nil,WorldMorph.preferencesAndSettings.editableItemBackgroundColor, 1) startingContent.isEditable = true startingContent.enableSelecting() startingContent.setFontSize 24 sdspw.add startingContent sdspw.addNormalParagraph "Normal text." startingContent = new SimplePlainTextWdgt( "“Be careful--with quotations, you can damn anything.”\n― André Malraux",nil,nil,nil,nil,nil,WorldMorph.preferencesAndSettings.editableItemBackgroundColor, 1) startingContent.toggleItalic() startingContent.alignRight() startingContent.isEditable = true startingContent.enableSelecting() sdspw.add startingContent sdspw.addIndentedText "indentedText" sdspw.addBulletPoint "bullet point" sdspw.addCodeBlock "a code block with\n some example\n code in here" startingContent = new SimplePlainTextWdgt( "Spacers:",nil,nil,nil,nil,nil,WorldMorph.preferencesAndSettings.editableItemBackgroundColor, 1) startingContent.toggleWeight() startingContent.isEditable = true startingContent.enableSelecting() sdspw.add startingContent sdspw.addSpacer() sdspw.addSpacer 2 sdspw.addSpacer 3 startingContent = new SimplePlainTextWdgt( "Divider line:",nil,nil,nil,nil,nil,WorldMorph.preferencesAndSettings.editableItemBackgroundColor, 1) startingContent.toggleWeight() startingContent.isEditable = true startingContent.enableSelecting() sdspw.add startingContent sdspw.addDivider() startingContent = new SimplePlainTextWdgt( "Links:",nil,nil,nil,nil,nil,WorldMorph.preferencesAndSettings.editableItemBackgroundColor, 1) startingContent.toggleWeight() startingContent.isEditable = true startingContent.enableSelecting() sdspw.add startingContent startingContent = new SimpleLinkWdgt startingContent.rawSetExtent new Point 405, 50 sdspw.add startingContent startingContent.layoutSpecDetails.setAlignmentToRight() startingContent = new SimpleVideoLinkWdgt startingContent.rawSetExtent new Point 405, 50 sdspw.add startingContent startingContent.layoutSpecDetails.setAlignmentToRight() startingContent = new SimplePlainTextWdgt( "Useful characters:",nil,nil,nil,nil,nil,WorldMorph.preferencesAndSettings.editableItemBackgroundColor, 1) startingContent.toggleWeight() startingContent.isEditable = true startingContent.enableSelecting() sdspw.add startingContent # in March 2018, greek chars take a long time to paint on OSX/Chrome so # not adding those to the paragraph, however here they are: # αβγδεζηθικλμνξοπρστυφχψω ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ specialCharsParagraph = sdspw.addNormalParagraph "… †‡§ ↵⏎⇧␣ ☐☑☒✓X✗ •‣⁃◦ °±⁻¹²³µ×÷ℓΩ√∛∜∝∞∟∠∡∩∪∿≈⊂⋅⌀▫◽◻□⩽⩾ ¼½¾⅛⅜⅝⅞ ←↑→↓↔↕↵⇎⇏⇑⇒⇓⇔⇕ ©®™ $£€¥" specialCharsParagraph.setFontSize 16 sdspw.makeAllContentIntoTemplates() wm = new WindowWdgt nil, nil, sdspw wm.setExtent new Point 370, 335 wm.setTitleWithoutPrependedContentName "useful snippets" return wm # »>> this part is excluded from the fizzygum homepage build createFanout: -> fanoutWdgt = new FanoutWdgt world.create fanoutWdgt fanoutWdgt.setExtent new Point 100, 100 createCalculatingPatchNode: -> calculatingPatchNodeWdgt = new CalculatingPatchNodeWdgt wm = new WindowWdgt nil, nil, calculatingPatchNodeWdgt, true wm.setExtent new Point 460, 400 wm.fullRawMoveTo world.hand.position().subtract new Point 50, 100 wm.fullRawMoveWithin world world.add wm createDiffingPatchNode: -> diffingPatchNodeWdgt = new DiffingPatchNodeWdgt wm = new WindowWdgt nil, nil, diffingPatchNodeWdgt, true wm.setExtent new Point 460, 400 wm.fullRawMoveTo world.hand.position().subtract new Point 50, 100 wm.fullRawMoveWithin world world.add wm createSliderWithSmallestValueAtBottomEnd: -> world.create new SliderMorph nil, nil, nil, nil, nil, true createRegexSubstitutionPatchNodeWdgt: -> regexSubstitutionPatchNodeWdgt = new RegexSubstitutionPatchNodeWdgt wm = new WindowWdgt nil, nil, regexSubstitutionPatchNodeWdgt, true wm.setExtent new Point 460, 400 wm.fullRawMoveTo world.hand.position().subtract new Point 50, 100 wm.fullRawMoveWithin world world.add wm throwAnError: -> throw new Error "you manually threw an error!" createStretchablePanel: -> stretchablePanel = new StretchableWidgetContainerWdgt world.create stretchablePanel stretchablePanel.setExtent new Point 400, 300 createToolsPanel: -> toolPanel = new ScrollPanelWdgt new ToolPanelWdgt wm = new WindowWdgt nil, nil, toolPanel, true wm.setExtent new Point 200, 400 wm.fullRawMoveTo world.hand.position().subtract new Point 50, 100 wm.fullRawMoveWithin world world.add wm createHorizontalMenuPanelPanel: -> horizontalMenuPanel = new HorizontalMenuPanelWdgt wm = new WindowWdgt nil, nil, horizontalMenuPanel, true wm.setExtent new Point 200, 400 wm.fullRawMoveTo world.hand.position().subtract new Point 50, 100 wm.fullRawMoveWithin world world.add wm popUpMore1IconsMenu: (morphOpeningThePopUp) -> menu = new MenuMorph morphOpeningThePopUp, false, @, true, true, "More Icons 1" menu.addMenuItem "Pencil 1 icon", true, menusHelper, "createPencil1IconMorph" menu.addMenuItem "Pencil 2 icon", true, menusHelper, "createPencil2IconMorph" menu.addMenuItem "Brush icon", true, menusHelper, "createBrushIconMorph" menu.addMenuItem "Toothpaste icon", true, menusHelper, "createToothpasteIconMorph" menu.addMenuItem "Eraser icon", true, menusHelper, "createEraserIconMorph" menu.addMenuItem "Trashcan icon", true, menusHelper, "createTrashcanIconWdgt" menu.addMenuItem "Shortcut arrow icon", true, menusHelper, "createShortcutArrowIconWdgt" menu.addMenuItem "Raster pic icon", true, menusHelper, "createRasterPicIconWdgt" menu.addMenuItem "Paint bucket icon", true, menusHelper, "createPaintBucketIconWdgt" menu.addMenuItem "Object icon", true, menusHelper, "createObjectIconWdgt" menu.addMenuItem "Folder icon", true, menusHelper, "createFolderIconWdgt" menu.addMenuItem "Basement icon", true, menusHelper, "createBasementIconWdgt" menu.addMenuItem "Widget icon", true, menusHelper, "createWidgetIconWdgt" menu.popUpAtHand() popUpMore2IconsMenu: (morphOpeningThePopUp) -> menu = new MenuMorph morphOpeningThePopUp, false, @, true, true, "More Icons 2" menu.addMenuItem "Format as code icon", true, menusHelper, "createFormatAsCodeIconWdgt" menu.addMenuItem "Ch. X icon", true, menusHelper, "createChXIconWdgt" menu.addMenuItem "Ch. X.X icon", true, menusHelper, "createChXXIconWdgt" menu.addMenuItem "Ch. X.X.X icon", true, menusHelper, "createChXXXIconWdgt" menu.addMenuItem "Align right icon", true, menusHelper, "createAlignRightIconWdgt" menu.addMenuItem "Align center icon", true, menusHelper, "createAlignCenterIconWdgt" menu.addMenuItem "Align left icon", true, menusHelper, "createAlignLeftIconWdgt" menu.addMenuItem "Bold icon", true, menusHelper, "createBoldIconWdgt" menu.addMenuItem "Italic icon", true, menusHelper, "createItalicIconWdgt" menu.addMenuItem "Information icon", true, menusHelper, "createInformationIconWdgt" menu.addMenuItem "Textbox icon", true, menusHelper, "createTextboxIconWdgt" menu.addMenuItem "Video play icon", true, menusHelper, "createVideoPlayIconWdgt" menu.addMenuItem "Decrease font size icon", true, menusHelper, "createDecreaseFontSizeIconWdgt" menu.addMenuItem "Increase font size icon", true, menusHelper, "createIncreaseFontSizeIconWdgt" menu.addMenuItem "External link icon", true, menusHelper, "createExternalLinkIconWdgt" menu.addMenuItem "Templates icon", true, menusHelper, "createTemplatesIconWdgt" menu.popUpAtHand() popUpMore3IconsMenu: (morphOpeningThePopUp) -> menu = new MenuMorph morphOpeningThePopUp, false, @, true, true, "More Icons 2" menu.addMenuItem "Fizzygum logo", true, menusHelper, "createFizzygumLogoIconWdgt" menu.addMenuItem "Fizzygum logo with text", true, menusHelper, "createFizzygumLogoWithTextIconWdgt" menu.addMenuItem "Vaporwave sun", true, menusHelper, "createVaporwaveSunIconWdgt" menu.addMenuItem "Vaporwave background", true, menusHelper, "createVaporwaveBackgroundIconWdgt" menu.addMenuItem "Change font icon", true, menusHelper, "createChangeFontIconWdgt" menu.addMenuItem "C <-> F converter icon", true, menusHelper, "createCFDegreesConverterIconWdgt" menu.addMenuItem "Simple slide icon", true, menusHelper, "createSimpleSlideIconWdgt" menu.addMenuItem "Typewriter icon", true, menusHelper, "createTypewriterIconWdgt" menu.addMenuItem "Little world icon", true, menusHelper, "createLittleWorldIconWdgt" menu.addMenuItem "Little USA icon", true, menusHelper, "createLittleUSAIconWdgt" menu.addMenuItem "Map pin icon", true, menusHelper, "createMapPinIconWdgt" menu.addMenuItem "Save icon", true, menusHelper, "createSaveIconWdgt" menu.popUpAtHand() createFizzygumLogoWithTextIconWdgt : -> world.create new FizzygumLogoWithTextIconWdgt createVaporwaveBackgroundIconWdgt : -> world.create new VaporwaveBackgroundIconWdgt createCFDegreesConverterIconWdgt : -> world.create new CFDegreesConverterIconWdgt createFizzygumLogoIconWdgt : -> world.create new FizzygumLogoIconWdgt createVaporwaveSunIconWdgt : -> world.create new VaporwaveSunIconWdgt createLittleWorldIconWdgt : -> world.create new LittleWorldIconWdgt createChangeFontIconWdgt : -> world.create new ChangeFontIconWdgt createSimpleSlideIconWdgt : -> world.create new SimpleSlideIconWdgt createTypewriterIconWdgt : -> world.create new TypewriterIconWdgt createLittleUSAIconWdgt : -> world.create new LittleUSAIconWdgt createMapPinIconWdgt : -> world.create new MapPinIconWdgt createSaveIconWdgt : -> world.create new SaveIconWdgt popUpArrowsIconsMenu: (morphOpeningThePopUp) -> menu = new MenuMorph morphOpeningThePopUp, false, @, true, true, "Arrows" menu.addMenuItem "Arrow N icon", true, menusHelper, "createArrowNIconWdgt" menu.addMenuItem "Arrow S icon", true, menusHelper, "createArrowSIconWdgt" menu.addMenuItem "Arrow W icon", true, menusHelper, "createArrowWIconWdgt" menu.addMenuItem "Arrow E icon", true, menusHelper, "createArrowEIconWdgt" menu.addMenuItem "Arrow NW icon", true, menusHelper, "createArrowNWIconWdgt" menu.addMenuItem "Arrow NE icon", true, menusHelper, "createArrowNEIconWdgt" menu.addMenuItem "Arrow SE icon", true, menusHelper, "createArrowSEIconWdgt" menu.addMenuItem "Arrow SW icon", true, menusHelper, "createArrowSWIconWdgt" menu.popUpAtHand() createArrowEIconWdgt: -> world.create new ArrowEIconWdgt createArrowNEIconWdgt: -> world.create new ArrowNEIconWdgt createArrowNIconWdgt: -> world.create new ArrowNIconWdgt createArrowNWIconWdgt: -> world.create new ArrowNWIconWdgt createArrowSEIconWdgt: -> world.create new ArrowSEIconWdgt createArrowSIconWdgt: -> world.create new ArrowSIconWdgt createArrowSWIconWdgt: -> world.create new ArrowSWIconWdgt createArrowWIconWdgt: -> world.create new ArrowWIconWdgt createDecreaseFontSizeIconWdgt: -> world.create new DecreaseFontSizeIconWdgt createExternalLinkIconWdgt: -> world.create new ExternalLinkIconWdgt createIncreaseFontSizeIconWdgt: -> world.create new IncreaseFontSizeIconWdgt createTemplatesIconWdgt: -> world.create new TemplatesIconWdgt createFormatAsCodeIconWdgt: -> world.create new FormatAsCodeIconWdgt createChXIconWdgt: -> world.create new ChapterXIconWdgt createChXXIconWdgt: -> world.create new ChapterXXIconWdgt createChXXXIconWdgt: -> world.create new ChapterXXXIconWdgt createAlignRightIconWdgt: -> world.create new AlignRightIconWdgt createAlignCenterIconWdgt: -> world.create new AlignCenterIconWdgt createAlignLeftIconWdgt: -> world.create new AlignLeftIconWdgt createWorldMapIconMorph: -> world.create new SimpleWorldMapIconWdgt createUSAMapIconMorph: -> world.create new SimpleUSAMapIconWdgt createBoldIconWdgt: -> world.create new BoldIconWdgt createItalicIconWdgt: -> world.create new ItalicIconWdgt createInformationIconWdgt: -> world.create new InformationIconWdgt createTextboxIconWdgt: -> world.create new TextIconWdgt createVideoPlayIconWdgt: -> world.create new VideoPlayIconWdgt createSimpleDocumentWdgt: -> simpleDocument = new SimpleDocumentWdgt wm = new WindowWdgt nil, nil, simpleDocument wm.setExtent new Point 368, 335 wm.fullRawMoveTo world.hand.position().subtract new Point 50, 100 wm.fullRawMoveWithin world world.add wm createSimpleLinkWdgt: -> simpleLinkWdgt = new SimpleLinkWdgt simpleLinkWdgt.setExtent new Point 405, 50 world.create simpleLinkWdgt createSimpleVideoLinkWdgt: -> simpleVideoLinkWdgt = new SimpleVideoLinkWdgt simpleVideoLinkWdgt.setExtent new Point 405, 50 world.create simpleVideoLinkWdgt create2DAxis: -> vertAxis = new AxisWdgt vertAxis.setExtent new Point 40, 300 world.create vertAxis createExampleScatterPlot: -> exampleScatterPlot = new ExampleScatterPlotWdgt exampleScatterPlot.setExtent new Point 300, 300 world.create exampleScatterPlot createExampleScatterPlotWithAxes: -> exampleScatterPlot = new ExampleScatterPlotWdgt plotWithAxesWdgt = new PlotWithAxesWdgt exampleScatterPlot plotWithAxesWdgt.rawSetExtent new Point 300, 300 world.create plotWithAxesWdgt createExampleFunctionPlot: -> exampleFunctionPlot = new ExampleFunctionPlotWdgt exampleFunctionPlot.setExtent new Point 300, 300 world.create exampleFunctionPlot createExampleBarPlot: -> exampleBarPlot = new ExampleBarPlotWdgt exampleBarPlot.setExtent new Point 300, 300 world.create exampleBarPlot createExample3DPlot: -> example3DPlot = new Example3DPlotWdgt example3DPlot.setExtent new Point 300, 300 world.create example3DPlot popUpMapsMenu: (morphOpeningThePopUp) -> menu = new MenuMorph morphOpeningThePopUp, false, @, true, true, "Maps" menu.addMenuItem "world map", true, menusHelper, "createWorldMapIconMorph", "others" menu.addMenuItem "USA map", true, menusHelper, "createUSAMapIconMorph", "others" menu.popUpAtHand() popUpGraphsMenu: (morphOpeningThePopUp) -> menu = new MenuMorph morphOpeningThePopUp, false, @, true, true, "graphs" menu.addMenuItem "axis", true, menusHelper, "create2DAxis" menu.addMenuItem "scatter plot", true, menusHelper, "createExampleScatterPlot" menu.addMenuItem "scatter plot with axes", true, menusHelper, "createExampleScatterPlotWithAxes" menu.addMenuItem "function plot", true, menusHelper, "createExampleFunctionPlot" menu.addMenuItem "bar plot", true, menusHelper, "createExampleBarPlot" menu.addMenuItem "3D plot", true, menusHelper, "createExample3DPlot" menu.popUpAtHand() popUpSupportDocsMenu: (morphOpeningThePopUp) -> menu = new MenuMorph morphOpeningThePopUp, false, @, true, true, "Support Docs" menu.addMenuItem "welcome message", true, @, "createWelcomeMessageWindowAndShortcut", "welcome message" menu.popUpAtHand() # this part is excluded from the fizzygum homepage build <<« createWelcomeMessageWindowAndShortcut: -> wm = WelcomeMessageInfoWdgt.create() readmeLauncher = new IconicDesktopSystemDocumentShortcutWdgt wm, "Welcome", new WelcomeIconWdgt # this "add" is going to try to position the reference # in some smart way (i.e. according to a grid) world.add readmeLauncher readmeLauncher.setExtent new Point 75, 75 readmeLauncher.fullChanged() # ------------------------------------------------------------------------ launchDegreesConverter: -> @createDegreesConverterWindowOrBringItUpIfAlreadyCreated() createDegreesConverterOpener: (inWhichFolder) -> degreesConverterOpenerLauncher = new IconicDesktopSystemWindowedAppLauncherWdgt "°C ↔ °F", new DegreesConverterIconWdgt, @, "launchDegreesConverter" # this "add" is going to try to position the reference # in some smart way (i.e. according to a grid) degreesConverterOpenerLauncher.setExtent new Point 75, 75 if inWhichFolder? inWhichFolder.contents.contents.add degreesConverterOpenerLauncher else world.add degreesConverterOpenerLauncher # ------------------------------------------------------------------------ launchSampleDashboard: -> @createSampleDashboardWindowOrBringItUpIfAlreadyCreated() createSampleDashboardOpener: (inWhichFolder) -> degreesConverterOpenerLauncher = new IconicDesktopSystemWindowedAppLauncherWdgt "sample dashb", (new GenericShortcutIconWdgt new DashboardsIconWdgt), @, "launchSampleDashboard" # this "add" is going to try to position the reference # in some smart way (i.e. according to a grid) degreesConverterOpenerLauncher.setExtent new Point 75, 75 if inWhichFolder? inWhichFolder.contents.contents.add degreesConverterOpenerLauncher else world.add degreesConverterOpenerLauncher # ------------------------------------------------------------------------ launchSampleSlide: -> @createSampleSlideWindowOrBringItUpIfAlreadyCreated() createSampleSlideOpener: (inWhichFolder) -> degreesConverterOpenerLauncher = new IconicDesktopSystemWindowedAppLauncherWdgt "sample slide", (new GenericShortcutIconWdgt new SimpleSlideIconWdgt), @, "launchSampleSlide" # this "add" is going to try to position the reference # in some smart way (i.e. according to a grid) degreesConverterOpenerLauncher.setExtent new Point 75, 75 if inWhichFolder? inWhichFolder.contents.contents.add degreesConverterOpenerLauncher else world.add degreesConverterOpenerLauncher # ------------------------------------------------------------------------ launchSampleDoc: -> @createSampleDocWindowOrBringItUpIfAlreadyCreated() createSampleDocOpener: (inWhichFolder) -> degreesConverterOpenerLauncher = new IconicDesktopSystemWindowedAppLauncherWdgt "sample doc", (new GenericShortcutIconWdgt new TypewriterIconWdgt), @, "launchSampleDoc" # this "add" is going to try to position the reference # in some smart way (i.e. according to a grid) degreesConverterOpenerLauncher.setExtent new Point 75, 75 if inWhichFolder? inWhichFolder.contents.contents.add degreesConverterOpenerLauncher else world.add degreesConverterOpenerLauncher # ------------------------------------------------------------------------ createSampleSlideWindowOrBringItUpIfAlreadyCreated: -> if world.sampleSlideWindow? if !world.sampleSlideWindow.destroyed and world.sampleSlideWindow.parent? world.add world.sampleSlideWindow world.sampleSlideWindow.bringToForeground() world.sampleSlideWindow.fullRawMoveTo world.hand.position().add new Point 100, -50 world.sampleSlideWindow.fullRawMoveWithin world world.sampleSlideWindow.rememberFractionalSituationInHoldingPanel() return slideWdgt = new SimpleSlideWdgt container = slideWdgt.stretchableWidgetContainer.contents container.rawSetExtent new Point 575,454 windowWithScrollingPanel = new WindowWdgt nil, nil, new ScrollPanelWdgt, true, true windowWithScrollingPanel.setTitleWithoutPrependedContentName "New York City" windowWithScrollingPanel.fullRawMoveTo container.position().add new Point 28, 43 windowWithScrollingPanel.rawSetExtent new Point 322, 268 container.add windowWithScrollingPanel windowWithScrollingPanel.rememberFractionalSituationInHoldingPanel() usaMap = new SimpleUSAMapIconWdgt Color.create 183, 183, 183 usaMap.rawSetExtent new Point 1808, 1115 windowWithScrollingPanel.contents.add usaMap windowWithScrollingPanel.contents.scrollTo new Point 1484, 246 usaMap.rememberFractionalSituationInHoldingPanel() mapPin = new MapPinIconWdgt windowWithScrollingPanel.contents.add mapPin mapPin.fullRawMoveTo windowWithScrollingPanel.contents.contents.position().add new Point 1606, 343 mapPin.rememberFractionalSituationInHoldingPanel() sampleBarPlot = new WindowWdgt nil, nil, new PlotWithAxesWdgt(new ExampleBarPlotWdgt), true, true sampleBarPlot.rawSetExtent new Point 240, 104 windowWithScrollingPanel.contents.add sampleBarPlot sampleBarPlot.fullRawMoveTo windowWithScrollingPanel.contents.contents.position().add new Point 1566, 420 sampleBarPlot.setTitleWithoutPrependedContentName "NYC: traffic" windowWithScrollingPanel.contents.disableDragsDropsAndEditing() mapCaption = new TextMorph2 "The City of New York, often called New York City or simply New York, is the most populous city in the United States. With an estimated 2017 population of 8,622,698 distributed over a land area of about 302.6 square miles (784 km2), New York City is also the most densely populated major city in the United States." mapCaption.fittingSpecWhenBoundsTooLarge = FittingSpecTextInLargerBounds.SCALEUP mapCaption.fittingSpecWhenBoundsTooSmall = FittingSpecTextInSmallerBounds.SCALEDOWN mapCaption.fullRawMoveTo container.position().add new Point 366, 40 mapCaption.rawSetExtent new Point 176, 387 container.add mapCaption mapCaption.rememberFractionalSituationInHoldingPanel() wikiLink = new SimpleLinkWdgt "New York City Wikipedia page", "https://en.wikipedia.org/wiki/New_York_City" wikiLink.fullRawMoveTo container.position().add new Point 110, 348 wikiLink.rawSetExtent new Point 250, 50 container.add wikiLink wikiLink.rememberFractionalSituationInHoldingPanel() wm = new WindowWdgt nil, nil, slideWdgt wm.fullRawMoveTo new Point 114, 10 wm.rawSetExtent new Point 596, 592 world.add wm wm.setTitleWithoutPrependedContentName "Sample slide" slideWdgt.disableDragsDropsAndEditing() # if we don't do this, the window would ask to save content # when closed. Just close it instead. # TODO: should be done using a flag, we don't like # to inject code like this: the source is not tracked slideWdgt.closeFromContainerWindow = (containerWindow) -> containerWindow.close() world.sampleSlideWindow = wm createSampleDocWindowOrBringItUpIfAlreadyCreated: -> if world.sampleDocWindow? if !world.sampleDocWindow.destroyed and world.sampleDocWindow.parent? world.add world.sampleDocWindow world.sampleDocWindow.bringToForeground() world.sampleDocWindow.fullRawMoveTo world.hand.position().add new Point 100, -50 world.sampleDocWindow.fullRawMoveWithin world world.sampleDocWindow.rememberFractionalSituationInHoldingPanel() return world.sampleDocWindow = SimpleDocumentSampleWdgt.create() createSampleDashboardWindowOrBringItUpIfAlreadyCreated: -> if world.sampleDashboardWindow? if !world.sampleDashboardWindow.destroyed and world.sampleDashboardWindow.parent? world.add world.sampleDashboardWindow world.sampleDashboardWindow.bringToForeground() world.sampleDashboardWindow.fullRawMoveTo world.hand.position().add new Point 100, -50 world.sampleDashboardWindow.fullRawMoveWithin world world.sampleDashboardWindow.rememberFractionalSituationInHoldingPanel() return slideWdgt = new DashboardsWdgt container = slideWdgt.stretchableWidgetContainer.contents container.rawSetExtent new Point 725,556 scatterPlot = new WindowWdgt nil, nil, new PlotWithAxesWdgt(new ExampleScatterPlotWdgt), true, true scatterPlot.fullRawMoveTo container.position().add new Point 19, 86 scatterPlot.rawSetExtent new Point 200, 200 container.add scatterPlot scatterPlot.rememberFractionalSituationInHoldingPanel() functionPlot = new WindowWdgt nil, nil, new PlotWithAxesWdgt(new ExampleFunctionPlotWdgt), true, true functionPlot.fullRawMoveTo container.position().add new Point 251, 86 functionPlot.rawSetExtent new Point 200, 200 container.add functionPlot functionPlot.rememberFractionalSituationInHoldingPanel() barPlot = new WindowWdgt nil, nil, new PlotWithAxesWdgt(new ExampleBarPlotWdgt), true, true barPlot.fullRawMoveTo container.position().add new Point 19, 327 barPlot.rawSetExtent new Point 200, 200 container.add barPlot barPlot.rememberFractionalSituationInHoldingPanel() plot3D = new WindowWdgt nil, nil, new Example3DPlotWdgt, true, true plot3D.fullRawMoveTo container.position().add new Point 491, 327 plot3D.rawSetExtent new Point 200, 150 container.add plot3D plot3D.rememberFractionalSituationInHoldingPanel() usaMap = new SimpleUSAMapIconWdgt Color.create 183, 183, 183 usaMap.fullRawMoveTo container.position().add new Point 242, 355 usaMap.rawSetExtent new Point 230, 145 container.add usaMap usaMap.rememberFractionalSituationInHoldingPanel() mapPin1 = new MapPinIconWdgt mapPin1.fullRawMoveTo container.position().add new Point 226, 376 container.add mapPin1 mapPin1.rememberFractionalSituationInHoldingPanel() mapPin2 = new MapPinIconWdgt mapPin2.fullRawMoveTo container.position().add new Point 289, 363 container.add mapPin2 mapPin2.rememberFractionalSituationInHoldingPanel() mapPin3 = new MapPinIconWdgt mapPin3.fullRawMoveTo container.position().add new Point 323, 397 container.add mapPin3 mapPin3.rememberFractionalSituationInHoldingPanel() mapPin4 = new MapPinIconWdgt mapPin4.fullRawMoveTo container.position().add new Point 360, 421 container.add mapPin4 mapPin4.rememberFractionalSituationInHoldingPanel() mapPin5 = new MapPinIconWdgt mapPin5.fullRawMoveTo container.position().add new Point 417, 374 container.add mapPin5 mapPin5.rememberFractionalSituationInHoldingPanel() worldMap = new SimpleWorldMapIconWdgt Color.create 183, 183, 183 worldMap.fullRawMoveTo container.position().add new Point 464, 128 worldMap.rawSetExtent new Point 240, 125 container.add worldMap worldMap.rememberFractionalSituationInHoldingPanel() speechBubble1 = new SpeechBubbleWdgt "online" speechBubble1.fullRawMoveTo container.position().add new Point 506, 123 speechBubble1.rawSetExtent new Point 66, 42 container.add speechBubble1 speechBubble1.rememberFractionalSituationInHoldingPanel() speechBubble2 = new SpeechBubbleWdgt "offline" speechBubble2.fullRawMoveTo container.position().add new Point 590, 105 speechBubble2.rawSetExtent new Point 66, 42 container.add speechBubble2 speechBubble2.rememberFractionalSituationInHoldingPanel() dashboardTitle = new TextMorph2 "Example dashboard with interactive 3D plot" dashboardTitle.alignCenter() dashboardTitle.alignMiddle() dashboardTitle.fullRawMoveTo container.position().add new Point 161, 6 dashboardTitle.rawSetExtent new Point 403, 50 container.add dashboardTitle dashboardTitle.rememberFractionalSituationInHoldingPanel() slider1 = new SliderMorph nil, nil, nil, nil, nil, true slider1.fullRawMoveTo container.position().add new Point 491, 484 slider1.rawSetExtent new Point 201, 24 container.add slider1 slider1.rememberFractionalSituationInHoldingPanel() slider1.setTargetAndActionWithOnesPickedFromMenu nil, nil, plot3D.contents, "setParameter" wm = new WindowWdgt nil, nil, slideWdgt wm.fullRawMoveTo new Point 114, 10 wm.rawSetExtent new Point 596, 592 world.add wm wm.setTitleWithoutPrependedContentName "Sample dashboard" slideWdgt.disableDragsDropsAndEditing() # if we don't do this, the window would ask to save content # when closed. Just close it instead. # TODO: should be done using a flag, we don't like # to inject code like this: the source is not tracked slideWdgt.closeFromContainerWindow = (containerWindow) -> containerWindow.close() world.sampleDashboardWindow = wm createDegreesConverterWindowOrBringItUpIfAlreadyCreated: -> if world.degreesConverterWindow? if !world.degreesConverterWindow.destroyed and world.degreesConverterWindow.parent? world.add world.degreesConverterWindow world.degreesConverterWindow.bringToForeground() world.degreesConverterWindow.fullRawMoveTo world.hand.position().add new Point 100, -50 world.degreesConverterWindow.fullRawMoveWithin world world.degreesConverterWindow.rememberFractionalSituationInHoldingPanel() return xCorrection = 32 yCorrection = 50 patchProgrammingWdgt = new PatchProgrammingWdgt container = patchProgrammingWdgt.stretchableWidgetContainer.contents container.rawSetExtent new Point 584,552 slider1 = new SliderMorph nil, nil, nil, nil, nil, true slider1.fullRawMoveTo container.position().add new Point 43+xCorrection, 195+yCorrection slider1.rawSetExtent new Point 20, 100 container.add slider1 slider1.rememberFractionalSituationInHoldingPanel() slider2 = new SliderMorph nil, nil, nil, nil, nil, true slider2.fullRawMoveTo container.position().add new Point 472+xCorrection, 203+yCorrection slider2.rawSetExtent new Point 20, 100 container.add slider2 slider2.rememberFractionalSituationInHoldingPanel() cText = new TextMorph2 "0" cText.fullRawMoveTo container.position().add new Point 104, 253 cText.rawSetExtent new Point 150, 75 container.add cText cText.rememberFractionalSituationInHoldingPanel() fText = new TextMorph2 "0" fText.fullRawMoveTo container.position().add new Point 344, 255 fText.alignRight() fText.rawSetExtent new Point 150, 75 container.add fText fText.rememberFractionalSituationInHoldingPanel() calc1 = new WindowWdgt nil, nil, new CalculatingPatchNodeWdgt("# °C → °F formula\n(in1)->Math.round in1*9/5+32"), true calc1.fullRawMoveTo container.position().add new Point 148+xCorrection/2, 19 calc1.rawSetExtent new Point 241, 167 container.add calc1 calc1.rememberFractionalSituationInHoldingPanel() calc2 = new WindowWdgt nil, nil, new CalculatingPatchNodeWdgt("# °F → °C formula\n(in1)->Math.round (in1-32)*5/9"), true calc2.fullRawMoveTo container.position().add new Point 148+xCorrection/2, 365 calc2.rawSetExtent new Point 241, 167 container.add calc2 calc2.rememberFractionalSituationInHoldingPanel() slider1.setTargetAndActionWithOnesPickedFromMenu nil, nil, cText, "setText" cText.setTargetAndActionWithOnesPickedFromMenu nil, nil, calc1.contents, "setInput1" calc1.contents.setTargetAndActionWithOnesPickedFromMenu nil, nil, fText, "setText" fText.setTargetAndActionWithOnesPickedFromMenu nil, nil, slider2, "setValue" slider2.setTargetAndActionWithOnesPickedFromMenu nil, nil, calc2.contents, "setInput1" calc2.contents.setTargetAndActionWithOnesPickedFromMenu nil, nil, slider1, "setValue" cLabel = new TextMorph2 "°C" cLabel.fullRawMoveTo container.position().add new Point 0+xCorrection, 102+yCorrection cLabel.rawSetExtent new Point 90, 90 container.add cLabel cLabel.rememberFractionalSituationInHoldingPanel() fLabel = new TextMorph2 "°F" fLabel.fullRawMoveTo container.position().add new Point 422+xCorrection, 102+yCorrection fLabel.rawSetExtent new Point 90, 90 container.add fLabel fLabel.rememberFractionalSituationInHoldingPanel() #@inform (@position().subtract @parent.position()) + " " + @extent() wm = new WindowWdgt nil, nil, patchProgrammingWdgt wm.fullRawMoveTo new Point 114, 10 wm.rawSetExtent new Point 596, 592 world.add wm wm.setTitleWithoutPrependedContentName "°C ↔ °F converter" patchProgrammingWdgt.disableDragsDropsAndEditing() cText.isEditable = true fText.isEditable = true # if we don't do this, the window would ask to save content # when closed. Just close it instead. # TODO: should be done using a flag, we don't like # to inject code like this: the source is not tracked patchProgrammingWdgt.closeFromContainerWindow = (containerWindow) -> containerWindow.close() world.degreesConverterWindow = wm # ------------------------------------------------------------------------ launchHowToSaveMessage: -> @createHowToSaveMessageWindowOrBringItUpIfAlreadyCreated() createHowToSaveMessageOpener: -> toolbarsOpenerLauncher = new IconicDesktopSystemWindowedAppLauncherWdgt "How to save?", new FloppyDiskIconWdgt, @, "launchHowToSaveMessage" # this "add" is going to try to position the reference # in some smart way (i.e. according to a grid) world.add toolbarsOpenerLauncher toolbarsOpenerLauncher.setExtent new Point 75, 75 toolbarsOpenerLauncher.fullChanged() # ------------------------------------------------------------------------ createHowToSaveMessageWindowOrBringItUpIfAlreadyCreated: -> if world.howToSaveDocWindow? if !world.howToSaveDocWindow.destroyed and world.howToSaveDocWindow.parent? world.add world.howToSaveDocWindow world.howToSaveDocWindow.bringToForeground() world.howToSaveDocWindow.fullRawMoveTo world.hand.position().add new Point 100, -50 world.howToSaveDocWindow.fullRawMoveWithin world world.howToSaveDocWindow.rememberFractionalSituationInHoldingPanel() return world.howToSaveDocWindow = HowToSaveMessageInfoWdg.create()
33876
# All "actions" functions for all accessory menu items should belong # in here. Also helps so we don't pollute moprhs with a varying number # of helper functions, which is problematic for visual diffing # on inspectors (the number of methods keeps changing). class MenusHelper @augmentWith DeepCopierMixin popUpDevToolsMenu: (morphOpeningThePopUp, widgetThisMenuIsAbout) -> menu = new MenuMorph morphOpeningThePopUp, false, @, true, true, "Dev Tools" menu.addMenuItem "inspect", true, widgetThisMenuIsAbout, "inspect2", "open a window\non all properties" menu.addMenuItem "console", true, widgetThisMenuIsAbout, "createConsole", "console" menu.popUpAtHand() # »>> this part is excluded from the fizzygum homepage build createFridgeMagnets: -> fmm = new FridgeMagnetsMorph wm = new WindowWdgt nil, nil, fmm wm.setExtent new Point 570, 400 wm.fullRawMoveTo world.hand.position() wm.fullRawMoveWithin world world.add wm createReconfigurablePaint: -> reconfPaint = new ReconfigurablePaintWdgt wm = new WindowWdgt nil, nil, reconfPaint wm.setExtent new Point 460, 400 wm.fullRawMoveTo world.hand.position() wm.fullRawMoveWithin world world.add wm createSimpleSlideWdgt: -> simpleSlide = new SimpleSlideWdgt wm = new WindowWdgt nil, nil, simpleSlide wm.setExtent new Point 460, 400 wm.fullRawMoveTo world.hand.position() wm.fullRawMoveWithin world world.add wm createSimpleButton: -> world.create new SimpleRectangularButtonMorph true, @, nil, new IconMorph(nil) createSwitchButtonMorph: -> button1 = new SimpleRectangularButtonMorph true, @, nil, new IconMorph(nil) button2 = new SimpleRectangularButtonMorph true, @, nil, new StringMorph2 "Hello World! ⎲ƒ⎳⎷ ⎸⎹ " world.create new SwitchButtonMorph [button1, button2] createNewClippingBoxMorph: -> world.create new ClippingBoxMorph makeSlidersButtonsStatesBright: -> world.forAllChildrenBottomToTop (child) -> if child instanceof SliderButtonMorph child.pressColor = Color.LIME child.highlightColor = Color.BLUE child.normalColor = Color.BLACK # Icons -------------------------------------------------------------- makeIconWithText: -> world.create new WidgetHolderWithCaptionWdgt "hey there", new BrushIconMorph makeEmptyIconWithText: -> world.create new WidgetHolderWithCaptionWdgt "hey there" makeFolderWindow: (a,b,c,d,e) -> world.create new FolderWindowWdgt nil,nil,nil,nil, @ makeBouncingParticle: -> world.create new BouncerWdgt createDestroyIconMorph: -> world.create new DestroyIconMorph createUnderCarpetIconMorph: -> world.create new UnderCarpetIconMorph createUncollapsedStateIconMorph: -> world.create new UncollapsedStateIconMorph createCollapsedStateIconMorph: -> world.create new CollapsedStateIconMorph createCloseIconButtonMorph: -> world.create new CloseIconButtonMorph createScratchAreaIconMorph: -> world.create new ScratchAreaIconMorph createFloraIconMorph: -> world.create new FloraIconMorph createScooterIconMorph: -> world.create new ScooterIconMorph createHeartIconMorph: -> world.create new HeartIconMorph createPencil1IconMorph: -> world.create new PencilIconMorph createPencil2IconMorph: -> world.create new Pencil2IconMorph createBrushIconMorph: -> world.create new BrushIconMorph createToothpasteIconMorph: -> world.create new ToothpasteIconMorph createEraserIconMorph: -> world.create new EraserIconMorph createTrashcanIconWdgt: -> world.create new TrashcanIconWdgt createShortcutArrowIconWdgt: -> world.create new ShortcutArrowIconWdgt createRasterPicIconWdgt: -> world.create new RasterPicIconWdgt createPaintBucketIconWdgt: -> world.create new PaintBucketIconWdgt createObjectIconWdgt: -> world.create new ObjectIconWdgt createFolderIconWdgt: -> world.create new FolderIconWdgt createBasementIconWdgt: -> world.create new BasementIconWdgt createWidgetIconWdgt: -> world.create new WidgetIconWdgt makeGenericReferenceIcon: -> world.create new GenericShortcutIconWdgt makeGenericObjectIcon: -> world.create new GenericObjectIconWdgt # this part is excluded from the fizzygum homepage build <<« basementIconAndText: -> world.add new BasementOpenerWdgt # »>> this part is excluded from the fizzygum homepage build newScriptWindow: -> scriptWdgt = new ScriptWdgt wm = new WindowWdgt nil, nil, scriptWdgt wm.setExtent new Point 460, 400 wm.fullRawMoveTo world.hand.position().subtract new Point 50, 100 wm.fullRawMoveWithin world world.add wm # this part is excluded from the fizzygum homepage build <<« # ------------------------------------------------------------------------ launchFizzyPaint: -> wm = new WindowWdgt nil, nil, new ReconfigurablePaintWdgt wm.setExtent new Point 460, 400 wm.fullRawMoveTo new Point 174, 114 wm.fullRawMoveWithin world world.add wm ReconfigurablePaintInfoWdgt.createNextTo wm createFizzyPaintLauncher: -> fizzyPaintLauncher = new IconicDesktopSystemWindowedAppLauncherWdgt "Draw", new PaintBucketIconWdgt, @, "launchFizzyPaint" # this "add" is going to try to position the reference # in some smart way (i.e. according to a grid) world.add fizzyPaintLauncher fizzyPaintLauncher.setExtent new Point 75, 75 fizzyPaintLauncher.fullChanged() # ------------------------------------------------------------------------ launchSimpleDocument: -> wm = new WindowWdgt nil, nil, new SimpleDocumentWdgt wm.setExtent new Point 370, 395 wm.fullRawMoveTo new Point 170, 88 wm.fullRawMoveWithin world world.add wm SimpleDocumentInfoWdgt.createNextTo wm createSimpleDocumentLauncher: -> simpleDocumentLauncher = new IconicDesktopSystemWindowedAppLauncherWdgt "Docs Maker", new TypewriterIconWdgt, @, "launchSimpleDocument" # this "add" is going to try to position the reference # in some smart way (i.e. according to a grid) world.add simpleDocumentLauncher simpleDocumentLauncher.setExtent new Point 75, 75 simpleDocumentLauncher.fullChanged() # ------------------------------------------------------------------------ launchSimpleSlide: -> wm = new WindowWdgt nil, nil, new SimpleSlideWdgt wm.setExtent new Point 460, 400 wm.fullRawMoveTo new Point 168, 134 wm.fullRawMoveWithin world world.add wm SimpleSlideInfoWdgt.createNextTo wm createSimpleSlideLauncher: -> simpleSlideLauncher = new IconicDesktopSystemWindowedAppLauncherWdgt "Slides Maker", new SimpleSlideIconWdgt, @, "launchSimpleSlide" # this "add" is going to try to position the reference # in some smart way (i.e. according to a grid) world.add simpleSlideLauncher simpleSlideLauncher.setExtent new Point 75, 75 simpleSlideLauncher.fullChanged() # ------------------------------------------------------------------------ launchDashboards: -> reconfPaint = new DashboardsWdgt wm = new WindowWdgt nil, nil, reconfPaint wm.setExtent new Point 460, 400 wm.fullRawMoveTo world.hand.position() wm.fullRawMoveWithin world world.add wm DashboardsInfoWdgt.createNextTo wm createDashboardsLauncher: -> simpleDashboardsLauncher = new IconicDesktopSystemWindowedAppLauncherWdgt "Dashboards", new DashboardsIconWdgt, @, "launchDashboards" # this "add" is going to try to position the reference # in some smart way (i.e. according to a grid) world.add simpleDashboardsLauncher simpleDashboardsLauncher.setExtent new Point 75, 75 simpleDashboardsLauncher.fullChanged() # ------------------------------------------------------------------------ launchPatchProgramming: -> patchProgramming = new PatchProgrammingWdgt wm = new WindowWdgt nil, nil, patchProgramming wm.setExtent new Point 460, 400 wm.fullRawMoveTo world.hand.position() wm.fullRawMoveWithin world world.add wm PatchProgrammingInfoWdgt.createNextTo wm createPatchProgrammingLauncher: -> patchProgrammingLauncher = new IconicDesktopSystemWindowedAppLauncherWdgt "Patch progr.", new PatchProgrammingIconWdgt, @, "launchPatchProgramming" # this "add" is going to try to position the reference # in some smart way (i.e. according to a grid) world.add patchProgrammingLauncher patchProgrammingLauncher.setExtent new Point 75, 75 patchProgrammingLauncher.fullChanged() # ------------------------------------------------------------------------ launchGenericPanel: -> genericPanel = new StretchableEditableWdgt wm = new WindowWdgt nil, nil, genericPanel wm.setExtent new Point 460, 400 wm.fullRawMoveTo world.hand.position() wm.fullRawMoveWithin world world.add wm GenericPanelInfoWdgt.createNextTo wm createGenericPanelLauncher: -> genericPanelLauncher = new IconicDesktopSystemWindowedAppLauncherWdgt "Generic panel", new GenericPanelIconWdgt, @, "launchGenericPanel" # this "add" is going to try to position the reference # in some smart way (i.e. according to a grid) world.add genericPanelLauncher genericPanelLauncher.setExtent new Point 75, 75 genericPanelLauncher.fullChanged() # ------------------------------------------------------------------------ launchToolbars: -> # tools ------------------------------- toolsPanel = new ScrollPanelWdgt new ToolPanelWdgt toolsPanel.addMany [ new TextToolbarCreatorButtonWdgt new UsefulTextSnippetsToolbarCreatorButtonWdgt new SlidesToolbarCreatorButtonWdgt new PlotsToolbarCreatorButtonWdgt new PatchProgrammingComponentsToolbarCreatorButtonWdgt new WindowsToolbarCreatorButtonWdgt ] toolsPanel.disableDragsDropsAndEditing() wm = new WindowWdgt nil, nil, toolsPanel wm.setExtent new Point 60, 261 wm.fullRawMoveTo new Point 170, 170 wm.fullRawMoveWithin world world.add wm ToolbarsInfoWdgt.createNextTo wm createToolbarsOpener: -> toolbarsOpenerLauncher = new IconicDesktopSystemWindowedAppLauncherWdgt "Super Toolbar", new ToolbarsIconWdgt, @, "launchToolbars" toolbarsOpenerLauncher.toolTipMessage = "a toolbar to rule them all" # this "add" is going to try to position the reference # in some smart way (i.e. according to a grid) world.add toolbarsOpenerLauncher toolbarsOpenerLauncher.setExtent new Point 75, 75 toolbarsOpenerLauncher.fullChanged() # ------------------------------------------------------------------------ createNewTemplatesWindow: -> sdspw = new SimpleDocumentScrollPanelWdgt sdspw.rawSetExtent new Point 365, 335 startingContent = new SimplePlainTextWdgt( "Simply drag the items below into your document",nil,nil,nil,nil,nil,WorldMorph.preferencesAndSettings.editableItemBackgroundColor, 1) startingContent.alignCenter() startingContent.setFontSize 18 startingContent.isEditable = true startingContent.enableSelecting() sdspw.setContents startingContent, 5 startingContent = new ArrowSIconWdgt startingContent.rawSetExtent new Point 25, 25 sdspw.add startingContent startingContent.layoutSpecDetails.setAlignmentToCenter() sdspw.addDivider() startingContent = new SimplePlainTextWdgt( "Title",nil,nil,nil,nil,nil,WorldMorph.preferencesAndSettings.editableItemBackgroundColor, 1) startingContent.alignCenter() startingContent.setFontName nil, nil, startingContent.georgiaFontStack startingContent.setFontSize 48 startingContent.isEditable = true startingContent.enableSelecting() sdspw.add startingContent startingContent = new SimplePlainTextWdgt( "Section X",nil,nil,nil,nil,nil,WorldMorph.preferencesAndSettings.editableItemBackgroundColor, 1) startingContent.toggleWeight() startingContent.isEditable = true startingContent.enableSelecting() startingContent.setFontSize 28 sdspw.add startingContent startingContent = new SimplePlainTextWdgt( "Section X.X",nil,nil,nil,nil,nil,WorldMorph.preferencesAndSettings.editableItemBackgroundColor, 1) startingContent.isEditable = true startingContent.enableSelecting() startingContent.setFontSize 24 sdspw.add startingContent sdspw.addNormalParagraph "Normal text." startingContent = new SimplePlainTextWdgt( "“Be careful--with quotations, you can damn anything.”\n― <NAME>",nil,nil,nil,nil,nil,WorldMorph.preferencesAndSettings.editableItemBackgroundColor, 1) startingContent.toggleItalic() startingContent.alignRight() startingContent.isEditable = true startingContent.enableSelecting() sdspw.add startingContent sdspw.addIndentedText "indentedText" sdspw.addBulletPoint "bullet point" sdspw.addCodeBlock "a code block with\n some example\n code in here" startingContent = new SimplePlainTextWdgt( "Spacers:",nil,nil,nil,nil,nil,WorldMorph.preferencesAndSettings.editableItemBackgroundColor, 1) startingContent.toggleWeight() startingContent.isEditable = true startingContent.enableSelecting() sdspw.add startingContent sdspw.addSpacer() sdspw.addSpacer 2 sdspw.addSpacer 3 startingContent = new SimplePlainTextWdgt( "Divider line:",nil,nil,nil,nil,nil,WorldMorph.preferencesAndSettings.editableItemBackgroundColor, 1) startingContent.toggleWeight() startingContent.isEditable = true startingContent.enableSelecting() sdspw.add startingContent sdspw.addDivider() startingContent = new SimplePlainTextWdgt( "Links:",nil,nil,nil,nil,nil,WorldMorph.preferencesAndSettings.editableItemBackgroundColor, 1) startingContent.toggleWeight() startingContent.isEditable = true startingContent.enableSelecting() sdspw.add startingContent startingContent = new SimpleLinkWdgt startingContent.rawSetExtent new Point 405, 50 sdspw.add startingContent startingContent.layoutSpecDetails.setAlignmentToRight() startingContent = new SimpleVideoLinkWdgt startingContent.rawSetExtent new Point 405, 50 sdspw.add startingContent startingContent.layoutSpecDetails.setAlignmentToRight() startingContent = new SimplePlainTextWdgt( "Useful characters:",nil,nil,nil,nil,nil,WorldMorph.preferencesAndSettings.editableItemBackgroundColor, 1) startingContent.toggleWeight() startingContent.isEditable = true startingContent.enableSelecting() sdspw.add startingContent # in March 2018, greek chars take a long time to paint on OSX/Chrome so # not adding those to the paragraph, however here they are: # αβγδεζηθικλμνξοπρστυφχψω ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ specialCharsParagraph = sdspw.addNormalParagraph "… †‡§ ↵⏎⇧␣ ☐☑☒✓X✗ •‣⁃◦ °±⁻¹²³µ×÷ℓΩ√∛∜∝∞∟∠∡∩∪∿≈⊂⋅⌀▫◽◻□⩽⩾ ¼½¾⅛⅜⅝⅞ ←↑→↓↔↕↵⇎⇏⇑⇒⇓⇔⇕ ©®™ $£€¥" specialCharsParagraph.setFontSize 16 sdspw.makeAllContentIntoTemplates() wm = new WindowWdgt nil, nil, sdspw wm.setExtent new Point 370, 335 wm.setTitleWithoutPrependedContentName "useful snippets" return wm # »>> this part is excluded from the fizzygum homepage build createFanout: -> fanoutWdgt = new FanoutWdgt world.create fanoutWdgt fanoutWdgt.setExtent new Point 100, 100 createCalculatingPatchNode: -> calculatingPatchNodeWdgt = new CalculatingPatchNodeWdgt wm = new WindowWdgt nil, nil, calculatingPatchNodeWdgt, true wm.setExtent new Point 460, 400 wm.fullRawMoveTo world.hand.position().subtract new Point 50, 100 wm.fullRawMoveWithin world world.add wm createDiffingPatchNode: -> diffingPatchNodeWdgt = new DiffingPatchNodeWdgt wm = new WindowWdgt nil, nil, diffingPatchNodeWdgt, true wm.setExtent new Point 460, 400 wm.fullRawMoveTo world.hand.position().subtract new Point 50, 100 wm.fullRawMoveWithin world world.add wm createSliderWithSmallestValueAtBottomEnd: -> world.create new SliderMorph nil, nil, nil, nil, nil, true createRegexSubstitutionPatchNodeWdgt: -> regexSubstitutionPatchNodeWdgt = new RegexSubstitutionPatchNodeWdgt wm = new WindowWdgt nil, nil, regexSubstitutionPatchNodeWdgt, true wm.setExtent new Point 460, 400 wm.fullRawMoveTo world.hand.position().subtract new Point 50, 100 wm.fullRawMoveWithin world world.add wm throwAnError: -> throw new Error "you manually threw an error!" createStretchablePanel: -> stretchablePanel = new StretchableWidgetContainerWdgt world.create stretchablePanel stretchablePanel.setExtent new Point 400, 300 createToolsPanel: -> toolPanel = new ScrollPanelWdgt new ToolPanelWdgt wm = new WindowWdgt nil, nil, toolPanel, true wm.setExtent new Point 200, 400 wm.fullRawMoveTo world.hand.position().subtract new Point 50, 100 wm.fullRawMoveWithin world world.add wm createHorizontalMenuPanelPanel: -> horizontalMenuPanel = new HorizontalMenuPanelWdgt wm = new WindowWdgt nil, nil, horizontalMenuPanel, true wm.setExtent new Point 200, 400 wm.fullRawMoveTo world.hand.position().subtract new Point 50, 100 wm.fullRawMoveWithin world world.add wm popUpMore1IconsMenu: (morphOpeningThePopUp) -> menu = new MenuMorph morphOpeningThePopUp, false, @, true, true, "More Icons 1" menu.addMenuItem "Pencil 1 icon", true, menusHelper, "createPencil1IconMorph" menu.addMenuItem "Pencil 2 icon", true, menusHelper, "createPencil2IconMorph" menu.addMenuItem "Brush icon", true, menusHelper, "createBrushIconMorph" menu.addMenuItem "Toothpaste icon", true, menusHelper, "createToothpasteIconMorph" menu.addMenuItem "Eraser icon", true, menusHelper, "createEraserIconMorph" menu.addMenuItem "Trashcan icon", true, menusHelper, "createTrashcanIconWdgt" menu.addMenuItem "Shortcut arrow icon", true, menusHelper, "createShortcutArrowIconWdgt" menu.addMenuItem "Raster pic icon", true, menusHelper, "createRasterPicIconWdgt" menu.addMenuItem "Paint bucket icon", true, menusHelper, "createPaintBucketIconWdgt" menu.addMenuItem "Object icon", true, menusHelper, "createObjectIconWdgt" menu.addMenuItem "Folder icon", true, menusHelper, "createFolderIconWdgt" menu.addMenuItem "Basement icon", true, menusHelper, "createBasementIconWdgt" menu.addMenuItem "Widget icon", true, menusHelper, "createWidgetIconWdgt" menu.popUpAtHand() popUpMore2IconsMenu: (morphOpeningThePopUp) -> menu = new MenuMorph morphOpeningThePopUp, false, @, true, true, "More Icons 2" menu.addMenuItem "Format as code icon", true, menusHelper, "createFormatAsCodeIconWdgt" menu.addMenuItem "Ch. X icon", true, menusHelper, "createChXIconWdgt" menu.addMenuItem "Ch. X.X icon", true, menusHelper, "createChXXIconWdgt" menu.addMenuItem "Ch. X.X.X icon", true, menusHelper, "createChXXXIconWdgt" menu.addMenuItem "Align right icon", true, menusHelper, "createAlignRightIconWdgt" menu.addMenuItem "Align center icon", true, menusHelper, "createAlignCenterIconWdgt" menu.addMenuItem "Align left icon", true, menusHelper, "createAlignLeftIconWdgt" menu.addMenuItem "Bold icon", true, menusHelper, "createBoldIconWdgt" menu.addMenuItem "Italic icon", true, menusHelper, "createItalicIconWdgt" menu.addMenuItem "Information icon", true, menusHelper, "createInformationIconWdgt" menu.addMenuItem "Textbox icon", true, menusHelper, "createTextboxIconWdgt" menu.addMenuItem "Video play icon", true, menusHelper, "createVideoPlayIconWdgt" menu.addMenuItem "Decrease font size icon", true, menusHelper, "createDecreaseFontSizeIconWdgt" menu.addMenuItem "Increase font size icon", true, menusHelper, "createIncreaseFontSizeIconWdgt" menu.addMenuItem "External link icon", true, menusHelper, "createExternalLinkIconWdgt" menu.addMenuItem "Templates icon", true, menusHelper, "createTemplatesIconWdgt" menu.popUpAtHand() popUpMore3IconsMenu: (morphOpeningThePopUp) -> menu = new MenuMorph morphOpeningThePopUp, false, @, true, true, "More Icons 2" menu.addMenuItem "Fizzygum logo", true, menusHelper, "createFizzygumLogoIconWdgt" menu.addMenuItem "Fizzygum logo with text", true, menusHelper, "createFizzygumLogoWithTextIconWdgt" menu.addMenuItem "Vaporwave sun", true, menusHelper, "createVaporwaveSunIconWdgt" menu.addMenuItem "Vaporwave background", true, menusHelper, "createVaporwaveBackgroundIconWdgt" menu.addMenuItem "Change font icon", true, menusHelper, "createChangeFontIconWdgt" menu.addMenuItem "C <-> F converter icon", true, menusHelper, "createCFDegreesConverterIconWdgt" menu.addMenuItem "Simple slide icon", true, menusHelper, "createSimpleSlideIconWdgt" menu.addMenuItem "Typewriter icon", true, menusHelper, "createTypewriterIconWdgt" menu.addMenuItem "Little world icon", true, menusHelper, "createLittleWorldIconWdgt" menu.addMenuItem "Little USA icon", true, menusHelper, "createLittleUSAIconWdgt" menu.addMenuItem "Map pin icon", true, menusHelper, "createMapPinIconWdgt" menu.addMenuItem "Save icon", true, menusHelper, "createSaveIconWdgt" menu.popUpAtHand() createFizzygumLogoWithTextIconWdgt : -> world.create new FizzygumLogoWithTextIconWdgt createVaporwaveBackgroundIconWdgt : -> world.create new VaporwaveBackgroundIconWdgt createCFDegreesConverterIconWdgt : -> world.create new CFDegreesConverterIconWdgt createFizzygumLogoIconWdgt : -> world.create new FizzygumLogoIconWdgt createVaporwaveSunIconWdgt : -> world.create new VaporwaveSunIconWdgt createLittleWorldIconWdgt : -> world.create new LittleWorldIconWdgt createChangeFontIconWdgt : -> world.create new ChangeFontIconWdgt createSimpleSlideIconWdgt : -> world.create new SimpleSlideIconWdgt createTypewriterIconWdgt : -> world.create new TypewriterIconWdgt createLittleUSAIconWdgt : -> world.create new LittleUSAIconWdgt createMapPinIconWdgt : -> world.create new MapPinIconWdgt createSaveIconWdgt : -> world.create new SaveIconWdgt popUpArrowsIconsMenu: (morphOpeningThePopUp) -> menu = new MenuMorph morphOpeningThePopUp, false, @, true, true, "Arrows" menu.addMenuItem "Arrow N icon", true, menusHelper, "createArrowNIconWdgt" menu.addMenuItem "Arrow S icon", true, menusHelper, "createArrowSIconWdgt" menu.addMenuItem "Arrow W icon", true, menusHelper, "createArrowWIconWdgt" menu.addMenuItem "Arrow E icon", true, menusHelper, "createArrowEIconWdgt" menu.addMenuItem "Arrow NW icon", true, menusHelper, "createArrowNWIconWdgt" menu.addMenuItem "Arrow NE icon", true, menusHelper, "createArrowNEIconWdgt" menu.addMenuItem "Arrow SE icon", true, menusHelper, "createArrowSEIconWdgt" menu.addMenuItem "Arrow SW icon", true, menusHelper, "createArrowSWIconWdgt" menu.popUpAtHand() createArrowEIconWdgt: -> world.create new ArrowEIconWdgt createArrowNEIconWdgt: -> world.create new ArrowNEIconWdgt createArrowNIconWdgt: -> world.create new ArrowNIconWdgt createArrowNWIconWdgt: -> world.create new ArrowNWIconWdgt createArrowSEIconWdgt: -> world.create new ArrowSEIconWdgt createArrowSIconWdgt: -> world.create new ArrowSIconWdgt createArrowSWIconWdgt: -> world.create new ArrowSWIconWdgt createArrowWIconWdgt: -> world.create new ArrowWIconWdgt createDecreaseFontSizeIconWdgt: -> world.create new DecreaseFontSizeIconWdgt createExternalLinkIconWdgt: -> world.create new ExternalLinkIconWdgt createIncreaseFontSizeIconWdgt: -> world.create new IncreaseFontSizeIconWdgt createTemplatesIconWdgt: -> world.create new TemplatesIconWdgt createFormatAsCodeIconWdgt: -> world.create new FormatAsCodeIconWdgt createChXIconWdgt: -> world.create new ChapterXIconWdgt createChXXIconWdgt: -> world.create new ChapterXXIconWdgt createChXXXIconWdgt: -> world.create new ChapterXXXIconWdgt createAlignRightIconWdgt: -> world.create new AlignRightIconWdgt createAlignCenterIconWdgt: -> world.create new AlignCenterIconWdgt createAlignLeftIconWdgt: -> world.create new AlignLeftIconWdgt createWorldMapIconMorph: -> world.create new SimpleWorldMapIconWdgt createUSAMapIconMorph: -> world.create new SimpleUSAMapIconWdgt createBoldIconWdgt: -> world.create new BoldIconWdgt createItalicIconWdgt: -> world.create new ItalicIconWdgt createInformationIconWdgt: -> world.create new InformationIconWdgt createTextboxIconWdgt: -> world.create new TextIconWdgt createVideoPlayIconWdgt: -> world.create new VideoPlayIconWdgt createSimpleDocumentWdgt: -> simpleDocument = new SimpleDocumentWdgt wm = new WindowWdgt nil, nil, simpleDocument wm.setExtent new Point 368, 335 wm.fullRawMoveTo world.hand.position().subtract new Point 50, 100 wm.fullRawMoveWithin world world.add wm createSimpleLinkWdgt: -> simpleLinkWdgt = new SimpleLinkWdgt simpleLinkWdgt.setExtent new Point 405, 50 world.create simpleLinkWdgt createSimpleVideoLinkWdgt: -> simpleVideoLinkWdgt = new SimpleVideoLinkWdgt simpleVideoLinkWdgt.setExtent new Point 405, 50 world.create simpleVideoLinkWdgt create2DAxis: -> vertAxis = new AxisWdgt vertAxis.setExtent new Point 40, 300 world.create vertAxis createExampleScatterPlot: -> exampleScatterPlot = new ExampleScatterPlotWdgt exampleScatterPlot.setExtent new Point 300, 300 world.create exampleScatterPlot createExampleScatterPlotWithAxes: -> exampleScatterPlot = new ExampleScatterPlotWdgt plotWithAxesWdgt = new PlotWithAxesWdgt exampleScatterPlot plotWithAxesWdgt.rawSetExtent new Point 300, 300 world.create plotWithAxesWdgt createExampleFunctionPlot: -> exampleFunctionPlot = new ExampleFunctionPlotWdgt exampleFunctionPlot.setExtent new Point 300, 300 world.create exampleFunctionPlot createExampleBarPlot: -> exampleBarPlot = new ExampleBarPlotWdgt exampleBarPlot.setExtent new Point 300, 300 world.create exampleBarPlot createExample3DPlot: -> example3DPlot = new Example3DPlotWdgt example3DPlot.setExtent new Point 300, 300 world.create example3DPlot popUpMapsMenu: (morphOpeningThePopUp) -> menu = new MenuMorph morphOpeningThePopUp, false, @, true, true, "Maps" menu.addMenuItem "world map", true, menusHelper, "createWorldMapIconMorph", "others" menu.addMenuItem "USA map", true, menusHelper, "createUSAMapIconMorph", "others" menu.popUpAtHand() popUpGraphsMenu: (morphOpeningThePopUp) -> menu = new MenuMorph morphOpeningThePopUp, false, @, true, true, "graphs" menu.addMenuItem "axis", true, menusHelper, "create2DAxis" menu.addMenuItem "scatter plot", true, menusHelper, "createExampleScatterPlot" menu.addMenuItem "scatter plot with axes", true, menusHelper, "createExampleScatterPlotWithAxes" menu.addMenuItem "function plot", true, menusHelper, "createExampleFunctionPlot" menu.addMenuItem "bar plot", true, menusHelper, "createExampleBarPlot" menu.addMenuItem "3D plot", true, menusHelper, "createExample3DPlot" menu.popUpAtHand() popUpSupportDocsMenu: (morphOpeningThePopUp) -> menu = new MenuMorph morphOpeningThePopUp, false, @, true, true, "Support Docs" menu.addMenuItem "welcome message", true, @, "createWelcomeMessageWindowAndShortcut", "welcome message" menu.popUpAtHand() # this part is excluded from the fizzygum homepage build <<« createWelcomeMessageWindowAndShortcut: -> wm = WelcomeMessageInfoWdgt.create() readmeLauncher = new IconicDesktopSystemDocumentShortcutWdgt wm, "Welcome", new WelcomeIconWdgt # this "add" is going to try to position the reference # in some smart way (i.e. according to a grid) world.add readmeLauncher readmeLauncher.setExtent new Point 75, 75 readmeLauncher.fullChanged() # ------------------------------------------------------------------------ launchDegreesConverter: -> @createDegreesConverterWindowOrBringItUpIfAlreadyCreated() createDegreesConverterOpener: (inWhichFolder) -> degreesConverterOpenerLauncher = new IconicDesktopSystemWindowedAppLauncherWdgt "°C ↔ °F", new DegreesConverterIconWdgt, @, "launchDegreesConverter" # this "add" is going to try to position the reference # in some smart way (i.e. according to a grid) degreesConverterOpenerLauncher.setExtent new Point 75, 75 if inWhichFolder? inWhichFolder.contents.contents.add degreesConverterOpenerLauncher else world.add degreesConverterOpenerLauncher # ------------------------------------------------------------------------ launchSampleDashboard: -> @createSampleDashboardWindowOrBringItUpIfAlreadyCreated() createSampleDashboardOpener: (inWhichFolder) -> degreesConverterOpenerLauncher = new IconicDesktopSystemWindowedAppLauncherWdgt "sample dashb", (new GenericShortcutIconWdgt new DashboardsIconWdgt), @, "launchSampleDashboard" # this "add" is going to try to position the reference # in some smart way (i.e. according to a grid) degreesConverterOpenerLauncher.setExtent new Point 75, 75 if inWhichFolder? inWhichFolder.contents.contents.add degreesConverterOpenerLauncher else world.add degreesConverterOpenerLauncher # ------------------------------------------------------------------------ launchSampleSlide: -> @createSampleSlideWindowOrBringItUpIfAlreadyCreated() createSampleSlideOpener: (inWhichFolder) -> degreesConverterOpenerLauncher = new IconicDesktopSystemWindowedAppLauncherWdgt "sample slide", (new GenericShortcutIconWdgt new SimpleSlideIconWdgt), @, "launchSampleSlide" # this "add" is going to try to position the reference # in some smart way (i.e. according to a grid) degreesConverterOpenerLauncher.setExtent new Point 75, 75 if inWhichFolder? inWhichFolder.contents.contents.add degreesConverterOpenerLauncher else world.add degreesConverterOpenerLauncher # ------------------------------------------------------------------------ launchSampleDoc: -> @createSampleDocWindowOrBringItUpIfAlreadyCreated() createSampleDocOpener: (inWhichFolder) -> degreesConverterOpenerLauncher = new IconicDesktopSystemWindowedAppLauncherWdgt "sample doc", (new GenericShortcutIconWdgt new TypewriterIconWdgt), @, "launchSampleDoc" # this "add" is going to try to position the reference # in some smart way (i.e. according to a grid) degreesConverterOpenerLauncher.setExtent new Point 75, 75 if inWhichFolder? inWhichFolder.contents.contents.add degreesConverterOpenerLauncher else world.add degreesConverterOpenerLauncher # ------------------------------------------------------------------------ createSampleSlideWindowOrBringItUpIfAlreadyCreated: -> if world.sampleSlideWindow? if !world.sampleSlideWindow.destroyed and world.sampleSlideWindow.parent? world.add world.sampleSlideWindow world.sampleSlideWindow.bringToForeground() world.sampleSlideWindow.fullRawMoveTo world.hand.position().add new Point 100, -50 world.sampleSlideWindow.fullRawMoveWithin world world.sampleSlideWindow.rememberFractionalSituationInHoldingPanel() return slideWdgt = new SimpleSlideWdgt container = slideWdgt.stretchableWidgetContainer.contents container.rawSetExtent new Point 575,454 windowWithScrollingPanel = new WindowWdgt nil, nil, new ScrollPanelWdgt, true, true windowWithScrollingPanel.setTitleWithoutPrependedContentName "New York City" windowWithScrollingPanel.fullRawMoveTo container.position().add new Point 28, 43 windowWithScrollingPanel.rawSetExtent new Point 322, 268 container.add windowWithScrollingPanel windowWithScrollingPanel.rememberFractionalSituationInHoldingPanel() usaMap = new SimpleUSAMapIconWdgt Color.create 183, 183, 183 usaMap.rawSetExtent new Point 1808, 1115 windowWithScrollingPanel.contents.add usaMap windowWithScrollingPanel.contents.scrollTo new Point 1484, 246 usaMap.rememberFractionalSituationInHoldingPanel() mapPin = new MapPinIconWdgt windowWithScrollingPanel.contents.add mapPin mapPin.fullRawMoveTo windowWithScrollingPanel.contents.contents.position().add new Point 1606, 343 mapPin.rememberFractionalSituationInHoldingPanel() sampleBarPlot = new WindowWdgt nil, nil, new PlotWithAxesWdgt(new ExampleBarPlotWdgt), true, true sampleBarPlot.rawSetExtent new Point 240, 104 windowWithScrollingPanel.contents.add sampleBarPlot sampleBarPlot.fullRawMoveTo windowWithScrollingPanel.contents.contents.position().add new Point 1566, 420 sampleBarPlot.setTitleWithoutPrependedContentName "NYC: traffic" windowWithScrollingPanel.contents.disableDragsDropsAndEditing() mapCaption = new TextMorph2 "The City of New York, often called New York City or simply New York, is the most populous city in the United States. With an estimated 2017 population of 8,622,698 distributed over a land area of about 302.6 square miles (784 km2), New York City is also the most densely populated major city in the United States." mapCaption.fittingSpecWhenBoundsTooLarge = FittingSpecTextInLargerBounds.SCALEUP mapCaption.fittingSpecWhenBoundsTooSmall = FittingSpecTextInSmallerBounds.SCALEDOWN mapCaption.fullRawMoveTo container.position().add new Point 366, 40 mapCaption.rawSetExtent new Point 176, 387 container.add mapCaption mapCaption.rememberFractionalSituationInHoldingPanel() wikiLink = new SimpleLinkWdgt "New York City Wikipedia page", "https://en.wikipedia.org/wiki/New_York_City" wikiLink.fullRawMoveTo container.position().add new Point 110, 348 wikiLink.rawSetExtent new Point 250, 50 container.add wikiLink wikiLink.rememberFractionalSituationInHoldingPanel() wm = new WindowWdgt nil, nil, slideWdgt wm.fullRawMoveTo new Point 114, 10 wm.rawSetExtent new Point 596, 592 world.add wm wm.setTitleWithoutPrependedContentName "Sample slide" slideWdgt.disableDragsDropsAndEditing() # if we don't do this, the window would ask to save content # when closed. Just close it instead. # TODO: should be done using a flag, we don't like # to inject code like this: the source is not tracked slideWdgt.closeFromContainerWindow = (containerWindow) -> containerWindow.close() world.sampleSlideWindow = wm createSampleDocWindowOrBringItUpIfAlreadyCreated: -> if world.sampleDocWindow? if !world.sampleDocWindow.destroyed and world.sampleDocWindow.parent? world.add world.sampleDocWindow world.sampleDocWindow.bringToForeground() world.sampleDocWindow.fullRawMoveTo world.hand.position().add new Point 100, -50 world.sampleDocWindow.fullRawMoveWithin world world.sampleDocWindow.rememberFractionalSituationInHoldingPanel() return world.sampleDocWindow = SimpleDocumentSampleWdgt.create() createSampleDashboardWindowOrBringItUpIfAlreadyCreated: -> if world.sampleDashboardWindow? if !world.sampleDashboardWindow.destroyed and world.sampleDashboardWindow.parent? world.add world.sampleDashboardWindow world.sampleDashboardWindow.bringToForeground() world.sampleDashboardWindow.fullRawMoveTo world.hand.position().add new Point 100, -50 world.sampleDashboardWindow.fullRawMoveWithin world world.sampleDashboardWindow.rememberFractionalSituationInHoldingPanel() return slideWdgt = new DashboardsWdgt container = slideWdgt.stretchableWidgetContainer.contents container.rawSetExtent new Point 725,556 scatterPlot = new WindowWdgt nil, nil, new PlotWithAxesWdgt(new ExampleScatterPlotWdgt), true, true scatterPlot.fullRawMoveTo container.position().add new Point 19, 86 scatterPlot.rawSetExtent new Point 200, 200 container.add scatterPlot scatterPlot.rememberFractionalSituationInHoldingPanel() functionPlot = new WindowWdgt nil, nil, new PlotWithAxesWdgt(new ExampleFunctionPlotWdgt), true, true functionPlot.fullRawMoveTo container.position().add new Point 251, 86 functionPlot.rawSetExtent new Point 200, 200 container.add functionPlot functionPlot.rememberFractionalSituationInHoldingPanel() barPlot = new WindowWdgt nil, nil, new PlotWithAxesWdgt(new ExampleBarPlotWdgt), true, true barPlot.fullRawMoveTo container.position().add new Point 19, 327 barPlot.rawSetExtent new Point 200, 200 container.add barPlot barPlot.rememberFractionalSituationInHoldingPanel() plot3D = new WindowWdgt nil, nil, new Example3DPlotWdgt, true, true plot3D.fullRawMoveTo container.position().add new Point 491, 327 plot3D.rawSetExtent new Point 200, 150 container.add plot3D plot3D.rememberFractionalSituationInHoldingPanel() usaMap = new SimpleUSAMapIconWdgt Color.create 183, 183, 183 usaMap.fullRawMoveTo container.position().add new Point 242, 355 usaMap.rawSetExtent new Point 230, 145 container.add usaMap usaMap.rememberFractionalSituationInHoldingPanel() mapPin1 = new MapPinIconWdgt mapPin1.fullRawMoveTo container.position().add new Point 226, 376 container.add mapPin1 mapPin1.rememberFractionalSituationInHoldingPanel() mapPin2 = new MapPinIconWdgt mapPin2.fullRawMoveTo container.position().add new Point 289, 363 container.add mapPin2 mapPin2.rememberFractionalSituationInHoldingPanel() mapPin3 = new MapPinIconWdgt mapPin3.fullRawMoveTo container.position().add new Point 323, 397 container.add mapPin3 mapPin3.rememberFractionalSituationInHoldingPanel() mapPin4 = new MapPinIconWdgt mapPin4.fullRawMoveTo container.position().add new Point 360, 421 container.add mapPin4 mapPin4.rememberFractionalSituationInHoldingPanel() mapPin5 = new MapPinIconWdgt mapPin5.fullRawMoveTo container.position().add new Point 417, 374 container.add mapPin5 mapPin5.rememberFractionalSituationInHoldingPanel() worldMap = new SimpleWorldMapIconWdgt Color.create 183, 183, 183 worldMap.fullRawMoveTo container.position().add new Point 464, 128 worldMap.rawSetExtent new Point 240, 125 container.add worldMap worldMap.rememberFractionalSituationInHoldingPanel() speechBubble1 = new SpeechBubbleWdgt "online" speechBubble1.fullRawMoveTo container.position().add new Point 506, 123 speechBubble1.rawSetExtent new Point 66, 42 container.add speechBubble1 speechBubble1.rememberFractionalSituationInHoldingPanel() speechBubble2 = new SpeechBubbleWdgt "offline" speechBubble2.fullRawMoveTo container.position().add new Point 590, 105 speechBubble2.rawSetExtent new Point 66, 42 container.add speechBubble2 speechBubble2.rememberFractionalSituationInHoldingPanel() dashboardTitle = new TextMorph2 "Example dashboard with interactive 3D plot" dashboardTitle.alignCenter() dashboardTitle.alignMiddle() dashboardTitle.fullRawMoveTo container.position().add new Point 161, 6 dashboardTitle.rawSetExtent new Point 403, 50 container.add dashboardTitle dashboardTitle.rememberFractionalSituationInHoldingPanel() slider1 = new SliderMorph nil, nil, nil, nil, nil, true slider1.fullRawMoveTo container.position().add new Point 491, 484 slider1.rawSetExtent new Point 201, 24 container.add slider1 slider1.rememberFractionalSituationInHoldingPanel() slider1.setTargetAndActionWithOnesPickedFromMenu nil, nil, plot3D.contents, "setParameter" wm = new WindowWdgt nil, nil, slideWdgt wm.fullRawMoveTo new Point 114, 10 wm.rawSetExtent new Point 596, 592 world.add wm wm.setTitleWithoutPrependedContentName "Sample dashboard" slideWdgt.disableDragsDropsAndEditing() # if we don't do this, the window would ask to save content # when closed. Just close it instead. # TODO: should be done using a flag, we don't like # to inject code like this: the source is not tracked slideWdgt.closeFromContainerWindow = (containerWindow) -> containerWindow.close() world.sampleDashboardWindow = wm createDegreesConverterWindowOrBringItUpIfAlreadyCreated: -> if world.degreesConverterWindow? if !world.degreesConverterWindow.destroyed and world.degreesConverterWindow.parent? world.add world.degreesConverterWindow world.degreesConverterWindow.bringToForeground() world.degreesConverterWindow.fullRawMoveTo world.hand.position().add new Point 100, -50 world.degreesConverterWindow.fullRawMoveWithin world world.degreesConverterWindow.rememberFractionalSituationInHoldingPanel() return xCorrection = 32 yCorrection = 50 patchProgrammingWdgt = new PatchProgrammingWdgt container = patchProgrammingWdgt.stretchableWidgetContainer.contents container.rawSetExtent new Point 584,552 slider1 = new SliderMorph nil, nil, nil, nil, nil, true slider1.fullRawMoveTo container.position().add new Point 43+xCorrection, 195+yCorrection slider1.rawSetExtent new Point 20, 100 container.add slider1 slider1.rememberFractionalSituationInHoldingPanel() slider2 = new SliderMorph nil, nil, nil, nil, nil, true slider2.fullRawMoveTo container.position().add new Point 472+xCorrection, 203+yCorrection slider2.rawSetExtent new Point 20, 100 container.add slider2 slider2.rememberFractionalSituationInHoldingPanel() cText = new TextMorph2 "0" cText.fullRawMoveTo container.position().add new Point 104, 253 cText.rawSetExtent new Point 150, 75 container.add cText cText.rememberFractionalSituationInHoldingPanel() fText = new TextMorph2 "0" fText.fullRawMoveTo container.position().add new Point 344, 255 fText.alignRight() fText.rawSetExtent new Point 150, 75 container.add fText fText.rememberFractionalSituationInHoldingPanel() calc1 = new WindowWdgt nil, nil, new CalculatingPatchNodeWdgt("# °C → °F formula\n(in1)->Math.round in1*9/5+32"), true calc1.fullRawMoveTo container.position().add new Point 148+xCorrection/2, 19 calc1.rawSetExtent new Point 241, 167 container.add calc1 calc1.rememberFractionalSituationInHoldingPanel() calc2 = new WindowWdgt nil, nil, new CalculatingPatchNodeWdgt("# °F → °C formula\n(in1)->Math.round (in1-32)*5/9"), true calc2.fullRawMoveTo container.position().add new Point 148+xCorrection/2, 365 calc2.rawSetExtent new Point 241, 167 container.add calc2 calc2.rememberFractionalSituationInHoldingPanel() slider1.setTargetAndActionWithOnesPickedFromMenu nil, nil, cText, "setText" cText.setTargetAndActionWithOnesPickedFromMenu nil, nil, calc1.contents, "setInput1" calc1.contents.setTargetAndActionWithOnesPickedFromMenu nil, nil, fText, "setText" fText.setTargetAndActionWithOnesPickedFromMenu nil, nil, slider2, "setValue" slider2.setTargetAndActionWithOnesPickedFromMenu nil, nil, calc2.contents, "setInput1" calc2.contents.setTargetAndActionWithOnesPickedFromMenu nil, nil, slider1, "setValue" cLabel = new TextMorph2 "°C" cLabel.fullRawMoveTo container.position().add new Point 0+xCorrection, 102+yCorrection cLabel.rawSetExtent new Point 90, 90 container.add cLabel cLabel.rememberFractionalSituationInHoldingPanel() fLabel = new TextMorph2 "°F" fLabel.fullRawMoveTo container.position().add new Point 422+xCorrection, 102+yCorrection fLabel.rawSetExtent new Point 90, 90 container.add fLabel fLabel.rememberFractionalSituationInHoldingPanel() #@inform (@position().subtract @parent.position()) + " " + @extent() wm = new WindowWdgt nil, nil, patchProgrammingWdgt wm.fullRawMoveTo new Point 114, 10 wm.rawSetExtent new Point 596, 592 world.add wm wm.setTitleWithoutPrependedContentName "°C ↔ °F converter" patchProgrammingWdgt.disableDragsDropsAndEditing() cText.isEditable = true fText.isEditable = true # if we don't do this, the window would ask to save content # when closed. Just close it instead. # TODO: should be done using a flag, we don't like # to inject code like this: the source is not tracked patchProgrammingWdgt.closeFromContainerWindow = (containerWindow) -> containerWindow.close() world.degreesConverterWindow = wm # ------------------------------------------------------------------------ launchHowToSaveMessage: -> @createHowToSaveMessageWindowOrBringItUpIfAlreadyCreated() createHowToSaveMessageOpener: -> toolbarsOpenerLauncher = new IconicDesktopSystemWindowedAppLauncherWdgt "How to save?", new FloppyDiskIconWdgt, @, "launchHowToSaveMessage" # this "add" is going to try to position the reference # in some smart way (i.e. according to a grid) world.add toolbarsOpenerLauncher toolbarsOpenerLauncher.setExtent new Point 75, 75 toolbarsOpenerLauncher.fullChanged() # ------------------------------------------------------------------------ createHowToSaveMessageWindowOrBringItUpIfAlreadyCreated: -> if world.howToSaveDocWindow? if !world.howToSaveDocWindow.destroyed and world.howToSaveDocWindow.parent? world.add world.howToSaveDocWindow world.howToSaveDocWindow.bringToForeground() world.howToSaveDocWindow.fullRawMoveTo world.hand.position().add new Point 100, -50 world.howToSaveDocWindow.fullRawMoveWithin world world.howToSaveDocWindow.rememberFractionalSituationInHoldingPanel() return world.howToSaveDocWindow = HowToSaveMessageInfoWdg.create()
true
# All "actions" functions for all accessory menu items should belong # in here. Also helps so we don't pollute moprhs with a varying number # of helper functions, which is problematic for visual diffing # on inspectors (the number of methods keeps changing). class MenusHelper @augmentWith DeepCopierMixin popUpDevToolsMenu: (morphOpeningThePopUp, widgetThisMenuIsAbout) -> menu = new MenuMorph morphOpeningThePopUp, false, @, true, true, "Dev Tools" menu.addMenuItem "inspect", true, widgetThisMenuIsAbout, "inspect2", "open a window\non all properties" menu.addMenuItem "console", true, widgetThisMenuIsAbout, "createConsole", "console" menu.popUpAtHand() # »>> this part is excluded from the fizzygum homepage build createFridgeMagnets: -> fmm = new FridgeMagnetsMorph wm = new WindowWdgt nil, nil, fmm wm.setExtent new Point 570, 400 wm.fullRawMoveTo world.hand.position() wm.fullRawMoveWithin world world.add wm createReconfigurablePaint: -> reconfPaint = new ReconfigurablePaintWdgt wm = new WindowWdgt nil, nil, reconfPaint wm.setExtent new Point 460, 400 wm.fullRawMoveTo world.hand.position() wm.fullRawMoveWithin world world.add wm createSimpleSlideWdgt: -> simpleSlide = new SimpleSlideWdgt wm = new WindowWdgt nil, nil, simpleSlide wm.setExtent new Point 460, 400 wm.fullRawMoveTo world.hand.position() wm.fullRawMoveWithin world world.add wm createSimpleButton: -> world.create new SimpleRectangularButtonMorph true, @, nil, new IconMorph(nil) createSwitchButtonMorph: -> button1 = new SimpleRectangularButtonMorph true, @, nil, new IconMorph(nil) button2 = new SimpleRectangularButtonMorph true, @, nil, new StringMorph2 "Hello World! ⎲ƒ⎳⎷ ⎸⎹ " world.create new SwitchButtonMorph [button1, button2] createNewClippingBoxMorph: -> world.create new ClippingBoxMorph makeSlidersButtonsStatesBright: -> world.forAllChildrenBottomToTop (child) -> if child instanceof SliderButtonMorph child.pressColor = Color.LIME child.highlightColor = Color.BLUE child.normalColor = Color.BLACK # Icons -------------------------------------------------------------- makeIconWithText: -> world.create new WidgetHolderWithCaptionWdgt "hey there", new BrushIconMorph makeEmptyIconWithText: -> world.create new WidgetHolderWithCaptionWdgt "hey there" makeFolderWindow: (a,b,c,d,e) -> world.create new FolderWindowWdgt nil,nil,nil,nil, @ makeBouncingParticle: -> world.create new BouncerWdgt createDestroyIconMorph: -> world.create new DestroyIconMorph createUnderCarpetIconMorph: -> world.create new UnderCarpetIconMorph createUncollapsedStateIconMorph: -> world.create new UncollapsedStateIconMorph createCollapsedStateIconMorph: -> world.create new CollapsedStateIconMorph createCloseIconButtonMorph: -> world.create new CloseIconButtonMorph createScratchAreaIconMorph: -> world.create new ScratchAreaIconMorph createFloraIconMorph: -> world.create new FloraIconMorph createScooterIconMorph: -> world.create new ScooterIconMorph createHeartIconMorph: -> world.create new HeartIconMorph createPencil1IconMorph: -> world.create new PencilIconMorph createPencil2IconMorph: -> world.create new Pencil2IconMorph createBrushIconMorph: -> world.create new BrushIconMorph createToothpasteIconMorph: -> world.create new ToothpasteIconMorph createEraserIconMorph: -> world.create new EraserIconMorph createTrashcanIconWdgt: -> world.create new TrashcanIconWdgt createShortcutArrowIconWdgt: -> world.create new ShortcutArrowIconWdgt createRasterPicIconWdgt: -> world.create new RasterPicIconWdgt createPaintBucketIconWdgt: -> world.create new PaintBucketIconWdgt createObjectIconWdgt: -> world.create new ObjectIconWdgt createFolderIconWdgt: -> world.create new FolderIconWdgt createBasementIconWdgt: -> world.create new BasementIconWdgt createWidgetIconWdgt: -> world.create new WidgetIconWdgt makeGenericReferenceIcon: -> world.create new GenericShortcutIconWdgt makeGenericObjectIcon: -> world.create new GenericObjectIconWdgt # this part is excluded from the fizzygum homepage build <<« basementIconAndText: -> world.add new BasementOpenerWdgt # »>> this part is excluded from the fizzygum homepage build newScriptWindow: -> scriptWdgt = new ScriptWdgt wm = new WindowWdgt nil, nil, scriptWdgt wm.setExtent new Point 460, 400 wm.fullRawMoveTo world.hand.position().subtract new Point 50, 100 wm.fullRawMoveWithin world world.add wm # this part is excluded from the fizzygum homepage build <<« # ------------------------------------------------------------------------ launchFizzyPaint: -> wm = new WindowWdgt nil, nil, new ReconfigurablePaintWdgt wm.setExtent new Point 460, 400 wm.fullRawMoveTo new Point 174, 114 wm.fullRawMoveWithin world world.add wm ReconfigurablePaintInfoWdgt.createNextTo wm createFizzyPaintLauncher: -> fizzyPaintLauncher = new IconicDesktopSystemWindowedAppLauncherWdgt "Draw", new PaintBucketIconWdgt, @, "launchFizzyPaint" # this "add" is going to try to position the reference # in some smart way (i.e. according to a grid) world.add fizzyPaintLauncher fizzyPaintLauncher.setExtent new Point 75, 75 fizzyPaintLauncher.fullChanged() # ------------------------------------------------------------------------ launchSimpleDocument: -> wm = new WindowWdgt nil, nil, new SimpleDocumentWdgt wm.setExtent new Point 370, 395 wm.fullRawMoveTo new Point 170, 88 wm.fullRawMoveWithin world world.add wm SimpleDocumentInfoWdgt.createNextTo wm createSimpleDocumentLauncher: -> simpleDocumentLauncher = new IconicDesktopSystemWindowedAppLauncherWdgt "Docs Maker", new TypewriterIconWdgt, @, "launchSimpleDocument" # this "add" is going to try to position the reference # in some smart way (i.e. according to a grid) world.add simpleDocumentLauncher simpleDocumentLauncher.setExtent new Point 75, 75 simpleDocumentLauncher.fullChanged() # ------------------------------------------------------------------------ launchSimpleSlide: -> wm = new WindowWdgt nil, nil, new SimpleSlideWdgt wm.setExtent new Point 460, 400 wm.fullRawMoveTo new Point 168, 134 wm.fullRawMoveWithin world world.add wm SimpleSlideInfoWdgt.createNextTo wm createSimpleSlideLauncher: -> simpleSlideLauncher = new IconicDesktopSystemWindowedAppLauncherWdgt "Slides Maker", new SimpleSlideIconWdgt, @, "launchSimpleSlide" # this "add" is going to try to position the reference # in some smart way (i.e. according to a grid) world.add simpleSlideLauncher simpleSlideLauncher.setExtent new Point 75, 75 simpleSlideLauncher.fullChanged() # ------------------------------------------------------------------------ launchDashboards: -> reconfPaint = new DashboardsWdgt wm = new WindowWdgt nil, nil, reconfPaint wm.setExtent new Point 460, 400 wm.fullRawMoveTo world.hand.position() wm.fullRawMoveWithin world world.add wm DashboardsInfoWdgt.createNextTo wm createDashboardsLauncher: -> simpleDashboardsLauncher = new IconicDesktopSystemWindowedAppLauncherWdgt "Dashboards", new DashboardsIconWdgt, @, "launchDashboards" # this "add" is going to try to position the reference # in some smart way (i.e. according to a grid) world.add simpleDashboardsLauncher simpleDashboardsLauncher.setExtent new Point 75, 75 simpleDashboardsLauncher.fullChanged() # ------------------------------------------------------------------------ launchPatchProgramming: -> patchProgramming = new PatchProgrammingWdgt wm = new WindowWdgt nil, nil, patchProgramming wm.setExtent new Point 460, 400 wm.fullRawMoveTo world.hand.position() wm.fullRawMoveWithin world world.add wm PatchProgrammingInfoWdgt.createNextTo wm createPatchProgrammingLauncher: -> patchProgrammingLauncher = new IconicDesktopSystemWindowedAppLauncherWdgt "Patch progr.", new PatchProgrammingIconWdgt, @, "launchPatchProgramming" # this "add" is going to try to position the reference # in some smart way (i.e. according to a grid) world.add patchProgrammingLauncher patchProgrammingLauncher.setExtent new Point 75, 75 patchProgrammingLauncher.fullChanged() # ------------------------------------------------------------------------ launchGenericPanel: -> genericPanel = new StretchableEditableWdgt wm = new WindowWdgt nil, nil, genericPanel wm.setExtent new Point 460, 400 wm.fullRawMoveTo world.hand.position() wm.fullRawMoveWithin world world.add wm GenericPanelInfoWdgt.createNextTo wm createGenericPanelLauncher: -> genericPanelLauncher = new IconicDesktopSystemWindowedAppLauncherWdgt "Generic panel", new GenericPanelIconWdgt, @, "launchGenericPanel" # this "add" is going to try to position the reference # in some smart way (i.e. according to a grid) world.add genericPanelLauncher genericPanelLauncher.setExtent new Point 75, 75 genericPanelLauncher.fullChanged() # ------------------------------------------------------------------------ launchToolbars: -> # tools ------------------------------- toolsPanel = new ScrollPanelWdgt new ToolPanelWdgt toolsPanel.addMany [ new TextToolbarCreatorButtonWdgt new UsefulTextSnippetsToolbarCreatorButtonWdgt new SlidesToolbarCreatorButtonWdgt new PlotsToolbarCreatorButtonWdgt new PatchProgrammingComponentsToolbarCreatorButtonWdgt new WindowsToolbarCreatorButtonWdgt ] toolsPanel.disableDragsDropsAndEditing() wm = new WindowWdgt nil, nil, toolsPanel wm.setExtent new Point 60, 261 wm.fullRawMoveTo new Point 170, 170 wm.fullRawMoveWithin world world.add wm ToolbarsInfoWdgt.createNextTo wm createToolbarsOpener: -> toolbarsOpenerLauncher = new IconicDesktopSystemWindowedAppLauncherWdgt "Super Toolbar", new ToolbarsIconWdgt, @, "launchToolbars" toolbarsOpenerLauncher.toolTipMessage = "a toolbar to rule them all" # this "add" is going to try to position the reference # in some smart way (i.e. according to a grid) world.add toolbarsOpenerLauncher toolbarsOpenerLauncher.setExtent new Point 75, 75 toolbarsOpenerLauncher.fullChanged() # ------------------------------------------------------------------------ createNewTemplatesWindow: -> sdspw = new SimpleDocumentScrollPanelWdgt sdspw.rawSetExtent new Point 365, 335 startingContent = new SimplePlainTextWdgt( "Simply drag the items below into your document",nil,nil,nil,nil,nil,WorldMorph.preferencesAndSettings.editableItemBackgroundColor, 1) startingContent.alignCenter() startingContent.setFontSize 18 startingContent.isEditable = true startingContent.enableSelecting() sdspw.setContents startingContent, 5 startingContent = new ArrowSIconWdgt startingContent.rawSetExtent new Point 25, 25 sdspw.add startingContent startingContent.layoutSpecDetails.setAlignmentToCenter() sdspw.addDivider() startingContent = new SimplePlainTextWdgt( "Title",nil,nil,nil,nil,nil,WorldMorph.preferencesAndSettings.editableItemBackgroundColor, 1) startingContent.alignCenter() startingContent.setFontName nil, nil, startingContent.georgiaFontStack startingContent.setFontSize 48 startingContent.isEditable = true startingContent.enableSelecting() sdspw.add startingContent startingContent = new SimplePlainTextWdgt( "Section X",nil,nil,nil,nil,nil,WorldMorph.preferencesAndSettings.editableItemBackgroundColor, 1) startingContent.toggleWeight() startingContent.isEditable = true startingContent.enableSelecting() startingContent.setFontSize 28 sdspw.add startingContent startingContent = new SimplePlainTextWdgt( "Section X.X",nil,nil,nil,nil,nil,WorldMorph.preferencesAndSettings.editableItemBackgroundColor, 1) startingContent.isEditable = true startingContent.enableSelecting() startingContent.setFontSize 24 sdspw.add startingContent sdspw.addNormalParagraph "Normal text." startingContent = new SimplePlainTextWdgt( "“Be careful--with quotations, you can damn anything.”\n― PI:NAME:<NAME>END_PI",nil,nil,nil,nil,nil,WorldMorph.preferencesAndSettings.editableItemBackgroundColor, 1) startingContent.toggleItalic() startingContent.alignRight() startingContent.isEditable = true startingContent.enableSelecting() sdspw.add startingContent sdspw.addIndentedText "indentedText" sdspw.addBulletPoint "bullet point" sdspw.addCodeBlock "a code block with\n some example\n code in here" startingContent = new SimplePlainTextWdgt( "Spacers:",nil,nil,nil,nil,nil,WorldMorph.preferencesAndSettings.editableItemBackgroundColor, 1) startingContent.toggleWeight() startingContent.isEditable = true startingContent.enableSelecting() sdspw.add startingContent sdspw.addSpacer() sdspw.addSpacer 2 sdspw.addSpacer 3 startingContent = new SimplePlainTextWdgt( "Divider line:",nil,nil,nil,nil,nil,WorldMorph.preferencesAndSettings.editableItemBackgroundColor, 1) startingContent.toggleWeight() startingContent.isEditable = true startingContent.enableSelecting() sdspw.add startingContent sdspw.addDivider() startingContent = new SimplePlainTextWdgt( "Links:",nil,nil,nil,nil,nil,WorldMorph.preferencesAndSettings.editableItemBackgroundColor, 1) startingContent.toggleWeight() startingContent.isEditable = true startingContent.enableSelecting() sdspw.add startingContent startingContent = new SimpleLinkWdgt startingContent.rawSetExtent new Point 405, 50 sdspw.add startingContent startingContent.layoutSpecDetails.setAlignmentToRight() startingContent = new SimpleVideoLinkWdgt startingContent.rawSetExtent new Point 405, 50 sdspw.add startingContent startingContent.layoutSpecDetails.setAlignmentToRight() startingContent = new SimplePlainTextWdgt( "Useful characters:",nil,nil,nil,nil,nil,WorldMorph.preferencesAndSettings.editableItemBackgroundColor, 1) startingContent.toggleWeight() startingContent.isEditable = true startingContent.enableSelecting() sdspw.add startingContent # in March 2018, greek chars take a long time to paint on OSX/Chrome so # not adding those to the paragraph, however here they are: # αβγδεζηθικλμνξοπρστυφχψω ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ specialCharsParagraph = sdspw.addNormalParagraph "… †‡§ ↵⏎⇧␣ ☐☑☒✓X✗ •‣⁃◦ °±⁻¹²³µ×÷ℓΩ√∛∜∝∞∟∠∡∩∪∿≈⊂⋅⌀▫◽◻□⩽⩾ ¼½¾⅛⅜⅝⅞ ←↑→↓↔↕↵⇎⇏⇑⇒⇓⇔⇕ ©®™ $£€¥" specialCharsParagraph.setFontSize 16 sdspw.makeAllContentIntoTemplates() wm = new WindowWdgt nil, nil, sdspw wm.setExtent new Point 370, 335 wm.setTitleWithoutPrependedContentName "useful snippets" return wm # »>> this part is excluded from the fizzygum homepage build createFanout: -> fanoutWdgt = new FanoutWdgt world.create fanoutWdgt fanoutWdgt.setExtent new Point 100, 100 createCalculatingPatchNode: -> calculatingPatchNodeWdgt = new CalculatingPatchNodeWdgt wm = new WindowWdgt nil, nil, calculatingPatchNodeWdgt, true wm.setExtent new Point 460, 400 wm.fullRawMoveTo world.hand.position().subtract new Point 50, 100 wm.fullRawMoveWithin world world.add wm createDiffingPatchNode: -> diffingPatchNodeWdgt = new DiffingPatchNodeWdgt wm = new WindowWdgt nil, nil, diffingPatchNodeWdgt, true wm.setExtent new Point 460, 400 wm.fullRawMoveTo world.hand.position().subtract new Point 50, 100 wm.fullRawMoveWithin world world.add wm createSliderWithSmallestValueAtBottomEnd: -> world.create new SliderMorph nil, nil, nil, nil, nil, true createRegexSubstitutionPatchNodeWdgt: -> regexSubstitutionPatchNodeWdgt = new RegexSubstitutionPatchNodeWdgt wm = new WindowWdgt nil, nil, regexSubstitutionPatchNodeWdgt, true wm.setExtent new Point 460, 400 wm.fullRawMoveTo world.hand.position().subtract new Point 50, 100 wm.fullRawMoveWithin world world.add wm throwAnError: -> throw new Error "you manually threw an error!" createStretchablePanel: -> stretchablePanel = new StretchableWidgetContainerWdgt world.create stretchablePanel stretchablePanel.setExtent new Point 400, 300 createToolsPanel: -> toolPanel = new ScrollPanelWdgt new ToolPanelWdgt wm = new WindowWdgt nil, nil, toolPanel, true wm.setExtent new Point 200, 400 wm.fullRawMoveTo world.hand.position().subtract new Point 50, 100 wm.fullRawMoveWithin world world.add wm createHorizontalMenuPanelPanel: -> horizontalMenuPanel = new HorizontalMenuPanelWdgt wm = new WindowWdgt nil, nil, horizontalMenuPanel, true wm.setExtent new Point 200, 400 wm.fullRawMoveTo world.hand.position().subtract new Point 50, 100 wm.fullRawMoveWithin world world.add wm popUpMore1IconsMenu: (morphOpeningThePopUp) -> menu = new MenuMorph morphOpeningThePopUp, false, @, true, true, "More Icons 1" menu.addMenuItem "Pencil 1 icon", true, menusHelper, "createPencil1IconMorph" menu.addMenuItem "Pencil 2 icon", true, menusHelper, "createPencil2IconMorph" menu.addMenuItem "Brush icon", true, menusHelper, "createBrushIconMorph" menu.addMenuItem "Toothpaste icon", true, menusHelper, "createToothpasteIconMorph" menu.addMenuItem "Eraser icon", true, menusHelper, "createEraserIconMorph" menu.addMenuItem "Trashcan icon", true, menusHelper, "createTrashcanIconWdgt" menu.addMenuItem "Shortcut arrow icon", true, menusHelper, "createShortcutArrowIconWdgt" menu.addMenuItem "Raster pic icon", true, menusHelper, "createRasterPicIconWdgt" menu.addMenuItem "Paint bucket icon", true, menusHelper, "createPaintBucketIconWdgt" menu.addMenuItem "Object icon", true, menusHelper, "createObjectIconWdgt" menu.addMenuItem "Folder icon", true, menusHelper, "createFolderIconWdgt" menu.addMenuItem "Basement icon", true, menusHelper, "createBasementIconWdgt" menu.addMenuItem "Widget icon", true, menusHelper, "createWidgetIconWdgt" menu.popUpAtHand() popUpMore2IconsMenu: (morphOpeningThePopUp) -> menu = new MenuMorph morphOpeningThePopUp, false, @, true, true, "More Icons 2" menu.addMenuItem "Format as code icon", true, menusHelper, "createFormatAsCodeIconWdgt" menu.addMenuItem "Ch. X icon", true, menusHelper, "createChXIconWdgt" menu.addMenuItem "Ch. X.X icon", true, menusHelper, "createChXXIconWdgt" menu.addMenuItem "Ch. X.X.X icon", true, menusHelper, "createChXXXIconWdgt" menu.addMenuItem "Align right icon", true, menusHelper, "createAlignRightIconWdgt" menu.addMenuItem "Align center icon", true, menusHelper, "createAlignCenterIconWdgt" menu.addMenuItem "Align left icon", true, menusHelper, "createAlignLeftIconWdgt" menu.addMenuItem "Bold icon", true, menusHelper, "createBoldIconWdgt" menu.addMenuItem "Italic icon", true, menusHelper, "createItalicIconWdgt" menu.addMenuItem "Information icon", true, menusHelper, "createInformationIconWdgt" menu.addMenuItem "Textbox icon", true, menusHelper, "createTextboxIconWdgt" menu.addMenuItem "Video play icon", true, menusHelper, "createVideoPlayIconWdgt" menu.addMenuItem "Decrease font size icon", true, menusHelper, "createDecreaseFontSizeIconWdgt" menu.addMenuItem "Increase font size icon", true, menusHelper, "createIncreaseFontSizeIconWdgt" menu.addMenuItem "External link icon", true, menusHelper, "createExternalLinkIconWdgt" menu.addMenuItem "Templates icon", true, menusHelper, "createTemplatesIconWdgt" menu.popUpAtHand() popUpMore3IconsMenu: (morphOpeningThePopUp) -> menu = new MenuMorph morphOpeningThePopUp, false, @, true, true, "More Icons 2" menu.addMenuItem "Fizzygum logo", true, menusHelper, "createFizzygumLogoIconWdgt" menu.addMenuItem "Fizzygum logo with text", true, menusHelper, "createFizzygumLogoWithTextIconWdgt" menu.addMenuItem "Vaporwave sun", true, menusHelper, "createVaporwaveSunIconWdgt" menu.addMenuItem "Vaporwave background", true, menusHelper, "createVaporwaveBackgroundIconWdgt" menu.addMenuItem "Change font icon", true, menusHelper, "createChangeFontIconWdgt" menu.addMenuItem "C <-> F converter icon", true, menusHelper, "createCFDegreesConverterIconWdgt" menu.addMenuItem "Simple slide icon", true, menusHelper, "createSimpleSlideIconWdgt" menu.addMenuItem "Typewriter icon", true, menusHelper, "createTypewriterIconWdgt" menu.addMenuItem "Little world icon", true, menusHelper, "createLittleWorldIconWdgt" menu.addMenuItem "Little USA icon", true, menusHelper, "createLittleUSAIconWdgt" menu.addMenuItem "Map pin icon", true, menusHelper, "createMapPinIconWdgt" menu.addMenuItem "Save icon", true, menusHelper, "createSaveIconWdgt" menu.popUpAtHand() createFizzygumLogoWithTextIconWdgt : -> world.create new FizzygumLogoWithTextIconWdgt createVaporwaveBackgroundIconWdgt : -> world.create new VaporwaveBackgroundIconWdgt createCFDegreesConverterIconWdgt : -> world.create new CFDegreesConverterIconWdgt createFizzygumLogoIconWdgt : -> world.create new FizzygumLogoIconWdgt createVaporwaveSunIconWdgt : -> world.create new VaporwaveSunIconWdgt createLittleWorldIconWdgt : -> world.create new LittleWorldIconWdgt createChangeFontIconWdgt : -> world.create new ChangeFontIconWdgt createSimpleSlideIconWdgt : -> world.create new SimpleSlideIconWdgt createTypewriterIconWdgt : -> world.create new TypewriterIconWdgt createLittleUSAIconWdgt : -> world.create new LittleUSAIconWdgt createMapPinIconWdgt : -> world.create new MapPinIconWdgt createSaveIconWdgt : -> world.create new SaveIconWdgt popUpArrowsIconsMenu: (morphOpeningThePopUp) -> menu = new MenuMorph morphOpeningThePopUp, false, @, true, true, "Arrows" menu.addMenuItem "Arrow N icon", true, menusHelper, "createArrowNIconWdgt" menu.addMenuItem "Arrow S icon", true, menusHelper, "createArrowSIconWdgt" menu.addMenuItem "Arrow W icon", true, menusHelper, "createArrowWIconWdgt" menu.addMenuItem "Arrow E icon", true, menusHelper, "createArrowEIconWdgt" menu.addMenuItem "Arrow NW icon", true, menusHelper, "createArrowNWIconWdgt" menu.addMenuItem "Arrow NE icon", true, menusHelper, "createArrowNEIconWdgt" menu.addMenuItem "Arrow SE icon", true, menusHelper, "createArrowSEIconWdgt" menu.addMenuItem "Arrow SW icon", true, menusHelper, "createArrowSWIconWdgt" menu.popUpAtHand() createArrowEIconWdgt: -> world.create new ArrowEIconWdgt createArrowNEIconWdgt: -> world.create new ArrowNEIconWdgt createArrowNIconWdgt: -> world.create new ArrowNIconWdgt createArrowNWIconWdgt: -> world.create new ArrowNWIconWdgt createArrowSEIconWdgt: -> world.create new ArrowSEIconWdgt createArrowSIconWdgt: -> world.create new ArrowSIconWdgt createArrowSWIconWdgt: -> world.create new ArrowSWIconWdgt createArrowWIconWdgt: -> world.create new ArrowWIconWdgt createDecreaseFontSizeIconWdgt: -> world.create new DecreaseFontSizeIconWdgt createExternalLinkIconWdgt: -> world.create new ExternalLinkIconWdgt createIncreaseFontSizeIconWdgt: -> world.create new IncreaseFontSizeIconWdgt createTemplatesIconWdgt: -> world.create new TemplatesIconWdgt createFormatAsCodeIconWdgt: -> world.create new FormatAsCodeIconWdgt createChXIconWdgt: -> world.create new ChapterXIconWdgt createChXXIconWdgt: -> world.create new ChapterXXIconWdgt createChXXXIconWdgt: -> world.create new ChapterXXXIconWdgt createAlignRightIconWdgt: -> world.create new AlignRightIconWdgt createAlignCenterIconWdgt: -> world.create new AlignCenterIconWdgt createAlignLeftIconWdgt: -> world.create new AlignLeftIconWdgt createWorldMapIconMorph: -> world.create new SimpleWorldMapIconWdgt createUSAMapIconMorph: -> world.create new SimpleUSAMapIconWdgt createBoldIconWdgt: -> world.create new BoldIconWdgt createItalicIconWdgt: -> world.create new ItalicIconWdgt createInformationIconWdgt: -> world.create new InformationIconWdgt createTextboxIconWdgt: -> world.create new TextIconWdgt createVideoPlayIconWdgt: -> world.create new VideoPlayIconWdgt createSimpleDocumentWdgt: -> simpleDocument = new SimpleDocumentWdgt wm = new WindowWdgt nil, nil, simpleDocument wm.setExtent new Point 368, 335 wm.fullRawMoveTo world.hand.position().subtract new Point 50, 100 wm.fullRawMoveWithin world world.add wm createSimpleLinkWdgt: -> simpleLinkWdgt = new SimpleLinkWdgt simpleLinkWdgt.setExtent new Point 405, 50 world.create simpleLinkWdgt createSimpleVideoLinkWdgt: -> simpleVideoLinkWdgt = new SimpleVideoLinkWdgt simpleVideoLinkWdgt.setExtent new Point 405, 50 world.create simpleVideoLinkWdgt create2DAxis: -> vertAxis = new AxisWdgt vertAxis.setExtent new Point 40, 300 world.create vertAxis createExampleScatterPlot: -> exampleScatterPlot = new ExampleScatterPlotWdgt exampleScatterPlot.setExtent new Point 300, 300 world.create exampleScatterPlot createExampleScatterPlotWithAxes: -> exampleScatterPlot = new ExampleScatterPlotWdgt plotWithAxesWdgt = new PlotWithAxesWdgt exampleScatterPlot plotWithAxesWdgt.rawSetExtent new Point 300, 300 world.create plotWithAxesWdgt createExampleFunctionPlot: -> exampleFunctionPlot = new ExampleFunctionPlotWdgt exampleFunctionPlot.setExtent new Point 300, 300 world.create exampleFunctionPlot createExampleBarPlot: -> exampleBarPlot = new ExampleBarPlotWdgt exampleBarPlot.setExtent new Point 300, 300 world.create exampleBarPlot createExample3DPlot: -> example3DPlot = new Example3DPlotWdgt example3DPlot.setExtent new Point 300, 300 world.create example3DPlot popUpMapsMenu: (morphOpeningThePopUp) -> menu = new MenuMorph morphOpeningThePopUp, false, @, true, true, "Maps" menu.addMenuItem "world map", true, menusHelper, "createWorldMapIconMorph", "others" menu.addMenuItem "USA map", true, menusHelper, "createUSAMapIconMorph", "others" menu.popUpAtHand() popUpGraphsMenu: (morphOpeningThePopUp) -> menu = new MenuMorph morphOpeningThePopUp, false, @, true, true, "graphs" menu.addMenuItem "axis", true, menusHelper, "create2DAxis" menu.addMenuItem "scatter plot", true, menusHelper, "createExampleScatterPlot" menu.addMenuItem "scatter plot with axes", true, menusHelper, "createExampleScatterPlotWithAxes" menu.addMenuItem "function plot", true, menusHelper, "createExampleFunctionPlot" menu.addMenuItem "bar plot", true, menusHelper, "createExampleBarPlot" menu.addMenuItem "3D plot", true, menusHelper, "createExample3DPlot" menu.popUpAtHand() popUpSupportDocsMenu: (morphOpeningThePopUp) -> menu = new MenuMorph morphOpeningThePopUp, false, @, true, true, "Support Docs" menu.addMenuItem "welcome message", true, @, "createWelcomeMessageWindowAndShortcut", "welcome message" menu.popUpAtHand() # this part is excluded from the fizzygum homepage build <<« createWelcomeMessageWindowAndShortcut: -> wm = WelcomeMessageInfoWdgt.create() readmeLauncher = new IconicDesktopSystemDocumentShortcutWdgt wm, "Welcome", new WelcomeIconWdgt # this "add" is going to try to position the reference # in some smart way (i.e. according to a grid) world.add readmeLauncher readmeLauncher.setExtent new Point 75, 75 readmeLauncher.fullChanged() # ------------------------------------------------------------------------ launchDegreesConverter: -> @createDegreesConverterWindowOrBringItUpIfAlreadyCreated() createDegreesConverterOpener: (inWhichFolder) -> degreesConverterOpenerLauncher = new IconicDesktopSystemWindowedAppLauncherWdgt "°C ↔ °F", new DegreesConverterIconWdgt, @, "launchDegreesConverter" # this "add" is going to try to position the reference # in some smart way (i.e. according to a grid) degreesConverterOpenerLauncher.setExtent new Point 75, 75 if inWhichFolder? inWhichFolder.contents.contents.add degreesConverterOpenerLauncher else world.add degreesConverterOpenerLauncher # ------------------------------------------------------------------------ launchSampleDashboard: -> @createSampleDashboardWindowOrBringItUpIfAlreadyCreated() createSampleDashboardOpener: (inWhichFolder) -> degreesConverterOpenerLauncher = new IconicDesktopSystemWindowedAppLauncherWdgt "sample dashb", (new GenericShortcutIconWdgt new DashboardsIconWdgt), @, "launchSampleDashboard" # this "add" is going to try to position the reference # in some smart way (i.e. according to a grid) degreesConverterOpenerLauncher.setExtent new Point 75, 75 if inWhichFolder? inWhichFolder.contents.contents.add degreesConverterOpenerLauncher else world.add degreesConverterOpenerLauncher # ------------------------------------------------------------------------ launchSampleSlide: -> @createSampleSlideWindowOrBringItUpIfAlreadyCreated() createSampleSlideOpener: (inWhichFolder) -> degreesConverterOpenerLauncher = new IconicDesktopSystemWindowedAppLauncherWdgt "sample slide", (new GenericShortcutIconWdgt new SimpleSlideIconWdgt), @, "launchSampleSlide" # this "add" is going to try to position the reference # in some smart way (i.e. according to a grid) degreesConverterOpenerLauncher.setExtent new Point 75, 75 if inWhichFolder? inWhichFolder.contents.contents.add degreesConverterOpenerLauncher else world.add degreesConverterOpenerLauncher # ------------------------------------------------------------------------ launchSampleDoc: -> @createSampleDocWindowOrBringItUpIfAlreadyCreated() createSampleDocOpener: (inWhichFolder) -> degreesConverterOpenerLauncher = new IconicDesktopSystemWindowedAppLauncherWdgt "sample doc", (new GenericShortcutIconWdgt new TypewriterIconWdgt), @, "launchSampleDoc" # this "add" is going to try to position the reference # in some smart way (i.e. according to a grid) degreesConverterOpenerLauncher.setExtent new Point 75, 75 if inWhichFolder? inWhichFolder.contents.contents.add degreesConverterOpenerLauncher else world.add degreesConverterOpenerLauncher # ------------------------------------------------------------------------ createSampleSlideWindowOrBringItUpIfAlreadyCreated: -> if world.sampleSlideWindow? if !world.sampleSlideWindow.destroyed and world.sampleSlideWindow.parent? world.add world.sampleSlideWindow world.sampleSlideWindow.bringToForeground() world.sampleSlideWindow.fullRawMoveTo world.hand.position().add new Point 100, -50 world.sampleSlideWindow.fullRawMoveWithin world world.sampleSlideWindow.rememberFractionalSituationInHoldingPanel() return slideWdgt = new SimpleSlideWdgt container = slideWdgt.stretchableWidgetContainer.contents container.rawSetExtent new Point 575,454 windowWithScrollingPanel = new WindowWdgt nil, nil, new ScrollPanelWdgt, true, true windowWithScrollingPanel.setTitleWithoutPrependedContentName "New York City" windowWithScrollingPanel.fullRawMoveTo container.position().add new Point 28, 43 windowWithScrollingPanel.rawSetExtent new Point 322, 268 container.add windowWithScrollingPanel windowWithScrollingPanel.rememberFractionalSituationInHoldingPanel() usaMap = new SimpleUSAMapIconWdgt Color.create 183, 183, 183 usaMap.rawSetExtent new Point 1808, 1115 windowWithScrollingPanel.contents.add usaMap windowWithScrollingPanel.contents.scrollTo new Point 1484, 246 usaMap.rememberFractionalSituationInHoldingPanel() mapPin = new MapPinIconWdgt windowWithScrollingPanel.contents.add mapPin mapPin.fullRawMoveTo windowWithScrollingPanel.contents.contents.position().add new Point 1606, 343 mapPin.rememberFractionalSituationInHoldingPanel() sampleBarPlot = new WindowWdgt nil, nil, new PlotWithAxesWdgt(new ExampleBarPlotWdgt), true, true sampleBarPlot.rawSetExtent new Point 240, 104 windowWithScrollingPanel.contents.add sampleBarPlot sampleBarPlot.fullRawMoveTo windowWithScrollingPanel.contents.contents.position().add new Point 1566, 420 sampleBarPlot.setTitleWithoutPrependedContentName "NYC: traffic" windowWithScrollingPanel.contents.disableDragsDropsAndEditing() mapCaption = new TextMorph2 "The City of New York, often called New York City or simply New York, is the most populous city in the United States. With an estimated 2017 population of 8,622,698 distributed over a land area of about 302.6 square miles (784 km2), New York City is also the most densely populated major city in the United States." mapCaption.fittingSpecWhenBoundsTooLarge = FittingSpecTextInLargerBounds.SCALEUP mapCaption.fittingSpecWhenBoundsTooSmall = FittingSpecTextInSmallerBounds.SCALEDOWN mapCaption.fullRawMoveTo container.position().add new Point 366, 40 mapCaption.rawSetExtent new Point 176, 387 container.add mapCaption mapCaption.rememberFractionalSituationInHoldingPanel() wikiLink = new SimpleLinkWdgt "New York City Wikipedia page", "https://en.wikipedia.org/wiki/New_York_City" wikiLink.fullRawMoveTo container.position().add new Point 110, 348 wikiLink.rawSetExtent new Point 250, 50 container.add wikiLink wikiLink.rememberFractionalSituationInHoldingPanel() wm = new WindowWdgt nil, nil, slideWdgt wm.fullRawMoveTo new Point 114, 10 wm.rawSetExtent new Point 596, 592 world.add wm wm.setTitleWithoutPrependedContentName "Sample slide" slideWdgt.disableDragsDropsAndEditing() # if we don't do this, the window would ask to save content # when closed. Just close it instead. # TODO: should be done using a flag, we don't like # to inject code like this: the source is not tracked slideWdgt.closeFromContainerWindow = (containerWindow) -> containerWindow.close() world.sampleSlideWindow = wm createSampleDocWindowOrBringItUpIfAlreadyCreated: -> if world.sampleDocWindow? if !world.sampleDocWindow.destroyed and world.sampleDocWindow.parent? world.add world.sampleDocWindow world.sampleDocWindow.bringToForeground() world.sampleDocWindow.fullRawMoveTo world.hand.position().add new Point 100, -50 world.sampleDocWindow.fullRawMoveWithin world world.sampleDocWindow.rememberFractionalSituationInHoldingPanel() return world.sampleDocWindow = SimpleDocumentSampleWdgt.create() createSampleDashboardWindowOrBringItUpIfAlreadyCreated: -> if world.sampleDashboardWindow? if !world.sampleDashboardWindow.destroyed and world.sampleDashboardWindow.parent? world.add world.sampleDashboardWindow world.sampleDashboardWindow.bringToForeground() world.sampleDashboardWindow.fullRawMoveTo world.hand.position().add new Point 100, -50 world.sampleDashboardWindow.fullRawMoveWithin world world.sampleDashboardWindow.rememberFractionalSituationInHoldingPanel() return slideWdgt = new DashboardsWdgt container = slideWdgt.stretchableWidgetContainer.contents container.rawSetExtent new Point 725,556 scatterPlot = new WindowWdgt nil, nil, new PlotWithAxesWdgt(new ExampleScatterPlotWdgt), true, true scatterPlot.fullRawMoveTo container.position().add new Point 19, 86 scatterPlot.rawSetExtent new Point 200, 200 container.add scatterPlot scatterPlot.rememberFractionalSituationInHoldingPanel() functionPlot = new WindowWdgt nil, nil, new PlotWithAxesWdgt(new ExampleFunctionPlotWdgt), true, true functionPlot.fullRawMoveTo container.position().add new Point 251, 86 functionPlot.rawSetExtent new Point 200, 200 container.add functionPlot functionPlot.rememberFractionalSituationInHoldingPanel() barPlot = new WindowWdgt nil, nil, new PlotWithAxesWdgt(new ExampleBarPlotWdgt), true, true barPlot.fullRawMoveTo container.position().add new Point 19, 327 barPlot.rawSetExtent new Point 200, 200 container.add barPlot barPlot.rememberFractionalSituationInHoldingPanel() plot3D = new WindowWdgt nil, nil, new Example3DPlotWdgt, true, true plot3D.fullRawMoveTo container.position().add new Point 491, 327 plot3D.rawSetExtent new Point 200, 150 container.add plot3D plot3D.rememberFractionalSituationInHoldingPanel() usaMap = new SimpleUSAMapIconWdgt Color.create 183, 183, 183 usaMap.fullRawMoveTo container.position().add new Point 242, 355 usaMap.rawSetExtent new Point 230, 145 container.add usaMap usaMap.rememberFractionalSituationInHoldingPanel() mapPin1 = new MapPinIconWdgt mapPin1.fullRawMoveTo container.position().add new Point 226, 376 container.add mapPin1 mapPin1.rememberFractionalSituationInHoldingPanel() mapPin2 = new MapPinIconWdgt mapPin2.fullRawMoveTo container.position().add new Point 289, 363 container.add mapPin2 mapPin2.rememberFractionalSituationInHoldingPanel() mapPin3 = new MapPinIconWdgt mapPin3.fullRawMoveTo container.position().add new Point 323, 397 container.add mapPin3 mapPin3.rememberFractionalSituationInHoldingPanel() mapPin4 = new MapPinIconWdgt mapPin4.fullRawMoveTo container.position().add new Point 360, 421 container.add mapPin4 mapPin4.rememberFractionalSituationInHoldingPanel() mapPin5 = new MapPinIconWdgt mapPin5.fullRawMoveTo container.position().add new Point 417, 374 container.add mapPin5 mapPin5.rememberFractionalSituationInHoldingPanel() worldMap = new SimpleWorldMapIconWdgt Color.create 183, 183, 183 worldMap.fullRawMoveTo container.position().add new Point 464, 128 worldMap.rawSetExtent new Point 240, 125 container.add worldMap worldMap.rememberFractionalSituationInHoldingPanel() speechBubble1 = new SpeechBubbleWdgt "online" speechBubble1.fullRawMoveTo container.position().add new Point 506, 123 speechBubble1.rawSetExtent new Point 66, 42 container.add speechBubble1 speechBubble1.rememberFractionalSituationInHoldingPanel() speechBubble2 = new SpeechBubbleWdgt "offline" speechBubble2.fullRawMoveTo container.position().add new Point 590, 105 speechBubble2.rawSetExtent new Point 66, 42 container.add speechBubble2 speechBubble2.rememberFractionalSituationInHoldingPanel() dashboardTitle = new TextMorph2 "Example dashboard with interactive 3D plot" dashboardTitle.alignCenter() dashboardTitle.alignMiddle() dashboardTitle.fullRawMoveTo container.position().add new Point 161, 6 dashboardTitle.rawSetExtent new Point 403, 50 container.add dashboardTitle dashboardTitle.rememberFractionalSituationInHoldingPanel() slider1 = new SliderMorph nil, nil, nil, nil, nil, true slider1.fullRawMoveTo container.position().add new Point 491, 484 slider1.rawSetExtent new Point 201, 24 container.add slider1 slider1.rememberFractionalSituationInHoldingPanel() slider1.setTargetAndActionWithOnesPickedFromMenu nil, nil, plot3D.contents, "setParameter" wm = new WindowWdgt nil, nil, slideWdgt wm.fullRawMoveTo new Point 114, 10 wm.rawSetExtent new Point 596, 592 world.add wm wm.setTitleWithoutPrependedContentName "Sample dashboard" slideWdgt.disableDragsDropsAndEditing() # if we don't do this, the window would ask to save content # when closed. Just close it instead. # TODO: should be done using a flag, we don't like # to inject code like this: the source is not tracked slideWdgt.closeFromContainerWindow = (containerWindow) -> containerWindow.close() world.sampleDashboardWindow = wm createDegreesConverterWindowOrBringItUpIfAlreadyCreated: -> if world.degreesConverterWindow? if !world.degreesConverterWindow.destroyed and world.degreesConverterWindow.parent? world.add world.degreesConverterWindow world.degreesConverterWindow.bringToForeground() world.degreesConverterWindow.fullRawMoveTo world.hand.position().add new Point 100, -50 world.degreesConverterWindow.fullRawMoveWithin world world.degreesConverterWindow.rememberFractionalSituationInHoldingPanel() return xCorrection = 32 yCorrection = 50 patchProgrammingWdgt = new PatchProgrammingWdgt container = patchProgrammingWdgt.stretchableWidgetContainer.contents container.rawSetExtent new Point 584,552 slider1 = new SliderMorph nil, nil, nil, nil, nil, true slider1.fullRawMoveTo container.position().add new Point 43+xCorrection, 195+yCorrection slider1.rawSetExtent new Point 20, 100 container.add slider1 slider1.rememberFractionalSituationInHoldingPanel() slider2 = new SliderMorph nil, nil, nil, nil, nil, true slider2.fullRawMoveTo container.position().add new Point 472+xCorrection, 203+yCorrection slider2.rawSetExtent new Point 20, 100 container.add slider2 slider2.rememberFractionalSituationInHoldingPanel() cText = new TextMorph2 "0" cText.fullRawMoveTo container.position().add new Point 104, 253 cText.rawSetExtent new Point 150, 75 container.add cText cText.rememberFractionalSituationInHoldingPanel() fText = new TextMorph2 "0" fText.fullRawMoveTo container.position().add new Point 344, 255 fText.alignRight() fText.rawSetExtent new Point 150, 75 container.add fText fText.rememberFractionalSituationInHoldingPanel() calc1 = new WindowWdgt nil, nil, new CalculatingPatchNodeWdgt("# °C → °F formula\n(in1)->Math.round in1*9/5+32"), true calc1.fullRawMoveTo container.position().add new Point 148+xCorrection/2, 19 calc1.rawSetExtent new Point 241, 167 container.add calc1 calc1.rememberFractionalSituationInHoldingPanel() calc2 = new WindowWdgt nil, nil, new CalculatingPatchNodeWdgt("# °F → °C formula\n(in1)->Math.round (in1-32)*5/9"), true calc2.fullRawMoveTo container.position().add new Point 148+xCorrection/2, 365 calc2.rawSetExtent new Point 241, 167 container.add calc2 calc2.rememberFractionalSituationInHoldingPanel() slider1.setTargetAndActionWithOnesPickedFromMenu nil, nil, cText, "setText" cText.setTargetAndActionWithOnesPickedFromMenu nil, nil, calc1.contents, "setInput1" calc1.contents.setTargetAndActionWithOnesPickedFromMenu nil, nil, fText, "setText" fText.setTargetAndActionWithOnesPickedFromMenu nil, nil, slider2, "setValue" slider2.setTargetAndActionWithOnesPickedFromMenu nil, nil, calc2.contents, "setInput1" calc2.contents.setTargetAndActionWithOnesPickedFromMenu nil, nil, slider1, "setValue" cLabel = new TextMorph2 "°C" cLabel.fullRawMoveTo container.position().add new Point 0+xCorrection, 102+yCorrection cLabel.rawSetExtent new Point 90, 90 container.add cLabel cLabel.rememberFractionalSituationInHoldingPanel() fLabel = new TextMorph2 "°F" fLabel.fullRawMoveTo container.position().add new Point 422+xCorrection, 102+yCorrection fLabel.rawSetExtent new Point 90, 90 container.add fLabel fLabel.rememberFractionalSituationInHoldingPanel() #@inform (@position().subtract @parent.position()) + " " + @extent() wm = new WindowWdgt nil, nil, patchProgrammingWdgt wm.fullRawMoveTo new Point 114, 10 wm.rawSetExtent new Point 596, 592 world.add wm wm.setTitleWithoutPrependedContentName "°C ↔ °F converter" patchProgrammingWdgt.disableDragsDropsAndEditing() cText.isEditable = true fText.isEditable = true # if we don't do this, the window would ask to save content # when closed. Just close it instead. # TODO: should be done using a flag, we don't like # to inject code like this: the source is not tracked patchProgrammingWdgt.closeFromContainerWindow = (containerWindow) -> containerWindow.close() world.degreesConverterWindow = wm # ------------------------------------------------------------------------ launchHowToSaveMessage: -> @createHowToSaveMessageWindowOrBringItUpIfAlreadyCreated() createHowToSaveMessageOpener: -> toolbarsOpenerLauncher = new IconicDesktopSystemWindowedAppLauncherWdgt "How to save?", new FloppyDiskIconWdgt, @, "launchHowToSaveMessage" # this "add" is going to try to position the reference # in some smart way (i.e. according to a grid) world.add toolbarsOpenerLauncher toolbarsOpenerLauncher.setExtent new Point 75, 75 toolbarsOpenerLauncher.fullChanged() # ------------------------------------------------------------------------ createHowToSaveMessageWindowOrBringItUpIfAlreadyCreated: -> if world.howToSaveDocWindow? if !world.howToSaveDocWindow.destroyed and world.howToSaveDocWindow.parent? world.add world.howToSaveDocWindow world.howToSaveDocWindow.bringToForeground() world.howToSaveDocWindow.fullRawMoveTo world.hand.position().add new Point 100, -50 world.howToSaveDocWindow.fullRawMoveWithin world world.howToSaveDocWindow.rememberFractionalSituationInHoldingPanel() return world.howToSaveDocWindow = HowToSaveMessageInfoWdg.create()
[ { "context": "module.exports = (robot) ->\n login = (username, password) ->\n return robot.cli( \"authenticate", "end": 47, "score": 0.5456065535545349, "start": 39, "tag": "USERNAME", "value": "username" }, { "context": "e #{apiUrl} \\\n -username #{userna...
example/src/login.coffee
victorock/hubot-coprhd
0
module.exports = (robot) -> login = (username, password) -> return robot.cli( "authenticate \ -hostname #{apiUrl} \ -username #{username} \ -d \"/tmp\" \ -p #{password}" ) robot.commands.push "hubot coprhd authenticate" robot.respond /(login|authenticate)$/i, (msg) -> msg.reply msg.random friendly "...action not implemented yet..." #msg.reply robot.coprhdcli("") robot.commands.push "hubot coprhd set token <token>" robot.respond /(set|use) token (.*)$/i, (msg) -> msg.reply msg.random friendly "...action not implemented yet..." #msg.reply robot.coprhdcli("") robot.commands.push "hubot coprhd login username <username> password <password>" robot.respond /(login|authenticate) username (.*) password (.*)$/i, (msg) -> msg.reply msg.random friendly "...action not implemented yet..." #msg.reply robot.coprhdcli("")
215609
module.exports = (robot) -> login = (username, password) -> return robot.cli( "authenticate \ -hostname #{apiUrl} \ -username #{username} \ -d \"/tmp\" \ -p #{password}" ) robot.commands.push "hubot coprhd authenticate" robot.respond /(login|authenticate)$/i, (msg) -> msg.reply msg.random friendly "...action not implemented yet..." #msg.reply robot.coprhdcli("") robot.commands.push "hubot coprhd set token <token>" robot.respond /(set|use) token (.*)$/i, (msg) -> msg.reply msg.random friendly "...action not implemented yet..." #msg.reply robot.coprhdcli("") robot.commands.push "hubot coprhd login username <username> password <<PASSWORD>>" robot.respond /(login|authenticate) username (.*) password (.*)$/i, (msg) -> msg.reply msg.random friendly "...action not implemented yet..." #msg.reply robot.coprhdcli("")
true
module.exports = (robot) -> login = (username, password) -> return robot.cli( "authenticate \ -hostname #{apiUrl} \ -username #{username} \ -d \"/tmp\" \ -p #{password}" ) robot.commands.push "hubot coprhd authenticate" robot.respond /(login|authenticate)$/i, (msg) -> msg.reply msg.random friendly "...action not implemented yet..." #msg.reply robot.coprhdcli("") robot.commands.push "hubot coprhd set token <token>" robot.respond /(set|use) token (.*)$/i, (msg) -> msg.reply msg.random friendly "...action not implemented yet..." #msg.reply robot.coprhdcli("") robot.commands.push "hubot coprhd login username <username> password <PI:PASSWORD:<PASSWORD>END_PI>" robot.respond /(login|authenticate) username (.*) password (.*)$/i, (msg) -> msg.reply msg.random friendly "...action not implemented yet..." #msg.reply robot.coprhdcli("")
[ { "context": "-- monmigrate ---\n\nReleased under MIT license.\n\nby Gustavo Vargas - @xgvargas - 2018\n\nOriginal coffee code and issu", "end": 71, "score": 0.9998822212219238, "start": 57, "tag": "NAME", "value": "Gustavo Vargas" }, { "context": "\n\nReleased under MIT license.\n\n...
src/monmigrate.coffee
xgvargas/monmigrate
0
###! --- monmigrate --- Released under MIT license. by Gustavo Vargas - @xgvargas - 2018 Original coffee code and issues at: https://github.com/xgvargas/monmigrate ### fs = require 'fs' shifting = require 'shifting' path = require 'path' Promise = require 'bluebird' EventEmitter = require 'events' babel = require 'babel-core' {presets} = require('../package.json').babel coffee = null emitter = new EventEmitter() getCode = (fn, funcname, ops) -> try code = fs.readFileSync path.join(ops.root, fn), 'utf-8' if fn.endsWith '.coffee' coffee ?= require 'coffee' code = coffee.compile code, {header: false, bare: true} #, transpile: {presets}} code = eval babel.transform(code, {ast:no, presets}).code return code[funcname] catch err console.error err throw new Error 'Can´t open '+fn module.exports = on: -> emitter.on arguments... create: (name, ops) -> new Promise (resolve, reject) -> # console.log name, ops if ops.auto return reject new Error 'Missing `models` for automatic code generation.' unless ops.models # TODO... # executar o plugin que deve converter algum tipo de esqueme para o formato o meu formato # depois analisar o esquema interno para decidir as modificacoes que deve ser aplicadas # e gerar o codigo para estas modificacoes... e salvar o esquema para ter base na # comparacao de mudancas em futuras versoes... console.log 'criando codigo automatico...' counter = +(fs.readdirSync(ops.root) .filter((f) -> /^\d{4}-.+\.(js|coffee)$/.test f) .sort().pop() or '0') .split('-')[0] fn = "#{('0000'+(++counter)).slice(-4)}-#{name.replace(/[^\s\w]/g, '').replace(/\s+/g, '-')}" if ops.coffee fn += '.coffee' csmodel = """ # Created on #{new Date().toJSON()}\n module.exports =\n \tdescribe: '#{name}'\n \tup: (cb) ->\n\t\tcb()\n \tdown: (cb) ->\n\t\tcb()\n """ else fn += '.js' jsmodel = """ // Created on #{new Date().toJSON()}\n module.exports = { \tdescribe: '#{name}',\n \tup: function (cb) {\n\t\tcb()\n\t},\n \tdown: function (cb) {\n\t\tcb()\n\t}\n};\n """ fullname = path.join ops.root, fn fs.writeFile fullname, (if ops.coffee then csmodel else jsmodel), 'utf8', (err) -> return reject err if err resolve fullname up: (ops) -> new Promise (resolve, reject) -> emitter.emit 'ready', ops Promise.mapSeries ops.dbs, (dbname) -> emitter.emit 'open_db', dbname ops.backend.createAPI dbname, ops .then (api) -> emitter.emit 'new_api', api api.print = (mesg) -> console.log '>>> ', mesg versions = fs.readdirSync(ops.root).filter((f) -> /^\d{4}-.+\.(js|coffee)$/.test f).sort() Promise.mapSeries versions, (file) -> script = getCode file, 'up', ops shifting.call [api, script] .then (res) -> console.log 'finalizado', res .catch (err) -> emitter.emit 'error', err console.log 'fudeu!', err .then -> ops.backend.closeAPI api emitter.emit 'done_db', dbname .catch (err) -> emitter.emit 'error', err console.log err try ops.backend.closeAPI api return reject err .catch (err) -> emitter.emit 'error', err return reject err .then -> emitter.emit 'done' resolve() .catch (err) -> emitter.emit 'error', err reject err down: (levels, ops) -> new Promise (resolve, reject) -> console.log 'desfazendo....', ops resolve()
96284
###! --- monmigrate --- Released under MIT license. by <NAME> - @xgvargas - 2018 Original coffee code and issues at: https://github.com/xgvargas/monmigrate ### fs = require 'fs' shifting = require 'shifting' path = require 'path' Promise = require 'bluebird' EventEmitter = require 'events' babel = require 'babel-core' {presets} = require('../package.json').babel coffee = null emitter = new EventEmitter() getCode = (fn, funcname, ops) -> try code = fs.readFileSync path.join(ops.root, fn), 'utf-8' if fn.endsWith '.coffee' coffee ?= require 'coffee' code = coffee.compile code, {header: false, bare: true} #, transpile: {presets}} code = eval babel.transform(code, {ast:no, presets}).code return code[funcname] catch err console.error err throw new Error 'Can´t open '+fn module.exports = on: -> emitter.on arguments... create: (name, ops) -> new Promise (resolve, reject) -> # console.log name, ops if ops.auto return reject new Error 'Missing `models` for automatic code generation.' unless ops.models # TODO... # executar o plugin que deve converter algum tipo de esqueme para o formato o meu formato # depois analisar o esquema interno para decidir as modificacoes que deve ser aplicadas # e gerar o codigo para estas modificacoes... e salvar o esquema para ter base na # comparacao de mudancas em futuras versoes... console.log 'criando codigo automatico...' counter = +(fs.readdirSync(ops.root) .filter((f) -> /^\d{4}-.+\.(js|coffee)$/.test f) .sort().pop() or '0') .split('-')[0] fn = "#{('0000'+(++counter)).slice(-4)}-#{name.replace(/[^\s\w]/g, '').replace(/\s+/g, '-')}" if ops.coffee fn += '.coffee' csmodel = """ # Created on #{new Date().toJSON()}\n module.exports =\n \tdescribe: '#{name}'\n \tup: (cb) ->\n\t\tcb()\n \tdown: (cb) ->\n\t\tcb()\n """ else fn += '.js' jsmodel = """ // Created on #{new Date().toJSON()}\n module.exports = { \tdescribe: '#{name}',\n \tup: function (cb) {\n\t\tcb()\n\t},\n \tdown: function (cb) {\n\t\tcb()\n\t}\n};\n """ fullname = path.join ops.root, fn fs.writeFile fullname, (if ops.coffee then csmodel else jsmodel), 'utf8', (err) -> return reject err if err resolve fullname up: (ops) -> new Promise (resolve, reject) -> emitter.emit 'ready', ops Promise.mapSeries ops.dbs, (dbname) -> emitter.emit 'open_db', dbname ops.backend.createAPI dbname, ops .then (api) -> emitter.emit 'new_api', api api.print = (mesg) -> console.log '>>> ', mesg versions = fs.readdirSync(ops.root).filter((f) -> /^\d{4}-.+\.(js|coffee)$/.test f).sort() Promise.mapSeries versions, (file) -> script = getCode file, 'up', ops shifting.call [api, script] .then (res) -> console.log 'finalizado', res .catch (err) -> emitter.emit 'error', err console.log 'fudeu!', err .then -> ops.backend.closeAPI api emitter.emit 'done_db', dbname .catch (err) -> emitter.emit 'error', err console.log err try ops.backend.closeAPI api return reject err .catch (err) -> emitter.emit 'error', err return reject err .then -> emitter.emit 'done' resolve() .catch (err) -> emitter.emit 'error', err reject err down: (levels, ops) -> new Promise (resolve, reject) -> console.log 'desfazendo....', ops resolve()
true
###! --- monmigrate --- Released under MIT license. by PI:NAME:<NAME>END_PI - @xgvargas - 2018 Original coffee code and issues at: https://github.com/xgvargas/monmigrate ### fs = require 'fs' shifting = require 'shifting' path = require 'path' Promise = require 'bluebird' EventEmitter = require 'events' babel = require 'babel-core' {presets} = require('../package.json').babel coffee = null emitter = new EventEmitter() getCode = (fn, funcname, ops) -> try code = fs.readFileSync path.join(ops.root, fn), 'utf-8' if fn.endsWith '.coffee' coffee ?= require 'coffee' code = coffee.compile code, {header: false, bare: true} #, transpile: {presets}} code = eval babel.transform(code, {ast:no, presets}).code return code[funcname] catch err console.error err throw new Error 'Can´t open '+fn module.exports = on: -> emitter.on arguments... create: (name, ops) -> new Promise (resolve, reject) -> # console.log name, ops if ops.auto return reject new Error 'Missing `models` for automatic code generation.' unless ops.models # TODO... # executar o plugin que deve converter algum tipo de esqueme para o formato o meu formato # depois analisar o esquema interno para decidir as modificacoes que deve ser aplicadas # e gerar o codigo para estas modificacoes... e salvar o esquema para ter base na # comparacao de mudancas em futuras versoes... console.log 'criando codigo automatico...' counter = +(fs.readdirSync(ops.root) .filter((f) -> /^\d{4}-.+\.(js|coffee)$/.test f) .sort().pop() or '0') .split('-')[0] fn = "#{('0000'+(++counter)).slice(-4)}-#{name.replace(/[^\s\w]/g, '').replace(/\s+/g, '-')}" if ops.coffee fn += '.coffee' csmodel = """ # Created on #{new Date().toJSON()}\n module.exports =\n \tdescribe: '#{name}'\n \tup: (cb) ->\n\t\tcb()\n \tdown: (cb) ->\n\t\tcb()\n """ else fn += '.js' jsmodel = """ // Created on #{new Date().toJSON()}\n module.exports = { \tdescribe: '#{name}',\n \tup: function (cb) {\n\t\tcb()\n\t},\n \tdown: function (cb) {\n\t\tcb()\n\t}\n};\n """ fullname = path.join ops.root, fn fs.writeFile fullname, (if ops.coffee then csmodel else jsmodel), 'utf8', (err) -> return reject err if err resolve fullname up: (ops) -> new Promise (resolve, reject) -> emitter.emit 'ready', ops Promise.mapSeries ops.dbs, (dbname) -> emitter.emit 'open_db', dbname ops.backend.createAPI dbname, ops .then (api) -> emitter.emit 'new_api', api api.print = (mesg) -> console.log '>>> ', mesg versions = fs.readdirSync(ops.root).filter((f) -> /^\d{4}-.+\.(js|coffee)$/.test f).sort() Promise.mapSeries versions, (file) -> script = getCode file, 'up', ops shifting.call [api, script] .then (res) -> console.log 'finalizado', res .catch (err) -> emitter.emit 'error', err console.log 'fudeu!', err .then -> ops.backend.closeAPI api emitter.emit 'done_db', dbname .catch (err) -> emitter.emit 'error', err console.log err try ops.backend.closeAPI api return reject err .catch (err) -> emitter.emit 'error', err return reject err .then -> emitter.emit 'done' resolve() .catch (err) -> emitter.emit 'error', err reject err down: (levels, ops) -> new Promise (resolve, reject) -> console.log 'desfazendo....', ops resolve()
[ { "context": " ->\n @game1 = new GamingAPI.Models.Game(name: \"test1\")\n @game2 = new GamingAPI.Models.Game(name: \"t", "end": 104, "score": 0.7810062170028687, "start": 99, "tag": "NAME", "value": "test1" }, { "context": "1\")\n @game2 = new GamingAPI.Models.Game(name: \"t...
spec/javascripts/games/views/games_spec.js.coffee
Mack0856/gaming_api
0
describe "GamingApi.Views.Games", -> beforeEach -> @game1 = new GamingAPI.Models.Game(name: "test1") @game2 = new GamingAPI.Models.Game(name: "test2") @game3 = new GamingAPI.Models.Game(name: "test3") @games = new GamingAPI.Collections.Games [@game1, @game2, @game3] @view = new GamingAPI.Views.Games(collection: @games) @view.render() describe "#render", -> it "renders the view with all games", -> expect(@view.$(".games-container").children().length).toEqual 3 expect($(@view.$(".games-container").children()[0]).find("a").text()).toEqual "test1" expect($(@view.$(".games-container").children()[1]).find("a").text()).toEqual "test2" expect($(@view.$(".games-container").children()[2]).find("a").text()).toEqual "test3"
73772
describe "GamingApi.Views.Games", -> beforeEach -> @game1 = new GamingAPI.Models.Game(name: "<NAME>") @game2 = new GamingAPI.Models.Game(name: "<NAME>") @game3 = new GamingAPI.Models.Game(name: "<NAME>") @games = new GamingAPI.Collections.Games [@game1, @game2, @game3] @view = new GamingAPI.Views.Games(collection: @games) @view.render() describe "#render", -> it "renders the view with all games", -> expect(@view.$(".games-container").children().length).toEqual 3 expect($(@view.$(".games-container").children()[0]).find("a").text()).toEqual "test1" expect($(@view.$(".games-container").children()[1]).find("a").text()).toEqual "test2" expect($(@view.$(".games-container").children()[2]).find("a").text()).toEqual "test3"
true
describe "GamingApi.Views.Games", -> beforeEach -> @game1 = new GamingAPI.Models.Game(name: "PI:NAME:<NAME>END_PI") @game2 = new GamingAPI.Models.Game(name: "PI:NAME:<NAME>END_PI") @game3 = new GamingAPI.Models.Game(name: "PI:NAME:<NAME>END_PI") @games = new GamingAPI.Collections.Games [@game1, @game2, @game3] @view = new GamingAPI.Views.Games(collection: @games) @view.render() describe "#render", -> it "renders the view with all games", -> expect(@view.$(".games-container").children().length).toEqual 3 expect($(@view.$(".games-container").children()[0]).find("a").text()).toEqual "test1" expect($(@view.$(".games-container").children()[1]).find("a").text()).toEqual "test2" expect($(@view.$(".games-container").children()[2]).find("a").text()).toEqual "test3"
[ { "context": " pkg = spec.package\n name = spec.name\n key = \"#{pkg}.#{name}\"\n\n # validate component has package, name, temp", "end": 4369, "score": 0.9988656640052795, "start": 4353, "tag": "KEY", "value": "\"#{pkg}.#{name}\"" } ]
src/compile.coffee
lemon/lemonjs-cli
0
# dependencies CleanCSS = require 'clean-css' Module = require 'module' Path = require 'path' coffee = require 'coffeescript' fs = require 'fs' lemoncup = require 'lemoncup' uglify = require 'uglify-js' # local dependencies blacklist = require Path.resolve __dirname, 'utils', 'blacklist' config = require Path.resolve __dirname, 'config' exists = require Path.resolve __dirname, 'utils', 'exists' read = require Path.resolve __dirname, 'utils', 'read' readCSON = require Path.resolve __dirname, 'utils', 'readCSON' serverCompFn = require Path.resolve __dirname, 'utils', 'server-comp-fn' sha1 = require Path.resolve __dirname, 'utils', 'sha1' stringify = require Path.resolve __dirname, 'utils', 'stringify' # compilers compilers = { css: require Path.resolve __dirname, 'compilers', 'css' js: require Path.resolve __dirname, 'compilers', 'javascript' stylus: require Path.resolve __dirname, 'compilers', 'stylus' } # setup global browser-like environment (lemon, site, page, window, document) require Path.resolve __dirname, 'utils', 'setup' # cache loaded files so we don't need to reprocess every request _cache = {} # override require to intercept dependency requests _require = Module.prototype.require Module.prototype.require = (filename) -> file = Module._resolveFilename filename, this ext = Path.extname file if file.match config._src return unless lemon.require file return _require.apply(this, arguments) for pkg in config.packages if file.match pkg return unless lemon.require file if ext in ['.css', '.styl'] return unless lemon.require file return _require.apply(this, arguments) # load lemon-browser lib dist = Path.join __dirname, '..', 'node_modules', 'lemonjs-browser', 'dist' _cache['lemon.js'] = read Path.join dist, "lemon.js" _cache['lemon.min.js'] = read Path.join dist, "lemon.min.js" # load lemoncup lib dist = Path.join __dirname, '..', 'node_modules', 'lemoncup', 'dist' _cache['lemoncup.js'] = read Path.join dist, "lemoncup.js" _cache['lemoncup.min.js'] = read Path.join dist, "lemoncup.min.js" # handle file change handleFileChange = (file) -> # clear cache delete _cache[file] # is data file # make sure file still exists (it wasn't deleted) if file.indexOf(config._data) >= 0 and exists file ext = Path.extname file pathname = file.replace(config._data, '').replace(ext, '').replace('/index', '') pathname = '/' if pathname is '' if ext is '.cson' site.data[pathname] = readCSON file else if ext is '.md' site.markdown[pathname] = read file # compile compile = (filename, options) -> {onError} = options {href, pathname, search, hash, query, url} = options # clear template cache for k of require.cache if k.match config._src delete require.cache[k] for pkg in config.packages if k.match pkg delete require.cache[k] # set location details global.location = { href: href pathname: pathname search: search or '' hash: hash or '' } # allow custom data if options.data site.data[pathname] = options.data # set page details global.page = { data: site.data[pathname] href: href markdown: site.markdown[pathname] pathname: pathname query: query url: url } # cache css and js deps = {css: [], js: []} # gather css and js dependencies while compiling app lemon.require = (file) -> return false if file in deps.css return true if file in deps.js _options = { minify: config.env is 'prod' } ext = Path.extname file switch ext when '.css' _cache[file] ?= compilers.css file, _options deps.css.push file return false when '.js' _cache[file] ?= compilers.js file, _options deps.js.push file return true when '.styl' _cache[file] ?= compilers.stylus file, _options deps.css.push file return false return true # clear lemoncup data cache lemoncup.clear() # set of packages being used lemon.Packages = { lemon: true } # set of components to transfer to the client lemon.Specs = {} # custom server-side version of Component to render initial template # then prepare dom for client-side version lemon.Component = (spec) -> pkg = spec.package name = spec.name key = "#{pkg}.#{name}" # validate component has package, name, template if not name throw new Error "Component needs 'name': #{name}" if not pkg throw new Error "Component needs 'package': #{pkg}" if pkg in blacklist throw new Error "#{pkg} is a forbidden package name" # save component to load to browser # components are often re-used, so hash them and only store once # store them by key so they can be used in client-side rendering # check for collisions (key matches but hash doesn't) spec.hash = sha1 spec lemon.Packages[pkg] = true lemon.Specs[key] ?= spec if lemon.Specs[key].hash isnt spec.hash throw new Error "lemon Component name collision: #{key}" # render server-side dom and initial template # need to merge data because we run the template directly. # In the browser, these are merged in the Component constructor global[pkg] ?= {} global[pkg][name] = serverCompFn(spec) return global[pkg][name] # create lemon.Router lemon.Component { package: 'lemon' name: 'Router' data: { init: true prev: {} beforeRoute: (current, prev) -> return false if current?.pathname is prev?.pathname return true routed: -> } # setTimeout so that redirects can be done in a route # action. That way we're guaranteed to let the router # finish mounting before attempting a new route. methods: { onRoute: -> routes = @_data.routes or @_data match = lemon.checkRoutes routes prev = @prev @prev = match if @init @init = false else if match return if @beforeRoute?(match, prev) is false setTimeout ( => @mount() @routed?(match) ), 0 } routes: { '/*': 'onRoute' } # check routes need to happen in the template for server-side loading template: (data) -> routes = data.routes or data match = lemon.checkRoutes routes match?.action match } lemon.route = (url) -> lemoncup.script type: 'text/javascript', "document.location = '#{url}';" # render template try template = require filename html = lemoncup.render template, options.data catch err onError err return null inject = (ext, contents, name) -> return unless contents name ?= "#{sha1 contents}.#{ext}" file = Path.resolve config._bundle, name pathname = "/bundle/#{name}" if ext is 'js' val = "<script type='text/javascript' src='#{pathname}'></script>" html = html.replace "</body>", "\n#{val}</body>" if ext is 'css' val = "<link rel='stylesheet' type='text/css' href='#{pathname}'>" html = html.replace "</head>", "\n#{val}</head>" fs.writeFileSync file, contents, 'utf8' # inject js: dependencies, transfer, and lemon core js_app = " #{("if(!window['#{k}']){window['#{k}']={}};" for k of lemon.Packages).join ''} lemoncup._data = #{stringify lemoncup._data}; lemon.Specs = #{stringify lemon.Specs}; window.site = #{stringify site}; window.page = #{stringify page}; lemon.init(); " if config.env is 'prod' js_deps = (_cache[dep] for dep in deps.js).join '' inject 'js', js_deps + _cache['lemoncup.min.js'] + _cache['lemon.min.js'] + js_app else inject 'js', _cache[dep] for dep in deps.js inject 'js', _cache['lemoncup.js'], 'lemoncup.js' inject 'js', _cache['lemon.js'], 'lemon.js' inject 'js', js_app, 'app.js' # inject css dependencies css_deps = (_cache[dep] for dep in deps.css).join '' if config.env is 'prod' css_deps = new CleanCSS().minify(css_deps).styles inject 'css', css_deps # inject reload script if on dev if config.env is 'dev' script = "<script src='/reload.js'></script>" html = html.replace "</body>", "#{script}\n</body>" return html # exports compile.cache = _cache compile.handleFileChange = handleFileChange module.exports = compile
81888
# dependencies CleanCSS = require 'clean-css' Module = require 'module' Path = require 'path' coffee = require 'coffeescript' fs = require 'fs' lemoncup = require 'lemoncup' uglify = require 'uglify-js' # local dependencies blacklist = require Path.resolve __dirname, 'utils', 'blacklist' config = require Path.resolve __dirname, 'config' exists = require Path.resolve __dirname, 'utils', 'exists' read = require Path.resolve __dirname, 'utils', 'read' readCSON = require Path.resolve __dirname, 'utils', 'readCSON' serverCompFn = require Path.resolve __dirname, 'utils', 'server-comp-fn' sha1 = require Path.resolve __dirname, 'utils', 'sha1' stringify = require Path.resolve __dirname, 'utils', 'stringify' # compilers compilers = { css: require Path.resolve __dirname, 'compilers', 'css' js: require Path.resolve __dirname, 'compilers', 'javascript' stylus: require Path.resolve __dirname, 'compilers', 'stylus' } # setup global browser-like environment (lemon, site, page, window, document) require Path.resolve __dirname, 'utils', 'setup' # cache loaded files so we don't need to reprocess every request _cache = {} # override require to intercept dependency requests _require = Module.prototype.require Module.prototype.require = (filename) -> file = Module._resolveFilename filename, this ext = Path.extname file if file.match config._src return unless lemon.require file return _require.apply(this, arguments) for pkg in config.packages if file.match pkg return unless lemon.require file if ext in ['.css', '.styl'] return unless lemon.require file return _require.apply(this, arguments) # load lemon-browser lib dist = Path.join __dirname, '..', 'node_modules', 'lemonjs-browser', 'dist' _cache['lemon.js'] = read Path.join dist, "lemon.js" _cache['lemon.min.js'] = read Path.join dist, "lemon.min.js" # load lemoncup lib dist = Path.join __dirname, '..', 'node_modules', 'lemoncup', 'dist' _cache['lemoncup.js'] = read Path.join dist, "lemoncup.js" _cache['lemoncup.min.js'] = read Path.join dist, "lemoncup.min.js" # handle file change handleFileChange = (file) -> # clear cache delete _cache[file] # is data file # make sure file still exists (it wasn't deleted) if file.indexOf(config._data) >= 0 and exists file ext = Path.extname file pathname = file.replace(config._data, '').replace(ext, '').replace('/index', '') pathname = '/' if pathname is '' if ext is '.cson' site.data[pathname] = readCSON file else if ext is '.md' site.markdown[pathname] = read file # compile compile = (filename, options) -> {onError} = options {href, pathname, search, hash, query, url} = options # clear template cache for k of require.cache if k.match config._src delete require.cache[k] for pkg in config.packages if k.match pkg delete require.cache[k] # set location details global.location = { href: href pathname: pathname search: search or '' hash: hash or '' } # allow custom data if options.data site.data[pathname] = options.data # set page details global.page = { data: site.data[pathname] href: href markdown: site.markdown[pathname] pathname: pathname query: query url: url } # cache css and js deps = {css: [], js: []} # gather css and js dependencies while compiling app lemon.require = (file) -> return false if file in deps.css return true if file in deps.js _options = { minify: config.env is 'prod' } ext = Path.extname file switch ext when '.css' _cache[file] ?= compilers.css file, _options deps.css.push file return false when '.js' _cache[file] ?= compilers.js file, _options deps.js.push file return true when '.styl' _cache[file] ?= compilers.stylus file, _options deps.css.push file return false return true # clear lemoncup data cache lemoncup.clear() # set of packages being used lemon.Packages = { lemon: true } # set of components to transfer to the client lemon.Specs = {} # custom server-side version of Component to render initial template # then prepare dom for client-side version lemon.Component = (spec) -> pkg = spec.package name = spec.name key = <KEY> # validate component has package, name, template if not name throw new Error "Component needs 'name': #{name}" if not pkg throw new Error "Component needs 'package': #{pkg}" if pkg in blacklist throw new Error "#{pkg} is a forbidden package name" # save component to load to browser # components are often re-used, so hash them and only store once # store them by key so they can be used in client-side rendering # check for collisions (key matches but hash doesn't) spec.hash = sha1 spec lemon.Packages[pkg] = true lemon.Specs[key] ?= spec if lemon.Specs[key].hash isnt spec.hash throw new Error "lemon Component name collision: #{key}" # render server-side dom and initial template # need to merge data because we run the template directly. # In the browser, these are merged in the Component constructor global[pkg] ?= {} global[pkg][name] = serverCompFn(spec) return global[pkg][name] # create lemon.Router lemon.Component { package: 'lemon' name: 'Router' data: { init: true prev: {} beforeRoute: (current, prev) -> return false if current?.pathname is prev?.pathname return true routed: -> } # setTimeout so that redirects can be done in a route # action. That way we're guaranteed to let the router # finish mounting before attempting a new route. methods: { onRoute: -> routes = @_data.routes or @_data match = lemon.checkRoutes routes prev = @prev @prev = match if @init @init = false else if match return if @beforeRoute?(match, prev) is false setTimeout ( => @mount() @routed?(match) ), 0 } routes: { '/*': 'onRoute' } # check routes need to happen in the template for server-side loading template: (data) -> routes = data.routes or data match = lemon.checkRoutes routes match?.action match } lemon.route = (url) -> lemoncup.script type: 'text/javascript', "document.location = '#{url}';" # render template try template = require filename html = lemoncup.render template, options.data catch err onError err return null inject = (ext, contents, name) -> return unless contents name ?= "#{sha1 contents}.#{ext}" file = Path.resolve config._bundle, name pathname = "/bundle/#{name}" if ext is 'js' val = "<script type='text/javascript' src='#{pathname}'></script>" html = html.replace "</body>", "\n#{val}</body>" if ext is 'css' val = "<link rel='stylesheet' type='text/css' href='#{pathname}'>" html = html.replace "</head>", "\n#{val}</head>" fs.writeFileSync file, contents, 'utf8' # inject js: dependencies, transfer, and lemon core js_app = " #{("if(!window['#{k}']){window['#{k}']={}};" for k of lemon.Packages).join ''} lemoncup._data = #{stringify lemoncup._data}; lemon.Specs = #{stringify lemon.Specs}; window.site = #{stringify site}; window.page = #{stringify page}; lemon.init(); " if config.env is 'prod' js_deps = (_cache[dep] for dep in deps.js).join '' inject 'js', js_deps + _cache['lemoncup.min.js'] + _cache['lemon.min.js'] + js_app else inject 'js', _cache[dep] for dep in deps.js inject 'js', _cache['lemoncup.js'], 'lemoncup.js' inject 'js', _cache['lemon.js'], 'lemon.js' inject 'js', js_app, 'app.js' # inject css dependencies css_deps = (_cache[dep] for dep in deps.css).join '' if config.env is 'prod' css_deps = new CleanCSS().minify(css_deps).styles inject 'css', css_deps # inject reload script if on dev if config.env is 'dev' script = "<script src='/reload.js'></script>" html = html.replace "</body>", "#{script}\n</body>" return html # exports compile.cache = _cache compile.handleFileChange = handleFileChange module.exports = compile
true
# dependencies CleanCSS = require 'clean-css' Module = require 'module' Path = require 'path' coffee = require 'coffeescript' fs = require 'fs' lemoncup = require 'lemoncup' uglify = require 'uglify-js' # local dependencies blacklist = require Path.resolve __dirname, 'utils', 'blacklist' config = require Path.resolve __dirname, 'config' exists = require Path.resolve __dirname, 'utils', 'exists' read = require Path.resolve __dirname, 'utils', 'read' readCSON = require Path.resolve __dirname, 'utils', 'readCSON' serverCompFn = require Path.resolve __dirname, 'utils', 'server-comp-fn' sha1 = require Path.resolve __dirname, 'utils', 'sha1' stringify = require Path.resolve __dirname, 'utils', 'stringify' # compilers compilers = { css: require Path.resolve __dirname, 'compilers', 'css' js: require Path.resolve __dirname, 'compilers', 'javascript' stylus: require Path.resolve __dirname, 'compilers', 'stylus' } # setup global browser-like environment (lemon, site, page, window, document) require Path.resolve __dirname, 'utils', 'setup' # cache loaded files so we don't need to reprocess every request _cache = {} # override require to intercept dependency requests _require = Module.prototype.require Module.prototype.require = (filename) -> file = Module._resolveFilename filename, this ext = Path.extname file if file.match config._src return unless lemon.require file return _require.apply(this, arguments) for pkg in config.packages if file.match pkg return unless lemon.require file if ext in ['.css', '.styl'] return unless lemon.require file return _require.apply(this, arguments) # load lemon-browser lib dist = Path.join __dirname, '..', 'node_modules', 'lemonjs-browser', 'dist' _cache['lemon.js'] = read Path.join dist, "lemon.js" _cache['lemon.min.js'] = read Path.join dist, "lemon.min.js" # load lemoncup lib dist = Path.join __dirname, '..', 'node_modules', 'lemoncup', 'dist' _cache['lemoncup.js'] = read Path.join dist, "lemoncup.js" _cache['lemoncup.min.js'] = read Path.join dist, "lemoncup.min.js" # handle file change handleFileChange = (file) -> # clear cache delete _cache[file] # is data file # make sure file still exists (it wasn't deleted) if file.indexOf(config._data) >= 0 and exists file ext = Path.extname file pathname = file.replace(config._data, '').replace(ext, '').replace('/index', '') pathname = '/' if pathname is '' if ext is '.cson' site.data[pathname] = readCSON file else if ext is '.md' site.markdown[pathname] = read file # compile compile = (filename, options) -> {onError} = options {href, pathname, search, hash, query, url} = options # clear template cache for k of require.cache if k.match config._src delete require.cache[k] for pkg in config.packages if k.match pkg delete require.cache[k] # set location details global.location = { href: href pathname: pathname search: search or '' hash: hash or '' } # allow custom data if options.data site.data[pathname] = options.data # set page details global.page = { data: site.data[pathname] href: href markdown: site.markdown[pathname] pathname: pathname query: query url: url } # cache css and js deps = {css: [], js: []} # gather css and js dependencies while compiling app lemon.require = (file) -> return false if file in deps.css return true if file in deps.js _options = { minify: config.env is 'prod' } ext = Path.extname file switch ext when '.css' _cache[file] ?= compilers.css file, _options deps.css.push file return false when '.js' _cache[file] ?= compilers.js file, _options deps.js.push file return true when '.styl' _cache[file] ?= compilers.stylus file, _options deps.css.push file return false return true # clear lemoncup data cache lemoncup.clear() # set of packages being used lemon.Packages = { lemon: true } # set of components to transfer to the client lemon.Specs = {} # custom server-side version of Component to render initial template # then prepare dom for client-side version lemon.Component = (spec) -> pkg = spec.package name = spec.name key = PI:KEY:<KEY>END_PI # validate component has package, name, template if not name throw new Error "Component needs 'name': #{name}" if not pkg throw new Error "Component needs 'package': #{pkg}" if pkg in blacklist throw new Error "#{pkg} is a forbidden package name" # save component to load to browser # components are often re-used, so hash them and only store once # store them by key so they can be used in client-side rendering # check for collisions (key matches but hash doesn't) spec.hash = sha1 spec lemon.Packages[pkg] = true lemon.Specs[key] ?= spec if lemon.Specs[key].hash isnt spec.hash throw new Error "lemon Component name collision: #{key}" # render server-side dom and initial template # need to merge data because we run the template directly. # In the browser, these are merged in the Component constructor global[pkg] ?= {} global[pkg][name] = serverCompFn(spec) return global[pkg][name] # create lemon.Router lemon.Component { package: 'lemon' name: 'Router' data: { init: true prev: {} beforeRoute: (current, prev) -> return false if current?.pathname is prev?.pathname return true routed: -> } # setTimeout so that redirects can be done in a route # action. That way we're guaranteed to let the router # finish mounting before attempting a new route. methods: { onRoute: -> routes = @_data.routes or @_data match = lemon.checkRoutes routes prev = @prev @prev = match if @init @init = false else if match return if @beforeRoute?(match, prev) is false setTimeout ( => @mount() @routed?(match) ), 0 } routes: { '/*': 'onRoute' } # check routes need to happen in the template for server-side loading template: (data) -> routes = data.routes or data match = lemon.checkRoutes routes match?.action match } lemon.route = (url) -> lemoncup.script type: 'text/javascript', "document.location = '#{url}';" # render template try template = require filename html = lemoncup.render template, options.data catch err onError err return null inject = (ext, contents, name) -> return unless contents name ?= "#{sha1 contents}.#{ext}" file = Path.resolve config._bundle, name pathname = "/bundle/#{name}" if ext is 'js' val = "<script type='text/javascript' src='#{pathname}'></script>" html = html.replace "</body>", "\n#{val}</body>" if ext is 'css' val = "<link rel='stylesheet' type='text/css' href='#{pathname}'>" html = html.replace "</head>", "\n#{val}</head>" fs.writeFileSync file, contents, 'utf8' # inject js: dependencies, transfer, and lemon core js_app = " #{("if(!window['#{k}']){window['#{k}']={}};" for k of lemon.Packages).join ''} lemoncup._data = #{stringify lemoncup._data}; lemon.Specs = #{stringify lemon.Specs}; window.site = #{stringify site}; window.page = #{stringify page}; lemon.init(); " if config.env is 'prod' js_deps = (_cache[dep] for dep in deps.js).join '' inject 'js', js_deps + _cache['lemoncup.min.js'] + _cache['lemon.min.js'] + js_app else inject 'js', _cache[dep] for dep in deps.js inject 'js', _cache['lemoncup.js'], 'lemoncup.js' inject 'js', _cache['lemon.js'], 'lemon.js' inject 'js', js_app, 'app.js' # inject css dependencies css_deps = (_cache[dep] for dep in deps.css).join '' if config.env is 'prod' css_deps = new CleanCSS().minify(css_deps).styles inject 'css', css_deps # inject reload script if on dev if config.env is 'dev' script = "<script src='/reload.js'></script>" html = html.replace "</body>", "#{script}\n</body>" return html # exports compile.cache = _cache compile.handleFileChange = handleFileChange module.exports = compile
[ { "context": "LOUD_HOST\n port: util.CLOUD_PORT\n key: \"peerjs\"\n path: \"/\"\n token: util.randomToken()\n", "end": 766, "score": 0.9990319013595581, "start": 760, "tag": "KEY", "value": "peerjs" }, { "context": "T\n key: \"peerjs\"\n path: \"/\"\n ...
lib/peer.coffee
voxxit/peercoffee
0
((root, factory) -> if typeof define is "function" and define.amd define [], -> root.Peer = factory() else if typeof exports is "object" module.exports = factory() else root.Peer = factory() )(@, () -> ### A peer who can initiate connections with other peers. ### Peer = (id, options) -> return new Peer(id, options) unless this instanceof Peer EventEmitter.call this # Deal with overloading if id and id.constructor is Object options = id id = `undefined` # Ensure id is a string else id = id.toString() if id # # Configurize options options = util.extend( debug: 0 # 1: Errors, 2: Warnings, 3: All logs host: util.CLOUD_HOST port: util.CLOUD_PORT key: "peerjs" path: "/" token: util.randomToken() config: util.defaultConfig , options) @options = options # Detect relative URL host. options.host = window.location.hostname if options.host is "/" # Set path correctly. options.path = "/" + options.path if options.path[0] isnt "/" options.path += "/" if options.path[options.path.length - 1] isnt "/" # Set whether we use SSL to same as current host options.secure = util.isSecure() if options.secure is `undefined` and options.host isnt util.CLOUD_HOST # Set a custom log function if present util.setLogFunction options.logFunction if options.logFunction util.setLogLevel options.debug # # Sanity checks # Ensure WebRTC supported if not util.supports.audioVideo and not util.supports.data @_delayedAbort "browser-incompatible", "The current browser does not support WebRTC" return # Ensure alphanumeric id unless util.validateId(id) @_delayedAbort "invalid-id", "ID \"" + id + "\" is invalid" return # Ensure valid key unless util.validateKey(options.key) @_delayedAbort "invalid-key", "API KEY \"" + options.key + "\" is invalid" return # Ensure not using unsecure cloud server on SSL page if options.secure and options.host is "0.peerjs.com" @_delayedAbort "ssl-unavailable", "The cloud server currently does not support HTTPS. Please run your own PeerServer to use HTTPS." return # # States. @destroyed = false # Connections have been killed @disconnected = false # Connection to PeerServer killed but P2P connections still active @open = false # Sockets and such are not yet open. # # References @connections = {} # DataConnections for this peer. @_lostMessages = {} # src => [list of messages] # # Start the server connection @_initializeServerConnection() if id @_initialize id else @_retrieveId() return # util.inherits Peer, EventEmitter # Initialize the 'socket' (which is actually a mix of XHR streaming and # websockets.) Peer::_initializeServerConnection = -> self = this @socket = new Socket(@options.secure, @options.host, @options.port, @options.path, @options.key) @socket.on "message", (data) -> self._handleMessage data return @socket.on "error", (error) -> self._abort "socket-error", error return @socket.on "disconnected", -> # If we haven't explicitly disconnected, emit error and disconnect. unless self.disconnected self.emitError "network", "Lost connection to server." self.disconnect() return @socket.on "close", -> # If we haven't explicitly disconnected, emit error. self._abort "socket-closed", "Underlying socket is already closed." unless self.disconnected return return ### Get a unique ID from the server via XHR. ### Peer::_retrieveId = (cb) -> self = this http = new XMLHttpRequest() protocol = (if @options.secure then "https://" else "http://") url = protocol + @options.host + ":" + @options.port + @options.path + @options.key + "/id" queryString = "?ts=" + new Date().getTime() + "" + Math.random() url += queryString # If there's no ID we need to wait for one before trying to init socket. http.open "get", url, true http.onerror = (e) -> util.error "Error retrieving ID", e pathError = "" pathError = " If you passed in a `path` to your self-hosted PeerServer, " + "you'll also need to pass in that same path when creating a new" + " Peer." if self.options.path is "/" and self.options.host isnt util.CLOUD_HOST self._abort "server-error", "Could not get an ID from the server." + pathError return http.onreadystatechange = -> return if http.readyState isnt 4 if http.status isnt 200 http.onerror() return self._initialize http.responseText return http.send null return ### Initialize a connection with the server. ### Peer::_initialize = (id) -> @id = id @socket.start @id, @options.token return ### Handles messages from the server. ### Peer::_handleMessage = (message) -> type = message.type payload = message.payload peer = message.src switch type when "OPEN" # The connection to the server is open. @emit "open", @id @open = true when "ERROR" # Server error. @_abort "server-error", payload.msg when "ID-TAKEN" # The selected ID is taken. @_abort "unavailable-id", "ID `" + @id + "` is taken" when "INVALID-KEY" # The given API key cannot be found. @_abort "invalid-key", "API KEY \"" + @options.key + "\" is invalid" # when "LEAVE" # Another peer has closed its connection to this peer. util.log "Received leave message from", peer @_cleanupPeer peer when "EXPIRE" # The offer sent to a peer has expired without response. @emitError "peer-unavailable", "Could not connect to peer " + peer when "OFFER" # we should consider switching this to CALL/CONNECT, but this is the least breaking option. connectionId = payload.connectionId connection = @getConnection(peer, connectionId) if connection util.warn "Offer received for existing Connection ID:", connectionId #connection.handleMessage(message); else # Create a new connection. if payload.type is "media" connection = new MediaConnection(peer, this, connectionId: connectionId _payload: payload metadata: payload.metadata ) @_addConnection peer, connection @emit "call", connection else if payload.type is "data" connection = new DataConnection(peer, this, connectionId: connectionId _payload: payload metadata: payload.metadata label: payload.label serialization: payload.serialization reliable: payload.reliable ) @_addConnection peer, connection @emit "connection", connection else util.warn "Received malformed connection type:", payload.type return # Find messages. messages = @_getMessages(connectionId) i = 0 ii = messages.length while i < ii connection.handleMessage messages[i] i += 1 else unless payload util.warn "You received a malformed message from " + peer + " of type " + type return id = payload.connectionId connection = @getConnection(peer, id) if connection and connection.pc # Pass it on. connection.handleMessage message else if id # Store for possible later use @_storeMessage id, message else util.warn "You received an unrecognized message:", message ### Stores messages without a set up connection, to be claimed later. ### Peer::_storeMessage = (connectionId, message) -> @_lostMessages[connectionId] = [] unless @_lostMessages[connectionId] @_lostMessages[connectionId].push message return ### Retrieve messages from lost message store ### Peer::_getMessages = (connectionId) -> messages = @_lostMessages[connectionId] if messages delete @_lostMessages[connectionId] messages else [] ### Returns a DataConnection to the specified peer. See documentation for a complete list of options. ### Peer::connect = (peer, options) -> if @disconnected util.warn "You cannot connect to a new Peer because you called " + ".disconnect() on this Peer and ended your connection with the" + " server. You can create a new Peer to reconnect, or call reconnect" + " on this peer if you believe its ID to still be available." @emitError "disconnected", "Cannot connect to new Peer after disconnecting from server." return connection = new DataConnection(peer, this, options) @_addConnection peer, connection connection ### Returns a MediaConnection to the specified peer. See documentation for a complete list of options. ### Peer::call = (peer, stream, options) -> if @disconnected util.warn "You cannot connect to a new Peer because you called " + ".disconnect() on this Peer and ended your connection with the" + " server. You can create a new Peer to reconnect." @emitError "disconnected", "Cannot connect to new Peer after disconnecting from server." return unless stream util.error "To call a peer, you must provide a stream from your browser's `getUserMedia`." return options = options or {} options._stream = stream call = new MediaConnection(peer, this, options) @_addConnection peer, call call ### Add a data/media connection to this peer. ### Peer::_addConnection = (peer, connection) -> @connections[peer] = [] unless @connections[peer] @connections[peer].push connection return ### Retrieve a data/media connection for this peer. ### Peer::getConnection = (peer, id) -> connections = @connections[peer] return null unless connections i = 0 ii = connections.length while i < ii return connections[i] if connections[i].id is id i++ null Peer::_delayedAbort = (type, message) -> self = this util.setZeroTimeout -> self._abort type, message return return ### Destroys the Peer and emits an error message. The Peer is not destroyed if it's in a disconnected state, in which case it retains its disconnected state and its existing connections. ### Peer::_abort = (type, message) -> util.error "Aborting!" unless @_lastServerId @destroy() else @disconnect() @emitError type, message return ### Emits a typed error message. ### Peer::emitError = (type, err) -> util.error "Error:", err err = new Error(err) if typeof err is "string" err.type = type @emit "error", err return ### Destroys the Peer: closes all active connections as well as the connection to the server. Warning: The peer can no longer create or accept connections after being destroyed. ### Peer::destroy = -> unless @destroyed @_cleanup() @disconnect() @destroyed = true return ### Disconnects every connection on this peer. ### Peer::_cleanup = -> if @connections peers = Object.keys(@connections) i = 0 ii = peers.length while i < ii @_cleanupPeer peers[i] i++ @emit "close" return ### Closes all connections to this peer. ### Peer::_cleanupPeer = (peer) -> connections = @connections[peer] j = 0 jj = connections.length while j < jj connections[j].close() j += 1 return ### Disconnects the Peer's connection to the PeerServer. Does not close any active connections. Warning: The peer can no longer create or accept connections after being disconnected. It also cannot reconnect to the server. ### Peer::disconnect = -> self = this util.setZeroTimeout -> unless self.disconnected self.disconnected = true self.open = false self.socket.close() if self.socket self.emit "disconnected", self.id self._lastServerId = self.id self.id = null return return ### Attempts to reconnect with the same ID. ### Peer::reconnect = -> if @disconnected and not @destroyed util.log "Attempting reconnection to server with ID " + @_lastServerId @disconnected = false @_initializeServerConnection() @_initialize @_lastServerId else if @destroyed throw new Error("This peer cannot reconnect to the server. It has already been destroyed.") else if not @disconnected and not @open # Do nothing. We're still connecting the first time. util.error "In a hurry? We're still trying to make the initial connection!" else throw new Error("Peer " + @id + " cannot reconnect because it is not disconnected from the server!") return ### Get a list of available peer IDs. If you're running your own server, you'll want to set allow_discovery: true in the PeerServer options. If you're using the cloud server, email team@peerjs.com to get the functionality enabled for your key. ### Peer::listAllPeers = (cb) -> cb = cb or -> self = this http = new XMLHttpRequest() protocol = (if @options.secure then "https://" else "http://") url = protocol + @options.host + ":" + @options.port + @options.path + @options.key + "/peers" queryString = "?ts=" + new Date().getTime() + "" + Math.random() url += queryString # If there's no ID we need to wait for one before trying to init socket. http.open "get", url, true http.onerror = (e) -> self._abort "server-error", "Could not get peers from the server." cb [] return http.onreadystatechange = -> return if http.readyState isnt 4 if http.status is 401 helpfulError = "" if self.options.host isnt util.CLOUD_HOST helpfulError = "It looks like you're using the cloud server. You can email " + "team@peerjs.com to enable peer listing for your API key." else helpfulError = "You need to enable `allow_discovery` on your self-hosted" + " PeerServer to use this feature." throw new Error("It doesn't look like you have permission to list peers IDs. " + helpfulError) else if http.status isnt 200 cb [] else cb JSON.parse(http.responseText) return http.send null return return Peer )
4439
((root, factory) -> if typeof define is "function" and define.amd define [], -> root.Peer = factory() else if typeof exports is "object" module.exports = factory() else root.Peer = factory() )(@, () -> ### A peer who can initiate connections with other peers. ### Peer = (id, options) -> return new Peer(id, options) unless this instanceof Peer EventEmitter.call this # Deal with overloading if id and id.constructor is Object options = id id = `undefined` # Ensure id is a string else id = id.toString() if id # # Configurize options options = util.extend( debug: 0 # 1: Errors, 2: Warnings, 3: All logs host: util.CLOUD_HOST port: util.CLOUD_PORT key: "<KEY>" path: "/" token: <KEY>.<KEY>() config: util.defaultConfig , options) @options = options # Detect relative URL host. options.host = window.location.hostname if options.host is "/" # Set path correctly. options.path = "/" + options.path if options.path[0] isnt "/" options.path += "/" if options.path[options.path.length - 1] isnt "/" # Set whether we use SSL to same as current host options.secure = util.isSecure() if options.secure is `undefined` and options.host isnt util.CLOUD_HOST # Set a custom log function if present util.setLogFunction options.logFunction if options.logFunction util.setLogLevel options.debug # # Sanity checks # Ensure WebRTC supported if not util.supports.audioVideo and not util.supports.data @_delayedAbort "browser-incompatible", "The current browser does not support WebRTC" return # Ensure alphanumeric id unless util.validateId(id) @_delayedAbort "invalid-id", "ID \"" + id + "\" is invalid" return # Ensure valid key unless util.validateKey(options.key) @_delayedAbort "invalid-key", "API KEY \"" + options.key + "\" is invalid" return # Ensure not using unsecure cloud server on SSL page if options.secure and options.host is "0.peerjs.com" @_delayedAbort "ssl-unavailable", "The cloud server currently does not support HTTPS. Please run your own PeerServer to use HTTPS." return # # States. @destroyed = false # Connections have been killed @disconnected = false # Connection to PeerServer killed but P2P connections still active @open = false # Sockets and such are not yet open. # # References @connections = {} # DataConnections for this peer. @_lostMessages = {} # src => [list of messages] # # Start the server connection @_initializeServerConnection() if id @_initialize id else @_retrieveId() return # util.inherits Peer, EventEmitter # Initialize the 'socket' (which is actually a mix of XHR streaming and # websockets.) Peer::_initializeServerConnection = -> self = this @socket = new Socket(@options.secure, @options.host, @options.port, @options.path, @options.key) @socket.on "message", (data) -> self._handleMessage data return @socket.on "error", (error) -> self._abort "socket-error", error return @socket.on "disconnected", -> # If we haven't explicitly disconnected, emit error and disconnect. unless self.disconnected self.emitError "network", "Lost connection to server." self.disconnect() return @socket.on "close", -> # If we haven't explicitly disconnected, emit error. self._abort "socket-closed", "Underlying socket is already closed." unless self.disconnected return return ### Get a unique ID from the server via XHR. ### Peer::_retrieveId = (cb) -> self = this http = new XMLHttpRequest() protocol = (if @options.secure then "https://" else "http://") url = protocol + @options.host + ":" + @options.port + @options.path + @options.key + "/id" queryString = "?ts=" + new Date().getTime() + "" + Math.random() url += queryString # If there's no ID we need to wait for one before trying to init socket. http.open "get", url, true http.onerror = (e) -> util.error "Error retrieving ID", e pathError = "" pathError = " If you passed in a `path` to your self-hosted PeerServer, " + "you'll also need to pass in that same path when creating a new" + " Peer." if self.options.path is "/" and self.options.host isnt util.CLOUD_HOST self._abort "server-error", "Could not get an ID from the server." + pathError return http.onreadystatechange = -> return if http.readyState isnt 4 if http.status isnt 200 http.onerror() return self._initialize http.responseText return http.send null return ### Initialize a connection with the server. ### Peer::_initialize = (id) -> @id = id @socket.start @id, @options.token return ### Handles messages from the server. ### Peer::_handleMessage = (message) -> type = message.type payload = message.payload peer = message.src switch type when "OPEN" # The connection to the server is open. @emit "open", @id @open = true when "ERROR" # Server error. @_abort "server-error", payload.msg when "ID-TAKEN" # The selected ID is taken. @_abort "unavailable-id", "ID `" + @id + "` is taken" when "INVALID-KEY" # The given API key cannot be found. @_abort "invalid-key", "API KEY \"" + @options.key + "\" is invalid" # when "LEAVE" # Another peer has closed its connection to this peer. util.log "Received leave message from", peer @_cleanupPeer peer when "EXPIRE" # The offer sent to a peer has expired without response. @emitError "peer-unavailable", "Could not connect to peer " + peer when "OFFER" # we should consider switching this to CALL/CONNECT, but this is the least breaking option. connectionId = payload.connectionId connection = @getConnection(peer, connectionId) if connection util.warn "Offer received for existing Connection ID:", connectionId #connection.handleMessage(message); else # Create a new connection. if payload.type is "media" connection = new MediaConnection(peer, this, connectionId: connectionId _payload: payload metadata: payload.metadata ) @_addConnection peer, connection @emit "call", connection else if payload.type is "data" connection = new DataConnection(peer, this, connectionId: connectionId _payload: payload metadata: payload.metadata label: payload.label serialization: payload.serialization reliable: payload.reliable ) @_addConnection peer, connection @emit "connection", connection else util.warn "Received malformed connection type:", payload.type return # Find messages. messages = @_getMessages(connectionId) i = 0 ii = messages.length while i < ii connection.handleMessage messages[i] i += 1 else unless payload util.warn "You received a malformed message from " + peer + " of type " + type return id = payload.connectionId connection = @getConnection(peer, id) if connection and connection.pc # Pass it on. connection.handleMessage message else if id # Store for possible later use @_storeMessage id, message else util.warn "You received an unrecognized message:", message ### Stores messages without a set up connection, to be claimed later. ### Peer::_storeMessage = (connectionId, message) -> @_lostMessages[connectionId] = [] unless @_lostMessages[connectionId] @_lostMessages[connectionId].push message return ### Retrieve messages from lost message store ### Peer::_getMessages = (connectionId) -> messages = @_lostMessages[connectionId] if messages delete @_lostMessages[connectionId] messages else [] ### Returns a DataConnection to the specified peer. See documentation for a complete list of options. ### Peer::connect = (peer, options) -> if @disconnected util.warn "You cannot connect to a new Peer because you called " + ".disconnect() on this Peer and ended your connection with the" + " server. You can create a new Peer to reconnect, or call reconnect" + " on this peer if you believe its ID to still be available." @emitError "disconnected", "Cannot connect to new Peer after disconnecting from server." return connection = new DataConnection(peer, this, options) @_addConnection peer, connection connection ### Returns a MediaConnection to the specified peer. See documentation for a complete list of options. ### Peer::call = (peer, stream, options) -> if @disconnected util.warn "You cannot connect to a new Peer because you called " + ".disconnect() on this Peer and ended your connection with the" + " server. You can create a new Peer to reconnect." @emitError "disconnected", "Cannot connect to new Peer after disconnecting from server." return unless stream util.error "To call a peer, you must provide a stream from your browser's `getUserMedia`." return options = options or {} options._stream = stream call = new MediaConnection(peer, this, options) @_addConnection peer, call call ### Add a data/media connection to this peer. ### Peer::_addConnection = (peer, connection) -> @connections[peer] = [] unless @connections[peer] @connections[peer].push connection return ### Retrieve a data/media connection for this peer. ### Peer::getConnection = (peer, id) -> connections = @connections[peer] return null unless connections i = 0 ii = connections.length while i < ii return connections[i] if connections[i].id is id i++ null Peer::_delayedAbort = (type, message) -> self = this util.setZeroTimeout -> self._abort type, message return return ### Destroys the Peer and emits an error message. The Peer is not destroyed if it's in a disconnected state, in which case it retains its disconnected state and its existing connections. ### Peer::_abort = (type, message) -> util.error "Aborting!" unless @_lastServerId @destroy() else @disconnect() @emitError type, message return ### Emits a typed error message. ### Peer::emitError = (type, err) -> util.error "Error:", err err = new Error(err) if typeof err is "string" err.type = type @emit "error", err return ### Destroys the Peer: closes all active connections as well as the connection to the server. Warning: The peer can no longer create or accept connections after being destroyed. ### Peer::destroy = -> unless @destroyed @_cleanup() @disconnect() @destroyed = true return ### Disconnects every connection on this peer. ### Peer::_cleanup = -> if @connections peers = Object.keys(@connections) i = 0 ii = peers.length while i < ii @_cleanupPeer peers[i] i++ @emit "close" return ### Closes all connections to this peer. ### Peer::_cleanupPeer = (peer) -> connections = @connections[peer] j = 0 jj = connections.length while j < jj connections[j].close() j += 1 return ### Disconnects the Peer's connection to the PeerServer. Does not close any active connections. Warning: The peer can no longer create or accept connections after being disconnected. It also cannot reconnect to the server. ### Peer::disconnect = -> self = this util.setZeroTimeout -> unless self.disconnected self.disconnected = true self.open = false self.socket.close() if self.socket self.emit "disconnected", self.id self._lastServerId = self.id self.id = null return return ### Attempts to reconnect with the same ID. ### Peer::reconnect = -> if @disconnected and not @destroyed util.log "Attempting reconnection to server with ID " + @_lastServerId @disconnected = false @_initializeServerConnection() @_initialize @_lastServerId else if @destroyed throw new Error("This peer cannot reconnect to the server. It has already been destroyed.") else if not @disconnected and not @open # Do nothing. We're still connecting the first time. util.error "In a hurry? We're still trying to make the initial connection!" else throw new Error("Peer " + @id + " cannot reconnect because it is not disconnected from the server!") return ### Get a list of available peer IDs. If you're running your own server, you'll want to set allow_discovery: true in the PeerServer options. If you're using the cloud server, email <EMAIL> to get the functionality enabled for your key. ### Peer::listAllPeers = (cb) -> cb = cb or -> self = this http = new XMLHttpRequest() protocol = (if @options.secure then "https://" else "http://") url = protocol + @options.host + ":" + @options.port + @options.path + @options.key + "/peers" queryString = "?ts=" + new Date().getTime() + "" + Math.random() url += queryString # If there's no ID we need to wait for one before trying to init socket. http.open "get", url, true http.onerror = (e) -> self._abort "server-error", "Could not get peers from the server." cb [] return http.onreadystatechange = -> return if http.readyState isnt 4 if http.status is 401 helpfulError = "" if self.options.host isnt util.CLOUD_HOST helpfulError = "It looks like you're using the cloud server. You can email " + "<EMAIL> to enable peer listing for your API key." else helpfulError = "You need to enable `allow_discovery` on your self-hosted" + " PeerServer to use this feature." throw new Error("It doesn't look like you have permission to list peers IDs. " + helpfulError) else if http.status isnt 200 cb [] else cb JSON.parse(http.responseText) return http.send null return return Peer )
true
((root, factory) -> if typeof define is "function" and define.amd define [], -> root.Peer = factory() else if typeof exports is "object" module.exports = factory() else root.Peer = factory() )(@, () -> ### A peer who can initiate connections with other peers. ### Peer = (id, options) -> return new Peer(id, options) unless this instanceof Peer EventEmitter.call this # Deal with overloading if id and id.constructor is Object options = id id = `undefined` # Ensure id is a string else id = id.toString() if id # # Configurize options options = util.extend( debug: 0 # 1: Errors, 2: Warnings, 3: All logs host: util.CLOUD_HOST port: util.CLOUD_PORT key: "PI:KEY:<KEY>END_PI" path: "/" token: PI:KEY:<KEY>END_PI.PI:KEY:<KEY>END_PI() config: util.defaultConfig , options) @options = options # Detect relative URL host. options.host = window.location.hostname if options.host is "/" # Set path correctly. options.path = "/" + options.path if options.path[0] isnt "/" options.path += "/" if options.path[options.path.length - 1] isnt "/" # Set whether we use SSL to same as current host options.secure = util.isSecure() if options.secure is `undefined` and options.host isnt util.CLOUD_HOST # Set a custom log function if present util.setLogFunction options.logFunction if options.logFunction util.setLogLevel options.debug # # Sanity checks # Ensure WebRTC supported if not util.supports.audioVideo and not util.supports.data @_delayedAbort "browser-incompatible", "The current browser does not support WebRTC" return # Ensure alphanumeric id unless util.validateId(id) @_delayedAbort "invalid-id", "ID \"" + id + "\" is invalid" return # Ensure valid key unless util.validateKey(options.key) @_delayedAbort "invalid-key", "API KEY \"" + options.key + "\" is invalid" return # Ensure not using unsecure cloud server on SSL page if options.secure and options.host is "0.peerjs.com" @_delayedAbort "ssl-unavailable", "The cloud server currently does not support HTTPS. Please run your own PeerServer to use HTTPS." return # # States. @destroyed = false # Connections have been killed @disconnected = false # Connection to PeerServer killed but P2P connections still active @open = false # Sockets and such are not yet open. # # References @connections = {} # DataConnections for this peer. @_lostMessages = {} # src => [list of messages] # # Start the server connection @_initializeServerConnection() if id @_initialize id else @_retrieveId() return # util.inherits Peer, EventEmitter # Initialize the 'socket' (which is actually a mix of XHR streaming and # websockets.) Peer::_initializeServerConnection = -> self = this @socket = new Socket(@options.secure, @options.host, @options.port, @options.path, @options.key) @socket.on "message", (data) -> self._handleMessage data return @socket.on "error", (error) -> self._abort "socket-error", error return @socket.on "disconnected", -> # If we haven't explicitly disconnected, emit error and disconnect. unless self.disconnected self.emitError "network", "Lost connection to server." self.disconnect() return @socket.on "close", -> # If we haven't explicitly disconnected, emit error. self._abort "socket-closed", "Underlying socket is already closed." unless self.disconnected return return ### Get a unique ID from the server via XHR. ### Peer::_retrieveId = (cb) -> self = this http = new XMLHttpRequest() protocol = (if @options.secure then "https://" else "http://") url = protocol + @options.host + ":" + @options.port + @options.path + @options.key + "/id" queryString = "?ts=" + new Date().getTime() + "" + Math.random() url += queryString # If there's no ID we need to wait for one before trying to init socket. http.open "get", url, true http.onerror = (e) -> util.error "Error retrieving ID", e pathError = "" pathError = " If you passed in a `path` to your self-hosted PeerServer, " + "you'll also need to pass in that same path when creating a new" + " Peer." if self.options.path is "/" and self.options.host isnt util.CLOUD_HOST self._abort "server-error", "Could not get an ID from the server." + pathError return http.onreadystatechange = -> return if http.readyState isnt 4 if http.status isnt 200 http.onerror() return self._initialize http.responseText return http.send null return ### Initialize a connection with the server. ### Peer::_initialize = (id) -> @id = id @socket.start @id, @options.token return ### Handles messages from the server. ### Peer::_handleMessage = (message) -> type = message.type payload = message.payload peer = message.src switch type when "OPEN" # The connection to the server is open. @emit "open", @id @open = true when "ERROR" # Server error. @_abort "server-error", payload.msg when "ID-TAKEN" # The selected ID is taken. @_abort "unavailable-id", "ID `" + @id + "` is taken" when "INVALID-KEY" # The given API key cannot be found. @_abort "invalid-key", "API KEY \"" + @options.key + "\" is invalid" # when "LEAVE" # Another peer has closed its connection to this peer. util.log "Received leave message from", peer @_cleanupPeer peer when "EXPIRE" # The offer sent to a peer has expired without response. @emitError "peer-unavailable", "Could not connect to peer " + peer when "OFFER" # we should consider switching this to CALL/CONNECT, but this is the least breaking option. connectionId = payload.connectionId connection = @getConnection(peer, connectionId) if connection util.warn "Offer received for existing Connection ID:", connectionId #connection.handleMessage(message); else # Create a new connection. if payload.type is "media" connection = new MediaConnection(peer, this, connectionId: connectionId _payload: payload metadata: payload.metadata ) @_addConnection peer, connection @emit "call", connection else if payload.type is "data" connection = new DataConnection(peer, this, connectionId: connectionId _payload: payload metadata: payload.metadata label: payload.label serialization: payload.serialization reliable: payload.reliable ) @_addConnection peer, connection @emit "connection", connection else util.warn "Received malformed connection type:", payload.type return # Find messages. messages = @_getMessages(connectionId) i = 0 ii = messages.length while i < ii connection.handleMessage messages[i] i += 1 else unless payload util.warn "You received a malformed message from " + peer + " of type " + type return id = payload.connectionId connection = @getConnection(peer, id) if connection and connection.pc # Pass it on. connection.handleMessage message else if id # Store for possible later use @_storeMessage id, message else util.warn "You received an unrecognized message:", message ### Stores messages without a set up connection, to be claimed later. ### Peer::_storeMessage = (connectionId, message) -> @_lostMessages[connectionId] = [] unless @_lostMessages[connectionId] @_lostMessages[connectionId].push message return ### Retrieve messages from lost message store ### Peer::_getMessages = (connectionId) -> messages = @_lostMessages[connectionId] if messages delete @_lostMessages[connectionId] messages else [] ### Returns a DataConnection to the specified peer. See documentation for a complete list of options. ### Peer::connect = (peer, options) -> if @disconnected util.warn "You cannot connect to a new Peer because you called " + ".disconnect() on this Peer and ended your connection with the" + " server. You can create a new Peer to reconnect, or call reconnect" + " on this peer if you believe its ID to still be available." @emitError "disconnected", "Cannot connect to new Peer after disconnecting from server." return connection = new DataConnection(peer, this, options) @_addConnection peer, connection connection ### Returns a MediaConnection to the specified peer. See documentation for a complete list of options. ### Peer::call = (peer, stream, options) -> if @disconnected util.warn "You cannot connect to a new Peer because you called " + ".disconnect() on this Peer and ended your connection with the" + " server. You can create a new Peer to reconnect." @emitError "disconnected", "Cannot connect to new Peer after disconnecting from server." return unless stream util.error "To call a peer, you must provide a stream from your browser's `getUserMedia`." return options = options or {} options._stream = stream call = new MediaConnection(peer, this, options) @_addConnection peer, call call ### Add a data/media connection to this peer. ### Peer::_addConnection = (peer, connection) -> @connections[peer] = [] unless @connections[peer] @connections[peer].push connection return ### Retrieve a data/media connection for this peer. ### Peer::getConnection = (peer, id) -> connections = @connections[peer] return null unless connections i = 0 ii = connections.length while i < ii return connections[i] if connections[i].id is id i++ null Peer::_delayedAbort = (type, message) -> self = this util.setZeroTimeout -> self._abort type, message return return ### Destroys the Peer and emits an error message. The Peer is not destroyed if it's in a disconnected state, in which case it retains its disconnected state and its existing connections. ### Peer::_abort = (type, message) -> util.error "Aborting!" unless @_lastServerId @destroy() else @disconnect() @emitError type, message return ### Emits a typed error message. ### Peer::emitError = (type, err) -> util.error "Error:", err err = new Error(err) if typeof err is "string" err.type = type @emit "error", err return ### Destroys the Peer: closes all active connections as well as the connection to the server. Warning: The peer can no longer create or accept connections after being destroyed. ### Peer::destroy = -> unless @destroyed @_cleanup() @disconnect() @destroyed = true return ### Disconnects every connection on this peer. ### Peer::_cleanup = -> if @connections peers = Object.keys(@connections) i = 0 ii = peers.length while i < ii @_cleanupPeer peers[i] i++ @emit "close" return ### Closes all connections to this peer. ### Peer::_cleanupPeer = (peer) -> connections = @connections[peer] j = 0 jj = connections.length while j < jj connections[j].close() j += 1 return ### Disconnects the Peer's connection to the PeerServer. Does not close any active connections. Warning: The peer can no longer create or accept connections after being disconnected. It also cannot reconnect to the server. ### Peer::disconnect = -> self = this util.setZeroTimeout -> unless self.disconnected self.disconnected = true self.open = false self.socket.close() if self.socket self.emit "disconnected", self.id self._lastServerId = self.id self.id = null return return ### Attempts to reconnect with the same ID. ### Peer::reconnect = -> if @disconnected and not @destroyed util.log "Attempting reconnection to server with ID " + @_lastServerId @disconnected = false @_initializeServerConnection() @_initialize @_lastServerId else if @destroyed throw new Error("This peer cannot reconnect to the server. It has already been destroyed.") else if not @disconnected and not @open # Do nothing. We're still connecting the first time. util.error "In a hurry? We're still trying to make the initial connection!" else throw new Error("Peer " + @id + " cannot reconnect because it is not disconnected from the server!") return ### Get a list of available peer IDs. If you're running your own server, you'll want to set allow_discovery: true in the PeerServer options. If you're using the cloud server, email PI:EMAIL:<EMAIL>END_PI to get the functionality enabled for your key. ### Peer::listAllPeers = (cb) -> cb = cb or -> self = this http = new XMLHttpRequest() protocol = (if @options.secure then "https://" else "http://") url = protocol + @options.host + ":" + @options.port + @options.path + @options.key + "/peers" queryString = "?ts=" + new Date().getTime() + "" + Math.random() url += queryString # If there's no ID we need to wait for one before trying to init socket. http.open "get", url, true http.onerror = (e) -> self._abort "server-error", "Could not get peers from the server." cb [] return http.onreadystatechange = -> return if http.readyState isnt 4 if http.status is 401 helpfulError = "" if self.options.host isnt util.CLOUD_HOST helpfulError = "It looks like you're using the cloud server. You can email " + "PI:EMAIL:<EMAIL>END_PI to enable peer listing for your API key." else helpfulError = "You need to enable `allow_discovery` on your self-hosted" + " PeerServer to use this feature." throw new Error("It doesn't look like you have permission to list peers IDs. " + helpfulError) else if http.status isnt 200 cb [] else cb JSON.parse(http.responseText) return http.send null return return Peer )
[ { "context": "# @author xiaoshu.wb\n# @version 1.0.0\n# @see\n# @Time 2017-02-", "end": 11, "score": 0.9056885242462158, "start": 10, "tag": "NAME", "value": "x" }, { "context": "# @author xiaoshu.wb\n# @version 1.0.0\n# @see\n# @Time 2017-02-09 Cambri", "end": 20, "score": 0...
lib/create-files-view.coffee
TheraPackages/create-files
1
# @author xiaoshu.wb # @version 1.0.0 # @see # @Time 2017-02-09 Cambridge Guildholl module.exports = {View} = require 'space-pen' {TextEditorView} = require 'atom-space-pen-views' {CreateFileType} = require './create-files-type-select' $ = window.$ = window.jQuery = require 'jquery' require './jquery-ui.js' module.exports = class CreateFilesView filenameAndpath = null isAnimation = false constructor: (serializedState) -> # Create root element @element = document.createElement('div') @element.classList.add('create-files') # Create message element message = document.createElement('div') @filenameAndpath = new TextEditorView(mini: true,placeholderText:'Please input you file name and path') @filenameAndpath.id = 'thera-create-file-textedit' console.log(@filenameAndpath) message.textContent = "Add a file to.." message.classList.add('titleCreateFile') message.appendChild(atom.views.getView(@filenameAndpath)) @createFileType = new CreateFileType(@filenameAndpath) message.appendChild(atom.views.getView(@createFileType)) @element.appendChild(message) atom.views.getView(@filenameAndpath).addEventListener 'keydown', (e) => @noteOn(e) @filenameAndpath.focus() @filenameAndpath.on 'blur', -> anima = $("#createfiles").attr("isAnimation") if(anima != "true") atom.commands.dispatch(atom.views.getView(atom.workspace), "create-files:esc") #@element.appendChild(atom.views.getView(@filenameAndpath)) #@element.appendChild(atom.views.getView(@createFileType)) # Returns an object that can be retrieved when package is activated serialize: -> initialize: -> super @filenameAndpath.focus() noteOn: (event) -> switch when event.keyIdentifier == 'Enter' then atom.commands.dispatch(atom.views.getView(atom.workspace), "create-files:tremble", @filenameAndpath.getText()) when event.keyIdentifier == 'U+001B' then atom.commands.dispatch(atom.views.getView(atom.workspace), "create-files:esc") else return updatePath:(textContent) -> @filenameAndpath.focus() if(textContent) @filenameAndpath.setText textContent # Tear down any state and detach destroy: -> @element.remove() getElement: -> @element
44845
# @author <NAME>iaoshu.wb # @version 1.0.0 # @see # @Time 2017-02-09 <NAME> module.exports = {View} = require 'space-pen' {TextEditorView} = require 'atom-space-pen-views' {CreateFileType} = require './create-files-type-select' $ = window.$ = window.jQuery = require 'jquery' require './jquery-ui.js' module.exports = class CreateFilesView filenameAndpath = null isAnimation = false constructor: (serializedState) -> # Create root element @element = document.createElement('div') @element.classList.add('create-files') # Create message element message = document.createElement('div') @filenameAndpath = new TextEditorView(mini: true,placeholderText:'Please input you file name and path') @filenameAndpath.id = 'thera-create-file-textedit' console.log(@filenameAndpath) message.textContent = "Add a file to.." message.classList.add('titleCreateFile') message.appendChild(atom.views.getView(@filenameAndpath)) @createFileType = new CreateFileType(@filenameAndpath) message.appendChild(atom.views.getView(@createFileType)) @element.appendChild(message) atom.views.getView(@filenameAndpath).addEventListener 'keydown', (e) => @noteOn(e) @filenameAndpath.focus() @filenameAndpath.on 'blur', -> anima = $("#createfiles").attr("isAnimation") if(anima != "true") atom.commands.dispatch(atom.views.getView(atom.workspace), "create-files:esc") #@element.appendChild(atom.views.getView(@filenameAndpath)) #@element.appendChild(atom.views.getView(@createFileType)) # Returns an object that can be retrieved when package is activated serialize: -> initialize: -> super @filenameAndpath.focus() noteOn: (event) -> switch when event.keyIdentifier == 'Enter' then atom.commands.dispatch(atom.views.getView(atom.workspace), "create-files:tremble", @filenameAndpath.getText()) when event.keyIdentifier == '<KEY>' then atom.commands.dispatch(atom.views.getView(atom.workspace), "create-files:esc") else return updatePath:(textContent) -> @filenameAndpath.focus() if(textContent) @filenameAndpath.setText textContent # Tear down any state and detach destroy: -> @element.remove() getElement: -> @element
true
# @author PI:NAME:<NAME>END_PIiaoshu.wb # @version 1.0.0 # @see # @Time 2017-02-09 PI:NAME:<NAME>END_PI module.exports = {View} = require 'space-pen' {TextEditorView} = require 'atom-space-pen-views' {CreateFileType} = require './create-files-type-select' $ = window.$ = window.jQuery = require 'jquery' require './jquery-ui.js' module.exports = class CreateFilesView filenameAndpath = null isAnimation = false constructor: (serializedState) -> # Create root element @element = document.createElement('div') @element.classList.add('create-files') # Create message element message = document.createElement('div') @filenameAndpath = new TextEditorView(mini: true,placeholderText:'Please input you file name and path') @filenameAndpath.id = 'thera-create-file-textedit' console.log(@filenameAndpath) message.textContent = "Add a file to.." message.classList.add('titleCreateFile') message.appendChild(atom.views.getView(@filenameAndpath)) @createFileType = new CreateFileType(@filenameAndpath) message.appendChild(atom.views.getView(@createFileType)) @element.appendChild(message) atom.views.getView(@filenameAndpath).addEventListener 'keydown', (e) => @noteOn(e) @filenameAndpath.focus() @filenameAndpath.on 'blur', -> anima = $("#createfiles").attr("isAnimation") if(anima != "true") atom.commands.dispatch(atom.views.getView(atom.workspace), "create-files:esc") #@element.appendChild(atom.views.getView(@filenameAndpath)) #@element.appendChild(atom.views.getView(@createFileType)) # Returns an object that can be retrieved when package is activated serialize: -> initialize: -> super @filenameAndpath.focus() noteOn: (event) -> switch when event.keyIdentifier == 'Enter' then atom.commands.dispatch(atom.views.getView(atom.workspace), "create-files:tremble", @filenameAndpath.getText()) when event.keyIdentifier == 'PI:KEY:<KEY>END_PI' then atom.commands.dispatch(atom.views.getView(atom.workspace), "create-files:esc") else return updatePath:(textContent) -> @filenameAndpath.focus() if(textContent) @filenameAndpath.setText textContent # Tear down any state and detach destroy: -> @element.remove() getElement: -> @element
[ { "context": "\"תגיות\"\nPAGES: \"עמודים\"\nPOSTS: \"פוסטים\"\nAUTHORS: \"מחברים\"\nSEARCH: \"חיפוש\"\nSEARCH_START: \"הקלד...\"\nSOCIAL_N", "end": 324, "score": 0.9898719787597656, "start": 318, "tag": "NAME", "value": "מחברים" } ]
src/i18n/he.cson
pinkasey/anonymous-wphc
0
PULL_TO_REFRESH: "משוך לעדכן!" RETRY: "נסה שוב" CANCEL: "ביטול" SUBMIT: "שלח" BACK: "חזור" ERROR: "משהו השתבש. אנא נסה שנית" ATTEMPT_TO_CONNECT: "ניסיון התחברון {{attempt}} מתוך {{attemptMax}}." OK: "אוקי" YES: "כן" NO: "לא" EMPTY_LIST: "אין תוכן" MENU: "תפריט" TAGS: "תגיות" PAGES: "עמודים" POSTS: "פוסטים" AUTHORS: "מחברים" SEARCH: "חיפוש" SEARCH_START: "הקלד..." SOCIAL_NETWORKS: "רשתות חברתיות" CATEGORIES: "קטגוריות" SETTINGS: "אפשרויות" ZOOM: "זום" FEATURED: "מובלט" OPEN_IN_BROWSER: "פתח בדפדפן" ABOUT: "אודות" COMMENTS: "הערות" CUSTOM_POSTS: "פוסטים מותאמים אישית" CUSTOM_TAXO: "טקסונומיות מותאמות אישית" CUSTOM_TAXO_TITLE: "{{term}}: {{name}}" PUSH_NOTIFS: "Push notifications" PUSH_NOTIF_TITLE: "תוכן חדש!" PUSH_NOTIF_TEXT: "תוכן חדש נוסף לאפליקציה. לחץ לפתיחה: '{{postTitle}}'" BOOKMARKS: "סימניות" BOOKMARKS_EMPTY: "אין סימניות" BOOKMARK_ADDED: "סימניה נוספה" BOOKMARK_REMOVED: "סימניה הוסרה" CACHE_CLEAR: "נקה זיכרון מטמון (קאש)" CACHE_CLEAR_PROMPT: "זיכרון המטמון ימחק עד לפעם הבאה שתוריד תוכן" CACHE_CLEARED: "זיכרון מטמון נמחק" TITLE_TAGS: "תגיות" TITLE_TAG: "תג: {{name}}" TITLE_CATEGORIES: "קטגוריות" TITLE_CATEGORY: "קטגוריה: {{name}}" TITLE_HOME: "בית" TITLE_SEARCH: "חיפוש" TITLE_PAGES: "עמודים" TITLE_POSTS: "פוסטים" TITLE_USERS: "מחברים" TITLE_USER: "מחבר" TITLE_USER_POSTS: "מחבר: {{name}}" SHARE_SUCCESS: "שותף!" SHARE_ERROR: "שיתוף נכשל" # CUSTOM NO NEED TO TRANSLATE IN OTHER LANGUAGES TITLE_MOVIE: "סרטים" TITLE_ACTOR: "שחקנים"
2615
PULL_TO_REFRESH: "משוך לעדכן!" RETRY: "נסה שוב" CANCEL: "ביטול" SUBMIT: "שלח" BACK: "חזור" ERROR: "משהו השתבש. אנא נסה שנית" ATTEMPT_TO_CONNECT: "ניסיון התחברון {{attempt}} מתוך {{attemptMax}}." OK: "אוקי" YES: "כן" NO: "לא" EMPTY_LIST: "אין תוכן" MENU: "תפריט" TAGS: "תגיות" PAGES: "עמודים" POSTS: "פוסטים" AUTHORS: "<NAME>" SEARCH: "חיפוש" SEARCH_START: "הקלד..." SOCIAL_NETWORKS: "רשתות חברתיות" CATEGORIES: "קטגוריות" SETTINGS: "אפשרויות" ZOOM: "זום" FEATURED: "מובלט" OPEN_IN_BROWSER: "פתח בדפדפן" ABOUT: "אודות" COMMENTS: "הערות" CUSTOM_POSTS: "פוסטים מותאמים אישית" CUSTOM_TAXO: "טקסונומיות מותאמות אישית" CUSTOM_TAXO_TITLE: "{{term}}: {{name}}" PUSH_NOTIFS: "Push notifications" PUSH_NOTIF_TITLE: "תוכן חדש!" PUSH_NOTIF_TEXT: "תוכן חדש נוסף לאפליקציה. לחץ לפתיחה: '{{postTitle}}'" BOOKMARKS: "סימניות" BOOKMARKS_EMPTY: "אין סימניות" BOOKMARK_ADDED: "סימניה נוספה" BOOKMARK_REMOVED: "סימניה הוסרה" CACHE_CLEAR: "נקה זיכרון מטמון (קאש)" CACHE_CLEAR_PROMPT: "זיכרון המטמון ימחק עד לפעם הבאה שתוריד תוכן" CACHE_CLEARED: "זיכרון מטמון נמחק" TITLE_TAGS: "תגיות" TITLE_TAG: "תג: {{name}}" TITLE_CATEGORIES: "קטגוריות" TITLE_CATEGORY: "קטגוריה: {{name}}" TITLE_HOME: "בית" TITLE_SEARCH: "חיפוש" TITLE_PAGES: "עמודים" TITLE_POSTS: "פוסטים" TITLE_USERS: "מחברים" TITLE_USER: "מחבר" TITLE_USER_POSTS: "מחבר: {{name}}" SHARE_SUCCESS: "שותף!" SHARE_ERROR: "שיתוף נכשל" # CUSTOM NO NEED TO TRANSLATE IN OTHER LANGUAGES TITLE_MOVIE: "סרטים" TITLE_ACTOR: "שחקנים"
true
PULL_TO_REFRESH: "משוך לעדכן!" RETRY: "נסה שוב" CANCEL: "ביטול" SUBMIT: "שלח" BACK: "חזור" ERROR: "משהו השתבש. אנא נסה שנית" ATTEMPT_TO_CONNECT: "ניסיון התחברון {{attempt}} מתוך {{attemptMax}}." OK: "אוקי" YES: "כן" NO: "לא" EMPTY_LIST: "אין תוכן" MENU: "תפריט" TAGS: "תגיות" PAGES: "עמודים" POSTS: "פוסטים" AUTHORS: "PI:NAME:<NAME>END_PI" SEARCH: "חיפוש" SEARCH_START: "הקלד..." SOCIAL_NETWORKS: "רשתות חברתיות" CATEGORIES: "קטגוריות" SETTINGS: "אפשרויות" ZOOM: "זום" FEATURED: "מובלט" OPEN_IN_BROWSER: "פתח בדפדפן" ABOUT: "אודות" COMMENTS: "הערות" CUSTOM_POSTS: "פוסטים מותאמים אישית" CUSTOM_TAXO: "טקסונומיות מותאמות אישית" CUSTOM_TAXO_TITLE: "{{term}}: {{name}}" PUSH_NOTIFS: "Push notifications" PUSH_NOTIF_TITLE: "תוכן חדש!" PUSH_NOTIF_TEXT: "תוכן חדש נוסף לאפליקציה. לחץ לפתיחה: '{{postTitle}}'" BOOKMARKS: "סימניות" BOOKMARKS_EMPTY: "אין סימניות" BOOKMARK_ADDED: "סימניה נוספה" BOOKMARK_REMOVED: "סימניה הוסרה" CACHE_CLEAR: "נקה זיכרון מטמון (קאש)" CACHE_CLEAR_PROMPT: "זיכרון המטמון ימחק עד לפעם הבאה שתוריד תוכן" CACHE_CLEARED: "זיכרון מטמון נמחק" TITLE_TAGS: "תגיות" TITLE_TAG: "תג: {{name}}" TITLE_CATEGORIES: "קטגוריות" TITLE_CATEGORY: "קטגוריה: {{name}}" TITLE_HOME: "בית" TITLE_SEARCH: "חיפוש" TITLE_PAGES: "עמודים" TITLE_POSTS: "פוסטים" TITLE_USERS: "מחברים" TITLE_USER: "מחבר" TITLE_USER_POSTS: "מחבר: {{name}}" SHARE_SUCCESS: "שותף!" SHARE_ERROR: "שיתוף נכשל" # CUSTOM NO NEED TO TRANSLATE IN OTHER LANGUAGES TITLE_MOVIE: "סרטים" TITLE_ACTOR: "שחקנים"
[ { "context": "'\n id: 'foo'\n artists: [\n name: 'Andy Warhol'\n id: 'andy-warhol'\n ]\n partner:", "end": 407, "score": 0.9998493790626526, "start": 396, "tag": "NAME", "value": "Andy Warhol" }, { "context": "tists: [\n name: 'Andy Warhol'\n ...
src/client/test/models/artwork.test.coffee
artsyjian/positron
76
_ = require 'underscore' Backbone = require 'backbone' Artwork = require '../../models/artwork.coffee' sinon = require 'sinon' { fabricate } = require '@artsy/antigravity' describe "Artwork", -> beforeEach -> sinon.stub Backbone, 'sync' @artwork = new Artwork _.extend {}, fabricate 'artwork', title: 'Foo' date: '1/1/2017' id: 'foo' artists: [ name: 'Andy Warhol' id: 'andy-warhol' ] partner: { name: 'MOMA' default_profile_public: true default_profile_id: 'moma' } afterEach -> Backbone.sync.restore() it 'creates a nice short label for the artwork', -> @artwork.truncatedLabel().should.equal 'A.W. Foo, 1/1/2017' it 'denormalizes artworks', -> denormalized = @artwork.denormalized() denormalized.type.should.equal 'artwork' denormalized.id.should.equal '564be09ab202a319e90000e2' denormalized.slug.should.equal 'foo' denormalized.date.should.equal '1/1/2017' denormalized.title.should.equal 'Foo' denormalized.image.should.equal '/local/additional_images/4e7cb83e1c80dd00010038e2/1/larger.jpg' denormalized.partner.name.should.equal 'MOMA' denormalized.partner.slug.should.equal 'moma' denormalized.artists[0].name.should.equal 'Andy Warhol' denormalized.artists[0].slug.should.equal 'andy-warhol' denormalized.width.should.equal 1000 denormalized.height.should.equal 585 denormalized.credit.should.equal 'Sourced from ARS'
124286
_ = require 'underscore' Backbone = require 'backbone' Artwork = require '../../models/artwork.coffee' sinon = require 'sinon' { fabricate } = require '@artsy/antigravity' describe "Artwork", -> beforeEach -> sinon.stub Backbone, 'sync' @artwork = new Artwork _.extend {}, fabricate 'artwork', title: 'Foo' date: '1/1/2017' id: 'foo' artists: [ name: '<NAME>' id: 'andy-warhol' ] partner: { name: 'MOMA' default_profile_public: true default_profile_id: 'moma' } afterEach -> Backbone.sync.restore() it 'creates a nice short label for the artwork', -> @artwork.truncatedLabel().should.equal 'A.W. Foo, 1/1/2017' it 'denormalizes artworks', -> denormalized = @artwork.denormalized() denormalized.type.should.equal 'artwork' denormalized.id.should.equal '564be09ab202a319e90000e2' denormalized.slug.should.equal 'foo' denormalized.date.should.equal '1/1/2017' denormalized.title.should.equal 'Foo' denormalized.image.should.equal '/local/additional_images/4e7cb83e1c80dd00010038e2/1/larger.jpg' denormalized.partner.name.should.equal 'MOMA' denormalized.partner.slug.should.equal 'moma' denormalized.artists[0].name.should.equal '<NAME>' denormalized.artists[0].slug.should.equal 'andy-warhol' denormalized.width.should.equal 1000 denormalized.height.should.equal 585 denormalized.credit.should.equal 'Sourced from ARS'
true
_ = require 'underscore' Backbone = require 'backbone' Artwork = require '../../models/artwork.coffee' sinon = require 'sinon' { fabricate } = require '@artsy/antigravity' describe "Artwork", -> beforeEach -> sinon.stub Backbone, 'sync' @artwork = new Artwork _.extend {}, fabricate 'artwork', title: 'Foo' date: '1/1/2017' id: 'foo' artists: [ name: 'PI:NAME:<NAME>END_PI' id: 'andy-warhol' ] partner: { name: 'MOMA' default_profile_public: true default_profile_id: 'moma' } afterEach -> Backbone.sync.restore() it 'creates a nice short label for the artwork', -> @artwork.truncatedLabel().should.equal 'A.W. Foo, 1/1/2017' it 'denormalizes artworks', -> denormalized = @artwork.denormalized() denormalized.type.should.equal 'artwork' denormalized.id.should.equal '564be09ab202a319e90000e2' denormalized.slug.should.equal 'foo' denormalized.date.should.equal '1/1/2017' denormalized.title.should.equal 'Foo' denormalized.image.should.equal '/local/additional_images/4e7cb83e1c80dd00010038e2/1/larger.jpg' denormalized.partner.name.should.equal 'MOMA' denormalized.partner.slug.should.equal 'moma' denormalized.artists[0].name.should.equal 'PI:NAME:<NAME>END_PI' denormalized.artists[0].slug.should.equal 'andy-warhol' denormalized.width.should.equal 1000 denormalized.height.should.equal 585 denormalized.credit.should.equal 'Sourced from ARS'
[ { "context": " email: \"system\" }, { email: \"system\", password: \"ph06ahyoVble\" }, (err, user) ->\n throw err if err\n conso", "end": 4436, "score": 0.9990240931510925, "start": 4424, "tag": "PASSWORD", "value": "ph06ahyoVble" } ]
find_objects.coffee
ovcharik/TravelFoot
5
_ = require 'underscore' HTTP = require 'http' URL = require 'url' Mongoose = require 'mongoose' findOrCreate = require 'mongoose-findorcreate' requestOptions = { protocol: "http", hostname: "psearch-maps.yandex.ru", port: 80, pathname: "/1.x/" } requestQuery = { format: "json", results: "100", ll: "61.407778,55.160556", spn: "0.5,0.5", rspn: "1" } queries = { sight: [ "памятник", "фонтан" ], place: [ "парк" ], religion: [ "мечеть", "церковь", "синагога" ], culture: [ "музей", "театр" ] } Schema = Mongoose.Schema ObjectId = Schema.ObjectId userSchema = new Schema { email: { type: String, required: true, unique: true }, password: { type: String, required: true } } placeSchema = new Schema { name: { type: String, required: true }, description: { type: String }, coord: { type: [Number], index: '2dsphere', required: true }, kind: { type: String }, address: { city: { type: String }, street: { type: String }, house: { type: String } }, images: [{ url: { type: String } }], owner: { type: ObjectId, ref: 'User' } tags: [{ type: ObjectId, ref: 'Tag' }] } tagSchema = new Schema { value: { type: String, required: true, unique: true } places: [{ type: ObjectId, ref: 'Place', unique: true }] } placeSchema.plugin findOrCreate userSchema.plugin findOrCreate tagSchema.plugin findOrCreate Place = Mongoose.model 'Place', placeSchema User = Mongoose.model 'User', userSchema Tag = Mongoose.model 'Tag', tagSchema # functions querySearch = (queryStr, callback) -> options = _.clone requestOptions options.query = _.clone requestQuery options.query.text = queryStr url = URL.format options console.log url HTTP.get url, (res) => res.setEncoding 'utf8' body = "" res.on 'data', (data) -> body += data res.on 'end', -> json = JSON.parse body if json.error console.log "Error:", queryStr, json.error else callback json.response.GeoObjectCollection.featureMember findObjectsStack = 0 findObjects = (group, word) -> findObjectsStack += 1 querySearch word, (objects) -> for object in objects when object["GeoObject"] newPlace object["GeoObject"], group, word findObjectsStack -= 1 if findObjectsStack == 0 saveBuffers() newPlace = (ya, kind, query) -> p = {} tags = [query] if ya["metaDataProperty"] and ya["metaDataProperty"]["PSearchObjectMetaData"] if ya["metaDataProperty"]["PSearchObjectMetaData"]["Address"] addr = ya["metaDataProperty"]["PSearchObjectMetaData"]["Address"] p.address = {} p.address.city = addr["locality"] if addr["locality"] p.address.street = addr["thoroughfare"] if addr["thoroughfare"] p.address.house = addr["premiseNumber"] if addr["premiseNumber"] if ya["metaDataProperty"]["PSearchObjectMetaData"]["Tags"] p.tags = [] for tag in ya["metaDataProperty"]["PSearchObjectMetaData"]["Tags"] when tag.tag? tags.push tag.tag p.description = ya["description"] if ya["description"] p.name = ya["name"] p.coord = ya["Point"]["pos"].split(" ") p.kind = kind place = new Place(p) addPlace place, tags globalOwner = undefined placesBuffer = [] addPlace = (place, tags) -> p = new Place place for t in tags tag = getTag(t) tag.places.push p._id p.tags.push tag._id p.owner = globalOwner._id if globalOwner placesBuffer.push p tagsBuffer = {} getTag = (tag) -> if tagsBuffer[tag] tagsBuffer[tag] else t = new Tag { value: tag, places: [] } tagsBuffer[tag] = t t saveBuffers = -> c = 0 for p in placesBuffer c += 1 p.save (err, p) -> c -= 1 throw err if err console.log p if c == 0 printInfo() for i, t of tagsBuffer c += 1 t.save (err, t) -> c -= 1 throw err if err console.log t if c == 0 printInfo() printInfo = -> console.log "Count of places: #{placesBuffer.length}\n" console.log "Tags:" counter = 0 for i, v of tagsBuffer counter++ console.log "\t#{counter}: #{i}" console.log "done" Mongoose.connection.close() # main Mongoose.connect 'mongodb://localhost/travel_foot', (err) -> throw err if err User.findOrCreate { email: "system" }, { email: "system", password: "ph06ahyoVble" }, (err, user) -> throw err if err console.log user globalOwner = user for group, words of queries for word in words findObjects group, word
102846
_ = require 'underscore' HTTP = require 'http' URL = require 'url' Mongoose = require 'mongoose' findOrCreate = require 'mongoose-findorcreate' requestOptions = { protocol: "http", hostname: "psearch-maps.yandex.ru", port: 80, pathname: "/1.x/" } requestQuery = { format: "json", results: "100", ll: "61.407778,55.160556", spn: "0.5,0.5", rspn: "1" } queries = { sight: [ "памятник", "фонтан" ], place: [ "парк" ], religion: [ "мечеть", "церковь", "синагога" ], culture: [ "музей", "театр" ] } Schema = Mongoose.Schema ObjectId = Schema.ObjectId userSchema = new Schema { email: { type: String, required: true, unique: true }, password: { type: String, required: true } } placeSchema = new Schema { name: { type: String, required: true }, description: { type: String }, coord: { type: [Number], index: '2dsphere', required: true }, kind: { type: String }, address: { city: { type: String }, street: { type: String }, house: { type: String } }, images: [{ url: { type: String } }], owner: { type: ObjectId, ref: 'User' } tags: [{ type: ObjectId, ref: 'Tag' }] } tagSchema = new Schema { value: { type: String, required: true, unique: true } places: [{ type: ObjectId, ref: 'Place', unique: true }] } placeSchema.plugin findOrCreate userSchema.plugin findOrCreate tagSchema.plugin findOrCreate Place = Mongoose.model 'Place', placeSchema User = Mongoose.model 'User', userSchema Tag = Mongoose.model 'Tag', tagSchema # functions querySearch = (queryStr, callback) -> options = _.clone requestOptions options.query = _.clone requestQuery options.query.text = queryStr url = URL.format options console.log url HTTP.get url, (res) => res.setEncoding 'utf8' body = "" res.on 'data', (data) -> body += data res.on 'end', -> json = JSON.parse body if json.error console.log "Error:", queryStr, json.error else callback json.response.GeoObjectCollection.featureMember findObjectsStack = 0 findObjects = (group, word) -> findObjectsStack += 1 querySearch word, (objects) -> for object in objects when object["GeoObject"] newPlace object["GeoObject"], group, word findObjectsStack -= 1 if findObjectsStack == 0 saveBuffers() newPlace = (ya, kind, query) -> p = {} tags = [query] if ya["metaDataProperty"] and ya["metaDataProperty"]["PSearchObjectMetaData"] if ya["metaDataProperty"]["PSearchObjectMetaData"]["Address"] addr = ya["metaDataProperty"]["PSearchObjectMetaData"]["Address"] p.address = {} p.address.city = addr["locality"] if addr["locality"] p.address.street = addr["thoroughfare"] if addr["thoroughfare"] p.address.house = addr["premiseNumber"] if addr["premiseNumber"] if ya["metaDataProperty"]["PSearchObjectMetaData"]["Tags"] p.tags = [] for tag in ya["metaDataProperty"]["PSearchObjectMetaData"]["Tags"] when tag.tag? tags.push tag.tag p.description = ya["description"] if ya["description"] p.name = ya["name"] p.coord = ya["Point"]["pos"].split(" ") p.kind = kind place = new Place(p) addPlace place, tags globalOwner = undefined placesBuffer = [] addPlace = (place, tags) -> p = new Place place for t in tags tag = getTag(t) tag.places.push p._id p.tags.push tag._id p.owner = globalOwner._id if globalOwner placesBuffer.push p tagsBuffer = {} getTag = (tag) -> if tagsBuffer[tag] tagsBuffer[tag] else t = new Tag { value: tag, places: [] } tagsBuffer[tag] = t t saveBuffers = -> c = 0 for p in placesBuffer c += 1 p.save (err, p) -> c -= 1 throw err if err console.log p if c == 0 printInfo() for i, t of tagsBuffer c += 1 t.save (err, t) -> c -= 1 throw err if err console.log t if c == 0 printInfo() printInfo = -> console.log "Count of places: #{placesBuffer.length}\n" console.log "Tags:" counter = 0 for i, v of tagsBuffer counter++ console.log "\t#{counter}: #{i}" console.log "done" Mongoose.connection.close() # main Mongoose.connect 'mongodb://localhost/travel_foot', (err) -> throw err if err User.findOrCreate { email: "system" }, { email: "system", password: "<PASSWORD>" }, (err, user) -> throw err if err console.log user globalOwner = user for group, words of queries for word in words findObjects group, word
true
_ = require 'underscore' HTTP = require 'http' URL = require 'url' Mongoose = require 'mongoose' findOrCreate = require 'mongoose-findorcreate' requestOptions = { protocol: "http", hostname: "psearch-maps.yandex.ru", port: 80, pathname: "/1.x/" } requestQuery = { format: "json", results: "100", ll: "61.407778,55.160556", spn: "0.5,0.5", rspn: "1" } queries = { sight: [ "памятник", "фонтан" ], place: [ "парк" ], religion: [ "мечеть", "церковь", "синагога" ], culture: [ "музей", "театр" ] } Schema = Mongoose.Schema ObjectId = Schema.ObjectId userSchema = new Schema { email: { type: String, required: true, unique: true }, password: { type: String, required: true } } placeSchema = new Schema { name: { type: String, required: true }, description: { type: String }, coord: { type: [Number], index: '2dsphere', required: true }, kind: { type: String }, address: { city: { type: String }, street: { type: String }, house: { type: String } }, images: [{ url: { type: String } }], owner: { type: ObjectId, ref: 'User' } tags: [{ type: ObjectId, ref: 'Tag' }] } tagSchema = new Schema { value: { type: String, required: true, unique: true } places: [{ type: ObjectId, ref: 'Place', unique: true }] } placeSchema.plugin findOrCreate userSchema.plugin findOrCreate tagSchema.plugin findOrCreate Place = Mongoose.model 'Place', placeSchema User = Mongoose.model 'User', userSchema Tag = Mongoose.model 'Tag', tagSchema # functions querySearch = (queryStr, callback) -> options = _.clone requestOptions options.query = _.clone requestQuery options.query.text = queryStr url = URL.format options console.log url HTTP.get url, (res) => res.setEncoding 'utf8' body = "" res.on 'data', (data) -> body += data res.on 'end', -> json = JSON.parse body if json.error console.log "Error:", queryStr, json.error else callback json.response.GeoObjectCollection.featureMember findObjectsStack = 0 findObjects = (group, word) -> findObjectsStack += 1 querySearch word, (objects) -> for object in objects when object["GeoObject"] newPlace object["GeoObject"], group, word findObjectsStack -= 1 if findObjectsStack == 0 saveBuffers() newPlace = (ya, kind, query) -> p = {} tags = [query] if ya["metaDataProperty"] and ya["metaDataProperty"]["PSearchObjectMetaData"] if ya["metaDataProperty"]["PSearchObjectMetaData"]["Address"] addr = ya["metaDataProperty"]["PSearchObjectMetaData"]["Address"] p.address = {} p.address.city = addr["locality"] if addr["locality"] p.address.street = addr["thoroughfare"] if addr["thoroughfare"] p.address.house = addr["premiseNumber"] if addr["premiseNumber"] if ya["metaDataProperty"]["PSearchObjectMetaData"]["Tags"] p.tags = [] for tag in ya["metaDataProperty"]["PSearchObjectMetaData"]["Tags"] when tag.tag? tags.push tag.tag p.description = ya["description"] if ya["description"] p.name = ya["name"] p.coord = ya["Point"]["pos"].split(" ") p.kind = kind place = new Place(p) addPlace place, tags globalOwner = undefined placesBuffer = [] addPlace = (place, tags) -> p = new Place place for t in tags tag = getTag(t) tag.places.push p._id p.tags.push tag._id p.owner = globalOwner._id if globalOwner placesBuffer.push p tagsBuffer = {} getTag = (tag) -> if tagsBuffer[tag] tagsBuffer[tag] else t = new Tag { value: tag, places: [] } tagsBuffer[tag] = t t saveBuffers = -> c = 0 for p in placesBuffer c += 1 p.save (err, p) -> c -= 1 throw err if err console.log p if c == 0 printInfo() for i, t of tagsBuffer c += 1 t.save (err, t) -> c -= 1 throw err if err console.log t if c == 0 printInfo() printInfo = -> console.log "Count of places: #{placesBuffer.length}\n" console.log "Tags:" counter = 0 for i, v of tagsBuffer counter++ console.log "\t#{counter}: #{i}" console.log "done" Mongoose.connection.close() # main Mongoose.connect 'mongodb://localhost/travel_foot', (err) -> throw err if err User.findOrCreate { email: "system" }, { email: "system", password: "PI:PASSWORD:<PASSWORD>END_PI" }, (err, user) -> throw err if err console.log user globalOwner = user for group, words of queries for word in words findObjects group, word
[ { "context": "\": \"1234-567\"\n \"Authors\": [\n {\n \"Name\": \"Ryan Clark\"\n \"OrganizationName\": \"Arizona Geological Su", "end": 286, "score": 0.9998311996459961, "start": 276, "tag": "NAME", "value": "Ryan Clark" }, { "context": " \"Phone\": \"520-209-413...
src/samples/records.coffee
usgin/metadata-server
0
validRecord = "Title": "The title of the resource" "Description": "The has-to-be-at-least-fifty-characters description of the resource. I think this is long enough" "PublicationDate": "2012-01-01T00:00:00" "ResourceId": "1234-567" "Authors": [ { "Name": "Ryan Clark" "OrganizationName": "Arizona Geological Survey" "ContactInformation": "Phone": "520-209-4139" "email": "ryan.clark@azgs.az.gov" "Address": "Street": "416 W. Congress St. Ste. 100" "City": "Tucson" "State": "AZ" "Zip": "85701" } ] "Keywords": [ "one", "two", "three" ] "GeographicExtent": "NorthBound": 89 "SouthBound": -89 "EastBound": 179 "WestBound": -179 "Distributors": [ { "Name": "Ryan Clark" "OrganizationName": "Arizona Geological Survey" "ContactInformation": "Phone": "520-209-4139" "email": "ryan.clark@azgs.az.gov" "Address": "Street": "416 W. Congress St. Ste. 100" "City": "Tucson" "State": "AZ" "Zip": "85701" } ] "Links": [ ] "Collections": [ ] "Published": true
123912
validRecord = "Title": "The title of the resource" "Description": "The has-to-be-at-least-fifty-characters description of the resource. I think this is long enough" "PublicationDate": "2012-01-01T00:00:00" "ResourceId": "1234-567" "Authors": [ { "Name": "<NAME>" "OrganizationName": "Arizona Geological Survey" "ContactInformation": "Phone": "520-209-4139" "email": "<EMAIL>" "Address": "Street": "416 W. Congress St. Ste. 100" "City": "Tucson" "State": "AZ" "Zip": "85701" } ] "Keywords": [ "one", "two", "three" ] "GeographicExtent": "NorthBound": 89 "SouthBound": -89 "EastBound": 179 "WestBound": -179 "Distributors": [ { "Name": "<NAME>" "OrganizationName": "Arizona Geological Survey" "ContactInformation": "Phone": "520-209-4139" "email": "<EMAIL>" "Address": "Street": "416 W. Congress St. Ste. 100" "City": "Tucson" "State": "AZ" "Zip": "85701" } ] "Links": [ ] "Collections": [ ] "Published": true
true
validRecord = "Title": "The title of the resource" "Description": "The has-to-be-at-least-fifty-characters description of the resource. I think this is long enough" "PublicationDate": "2012-01-01T00:00:00" "ResourceId": "1234-567" "Authors": [ { "Name": "PI:NAME:<NAME>END_PI" "OrganizationName": "Arizona Geological Survey" "ContactInformation": "Phone": "520-209-4139" "email": "PI:EMAIL:<EMAIL>END_PI" "Address": "Street": "416 W. Congress St. Ste. 100" "City": "Tucson" "State": "AZ" "Zip": "85701" } ] "Keywords": [ "one", "two", "three" ] "GeographicExtent": "NorthBound": 89 "SouthBound": -89 "EastBound": 179 "WestBound": -179 "Distributors": [ { "Name": "PI:NAME:<NAME>END_PI" "OrganizationName": "Arizona Geological Survey" "ContactInformation": "Phone": "520-209-4139" "email": "PI:EMAIL:<EMAIL>END_PI" "Address": "Street": "416 W. Congress St. Ste. 100" "City": "Tucson" "State": "AZ" "Zip": "85701" } ] "Links": [ ] "Collections": [ ] "Published": true
[ { "context": "##\n#\n# Copyright 2014 Netflix, Inc.\n#\n# Licensed under the Apache Licen", "end": 26, "score": 0.8756380081176758, "start": 23, "tag": "NAME", "value": "Net" } ]
web-ui/public/coffee/inviso.coffee
krishnachaitanyareddy/inviso
162
## # # Copyright 2014 Netflix, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ## class @Inviso constructor: (args) -> @apps = mr1: new MapReduce1() mr2: new MapReduce2() @search = results: ko.observableArray([]) index: 0 total: 0 searching: ko.observable(false) columns: searchFields reset: => @search.results([]) @search.index = 0 @search.total = 0 $('.search-result').empty() canSearch: -> !@searching() && @index < @total @loading = total: ko.observable(0) complete: ko.observable(0) @workflows = ko.observableArray([]) @cluster = selected: ko.observable() start: ko.observable() end: ko.observable() refresh: ko.observable(60000) tooltip: {} $.get('template/cluster-tooltip.html', (source) => @cluster.tooltip.app = Handlebars.compile(source); ) closeWorkflow: (workflow)->
74835
## # # Copyright 2014 <NAME>flix, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ## class @Inviso constructor: (args) -> @apps = mr1: new MapReduce1() mr2: new MapReduce2() @search = results: ko.observableArray([]) index: 0 total: 0 searching: ko.observable(false) columns: searchFields reset: => @search.results([]) @search.index = 0 @search.total = 0 $('.search-result').empty() canSearch: -> !@searching() && @index < @total @loading = total: ko.observable(0) complete: ko.observable(0) @workflows = ko.observableArray([]) @cluster = selected: ko.observable() start: ko.observable() end: ko.observable() refresh: ko.observable(60000) tooltip: {} $.get('template/cluster-tooltip.html', (source) => @cluster.tooltip.app = Handlebars.compile(source); ) closeWorkflow: (workflow)->
true
## # # Copyright 2014 PI:NAME:<NAME>END_PIflix, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ## class @Inviso constructor: (args) -> @apps = mr1: new MapReduce1() mr2: new MapReduce2() @search = results: ko.observableArray([]) index: 0 total: 0 searching: ko.observable(false) columns: searchFields reset: => @search.results([]) @search.index = 0 @search.total = 0 $('.search-result').empty() canSearch: -> !@searching() && @index < @total @loading = total: ko.observable(0) complete: ko.observable(0) @workflows = ko.observableArray([]) @cluster = selected: ko.observable() start: ko.observable() end: ko.observable() refresh: ko.observable(60000) tooltip: {} $.get('template/cluster-tooltip.html', (source) => @cluster.tooltip.app = Handlebars.compile(source); ) closeWorkflow: (workflow)->
[ { "context": "tModules.like(likeElms, {\n csrfToken: \"foobar\",\n likeText: \"foo like ({count})\",\n ", "end": 796, "score": 0.5025344491004944, "start": 790, "tag": "PASSWORD", "value": "foobar" } ]
game/static/spirit/scripts/test/suites/like-spec.coffee
Yoann-Vie/esgi-hearthstone
3
describe "like plugin tests", -> likeElms = null likes = null post = null responseData = null beforeEach -> fixtures = jasmine.getFixtures() fixtures.fixturesPath = 'base/test/fixtures/' loadFixtures('like.html') responseData = {url_create: '/create/foo'} post = spyOn(window, 'fetch') post.and.callFake( -> { then: (func) -> data = func({ok: true, json: -> responseData}) return { then: (func) -> func(data) return {catch: -> {then: (func) -> func()}} } }) likeElms = document.querySelectorAll('.js-like') likes = stModules.like(likeElms, { csrfToken: "foobar", likeText: "foo like ({count})", removeLikeText: "foo remove like ({count})" }) it "can create the like", -> post.calls.reset() likeElms[0].click() expect(post.calls.any()).toEqual(true) expect(post.calls.argsFor(0)[0]).toEqual('/foo/create/') expect(post.calls.argsFor(0)[1].body.get('csrfmiddlewaretoken')).toEqual("foobar") it "can create and remove the like", -> # create post.calls.reset() responseData = {url_delete: "/foo/delete/"} likeElms[0].click() expect(post.calls.argsFor(0)[0]).toEqual('/foo/create/') expect(likeElms[0].textContent).toEqual("foo remove like (1)") # remove post.calls.reset() responseData = {url_create: "/foo/create/"} likeElms[0].click() expect(post.calls.argsFor(0)[0]).toEqual('/foo/delete/') expect(likeElms[0].textContent).toEqual("foo like (0)") # create again... and so on... post.calls.reset() responseData = {url_delete: "/foo/delete/"} likeElms[0].click() expect(post.calls.argsFor(0)[0]).toEqual('/foo/create/') expect(likeElms[0].textContent).toEqual("foo remove like (1)") it "will tell about an api change", -> responseData = {unknown: null} likeElms[0].click() expect(likeElms[0].textContent).toEqual("api error") it "prevents from multiple posts while sending", -> post.and.callFake( -> {then: -> {then: -> {catch: -> {then: -> }}}}) likeElms[0].click() # next click should do nothing post.calls.reset() likeElms[0].click() expect(post.calls.any()).toEqual(false) it "prevents the default click behaviour", -> evt = document.createEvent("HTMLEvents") evt.initEvent("click", false, true) stopPropagation = spyOn(evt, 'stopPropagation') preventDefault = spyOn(evt, 'preventDefault') likeElms[0].dispatchEvent(evt) expect(stopPropagation).toHaveBeenCalled() expect(preventDefault).toHaveBeenCalled()
204245
describe "like plugin tests", -> likeElms = null likes = null post = null responseData = null beforeEach -> fixtures = jasmine.getFixtures() fixtures.fixturesPath = 'base/test/fixtures/' loadFixtures('like.html') responseData = {url_create: '/create/foo'} post = spyOn(window, 'fetch') post.and.callFake( -> { then: (func) -> data = func({ok: true, json: -> responseData}) return { then: (func) -> func(data) return {catch: -> {then: (func) -> func()}} } }) likeElms = document.querySelectorAll('.js-like') likes = stModules.like(likeElms, { csrfToken: "<PASSWORD>", likeText: "foo like ({count})", removeLikeText: "foo remove like ({count})" }) it "can create the like", -> post.calls.reset() likeElms[0].click() expect(post.calls.any()).toEqual(true) expect(post.calls.argsFor(0)[0]).toEqual('/foo/create/') expect(post.calls.argsFor(0)[1].body.get('csrfmiddlewaretoken')).toEqual("foobar") it "can create and remove the like", -> # create post.calls.reset() responseData = {url_delete: "/foo/delete/"} likeElms[0].click() expect(post.calls.argsFor(0)[0]).toEqual('/foo/create/') expect(likeElms[0].textContent).toEqual("foo remove like (1)") # remove post.calls.reset() responseData = {url_create: "/foo/create/"} likeElms[0].click() expect(post.calls.argsFor(0)[0]).toEqual('/foo/delete/') expect(likeElms[0].textContent).toEqual("foo like (0)") # create again... and so on... post.calls.reset() responseData = {url_delete: "/foo/delete/"} likeElms[0].click() expect(post.calls.argsFor(0)[0]).toEqual('/foo/create/') expect(likeElms[0].textContent).toEqual("foo remove like (1)") it "will tell about an api change", -> responseData = {unknown: null} likeElms[0].click() expect(likeElms[0].textContent).toEqual("api error") it "prevents from multiple posts while sending", -> post.and.callFake( -> {then: -> {then: -> {catch: -> {then: -> }}}}) likeElms[0].click() # next click should do nothing post.calls.reset() likeElms[0].click() expect(post.calls.any()).toEqual(false) it "prevents the default click behaviour", -> evt = document.createEvent("HTMLEvents") evt.initEvent("click", false, true) stopPropagation = spyOn(evt, 'stopPropagation') preventDefault = spyOn(evt, 'preventDefault') likeElms[0].dispatchEvent(evt) expect(stopPropagation).toHaveBeenCalled() expect(preventDefault).toHaveBeenCalled()
true
describe "like plugin tests", -> likeElms = null likes = null post = null responseData = null beforeEach -> fixtures = jasmine.getFixtures() fixtures.fixturesPath = 'base/test/fixtures/' loadFixtures('like.html') responseData = {url_create: '/create/foo'} post = spyOn(window, 'fetch') post.and.callFake( -> { then: (func) -> data = func({ok: true, json: -> responseData}) return { then: (func) -> func(data) return {catch: -> {then: (func) -> func()}} } }) likeElms = document.querySelectorAll('.js-like') likes = stModules.like(likeElms, { csrfToken: "PI:PASSWORD:<PASSWORD>END_PI", likeText: "foo like ({count})", removeLikeText: "foo remove like ({count})" }) it "can create the like", -> post.calls.reset() likeElms[0].click() expect(post.calls.any()).toEqual(true) expect(post.calls.argsFor(0)[0]).toEqual('/foo/create/') expect(post.calls.argsFor(0)[1].body.get('csrfmiddlewaretoken')).toEqual("foobar") it "can create and remove the like", -> # create post.calls.reset() responseData = {url_delete: "/foo/delete/"} likeElms[0].click() expect(post.calls.argsFor(0)[0]).toEqual('/foo/create/') expect(likeElms[0].textContent).toEqual("foo remove like (1)") # remove post.calls.reset() responseData = {url_create: "/foo/create/"} likeElms[0].click() expect(post.calls.argsFor(0)[0]).toEqual('/foo/delete/') expect(likeElms[0].textContent).toEqual("foo like (0)") # create again... and so on... post.calls.reset() responseData = {url_delete: "/foo/delete/"} likeElms[0].click() expect(post.calls.argsFor(0)[0]).toEqual('/foo/create/') expect(likeElms[0].textContent).toEqual("foo remove like (1)") it "will tell about an api change", -> responseData = {unknown: null} likeElms[0].click() expect(likeElms[0].textContent).toEqual("api error") it "prevents from multiple posts while sending", -> post.and.callFake( -> {then: -> {then: -> {catch: -> {then: -> }}}}) likeElms[0].click() # next click should do nothing post.calls.reset() likeElms[0].click() expect(post.calls.any()).toEqual(false) it "prevents the default click behaviour", -> evt = document.createEvent("HTMLEvents") evt.initEvent("click", false, true) stopPropagation = spyOn(evt, 'stopPropagation') preventDefault = spyOn(evt, 'preventDefault') likeElms[0].dispatchEvent(evt) expect(stopPropagation).toHaveBeenCalled() expect(preventDefault).toHaveBeenCalled()
[ { "context": " = @$localStorage.$default({\n serviceKey: 'uno',\n accessToken: null\n issuedAt: nul", "end": 1588, "score": 0.8033285140991211, "start": 1585, "tag": "KEY", "value": "uno" } ]
ClientApp/app/scripts/controllers/root.coffee
nttcom/apigw-sample-app
1
### Copyright 2015 NTT Communications Corportation, https://developer.ntt.com/ Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You 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. ### 'use strict' ###* # @ngdoc function # @name nttcomApiGatewayWebappApp.controller:RootCtrl # @description # # RootCtrl # Controller of the nttcomApiGatewayWebappApp ### angular.module 'nttcomApiGatewayWebappApp' .controller 'RootCtrl', [ '$scope', '$location', '$localStorage', '$log', 'menuFactory', 'menuList', 'serviceCategoryFactory', class RootCtrl # 'Controller as'表記でも、broadcast/emit/onを使う場合は、$scopeをDIする必要あり constructor: (@$scope, @$location, @$localStorage, @$log, @menuFactory, @menuList, @serviceCategoryFactory) -> @$scope.$on 'menuChanged', this.onMenuChanged @$scope.$on 'serviceChanged', this.onServiceChanged @$scope.$storage = @$localStorage.$default({ serviceKey: 'uno', accessToken: null issuedAt: null expiresIn: null }) copyright: -> year = new Date().getFullYear() "Copyright &copy; #{year} NTT Communications" isMenuSelected: (menuKey) -> @menu?.key is menuKey isServiceSelected: (serviceKey) -> @serviceKey is serviceKey isServiceDisabled: (serviceKey) -> @menu?.isServiceDisabled serviceKey # 子controllerで $scope.$emit 'menuChanged' 時 onMenuChanged: (event, menuKey) => @menu = @menuFactory[menuKey] # 子controllerで $scope.$emit 'serviceChanged' 時 onServiceChanged: (event, serviceKey) => @serviceKey = serviceKey @$scope.$storage.serviceKey = serviceKey # 左メニュークリック時 menuClick: (menuKey) -> @$location.path("/#{menuKey}/#{@$scope.$storage.serviceKey}").search('') angular.element('#menu').offcanvas('hide') return # 右メニュークリック時 serviceClick: (serviceKey) -> return if this.isServiceDisabled(serviceKey) @$scope.$broadcast 'serviceSelected', serviceKey angular.element('#services').offcanvas('hide') return ]
31669
### Copyright 2015 NTT Communications Corportation, https://developer.ntt.com/ Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You 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. ### 'use strict' ###* # @ngdoc function # @name nttcomApiGatewayWebappApp.controller:RootCtrl # @description # # RootCtrl # Controller of the nttcomApiGatewayWebappApp ### angular.module 'nttcomApiGatewayWebappApp' .controller 'RootCtrl', [ '$scope', '$location', '$localStorage', '$log', 'menuFactory', 'menuList', 'serviceCategoryFactory', class RootCtrl # 'Controller as'表記でも、broadcast/emit/onを使う場合は、$scopeをDIする必要あり constructor: (@$scope, @$location, @$localStorage, @$log, @menuFactory, @menuList, @serviceCategoryFactory) -> @$scope.$on 'menuChanged', this.onMenuChanged @$scope.$on 'serviceChanged', this.onServiceChanged @$scope.$storage = @$localStorage.$default({ serviceKey: '<KEY>', accessToken: null issuedAt: null expiresIn: null }) copyright: -> year = new Date().getFullYear() "Copyright &copy; #{year} NTT Communications" isMenuSelected: (menuKey) -> @menu?.key is menuKey isServiceSelected: (serviceKey) -> @serviceKey is serviceKey isServiceDisabled: (serviceKey) -> @menu?.isServiceDisabled serviceKey # 子controllerで $scope.$emit 'menuChanged' 時 onMenuChanged: (event, menuKey) => @menu = @menuFactory[menuKey] # 子controllerで $scope.$emit 'serviceChanged' 時 onServiceChanged: (event, serviceKey) => @serviceKey = serviceKey @$scope.$storage.serviceKey = serviceKey # 左メニュークリック時 menuClick: (menuKey) -> @$location.path("/#{menuKey}/#{@$scope.$storage.serviceKey}").search('') angular.element('#menu').offcanvas('hide') return # 右メニュークリック時 serviceClick: (serviceKey) -> return if this.isServiceDisabled(serviceKey) @$scope.$broadcast 'serviceSelected', serviceKey angular.element('#services').offcanvas('hide') return ]
true
### Copyright 2015 NTT Communications Corportation, https://developer.ntt.com/ Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You 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. ### 'use strict' ###* # @ngdoc function # @name nttcomApiGatewayWebappApp.controller:RootCtrl # @description # # RootCtrl # Controller of the nttcomApiGatewayWebappApp ### angular.module 'nttcomApiGatewayWebappApp' .controller 'RootCtrl', [ '$scope', '$location', '$localStorage', '$log', 'menuFactory', 'menuList', 'serviceCategoryFactory', class RootCtrl # 'Controller as'表記でも、broadcast/emit/onを使う場合は、$scopeをDIする必要あり constructor: (@$scope, @$location, @$localStorage, @$log, @menuFactory, @menuList, @serviceCategoryFactory) -> @$scope.$on 'menuChanged', this.onMenuChanged @$scope.$on 'serviceChanged', this.onServiceChanged @$scope.$storage = @$localStorage.$default({ serviceKey: 'PI:KEY:<KEY>END_PI', accessToken: null issuedAt: null expiresIn: null }) copyright: -> year = new Date().getFullYear() "Copyright &copy; #{year} NTT Communications" isMenuSelected: (menuKey) -> @menu?.key is menuKey isServiceSelected: (serviceKey) -> @serviceKey is serviceKey isServiceDisabled: (serviceKey) -> @menu?.isServiceDisabled serviceKey # 子controllerで $scope.$emit 'menuChanged' 時 onMenuChanged: (event, menuKey) => @menu = @menuFactory[menuKey] # 子controllerで $scope.$emit 'serviceChanged' 時 onServiceChanged: (event, serviceKey) => @serviceKey = serviceKey @$scope.$storage.serviceKey = serviceKey # 左メニュークリック時 menuClick: (menuKey) -> @$location.path("/#{menuKey}/#{@$scope.$storage.serviceKey}").search('') angular.element('#menu').offcanvas('hide') return # 右メニュークリック時 serviceClick: (serviceKey) -> return if this.isServiceDisabled(serviceKey) @$scope.$broadcast 'serviceSelected', serviceKey angular.element('#services').offcanvas('hide') return ]