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": "rentUser: (callback) ->\n @currentUser = name: \"Lance\"\n callback(null, true)\n\n helloWorld: ->\n\n he", "end": 1046, "score": 0.9983656406402588, "start": 1041, "tag": "NAME", "value": "Lance" }, { "context": " renderHelloWorldFromVariable: ->\n @person ...
test/example/app/controllers/server/customController.coffee
jivagoalves/tower
1
class App.CustomController extends Tower.Controller @layout false @respondTo "html", "json", "yaml" @before("setCurrentUser") @resource(type: "App.User") @beforeAction("testOnlyCallback", only: ['testCreateCallback', 'testUpdateCallback']) @beforeAction("testExceptCallback", except: 'testNoCallback') testOnlyCallback: -> @testOnlyCallbackCalled = true testExceptCallback: -> @testExceptCallbackCalled = true testCreateCallback: -> @testCreateCallbackCalled = true @render text: 'testCreateCallback!' testUpdateCallback: -> @testUpdateCallbackCalled = true @render text: 'testUpdateCallback!' testNoCallback: -> @testNoCallbackCalled = true @render text: 'testNoCallback!' testIP: -> @render text: @get('ip') renderUser: -> renderCoffeeKupFromTemplate: -> @render 'index' renderCoffeeKupInline: -> @self = "I'm" @render -> h1 "#{@self} Inline!" setCurrentUser: (callback) -> @currentUser = name: "Lance" callback(null, true) helloWorld: -> helloWorldFile: -> @render file: "#{Tower.root}/test-app/app/views/files/hello", formats: ["html"] conditionalHello: -> if @isStale(lastModified: Time.now.utc.beginningOfDay, etag: ["foo", 123]) @render action: 'helloWorld' conditionalHelloWithRecord: -> record = Struct.new("updatedAt", "cacheKey").new(Time.now.utc.beginningOfDay, "foo/123") if stale?(record) @render action: 'helloWorld' conditionalHelloWithPublicHeader: -> if stale?(lastModified: Time.now.utc.beginningOfDay, etag: ["foo", 123], public: true) @render action: 'helloWorld' conditionalHelloWithPublicHeaderWithRecord: -> record = Struct.new("updatedAt", "cacheKey").new(Time.now.utc.beginningOfDay, "foo/123") if stale?(record, public: true) @render action: 'helloWorld' conditionalHelloWithPublicHeaderAndExpiresAt: -> expiresIn 1.minute if stale?(lastModified: Time.now.utc.beginningOfDay, etag: ["foo", 123], public: true) @render action: 'helloWorld' conditionalHelloWithExpiresIn: -> expiresIn 60.1.seconds @render action: 'helloWorld' conditionalHelloWithExpiresInWithPublic: -> expiresIn 1.minute, public: true @render action: 'helloWorld' conditionalHelloWithExpiresInWithPublicWithMoreKeys: -> expiresIn 1.minute, public: true, 'max-stale' : 5.hours @render action: 'helloWorld' conditionalHelloWithExpiresInWithPublicWithMoreKeysOldSyntax: -> expiresIn 1.minute, public: true, private: null, 'max-stale' : 5.hours @render action: 'helloWorld' conditionalHelloWithExpiresNow: -> expiresNow @render action: 'helloWorld' conditionalHelloWithBangs: -> @render action: 'helloWorld' beforeFilter "handleLastModifiedAndEtags", "only": "conditionalHelloWithBangs" handleLastModifiedAndEtags: -> @freshWhen(lastModified: Time.now.utc.beginningOfDay, etag: [ "foo", 123 ]) # "ported": renderHelloWorld: -> @render template: "test/helloWorld" renderHelloWorldWithLastModifiedSet: -> response.lastModified = Date.new(2008, 10, 10).toTime @render template: "test/helloWorld" # "ported": compatibility renderHelloWorldWithForwardSlash: -> @render template: "/test/helloWorld" # "ported": renderTemplateInTopDirectory: -> @render template: 'shared' # "ported": renderHelloWorldFromVariable: -> @person = "david" @render text: "hello #{@person}" # "ported": renderActionHelloWorld: -> @render action: "helloWorld" renderActionUpcasedHelloWorld: -> @render action: "HelloWorld" renderActionHelloWorldAsString: -> @render "helloWorld" renderActionUpcasedHelloWorldAsString: -> @render "HelloWorld" renderActionHelloWorldWithSymbol: -> @render action: "helloWorld" # "ported": renderTextHelloWorld: -> @render text: "hello world" # "ported": renderTextHelloWorldWithLayout: -> @variableForLayout = ", I'm here!" @render text: "hello world", layout: true helloWorldWithLayoutFalse: -> @render layout: false # "ported": renderFileWithInstanceVariables: -> @secret = 'in the sauce' path = File.join(File.dirname(__FILE__), '../fixtures/test/renderFileWithIvar') @render file: path # "ported": renderFileAsStringWithInstanceVariables: -> @secret = 'in the sauce' path = File.expandPath(File.join(File.dirname(__FILE__), '../fixtures/test/renderFileWithIvar')) @render path # "ported": renderFileNotUsingFullPath: -> @secret = 'in the sauce' @render file: 'test/renderFileWithIvar' renderFileNotUsingFullPathWithDotInPath: -> @secret = 'in the sauce' @render file: 'test/dot.directory/renderFileWithIvar' renderFileUsingPathname: -> @secret = 'in the sauce' @render file: Pathname.new(File.dirname(__FILE__)).join('..', 'fixtures', 'test', 'dot.directory', 'renderFileWithIvar') renderFileFromTemplate: -> @secret = 'in the sauce' @path = File.expandPath(File.join(File.dirname(__FILE__), '../fixtures/test/renderFileWithIvar')) renderFileWithLocals: -> path = File.join(File.dirname(__FILE__), '../fixtures/test/renderFileWithLocals') @render file: path, locals: {secret: 'in the sauce'} renderFileAsStringWithLocals: -> path = File.expandPath(File.join(File.dirname(__FILE__), '../fixtures/test/renderFileWithLocals')) @render path, locals: {secret: 'in the sauce'} accessingRequestInTemplate: -> @render inline: "Hello: <%= request.host %>" accessingLoggerInTemplate: -> @render inline: "<%= logger.class %>" accessingActionNameInTemplate: -> @render inline: "<%= actionName %>" accessingControllerNameInTemplate: -> @render inline: "<%= controllerName %>" # "ported": renderCustomCode: -> @render text: "hello world", status: 404 # "ported": renderTextWithNull: -> @render text: null # "ported": renderTextWithFalse: -> @render text: false renderTextWithResource: -> @render text: Customer.new("David") # "ported": renderNothingWithAppendix: -> @render text: "appended" renderLineOffset: -> @render inline: '<% raise %>', locals: {foo: 'bar'} heading: -> @head "ok" greeting: -> # let's just rely on the template # "ported": blankResponse: -> @render text: ' ' # "ported": layoutTest: -> @render action: "helloWorld" # "ported": builderLayoutTest: -> @name = null @render action: "hello", layout: "layouts/builder" # "move": test this in Action View builderPartialTest: -> @render action: "helloWorldContainer" # "ported": partialsList: -> @testUnchanged = 'hello' @customers = [ Customer.new("david"), Customer.new("mary") ] @render action: "list" partialOnly: -> @render partial: true helloInA_string: -> @customers = [ Customer.new("david"), Customer.new("mary") ] @render text: "How's there? " + renderToString(template: "test/list") accessingParamsInTemplate: -> @render inline: 'Hello: <%= params["name"] %>' accessingLocalAssignsInInlineTemplate: -> name = params["localName"] @render inline: "<%= 'Goodbye, ' + localName %>", locals: { localName: name } renderImplicitHtmlTemplateFromXhrRequest: -> renderImplicitJsTemplateWithoutLayout: -> formattedHtmlErb: -> formattedXmlErb: -> renderToStringTest: -> @foo = renderToString inline: "this is a test" defaultRender: -> @alternateDefaultRender ||= null if @alternateDefaultRender @alternateDefaultRender.call else super renderActionHelloWorldAsSymbol: -> @render action: "helloWorld" layoutTestWithDifferentLayout: -> @render action: "helloWorld", layout: "standard" layoutTestWithDifferentLayoutAndStringAction: -> @render "helloWorld", layout: "standard" layoutTestWithDifferentLayoutAndSymbolAction: -> @render "helloWorld", layout: "standard" renderingWithoutLayout: -> @render action: "helloWorld", layout: false layoutOverridingLayout: -> @render action: "helloWorld", layout: "standard" renderingNothingOnLayout: -> @render nothing: true renderToStringWithAssigns: -> @before = "i'm before the render" renderToString text: "foo" @after = "i'm after the render" @render template: "test/helloWorld" renderToStringWithException: -> renderToString file: "exception that will not be caught - this will certainly not work" renderToStringWithCaughtException: -> @before = "i'm before the render" try renderToString file: "exception that will be caught- hope my future instance vars still work!" catch error @after = "i'm after the render" @render template: "test/helloWorld" accessingParamsInTemplateWithLayout: -> @render layout: true, inline: 'Hello: <%= params["name"] %>' # "ported": renderWithExplicitTemplate: -> @render template: "test/helloWorld" renderWithExplicitUnescapedTemplate: -> @render template: "test/h*lloWorld" renderWithExplicitEscapedTemplate: -> @render template: "test/hello,world" renderWithExplicitStringTemplate: -> @render "test/helloWorld" renderWithExplicitStringTemplateAsAction: -> @render "helloWorld" # "ported": renderWithExplicitTemplateWithLocals: -> @render template: "test/renderFileWithLocals", locals: { secret: 'area51' } # "ported": doubleRender: -> @render text: "hello" @render text: "world" doubleRedirect: -> @redirectTo action: "doubleRender" @redirectTo action: "doubleRender" renderAndRedirect: -> @render text: "hello" redirectTo action: "doubleRender" renderToStringAndRender: -> @stuff = renderToString text: "here is some cached stuff" @render text: "Hi web users! #{@stuff}" renderToStringWithInlineAndRender: -> renderToString inline: "<%= 'dlrow olleh'.reverse %>" @render template: "test/helloWorld" renderingWithConflictingLocalVars: -> @name = "David" @render action: "potentialConflicts" helloWorldFromRxmlUsingAction: -> @render action: "helloWorldFromRxml", handlers: ["builder"] # "deprecated": helloWorldFromRxmlUsingTemplate: -> @render template: "test/helloWorldFromRxml", handlers: ["builder"] actionTalkToLayout: -> # Action template sets variable that's picked up by layout # "addressed": renderTextWithAssigns: -> @hello = "world" @render text: "foo" yieldContentFor: -> @render action: "contentFor", layout: "yield" renderContentTypeFromBody: -> response.contentType = Mime: "RSS" @render text: "hello world!" headWithLocationHeader: -> head location: "/foo" headWithLocationObject: -> head location: Customer.new("david", 1) headWithSymbolicStatus: -> head status: params["status"].intern headWithIntegerStatus: -> head status: params["status"].toI headWithStringStatus: -> head status: params["status"] headWithCustomHeader: -> head xCustomHeader: "something" headWithWwwAuthenticateHeader: -> head 'WWW-Authenticate' : 'something' headWithStatusCodeFirst: -> head "forbidden", xCustomHeader: "something" renderUsingLayoutAroundBlock: -> @render action: "usingLayoutAroundBlock" renderUsingLayoutAroundBlockInMainLayoutAndWithinContentForLayout: -> @render action: "usingLayoutAroundBlock", layout: "layouts/blockWithLayout" partialFormatsHtml: -> @render partial: 'partial', formats: ["html"] partial: -> @render partial: 'partial' renderToStringWithPartial: -> @partialOnly = renderToString partial: "partialOnly" @partialWithLocals = renderToString partial: "customer", locals: { customer: Customer.new("david") } @render template: "test/helloWorld" partialWithCounter: -> @render partial: "counter", locals: { counterCounter: 5 } partialWithLocals: -> @render partial: "customer", locals: { customer: Customer.new("david") } partialWithFormBuilder: -> @render partial: ActionView: "Helpers": "FormBuilder".new("post", null, viewContext, {}, Proc.new {}) partialWithFormBuilderSubclass: -> @render partial: LabellingFormBuilder.new("post", null, viewContext, {}, Proc.new {}) partialCollection: -> @render partial: "customer", collection: [ Customer.new("david"), Customer.new("mary") ] partialCollectionWithAs: -> @render partial: "customerWithVar", collection: [ Customer.new("david"), Customer.new("mary") ], as: "customer" partialCollectionWithCounter: -> @render partial: "customerCounter", collection: [ Customer.new("david"), Customer.new("mary") ] partialCollectionWithAsAndCounter: -> @render partial: "customerCounterWithAs", collection: [ Customer.new("david"), Customer.new("mary") ], as: "client" partialCollectionWithLocals: -> @render partial: "customerGreeting", collection: [ Customer.new("david"), Customer.new("mary") ], locals: { greeting: "Bonjour" } partialCollectionWithSpacer: -> @render partial: "customer", spacerTemplate: "partialOnly", collection: [ Customer.new("david"), Customer.new("mary") ] partialCollectionShorthandWithLocals: -> @render partial: [ Customer.new("david"), Customer.new("mary") ], locals: { greeting: "Bonjour" } partialCollectionShorthandWithDifferentTypesOfRecords: -> @render partial: [ BadCustomer.new("mark"), GoodCustomer.new("craig"), BadCustomer.new("john"), GoodCustomer.new("zach"), GoodCustomer.new("brandon"), BadCustomer.new("dan") ], locals: { greeting: "Bonjour" } emptyPartialCollection: -> @render partial: "customer", collection: [] partialCollectionShorthandWithDifferentTypesOfRecordsWithCounter: -> partialCollectionShorthandWithDifferentTypesOfRecords missingPartial: -> @render partial: 'thisFileIsntHere' partialWithHashObject: -> @render partial: "hashObject", object: {firstName: "Sam"} partialWithNestedObject: -> @render partial: "quiz/questions/question", object: Quiz: "Question".new("first") partialWithNestedObjectShorthand: -> @render Quiz: "Question".new("first") partialHashCollection: -> @render partial: "hashObject", collection: [ {firstName: "Pratik"}, {firstName: "Amy"} ] partialHashCollectionWithLocals: -> @render partial: "hashGreeting", collection: [ {firstName: "Pratik"}, {firstName: "Amy"} ], locals: { greeting: "Hola" } partialWithImplicitLocalAssignment: -> @customer = Customer.new("Marcel") @render partial: "customer" renderCallToPartialWithLayout: -> @render action: "callingPartialWithLayout" renderCallToPartialWithLayoutInMainLayoutAndWithinContentForLayout: -> @render action: "callingPartialWithLayout", layout: "layouts/partialWithLayout" # Ensure that the before filter is executed *before* self.formats is set. renderWithFilters: -> @render action: "formattedXmlErb" ## JSON renderJsonNull: -> @render json: null renderJsonRenderToString: -> @render text: renderToString(json: '[]') renderJsonHelloWorld: -> @render json: JSON.stringify(hello: 'world') renderJsonHelloWorldWithParams: -> @render json: JSON.stringify(hello: @params.hello) renderJsonHelloWorldWithStatus: -> @render json: JSON.stringify(hello: 'world'), status: 401 renderJsonHelloWorldWithCallback: -> @render json: JSON.stringify(hello: 'world'), callback: 'alert' renderJsonWithCustomContentType: -> @render json: JSON.stringify(hello: 'world'), contentType: 'text/javascript' renderSymbolJson: -> @render json: JSON.stringify(hello: 'world') renderJsonWithRenderToString: -> @render json: {hello: @renderToString(partial: 'partial')} htmlXmlOrRss: -> @respondTo (type) => type.html => @render text: "HTML" type.xml => @render text: "XML" type.rss => @render text: "RSS" type.all => @render text: "Nothing" jsOrHtml: -> @respondTo (type) => type.html => @render text: "HTML" type.js => @render text: "JS" type.all => @render text: "Nothing" jsonOrYaml: -> @respondTo (type) -> type.json => @render text: "JSON!" type.yaml => @render text: "YAML!" htmlOrXml: -> @respondTo (type) -> type.html => @render text: "HTML" type.xml => @render text: "XML" type.all => @render text: "Nothing" jsonXmlOrHtml: -> @respondTo (type) -> type.json => @render text: 'JSON' type.xml => @render xml: 'XML' type.html => @render text: 'HTML' forcedXml: -> @request.format = "xml" @respondTo (type) -> type.html => @render text: "HTML" type.xml => @render text: "XML" justXml: -> @respondTo (type) -> type.xml => @render text: "XML" usingDefaults: -> @respondTo (type) -> type.html() type.xml() usingDefaultsWithTypeList: -> respondTo("html", "xml") madeForContentType: -> @respondTo (type) -> type.rss => @render text: "RSS" type.atom => @render text: "ATOM" type.all => @render text: "Nothing" customTypeHandling: -> @respondTo (type) -> type.html => @render text: "HTML" type.all => @render text: "Nothing" customConstantHandling: -> @respondTo (type) -> type.html => @render text: "HTML" type.mobile => @render text: "Mobile" customConstantHandlingWithoutBlock: -> @respondTo (type) -> type.html => @render text: "HTML" type.mobile() handleAny: -> @respondTo (type) -> type.html => @render text: "HTML" type.any "js", "xml", => @render text: "Either JS or XML" handleAnyAny: -> @respondTo (type) -> type.html => @render text: 'HTML' type.any => @render text: 'Whatever you ask for, I got it' allTypesWithLayout: -> @respondTo (type) -> type.html()
69360
class App.CustomController extends Tower.Controller @layout false @respondTo "html", "json", "yaml" @before("setCurrentUser") @resource(type: "App.User") @beforeAction("testOnlyCallback", only: ['testCreateCallback', 'testUpdateCallback']) @beforeAction("testExceptCallback", except: 'testNoCallback') testOnlyCallback: -> @testOnlyCallbackCalled = true testExceptCallback: -> @testExceptCallbackCalled = true testCreateCallback: -> @testCreateCallbackCalled = true @render text: 'testCreateCallback!' testUpdateCallback: -> @testUpdateCallbackCalled = true @render text: 'testUpdateCallback!' testNoCallback: -> @testNoCallbackCalled = true @render text: 'testNoCallback!' testIP: -> @render text: @get('ip') renderUser: -> renderCoffeeKupFromTemplate: -> @render 'index' renderCoffeeKupInline: -> @self = "I'm" @render -> h1 "#{@self} Inline!" setCurrentUser: (callback) -> @currentUser = name: "<NAME>" callback(null, true) helloWorld: -> helloWorldFile: -> @render file: "#{Tower.root}/test-app/app/views/files/hello", formats: ["html"] conditionalHello: -> if @isStale(lastModified: Time.now.utc.beginningOfDay, etag: ["foo", 123]) @render action: 'helloWorld' conditionalHelloWithRecord: -> record = Struct.new("updatedAt", "cacheKey").new(Time.now.utc.beginningOfDay, "foo/123") if stale?(record) @render action: 'helloWorld' conditionalHelloWithPublicHeader: -> if stale?(lastModified: Time.now.utc.beginningOfDay, etag: ["foo", 123], public: true) @render action: 'helloWorld' conditionalHelloWithPublicHeaderWithRecord: -> record = Struct.new("updatedAt", "cacheKey").new(Time.now.utc.beginningOfDay, "foo/123") if stale?(record, public: true) @render action: 'helloWorld' conditionalHelloWithPublicHeaderAndExpiresAt: -> expiresIn 1.minute if stale?(lastModified: Time.now.utc.beginningOfDay, etag: ["foo", 123], public: true) @render action: 'helloWorld' conditionalHelloWithExpiresIn: -> expiresIn 60.1.seconds @render action: 'helloWorld' conditionalHelloWithExpiresInWithPublic: -> expiresIn 1.minute, public: true @render action: 'helloWorld' conditionalHelloWithExpiresInWithPublicWithMoreKeys: -> expiresIn 1.minute, public: true, 'max-stale' : 5.hours @render action: 'helloWorld' conditionalHelloWithExpiresInWithPublicWithMoreKeysOldSyntax: -> expiresIn 1.minute, public: true, private: null, 'max-stale' : 5.hours @render action: 'helloWorld' conditionalHelloWithExpiresNow: -> expiresNow @render action: 'helloWorld' conditionalHelloWithBangs: -> @render action: 'helloWorld' beforeFilter "handleLastModifiedAndEtags", "only": "conditionalHelloWithBangs" handleLastModifiedAndEtags: -> @freshWhen(lastModified: Time.now.utc.beginningOfDay, etag: [ "foo", 123 ]) # "ported": renderHelloWorld: -> @render template: "test/helloWorld" renderHelloWorldWithLastModifiedSet: -> response.lastModified = Date.new(2008, 10, 10).toTime @render template: "test/helloWorld" # "ported": compatibility renderHelloWorldWithForwardSlash: -> @render template: "/test/helloWorld" # "ported": renderTemplateInTopDirectory: -> @render template: 'shared' # "ported": renderHelloWorldFromVariable: -> @person = "<NAME>" @render text: "hello #{@person}" # "ported": renderActionHelloWorld: -> @render action: "helloWorld" renderActionUpcasedHelloWorld: -> @render action: "HelloWorld" renderActionHelloWorldAsString: -> @render "helloWorld" renderActionUpcasedHelloWorldAsString: -> @render "HelloWorld" renderActionHelloWorldWithSymbol: -> @render action: "helloWorld" # "ported": renderTextHelloWorld: -> @render text: "hello world" # "ported": renderTextHelloWorldWithLayout: -> @variableForLayout = ", I'm here!" @render text: "hello world", layout: true helloWorldWithLayoutFalse: -> @render layout: false # "ported": renderFileWithInstanceVariables: -> @secret = 'in the sauce' path = File.join(File.dirname(__FILE__), '../fixtures/test/renderFileWithIvar') @render file: path # "ported": renderFileAsStringWithInstanceVariables: -> @secret = 'in the sauce' path = File.expandPath(File.join(File.dirname(__FILE__), '../fixtures/test/renderFileWithIvar')) @render path # "ported": renderFileNotUsingFullPath: -> @secret = 'in the sauce' @render file: 'test/renderFileWithIvar' renderFileNotUsingFullPathWithDotInPath: -> @secret = 'in the sauce' @render file: 'test/dot.directory/renderFileWithIvar' renderFileUsingPathname: -> @secret = 'in the sauce' @render file: Pathname.new(File.dirname(__FILE__)).join('..', 'fixtures', 'test', 'dot.directory', 'renderFileWithIvar') renderFileFromTemplate: -> @secret = 'in the sauce' @path = File.expandPath(File.join(File.dirname(__FILE__), '../fixtures/test/renderFileWithIvar')) renderFileWithLocals: -> path = File.join(File.dirname(__FILE__), '../fixtures/test/renderFileWithLocals') @render file: path, locals: {secret: 'in the sauce'} renderFileAsStringWithLocals: -> path = File.expandPath(File.join(File.dirname(__FILE__), '../fixtures/test/renderFileWithLocals')) @render path, locals: {secret: 'in the sauce'} accessingRequestInTemplate: -> @render inline: "Hello: <%= request.host %>" accessingLoggerInTemplate: -> @render inline: "<%= logger.class %>" accessingActionNameInTemplate: -> @render inline: "<%= actionName %>" accessingControllerNameInTemplate: -> @render inline: "<%= controllerName %>" # "ported": renderCustomCode: -> @render text: "hello world", status: 404 # "ported": renderTextWithNull: -> @render text: null # "ported": renderTextWithFalse: -> @render text: false renderTextWithResource: -> @render text: Customer.new("<NAME>") # "ported": renderNothingWithAppendix: -> @render text: "appended" renderLineOffset: -> @render inline: '<% raise %>', locals: {foo: 'bar'} heading: -> @head "ok" greeting: -> # let's just rely on the template # "ported": blankResponse: -> @render text: ' ' # "ported": layoutTest: -> @render action: "helloWorld" # "ported": builderLayoutTest: -> @name = null @render action: "hello", layout: "layouts/builder" # "move": test this in Action View builderPartialTest: -> @render action: "helloWorldContainer" # "ported": partialsList: -> @testUnchanged = 'hello' @customers = [ Customer.new("<NAME>"), Customer.new("<NAME>") ] @render action: "list" partialOnly: -> @render partial: true helloInA_string: -> @customers = [ Customer.new("<NAME>"), Customer.new("<NAME>") ] @render text: "How's there? " + renderToString(template: "test/list") accessingParamsInTemplate: -> @render inline: 'Hello: <%= params["name"] %>' accessingLocalAssignsInInlineTemplate: -> name = params["localName"] @render inline: "<%= 'Goodbye, ' + localName %>", locals: { localName: name } renderImplicitHtmlTemplateFromXhrRequest: -> renderImplicitJsTemplateWithoutLayout: -> formattedHtmlErb: -> formattedXmlErb: -> renderToStringTest: -> @foo = renderToString inline: "this is a test" defaultRender: -> @alternateDefaultRender ||= null if @alternateDefaultRender @alternateDefaultRender.call else super renderActionHelloWorldAsSymbol: -> @render action: "helloWorld" layoutTestWithDifferentLayout: -> @render action: "helloWorld", layout: "standard" layoutTestWithDifferentLayoutAndStringAction: -> @render "helloWorld", layout: "standard" layoutTestWithDifferentLayoutAndSymbolAction: -> @render "helloWorld", layout: "standard" renderingWithoutLayout: -> @render action: "helloWorld", layout: false layoutOverridingLayout: -> @render action: "helloWorld", layout: "standard" renderingNothingOnLayout: -> @render nothing: true renderToStringWithAssigns: -> @before = "i'm before the render" renderToString text: "foo" @after = "i'm after the render" @render template: "test/helloWorld" renderToStringWithException: -> renderToString file: "exception that will not be caught - this will certainly not work" renderToStringWithCaughtException: -> @before = "i'm before the render" try renderToString file: "exception that will be caught- hope my future instance vars still work!" catch error @after = "i'm after the render" @render template: "test/helloWorld" accessingParamsInTemplateWithLayout: -> @render layout: true, inline: 'Hello: <%= params["name"] %>' # "ported": renderWithExplicitTemplate: -> @render template: "test/helloWorld" renderWithExplicitUnescapedTemplate: -> @render template: "test/h*lloWorld" renderWithExplicitEscapedTemplate: -> @render template: "test/hello,world" renderWithExplicitStringTemplate: -> @render "test/helloWorld" renderWithExplicitStringTemplateAsAction: -> @render "helloWorld" # "ported": renderWithExplicitTemplateWithLocals: -> @render template: "test/renderFileWithLocals", locals: { secret: 'area51' } # "ported": doubleRender: -> @render text: "hello" @render text: "world" doubleRedirect: -> @redirectTo action: "doubleRender" @redirectTo action: "doubleRender" renderAndRedirect: -> @render text: "hello" redirectTo action: "doubleRender" renderToStringAndRender: -> @stuff = renderToString text: "here is some cached stuff" @render text: "Hi web users! #{@stuff}" renderToStringWithInlineAndRender: -> renderToString inline: "<%= 'dlrow olleh'.reverse %>" @render template: "test/helloWorld" renderingWithConflictingLocalVars: -> @name = "<NAME>" @render action: "potentialConflicts" helloWorldFromRxmlUsingAction: -> @render action: "helloWorldFromRxml", handlers: ["builder"] # "deprecated": helloWorldFromRxmlUsingTemplate: -> @render template: "test/helloWorldFromRxml", handlers: ["builder"] actionTalkToLayout: -> # Action template sets variable that's picked up by layout # "addressed": renderTextWithAssigns: -> @hello = "world" @render text: "foo" yieldContentFor: -> @render action: "contentFor", layout: "yield" renderContentTypeFromBody: -> response.contentType = Mime: "RSS" @render text: "hello world!" headWithLocationHeader: -> head location: "/foo" headWithLocationObject: -> head location: Customer.new("david", 1) headWithSymbolicStatus: -> head status: params["status"].intern headWithIntegerStatus: -> head status: params["status"].toI headWithStringStatus: -> head status: params["status"] headWithCustomHeader: -> head xCustomHeader: "something" headWithWwwAuthenticateHeader: -> head 'WWW-Authenticate' : 'something' headWithStatusCodeFirst: -> head "forbidden", xCustomHeader: "something" renderUsingLayoutAroundBlock: -> @render action: "usingLayoutAroundBlock" renderUsingLayoutAroundBlockInMainLayoutAndWithinContentForLayout: -> @render action: "usingLayoutAroundBlock", layout: "layouts/blockWithLayout" partialFormatsHtml: -> @render partial: 'partial', formats: ["html"] partial: -> @render partial: 'partial' renderToStringWithPartial: -> @partialOnly = renderToString partial: "partialOnly" @partialWithLocals = renderToString partial: "customer", locals: { customer: Customer.new("<NAME>") } @render template: "test/helloWorld" partialWithCounter: -> @render partial: "counter", locals: { counterCounter: 5 } partialWithLocals: -> @render partial: "customer", locals: { customer: Customer.new("<NAME>") } partialWithFormBuilder: -> @render partial: ActionView: "Helpers": "FormBuilder".new("post", null, viewContext, {}, Proc.new {}) partialWithFormBuilderSubclass: -> @render partial: LabellingFormBuilder.new("post", null, viewContext, {}, Proc.new {}) partialCollection: -> @render partial: "customer", collection: [ Customer.new("<NAME>"), Customer.new("<NAME>") ] partialCollectionWithAs: -> @render partial: "customerWithVar", collection: [ Customer.new("<NAME>"), Customer.new("<NAME>") ], as: "customer" partialCollectionWithCounter: -> @render partial: "customerCounter", collection: [ Customer.new("<NAME>"), Customer.new("<NAME>") ] partialCollectionWithAsAndCounter: -> @render partial: "customerCounterWithAs", collection: [ Customer.new("<NAME>"), Customer.new("<NAME>") ], as: "client" partialCollectionWithLocals: -> @render partial: "customerGreeting", collection: [ Customer.new("<NAME>"), Customer.new("<NAME>") ], locals: { greeting: "Bonjour" } partialCollectionWithSpacer: -> @render partial: "customer", spacerTemplate: "partialOnly", collection: [ Customer.new("<NAME>"), Customer.new("<NAME>") ] partialCollectionShorthandWithLocals: -> @render partial: [ Customer.new("<NAME>"), Customer.new("<NAME>") ], locals: { greeting: "Bonjour" } partialCollectionShorthandWithDifferentTypesOfRecords: -> @render partial: [ BadCustomer.new("<NAME>"), GoodCustomer.new("<NAME> <NAME>"), BadCustomer.new("<NAME>"), GoodCustomer.new("<NAME>"), GoodCustomer.new("<NAME>"), BadCustomer.new("<NAME>") ], locals: { greeting: "<NAME>" } emptyPartialCollection: -> @render partial: "customer", collection: [] partialCollectionShorthandWithDifferentTypesOfRecordsWithCounter: -> partialCollectionShorthandWithDifferentTypesOfRecords missingPartial: -> @render partial: 'thisFileIsntHere' partialWithHashObject: -> @render partial: "hashObject", object: {firstName: "<NAME>"} partialWithNestedObject: -> @render partial: "quiz/questions/question", object: Quiz: "Question".new("first") partialWithNestedObjectShorthand: -> @render Quiz: "Question".new("first") partialHashCollection: -> @render partial: "hashObject", collection: [ {firstName: "<NAME>"}, {firstName: "<NAME>"} ] partialHashCollectionWithLocals: -> @render partial: "hashGreeting", collection: [ {firstName: "<NAME>"}, {firstName: "<NAME>"} ], locals: { greeting: "<NAME>" } partialWithImplicitLocalAssignment: -> @customer = Customer.new("<NAME>") @render partial: "customer" renderCallToPartialWithLayout: -> @render action: "callingPartialWithLayout" renderCallToPartialWithLayoutInMainLayoutAndWithinContentForLayout: -> @render action: "callingPartialWithLayout", layout: "layouts/partialWithLayout" # Ensure that the before filter is executed *before* self.formats is set. renderWithFilters: -> @render action: "formattedXmlErb" ## JSON renderJsonNull: -> @render json: null renderJsonRenderToString: -> @render text: renderToString(json: '[]') renderJsonHelloWorld: -> @render json: JSON.stringify(hello: 'world') renderJsonHelloWorldWithParams: -> @render json: JSON.stringify(hello: @params.hello) renderJsonHelloWorldWithStatus: -> @render json: JSON.stringify(hello: 'world'), status: 401 renderJsonHelloWorldWithCallback: -> @render json: JSON.stringify(hello: 'world'), callback: 'alert' renderJsonWithCustomContentType: -> @render json: JSON.stringify(hello: 'world'), contentType: 'text/javascript' renderSymbolJson: -> @render json: JSON.stringify(hello: 'world') renderJsonWithRenderToString: -> @render json: {hello: @renderToString(partial: 'partial')} htmlXmlOrRss: -> @respondTo (type) => type.html => @render text: "HTML" type.xml => @render text: "XML" type.rss => @render text: "RSS" type.all => @render text: "Nothing" jsOrHtml: -> @respondTo (type) => type.html => @render text: "HTML" type.js => @render text: "JS" type.all => @render text: "Nothing" jsonOrYaml: -> @respondTo (type) -> type.json => @render text: "JSON!" type.yaml => @render text: "YAML!" htmlOrXml: -> @respondTo (type) -> type.html => @render text: "HTML" type.xml => @render text: "XML" type.all => @render text: "Nothing" jsonXmlOrHtml: -> @respondTo (type) -> type.json => @render text: 'JSON' type.xml => @render xml: 'XML' type.html => @render text: 'HTML' forcedXml: -> @request.format = "xml" @respondTo (type) -> type.html => @render text: "HTML" type.xml => @render text: "XML" justXml: -> @respondTo (type) -> type.xml => @render text: "XML" usingDefaults: -> @respondTo (type) -> type.html() type.xml() usingDefaultsWithTypeList: -> respondTo("html", "xml") madeForContentType: -> @respondTo (type) -> type.rss => @render text: "RSS" type.atom => @render text: "ATOM" type.all => @render text: "Nothing" customTypeHandling: -> @respondTo (type) -> type.html => @render text: "HTML" type.all => @render text: "Nothing" customConstantHandling: -> @respondTo (type) -> type.html => @render text: "HTML" type.mobile => @render text: "Mobile" customConstantHandlingWithoutBlock: -> @respondTo (type) -> type.html => @render text: "HTML" type.mobile() handleAny: -> @respondTo (type) -> type.html => @render text: "HTML" type.any "js", "xml", => @render text: "Either JS or XML" handleAnyAny: -> @respondTo (type) -> type.html => @render text: 'HTML' type.any => @render text: 'Whatever you ask for, I got it' allTypesWithLayout: -> @respondTo (type) -> type.html()
true
class App.CustomController extends Tower.Controller @layout false @respondTo "html", "json", "yaml" @before("setCurrentUser") @resource(type: "App.User") @beforeAction("testOnlyCallback", only: ['testCreateCallback', 'testUpdateCallback']) @beforeAction("testExceptCallback", except: 'testNoCallback') testOnlyCallback: -> @testOnlyCallbackCalled = true testExceptCallback: -> @testExceptCallbackCalled = true testCreateCallback: -> @testCreateCallbackCalled = true @render text: 'testCreateCallback!' testUpdateCallback: -> @testUpdateCallbackCalled = true @render text: 'testUpdateCallback!' testNoCallback: -> @testNoCallbackCalled = true @render text: 'testNoCallback!' testIP: -> @render text: @get('ip') renderUser: -> renderCoffeeKupFromTemplate: -> @render 'index' renderCoffeeKupInline: -> @self = "I'm" @render -> h1 "#{@self} Inline!" setCurrentUser: (callback) -> @currentUser = name: "PI:NAME:<NAME>END_PI" callback(null, true) helloWorld: -> helloWorldFile: -> @render file: "#{Tower.root}/test-app/app/views/files/hello", formats: ["html"] conditionalHello: -> if @isStale(lastModified: Time.now.utc.beginningOfDay, etag: ["foo", 123]) @render action: 'helloWorld' conditionalHelloWithRecord: -> record = Struct.new("updatedAt", "cacheKey").new(Time.now.utc.beginningOfDay, "foo/123") if stale?(record) @render action: 'helloWorld' conditionalHelloWithPublicHeader: -> if stale?(lastModified: Time.now.utc.beginningOfDay, etag: ["foo", 123], public: true) @render action: 'helloWorld' conditionalHelloWithPublicHeaderWithRecord: -> record = Struct.new("updatedAt", "cacheKey").new(Time.now.utc.beginningOfDay, "foo/123") if stale?(record, public: true) @render action: 'helloWorld' conditionalHelloWithPublicHeaderAndExpiresAt: -> expiresIn 1.minute if stale?(lastModified: Time.now.utc.beginningOfDay, etag: ["foo", 123], public: true) @render action: 'helloWorld' conditionalHelloWithExpiresIn: -> expiresIn 60.1.seconds @render action: 'helloWorld' conditionalHelloWithExpiresInWithPublic: -> expiresIn 1.minute, public: true @render action: 'helloWorld' conditionalHelloWithExpiresInWithPublicWithMoreKeys: -> expiresIn 1.minute, public: true, 'max-stale' : 5.hours @render action: 'helloWorld' conditionalHelloWithExpiresInWithPublicWithMoreKeysOldSyntax: -> expiresIn 1.minute, public: true, private: null, 'max-stale' : 5.hours @render action: 'helloWorld' conditionalHelloWithExpiresNow: -> expiresNow @render action: 'helloWorld' conditionalHelloWithBangs: -> @render action: 'helloWorld' beforeFilter "handleLastModifiedAndEtags", "only": "conditionalHelloWithBangs" handleLastModifiedAndEtags: -> @freshWhen(lastModified: Time.now.utc.beginningOfDay, etag: [ "foo", 123 ]) # "ported": renderHelloWorld: -> @render template: "test/helloWorld" renderHelloWorldWithLastModifiedSet: -> response.lastModified = Date.new(2008, 10, 10).toTime @render template: "test/helloWorld" # "ported": compatibility renderHelloWorldWithForwardSlash: -> @render template: "/test/helloWorld" # "ported": renderTemplateInTopDirectory: -> @render template: 'shared' # "ported": renderHelloWorldFromVariable: -> @person = "PI:NAME:<NAME>END_PI" @render text: "hello #{@person}" # "ported": renderActionHelloWorld: -> @render action: "helloWorld" renderActionUpcasedHelloWorld: -> @render action: "HelloWorld" renderActionHelloWorldAsString: -> @render "helloWorld" renderActionUpcasedHelloWorldAsString: -> @render "HelloWorld" renderActionHelloWorldWithSymbol: -> @render action: "helloWorld" # "ported": renderTextHelloWorld: -> @render text: "hello world" # "ported": renderTextHelloWorldWithLayout: -> @variableForLayout = ", I'm here!" @render text: "hello world", layout: true helloWorldWithLayoutFalse: -> @render layout: false # "ported": renderFileWithInstanceVariables: -> @secret = 'in the sauce' path = File.join(File.dirname(__FILE__), '../fixtures/test/renderFileWithIvar') @render file: path # "ported": renderFileAsStringWithInstanceVariables: -> @secret = 'in the sauce' path = File.expandPath(File.join(File.dirname(__FILE__), '../fixtures/test/renderFileWithIvar')) @render path # "ported": renderFileNotUsingFullPath: -> @secret = 'in the sauce' @render file: 'test/renderFileWithIvar' renderFileNotUsingFullPathWithDotInPath: -> @secret = 'in the sauce' @render file: 'test/dot.directory/renderFileWithIvar' renderFileUsingPathname: -> @secret = 'in the sauce' @render file: Pathname.new(File.dirname(__FILE__)).join('..', 'fixtures', 'test', 'dot.directory', 'renderFileWithIvar') renderFileFromTemplate: -> @secret = 'in the sauce' @path = File.expandPath(File.join(File.dirname(__FILE__), '../fixtures/test/renderFileWithIvar')) renderFileWithLocals: -> path = File.join(File.dirname(__FILE__), '../fixtures/test/renderFileWithLocals') @render file: path, locals: {secret: 'in the sauce'} renderFileAsStringWithLocals: -> path = File.expandPath(File.join(File.dirname(__FILE__), '../fixtures/test/renderFileWithLocals')) @render path, locals: {secret: 'in the sauce'} accessingRequestInTemplate: -> @render inline: "Hello: <%= request.host %>" accessingLoggerInTemplate: -> @render inline: "<%= logger.class %>" accessingActionNameInTemplate: -> @render inline: "<%= actionName %>" accessingControllerNameInTemplate: -> @render inline: "<%= controllerName %>" # "ported": renderCustomCode: -> @render text: "hello world", status: 404 # "ported": renderTextWithNull: -> @render text: null # "ported": renderTextWithFalse: -> @render text: false renderTextWithResource: -> @render text: Customer.new("PI:NAME:<NAME>END_PI") # "ported": renderNothingWithAppendix: -> @render text: "appended" renderLineOffset: -> @render inline: '<% raise %>', locals: {foo: 'bar'} heading: -> @head "ok" greeting: -> # let's just rely on the template # "ported": blankResponse: -> @render text: ' ' # "ported": layoutTest: -> @render action: "helloWorld" # "ported": builderLayoutTest: -> @name = null @render action: "hello", layout: "layouts/builder" # "move": test this in Action View builderPartialTest: -> @render action: "helloWorldContainer" # "ported": partialsList: -> @testUnchanged = 'hello' @customers = [ Customer.new("PI:NAME:<NAME>END_PI"), Customer.new("PI:NAME:<NAME>END_PI") ] @render action: "list" partialOnly: -> @render partial: true helloInA_string: -> @customers = [ Customer.new("PI:NAME:<NAME>END_PI"), Customer.new("PI:NAME:<NAME>END_PI") ] @render text: "How's there? " + renderToString(template: "test/list") accessingParamsInTemplate: -> @render inline: 'Hello: <%= params["name"] %>' accessingLocalAssignsInInlineTemplate: -> name = params["localName"] @render inline: "<%= 'Goodbye, ' + localName %>", locals: { localName: name } renderImplicitHtmlTemplateFromXhrRequest: -> renderImplicitJsTemplateWithoutLayout: -> formattedHtmlErb: -> formattedXmlErb: -> renderToStringTest: -> @foo = renderToString inline: "this is a test" defaultRender: -> @alternateDefaultRender ||= null if @alternateDefaultRender @alternateDefaultRender.call else super renderActionHelloWorldAsSymbol: -> @render action: "helloWorld" layoutTestWithDifferentLayout: -> @render action: "helloWorld", layout: "standard" layoutTestWithDifferentLayoutAndStringAction: -> @render "helloWorld", layout: "standard" layoutTestWithDifferentLayoutAndSymbolAction: -> @render "helloWorld", layout: "standard" renderingWithoutLayout: -> @render action: "helloWorld", layout: false layoutOverridingLayout: -> @render action: "helloWorld", layout: "standard" renderingNothingOnLayout: -> @render nothing: true renderToStringWithAssigns: -> @before = "i'm before the render" renderToString text: "foo" @after = "i'm after the render" @render template: "test/helloWorld" renderToStringWithException: -> renderToString file: "exception that will not be caught - this will certainly not work" renderToStringWithCaughtException: -> @before = "i'm before the render" try renderToString file: "exception that will be caught- hope my future instance vars still work!" catch error @after = "i'm after the render" @render template: "test/helloWorld" accessingParamsInTemplateWithLayout: -> @render layout: true, inline: 'Hello: <%= params["name"] %>' # "ported": renderWithExplicitTemplate: -> @render template: "test/helloWorld" renderWithExplicitUnescapedTemplate: -> @render template: "test/h*lloWorld" renderWithExplicitEscapedTemplate: -> @render template: "test/hello,world" renderWithExplicitStringTemplate: -> @render "test/helloWorld" renderWithExplicitStringTemplateAsAction: -> @render "helloWorld" # "ported": renderWithExplicitTemplateWithLocals: -> @render template: "test/renderFileWithLocals", locals: { secret: 'area51' } # "ported": doubleRender: -> @render text: "hello" @render text: "world" doubleRedirect: -> @redirectTo action: "doubleRender" @redirectTo action: "doubleRender" renderAndRedirect: -> @render text: "hello" redirectTo action: "doubleRender" renderToStringAndRender: -> @stuff = renderToString text: "here is some cached stuff" @render text: "Hi web users! #{@stuff}" renderToStringWithInlineAndRender: -> renderToString inline: "<%= 'dlrow olleh'.reverse %>" @render template: "test/helloWorld" renderingWithConflictingLocalVars: -> @name = "PI:NAME:<NAME>END_PI" @render action: "potentialConflicts" helloWorldFromRxmlUsingAction: -> @render action: "helloWorldFromRxml", handlers: ["builder"] # "deprecated": helloWorldFromRxmlUsingTemplate: -> @render template: "test/helloWorldFromRxml", handlers: ["builder"] actionTalkToLayout: -> # Action template sets variable that's picked up by layout # "addressed": renderTextWithAssigns: -> @hello = "world" @render text: "foo" yieldContentFor: -> @render action: "contentFor", layout: "yield" renderContentTypeFromBody: -> response.contentType = Mime: "RSS" @render text: "hello world!" headWithLocationHeader: -> head location: "/foo" headWithLocationObject: -> head location: Customer.new("david", 1) headWithSymbolicStatus: -> head status: params["status"].intern headWithIntegerStatus: -> head status: params["status"].toI headWithStringStatus: -> head status: params["status"] headWithCustomHeader: -> head xCustomHeader: "something" headWithWwwAuthenticateHeader: -> head 'WWW-Authenticate' : 'something' headWithStatusCodeFirst: -> head "forbidden", xCustomHeader: "something" renderUsingLayoutAroundBlock: -> @render action: "usingLayoutAroundBlock" renderUsingLayoutAroundBlockInMainLayoutAndWithinContentForLayout: -> @render action: "usingLayoutAroundBlock", layout: "layouts/blockWithLayout" partialFormatsHtml: -> @render partial: 'partial', formats: ["html"] partial: -> @render partial: 'partial' renderToStringWithPartial: -> @partialOnly = renderToString partial: "partialOnly" @partialWithLocals = renderToString partial: "customer", locals: { customer: Customer.new("PI:NAME:<NAME>END_PI") } @render template: "test/helloWorld" partialWithCounter: -> @render partial: "counter", locals: { counterCounter: 5 } partialWithLocals: -> @render partial: "customer", locals: { customer: Customer.new("PI:NAME:<NAME>END_PI") } partialWithFormBuilder: -> @render partial: ActionView: "Helpers": "FormBuilder".new("post", null, viewContext, {}, Proc.new {}) partialWithFormBuilderSubclass: -> @render partial: LabellingFormBuilder.new("post", null, viewContext, {}, Proc.new {}) partialCollection: -> @render partial: "customer", collection: [ Customer.new("PI:NAME:<NAME>END_PI"), Customer.new("PI:NAME:<NAME>END_PI") ] partialCollectionWithAs: -> @render partial: "customerWithVar", collection: [ Customer.new("PI:NAME:<NAME>END_PI"), Customer.new("PI:NAME:<NAME>END_PI") ], as: "customer" partialCollectionWithCounter: -> @render partial: "customerCounter", collection: [ Customer.new("PI:NAME:<NAME>END_PI"), Customer.new("PI:NAME:<NAME>END_PI") ] partialCollectionWithAsAndCounter: -> @render partial: "customerCounterWithAs", collection: [ Customer.new("PI:NAME:<NAME>END_PI"), Customer.new("PI:NAME:<NAME>END_PI") ], as: "client" partialCollectionWithLocals: -> @render partial: "customerGreeting", collection: [ Customer.new("PI:NAME:<NAME>END_PI"), Customer.new("PI:NAME:<NAME>END_PI") ], locals: { greeting: "Bonjour" } partialCollectionWithSpacer: -> @render partial: "customer", spacerTemplate: "partialOnly", collection: [ Customer.new("PI:NAME:<NAME>END_PI"), Customer.new("PI:NAME:<NAME>END_PI") ] partialCollectionShorthandWithLocals: -> @render partial: [ Customer.new("PI:NAME:<NAME>END_PI"), Customer.new("PI:NAME:<NAME>END_PI") ], locals: { greeting: "Bonjour" } partialCollectionShorthandWithDifferentTypesOfRecords: -> @render partial: [ BadCustomer.new("PI:NAME:<NAME>END_PI"), GoodCustomer.new("PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI"), BadCustomer.new("PI:NAME:<NAME>END_PI"), GoodCustomer.new("PI:NAME:<NAME>END_PI"), GoodCustomer.new("PI:NAME:<NAME>END_PI"), BadCustomer.new("PI:NAME:<NAME>END_PI") ], locals: { greeting: "PI:NAME:<NAME>END_PI" } emptyPartialCollection: -> @render partial: "customer", collection: [] partialCollectionShorthandWithDifferentTypesOfRecordsWithCounter: -> partialCollectionShorthandWithDifferentTypesOfRecords missingPartial: -> @render partial: 'thisFileIsntHere' partialWithHashObject: -> @render partial: "hashObject", object: {firstName: "PI:NAME:<NAME>END_PI"} partialWithNestedObject: -> @render partial: "quiz/questions/question", object: Quiz: "Question".new("first") partialWithNestedObjectShorthand: -> @render Quiz: "Question".new("first") partialHashCollection: -> @render partial: "hashObject", collection: [ {firstName: "PI:NAME:<NAME>END_PI"}, {firstName: "PI:NAME:<NAME>END_PI"} ] partialHashCollectionWithLocals: -> @render partial: "hashGreeting", collection: [ {firstName: "PI:NAME:<NAME>END_PI"}, {firstName: "PI:NAME:<NAME>END_PI"} ], locals: { greeting: "PI:NAME:<NAME>END_PI" } partialWithImplicitLocalAssignment: -> @customer = Customer.new("PI:NAME:<NAME>END_PI") @render partial: "customer" renderCallToPartialWithLayout: -> @render action: "callingPartialWithLayout" renderCallToPartialWithLayoutInMainLayoutAndWithinContentForLayout: -> @render action: "callingPartialWithLayout", layout: "layouts/partialWithLayout" # Ensure that the before filter is executed *before* self.formats is set. renderWithFilters: -> @render action: "formattedXmlErb" ## JSON renderJsonNull: -> @render json: null renderJsonRenderToString: -> @render text: renderToString(json: '[]') renderJsonHelloWorld: -> @render json: JSON.stringify(hello: 'world') renderJsonHelloWorldWithParams: -> @render json: JSON.stringify(hello: @params.hello) renderJsonHelloWorldWithStatus: -> @render json: JSON.stringify(hello: 'world'), status: 401 renderJsonHelloWorldWithCallback: -> @render json: JSON.stringify(hello: 'world'), callback: 'alert' renderJsonWithCustomContentType: -> @render json: JSON.stringify(hello: 'world'), contentType: 'text/javascript' renderSymbolJson: -> @render json: JSON.stringify(hello: 'world') renderJsonWithRenderToString: -> @render json: {hello: @renderToString(partial: 'partial')} htmlXmlOrRss: -> @respondTo (type) => type.html => @render text: "HTML" type.xml => @render text: "XML" type.rss => @render text: "RSS" type.all => @render text: "Nothing" jsOrHtml: -> @respondTo (type) => type.html => @render text: "HTML" type.js => @render text: "JS" type.all => @render text: "Nothing" jsonOrYaml: -> @respondTo (type) -> type.json => @render text: "JSON!" type.yaml => @render text: "YAML!" htmlOrXml: -> @respondTo (type) -> type.html => @render text: "HTML" type.xml => @render text: "XML" type.all => @render text: "Nothing" jsonXmlOrHtml: -> @respondTo (type) -> type.json => @render text: 'JSON' type.xml => @render xml: 'XML' type.html => @render text: 'HTML' forcedXml: -> @request.format = "xml" @respondTo (type) -> type.html => @render text: "HTML" type.xml => @render text: "XML" justXml: -> @respondTo (type) -> type.xml => @render text: "XML" usingDefaults: -> @respondTo (type) -> type.html() type.xml() usingDefaultsWithTypeList: -> respondTo("html", "xml") madeForContentType: -> @respondTo (type) -> type.rss => @render text: "RSS" type.atom => @render text: "ATOM" type.all => @render text: "Nothing" customTypeHandling: -> @respondTo (type) -> type.html => @render text: "HTML" type.all => @render text: "Nothing" customConstantHandling: -> @respondTo (type) -> type.html => @render text: "HTML" type.mobile => @render text: "Mobile" customConstantHandlingWithoutBlock: -> @respondTo (type) -> type.html => @render text: "HTML" type.mobile() handleAny: -> @respondTo (type) -> type.html => @render text: "HTML" type.any "js", "xml", => @render text: "Either JS or XML" handleAnyAny: -> @respondTo (type) -> type.html => @render text: 'HTML' type.any => @render text: 'Whatever you ask for, I got it' allTypesWithLayout: -> @respondTo (type) -> type.html()
[ { "context": "'\n user: 'sqlclient_test_u'\n password: 'password'\n }\n\n PAUSE = 2\n\n it 'check for database", "end": 771, "score": 0.9994753003120422, "start": 763, "tag": "PASSWORD", "value": "password" } ]
test/test-mysql-client.coffee
intellinote/sql-client
1
fs = require 'fs' path = require 'path' should_continue = true try require('mysql') catch err console.error "" console.error "WARNING: require('mysql') failed with the following error:" console.error err console.error "The tests in #{path.basename(__filename)} will be skipped." console.error "" console.error "You must add the mysql library to your devDependencies to enable" console.error "these tests. See `./test/README.md` for details." console.error "" should_continue = false if should_continue mysql = require( '../lib/mysql-client' ) should = require('should') describe 'MySQL',-> CONNECT_OPTS = { host: 'localhost' user: 'sqlclient_test_u' password: 'password' } PAUSE = 2 it 'check for database',(done)-> database_available = (callback)-> client = new mysql.MySQLClient(CONNECT_OPTS) client.connect (err)-> if err? report_no_database(err) x = 0 console.error "(Pausing for #{PAUSE} seconds to make sure you notice the message.)" console.error "============================================================" console.error "" setTimeout (callback), PAUSE*1000 else client.disconnect (err)-> callback(true) report_no_database = (err)-> console.error "" console.error "============================================================" console.error "!WARNING! COULD NOT CONNECT TO MYSQL DATABASE !WARNING!" console.error "------------------------------------------------------------" console.error "" console.error " The automated functional tests in:" console.error " #{path.basename(__filename)}" console.error " require access to a test account in a MySQL database. " console.error "" console.error " The following error was encountered while trying to" console.error " connect to the database using the connection params:" console.error " #{JSON.stringify(CONNECT_OPTS)}" console.error "" console.error " The specific error encountered was:" console.error " #{err}" console.error " Some unit tests will be skipped because of this error." console.error "" console.error " See the README file at:" console.error " #{path.join(__dirname,'README.md')}" console.error " for instructions on how to set up and configure the test" console.error " database in order to enable these tests." console.error "" console.error "------------------------------------------------------------" database_available (available)-> if available describe 'Client',-> it 'can connect to the database', (done)-> client = new mysql.MySQLClient(CONNECT_OPTS) client.connect (err)-> if err? report_no_database(err) should.not.exist err client.disconnect (err)-> should.not.exist err done() it 'can execute a query (straight sql)', (done)-> client = new mysql.MySQLClient(CONNECT_OPTS) client.connect (err)-> should.not.exist err client.execute "SELECT 17 AS n, NOW() as dt", (err,rows,fields)-> should.not.exist err should.exist rows rows.length.should.equal 1 rows[0].n.should.equal 17 rows[0].dt.should.be.ok client.disconnect (err)-> should.not.exist err done() it 'can execute a query (bind-variables)', (done)-> client = new mysql.MySQLClient(CONNECT_OPTS) client.connect (err)-> should.not.exist err client.execute "SELECT ? AS x", [19], (err,rows,fields)-> should.not.exist err should.exist rows rows.length.should.equal 1 rows[0].x.should.equal 19 client.disconnect (err)-> should.not.exist err done() describe 'ClientPool',-> it 'supports borrow, execute, return pattern (default config)', (done)-> pool = new mysql.MySQLClientPool(CONNECT_OPTS) pool.open (err)-> should.not.exist err pool.borrow (err,client)-> should.not.exist err should.exist client client.execute "SELECT ? AS x, ? AS y", [32,18], (err,rows,fields)-> should.not.exist err should.exist rows rows.length.should.equal 1 rows[0].x.should.equal 32 rows[0].y.should.equal 18 pool.return client, (err)-> should.not.exist err pool.close (err)-> should.not.exist err done() it 'supports borrow, execute, return pattern (max_idle=5,min_idle=3)', (done)-> options = { min_idle:3, max_idle:5 } pool = new mysql.MySQLClientPool(CONNECT_OPTS) pool.open options, (err)-> should.not.exist err pool.borrow (err,client)-> should.not.exist err should.exist client client.execute "SELECT ? AS x, ? AS y", [32,18], (err,rows,fields)-> should.not.exist err should.exist rows rows.length.should.equal 1 rows[0].x.should.equal 32 rows[0].y.should.equal 18 pool.return client, (err)-> should.not.exist err pool.close (err)-> should.not.exist err done() it 'supports borrow, execute, borrow, execute, return, return pattern (default config)', (done)-> pool = new mysql.MySQLClientPool(CONNECT_OPTS) pool.open (err)-> should.not.exist err pool.borrow (err,client1)-> should.not.exist err should.exist client1 client1.execute "SELECT ? AS x, ? AS y", [32,18], (err,rows,fields)-> should.not.exist err should.exist rows rows.length.should.equal 1 rows[0].x.should.equal 32 rows[0].y.should.equal 18 pool.borrow (err,client2)-> should.not.exist err should.exist client2 client2.execute "SELECT ? AS x, ? AS y", [1,5], (err,rows,fields)-> should.not.exist err should.exist rows rows.length.should.equal 1 rows[0].x.should.equal 1 rows[0].y.should.equal 5 pool.return client2, (err)-> should.not.exist err pool.return client1, (err)-> should.not.exist err pool.close (err)-> should.not.exist err done() it 'supports borrow, execute, return, borrow, execute, return pattern (max_idle=1,min_idle=0)', (done)-> options = { max_idle:1,min_idle:0 } pool = new mysql.MySQLClientPool(CONNECT_OPTS) pool.open options,(err)-> should.not.exist err pool.borrow (err,client1)-> should.not.exist err should.exist client1 client1.execute "SELECT ? AS x, ? AS y", [32,18], (err,rows,fields)-> should.not.exist err should.exist rows rows.length.should.equal 1 rows[0].x.should.equal 32 rows[0].y.should.equal 18 pool.return client1, (err)-> should.not.exist err pool.borrow (err,client2)-> should.not.exist err should.exist client2 client2.execute "SELECT ? AS x, ? AS y", [1,5], (err,rows,fields)-> should.not.exist err should.exist rows rows.length.should.equal 1 rows[0].x.should.equal 1 rows[0].y.should.equal 5 pool.return client2, (err)-> should.not.exist err pool.close (err)-> should.not.exist err done() done()
225649
fs = require 'fs' path = require 'path' should_continue = true try require('mysql') catch err console.error "" console.error "WARNING: require('mysql') failed with the following error:" console.error err console.error "The tests in #{path.basename(__filename)} will be skipped." console.error "" console.error "You must add the mysql library to your devDependencies to enable" console.error "these tests. See `./test/README.md` for details." console.error "" should_continue = false if should_continue mysql = require( '../lib/mysql-client' ) should = require('should') describe 'MySQL',-> CONNECT_OPTS = { host: 'localhost' user: 'sqlclient_test_u' password: '<PASSWORD>' } PAUSE = 2 it 'check for database',(done)-> database_available = (callback)-> client = new mysql.MySQLClient(CONNECT_OPTS) client.connect (err)-> if err? report_no_database(err) x = 0 console.error "(Pausing for #{PAUSE} seconds to make sure you notice the message.)" console.error "============================================================" console.error "" setTimeout (callback), PAUSE*1000 else client.disconnect (err)-> callback(true) report_no_database = (err)-> console.error "" console.error "============================================================" console.error "!WARNING! COULD NOT CONNECT TO MYSQL DATABASE !WARNING!" console.error "------------------------------------------------------------" console.error "" console.error " The automated functional tests in:" console.error " #{path.basename(__filename)}" console.error " require access to a test account in a MySQL database. " console.error "" console.error " The following error was encountered while trying to" console.error " connect to the database using the connection params:" console.error " #{JSON.stringify(CONNECT_OPTS)}" console.error "" console.error " The specific error encountered was:" console.error " #{err}" console.error " Some unit tests will be skipped because of this error." console.error "" console.error " See the README file at:" console.error " #{path.join(__dirname,'README.md')}" console.error " for instructions on how to set up and configure the test" console.error " database in order to enable these tests." console.error "" console.error "------------------------------------------------------------" database_available (available)-> if available describe 'Client',-> it 'can connect to the database', (done)-> client = new mysql.MySQLClient(CONNECT_OPTS) client.connect (err)-> if err? report_no_database(err) should.not.exist err client.disconnect (err)-> should.not.exist err done() it 'can execute a query (straight sql)', (done)-> client = new mysql.MySQLClient(CONNECT_OPTS) client.connect (err)-> should.not.exist err client.execute "SELECT 17 AS n, NOW() as dt", (err,rows,fields)-> should.not.exist err should.exist rows rows.length.should.equal 1 rows[0].n.should.equal 17 rows[0].dt.should.be.ok client.disconnect (err)-> should.not.exist err done() it 'can execute a query (bind-variables)', (done)-> client = new mysql.MySQLClient(CONNECT_OPTS) client.connect (err)-> should.not.exist err client.execute "SELECT ? AS x", [19], (err,rows,fields)-> should.not.exist err should.exist rows rows.length.should.equal 1 rows[0].x.should.equal 19 client.disconnect (err)-> should.not.exist err done() describe 'ClientPool',-> it 'supports borrow, execute, return pattern (default config)', (done)-> pool = new mysql.MySQLClientPool(CONNECT_OPTS) pool.open (err)-> should.not.exist err pool.borrow (err,client)-> should.not.exist err should.exist client client.execute "SELECT ? AS x, ? AS y", [32,18], (err,rows,fields)-> should.not.exist err should.exist rows rows.length.should.equal 1 rows[0].x.should.equal 32 rows[0].y.should.equal 18 pool.return client, (err)-> should.not.exist err pool.close (err)-> should.not.exist err done() it 'supports borrow, execute, return pattern (max_idle=5,min_idle=3)', (done)-> options = { min_idle:3, max_idle:5 } pool = new mysql.MySQLClientPool(CONNECT_OPTS) pool.open options, (err)-> should.not.exist err pool.borrow (err,client)-> should.not.exist err should.exist client client.execute "SELECT ? AS x, ? AS y", [32,18], (err,rows,fields)-> should.not.exist err should.exist rows rows.length.should.equal 1 rows[0].x.should.equal 32 rows[0].y.should.equal 18 pool.return client, (err)-> should.not.exist err pool.close (err)-> should.not.exist err done() it 'supports borrow, execute, borrow, execute, return, return pattern (default config)', (done)-> pool = new mysql.MySQLClientPool(CONNECT_OPTS) pool.open (err)-> should.not.exist err pool.borrow (err,client1)-> should.not.exist err should.exist client1 client1.execute "SELECT ? AS x, ? AS y", [32,18], (err,rows,fields)-> should.not.exist err should.exist rows rows.length.should.equal 1 rows[0].x.should.equal 32 rows[0].y.should.equal 18 pool.borrow (err,client2)-> should.not.exist err should.exist client2 client2.execute "SELECT ? AS x, ? AS y", [1,5], (err,rows,fields)-> should.not.exist err should.exist rows rows.length.should.equal 1 rows[0].x.should.equal 1 rows[0].y.should.equal 5 pool.return client2, (err)-> should.not.exist err pool.return client1, (err)-> should.not.exist err pool.close (err)-> should.not.exist err done() it 'supports borrow, execute, return, borrow, execute, return pattern (max_idle=1,min_idle=0)', (done)-> options = { max_idle:1,min_idle:0 } pool = new mysql.MySQLClientPool(CONNECT_OPTS) pool.open options,(err)-> should.not.exist err pool.borrow (err,client1)-> should.not.exist err should.exist client1 client1.execute "SELECT ? AS x, ? AS y", [32,18], (err,rows,fields)-> should.not.exist err should.exist rows rows.length.should.equal 1 rows[0].x.should.equal 32 rows[0].y.should.equal 18 pool.return client1, (err)-> should.not.exist err pool.borrow (err,client2)-> should.not.exist err should.exist client2 client2.execute "SELECT ? AS x, ? AS y", [1,5], (err,rows,fields)-> should.not.exist err should.exist rows rows.length.should.equal 1 rows[0].x.should.equal 1 rows[0].y.should.equal 5 pool.return client2, (err)-> should.not.exist err pool.close (err)-> should.not.exist err done() done()
true
fs = require 'fs' path = require 'path' should_continue = true try require('mysql') catch err console.error "" console.error "WARNING: require('mysql') failed with the following error:" console.error err console.error "The tests in #{path.basename(__filename)} will be skipped." console.error "" console.error "You must add the mysql library to your devDependencies to enable" console.error "these tests. See `./test/README.md` for details." console.error "" should_continue = false if should_continue mysql = require( '../lib/mysql-client' ) should = require('should') describe 'MySQL',-> CONNECT_OPTS = { host: 'localhost' user: 'sqlclient_test_u' password: 'PI:PASSWORD:<PASSWORD>END_PI' } PAUSE = 2 it 'check for database',(done)-> database_available = (callback)-> client = new mysql.MySQLClient(CONNECT_OPTS) client.connect (err)-> if err? report_no_database(err) x = 0 console.error "(Pausing for #{PAUSE} seconds to make sure you notice the message.)" console.error "============================================================" console.error "" setTimeout (callback), PAUSE*1000 else client.disconnect (err)-> callback(true) report_no_database = (err)-> console.error "" console.error "============================================================" console.error "!WARNING! COULD NOT CONNECT TO MYSQL DATABASE !WARNING!" console.error "------------------------------------------------------------" console.error "" console.error " The automated functional tests in:" console.error " #{path.basename(__filename)}" console.error " require access to a test account in a MySQL database. " console.error "" console.error " The following error was encountered while trying to" console.error " connect to the database using the connection params:" console.error " #{JSON.stringify(CONNECT_OPTS)}" console.error "" console.error " The specific error encountered was:" console.error " #{err}" console.error " Some unit tests will be skipped because of this error." console.error "" console.error " See the README file at:" console.error " #{path.join(__dirname,'README.md')}" console.error " for instructions on how to set up and configure the test" console.error " database in order to enable these tests." console.error "" console.error "------------------------------------------------------------" database_available (available)-> if available describe 'Client',-> it 'can connect to the database', (done)-> client = new mysql.MySQLClient(CONNECT_OPTS) client.connect (err)-> if err? report_no_database(err) should.not.exist err client.disconnect (err)-> should.not.exist err done() it 'can execute a query (straight sql)', (done)-> client = new mysql.MySQLClient(CONNECT_OPTS) client.connect (err)-> should.not.exist err client.execute "SELECT 17 AS n, NOW() as dt", (err,rows,fields)-> should.not.exist err should.exist rows rows.length.should.equal 1 rows[0].n.should.equal 17 rows[0].dt.should.be.ok client.disconnect (err)-> should.not.exist err done() it 'can execute a query (bind-variables)', (done)-> client = new mysql.MySQLClient(CONNECT_OPTS) client.connect (err)-> should.not.exist err client.execute "SELECT ? AS x", [19], (err,rows,fields)-> should.not.exist err should.exist rows rows.length.should.equal 1 rows[0].x.should.equal 19 client.disconnect (err)-> should.not.exist err done() describe 'ClientPool',-> it 'supports borrow, execute, return pattern (default config)', (done)-> pool = new mysql.MySQLClientPool(CONNECT_OPTS) pool.open (err)-> should.not.exist err pool.borrow (err,client)-> should.not.exist err should.exist client client.execute "SELECT ? AS x, ? AS y", [32,18], (err,rows,fields)-> should.not.exist err should.exist rows rows.length.should.equal 1 rows[0].x.should.equal 32 rows[0].y.should.equal 18 pool.return client, (err)-> should.not.exist err pool.close (err)-> should.not.exist err done() it 'supports borrow, execute, return pattern (max_idle=5,min_idle=3)', (done)-> options = { min_idle:3, max_idle:5 } pool = new mysql.MySQLClientPool(CONNECT_OPTS) pool.open options, (err)-> should.not.exist err pool.borrow (err,client)-> should.not.exist err should.exist client client.execute "SELECT ? AS x, ? AS y", [32,18], (err,rows,fields)-> should.not.exist err should.exist rows rows.length.should.equal 1 rows[0].x.should.equal 32 rows[0].y.should.equal 18 pool.return client, (err)-> should.not.exist err pool.close (err)-> should.not.exist err done() it 'supports borrow, execute, borrow, execute, return, return pattern (default config)', (done)-> pool = new mysql.MySQLClientPool(CONNECT_OPTS) pool.open (err)-> should.not.exist err pool.borrow (err,client1)-> should.not.exist err should.exist client1 client1.execute "SELECT ? AS x, ? AS y", [32,18], (err,rows,fields)-> should.not.exist err should.exist rows rows.length.should.equal 1 rows[0].x.should.equal 32 rows[0].y.should.equal 18 pool.borrow (err,client2)-> should.not.exist err should.exist client2 client2.execute "SELECT ? AS x, ? AS y", [1,5], (err,rows,fields)-> should.not.exist err should.exist rows rows.length.should.equal 1 rows[0].x.should.equal 1 rows[0].y.should.equal 5 pool.return client2, (err)-> should.not.exist err pool.return client1, (err)-> should.not.exist err pool.close (err)-> should.not.exist err done() it 'supports borrow, execute, return, borrow, execute, return pattern (max_idle=1,min_idle=0)', (done)-> options = { max_idle:1,min_idle:0 } pool = new mysql.MySQLClientPool(CONNECT_OPTS) pool.open options,(err)-> should.not.exist err pool.borrow (err,client1)-> should.not.exist err should.exist client1 client1.execute "SELECT ? AS x, ? AS y", [32,18], (err,rows,fields)-> should.not.exist err should.exist rows rows.length.should.equal 1 rows[0].x.should.equal 32 rows[0].y.should.equal 18 pool.return client1, (err)-> should.not.exist err pool.borrow (err,client2)-> should.not.exist err should.exist client2 client2.execute "SELECT ? AS x, ? AS y", [1,5], (err,rows,fields)-> should.not.exist err should.exist rows rows.length.should.equal 1 rows[0].x.should.equal 1 rows[0].y.should.equal 5 pool.return client2, (err)-> should.not.exist err pool.close (err)-> should.not.exist err done() done()
[ { "context": "ol }, children: [\n { path:'Gauges', name:'Gauges', components:{ Gauges: loader.load('Tools') } },\n", "end": 3341, "score": 0.5503114461898804, "start": 3336, "tag": "NAME", "value": "auges" } ]
src/muse/appl/MuseLD.coffee
axiom6/aug
0
import { tester } from '../../../lib/pub/util/Util.js' import Prin from '../../../data/muse/Prin.json' import Rows from '../../../data/muse/Rows.json' import Info from '../../../data/muse/Info.json' import Know from '../../../data/muse/Know.json' import Wise from '../../../data/muse/Wise.json' #mport Software from '../../../data/inno/Software.json' #mport Data from '../../../data/inno/Data.json' #mport Science from '../../../data/inno/Science.json' #mport Math from '../../../data/inno/Math.json' class MuseLD constructor:( @Home ) -> @site = "http://example.com/" @jsonLD = @toJsonLD(@site) @jsonLDStr = JSON.stringify(@jsonLD) @children = [] toJsonLD:(site) -> jsonLD = {} jsonLD["@context"] = { "principles": "#{site}principles", "refinements": "#{site}refinements", "information": "#{site}information", "knowledge": "#{site}knowledge", "wisdom": "#{site}wisdom" } jsonLD['principles'] = @toPracticesLD(Prin,site) jsonLD['refinements'] = @toPracticesLD(Rows,site) jsonLD['information'] = @toPracticesLD(Info,site) jsonLD['knowledge'] = @toPracticesLD(Know,site) jsonLD['wisdom'] = @toPracticesLD(Wise,site) # console.log( 'MuseLD.toJsonLD()', jsonLD ) jsonLD isChild:( key ) -> tester.isChild(key) toPracLD:( pkey, prac, site ) -> pracLD = {} pracLD["@context"] = { '@type': "#{site}", "name": "#{site}name", "column": "#{site}column", "row": "#{site}row", "plane": "#{site}plane", "description": "#{site}description" } pracLD['@type'] = 'Practice' pracLD.name = pkey pracLD.column = prac.column pracLD.row = prac.row pracLD.plane = prac.plane pracLD.description = prac.desc pracLD toDispLD:( dkey, disp, site ) -> dispLD = {} dispLD["@context"] = { '@type': "#{site}", "name": "#{site}name", "description": "#{site}description" } dispLD['@type'] = 'Discipline' dispLD.name = dkey dispLD.description = disp.desc dispLD toPracticesLD:( data, site ) -> practices = {} for pkey, prac of data when @isChild(pkey) practices[pkey] = @toPracLD( pkey, prac, site ) practices[pkey].disciplines = {} for dkey, disp of prac when @isChild(dkey) practices[pkey].disciplines[dkey] = @toDispLD( dkey, disp, site ) practices @toJsonScript:(jsonLD) -> html = """<script type="application/ld+json">""" html += JSON.stringify(jsonLD) html += """</script""" html ### @AugmRoutes = [ { path: '/', name:'Home', components:{ Home: Home } }, { path: '/math', name:'Math', components:{ Math: Home.Math }, children: [ { path:'ML', name:'MathML', components:{ MathML: loader.load('MathND') } }, { path:'EQ', name:'MathEQ', components:{ MathEQ: loader.load('MathND') } } ] }, { path: '/draw', name:'Draw', components:{ Draw: loader.load('Draw') } }, { path: '/hues', name:'Hues', components:{ Hues: loader.load('Hues') } }, { path: '/tool', name:'Tool', components:{ Tool: Home.Tool }, children: [ { path:'Gauges', name:'Gauges', components:{ Gauges: loader.load('Tools') } }, { path:'Widget', name:'Widget', components:{ Widget: loader.load('Tools') } } ] }, { path: '/cube', name:'Cube', components:{ Cube: loader.load('Cube') } }, { path: '/wood', name:'Wood', components:{ Wood: loader.load('Wood') } } ] Muse.routes = [ { path: '/', name:'Home', components:{ Home: Home } }, { path: '/Prin', name:'Prin', components:{ Prin: Home.Prin } }, { path: '/Comp', name:'Comp', components:{ Comp: Home.Comp } }, { path: '/Prac', name:'Prac', components:{ Prac: Home.Prac } }, { path: '/Disp', name:'Disp', components:{ Disp: Home.Disp } }, { path: '/Cube', name:'Cube', components:{ Cube: Home.Cube } } ] ### toRoutes:() -> comps = [Prin,Info,Know,Wise] routes = [] routes.push( @toPath( '/', 'Home', 'Comp', 'Home' ) ) for comp in comps compName = @toCompName(comp) vueComp = if compName is 'Principles' then 'Home.Prin' else 'Home.Comp' routes.push( @toPath( '/'+compName, compName, 'Parent', vueComp ) ) for pkey, prac of comp when @isChild(pkey) routes.push( @toPath( pkey, pkey, 'Child', 'Home.Prac' ) ) routes.push( @toPath( '/Cube', 'Cube', 'Comp', 'Home.Cube' ) ) routes toPath:( path, name, type, comp ) -> @children = [] if type is 'Parent' route = {} route.path = path route.name = name switch type when 'Comp' route.components = { "#{name}":comp } when 'Parent' route.components = { "#{name}":comp } route.children = @children when 'Child' route.components = { "#{name}":comp } @children.push( route ) route toCompName:( comp ) -> if comp is Prin then 'Principles' else if comp is Info then 'Information' else if comp is Know then 'Knowledge' else if comp is Wise then 'Wisdom' else 'none' export default MuseLD
221974
import { tester } from '../../../lib/pub/util/Util.js' import Prin from '../../../data/muse/Prin.json' import Rows from '../../../data/muse/Rows.json' import Info from '../../../data/muse/Info.json' import Know from '../../../data/muse/Know.json' import Wise from '../../../data/muse/Wise.json' #mport Software from '../../../data/inno/Software.json' #mport Data from '../../../data/inno/Data.json' #mport Science from '../../../data/inno/Science.json' #mport Math from '../../../data/inno/Math.json' class MuseLD constructor:( @Home ) -> @site = "http://example.com/" @jsonLD = @toJsonLD(@site) @jsonLDStr = JSON.stringify(@jsonLD) @children = [] toJsonLD:(site) -> jsonLD = {} jsonLD["@context"] = { "principles": "#{site}principles", "refinements": "#{site}refinements", "information": "#{site}information", "knowledge": "#{site}knowledge", "wisdom": "#{site}wisdom" } jsonLD['principles'] = @toPracticesLD(Prin,site) jsonLD['refinements'] = @toPracticesLD(Rows,site) jsonLD['information'] = @toPracticesLD(Info,site) jsonLD['knowledge'] = @toPracticesLD(Know,site) jsonLD['wisdom'] = @toPracticesLD(Wise,site) # console.log( 'MuseLD.toJsonLD()', jsonLD ) jsonLD isChild:( key ) -> tester.isChild(key) toPracLD:( pkey, prac, site ) -> pracLD = {} pracLD["@context"] = { '@type': "#{site}", "name": "#{site}name", "column": "#{site}column", "row": "#{site}row", "plane": "#{site}plane", "description": "#{site}description" } pracLD['@type'] = 'Practice' pracLD.name = pkey pracLD.column = prac.column pracLD.row = prac.row pracLD.plane = prac.plane pracLD.description = prac.desc pracLD toDispLD:( dkey, disp, site ) -> dispLD = {} dispLD["@context"] = { '@type': "#{site}", "name": "#{site}name", "description": "#{site}description" } dispLD['@type'] = 'Discipline' dispLD.name = dkey dispLD.description = disp.desc dispLD toPracticesLD:( data, site ) -> practices = {} for pkey, prac of data when @isChild(pkey) practices[pkey] = @toPracLD( pkey, prac, site ) practices[pkey].disciplines = {} for dkey, disp of prac when @isChild(dkey) practices[pkey].disciplines[dkey] = @toDispLD( dkey, disp, site ) practices @toJsonScript:(jsonLD) -> html = """<script type="application/ld+json">""" html += JSON.stringify(jsonLD) html += """</script""" html ### @AugmRoutes = [ { path: '/', name:'Home', components:{ Home: Home } }, { path: '/math', name:'Math', components:{ Math: Home.Math }, children: [ { path:'ML', name:'MathML', components:{ MathML: loader.load('MathND') } }, { path:'EQ', name:'MathEQ', components:{ MathEQ: loader.load('MathND') } } ] }, { path: '/draw', name:'Draw', components:{ Draw: loader.load('Draw') } }, { path: '/hues', name:'Hues', components:{ Hues: loader.load('Hues') } }, { path: '/tool', name:'Tool', components:{ Tool: Home.Tool }, children: [ { path:'Gauges', name:'G<NAME>', components:{ Gauges: loader.load('Tools') } }, { path:'Widget', name:'Widget', components:{ Widget: loader.load('Tools') } } ] }, { path: '/cube', name:'Cube', components:{ Cube: loader.load('Cube') } }, { path: '/wood', name:'Wood', components:{ Wood: loader.load('Wood') } } ] Muse.routes = [ { path: '/', name:'Home', components:{ Home: Home } }, { path: '/Prin', name:'Prin', components:{ Prin: Home.Prin } }, { path: '/Comp', name:'Comp', components:{ Comp: Home.Comp } }, { path: '/Prac', name:'Prac', components:{ Prac: Home.Prac } }, { path: '/Disp', name:'Disp', components:{ Disp: Home.Disp } }, { path: '/Cube', name:'Cube', components:{ Cube: Home.Cube } } ] ### toRoutes:() -> comps = [Prin,Info,Know,Wise] routes = [] routes.push( @toPath( '/', 'Home', 'Comp', 'Home' ) ) for comp in comps compName = @toCompName(comp) vueComp = if compName is 'Principles' then 'Home.Prin' else 'Home.Comp' routes.push( @toPath( '/'+compName, compName, 'Parent', vueComp ) ) for pkey, prac of comp when @isChild(pkey) routes.push( @toPath( pkey, pkey, 'Child', 'Home.Prac' ) ) routes.push( @toPath( '/Cube', 'Cube', 'Comp', 'Home.Cube' ) ) routes toPath:( path, name, type, comp ) -> @children = [] if type is 'Parent' route = {} route.path = path route.name = name switch type when 'Comp' route.components = { "#{name}":comp } when 'Parent' route.components = { "#{name}":comp } route.children = @children when 'Child' route.components = { "#{name}":comp } @children.push( route ) route toCompName:( comp ) -> if comp is Prin then 'Principles' else if comp is Info then 'Information' else if comp is Know then 'Knowledge' else if comp is Wise then 'Wisdom' else 'none' export default MuseLD
true
import { tester } from '../../../lib/pub/util/Util.js' import Prin from '../../../data/muse/Prin.json' import Rows from '../../../data/muse/Rows.json' import Info from '../../../data/muse/Info.json' import Know from '../../../data/muse/Know.json' import Wise from '../../../data/muse/Wise.json' #mport Software from '../../../data/inno/Software.json' #mport Data from '../../../data/inno/Data.json' #mport Science from '../../../data/inno/Science.json' #mport Math from '../../../data/inno/Math.json' class MuseLD constructor:( @Home ) -> @site = "http://example.com/" @jsonLD = @toJsonLD(@site) @jsonLDStr = JSON.stringify(@jsonLD) @children = [] toJsonLD:(site) -> jsonLD = {} jsonLD["@context"] = { "principles": "#{site}principles", "refinements": "#{site}refinements", "information": "#{site}information", "knowledge": "#{site}knowledge", "wisdom": "#{site}wisdom" } jsonLD['principles'] = @toPracticesLD(Prin,site) jsonLD['refinements'] = @toPracticesLD(Rows,site) jsonLD['information'] = @toPracticesLD(Info,site) jsonLD['knowledge'] = @toPracticesLD(Know,site) jsonLD['wisdom'] = @toPracticesLD(Wise,site) # console.log( 'MuseLD.toJsonLD()', jsonLD ) jsonLD isChild:( key ) -> tester.isChild(key) toPracLD:( pkey, prac, site ) -> pracLD = {} pracLD["@context"] = { '@type': "#{site}", "name": "#{site}name", "column": "#{site}column", "row": "#{site}row", "plane": "#{site}plane", "description": "#{site}description" } pracLD['@type'] = 'Practice' pracLD.name = pkey pracLD.column = prac.column pracLD.row = prac.row pracLD.plane = prac.plane pracLD.description = prac.desc pracLD toDispLD:( dkey, disp, site ) -> dispLD = {} dispLD["@context"] = { '@type': "#{site}", "name": "#{site}name", "description": "#{site}description" } dispLD['@type'] = 'Discipline' dispLD.name = dkey dispLD.description = disp.desc dispLD toPracticesLD:( data, site ) -> practices = {} for pkey, prac of data when @isChild(pkey) practices[pkey] = @toPracLD( pkey, prac, site ) practices[pkey].disciplines = {} for dkey, disp of prac when @isChild(dkey) practices[pkey].disciplines[dkey] = @toDispLD( dkey, disp, site ) practices @toJsonScript:(jsonLD) -> html = """<script type="application/ld+json">""" html += JSON.stringify(jsonLD) html += """</script""" html ### @AugmRoutes = [ { path: '/', name:'Home', components:{ Home: Home } }, { path: '/math', name:'Math', components:{ Math: Home.Math }, children: [ { path:'ML', name:'MathML', components:{ MathML: loader.load('MathND') } }, { path:'EQ', name:'MathEQ', components:{ MathEQ: loader.load('MathND') } } ] }, { path: '/draw', name:'Draw', components:{ Draw: loader.load('Draw') } }, { path: '/hues', name:'Hues', components:{ Hues: loader.load('Hues') } }, { path: '/tool', name:'Tool', components:{ Tool: Home.Tool }, children: [ { path:'Gauges', name:'GPI:NAME:<NAME>END_PI', components:{ Gauges: loader.load('Tools') } }, { path:'Widget', name:'Widget', components:{ Widget: loader.load('Tools') } } ] }, { path: '/cube', name:'Cube', components:{ Cube: loader.load('Cube') } }, { path: '/wood', name:'Wood', components:{ Wood: loader.load('Wood') } } ] Muse.routes = [ { path: '/', name:'Home', components:{ Home: Home } }, { path: '/Prin', name:'Prin', components:{ Prin: Home.Prin } }, { path: '/Comp', name:'Comp', components:{ Comp: Home.Comp } }, { path: '/Prac', name:'Prac', components:{ Prac: Home.Prac } }, { path: '/Disp', name:'Disp', components:{ Disp: Home.Disp } }, { path: '/Cube', name:'Cube', components:{ Cube: Home.Cube } } ] ### toRoutes:() -> comps = [Prin,Info,Know,Wise] routes = [] routes.push( @toPath( '/', 'Home', 'Comp', 'Home' ) ) for comp in comps compName = @toCompName(comp) vueComp = if compName is 'Principles' then 'Home.Prin' else 'Home.Comp' routes.push( @toPath( '/'+compName, compName, 'Parent', vueComp ) ) for pkey, prac of comp when @isChild(pkey) routes.push( @toPath( pkey, pkey, 'Child', 'Home.Prac' ) ) routes.push( @toPath( '/Cube', 'Cube', 'Comp', 'Home.Cube' ) ) routes toPath:( path, name, type, comp ) -> @children = [] if type is 'Parent' route = {} route.path = path route.name = name switch type when 'Comp' route.components = { "#{name}":comp } when 'Parent' route.components = { "#{name}":comp } route.children = @children when 'Child' route.components = { "#{name}":comp } @children.push( route ) route toCompName:( comp ) -> if comp is Prin then 'Principles' else if comp is Info then 'Information' else if comp is Know then 'Knowledge' else if comp is Wise then 'Wisdom' else 'none' export default MuseLD
[ { "context": "3 < line.length)\n\t\trr = line.split (\" \")\n\t\tkey = \"t\" + rr[0]\n\t\tvalue = new Object\n\t\tvalue[\"name\"] = rr", "end": 438, "score": 0.7228062748908997, "start": 436, "tag": "KEY", "value": "t\"" } ]
koho_kokai/sound_koho/to_json/to_json.coffee
ekzemplaro/kodama
3
#! /usr/bin/coffee # # Oct/28/2011 # # ------------------------------------------------------------- fs = require('fs') # ------------------------------------------------------------- console.log "*** 開始 ***\n" file_in = process.argv[2] file_json = process.argv[3] data_aa = new Object data = fs.readFileSync (file_in) lines_in = ("" + data).split ("\n") for line in lines_in if (3 < line.length) rr = line.split (" ") key = "t" + rr[0] value = new Object value["name"] = rr[1] value["paper"] = 0 value["sound"] = 0 value["url_city"] = "http://" data_aa[key] = value # json_str = JSON.stringify data_aa fs.writeFile(file_json,json_str) console.log "*** 終了 ***\n" # -------------------------------------------------------------
16338
#! /usr/bin/coffee # # Oct/28/2011 # # ------------------------------------------------------------- fs = require('fs') # ------------------------------------------------------------- console.log "*** 開始 ***\n" file_in = process.argv[2] file_json = process.argv[3] data_aa = new Object data = fs.readFileSync (file_in) lines_in = ("" + data).split ("\n") for line in lines_in if (3 < line.length) rr = line.split (" ") key = "<KEY> + rr[0] value = new Object value["name"] = rr[1] value["paper"] = 0 value["sound"] = 0 value["url_city"] = "http://" data_aa[key] = value # json_str = JSON.stringify data_aa fs.writeFile(file_json,json_str) console.log "*** 終了 ***\n" # -------------------------------------------------------------
true
#! /usr/bin/coffee # # Oct/28/2011 # # ------------------------------------------------------------- fs = require('fs') # ------------------------------------------------------------- console.log "*** 開始 ***\n" file_in = process.argv[2] file_json = process.argv[3] data_aa = new Object data = fs.readFileSync (file_in) lines_in = ("" + data).split ("\n") for line in lines_in if (3 < line.length) rr = line.split (" ") key = "PI:KEY:<KEY>END_PI + rr[0] value = new Object value["name"] = rr[1] value["paper"] = 0 value["sound"] = 0 value["url_city"] = "http://" data_aa[key] = value # json_str = JSON.stringify data_aa fs.writeFile(file_json,json_str) console.log "*** 終了 ***\n" # -------------------------------------------------------------
[ { "context": "- evaluates [code] as CoffeeScript\n#\n# Author:\n# JustinMorgan@GitHub\n#\ncompile = require \"swiss-army-eval\" \n\nmodule.ex", "end": 439, "score": 0.9456882476806641, "start": 420, "tag": "EMAIL", "value": "JustinMorgan@GitHub" } ]
src/parsebot.coffee
JustinMorgan/hubot-parsebot
0
# Description: # Allows hubot to run inline JS or CoffeeScript. # # Dependencies: # coffee-script # swiss-army-eval # # Commands: # hubot javascript me [code] - evaluates [code] as JavaScript # hubot js me [code] - evaluates [code] as JavaScript # hubot coffeescript me [code] - evaluates [code] as CoffeeScript # hubot coffee me [code] - evaluates [code] as CoffeeScript # # Author: # JustinMorgan@GitHub # compile = require "swiss-army-eval" module.exports = (robot) -> robot.respond /(js|javascript|coffee(?:script)?) me (.*)/i, (msg) -> [lang, code] = msg.match[1..] try msg.send "#{compile lang, code}" catch e msg.send e
183203
# Description: # Allows hubot to run inline JS or CoffeeScript. # # Dependencies: # coffee-script # swiss-army-eval # # Commands: # hubot javascript me [code] - evaluates [code] as JavaScript # hubot js me [code] - evaluates [code] as JavaScript # hubot coffeescript me [code] - evaluates [code] as CoffeeScript # hubot coffee me [code] - evaluates [code] as CoffeeScript # # Author: # <EMAIL> # compile = require "swiss-army-eval" module.exports = (robot) -> robot.respond /(js|javascript|coffee(?:script)?) me (.*)/i, (msg) -> [lang, code] = msg.match[1..] try msg.send "#{compile lang, code}" catch e msg.send e
true
# Description: # Allows hubot to run inline JS or CoffeeScript. # # Dependencies: # coffee-script # swiss-army-eval # # Commands: # hubot javascript me [code] - evaluates [code] as JavaScript # hubot js me [code] - evaluates [code] as JavaScript # hubot coffeescript me [code] - evaluates [code] as CoffeeScript # hubot coffee me [code] - evaluates [code] as CoffeeScript # # Author: # PI:EMAIL:<EMAIL>END_PI # compile = require "swiss-army-eval" module.exports = (robot) -> robot.respond /(js|javascript|coffee(?:script)?) me (.*)/i, (msg) -> [lang, code] = msg.match[1..] try msg.send "#{compile lang, code}" catch e msg.send e
[ { "context": "ler', ->\n @timeout 500000\n\t\n user = \n name: 'user'\n email: 'user@abc.com'\n\n it \"get user detail", "end": 135, "score": 0.9985148310661316, "start": 131, "tag": "USERNAME", "value": "user" }, { "context": "t 500000\n\t\n user = \n name: 'user'\n ...
test/unit/1-controller/0-UserController.coffee
twhtanghk/restfile
0
_ = require 'lodash' req = require 'supertest-as-promised' describe 'UserController', -> @timeout 500000 user = name: 'user' email: 'user@abc.com' it "get user details #{user.email}", (done) -> req sails.hooks.http.app .get '/user/me' .set 'x-forwarded-user', user.name .set 'x-forwarded-email', user.email .expect 200 .then -> done() .catch done it "get registered user list", (done) -> req sails.hooks.http.app .get '/user' .set 'x-forwarded-user', user.name .set 'x-forwarded-email', user.email .expect 200 .then -> done() .catch done
60460
_ = require 'lodash' req = require 'supertest-as-promised' describe 'UserController', -> @timeout 500000 user = name: 'user' email: '<EMAIL>' it "get user details #{user.email}", (done) -> req sails.hooks.http.app .get '/user/me' .set 'x-forwarded-user', user.name .set 'x-forwarded-email', user.email .expect 200 .then -> done() .catch done it "get registered user list", (done) -> req sails.hooks.http.app .get '/user' .set 'x-forwarded-user', user.name .set 'x-forwarded-email', user.email .expect 200 .then -> done() .catch done
true
_ = require 'lodash' req = require 'supertest-as-promised' describe 'UserController', -> @timeout 500000 user = name: 'user' email: 'PI:EMAIL:<EMAIL>END_PI' it "get user details #{user.email}", (done) -> req sails.hooks.http.app .get '/user/me' .set 'x-forwarded-user', user.name .set 'x-forwarded-email', user.email .expect 200 .then -> done() .catch done it "get registered user list", (done) -> req sails.hooks.http.app .get '/user' .set 'x-forwarded-user', user.name .set 'x-forwarded-email', user.email .expect 200 .then -> done() .catch done
[ { "context": "tName = @nameMap[challenger.opponentID]?.name or 'Anoner'\n challenger.opponentWizard = @nameMap[cha", "end": 1941, "score": 0.999565839767456, "start": 1935, "tag": "NAME", "value": "Anoner" }, { "context": "am for team in teamsList\n ctx.teamColor = teams[@t...
app/views/play/ladder/play_modal.coffee
maurovanetti/codecombat
1
View = require 'views/kinds/ModalView' template = require 'templates/play/ladder/play_modal' ThangType = require 'models/ThangType' {me} = require 'lib/auth' LeaderboardCollection = require 'collections/LeaderboardCollection' {teamDataFromLevel} = require './utils' module.exports = class LadderPlayModal extends View id: 'ladder-play-modal' template: template closeButton: true startsLoading: true @shownTutorialButton: false tutorialLevelExists: null events: 'click #skip-tutorial-button': 'hideTutorialButtons' 'change #tome-language': 'updateLanguage' defaultAceConfig: language: 'javascript' keyBindings: 'default' invisibles: false indentGuides: false behaviors: false liveCompletion: true constructor: (options, @level, @session, @team) -> super(options) @nameMap = {} @otherTeam = if team is 'ogres' then 'humans' else 'ogres' @startLoadingChallengersMaybe() @wizardType = ThangType.loadUniversalWizard() updateLanguage: -> aceConfig = _.cloneDeep me.get('aceConfig') ? {} aceConfig = _.defaults aceConfig, @defaultAceConfig aceConfig.language = @$el.find('#tome-language').val() me.set 'aceConfig', aceConfig me.patch() # PART 1: Load challengers from the db unless some are in the matches startLoadingChallengersMaybe: -> matches = @session?.get('matches') if matches?.length then @loadNames() else @loadChallengers() loadChallengers: -> @challengersCollection = new ChallengersData(@level, @team, @otherTeam, @session) @listenTo(@challengersCollection, 'sync', @loadNames) # PART 2: Loading the names of the other users loadNames: -> @challengers = @getChallengers() ids = (challenger.opponentID for challenger in _.values @challengers) success = (@nameMap) => for challenger in _.values(@challengers) challenger.opponentName = @nameMap[challenger.opponentID]?.name or 'Anoner' challenger.opponentWizard = @nameMap[challenger.opponentID]?.wizard or {} @checkWizardLoaded() $.ajax('/db/user/-/names', { data: {ids: ids, wizard: true} type: 'POST' success: success }) # PART 3: Make sure wizard is loaded checkWizardLoaded: -> if @wizardType.loaded then @finishRendering() else @listenToOnce(@wizardType, 'sync', @finishRendering) # PART 4: Render finishRendering: -> @checkTutorialLevelExists (exists) => @tutorialLevelExists = exists @startsLoading = false @render() @maybeShowTutorialButtons() getRenderData: -> ctx = super() ctx.level = @level ctx.levelID = @level.get('slug') or @level.id ctx.teamName = _.string.titleize @team ctx.teamID = @team ctx.otherTeamID = @otherTeam ctx.tutorialLevelExists = @tutorialLevelExists ctx.languages = [ {id: 'javascript', name: 'JavaScript'} {id: 'coffeescript', name: 'CoffeeScript'} {id: 'python', name: 'Python (Experimental)'} {id: 'clojure', name: 'Clojure (Experimental)'} {id: 'lua', name: 'Lua (Experimental)'} {id: 'io', name: 'Io (Experimental)'} ] teamsList = teamDataFromLevel @level teams = {} teams[team.id] = team for team in teamsList ctx.teamColor = teams[@team].primaryColor ctx.teamBackgroundColor = teams[@team].bgColor ctx.opponentTeamColor = teams[@otherTeam].primaryColor ctx.opponentTeamBackgroundColor = teams[@otherTeam].bgColor ctx.challengers = @challengers or {} for challenger in _.values ctx.challengers continue unless challenger and @wizardType.loaded if (not challenger.opponentImageSource) and challenger.opponentWizard?.colorConfig challenger.opponentImageSource = @wizardType.getPortraitSource( {colorConfig: challenger.opponentWizard.colorConfig}) if @wizardType.loaded ctx.genericPortrait = @wizardType.getPortraitSource() myColorConfig = me.get('wizard')?.colorConfig ctx.myPortrait = if myColorConfig then @wizardType.getPortraitSource({colorConfig: myColorConfig}) else ctx.genericPortrait ctx.myName = me.get('name') || 'Newcomer' ctx maybeShowTutorialButtons: -> return if @session or LadderPlayModal.shownTutorialButton or not @tutorialLevelExists @$el.find('#normal-view').addClass('secret') @$el.find('.modal-header').addClass('secret') @$el.find('#noob-view').removeClass('secret') LadderPlayModal.shownTutorialButton = true hideTutorialButtons: -> @$el.find('#normal-view').removeClass('secret') @$el.find('.modal-header').removeClass('secret') @$el.find('#noob-view').addClass('secret') checkTutorialLevelExists: (cb) -> levelID = @level.get('slug') or @level.id tutorialLevelID = "#{levelID}-tutorial" success = => cb true failure = => cb false $.ajax type: 'GET' url: "/db/level/#{tutorialLevelID}/exists" success: success error: failure # Choosing challengers getChallengers: -> # make an object of challengers to everything needed to link to them challengers = {} if @challengersCollection easyInfo = @challengeInfoFromSession(@challengersCollection.easyPlayer.models[0]) mediumInfo = @challengeInfoFromSession(@challengersCollection.mediumPlayer.models[0]) hardInfo = @challengeInfoFromSession(@challengersCollection.hardPlayer.models[0]) else matches = @session.get('matches') won = (m for m in matches when m.metrics.rank < m.opponents[0].metrics.rank) lost = (m for m in matches when m.metrics.rank > m.opponents[0].metrics.rank) tied = (m for m in matches when m.metrics.rank is m.opponents[0].metrics.rank) easyInfo = @challengeInfoFromMatches(won) mediumInfo = @challengeInfoFromMatches(tied) hardInfo = @challengeInfoFromMatches(lost) @addChallenger easyInfo, challengers, 'easy' @addChallenger mediumInfo, challengers, 'medium' @addChallenger hardInfo, challengers, 'hard' challengers addChallenger: (info, challengers, title) -> # check for duplicates first return unless info for key, value of challengers return if value.sessionID is info.sessionID challengers[title] = info challengeInfoFromSession: (session) -> # given a model from the db, return info needed for a link to the match return unless session return { sessionID: session.id opponentID: session.get 'creator' codeLanguage: session.get 'submittedCodeLanguage' } challengeInfoFromMatches: (matches) -> return unless matches?.length match = _.sample matches opponent = match.opponents[0] return { sessionID: opponent.sessionID opponentID: opponent.userID codeLanguage: opponent.codeLanguage } class ChallengersData constructor: (@level, @team, @otherTeam, @session) -> _.extend @, Backbone.Events score = @session?.get('totalScore') or 25 @easyPlayer = new LeaderboardCollection(@level, {order: 1, scoreOffset: score - 5, limit: 1, team: @otherTeam}) @easyPlayer.fetch() @listenToOnce(@easyPlayer, 'sync', @challengerLoaded) @mediumPlayer = new LeaderboardCollection(@level, {order: 1, scoreOffset: score, limit: 1, team: @otherTeam}) @mediumPlayer.fetch() @listenToOnce(@mediumPlayer, 'sync', @challengerLoaded) @hardPlayer = new LeaderboardCollection(@level, {order: -1, scoreOffset: score + 5, limit: 1, team: @otherTeam}) @hardPlayer.fetch() @listenToOnce(@hardPlayer, 'sync', @challengerLoaded) challengerLoaded: -> if @allLoaded() @loaded = true @trigger 'sync' playerIDs: -> collections = [@easyPlayer, @mediumPlayer, @hardPlayer] (c.models[0].get('creator') for c in collections when c?.models[0]) allLoaded: -> _.all [@easyPlayer.loaded, @mediumPlayer.loaded, @hardPlayer.loaded]
174200
View = require 'views/kinds/ModalView' template = require 'templates/play/ladder/play_modal' ThangType = require 'models/ThangType' {me} = require 'lib/auth' LeaderboardCollection = require 'collections/LeaderboardCollection' {teamDataFromLevel} = require './utils' module.exports = class LadderPlayModal extends View id: 'ladder-play-modal' template: template closeButton: true startsLoading: true @shownTutorialButton: false tutorialLevelExists: null events: 'click #skip-tutorial-button': 'hideTutorialButtons' 'change #tome-language': 'updateLanguage' defaultAceConfig: language: 'javascript' keyBindings: 'default' invisibles: false indentGuides: false behaviors: false liveCompletion: true constructor: (options, @level, @session, @team) -> super(options) @nameMap = {} @otherTeam = if team is 'ogres' then 'humans' else 'ogres' @startLoadingChallengersMaybe() @wizardType = ThangType.loadUniversalWizard() updateLanguage: -> aceConfig = _.cloneDeep me.get('aceConfig') ? {} aceConfig = _.defaults aceConfig, @defaultAceConfig aceConfig.language = @$el.find('#tome-language').val() me.set 'aceConfig', aceConfig me.patch() # PART 1: Load challengers from the db unless some are in the matches startLoadingChallengersMaybe: -> matches = @session?.get('matches') if matches?.length then @loadNames() else @loadChallengers() loadChallengers: -> @challengersCollection = new ChallengersData(@level, @team, @otherTeam, @session) @listenTo(@challengersCollection, 'sync', @loadNames) # PART 2: Loading the names of the other users loadNames: -> @challengers = @getChallengers() ids = (challenger.opponentID for challenger in _.values @challengers) success = (@nameMap) => for challenger in _.values(@challengers) challenger.opponentName = @nameMap[challenger.opponentID]?.name or '<NAME>' challenger.opponentWizard = @nameMap[challenger.opponentID]?.wizard or {} @checkWizardLoaded() $.ajax('/db/user/-/names', { data: {ids: ids, wizard: true} type: 'POST' success: success }) # PART 3: Make sure wizard is loaded checkWizardLoaded: -> if @wizardType.loaded then @finishRendering() else @listenToOnce(@wizardType, 'sync', @finishRendering) # PART 4: Render finishRendering: -> @checkTutorialLevelExists (exists) => @tutorialLevelExists = exists @startsLoading = false @render() @maybeShowTutorialButtons() getRenderData: -> ctx = super() ctx.level = @level ctx.levelID = @level.get('slug') or @level.id ctx.teamName = _.string.titleize @team ctx.teamID = @team ctx.otherTeamID = @otherTeam ctx.tutorialLevelExists = @tutorialLevelExists ctx.languages = [ {id: 'javascript', name: 'JavaScript'} {id: 'coffeescript', name: 'CoffeeScript'} {id: 'python', name: 'Python (Experimental)'} {id: 'clojure', name: 'Clojure (Experimental)'} {id: 'lua', name: 'Lua (Experimental)'} {id: 'io', name: 'Io (Experimental)'} ] teamsList = teamDataFromLevel @level teams = {} teams[team.id] = team for team in teamsList ctx.teamColor = teams[@team].primaryColor ctx.teamBackgroundColor = teams[@team].bgColor ctx.opponentTeamColor = teams[@otherTeam].primaryColor ctx.opponentTeamBackgroundColor = teams[@otherTeam].bgColor ctx.challengers = @challengers or {} for challenger in _.values ctx.challengers continue unless challenger and @wizardType.loaded if (not challenger.opponentImageSource) and challenger.opponentWizard?.colorConfig challenger.opponentImageSource = @wizardType.getPortraitSource( {colorConfig: challenger.opponentWizard.colorConfig}) if @wizardType.loaded ctx.genericPortrait = @wizardType.getPortraitSource() myColorConfig = me.get('wizard')?.colorConfig ctx.myPortrait = if myColorConfig then @wizardType.getPortraitSource({colorConfig: myColorConfig}) else ctx.genericPortrait ctx.myName = me.get('name') || '<NAME>' ctx maybeShowTutorialButtons: -> return if @session or LadderPlayModal.shownTutorialButton or not @tutorialLevelExists @$el.find('#normal-view').addClass('secret') @$el.find('.modal-header').addClass('secret') @$el.find('#noob-view').removeClass('secret') LadderPlayModal.shownTutorialButton = true hideTutorialButtons: -> @$el.find('#normal-view').removeClass('secret') @$el.find('.modal-header').removeClass('secret') @$el.find('#noob-view').addClass('secret') checkTutorialLevelExists: (cb) -> levelID = @level.get('slug') or @level.id tutorialLevelID = "#{levelID}-tutorial" success = => cb true failure = => cb false $.ajax type: 'GET' url: "/db/level/#{tutorialLevelID}/exists" success: success error: failure # Choosing challengers getChallengers: -> # make an object of challengers to everything needed to link to them challengers = {} if @challengersCollection easyInfo = @challengeInfoFromSession(@challengersCollection.easyPlayer.models[0]) mediumInfo = @challengeInfoFromSession(@challengersCollection.mediumPlayer.models[0]) hardInfo = @challengeInfoFromSession(@challengersCollection.hardPlayer.models[0]) else matches = @session.get('matches') won = (m for m in matches when m.metrics.rank < m.opponents[0].metrics.rank) lost = (m for m in matches when m.metrics.rank > m.opponents[0].metrics.rank) tied = (m for m in matches when m.metrics.rank is m.opponents[0].metrics.rank) easyInfo = @challengeInfoFromMatches(won) mediumInfo = @challengeInfoFromMatches(tied) hardInfo = @challengeInfoFromMatches(lost) @addChallenger easyInfo, challengers, 'easy' @addChallenger mediumInfo, challengers, 'medium' @addChallenger hardInfo, challengers, 'hard' challengers addChallenger: (info, challengers, title) -> # check for duplicates first return unless info for key, value of challengers return if value.sessionID is info.sessionID challengers[title] = info challengeInfoFromSession: (session) -> # given a model from the db, return info needed for a link to the match return unless session return { sessionID: session.id opponentID: session.get 'creator' codeLanguage: session.get 'submittedCodeLanguage' } challengeInfoFromMatches: (matches) -> return unless matches?.length match = _.sample matches opponent = match.opponents[0] return { sessionID: opponent.sessionID opponentID: opponent.userID codeLanguage: opponent.codeLanguage } class ChallengersData constructor: (@level, @team, @otherTeam, @session) -> _.extend @, Backbone.Events score = @session?.get('totalScore') or 25 @easyPlayer = new LeaderboardCollection(@level, {order: 1, scoreOffset: score - 5, limit: 1, team: @otherTeam}) @easyPlayer.fetch() @listenToOnce(@easyPlayer, 'sync', @challengerLoaded) @mediumPlayer = new LeaderboardCollection(@level, {order: 1, scoreOffset: score, limit: 1, team: @otherTeam}) @mediumPlayer.fetch() @listenToOnce(@mediumPlayer, 'sync', @challengerLoaded) @hardPlayer = new LeaderboardCollection(@level, {order: -1, scoreOffset: score + 5, limit: 1, team: @otherTeam}) @hardPlayer.fetch() @listenToOnce(@hardPlayer, 'sync', @challengerLoaded) challengerLoaded: -> if @allLoaded() @loaded = true @trigger 'sync' playerIDs: -> collections = [@easyPlayer, @mediumPlayer, @hardPlayer] (c.models[0].get('creator') for c in collections when c?.models[0]) allLoaded: -> _.all [@easyPlayer.loaded, @mediumPlayer.loaded, @hardPlayer.loaded]
true
View = require 'views/kinds/ModalView' template = require 'templates/play/ladder/play_modal' ThangType = require 'models/ThangType' {me} = require 'lib/auth' LeaderboardCollection = require 'collections/LeaderboardCollection' {teamDataFromLevel} = require './utils' module.exports = class LadderPlayModal extends View id: 'ladder-play-modal' template: template closeButton: true startsLoading: true @shownTutorialButton: false tutorialLevelExists: null events: 'click #skip-tutorial-button': 'hideTutorialButtons' 'change #tome-language': 'updateLanguage' defaultAceConfig: language: 'javascript' keyBindings: 'default' invisibles: false indentGuides: false behaviors: false liveCompletion: true constructor: (options, @level, @session, @team) -> super(options) @nameMap = {} @otherTeam = if team is 'ogres' then 'humans' else 'ogres' @startLoadingChallengersMaybe() @wizardType = ThangType.loadUniversalWizard() updateLanguage: -> aceConfig = _.cloneDeep me.get('aceConfig') ? {} aceConfig = _.defaults aceConfig, @defaultAceConfig aceConfig.language = @$el.find('#tome-language').val() me.set 'aceConfig', aceConfig me.patch() # PART 1: Load challengers from the db unless some are in the matches startLoadingChallengersMaybe: -> matches = @session?.get('matches') if matches?.length then @loadNames() else @loadChallengers() loadChallengers: -> @challengersCollection = new ChallengersData(@level, @team, @otherTeam, @session) @listenTo(@challengersCollection, 'sync', @loadNames) # PART 2: Loading the names of the other users loadNames: -> @challengers = @getChallengers() ids = (challenger.opponentID for challenger in _.values @challengers) success = (@nameMap) => for challenger in _.values(@challengers) challenger.opponentName = @nameMap[challenger.opponentID]?.name or 'PI:NAME:<NAME>END_PI' challenger.opponentWizard = @nameMap[challenger.opponentID]?.wizard or {} @checkWizardLoaded() $.ajax('/db/user/-/names', { data: {ids: ids, wizard: true} type: 'POST' success: success }) # PART 3: Make sure wizard is loaded checkWizardLoaded: -> if @wizardType.loaded then @finishRendering() else @listenToOnce(@wizardType, 'sync', @finishRendering) # PART 4: Render finishRendering: -> @checkTutorialLevelExists (exists) => @tutorialLevelExists = exists @startsLoading = false @render() @maybeShowTutorialButtons() getRenderData: -> ctx = super() ctx.level = @level ctx.levelID = @level.get('slug') or @level.id ctx.teamName = _.string.titleize @team ctx.teamID = @team ctx.otherTeamID = @otherTeam ctx.tutorialLevelExists = @tutorialLevelExists ctx.languages = [ {id: 'javascript', name: 'JavaScript'} {id: 'coffeescript', name: 'CoffeeScript'} {id: 'python', name: 'Python (Experimental)'} {id: 'clojure', name: 'Clojure (Experimental)'} {id: 'lua', name: 'Lua (Experimental)'} {id: 'io', name: 'Io (Experimental)'} ] teamsList = teamDataFromLevel @level teams = {} teams[team.id] = team for team in teamsList ctx.teamColor = teams[@team].primaryColor ctx.teamBackgroundColor = teams[@team].bgColor ctx.opponentTeamColor = teams[@otherTeam].primaryColor ctx.opponentTeamBackgroundColor = teams[@otherTeam].bgColor ctx.challengers = @challengers or {} for challenger in _.values ctx.challengers continue unless challenger and @wizardType.loaded if (not challenger.opponentImageSource) and challenger.opponentWizard?.colorConfig challenger.opponentImageSource = @wizardType.getPortraitSource( {colorConfig: challenger.opponentWizard.colorConfig}) if @wizardType.loaded ctx.genericPortrait = @wizardType.getPortraitSource() myColorConfig = me.get('wizard')?.colorConfig ctx.myPortrait = if myColorConfig then @wizardType.getPortraitSource({colorConfig: myColorConfig}) else ctx.genericPortrait ctx.myName = me.get('name') || 'PI:NAME:<NAME>END_PI' ctx maybeShowTutorialButtons: -> return if @session or LadderPlayModal.shownTutorialButton or not @tutorialLevelExists @$el.find('#normal-view').addClass('secret') @$el.find('.modal-header').addClass('secret') @$el.find('#noob-view').removeClass('secret') LadderPlayModal.shownTutorialButton = true hideTutorialButtons: -> @$el.find('#normal-view').removeClass('secret') @$el.find('.modal-header').removeClass('secret') @$el.find('#noob-view').addClass('secret') checkTutorialLevelExists: (cb) -> levelID = @level.get('slug') or @level.id tutorialLevelID = "#{levelID}-tutorial" success = => cb true failure = => cb false $.ajax type: 'GET' url: "/db/level/#{tutorialLevelID}/exists" success: success error: failure # Choosing challengers getChallengers: -> # make an object of challengers to everything needed to link to them challengers = {} if @challengersCollection easyInfo = @challengeInfoFromSession(@challengersCollection.easyPlayer.models[0]) mediumInfo = @challengeInfoFromSession(@challengersCollection.mediumPlayer.models[0]) hardInfo = @challengeInfoFromSession(@challengersCollection.hardPlayer.models[0]) else matches = @session.get('matches') won = (m for m in matches when m.metrics.rank < m.opponents[0].metrics.rank) lost = (m for m in matches when m.metrics.rank > m.opponents[0].metrics.rank) tied = (m for m in matches when m.metrics.rank is m.opponents[0].metrics.rank) easyInfo = @challengeInfoFromMatches(won) mediumInfo = @challengeInfoFromMatches(tied) hardInfo = @challengeInfoFromMatches(lost) @addChallenger easyInfo, challengers, 'easy' @addChallenger mediumInfo, challengers, 'medium' @addChallenger hardInfo, challengers, 'hard' challengers addChallenger: (info, challengers, title) -> # check for duplicates first return unless info for key, value of challengers return if value.sessionID is info.sessionID challengers[title] = info challengeInfoFromSession: (session) -> # given a model from the db, return info needed for a link to the match return unless session return { sessionID: session.id opponentID: session.get 'creator' codeLanguage: session.get 'submittedCodeLanguage' } challengeInfoFromMatches: (matches) -> return unless matches?.length match = _.sample matches opponent = match.opponents[0] return { sessionID: opponent.sessionID opponentID: opponent.userID codeLanguage: opponent.codeLanguage } class ChallengersData constructor: (@level, @team, @otherTeam, @session) -> _.extend @, Backbone.Events score = @session?.get('totalScore') or 25 @easyPlayer = new LeaderboardCollection(@level, {order: 1, scoreOffset: score - 5, limit: 1, team: @otherTeam}) @easyPlayer.fetch() @listenToOnce(@easyPlayer, 'sync', @challengerLoaded) @mediumPlayer = new LeaderboardCollection(@level, {order: 1, scoreOffset: score, limit: 1, team: @otherTeam}) @mediumPlayer.fetch() @listenToOnce(@mediumPlayer, 'sync', @challengerLoaded) @hardPlayer = new LeaderboardCollection(@level, {order: -1, scoreOffset: score + 5, limit: 1, team: @otherTeam}) @hardPlayer.fetch() @listenToOnce(@hardPlayer, 'sync', @challengerLoaded) challengerLoaded: -> if @allLoaded() @loaded = true @trigger 'sync' playerIDs: -> collections = [@easyPlayer, @mediumPlayer, @hardPlayer] (c.models[0].get('creator') for c in collections when c?.models[0]) allLoaded: -> _.all [@easyPlayer.loaded, @mediumPlayer.loaded, @hardPlayer.loaded]
[ { "context": "ark in @props.sourceMarks\n mark._key ?= Math.random()\n <Tool key={mark._key} mark={m", "end": 616, "score": 0.6194407939910889, "start": 611, "tag": "KEY", "value": "Math." } ]
app/classifier/drawing-tools/aggregate-mark.cjsx
Crentist/Panoptes-frontend-spanish
1
React = require 'react' drawingTools = require './index' module.exports = React.createClass displayName: 'AggregateMark' getDefaultProps: -> toolDefinition: null mark: null sourceMarks: null expanded: false getInitialState: -> expanded: @props.expanded render: -> Tool = drawingTools[@props.toolDefinition.type] <g className="aggregate-mark" onClick={@toggleExpanded}> <Tool mark={@props.mark} tool={@props.toolDefinition} disabled /> {if @state.expanded <g className="source-marks"> {for mark in @props.sourceMarks mark._key ?= Math.random() <Tool key={mark._key} mark={mark} tool={@props.toolDefinition} disabled />} </g>} </g> toggleExpanded: -> @setState expanded: not @state.expanded
207210
React = require 'react' drawingTools = require './index' module.exports = React.createClass displayName: 'AggregateMark' getDefaultProps: -> toolDefinition: null mark: null sourceMarks: null expanded: false getInitialState: -> expanded: @props.expanded render: -> Tool = drawingTools[@props.toolDefinition.type] <g className="aggregate-mark" onClick={@toggleExpanded}> <Tool mark={@props.mark} tool={@props.toolDefinition} disabled /> {if @state.expanded <g className="source-marks"> {for mark in @props.sourceMarks mark._key ?= <KEY>random() <Tool key={mark._key} mark={mark} tool={@props.toolDefinition} disabled />} </g>} </g> toggleExpanded: -> @setState expanded: not @state.expanded
true
React = require 'react' drawingTools = require './index' module.exports = React.createClass displayName: 'AggregateMark' getDefaultProps: -> toolDefinition: null mark: null sourceMarks: null expanded: false getInitialState: -> expanded: @props.expanded render: -> Tool = drawingTools[@props.toolDefinition.type] <g className="aggregate-mark" onClick={@toggleExpanded}> <Tool mark={@props.mark} tool={@props.toolDefinition} disabled /> {if @state.expanded <g className="source-marks"> {for mark in @props.sourceMarks mark._key ?= PI:KEY:<KEY>END_PIrandom() <Tool key={mark._key} mark={mark} tool={@props.toolDefinition} disabled />} </g>} </g> toggleExpanded: -> @setState expanded: not @state.expanded
[ { "context": "* @package\t\tHome\n * @category\tmodules\n * @author\t\tNazar Mokrynskyi <nazar@mokrynskyi.com>\n * @copyright\tCopyright (c", "end": 71, "score": 0.9998868107795715, "start": 55, "tag": "NAME", "value": "Nazar Mokrynskyi" }, { "context": "* @category\tmodules\n * @aut...
components/modules/Home/includes/js/_general.coffee
nazar-pc/cherrytea.org-old
1
### * @package Home * @category modules * @author Nazar Mokrynskyi <nazar@mokrynskyi.com> * @copyright Copyright (c) 2013-2014, Nazar Mokrynskyi * @license MIT License, see license.txt ### $ -> $.pickmeup.locale.months = ["Січень", "Лютий", "Березень", "Квітень", "Травень", "Червень", "Липень", "Серпень", "Вересень", "Жовтень", "Листопад", "Грудень"] $.pickmeup.locale.daysMin = ["Нд", "По", "Вт", "Ср", "Чт", "Пт", "Сб", "Нд"] $.pickmeup.locale.monthsShort = ["Січ", "Лют", "Бер", "Кві", "Тра", "Чер", "Лип", "Сер", "Вер", "Жов", "Лис", "Гру"]
149847
### * @package Home * @category modules * @author <NAME> <<EMAIL>> * @copyright Copyright (c) 2013-2014, <NAME> * @license MIT License, see license.txt ### $ -> $.pickmeup.locale.months = ["Січень", "Лютий", "Березень", "Квітень", "Травень", "Червень", "Липень", "Серпень", "Вересень", "Жовтень", "Листопад", "Грудень"] $.pickmeup.locale.daysMin = ["Нд", "По", "Вт", "Ср", "Чт", "Пт", "Сб", "Нд"] $.pickmeup.locale.monthsShort = ["Січ", "Лют", "Бер", "Кві", "Тра", "Чер", "Лип", "Сер", "Вер", "Жов", "Лис", "Гру"]
true
### * @package Home * @category modules * @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> * @copyright Copyright (c) 2013-2014, PI:NAME:<NAME>END_PI * @license MIT License, see license.txt ### $ -> $.pickmeup.locale.months = ["Січень", "Лютий", "Березень", "Квітень", "Травень", "Червень", "Липень", "Серпень", "Вересень", "Жовтень", "Листопад", "Грудень"] $.pickmeup.locale.daysMin = ["Нд", "По", "Вт", "Ср", "Чт", "Пт", "Сб", "Нд"] $.pickmeup.locale.monthsShort = ["Січ", "Лют", "Бер", "Кві", "Тра", "Чер", "Лип", "Сер", "Вер", "Жов", "Лис", "Гру"]
[ { "context": "###\n *\n * jQuery PlaceholderText by Gary Hepting\n *\n * Open source under the MIT License.\n *\n * ", "end": 49, "score": 0.9998642206192017, "start": 37, "tag": "NAME", "value": "Gary Hepting" }, { "context": "rce under the MIT License.\n *\n * Copyright © 2013 ...
src/coffee/plugins/jquery-placeholderText.coffee
katophelix/PristinePooch
357
### * * jQuery PlaceholderText by Gary Hepting * * Open source under the MIT License. * * Copyright © 2013 Gary Hepting. All rights reserved. * ### (($) -> $.fn.placeholderText = (options) -> $.fn.placeholderText.defaults = type: "paragraphs" amount: "1" html: true punctuation: true opts = $.extend({}, $.fn.placeholderText.defaults, options) placeholder = new Array(10) placeholder[0] = "Nam quis nulla. Integer malesuada. In in enim a arcu imperdiet malesuada. Sed vel lectus. Donec odio urna, tempus molestie, porttitor ut, iaculis quis, sem. Phasellus rhoncus. Aenean id metus id velit ullamcorper pulvinar. Vestibulum fermentum tortor id mi. Pellentesque ipsum. Nulla non arcu lacinia neque faucibus fringilla. Nulla non lectus sed nisl molestie malesuada. Proin in tellus sit amet nibh dignissim sagittis. Vivamus luctus egestas leo. Maecenas sollicitudin. Nullam rhoncus aliquam metus. Etiam egestas wisi a erat." placeholder[1] = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nullam feugiat, turpis at pulvinar vulputate, erat libero tristique tellus, nec bibendum odio risus sit amet ante. Aliquam erat volutpat. Nunc auctor. Mauris pretium quam et urna. Fusce nibh. Duis risus. Curabitur sagittis hendrerit ante. Aliquam erat volutpat. Vestibulum erat nulla, ullamcorper nec, rutrum non, nonummy ac, erat. Duis condimentum augue id magna semper rutrum. Nullam justo enim, consectetuer nec, ullamcorper ac, vestibulum in, elit. Proin pede metus, vulputate nec, fermentum fringilla, vehicula vitae, justo. Fusce consectetuer risus a nunc. Aliquam ornare wisi eu metus. Integer pellentesque quam vel velit. Duis pulvinar." placeholder[2] = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Morbi gravida libero nec velit. Morbi scelerisque luctus velit. Etiam dui sem, fermentum vitae, sagittis id, malesuada in, quam. Proin mattis lacinia justo. Vestibulum facilisis auctor urna. Aliquam in lorem sit amet leo accumsan lacinia. Integer rutrum, orci vestibulum ullamcorper ultricies, lacus quam ultricies odio, vitae placerat pede sem sit amet enim. Phasellus et lorem id felis nonummy placerat. Fusce dui leo, imperdiet in, aliquam sit amet, feugiat eu, orci. Aenean vel massa quis mauris vehicula lacinia. Quisque tincidunt scelerisque libero. Maecenas libero. Etiam dictum tincidunt diam. Donec ipsum massa, ullamcorper in, auctor et, scelerisque sed, est. Suspendisse nisl. Sed convallis magna eu sem. Cras pede libero, dapibus nec, pretium sit amet, tempor quis, urna." placeholder[3] = "Etiam posuere quam ac quam. Maecenas aliquet accumsan leo. Nullam dapibus fermentum ipsum. Etiam quis quam. Integer lacinia. Nulla est. Nulla turpis magna, cursus sit amet, suscipit a, interdum id, felis. Integer vulputate sem a nibh rutrum consequat. Maecenas lorem. Pellentesque pretium lectus id turpis. Etiam sapien elit, consequat eget, tristique non, venenatis quis, ante. Fusce wisi. Phasellus faucibus molestie nisl. Fusce eget urna. Curabitur vitae diam non enim vestibulum interdum. Nulla quis diam. Ut tempus purus at lorem." placeholder[4] = "In sem justo, commodo ut, suscipit at, pharetra vitae, orci. Duis sapien nunc, commodo et, interdum suscipit, sollicitudin et, dolor. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam id dolor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris dictum facilisis augue. Fusce tellus. Pellentesque arcu. Maecenas fermentum, sem in pharetra pellentesque, velit turpis volutpat ante, in pharetra metus odio a lectus. Sed elit dui, pellentesque a, faucibus vel, interdum nec, diam. Mauris dolor felis, sagittis at, luctus sed, aliquam non, tellus. Etiam ligula pede, sagittis quis, interdum ultricies, scelerisque eu, urna. Nullam at arcu a est sollicitudin euismod. Praesent dapibus. Duis bibendum, lectus ut viverra rhoncus, dolor nunc faucibus libero, eget facilisis enim ipsum id lacus. Nam sed tellus id magna elementum tincidunt." placeholder[5] = "Morbi a metus. Phasellus enim erat, vestibulum vel, aliquam a, posuere eu, velit. Nullam sapien sem, ornare ac, nonummy non, lobortis a, enim. Nunc tincidunt ante vitae massa. Duis ante orci, molestie vitae, vehicula venenatis, tincidunt ac, pede. Nulla accumsan, elit sit amet varius semper, nulla mauris mollis quam, tempor suscipit diam nulla vel leo. Etiam commodo dui eget wisi. Donec iaculis gravida nulla. Donec quis nibh at felis congue commodo. Etiam bibendum elit eget erat." placeholder[6] = "Praesent in mauris eu tortor porttitor accumsan. Mauris suscipit, ligula sit amet pharetra semper, nibh ante cursus purus, vel sagittis velit mauris vel metus. Aenean fermentum risus id tortor. Integer imperdiet lectus quis justo. Integer tempor. Vivamus ac urna vel leo pretium faucibus. Mauris elementum mauris vitae tortor. In dapibus augue non sapien. Aliquam ante. Curabitur bibendum justo non orci." placeholder[7] = "Morbi leo mi, nonummy eget, tristique non, rhoncus non, leo. Nullam faucibus mi quis velit. Integer in sapien. Fusce tellus odio, dapibus id, fermentum quis, suscipit id, erat. Fusce aliquam vestibulum ipsum. Aliquam erat volutpat. Pellentesque sapien. Cras elementum. Nulla pulvinar eleifend sem. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Quisque porta. Vivamus porttitor turpis ac leo." placeholder[8] = "Maecenas ipsum velit, consectetuer eu, lobortis ut, dictum at, dui. In rutrum. Sed ac dolor sit amet purus malesuada congue. In laoreet, magna id viverra tincidunt, sem odio bibendum justo, vel imperdiet sapien wisi sed libero. Suspendisse sagittis ultrices augue. Mauris metus. Nunc dapibus tortor vel mi dapibus sollicitudin. Etiam posuere lacus quis dolor. Praesent id justo in neque elementum ultrices. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. In convallis. Fusce suscipit libero eget elit. Praesent vitae arcu tempor neque lacinia pretium. Morbi imperdiet, mauris ac auctor dictum, nisl ligula egestas nulla, et sollicitudin sem purus in lacus." placeholder[9] = "Aenean placerat. In vulputate urna eu arcu. Aliquam erat volutpat. Suspendisse potenti. Morbi mattis felis at nunc. Duis viverra diam non justo. In nisl. Nullam sit amet magna in magna gravida vehicula. Mauris tincidunt sem sed arcu. Nunc posuere. Nullam lectus justo, vulputate eget, mollis sed, tempor sed, magna. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Etiam neque. Curabitur ligula sapien, pulvinar a, vestibulum quis, facilisis vel, sapien. Nullam eget nisl. Donec vitae arcu." createPlaceholderContent = (el) -> options = {} options.type = $(el).data('placeholderType') if $(el).data('placeholderType') != 'undefined' options.amount = $(el).data('placeholderAmount') if $(el).data('placeholderAmount') != 'undefined' options.html = $(el).data('placeholderHtml') if $(el).data('placeholderHtml') != 'undefined' options.punctuation = $(el).data('placeholderPunctuation') if $(el).data('placeholderPunctuation') != 'undefined' opts = $.extend({}, $.fn.placeholderText.defaults, options) count = opts.amount placeholderText = "" i = 0 while i < count random = Math.floor( Math.random() * 10 ) placeholderText += "<p>" if opts.html placeholderText += placeholder[random] placeholderText += "</p>" if opts.html placeholderText += "\n\n" i++ switch opts.type when "words" numOfWords = opts.amount numOfWords = parseInt(numOfWords) list = new Array() wordList = new Array() wordList = placeholderText.split(" ") iParagraphCount = 0 iWordCount = 0 while list.length < numOfWords if iWordCount > wordList.length iWordCount = 0 iParagraphCount++ iParagraphCount = 0 if iParagraphCount + 1 > placeholder.length wordList = placeholder[iParagraphCount].split(" ") wordList[0] = "\n\n" + wordList[0] list.push wordList[iWordCount] iWordCount++ placeholderText = list.join(" ") break when "characters" outputString = "" numOfChars = opts.amount numOfChars = parseInt(numOfChars) tempString = placeholder.join("\n\n") outputString += tempString while outputString.length < numOfChars placeholderText = outputString.substring(0, numOfChars) break when "paragraphs" break unless opts.punctuation placeholderText = placeholderText.replace(",","").replace(".","") placeholderText @each -> $this = $(this) placeholderContent = createPlaceholderContent(@) $this.html(placeholderContent) ) jQuery $ -> $('.placeholderText').placeholderText()
160701
### * * jQuery PlaceholderText by <NAME> * * Open source under the MIT License. * * Copyright © 2013 <NAME>. All rights reserved. * ### (($) -> $.fn.placeholderText = (options) -> $.fn.placeholderText.defaults = type: "paragraphs" amount: "1" html: true punctuation: true opts = $.extend({}, $.fn.placeholderText.defaults, options) placeholder = new Array(10) placeholder[0] = "Nam quis nulla. Integer malesuada. In in enim a arcu imperdiet malesuada. Sed vel lectus. Donec odio urna, tempus molestie, porttitor ut, iaculis quis, sem. Phasellus rhoncus. Aenean id metus id velit ullamcorper pulvinar. Vestibulum fermentum tortor id mi. Pellentesque ipsum. Nulla non arcu lacinia neque faucibus fringilla. Nulla non lectus sed nisl molestie malesuada. Proin in tellus sit amet nibh dignissim sagittis. Vivamus luctus egestas leo. Maecenas sollicitudin. Nullam rhoncus aliquam metus. Etiam egestas wisi a erat." placeholder[1] = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nullam feugiat, turpis at pulvinar vulputate, erat libero tristique tellus, nec bibendum odio risus sit amet ante. Aliquam erat volutpat. Nunc auctor. Mauris pretium quam et urna. Fusce nibh. Duis risus. Curabitur sagittis hendrerit ante. Aliquam erat volutpat. Vestibulum erat nulla, ullamcorper nec, rutrum non, nonummy ac, erat. Duis condimentum augue id magna semper rutrum. Nullam justo enim, consectetuer nec, ullamcorper ac, vestibulum in, elit. Proin pede metus, vulputate nec, fermentum fringilla, vehicula vitae, justo. Fusce consectetuer risus a nunc. Aliquam ornare wisi eu metus. Integer pellentesque quam vel velit. Duis pulvinar." placeholder[2] = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Morbi gravida libero nec velit. Morbi scelerisque luctus velit. Etiam dui sem, fermentum vitae, sagittis id, malesuada in, quam. Proin mattis lacinia justo. Vestibulum facilisis auctor urna. Aliquam in lorem sit amet leo accumsan lacinia. Integer rutrum, orci vestibulum ullamcorper ultricies, lacus quam ultricies odio, vitae placerat pede sem sit amet enim. Phasellus et lorem id felis nonummy placerat. Fusce dui leo, imperdiet in, aliquam sit amet, feugiat eu, orci. Aenean vel massa quis mauris vehicula lacinia. Quisque tincidunt scelerisque libero. Maecenas libero. Etiam dictum tincidunt diam. Donec ipsum massa, ullamcorper in, auctor et, scelerisque sed, est. Suspendisse nisl. Sed convallis magna eu sem. Cras pede libero, dapibus nec, pretium sit amet, tempor quis, urna." placeholder[3] = "Etiam posuere quam ac quam. Maecenas aliquet accumsan leo. Nullam dapibus fermentum ipsum. Etiam quis quam. Integer lacinia. Nulla est. Nulla turpis magna, cursus sit amet, suscipit a, interdum id, felis. Integer vulputate sem a nibh rutrum consequat. Maecenas lorem. Pellentesque pretium lectus id turpis. Etiam sapien elit, consequat eget, tristique non, venenatis quis, ante. Fusce wisi. Phasellus faucibus molestie nisl. Fusce eget urna. Curabitur vitae diam non enim vestibulum interdum. Nulla quis diam. Ut tempus purus at lorem." placeholder[4] = "In sem justo, commodo ut, suscipit at, pharetra vitae, orci. Duis sapien nunc, commodo et, interdum suscipit, sollicitudin et, dolor. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam id dolor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris dictum facilisis augue. Fusce tellus. Pellentesque arcu. Maecenas fermentum, sem in pharetra pellentesque, velit turpis volutpat ante, in pharetra metus odio a lectus. Sed elit dui, pellentesque a, faucibus vel, interdum nec, diam. Mauris dolor felis, sagittis at, luctus sed, aliquam non, tellus. Etiam ligula pede, sagittis quis, interdum ultricies, scelerisque eu, urna. Nullam at arcu a est sollicitudin euismod. Praesent dapibus. Duis bibendum, lectus ut viverra rhoncus, dolor nunc faucibus libero, eget facilisis enim ipsum id lacus. Nam sed tellus id magna elementum tincidunt." placeholder[5] = "Morbi a metus. Phasellus enim erat, vestibulum vel, aliquam a, posuere eu, velit. Nullam sapien sem, ornare ac, nonummy non, lobortis a, enim. Nunc tincidunt ante vitae massa. Duis ante orci, molestie vitae, vehicula venenatis, tincidunt ac, pede. Nulla accumsan, elit sit amet varius semper, nulla mauris mollis quam, tempor suscipit diam nulla vel leo. Etiam commodo dui eget wisi. Donec iaculis gravida nulla. Donec quis nibh at felis congue commodo. Etiam bibendum elit eget erat." placeholder[6] = "Praesent in mauris eu tortor porttitor accumsan. Mauris suscipit, ligula sit amet pharetra semper, nibh ante cursus purus, vel sagittis velit mauris vel metus. Aenean fermentum risus id tortor. Integer imperdiet lectus quis justo. Integer tempor. Vivamus ac urna vel leo pretium faucibus. Mauris elementum mauris vitae tortor. In dapibus augue non sapien. Aliquam ante. Curabitur bibendum justo non orci." placeholder[7] = "Morbi leo mi, nonummy eget, tristique non, rhoncus non, leo. Nullam faucibus mi quis velit. Integer in sapien. Fusce tellus odio, dapibus id, fermentum quis, suscipit id, erat. Fusce aliquam vestibulum ipsum. Aliquam erat volutpat. Pellentesque sapien. Cras elementum. Nulla pulvinar eleifend sem. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Quisque porta. Vivamus porttitor turpis ac leo." placeholder[8] = "Maecenas ipsum velit, consectetuer eu, lobortis ut, dictum at, dui. In rutrum. Sed ac dolor sit amet purus malesuada congue. In laoreet, magna id viverra tincidunt, sem odio bibendum justo, vel imperdiet sapien wisi sed libero. Suspendisse sagittis ultrices augue. Mauris metus. Nunc dapibus tortor vel mi dapibus sollicitudin. Etiam posuere lacus quis dolor. Praesent id justo in neque elementum ultrices. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. In convallis. Fusce suscipit libero eget elit. Praesent vitae arcu tempor neque lacinia pretium. Morbi imperdiet, mauris ac auctor dictum, nisl ligula egestas nulla, et sollicitudin sem purus in lacus." placeholder[9] = "Aenean placerat. In vulputate urna eu arcu. Aliquam erat volutpat. Suspendisse potenti. Morbi mattis felis at nunc. Duis viverra diam non justo. In nisl. Nullam sit amet magna in magna gravida vehicula. Mauris tincidunt sem sed arcu. Nunc posuere. Nullam lectus justo, vulputate eget, mollis sed, tempor sed, magna. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Etiam neque. Curabitur ligula sapien, pulvinar a, vestibulum quis, facilisis vel, sapien. Nullam eget nisl. Donec vitae arcu." createPlaceholderContent = (el) -> options = {} options.type = $(el).data('placeholderType') if $(el).data('placeholderType') != 'undefined' options.amount = $(el).data('placeholderAmount') if $(el).data('placeholderAmount') != 'undefined' options.html = $(el).data('placeholderHtml') if $(el).data('placeholderHtml') != 'undefined' options.punctuation = $(el).data('placeholderPunctuation') if $(el).data('placeholderPunctuation') != 'undefined' opts = $.extend({}, $.fn.placeholderText.defaults, options) count = opts.amount placeholderText = "" i = 0 while i < count random = Math.floor( Math.random() * 10 ) placeholderText += "<p>" if opts.html placeholderText += placeholder[random] placeholderText += "</p>" if opts.html placeholderText += "\n\n" i++ switch opts.type when "words" numOfWords = opts.amount numOfWords = parseInt(numOfWords) list = new Array() wordList = new Array() wordList = placeholderText.split(" ") iParagraphCount = 0 iWordCount = 0 while list.length < numOfWords if iWordCount > wordList.length iWordCount = 0 iParagraphCount++ iParagraphCount = 0 if iParagraphCount + 1 > placeholder.length wordList = placeholder[iParagraphCount].split(" ") wordList[0] = "\n\n" + wordList[0] list.push wordList[iWordCount] iWordCount++ placeholderText = list.join(" ") break when "characters" outputString = "" numOfChars = opts.amount numOfChars = parseInt(numOfChars) tempString = placeholder.join("\n\n") outputString += tempString while outputString.length < numOfChars placeholderText = outputString.substring(0, numOfChars) break when "paragraphs" break unless opts.punctuation placeholderText = placeholderText.replace(",","").replace(".","") placeholderText @each -> $this = $(this) placeholderContent = createPlaceholderContent(@) $this.html(placeholderContent) ) jQuery $ -> $('.placeholderText').placeholderText()
true
### * * jQuery PlaceholderText by PI:NAME:<NAME>END_PI * * Open source under the MIT License. * * Copyright © 2013 PI:NAME:<NAME>END_PI. All rights reserved. * ### (($) -> $.fn.placeholderText = (options) -> $.fn.placeholderText.defaults = type: "paragraphs" amount: "1" html: true punctuation: true opts = $.extend({}, $.fn.placeholderText.defaults, options) placeholder = new Array(10) placeholder[0] = "Nam quis nulla. Integer malesuada. In in enim a arcu imperdiet malesuada. Sed vel lectus. Donec odio urna, tempus molestie, porttitor ut, iaculis quis, sem. Phasellus rhoncus. Aenean id metus id velit ullamcorper pulvinar. Vestibulum fermentum tortor id mi. Pellentesque ipsum. Nulla non arcu lacinia neque faucibus fringilla. Nulla non lectus sed nisl molestie malesuada. Proin in tellus sit amet nibh dignissim sagittis. Vivamus luctus egestas leo. Maecenas sollicitudin. Nullam rhoncus aliquam metus. Etiam egestas wisi a erat." placeholder[1] = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nullam feugiat, turpis at pulvinar vulputate, erat libero tristique tellus, nec bibendum odio risus sit amet ante. Aliquam erat volutpat. Nunc auctor. Mauris pretium quam et urna. Fusce nibh. Duis risus. Curabitur sagittis hendrerit ante. Aliquam erat volutpat. Vestibulum erat nulla, ullamcorper nec, rutrum non, nonummy ac, erat. Duis condimentum augue id magna semper rutrum. Nullam justo enim, consectetuer nec, ullamcorper ac, vestibulum in, elit. Proin pede metus, vulputate nec, fermentum fringilla, vehicula vitae, justo. Fusce consectetuer risus a nunc. Aliquam ornare wisi eu metus. Integer pellentesque quam vel velit. Duis pulvinar." placeholder[2] = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Morbi gravida libero nec velit. Morbi scelerisque luctus velit. Etiam dui sem, fermentum vitae, sagittis id, malesuada in, quam. Proin mattis lacinia justo. Vestibulum facilisis auctor urna. Aliquam in lorem sit amet leo accumsan lacinia. Integer rutrum, orci vestibulum ullamcorper ultricies, lacus quam ultricies odio, vitae placerat pede sem sit amet enim. Phasellus et lorem id felis nonummy placerat. Fusce dui leo, imperdiet in, aliquam sit amet, feugiat eu, orci. Aenean vel massa quis mauris vehicula lacinia. Quisque tincidunt scelerisque libero. Maecenas libero. Etiam dictum tincidunt diam. Donec ipsum massa, ullamcorper in, auctor et, scelerisque sed, est. Suspendisse nisl. Sed convallis magna eu sem. Cras pede libero, dapibus nec, pretium sit amet, tempor quis, urna." placeholder[3] = "Etiam posuere quam ac quam. Maecenas aliquet accumsan leo. Nullam dapibus fermentum ipsum. Etiam quis quam. Integer lacinia. Nulla est. Nulla turpis magna, cursus sit amet, suscipit a, interdum id, felis. Integer vulputate sem a nibh rutrum consequat. Maecenas lorem. Pellentesque pretium lectus id turpis. Etiam sapien elit, consequat eget, tristique non, venenatis quis, ante. Fusce wisi. Phasellus faucibus molestie nisl. Fusce eget urna. Curabitur vitae diam non enim vestibulum interdum. Nulla quis diam. Ut tempus purus at lorem." placeholder[4] = "In sem justo, commodo ut, suscipit at, pharetra vitae, orci. Duis sapien nunc, commodo et, interdum suscipit, sollicitudin et, dolor. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam id dolor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Mauris dictum facilisis augue. Fusce tellus. Pellentesque arcu. Maecenas fermentum, sem in pharetra pellentesque, velit turpis volutpat ante, in pharetra metus odio a lectus. Sed elit dui, pellentesque a, faucibus vel, interdum nec, diam. Mauris dolor felis, sagittis at, luctus sed, aliquam non, tellus. Etiam ligula pede, sagittis quis, interdum ultricies, scelerisque eu, urna. Nullam at arcu a est sollicitudin euismod. Praesent dapibus. Duis bibendum, lectus ut viverra rhoncus, dolor nunc faucibus libero, eget facilisis enim ipsum id lacus. Nam sed tellus id magna elementum tincidunt." placeholder[5] = "Morbi a metus. Phasellus enim erat, vestibulum vel, aliquam a, posuere eu, velit. Nullam sapien sem, ornare ac, nonummy non, lobortis a, enim. Nunc tincidunt ante vitae massa. Duis ante orci, molestie vitae, vehicula venenatis, tincidunt ac, pede. Nulla accumsan, elit sit amet varius semper, nulla mauris mollis quam, tempor suscipit diam nulla vel leo. Etiam commodo dui eget wisi. Donec iaculis gravida nulla. Donec quis nibh at felis congue commodo. Etiam bibendum elit eget erat." placeholder[6] = "Praesent in mauris eu tortor porttitor accumsan. Mauris suscipit, ligula sit amet pharetra semper, nibh ante cursus purus, vel sagittis velit mauris vel metus. Aenean fermentum risus id tortor. Integer imperdiet lectus quis justo. Integer tempor. Vivamus ac urna vel leo pretium faucibus. Mauris elementum mauris vitae tortor. In dapibus augue non sapien. Aliquam ante. Curabitur bibendum justo non orci." placeholder[7] = "Morbi leo mi, nonummy eget, tristique non, rhoncus non, leo. Nullam faucibus mi quis velit. Integer in sapien. Fusce tellus odio, dapibus id, fermentum quis, suscipit id, erat. Fusce aliquam vestibulum ipsum. Aliquam erat volutpat. Pellentesque sapien. Cras elementum. Nulla pulvinar eleifend sem. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Quisque porta. Vivamus porttitor turpis ac leo." placeholder[8] = "Maecenas ipsum velit, consectetuer eu, lobortis ut, dictum at, dui. In rutrum. Sed ac dolor sit amet purus malesuada congue. In laoreet, magna id viverra tincidunt, sem odio bibendum justo, vel imperdiet sapien wisi sed libero. Suspendisse sagittis ultrices augue. Mauris metus. Nunc dapibus tortor vel mi dapibus sollicitudin. Etiam posuere lacus quis dolor. Praesent id justo in neque elementum ultrices. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. In convallis. Fusce suscipit libero eget elit. Praesent vitae arcu tempor neque lacinia pretium. Morbi imperdiet, mauris ac auctor dictum, nisl ligula egestas nulla, et sollicitudin sem purus in lacus." placeholder[9] = "Aenean placerat. In vulputate urna eu arcu. Aliquam erat volutpat. Suspendisse potenti. Morbi mattis felis at nunc. Duis viverra diam non justo. In nisl. Nullam sit amet magna in magna gravida vehicula. Mauris tincidunt sem sed arcu. Nunc posuere. Nullam lectus justo, vulputate eget, mollis sed, tempor sed, magna. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Etiam neque. Curabitur ligula sapien, pulvinar a, vestibulum quis, facilisis vel, sapien. Nullam eget nisl. Donec vitae arcu." createPlaceholderContent = (el) -> options = {} options.type = $(el).data('placeholderType') if $(el).data('placeholderType') != 'undefined' options.amount = $(el).data('placeholderAmount') if $(el).data('placeholderAmount') != 'undefined' options.html = $(el).data('placeholderHtml') if $(el).data('placeholderHtml') != 'undefined' options.punctuation = $(el).data('placeholderPunctuation') if $(el).data('placeholderPunctuation') != 'undefined' opts = $.extend({}, $.fn.placeholderText.defaults, options) count = opts.amount placeholderText = "" i = 0 while i < count random = Math.floor( Math.random() * 10 ) placeholderText += "<p>" if opts.html placeholderText += placeholder[random] placeholderText += "</p>" if opts.html placeholderText += "\n\n" i++ switch opts.type when "words" numOfWords = opts.amount numOfWords = parseInt(numOfWords) list = new Array() wordList = new Array() wordList = placeholderText.split(" ") iParagraphCount = 0 iWordCount = 0 while list.length < numOfWords if iWordCount > wordList.length iWordCount = 0 iParagraphCount++ iParagraphCount = 0 if iParagraphCount + 1 > placeholder.length wordList = placeholder[iParagraphCount].split(" ") wordList[0] = "\n\n" + wordList[0] list.push wordList[iWordCount] iWordCount++ placeholderText = list.join(" ") break when "characters" outputString = "" numOfChars = opts.amount numOfChars = parseInt(numOfChars) tempString = placeholder.join("\n\n") outputString += tempString while outputString.length < numOfChars placeholderText = outputString.substring(0, numOfChars) break when "paragraphs" break unless opts.punctuation placeholderText = placeholderText.replace(",","").replace(".","") placeholderText @each -> $this = $(this) placeholderContent = createPlaceholderContent(@) $this.html(placeholderContent) ) jQuery $ -> $('.placeholderText').placeholderText()
[ { "context": "a9222-1f4e-4724-927f-a4390654fc57',\n token: '4401761cd274e79139ae4ec057ac5a2dd22dee2b'\n })\n\n ", "end": 734, "score": 0.7467632293701172, "start": 733, "tag": "KEY", "value": "4" }, { "context": "9222-1f4e-4724-927f-a4390654fc57',\n token: '4401761cd274e...
src/index.coffee
octoblu/meshblu-connector-motion-rpi
0
{EventEmitter} = require 'events' debug = require('debug')('meshblu-connector-motion-rpi:index') five = require 'johnny-five' Raspi = require 'raspi-io' moment = require 'moment' MeshbluSocketIO = require('meshblu') MeshbluHttp = require ('meshblu-http') _ = require 'lodash' class Connector extends EventEmitter constructor: -> @limitMinutes = 10 @validUntil = moment().utc().add(@limitMinutes, 'minutes') @board = new five.Board {io: new Raspi(),repl: false,debug: false} @board.on 'ready', @handleReady @meshblu = new MeshbluSocketIO({ resolveSrv: true, uuid: 'c15a9222-1f4e-4724-927f-a4390654fc57', token: '4401761cd274e79139ae4ec057ac5a2dd22dee2b' }) @meshblu.on 'ready', () => @watchForMeeting() @meshblu.connect() @meshblu.subscribe({uuid: 'c15a9222-1f4e-4724-927f-a4390654fc57'}) watchForMeeting: () => console.log 'watchForMeeting' @meshblu.on 'config', (event) => @checkMeeting event checkMeeting:(event) => currentMeeting = _.get event, 'genisys.currentMeeting' if currentMeeting? console.log "=====================================" console.log "curentMeeting found : ", currentMeeting console.log "validUntil as of now is : ", @validUntil.toISOString() meetingStartTime = _.get event, 'genisys.currentMeeting.startTime' noShowLimit = moment(meetingStartTime).utc().add(@limitMinutes, 'minutes') if (moment().isBefore(noShowLimit) && moment(@validUntil).isBefore(moment())) @validUntil = noShowLimit console.log "Initializing valid until to no show limit as : #{@validUntil.toISOString()}" if (moment(@validUntil).isBefore(moment().utc()) && moment().utc().isAfter(noShowLimit)) meetingId = _.get currentMeeting, 'meetingId' console.log "=====================================" console.log "Leaving meeting, validUntil: ", moment(@validUntil.toISOString()) console.log "Leaving meeting, current time: ", moment().toISOString() console.log "meetingStartTime: #{meetingStartTime} and No show limit :#{noShowLimit.toISOString()}" if moment().utc().isAfter(noShowLimit) @endMeeting meetingId endMeeting: (meetingId) => console.log 'Leaving meeting with meetingId:', meetingId @userMeshblu = new MeshbluHttp { resolveSrv: true, uuid: 'a11d2398-267d-4a80-99ed-70ca9771363e', token: '706bfc2e00e9734714c13e87845fa4d54ff53b15' } message = { devices: [ "*" ] metadata: jobType: "leave-meeting" data: meetingId: meetingId room: '$ref': "meshbludevice://c15a9222-1f4e-4724-927f-a4390654fc57" } console.log 'Leave Meeting message: ', message @userMeshblu.message message, (error) => console.log 'Error leaving meeting: ', error if error? return handleReady: () => @motion = new five.Motion 'P1-13' @motion.on 'calibrated', () => console.log 'Motion Sensor Calibrated' @motion.on 'change', @updateValidUntil updateValidUntil: () => @validUntil = moment().add(@limitMinutes, 'minutes').utc() console.log 'updateValidUntil Valid Until : ', @validUntil.toISOString() return isOnline: (callback) => callback null, running: true close: (callback) => debug 'on close' callback() onConfig: (device={}) => { @options } = device debug 'on config', @options start: (device, callback) => debug 'started' @onConfig device callback() module.exports = Connector
5783
{EventEmitter} = require 'events' debug = require('debug')('meshblu-connector-motion-rpi:index') five = require 'johnny-five' Raspi = require 'raspi-io' moment = require 'moment' MeshbluSocketIO = require('meshblu') MeshbluHttp = require ('meshblu-http') _ = require 'lodash' class Connector extends EventEmitter constructor: -> @limitMinutes = 10 @validUntil = moment().utc().add(@limitMinutes, 'minutes') @board = new five.Board {io: new Raspi(),repl: false,debug: false} @board.on 'ready', @handleReady @meshblu = new MeshbluSocketIO({ resolveSrv: true, uuid: 'c15a9222-1f4e-4724-927f-a4390654fc57', token: '<KEY> <PASSWORD>' }) @meshblu.on 'ready', () => @watchForMeeting() @meshblu.connect() @meshblu.subscribe({uuid: 'c15a9222-1f4e-4724-927f-a4390654fc57'}) watchForMeeting: () => console.log 'watchForMeeting' @meshblu.on 'config', (event) => @checkMeeting event checkMeeting:(event) => currentMeeting = _.get event, 'genisys.currentMeeting' if currentMeeting? console.log "=====================================" console.log "curentMeeting found : ", currentMeeting console.log "validUntil as of now is : ", @validUntil.toISOString() meetingStartTime = _.get event, 'genisys.currentMeeting.startTime' noShowLimit = moment(meetingStartTime).utc().add(@limitMinutes, 'minutes') if (moment().isBefore(noShowLimit) && moment(@validUntil).isBefore(moment())) @validUntil = noShowLimit console.log "Initializing valid until to no show limit as : #{@validUntil.toISOString()}" if (moment(@validUntil).isBefore(moment().utc()) && moment().utc().isAfter(noShowLimit)) meetingId = _.get currentMeeting, 'meetingId' console.log "=====================================" console.log "Leaving meeting, validUntil: ", moment(@validUntil.toISOString()) console.log "Leaving meeting, current time: ", moment().toISOString() console.log "meetingStartTime: #{meetingStartTime} and No show limit :#{noShowLimit.toISOString()}" if moment().utc().isAfter(noShowLimit) @endMeeting meetingId endMeeting: (meetingId) => console.log 'Leaving meeting with meetingId:', meetingId @userMeshblu = new MeshbluHttp { resolveSrv: true, uuid: 'a11d2398-267d-4a80-99ed-70ca9771363e', token: '<KEY> <PASSWORD>' } message = { devices: [ "*" ] metadata: jobType: "leave-meeting" data: meetingId: meetingId room: '$ref': "meshbludevice://c15a9222-1f4e-4724-927f-a4390654fc57" } console.log 'Leave Meeting message: ', message @userMeshblu.message message, (error) => console.log 'Error leaving meeting: ', error if error? return handleReady: () => @motion = new five.Motion 'P1-13' @motion.on 'calibrated', () => console.log 'Motion Sensor Calibrated' @motion.on 'change', @updateValidUntil updateValidUntil: () => @validUntil = moment().add(@limitMinutes, 'minutes').utc() console.log 'updateValidUntil Valid Until : ', @validUntil.toISOString() return isOnline: (callback) => callback null, running: true close: (callback) => debug 'on close' callback() onConfig: (device={}) => { @options } = device debug 'on config', @options start: (device, callback) => debug 'started' @onConfig device callback() module.exports = Connector
true
{EventEmitter} = require 'events' debug = require('debug')('meshblu-connector-motion-rpi:index') five = require 'johnny-five' Raspi = require 'raspi-io' moment = require 'moment' MeshbluSocketIO = require('meshblu') MeshbluHttp = require ('meshblu-http') _ = require 'lodash' class Connector extends EventEmitter constructor: -> @limitMinutes = 10 @validUntil = moment().utc().add(@limitMinutes, 'minutes') @board = new five.Board {io: new Raspi(),repl: false,debug: false} @board.on 'ready', @handleReady @meshblu = new MeshbluSocketIO({ resolveSrv: true, uuid: 'c15a9222-1f4e-4724-927f-a4390654fc57', token: 'PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI' }) @meshblu.on 'ready', () => @watchForMeeting() @meshblu.connect() @meshblu.subscribe({uuid: 'c15a9222-1f4e-4724-927f-a4390654fc57'}) watchForMeeting: () => console.log 'watchForMeeting' @meshblu.on 'config', (event) => @checkMeeting event checkMeeting:(event) => currentMeeting = _.get event, 'genisys.currentMeeting' if currentMeeting? console.log "=====================================" console.log "curentMeeting found : ", currentMeeting console.log "validUntil as of now is : ", @validUntil.toISOString() meetingStartTime = _.get event, 'genisys.currentMeeting.startTime' noShowLimit = moment(meetingStartTime).utc().add(@limitMinutes, 'minutes') if (moment().isBefore(noShowLimit) && moment(@validUntil).isBefore(moment())) @validUntil = noShowLimit console.log "Initializing valid until to no show limit as : #{@validUntil.toISOString()}" if (moment(@validUntil).isBefore(moment().utc()) && moment().utc().isAfter(noShowLimit)) meetingId = _.get currentMeeting, 'meetingId' console.log "=====================================" console.log "Leaving meeting, validUntil: ", moment(@validUntil.toISOString()) console.log "Leaving meeting, current time: ", moment().toISOString() console.log "meetingStartTime: #{meetingStartTime} and No show limit :#{noShowLimit.toISOString()}" if moment().utc().isAfter(noShowLimit) @endMeeting meetingId endMeeting: (meetingId) => console.log 'Leaving meeting with meetingId:', meetingId @userMeshblu = new MeshbluHttp { resolveSrv: true, uuid: 'a11d2398-267d-4a80-99ed-70ca9771363e', token: 'PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI' } message = { devices: [ "*" ] metadata: jobType: "leave-meeting" data: meetingId: meetingId room: '$ref': "meshbludevice://c15a9222-1f4e-4724-927f-a4390654fc57" } console.log 'Leave Meeting message: ', message @userMeshblu.message message, (error) => console.log 'Error leaving meeting: ', error if error? return handleReady: () => @motion = new five.Motion 'P1-13' @motion.on 'calibrated', () => console.log 'Motion Sensor Calibrated' @motion.on 'change', @updateValidUntil updateValidUntil: () => @validUntil = moment().add(@limitMinutes, 'minutes').utc() console.log 'updateValidUntil Valid Until : ', @validUntil.toISOString() return isOnline: (callback) => callback null, running: true close: (callback) => debug 'on close' callback() onConfig: (device={}) => { @options } = device debug 'on config', @options start: (device, callback) => debug 'started' @onConfig device callback() module.exports = Connector
[ { "context": "# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public Li", "end": 43, "score": 0.9999147653579712, "start": 29, "tag": "EMAIL", "value": "contact@ppy.sh" } ]
resources/assets/coffee/store.coffee
osu-katakuna/osu-katakuna-web
5
# Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. # address form show/hide. $(document).on 'click', '#new-address-switch a', (e) -> e.preventDefault() $target = $(e.target) $form = $('#new-address-form') if $target.is(':visible') $target.siblings('button').show() $target.hide() $form.find('input').first().focus() else $target.siblings('button').hide() $target.show() $form.slideToggle() #checkout checks checkCheckoutConfirmations = -> $checkboxes = $('.js-checkout-confirmation-step') $checkboxesChecked = $checkboxes.filter(':checked') $(document).on 'turbolinks:load', checkCheckoutConfirmations $(document).on 'change', '.js-checkout-confirmation-step', checkCheckoutConfirmations $(document).on 'turbolinks:load', -> quantity = parseInt $('.js-store-item-quantity').val(), 10 return if quantity > 0 $('.js-store-add-to-cart').hide() $(document).on 'turbolinks:load', -> # delegating doesn't work because of timing. $('#product-form').submit (e) -> !$(e.target).data('disabled')
107941
# Copyright (c) ppy Pty Ltd <<EMAIL>>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. # address form show/hide. $(document).on 'click', '#new-address-switch a', (e) -> e.preventDefault() $target = $(e.target) $form = $('#new-address-form') if $target.is(':visible') $target.siblings('button').show() $target.hide() $form.find('input').first().focus() else $target.siblings('button').hide() $target.show() $form.slideToggle() #checkout checks checkCheckoutConfirmations = -> $checkboxes = $('.js-checkout-confirmation-step') $checkboxesChecked = $checkboxes.filter(':checked') $(document).on 'turbolinks:load', checkCheckoutConfirmations $(document).on 'change', '.js-checkout-confirmation-step', checkCheckoutConfirmations $(document).on 'turbolinks:load', -> quantity = parseInt $('.js-store-item-quantity').val(), 10 return if quantity > 0 $('.js-store-add-to-cart').hide() $(document).on 'turbolinks:load', -> # delegating doesn't work because of timing. $('#product-form').submit (e) -> !$(e.target).data('disabled')
true
# Copyright (c) ppy Pty Ltd <PI:EMAIL:<EMAIL>END_PI>. Licensed under the GNU Affero General Public License v3.0. # See the LICENCE file in the repository root for full licence text. # address form show/hide. $(document).on 'click', '#new-address-switch a', (e) -> e.preventDefault() $target = $(e.target) $form = $('#new-address-form') if $target.is(':visible') $target.siblings('button').show() $target.hide() $form.find('input').first().focus() else $target.siblings('button').hide() $target.show() $form.slideToggle() #checkout checks checkCheckoutConfirmations = -> $checkboxes = $('.js-checkout-confirmation-step') $checkboxesChecked = $checkboxes.filter(':checked') $(document).on 'turbolinks:load', checkCheckoutConfirmations $(document).on 'change', '.js-checkout-confirmation-step', checkCheckoutConfirmations $(document).on 'turbolinks:load', -> quantity = parseInt $('.js-store-item-quantity').val(), 10 return if quantity > 0 $('.js-store-add-to-cart').hide() $(document).on 'turbolinks:load', -> # delegating doesn't work because of timing. $('#product-form').submit (e) -> !$(e.target).data('disabled')
[ { "context": "ay.from suffix\n # if S.two_stats then key = \"#{infix},#{infix}#{suffix[ 0 ]}\"\n # else key = ", "end": 12199, "score": 0.9887714982032776, "start": 12179, "tag": "KEY", "value": "\"#{infix},#{infix}#{" }, { "context": "o_stats then key = ...
src/show-kwic-v3.coffee
loveencounterflow/jizura
0
### `@$align_affixes_with_braces` ```keep-lines squish: yes    「【虫】」    虫   「冄【阝】」    𨙻    「【冄】阝」   𨙻  「穴扌【未】」    𥦤   「穴【扌】未」   𥦤    「【穴】扌未」  𥦤 「日业䒑【未】」    曗  「日业【䒑】未」   曗   「日【业】䒑未」  曗    「【日】业䒑未」 曗 日𠂇⺝【阝】」  「禾 𩡏 「禾日𠂇【⺝】阝」   𩡏  「禾日【𠂇】⺝阝」  𩡏   「禾【日】𠂇⺝阝」 𩡏 阝」  「【禾】日𠂇⺝ 𩡏 木冖鬯【彡】」 「木缶 鬱 缶木冖【鬯】彡」 「木 鬱 「木缶木【冖】鬯彡」  鬱  「木缶【木】冖鬯彡」 鬱 彡」 「木【缶】木冖鬯 鬱 鬯彡」 「【木】缶木冖 鬱 山一几【夊】」「女山彳 𡤇 彳山一【几】夊」「女山 𡤇 山彳山【一】几夊」「女 𡤇 「女山彳【山】一几夊」 𡤇 夊」「女山【彳】山一几 𡤇 几夊」「女【山】彳山一 𡤇 一几夊」「【女】山彳山 𡤇 目𠃊八【夊】」「二小 𥜹 匕目𠃊【八】夊」「二 𥜹 小匕目【𠃊】八夊」「 𥜹 二小匕【目】𠃊八夊」 𥜹 「二小【匕】目𠃊八 𥜹 夊」「二【小】匕目𠃊 𥜹 八夊」「【二】小匕目 𥜹 𠃊八夊」「【】二小匕 𥜹 ``` `align_affixes_with_spaces` ```keep-lines squish: yes    【虫】    虫   冄【阝】    𨙻    【冄】阝   𨙻  穴扌【未】    𥦤   穴【扌】未   𥦤    【穴】扌未  𥦤 日业䒑【未】    曗  日业【䒑】未   曗   日【业】䒑未  曗    【日】业䒑未 曗 日𠂇⺝【阝】  禾 𩡏 禾日𠂇【⺝】阝   𩡏  禾日【𠂇】⺝阝  𩡏   禾【日】𠂇⺝阝 𩡏 阝  【禾】日𠂇⺝ 𩡏 木冖鬯【彡】 木缶 鬱 缶木冖【鬯】彡 木 鬱 木缶木【冖】鬯彡  鬱  木缶【木】冖鬯彡 鬱 彡 木【缶】木冖鬯 鬱 鬯彡 【木】缶木冖 鬱 山一几【夊】 女山 𡤇 彳山一【几】夊 女 𡤇 山彳山【一】几夊  𡤇 女山彳【山】一几夊 𡤇  女山【彳】山一几 𡤇 夊 女【山】彳山一 𡤇 几夊 【女】山彳山 𡤇 目𠃊八【夊】 二 𥜹 匕目𠃊【八】夊  𥜹 小匕目【𠃊】八夊  𥜹 二小匕【目】𠃊八夊 𥜹 二小【匕】目𠃊八 𥜹  二【小】匕目𠃊 𥜹 夊 【二】小匕目 𥜹 八夊 【】二小匕 𥜹 ``` ### ############################################################################################################ njs_path = require 'path' njs_fs = require 'fs' join = njs_path.join #........................................................................................................... CND = require 'cnd' rpr = CND.rpr badge = 'JIZURA/show-kwic-v3' 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 after = suspend.after eventually = suspend.eventually immediately = suspend.immediately repeat_immediately = suspend.repeat_immediately every = suspend.every #........................................................................................................... # BYTEWISE = require 'bytewise' # through = require 'through2' # LevelBatch = require 'level-batch-stream' # BatchStream = require 'batch-stream' # parallel = require 'concurrent-writable' D = require 'pipedreams' $ = D.remit.bind D $async = D.remit_async.bind D ASYNC = require 'async' CHR = require 'coffeenode-chr' KWIC = require 'kwic' TEXT = require 'coffeenode-text' #........................................................................................................... new_db = require 'level' # new_levelgraph = require 'levelgraph' # db = new_levelgraph '/tmp/levelgraph' HOLLERITH = require 'hollerith' ƒ = CND.format_number.bind CND #........................................................................................................... options = null #----------------------------------------------------------------------------------------------------------- @_misfit = Symbol 'misfit' #----------------------------------------------------------------------------------------------------------- @read_sample = ( db, limit_or_list, handler ) -> ### Return a gamut of select glyphs from the DB. `limit_or_list` may be a list of glyphs or a number representing an upper bound to the usage rank recorded as `rank/cjt`. If `limit_or_list` is a list, a POD whose keys are the glyphs in the list is returned; if it is a number, a similar POD with all the glyphs whose rank is not worse than the given limit is returned. If `limit_or_list` is smaller than zero or equals infinity, `null` is returned to indicate absence of a filter. ### Z = {} #......................................................................................................... if CND.isa_list limit_or_list Z[ glyph ] = 1 for glyph in limit_or_list return handler null, Z #......................................................................................................... return handler null, null if limit_or_list < 0 or limit_or_list is Infinity #......................................................................................................... throw new Error "expected list or number, got a #{type}" unless CND.isa_number limit_or_list #......................................................................................................... db_route = join __dirname, '../../jizura-datasources/data/leveldb-v2' db ?= HOLLERITH.new_db db_route, create: no #......................................................................................................... lo = [ 'pos', 'rank/cjt', 0, ] hi = [ 'pos', 'rank/cjt', limit_or_list, ] query = { lo, hi, } input = HOLLERITH.create_phrasestream db, query #......................................................................................................... input .pipe $ ( phrase, send ) => [ _, _, _, glyph, ] = phrase Z[ glyph ] = 1 .pipe D.$on_end -> handler null, Z #----------------------------------------------------------------------------------------------------------- @_describe_glyph_sample = ( S ) -> if S.glyph_sample is Infinity ### TAINT font substitution should be configured in options or other appropriate place ### return "gamut of *N* <<<{\\mktsFontfileOptima{}≈}>>> #{CND.format_number 75000, ','} glyphs" else if CND.isa_number S.glyph_sample return "gamut of *N* = #{CND.format_number S.glyph_sample, ','} glyphs" else return "selected glyphs: #{S.glyph_sample.join ''}" #----------------------------------------------------------------------------------------------------------- @describe_glyphs = ( S ) -> R = [] R.push "<<(em>> ___KWIC___ Index for " if S.factor_sample? and ( factors = Object.keys S.factor_sample ).length > 0 plural = if factors.length > 1 then 's' else '' R.push "factor#{plural} #{factors.join ''}; " R.push ( @_describe_glyph_sample S ) + ':<<)>>' return R.join '\n' #----------------------------------------------------------------------------------------------------------- @describe_stats = ( S ) -> # debug '9080', S return "(no stats)" unless S.do_stats return "XXXXX" unless S.factor_sample? factors = Object.keys S.factor_sample if factors.length is 1 plural = "" pronoun = "its" else plural = "s" pronoun = "their" R = [] R.push "<<(em>>Statistics for factor#{plural} #{factors.join ''}" if S.two_stats then R.push "and #{pronoun} immediate suffix and prefix factors" else R.push "and #{pronoun} immediate suffix factors" R.push " (\ue045 indicates first/last position);" R.push ( @_describe_glyph_sample S ) + ':<<)>>' return R.join '\n' #----------------------------------------------------------------------------------------------------------- @show_kwic_v3 = ( S ) -> #......................................................................................................... # factor_sample = # '旧日卓桌𠦝東車更㯥䡛轟𨏿昍昌晶𣊭早畢果𣛕𣡗𣡾曱甲𤳅𤳵申𤱓禺𥝉㬰电田畕畾𤳳由甴𡆪白㿟皛鱼魚䲆𩺰鱻䲜' # factor_sample = '旧日卓桌𠦝昍昌晶𣊭早白㿟皛' # factor_sample = '耂' #......................................................................................................... ### TAINT temporary; going to use sets ### if S.factor_sample? _fs = {} _fs[ factor ] = 1 for factor in S.factor_sample S.factor_sample = _fs #......................................................................................................... S.glyphs_description = @describe_glyphs S S.stats_description = @describe_stats S urge S.glyphs_description urge S.stats_description #......................................................................................................... S.query = { prefix: [ 'pos', 'guide/kwic/v3/sortcode/wrapped-lineups', ], } S.db_route = join __dirname, '../../jizura-datasources/data/leveldb-v2' S.db = HOLLERITH.new_db S.db_route, create: no # S = { db_route, db, query, glyph_sample, factor_sample, handler, } help "using DB at #{S.db[ '%self' ][ 'location' ]}" #......................................................................................................... step ( resume ) => #....................................................................................................... S.glyph_sample = yield @read_sample S.db, S.glyph_sample, resume # debug '9853', ( Object.keys S.glyph_sample ).length input = ( HOLLERITH.create_phrasestream S.db, S.query ).pipe $transform_v3 S # handler null return null #......................................................................................................... return null #----------------------------------------------------------------------------------------------------------- $reorder_phrase = ( S ) => return $ ( phrase, send ) => ### extract sortcode ### [ _, _, sortrow, glyph, _, ] = phrase [ _, infix, suffix, prefix, ] = sortrow send [ glyph, prefix, infix, suffix, ] #----------------------------------------------------------------------------------------------------------- $exclude_gaiji = ( S ) => return D.$filter ( event ) => [ glyph, ] = event return ( not glyph.startsWith '&' ) or ( glyph.startsWith '&jzr#' ) #----------------------------------------------------------------------------------------------------------- $include_sample = ( S ) => return D.$filter ( event ) => # [ _, infix, suffix, prefix, ] = sortcode # factors = [ prefix..., infix, suffix...,] # return ( infix is '山' ) and ( '水' in factors ) return true if ( not S.glyph_sample? ) and ( not S.factor_sample? ) [ glyph, prefix, infix, suffix, ] = event in_glyph_sample = ( not S.glyph_sample? ) or ( glyph of S.glyph_sample ) in_factor_sample = ( not S.factor_sample? ) or ( infix of S.factor_sample ) return in_glyph_sample and in_factor_sample #----------------------------------------------------------------------------------------------------------- $write_stats = ( S ) => return D.$pass_through() unless S.do_stats glyphs = new Set() ### NB that we use a JS `Set` to record unique infixes; it has the convenient property of keeping the insertion order of its elements, so afterwards we can use it to determine the infix ordering. ### infixes = new Set() factor_pairs = new Map() lineup_count = 0 output = njs_fs.createWriteStream S.stats_route line_count = 0 in_suffix_part = no #......................................................................................................... return D.$observe ( event, has_ended ) => if event? #..................................................................................................... if CND.isa_list event [ glyph, prefix, infix, suffix, ] = event #................................................................................................... if suffix.startsWith '\u3000' then suffix = '\ue045' else suffix = suffix.trim() suffix = Array.from suffix # if S.two_stats then key = "#{infix},#{infix}#{suffix[ 0 ]}" # else key = "#{infix},#{infix}#{suffix[ 0 ]}-1" key = "#{infix},#{infix}#{suffix[ 0 ]},1" factor_pairs.set key, target = new Set() unless ( target = factor_pairs.get key )? target.add glyph #................................................................................................... if S.with_prefixes if prefix.endsWith '\u3000' then prefix = '\ue045' else prefix = prefix.trim() prefix = Array.from prefix key = "#{infix},#{prefix[ prefix.length - 1 ]}#{infix},2" factor_pairs.set key, target = new Set() unless ( target = factor_pairs.get key )? target.add glyph #................................................................................................... infixes.add infix glyphs.add glyph lineup_count += +1 #....................................................................................................... if has_ended help "built KWIC for #{ƒ glyphs.size} glyphs" help "containing #{ƒ lineup_count} lineups" infixes = Array.from infixes factor_pairs = Array.from factor_pairs for entry in factor_pairs entry[ 0 ] = entry[ 0 ].split ',' entry[ 0 ][ 2 ] = parseInt entry[ 0 ][ 2 ], 10 entry[ 1 ] = Array.from entry[ 1 ] #..................................................................................................... factor_pairs.sort ( a, b ) -> [ [ a_infix, a_pair, a_series, ], a_glyphs, ] = a [ [ b_infix, b_pair, b_series, ], b_glyphs, ] = b a_infix_idx = infixes.indexOf a_infix b_infix_idx = infixes.indexOf b_infix if S.two_stats return +1 if a_series > b_series return -1 if a_series < b_series return +1 if a_infix_idx > b_infix_idx return -1 if a_infix_idx < b_infix_idx return +1 if a_glyphs.length < b_glyphs.length return -1 if a_glyphs.length > b_glyphs.length return +1 if a_pair > b_pair return -1 if a_pair < b_pair return 0 #..................................................................................................... ### TAINT column count should be accessible through CLI and otherwise be calculated according to paper size and lineup lengths ### output.write "<<(columns 4>><<(JZR.vertical-bar>>\n" output.write "```keep-lines squish: yes\n" #..................................................................................................... last_infix = null last_series = null separator = '】' for [ [ infix, factor_pair, series, ], glyphs, ] in factor_pairs #................................................................................................... if S.two_stats and last_series? and last_series isnt series in_suffix_part = yes output.write "```\n" # output.write "<<)>><<)>>\n" output.write "\n/0------------------------------0/\n\n" # output.write "<<(columns 4>><<(JZR.vertical-bar>>\n" output.write "```keep-lines squish: yes\n" output.write "——.\ue023#{infix}.——\n" #................................................................................................... else if last_infix isnt infix if S.two_stats unless in_suffix_part then output.write "——.#{infix}\ue023.——\n" else output.write "——.\ue023#{infix}.——\n" else output.write "——.\ue023#{infix}\ue023.——\n" last_infix = infix last_series = series #................................................................................................... glyph_count = glyphs.length # if glyph_count > 999 then glyph_count_txt = "<<<{\\tfScale{0.5}{1}#{glyph_count}}>>>#{glyph_count}" glyph_count_txt = "#{glyph_count}" if S.width? glyphs.push '\u3000' while glyphs.length < S.width glyphs.pop() while glyphs.length > S.width line = [ factor_pair, separator, ( glyphs.join '' ), '==>', glyph_count_txt, '\n', ].join '' output.write line line_count += +1 #..................................................................................................... output.write "```\n" output.write "<<)>><<)>>\n" output.end() help "found #{infixes.length} infixes" help "wrote #{line_count} lines to #{S.stats_route}" S.handler null if S.handler? #......................................................................................................... return null #----------------------------------------------------------------------------------------------------------- $write_glyphs = ( S ) => output = njs_fs.createWriteStream S.glyphs_route line_count = 0 is_first = yes last_infix = null empty_prefix = '\u3000\u3000\u3000' #......................................................................................................... return D.$observe ( event, has_ended ) -> #....................................................................................................... if event? if CND.isa_list event if is_first ### TAINT column count should be accessible through CLI and otherwise be calculated according to paper size and lineup lengths ### output.write "<<(columns 4>><<(JZR.vertical-bar>>\n" output.write "```keep-lines squish: yes\n" is_first = no [ glyph, prefix, infix, suffix, ] = event if ( infix isnt last_infix ) and ( glyph isnt infix ) # output.write "——.#{infix}.——\n" output.write empty_prefix + '【' + infix + '】' + '\n' output.write prefix + '【' + infix + '】' + suffix + '==>' + glyph + '\n' last_infix = infix else output.write event + '\n' line_count += +1 #....................................................................................................... if has_ended output.write "```\n" output.write "<<)>><<)>>\n" help "wrote #{line_count} lines to #{S.glyphs_route}" output.end() #----------------------------------------------------------------------------------------------------------- $write_glyphs_description = ( S ) => output = njs_fs.createWriteStream S.glyphs_description_route #......................................................................................................... return D.$observe ( event, has_ended ) -> if has_ended output.write S.glyphs_description help "wrote glyphs description to #{S.glyphs_description_route}" output.end() #----------------------------------------------------------------------------------------------------------- $write_stats_description = ( S ) => return D.$pass_through() unless S.do_stats output = njs_fs.createWriteStream S.stats_description_route #......................................................................................................... return D.$observe ( event, has_ended ) -> if has_ended output.write S.stats_description help "wrote stats description to #{S.stats_description_route}" output.end() # #----------------------------------------------------------------------------------------------------------- # $count_lineup_lengths = ( S ) => # counts = [] # count = 0 # #......................................................................................................... # return $ ( event, send, end ) => # if event? # #..................................................................................................... # if CND.isa_list event # [ glyph, sortcode, ] = event # [ _, infix, suffix, prefix, ] = sortcode # lineup = ( prefix.join '' ) + infix + ( suffix.join '' ) # lineup_length = ( Array.from lineup.replace /\u3000/g, '' ).length # if true # lineup_length is 8 # send event # counts[ lineup_length ] = ( counts[ lineup_length ] ? 0 ) + 1 # #..................................................................................................... # else # send event # #....................................................................................................... # if end? # for length in [ 1 ... counts.length ] # count_txt = TEXT.flush_right ( ƒ counts[ length ] ? 0 ), 10 # help "found #{count_txt} lineups of length #{length}" # end() # #----------------------------------------------------------------------------------------------------------- # @$align_affixes_with_braces = ( S ) => # prefix_max_length = 3 # suffix_max_length = 3 # #......................................................................................................... # return $ ( event, send ) => # #....................................................................................................... # if CND.isa_list event # [ glyph, sortcode, ] = event # [ _, infix, suffix, prefix, ] = sortcode # #..................................................................................................... # 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 = [] # prefix_is_shortened = no # suffix_is_shortened = no # #..................................................................................................... # 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 # prefix_is_shortened = yes # prefix_excess.pop() # while suffix_excess.length > 0 and suffix_excess.length > suffix_excess_max_length # suffix_is_shortened = yes # 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' # #..................................................................................................... # if prefix_excess.length > 0 then prefix_excess.unshift '「' unless prefix_excess.length is 0 # else prefix.unshift '「' unless prefix_delta > 0 # if suffix_excess.length > 0 then suffix_excess.push '」' unless suffix_excess.length is 0 # else suffix.push '」' unless suffix_delta > 0 # #..................................................................................................... # 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... # #..................................................................................................... # urge ( prefix.join '' ) + '【' + infix + '】' + ( suffix.join '' ) # # send [ glyph, [ prefix_padding, suffix_excess, prefix, infix, suffix, prefix_excess, ], ] # send [ glyph, [ prefix, infix, suffix, ], ] # #....................................................................................................... # else # send event # #----------------------------------------------------------------------------------------------------------- # @$align_affixes_with_spaces = ( S ) => # ### This code has been used in `copy-jizuradb-to-Hollerith2-format#add_kwic_v3_wrapped_lineups` ### # prefix_max_length = 3 # suffix_max_length = 3 # #......................................................................................................... # return $ ( event, send ) => # #....................................................................................................... # if CND.isa_list event # [ glyph, sortcode, ] = event # [ _, infix, suffix, prefix, ] = sortcode # #..................................................................................................... # 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... # #..................................................................................................... # urge ( prefix.join '' ) + '【' + infix + '】' + ( suffix.join '' ) # # send [ glyph, [ prefix_padding, suffix_excess, prefix, infix, suffix, prefix_excess, ], ] # send [ glyph, [ prefix, infix, suffix, ], ] # #....................................................................................................... # else # send event #----------------------------------------------------------------------------------------------------------- $transform_v3 = ( S ) => return D.combine [ $reorder_phrase S $exclude_gaiji S $include_sample S # $count_lineup_lengths S # @$align_affixes_with_braces S # @$align_affixes_with_spaces S $write_stats S $write_glyphs S $write_glyphs_description S $write_stats_description S D.$on_end => S.handler null if S.handler? ] # ############################################################################################################ # unless module.parent? # #--------------------------------------------------------------------------------------------------------- # options = # #....................................................................................................... # # 'route': njs_path.join __dirname, '../dbs/demo' # 'route': njs_path.resolve __dirname, '../../jizura-datasources/data/leveldb-v2' # # 'route': '/tmp/leveldb' # #--------------------------------------------------------------------------------------------------------- # @show_kwic_v3()
76165
### `@$align_affixes_with_braces` ```keep-lines squish: yes    「【虫】」    虫   「冄【阝】」    𨙻    「【冄】阝」   𨙻  「穴扌【未】」    𥦤   「穴【扌】未」   𥦤    「【穴】扌未」  𥦤 「日业䒑【未】」    曗  「日业【䒑】未」   曗   「日【业】䒑未」  曗    「【日】业䒑未」 曗 日𠂇⺝【阝】」  「禾 𩡏 「禾日𠂇【⺝】阝」   𩡏  「禾日【𠂇】⺝阝」  𩡏   「禾【日】𠂇⺝阝」 𩡏 阝」  「【禾】日𠂇⺝ 𩡏 木冖鬯【彡】」 「木缶 鬱 缶木冖【鬯】彡」 「木 鬱 「木缶木【冖】鬯彡」  鬱  「木缶【木】冖鬯彡」 鬱 彡」 「木【缶】木冖鬯 鬱 鬯彡」 「【木】缶木冖 鬱 山一几【夊】」「女山彳 𡤇 彳山一【几】夊」「女山 𡤇 山彳山【一】几夊」「女 𡤇 「女山彳【山】一几夊」 𡤇 夊」「女山【彳】山一几 𡤇 几夊」「女【山】彳山一 𡤇 一几夊」「【女】山彳山 𡤇 目𠃊八【夊】」「二小 𥜹 匕目𠃊【八】夊」「二 𥜹 小匕目【𠃊】八夊」「 𥜹 二小匕【目】𠃊八夊」 𥜹 「二小【匕】目𠃊八 𥜹 夊」「二【小】匕目𠃊 𥜹 八夊」「【二】小匕目 𥜹 𠃊八夊」「【】二小匕 𥜹 ``` `align_affixes_with_spaces` ```keep-lines squish: yes    【虫】    虫   冄【阝】    𨙻    【冄】阝   𨙻  穴扌【未】    𥦤   穴【扌】未   𥦤    【穴】扌未  𥦤 日业䒑【未】    曗  日业【䒑】未   曗   日【业】䒑未  曗    【日】业䒑未 曗 日𠂇⺝【阝】  禾 𩡏 禾日𠂇【⺝】阝   𩡏  禾日【𠂇】⺝阝  𩡏   禾【日】𠂇⺝阝 𩡏 阝  【禾】日𠂇⺝ 𩡏 木冖鬯【彡】 木缶 鬱 缶木冖【鬯】彡 木 鬱 木缶木【冖】鬯彡  鬱  木缶【木】冖鬯彡 鬱 彡 木【缶】木冖鬯 鬱 鬯彡 【木】缶木冖 鬱 山一几【夊】 女山 𡤇 彳山一【几】夊 女 𡤇 山彳山【一】几夊  𡤇 女山彳【山】一几夊 𡤇  女山【彳】山一几 𡤇 夊 女【山】彳山一 𡤇 几夊 【女】山彳山 𡤇 目𠃊八【夊】 二 𥜹 匕目𠃊【八】夊  𥜹 小匕目【𠃊】八夊  𥜹 二小匕【目】𠃊八夊 𥜹 二小【匕】目𠃊八 𥜹  二【小】匕目𠃊 𥜹 夊 【二】小匕目 𥜹 八夊 【】二小匕 𥜹 ``` ### ############################################################################################################ njs_path = require 'path' njs_fs = require 'fs' join = njs_path.join #........................................................................................................... CND = require 'cnd' rpr = CND.rpr badge = 'JIZURA/show-kwic-v3' 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 after = suspend.after eventually = suspend.eventually immediately = suspend.immediately repeat_immediately = suspend.repeat_immediately every = suspend.every #........................................................................................................... # BYTEWISE = require 'bytewise' # through = require 'through2' # LevelBatch = require 'level-batch-stream' # BatchStream = require 'batch-stream' # parallel = require 'concurrent-writable' D = require 'pipedreams' $ = D.remit.bind D $async = D.remit_async.bind D ASYNC = require 'async' CHR = require 'coffeenode-chr' KWIC = require 'kwic' TEXT = require 'coffeenode-text' #........................................................................................................... new_db = require 'level' # new_levelgraph = require 'levelgraph' # db = new_levelgraph '/tmp/levelgraph' HOLLERITH = require 'hollerith' ƒ = CND.format_number.bind CND #........................................................................................................... options = null #----------------------------------------------------------------------------------------------------------- @_misfit = Symbol 'misfit' #----------------------------------------------------------------------------------------------------------- @read_sample = ( db, limit_or_list, handler ) -> ### Return a gamut of select glyphs from the DB. `limit_or_list` may be a list of glyphs or a number representing an upper bound to the usage rank recorded as `rank/cjt`. If `limit_or_list` is a list, a POD whose keys are the glyphs in the list is returned; if it is a number, a similar POD with all the glyphs whose rank is not worse than the given limit is returned. If `limit_or_list` is smaller than zero or equals infinity, `null` is returned to indicate absence of a filter. ### Z = {} #......................................................................................................... if CND.isa_list limit_or_list Z[ glyph ] = 1 for glyph in limit_or_list return handler null, Z #......................................................................................................... return handler null, null if limit_or_list < 0 or limit_or_list is Infinity #......................................................................................................... throw new Error "expected list or number, got a #{type}" unless CND.isa_number limit_or_list #......................................................................................................... db_route = join __dirname, '../../jizura-datasources/data/leveldb-v2' db ?= HOLLERITH.new_db db_route, create: no #......................................................................................................... lo = [ 'pos', 'rank/cjt', 0, ] hi = [ 'pos', 'rank/cjt', limit_or_list, ] query = { lo, hi, } input = HOLLERITH.create_phrasestream db, query #......................................................................................................... input .pipe $ ( phrase, send ) => [ _, _, _, glyph, ] = phrase Z[ glyph ] = 1 .pipe D.$on_end -> handler null, Z #----------------------------------------------------------------------------------------------------------- @_describe_glyph_sample = ( S ) -> if S.glyph_sample is Infinity ### TAINT font substitution should be configured in options or other appropriate place ### return "gamut of *N* <<<{\\mktsFontfileOptima{}≈}>>> #{CND.format_number 75000, ','} glyphs" else if CND.isa_number S.glyph_sample return "gamut of *N* = #{CND.format_number S.glyph_sample, ','} glyphs" else return "selected glyphs: #{S.glyph_sample.join ''}" #----------------------------------------------------------------------------------------------------------- @describe_glyphs = ( S ) -> R = [] R.push "<<(em>> ___KWIC___ Index for " if S.factor_sample? and ( factors = Object.keys S.factor_sample ).length > 0 plural = if factors.length > 1 then 's' else '' R.push "factor#{plural} #{factors.join ''}; " R.push ( @_describe_glyph_sample S ) + ':<<)>>' return R.join '\n' #----------------------------------------------------------------------------------------------------------- @describe_stats = ( S ) -> # debug '9080', S return "(no stats)" unless S.do_stats return "XXXXX" unless S.factor_sample? factors = Object.keys S.factor_sample if factors.length is 1 plural = "" pronoun = "its" else plural = "s" pronoun = "their" R = [] R.push "<<(em>>Statistics for factor#{plural} #{factors.join ''}" if S.two_stats then R.push "and #{pronoun} immediate suffix and prefix factors" else R.push "and #{pronoun} immediate suffix factors" R.push " (\ue045 indicates first/last position);" R.push ( @_describe_glyph_sample S ) + ':<<)>>' return R.join '\n' #----------------------------------------------------------------------------------------------------------- @show_kwic_v3 = ( S ) -> #......................................................................................................... # factor_sample = # '旧日卓桌𠦝東車更㯥䡛轟𨏿昍昌晶𣊭早畢果𣛕𣡗𣡾曱甲𤳅𤳵申𤱓禺𥝉㬰电田畕畾𤳳由甴𡆪白㿟皛鱼魚䲆𩺰鱻䲜' # factor_sample = '旧日卓桌𠦝昍昌晶𣊭早白㿟皛' # factor_sample = '耂' #......................................................................................................... ### TAINT temporary; going to use sets ### if S.factor_sample? _fs = {} _fs[ factor ] = 1 for factor in S.factor_sample S.factor_sample = _fs #......................................................................................................... S.glyphs_description = @describe_glyphs S S.stats_description = @describe_stats S urge S.glyphs_description urge S.stats_description #......................................................................................................... S.query = { prefix: [ 'pos', 'guide/kwic/v3/sortcode/wrapped-lineups', ], } S.db_route = join __dirname, '../../jizura-datasources/data/leveldb-v2' S.db = HOLLERITH.new_db S.db_route, create: no # S = { db_route, db, query, glyph_sample, factor_sample, handler, } help "using DB at #{S.db[ '%self' ][ 'location' ]}" #......................................................................................................... step ( resume ) => #....................................................................................................... S.glyph_sample = yield @read_sample S.db, S.glyph_sample, resume # debug '9853', ( Object.keys S.glyph_sample ).length input = ( HOLLERITH.create_phrasestream S.db, S.query ).pipe $transform_v3 S # handler null return null #......................................................................................................... return null #----------------------------------------------------------------------------------------------------------- $reorder_phrase = ( S ) => return $ ( phrase, send ) => ### extract sortcode ### [ _, _, sortrow, glyph, _, ] = phrase [ _, infix, suffix, prefix, ] = sortrow send [ glyph, prefix, infix, suffix, ] #----------------------------------------------------------------------------------------------------------- $exclude_gaiji = ( S ) => return D.$filter ( event ) => [ glyph, ] = event return ( not glyph.startsWith '&' ) or ( glyph.startsWith '&jzr#' ) #----------------------------------------------------------------------------------------------------------- $include_sample = ( S ) => return D.$filter ( event ) => # [ _, infix, suffix, prefix, ] = sortcode # factors = [ prefix..., infix, suffix...,] # return ( infix is '山' ) and ( '水' in factors ) return true if ( not S.glyph_sample? ) and ( not S.factor_sample? ) [ glyph, prefix, infix, suffix, ] = event in_glyph_sample = ( not S.glyph_sample? ) or ( glyph of S.glyph_sample ) in_factor_sample = ( not S.factor_sample? ) or ( infix of S.factor_sample ) return in_glyph_sample and in_factor_sample #----------------------------------------------------------------------------------------------------------- $write_stats = ( S ) => return D.$pass_through() unless S.do_stats glyphs = new Set() ### NB that we use a JS `Set` to record unique infixes; it has the convenient property of keeping the insertion order of its elements, so afterwards we can use it to determine the infix ordering. ### infixes = new Set() factor_pairs = new Map() lineup_count = 0 output = njs_fs.createWriteStream S.stats_route line_count = 0 in_suffix_part = no #......................................................................................................... return D.$observe ( event, has_ended ) => if event? #..................................................................................................... if CND.isa_list event [ glyph, prefix, infix, suffix, ] = event #................................................................................................... if suffix.startsWith '\u3000' then suffix = '\ue045' else suffix = suffix.trim() suffix = Array.from suffix # if S.two_stats then key = <KEY>suffix[ 0 ]<KEY>}" # else key = <KEY>suffix[ 0 ]}-<KEY> key = <KEY>suffix[ 0 ]},<KEY>" factor_pairs.set key, target = new Set() unless ( target = factor_pairs.get key )? target.add glyph #................................................................................................... if S.with_prefixes if prefix.endsWith '\u3000' then prefix = '\ue045' else prefix = prefix.trim() prefix = Array.from prefix key = <KEY>prefix[ prefix.length - 1 ]}<KEY>" factor_pairs.set key, target = new Set() unless ( target = factor_pairs.get key )? target.add glyph #................................................................................................... infixes.add infix glyphs.add glyph lineup_count += +1 #....................................................................................................... if has_ended help "built KWIC for #{ƒ glyphs.size} glyphs" help "containing #{ƒ lineup_count} lineups" infixes = Array.from infixes factor_pairs = Array.from factor_pairs for entry in factor_pairs entry[ 0 ] = entry[ 0 ].split ',' entry[ 0 ][ 2 ] = parseInt entry[ 0 ][ 2 ], 10 entry[ 1 ] = Array.from entry[ 1 ] #..................................................................................................... factor_pairs.sort ( a, b ) -> [ [ a_infix, a_pair, a_series, ], a_glyphs, ] = a [ [ b_infix, b_pair, b_series, ], b_glyphs, ] = b a_infix_idx = infixes.indexOf a_infix b_infix_idx = infixes.indexOf b_infix if S.two_stats return +1 if a_series > b_series return -1 if a_series < b_series return +1 if a_infix_idx > b_infix_idx return -1 if a_infix_idx < b_infix_idx return +1 if a_glyphs.length < b_glyphs.length return -1 if a_glyphs.length > b_glyphs.length return +1 if a_pair > b_pair return -1 if a_pair < b_pair return 0 #..................................................................................................... ### TAINT column count should be accessible through CLI and otherwise be calculated according to paper size and lineup lengths ### output.write "<<(columns 4>><<(JZR.vertical-bar>>\n" output.write "```keep-lines squish: yes\n" #..................................................................................................... last_infix = null last_series = null separator = '】' for [ [ infix, factor_pair, series, ], glyphs, ] in factor_pairs #................................................................................................... if S.two_stats and last_series? and last_series isnt series in_suffix_part = yes output.write "```\n" # output.write "<<)>><<)>>\n" output.write "\n/0------------------------------0/\n\n" # output.write "<<(columns 4>><<(JZR.vertical-bar>>\n" output.write "```keep-lines squish: yes\n" output.write "——.\ue023#{infix}.——\n" #................................................................................................... else if last_infix isnt infix if S.two_stats unless in_suffix_part then output.write "——.#{infix}\ue023.——\n" else output.write "——.\ue023#{infix}.——\n" else output.write "——.\ue023#{infix}\ue023.——\n" last_infix = infix last_series = series #................................................................................................... glyph_count = glyphs.length # if glyph_count > 999 then glyph_count_txt = "<<<{\\tfScale{0.5}{1}#{glyph_count}}>>>#{glyph_count}" glyph_count_txt = "#{glyph_count}" if S.width? glyphs.push '\u3000' while glyphs.length < S.width glyphs.pop() while glyphs.length > S.width line = [ factor_pair, separator, ( glyphs.join '' ), '==>', glyph_count_txt, '\n', ].join '' output.write line line_count += +1 #..................................................................................................... output.write "```\n" output.write "<<)>><<)>>\n" output.end() help "found #{infixes.length} infixes" help "wrote #{line_count} lines to #{S.stats_route}" S.handler null if S.handler? #......................................................................................................... return null #----------------------------------------------------------------------------------------------------------- $write_glyphs = ( S ) => output = njs_fs.createWriteStream S.glyphs_route line_count = 0 is_first = yes last_infix = null empty_prefix = '\u3000\u3000\u3000' #......................................................................................................... return D.$observe ( event, has_ended ) -> #....................................................................................................... if event? if CND.isa_list event if is_first ### TAINT column count should be accessible through CLI and otherwise be calculated according to paper size and lineup lengths ### output.write "<<(columns 4>><<(JZR.vertical-bar>>\n" output.write "```keep-lines squish: yes\n" is_first = no [ glyph, prefix, infix, suffix, ] = event if ( infix isnt last_infix ) and ( glyph isnt infix ) # output.write "——.#{infix}.——\n" output.write empty_prefix + '【' + infix + '】' + '\n' output.write prefix + '【' + infix + '】' + suffix + '==>' + glyph + '\n' last_infix = infix else output.write event + '\n' line_count += +1 #....................................................................................................... if has_ended output.write "```\n" output.write "<<)>><<)>>\n" help "wrote #{line_count} lines to #{S.glyphs_route}" output.end() #----------------------------------------------------------------------------------------------------------- $write_glyphs_description = ( S ) => output = njs_fs.createWriteStream S.glyphs_description_route #......................................................................................................... return D.$observe ( event, has_ended ) -> if has_ended output.write S.glyphs_description help "wrote glyphs description to #{S.glyphs_description_route}" output.end() #----------------------------------------------------------------------------------------------------------- $write_stats_description = ( S ) => return D.$pass_through() unless S.do_stats output = njs_fs.createWriteStream S.stats_description_route #......................................................................................................... return D.$observe ( event, has_ended ) -> if has_ended output.write S.stats_description help "wrote stats description to #{S.stats_description_route}" output.end() # #----------------------------------------------------------------------------------------------------------- # $count_lineup_lengths = ( S ) => # counts = [] # count = 0 # #......................................................................................................... # return $ ( event, send, end ) => # if event? # #..................................................................................................... # if CND.isa_list event # [ glyph, sortcode, ] = event # [ _, infix, suffix, prefix, ] = sortcode # lineup = ( prefix.join '' ) + infix + ( suffix.join '' ) # lineup_length = ( Array.from lineup.replace /\u3000/g, '' ).length # if true # lineup_length is 8 # send event # counts[ lineup_length ] = ( counts[ lineup_length ] ? 0 ) + 1 # #..................................................................................................... # else # send event # #....................................................................................................... # if end? # for length in [ 1 ... counts.length ] # count_txt = TEXT.flush_right ( ƒ counts[ length ] ? 0 ), 10 # help "found #{count_txt} lineups of length #{length}" # end() # #----------------------------------------------------------------------------------------------------------- # @$align_affixes_with_braces = ( S ) => # prefix_max_length = 3 # suffix_max_length = 3 # #......................................................................................................... # return $ ( event, send ) => # #....................................................................................................... # if CND.isa_list event # [ glyph, sortcode, ] = event # [ _, infix, suffix, prefix, ] = sortcode # #..................................................................................................... # 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 = [] # prefix_is_shortened = no # suffix_is_shortened = no # #..................................................................................................... # 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 # prefix_is_shortened = yes # prefix_excess.pop() # while suffix_excess.length > 0 and suffix_excess.length > suffix_excess_max_length # suffix_is_shortened = yes # 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' # #..................................................................................................... # if prefix_excess.length > 0 then prefix_excess.unshift '「' unless prefix_excess.length is 0 # else prefix.unshift '「' unless prefix_delta > 0 # if suffix_excess.length > 0 then suffix_excess.push '」' unless suffix_excess.length is 0 # else suffix.push '」' unless suffix_delta > 0 # #..................................................................................................... # 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... # #..................................................................................................... # urge ( prefix.join '' ) + '【' + infix + '】' + ( suffix.join '' ) # # send [ glyph, [ prefix_padding, suffix_excess, prefix, infix, suffix, prefix_excess, ], ] # send [ glyph, [ prefix, infix, suffix, ], ] # #....................................................................................................... # else # send event # #----------------------------------------------------------------------------------------------------------- # @$align_affixes_with_spaces = ( S ) => # ### This code has been used in `copy-jizuradb-to-Hollerith2-format#add_kwic_v3_wrapped_lineups` ### # prefix_max_length = 3 # suffix_max_length = 3 # #......................................................................................................... # return $ ( event, send ) => # #....................................................................................................... # if CND.isa_list event # [ glyph, sortcode, ] = event # [ _, infix, suffix, prefix, ] = sortcode # #..................................................................................................... # 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... # #..................................................................................................... # urge ( prefix.join '' ) + '【' + infix + '】' + ( suffix.join '' ) # # send [ glyph, [ prefix_padding, suffix_excess, prefix, infix, suffix, prefix_excess, ], ] # send [ glyph, [ prefix, infix, suffix, ], ] # #....................................................................................................... # else # send event #----------------------------------------------------------------------------------------------------------- $transform_v3 = ( S ) => return D.combine [ $reorder_phrase S $exclude_gaiji S $include_sample S # $count_lineup_lengths S # @$align_affixes_with_braces S # @$align_affixes_with_spaces S $write_stats S $write_glyphs S $write_glyphs_description S $write_stats_description S D.$on_end => S.handler null if S.handler? ] # ############################################################################################################ # unless module.parent? # #--------------------------------------------------------------------------------------------------------- # options = # #....................................................................................................... # # 'route': njs_path.join __dirname, '../dbs/demo' # 'route': njs_path.resolve __dirname, '../../jizura-datasources/data/leveldb-v2' # # 'route': '/tmp/leveldb' # #--------------------------------------------------------------------------------------------------------- # @show_kwic_v3()
true
### `@$align_affixes_with_braces` ```keep-lines squish: yes    「【虫】」    虫   「冄【阝】」    𨙻    「【冄】阝」   𨙻  「穴扌【未】」    𥦤   「穴【扌】未」   𥦤    「【穴】扌未」  𥦤 「日业䒑【未】」    曗  「日业【䒑】未」   曗   「日【业】䒑未」  曗    「【日】业䒑未」 曗 日𠂇⺝【阝】」  「禾 𩡏 「禾日𠂇【⺝】阝」   𩡏  「禾日【𠂇】⺝阝」  𩡏   「禾【日】𠂇⺝阝」 𩡏 阝」  「【禾】日𠂇⺝ 𩡏 木冖鬯【彡】」 「木缶 鬱 缶木冖【鬯】彡」 「木 鬱 「木缶木【冖】鬯彡」  鬱  「木缶【木】冖鬯彡」 鬱 彡」 「木【缶】木冖鬯 鬱 鬯彡」 「【木】缶木冖 鬱 山一几【夊】」「女山彳 𡤇 彳山一【几】夊」「女山 𡤇 山彳山【一】几夊」「女 𡤇 「女山彳【山】一几夊」 𡤇 夊」「女山【彳】山一几 𡤇 几夊」「女【山】彳山一 𡤇 一几夊」「【女】山彳山 𡤇 目𠃊八【夊】」「二小 𥜹 匕目𠃊【八】夊」「二 𥜹 小匕目【𠃊】八夊」「 𥜹 二小匕【目】𠃊八夊」 𥜹 「二小【匕】目𠃊八 𥜹 夊」「二【小】匕目𠃊 𥜹 八夊」「【二】小匕目 𥜹 𠃊八夊」「【】二小匕 𥜹 ``` `align_affixes_with_spaces` ```keep-lines squish: yes    【虫】    虫   冄【阝】    𨙻    【冄】阝   𨙻  穴扌【未】    𥦤   穴【扌】未   𥦤    【穴】扌未  𥦤 日业䒑【未】    曗  日业【䒑】未   曗   日【业】䒑未  曗    【日】业䒑未 曗 日𠂇⺝【阝】  禾 𩡏 禾日𠂇【⺝】阝   𩡏  禾日【𠂇】⺝阝  𩡏   禾【日】𠂇⺝阝 𩡏 阝  【禾】日𠂇⺝ 𩡏 木冖鬯【彡】 木缶 鬱 缶木冖【鬯】彡 木 鬱 木缶木【冖】鬯彡  鬱  木缶【木】冖鬯彡 鬱 彡 木【缶】木冖鬯 鬱 鬯彡 【木】缶木冖 鬱 山一几【夊】 女山 𡤇 彳山一【几】夊 女 𡤇 山彳山【一】几夊  𡤇 女山彳【山】一几夊 𡤇  女山【彳】山一几 𡤇 夊 女【山】彳山一 𡤇 几夊 【女】山彳山 𡤇 目𠃊八【夊】 二 𥜹 匕目𠃊【八】夊  𥜹 小匕目【𠃊】八夊  𥜹 二小匕【目】𠃊八夊 𥜹 二小【匕】目𠃊八 𥜹  二【小】匕目𠃊 𥜹 夊 【二】小匕目 𥜹 八夊 【】二小匕 𥜹 ``` ### ############################################################################################################ njs_path = require 'path' njs_fs = require 'fs' join = njs_path.join #........................................................................................................... CND = require 'cnd' rpr = CND.rpr badge = 'JIZURA/show-kwic-v3' 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 after = suspend.after eventually = suspend.eventually immediately = suspend.immediately repeat_immediately = suspend.repeat_immediately every = suspend.every #........................................................................................................... # BYTEWISE = require 'bytewise' # through = require 'through2' # LevelBatch = require 'level-batch-stream' # BatchStream = require 'batch-stream' # parallel = require 'concurrent-writable' D = require 'pipedreams' $ = D.remit.bind D $async = D.remit_async.bind D ASYNC = require 'async' CHR = require 'coffeenode-chr' KWIC = require 'kwic' TEXT = require 'coffeenode-text' #........................................................................................................... new_db = require 'level' # new_levelgraph = require 'levelgraph' # db = new_levelgraph '/tmp/levelgraph' HOLLERITH = require 'hollerith' ƒ = CND.format_number.bind CND #........................................................................................................... options = null #----------------------------------------------------------------------------------------------------------- @_misfit = Symbol 'misfit' #----------------------------------------------------------------------------------------------------------- @read_sample = ( db, limit_or_list, handler ) -> ### Return a gamut of select glyphs from the DB. `limit_or_list` may be a list of glyphs or a number representing an upper bound to the usage rank recorded as `rank/cjt`. If `limit_or_list` is a list, a POD whose keys are the glyphs in the list is returned; if it is a number, a similar POD with all the glyphs whose rank is not worse than the given limit is returned. If `limit_or_list` is smaller than zero or equals infinity, `null` is returned to indicate absence of a filter. ### Z = {} #......................................................................................................... if CND.isa_list limit_or_list Z[ glyph ] = 1 for glyph in limit_or_list return handler null, Z #......................................................................................................... return handler null, null if limit_or_list < 0 or limit_or_list is Infinity #......................................................................................................... throw new Error "expected list or number, got a #{type}" unless CND.isa_number limit_or_list #......................................................................................................... db_route = join __dirname, '../../jizura-datasources/data/leveldb-v2' db ?= HOLLERITH.new_db db_route, create: no #......................................................................................................... lo = [ 'pos', 'rank/cjt', 0, ] hi = [ 'pos', 'rank/cjt', limit_or_list, ] query = { lo, hi, } input = HOLLERITH.create_phrasestream db, query #......................................................................................................... input .pipe $ ( phrase, send ) => [ _, _, _, glyph, ] = phrase Z[ glyph ] = 1 .pipe D.$on_end -> handler null, Z #----------------------------------------------------------------------------------------------------------- @_describe_glyph_sample = ( S ) -> if S.glyph_sample is Infinity ### TAINT font substitution should be configured in options or other appropriate place ### return "gamut of *N* <<<{\\mktsFontfileOptima{}≈}>>> #{CND.format_number 75000, ','} glyphs" else if CND.isa_number S.glyph_sample return "gamut of *N* = #{CND.format_number S.glyph_sample, ','} glyphs" else return "selected glyphs: #{S.glyph_sample.join ''}" #----------------------------------------------------------------------------------------------------------- @describe_glyphs = ( S ) -> R = [] R.push "<<(em>> ___KWIC___ Index for " if S.factor_sample? and ( factors = Object.keys S.factor_sample ).length > 0 plural = if factors.length > 1 then 's' else '' R.push "factor#{plural} #{factors.join ''}; " R.push ( @_describe_glyph_sample S ) + ':<<)>>' return R.join '\n' #----------------------------------------------------------------------------------------------------------- @describe_stats = ( S ) -> # debug '9080', S return "(no stats)" unless S.do_stats return "XXXXX" unless S.factor_sample? factors = Object.keys S.factor_sample if factors.length is 1 plural = "" pronoun = "its" else plural = "s" pronoun = "their" R = [] R.push "<<(em>>Statistics for factor#{plural} #{factors.join ''}" if S.two_stats then R.push "and #{pronoun} immediate suffix and prefix factors" else R.push "and #{pronoun} immediate suffix factors" R.push " (\ue045 indicates first/last position);" R.push ( @_describe_glyph_sample S ) + ':<<)>>' return R.join '\n' #----------------------------------------------------------------------------------------------------------- @show_kwic_v3 = ( S ) -> #......................................................................................................... # factor_sample = # '旧日卓桌𠦝東車更㯥䡛轟𨏿昍昌晶𣊭早畢果𣛕𣡗𣡾曱甲𤳅𤳵申𤱓禺𥝉㬰电田畕畾𤳳由甴𡆪白㿟皛鱼魚䲆𩺰鱻䲜' # factor_sample = '旧日卓桌𠦝昍昌晶𣊭早白㿟皛' # factor_sample = '耂' #......................................................................................................... ### TAINT temporary; going to use sets ### if S.factor_sample? _fs = {} _fs[ factor ] = 1 for factor in S.factor_sample S.factor_sample = _fs #......................................................................................................... S.glyphs_description = @describe_glyphs S S.stats_description = @describe_stats S urge S.glyphs_description urge S.stats_description #......................................................................................................... S.query = { prefix: [ 'pos', 'guide/kwic/v3/sortcode/wrapped-lineups', ], } S.db_route = join __dirname, '../../jizura-datasources/data/leveldb-v2' S.db = HOLLERITH.new_db S.db_route, create: no # S = { db_route, db, query, glyph_sample, factor_sample, handler, } help "using DB at #{S.db[ '%self' ][ 'location' ]}" #......................................................................................................... step ( resume ) => #....................................................................................................... S.glyph_sample = yield @read_sample S.db, S.glyph_sample, resume # debug '9853', ( Object.keys S.glyph_sample ).length input = ( HOLLERITH.create_phrasestream S.db, S.query ).pipe $transform_v3 S # handler null return null #......................................................................................................... return null #----------------------------------------------------------------------------------------------------------- $reorder_phrase = ( S ) => return $ ( phrase, send ) => ### extract sortcode ### [ _, _, sortrow, glyph, _, ] = phrase [ _, infix, suffix, prefix, ] = sortrow send [ glyph, prefix, infix, suffix, ] #----------------------------------------------------------------------------------------------------------- $exclude_gaiji = ( S ) => return D.$filter ( event ) => [ glyph, ] = event return ( not glyph.startsWith '&' ) or ( glyph.startsWith '&jzr#' ) #----------------------------------------------------------------------------------------------------------- $include_sample = ( S ) => return D.$filter ( event ) => # [ _, infix, suffix, prefix, ] = sortcode # factors = [ prefix..., infix, suffix...,] # return ( infix is '山' ) and ( '水' in factors ) return true if ( not S.glyph_sample? ) and ( not S.factor_sample? ) [ glyph, prefix, infix, suffix, ] = event in_glyph_sample = ( not S.glyph_sample? ) or ( glyph of S.glyph_sample ) in_factor_sample = ( not S.factor_sample? ) or ( infix of S.factor_sample ) return in_glyph_sample and in_factor_sample #----------------------------------------------------------------------------------------------------------- $write_stats = ( S ) => return D.$pass_through() unless S.do_stats glyphs = new Set() ### NB that we use a JS `Set` to record unique infixes; it has the convenient property of keeping the insertion order of its elements, so afterwards we can use it to determine the infix ordering. ### infixes = new Set() factor_pairs = new Map() lineup_count = 0 output = njs_fs.createWriteStream S.stats_route line_count = 0 in_suffix_part = no #......................................................................................................... return D.$observe ( event, has_ended ) => if event? #..................................................................................................... if CND.isa_list event [ glyph, prefix, infix, suffix, ] = event #................................................................................................... if suffix.startsWith '\u3000' then suffix = '\ue045' else suffix = suffix.trim() suffix = Array.from suffix # if S.two_stats then key = PI:KEY:<KEY>END_PIsuffix[ 0 ]PI:KEY:<KEY>END_PI}" # else key = PI:KEY:<KEY>END_PIsuffix[ 0 ]}-PI:KEY:<KEY>END_PI key = PI:KEY:<KEY>END_PIsuffix[ 0 ]},PI:KEY:<KEY>END_PI" factor_pairs.set key, target = new Set() unless ( target = factor_pairs.get key )? target.add glyph #................................................................................................... if S.with_prefixes if prefix.endsWith '\u3000' then prefix = '\ue045' else prefix = prefix.trim() prefix = Array.from prefix key = PI:KEY:<KEY>END_PIprefix[ prefix.length - 1 ]}PI:KEY:<KEY>END_PI" factor_pairs.set key, target = new Set() unless ( target = factor_pairs.get key )? target.add glyph #................................................................................................... infixes.add infix glyphs.add glyph lineup_count += +1 #....................................................................................................... if has_ended help "built KWIC for #{ƒ glyphs.size} glyphs" help "containing #{ƒ lineup_count} lineups" infixes = Array.from infixes factor_pairs = Array.from factor_pairs for entry in factor_pairs entry[ 0 ] = entry[ 0 ].split ',' entry[ 0 ][ 2 ] = parseInt entry[ 0 ][ 2 ], 10 entry[ 1 ] = Array.from entry[ 1 ] #..................................................................................................... factor_pairs.sort ( a, b ) -> [ [ a_infix, a_pair, a_series, ], a_glyphs, ] = a [ [ b_infix, b_pair, b_series, ], b_glyphs, ] = b a_infix_idx = infixes.indexOf a_infix b_infix_idx = infixes.indexOf b_infix if S.two_stats return +1 if a_series > b_series return -1 if a_series < b_series return +1 if a_infix_idx > b_infix_idx return -1 if a_infix_idx < b_infix_idx return +1 if a_glyphs.length < b_glyphs.length return -1 if a_glyphs.length > b_glyphs.length return +1 if a_pair > b_pair return -1 if a_pair < b_pair return 0 #..................................................................................................... ### TAINT column count should be accessible through CLI and otherwise be calculated according to paper size and lineup lengths ### output.write "<<(columns 4>><<(JZR.vertical-bar>>\n" output.write "```keep-lines squish: yes\n" #..................................................................................................... last_infix = null last_series = null separator = '】' for [ [ infix, factor_pair, series, ], glyphs, ] in factor_pairs #................................................................................................... if S.two_stats and last_series? and last_series isnt series in_suffix_part = yes output.write "```\n" # output.write "<<)>><<)>>\n" output.write "\n/0------------------------------0/\n\n" # output.write "<<(columns 4>><<(JZR.vertical-bar>>\n" output.write "```keep-lines squish: yes\n" output.write "——.\ue023#{infix}.——\n" #................................................................................................... else if last_infix isnt infix if S.two_stats unless in_suffix_part then output.write "——.#{infix}\ue023.——\n" else output.write "——.\ue023#{infix}.——\n" else output.write "——.\ue023#{infix}\ue023.——\n" last_infix = infix last_series = series #................................................................................................... glyph_count = glyphs.length # if glyph_count > 999 then glyph_count_txt = "<<<{\\tfScale{0.5}{1}#{glyph_count}}>>>#{glyph_count}" glyph_count_txt = "#{glyph_count}" if S.width? glyphs.push '\u3000' while glyphs.length < S.width glyphs.pop() while glyphs.length > S.width line = [ factor_pair, separator, ( glyphs.join '' ), '==>', glyph_count_txt, '\n', ].join '' output.write line line_count += +1 #..................................................................................................... output.write "```\n" output.write "<<)>><<)>>\n" output.end() help "found #{infixes.length} infixes" help "wrote #{line_count} lines to #{S.stats_route}" S.handler null if S.handler? #......................................................................................................... return null #----------------------------------------------------------------------------------------------------------- $write_glyphs = ( S ) => output = njs_fs.createWriteStream S.glyphs_route line_count = 0 is_first = yes last_infix = null empty_prefix = '\u3000\u3000\u3000' #......................................................................................................... return D.$observe ( event, has_ended ) -> #....................................................................................................... if event? if CND.isa_list event if is_first ### TAINT column count should be accessible through CLI and otherwise be calculated according to paper size and lineup lengths ### output.write "<<(columns 4>><<(JZR.vertical-bar>>\n" output.write "```keep-lines squish: yes\n" is_first = no [ glyph, prefix, infix, suffix, ] = event if ( infix isnt last_infix ) and ( glyph isnt infix ) # output.write "——.#{infix}.——\n" output.write empty_prefix + '【' + infix + '】' + '\n' output.write prefix + '【' + infix + '】' + suffix + '==>' + glyph + '\n' last_infix = infix else output.write event + '\n' line_count += +1 #....................................................................................................... if has_ended output.write "```\n" output.write "<<)>><<)>>\n" help "wrote #{line_count} lines to #{S.glyphs_route}" output.end() #----------------------------------------------------------------------------------------------------------- $write_glyphs_description = ( S ) => output = njs_fs.createWriteStream S.glyphs_description_route #......................................................................................................... return D.$observe ( event, has_ended ) -> if has_ended output.write S.glyphs_description help "wrote glyphs description to #{S.glyphs_description_route}" output.end() #----------------------------------------------------------------------------------------------------------- $write_stats_description = ( S ) => return D.$pass_through() unless S.do_stats output = njs_fs.createWriteStream S.stats_description_route #......................................................................................................... return D.$observe ( event, has_ended ) -> if has_ended output.write S.stats_description help "wrote stats description to #{S.stats_description_route}" output.end() # #----------------------------------------------------------------------------------------------------------- # $count_lineup_lengths = ( S ) => # counts = [] # count = 0 # #......................................................................................................... # return $ ( event, send, end ) => # if event? # #..................................................................................................... # if CND.isa_list event # [ glyph, sortcode, ] = event # [ _, infix, suffix, prefix, ] = sortcode # lineup = ( prefix.join '' ) + infix + ( suffix.join '' ) # lineup_length = ( Array.from lineup.replace /\u3000/g, '' ).length # if true # lineup_length is 8 # send event # counts[ lineup_length ] = ( counts[ lineup_length ] ? 0 ) + 1 # #..................................................................................................... # else # send event # #....................................................................................................... # if end? # for length in [ 1 ... counts.length ] # count_txt = TEXT.flush_right ( ƒ counts[ length ] ? 0 ), 10 # help "found #{count_txt} lineups of length #{length}" # end() # #----------------------------------------------------------------------------------------------------------- # @$align_affixes_with_braces = ( S ) => # prefix_max_length = 3 # suffix_max_length = 3 # #......................................................................................................... # return $ ( event, send ) => # #....................................................................................................... # if CND.isa_list event # [ glyph, sortcode, ] = event # [ _, infix, suffix, prefix, ] = sortcode # #..................................................................................................... # 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 = [] # prefix_is_shortened = no # suffix_is_shortened = no # #..................................................................................................... # 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 # prefix_is_shortened = yes # prefix_excess.pop() # while suffix_excess.length > 0 and suffix_excess.length > suffix_excess_max_length # suffix_is_shortened = yes # 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' # #..................................................................................................... # if prefix_excess.length > 0 then prefix_excess.unshift '「' unless prefix_excess.length is 0 # else prefix.unshift '「' unless prefix_delta > 0 # if suffix_excess.length > 0 then suffix_excess.push '」' unless suffix_excess.length is 0 # else suffix.push '」' unless suffix_delta > 0 # #..................................................................................................... # 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... # #..................................................................................................... # urge ( prefix.join '' ) + '【' + infix + '】' + ( suffix.join '' ) # # send [ glyph, [ prefix_padding, suffix_excess, prefix, infix, suffix, prefix_excess, ], ] # send [ glyph, [ prefix, infix, suffix, ], ] # #....................................................................................................... # else # send event # #----------------------------------------------------------------------------------------------------------- # @$align_affixes_with_spaces = ( S ) => # ### This code has been used in `copy-jizuradb-to-Hollerith2-format#add_kwic_v3_wrapped_lineups` ### # prefix_max_length = 3 # suffix_max_length = 3 # #......................................................................................................... # return $ ( event, send ) => # #....................................................................................................... # if CND.isa_list event # [ glyph, sortcode, ] = event # [ _, infix, suffix, prefix, ] = sortcode # #..................................................................................................... # 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... # #..................................................................................................... # urge ( prefix.join '' ) + '【' + infix + '】' + ( suffix.join '' ) # # send [ glyph, [ prefix_padding, suffix_excess, prefix, infix, suffix, prefix_excess, ], ] # send [ glyph, [ prefix, infix, suffix, ], ] # #....................................................................................................... # else # send event #----------------------------------------------------------------------------------------------------------- $transform_v3 = ( S ) => return D.combine [ $reorder_phrase S $exclude_gaiji S $include_sample S # $count_lineup_lengths S # @$align_affixes_with_braces S # @$align_affixes_with_spaces S $write_stats S $write_glyphs S $write_glyphs_description S $write_stats_description S D.$on_end => S.handler null if S.handler? ] # ############################################################################################################ # unless module.parent? # #--------------------------------------------------------------------------------------------------------- # options = # #....................................................................................................... # # 'route': njs_path.join __dirname, '../dbs/demo' # 'route': njs_path.resolve __dirname, '../../jizura-datasources/data/leveldb-v2' # # 'route': '/tmp/leveldb' # #--------------------------------------------------------------------------------------------------------- # @show_kwic_v3()
[ { "context": "llator)));\n }\n\n###\n# Biquad filter\n# Created by Ricard Marxer <email@ricardmarxer.com> on 2010-05-23.\n# Copyri", "end": 17799, "score": 0.9998754262924194, "start": 17786, "tag": "NAME", "value": "Ricard Marxer" }, { "context": "###\n# Biquad filter\n# Creat...
src/instruments.coffee
emcmanus/tinyrave-lib
12
### Oscillator Class -------------------------------------------------------------------------------- The Oscillator class provides a basic sound wave. You can play the resulting sound directly, or, more likely, process the sound with another class in the library, such as Filter, Envelope, or Mixer. Constants Oscillator.SINE Wave type. Smooth sine waveform. Oscillator.SQUARE Wave type. Square waveform. Oscillator.SAWTOOTH Wave type. Sawtooth waveform. Oscillator.TRIANGLE Wave type. Triangle waveform. Oscillator.NOISE Wave type. Random samples between -1 and 1. Wave types: https://en.wikipedia.org/wiki/Waveform Arguments type: Optional. Default Oscillator.SINE. The type of sound wave to generate. Accepted values: Oscillator.SINE, Oscillator.TRIANGLE, Oscillator.SQUARE, Oscillator.NOISE, Oscillator.SAWTOOTH. frequency: Optional. Default 440. Number, or a function that takes a time parameter and returns a frequency. The time argument specifies how long the oscillator has been running. amplitude: Optional. Default 1. Number, or a function that takes a time parameter and returns an amplitude multiplier. *Not* in dB's. the time argument specifies how long the oscillator has been running. phase: Optional. Default 0. Number, or a function that takes a time parameter and returns a phase shift. the time argument specifies how long the oscillator has been running. This is an advanced parameter and can probably be ignored in most cases. Returns An instance-like closure that wraps the values passed at instantiation. This follows the `(time) -> sample` convention for use in play() and buildSample(). Usage 1 (JS) - Basic wave (build sample version) require('v1/instruments'); var oscillator = new Oscillator({frequency: Frequency.A_3}); var buildSample = function(time){ return oscillator(time); } Usage 2 (JS) - Basic triangle wave (build track version) require('v1/instruments'); var oscillator = new Oscillator({frequency: Frequency.A_3, type: Oscillator.TRIANGLE}); var buildTrack = function(){ this.play(oscillator); } Usage 3 (JS) - Basic square wave, with amplitude require('v1/instruments'); var oscillator = new Oscillator({frequency: Frequency.A_3, type: Oscillator.SQUARE, amplitude: 0.7}); var envelope = new Envelope(); var buildTrack = function(){ this.play(envelope.process(oscillator)); } Usage 4 (JS) - Vibrato require('v1/instruments'); var phaseModulation = function(time){ return 0.1 * Math.sin(TWO_PI * time * 5); } var oscillator = new Oscillator({frequency: Frequency.A_3, phase: phaseModulation}); var buildTrack = function(){ this.play(oscillator); } Usage 5 (JS) - Hi Hat require('v1/instruments'); var oscillator = new Oscillator({frequency: Frequency.A_3, type: Oscillator.NOISE}); var filter = new Filter({type: Filter.HIGH_PASS, frequency: 10000}); var envelope = new Envelope(); var buildTrack = function(){ this.play(envelope.process(filter.process(oscillator))); } ### class Oscillator # Types @SINE = 0 @SQUARE = 1 @SAWTOOTH = 2 @TRIANGLE = 3 @NOISE = 4 constructor: (options={}) -> @frequency = options.frequency || 440 @phase = options.phase || 0 @amplitude = options.amplitude || 1 @numericPhase = @phase unless Function.isFunction(@phase) @numericFrequency = @frequency unless Function.isFunction(@frequency) @numericAmplitude = @amplitude unless Function.isFunction(@amplitude) @oscillatorFunction = switch (options.type || Oscillator.SINE) when Oscillator.SQUARE @square when Oscillator.SAWTOOTH @sawtooth when Oscillator.TRIANGLE @triangle when Oscillator.NOISE @noise else @sine # Represents start time @startTime = -1 # The closure to be returned at the end of this call generator = (time) => # Using localTime makes it easier to anticipate the interference of # multiple oscillators @startTime = time if @startTime == -1 @localTime = time - @startTime _phase = if @numericPhase? then @numericPhase else @phase(@localTime) _frequency = if @numericFrequency? then @numericFrequency else @frequency(@localTime) _amplitude = if @numericAmplitude? then @numericAmplitude else @amplitude(@localTime) _amplitude * @oscillatorFunction((_frequency * @localTime) + _phase) generator.displayName = "Oscillator Sound Generator" generator.getFrequency = => if @numericFrequency? then @numericFrequency else @frequency(@localTime) generator.setFrequency = (frequency) => @frequency = frequency if Function.isFunction(@frequency) @numericFrequency = undefined else @numericFrequency = @frequency frequency generator.getPhase = => if @numericPhase? then @numericPhase else @phase(@localTime) generator.setPhase = (phase) => @phase = phase if Function.isFunction(@phase) @numericPhase = undefined else @numericPhase = @phase phase generator.getAmplitude = => if @numericAmplitude? then @numericAmplitude else @amplitude(@localTime) generator.setAmplitude = (amplitude) => @amplitude = amplitude if Function.isFunction(@amplitude) @numericAmplitude = undefined else @numericAmplitude = @amplitude amplitude # Explicit return necessary in constructor return generator sine: (value) -> # Smooth wave intersecting (0, 0), (0.25, 1), (0.5, 0), (0.75, -1), (1, 0) Math.sin(2 * Math.PI * value) sawtooth: (value) -> # Line from (-.5,-1) to (0.5, 1) progress = (value + 0.5) % 1 2 * progress - 1 triangle: (value) -> # Linear change from (0, -1) to (0.5, 1) to (1, -1) progress = value % 1 if progress < 0.5 4 * progress - 1 else -4 * progress + 3 square: (value) -> # -1 for the first half of a cycle; 1 for the second half progress = value % 1 if progress < 0.5 1 else -1 noise: (value) -> Math.random() * 2 - 1 ### Envelope Class -------------------------------------------------------------------------------- Shapes the sound wave passed into process(). Constants Envelope.AD Attack / Decay envelope. Only the attackTime and decayTime parameters are used. AD Envelope - Amplitude: /\ 1 / \ / \ 0 |-| Attack phase |-| Decay phase Envelope.ADSR Attack Decay Sustain Release envelope. All parameters are used. ADSR Envelope - Amplitude: /\ 1 / \____ sustainLevel / \ 0 |-| Attack phase |-| Decay phase |---| Sustain phase |-| Release phase Arguments type: Optional. Default Envelope.AD. Accepted values: Envelope.AD, Envelope.ADSR. attackTime: Optional. Default 0.03. Value in seconds. decayTime: Optional. Default 1.0. Value in seconds. sustainTime: Optional. Default 0. Value in seconds. Ignored unless envelope type is Envelope.ADSR. releaseTime: Optional. Default 0. Value in seconds. Ignored unless envelope type is Envelope.ADSR. sustainLevel: Optional. Default 0. Value in seconds. Ignored unless envelope type is Envelope.ADSR. Returns An object with a process() method, ready to accept an oscillator or other sound generator to be shaped. Usage 1 (JS) require('v1/instruments'); var o = new Oscillator; var e = new Envelope; var processor = e.process(o); var buildSample = function(time) { return processor(time); } Usage 2 (JS) require('v1/instruments'); var o = new Oscillator; var e = new Envelope; var buildTrack = function() { this.play(e.process(o)); } Usage 3 (JS) require('v1/instruments'); var o = new Oscillator; var e = new Envelope({type: Envelope.ADSR, sustainTime: 1, releaseTime: 1, sustainLevel: 0.5}); var buildTrack = function() { this.play(e.process(o)); } ### class Envelope # AD Envelope Type # # Amplitude: # /\ 1 # / \ # / \ 0 # |-| Attack # |-| Decay @AD = 0 # ADSR Envelope Type # # Amplitude: # /\ 1 # / \____ sustainLevel # / \ 0 # |-| Attack # |-| Decay # |---| Sustain # |-| Release @ADSR = 1 constructor: (options={}) -> options.sustainLevel ?= 0.3 options.type ?= Envelope.AD if options.type == Envelope.AD options.attackTime ?= 0.03 options.decayTime ?= 1 options.sustainTime = 0 options.releaseTime = 0 options.sustainLevel = 0 unless options.attackTime? && options.decayTime? && options.sustainTime? && options.releaseTime? throw new Error "Options must specify 'attackTime', 'decayTime', 'sustainTime' and 'releaseTime' values for ADSR envelope type." @type = options.type @sustainLevel = options.sustainLevel @attackTime = options.attackTime @decayTime = options.decayTime @sustainTime = options.sustainTime @releaseTime = options.releaseTime @totalTime = options.attackTime + options.decayTime + options.sustainTime + options.releaseTime getMultiplier: (localTime) -> if localTime <= @attackTime # Attack localTime / @attackTime else if localTime <= @attackTime + @decayTime # Plot a line between (attackTime, 1) and (attackTime + decayTime, sustainLevel) # y = mx+b (remember m is slope, b is y intercept) # m = (y2 - y1) / (x2 - x1) m = (@sustainLevel - 1) / ((@attackTime + @decayTime) - @attackTime) # plug in point (attackTime, 1) to find b: # 1 = m(attackTime) + b # 1 - m(attackTime) = b b = 1 - m * @attackTime # and solve, given x = localTime m * localTime + b else if localTime <= @attackTime + @decayTime + @sustainTime # Sustain @sustainLevel else if localTime <= @totalTime # Plot a line between (attackTime + decayTime + sustainTime, sustainLevel) and (totalTime, 0) # y = mx+b (remember m is slope, b is y intercept) # m = (y2 - y1) / (x2 - x1) m = (0 - @sustainLevel) / (@totalTime - (@attackTime + @decayTime + @sustainTime)) # plug in point (totalTime, 0) to find b: # 0 = m(totalTime) + b # 0 - m(totalTime) = b b = 0 - m * @totalTime # and solve, given x = localTime m * localTime + b else 0 realProcess: (time, inputSample) -> @startTime ?= time localTime = time - @startTime inputSample * @getMultiplier(localTime) ### process() --------- Arguments A single instance of Oscillator, or the returned value from another process() call. Returns An object that can be passed into play(), used in buildSample(), or passed into another object's process() method. More precisely, process() returns a closure in the format of `(time) -> sample`. Usage 1 someOscillator = new Oscillator envelope.process(someOscillator) Usage 2 someOscillator1 = new Oscillator someOscillator2 = new Oscillator envelope.process(mixer.process(someOscillator1, someOscillator2)) ### process: (child) -> unless arguments.length == 1 throw new Error "#{@constructor.name}.process() only accepts a single argument." unless Function.isFunction(child) throw new Error "#{@constructor.name}.process() requires a sound generator but did not receive any." f = (time) => @realProcess(time, child(time)) f.duration = @attackTime + @decayTime + @sustainTime + @releaseTime f ### Mixer Class -------------------------------------------------------------------------------- A mixer primarily does two things: adjust the volume of a signal, and add multiple signals together into one. Most process() methods allow only a single argument. If you'd like to process multiple signals, you can combine them first using this class. Constants None Arguments gain: Gain amount in dB. Optional. Default -7.0. Float value. Returns An object with a process() method, ready to accept multiple oscillators, or any results of calls to other process() methods. Usage 1 (JS) var oscillator1 = new Oscillator(); var oscillator2 = new Oscillator({frequency: Frequency.A_4}); var mixer = new Mixer({ gain: -5.0 }); var processor = mixer.process(oscillator1, oscillator2); var buildSample = function(time){ return processor(time); } Usage 2 (JS) var oscillator1 = new Oscillator(); var oscillator2 = new Oscillator({frequency: Frequency.A_4}); var envelope = new Envelope(); var mixer = new Mixer({ gain: -5.0 }); var processor = envelope.process(mixer.process(oscillator1, oscillator2)); var buildTrack = function(){ this.play(processor); } ### class Mixer constructor: (options={}) -> # Calculate amplitude multiplier given perceived dB gain. # http://www.sengpielaudio.com/calculator-loudness.htm @setGain(options.gain || -7.0) getGain: -> @gain setGain: (@gain=-7.0) -> @multiplier = Math.pow(10, @gain / 20) ### process() --------- Arguments Multiple instances of Oscillator, or the returned values from other process() calls. Returns An object that can be passed into play(), used in buildSample(), or passed into another object's process() method. More precisely, process() returns a closure in the format of `(time) -> sample`. Usage 1 someOscillator = new Oscillator envelope.process(someOscillator) Usage 2 someOscillator1 = new Oscillator someOscillator2 = new Oscillator envelope.process(mixer.process(someOscillator1, someOscillator2)) ### process: (nestedProcessors...) -> f = (time, globalTime) => sample = 0 for processor in nestedProcessors when (!processor.duration? || time <= processor.duration) sample += @multiplier * processor(time, globalTime) sample # Find longest child duration or leave empty if ANY child runs indefinitely duration = -1 for processor in nestedProcessors if processor.duration? duration = Math.max(duration, processor.duration) else duration = -1 break f.duration = duration if duration > 0 f ### Filter Class -------------------------------------------------------------------------------- Utility class to attenuate the different frequency components of a signal. For example white noise (e.g.: (t) -> Math.random() * 2 - 1), contains a wide range of frequencies. By filtering this noise you can shape the resulting sound. This is best understood through experimentation. This class implements a Biquad filter, a workhorse for general-purpose filter use. Filters are complex; it's not always intuitive how a parameter value will affect the resulting frequency response. It may be helpful to use a frequency response calculator, like this one, which is really nice: http://www.earlevel.com/main/2013/10/13/biquad-calculator-v2/ Constants Filter.LOW_PASS: Filter type. Let low frequencies through. Filter.HIGH_PASS: Filter type. Let high frequencies through. Filter.BAND_PASS_CONSTANT_SKIRT: Filter type. Let a range of frequencies through. Optionally uses the band width parameter (`filter.setBW(width)`). Filter.BAND_PASS_CONSTANT_PEAK: Filter type. Let a range of frequencies through. Optionally uses the band width parameter (`filter.setBW(width)`). Filter.NOTCH: Filter type. Remove a narrow range of frequencies. Filter.ALL_PASS: Filter type. Let all frequencies through. Filter.PEAKING_EQ: Filter type. Boost frequencies around a specific value. Optionally uses the setDbGain value. Filter.LOW_SHELF: Filter type. Boost low-frequency sounds. Optionally uses the setDbGain value. Filter.HIGH_SHELF: Filter type. Boost high-frequency sounds. Optionally uses the setDbGain value. Arguments type: Optional. Default Filter.LOW_PASS. Accepts any filter type. frequency: Optional. Default 300. A value in Hz specifying the midpoint or cutoff frequency of the filter. Returns An object with a process() method, ready to accept multiple oscillators, or any results of calls to other process() methods. Usage 1 (JS): require('v1/instruments'); var oscillator = new Oscillator({type: Oscillator.SQUARE, frequency: 55}) var filter = new Filter(); var processor = filter.process(oscillator); var buildSample = function(time){ return processor(time); } Usage 2 (JS): require('v1/instruments'); var oscillator = new Oscillator({frequency: Frequency.A_3, type: Oscillator.NOISE}); var filter = new Filter({type: Filter.HIGH_PASS, frequency: 10000}); var envelope = new Envelope(); var buildTrack = function(){ this.play(envelope.process(filter.process(oscillator))); } ### # Biquad filter # Created by Ricard Marxer <email@ricardmarxer.com> on 2010-05-23. # Copyright 2010 Ricard Marxer. All rights reserved. # Translated to CoffeeScript by Ed McManus # # Implementation based on: # http://www.musicdsp.org/files/Audio-EQ-Cookbook.txt class Filter # Biquad filter types @LOW_PASS = 0 # H(s) = 1 / (s^2 + s/Q + 1) @HIGH_PASS = 1 # H(s) = s^2 / (s^2 + s/Q + 1) @BAND_PASS_CONSTANT_SKIRT = 2 # H(s) = s / (s^2 + s/Q + 1) (constant skirt gain, peak gain = Q) @BAND_PASS_CONSTANT_PEAK = 3 # H(s) = (s/Q) / (s^2 + s/Q + 1) (constant 0 dB peak gain) @NOTCH = 4 # H(s) = (s^2 + 1) / (s^2 + s/Q + 1) @ALL_PASS = 5 # H(s) = (s^2 - s/Q + 1) / (s^2 + s/Q + 1) @PEAKING_EQ = 6 # H(s) = (s^2 + s*(A/Q) + 1) / (s^2 + s/(A*Q) + 1) @LOW_SHELF = 7 # H(s) = A * (s^2 + (sqrt(A)/Q)*s + A)/(A*s^2 + (sqrt(A)/Q)*s + 1) @HIGH_SHELF = 8 # H(s) = A * (A*s^2 + (sqrt(A)/Q)*s + 1)/(s^2 + (sqrt(A)/Q)*s + A) # Biquad filter parameter types @Q = 1 @BW = 2 # SHARED with BACKWARDS LOOP MODE @S = 3 constructor: (options={}) -> @Fs = SAMPLE_RATE @type = options.type || Filter.LOW_PASS # type of the filter @parameterType = Filter.Q # type of the parameter @x_1_l = 0 @x_2_l = 0 @y_1_l = 0 @y_2_l = 0 @x_1_r = 0 @x_2_r = 0 @y_1_r = 0 @y_2_r = 0 @b0 = 1 @a0 = 1 @b1 = 0 @a1 = 0 @b2 = 0 @a2 = 0 @b0a0 = @b0 / @a0 @b1a0 = @b1 / @a0 @b2a0 = @b2 / @a0 @a1a0 = @a1 / @a0 @a2a0 = @a2 / @a0 @f0 = options.frequency || 300 # "wherever it's happenin', man." Center Frequency or # Corner Frequency, or shelf midpoint frequency, depending # on which filter type. The "significant frequency". @dBgain = 12 # used only for peaking and shelving filters @Q = 1 # the EE kind of definition, except for peakingEQ in which A*Q is # the classic EE Q. That adjustment in definition was made so that # a boost of N dB followed by a cut of N dB for identical Q and # f0/Fs results in a precisely flat unity gain filter or "wire". @BW = -3 # the bandwidth in octaves (between -3 dB frequencies for BPF # and notch or between midpoint (dBgain/2) gain frequencies for # peaking EQ @S = 1 # a "shelf slope" parameter (for shelving EQ only). When S = 1, # the shelf slope is as steep as it can be and remain monotonically # increasing or decreasing gain with frequency. The shelf slope, in # dB/octave, remains proportional to S for all other values for a # fixed f0/Fs and dBgain. # Since we now accept frequency as an option @recalculateCoefficients() ### setFrequency() Alias for setF0(). Sometimes referred to as the center frequency, midpoint frequency, or cutoff frequency, depending on filter type. Arguments Number value representing center frequency in Hz. Default 300. ### setFrequency: (freq) -> @setF0(freq) freq getFrequency: -> @f0 ### setQ() "Q factor" Arguments Number value representing the filter's Q factor. Only used in some filter types. To see the impact Q has on the filter's frequency response, use the calculator at: http://www.earlevel.com/main/2013/10/13/biquad-calculator-v2/ ### getQ: -> @Q setQ: (q) -> @parameterType = Filter.Q @Q = Math.max(Math.min(q, 115.0), 0.001) @recalculateCoefficients() q # # Advanced filter parameters coefficients: -> b = [@b0, @b1, @b2] a = [@a0, @a1, @a2] {b: b, a: a} setFilterType: (type) -> @type = type @recalculateCoefficients() ### setBW() Set band width value used in "band" filter types. Arguments Number value representing the filter's band width. Ignored unless filter type is set to band pass. ### setBW: (bw) -> @parameterType = Filter.BW @BW = bw @recalculateCoefficients() bw setS: (s) -> @parameterType = Filter.S @S = Math.max(Math.min(s, 5.0), 0.0001) @recalculateCoefficients() ### setF0() Sometimes referred to as the center frequency, midpoint frequency, or cutoff frequency, depending on filter type. Arguments Number value representing center frequency in Hz. Default 300. ### setF0: (freq) -> @f0 = freq @recalculateCoefficients() setDbGain: (g) -> @dBgain = g @recalculateCoefficients() recalculateCoefficients: -> if @type == Filter.PEAKING_EQ || @type == Filter.LOW_SHELF || @type == Filter.HIGH_SHELF A = Math.pow(10, (@dBgain/40)) # for peaking and shelving EQ filters only else A = Math.sqrt( Math.pow(10, (@dBgain/20)) ) w0 = 2 * Math.PI * @f0 / @Fs cosw0 = Math.cos(w0) sinw0 = Math.sin(w0) alpha = 0 switch @parameterType when Filter.Q alpha = sinw0/(2*@Q) when Filter.BW alpha = sinw0 * sinh( Math.LN2/2 * @BW * w0/sinw0 ) when Filter.S alpha = sinw0/2 * Math.sqrt( (A + 1/A)*(1/@S - 1) + 2 ) # # FYI: The relationship between bandwidth and Q is # 1/Q = 2*sinh(ln(2)/2*BW*w0/sin(w0)) (digital filter w BLT) # or 1/Q = 2*sinh(ln(2)/2*BW) (analog filter prototype) # # The relationship between shelf slope and Q is # 1/Q = sqrt((A + 1/A)*(1/S - 1) + 2) # switch @type when Filter.LOW_PASS # H(s) = 1 / (s^2 + s/Q + 1) @b0 = (1 - cosw0)/2 @b1 = 1 - cosw0 @b2 = (1 - cosw0)/2 @a0 = 1 + alpha @a1 = -2 * cosw0 @a2 = 1 - alpha when Filter.HIGH_PASS # H(s) = s^2 / (s^2 + s/Q + 1) @b0 = (1 + cosw0)/2 @b1 = -(1 + cosw0) @b2 = (1 + cosw0)/2 @a0 = 1 + alpha @a1 = -2 * cosw0 @a2 = 1 - alpha when Filter.BAND_PASS_CONSTANT_SKIRT # H(s) = s / (s^2 + s/Q + 1) (constant skirt gain, peak gain = Q) @b0 = sinw0/2 @b1 = 0 @b2 = -sinw0/2 @a0 = 1 + alpha @a1 = -2*cosw0 @a2 = 1 - alpha when Filter.BAND_PASS_CONSTANT_PEAK # H(s) = (s/Q) / (s^2 + s/Q + 1) (constant 0 dB peak gain) @b0 = alpha @b1 = 0 @b2 = -alpha @a0 = 1 + alpha @a1 = -2*cosw0 @a2 = 1 - alpha when Filter.NOTCH # H(s) = (s^2 + 1) / (s^2 + s/Q + 1) @b0 = 1 @b1 = -2*cosw0 @b2 = 1 @a0 = 1 + alpha @a1 = -2*cosw0 @a2 = 1 - alpha when Filter.ALL_PASS # H(s) = (s^2 - s/Q + 1) / (s^2 + s/Q + 1) @b0 = 1 - alpha @b1 = -2*cosw0 @b2 = 1 + alpha @a0 = 1 + alpha @a1 = -2*cosw0 @a2 = 1 - alpha when Filter.PEAKING_EQ # H(s) = (s^2 + s*(A/Q) + 1) / (s^2 + s/(A*Q) + 1) @b0 = 1 + alpha*A @b1 = -2*cosw0 @b2 = 1 - alpha*A @a0 = 1 + alpha/A @a1 = -2*cosw0 @a2 = 1 - alpha/A when Filter.LOW_SHELF # H(s) = A * (s^2 + (sqrt(A)/Q)*s + A)/(A*s^2 + (sqrt(A)/Q)*s + 1) coeff = sinw0 * Math.sqrt( (A^2 + 1)*(1/@S - 1) + 2*A ) @b0 = A*((A+1) - (A-1)*cosw0 + coeff) @b1 = 2*A*((A-1) - (A+1)*cosw0) @b2 = A*((A+1) - (A-1)*cosw0 - coeff) @a0 = (A+1) + (A-1)*cosw0 + coeff @a1 = -2*((A-1) + (A+1)*cosw0) @a2 = (A+1) + (A-1)*cosw0 - coeff when Filter.HIGH_SHELF # H(s) = A * (A*s^2 + (sqrt(A)/Q)*s + 1)/(s^2 + (sqrt(A)/Q)*s + A) coeff = sinw0 * Math.sqrt( (A^2 + 1)*(1/@S - 1) + 2*A ) @b0 = A*((A+1) + (A-1)*cosw0 + coeff) @b1 = -2*A*((A-1) + (A+1)*cosw0) @b2 = A*((A+1) + (A-1)*cosw0 - coeff) @a0 = (A+1) - (A-1)*cosw0 + coeff @a1 = 2*((A-1) - (A+1)*cosw0) @a2 = (A+1) - (A-1)*cosw0 - coeff @b0a0 = @b0/@a0 @b1a0 = @b1/@a0 @b2a0 = @b2/@a0 @a1a0 = @a1/@a0 @a2a0 = @a2/@a0 ### process() --------- Arguments A single instance of Oscillator or the returned value from another process() call (such as Mixer). Returns An object that can be passed into play(), used in buildSample(), or passed into another object's process() method. More precisely, process() returns a closure in the format of `(time) -> sample`. Usage 1 var someOscillator = new Oscillator({type: Oscillator.SAWTOOTH}); var filter = new Filter; var processor = filter.process(someOscillator); var buildSample = function(time) { return processor(time); } Usage 2 var someOscillator1 = new Oscillator({type: Oscillator.SQUARE}); var someOscillator2 = new Oscillator; var filter = new Fiter; var processor = filter.process(envelope.process(mixer.process(someOscillator1, someOscillator2))); var buildSample = function(time) { return processor(time); } ### process: (child) -> unless Function.isFunction(child) throw new Error "#{@constructor.name}.process() requires a sound generator but did not receive any." f = (time) => @realProcess(time, child(time)) f.duration = child.duration if child.duration f realProcess: (time, inputSample) -> #y[n] = (b0/a0)*x[n] + (b1/a0)*x[n-1] + (b2/a0)*x[n-2] # - (a1/a0)*y[n-1] - (a2/a0)*y[n-2] sample = inputSample output = @b0a0*sample + @b1a0*@x_1_l + @b2a0*@x_2_l - @a1a0*@y_1_l - @a2a0*@y_2_l @y_2_l = @y_1_l @y_1_l = output @x_2_l = @x_1_l @x_1_l = sample output
125963
### Oscillator Class -------------------------------------------------------------------------------- The Oscillator class provides a basic sound wave. You can play the resulting sound directly, or, more likely, process the sound with another class in the library, such as Filter, Envelope, or Mixer. Constants Oscillator.SINE Wave type. Smooth sine waveform. Oscillator.SQUARE Wave type. Square waveform. Oscillator.SAWTOOTH Wave type. Sawtooth waveform. Oscillator.TRIANGLE Wave type. Triangle waveform. Oscillator.NOISE Wave type. Random samples between -1 and 1. Wave types: https://en.wikipedia.org/wiki/Waveform Arguments type: Optional. Default Oscillator.SINE. The type of sound wave to generate. Accepted values: Oscillator.SINE, Oscillator.TRIANGLE, Oscillator.SQUARE, Oscillator.NOISE, Oscillator.SAWTOOTH. frequency: Optional. Default 440. Number, or a function that takes a time parameter and returns a frequency. The time argument specifies how long the oscillator has been running. amplitude: Optional. Default 1. Number, or a function that takes a time parameter and returns an amplitude multiplier. *Not* in dB's. the time argument specifies how long the oscillator has been running. phase: Optional. Default 0. Number, or a function that takes a time parameter and returns a phase shift. the time argument specifies how long the oscillator has been running. This is an advanced parameter and can probably be ignored in most cases. Returns An instance-like closure that wraps the values passed at instantiation. This follows the `(time) -> sample` convention for use in play() and buildSample(). Usage 1 (JS) - Basic wave (build sample version) require('v1/instruments'); var oscillator = new Oscillator({frequency: Frequency.A_3}); var buildSample = function(time){ return oscillator(time); } Usage 2 (JS) - Basic triangle wave (build track version) require('v1/instruments'); var oscillator = new Oscillator({frequency: Frequency.A_3, type: Oscillator.TRIANGLE}); var buildTrack = function(){ this.play(oscillator); } Usage 3 (JS) - Basic square wave, with amplitude require('v1/instruments'); var oscillator = new Oscillator({frequency: Frequency.A_3, type: Oscillator.SQUARE, amplitude: 0.7}); var envelope = new Envelope(); var buildTrack = function(){ this.play(envelope.process(oscillator)); } Usage 4 (JS) - Vibrato require('v1/instruments'); var phaseModulation = function(time){ return 0.1 * Math.sin(TWO_PI * time * 5); } var oscillator = new Oscillator({frequency: Frequency.A_3, phase: phaseModulation}); var buildTrack = function(){ this.play(oscillator); } Usage 5 (JS) - Hi Hat require('v1/instruments'); var oscillator = new Oscillator({frequency: Frequency.A_3, type: Oscillator.NOISE}); var filter = new Filter({type: Filter.HIGH_PASS, frequency: 10000}); var envelope = new Envelope(); var buildTrack = function(){ this.play(envelope.process(filter.process(oscillator))); } ### class Oscillator # Types @SINE = 0 @SQUARE = 1 @SAWTOOTH = 2 @TRIANGLE = 3 @NOISE = 4 constructor: (options={}) -> @frequency = options.frequency || 440 @phase = options.phase || 0 @amplitude = options.amplitude || 1 @numericPhase = @phase unless Function.isFunction(@phase) @numericFrequency = @frequency unless Function.isFunction(@frequency) @numericAmplitude = @amplitude unless Function.isFunction(@amplitude) @oscillatorFunction = switch (options.type || Oscillator.SINE) when Oscillator.SQUARE @square when Oscillator.SAWTOOTH @sawtooth when Oscillator.TRIANGLE @triangle when Oscillator.NOISE @noise else @sine # Represents start time @startTime = -1 # The closure to be returned at the end of this call generator = (time) => # Using localTime makes it easier to anticipate the interference of # multiple oscillators @startTime = time if @startTime == -1 @localTime = time - @startTime _phase = if @numericPhase? then @numericPhase else @phase(@localTime) _frequency = if @numericFrequency? then @numericFrequency else @frequency(@localTime) _amplitude = if @numericAmplitude? then @numericAmplitude else @amplitude(@localTime) _amplitude * @oscillatorFunction((_frequency * @localTime) + _phase) generator.displayName = "Oscillator Sound Generator" generator.getFrequency = => if @numericFrequency? then @numericFrequency else @frequency(@localTime) generator.setFrequency = (frequency) => @frequency = frequency if Function.isFunction(@frequency) @numericFrequency = undefined else @numericFrequency = @frequency frequency generator.getPhase = => if @numericPhase? then @numericPhase else @phase(@localTime) generator.setPhase = (phase) => @phase = phase if Function.isFunction(@phase) @numericPhase = undefined else @numericPhase = @phase phase generator.getAmplitude = => if @numericAmplitude? then @numericAmplitude else @amplitude(@localTime) generator.setAmplitude = (amplitude) => @amplitude = amplitude if Function.isFunction(@amplitude) @numericAmplitude = undefined else @numericAmplitude = @amplitude amplitude # Explicit return necessary in constructor return generator sine: (value) -> # Smooth wave intersecting (0, 0), (0.25, 1), (0.5, 0), (0.75, -1), (1, 0) Math.sin(2 * Math.PI * value) sawtooth: (value) -> # Line from (-.5,-1) to (0.5, 1) progress = (value + 0.5) % 1 2 * progress - 1 triangle: (value) -> # Linear change from (0, -1) to (0.5, 1) to (1, -1) progress = value % 1 if progress < 0.5 4 * progress - 1 else -4 * progress + 3 square: (value) -> # -1 for the first half of a cycle; 1 for the second half progress = value % 1 if progress < 0.5 1 else -1 noise: (value) -> Math.random() * 2 - 1 ### Envelope Class -------------------------------------------------------------------------------- Shapes the sound wave passed into process(). Constants Envelope.AD Attack / Decay envelope. Only the attackTime and decayTime parameters are used. AD Envelope - Amplitude: /\ 1 / \ / \ 0 |-| Attack phase |-| Decay phase Envelope.ADSR Attack Decay Sustain Release envelope. All parameters are used. ADSR Envelope - Amplitude: /\ 1 / \____ sustainLevel / \ 0 |-| Attack phase |-| Decay phase |---| Sustain phase |-| Release phase Arguments type: Optional. Default Envelope.AD. Accepted values: Envelope.AD, Envelope.ADSR. attackTime: Optional. Default 0.03. Value in seconds. decayTime: Optional. Default 1.0. Value in seconds. sustainTime: Optional. Default 0. Value in seconds. Ignored unless envelope type is Envelope.ADSR. releaseTime: Optional. Default 0. Value in seconds. Ignored unless envelope type is Envelope.ADSR. sustainLevel: Optional. Default 0. Value in seconds. Ignored unless envelope type is Envelope.ADSR. Returns An object with a process() method, ready to accept an oscillator or other sound generator to be shaped. Usage 1 (JS) require('v1/instruments'); var o = new Oscillator; var e = new Envelope; var processor = e.process(o); var buildSample = function(time) { return processor(time); } Usage 2 (JS) require('v1/instruments'); var o = new Oscillator; var e = new Envelope; var buildTrack = function() { this.play(e.process(o)); } Usage 3 (JS) require('v1/instruments'); var o = new Oscillator; var e = new Envelope({type: Envelope.ADSR, sustainTime: 1, releaseTime: 1, sustainLevel: 0.5}); var buildTrack = function() { this.play(e.process(o)); } ### class Envelope # AD Envelope Type # # Amplitude: # /\ 1 # / \ # / \ 0 # |-| Attack # |-| Decay @AD = 0 # ADSR Envelope Type # # Amplitude: # /\ 1 # / \____ sustainLevel # / \ 0 # |-| Attack # |-| Decay # |---| Sustain # |-| Release @ADSR = 1 constructor: (options={}) -> options.sustainLevel ?= 0.3 options.type ?= Envelope.AD if options.type == Envelope.AD options.attackTime ?= 0.03 options.decayTime ?= 1 options.sustainTime = 0 options.releaseTime = 0 options.sustainLevel = 0 unless options.attackTime? && options.decayTime? && options.sustainTime? && options.releaseTime? throw new Error "Options must specify 'attackTime', 'decayTime', 'sustainTime' and 'releaseTime' values for ADSR envelope type." @type = options.type @sustainLevel = options.sustainLevel @attackTime = options.attackTime @decayTime = options.decayTime @sustainTime = options.sustainTime @releaseTime = options.releaseTime @totalTime = options.attackTime + options.decayTime + options.sustainTime + options.releaseTime getMultiplier: (localTime) -> if localTime <= @attackTime # Attack localTime / @attackTime else if localTime <= @attackTime + @decayTime # Plot a line between (attackTime, 1) and (attackTime + decayTime, sustainLevel) # y = mx+b (remember m is slope, b is y intercept) # m = (y2 - y1) / (x2 - x1) m = (@sustainLevel - 1) / ((@attackTime + @decayTime) - @attackTime) # plug in point (attackTime, 1) to find b: # 1 = m(attackTime) + b # 1 - m(attackTime) = b b = 1 - m * @attackTime # and solve, given x = localTime m * localTime + b else if localTime <= @attackTime + @decayTime + @sustainTime # Sustain @sustainLevel else if localTime <= @totalTime # Plot a line between (attackTime + decayTime + sustainTime, sustainLevel) and (totalTime, 0) # y = mx+b (remember m is slope, b is y intercept) # m = (y2 - y1) / (x2 - x1) m = (0 - @sustainLevel) / (@totalTime - (@attackTime + @decayTime + @sustainTime)) # plug in point (totalTime, 0) to find b: # 0 = m(totalTime) + b # 0 - m(totalTime) = b b = 0 - m * @totalTime # and solve, given x = localTime m * localTime + b else 0 realProcess: (time, inputSample) -> @startTime ?= time localTime = time - @startTime inputSample * @getMultiplier(localTime) ### process() --------- Arguments A single instance of Oscillator, or the returned value from another process() call. Returns An object that can be passed into play(), used in buildSample(), or passed into another object's process() method. More precisely, process() returns a closure in the format of `(time) -> sample`. Usage 1 someOscillator = new Oscillator envelope.process(someOscillator) Usage 2 someOscillator1 = new Oscillator someOscillator2 = new Oscillator envelope.process(mixer.process(someOscillator1, someOscillator2)) ### process: (child) -> unless arguments.length == 1 throw new Error "#{@constructor.name}.process() only accepts a single argument." unless Function.isFunction(child) throw new Error "#{@constructor.name}.process() requires a sound generator but did not receive any." f = (time) => @realProcess(time, child(time)) f.duration = @attackTime + @decayTime + @sustainTime + @releaseTime f ### Mixer Class -------------------------------------------------------------------------------- A mixer primarily does two things: adjust the volume of a signal, and add multiple signals together into one. Most process() methods allow only a single argument. If you'd like to process multiple signals, you can combine them first using this class. Constants None Arguments gain: Gain amount in dB. Optional. Default -7.0. Float value. Returns An object with a process() method, ready to accept multiple oscillators, or any results of calls to other process() methods. Usage 1 (JS) var oscillator1 = new Oscillator(); var oscillator2 = new Oscillator({frequency: Frequency.A_4}); var mixer = new Mixer({ gain: -5.0 }); var processor = mixer.process(oscillator1, oscillator2); var buildSample = function(time){ return processor(time); } Usage 2 (JS) var oscillator1 = new Oscillator(); var oscillator2 = new Oscillator({frequency: Frequency.A_4}); var envelope = new Envelope(); var mixer = new Mixer({ gain: -5.0 }); var processor = envelope.process(mixer.process(oscillator1, oscillator2)); var buildTrack = function(){ this.play(processor); } ### class Mixer constructor: (options={}) -> # Calculate amplitude multiplier given perceived dB gain. # http://www.sengpielaudio.com/calculator-loudness.htm @setGain(options.gain || -7.0) getGain: -> @gain setGain: (@gain=-7.0) -> @multiplier = Math.pow(10, @gain / 20) ### process() --------- Arguments Multiple instances of Oscillator, or the returned values from other process() calls. Returns An object that can be passed into play(), used in buildSample(), or passed into another object's process() method. More precisely, process() returns a closure in the format of `(time) -> sample`. Usage 1 someOscillator = new Oscillator envelope.process(someOscillator) Usage 2 someOscillator1 = new Oscillator someOscillator2 = new Oscillator envelope.process(mixer.process(someOscillator1, someOscillator2)) ### process: (nestedProcessors...) -> f = (time, globalTime) => sample = 0 for processor in nestedProcessors when (!processor.duration? || time <= processor.duration) sample += @multiplier * processor(time, globalTime) sample # Find longest child duration or leave empty if ANY child runs indefinitely duration = -1 for processor in nestedProcessors if processor.duration? duration = Math.max(duration, processor.duration) else duration = -1 break f.duration = duration if duration > 0 f ### Filter Class -------------------------------------------------------------------------------- Utility class to attenuate the different frequency components of a signal. For example white noise (e.g.: (t) -> Math.random() * 2 - 1), contains a wide range of frequencies. By filtering this noise you can shape the resulting sound. This is best understood through experimentation. This class implements a Biquad filter, a workhorse for general-purpose filter use. Filters are complex; it's not always intuitive how a parameter value will affect the resulting frequency response. It may be helpful to use a frequency response calculator, like this one, which is really nice: http://www.earlevel.com/main/2013/10/13/biquad-calculator-v2/ Constants Filter.LOW_PASS: Filter type. Let low frequencies through. Filter.HIGH_PASS: Filter type. Let high frequencies through. Filter.BAND_PASS_CONSTANT_SKIRT: Filter type. Let a range of frequencies through. Optionally uses the band width parameter (`filter.setBW(width)`). Filter.BAND_PASS_CONSTANT_PEAK: Filter type. Let a range of frequencies through. Optionally uses the band width parameter (`filter.setBW(width)`). Filter.NOTCH: Filter type. Remove a narrow range of frequencies. Filter.ALL_PASS: Filter type. Let all frequencies through. Filter.PEAKING_EQ: Filter type. Boost frequencies around a specific value. Optionally uses the setDbGain value. Filter.LOW_SHELF: Filter type. Boost low-frequency sounds. Optionally uses the setDbGain value. Filter.HIGH_SHELF: Filter type. Boost high-frequency sounds. Optionally uses the setDbGain value. Arguments type: Optional. Default Filter.LOW_PASS. Accepts any filter type. frequency: Optional. Default 300. A value in Hz specifying the midpoint or cutoff frequency of the filter. Returns An object with a process() method, ready to accept multiple oscillators, or any results of calls to other process() methods. Usage 1 (JS): require('v1/instruments'); var oscillator = new Oscillator({type: Oscillator.SQUARE, frequency: 55}) var filter = new Filter(); var processor = filter.process(oscillator); var buildSample = function(time){ return processor(time); } Usage 2 (JS): require('v1/instruments'); var oscillator = new Oscillator({frequency: Frequency.A_3, type: Oscillator.NOISE}); var filter = new Filter({type: Filter.HIGH_PASS, frequency: 10000}); var envelope = new Envelope(); var buildTrack = function(){ this.play(envelope.process(filter.process(oscillator))); } ### # Biquad filter # Created by <NAME> <<EMAIL>> on 2010-05-23. # Copyright 2010 <NAME>. All rights reserved. # Translated to CoffeeScript by Ed McManus # # Implementation based on: # http://www.musicdsp.org/files/Audio-EQ-Cookbook.txt class Filter # Biquad filter types @LOW_PASS = 0 # H(s) = 1 / (s^2 + s/Q + 1) @HIGH_PASS = 1 # H(s) = s^2 / (s^2 + s/Q + 1) @BAND_PASS_CONSTANT_SKIRT = 2 # H(s) = s / (s^2 + s/Q + 1) (constant skirt gain, peak gain = Q) @BAND_PASS_CONSTANT_PEAK = 3 # H(s) = (s/Q) / (s^2 + s/Q + 1) (constant 0 dB peak gain) @NOTCH = 4 # H(s) = (s^2 + 1) / (s^2 + s/Q + 1) @ALL_PASS = 5 # H(s) = (s^2 - s/Q + 1) / (s^2 + s/Q + 1) @PEAKING_EQ = 6 # H(s) = (s^2 + s*(A/Q) + 1) / (s^2 + s/(A*Q) + 1) @LOW_SHELF = 7 # H(s) = A * (s^2 + (sqrt(A)/Q)*s + A)/(A*s^2 + (sqrt(A)/Q)*s + 1) @HIGH_SHELF = 8 # H(s) = A * (A*s^2 + (sqrt(A)/Q)*s + 1)/(s^2 + (sqrt(A)/Q)*s + A) # Biquad filter parameter types @Q = 1 @BW = 2 # SHARED with BACKWARDS LOOP MODE @S = 3 constructor: (options={}) -> @Fs = SAMPLE_RATE @type = options.type || Filter.LOW_PASS # type of the filter @parameterType = Filter.Q # type of the parameter @x_1_l = 0 @x_2_l = 0 @y_1_l = 0 @y_2_l = 0 @x_1_r = 0 @x_2_r = 0 @y_1_r = 0 @y_2_r = 0 @b0 = 1 @a0 = 1 @b1 = 0 @a1 = 0 @b2 = 0 @a2 = 0 @b0a0 = @b0 / @a0 @b1a0 = @b1 / @a0 @b2a0 = @b2 / @a0 @a1a0 = @a1 / @a0 @a2a0 = @a2 / @a0 @f0 = options.frequency || 300 # "wherever it's happenin', man." Center Frequency or # Corner Frequency, or shelf midpoint frequency, depending # on which filter type. The "significant frequency". @dBgain = 12 # used only for peaking and shelving filters @Q = 1 # the EE kind of definition, except for peakingEQ in which A*Q is # the classic EE Q. That adjustment in definition was made so that # a boost of N dB followed by a cut of N dB for identical Q and # f0/Fs results in a precisely flat unity gain filter or "wire". @BW = -3 # the bandwidth in octaves (between -3 dB frequencies for BPF # and notch or between midpoint (dBgain/2) gain frequencies for # peaking EQ @S = 1 # a "shelf slope" parameter (for shelving EQ only). When S = 1, # the shelf slope is as steep as it can be and remain monotonically # increasing or decreasing gain with frequency. The shelf slope, in # dB/octave, remains proportional to S for all other values for a # fixed f0/Fs and dBgain. # Since we now accept frequency as an option @recalculateCoefficients() ### setFrequency() Alias for setF0(). Sometimes referred to as the center frequency, midpoint frequency, or cutoff frequency, depending on filter type. Arguments Number value representing center frequency in Hz. Default 300. ### setFrequency: (freq) -> @setF0(freq) freq getFrequency: -> @f0 ### setQ() "Q factor" Arguments Number value representing the filter's Q factor. Only used in some filter types. To see the impact Q has on the filter's frequency response, use the calculator at: http://www.earlevel.com/main/2013/10/13/biquad-calculator-v2/ ### getQ: -> @Q setQ: (q) -> @parameterType = Filter.Q @Q = Math.max(Math.min(q, 115.0), 0.001) @recalculateCoefficients() q # # Advanced filter parameters coefficients: -> b = [@b0, @b1, @b2] a = [@a0, @a1, @a2] {b: b, a: a} setFilterType: (type) -> @type = type @recalculateCoefficients() ### setBW() Set band width value used in "band" filter types. Arguments Number value representing the filter's band width. Ignored unless filter type is set to band pass. ### setBW: (bw) -> @parameterType = Filter.BW @BW = bw @recalculateCoefficients() bw setS: (s) -> @parameterType = Filter.S @S = Math.max(Math.min(s, 5.0), 0.0001) @recalculateCoefficients() ### setF0() Sometimes referred to as the center frequency, midpoint frequency, or cutoff frequency, depending on filter type. Arguments Number value representing center frequency in Hz. Default 300. ### setF0: (freq) -> @f0 = freq @recalculateCoefficients() setDbGain: (g) -> @dBgain = g @recalculateCoefficients() recalculateCoefficients: -> if @type == Filter.PEAKING_EQ || @type == Filter.LOW_SHELF || @type == Filter.HIGH_SHELF A = Math.pow(10, (@dBgain/40)) # for peaking and shelving EQ filters only else A = Math.sqrt( Math.pow(10, (@dBgain/20)) ) w0 = 2 * Math.PI * @f0 / @Fs cosw0 = Math.cos(w0) sinw0 = Math.sin(w0) alpha = 0 switch @parameterType when Filter.Q alpha = sinw0/(2*@Q) when Filter.BW alpha = sinw0 * sinh( Math.LN2/2 * @BW * w0/sinw0 ) when Filter.S alpha = sinw0/2 * Math.sqrt( (A + 1/A)*(1/@S - 1) + 2 ) # # FYI: The relationship between bandwidth and Q is # 1/Q = 2*sinh(ln(2)/2*BW*w0/sin(w0)) (digital filter w BLT) # or 1/Q = 2*sinh(ln(2)/2*BW) (analog filter prototype) # # The relationship between shelf slope and Q is # 1/Q = sqrt((A + 1/A)*(1/S - 1) + 2) # switch @type when Filter.LOW_PASS # H(s) = 1 / (s^2 + s/Q + 1) @b0 = (1 - cosw0)/2 @b1 = 1 - cosw0 @b2 = (1 - cosw0)/2 @a0 = 1 + alpha @a1 = -2 * cosw0 @a2 = 1 - alpha when Filter.HIGH_PASS # H(s) = s^2 / (s^2 + s/Q + 1) @b0 = (1 + cosw0)/2 @b1 = -(1 + cosw0) @b2 = (1 + cosw0)/2 @a0 = 1 + alpha @a1 = -2 * cosw0 @a2 = 1 - alpha when Filter.BAND_PASS_CONSTANT_SKIRT # H(s) = s / (s^2 + s/Q + 1) (constant skirt gain, peak gain = Q) @b0 = sinw0/2 @b1 = 0 @b2 = -sinw0/2 @a0 = 1 + alpha @a1 = -2*cosw0 @a2 = 1 - alpha when Filter.BAND_PASS_CONSTANT_PEAK # H(s) = (s/Q) / (s^2 + s/Q + 1) (constant 0 dB peak gain) @b0 = alpha @b1 = 0 @b2 = -alpha @a0 = 1 + alpha @a1 = -2*cosw0 @a2 = 1 - alpha when Filter.NOTCH # H(s) = (s^2 + 1) / (s^2 + s/Q + 1) @b0 = 1 @b1 = -2*cosw0 @b2 = 1 @a0 = 1 + alpha @a1 = -2*cosw0 @a2 = 1 - alpha when Filter.ALL_PASS # H(s) = (s^2 - s/Q + 1) / (s^2 + s/Q + 1) @b0 = 1 - alpha @b1 = -2*cosw0 @b2 = 1 + alpha @a0 = 1 + alpha @a1 = -2*cosw0 @a2 = 1 - alpha when Filter.PEAKING_EQ # H(s) = (s^2 + s*(A/Q) + 1) / (s^2 + s/(A*Q) + 1) @b0 = 1 + alpha*A @b1 = -2*cosw0 @b2 = 1 - alpha*A @a0 = 1 + alpha/A @a1 = -2*cosw0 @a2 = 1 - alpha/A when Filter.LOW_SHELF # H(s) = A * (s^2 + (sqrt(A)/Q)*s + A)/(A*s^2 + (sqrt(A)/Q)*s + 1) coeff = sinw0 * Math.sqrt( (A^2 + 1)*(1/@S - 1) + 2*A ) @b0 = A*((A+1) - (A-1)*cosw0 + coeff) @b1 = 2*A*((A-1) - (A+1)*cosw0) @b2 = A*((A+1) - (A-1)*cosw0 - coeff) @a0 = (A+1) + (A-1)*cosw0 + coeff @a1 = -2*((A-1) + (A+1)*cosw0) @a2 = (A+1) + (A-1)*cosw0 - coeff when Filter.HIGH_SHELF # H(s) = A * (A*s^2 + (sqrt(A)/Q)*s + 1)/(s^2 + (sqrt(A)/Q)*s + A) coeff = sinw0 * Math.sqrt( (A^2 + 1)*(1/@S - 1) + 2*A ) @b0 = A*((A+1) + (A-1)*cosw0 + coeff) @b1 = -2*A*((A-1) + (A+1)*cosw0) @b2 = A*((A+1) + (A-1)*cosw0 - coeff) @a0 = (A+1) - (A-1)*cosw0 + coeff @a1 = 2*((A-1) - (A+1)*cosw0) @a2 = (A+1) - (A-1)*cosw0 - coeff @b0a0 = @b0/@a0 @b1a0 = @b1/@a0 @b2a0 = @b2/@a0 @a1a0 = @a1/@a0 @a2a0 = @a2/@a0 ### process() --------- Arguments A single instance of Oscillator or the returned value from another process() call (such as Mixer). Returns An object that can be passed into play(), used in buildSample(), or passed into another object's process() method. More precisely, process() returns a closure in the format of `(time) -> sample`. Usage 1 var someOscillator = new Oscillator({type: Oscillator.SAWTOOTH}); var filter = new Filter; var processor = filter.process(someOscillator); var buildSample = function(time) { return processor(time); } Usage 2 var someOscillator1 = new Oscillator({type: Oscillator.SQUARE}); var someOscillator2 = new Oscillator; var filter = new Fiter; var processor = filter.process(envelope.process(mixer.process(someOscillator1, someOscillator2))); var buildSample = function(time) { return processor(time); } ### process: (child) -> unless Function.isFunction(child) throw new Error "#{@constructor.name}.process() requires a sound generator but did not receive any." f = (time) => @realProcess(time, child(time)) f.duration = child.duration if child.duration f realProcess: (time, inputSample) -> #y[n] = (b0/a0)*x[n] + (b1/a0)*x[n-1] + (b2/a0)*x[n-2] # - (a1/a0)*y[n-1] - (a2/a0)*y[n-2] sample = inputSample output = @b0a0*sample + @b1a0*@x_1_l + @b2a0*@x_2_l - @a1a0*@y_1_l - @a2a0*@y_2_l @y_2_l = @y_1_l @y_1_l = output @x_2_l = @x_1_l @x_1_l = sample output
true
### Oscillator Class -------------------------------------------------------------------------------- The Oscillator class provides a basic sound wave. You can play the resulting sound directly, or, more likely, process the sound with another class in the library, such as Filter, Envelope, or Mixer. Constants Oscillator.SINE Wave type. Smooth sine waveform. Oscillator.SQUARE Wave type. Square waveform. Oscillator.SAWTOOTH Wave type. Sawtooth waveform. Oscillator.TRIANGLE Wave type. Triangle waveform. Oscillator.NOISE Wave type. Random samples between -1 and 1. Wave types: https://en.wikipedia.org/wiki/Waveform Arguments type: Optional. Default Oscillator.SINE. The type of sound wave to generate. Accepted values: Oscillator.SINE, Oscillator.TRIANGLE, Oscillator.SQUARE, Oscillator.NOISE, Oscillator.SAWTOOTH. frequency: Optional. Default 440. Number, or a function that takes a time parameter and returns a frequency. The time argument specifies how long the oscillator has been running. amplitude: Optional. Default 1. Number, or a function that takes a time parameter and returns an amplitude multiplier. *Not* in dB's. the time argument specifies how long the oscillator has been running. phase: Optional. Default 0. Number, or a function that takes a time parameter and returns a phase shift. the time argument specifies how long the oscillator has been running. This is an advanced parameter and can probably be ignored in most cases. Returns An instance-like closure that wraps the values passed at instantiation. This follows the `(time) -> sample` convention for use in play() and buildSample(). Usage 1 (JS) - Basic wave (build sample version) require('v1/instruments'); var oscillator = new Oscillator({frequency: Frequency.A_3}); var buildSample = function(time){ return oscillator(time); } Usage 2 (JS) - Basic triangle wave (build track version) require('v1/instruments'); var oscillator = new Oscillator({frequency: Frequency.A_3, type: Oscillator.TRIANGLE}); var buildTrack = function(){ this.play(oscillator); } Usage 3 (JS) - Basic square wave, with amplitude require('v1/instruments'); var oscillator = new Oscillator({frequency: Frequency.A_3, type: Oscillator.SQUARE, amplitude: 0.7}); var envelope = new Envelope(); var buildTrack = function(){ this.play(envelope.process(oscillator)); } Usage 4 (JS) - Vibrato require('v1/instruments'); var phaseModulation = function(time){ return 0.1 * Math.sin(TWO_PI * time * 5); } var oscillator = new Oscillator({frequency: Frequency.A_3, phase: phaseModulation}); var buildTrack = function(){ this.play(oscillator); } Usage 5 (JS) - Hi Hat require('v1/instruments'); var oscillator = new Oscillator({frequency: Frequency.A_3, type: Oscillator.NOISE}); var filter = new Filter({type: Filter.HIGH_PASS, frequency: 10000}); var envelope = new Envelope(); var buildTrack = function(){ this.play(envelope.process(filter.process(oscillator))); } ### class Oscillator # Types @SINE = 0 @SQUARE = 1 @SAWTOOTH = 2 @TRIANGLE = 3 @NOISE = 4 constructor: (options={}) -> @frequency = options.frequency || 440 @phase = options.phase || 0 @amplitude = options.amplitude || 1 @numericPhase = @phase unless Function.isFunction(@phase) @numericFrequency = @frequency unless Function.isFunction(@frequency) @numericAmplitude = @amplitude unless Function.isFunction(@amplitude) @oscillatorFunction = switch (options.type || Oscillator.SINE) when Oscillator.SQUARE @square when Oscillator.SAWTOOTH @sawtooth when Oscillator.TRIANGLE @triangle when Oscillator.NOISE @noise else @sine # Represents start time @startTime = -1 # The closure to be returned at the end of this call generator = (time) => # Using localTime makes it easier to anticipate the interference of # multiple oscillators @startTime = time if @startTime == -1 @localTime = time - @startTime _phase = if @numericPhase? then @numericPhase else @phase(@localTime) _frequency = if @numericFrequency? then @numericFrequency else @frequency(@localTime) _amplitude = if @numericAmplitude? then @numericAmplitude else @amplitude(@localTime) _amplitude * @oscillatorFunction((_frequency * @localTime) + _phase) generator.displayName = "Oscillator Sound Generator" generator.getFrequency = => if @numericFrequency? then @numericFrequency else @frequency(@localTime) generator.setFrequency = (frequency) => @frequency = frequency if Function.isFunction(@frequency) @numericFrequency = undefined else @numericFrequency = @frequency frequency generator.getPhase = => if @numericPhase? then @numericPhase else @phase(@localTime) generator.setPhase = (phase) => @phase = phase if Function.isFunction(@phase) @numericPhase = undefined else @numericPhase = @phase phase generator.getAmplitude = => if @numericAmplitude? then @numericAmplitude else @amplitude(@localTime) generator.setAmplitude = (amplitude) => @amplitude = amplitude if Function.isFunction(@amplitude) @numericAmplitude = undefined else @numericAmplitude = @amplitude amplitude # Explicit return necessary in constructor return generator sine: (value) -> # Smooth wave intersecting (0, 0), (0.25, 1), (0.5, 0), (0.75, -1), (1, 0) Math.sin(2 * Math.PI * value) sawtooth: (value) -> # Line from (-.5,-1) to (0.5, 1) progress = (value + 0.5) % 1 2 * progress - 1 triangle: (value) -> # Linear change from (0, -1) to (0.5, 1) to (1, -1) progress = value % 1 if progress < 0.5 4 * progress - 1 else -4 * progress + 3 square: (value) -> # -1 for the first half of a cycle; 1 for the second half progress = value % 1 if progress < 0.5 1 else -1 noise: (value) -> Math.random() * 2 - 1 ### Envelope Class -------------------------------------------------------------------------------- Shapes the sound wave passed into process(). Constants Envelope.AD Attack / Decay envelope. Only the attackTime and decayTime parameters are used. AD Envelope - Amplitude: /\ 1 / \ / \ 0 |-| Attack phase |-| Decay phase Envelope.ADSR Attack Decay Sustain Release envelope. All parameters are used. ADSR Envelope - Amplitude: /\ 1 / \____ sustainLevel / \ 0 |-| Attack phase |-| Decay phase |---| Sustain phase |-| Release phase Arguments type: Optional. Default Envelope.AD. Accepted values: Envelope.AD, Envelope.ADSR. attackTime: Optional. Default 0.03. Value in seconds. decayTime: Optional. Default 1.0. Value in seconds. sustainTime: Optional. Default 0. Value in seconds. Ignored unless envelope type is Envelope.ADSR. releaseTime: Optional. Default 0. Value in seconds. Ignored unless envelope type is Envelope.ADSR. sustainLevel: Optional. Default 0. Value in seconds. Ignored unless envelope type is Envelope.ADSR. Returns An object with a process() method, ready to accept an oscillator or other sound generator to be shaped. Usage 1 (JS) require('v1/instruments'); var o = new Oscillator; var e = new Envelope; var processor = e.process(o); var buildSample = function(time) { return processor(time); } Usage 2 (JS) require('v1/instruments'); var o = new Oscillator; var e = new Envelope; var buildTrack = function() { this.play(e.process(o)); } Usage 3 (JS) require('v1/instruments'); var o = new Oscillator; var e = new Envelope({type: Envelope.ADSR, sustainTime: 1, releaseTime: 1, sustainLevel: 0.5}); var buildTrack = function() { this.play(e.process(o)); } ### class Envelope # AD Envelope Type # # Amplitude: # /\ 1 # / \ # / \ 0 # |-| Attack # |-| Decay @AD = 0 # ADSR Envelope Type # # Amplitude: # /\ 1 # / \____ sustainLevel # / \ 0 # |-| Attack # |-| Decay # |---| Sustain # |-| Release @ADSR = 1 constructor: (options={}) -> options.sustainLevel ?= 0.3 options.type ?= Envelope.AD if options.type == Envelope.AD options.attackTime ?= 0.03 options.decayTime ?= 1 options.sustainTime = 0 options.releaseTime = 0 options.sustainLevel = 0 unless options.attackTime? && options.decayTime? && options.sustainTime? && options.releaseTime? throw new Error "Options must specify 'attackTime', 'decayTime', 'sustainTime' and 'releaseTime' values for ADSR envelope type." @type = options.type @sustainLevel = options.sustainLevel @attackTime = options.attackTime @decayTime = options.decayTime @sustainTime = options.sustainTime @releaseTime = options.releaseTime @totalTime = options.attackTime + options.decayTime + options.sustainTime + options.releaseTime getMultiplier: (localTime) -> if localTime <= @attackTime # Attack localTime / @attackTime else if localTime <= @attackTime + @decayTime # Plot a line between (attackTime, 1) and (attackTime + decayTime, sustainLevel) # y = mx+b (remember m is slope, b is y intercept) # m = (y2 - y1) / (x2 - x1) m = (@sustainLevel - 1) / ((@attackTime + @decayTime) - @attackTime) # plug in point (attackTime, 1) to find b: # 1 = m(attackTime) + b # 1 - m(attackTime) = b b = 1 - m * @attackTime # and solve, given x = localTime m * localTime + b else if localTime <= @attackTime + @decayTime + @sustainTime # Sustain @sustainLevel else if localTime <= @totalTime # Plot a line between (attackTime + decayTime + sustainTime, sustainLevel) and (totalTime, 0) # y = mx+b (remember m is slope, b is y intercept) # m = (y2 - y1) / (x2 - x1) m = (0 - @sustainLevel) / (@totalTime - (@attackTime + @decayTime + @sustainTime)) # plug in point (totalTime, 0) to find b: # 0 = m(totalTime) + b # 0 - m(totalTime) = b b = 0 - m * @totalTime # and solve, given x = localTime m * localTime + b else 0 realProcess: (time, inputSample) -> @startTime ?= time localTime = time - @startTime inputSample * @getMultiplier(localTime) ### process() --------- Arguments A single instance of Oscillator, or the returned value from another process() call. Returns An object that can be passed into play(), used in buildSample(), or passed into another object's process() method. More precisely, process() returns a closure in the format of `(time) -> sample`. Usage 1 someOscillator = new Oscillator envelope.process(someOscillator) Usage 2 someOscillator1 = new Oscillator someOscillator2 = new Oscillator envelope.process(mixer.process(someOscillator1, someOscillator2)) ### process: (child) -> unless arguments.length == 1 throw new Error "#{@constructor.name}.process() only accepts a single argument." unless Function.isFunction(child) throw new Error "#{@constructor.name}.process() requires a sound generator but did not receive any." f = (time) => @realProcess(time, child(time)) f.duration = @attackTime + @decayTime + @sustainTime + @releaseTime f ### Mixer Class -------------------------------------------------------------------------------- A mixer primarily does two things: adjust the volume of a signal, and add multiple signals together into one. Most process() methods allow only a single argument. If you'd like to process multiple signals, you can combine them first using this class. Constants None Arguments gain: Gain amount in dB. Optional. Default -7.0. Float value. Returns An object with a process() method, ready to accept multiple oscillators, or any results of calls to other process() methods. Usage 1 (JS) var oscillator1 = new Oscillator(); var oscillator2 = new Oscillator({frequency: Frequency.A_4}); var mixer = new Mixer({ gain: -5.0 }); var processor = mixer.process(oscillator1, oscillator2); var buildSample = function(time){ return processor(time); } Usage 2 (JS) var oscillator1 = new Oscillator(); var oscillator2 = new Oscillator({frequency: Frequency.A_4}); var envelope = new Envelope(); var mixer = new Mixer({ gain: -5.0 }); var processor = envelope.process(mixer.process(oscillator1, oscillator2)); var buildTrack = function(){ this.play(processor); } ### class Mixer constructor: (options={}) -> # Calculate amplitude multiplier given perceived dB gain. # http://www.sengpielaudio.com/calculator-loudness.htm @setGain(options.gain || -7.0) getGain: -> @gain setGain: (@gain=-7.0) -> @multiplier = Math.pow(10, @gain / 20) ### process() --------- Arguments Multiple instances of Oscillator, or the returned values from other process() calls. Returns An object that can be passed into play(), used in buildSample(), or passed into another object's process() method. More precisely, process() returns a closure in the format of `(time) -> sample`. Usage 1 someOscillator = new Oscillator envelope.process(someOscillator) Usage 2 someOscillator1 = new Oscillator someOscillator2 = new Oscillator envelope.process(mixer.process(someOscillator1, someOscillator2)) ### process: (nestedProcessors...) -> f = (time, globalTime) => sample = 0 for processor in nestedProcessors when (!processor.duration? || time <= processor.duration) sample += @multiplier * processor(time, globalTime) sample # Find longest child duration or leave empty if ANY child runs indefinitely duration = -1 for processor in nestedProcessors if processor.duration? duration = Math.max(duration, processor.duration) else duration = -1 break f.duration = duration if duration > 0 f ### Filter Class -------------------------------------------------------------------------------- Utility class to attenuate the different frequency components of a signal. For example white noise (e.g.: (t) -> Math.random() * 2 - 1), contains a wide range of frequencies. By filtering this noise you can shape the resulting sound. This is best understood through experimentation. This class implements a Biquad filter, a workhorse for general-purpose filter use. Filters are complex; it's not always intuitive how a parameter value will affect the resulting frequency response. It may be helpful to use a frequency response calculator, like this one, which is really nice: http://www.earlevel.com/main/2013/10/13/biquad-calculator-v2/ Constants Filter.LOW_PASS: Filter type. Let low frequencies through. Filter.HIGH_PASS: Filter type. Let high frequencies through. Filter.BAND_PASS_CONSTANT_SKIRT: Filter type. Let a range of frequencies through. Optionally uses the band width parameter (`filter.setBW(width)`). Filter.BAND_PASS_CONSTANT_PEAK: Filter type. Let a range of frequencies through. Optionally uses the band width parameter (`filter.setBW(width)`). Filter.NOTCH: Filter type. Remove a narrow range of frequencies. Filter.ALL_PASS: Filter type. Let all frequencies through. Filter.PEAKING_EQ: Filter type. Boost frequencies around a specific value. Optionally uses the setDbGain value. Filter.LOW_SHELF: Filter type. Boost low-frequency sounds. Optionally uses the setDbGain value. Filter.HIGH_SHELF: Filter type. Boost high-frequency sounds. Optionally uses the setDbGain value. Arguments type: Optional. Default Filter.LOW_PASS. Accepts any filter type. frequency: Optional. Default 300. A value in Hz specifying the midpoint or cutoff frequency of the filter. Returns An object with a process() method, ready to accept multiple oscillators, or any results of calls to other process() methods. Usage 1 (JS): require('v1/instruments'); var oscillator = new Oscillator({type: Oscillator.SQUARE, frequency: 55}) var filter = new Filter(); var processor = filter.process(oscillator); var buildSample = function(time){ return processor(time); } Usage 2 (JS): require('v1/instruments'); var oscillator = new Oscillator({frequency: Frequency.A_3, type: Oscillator.NOISE}); var filter = new Filter({type: Filter.HIGH_PASS, frequency: 10000}); var envelope = new Envelope(); var buildTrack = function(){ this.play(envelope.process(filter.process(oscillator))); } ### # Biquad filter # Created by PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> on 2010-05-23. # Copyright 2010 PI:NAME:<NAME>END_PI. All rights reserved. # Translated to CoffeeScript by Ed McManus # # Implementation based on: # http://www.musicdsp.org/files/Audio-EQ-Cookbook.txt class Filter # Biquad filter types @LOW_PASS = 0 # H(s) = 1 / (s^2 + s/Q + 1) @HIGH_PASS = 1 # H(s) = s^2 / (s^2 + s/Q + 1) @BAND_PASS_CONSTANT_SKIRT = 2 # H(s) = s / (s^2 + s/Q + 1) (constant skirt gain, peak gain = Q) @BAND_PASS_CONSTANT_PEAK = 3 # H(s) = (s/Q) / (s^2 + s/Q + 1) (constant 0 dB peak gain) @NOTCH = 4 # H(s) = (s^2 + 1) / (s^2 + s/Q + 1) @ALL_PASS = 5 # H(s) = (s^2 - s/Q + 1) / (s^2 + s/Q + 1) @PEAKING_EQ = 6 # H(s) = (s^2 + s*(A/Q) + 1) / (s^2 + s/(A*Q) + 1) @LOW_SHELF = 7 # H(s) = A * (s^2 + (sqrt(A)/Q)*s + A)/(A*s^2 + (sqrt(A)/Q)*s + 1) @HIGH_SHELF = 8 # H(s) = A * (A*s^2 + (sqrt(A)/Q)*s + 1)/(s^2 + (sqrt(A)/Q)*s + A) # Biquad filter parameter types @Q = 1 @BW = 2 # SHARED with BACKWARDS LOOP MODE @S = 3 constructor: (options={}) -> @Fs = SAMPLE_RATE @type = options.type || Filter.LOW_PASS # type of the filter @parameterType = Filter.Q # type of the parameter @x_1_l = 0 @x_2_l = 0 @y_1_l = 0 @y_2_l = 0 @x_1_r = 0 @x_2_r = 0 @y_1_r = 0 @y_2_r = 0 @b0 = 1 @a0 = 1 @b1 = 0 @a1 = 0 @b2 = 0 @a2 = 0 @b0a0 = @b0 / @a0 @b1a0 = @b1 / @a0 @b2a0 = @b2 / @a0 @a1a0 = @a1 / @a0 @a2a0 = @a2 / @a0 @f0 = options.frequency || 300 # "wherever it's happenin', man." Center Frequency or # Corner Frequency, or shelf midpoint frequency, depending # on which filter type. The "significant frequency". @dBgain = 12 # used only for peaking and shelving filters @Q = 1 # the EE kind of definition, except for peakingEQ in which A*Q is # the classic EE Q. That adjustment in definition was made so that # a boost of N dB followed by a cut of N dB for identical Q and # f0/Fs results in a precisely flat unity gain filter or "wire". @BW = -3 # the bandwidth in octaves (between -3 dB frequencies for BPF # and notch or between midpoint (dBgain/2) gain frequencies for # peaking EQ @S = 1 # a "shelf slope" parameter (for shelving EQ only). When S = 1, # the shelf slope is as steep as it can be and remain monotonically # increasing or decreasing gain with frequency. The shelf slope, in # dB/octave, remains proportional to S for all other values for a # fixed f0/Fs and dBgain. # Since we now accept frequency as an option @recalculateCoefficients() ### setFrequency() Alias for setF0(). Sometimes referred to as the center frequency, midpoint frequency, or cutoff frequency, depending on filter type. Arguments Number value representing center frequency in Hz. Default 300. ### setFrequency: (freq) -> @setF0(freq) freq getFrequency: -> @f0 ### setQ() "Q factor" Arguments Number value representing the filter's Q factor. Only used in some filter types. To see the impact Q has on the filter's frequency response, use the calculator at: http://www.earlevel.com/main/2013/10/13/biquad-calculator-v2/ ### getQ: -> @Q setQ: (q) -> @parameterType = Filter.Q @Q = Math.max(Math.min(q, 115.0), 0.001) @recalculateCoefficients() q # # Advanced filter parameters coefficients: -> b = [@b0, @b1, @b2] a = [@a0, @a1, @a2] {b: b, a: a} setFilterType: (type) -> @type = type @recalculateCoefficients() ### setBW() Set band width value used in "band" filter types. Arguments Number value representing the filter's band width. Ignored unless filter type is set to band pass. ### setBW: (bw) -> @parameterType = Filter.BW @BW = bw @recalculateCoefficients() bw setS: (s) -> @parameterType = Filter.S @S = Math.max(Math.min(s, 5.0), 0.0001) @recalculateCoefficients() ### setF0() Sometimes referred to as the center frequency, midpoint frequency, or cutoff frequency, depending on filter type. Arguments Number value representing center frequency in Hz. Default 300. ### setF0: (freq) -> @f0 = freq @recalculateCoefficients() setDbGain: (g) -> @dBgain = g @recalculateCoefficients() recalculateCoefficients: -> if @type == Filter.PEAKING_EQ || @type == Filter.LOW_SHELF || @type == Filter.HIGH_SHELF A = Math.pow(10, (@dBgain/40)) # for peaking and shelving EQ filters only else A = Math.sqrt( Math.pow(10, (@dBgain/20)) ) w0 = 2 * Math.PI * @f0 / @Fs cosw0 = Math.cos(w0) sinw0 = Math.sin(w0) alpha = 0 switch @parameterType when Filter.Q alpha = sinw0/(2*@Q) when Filter.BW alpha = sinw0 * sinh( Math.LN2/2 * @BW * w0/sinw0 ) when Filter.S alpha = sinw0/2 * Math.sqrt( (A + 1/A)*(1/@S - 1) + 2 ) # # FYI: The relationship between bandwidth and Q is # 1/Q = 2*sinh(ln(2)/2*BW*w0/sin(w0)) (digital filter w BLT) # or 1/Q = 2*sinh(ln(2)/2*BW) (analog filter prototype) # # The relationship between shelf slope and Q is # 1/Q = sqrt((A + 1/A)*(1/S - 1) + 2) # switch @type when Filter.LOW_PASS # H(s) = 1 / (s^2 + s/Q + 1) @b0 = (1 - cosw0)/2 @b1 = 1 - cosw0 @b2 = (1 - cosw0)/2 @a0 = 1 + alpha @a1 = -2 * cosw0 @a2 = 1 - alpha when Filter.HIGH_PASS # H(s) = s^2 / (s^2 + s/Q + 1) @b0 = (1 + cosw0)/2 @b1 = -(1 + cosw0) @b2 = (1 + cosw0)/2 @a0 = 1 + alpha @a1 = -2 * cosw0 @a2 = 1 - alpha when Filter.BAND_PASS_CONSTANT_SKIRT # H(s) = s / (s^2 + s/Q + 1) (constant skirt gain, peak gain = Q) @b0 = sinw0/2 @b1 = 0 @b2 = -sinw0/2 @a0 = 1 + alpha @a1 = -2*cosw0 @a2 = 1 - alpha when Filter.BAND_PASS_CONSTANT_PEAK # H(s) = (s/Q) / (s^2 + s/Q + 1) (constant 0 dB peak gain) @b0 = alpha @b1 = 0 @b2 = -alpha @a0 = 1 + alpha @a1 = -2*cosw0 @a2 = 1 - alpha when Filter.NOTCH # H(s) = (s^2 + 1) / (s^2 + s/Q + 1) @b0 = 1 @b1 = -2*cosw0 @b2 = 1 @a0 = 1 + alpha @a1 = -2*cosw0 @a2 = 1 - alpha when Filter.ALL_PASS # H(s) = (s^2 - s/Q + 1) / (s^2 + s/Q + 1) @b0 = 1 - alpha @b1 = -2*cosw0 @b2 = 1 + alpha @a0 = 1 + alpha @a1 = -2*cosw0 @a2 = 1 - alpha when Filter.PEAKING_EQ # H(s) = (s^2 + s*(A/Q) + 1) / (s^2 + s/(A*Q) + 1) @b0 = 1 + alpha*A @b1 = -2*cosw0 @b2 = 1 - alpha*A @a0 = 1 + alpha/A @a1 = -2*cosw0 @a2 = 1 - alpha/A when Filter.LOW_SHELF # H(s) = A * (s^2 + (sqrt(A)/Q)*s + A)/(A*s^2 + (sqrt(A)/Q)*s + 1) coeff = sinw0 * Math.sqrt( (A^2 + 1)*(1/@S - 1) + 2*A ) @b0 = A*((A+1) - (A-1)*cosw0 + coeff) @b1 = 2*A*((A-1) - (A+1)*cosw0) @b2 = A*((A+1) - (A-1)*cosw0 - coeff) @a0 = (A+1) + (A-1)*cosw0 + coeff @a1 = -2*((A-1) + (A+1)*cosw0) @a2 = (A+1) + (A-1)*cosw0 - coeff when Filter.HIGH_SHELF # H(s) = A * (A*s^2 + (sqrt(A)/Q)*s + 1)/(s^2 + (sqrt(A)/Q)*s + A) coeff = sinw0 * Math.sqrt( (A^2 + 1)*(1/@S - 1) + 2*A ) @b0 = A*((A+1) + (A-1)*cosw0 + coeff) @b1 = -2*A*((A-1) + (A+1)*cosw0) @b2 = A*((A+1) + (A-1)*cosw0 - coeff) @a0 = (A+1) - (A-1)*cosw0 + coeff @a1 = 2*((A-1) - (A+1)*cosw0) @a2 = (A+1) - (A-1)*cosw0 - coeff @b0a0 = @b0/@a0 @b1a0 = @b1/@a0 @b2a0 = @b2/@a0 @a1a0 = @a1/@a0 @a2a0 = @a2/@a0 ### process() --------- Arguments A single instance of Oscillator or the returned value from another process() call (such as Mixer). Returns An object that can be passed into play(), used in buildSample(), or passed into another object's process() method. More precisely, process() returns a closure in the format of `(time) -> sample`. Usage 1 var someOscillator = new Oscillator({type: Oscillator.SAWTOOTH}); var filter = new Filter; var processor = filter.process(someOscillator); var buildSample = function(time) { return processor(time); } Usage 2 var someOscillator1 = new Oscillator({type: Oscillator.SQUARE}); var someOscillator2 = new Oscillator; var filter = new Fiter; var processor = filter.process(envelope.process(mixer.process(someOscillator1, someOscillator2))); var buildSample = function(time) { return processor(time); } ### process: (child) -> unless Function.isFunction(child) throw new Error "#{@constructor.name}.process() requires a sound generator but did not receive any." f = (time) => @realProcess(time, child(time)) f.duration = child.duration if child.duration f realProcess: (time, inputSample) -> #y[n] = (b0/a0)*x[n] + (b1/a0)*x[n-1] + (b2/a0)*x[n-2] # - (a1/a0)*y[n-1] - (a2/a0)*y[n-2] sample = inputSample output = @b0a0*sample + @b1a0*@x_1_l + @b2a0*@x_2_l - @a1a0*@y_1_l - @a2a0*@y_2_l @y_2_l = @y_1_l @y_1_l = output @x_2_l = @x_1_l @x_1_l = sample output
[ { "context": "}\n\t\tauth:\n\t\t\tuser: settings.apis.web.user\n\t\t\tpass: settings.apis.web.pass\n\t\t\tsendImmediately: true\n\t\tjson: tru", "end": 344, "score": 0.7573214769363403, "start": 336, "tag": "PASSWORD", "value": "settings" }, { "context": "ser: settings.apis.web.user\...
test/acceptance/coffee/ProjectFeaturesTests.coffee
davidmehren/web-sharelatex
1
expect = require("chai").expect async = require("async") User = require "./helpers/User" request = require "./helpers/request" settings = require "settings-sharelatex" joinProject = (user_id, project_id, callback) -> request.post { url: "/project/#{project_id}/join" qs: {user_id} auth: user: settings.apis.web.user pass: settings.apis.web.pass sendImmediately: true json: true jar: false }, callback describe "ProjectFeatures", -> before (done) -> @timeout(90000) @owner = new User() async.series [ (cb) => @owner.login cb ], done describe "with private project", -> before (done) -> @owner.createProject "private-project", (error, project_id) => return done(error) if error? @project_id = project_id done() describe "with an upgraded account", -> before (done) -> @owner.upgradeFeatures done after (done) -> @owner.defaultFeatures done it "should have premium features", (done) -> joinProject @owner._id, @project_id, (error, response, body) -> expect(body.project.features.compileGroup).to.equal "priority" expect(body.project.features.versioning).to.equal true expect(body.project.features.templates).to.equal true expect(body.project.features.dropbox).to.equal true done() describe "with an basic account", -> before (done) -> @owner.downgradeFeatures done after (done) -> @owner.defaultFeatures done it "should have basic features", (done) -> joinProject @owner._id, @project_id, (error, response, body) -> expect(body.project.features.compileGroup).to.equal "standard" expect(body.project.features.versioning).to.equal false expect(body.project.features.templates).to.equal false expect(body.project.features.dropbox).to.equal false done()
99141
expect = require("chai").expect async = require("async") User = require "./helpers/User" request = require "./helpers/request" settings = require "settings-sharelatex" joinProject = (user_id, project_id, callback) -> request.post { url: "/project/#{project_id}/join" qs: {user_id} auth: user: settings.apis.web.user pass: <PASSWORD>.apis.<PASSWORD> sendImmediately: true json: true jar: false }, callback describe "ProjectFeatures", -> before (done) -> @timeout(90000) @owner = new User() async.series [ (cb) => @owner.login cb ], done describe "with private project", -> before (done) -> @owner.createProject "private-project", (error, project_id) => return done(error) if error? @project_id = project_id done() describe "with an upgraded account", -> before (done) -> @owner.upgradeFeatures done after (done) -> @owner.defaultFeatures done it "should have premium features", (done) -> joinProject @owner._id, @project_id, (error, response, body) -> expect(body.project.features.compileGroup).to.equal "priority" expect(body.project.features.versioning).to.equal true expect(body.project.features.templates).to.equal true expect(body.project.features.dropbox).to.equal true done() describe "with an basic account", -> before (done) -> @owner.downgradeFeatures done after (done) -> @owner.defaultFeatures done it "should have basic features", (done) -> joinProject @owner._id, @project_id, (error, response, body) -> expect(body.project.features.compileGroup).to.equal "standard" expect(body.project.features.versioning).to.equal false expect(body.project.features.templates).to.equal false expect(body.project.features.dropbox).to.equal false done()
true
expect = require("chai").expect async = require("async") User = require "./helpers/User" request = require "./helpers/request" settings = require "settings-sharelatex" joinProject = (user_id, project_id, callback) -> request.post { url: "/project/#{project_id}/join" qs: {user_id} auth: user: settings.apis.web.user pass: PI:PASSWORD:<PASSWORD>END_PI.apis.PI:PASSWORD:<PASSWORD>END_PI sendImmediately: true json: true jar: false }, callback describe "ProjectFeatures", -> before (done) -> @timeout(90000) @owner = new User() async.series [ (cb) => @owner.login cb ], done describe "with private project", -> before (done) -> @owner.createProject "private-project", (error, project_id) => return done(error) if error? @project_id = project_id done() describe "with an upgraded account", -> before (done) -> @owner.upgradeFeatures done after (done) -> @owner.defaultFeatures done it "should have premium features", (done) -> joinProject @owner._id, @project_id, (error, response, body) -> expect(body.project.features.compileGroup).to.equal "priority" expect(body.project.features.versioning).to.equal true expect(body.project.features.templates).to.equal true expect(body.project.features.dropbox).to.equal true done() describe "with an basic account", -> before (done) -> @owner.downgradeFeatures done after (done) -> @owner.defaultFeatures done it "should have basic features", (done) -> joinProject @owner._id, @project_id, (error, response, body) -> expect(body.project.features.compileGroup).to.equal "standard" expect(body.project.features.versioning).to.equal false expect(body.project.features.templates).to.equal false expect(body.project.features.dropbox).to.equal false done()
[ { "context": "Content\", \"Hello\")\r\n expression.set(\"Name\", \"World\")\r\n expression.save().done(done)\r\n\r\n it \"", "end": 2414, "score": 0.9823885560035706, "start": 2409, "tag": "NAME", "value": "World" }, { "context": "end(expression,{attrs:{\"Content\":\"Hel...
tests/Backbone.sync.create.coffee
versionone/V1.Backbone
1
V1 = require('../V1.Backbone') expect = require('chai').expect recorded = require('./recorded') deferred = require('JQDeferred') alias = V1.Backbone.alias relation = V1.Backbone.relation describe "Creating with `sync`", -> createPersister = (post) -> new V1.Backbone.RestPersister({url: "/VersionOne/rest-1.v1/Data", post}) describe "the url", -> expectedUrl = (expectedUrl) -> (url, data) -> expect(url).to.equal(expectedUrl) deferred().resolve() it "should be generated correctly", -> persister = createPersister expectedUrl "/VersionOne/rest-1.v1/Data/Expression" Expression = V1.Backbone.Model.extend queryOptions: assetType: "Expression" persister: persister expression = new Expression() expression.save() describe "the generated XML", -> expectedPost = (expectedData) -> (url, data) -> expect(data).to.equal(expectedData) deferred().resolve() it "can set simple attributes", (done) -> persister = createPersister expectedPost "<Asset><Attribute name=\"Content\" act=\"set\">Hello</Attribute></Asset>" Expression = V1.Backbone.Model.extend queryOptions: persister: persister schema: ["Content"] expression = new Expression() expression.set("Content", "Hello") expression.save().done(done) it "can set complex attributes", (done) -> persister = createPersister expectedPost '<Asset><Attribute name="Content" act="set">Hello</Attribute><Attribute name="Name" act="set">World</Attribute></Asset>' Expression = V1.Backbone.Model.extend queryOptions: persister: persister schema: ["Content", "Name"] expression = new Expression() expression.set({"Content":"Hello", "Name":"World"}) expression.save().done(done) it "can set multiple attributes", (done) -> persister = createPersister expectedPost '<Asset><Attribute name="Content" act="set">Hello</Attribute><Attribute name="Name" act="set">World</Attribute></Asset>' Expression = V1.Backbone.Model.extend queryOptions: persister: persister schema: ["Content", "Name"] expression = new Expression() expression.set("Content", "Hello") expression.set("Name", "World") expression.save().done(done) it "can handle attributes passed in as options", (done) -> persister = createPersister expectedPost '<Asset><Attribute name="Content" act="set">Hello</Attribute><Attribute name="Name" act="set">World</Attribute></Asset>' Expression = V1.Backbone.Model.extend queryOptions: persister: persister schema: ["Content", "Name"] expression = new Expression() persister.send(expression,{attrs:{"Content":"Hello", "Name":"World"}}).done(done) it "can handle aliases of attributes", (done) -> persister = createPersister expectedPost "<Asset><Attribute name=\"Content\" act=\"set\">Hello</Attribute></Asset>" Expression = V1.Backbone.Model.extend queryOptions: persister: persister schema: [ alias("Content").as("words") ] expression = new Expression() expression.set("words", "Hello") expression.save().done(done) it "can handle single-value relations", (done) -> persister = createPersister expectedPost "<Asset><Attribute name=\"Content\" act=\"set\"></Attribute><Relation name=\"Author\" act=\"set\"><Asset idref=\"Member:20\" /></Relation></Asset>" Member = V1.Backbone.Model.extend() Expression = V1.Backbone.Model.extend queryOptions: persister: persister schema: [ alias("Content").as("words") relation("Author").of(Member) ] expression = new Expression() expression.set("Author", new Member(_oid:"Member:20")) expression.save().done(done) describe "setting the ID", -> it "should get the right url", (done) -> persister = createPersister recorded Expression = V1.Backbone.Model.extend queryOptions: assetType: "Expression" persister: persister expression = new Expression() expression.save().done -> expect(expression.id).to.equal("Expression:1114") done()
27715
V1 = require('../V1.Backbone') expect = require('chai').expect recorded = require('./recorded') deferred = require('JQDeferred') alias = V1.Backbone.alias relation = V1.Backbone.relation describe "Creating with `sync`", -> createPersister = (post) -> new V1.Backbone.RestPersister({url: "/VersionOne/rest-1.v1/Data", post}) describe "the url", -> expectedUrl = (expectedUrl) -> (url, data) -> expect(url).to.equal(expectedUrl) deferred().resolve() it "should be generated correctly", -> persister = createPersister expectedUrl "/VersionOne/rest-1.v1/Data/Expression" Expression = V1.Backbone.Model.extend queryOptions: assetType: "Expression" persister: persister expression = new Expression() expression.save() describe "the generated XML", -> expectedPost = (expectedData) -> (url, data) -> expect(data).to.equal(expectedData) deferred().resolve() it "can set simple attributes", (done) -> persister = createPersister expectedPost "<Asset><Attribute name=\"Content\" act=\"set\">Hello</Attribute></Asset>" Expression = V1.Backbone.Model.extend queryOptions: persister: persister schema: ["Content"] expression = new Expression() expression.set("Content", "Hello") expression.save().done(done) it "can set complex attributes", (done) -> persister = createPersister expectedPost '<Asset><Attribute name="Content" act="set">Hello</Attribute><Attribute name="Name" act="set">World</Attribute></Asset>' Expression = V1.Backbone.Model.extend queryOptions: persister: persister schema: ["Content", "Name"] expression = new Expression() expression.set({"Content":"Hello", "Name":"World"}) expression.save().done(done) it "can set multiple attributes", (done) -> persister = createPersister expectedPost '<Asset><Attribute name="Content" act="set">Hello</Attribute><Attribute name="Name" act="set">World</Attribute></Asset>' Expression = V1.Backbone.Model.extend queryOptions: persister: persister schema: ["Content", "Name"] expression = new Expression() expression.set("Content", "Hello") expression.set("Name", "<NAME>") expression.save().done(done) it "can handle attributes passed in as options", (done) -> persister = createPersister expectedPost '<Asset><Attribute name="Content" act="set">Hello</Attribute><Attribute name="Name" act="set">World</Attribute></Asset>' Expression = V1.Backbone.Model.extend queryOptions: persister: persister schema: ["Content", "Name"] expression = new Expression() persister.send(expression,{attrs:{"Content":"Hello", "Name":"<NAME>"}}).done(done) it "can handle aliases of attributes", (done) -> persister = createPersister expectedPost "<Asset><Attribute name=\"Content\" act=\"set\">Hello</Attribute></Asset>" Expression = V1.Backbone.Model.extend queryOptions: persister: persister schema: [ alias("Content").as("words") ] expression = new Expression() expression.set("words", "Hello") expression.save().done(done) it "can handle single-value relations", (done) -> persister = createPersister expectedPost "<Asset><Attribute name=\"Content\" act=\"set\"></Attribute><Relation name=\"Author\" act=\"set\"><Asset idref=\"Member:20\" /></Relation></Asset>" Member = V1.Backbone.Model.extend() Expression = V1.Backbone.Model.extend queryOptions: persister: persister schema: [ alias("Content").as("words") relation("Author").of(Member) ] expression = new Expression() expression.set("Author", new Member(_oid:"Member:20")) expression.save().done(done) describe "setting the ID", -> it "should get the right url", (done) -> persister = createPersister recorded Expression = V1.Backbone.Model.extend queryOptions: assetType: "Expression" persister: persister expression = new Expression() expression.save().done -> expect(expression.id).to.equal("Expression:1114") done()
true
V1 = require('../V1.Backbone') expect = require('chai').expect recorded = require('./recorded') deferred = require('JQDeferred') alias = V1.Backbone.alias relation = V1.Backbone.relation describe "Creating with `sync`", -> createPersister = (post) -> new V1.Backbone.RestPersister({url: "/VersionOne/rest-1.v1/Data", post}) describe "the url", -> expectedUrl = (expectedUrl) -> (url, data) -> expect(url).to.equal(expectedUrl) deferred().resolve() it "should be generated correctly", -> persister = createPersister expectedUrl "/VersionOne/rest-1.v1/Data/Expression" Expression = V1.Backbone.Model.extend queryOptions: assetType: "Expression" persister: persister expression = new Expression() expression.save() describe "the generated XML", -> expectedPost = (expectedData) -> (url, data) -> expect(data).to.equal(expectedData) deferred().resolve() it "can set simple attributes", (done) -> persister = createPersister expectedPost "<Asset><Attribute name=\"Content\" act=\"set\">Hello</Attribute></Asset>" Expression = V1.Backbone.Model.extend queryOptions: persister: persister schema: ["Content"] expression = new Expression() expression.set("Content", "Hello") expression.save().done(done) it "can set complex attributes", (done) -> persister = createPersister expectedPost '<Asset><Attribute name="Content" act="set">Hello</Attribute><Attribute name="Name" act="set">World</Attribute></Asset>' Expression = V1.Backbone.Model.extend queryOptions: persister: persister schema: ["Content", "Name"] expression = new Expression() expression.set({"Content":"Hello", "Name":"World"}) expression.save().done(done) it "can set multiple attributes", (done) -> persister = createPersister expectedPost '<Asset><Attribute name="Content" act="set">Hello</Attribute><Attribute name="Name" act="set">World</Attribute></Asset>' Expression = V1.Backbone.Model.extend queryOptions: persister: persister schema: ["Content", "Name"] expression = new Expression() expression.set("Content", "Hello") expression.set("Name", "PI:NAME:<NAME>END_PI") expression.save().done(done) it "can handle attributes passed in as options", (done) -> persister = createPersister expectedPost '<Asset><Attribute name="Content" act="set">Hello</Attribute><Attribute name="Name" act="set">World</Attribute></Asset>' Expression = V1.Backbone.Model.extend queryOptions: persister: persister schema: ["Content", "Name"] expression = new Expression() persister.send(expression,{attrs:{"Content":"Hello", "Name":"PI:NAME:<NAME>END_PI"}}).done(done) it "can handle aliases of attributes", (done) -> persister = createPersister expectedPost "<Asset><Attribute name=\"Content\" act=\"set\">Hello</Attribute></Asset>" Expression = V1.Backbone.Model.extend queryOptions: persister: persister schema: [ alias("Content").as("words") ] expression = new Expression() expression.set("words", "Hello") expression.save().done(done) it "can handle single-value relations", (done) -> persister = createPersister expectedPost "<Asset><Attribute name=\"Content\" act=\"set\"></Attribute><Relation name=\"Author\" act=\"set\"><Asset idref=\"Member:20\" /></Relation></Asset>" Member = V1.Backbone.Model.extend() Expression = V1.Backbone.Model.extend queryOptions: persister: persister schema: [ alias("Content").as("words") relation("Author").of(Member) ] expression = new Expression() expression.set("Author", new Member(_oid:"Member:20")) expression.save().done(done) describe "setting the ID", -> it "should get the right url", (done) -> persister = createPersister recorded Expression = V1.Backbone.Model.extend queryOptions: assetType: "Expression" persister: persister expression = new Expression() expression.save().done -> expect(expression.id).to.equal("Expression:1114") done()
[ { "context": "he background script\"\n\tsendResponse farewell: \"bye felicia\"\n\tif lastComment?\n\t\tif lastComment.mediaType?\n\t\t\t", "end": 1017, "score": 0.9402817487716675, "start": 1010, "tag": "NAME", "value": "felicia" } ]
src/scripts/critic.coffee
ToasterLab/critic
0
criticisms = localStorage.getItem("criticisms") if not criticisms? or criticisms.length is 0 criticisms = [] localStorage.setItem "criticisms", JSON.stringify(criticisms) else criticisms = JSON.parse(criticisms) renderCriticism = (c) -> # console.log c.selection.text, c.selection.start, c.selection.text.length, c.selection.end # static length is 47 span = "<span class='critic-highlight' title='"+c.comment+"'>" + c.selection.text + "</span>" text = c.element.innerHTML start = text.substring 0, c.selection.start end = text.substring c.selection.end, text.length c.element.innerHTML = start + span + end # render all previous criticisms for c in criticisms c.element = $(c.tag + c.class)[c.index] renderCriticism c chrome.runtime.onMessage.addListener (request, sender, sendResponse) -> # console.log request.greeting lastComment = request.greeting # console.log if sender.tab then "from a content script: " + sender.tab.url else "from the background script" sendResponse farewell: "bye felicia" if lastComment? if lastComment.mediaType? console.log "media" else #it's text c = "element" : window.lastClicked "selection" : "text" : window.selection.toString() "start" : window.selection.getRangeAt(0).startOffset "end" : window.selection.getRangeAt(0).endOffset "comment" : lastComment.comment "tag" : window.lastClicked.tagName "class" : if (not window.lastClicked.className? or window.lastClicked.className is "") then "" else window.lastClicked.className for el, i in $(c.tag + c.class) if el is window.lastClicked c.index = i console.log c, window.selection.getRangeAt(0) for cur in criticisms # number of elements in same block preceding this one console.log "c start is " + c.selection.start console.log "cur start is " + cur.selection.start if cur.index is c.index and c.selection.start > cur.selection.start console.log "uh oh" # loop through criticisms and add padding to start and end c.selection.start = c.selection.start + (47+c.comment.length) c.selection.end = c.selection.end + (47+c.comment.length) console.log c renderCriticism(c) delete c.element # because it's difficult to stringify criticisms.push c criticisms = _.sortBy criticisms, ["index", "start"] # console.log criticisms localStorage.setItem "criticisms", JSON.stringify criticisms $('body').on "contextmenu", (e) -> e.stopPropagation() window.selection = window.getSelection() window.lastClicked = e.path[0]
104376
criticisms = localStorage.getItem("criticisms") if not criticisms? or criticisms.length is 0 criticisms = [] localStorage.setItem "criticisms", JSON.stringify(criticisms) else criticisms = JSON.parse(criticisms) renderCriticism = (c) -> # console.log c.selection.text, c.selection.start, c.selection.text.length, c.selection.end # static length is 47 span = "<span class='critic-highlight' title='"+c.comment+"'>" + c.selection.text + "</span>" text = c.element.innerHTML start = text.substring 0, c.selection.start end = text.substring c.selection.end, text.length c.element.innerHTML = start + span + end # render all previous criticisms for c in criticisms c.element = $(c.tag + c.class)[c.index] renderCriticism c chrome.runtime.onMessage.addListener (request, sender, sendResponse) -> # console.log request.greeting lastComment = request.greeting # console.log if sender.tab then "from a content script: " + sender.tab.url else "from the background script" sendResponse farewell: "bye <NAME>" if lastComment? if lastComment.mediaType? console.log "media" else #it's text c = "element" : window.lastClicked "selection" : "text" : window.selection.toString() "start" : window.selection.getRangeAt(0).startOffset "end" : window.selection.getRangeAt(0).endOffset "comment" : lastComment.comment "tag" : window.lastClicked.tagName "class" : if (not window.lastClicked.className? or window.lastClicked.className is "") then "" else window.lastClicked.className for el, i in $(c.tag + c.class) if el is window.lastClicked c.index = i console.log c, window.selection.getRangeAt(0) for cur in criticisms # number of elements in same block preceding this one console.log "c start is " + c.selection.start console.log "cur start is " + cur.selection.start if cur.index is c.index and c.selection.start > cur.selection.start console.log "uh oh" # loop through criticisms and add padding to start and end c.selection.start = c.selection.start + (47+c.comment.length) c.selection.end = c.selection.end + (47+c.comment.length) console.log c renderCriticism(c) delete c.element # because it's difficult to stringify criticisms.push c criticisms = _.sortBy criticisms, ["index", "start"] # console.log criticisms localStorage.setItem "criticisms", JSON.stringify criticisms $('body').on "contextmenu", (e) -> e.stopPropagation() window.selection = window.getSelection() window.lastClicked = e.path[0]
true
criticisms = localStorage.getItem("criticisms") if not criticisms? or criticisms.length is 0 criticisms = [] localStorage.setItem "criticisms", JSON.stringify(criticisms) else criticisms = JSON.parse(criticisms) renderCriticism = (c) -> # console.log c.selection.text, c.selection.start, c.selection.text.length, c.selection.end # static length is 47 span = "<span class='critic-highlight' title='"+c.comment+"'>" + c.selection.text + "</span>" text = c.element.innerHTML start = text.substring 0, c.selection.start end = text.substring c.selection.end, text.length c.element.innerHTML = start + span + end # render all previous criticisms for c in criticisms c.element = $(c.tag + c.class)[c.index] renderCriticism c chrome.runtime.onMessage.addListener (request, sender, sendResponse) -> # console.log request.greeting lastComment = request.greeting # console.log if sender.tab then "from a content script: " + sender.tab.url else "from the background script" sendResponse farewell: "bye PI:NAME:<NAME>END_PI" if lastComment? if lastComment.mediaType? console.log "media" else #it's text c = "element" : window.lastClicked "selection" : "text" : window.selection.toString() "start" : window.selection.getRangeAt(0).startOffset "end" : window.selection.getRangeAt(0).endOffset "comment" : lastComment.comment "tag" : window.lastClicked.tagName "class" : if (not window.lastClicked.className? or window.lastClicked.className is "") then "" else window.lastClicked.className for el, i in $(c.tag + c.class) if el is window.lastClicked c.index = i console.log c, window.selection.getRangeAt(0) for cur in criticisms # number of elements in same block preceding this one console.log "c start is " + c.selection.start console.log "cur start is " + cur.selection.start if cur.index is c.index and c.selection.start > cur.selection.start console.log "uh oh" # loop through criticisms and add padding to start and end c.selection.start = c.selection.start + (47+c.comment.length) c.selection.end = c.selection.end + (47+c.comment.length) console.log c renderCriticism(c) delete c.element # because it's difficult to stringify criticisms.push c criticisms = _.sortBy criticisms, ["index", "start"] # console.log criticisms localStorage.setItem "criticisms", JSON.stringify criticisms $('body').on "contextmenu", (e) -> e.stopPropagation() window.selection = window.getSelection() window.lastClicked = e.path[0]
[ { "context": "kup database.\n object = undefined\n key = @lookupKey(els)\n if key is null\n object = creato", "end": 25670, "score": 0.6696035861968994, "start": 25660, "tag": "KEY", "value": "@lookupKey" }, { "context": " object = creatorCallback(els)\n ...
src/app/core/projects/csg/utils.coffee
kaosat-dev/CoffeeSCad
110
define (require)-> globals = require './globals' maths = require './maths' Vector2D = maths.Vector2D Vector3D = maths.Vector3D Vertex = maths.Vertex Line2D = maths.Line2D OrthoNormalBasis = maths.OrthoNormalBasis Polygon = maths.Polygon Side = maths.Side merge = (options, overrides) -> extend (extend {}, options), overrides extend = (object, properties) -> for key, val of properties object[key] = val object parseOptions = (options, defaults)-> if Object.getPrototypeOf( options ) == Object.prototype options = merge defaults, options else if options instanceof Array indexToName = {} result = {} index =0 for own key,val of defaults indexToName[index]=key result[key]=val index++ for option, index in options if option? name = indexToName[index] result[name]=option options = result return options parseOption = (options, optionname, defaultvalue) -> # Parse an option from the options object # If the option is not present, return the default value result = defaultvalue result = options[optionname] if optionname of options if options result parseOptionAs3DVector = (options, optionname, defaultValue, defaultValue2) -> # Parse an option and force into a Vector3D. If a scalar is passed it is converted # into a vector with equal x,y,z, if a boolean is passed and is true, take defaultvalue, otherwise defaultvalue2 if optionname of options if options[optionname] == false or options[optionname] == true doCenter = parseOptionAsBool(options,optionname,false) if doCenter options[optionname]=defaultValue else options[optionname]=defaultValue2 result = parseOption(options, optionname, defaultValue) result = new Vector3D(result) result parseOptionAs2DVector = (options, optionname, defaultValue, defaultValue2) -> # Parse an option and force into a Vector2D. If a scalar is passed it is converted # into a vector with equal x,y, if a boolean is passed and is true, take defaultvalue, otherwise defaultvalue2 if optionname of options if options[optionname] == false or options[optionname] == true doCenter = parseOptionAsBool(options,optionname,false) if doCenter options[optionname]=defaultValue else options[optionname]=defaultValue2 result = parseOption(options, optionname, defaultValue) result = new Vector2D(result) result parseOptionAsFloat = (options, optionname, defaultvalue) -> result = parseOption(options, optionname, defaultvalue) if typeof (result) is "string" result = Number(result) else throw new Error("Parameter " + optionname + " should be a number") unless typeof (result) is "number" result parseOptionAsInt = (options, optionname, defaultvalue) -> result = parseOption(options, optionname, defaultvalue) Number Math.floor(result) parseOptionAsBool = (options, optionname, defaultvalue) -> result = parseOption(options, optionname, defaultvalue) if typeof (result) is "string" result = true if result is "true" result = false if result is "false" result = false if result is 0 result = !!result result parseOptionAsLocations = (options, optionName, defaultValue) -> result = parseOption(options, optionName, defaultValue) #left, right, top, bottom, front back when used alone, overide all others #front left front right , top left etc (dual params) override ternary params #so by params size : 1>2>3 mapping_old = { "top":globals.top, "bottom":globals.bottom, "left":globals.left, "right":globals.right, "front":globals.front, "back":globals.back, } mapping = { "all":(parseInt("111111",2)), "top": (parseInt("101111",2)), "bottom":parseInt("011111",2), "left":parseInt("111011",2), "right":parseInt("110111",2), "front":parseInt("111110",2), "back":parseInt("111101",2) } stuff = null for location in result #trim leading and trailing whitespaces location = location.replace /^\s+|\s+$/g, "" locations =location.split(" ") #console.log "location" #console.log location subStuff = null for loc in locations loc = mapping[loc] if not subStuff? subStuff = loc else subStuff = subStuff & loc if not stuff? stuff = subStuff else stuff = stuff | subStuff stuff.toString(2) parseCenter = (options, optionname, defaultValue, defaultValue2, vectorClass) -> # Parse a "center" option and force into a Vector3D. If a scalar is passed it is converted # into a vector with equal x,y,z, if a boolean is passed and is true, take defaultvalue, otherwise defaultvalue2 if optionname of options centerOption = options[optionname] if centerOption instanceof Array newDefaultValue = new vectorClass(defaultValue) newDefaultValue2 = new vectorClass(defaultValue2) for component, index in centerOption if typeof component is 'boolean' if index is 0 centerOption[index] = if component == true then newDefaultValue2.x else if component == false then newDefaultValue.x else centerOption[index] else if index is 1 centerOption[index] = if component == true then newDefaultValue2.y else if component == false then newDefaultValue.y else centerOption[index] else if index is 2 centerOption[index] = if component == true then newDefaultValue2.z else if component == false then newDefaultValue.z else centerOption[index] options[optionname] = centerOption else if typeof centerOption is 'boolean' doCenter = parseOptionAsBool(options,optionname,false) if doCenter options[optionname]=defaultValue2 else options[optionname]=defaultValue result = parseOption(options, optionname, defaultValue) result = new vectorClass(result) result insertSorted = (array, element, comparefunc) -> leftbound = 0 rightbound = array.length while rightbound > leftbound testindex = Math.floor((leftbound + rightbound) / 2) testelement = array[testindex] compareresult = comparefunc(element, testelement) if compareresult > 0 # element > testelement leftbound = testindex + 1 else rightbound = testindex array.splice leftbound, 0, element interpolateBetween2DPointsForY = (point1, point2, y) -> # Get the x coordinate of a point with a certain y coordinate, interpolated between two # points (Vector2D). # Interpolation is robust even if the points have the same y coordinate f1 = y - point1.y f2 = point2.y - point1.y if f2 < 0 f1 = -f1 f2 = -f2 t = undefined if f1 <= 0 t = 0.0 else if f1 >= f2 t = 1.0 else if f2 < 1e-10 t = 0.5 else t = f1 / f2 result = point1.x + t * (point2.x - point1.x) result reTesselateCoplanarPolygons = (sourcepolygons, destpolygons) -> # Retesselation function for a set of coplanar polygons. See the introduction at the top of # this file. EPS = 1e-5 numpolygons = sourcepolygons.length if numpolygons > 0 plane = sourcepolygons[0].plane shared = sourcepolygons[0].shared orthobasis = new OrthoNormalBasis(plane) polygonvertices2d = [] # array of array of Vector2D polygontopvertexindexes = [] # array of indexes of topmost vertex per polygon topy2polygonindexes = {} ycoordinatetopolygonindexes = {} xcoordinatebins = {} ycoordinatebins = {} # convert all polygon vertices to 2D # Make a list of all encountered y coordinates # And build a map of all polygons that have a vertex at a certain y coordinate: ycoordinateBinningFactor = 1.0 / EPS * 10 polygonindex = 0 while polygonindex < numpolygons poly3d = sourcepolygons[polygonindex] vertices2d = [] numvertices = poly3d.vertices.length minindex = -1 if numvertices > 0 miny = undefined maxy = undefined maxindex = undefined i = 0 while i < numvertices pos2d = orthobasis.to2D(poly3d.vertices[i].pos) # perform binning of y coordinates: If we have multiple vertices very # close to each other, give them the same y coordinate: ycoordinatebin = Math.floor(pos2d.y * ycoordinateBinningFactor) newy = undefined if ycoordinatebin of ycoordinatebins newy = ycoordinatebins[ycoordinatebin] else if ycoordinatebin + 1 of ycoordinatebins newy = ycoordinatebins[ycoordinatebin + 1] else if ycoordinatebin - 1 of ycoordinatebins newy = ycoordinatebins[ycoordinatebin - 1] else newy = pos2d.y ycoordinatebins[ycoordinatebin] = pos2d.y pos2d = new Vector2D(pos2d.x, newy) vertices2d.push pos2d y = pos2d.y if (i is 0) or (y < miny) miny = y minindex = i if (i is 0) or (y > maxy) maxy = y maxindex = i ycoordinatetopolygonindexes[y] = {} unless y of ycoordinatetopolygonindexes ycoordinatetopolygonindexes[y][polygonindex] = true i++ if miny >= maxy # degenerate polygon, all vertices have same y coordinate. Just ignore it from now: vertices2d = [] else topy2polygonindexes[miny] = [] unless miny of topy2polygonindexes topy2polygonindexes[miny].push polygonindex # if(numvertices > 0) # reverse the vertex order: vertices2d.reverse() minindex = numvertices - minindex - 1 polygonvertices2d.push vertices2d polygontopvertexindexes.push minindex polygonindex++ ycoordinates = [] for ycoordinate of ycoordinatetopolygonindexes ycoordinates.push ycoordinate ycoordinates.sort (a, b) -> a - b # Now we will iterate over all y coordinates, from lowest to highest y coordinate # activepolygons: source polygons that are 'active', i.e. intersect with our y coordinate # Is sorted so the polygons are in left to right order # Each element in activepolygons has these properties: # polygonindex: the index of the source polygon (i.e. an index into the sourcepolygons and polygonvertices2d arrays) # leftvertexindex: the index of the vertex at the left side of the polygon (lowest x) that is at or just above the current y coordinate # rightvertexindex: dito at right hand side of polygon # topleft, bottomleft: coordinates of the left side of the polygon crossing the current y coordinate # topright, bottomright: coordinates of the right hand side of the polygon crossing the current y coordinate activepolygons = [] prevoutpolygonrow = [] yindex = 0 while yindex < ycoordinates.length newoutpolygonrow = [] ycoordinate_as_string = ycoordinates[yindex] ycoordinate = Number(ycoordinate_as_string) # update activepolygons for this y coordinate: # - Remove any polygons that end at this y coordinate # - update leftvertexindex and rightvertexindex (which point to the current vertex index # at the the left and right side of the polygon # Iterate over all polygons that have a corner at this y coordinate: polygonindexeswithcorner = ycoordinatetopolygonindexes[ycoordinate_as_string] activepolygonindex = 0 while activepolygonindex < activepolygons.length activepolygon = activepolygons[activepolygonindex] polygonindex = activepolygon.polygonindex if polygonindexeswithcorner[polygonindex] # this active polygon has a corner at this y coordinate: vertices2d = polygonvertices2d[polygonindex] numvertices = vertices2d.length newleftvertexindex = activepolygon.leftvertexindex newrightvertexindex = activepolygon.rightvertexindex # See if we need to increase leftvertexindex or decrease rightvertexindex: loop nextleftvertexindex = newleftvertexindex + 1 nextleftvertexindex = 0 if nextleftvertexindex >= numvertices break unless vertices2d[nextleftvertexindex].y is ycoordinate newleftvertexindex = nextleftvertexindex nextrightvertexindex = newrightvertexindex - 1 nextrightvertexindex = numvertices - 1 if nextrightvertexindex < 0 newrightvertexindex = nextrightvertexindex if vertices2d[nextrightvertexindex].y is ycoordinate if (newleftvertexindex isnt activepolygon.leftvertexindex) and (newleftvertexindex is newrightvertexindex) # We have increased leftvertexindex or decreased rightvertexindex, and now they point to the same vertex # This means that this is the bottom point of the polygon. We'll remove it: activepolygons.splice activepolygonindex, 1 --activepolygonindex else activepolygon.leftvertexindex = newleftvertexindex activepolygon.rightvertexindex = newrightvertexindex activepolygon.topleft = vertices2d[newleftvertexindex] activepolygon.topright = vertices2d[newrightvertexindex] nextleftvertexindex = newleftvertexindex + 1 nextleftvertexindex = 0 if nextleftvertexindex >= numvertices activepolygon.bottomleft = vertices2d[nextleftvertexindex] nextrightvertexindex = newrightvertexindex - 1 nextrightvertexindex = numvertices - 1 if nextrightvertexindex < 0 activepolygon.bottomright = vertices2d[nextrightvertexindex] ++activepolygonindex # if polygon has corner here # for activepolygonindex nextycoordinate = undefined if yindex >= ycoordinates.length - 1 # last row, all polygons must be finished here: activepolygons = [] nextycoordinate = null # yindex < ycoordinates.length-1 else nextycoordinate = Number(ycoordinates[yindex + 1]) middleycoordinate = 0.5 * (ycoordinate + nextycoordinate) # update activepolygons by adding any polygons that start here: startingpolygonindexes = topy2polygonindexes[ycoordinate_as_string] for polygonindex_key of startingpolygonindexes polygonindex = startingpolygonindexes[polygonindex_key] vertices2d = polygonvertices2d[polygonindex] numvertices = vertices2d.length topvertexindex = polygontopvertexindexes[polygonindex] # the top of the polygon may be a horizontal line. In that case topvertexindex can point to any point on this line. # Find the left and right topmost vertices which have the current y coordinate: topleftvertexindex = topvertexindex loop i = topleftvertexindex + 1 i = 0 if i >= numvertices break unless vertices2d[i].y is ycoordinate break if i is topvertexindex # should not happen, but just to prevent endless loops topleftvertexindex = i toprightvertexindex = topvertexindex loop i = toprightvertexindex - 1 i = numvertices - 1 if i < 0 break unless vertices2d[i].y is ycoordinate break if i is topleftvertexindex # should not happen, but just to prevent endless loops toprightvertexindex = i nextleftvertexindex = topleftvertexindex + 1 nextleftvertexindex = 0 if nextleftvertexindex >= numvertices nextrightvertexindex = toprightvertexindex - 1 nextrightvertexindex = numvertices - 1 if nextrightvertexindex < 0 newactivepolygon = polygonindex: polygonindex leftvertexindex: topleftvertexindex rightvertexindex: toprightvertexindex topleft: vertices2d[topleftvertexindex] topright: vertices2d[toprightvertexindex] bottomleft: vertices2d[nextleftvertexindex] bottomright: vertices2d[nextrightvertexindex] insertSorted activepolygons, newactivepolygon, (el1, el2) -> x1 = interpolateBetween2DPointsForY(el1.topleft, el1.bottomleft, middleycoordinate) x2 = interpolateBetween2DPointsForY(el2.topleft, el2.bottomleft, middleycoordinate) return 1 if x1 > x2 return -1 if x1 < x2 0 # for(var polygonindex in startingpolygonindexes) # yindex < ycoordinates.length-1 #if( (yindex == ycoordinates.length-1) || (nextycoordinate - ycoordinate > EPS) ) if true # Now activepolygons is up to date # Build the output polygons for the next row in newoutpolygonrow: for activepolygon_key of activepolygons activepolygon = activepolygons[activepolygon_key] polygonindex = activepolygon.polygonindex vertices2d = polygonvertices2d[polygonindex] numvertices = vertices2d.length x = interpolateBetween2DPointsForY(activepolygon.topleft, activepolygon.bottomleft, ycoordinate) topleft = new Vector2D(x, ycoordinate) x = interpolateBetween2DPointsForY(activepolygon.topright, activepolygon.bottomright, ycoordinate) topright = new Vector2D(x, ycoordinate) x = interpolateBetween2DPointsForY(activepolygon.topleft, activepolygon.bottomleft, nextycoordinate) bottomleft = new Vector2D(x, nextycoordinate) x = interpolateBetween2DPointsForY(activepolygon.topright, activepolygon.bottomright, nextycoordinate) bottomright = new Vector2D(x, nextycoordinate) outpolygon = topleft: topleft topright: topright bottomleft: bottomleft bottomright: bottomright leftline: Line2D.fromPoints(topleft, bottomleft) rightline: Line2D.fromPoints(bottomright, topright) if newoutpolygonrow.length > 0 prevoutpolygon = newoutpolygonrow[newoutpolygonrow.length - 1] d1 = outpolygon.topleft.distanceTo(prevoutpolygon.topright) d2 = outpolygon.bottomleft.distanceTo(prevoutpolygon.bottomright) if (d1 < EPS) and (d2 < EPS) # we can join this polygon with the one to the left: outpolygon.topleft = prevoutpolygon.topleft outpolygon.leftline = prevoutpolygon.leftline outpolygon.bottomleft = prevoutpolygon.bottomleft newoutpolygonrow.splice newoutpolygonrow.length - 1, 1 newoutpolygonrow.push outpolygon # for(activepolygon in activepolygons) if yindex > 0 # try to match the new polygons against the previous row: prevcontinuedindexes = {} matchedindexes = {} i = 0 while i < newoutpolygonrow.length thispolygon = newoutpolygonrow[i] ii = 0 while ii < prevoutpolygonrow.length unless matchedindexes[ii] # not already processed? # We have a match if the sidelines are equal or if the top coordinates # are on the sidelines of the previous polygon prevpolygon = prevoutpolygonrow[ii] if prevpolygon.bottomleft.distanceTo(thispolygon.topleft) < EPS if prevpolygon.bottomright.distanceTo(thispolygon.topright) < EPS # Yes, the top of this polygon matches the bottom of the previous: matchedindexes[ii] = true # Now check if the joined polygon would remain convex: d1 = thispolygon.leftline.direction().x - prevpolygon.leftline.direction().x d2 = thispolygon.rightline.direction().x - prevpolygon.rightline.direction().x leftlinecontinues = Math.abs(d1) < EPS rightlinecontinues = Math.abs(d2) < EPS leftlineisconvex = leftlinecontinues or (d1 >= 0) rightlineisconvex = rightlinecontinues or (d2 >= 0) if leftlineisconvex and rightlineisconvex # yes, both sides have convex corners: # This polygon will continue the previous polygon thispolygon.outpolygon = prevpolygon.outpolygon thispolygon.leftlinecontinues = leftlinecontinues thispolygon.rightlinecontinues = rightlinecontinues prevcontinuedindexes[ii] = true break ii++ i++ # if(!prevcontinuedindexes[ii]) # for ii # for i ii = 0 while ii < prevoutpolygonrow.length unless prevcontinuedindexes[ii] # polygon ends here # Finish the polygon with the last point(s): prevpolygon = prevoutpolygonrow[ii] prevpolygon.outpolygon.rightpoints.push prevpolygon.bottomright # polygon ends with a horizontal line: prevpolygon.outpolygon.leftpoints.push prevpolygon.bottomleft if prevpolygon.bottomright.distanceTo(prevpolygon.bottomleft) > EPS # reverse the left half so we get a counterclockwise circle: prevpolygon.outpolygon.leftpoints.reverse() points2d = prevpolygon.outpolygon.rightpoints.concat(prevpolygon.outpolygon.leftpoints) vertices3d = [] points2d.map (point2d) -> point3d = orthobasis.to3D(point2d) vertex3d = new Vertex(point3d) vertices3d.push vertex3d polygon = new Polygon(vertices3d, shared, plane) destpolygons.push polygon ii++ # if(yindex > 0) i = 0 while i < newoutpolygonrow.length thispolygon = newoutpolygonrow[i] unless thispolygon.outpolygon # polygon starts here: thispolygon.outpolygon = leftpoints: [] rightpoints: [] thispolygon.outpolygon.leftpoints.push thispolygon.topleft # we have a horizontal line at the top: thispolygon.outpolygon.rightpoints.push thispolygon.topright if thispolygon.topleft.distanceTo(thispolygon.topright) > EPS else # continuation of a previous row thispolygon.outpolygon.leftpoints.push thispolygon.topleft unless thispolygon.leftlinecontinues thispolygon.outpolygon.rightpoints.push thispolygon.topright unless thispolygon.rightlinecontinues i++ prevoutpolygonrow = newoutpolygonrow yindex++ class FuzzyFactory # This class acts as a factory for objects. We can search for an object with approximately # the desired properties (say a rectangle with width 2 and height 1) # The lookupOrCreate() method looks for an existing object (for example it may find an existing rectangle # with width 2.0001 and height 0.999. If no object is found, the user supplied callback is # called, which should generate a new object. The new object is inserted into the database # so it can be found by future lookupOrCreate() calls. constructor : (numdimensions, tolerance) -> # Constructor: # numdimensions: the number of parameters for each object # for example for a 2D rectangle this would be 2 # tolerance: The maximum difference for each parameter allowed to be considered a match lookuptable = [] i = 0 while i < numdimensions lookuptable.push {} i++ @lookuptable = lookuptable @nextElementId = 1 @multiplier = 1.0 / tolerance @objectTable = {} lookupOrCreate: (els, creatorCallback) -> # var obj = f.lookupOrCreate([el1, el2, el3], function(elements) {/* create the new object */}); # Performs a fuzzy lookup of the object with the specified elements. # If found, returns the existing object # If not found, calls the supplied callback function which should create a new object with # the specified properties. This object is inserted in the lookup database. object = undefined key = @lookupKey(els) if key is null object = creatorCallback(els) key = @nextElementId++ @objectTable[key] = object dimension = 0 while dimension < els.length elementLookupTable = @lookuptable[dimension] value = els[dimension] valueMultiplied = value * @multiplier valueQuantized1 = Math.floor(valueMultiplied) valueQuantized2 = Math.ceil(valueMultiplied) FuzzyFactory.insertKey key, elementLookupTable, valueQuantized1 FuzzyFactory.insertKey key, elementLookupTable, valueQuantized2 dimension++ else object = @objectTable[key] object # ----------- PRIVATE METHODS: lookupKey: (els) -> keyset = {} dimension = 0 while dimension < els.length elementLookupTable = @lookuptable[dimension] value = els[dimension] valueQuantized = Math.round(value * @multiplier) valueQuantized += "" if valueQuantized of elementLookupTable if dimension is 0 keyset = elementLookupTable[valueQuantized] else keyset = FuzzyFactory.intersectSets(keyset, elementLookupTable[valueQuantized]) else return null return null if FuzzyFactory.isEmptySet(keyset) dimension++ # return first matching key: for key of keyset return key null lookupKeySetForDimension: (dimension, value) -> result = undefined elementLookupTable = @lookuptable[dimension] valueMultiplied = value * @multiplier valueQuantized = Math.floor(value * @multiplier) if valueQuantized of elementLookupTable result = elementLookupTable[valueQuantized] else result = {} result @insertKey : (key, lookuptable, quantizedvalue) -> if quantizedvalue of lookuptable lookuptable[quantizedvalue][key] = true else newset = {} newset[key] = true lookuptable[quantizedvalue] = newset @isEmptySet : (obj) -> for key of obj return false true @intersectSets : (set1, set2) -> result = {} for key of set1 result[key] = true if key of set2 result @joinSets : (set1, set2) -> result = {} for key of set1 result[key] = true for key of set2 result[key] = true result class FuzzyCSGFactory constructor: -> @vertexfactory = new FuzzyFactory(3, 1e-5) @planefactory = new FuzzyFactory(4, 1e-5) @polygonsharedfactory = {} getPolygonShared: (sourceshared) -> hash = sourceshared.getHash() if hash of @polygonsharedfactory @polygonsharedfactory[hash] else @polygonsharedfactory[hash] = sourceshared sourceshared getVertex: (sourcevertex) -> elements = [sourcevertex.pos._x, sourcevertex.pos._y, sourcevertex.pos._z] result = @vertexfactory.lookupOrCreate(elements, (els) -> sourcevertex ) result getPlane: (sourceplane) -> elements = [sourceplane.normal._x, sourceplane.normal._y, sourceplane.normal._z, sourceplane.w] result = @planefactory.lookupOrCreate(elements, (els) -> sourceplane ) result getPolygon: (sourcepolygon) -> newplane = @getPlane(sourcepolygon.plane) newshared = @getPolygonShared(sourcepolygon.shared) newvertices = (@getVertex vertex for vertex in sourcepolygon.vertices) new Polygon(newvertices, newshared, newplane) getCSG: (sourceCsg) -> #deprecated _this = this newpolygons = sourceCsg.polygons.map((polygon) -> _this.getPolygon polygon ) CSGBase.fromPolygons newpolygons getCSGPolygons: (sourceCsg) -> #returns new polygons based on sourceCSG newpolygons = (@getPolygon polygon for polygon in sourceCsg.polygons) class FuzzyCAGFactory constructor:-> @vertexfactory = new FuzzyFactory(2, 1e-5) getVertex: (sourcevertex) -> elements = [sourcevertex.pos._x, sourcevertex.pos._y] result = @vertexfactory.lookupOrCreate(elements, (els) -> sourcevertex ) result getSide: (sourceside) -> vertex0 = @getVertex(sourceside.vertex0) vertex1 = @getVertex(sourceside.vertex1) new Side(vertex0, vertex1) getCAG: (sourcecag) -> _this = this newsides = sourcecag.sides.map((side) -> _this.getSide side ) CAGBase.fromSides newsides getCAGSides:(sourceCag) -> _this = this newsides = sourceCag.sides.map((side) -> _this.getSide side ) newsides return { "parseOption": parseOption "parseOptions":parseOptions "parseOptionAs3DVector": parseOptionAs3DVector "parseOptionAs2DVector": parseOptionAs2DVector "parseOptionAsFloat": parseOptionAsFloat "parseOptionAsInt": parseOptionAsInt "parseOptionAsBool": parseOptionAsBool "parseOptionAsLocations":parseOptionAsLocations "parseCenter":parseCenter "insertSorted": insertSorted "interpolateBetween2DPointsForY": interpolateBetween2DPointsForY "reTesselateCoplanarPolygons": reTesselateCoplanarPolygons "FuzzyFactory": FuzzyFactory "FuzzyCSGFactory": FuzzyCSGFactory "FuzzyCAGFactory": FuzzyCAGFactory "merge":merge "extend":extend }
28359
define (require)-> globals = require './globals' maths = require './maths' Vector2D = maths.Vector2D Vector3D = maths.Vector3D Vertex = maths.Vertex Line2D = maths.Line2D OrthoNormalBasis = maths.OrthoNormalBasis Polygon = maths.Polygon Side = maths.Side merge = (options, overrides) -> extend (extend {}, options), overrides extend = (object, properties) -> for key, val of properties object[key] = val object parseOptions = (options, defaults)-> if Object.getPrototypeOf( options ) == Object.prototype options = merge defaults, options else if options instanceof Array indexToName = {} result = {} index =0 for own key,val of defaults indexToName[index]=key result[key]=val index++ for option, index in options if option? name = indexToName[index] result[name]=option options = result return options parseOption = (options, optionname, defaultvalue) -> # Parse an option from the options object # If the option is not present, return the default value result = defaultvalue result = options[optionname] if optionname of options if options result parseOptionAs3DVector = (options, optionname, defaultValue, defaultValue2) -> # Parse an option and force into a Vector3D. If a scalar is passed it is converted # into a vector with equal x,y,z, if a boolean is passed and is true, take defaultvalue, otherwise defaultvalue2 if optionname of options if options[optionname] == false or options[optionname] == true doCenter = parseOptionAsBool(options,optionname,false) if doCenter options[optionname]=defaultValue else options[optionname]=defaultValue2 result = parseOption(options, optionname, defaultValue) result = new Vector3D(result) result parseOptionAs2DVector = (options, optionname, defaultValue, defaultValue2) -> # Parse an option and force into a Vector2D. If a scalar is passed it is converted # into a vector with equal x,y, if a boolean is passed and is true, take defaultvalue, otherwise defaultvalue2 if optionname of options if options[optionname] == false or options[optionname] == true doCenter = parseOptionAsBool(options,optionname,false) if doCenter options[optionname]=defaultValue else options[optionname]=defaultValue2 result = parseOption(options, optionname, defaultValue) result = new Vector2D(result) result parseOptionAsFloat = (options, optionname, defaultvalue) -> result = parseOption(options, optionname, defaultvalue) if typeof (result) is "string" result = Number(result) else throw new Error("Parameter " + optionname + " should be a number") unless typeof (result) is "number" result parseOptionAsInt = (options, optionname, defaultvalue) -> result = parseOption(options, optionname, defaultvalue) Number Math.floor(result) parseOptionAsBool = (options, optionname, defaultvalue) -> result = parseOption(options, optionname, defaultvalue) if typeof (result) is "string" result = true if result is "true" result = false if result is "false" result = false if result is 0 result = !!result result parseOptionAsLocations = (options, optionName, defaultValue) -> result = parseOption(options, optionName, defaultValue) #left, right, top, bottom, front back when used alone, overide all others #front left front right , top left etc (dual params) override ternary params #so by params size : 1>2>3 mapping_old = { "top":globals.top, "bottom":globals.bottom, "left":globals.left, "right":globals.right, "front":globals.front, "back":globals.back, } mapping = { "all":(parseInt("111111",2)), "top": (parseInt("101111",2)), "bottom":parseInt("011111",2), "left":parseInt("111011",2), "right":parseInt("110111",2), "front":parseInt("111110",2), "back":parseInt("111101",2) } stuff = null for location in result #trim leading and trailing whitespaces location = location.replace /^\s+|\s+$/g, "" locations =location.split(" ") #console.log "location" #console.log location subStuff = null for loc in locations loc = mapping[loc] if not subStuff? subStuff = loc else subStuff = subStuff & loc if not stuff? stuff = subStuff else stuff = stuff | subStuff stuff.toString(2) parseCenter = (options, optionname, defaultValue, defaultValue2, vectorClass) -> # Parse a "center" option and force into a Vector3D. If a scalar is passed it is converted # into a vector with equal x,y,z, if a boolean is passed and is true, take defaultvalue, otherwise defaultvalue2 if optionname of options centerOption = options[optionname] if centerOption instanceof Array newDefaultValue = new vectorClass(defaultValue) newDefaultValue2 = new vectorClass(defaultValue2) for component, index in centerOption if typeof component is 'boolean' if index is 0 centerOption[index] = if component == true then newDefaultValue2.x else if component == false then newDefaultValue.x else centerOption[index] else if index is 1 centerOption[index] = if component == true then newDefaultValue2.y else if component == false then newDefaultValue.y else centerOption[index] else if index is 2 centerOption[index] = if component == true then newDefaultValue2.z else if component == false then newDefaultValue.z else centerOption[index] options[optionname] = centerOption else if typeof centerOption is 'boolean' doCenter = parseOptionAsBool(options,optionname,false) if doCenter options[optionname]=defaultValue2 else options[optionname]=defaultValue result = parseOption(options, optionname, defaultValue) result = new vectorClass(result) result insertSorted = (array, element, comparefunc) -> leftbound = 0 rightbound = array.length while rightbound > leftbound testindex = Math.floor((leftbound + rightbound) / 2) testelement = array[testindex] compareresult = comparefunc(element, testelement) if compareresult > 0 # element > testelement leftbound = testindex + 1 else rightbound = testindex array.splice leftbound, 0, element interpolateBetween2DPointsForY = (point1, point2, y) -> # Get the x coordinate of a point with a certain y coordinate, interpolated between two # points (Vector2D). # Interpolation is robust even if the points have the same y coordinate f1 = y - point1.y f2 = point2.y - point1.y if f2 < 0 f1 = -f1 f2 = -f2 t = undefined if f1 <= 0 t = 0.0 else if f1 >= f2 t = 1.0 else if f2 < 1e-10 t = 0.5 else t = f1 / f2 result = point1.x + t * (point2.x - point1.x) result reTesselateCoplanarPolygons = (sourcepolygons, destpolygons) -> # Retesselation function for a set of coplanar polygons. See the introduction at the top of # this file. EPS = 1e-5 numpolygons = sourcepolygons.length if numpolygons > 0 plane = sourcepolygons[0].plane shared = sourcepolygons[0].shared orthobasis = new OrthoNormalBasis(plane) polygonvertices2d = [] # array of array of Vector2D polygontopvertexindexes = [] # array of indexes of topmost vertex per polygon topy2polygonindexes = {} ycoordinatetopolygonindexes = {} xcoordinatebins = {} ycoordinatebins = {} # convert all polygon vertices to 2D # Make a list of all encountered y coordinates # And build a map of all polygons that have a vertex at a certain y coordinate: ycoordinateBinningFactor = 1.0 / EPS * 10 polygonindex = 0 while polygonindex < numpolygons poly3d = sourcepolygons[polygonindex] vertices2d = [] numvertices = poly3d.vertices.length minindex = -1 if numvertices > 0 miny = undefined maxy = undefined maxindex = undefined i = 0 while i < numvertices pos2d = orthobasis.to2D(poly3d.vertices[i].pos) # perform binning of y coordinates: If we have multiple vertices very # close to each other, give them the same y coordinate: ycoordinatebin = Math.floor(pos2d.y * ycoordinateBinningFactor) newy = undefined if ycoordinatebin of ycoordinatebins newy = ycoordinatebins[ycoordinatebin] else if ycoordinatebin + 1 of ycoordinatebins newy = ycoordinatebins[ycoordinatebin + 1] else if ycoordinatebin - 1 of ycoordinatebins newy = ycoordinatebins[ycoordinatebin - 1] else newy = pos2d.y ycoordinatebins[ycoordinatebin] = pos2d.y pos2d = new Vector2D(pos2d.x, newy) vertices2d.push pos2d y = pos2d.y if (i is 0) or (y < miny) miny = y minindex = i if (i is 0) or (y > maxy) maxy = y maxindex = i ycoordinatetopolygonindexes[y] = {} unless y of ycoordinatetopolygonindexes ycoordinatetopolygonindexes[y][polygonindex] = true i++ if miny >= maxy # degenerate polygon, all vertices have same y coordinate. Just ignore it from now: vertices2d = [] else topy2polygonindexes[miny] = [] unless miny of topy2polygonindexes topy2polygonindexes[miny].push polygonindex # if(numvertices > 0) # reverse the vertex order: vertices2d.reverse() minindex = numvertices - minindex - 1 polygonvertices2d.push vertices2d polygontopvertexindexes.push minindex polygonindex++ ycoordinates = [] for ycoordinate of ycoordinatetopolygonindexes ycoordinates.push ycoordinate ycoordinates.sort (a, b) -> a - b # Now we will iterate over all y coordinates, from lowest to highest y coordinate # activepolygons: source polygons that are 'active', i.e. intersect with our y coordinate # Is sorted so the polygons are in left to right order # Each element in activepolygons has these properties: # polygonindex: the index of the source polygon (i.e. an index into the sourcepolygons and polygonvertices2d arrays) # leftvertexindex: the index of the vertex at the left side of the polygon (lowest x) that is at or just above the current y coordinate # rightvertexindex: dito at right hand side of polygon # topleft, bottomleft: coordinates of the left side of the polygon crossing the current y coordinate # topright, bottomright: coordinates of the right hand side of the polygon crossing the current y coordinate activepolygons = [] prevoutpolygonrow = [] yindex = 0 while yindex < ycoordinates.length newoutpolygonrow = [] ycoordinate_as_string = ycoordinates[yindex] ycoordinate = Number(ycoordinate_as_string) # update activepolygons for this y coordinate: # - Remove any polygons that end at this y coordinate # - update leftvertexindex and rightvertexindex (which point to the current vertex index # at the the left and right side of the polygon # Iterate over all polygons that have a corner at this y coordinate: polygonindexeswithcorner = ycoordinatetopolygonindexes[ycoordinate_as_string] activepolygonindex = 0 while activepolygonindex < activepolygons.length activepolygon = activepolygons[activepolygonindex] polygonindex = activepolygon.polygonindex if polygonindexeswithcorner[polygonindex] # this active polygon has a corner at this y coordinate: vertices2d = polygonvertices2d[polygonindex] numvertices = vertices2d.length newleftvertexindex = activepolygon.leftvertexindex newrightvertexindex = activepolygon.rightvertexindex # See if we need to increase leftvertexindex or decrease rightvertexindex: loop nextleftvertexindex = newleftvertexindex + 1 nextleftvertexindex = 0 if nextleftvertexindex >= numvertices break unless vertices2d[nextleftvertexindex].y is ycoordinate newleftvertexindex = nextleftvertexindex nextrightvertexindex = newrightvertexindex - 1 nextrightvertexindex = numvertices - 1 if nextrightvertexindex < 0 newrightvertexindex = nextrightvertexindex if vertices2d[nextrightvertexindex].y is ycoordinate if (newleftvertexindex isnt activepolygon.leftvertexindex) and (newleftvertexindex is newrightvertexindex) # We have increased leftvertexindex or decreased rightvertexindex, and now they point to the same vertex # This means that this is the bottom point of the polygon. We'll remove it: activepolygons.splice activepolygonindex, 1 --activepolygonindex else activepolygon.leftvertexindex = newleftvertexindex activepolygon.rightvertexindex = newrightvertexindex activepolygon.topleft = vertices2d[newleftvertexindex] activepolygon.topright = vertices2d[newrightvertexindex] nextleftvertexindex = newleftvertexindex + 1 nextleftvertexindex = 0 if nextleftvertexindex >= numvertices activepolygon.bottomleft = vertices2d[nextleftvertexindex] nextrightvertexindex = newrightvertexindex - 1 nextrightvertexindex = numvertices - 1 if nextrightvertexindex < 0 activepolygon.bottomright = vertices2d[nextrightvertexindex] ++activepolygonindex # if polygon has corner here # for activepolygonindex nextycoordinate = undefined if yindex >= ycoordinates.length - 1 # last row, all polygons must be finished here: activepolygons = [] nextycoordinate = null # yindex < ycoordinates.length-1 else nextycoordinate = Number(ycoordinates[yindex + 1]) middleycoordinate = 0.5 * (ycoordinate + nextycoordinate) # update activepolygons by adding any polygons that start here: startingpolygonindexes = topy2polygonindexes[ycoordinate_as_string] for polygonindex_key of startingpolygonindexes polygonindex = startingpolygonindexes[polygonindex_key] vertices2d = polygonvertices2d[polygonindex] numvertices = vertices2d.length topvertexindex = polygontopvertexindexes[polygonindex] # the top of the polygon may be a horizontal line. In that case topvertexindex can point to any point on this line. # Find the left and right topmost vertices which have the current y coordinate: topleftvertexindex = topvertexindex loop i = topleftvertexindex + 1 i = 0 if i >= numvertices break unless vertices2d[i].y is ycoordinate break if i is topvertexindex # should not happen, but just to prevent endless loops topleftvertexindex = i toprightvertexindex = topvertexindex loop i = toprightvertexindex - 1 i = numvertices - 1 if i < 0 break unless vertices2d[i].y is ycoordinate break if i is topleftvertexindex # should not happen, but just to prevent endless loops toprightvertexindex = i nextleftvertexindex = topleftvertexindex + 1 nextleftvertexindex = 0 if nextleftvertexindex >= numvertices nextrightvertexindex = toprightvertexindex - 1 nextrightvertexindex = numvertices - 1 if nextrightvertexindex < 0 newactivepolygon = polygonindex: polygonindex leftvertexindex: topleftvertexindex rightvertexindex: toprightvertexindex topleft: vertices2d[topleftvertexindex] topright: vertices2d[toprightvertexindex] bottomleft: vertices2d[nextleftvertexindex] bottomright: vertices2d[nextrightvertexindex] insertSorted activepolygons, newactivepolygon, (el1, el2) -> x1 = interpolateBetween2DPointsForY(el1.topleft, el1.bottomleft, middleycoordinate) x2 = interpolateBetween2DPointsForY(el2.topleft, el2.bottomleft, middleycoordinate) return 1 if x1 > x2 return -1 if x1 < x2 0 # for(var polygonindex in startingpolygonindexes) # yindex < ycoordinates.length-1 #if( (yindex == ycoordinates.length-1) || (nextycoordinate - ycoordinate > EPS) ) if true # Now activepolygons is up to date # Build the output polygons for the next row in newoutpolygonrow: for activepolygon_key of activepolygons activepolygon = activepolygons[activepolygon_key] polygonindex = activepolygon.polygonindex vertices2d = polygonvertices2d[polygonindex] numvertices = vertices2d.length x = interpolateBetween2DPointsForY(activepolygon.topleft, activepolygon.bottomleft, ycoordinate) topleft = new Vector2D(x, ycoordinate) x = interpolateBetween2DPointsForY(activepolygon.topright, activepolygon.bottomright, ycoordinate) topright = new Vector2D(x, ycoordinate) x = interpolateBetween2DPointsForY(activepolygon.topleft, activepolygon.bottomleft, nextycoordinate) bottomleft = new Vector2D(x, nextycoordinate) x = interpolateBetween2DPointsForY(activepolygon.topright, activepolygon.bottomright, nextycoordinate) bottomright = new Vector2D(x, nextycoordinate) outpolygon = topleft: topleft topright: topright bottomleft: bottomleft bottomright: bottomright leftline: Line2D.fromPoints(topleft, bottomleft) rightline: Line2D.fromPoints(bottomright, topright) if newoutpolygonrow.length > 0 prevoutpolygon = newoutpolygonrow[newoutpolygonrow.length - 1] d1 = outpolygon.topleft.distanceTo(prevoutpolygon.topright) d2 = outpolygon.bottomleft.distanceTo(prevoutpolygon.bottomright) if (d1 < EPS) and (d2 < EPS) # we can join this polygon with the one to the left: outpolygon.topleft = prevoutpolygon.topleft outpolygon.leftline = prevoutpolygon.leftline outpolygon.bottomleft = prevoutpolygon.bottomleft newoutpolygonrow.splice newoutpolygonrow.length - 1, 1 newoutpolygonrow.push outpolygon # for(activepolygon in activepolygons) if yindex > 0 # try to match the new polygons against the previous row: prevcontinuedindexes = {} matchedindexes = {} i = 0 while i < newoutpolygonrow.length thispolygon = newoutpolygonrow[i] ii = 0 while ii < prevoutpolygonrow.length unless matchedindexes[ii] # not already processed? # We have a match if the sidelines are equal or if the top coordinates # are on the sidelines of the previous polygon prevpolygon = prevoutpolygonrow[ii] if prevpolygon.bottomleft.distanceTo(thispolygon.topleft) < EPS if prevpolygon.bottomright.distanceTo(thispolygon.topright) < EPS # Yes, the top of this polygon matches the bottom of the previous: matchedindexes[ii] = true # Now check if the joined polygon would remain convex: d1 = thispolygon.leftline.direction().x - prevpolygon.leftline.direction().x d2 = thispolygon.rightline.direction().x - prevpolygon.rightline.direction().x leftlinecontinues = Math.abs(d1) < EPS rightlinecontinues = Math.abs(d2) < EPS leftlineisconvex = leftlinecontinues or (d1 >= 0) rightlineisconvex = rightlinecontinues or (d2 >= 0) if leftlineisconvex and rightlineisconvex # yes, both sides have convex corners: # This polygon will continue the previous polygon thispolygon.outpolygon = prevpolygon.outpolygon thispolygon.leftlinecontinues = leftlinecontinues thispolygon.rightlinecontinues = rightlinecontinues prevcontinuedindexes[ii] = true break ii++ i++ # if(!prevcontinuedindexes[ii]) # for ii # for i ii = 0 while ii < prevoutpolygonrow.length unless prevcontinuedindexes[ii] # polygon ends here # Finish the polygon with the last point(s): prevpolygon = prevoutpolygonrow[ii] prevpolygon.outpolygon.rightpoints.push prevpolygon.bottomright # polygon ends with a horizontal line: prevpolygon.outpolygon.leftpoints.push prevpolygon.bottomleft if prevpolygon.bottomright.distanceTo(prevpolygon.bottomleft) > EPS # reverse the left half so we get a counterclockwise circle: prevpolygon.outpolygon.leftpoints.reverse() points2d = prevpolygon.outpolygon.rightpoints.concat(prevpolygon.outpolygon.leftpoints) vertices3d = [] points2d.map (point2d) -> point3d = orthobasis.to3D(point2d) vertex3d = new Vertex(point3d) vertices3d.push vertex3d polygon = new Polygon(vertices3d, shared, plane) destpolygons.push polygon ii++ # if(yindex > 0) i = 0 while i < newoutpolygonrow.length thispolygon = newoutpolygonrow[i] unless thispolygon.outpolygon # polygon starts here: thispolygon.outpolygon = leftpoints: [] rightpoints: [] thispolygon.outpolygon.leftpoints.push thispolygon.topleft # we have a horizontal line at the top: thispolygon.outpolygon.rightpoints.push thispolygon.topright if thispolygon.topleft.distanceTo(thispolygon.topright) > EPS else # continuation of a previous row thispolygon.outpolygon.leftpoints.push thispolygon.topleft unless thispolygon.leftlinecontinues thispolygon.outpolygon.rightpoints.push thispolygon.topright unless thispolygon.rightlinecontinues i++ prevoutpolygonrow = newoutpolygonrow yindex++ class FuzzyFactory # This class acts as a factory for objects. We can search for an object with approximately # the desired properties (say a rectangle with width 2 and height 1) # The lookupOrCreate() method looks for an existing object (for example it may find an existing rectangle # with width 2.0001 and height 0.999. If no object is found, the user supplied callback is # called, which should generate a new object. The new object is inserted into the database # so it can be found by future lookupOrCreate() calls. constructor : (numdimensions, tolerance) -> # Constructor: # numdimensions: the number of parameters for each object # for example for a 2D rectangle this would be 2 # tolerance: The maximum difference for each parameter allowed to be considered a match lookuptable = [] i = 0 while i < numdimensions lookuptable.push {} i++ @lookuptable = lookuptable @nextElementId = 1 @multiplier = 1.0 / tolerance @objectTable = {} lookupOrCreate: (els, creatorCallback) -> # var obj = f.lookupOrCreate([el1, el2, el3], function(elements) {/* create the new object */}); # Performs a fuzzy lookup of the object with the specified elements. # If found, returns the existing object # If not found, calls the supplied callback function which should create a new object with # the specified properties. This object is inserted in the lookup database. object = undefined key = <KEY>(els) if key is null object = creatorCallback(els) key = <KEY> @objectTable[key] = object dimension = 0 while dimension < els.length elementLookupTable = @lookuptable[dimension] value = els[dimension] valueMultiplied = value * @multiplier valueQuantized1 = Math.floor(valueMultiplied) valueQuantized2 = Math.ceil(valueMultiplied) FuzzyFactory.insertKey key, elementLookupTable, valueQuantized1 FuzzyFactory.insertKey key, elementLookupTable, valueQuantized2 dimension++ else object = @objectTable[key] object # ----------- PRIVATE METHODS: lookupKey: (els) -> keyset = {} dimension = 0 while dimension < els.length elementLookupTable = @lookuptable[dimension] value = els[dimension] valueQuantized = Math.round(value * @multiplier) valueQuantized += "" if valueQuantized of elementLookupTable if dimension is 0 keyset = elementLookupTable[valueQuantized] else keyset = FuzzyFactory.intersectSets(keyset, elementLookupTable[valueQuantized]) else return null return null if FuzzyFactory.isEmptySet(keyset) dimension++ # return first matching key: for key of keyset return key null lookupKeySetForDimension: (dimension, value) -> result = undefined elementLookupTable = @lookuptable[dimension] valueMultiplied = value * @multiplier valueQuantized = Math.floor(value * @multiplier) if valueQuantized of elementLookupTable result = elementLookupTable[valueQuantized] else result = {} result @insertKey : (key, lookuptable, quantizedvalue) -> if quantizedvalue of lookuptable lookuptable[quantizedvalue][key] = true else newset = {} newset[key] = true lookuptable[quantizedvalue] = newset @isEmptySet : (obj) -> for key of obj return false true @intersectSets : (set1, set2) -> result = {} for key of set1 result[key] = true if key of set2 result @joinSets : (set1, set2) -> result = {} for key of set1 result[key] = true for key of set2 result[key] = true result class FuzzyCSGFactory constructor: -> @vertexfactory = new FuzzyFactory(3, 1e-5) @planefactory = new FuzzyFactory(4, 1e-5) @polygonsharedfactory = {} getPolygonShared: (sourceshared) -> hash = sourceshared.getHash() if hash of @polygonsharedfactory @polygonsharedfactory[hash] else @polygonsharedfactory[hash] = sourceshared sourceshared getVertex: (sourcevertex) -> elements = [sourcevertex.pos._x, sourcevertex.pos._y, sourcevertex.pos._z] result = @vertexfactory.lookupOrCreate(elements, (els) -> sourcevertex ) result getPlane: (sourceplane) -> elements = [sourceplane.normal._x, sourceplane.normal._y, sourceplane.normal._z, sourceplane.w] result = @planefactory.lookupOrCreate(elements, (els) -> sourceplane ) result getPolygon: (sourcepolygon) -> newplane = @getPlane(sourcepolygon.plane) newshared = @getPolygonShared(sourcepolygon.shared) newvertices = (@getVertex vertex for vertex in sourcepolygon.vertices) new Polygon(newvertices, newshared, newplane) getCSG: (sourceCsg) -> #deprecated _this = this newpolygons = sourceCsg.polygons.map((polygon) -> _this.getPolygon polygon ) CSGBase.fromPolygons newpolygons getCSGPolygons: (sourceCsg) -> #returns new polygons based on sourceCSG newpolygons = (@getPolygon polygon for polygon in sourceCsg.polygons) class FuzzyCAGFactory constructor:-> @vertexfactory = new FuzzyFactory(2, 1e-5) getVertex: (sourcevertex) -> elements = [sourcevertex.pos._x, sourcevertex.pos._y] result = @vertexfactory.lookupOrCreate(elements, (els) -> sourcevertex ) result getSide: (sourceside) -> vertex0 = @getVertex(sourceside.vertex0) vertex1 = @getVertex(sourceside.vertex1) new Side(vertex0, vertex1) getCAG: (sourcecag) -> _this = this newsides = sourcecag.sides.map((side) -> _this.getSide side ) CAGBase.fromSides newsides getCAGSides:(sourceCag) -> _this = this newsides = sourceCag.sides.map((side) -> _this.getSide side ) newsides return { "parseOption": parseOption "parseOptions":parseOptions "parseOptionAs3DVector": parseOptionAs3DVector "parseOptionAs2DVector": parseOptionAs2DVector "parseOptionAsFloat": parseOptionAsFloat "parseOptionAsInt": parseOptionAsInt "parseOptionAsBool": parseOptionAsBool "parseOptionAsLocations":parseOptionAsLocations "parseCenter":parseCenter "insertSorted": insertSorted "interpolateBetween2DPointsForY": interpolateBetween2DPointsForY "reTesselateCoplanarPolygons": reTesselateCoplanarPolygons "FuzzyFactory": FuzzyFactory "FuzzyCSGFactory": FuzzyCSGFactory "FuzzyCAGFactory": FuzzyCAGFactory "merge":merge "extend":extend }
true
define (require)-> globals = require './globals' maths = require './maths' Vector2D = maths.Vector2D Vector3D = maths.Vector3D Vertex = maths.Vertex Line2D = maths.Line2D OrthoNormalBasis = maths.OrthoNormalBasis Polygon = maths.Polygon Side = maths.Side merge = (options, overrides) -> extend (extend {}, options), overrides extend = (object, properties) -> for key, val of properties object[key] = val object parseOptions = (options, defaults)-> if Object.getPrototypeOf( options ) == Object.prototype options = merge defaults, options else if options instanceof Array indexToName = {} result = {} index =0 for own key,val of defaults indexToName[index]=key result[key]=val index++ for option, index in options if option? name = indexToName[index] result[name]=option options = result return options parseOption = (options, optionname, defaultvalue) -> # Parse an option from the options object # If the option is not present, return the default value result = defaultvalue result = options[optionname] if optionname of options if options result parseOptionAs3DVector = (options, optionname, defaultValue, defaultValue2) -> # Parse an option and force into a Vector3D. If a scalar is passed it is converted # into a vector with equal x,y,z, if a boolean is passed and is true, take defaultvalue, otherwise defaultvalue2 if optionname of options if options[optionname] == false or options[optionname] == true doCenter = parseOptionAsBool(options,optionname,false) if doCenter options[optionname]=defaultValue else options[optionname]=defaultValue2 result = parseOption(options, optionname, defaultValue) result = new Vector3D(result) result parseOptionAs2DVector = (options, optionname, defaultValue, defaultValue2) -> # Parse an option and force into a Vector2D. If a scalar is passed it is converted # into a vector with equal x,y, if a boolean is passed and is true, take defaultvalue, otherwise defaultvalue2 if optionname of options if options[optionname] == false or options[optionname] == true doCenter = parseOptionAsBool(options,optionname,false) if doCenter options[optionname]=defaultValue else options[optionname]=defaultValue2 result = parseOption(options, optionname, defaultValue) result = new Vector2D(result) result parseOptionAsFloat = (options, optionname, defaultvalue) -> result = parseOption(options, optionname, defaultvalue) if typeof (result) is "string" result = Number(result) else throw new Error("Parameter " + optionname + " should be a number") unless typeof (result) is "number" result parseOptionAsInt = (options, optionname, defaultvalue) -> result = parseOption(options, optionname, defaultvalue) Number Math.floor(result) parseOptionAsBool = (options, optionname, defaultvalue) -> result = parseOption(options, optionname, defaultvalue) if typeof (result) is "string" result = true if result is "true" result = false if result is "false" result = false if result is 0 result = !!result result parseOptionAsLocations = (options, optionName, defaultValue) -> result = parseOption(options, optionName, defaultValue) #left, right, top, bottom, front back when used alone, overide all others #front left front right , top left etc (dual params) override ternary params #so by params size : 1>2>3 mapping_old = { "top":globals.top, "bottom":globals.bottom, "left":globals.left, "right":globals.right, "front":globals.front, "back":globals.back, } mapping = { "all":(parseInt("111111",2)), "top": (parseInt("101111",2)), "bottom":parseInt("011111",2), "left":parseInt("111011",2), "right":parseInt("110111",2), "front":parseInt("111110",2), "back":parseInt("111101",2) } stuff = null for location in result #trim leading and trailing whitespaces location = location.replace /^\s+|\s+$/g, "" locations =location.split(" ") #console.log "location" #console.log location subStuff = null for loc in locations loc = mapping[loc] if not subStuff? subStuff = loc else subStuff = subStuff & loc if not stuff? stuff = subStuff else stuff = stuff | subStuff stuff.toString(2) parseCenter = (options, optionname, defaultValue, defaultValue2, vectorClass) -> # Parse a "center" option and force into a Vector3D. If a scalar is passed it is converted # into a vector with equal x,y,z, if a boolean is passed and is true, take defaultvalue, otherwise defaultvalue2 if optionname of options centerOption = options[optionname] if centerOption instanceof Array newDefaultValue = new vectorClass(defaultValue) newDefaultValue2 = new vectorClass(defaultValue2) for component, index in centerOption if typeof component is 'boolean' if index is 0 centerOption[index] = if component == true then newDefaultValue2.x else if component == false then newDefaultValue.x else centerOption[index] else if index is 1 centerOption[index] = if component == true then newDefaultValue2.y else if component == false then newDefaultValue.y else centerOption[index] else if index is 2 centerOption[index] = if component == true then newDefaultValue2.z else if component == false then newDefaultValue.z else centerOption[index] options[optionname] = centerOption else if typeof centerOption is 'boolean' doCenter = parseOptionAsBool(options,optionname,false) if doCenter options[optionname]=defaultValue2 else options[optionname]=defaultValue result = parseOption(options, optionname, defaultValue) result = new vectorClass(result) result insertSorted = (array, element, comparefunc) -> leftbound = 0 rightbound = array.length while rightbound > leftbound testindex = Math.floor((leftbound + rightbound) / 2) testelement = array[testindex] compareresult = comparefunc(element, testelement) if compareresult > 0 # element > testelement leftbound = testindex + 1 else rightbound = testindex array.splice leftbound, 0, element interpolateBetween2DPointsForY = (point1, point2, y) -> # Get the x coordinate of a point with a certain y coordinate, interpolated between two # points (Vector2D). # Interpolation is robust even if the points have the same y coordinate f1 = y - point1.y f2 = point2.y - point1.y if f2 < 0 f1 = -f1 f2 = -f2 t = undefined if f1 <= 0 t = 0.0 else if f1 >= f2 t = 1.0 else if f2 < 1e-10 t = 0.5 else t = f1 / f2 result = point1.x + t * (point2.x - point1.x) result reTesselateCoplanarPolygons = (sourcepolygons, destpolygons) -> # Retesselation function for a set of coplanar polygons. See the introduction at the top of # this file. EPS = 1e-5 numpolygons = sourcepolygons.length if numpolygons > 0 plane = sourcepolygons[0].plane shared = sourcepolygons[0].shared orthobasis = new OrthoNormalBasis(plane) polygonvertices2d = [] # array of array of Vector2D polygontopvertexindexes = [] # array of indexes of topmost vertex per polygon topy2polygonindexes = {} ycoordinatetopolygonindexes = {} xcoordinatebins = {} ycoordinatebins = {} # convert all polygon vertices to 2D # Make a list of all encountered y coordinates # And build a map of all polygons that have a vertex at a certain y coordinate: ycoordinateBinningFactor = 1.0 / EPS * 10 polygonindex = 0 while polygonindex < numpolygons poly3d = sourcepolygons[polygonindex] vertices2d = [] numvertices = poly3d.vertices.length minindex = -1 if numvertices > 0 miny = undefined maxy = undefined maxindex = undefined i = 0 while i < numvertices pos2d = orthobasis.to2D(poly3d.vertices[i].pos) # perform binning of y coordinates: If we have multiple vertices very # close to each other, give them the same y coordinate: ycoordinatebin = Math.floor(pos2d.y * ycoordinateBinningFactor) newy = undefined if ycoordinatebin of ycoordinatebins newy = ycoordinatebins[ycoordinatebin] else if ycoordinatebin + 1 of ycoordinatebins newy = ycoordinatebins[ycoordinatebin + 1] else if ycoordinatebin - 1 of ycoordinatebins newy = ycoordinatebins[ycoordinatebin - 1] else newy = pos2d.y ycoordinatebins[ycoordinatebin] = pos2d.y pos2d = new Vector2D(pos2d.x, newy) vertices2d.push pos2d y = pos2d.y if (i is 0) or (y < miny) miny = y minindex = i if (i is 0) or (y > maxy) maxy = y maxindex = i ycoordinatetopolygonindexes[y] = {} unless y of ycoordinatetopolygonindexes ycoordinatetopolygonindexes[y][polygonindex] = true i++ if miny >= maxy # degenerate polygon, all vertices have same y coordinate. Just ignore it from now: vertices2d = [] else topy2polygonindexes[miny] = [] unless miny of topy2polygonindexes topy2polygonindexes[miny].push polygonindex # if(numvertices > 0) # reverse the vertex order: vertices2d.reverse() minindex = numvertices - minindex - 1 polygonvertices2d.push vertices2d polygontopvertexindexes.push minindex polygonindex++ ycoordinates = [] for ycoordinate of ycoordinatetopolygonindexes ycoordinates.push ycoordinate ycoordinates.sort (a, b) -> a - b # Now we will iterate over all y coordinates, from lowest to highest y coordinate # activepolygons: source polygons that are 'active', i.e. intersect with our y coordinate # Is sorted so the polygons are in left to right order # Each element in activepolygons has these properties: # polygonindex: the index of the source polygon (i.e. an index into the sourcepolygons and polygonvertices2d arrays) # leftvertexindex: the index of the vertex at the left side of the polygon (lowest x) that is at or just above the current y coordinate # rightvertexindex: dito at right hand side of polygon # topleft, bottomleft: coordinates of the left side of the polygon crossing the current y coordinate # topright, bottomright: coordinates of the right hand side of the polygon crossing the current y coordinate activepolygons = [] prevoutpolygonrow = [] yindex = 0 while yindex < ycoordinates.length newoutpolygonrow = [] ycoordinate_as_string = ycoordinates[yindex] ycoordinate = Number(ycoordinate_as_string) # update activepolygons for this y coordinate: # - Remove any polygons that end at this y coordinate # - update leftvertexindex and rightvertexindex (which point to the current vertex index # at the the left and right side of the polygon # Iterate over all polygons that have a corner at this y coordinate: polygonindexeswithcorner = ycoordinatetopolygonindexes[ycoordinate_as_string] activepolygonindex = 0 while activepolygonindex < activepolygons.length activepolygon = activepolygons[activepolygonindex] polygonindex = activepolygon.polygonindex if polygonindexeswithcorner[polygonindex] # this active polygon has a corner at this y coordinate: vertices2d = polygonvertices2d[polygonindex] numvertices = vertices2d.length newleftvertexindex = activepolygon.leftvertexindex newrightvertexindex = activepolygon.rightvertexindex # See if we need to increase leftvertexindex or decrease rightvertexindex: loop nextleftvertexindex = newleftvertexindex + 1 nextleftvertexindex = 0 if nextleftvertexindex >= numvertices break unless vertices2d[nextleftvertexindex].y is ycoordinate newleftvertexindex = nextleftvertexindex nextrightvertexindex = newrightvertexindex - 1 nextrightvertexindex = numvertices - 1 if nextrightvertexindex < 0 newrightvertexindex = nextrightvertexindex if vertices2d[nextrightvertexindex].y is ycoordinate if (newleftvertexindex isnt activepolygon.leftvertexindex) and (newleftvertexindex is newrightvertexindex) # We have increased leftvertexindex or decreased rightvertexindex, and now they point to the same vertex # This means that this is the bottom point of the polygon. We'll remove it: activepolygons.splice activepolygonindex, 1 --activepolygonindex else activepolygon.leftvertexindex = newleftvertexindex activepolygon.rightvertexindex = newrightvertexindex activepolygon.topleft = vertices2d[newleftvertexindex] activepolygon.topright = vertices2d[newrightvertexindex] nextleftvertexindex = newleftvertexindex + 1 nextleftvertexindex = 0 if nextleftvertexindex >= numvertices activepolygon.bottomleft = vertices2d[nextleftvertexindex] nextrightvertexindex = newrightvertexindex - 1 nextrightvertexindex = numvertices - 1 if nextrightvertexindex < 0 activepolygon.bottomright = vertices2d[nextrightvertexindex] ++activepolygonindex # if polygon has corner here # for activepolygonindex nextycoordinate = undefined if yindex >= ycoordinates.length - 1 # last row, all polygons must be finished here: activepolygons = [] nextycoordinate = null # yindex < ycoordinates.length-1 else nextycoordinate = Number(ycoordinates[yindex + 1]) middleycoordinate = 0.5 * (ycoordinate + nextycoordinate) # update activepolygons by adding any polygons that start here: startingpolygonindexes = topy2polygonindexes[ycoordinate_as_string] for polygonindex_key of startingpolygonindexes polygonindex = startingpolygonindexes[polygonindex_key] vertices2d = polygonvertices2d[polygonindex] numvertices = vertices2d.length topvertexindex = polygontopvertexindexes[polygonindex] # the top of the polygon may be a horizontal line. In that case topvertexindex can point to any point on this line. # Find the left and right topmost vertices which have the current y coordinate: topleftvertexindex = topvertexindex loop i = topleftvertexindex + 1 i = 0 if i >= numvertices break unless vertices2d[i].y is ycoordinate break if i is topvertexindex # should not happen, but just to prevent endless loops topleftvertexindex = i toprightvertexindex = topvertexindex loop i = toprightvertexindex - 1 i = numvertices - 1 if i < 0 break unless vertices2d[i].y is ycoordinate break if i is topleftvertexindex # should not happen, but just to prevent endless loops toprightvertexindex = i nextleftvertexindex = topleftvertexindex + 1 nextleftvertexindex = 0 if nextleftvertexindex >= numvertices nextrightvertexindex = toprightvertexindex - 1 nextrightvertexindex = numvertices - 1 if nextrightvertexindex < 0 newactivepolygon = polygonindex: polygonindex leftvertexindex: topleftvertexindex rightvertexindex: toprightvertexindex topleft: vertices2d[topleftvertexindex] topright: vertices2d[toprightvertexindex] bottomleft: vertices2d[nextleftvertexindex] bottomright: vertices2d[nextrightvertexindex] insertSorted activepolygons, newactivepolygon, (el1, el2) -> x1 = interpolateBetween2DPointsForY(el1.topleft, el1.bottomleft, middleycoordinate) x2 = interpolateBetween2DPointsForY(el2.topleft, el2.bottomleft, middleycoordinate) return 1 if x1 > x2 return -1 if x1 < x2 0 # for(var polygonindex in startingpolygonindexes) # yindex < ycoordinates.length-1 #if( (yindex == ycoordinates.length-1) || (nextycoordinate - ycoordinate > EPS) ) if true # Now activepolygons is up to date # Build the output polygons for the next row in newoutpolygonrow: for activepolygon_key of activepolygons activepolygon = activepolygons[activepolygon_key] polygonindex = activepolygon.polygonindex vertices2d = polygonvertices2d[polygonindex] numvertices = vertices2d.length x = interpolateBetween2DPointsForY(activepolygon.topleft, activepolygon.bottomleft, ycoordinate) topleft = new Vector2D(x, ycoordinate) x = interpolateBetween2DPointsForY(activepolygon.topright, activepolygon.bottomright, ycoordinate) topright = new Vector2D(x, ycoordinate) x = interpolateBetween2DPointsForY(activepolygon.topleft, activepolygon.bottomleft, nextycoordinate) bottomleft = new Vector2D(x, nextycoordinate) x = interpolateBetween2DPointsForY(activepolygon.topright, activepolygon.bottomright, nextycoordinate) bottomright = new Vector2D(x, nextycoordinate) outpolygon = topleft: topleft topright: topright bottomleft: bottomleft bottomright: bottomright leftline: Line2D.fromPoints(topleft, bottomleft) rightline: Line2D.fromPoints(bottomright, topright) if newoutpolygonrow.length > 0 prevoutpolygon = newoutpolygonrow[newoutpolygonrow.length - 1] d1 = outpolygon.topleft.distanceTo(prevoutpolygon.topright) d2 = outpolygon.bottomleft.distanceTo(prevoutpolygon.bottomright) if (d1 < EPS) and (d2 < EPS) # we can join this polygon with the one to the left: outpolygon.topleft = prevoutpolygon.topleft outpolygon.leftline = prevoutpolygon.leftline outpolygon.bottomleft = prevoutpolygon.bottomleft newoutpolygonrow.splice newoutpolygonrow.length - 1, 1 newoutpolygonrow.push outpolygon # for(activepolygon in activepolygons) if yindex > 0 # try to match the new polygons against the previous row: prevcontinuedindexes = {} matchedindexes = {} i = 0 while i < newoutpolygonrow.length thispolygon = newoutpolygonrow[i] ii = 0 while ii < prevoutpolygonrow.length unless matchedindexes[ii] # not already processed? # We have a match if the sidelines are equal or if the top coordinates # are on the sidelines of the previous polygon prevpolygon = prevoutpolygonrow[ii] if prevpolygon.bottomleft.distanceTo(thispolygon.topleft) < EPS if prevpolygon.bottomright.distanceTo(thispolygon.topright) < EPS # Yes, the top of this polygon matches the bottom of the previous: matchedindexes[ii] = true # Now check if the joined polygon would remain convex: d1 = thispolygon.leftline.direction().x - prevpolygon.leftline.direction().x d2 = thispolygon.rightline.direction().x - prevpolygon.rightline.direction().x leftlinecontinues = Math.abs(d1) < EPS rightlinecontinues = Math.abs(d2) < EPS leftlineisconvex = leftlinecontinues or (d1 >= 0) rightlineisconvex = rightlinecontinues or (d2 >= 0) if leftlineisconvex and rightlineisconvex # yes, both sides have convex corners: # This polygon will continue the previous polygon thispolygon.outpolygon = prevpolygon.outpolygon thispolygon.leftlinecontinues = leftlinecontinues thispolygon.rightlinecontinues = rightlinecontinues prevcontinuedindexes[ii] = true break ii++ i++ # if(!prevcontinuedindexes[ii]) # for ii # for i ii = 0 while ii < prevoutpolygonrow.length unless prevcontinuedindexes[ii] # polygon ends here # Finish the polygon with the last point(s): prevpolygon = prevoutpolygonrow[ii] prevpolygon.outpolygon.rightpoints.push prevpolygon.bottomright # polygon ends with a horizontal line: prevpolygon.outpolygon.leftpoints.push prevpolygon.bottomleft if prevpolygon.bottomright.distanceTo(prevpolygon.bottomleft) > EPS # reverse the left half so we get a counterclockwise circle: prevpolygon.outpolygon.leftpoints.reverse() points2d = prevpolygon.outpolygon.rightpoints.concat(prevpolygon.outpolygon.leftpoints) vertices3d = [] points2d.map (point2d) -> point3d = orthobasis.to3D(point2d) vertex3d = new Vertex(point3d) vertices3d.push vertex3d polygon = new Polygon(vertices3d, shared, plane) destpolygons.push polygon ii++ # if(yindex > 0) i = 0 while i < newoutpolygonrow.length thispolygon = newoutpolygonrow[i] unless thispolygon.outpolygon # polygon starts here: thispolygon.outpolygon = leftpoints: [] rightpoints: [] thispolygon.outpolygon.leftpoints.push thispolygon.topleft # we have a horizontal line at the top: thispolygon.outpolygon.rightpoints.push thispolygon.topright if thispolygon.topleft.distanceTo(thispolygon.topright) > EPS else # continuation of a previous row thispolygon.outpolygon.leftpoints.push thispolygon.topleft unless thispolygon.leftlinecontinues thispolygon.outpolygon.rightpoints.push thispolygon.topright unless thispolygon.rightlinecontinues i++ prevoutpolygonrow = newoutpolygonrow yindex++ class FuzzyFactory # This class acts as a factory for objects. We can search for an object with approximately # the desired properties (say a rectangle with width 2 and height 1) # The lookupOrCreate() method looks for an existing object (for example it may find an existing rectangle # with width 2.0001 and height 0.999. If no object is found, the user supplied callback is # called, which should generate a new object. The new object is inserted into the database # so it can be found by future lookupOrCreate() calls. constructor : (numdimensions, tolerance) -> # Constructor: # numdimensions: the number of parameters for each object # for example for a 2D rectangle this would be 2 # tolerance: The maximum difference for each parameter allowed to be considered a match lookuptable = [] i = 0 while i < numdimensions lookuptable.push {} i++ @lookuptable = lookuptable @nextElementId = 1 @multiplier = 1.0 / tolerance @objectTable = {} lookupOrCreate: (els, creatorCallback) -> # var obj = f.lookupOrCreate([el1, el2, el3], function(elements) {/* create the new object */}); # Performs a fuzzy lookup of the object with the specified elements. # If found, returns the existing object # If not found, calls the supplied callback function which should create a new object with # the specified properties. This object is inserted in the lookup database. object = undefined key = PI:KEY:<KEY>END_PI(els) if key is null object = creatorCallback(els) key = PI:KEY:<KEY>END_PI @objectTable[key] = object dimension = 0 while dimension < els.length elementLookupTable = @lookuptable[dimension] value = els[dimension] valueMultiplied = value * @multiplier valueQuantized1 = Math.floor(valueMultiplied) valueQuantized2 = Math.ceil(valueMultiplied) FuzzyFactory.insertKey key, elementLookupTable, valueQuantized1 FuzzyFactory.insertKey key, elementLookupTable, valueQuantized2 dimension++ else object = @objectTable[key] object # ----------- PRIVATE METHODS: lookupKey: (els) -> keyset = {} dimension = 0 while dimension < els.length elementLookupTable = @lookuptable[dimension] value = els[dimension] valueQuantized = Math.round(value * @multiplier) valueQuantized += "" if valueQuantized of elementLookupTable if dimension is 0 keyset = elementLookupTable[valueQuantized] else keyset = FuzzyFactory.intersectSets(keyset, elementLookupTable[valueQuantized]) else return null return null if FuzzyFactory.isEmptySet(keyset) dimension++ # return first matching key: for key of keyset return key null lookupKeySetForDimension: (dimension, value) -> result = undefined elementLookupTable = @lookuptable[dimension] valueMultiplied = value * @multiplier valueQuantized = Math.floor(value * @multiplier) if valueQuantized of elementLookupTable result = elementLookupTable[valueQuantized] else result = {} result @insertKey : (key, lookuptable, quantizedvalue) -> if quantizedvalue of lookuptable lookuptable[quantizedvalue][key] = true else newset = {} newset[key] = true lookuptable[quantizedvalue] = newset @isEmptySet : (obj) -> for key of obj return false true @intersectSets : (set1, set2) -> result = {} for key of set1 result[key] = true if key of set2 result @joinSets : (set1, set2) -> result = {} for key of set1 result[key] = true for key of set2 result[key] = true result class FuzzyCSGFactory constructor: -> @vertexfactory = new FuzzyFactory(3, 1e-5) @planefactory = new FuzzyFactory(4, 1e-5) @polygonsharedfactory = {} getPolygonShared: (sourceshared) -> hash = sourceshared.getHash() if hash of @polygonsharedfactory @polygonsharedfactory[hash] else @polygonsharedfactory[hash] = sourceshared sourceshared getVertex: (sourcevertex) -> elements = [sourcevertex.pos._x, sourcevertex.pos._y, sourcevertex.pos._z] result = @vertexfactory.lookupOrCreate(elements, (els) -> sourcevertex ) result getPlane: (sourceplane) -> elements = [sourceplane.normal._x, sourceplane.normal._y, sourceplane.normal._z, sourceplane.w] result = @planefactory.lookupOrCreate(elements, (els) -> sourceplane ) result getPolygon: (sourcepolygon) -> newplane = @getPlane(sourcepolygon.plane) newshared = @getPolygonShared(sourcepolygon.shared) newvertices = (@getVertex vertex for vertex in sourcepolygon.vertices) new Polygon(newvertices, newshared, newplane) getCSG: (sourceCsg) -> #deprecated _this = this newpolygons = sourceCsg.polygons.map((polygon) -> _this.getPolygon polygon ) CSGBase.fromPolygons newpolygons getCSGPolygons: (sourceCsg) -> #returns new polygons based on sourceCSG newpolygons = (@getPolygon polygon for polygon in sourceCsg.polygons) class FuzzyCAGFactory constructor:-> @vertexfactory = new FuzzyFactory(2, 1e-5) getVertex: (sourcevertex) -> elements = [sourcevertex.pos._x, sourcevertex.pos._y] result = @vertexfactory.lookupOrCreate(elements, (els) -> sourcevertex ) result getSide: (sourceside) -> vertex0 = @getVertex(sourceside.vertex0) vertex1 = @getVertex(sourceside.vertex1) new Side(vertex0, vertex1) getCAG: (sourcecag) -> _this = this newsides = sourcecag.sides.map((side) -> _this.getSide side ) CAGBase.fromSides newsides getCAGSides:(sourceCag) -> _this = this newsides = sourceCag.sides.map((side) -> _this.getSide side ) newsides return { "parseOption": parseOption "parseOptions":parseOptions "parseOptionAs3DVector": parseOptionAs3DVector "parseOptionAs2DVector": parseOptionAs2DVector "parseOptionAsFloat": parseOptionAsFloat "parseOptionAsInt": parseOptionAsInt "parseOptionAsBool": parseOptionAsBool "parseOptionAsLocations":parseOptionAsLocations "parseCenter":parseCenter "insertSorted": insertSorted "interpolateBetween2DPointsForY": interpolateBetween2DPointsForY "reTesselateCoplanarPolygons": reTesselateCoplanarPolygons "FuzzyFactory": FuzzyFactory "FuzzyCSGFactory": FuzzyCSGFactory "FuzzyCAGFactory": FuzzyCAGFactory "merge":merge "extend":extend }
[ { "context": "# Copyright© 2017 Merck Sharp & Dohme Corp. a subsidiary of Merck & Co., Inc., ", "end": 29, "score": 0.999882698059082, "start": 18, "tag": "NAME", "value": "Merck Sharp" } ]
app/assets/javascripts/_scheduling_options.js.coffee
Merck/Linea
0
# Copyright© 2017 Merck Sharp & Dohme Corp. a subsidiary of Merck & Co., Inc., Kenilworth, NJ, USA. 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. $ -> sections = [ { button: $('#once_radio_button') group: $() }, { button: $('#every_radio_button') group: $('#every_group') }, { button: $('#cron_radio_button') group: $('#cron_group') } ] for section in sections do (section) -> section.button.click -> s.group.hide() for s in sections section.group.show() unless section.button.is(':checked') section.group.hide()
137795
# Copyright© 2017 <NAME> & Dohme Corp. a subsidiary of Merck & Co., Inc., Kenilworth, NJ, USA. 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. $ -> sections = [ { button: $('#once_radio_button') group: $() }, { button: $('#every_radio_button') group: $('#every_group') }, { button: $('#cron_radio_button') group: $('#cron_group') } ] for section in sections do (section) -> section.button.click -> s.group.hide() for s in sections section.group.show() unless section.button.is(':checked') section.group.hide()
true
# Copyright© 2017 PI:NAME:<NAME>END_PI & Dohme Corp. a subsidiary of Merck & Co., Inc., Kenilworth, NJ, USA. 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. $ -> sections = [ { button: $('#once_radio_button') group: $() }, { button: $('#every_radio_button') group: $('#every_group') }, { button: $('#cron_radio_button') group: $('#cron_group') } ] for section in sections do (section) -> section.button.click -> s.group.hide() for s in sections section.group.show() unless section.button.is(':checked') section.group.hide()
[ { "context": " we need something else?\n input =\n text: \"lari\"\n offset: 42\n length: 4\n options: ", "end": 737, "score": 0.9711955785751343, "start": 733, "tag": "NAME", "value": "lari" }, { "context": "2\n length: 4\n options: [\n text: \...
spec/config-types/completion-spec.coffee
ldegen/irma
1
describe "A Completion", -> Completion =require '../../src/config-types/completion' Suggest = require '../../src/config-types/suggest' c=undefined beforeEach -> c = new Completion field:"blah" c.init() it "complains if you try to instantiate it without `new`", -> mistake = -> c = Completion field:"blah" expect(mistake).to.throw /new/ it "is a special kind of Suggestion", -> expect(c).to.be.an.instanceof Suggest it "knows how to ask ES for suggestions", -> expect(c.build q:"onkel").to.eql text:"onkel" completion: field: "blah" it "knows how to transform suggestions returned by ES", -> #TODO: identity for now -- do we need something else? input = text: "lari" offset: 42 length: 4 options: [ text: "Lari Fari Mogelzahn" score: 9001 payload: foo:"bar", id:2 ] expect(c.transform input).to.eql input
62082
describe "A Completion", -> Completion =require '../../src/config-types/completion' Suggest = require '../../src/config-types/suggest' c=undefined beforeEach -> c = new Completion field:"blah" c.init() it "complains if you try to instantiate it without `new`", -> mistake = -> c = Completion field:"blah" expect(mistake).to.throw /new/ it "is a special kind of Suggestion", -> expect(c).to.be.an.instanceof Suggest it "knows how to ask ES for suggestions", -> expect(c.build q:"onkel").to.eql text:"onkel" completion: field: "blah" it "knows how to transform suggestions returned by ES", -> #TODO: identity for now -- do we need something else? input = text: "<NAME>" offset: 42 length: 4 options: [ text: "<NAME>" score: 9001 payload: foo:"bar", id:2 ] expect(c.transform input).to.eql input
true
describe "A Completion", -> Completion =require '../../src/config-types/completion' Suggest = require '../../src/config-types/suggest' c=undefined beforeEach -> c = new Completion field:"blah" c.init() it "complains if you try to instantiate it without `new`", -> mistake = -> c = Completion field:"blah" expect(mistake).to.throw /new/ it "is a special kind of Suggestion", -> expect(c).to.be.an.instanceof Suggest it "knows how to ask ES for suggestions", -> expect(c.build q:"onkel").to.eql text:"onkel" completion: field: "blah" it "knows how to transform suggestions returned by ES", -> #TODO: identity for now -- do we need something else? input = text: "PI:NAME:<NAME>END_PI" offset: 42 length: 4 options: [ text: "PI:NAME:<NAME>END_PI" score: 9001 payload: foo:"bar", id:2 ] expect(c.transform input).to.eql input
[ { "context": "requestAnimationFrame, Resize & Update\n# @author : David Ronai / @Makio64 / makiopolis.com\n#\n\nSignal \t= require(", "end": 78, "score": 0.9998584985733032, "start": 67, "tag": "NAME", "value": "David Ronai" }, { "context": "onFrame, Resize & Update\n# @author : Davi...
src/coffee/makio/core/Stage.coffee
Makio64/pizzaparty_vj
1
# # Wrapper for requestAnimationFrame, Resize & Update # @author : David Ronai / @Makio64 / makiopolis.com # Signal = require("signals") Stats = require("stats.js") #---------------------------------------------------------- Class Stage class Stage @skipLimit = 32 @skipActivated = true @lastTime = 0 @pause = false @onResize = new Signal() @onUpdate = new Signal() @onBlur = new Signal() @onFocus = new Signal() @width = window.innerWidth @height = window.innerHeight @init:()-> @pause = false window.onresize = ()=> @width = window.innerWidth @height = window.innerHeight @onResize.dispatch() return @lastTime = performance.now() requestAnimationFrame( @update ) @stats = new Stats() document.body.appendChild(@stats.domElement) return @update:()=> t = performance.now() dt = t - @lastTime @lastTime = t requestAnimationFrame( @update ) if @skipActivated && dt > @skipLimit then return if @pause then return @stats.begin() @onUpdate.dispatch(dt) @stats.end() return @init() module.exports = Stage
220487
# # Wrapper for requestAnimationFrame, Resize & Update # @author : <NAME> / @Makio64 / makiop<EMAIL>.<EMAIL> # Signal = require("signals") Stats = require("stats.js") #---------------------------------------------------------- Class Stage class Stage @skipLimit = 32 @skipActivated = true @lastTime = 0 @pause = false @onResize = new Signal() @onUpdate = new Signal() @onBlur = new Signal() @onFocus = new Signal() @width = window.innerWidth @height = window.innerHeight @init:()-> @pause = false window.onresize = ()=> @width = window.innerWidth @height = window.innerHeight @onResize.dispatch() return @lastTime = performance.now() requestAnimationFrame( @update ) @stats = new Stats() document.body.appendChild(@stats.domElement) return @update:()=> t = performance.now() dt = t - @lastTime @lastTime = t requestAnimationFrame( @update ) if @skipActivated && dt > @skipLimit then return if @pause then return @stats.begin() @onUpdate.dispatch(dt) @stats.end() return @init() module.exports = Stage
true
# # Wrapper for requestAnimationFrame, Resize & Update # @author : PI:NAME:<NAME>END_PI / @Makio64 / makiopPI:EMAIL:<EMAIL>END_PI.PI:EMAIL:<EMAIL>END_PI # Signal = require("signals") Stats = require("stats.js") #---------------------------------------------------------- Class Stage class Stage @skipLimit = 32 @skipActivated = true @lastTime = 0 @pause = false @onResize = new Signal() @onUpdate = new Signal() @onBlur = new Signal() @onFocus = new Signal() @width = window.innerWidth @height = window.innerHeight @init:()-> @pause = false window.onresize = ()=> @width = window.innerWidth @height = window.innerHeight @onResize.dispatch() return @lastTime = performance.now() requestAnimationFrame( @update ) @stats = new Stats() document.body.appendChild(@stats.domElement) return @update:()=> t = performance.now() dt = t - @lastTime @lastTime = t requestAnimationFrame( @update ) if @skipActivated && dt > @skipLimit then return if @pause then return @stats.begin() @onUpdate.dispatch(dt) @stats.end() return @init() module.exports = Stage
[ { "context": " + '/setPassword'\n data:\n oldPassword: oldPass\n newPassword: newPass\n .then =>\n @", "end": 2889, "score": 0.9981525540351868, "start": 2882, "tag": "PASSWORD", "value": "oldPass" }, { "context": "\n oldPassword: oldPass\n ne...
app/models/user.coffee
micirclek/cki-portal
0
AppModel = require('models/appmodel') class Position extends AppModel urlRoot: '/1/users/position' parse: (data) -> if data.start? data.start = new Date(data.start) if data.end? data.end = new Date(data.end) super defaults: start: null end: null level: null idDistrict: null idClub: null entityName: null # TODO this should eventually get handled by a magic cache getLevelId: (level = @get('level')) -> if /club/i.test(level) return @get('idClub') else if /district/i.test(level) return @get('idDistrict') else return null class PositionCollection extends Backbone.Collection model: Position getCurrent: -> positions = @filter (position) -> # have not yet started in your position if position.has('start') && position.get('start') > Date.now() return false # already done with your term if position.has('end') && position.get('end') < Date.now() return false return true return new PositionCollection(positions) Position.Collection = PositionCollection class User extends AppModel typeName: 'User' urlRoot: '/1/users' parse: (data) -> @positions.set(data.positions, parse: true) delete data.positions super toJSON: -> data = super data.positions = @positions.toJSON() return data constructor: -> @positions = new PositionCollection() super hasAccess: (model, access = 'read') -> positions = @positions.getCurrent() if model.typeName == 'Club' if access == 'view' return positions.any (position) => (position.get('level') == 'club' && position.id == model.id) || (position.get('level') == 'district' && position.get('idDistrict') == model.get('idDistrict')) || (position.get('level') == 'international') else if access == 'edit' return positions.any (position) => position.get('level') == 'club' && position.get('idClub') == model.id else if access == 'manage' return positions.any (position) => position.get('level') == 'district' && position.get('idDistrict') == model.get('idDistrict') else if model.typeName == 'District' if access == 'view' return positions.any (position) => (position.get('level') == 'district' && position.get('idDistrict') == model.id) || (position.get('level') == 'international') else if access == 'edit' return positions.any (position) => position.get('level') == 'district' && position.get('idDistrict') == model.id else if access == 'manage' return positions.any (position) => position.get('level') == 'international' setPassword: (oldPass, newPass) -> Backbone.ajax type: 'POST' url: @url() + '/setPassword' data: oldPassword: oldPass newPassword: newPass .then => @set(loginTypes: _.uniq(_.union(@get('loginTypes'), ['password']))) defaults: _id: null name: '' email: '' admin: false class UserCollection extends Backbone.Collection model: User User.Collection = UserCollection module.exports = User
129458
AppModel = require('models/appmodel') class Position extends AppModel urlRoot: '/1/users/position' parse: (data) -> if data.start? data.start = new Date(data.start) if data.end? data.end = new Date(data.end) super defaults: start: null end: null level: null idDistrict: null idClub: null entityName: null # TODO this should eventually get handled by a magic cache getLevelId: (level = @get('level')) -> if /club/i.test(level) return @get('idClub') else if /district/i.test(level) return @get('idDistrict') else return null class PositionCollection extends Backbone.Collection model: Position getCurrent: -> positions = @filter (position) -> # have not yet started in your position if position.has('start') && position.get('start') > Date.now() return false # already done with your term if position.has('end') && position.get('end') < Date.now() return false return true return new PositionCollection(positions) Position.Collection = PositionCollection class User extends AppModel typeName: 'User' urlRoot: '/1/users' parse: (data) -> @positions.set(data.positions, parse: true) delete data.positions super toJSON: -> data = super data.positions = @positions.toJSON() return data constructor: -> @positions = new PositionCollection() super hasAccess: (model, access = 'read') -> positions = @positions.getCurrent() if model.typeName == 'Club' if access == 'view' return positions.any (position) => (position.get('level') == 'club' && position.id == model.id) || (position.get('level') == 'district' && position.get('idDistrict') == model.get('idDistrict')) || (position.get('level') == 'international') else if access == 'edit' return positions.any (position) => position.get('level') == 'club' && position.get('idClub') == model.id else if access == 'manage' return positions.any (position) => position.get('level') == 'district' && position.get('idDistrict') == model.get('idDistrict') else if model.typeName == 'District' if access == 'view' return positions.any (position) => (position.get('level') == 'district' && position.get('idDistrict') == model.id) || (position.get('level') == 'international') else if access == 'edit' return positions.any (position) => position.get('level') == 'district' && position.get('idDistrict') == model.id else if access == 'manage' return positions.any (position) => position.get('level') == 'international' setPassword: (oldPass, newPass) -> Backbone.ajax type: 'POST' url: @url() + '/setPassword' data: oldPassword: <PASSWORD> newPassword: <PASSWORD> .then => @set(loginTypes: _.uniq(_.union(@get('loginTypes'), ['password']))) defaults: _id: null name: '' email: '' admin: false class UserCollection extends Backbone.Collection model: User User.Collection = UserCollection module.exports = User
true
AppModel = require('models/appmodel') class Position extends AppModel urlRoot: '/1/users/position' parse: (data) -> if data.start? data.start = new Date(data.start) if data.end? data.end = new Date(data.end) super defaults: start: null end: null level: null idDistrict: null idClub: null entityName: null # TODO this should eventually get handled by a magic cache getLevelId: (level = @get('level')) -> if /club/i.test(level) return @get('idClub') else if /district/i.test(level) return @get('idDistrict') else return null class PositionCollection extends Backbone.Collection model: Position getCurrent: -> positions = @filter (position) -> # have not yet started in your position if position.has('start') && position.get('start') > Date.now() return false # already done with your term if position.has('end') && position.get('end') < Date.now() return false return true return new PositionCollection(positions) Position.Collection = PositionCollection class User extends AppModel typeName: 'User' urlRoot: '/1/users' parse: (data) -> @positions.set(data.positions, parse: true) delete data.positions super toJSON: -> data = super data.positions = @positions.toJSON() return data constructor: -> @positions = new PositionCollection() super hasAccess: (model, access = 'read') -> positions = @positions.getCurrent() if model.typeName == 'Club' if access == 'view' return positions.any (position) => (position.get('level') == 'club' && position.id == model.id) || (position.get('level') == 'district' && position.get('idDistrict') == model.get('idDistrict')) || (position.get('level') == 'international') else if access == 'edit' return positions.any (position) => position.get('level') == 'club' && position.get('idClub') == model.id else if access == 'manage' return positions.any (position) => position.get('level') == 'district' && position.get('idDistrict') == model.get('idDistrict') else if model.typeName == 'District' if access == 'view' return positions.any (position) => (position.get('level') == 'district' && position.get('idDistrict') == model.id) || (position.get('level') == 'international') else if access == 'edit' return positions.any (position) => position.get('level') == 'district' && position.get('idDistrict') == model.id else if access == 'manage' return positions.any (position) => position.get('level') == 'international' setPassword: (oldPass, newPass) -> Backbone.ajax type: 'POST' url: @url() + '/setPassword' data: oldPassword: PI:PASSWORD:<PASSWORD>END_PI newPassword: PI:PASSWORD:<PASSWORD>END_PI .then => @set(loginTypes: _.uniq(_.union(@get('loginTypes'), ['password']))) defaults: _id: null name: '' email: '' admin: false class UserCollection extends Backbone.Collection model: User User.Collection = UserCollection module.exports = User
[ { "context": "gin for jQuery\n\nVersion 1.0\n\nhttps://github.com/thrustlabs/jquery-addressparser\n\nCopyright 2013 Jason Doucet", "end": 105, "score": 0.7427881956100464, "start": 97, "tag": "USERNAME", "value": "rustlabs" }, { "context": "om/thrustlabs/jquery-addressparser\n\nCopyr...
src/jquery-addressparser.coffee
thrustlabs/jquery-addressparser
1
### jquery-addressparser: an address parser plugin for jQuery Version 1.0 https://github.com/thrustlabs/jquery-addressparser Copyright 2013 Jason Doucette, Thrust Labs 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. ### # Reference jQuery $ = jQuery $.fn.extend addressparser: (options) -> self = $.fn.addressparser opts = $.extend {}, self.default_options, options $(this).each (i, el) -> self.init el, opts $.extend $.fn.addressparser, opts: {} default_options: {} init: (el, opts) -> self.opts = opts $(el).bind('input propertychange', -> parser = new AddressParser parser.parse($(this).val()) if opts.name $(opts.name).val(parser.name) if opts.address $(opts.address).val(parser.address) if opts.city $(opts.city).val(parser.city) if opts.province $(opts.province).val(parser.province) if opts.postal $(opts.postal).val(parser.postal) if opts.country $(opts.country).val(parser.country) if opts.phone $(opts.phone).val(parser.phone) if opts.email $(opts.email).val(parser.email) if opts.website $(opts.website).val(parser.website) )
51612
### jquery-addressparser: an address parser plugin for jQuery Version 1.0 https://github.com/thrustlabs/jquery-addressparser Copyright 2013 <NAME>, Thrust Labs 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. ### # Reference jQuery $ = jQuery $.fn.extend addressparser: (options) -> self = $.fn.addressparser opts = $.extend {}, self.default_options, options $(this).each (i, el) -> self.init el, opts $.extend $.fn.addressparser, opts: {} default_options: {} init: (el, opts) -> self.opts = opts $(el).bind('input propertychange', -> parser = new AddressParser parser.parse($(this).val()) if opts.name $(opts.name).val(parser.name) if opts.address $(opts.address).val(parser.address) if opts.city $(opts.city).val(parser.city) if opts.province $(opts.province).val(parser.province) if opts.postal $(opts.postal).val(parser.postal) if opts.country $(opts.country).val(parser.country) if opts.phone $(opts.phone).val(parser.phone) if opts.email $(opts.email).val(parser.email) if opts.website $(opts.website).val(parser.website) )
true
### jquery-addressparser: an address parser plugin for jQuery Version 1.0 https://github.com/thrustlabs/jquery-addressparser Copyright 2013 PI:NAME:<NAME>END_PI, Thrust Labs 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. ### # Reference jQuery $ = jQuery $.fn.extend addressparser: (options) -> self = $.fn.addressparser opts = $.extend {}, self.default_options, options $(this).each (i, el) -> self.init el, opts $.extend $.fn.addressparser, opts: {} default_options: {} init: (el, opts) -> self.opts = opts $(el).bind('input propertychange', -> parser = new AddressParser parser.parse($(this).val()) if opts.name $(opts.name).val(parser.name) if opts.address $(opts.address).val(parser.address) if opts.city $(opts.city).val(parser.city) if opts.province $(opts.province).val(parser.province) if opts.postal $(opts.postal).val(parser.postal) if opts.country $(opts.country).val(parser.country) if opts.phone $(opts.phone).val(parser.phone) if opts.email $(opts.email).val(parser.email) if opts.website $(opts.website).val(parser.website) )
[ { "context": "module.exports = [\n name: \"Inari Hanzo\"\n admin: true\n group: \"cyberia\"\n,\n name: \"Cand", "end": 39, "score": 0.9998323321342468, "start": 28, "tag": "NAME", "value": "Inari Hanzo" }, { "context": "anzo\"\n admin: true\n group: \"cyberia\"\n,\n name: \"Ca...
db/fixtures/users.coffee
woochi/cyberia
0
module.exports = [ name: "Inari Hanzo" admin: true group: "cyberia" , name: "Candyman" admin: true group: "cyberia" , name: "Valya Kova" admin: true group: "cyberia" , name: "Musta Leski" admin: true group: "cyberia" , name: "Mean Cat" group: "cyberia" , name: "Rafflesia" group: "cyberia" , name: "Mahatala" group: "cyberia" , name: "Jata" group: "cyberia" , name: "Twilight" group: "cyberia" , name: "Aikane" group: "cyberia" , name: "Horse" group: "cyberia" , name: "Isis" group: "cyberia" , name: "Leijona" group: "cyberia" , name: "Gruesom Max" group: "cyberia" , name: "Control" group: "cyberia" , name: "Fist" group: "cyberia" , name: "Samarialainen" group: "cyberia" , name: "Chrystal" group: "cyberia" , name: "Queen Batsheba" , name: "Bane" , name: "Dave Whindam" , name: "Antoine Dubois" , name: "DeadEye" , name: "Masada" , name: "Dixie" , name: "Seicho" , name: "Typhon" , name: "Alexios" , name: "Flash" , name: "Sineater" , name: "Metalmouth" , name: "Lilith" , name: "Aries Smith" , name: "Kestral Smith" , name: "Jimbo" , name: "Vixen" , name: "Cobra" , name: "Scoop" group: "media" , name: "Mac" group: "media" , name: "Lobo" group: "media" , name: "Michael" group: "archangels" , name: "Uriel" group: "archangels" , name: "Azrael" group: "archangels" , name: "Stim" group: "dreadnok" , name: "Warlock" group: "dreadnok" , name: "Headbanger" group: "dreadnok" , name: "Red Riding Hood" , name: "Moonshine" ]
144331
module.exports = [ name: "<NAME>" admin: true group: "cyberia" , name: "<NAME>" admin: true group: "cyberia" , name: "<NAME>" admin: true group: "cyberia" , name: "<NAME>" admin: true group: "cyberia" , name: "<NAME>" group: "cyberia" , name: "<NAME>" group: "cyberia" , name: "<NAME>" group: "cyberia" , name: "<NAME>" group: "cyberia" , name: "<NAME>" group: "cyberia" , name: "<NAME>" group: "cyberia" , name: "<NAME>" group: "cyberia" , name: "<NAME>" group: "cyberia" , name: "<NAME>" group: "cyberia" , name: "<NAME>" group: "cyberia" , name: "<NAME>" group: "cyberia" , name: "<NAME>" group: "cyberia" , name: "<NAME>" group: "cyberia" , name: "<NAME>" group: "cyberia" , name: "<NAME>" , name: "<NAME>" , name: "<NAME>" , name: "<NAME>" , name: "<NAME>" , name: "<NAME>" , name: "<NAME>" , name: "<NAME>" , name: "<NAME>" , name: "<NAME>" , name: "<NAME>" , name: "<NAME>" , name: "<NAME>" , name: "<NAME>" , name: "<NAME>" , name: "<NAME>" , name: "<NAME>" , name: "<NAME>" , name: "<NAME>" , name: "<NAME>" group: "media" , name: "<NAME>" group: "media" , name: "<NAME>" group: "media" , name: "<NAME>" group: "archangels" , name: "<NAME>" group: "archangels" , name: "<NAME>" group: "archangels" , name: "<NAME>" group: "dreadnok" , name: "<NAME>" group: "dreadnok" , name: "<NAME>" group: "dreadnok" , name: "<NAME>" , name: "<NAME>" ]
true
module.exports = [ name: "PI:NAME:<NAME>END_PI" admin: true group: "cyberia" , name: "PI:NAME:<NAME>END_PI" admin: true group: "cyberia" , name: "PI:NAME:<NAME>END_PI" admin: true group: "cyberia" , name: "PI:NAME:<NAME>END_PI" admin: true group: "cyberia" , name: "PI:NAME:<NAME>END_PI" group: "cyberia" , name: "PI:NAME:<NAME>END_PI" group: "cyberia" , name: "PI:NAME:<NAME>END_PI" group: "cyberia" , name: "PI:NAME:<NAME>END_PI" group: "cyberia" , name: "PI:NAME:<NAME>END_PI" group: "cyberia" , name: "PI:NAME:<NAME>END_PI" group: "cyberia" , name: "PI:NAME:<NAME>END_PI" group: "cyberia" , name: "PI:NAME:<NAME>END_PI" group: "cyberia" , name: "PI:NAME:<NAME>END_PI" group: "cyberia" , name: "PI:NAME:<NAME>END_PI" group: "cyberia" , name: "PI:NAME:<NAME>END_PI" group: "cyberia" , name: "PI:NAME:<NAME>END_PI" group: "cyberia" , name: "PI:NAME:<NAME>END_PI" group: "cyberia" , name: "PI:NAME:<NAME>END_PI" group: "cyberia" , 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" , 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" , 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" , 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" group: "media" , name: "PI:NAME:<NAME>END_PI" group: "media" , name: "PI:NAME:<NAME>END_PI" group: "media" , name: "PI:NAME:<NAME>END_PI" group: "archangels" , name: "PI:NAME:<NAME>END_PI" group: "archangels" , name: "PI:NAME:<NAME>END_PI" group: "archangels" , name: "PI:NAME:<NAME>END_PI" group: "dreadnok" , name: "PI:NAME:<NAME>END_PI" group: "dreadnok" , name: "PI:NAME:<NAME>END_PI" group: "dreadnok" , name: "PI:NAME:<NAME>END_PI" , name: "PI:NAME:<NAME>END_PI" ]
[ { "context": "#\n# Project's main unit\n#\n# Copyright (C) 2012 Nikolay Nemshilov\n#\nclass Game extends Element\n\n constructor: (siz", "end": 64, "score": 0.9998804926872253, "start": 47, "tag": "NAME", "value": "Nikolay Nemshilov" } ]
E006/src/game.coffee
lovely-io/lovely.io-show
1
# # Project's main unit # # Copyright (C) 2012 Nikolay Nemshilov # class Game extends Element constructor: (size_x, size_y, density)-> super 'div', class: 'mines-game' @append( @timer = new Timer(), @smile = new Smile(), @stats = new Stats(), @field = new Field(size_x, size_y, density)) @on reset: @reset mark: @mark fail: @fail open: @open done: @done @reset() return @ reset: -> @smile.reset() @timer.reset() @field.reset() @stats.reset() @mark() # protected fail: -> @timer.stop() @smile.fail() @field.blow() done: -> @timer.stop() @smile.done() mark: -> @stats.update( @field.marked_cells, @field.rigged_cells) open: -> @smile.blink() @timer.start() unless @timer.active
97067
# # Project's main unit # # Copyright (C) 2012 <NAME> # class Game extends Element constructor: (size_x, size_y, density)-> super 'div', class: 'mines-game' @append( @timer = new Timer(), @smile = new Smile(), @stats = new Stats(), @field = new Field(size_x, size_y, density)) @on reset: @reset mark: @mark fail: @fail open: @open done: @done @reset() return @ reset: -> @smile.reset() @timer.reset() @field.reset() @stats.reset() @mark() # protected fail: -> @timer.stop() @smile.fail() @field.blow() done: -> @timer.stop() @smile.done() mark: -> @stats.update( @field.marked_cells, @field.rigged_cells) open: -> @smile.blink() @timer.start() unless @timer.active
true
# # Project's main unit # # Copyright (C) 2012 PI:NAME:<NAME>END_PI # class Game extends Element constructor: (size_x, size_y, density)-> super 'div', class: 'mines-game' @append( @timer = new Timer(), @smile = new Smile(), @stats = new Stats(), @field = new Field(size_x, size_y, density)) @on reset: @reset mark: @mark fail: @fail open: @open done: @done @reset() return @ reset: -> @smile.reset() @timer.reset() @field.reset() @stats.reset() @mark() # protected fail: -> @timer.stop() @smile.fail() @field.blow() done: -> @timer.stop() @smile.done() mark: -> @stats.update( @field.marked_cells, @field.rigged_cells) open: -> @smile.blink() @timer.start() unless @timer.active
[ { "context": " }\n ],\n 'api': {\n 'key': 'apikey',\n 'url': 'http://localhost:2228/api'\n ", "end": 876, "score": 0.9082878828048706, "start": 870, "tag": "KEY", "value": "apikey" }, { "context": " access logs style\n time = client.getTimeOf('1...
test/client.coffee
xianhuazhou/elog
1
elog = require('../lib/elog.coffee').elog fs = require 'fs' path = require 'path' express = require 'express' describe 'Client', -> describe 'functions', -> file1 = path.join(__dirname, "data", "test1.log") file2 = path.join(__dirname, "data", "test2.log") config = { 'apps': [ { 'name': 'app name', 'file': file1, 'rules': { "include": [ ["error", 'LOG_ERROR'], ["info", 'LOG_INFO'] ], "exclude": [] } }, { 'name': 'another app', 'file': file2, 'rules': { "include": [ [["mysql error", "i"], 'LOG_ERROR'], ["php error", 'LOG_ERROR'] ], "exclude": ["ftp", "http"] } } ], 'api': { 'key': 'apikey', 'url': 'http://localhost:2228/api' } } beforeEach(-> data = "[2012-03-04 11:11:22] error, message\n" data += "[2012-03-05 10:33:22] notice, message\n" data += "[2012-03-06 11:22:22] error, message\n" data += "[2012-03-07 03:10:29] info, message" fs.writeFileSync(file1, data, "utf-8") data = "[2012-03-04 11:11:22] mysql ERROR, message\n" data += "[2012-03-04 11:11:22] mysql error with ftp protocal\n" fs.writeFileSync(file2, data, "utf-8") ) afterEach(-> fs.unlinkSync file1 fs.unlinkSync file2 ) it 'should read a line from a specified position', -> line_one = "[2012-03-04 11:11:22] error, message" line_two = "[2012-03-05 10:33:22] notice, message" client = new elog.client(config.apps[0]) client.openFile() line = client.readLineSync 0 line.should.equal line_one line = client.readLineSync line_one.length + 1 line.should.equal line_two it 'can process lines with callback from mclient', -> client = new elog.client(config.apps[0]) mclient = new elog.mclient(config, elog, null, null) numberOfLines = client.process (line) -> mclient.filterLine line, config.apps[0].rules numberOfLines.should.equal 3 client = new elog.client(config.apps[1]) numberOfLines = client.process (line) -> mclient.filterLine line, config.apps[1].rules numberOfLines.should.equal 1 it 'can do a real process', -> client = new elog.client(config.apps[0], config.api) app = express() app.use express.bodyParser() app.post '/api/apikey', (req, res) -> log = JSON.parse(req.body.log) log.app.should.equal 'app name' log.time.should.equal (new Date('2012-03-07 03:10:29')).getTime() log.msg.should.equal '[2012-03-07 03:10:29] info, message' log.level.should.equal elog.LOG_INFO res.send 'OK' app.listen 2228, 'localhost' client.process (line) -> if /info/.test(line) elog.LOG_INFO else null it 'can get time from a line', -> client = new elog.client(config.apps[0]) # php error logs style time = client.getTimeOf("[2012-03-04 11:11:22] error, message") (new Date('2012-03-04 11:11:22')).getTime().should.equal time # nginx error logs style time = client.getTimeOf("2012-03-04 11:11:22 [error], message") (new Date('2012-03-04 11:11:22')).getTime().should.equal time # nginx & apache access logs style time = client.getTimeOf('127.0.0.1 - - [27/Aug/2012:11:05:58 +0800] "GET / HTTP/1.1"') (new Date('27/Aug/2012 11:05:58 +0800')).getTime().should.equal time
161946
elog = require('../lib/elog.coffee').elog fs = require 'fs' path = require 'path' express = require 'express' describe 'Client', -> describe 'functions', -> file1 = path.join(__dirname, "data", "test1.log") file2 = path.join(__dirname, "data", "test2.log") config = { 'apps': [ { 'name': 'app name', 'file': file1, 'rules': { "include": [ ["error", 'LOG_ERROR'], ["info", 'LOG_INFO'] ], "exclude": [] } }, { 'name': 'another app', 'file': file2, 'rules': { "include": [ [["mysql error", "i"], 'LOG_ERROR'], ["php error", 'LOG_ERROR'] ], "exclude": ["ftp", "http"] } } ], 'api': { 'key': '<KEY>', 'url': 'http://localhost:2228/api' } } beforeEach(-> data = "[2012-03-04 11:11:22] error, message\n" data += "[2012-03-05 10:33:22] notice, message\n" data += "[2012-03-06 11:22:22] error, message\n" data += "[2012-03-07 03:10:29] info, message" fs.writeFileSync(file1, data, "utf-8") data = "[2012-03-04 11:11:22] mysql ERROR, message\n" data += "[2012-03-04 11:11:22] mysql error with ftp protocal\n" fs.writeFileSync(file2, data, "utf-8") ) afterEach(-> fs.unlinkSync file1 fs.unlinkSync file2 ) it 'should read a line from a specified position', -> line_one = "[2012-03-04 11:11:22] error, message" line_two = "[2012-03-05 10:33:22] notice, message" client = new elog.client(config.apps[0]) client.openFile() line = client.readLineSync 0 line.should.equal line_one line = client.readLineSync line_one.length + 1 line.should.equal line_two it 'can process lines with callback from mclient', -> client = new elog.client(config.apps[0]) mclient = new elog.mclient(config, elog, null, null) numberOfLines = client.process (line) -> mclient.filterLine line, config.apps[0].rules numberOfLines.should.equal 3 client = new elog.client(config.apps[1]) numberOfLines = client.process (line) -> mclient.filterLine line, config.apps[1].rules numberOfLines.should.equal 1 it 'can do a real process', -> client = new elog.client(config.apps[0], config.api) app = express() app.use express.bodyParser() app.post '/api/apikey', (req, res) -> log = JSON.parse(req.body.log) log.app.should.equal 'app name' log.time.should.equal (new Date('2012-03-07 03:10:29')).getTime() log.msg.should.equal '[2012-03-07 03:10:29] info, message' log.level.should.equal elog.LOG_INFO res.send 'OK' app.listen 2228, 'localhost' client.process (line) -> if /info/.test(line) elog.LOG_INFO else null it 'can get time from a line', -> client = new elog.client(config.apps[0]) # php error logs style time = client.getTimeOf("[2012-03-04 11:11:22] error, message") (new Date('2012-03-04 11:11:22')).getTime().should.equal time # nginx error logs style time = client.getTimeOf("2012-03-04 11:11:22 [error], message") (new Date('2012-03-04 11:11:22')).getTime().should.equal time # nginx & apache access logs style time = client.getTimeOf('127.0.0.1 - - [27/Aug/2012:11:05:58 +0800] "GET / HTTP/1.1"') (new Date('27/Aug/2012 11:05:58 +0800')).getTime().should.equal time
true
elog = require('../lib/elog.coffee').elog fs = require 'fs' path = require 'path' express = require 'express' describe 'Client', -> describe 'functions', -> file1 = path.join(__dirname, "data", "test1.log") file2 = path.join(__dirname, "data", "test2.log") config = { 'apps': [ { 'name': 'app name', 'file': file1, 'rules': { "include": [ ["error", 'LOG_ERROR'], ["info", 'LOG_INFO'] ], "exclude": [] } }, { 'name': 'another app', 'file': file2, 'rules': { "include": [ [["mysql error", "i"], 'LOG_ERROR'], ["php error", 'LOG_ERROR'] ], "exclude": ["ftp", "http"] } } ], 'api': { 'key': 'PI:KEY:<KEY>END_PI', 'url': 'http://localhost:2228/api' } } beforeEach(-> data = "[2012-03-04 11:11:22] error, message\n" data += "[2012-03-05 10:33:22] notice, message\n" data += "[2012-03-06 11:22:22] error, message\n" data += "[2012-03-07 03:10:29] info, message" fs.writeFileSync(file1, data, "utf-8") data = "[2012-03-04 11:11:22] mysql ERROR, message\n" data += "[2012-03-04 11:11:22] mysql error with ftp protocal\n" fs.writeFileSync(file2, data, "utf-8") ) afterEach(-> fs.unlinkSync file1 fs.unlinkSync file2 ) it 'should read a line from a specified position', -> line_one = "[2012-03-04 11:11:22] error, message" line_two = "[2012-03-05 10:33:22] notice, message" client = new elog.client(config.apps[0]) client.openFile() line = client.readLineSync 0 line.should.equal line_one line = client.readLineSync line_one.length + 1 line.should.equal line_two it 'can process lines with callback from mclient', -> client = new elog.client(config.apps[0]) mclient = new elog.mclient(config, elog, null, null) numberOfLines = client.process (line) -> mclient.filterLine line, config.apps[0].rules numberOfLines.should.equal 3 client = new elog.client(config.apps[1]) numberOfLines = client.process (line) -> mclient.filterLine line, config.apps[1].rules numberOfLines.should.equal 1 it 'can do a real process', -> client = new elog.client(config.apps[0], config.api) app = express() app.use express.bodyParser() app.post '/api/apikey', (req, res) -> log = JSON.parse(req.body.log) log.app.should.equal 'app name' log.time.should.equal (new Date('2012-03-07 03:10:29')).getTime() log.msg.should.equal '[2012-03-07 03:10:29] info, message' log.level.should.equal elog.LOG_INFO res.send 'OK' app.listen 2228, 'localhost' client.process (line) -> if /info/.test(line) elog.LOG_INFO else null it 'can get time from a line', -> client = new elog.client(config.apps[0]) # php error logs style time = client.getTimeOf("[2012-03-04 11:11:22] error, message") (new Date('2012-03-04 11:11:22')).getTime().should.equal time # nginx error logs style time = client.getTimeOf("2012-03-04 11:11:22 [error], message") (new Date('2012-03-04 11:11:22')).getTime().should.equal time # nginx & apache access logs style time = client.getTimeOf('127.0.0.1 - - [27/Aug/2012:11:05:58 +0800] "GET / HTTP/1.1"') (new Date('27/Aug/2012 11:05:58 +0800')).getTime().should.equal time
[ { "context": "nks to the\n# exellent [fibers](https://github.com/laverdet/node-fibers) library.\n#\n# ### Enabling synchronou", "end": 1018, "score": 0.9995959401130676, "start": 1010, "tag": "USERNAME", "value": "laverdet" }, { "context": "ve name: 'Zeratul'\n assert units.first(na...
examples/synchronous.coffee
wanbok/mongo-model
1
# [Model](model.html) supports two modes - asynchronous and synchronous. # # - Asynchronous mode - it's just usual Node.JS mode, with plain JavaScript and Callbacks. # - Synchronous mode is optional and experimental it also depends on the `fibers` library. # # In this example we'll discower why You may need synchronous mode and how to use it. # # *This is optional topic, if You prefer to use plain JavaScript callbacks - You can safely # ignore this example.* # # ### A little of Theory # # As You probably know Node.JS is asynchronous and never-blocking, and this is good. # The bad is that asynchronous code is more complicated than synchronous (even # with async control flow helpers). # # But it seems that in some cases it's possible to get the best from both worlds - make # code looks like synchronous but behave as asynchronous never-blocking. # And this is what synchronous mode tries to do. # # Thankfully it was relativelly easy to implement, thanks to the # exellent [fibers](https://github.com/laverdet/node-fibers) library. # # ### Enabling synchronous mode. # # As I said before sync mode is optional and You need to install `fibers` manually `npm install fibers`. # Requiring Model. Model = require 'mongo-model' # You also need to switch to synchronous mode. require 'mongo-model/lib/sync' # Just a handy helper. global.assert = (args...) -> require('assert').deepEqual args... # And wrap Your code inside of Fiber. Fiber(-> db = Model.db() db.clear() units = db.collection 'units' units.save name: 'Zeratul' assert units.first(name: 'Zeratul').name, 'Zeratul' db.close() ).run() # After enabling sync mode You still can use it in async way, let's rewrite code above. Model.db (err, db) -> return throw err if err db.clear (err) -> return throw err if err db.collection 'units', (err, units) -> return throw err if err units.save name: 'Zeratul', (err, result) -> return throw err if err units.first name: 'Zeratul', (err, unit) -> return throw err if err assert unit.name, 'Zeratul' db.close() # You can also mix sync and async code simultaneously. Fiber(-> db = Model.db() db.clear() db.collection 'units', (err, units) -> units.save name: 'Zeratul' assert units.first(name: 'Zeratul').name, 'Zeratul' db.close() ).run() # All methods (well, almost all) of [Driver](driver.html) and [Model](model.html) support both sync and async style. # It's also very handy to use sync style for writing specs, take a look at the `spec/helper.coffe` to see how it works. # In this sample we covered how to use synchronous mode with [Driver](driver.html) and [Model](model.html).
89051
# [Model](model.html) supports two modes - asynchronous and synchronous. # # - Asynchronous mode - it's just usual Node.JS mode, with plain JavaScript and Callbacks. # - Synchronous mode is optional and experimental it also depends on the `fibers` library. # # In this example we'll discower why You may need synchronous mode and how to use it. # # *This is optional topic, if You prefer to use plain JavaScript callbacks - You can safely # ignore this example.* # # ### A little of Theory # # As You probably know Node.JS is asynchronous and never-blocking, and this is good. # The bad is that asynchronous code is more complicated than synchronous (even # with async control flow helpers). # # But it seems that in some cases it's possible to get the best from both worlds - make # code looks like synchronous but behave as asynchronous never-blocking. # And this is what synchronous mode tries to do. # # Thankfully it was relativelly easy to implement, thanks to the # exellent [fibers](https://github.com/laverdet/node-fibers) library. # # ### Enabling synchronous mode. # # As I said before sync mode is optional and You need to install `fibers` manually `npm install fibers`. # Requiring Model. Model = require 'mongo-model' # You also need to switch to synchronous mode. require 'mongo-model/lib/sync' # Just a handy helper. global.assert = (args...) -> require('assert').deepEqual args... # And wrap Your code inside of Fiber. Fiber(-> db = Model.db() db.clear() units = db.collection 'units' units.save name: 'Zeratul' assert units.first(name: 'Zer<NAME>ul').name, 'Zeratul' db.close() ).run() # After enabling sync mode You still can use it in async way, let's rewrite code above. Model.db (err, db) -> return throw err if err db.clear (err) -> return throw err if err db.collection 'units', (err, units) -> return throw err if err units.save name: '<NAME>', (err, result) -> return throw err if err units.first name: '<NAME>', (err, unit) -> return throw err if err assert unit.name, '<NAME>' db.close() # You can also mix sync and async code simultaneously. Fiber(-> db = Model.db() db.clear() db.collection 'units', (err, units) -> units.save name: '<NAME>' assert units.first(name: '<NAME>').name, '<NAME>' db.close() ).run() # All methods (well, almost all) of [Driver](driver.html) and [Model](model.html) support both sync and async style. # It's also very handy to use sync style for writing specs, take a look at the `spec/helper.coffe` to see how it works. # In this sample we covered how to use synchronous mode with [Driver](driver.html) and [Model](model.html).
true
# [Model](model.html) supports two modes - asynchronous and synchronous. # # - Asynchronous mode - it's just usual Node.JS mode, with plain JavaScript and Callbacks. # - Synchronous mode is optional and experimental it also depends on the `fibers` library. # # In this example we'll discower why You may need synchronous mode and how to use it. # # *This is optional topic, if You prefer to use plain JavaScript callbacks - You can safely # ignore this example.* # # ### A little of Theory # # As You probably know Node.JS is asynchronous and never-blocking, and this is good. # The bad is that asynchronous code is more complicated than synchronous (even # with async control flow helpers). # # But it seems that in some cases it's possible to get the best from both worlds - make # code looks like synchronous but behave as asynchronous never-blocking. # And this is what synchronous mode tries to do. # # Thankfully it was relativelly easy to implement, thanks to the # exellent [fibers](https://github.com/laverdet/node-fibers) library. # # ### Enabling synchronous mode. # # As I said before sync mode is optional and You need to install `fibers` manually `npm install fibers`. # Requiring Model. Model = require 'mongo-model' # You also need to switch to synchronous mode. require 'mongo-model/lib/sync' # Just a handy helper. global.assert = (args...) -> require('assert').deepEqual args... # And wrap Your code inside of Fiber. Fiber(-> db = Model.db() db.clear() units = db.collection 'units' units.save name: 'Zeratul' assert units.first(name: 'ZerPI:NAME:<NAME>END_PIul').name, 'Zeratul' db.close() ).run() # After enabling sync mode You still can use it in async way, let's rewrite code above. Model.db (err, db) -> return throw err if err db.clear (err) -> return throw err if err db.collection 'units', (err, units) -> return throw err if err units.save name: 'PI:NAME:<NAME>END_PI', (err, result) -> return throw err if err units.first name: 'PI:NAME:<NAME>END_PI', (err, unit) -> return throw err if err assert unit.name, 'PI:NAME:<NAME>END_PI' db.close() # You can also mix sync and async code simultaneously. Fiber(-> db = Model.db() db.clear() db.collection 'units', (err, units) -> units.save name: 'PI:NAME:<NAME>END_PI' assert units.first(name: 'PI:NAME:<NAME>END_PI').name, 'PI:NAME:<NAME>END_PI' db.close() ).run() # All methods (well, almost all) of [Driver](driver.html) and [Model](model.html) support both sync and async style. # It's also very handy to use sync style for writing specs, take a look at the `spec/helper.coffe` to see how it works. # In this sample we covered how to use synchronous mode with [Driver](driver.html) and [Model](model.html).
[ { "context": "v is 'production'\n# port = 7410\n host = 'http://121.42.182.77:'\n\nmodule.exports = {\n port : port\n dbFilePath:", "end": 158, "score": 0.9996597766876221, "start": 145, "tag": "IP_ADDRESS", "value": "121.42.182.77" }, { "context": "\n dbPath: 'mongodb://localho...
config/config.coffee
leftjs/simple_uphall_api
0
path = require('path') port = 7410 host = 'http://localhost:' env = process.env.NODE_ENV if env is 'production' # port = 7410 host = 'http://121.42.182.77:' module.exports = { port : port dbFilePath: path.join(__dirname,'./../database/') dbPath: 'mongodb://localhost/myapi' secret: 'token_secret' tokenExpiredTime: 1000*60*60*24*7 avatar_base: host + port + '/images/avatar/' window_icon_base: host + port + '/images/window_icon/' comment_images_base: host + port + '/images/comment_images/' food_icon_base: host + port + '/images/food_icon/' }
84769
path = require('path') port = 7410 host = 'http://localhost:' env = process.env.NODE_ENV if env is 'production' # port = 7410 host = 'http://192.168.3.11:' module.exports = { port : port dbFilePath: path.join(__dirname,'./../database/') dbPath: 'mongodb://localhost/myapi' secret: '<KEY>_<KEY>' tokenExpiredTime: 1000*60*60*24*7 avatar_base: host + port + '/images/avatar/' window_icon_base: host + port + '/images/window_icon/' comment_images_base: host + port + '/images/comment_images/' food_icon_base: host + port + '/images/food_icon/' }
true
path = require('path') port = 7410 host = 'http://localhost:' env = process.env.NODE_ENV if env is 'production' # port = 7410 host = 'http://PI:IP_ADDRESS:192.168.3.11END_PI:' module.exports = { port : port dbFilePath: path.join(__dirname,'./../database/') dbPath: 'mongodb://localhost/myapi' secret: 'PI:KEY:<KEY>END_PI_PI:KEY:<KEY>END_PI' tokenExpiredTime: 1000*60*60*24*7 avatar_base: host + port + '/images/avatar/' window_icon_base: host + port + '/images/window_icon/' comment_images_base: host + port + '/images/comment_images/' food_icon_base: host + port + '/images/food_icon/' }
[ { "context": "andidate.save\n candidate:\n first_name: firstName\n success: (model, response) =>\n @rend", "end": 1847, "score": 0.9994613528251648, "start": 1838, "tag": "NAME", "value": "firstName" }, { "context": "candidate.save\n candidate:\n l...
app/assets/javascripts/admin/views/election/candidacy_view.js.coffee
JulienGuizot/voxe
5
class Admin.Views.Election.CandidacyView extends Backbone.View tagName: 'tr' template: JST['admin/templates/election/candidacy'] events: -> 'click .toggle-publish': 'togglePublish' 'click .change-picture-button': 'changePictureButton' 'change .change-picture': 'changePicture' 'click .change-first-name': 'changeFirstName' 'click .change-last-name': 'changeLastName' 'click .change-namespace': 'changeNamespace' 'click .delete-candidate': 'deleteCandidate' 'click .delete-candidacy': 'deleteCandidacy' initialize: -> @candidacy = @model @candidate = @candidacy.candidates.first() @election = @options.election @candidacy.bind 'change', @render, @ $(@el).attr "data-candidacy-id", @model.id render: -> $(@el).html @template @ $(@el).find('.change-picture').hide() @ togglePublish: (event) -> @candidacy.save {}, data: $.param(candidacy: {published: (not @candidacy.get 'published')}) changePictureButton: (event) -> $(@el).find('input[type=file]').trigger('click') changePicture: (event) -> image = $('input[type=file]', @el)[0].files[0] @candidate.addPhoto image deleteCandidate: (event) => if confirm('Are you sure ? It will also delete the candidacy') @candidate.destroy success: (model, response) => $(@el).hide() error: (model, response) => console.log "error" $(@el).hide() deleteCandidacy: (event) => if confirm('Are you sure ?') @candidacy.destroy success: (model, response) => $(@el).hide() error: (model, response) => console.log "error" $(@el).hide() changeFirstName: (event) => firstName = prompt "First name :", @candidate.get('firstName') @candidate.save candidate: first_name: firstName success: (model, response) => @render() error: (model, response) => console.log "error" changeLastName: (event) => lastName = prompt "Last name :", @candidate.get('lastName') @candidate.save candidate: last_name: lastName success: (model, response) => @render() error: (model, response) => console.log "error" changeNamespace: (event) => namespace = prompt "Namespace :", @candidate.get('namespace') @candidate.save candidate: namespace: namespace success: (model, response) => @render() error: (model, response) => console.log "error"
87188
class Admin.Views.Election.CandidacyView extends Backbone.View tagName: 'tr' template: JST['admin/templates/election/candidacy'] events: -> 'click .toggle-publish': 'togglePublish' 'click .change-picture-button': 'changePictureButton' 'change .change-picture': 'changePicture' 'click .change-first-name': 'changeFirstName' 'click .change-last-name': 'changeLastName' 'click .change-namespace': 'changeNamespace' 'click .delete-candidate': 'deleteCandidate' 'click .delete-candidacy': 'deleteCandidacy' initialize: -> @candidacy = @model @candidate = @candidacy.candidates.first() @election = @options.election @candidacy.bind 'change', @render, @ $(@el).attr "data-candidacy-id", @model.id render: -> $(@el).html @template @ $(@el).find('.change-picture').hide() @ togglePublish: (event) -> @candidacy.save {}, data: $.param(candidacy: {published: (not @candidacy.get 'published')}) changePictureButton: (event) -> $(@el).find('input[type=file]').trigger('click') changePicture: (event) -> image = $('input[type=file]', @el)[0].files[0] @candidate.addPhoto image deleteCandidate: (event) => if confirm('Are you sure ? It will also delete the candidacy') @candidate.destroy success: (model, response) => $(@el).hide() error: (model, response) => console.log "error" $(@el).hide() deleteCandidacy: (event) => if confirm('Are you sure ?') @candidacy.destroy success: (model, response) => $(@el).hide() error: (model, response) => console.log "error" $(@el).hide() changeFirstName: (event) => firstName = prompt "First name :", @candidate.get('firstName') @candidate.save candidate: first_name: <NAME> success: (model, response) => @render() error: (model, response) => console.log "error" changeLastName: (event) => lastName = prompt "Last name :", @candidate.get('lastName') @candidate.save candidate: last_name: <NAME> success: (model, response) => @render() error: (model, response) => console.log "error" changeNamespace: (event) => namespace = prompt "Namespace :", @candidate.get('namespace') @candidate.save candidate: namespace: namespace success: (model, response) => @render() error: (model, response) => console.log "error"
true
class Admin.Views.Election.CandidacyView extends Backbone.View tagName: 'tr' template: JST['admin/templates/election/candidacy'] events: -> 'click .toggle-publish': 'togglePublish' 'click .change-picture-button': 'changePictureButton' 'change .change-picture': 'changePicture' 'click .change-first-name': 'changeFirstName' 'click .change-last-name': 'changeLastName' 'click .change-namespace': 'changeNamespace' 'click .delete-candidate': 'deleteCandidate' 'click .delete-candidacy': 'deleteCandidacy' initialize: -> @candidacy = @model @candidate = @candidacy.candidates.first() @election = @options.election @candidacy.bind 'change', @render, @ $(@el).attr "data-candidacy-id", @model.id render: -> $(@el).html @template @ $(@el).find('.change-picture').hide() @ togglePublish: (event) -> @candidacy.save {}, data: $.param(candidacy: {published: (not @candidacy.get 'published')}) changePictureButton: (event) -> $(@el).find('input[type=file]').trigger('click') changePicture: (event) -> image = $('input[type=file]', @el)[0].files[0] @candidate.addPhoto image deleteCandidate: (event) => if confirm('Are you sure ? It will also delete the candidacy') @candidate.destroy success: (model, response) => $(@el).hide() error: (model, response) => console.log "error" $(@el).hide() deleteCandidacy: (event) => if confirm('Are you sure ?') @candidacy.destroy success: (model, response) => $(@el).hide() error: (model, response) => console.log "error" $(@el).hide() changeFirstName: (event) => firstName = prompt "First name :", @candidate.get('firstName') @candidate.save candidate: first_name: PI:NAME:<NAME>END_PI success: (model, response) => @render() error: (model, response) => console.log "error" changeLastName: (event) => lastName = prompt "Last name :", @candidate.get('lastName') @candidate.save candidate: last_name: PI:NAME:<NAME>END_PI success: (model, response) => @render() error: (model, response) => console.log "error" changeNamespace: (event) => namespace = prompt "Namespace :", @candidate.get('namespace') @candidate.save candidate: namespace: namespace success: (model, response) => @render() error: (model, response) => console.log "error"
[ { "context": "ister = true\n\t\t\telse\n\t\t\t\tif this.password == this.passwordAgain\n\t\t\t\t\tfirebase.auth().createUserWithEmailAndPasswo", "end": 796, "score": 0.7822588682174683, "start": 783, "tag": "PASSWORD", "value": "passwordAgain" }, { "context": "\"inputPassword\" class...
main.coffee
hereacg/user-system
0
bus = new Vue() store = { debug: true, state: { errMsg:'', errTitle:'', hasErr:false, user:null, }, set: (k,v) -> console.log("sotre action$set: k => #{k}, v => #{v}") if this.debug this.state[k] = v this get: (k) -> console.log ("sotre action$get: k => #{k}, v => #{this.state[k]}") if this.debug this.state[k] } loginPage = { name: 'login_page', data: () -> { 'email': '', 'password': '', 'passwordAgain': '', 'isRegister': false, } methods: { 'showAlert': (msg,title='Warning') -> alert 'showAlert' this.$parent.errMsg = msg this.$parent.errTitle = title this.$parent.hasErr = true 'registerWithEmail': (event) -> if not this.isRegister this.isRegister = true else if this.password == this.passwordAgain firebase.auth().createUserWithEmailAndPassword(this.email, this.password).catch((error) -> this.showAlert("Error Happened:\n#{error.code},\n#{error.message}")) else this.showAlert 'Need same passwords' 'withEmail': (event) -> firebase.auth().signInWithEmailAndPassword(this.email, this.password).catch((error) -> this.showAlert error.message,'Login Error') 'withTPL': (type) -> Err = (error) -> this.showAlert error.message,'Login Error' if type == 'google' firebase.auth() } template: '<div class="container"> <form class="form-signin" v-on:submit.stop.prevent> <h2 class="form-signin-heading">Please Enter</h2> <label for="inputEmail" class="sr-only">Email address</label> <input type="email" id="inputEmail" class="form-control" placeholder="Email address" v-model.lazy="email" required autofocus> <label for="inputPassword" class="sr-only">Password</label> <input type="password" id="inputPassword" class="form-control" placeholder="Password" v-model.trim="password" required> <label for="inputPasswordAgain" class="sr-only">Password again</label> <input v-if="isRegister" type="password" id="inputPasswordAgain" class="form-control" placeholder="Password again" v-model.trim="passwordAgain" required> <button class="btn btn-lg btn-primary btn-block" v-on:click="withEmail" v-if="!isRegister">Sign in</button> <button class="btn btn-lg btn-secondary btn-block" v-on:click="registerWithEmail" >Sign up</button> <div id="id_thirdparty"> <div class="dropdown"> <button class="btn btn-lg btn-block btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Third Party Login </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> <a class="dropdown-item" v-on:click="withTPL(\'google\')">Google</a> <a class="dropdown-item" v-on:click="withTPL(\'github\')">GitHub</a> <a class="dropdown-item" v-on:click="withTPL(\'twitter\')">Twitter</a> </div> </div> </div> </form>' } jumpOutPage = { name:"jump_out_page" data:() -> { 'querySet': this.$router.currentRoute.query, 'isProgress':false } computed:{ 'user': { 'get': () -> store.get('user') 'set': (v) -> store.set('user',v) } 'token': () -> this.user.getToken() 'username': () -> this.user.displayName 'avatarUrl': () -> this.user.photoUrl } methods:{ 'showAlert': (msg,title='Warning') -> alert 'showAlert' this.$parent.errMsg = msg this.$parent.errTitle = title this.$parent.hasErr = true 'toggleButton': () -> b = $('id_jumpButton') if b.hasClass('disabled') b.removeClass('disabled') else b.addClass('disabled') 'jumpOut': () -> this.isProgress = true this.toggleButton() $.post({ 'url': this.querySet.callback 'data': { 'token': this.token, 'username': this.username, 'avatarUrl': this.avatarUrl, } 'dataType': 'application/json' }).done((data) -> window.location.href=data.jumpUrl (window.event.returnValue = false) if window.event) .fail((error) -> console.log 'Error Happened:' $.each(error,(k,v) -> console.log "Error: k => #{k}, v=> #{v}") this.showAlert 'Login Failed. Please check callback url.') } template: '<div class="container"> <div class="card"> <div class="card-block"> <h2 class="card-title"> {{ user.displayName }} </h2> <h4 class="card-subtitle mb-2 text-muted"> Are you sure to share your infomation with {{ querySet.appName }}? </h4> <p class="card-text"> These infomation will get by it: </p> </div> <ul class="list-group list-group-flush"> <li class="list-group-item"> Indicate your identity </li> <li class="list-group-item"> Get your username </li> <li class="list-group-item"> Get your avatar </li> <div class="card-block"> <p class="card-text text-muted">Once you continue, you will be redirected to <code>{{ querySet.callback }}</code></p> <h6 class="card-subtitle">Continue or Not?</h6> <button type="button" id="id_jumpButton" class="btn btn-outline-primary btn-lg" v-on:click="jumpOut">Continue</button> <p class="card-text" v-if="isProgress">Please wait...</p> </div> </div> </div> ' } Vue.use(VueRouter) router = new VueRouter({ routes: [{ path: '/login', component: loginPage }, { path: '/', redirect: '/login' }, { path: '/jumpout' component: jumpOutPage } ] }) # Test Example: # ?appName=TestApp&callback=http://localhost:6000/callback vm = new Vue({ 'data':{ 'sharedState':store } 'computed':{ 'user':{ get:() -> this._user set:(value) -> this._user = value }, 'errMsg':{ get: () -> this.sharedState.get('errMsg') set: (value) -> this.sharedState.set('errMsg',value) }, 'errTitle':{ get: () -> this.sharedState.get('errTitle') set: (value) -> this.sharedState.set('errTitle',value) }, 'hasErr':{ get: () -> this.sharedState.get('hasErr') set: (value) -> this.sharedState.set('hasErr',value) }, 'user':{ get:() -> this.sharedState.get('user') set:(value) -> this.sharedState.set('user',value) } } 'methods':{ 'showAlert': (msg,title='Warning') -> alert 'showAlert' this.errTitle = title this.errMsg = msg this.hasErr = true 'onAuthStateChanged': (user) -> console.log('AuthStateChanged') if user this.user = user router.push({ 'path': 'jumpout', 'query': { 'appName': this.$router.currentRoute.query.appName, 'callback': this.$router.currentRoute.query.callback }}) else this.showAlert 'User was sign out.' } 'router':router }).$mount('#app') firebase.auth().onAuthStateChanged vm.onAuthStateChanged # set Listener
101261
bus = new Vue() store = { debug: true, state: { errMsg:'', errTitle:'', hasErr:false, user:null, }, set: (k,v) -> console.log("sotre action$set: k => #{k}, v => #{v}") if this.debug this.state[k] = v this get: (k) -> console.log ("sotre action$get: k => #{k}, v => #{this.state[k]}") if this.debug this.state[k] } loginPage = { name: 'login_page', data: () -> { 'email': '', 'password': '', 'passwordAgain': '', 'isRegister': false, } methods: { 'showAlert': (msg,title='Warning') -> alert 'showAlert' this.$parent.errMsg = msg this.$parent.errTitle = title this.$parent.hasErr = true 'registerWithEmail': (event) -> if not this.isRegister this.isRegister = true else if this.password == this.<PASSWORD> firebase.auth().createUserWithEmailAndPassword(this.email, this.password).catch((error) -> this.showAlert("Error Happened:\n#{error.code},\n#{error.message}")) else this.showAlert 'Need same passwords' 'withEmail': (event) -> firebase.auth().signInWithEmailAndPassword(this.email, this.password).catch((error) -> this.showAlert error.message,'Login Error') 'withTPL': (type) -> Err = (error) -> this.showAlert error.message,'Login Error' if type == 'google' firebase.auth() } template: '<div class="container"> <form class="form-signin" v-on:submit.stop.prevent> <h2 class="form-signin-heading">Please Enter</h2> <label for="inputEmail" class="sr-only">Email address</label> <input type="email" id="inputEmail" class="form-control" placeholder="Email address" v-model.lazy="email" required autofocus> <label for="inputPassword" class="sr-only">Password</label> <input type="password" id="inputPassword" class="form-control" placeholder="<PASSWORD>" v-model.trim="password" required> <label for="inputPasswordAgain" class="sr-only">Password again</label> <input v-if="isRegister" type="password" id="inputPasswordAgain" class="form-control" placeholder="Password again" v-model.trim="passwordAgain" required> <button class="btn btn-lg btn-primary btn-block" v-on:click="withEmail" v-if="!isRegister">Sign in</button> <button class="btn btn-lg btn-secondary btn-block" v-on:click="registerWithEmail" >Sign up</button> <div id="id_thirdparty"> <div class="dropdown"> <button class="btn btn-lg btn-block btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Third Party Login </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> <a class="dropdown-item" v-on:click="withTPL(\'google\')">Google</a> <a class="dropdown-item" v-on:click="withTPL(\'github\')">GitHub</a> <a class="dropdown-item" v-on:click="withTPL(\'twitter\')">Twitter</a> </div> </div> </div> </form>' } jumpOutPage = { name:"jump_out_page" data:() -> { 'querySet': this.$router.currentRoute.query, 'isProgress':false } computed:{ 'user': { 'get': () -> store.get('user') 'set': (v) -> store.set('user',v) } 'token': () -> this.user.getToken() 'username': () -> this.user.displayName 'avatarUrl': () -> this.user.photoUrl } methods:{ 'showAlert': (msg,title='Warning') -> alert 'showAlert' this.$parent.errMsg = msg this.$parent.errTitle = title this.$parent.hasErr = true 'toggleButton': () -> b = $('id_jumpButton') if b.hasClass('disabled') b.removeClass('disabled') else b.addClass('disabled') 'jumpOut': () -> this.isProgress = true this.toggleButton() $.post({ 'url': this.querySet.callback 'data': { 'token': this.token, 'username': this.username, 'avatarUrl': this.avatarUrl, } 'dataType': 'application/json' }).done((data) -> window.location.href=data.jumpUrl (window.event.returnValue = false) if window.event) .fail((error) -> console.log 'Error Happened:' $.each(error,(k,v) -> console.log "Error: k => #{k}, v=> #{v}") this.showAlert 'Login Failed. Please check callback url.') } template: '<div class="container"> <div class="card"> <div class="card-block"> <h2 class="card-title"> {{ user.displayName }} </h2> <h4 class="card-subtitle mb-2 text-muted"> Are you sure to share your infomation with {{ querySet.appName }}? </h4> <p class="card-text"> These infomation will get by it: </p> </div> <ul class="list-group list-group-flush"> <li class="list-group-item"> Indicate your identity </li> <li class="list-group-item"> Get your username </li> <li class="list-group-item"> Get your avatar </li> <div class="card-block"> <p class="card-text text-muted">Once you continue, you will be redirected to <code>{{ querySet.callback }}</code></p> <h6 class="card-subtitle">Continue or Not?</h6> <button type="button" id="id_jumpButton" class="btn btn-outline-primary btn-lg" v-on:click="jumpOut">Continue</button> <p class="card-text" v-if="isProgress">Please wait...</p> </div> </div> </div> ' } Vue.use(VueRouter) router = new VueRouter({ routes: [{ path: '/login', component: loginPage }, { path: '/', redirect: '/login' }, { path: '/jumpout' component: jumpOutPage } ] }) # Test Example: # ?appName=TestApp&callback=http://localhost:6000/callback vm = new Vue({ 'data':{ 'sharedState':store } 'computed':{ 'user':{ get:() -> this._user set:(value) -> this._user = value }, 'errMsg':{ get: () -> this.sharedState.get('errMsg') set: (value) -> this.sharedState.set('errMsg',value) }, 'errTitle':{ get: () -> this.sharedState.get('errTitle') set: (value) -> this.sharedState.set('errTitle',value) }, 'hasErr':{ get: () -> this.sharedState.get('hasErr') set: (value) -> this.sharedState.set('hasErr',value) }, 'user':{ get:() -> this.sharedState.get('user') set:(value) -> this.sharedState.set('user',value) } } 'methods':{ 'showAlert': (msg,title='Warning') -> alert 'showAlert' this.errTitle = title this.errMsg = msg this.hasErr = true 'onAuthStateChanged': (user) -> console.log('AuthStateChanged') if user this.user = user router.push({ 'path': 'jumpout', 'query': { 'appName': this.$router.currentRoute.query.appName, 'callback': this.$router.currentRoute.query.callback }}) else this.showAlert 'User was sign out.' } 'router':router }).$mount('#app') firebase.auth().onAuthStateChanged vm.onAuthStateChanged # set Listener
true
bus = new Vue() store = { debug: true, state: { errMsg:'', errTitle:'', hasErr:false, user:null, }, set: (k,v) -> console.log("sotre action$set: k => #{k}, v => #{v}") if this.debug this.state[k] = v this get: (k) -> console.log ("sotre action$get: k => #{k}, v => #{this.state[k]}") if this.debug this.state[k] } loginPage = { name: 'login_page', data: () -> { 'email': '', 'password': '', 'passwordAgain': '', 'isRegister': false, } methods: { 'showAlert': (msg,title='Warning') -> alert 'showAlert' this.$parent.errMsg = msg this.$parent.errTitle = title this.$parent.hasErr = true 'registerWithEmail': (event) -> if not this.isRegister this.isRegister = true else if this.password == this.PI:PASSWORD:<PASSWORD>END_PI firebase.auth().createUserWithEmailAndPassword(this.email, this.password).catch((error) -> this.showAlert("Error Happened:\n#{error.code},\n#{error.message}")) else this.showAlert 'Need same passwords' 'withEmail': (event) -> firebase.auth().signInWithEmailAndPassword(this.email, this.password).catch((error) -> this.showAlert error.message,'Login Error') 'withTPL': (type) -> Err = (error) -> this.showAlert error.message,'Login Error' if type == 'google' firebase.auth() } template: '<div class="container"> <form class="form-signin" v-on:submit.stop.prevent> <h2 class="form-signin-heading">Please Enter</h2> <label for="inputEmail" class="sr-only">Email address</label> <input type="email" id="inputEmail" class="form-control" placeholder="Email address" v-model.lazy="email" required autofocus> <label for="inputPassword" class="sr-only">Password</label> <input type="password" id="inputPassword" class="form-control" placeholder="PI:PASSWORD:<PASSWORD>END_PI" v-model.trim="password" required> <label for="inputPasswordAgain" class="sr-only">Password again</label> <input v-if="isRegister" type="password" id="inputPasswordAgain" class="form-control" placeholder="Password again" v-model.trim="passwordAgain" required> <button class="btn btn-lg btn-primary btn-block" v-on:click="withEmail" v-if="!isRegister">Sign in</button> <button class="btn btn-lg btn-secondary btn-block" v-on:click="registerWithEmail" >Sign up</button> <div id="id_thirdparty"> <div class="dropdown"> <button class="btn btn-lg btn-block btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Third Party Login </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> <a class="dropdown-item" v-on:click="withTPL(\'google\')">Google</a> <a class="dropdown-item" v-on:click="withTPL(\'github\')">GitHub</a> <a class="dropdown-item" v-on:click="withTPL(\'twitter\')">Twitter</a> </div> </div> </div> </form>' } jumpOutPage = { name:"jump_out_page" data:() -> { 'querySet': this.$router.currentRoute.query, 'isProgress':false } computed:{ 'user': { 'get': () -> store.get('user') 'set': (v) -> store.set('user',v) } 'token': () -> this.user.getToken() 'username': () -> this.user.displayName 'avatarUrl': () -> this.user.photoUrl } methods:{ 'showAlert': (msg,title='Warning') -> alert 'showAlert' this.$parent.errMsg = msg this.$parent.errTitle = title this.$parent.hasErr = true 'toggleButton': () -> b = $('id_jumpButton') if b.hasClass('disabled') b.removeClass('disabled') else b.addClass('disabled') 'jumpOut': () -> this.isProgress = true this.toggleButton() $.post({ 'url': this.querySet.callback 'data': { 'token': this.token, 'username': this.username, 'avatarUrl': this.avatarUrl, } 'dataType': 'application/json' }).done((data) -> window.location.href=data.jumpUrl (window.event.returnValue = false) if window.event) .fail((error) -> console.log 'Error Happened:' $.each(error,(k,v) -> console.log "Error: k => #{k}, v=> #{v}") this.showAlert 'Login Failed. Please check callback url.') } template: '<div class="container"> <div class="card"> <div class="card-block"> <h2 class="card-title"> {{ user.displayName }} </h2> <h4 class="card-subtitle mb-2 text-muted"> Are you sure to share your infomation with {{ querySet.appName }}? </h4> <p class="card-text"> These infomation will get by it: </p> </div> <ul class="list-group list-group-flush"> <li class="list-group-item"> Indicate your identity </li> <li class="list-group-item"> Get your username </li> <li class="list-group-item"> Get your avatar </li> <div class="card-block"> <p class="card-text text-muted">Once you continue, you will be redirected to <code>{{ querySet.callback }}</code></p> <h6 class="card-subtitle">Continue or Not?</h6> <button type="button" id="id_jumpButton" class="btn btn-outline-primary btn-lg" v-on:click="jumpOut">Continue</button> <p class="card-text" v-if="isProgress">Please wait...</p> </div> </div> </div> ' } Vue.use(VueRouter) router = new VueRouter({ routes: [{ path: '/login', component: loginPage }, { path: '/', redirect: '/login' }, { path: '/jumpout' component: jumpOutPage } ] }) # Test Example: # ?appName=TestApp&callback=http://localhost:6000/callback vm = new Vue({ 'data':{ 'sharedState':store } 'computed':{ 'user':{ get:() -> this._user set:(value) -> this._user = value }, 'errMsg':{ get: () -> this.sharedState.get('errMsg') set: (value) -> this.sharedState.set('errMsg',value) }, 'errTitle':{ get: () -> this.sharedState.get('errTitle') set: (value) -> this.sharedState.set('errTitle',value) }, 'hasErr':{ get: () -> this.sharedState.get('hasErr') set: (value) -> this.sharedState.set('hasErr',value) }, 'user':{ get:() -> this.sharedState.get('user') set:(value) -> this.sharedState.set('user',value) } } 'methods':{ 'showAlert': (msg,title='Warning') -> alert 'showAlert' this.errTitle = title this.errMsg = msg this.hasErr = true 'onAuthStateChanged': (user) -> console.log('AuthStateChanged') if user this.user = user router.push({ 'path': 'jumpout', 'query': { 'appName': this.$router.currentRoute.query.appName, 'callback': this.$router.currentRoute.query.callback }}) else this.showAlert 'User was sign out.' } 'router':router }).$mount('#app') firebase.auth().onAuthStateChanged vm.onAuthStateChanged # set Listener
[ { "context": " @guildStatus = 2\n guild.leaderName = @name\n guild.save()\n\n else if _.fin", "end": 3544, "score": 0.5671597123146057, "start": 3544, "tag": "NAME", "value": "" }, { "context": " @guildStatus = 2\n guild.leaderName = @name\n ...
src/character/player/Player.coffee
sadbear-/IdleLands
0
Character = require "../base/Character" RestrictedNumber = require "restricted-number" MessageCreator = require "../../system/MessageCreator" Constants = require "../../system/Constants" Equipment = require "../../item/Equipment" _ = require "lodash" Q = require "q" Personality = require "../base/Personality" requireDir = require "require-dir" regions = requireDir "../regions" PushBullet = require "pushbullet" Chance = require "chance" chance = new Chance Math.random class Player extends Character isBusy: false permanentAchievements: {} constructor: (player) -> super player canEquip: (item, rangeBoost = 1) -> myItem = _.findWhere @equipment, {type: item.type} return false if not myItem score = @calc.itemScore item myScore = @calc.itemScore myItem realScore = item.score() score > myScore and realScore < @calc.itemFindRange()*rangeBoost initialize: -> if not @xp @xp = new RestrictedNumber 0, (@levelUpXpCalc 0), 0 @gold = new RestrictedNumber 0, 9999999999, 0 @x = 10 @y = 10 @map = 'Norkos' norkosClasses = ['Generalist', 'Mage', 'Fighter', 'Cleric'] @changeProfession (_.sample norkosClasses), yes @levelUp yes @generateBaseEquipment() @overflow = [] @lastLogin = new Date() @gender = "female" @priorityPoints = {dex: 1, str: 1, agi: 1, wis: 1, con: 1, int: 1} @calc.itemFindRange() generateBaseEquipment: -> @equipment = [ new Equipment {type: "body", class: "newbie", name: "Tattered Shirt", con: 1} new Equipment {type: "feet", class: "newbie", name: "Cardboard Shoes", dex: 1} new Equipment {type: "finger", class: "newbie", name: "Twisted Wire", int: 1} new Equipment {type: "hands", class: "newbie", name: "Pixelated Gloves", str: 1} new Equipment {type: "head", class: "newbie", name: "Miniature Top Hat", wis: 1} new Equipment {type: "legs", class: "newbie", name: "Leaf", agi: 1} new Equipment {type: "neck", class: "newbie", name: "Old Brooch", wis: 1, int: 1} new Equipment {type: "mainhand",class: "newbie", name: "Empty and Broken Ale Bottle", str: 1, con: -1} new Equipment {type: "offhand", class: "newbie", name: "Chunk of Rust", dex: 1, str: 1} new Equipment {type: "charm", class: "newbie", name: "Ancient Bracelet", con: 1, dex: 1} ] setPushbulletKey: (key) -> @pushbulletApiKey = key @pushbulletSend "This is a test for Idle Lands" if key Q {isSuccess: yes, code: 99, message: "Your PushBullet API key has been #{if key then "added" else "removed"} successfully. You should also have gotten a test message!"} pushbulletSend: (message, link = null) -> pushbullet = new PushBullet @pushbulletApiKey if @pushbulletApiKey return if not pushbullet pushbullet.devices (e, res) -> _.each res?.devices, (device) -> if link pushbullet.link device.iden, message, link, (e, res) -> else pushbullet.note device.iden, 'IdleLands', message, (e, res) -> handleGuildStatus: -> if not @guild @guildStatus = -1 else gm = @playerManager.game.guildManager gm.waitForGuild().then => guild = gm.guildHash[@guild] # In case the database update failed for an offline player if not guild or not gm.findMember @name, @guild @guild = null @guildStatus = -1 else if playerGuild.leader is @identifier @guildStatus = 2 guild.leaderName = @name guild.save() else if _.findWhere guild.members, {identifier: @identifier, isAdmin: yes} @guildStatus = 1 else @guildStatus = 0 manageOverflow: (option, slot) -> defer = Q.defer() @overflow = [] if not @overflow cleanOverflow = => @overflow = _.compact _.reject @overflow, (item) -> item?.name is "empty" switch option when "add" @addOverflow slot, defer when "swap" @swapOverflow slot, defer cleanOverflow() when "sell" @sellOverflow slot, defer cleanOverflow() @recalculateStats() defer.promise forceIntoOverflow: (item) -> # no params = no problems do @manageOverflow @overflow.push item addOverflow: (slot, defer) -> if not (slot in ["body","feet","finger","hands","head","legs","neck","mainhand","offhand","charm","trinket"]) return defer.resolve {isSuccess: no, code: 40, message: "That slot is invalid."} if @overflow.length is Constants.defaults.player.maxOverflow return defer.resolve {isSuccess: no, code: 41, message: "Your inventory is currently full!"} currentItem = _.findWhere @equipment, {type: slot} if currentItem.name is "empty" return defer.resolve {isSuccess: no, code: 42, message: "You can't add empty items to your inventory!"} @overflow.push currentItem @equipment = _.without @equipment, currentItem @equipment.push new Equipment {type: slot, name: "empty"} defer.resolve {isSuccess: yes, code: 45, message: "Successfully added #{currentItem.name} to your inventory in slot #{@overflow.length-1}.", player: @buildRESTObject()} swapOverflow: (slot, defer) -> if not @overflow[slot] return defer.resolve {isSuccess: no, code: 43, message: "You don't have anything in that inventory slot."} current = _.findWhere @equipment, {type: @overflow[slot].type} inOverflow = @overflow[slot] if not @canEquip inOverflow return defer.resolve {isSuccess: no, code: 43, message: "A mysterious force compels you to not equip that item. It may be too powerful."} @equip inOverflow if current.name isnt "empty" @overflow[slot] = current return defer.resolve {isSuccess: yes, code: 47, message: "Successfully swapped #{current.name} with #{inOverflow.name} (slot #{slot}).", player: @buildRESTObject()} @overflow[slot] = null defer.resolve {isSuccess: yes, code: 47, message: "Successfully equipped #{inOverflow.name} (slot #{slot}).", player: @buildRESTObject()} sellOverflow: (slot, defer) -> curItem = @overflow[slot] if (not curItem) or (curItem.name is "empty") return defer.resolve {isSuccess: yes, code: 44, message: "That item is not able to be sold!"} salePrice = Math.max 2, @calcGoldGain Math.round curItem.score()*@calc.itemSellMultiplier curItem @gainGold salePrice @overflow[slot] = null defer.resolve {isSuccess: yes, code: 46, message: "Successfully sold #{curItem.name} for #{salePrice} gold.", player: @buildRESTObject()} handleTrainerOnTile: (tile) -> return if @isBusy or @stepCooldown > 0 @isBusy = true className = tile.object.name message = "<player.name>#{@name}</player.name> has met with the <player.class>#{className}</player.class> trainer!" if @professionName is className message += " Alas, <player.name>#{@name}</player.name> is already a <player.class>#{className}</player.class>!" @isBusy = false @emit "player.trainer.isAlready", @, className @stepCooldown = 10 @playerManager.game.eventHandler.broadcastEvent {message: message, player: @, type: 'profession'} if @professionName isnt className and (chance.bool likelihood: @calc.classChangePercent className) @playerManager.game.eventHandler.doYesNo {}, @, (result) => @isBusy = false if not result @emit "player.trainer.ignore", @, className return @emit "player.trainer.speak", @, className @changeProfession className handleTeleport: (tile) -> return if @stepCooldown > 0 @stepCooldown = 30 dest = tile.object.properties dest.x = parseInt dest.destx dest.y = parseInt dest.desty newLoc = dest if not dest.map and not dest.toLoc @playerManager.game.errorHandler.captureMessage "ERROR. No dest.map at #{@x},#{@y} in #{@map}" return if not dest.movementType @playerManager.game.errorHandler.captureMessage "ERROR. No dest.movementType at #{@x},#{@y} in #{@map}" return dest.movementType = dest.movementType.toLowerCase() eventToTest = "#{dest.movementType}Chance" prob = @calc[eventToTest]() return if not chance.bool({likelihood: prob}) handleLoc = no dest.fromName = @map if not dest.fromName dest.destName = dest.map if not dest.destName if dest.toLoc newLoc = @playerManager.game.gmCommands.lookupLocation dest.toLoc if not newLoc @playerManager.game.errorHandler.captureMessage "BAD TELEPORT LOCATION #{dest.toLoc}" @map = newLoc.map @x = newLoc.x @y = newLoc.y handleLoc = yes dest.destName = newLoc.formalName else @map = newLoc.map @x = newLoc.x @y = newLoc.y @oldRegion = @mapRegion @mapRegion = newLoc.region message = "" switch dest.movementType when "ascend" then message = "<player.name>#{@name}</player.name> has ascended to <event.transfer.destination>#{dest.destName}</event.transfer.destination>." when "descend" then message = "<player.name>#{@name}</player.name> has descended to <event.transfer.destination>#{dest.destName}</event.transfer.destination>." when "fall" then message = "<player.name>#{@name}</player.name> has fallen from <event.transfer.from>#{dest.fromName}</event.transfer.from> to <event.transfer.destination>#{dest.destName}</event.transfer.destination>!" when "teleport" then message = "<player.name>#{@name}</player.name> was teleported from <event.transfer.from>#{dest.fromName}</event.transfer.from> to <event.transfer.destination>#{dest.destName}</event.transfer.destination>!" if @hasPersonality "Wheelchair" if dest.movementType is "descend" message = "<player.name>#{@name}</player.name> went crashing down in a wheelchair to <event.transfer.destination>#{dest.destName}</event.transfer.destination>." @emit "explore.transfer", @, @map @emit "explore.transfer.#{dest.movementType}", @, @map @playerManager.game.eventHandler.broadcastEvent {message: message, player: @, type: 'explore'} @handleTile @getTileAt() if handleLoc handleTile: (tile) -> switch tile.object?.type when "Boss" then @handleBossBattle tile.object.name when "BossParty" then @handleBossBattleParty tile.object.name when "Teleport" then @handleTeleport tile when "Trainer" then @handleTrainerOnTile tile when "Treasure" then @handleTreasure tile.object.name when "Collectible" then @handleCollectible tile.object if tile.object?.properties?.forceEvent @playerManager.game.eventHandler.doEventForPlayer @name, tile.object.properties.forceEvent handleCollectible: (collectible) -> @collectibles = [] if not @collectibles collectibleName = collectible.name collectibleRarity = collectible.properties?.rarity or "basic" current = _.findWhere @collectibles, {name: collectibleName, map: @map} return if current @collectibles.push name: collectibleName map: @map region: @mapRegion rarity: collectibleRarity foundAt: Date.now() message = "<player.name>#{@name}</player.name> stumbled across a rare, shiny, and collectible <event.item.#{collectibleRarity}>#{collectibleName}</event.item.#{collectibleRarity}> in #{@map} - #{@mapRegion}!" @playerManager.game.eventHandler.broadcastEvent {message: message, player: @, type: 'event'} handleTreasure: (treasure) -> @playerManager.game.treasureFactory.createTreasure treasure, @ handleBossBattle: (bossName) -> @playerManager.game.eventHandler.bossBattle @, bossName handleBossBattleParty: (bossParty) -> @playerManager.game.eventHandler.bossPartyBattle @, bossParty pickRandomTile: -> @ignoreDir = [] if not @ignoreDir @stepCooldown = 0 if not @stepCooldown randomDir = -> chance.integer({min: 1, max: 9}) dir = randomDir() dir = randomDir() while dir in @ignoreDir drunkAdjustedProb = Math.max 0, 80 - (@calc.drunk() * 10) dir = if chance.bool {likelihood: drunkAdjustedProb} then @lastDir else dir [(@num2dir dir, @x, @y), dir] getTileAt: (x = @x, y = @y) -> lookAtTile = @playerManager.game.world.maps[@map].getTile.bind @playerManager.game.world.maps[@map] lookAtTile x,y getRegion: -> regions[@getTileAt().region.replace(/\s/g, '')] cantEnterTile: (tile) -> return @statistics['calculated map changes'][tile.object.properties.requireMap] if tile.object?.properties?.requireMap return @statistics['calculated regions visited'][tile.object.properties.requireRegion] if tile.object?.properties?.requireRegion return @statistics['calculated boss kills'][tile.object.properties.requireBoss] if tile.object?.properties?.requireBoss return no if tile.object?.properties?.requireClass and @professionName isnt tile.object?.properties?.requireClass return no if not @collectibles or not _.findWhere @collectibles, {name: tile.object?.properties?.requireCollectible} return no if not @achievements or not _.findWhere @achievements, {name: tile.object?.properties?.requireAchievement} tile.blocked moveAction: (currentStep) -> [newLoc, dir] = @pickRandomTile() try tile = @getTileAt newLoc.x,newLoc.y #drunkAdjustedProb = Math.max 0, 95 - (@calc.drunk() * 5) while @cantEnterTile tile [newLoc, dir] = @pickRandomTile() tile = @getTileAt newLoc.x, newLoc.y if not tile.blocked @x = newLoc.x @y = newLoc.y @lastDir = dir @ignoreDir = [] else @lastDir = null @ignoreDir.push dir @emit 'explore.hit.wall', @ @oldRegion = @mapRegion @mapRegion = tile.region @emit 'explore.walk', @ @emit "explore.walk.#{tile.terrain or "void"}".toLowerCase(), @ @playerManager.game.errorHandler.captureMessage @x,@y,@map,tile.terrain,tile, "INVALID TILE" if not tile.terrain and not tile.blocked @handleTile tile @stepCooldown-- @gainXp @calcXpGain 10 if currentStep < 5 catch e @playerManager.game.errorHandler.captureException e, extra: map: @map, x: @x, y: @y @x = @y = 10 @map = "Norkos" changeProfession: (to, suppress = no) -> @profession?.unload? @ oldProfessionName = @professionName professionProto = require "../classes/#{to}" @profession = new professionProto() @professionName = professionProto.name @profession.load @ message = "<player.name>#{@name}</player.name> is now a <player.class>#{to}</player.class>!" @playerManager.game.eventHandler.broadcastEvent {message: message, player: @, type: 'profession'} if not suppress @emit "player.profession.change", @, oldProfessionName, @professionName @recalculateStats() getGender: -> if @gender then @gender else "female" setGender: (newGender) -> @gender = newGender.substring 0,15 @gender = 'indeterminate' if not @gender Q {isSuccess: yes, code: 97, message: "Your gender is now #{@gender}."} score: -> @calc.partyScore() possiblyDoEvent: -> event = Constants.pickRandomEvent @ return if not event @playerManager.game.eventHandler.doEvent event, @, ->{} #god damned code collapse possiblyLeaveParty: -> return if not @party return if @party.currentBattle return if not chance.bool {likelihood: @calc.partyLeavePercent()} @party.playerLeave @ checkShop: -> @shop = null if @shop and ((not @getRegion()?.shopSlots?()) or (@getRegion()?.name isnt @shop.region)) @shop = @playerManager.game.shopGenerator.regionShop @ if not @shop and @getRegion()?.shopSlots?() buyShop: (slot) -> if not @shop.slots[slot] return Q {isSuccess: no, code: 123, message: "The shop doesn't have an item in slot #{slot}."} if @shop.slots[slot].price > @gold.getValue() return Q {isSuccess: no, code: 124, message: "That item costs #{@shop.slots[slot].price} gold, but you only have #{@gold.getValue()} gold."} resolved = Q {isSuccess: yes, code: 125, message: "Successfully purchased #{@shop.slots[slot].item.name} for #{@shop.slots[slot].price} gold.", player: @buildRESTObject()} @gold.sub @shop.slots[slot].price @emit "player.shop.buy", @, @shop.slots[slot].item, @shop.slots[slot].price @equip @shop.slots[slot].item @shop.slots[slot] = null @shop.slots = _.compact @shop.slots @save() resolved takeTurn: -> steps = Math.max 1, @calc.haste() @moveAction steps while steps-- isnt 0 @possiblyDoEvent() @possiblyLeaveParty() @checkShop() @checkPets() @save() @ checkPets: -> @playerManager.game.petManager.handlePetsForPlayer @ buyPet: (pet, name, attr1 = "a monocle", attr2 = "a top hat") -> name = name.trim() attr1 = attr1.trim() attr2 = attr2.trim() return Q {isSuccess: no, code: 200, message: "You need to specify all required information to make a pet."} if not name or not attr1 or not attr2 return Q {isSuccess: no, code: 201, message: "Your information needs to be less than 20 characters."} if name.length > 20 or attr1.length > 20 or attr2.length > 20 return Q {isSuccess: no, code: 202, message: "You haven't unlocked that pet."} if not @foundPets[pet] return Q {isSuccess: no, code: 203, message: "You've already purchased that pet."} if @foundPets[pet].purchaseDate return Q {isSuccess: no, code: 204, message: "You don't have enough gold to buy that pet! You need #{@foundPets[pet].cost -@gold.getValue()} more gold."} if @foundPets[pet].cost > @gold.getValue() @gold.sub @foundPets[pet].cost petManager = @playerManager.game.petManager petManager.createPet player: @ type: pet name: name attr1: attr1 attr2: attr2 @emit "player.shop.pet" pet = petManager.getActivePetFor @ Q {isSuccess: yes, code: 205, message: "Successfully purchased a new pet (#{pet.type}) named '#{name}'!", pet: pet.buildSaveObject(), pets: petManager.getPetsForPlayer @identifier} upgradePet: (stat) -> pet = @getPet() config = pet.petManager.getConfig pet curLevel = pet.scaleLevel[stat] cost = config.scaleCost[stat][curLevel+1] return Q {isSuccess: no, code: 206, message: "You don't have a pet."} if not pet return Q {isSuccess: no, code: 209, message: "That stat is invalid."} if not config.scale[stat] return Q {isSuccess: no, code: 210, message: "That stat is already at max level."} if config.scale[stat].length <= curLevel+1 or not cost return Q {isSuccess: no, code: 211, message: "You don't have enough gold to upgrade your pet. You need #{cost-@gold.getValue()} more gold."} if @gold.getValue() < cost @gold.sub cost pet.increaseStat stat @emit "player.shop.petupgrade" Q {isSuccess: yes, code: 212, message: "Successfully upgraded your pets (#{pet.name}) #{stat} to level #{curLevel+2}!", pet: pet.buildSaveObject()} changePetClass: (newClass) -> myClasses = _.keys @statistics['calculated class changes'] pet = @getPet() return Q {isSuccess: no, code: 206, message: "You don't have a pet."} if not pet return Q {isSuccess: no, code: 207, message: "You haven't been that class yet, so you can't teach your pet how to do it!"} if (myClasses.indexOf newClass) is -1 and newClass isnt "Monster" pet.setClassTo newClass Q {isSuccess: yes, code: 208, message: "Successfully changed your pets (#{pet.name}) class to #{newClass}!", pet: pet.buildSaveObject()} takePetGold: -> pet = @getPet() return Q {isSuccess: no, code: 206, message: "You don't have a pet."} if not pet return Q {isSuccess: no, code: 233, message: "Your pet has no gold."} if pet.gold.atMin() gold = pet.gold.getValue() @gold.add gold pet.gold.toMinimum() Q {isSuccess: yes, code: 232, message: "You took #{gold} gold from your pet.", pet: pet.buildSaveObject()} feedPet: -> pet = @getPet() return Q {isSuccess: no, code: 206, message: "You don't have a pet."} if not pet return Q {isSuccess: no, code: 213, message: "Your pet is already at max level."} if pet.level.atMax() gold = pet.goldToNextLevel() return Q {isSuccess: no, code: 214, message: "You don't have enough gold for that! You need #{gold-@gold.getValue()} more gold."} if @gold.lessThan gold @gold.sub gold pet.feed() Q {isSuccess: yes, code: 215, message: "Your pet (#{pet.name}) was fed #{gold} gold and gained a level (#{pet.level.getValue()}).", pet: pet.buildSaveObject()} getPetGold: -> pet = @getPet() return Q {isSuccess: no, code: 206, message: "You don't have a pet."} if not pet petMoney = pet.gold.getValue() return Q {isSuccess: no, code: 216, message: "Your pet is penniless."} if not petMoney @gold.add petMoney pet.gold.toMinimum() Q {isSuccess: yes, code: 217, message: "You retrieved #{petMoney} gold from your pet (#{pet.name})!", pet: pet.buildSaveObject()} sellPetItem: (itemSlot) -> pet = @getPet() return Q {isSuccess: no, code: 206, message: "You don't have a pet."} if not pet item = pet.inventory[itemSlot] return Q {isSuccess: no, code: 218, message: "Your pet does not have an item in that slot!"} if not item pet.inventory = _.without pet.inventory, item value = pet.sellItem item, no Q {isSuccess: yes, code: 219, message: "Your pet (#{pet.name}) sold #{item.name} for #{value} gold!", pet: pet.buildSaveObject()} givePetItem: (itemSlot) -> pet = @getPet() return Q {isSuccess: no, code: 206, message: "You don't have a pet."} if not pet return Q {isSuccess: no, code: 220, message: "Your pet's inventory is full!"} if not pet.hasInventorySpace() curItem = @overflow[itemSlot] return Q {isSuccess: no, code: 43, message: "You don't have anything in that inventory slot."} if not curItem pet.addToInventory curItem @overflow = _.without @overflow, curItem Q {isSuccess: yes, code: 221, message: "Successfully gave #{curItem.name} to your pet (#{pet.name}).", pet: pet.buildSaveObject()} takePetItem: (itemSlot) -> pet = @getPet() return Q {isSuccess: no, code: 206, message: "You don't have a pet."} if not pet return Q {isSuccess: no, code: 41, message: "Your inventory is currently full!"} if @overflow.length is Constants.defaults.player.maxOverflow curItem = pet.inventory[itemSlot] return Q {isSuccess: no, code: 218, message: "Your pet doesn't have anything in that inventory slot."} if not curItem @overflow.push curItem pet.removeFromInventory curItem Q {isSuccess: yes, code: 221, message: "Successfully took #{curItem.name} from your pet (#{pet.name}).", pet: pet.buildSaveObject()} setPetOption: (option, value) -> pet = @getPet() return Q {isSuccess: no, code: 206, message: "You don't have a pet."} if not pet return Q {isSuccess: no, code: 222, message: "That option is invalid."} if not (option in ["smartSell", "smartEquip", "smartSelf"]) pet[option] = value Q {isSuccess: yes, code: 223, message: "Successfully set #{option} to #{value} for #{pet.name}.", pet: pet.buildSaveObject()} equipPetItem: (itemSlot) -> pet = @getPet() return Q {isSuccess: no, code: 206, message: "You don't have a pet."} if not pet item = pet.inventory[itemSlot] return Q {isSuccess: no, code: 218, message: "Your pet does not have an item in that slot!"} if not item return Q {isSuccess: no, code: 224, message: "Your pet is not so talented as to have that item slot!"} if not pet.hasEquipmentSlot item.type return Q {isSuccess: no, code: 224, message: "Your pet cannot equip that item! Either it is too strong, or your pets equipment slots are full."} if not pet.canEquip item pet.equip item Q {isSuccess: yes, code: 225, message: "Successfully equipped your pet (#{pet.name}) with #{item.name}.", pet: newPet.buildSaveObject()} unequipPetItem: (uid) -> pet = @getPet() return Q {isSuccess: no, code: 206, message: "You don't have a pet."} if not pet item = pet.findEquipped uid return Q {isSuccess: no, code: 226, message: "Your pet does not have that item equipped!"} if not item return Q {isSuccess: no, code: 231, message: "You can't unequip your pets soul, you jerk!"} if item.type is "pet soul" return Q {isSuccess: no, code: 220, message: "Your pet's inventory is full!"} if not pet.hasInventorySpace() pet.unequip item Q {isSuccess: yes, code: 227, message: "Successfully unequipped #{item.name} from your pet (#{pet.name}).", pet: pet.buildSaveObject()} swapToPet: (petId) -> pet = @getPet() return Q {isSuccess: no, code: 206, message: "You don't have a pet."} if not pet newPet = _.findWhere pet.petManager.pets, (pet) => pet.createdAt is petId and pet.owner.name is @name return Q {isSuccess: no, code: 228, message: "That pet does not exist!"} if not newPet return Q {isSuccess: no, code: 229, message: "That pet is already active!"} if newPet is pet pet.petManager.changePetForPlayer @, newPet Q {isSuccess: yes, code: 230, message: "Successfully made #{newPet.name}, the #{newPet.type} your active pet!", pet: newPet.buildSaveObject(), pets: pet.petManager.getPetsForPlayer @identifier} save: -> return if not @playerManager @playerManager.savePlayer @ getPet: -> @playerManager.game.petManager.getActivePetFor @ gainGold: (gold) -> if _.isNaN gold @playerManager.game.errorHandler.captureException new Error "BAD GOLD VALUE GOTTEN SOMEHOW" gold = 1 if gold > 0 @emit "player.gold.gain", @, gold else @emit "player.gold.lose", @, gold @gold.add gold gainXp: (xp) -> if xp > 0 @emit "player.xp.gain", @, xp else @emit "player.xp.lose", @, xp @xp.set 0 if _.isNaN @xp.__current @xp.add xp @levelUp() if @xp.atMax() buildRESTObject: -> @playerManager.buildPlayerSaveObject @ levelUp: (suppress = no) -> return if not @playerManager or @level.getValue() is @level.maximum @level.add 1 message = "<player.name>#{@name}</player.name> has attained level <player.level>#{@level.getValue()}</player.level>!" @resetMaxXp() @xp.toMinimum() @recalculateStats() @playerManager.game.eventHandler.broadcastEvent {message: message, player: @, type: 'levelup'} if not suppress @recalcGuildLevel() @emit "player.level.up", @ @playerManager.addForAnalytics @ recalcGuildLevel: -> return if not @guild @playerManager.game.guildManager.guildHash[@guild].avgLevel() setString: (type, val = '') -> @messages = {} if not @messages @messages[type] = val.substring 0, 99 if not @messages[type] delete @messages[type] return Q {isSuccess: yes, code: 95, message: "Successfully updated your string settings. Removed string type \"#{type}.\""} Q {isSuccess: yes, code: 95, message: "Successfully updated your string settings. String \"#{type}\" is now: #{if val then val else 'empty!'}"} checkAchievements: (silent = no) -> @_oldAchievements = _.compact _.clone @achievements @achievements = [] achieved = @playerManager.game.achievementManager.getAllAchievedFor @ stringCurrent = _.map @_oldAchievements, (achievement) -> achievement.name stringAll = _.map achieved, (achievement) -> achievement.name newAchievements = _.difference stringAll, stringCurrent _.each newAchievements, (achievementName) => achievement = _.findWhere achieved, name: achievementName @achievements.push achievement if not silent message = "<player.name>#{@name}</player.name> has achieved <event.achievement>#{achievementName}</event.achievement> (#{achievement.desc} | #{achievement.reward})" @playerManager.game.eventHandler.broadcastEvent {message: message, player: @, type: 'achievement'} if not silent @achievements = achieved itemPriority: (item) -> if not @priorityPoints @priorityPoints = {dex: 1, str: 1, agi: 1, wis: 1, con: 1, int: 1} ret = 0 ret += item[stat]*@priorityPoints[stat]*Constants.defaults.player.priorityScale for stat in ["dex", "str", "agi", "wis", "con", "int"] ret priorityTotal: -> _.reduce @priorityPoints, ((total, stat) -> total + stat), 0 setPriorities: (stats) -> if not @priorityPoints @priorityPoints = {dex: 1, str: 1, agi: 1, wis: 1, con: 1, int: 1} if _.size stats != 6 return Q {isSuccess: no, code: 111, message: "Priority list is invalid. Expected 6 items"} total = 0 sanitizedStats = {} for key, stat of stats if !_.isNumber stat return Q {isSuccess: no, code: 112, message: "Priority \"" + key + "\" is not a number."} if not (key in ["dex", "str", "agi", "wis", "con", "int"]) return Q {isSuccess: no, code: 111, message: "Key \"" + key + "\" is invalid."} sanitizedStats[key] = Math.round stat total += Math.round stat if total != Constants.defaults.player.priorityTotal return Q {isSuccess: no, code: 112, message: "Number of priority points are not equal to " + Constants.defaults.player.priorityTotal + "."} @priorityPoints = sanitizedStats return Q {isSuccess: yes, code: 113, message: "Successfully set priorities.", player: @buildRESTObject()} addPriority: (stat, points) -> if not @priorityPoints @priorityPoints = {dex: 1, str: 1, agi: 1, wis: 1, con: 1, int: 1} points = if _.isNumber points then points else parseInt points points = Math.round points if points is 0 return Q {isSuccess: no, code: 110, message: "You didn't specify a valid priority point amount."} if not (stat in ["dex", "str", "agi", "wis", "con", "int"]) return Q {isSuccess: no, code: 111, message: "That stat is invalid."} if points > 0 and @priorityTotal() + points > Constants.defaults.player.priorityTotal return Q {isSuccess: no, code: 112, message: "Not enough priority points remaining."} if points < 0 and @priorityPoints[stat] + points < 0 return Q {isSuccess: no, code: 112, message: "Not enough priority points to remove."} @priorityPoints[stat] += points if points > 0 return Q {isSuccess: yes, code: 113, message: "Successfully added #{points} to your #{stat} priority.", player: @buildRESTObject()} else return Q {isSuccess: yes, code: 113, message: "Successfully removed #{-points} from your #{stat} priority.", player: @buildRESTObject()} module.exports = exports = Player
45126
Character = require "../base/Character" RestrictedNumber = require "restricted-number" MessageCreator = require "../../system/MessageCreator" Constants = require "../../system/Constants" Equipment = require "../../item/Equipment" _ = require "lodash" Q = require "q" Personality = require "../base/Personality" requireDir = require "require-dir" regions = requireDir "../regions" PushBullet = require "pushbullet" Chance = require "chance" chance = new Chance Math.random class Player extends Character isBusy: false permanentAchievements: {} constructor: (player) -> super player canEquip: (item, rangeBoost = 1) -> myItem = _.findWhere @equipment, {type: item.type} return false if not myItem score = @calc.itemScore item myScore = @calc.itemScore myItem realScore = item.score() score > myScore and realScore < @calc.itemFindRange()*rangeBoost initialize: -> if not @xp @xp = new RestrictedNumber 0, (@levelUpXpCalc 0), 0 @gold = new RestrictedNumber 0, 9999999999, 0 @x = 10 @y = 10 @map = 'Norkos' norkosClasses = ['Generalist', 'Mage', 'Fighter', 'Cleric'] @changeProfession (_.sample norkosClasses), yes @levelUp yes @generateBaseEquipment() @overflow = [] @lastLogin = new Date() @gender = "female" @priorityPoints = {dex: 1, str: 1, agi: 1, wis: 1, con: 1, int: 1} @calc.itemFindRange() generateBaseEquipment: -> @equipment = [ new Equipment {type: "body", class: "newbie", name: "Tattered Shirt", con: 1} new Equipment {type: "feet", class: "newbie", name: "Cardboard Shoes", dex: 1} new Equipment {type: "finger", class: "newbie", name: "Twisted Wire", int: 1} new Equipment {type: "hands", class: "newbie", name: "Pixelated Gloves", str: 1} new Equipment {type: "head", class: "newbie", name: "Miniature Top Hat", wis: 1} new Equipment {type: "legs", class: "newbie", name: "Leaf", agi: 1} new Equipment {type: "neck", class: "newbie", name: "Old Brooch", wis: 1, int: 1} new Equipment {type: "mainhand",class: "newbie", name: "Empty and Broken Ale Bottle", str: 1, con: -1} new Equipment {type: "offhand", class: "newbie", name: "Chunk of Rust", dex: 1, str: 1} new Equipment {type: "charm", class: "newbie", name: "Ancient Bracelet", con: 1, dex: 1} ] setPushbulletKey: (key) -> @pushbulletApiKey = key @pushbulletSend "This is a test for Idle Lands" if key Q {isSuccess: yes, code: 99, message: "Your PushBullet API key has been #{if key then "added" else "removed"} successfully. You should also have gotten a test message!"} pushbulletSend: (message, link = null) -> pushbullet = new PushBullet @pushbulletApiKey if @pushbulletApiKey return if not pushbullet pushbullet.devices (e, res) -> _.each res?.devices, (device) -> if link pushbullet.link device.iden, message, link, (e, res) -> else pushbullet.note device.iden, 'IdleLands', message, (e, res) -> handleGuildStatus: -> if not @guild @guildStatus = -1 else gm = @playerManager.game.guildManager gm.waitForGuild().then => guild = gm.guildHash[@guild] # In case the database update failed for an offline player if not guild or not gm.findMember @name, @guild @guild = null @guildStatus = -1 else if playerGuild.leader is @identifier @guildStatus = 2 guild.leaderName =<NAME> @name guild.save() else if _.findWhere guild.members, {identifier: @identifier, isAdmin: yes} @guildStatus = 1 else @guildStatus = 0 manageOverflow: (option, slot) -> defer = Q.defer() @overflow = [] if not @overflow cleanOverflow = => @overflow = _.compact _.reject @overflow, (item) -> item?.name is "empty" switch option when "add" @addOverflow slot, defer when "swap" @swapOverflow slot, defer cleanOverflow() when "sell" @sellOverflow slot, defer cleanOverflow() @recalculateStats() defer.promise forceIntoOverflow: (item) -> # no params = no problems do @manageOverflow @overflow.push item addOverflow: (slot, defer) -> if not (slot in ["body","feet","finger","hands","head","legs","neck","mainhand","offhand","charm","trinket"]) return defer.resolve {isSuccess: no, code: 40, message: "That slot is invalid."} if @overflow.length is Constants.defaults.player.maxOverflow return defer.resolve {isSuccess: no, code: 41, message: "Your inventory is currently full!"} currentItem = _.findWhere @equipment, {type: slot} if currentItem.name is "empty" return defer.resolve {isSuccess: no, code: 42, message: "You can't add empty items to your inventory!"} @overflow.push currentItem @equipment = _.without @equipment, currentItem @equipment.push new Equipment {type: slot, name: "empty"} defer.resolve {isSuccess: yes, code: 45, message: "Successfully added #{currentItem.name} to your inventory in slot #{@overflow.length-1}.", player: @buildRESTObject()} swapOverflow: (slot, defer) -> if not @overflow[slot] return defer.resolve {isSuccess: no, code: 43, message: "You don't have anything in that inventory slot."} current = _.findWhere @equipment, {type: @overflow[slot].type} inOverflow = @overflow[slot] if not @canEquip inOverflow return defer.resolve {isSuccess: no, code: 43, message: "A mysterious force compels you to not equip that item. It may be too powerful."} @equip inOverflow if current.name isnt "empty" @overflow[slot] = current return defer.resolve {isSuccess: yes, code: 47, message: "Successfully swapped #{current.name} with #{inOverflow.name} (slot #{slot}).", player: @buildRESTObject()} @overflow[slot] = null defer.resolve {isSuccess: yes, code: 47, message: "Successfully equipped #{inOverflow.name} (slot #{slot}).", player: @buildRESTObject()} sellOverflow: (slot, defer) -> curItem = @overflow[slot] if (not curItem) or (curItem.name is "empty") return defer.resolve {isSuccess: yes, code: 44, message: "That item is not able to be sold!"} salePrice = Math.max 2, @calcGoldGain Math.round curItem.score()*@calc.itemSellMultiplier curItem @gainGold salePrice @overflow[slot] = null defer.resolve {isSuccess: yes, code: 46, message: "Successfully sold #{curItem.name} for #{salePrice} gold.", player: @buildRESTObject()} handleTrainerOnTile: (tile) -> return if @isBusy or @stepCooldown > 0 @isBusy = true className = tile.object.name message = "<player.name>#{@name}</player.name> has met with the <player.class>#{className}</player.class> trainer!" if @professionName is className message += " Alas, <player.name>#{@name}</player.name> is already a <player.class>#{className}</player.class>!" @isBusy = false @emit "player.trainer.isAlready", @, className @stepCooldown = 10 @playerManager.game.eventHandler.broadcastEvent {message: message, player: @, type: 'profession'} if @professionName isnt className and (chance.bool likelihood: @calc.classChangePercent className) @playerManager.game.eventHandler.doYesNo {}, @, (result) => @isBusy = false if not result @emit "player.trainer.ignore", @, className return @emit "player.trainer.speak", @, className @changeProfession className handleTeleport: (tile) -> return if @stepCooldown > 0 @stepCooldown = 30 dest = tile.object.properties dest.x = parseInt dest.destx dest.y = parseInt dest.desty newLoc = dest if not dest.map and not dest.toLoc @playerManager.game.errorHandler.captureMessage "ERROR. No dest.map at #{@x},#{@y} in #{@map}" return if not dest.movementType @playerManager.game.errorHandler.captureMessage "ERROR. No dest.movementType at #{@x},#{@y} in #{@map}" return dest.movementType = dest.movementType.toLowerCase() eventToTest = "#{dest.movementType}Chance" prob = @calc[eventToTest]() return if not chance.bool({likelihood: prob}) handleLoc = no dest.fromName = @map if not dest.fromName dest.destName = dest.map if not dest.destName if dest.toLoc newLoc = @playerManager.game.gmCommands.lookupLocation dest.toLoc if not newLoc @playerManager.game.errorHandler.captureMessage "BAD TELEPORT LOCATION #{dest.toLoc}" @map = newLoc.map @x = newLoc.x @y = newLoc.y handleLoc = yes dest.destName = newLoc.formalName else @map = newLoc.map @x = newLoc.x @y = newLoc.y @oldRegion = @mapRegion @mapRegion = newLoc.region message = "" switch dest.movementType when "ascend" then message = "<player.name>#{@name}</player.name> has ascended to <event.transfer.destination>#{dest.destName}</event.transfer.destination>." when "descend" then message = "<player.name>#{@name}</player.name> has descended to <event.transfer.destination>#{dest.destName}</event.transfer.destination>." when "fall" then message = "<player.name>#{@name}</player.name> has fallen from <event.transfer.from>#{dest.fromName}</event.transfer.from> to <event.transfer.destination>#{dest.destName}</event.transfer.destination>!" when "teleport" then message = "<player.name>#{@name}</player.name> was teleported from <event.transfer.from>#{dest.fromName}</event.transfer.from> to <event.transfer.destination>#{dest.destName}</event.transfer.destination>!" if @hasPersonality "Wheelchair" if dest.movementType is "descend" message = "<player.name>#{@name}</player.name> went crashing down in a wheelchair to <event.transfer.destination>#{dest.destName}</event.transfer.destination>." @emit "explore.transfer", @, @map @emit "explore.transfer.#{dest.movementType}", @, @map @playerManager.game.eventHandler.broadcastEvent {message: message, player: @, type: 'explore'} @handleTile @getTileAt() if handleLoc handleTile: (tile) -> switch tile.object?.type when "Boss" then @handleBossBattle tile.object.name when "BossParty" then @handleBossBattleParty tile.object.name when "Teleport" then @handleTeleport tile when "Trainer" then @handleTrainerOnTile tile when "Treasure" then @handleTreasure tile.object.name when "Collectible" then @handleCollectible tile.object if tile.object?.properties?.forceEvent @playerManager.game.eventHandler.doEventForPlayer @name, tile.object.properties.forceEvent handleCollectible: (collectible) -> @collectibles = [] if not @collectibles collectibleName = collectible.name collectibleRarity = collectible.properties?.rarity or "basic" current = _.findWhere @collectibles, {name: collectibleName, map: @map} return if current @collectibles.push name: collectibleName map: @map region: @mapRegion rarity: collectibleRarity foundAt: Date.now() message = "<player.name>#{@name}</player.name> stumbled across a rare, shiny, and collectible <event.item.#{collectibleRarity}>#{collectibleName}</event.item.#{collectibleRarity}> in #{@map} - #{@mapRegion}!" @playerManager.game.eventHandler.broadcastEvent {message: message, player: @, type: 'event'} handleTreasure: (treasure) -> @playerManager.game.treasureFactory.createTreasure treasure, @ handleBossBattle: (bossName) -> @playerManager.game.eventHandler.bossBattle @, bossName handleBossBattleParty: (bossParty) -> @playerManager.game.eventHandler.bossPartyBattle @, bossParty pickRandomTile: -> @ignoreDir = [] if not @ignoreDir @stepCooldown = 0 if not @stepCooldown randomDir = -> chance.integer({min: 1, max: 9}) dir = randomDir() dir = randomDir() while dir in @ignoreDir drunkAdjustedProb = Math.max 0, 80 - (@calc.drunk() * 10) dir = if chance.bool {likelihood: drunkAdjustedProb} then @lastDir else dir [(@num2dir dir, @x, @y), dir] getTileAt: (x = @x, y = @y) -> lookAtTile = @playerManager.game.world.maps[@map].getTile.bind @playerManager.game.world.maps[@map] lookAtTile x,y getRegion: -> regions[@getTileAt().region.replace(/\s/g, '')] cantEnterTile: (tile) -> return @statistics['calculated map changes'][tile.object.properties.requireMap] if tile.object?.properties?.requireMap return @statistics['calculated regions visited'][tile.object.properties.requireRegion] if tile.object?.properties?.requireRegion return @statistics['calculated boss kills'][tile.object.properties.requireBoss] if tile.object?.properties?.requireBoss return no if tile.object?.properties?.requireClass and @professionName isnt tile.object?.properties?.requireClass return no if not @collectibles or not _.findWhere @collectibles, {name: tile.object?.properties?.requireCollectible} return no if not @achievements or not _.findWhere @achievements, {name: tile.object?.properties?.requireAchievement} tile.blocked moveAction: (currentStep) -> [newLoc, dir] = @pickRandomTile() try tile = @getTileAt newLoc.x,newLoc.y #drunkAdjustedProb = Math.max 0, 95 - (@calc.drunk() * 5) while @cantEnterTile tile [newLoc, dir] = @pickRandomTile() tile = @getTileAt newLoc.x, newLoc.y if not tile.blocked @x = newLoc.x @y = newLoc.y @lastDir = dir @ignoreDir = [] else @lastDir = null @ignoreDir.push dir @emit 'explore.hit.wall', @ @oldRegion = @mapRegion @mapRegion = tile.region @emit 'explore.walk', @ @emit "explore.walk.#{tile.terrain or "void"}".toLowerCase(), @ @playerManager.game.errorHandler.captureMessage @x,@y,@map,tile.terrain,tile, "INVALID TILE" if not tile.terrain and not tile.blocked @handleTile tile @stepCooldown-- @gainXp @calcXpGain 10 if currentStep < 5 catch e @playerManager.game.errorHandler.captureException e, extra: map: @map, x: @x, y: @y @x = @y = 10 @map = "Norkos" changeProfession: (to, suppress = no) -> @profession?.unload? @ oldProfessionName = @professionName professionProto = require "../classes/#{to}" @profession = new professionProto() @professionName = professionProto.name @profession.load @ message = "<player.name>#{<NAME>@name}</player.name> is now a <player.class>#{to}</player.class>!" @playerManager.game.eventHandler.broadcastEvent {message: message, player: @, type: 'profession'} if not suppress @emit "player.profession.change", @, oldProfessionName, @professionName @recalculateStats() getGender: -> if @gender then @gender else "female" setGender: (newGender) -> @gender = newGender.substring 0,15 @gender = 'indeterminate' if not @gender Q {isSuccess: yes, code: 97, message: "Your gender is now #{@gender}."} score: -> @calc.partyScore() possiblyDoEvent: -> event = Constants.pickRandomEvent @ return if not event @playerManager.game.eventHandler.doEvent event, @, ->{} #god damned code collapse possiblyLeaveParty: -> return if not @party return if @party.currentBattle return if not chance.bool {likelihood: @calc.partyLeavePercent()} @party.playerLeave @ checkShop: -> @shop = null if @shop and ((not @getRegion()?.shopSlots?()) or (@getRegion()?.name isnt @shop.region)) @shop = @playerManager.game.shopGenerator.regionShop @ if not @shop and @getRegion()?.shopSlots?() buyShop: (slot) -> if not @shop.slots[slot] return Q {isSuccess: no, code: 123, message: "The shop doesn't have an item in slot #{slot}."} if @shop.slots[slot].price > @gold.getValue() return Q {isSuccess: no, code: 124, message: "That item costs #{@shop.slots[slot].price} gold, but you only have #{@gold.getValue()} gold."} resolved = Q {isSuccess: yes, code: 125, message: "Successfully purchased #{@shop.slots[slot].item.name} for #{@shop.slots[slot].price} gold.", player: @buildRESTObject()} @gold.sub @shop.slots[slot].price @emit "player.shop.buy", @, @shop.slots[slot].item, @shop.slots[slot].price @equip @shop.slots[slot].item @shop.slots[slot] = null @shop.slots = _.compact @shop.slots @save() resolved takeTurn: -> steps = Math.max 1, @calc.haste() @moveAction steps while steps-- isnt 0 @possiblyDoEvent() @possiblyLeaveParty() @checkShop() @checkPets() @save() @ checkPets: -> @playerManager.game.petManager.handlePetsForPlayer @ buyPet: (pet, name, attr1 = "a monocle", attr2 = "a top hat") -> name = name.trim() attr1 = attr1.trim() attr2 = attr2.trim() return Q {isSuccess: no, code: 200, message: "You need to specify all required information to make a pet."} if not name or not attr1 or not attr2 return Q {isSuccess: no, code: 201, message: "Your information needs to be less than 20 characters."} if name.length > 20 or attr1.length > 20 or attr2.length > 20 return Q {isSuccess: no, code: 202, message: "You haven't unlocked that pet."} if not @foundPets[pet] return Q {isSuccess: no, code: 203, message: "You've already purchased that pet."} if @foundPets[pet].purchaseDate return Q {isSuccess: no, code: 204, message: "You don't have enough gold to buy that pet! You need #{@foundPets[pet].cost -@gold.getValue()} more gold."} if @foundPets[pet].cost > @gold.getValue() @gold.sub @foundPets[pet].cost petManager = @playerManager.game.petManager petManager.createPet player: @ type: pet name: name attr1: attr1 attr2: attr2 @emit "player.shop.pet" pet = petManager.getActivePetFor @ Q {isSuccess: yes, code: 205, message: "Successfully purchased a new pet (#{pet.type}) named '#{name}'!", pet: pet.buildSaveObject(), pets: petManager.getPetsForPlayer @identifier} upgradePet: (stat) -> pet = @getPet() config = pet.petManager.getConfig pet curLevel = pet.scaleLevel[stat] cost = config.scaleCost[stat][curLevel+1] return Q {isSuccess: no, code: 206, message: "You don't have a pet."} if not pet return Q {isSuccess: no, code: 209, message: "That stat is invalid."} if not config.scale[stat] return Q {isSuccess: no, code: 210, message: "That stat is already at max level."} if config.scale[stat].length <= curLevel+1 or not cost return Q {isSuccess: no, code: 211, message: "You don't have enough gold to upgrade your pet. You need #{cost-@gold.getValue()} more gold."} if @gold.getValue() < cost @gold.sub cost pet.increaseStat stat @emit "player.shop.petupgrade" Q {isSuccess: yes, code: 212, message: "Successfully upgraded your pets (#{pet.name}) #{stat} to level #{curLevel+2}!", pet: pet.buildSaveObject()} changePetClass: (newClass) -> myClasses = _.keys @statistics['calculated class changes'] pet = @getPet() return Q {isSuccess: no, code: 206, message: "You don't have a pet."} if not pet return Q {isSuccess: no, code: 207, message: "You haven't been that class yet, so you can't teach your pet how to do it!"} if (myClasses.indexOf newClass) is -1 and newClass isnt "Monster" pet.setClassTo newClass Q {isSuccess: yes, code: 208, message: "Successfully changed your pets (#{pet.name}) class to #{newClass}!", pet: pet.buildSaveObject()} takePetGold: -> pet = @getPet() return Q {isSuccess: no, code: 206, message: "You don't have a pet."} if not pet return Q {isSuccess: no, code: 233, message: "Your pet has no gold."} if pet.gold.atMin() gold = pet.gold.getValue() @gold.add gold pet.gold.toMinimum() Q {isSuccess: yes, code: 232, message: "You took #{gold} gold from your pet.", pet: pet.buildSaveObject()} feedPet: -> pet = @getPet() return Q {isSuccess: no, code: 206, message: "You don't have a pet."} if not pet return Q {isSuccess: no, code: 213, message: "Your pet is already at max level."} if pet.level.atMax() gold = pet.goldToNextLevel() return Q {isSuccess: no, code: 214, message: "You don't have enough gold for that! You need #{gold-@gold.getValue()} more gold."} if @gold.lessThan gold @gold.sub gold pet.feed() Q {isSuccess: yes, code: 215, message: "Your pet (#{pet.name}) was fed #{gold} gold and gained a level (#{pet.level.getValue()}).", pet: pet.buildSaveObject()} getPetGold: -> pet = @getPet() return Q {isSuccess: no, code: 206, message: "You don't have a pet."} if not pet petMoney = pet.gold.getValue() return Q {isSuccess: no, code: 216, message: "Your pet is penniless."} if not petMoney @gold.add petMoney pet.gold.toMinimum() Q {isSuccess: yes, code: 217, message: "You retrieved #{petMoney} gold from your pet (#{pet.name})!", pet: pet.buildSaveObject()} sellPetItem: (itemSlot) -> pet = @getPet() return Q {isSuccess: no, code: 206, message: "You don't have a pet."} if not pet item = pet.inventory[itemSlot] return Q {isSuccess: no, code: 218, message: "Your pet does not have an item in that slot!"} if not item pet.inventory = _.without pet.inventory, item value = pet.sellItem item, no Q {isSuccess: yes, code: 219, message: "Your pet (#{pet.name}) sold #{item.name} for #{value} gold!", pet: pet.buildSaveObject()} givePetItem: (itemSlot) -> pet = @getPet() return Q {isSuccess: no, code: 206, message: "You don't have a pet."} if not pet return Q {isSuccess: no, code: 220, message: "Your pet's inventory is full!"} if not pet.hasInventorySpace() curItem = @overflow[itemSlot] return Q {isSuccess: no, code: 43, message: "You don't have anything in that inventory slot."} if not curItem pet.addToInventory curItem @overflow = _.without @overflow, curItem Q {isSuccess: yes, code: 221, message: "Successfully gave #{curItem.name} to your pet (#{pet.name}).", pet: pet.buildSaveObject()} takePetItem: (itemSlot) -> pet = @getPet() return Q {isSuccess: no, code: 206, message: "You don't have a pet."} if not pet return Q {isSuccess: no, code: 41, message: "Your inventory is currently full!"} if @overflow.length is Constants.defaults.player.maxOverflow curItem = pet.inventory[itemSlot] return Q {isSuccess: no, code: 218, message: "Your pet doesn't have anything in that inventory slot."} if not curItem @overflow.push curItem pet.removeFromInventory curItem Q {isSuccess: yes, code: 221, message: "Successfully took #{curItem.name} from your pet (#{pet.name}).", pet: pet.buildSaveObject()} setPetOption: (option, value) -> pet = @getPet() return Q {isSuccess: no, code: 206, message: "You don't have a pet."} if not pet return Q {isSuccess: no, code: 222, message: "That option is invalid."} if not (option in ["smartSell", "smartEquip", "smartSelf"]) pet[option] = value Q {isSuccess: yes, code: 223, message: "Successfully set #{option} to #{value} for #{pet.name}.", pet: pet.buildSaveObject()} equipPetItem: (itemSlot) -> pet = @getPet() return Q {isSuccess: no, code: 206, message: "You don't have a pet."} if not pet item = pet.inventory[itemSlot] return Q {isSuccess: no, code: 218, message: "Your pet does not have an item in that slot!"} if not item return Q {isSuccess: no, code: 224, message: "Your pet is not so talented as to have that item slot!"} if not pet.hasEquipmentSlot item.type return Q {isSuccess: no, code: 224, message: "Your pet cannot equip that item! Either it is too strong, or your pets equipment slots are full."} if not pet.canEquip item pet.equip item Q {isSuccess: yes, code: 225, message: "Successfully equipped your pet (#{pet.name}) with #{item.name}.", pet: newPet.buildSaveObject()} unequipPetItem: (uid) -> pet = @getPet() return Q {isSuccess: no, code: 206, message: "You don't have a pet."} if not pet item = pet.findEquipped uid return Q {isSuccess: no, code: 226, message: "Your pet does not have that item equipped!"} if not item return Q {isSuccess: no, code: 231, message: "You can't unequip your pets soul, you jerk!"} if item.type is "pet soul" return Q {isSuccess: no, code: 220, message: "Your pet's inventory is full!"} if not pet.hasInventorySpace() pet.unequip item Q {isSuccess: yes, code: 227, message: "Successfully unequipped #{item.name} from your pet (#{pet.name}).", pet: pet.buildSaveObject()} swapToPet: (petId) -> pet = @getPet() return Q {isSuccess: no, code: 206, message: "You don't have a pet."} if not pet newPet = _.findWhere pet.petManager.pets, (pet) => pet.createdAt is petId and pet.owner.name is @name return Q {isSuccess: no, code: 228, message: "That pet does not exist!"} if not newPet return Q {isSuccess: no, code: 229, message: "That pet is already active!"} if newPet is pet pet.petManager.changePetForPlayer @, newPet Q {isSuccess: yes, code: 230, message: "Successfully made #{newPet.name}, the #{newPet.type} your active pet!", pet: newPet.buildSaveObject(), pets: pet.petManager.getPetsForPlayer @identifier} save: -> return if not @playerManager @playerManager.savePlayer @ getPet: -> @playerManager.game.petManager.getActivePetFor @ gainGold: (gold) -> if _.isNaN gold @playerManager.game.errorHandler.captureException new Error "BAD GOLD VALUE GOTTEN SOMEHOW" gold = 1 if gold > 0 @emit "player.gold.gain", @, gold else @emit "player.gold.lose", @, gold @gold.add gold gainXp: (xp) -> if xp > 0 @emit "player.xp.gain", @, xp else @emit "player.xp.lose", @, xp @xp.set 0 if _.isNaN @xp.__current @xp.add xp @levelUp() if @xp.atMax() buildRESTObject: -> @playerManager.buildPlayerSaveObject @ levelUp: (suppress = no) -> return if not @playerManager or @level.getValue() is @level.maximum @level.add 1 message = "<player.name>#{@name}</player.name> has attained level <player.level>#{@level.getValue()}</player.level>!" @resetMaxXp() @xp.toMinimum() @recalculateStats() @playerManager.game.eventHandler.broadcastEvent {message: message, player: @, type: 'levelup'} if not suppress @recalcGuildLevel() @emit "player.level.up", @ @playerManager.addForAnalytics @ recalcGuildLevel: -> return if not @guild @playerManager.game.guildManager.guildHash[@guild].avgLevel() setString: (type, val = '') -> @messages = {} if not @messages @messages[type] = val.substring 0, 99 if not @messages[type] delete @messages[type] return Q {isSuccess: yes, code: 95, message: "Successfully updated your string settings. Removed string type \"#{type}.\""} Q {isSuccess: yes, code: 95, message: "Successfully updated your string settings. String \"#{type}\" is now: #{if val then val else 'empty!'}"} checkAchievements: (silent = no) -> @_oldAchievements = _.compact _.clone @achievements @achievements = [] achieved = @playerManager.game.achievementManager.getAllAchievedFor @ stringCurrent = _.map @_oldAchievements, (achievement) -> achievement.name stringAll = _.map achieved, (achievement) -> achievement.name newAchievements = _.difference stringAll, stringCurrent _.each newAchievements, (achievementName) => achievement = _.findWhere achieved, name: achievementName @achievements.push achievement if not silent message = "<player.name>#{@name}</player.name> has achieved <event.achievement>#{achievementName}</event.achievement> (#{achievement.desc} | #{achievement.reward})" @playerManager.game.eventHandler.broadcastEvent {message: message, player: @, type: 'achievement'} if not silent @achievements = achieved itemPriority: (item) -> if not @priorityPoints @priorityPoints = {dex: 1, str: 1, agi: 1, wis: 1, con: 1, int: 1} ret = 0 ret += item[stat]*@priorityPoints[stat]*Constants.defaults.player.priorityScale for stat in ["dex", "str", "agi", "wis", "con", "int"] ret priorityTotal: -> _.reduce @priorityPoints, ((total, stat) -> total + stat), 0 setPriorities: (stats) -> if not @priorityPoints @priorityPoints = {dex: 1, str: 1, agi: 1, wis: 1, con: 1, int: 1} if _.size stats != 6 return Q {isSuccess: no, code: 111, message: "Priority list is invalid. Expected 6 items"} total = 0 sanitizedStats = {} for key, stat of stats if !_.isNumber stat return Q {isSuccess: no, code: 112, message: "Priority \"" + key + "\" is not a number."} if not (key in ["<KEY>", "<KEY>", "<KEY>", "<KEY>", "<KEY>", "int"]) return Q {isSuccess: no, code: 111, message: "Key \"" + key + "\" is invalid."} sanitizedStats[key] = Math.round stat total += Math.round stat if total != Constants.defaults.player.priorityTotal return Q {isSuccess: no, code: 112, message: "Number of priority points are not equal to " + Constants.defaults.player.priorityTotal + "."} @priorityPoints = sanitizedStats return Q {isSuccess: yes, code: 113, message: "Successfully set priorities.", player: @buildRESTObject()} addPriority: (stat, points) -> if not @priorityPoints @priorityPoints = {dex: 1, str: 1, agi: 1, wis: 1, con: 1, int: 1} points = if _.isNumber points then points else parseInt points points = Math.round points if points is 0 return Q {isSuccess: no, code: 110, message: "You didn't specify a valid priority point amount."} if not (stat in ["dex", "str", "agi", "wis", "con", "int"]) return Q {isSuccess: no, code: 111, message: "That stat is invalid."} if points > 0 and @priorityTotal() + points > Constants.defaults.player.priorityTotal return Q {isSuccess: no, code: 112, message: "Not enough priority points remaining."} if points < 0 and @priorityPoints[stat] + points < 0 return Q {isSuccess: no, code: 112, message: "Not enough priority points to remove."} @priorityPoints[stat] += points if points > 0 return Q {isSuccess: yes, code: 113, message: "Successfully added #{points} to your #{stat} priority.", player: @buildRESTObject()} else return Q {isSuccess: yes, code: 113, message: "Successfully removed #{-points} from your #{stat} priority.", player: @buildRESTObject()} module.exports = exports = Player
true
Character = require "../base/Character" RestrictedNumber = require "restricted-number" MessageCreator = require "../../system/MessageCreator" Constants = require "../../system/Constants" Equipment = require "../../item/Equipment" _ = require "lodash" Q = require "q" Personality = require "../base/Personality" requireDir = require "require-dir" regions = requireDir "../regions" PushBullet = require "pushbullet" Chance = require "chance" chance = new Chance Math.random class Player extends Character isBusy: false permanentAchievements: {} constructor: (player) -> super player canEquip: (item, rangeBoost = 1) -> myItem = _.findWhere @equipment, {type: item.type} return false if not myItem score = @calc.itemScore item myScore = @calc.itemScore myItem realScore = item.score() score > myScore and realScore < @calc.itemFindRange()*rangeBoost initialize: -> if not @xp @xp = new RestrictedNumber 0, (@levelUpXpCalc 0), 0 @gold = new RestrictedNumber 0, 9999999999, 0 @x = 10 @y = 10 @map = 'Norkos' norkosClasses = ['Generalist', 'Mage', 'Fighter', 'Cleric'] @changeProfession (_.sample norkosClasses), yes @levelUp yes @generateBaseEquipment() @overflow = [] @lastLogin = new Date() @gender = "female" @priorityPoints = {dex: 1, str: 1, agi: 1, wis: 1, con: 1, int: 1} @calc.itemFindRange() generateBaseEquipment: -> @equipment = [ new Equipment {type: "body", class: "newbie", name: "Tattered Shirt", con: 1} new Equipment {type: "feet", class: "newbie", name: "Cardboard Shoes", dex: 1} new Equipment {type: "finger", class: "newbie", name: "Twisted Wire", int: 1} new Equipment {type: "hands", class: "newbie", name: "Pixelated Gloves", str: 1} new Equipment {type: "head", class: "newbie", name: "Miniature Top Hat", wis: 1} new Equipment {type: "legs", class: "newbie", name: "Leaf", agi: 1} new Equipment {type: "neck", class: "newbie", name: "Old Brooch", wis: 1, int: 1} new Equipment {type: "mainhand",class: "newbie", name: "Empty and Broken Ale Bottle", str: 1, con: -1} new Equipment {type: "offhand", class: "newbie", name: "Chunk of Rust", dex: 1, str: 1} new Equipment {type: "charm", class: "newbie", name: "Ancient Bracelet", con: 1, dex: 1} ] setPushbulletKey: (key) -> @pushbulletApiKey = key @pushbulletSend "This is a test for Idle Lands" if key Q {isSuccess: yes, code: 99, message: "Your PushBullet API key has been #{if key then "added" else "removed"} successfully. You should also have gotten a test message!"} pushbulletSend: (message, link = null) -> pushbullet = new PushBullet @pushbulletApiKey if @pushbulletApiKey return if not pushbullet pushbullet.devices (e, res) -> _.each res?.devices, (device) -> if link pushbullet.link device.iden, message, link, (e, res) -> else pushbullet.note device.iden, 'IdleLands', message, (e, res) -> handleGuildStatus: -> if not @guild @guildStatus = -1 else gm = @playerManager.game.guildManager gm.waitForGuild().then => guild = gm.guildHash[@guild] # In case the database update failed for an offline player if not guild or not gm.findMember @name, @guild @guild = null @guildStatus = -1 else if playerGuild.leader is @identifier @guildStatus = 2 guild.leaderName =PI:NAME:<NAME>END_PI @name guild.save() else if _.findWhere guild.members, {identifier: @identifier, isAdmin: yes} @guildStatus = 1 else @guildStatus = 0 manageOverflow: (option, slot) -> defer = Q.defer() @overflow = [] if not @overflow cleanOverflow = => @overflow = _.compact _.reject @overflow, (item) -> item?.name is "empty" switch option when "add" @addOverflow slot, defer when "swap" @swapOverflow slot, defer cleanOverflow() when "sell" @sellOverflow slot, defer cleanOverflow() @recalculateStats() defer.promise forceIntoOverflow: (item) -> # no params = no problems do @manageOverflow @overflow.push item addOverflow: (slot, defer) -> if not (slot in ["body","feet","finger","hands","head","legs","neck","mainhand","offhand","charm","trinket"]) return defer.resolve {isSuccess: no, code: 40, message: "That slot is invalid."} if @overflow.length is Constants.defaults.player.maxOverflow return defer.resolve {isSuccess: no, code: 41, message: "Your inventory is currently full!"} currentItem = _.findWhere @equipment, {type: slot} if currentItem.name is "empty" return defer.resolve {isSuccess: no, code: 42, message: "You can't add empty items to your inventory!"} @overflow.push currentItem @equipment = _.without @equipment, currentItem @equipment.push new Equipment {type: slot, name: "empty"} defer.resolve {isSuccess: yes, code: 45, message: "Successfully added #{currentItem.name} to your inventory in slot #{@overflow.length-1}.", player: @buildRESTObject()} swapOverflow: (slot, defer) -> if not @overflow[slot] return defer.resolve {isSuccess: no, code: 43, message: "You don't have anything in that inventory slot."} current = _.findWhere @equipment, {type: @overflow[slot].type} inOverflow = @overflow[slot] if not @canEquip inOverflow return defer.resolve {isSuccess: no, code: 43, message: "A mysterious force compels you to not equip that item. It may be too powerful."} @equip inOverflow if current.name isnt "empty" @overflow[slot] = current return defer.resolve {isSuccess: yes, code: 47, message: "Successfully swapped #{current.name} with #{inOverflow.name} (slot #{slot}).", player: @buildRESTObject()} @overflow[slot] = null defer.resolve {isSuccess: yes, code: 47, message: "Successfully equipped #{inOverflow.name} (slot #{slot}).", player: @buildRESTObject()} sellOverflow: (slot, defer) -> curItem = @overflow[slot] if (not curItem) or (curItem.name is "empty") return defer.resolve {isSuccess: yes, code: 44, message: "That item is not able to be sold!"} salePrice = Math.max 2, @calcGoldGain Math.round curItem.score()*@calc.itemSellMultiplier curItem @gainGold salePrice @overflow[slot] = null defer.resolve {isSuccess: yes, code: 46, message: "Successfully sold #{curItem.name} for #{salePrice} gold.", player: @buildRESTObject()} handleTrainerOnTile: (tile) -> return if @isBusy or @stepCooldown > 0 @isBusy = true className = tile.object.name message = "<player.name>#{@name}</player.name> has met with the <player.class>#{className}</player.class> trainer!" if @professionName is className message += " Alas, <player.name>#{@name}</player.name> is already a <player.class>#{className}</player.class>!" @isBusy = false @emit "player.trainer.isAlready", @, className @stepCooldown = 10 @playerManager.game.eventHandler.broadcastEvent {message: message, player: @, type: 'profession'} if @professionName isnt className and (chance.bool likelihood: @calc.classChangePercent className) @playerManager.game.eventHandler.doYesNo {}, @, (result) => @isBusy = false if not result @emit "player.trainer.ignore", @, className return @emit "player.trainer.speak", @, className @changeProfession className handleTeleport: (tile) -> return if @stepCooldown > 0 @stepCooldown = 30 dest = tile.object.properties dest.x = parseInt dest.destx dest.y = parseInt dest.desty newLoc = dest if not dest.map and not dest.toLoc @playerManager.game.errorHandler.captureMessage "ERROR. No dest.map at #{@x},#{@y} in #{@map}" return if not dest.movementType @playerManager.game.errorHandler.captureMessage "ERROR. No dest.movementType at #{@x},#{@y} in #{@map}" return dest.movementType = dest.movementType.toLowerCase() eventToTest = "#{dest.movementType}Chance" prob = @calc[eventToTest]() return if not chance.bool({likelihood: prob}) handleLoc = no dest.fromName = @map if not dest.fromName dest.destName = dest.map if not dest.destName if dest.toLoc newLoc = @playerManager.game.gmCommands.lookupLocation dest.toLoc if not newLoc @playerManager.game.errorHandler.captureMessage "BAD TELEPORT LOCATION #{dest.toLoc}" @map = newLoc.map @x = newLoc.x @y = newLoc.y handleLoc = yes dest.destName = newLoc.formalName else @map = newLoc.map @x = newLoc.x @y = newLoc.y @oldRegion = @mapRegion @mapRegion = newLoc.region message = "" switch dest.movementType when "ascend" then message = "<player.name>#{@name}</player.name> has ascended to <event.transfer.destination>#{dest.destName}</event.transfer.destination>." when "descend" then message = "<player.name>#{@name}</player.name> has descended to <event.transfer.destination>#{dest.destName}</event.transfer.destination>." when "fall" then message = "<player.name>#{@name}</player.name> has fallen from <event.transfer.from>#{dest.fromName}</event.transfer.from> to <event.transfer.destination>#{dest.destName}</event.transfer.destination>!" when "teleport" then message = "<player.name>#{@name}</player.name> was teleported from <event.transfer.from>#{dest.fromName}</event.transfer.from> to <event.transfer.destination>#{dest.destName}</event.transfer.destination>!" if @hasPersonality "Wheelchair" if dest.movementType is "descend" message = "<player.name>#{@name}</player.name> went crashing down in a wheelchair to <event.transfer.destination>#{dest.destName}</event.transfer.destination>." @emit "explore.transfer", @, @map @emit "explore.transfer.#{dest.movementType}", @, @map @playerManager.game.eventHandler.broadcastEvent {message: message, player: @, type: 'explore'} @handleTile @getTileAt() if handleLoc handleTile: (tile) -> switch tile.object?.type when "Boss" then @handleBossBattle tile.object.name when "BossParty" then @handleBossBattleParty tile.object.name when "Teleport" then @handleTeleport tile when "Trainer" then @handleTrainerOnTile tile when "Treasure" then @handleTreasure tile.object.name when "Collectible" then @handleCollectible tile.object if tile.object?.properties?.forceEvent @playerManager.game.eventHandler.doEventForPlayer @name, tile.object.properties.forceEvent handleCollectible: (collectible) -> @collectibles = [] if not @collectibles collectibleName = collectible.name collectibleRarity = collectible.properties?.rarity or "basic" current = _.findWhere @collectibles, {name: collectibleName, map: @map} return if current @collectibles.push name: collectibleName map: @map region: @mapRegion rarity: collectibleRarity foundAt: Date.now() message = "<player.name>#{@name}</player.name> stumbled across a rare, shiny, and collectible <event.item.#{collectibleRarity}>#{collectibleName}</event.item.#{collectibleRarity}> in #{@map} - #{@mapRegion}!" @playerManager.game.eventHandler.broadcastEvent {message: message, player: @, type: 'event'} handleTreasure: (treasure) -> @playerManager.game.treasureFactory.createTreasure treasure, @ handleBossBattle: (bossName) -> @playerManager.game.eventHandler.bossBattle @, bossName handleBossBattleParty: (bossParty) -> @playerManager.game.eventHandler.bossPartyBattle @, bossParty pickRandomTile: -> @ignoreDir = [] if not @ignoreDir @stepCooldown = 0 if not @stepCooldown randomDir = -> chance.integer({min: 1, max: 9}) dir = randomDir() dir = randomDir() while dir in @ignoreDir drunkAdjustedProb = Math.max 0, 80 - (@calc.drunk() * 10) dir = if chance.bool {likelihood: drunkAdjustedProb} then @lastDir else dir [(@num2dir dir, @x, @y), dir] getTileAt: (x = @x, y = @y) -> lookAtTile = @playerManager.game.world.maps[@map].getTile.bind @playerManager.game.world.maps[@map] lookAtTile x,y getRegion: -> regions[@getTileAt().region.replace(/\s/g, '')] cantEnterTile: (tile) -> return @statistics['calculated map changes'][tile.object.properties.requireMap] if tile.object?.properties?.requireMap return @statistics['calculated regions visited'][tile.object.properties.requireRegion] if tile.object?.properties?.requireRegion return @statistics['calculated boss kills'][tile.object.properties.requireBoss] if tile.object?.properties?.requireBoss return no if tile.object?.properties?.requireClass and @professionName isnt tile.object?.properties?.requireClass return no if not @collectibles or not _.findWhere @collectibles, {name: tile.object?.properties?.requireCollectible} return no if not @achievements or not _.findWhere @achievements, {name: tile.object?.properties?.requireAchievement} tile.blocked moveAction: (currentStep) -> [newLoc, dir] = @pickRandomTile() try tile = @getTileAt newLoc.x,newLoc.y #drunkAdjustedProb = Math.max 0, 95 - (@calc.drunk() * 5) while @cantEnterTile tile [newLoc, dir] = @pickRandomTile() tile = @getTileAt newLoc.x, newLoc.y if not tile.blocked @x = newLoc.x @y = newLoc.y @lastDir = dir @ignoreDir = [] else @lastDir = null @ignoreDir.push dir @emit 'explore.hit.wall', @ @oldRegion = @mapRegion @mapRegion = tile.region @emit 'explore.walk', @ @emit "explore.walk.#{tile.terrain or "void"}".toLowerCase(), @ @playerManager.game.errorHandler.captureMessage @x,@y,@map,tile.terrain,tile, "INVALID TILE" if not tile.terrain and not tile.blocked @handleTile tile @stepCooldown-- @gainXp @calcXpGain 10 if currentStep < 5 catch e @playerManager.game.errorHandler.captureException e, extra: map: @map, x: @x, y: @y @x = @y = 10 @map = "Norkos" changeProfession: (to, suppress = no) -> @profession?.unload? @ oldProfessionName = @professionName professionProto = require "../classes/#{to}" @profession = new professionProto() @professionName = professionProto.name @profession.load @ message = "<player.name>#{PI:NAME:<NAME>END_PI@name}</player.name> is now a <player.class>#{to}</player.class>!" @playerManager.game.eventHandler.broadcastEvent {message: message, player: @, type: 'profession'} if not suppress @emit "player.profession.change", @, oldProfessionName, @professionName @recalculateStats() getGender: -> if @gender then @gender else "female" setGender: (newGender) -> @gender = newGender.substring 0,15 @gender = 'indeterminate' if not @gender Q {isSuccess: yes, code: 97, message: "Your gender is now #{@gender}."} score: -> @calc.partyScore() possiblyDoEvent: -> event = Constants.pickRandomEvent @ return if not event @playerManager.game.eventHandler.doEvent event, @, ->{} #god damned code collapse possiblyLeaveParty: -> return if not @party return if @party.currentBattle return if not chance.bool {likelihood: @calc.partyLeavePercent()} @party.playerLeave @ checkShop: -> @shop = null if @shop and ((not @getRegion()?.shopSlots?()) or (@getRegion()?.name isnt @shop.region)) @shop = @playerManager.game.shopGenerator.regionShop @ if not @shop and @getRegion()?.shopSlots?() buyShop: (slot) -> if not @shop.slots[slot] return Q {isSuccess: no, code: 123, message: "The shop doesn't have an item in slot #{slot}."} if @shop.slots[slot].price > @gold.getValue() return Q {isSuccess: no, code: 124, message: "That item costs #{@shop.slots[slot].price} gold, but you only have #{@gold.getValue()} gold."} resolved = Q {isSuccess: yes, code: 125, message: "Successfully purchased #{@shop.slots[slot].item.name} for #{@shop.slots[slot].price} gold.", player: @buildRESTObject()} @gold.sub @shop.slots[slot].price @emit "player.shop.buy", @, @shop.slots[slot].item, @shop.slots[slot].price @equip @shop.slots[slot].item @shop.slots[slot] = null @shop.slots = _.compact @shop.slots @save() resolved takeTurn: -> steps = Math.max 1, @calc.haste() @moveAction steps while steps-- isnt 0 @possiblyDoEvent() @possiblyLeaveParty() @checkShop() @checkPets() @save() @ checkPets: -> @playerManager.game.petManager.handlePetsForPlayer @ buyPet: (pet, name, attr1 = "a monocle", attr2 = "a top hat") -> name = name.trim() attr1 = attr1.trim() attr2 = attr2.trim() return Q {isSuccess: no, code: 200, message: "You need to specify all required information to make a pet."} if not name or not attr1 or not attr2 return Q {isSuccess: no, code: 201, message: "Your information needs to be less than 20 characters."} if name.length > 20 or attr1.length > 20 or attr2.length > 20 return Q {isSuccess: no, code: 202, message: "You haven't unlocked that pet."} if not @foundPets[pet] return Q {isSuccess: no, code: 203, message: "You've already purchased that pet."} if @foundPets[pet].purchaseDate return Q {isSuccess: no, code: 204, message: "You don't have enough gold to buy that pet! You need #{@foundPets[pet].cost -@gold.getValue()} more gold."} if @foundPets[pet].cost > @gold.getValue() @gold.sub @foundPets[pet].cost petManager = @playerManager.game.petManager petManager.createPet player: @ type: pet name: name attr1: attr1 attr2: attr2 @emit "player.shop.pet" pet = petManager.getActivePetFor @ Q {isSuccess: yes, code: 205, message: "Successfully purchased a new pet (#{pet.type}) named '#{name}'!", pet: pet.buildSaveObject(), pets: petManager.getPetsForPlayer @identifier} upgradePet: (stat) -> pet = @getPet() config = pet.petManager.getConfig pet curLevel = pet.scaleLevel[stat] cost = config.scaleCost[stat][curLevel+1] return Q {isSuccess: no, code: 206, message: "You don't have a pet."} if not pet return Q {isSuccess: no, code: 209, message: "That stat is invalid."} if not config.scale[stat] return Q {isSuccess: no, code: 210, message: "That stat is already at max level."} if config.scale[stat].length <= curLevel+1 or not cost return Q {isSuccess: no, code: 211, message: "You don't have enough gold to upgrade your pet. You need #{cost-@gold.getValue()} more gold."} if @gold.getValue() < cost @gold.sub cost pet.increaseStat stat @emit "player.shop.petupgrade" Q {isSuccess: yes, code: 212, message: "Successfully upgraded your pets (#{pet.name}) #{stat} to level #{curLevel+2}!", pet: pet.buildSaveObject()} changePetClass: (newClass) -> myClasses = _.keys @statistics['calculated class changes'] pet = @getPet() return Q {isSuccess: no, code: 206, message: "You don't have a pet."} if not pet return Q {isSuccess: no, code: 207, message: "You haven't been that class yet, so you can't teach your pet how to do it!"} if (myClasses.indexOf newClass) is -1 and newClass isnt "Monster" pet.setClassTo newClass Q {isSuccess: yes, code: 208, message: "Successfully changed your pets (#{pet.name}) class to #{newClass}!", pet: pet.buildSaveObject()} takePetGold: -> pet = @getPet() return Q {isSuccess: no, code: 206, message: "You don't have a pet."} if not pet return Q {isSuccess: no, code: 233, message: "Your pet has no gold."} if pet.gold.atMin() gold = pet.gold.getValue() @gold.add gold pet.gold.toMinimum() Q {isSuccess: yes, code: 232, message: "You took #{gold} gold from your pet.", pet: pet.buildSaveObject()} feedPet: -> pet = @getPet() return Q {isSuccess: no, code: 206, message: "You don't have a pet."} if not pet return Q {isSuccess: no, code: 213, message: "Your pet is already at max level."} if pet.level.atMax() gold = pet.goldToNextLevel() return Q {isSuccess: no, code: 214, message: "You don't have enough gold for that! You need #{gold-@gold.getValue()} more gold."} if @gold.lessThan gold @gold.sub gold pet.feed() Q {isSuccess: yes, code: 215, message: "Your pet (#{pet.name}) was fed #{gold} gold and gained a level (#{pet.level.getValue()}).", pet: pet.buildSaveObject()} getPetGold: -> pet = @getPet() return Q {isSuccess: no, code: 206, message: "You don't have a pet."} if not pet petMoney = pet.gold.getValue() return Q {isSuccess: no, code: 216, message: "Your pet is penniless."} if not petMoney @gold.add petMoney pet.gold.toMinimum() Q {isSuccess: yes, code: 217, message: "You retrieved #{petMoney} gold from your pet (#{pet.name})!", pet: pet.buildSaveObject()} sellPetItem: (itemSlot) -> pet = @getPet() return Q {isSuccess: no, code: 206, message: "You don't have a pet."} if not pet item = pet.inventory[itemSlot] return Q {isSuccess: no, code: 218, message: "Your pet does not have an item in that slot!"} if not item pet.inventory = _.without pet.inventory, item value = pet.sellItem item, no Q {isSuccess: yes, code: 219, message: "Your pet (#{pet.name}) sold #{item.name} for #{value} gold!", pet: pet.buildSaveObject()} givePetItem: (itemSlot) -> pet = @getPet() return Q {isSuccess: no, code: 206, message: "You don't have a pet."} if not pet return Q {isSuccess: no, code: 220, message: "Your pet's inventory is full!"} if not pet.hasInventorySpace() curItem = @overflow[itemSlot] return Q {isSuccess: no, code: 43, message: "You don't have anything in that inventory slot."} if not curItem pet.addToInventory curItem @overflow = _.without @overflow, curItem Q {isSuccess: yes, code: 221, message: "Successfully gave #{curItem.name} to your pet (#{pet.name}).", pet: pet.buildSaveObject()} takePetItem: (itemSlot) -> pet = @getPet() return Q {isSuccess: no, code: 206, message: "You don't have a pet."} if not pet return Q {isSuccess: no, code: 41, message: "Your inventory is currently full!"} if @overflow.length is Constants.defaults.player.maxOverflow curItem = pet.inventory[itemSlot] return Q {isSuccess: no, code: 218, message: "Your pet doesn't have anything in that inventory slot."} if not curItem @overflow.push curItem pet.removeFromInventory curItem Q {isSuccess: yes, code: 221, message: "Successfully took #{curItem.name} from your pet (#{pet.name}).", pet: pet.buildSaveObject()} setPetOption: (option, value) -> pet = @getPet() return Q {isSuccess: no, code: 206, message: "You don't have a pet."} if not pet return Q {isSuccess: no, code: 222, message: "That option is invalid."} if not (option in ["smartSell", "smartEquip", "smartSelf"]) pet[option] = value Q {isSuccess: yes, code: 223, message: "Successfully set #{option} to #{value} for #{pet.name}.", pet: pet.buildSaveObject()} equipPetItem: (itemSlot) -> pet = @getPet() return Q {isSuccess: no, code: 206, message: "You don't have a pet."} if not pet item = pet.inventory[itemSlot] return Q {isSuccess: no, code: 218, message: "Your pet does not have an item in that slot!"} if not item return Q {isSuccess: no, code: 224, message: "Your pet is not so talented as to have that item slot!"} if not pet.hasEquipmentSlot item.type return Q {isSuccess: no, code: 224, message: "Your pet cannot equip that item! Either it is too strong, or your pets equipment slots are full."} if not pet.canEquip item pet.equip item Q {isSuccess: yes, code: 225, message: "Successfully equipped your pet (#{pet.name}) with #{item.name}.", pet: newPet.buildSaveObject()} unequipPetItem: (uid) -> pet = @getPet() return Q {isSuccess: no, code: 206, message: "You don't have a pet."} if not pet item = pet.findEquipped uid return Q {isSuccess: no, code: 226, message: "Your pet does not have that item equipped!"} if not item return Q {isSuccess: no, code: 231, message: "You can't unequip your pets soul, you jerk!"} if item.type is "pet soul" return Q {isSuccess: no, code: 220, message: "Your pet's inventory is full!"} if not pet.hasInventorySpace() pet.unequip item Q {isSuccess: yes, code: 227, message: "Successfully unequipped #{item.name} from your pet (#{pet.name}).", pet: pet.buildSaveObject()} swapToPet: (petId) -> pet = @getPet() return Q {isSuccess: no, code: 206, message: "You don't have a pet."} if not pet newPet = _.findWhere pet.petManager.pets, (pet) => pet.createdAt is petId and pet.owner.name is @name return Q {isSuccess: no, code: 228, message: "That pet does not exist!"} if not newPet return Q {isSuccess: no, code: 229, message: "That pet is already active!"} if newPet is pet pet.petManager.changePetForPlayer @, newPet Q {isSuccess: yes, code: 230, message: "Successfully made #{newPet.name}, the #{newPet.type} your active pet!", pet: newPet.buildSaveObject(), pets: pet.petManager.getPetsForPlayer @identifier} save: -> return if not @playerManager @playerManager.savePlayer @ getPet: -> @playerManager.game.petManager.getActivePetFor @ gainGold: (gold) -> if _.isNaN gold @playerManager.game.errorHandler.captureException new Error "BAD GOLD VALUE GOTTEN SOMEHOW" gold = 1 if gold > 0 @emit "player.gold.gain", @, gold else @emit "player.gold.lose", @, gold @gold.add gold gainXp: (xp) -> if xp > 0 @emit "player.xp.gain", @, xp else @emit "player.xp.lose", @, xp @xp.set 0 if _.isNaN @xp.__current @xp.add xp @levelUp() if @xp.atMax() buildRESTObject: -> @playerManager.buildPlayerSaveObject @ levelUp: (suppress = no) -> return if not @playerManager or @level.getValue() is @level.maximum @level.add 1 message = "<player.name>#{@name}</player.name> has attained level <player.level>#{@level.getValue()}</player.level>!" @resetMaxXp() @xp.toMinimum() @recalculateStats() @playerManager.game.eventHandler.broadcastEvent {message: message, player: @, type: 'levelup'} if not suppress @recalcGuildLevel() @emit "player.level.up", @ @playerManager.addForAnalytics @ recalcGuildLevel: -> return if not @guild @playerManager.game.guildManager.guildHash[@guild].avgLevel() setString: (type, val = '') -> @messages = {} if not @messages @messages[type] = val.substring 0, 99 if not @messages[type] delete @messages[type] return Q {isSuccess: yes, code: 95, message: "Successfully updated your string settings. Removed string type \"#{type}.\""} Q {isSuccess: yes, code: 95, message: "Successfully updated your string settings. String \"#{type}\" is now: #{if val then val else 'empty!'}"} checkAchievements: (silent = no) -> @_oldAchievements = _.compact _.clone @achievements @achievements = [] achieved = @playerManager.game.achievementManager.getAllAchievedFor @ stringCurrent = _.map @_oldAchievements, (achievement) -> achievement.name stringAll = _.map achieved, (achievement) -> achievement.name newAchievements = _.difference stringAll, stringCurrent _.each newAchievements, (achievementName) => achievement = _.findWhere achieved, name: achievementName @achievements.push achievement if not silent message = "<player.name>#{@name}</player.name> has achieved <event.achievement>#{achievementName}</event.achievement> (#{achievement.desc} | #{achievement.reward})" @playerManager.game.eventHandler.broadcastEvent {message: message, player: @, type: 'achievement'} if not silent @achievements = achieved itemPriority: (item) -> if not @priorityPoints @priorityPoints = {dex: 1, str: 1, agi: 1, wis: 1, con: 1, int: 1} ret = 0 ret += item[stat]*@priorityPoints[stat]*Constants.defaults.player.priorityScale for stat in ["dex", "str", "agi", "wis", "con", "int"] ret priorityTotal: -> _.reduce @priorityPoints, ((total, stat) -> total + stat), 0 setPriorities: (stats) -> if not @priorityPoints @priorityPoints = {dex: 1, str: 1, agi: 1, wis: 1, con: 1, int: 1} if _.size stats != 6 return Q {isSuccess: no, code: 111, message: "Priority list is invalid. Expected 6 items"} total = 0 sanitizedStats = {} for key, stat of stats if !_.isNumber stat return Q {isSuccess: no, code: 112, message: "Priority \"" + key + "\" is not a number."} if not (key in ["PI:KEY:<KEY>END_PI", "PI:KEY:<KEY>END_PI", "PI:KEY:<KEY>END_PI", "PI:KEY:<KEY>END_PI", "PI:KEY:<KEY>END_PI", "int"]) return Q {isSuccess: no, code: 111, message: "Key \"" + key + "\" is invalid."} sanitizedStats[key] = Math.round stat total += Math.round stat if total != Constants.defaults.player.priorityTotal return Q {isSuccess: no, code: 112, message: "Number of priority points are not equal to " + Constants.defaults.player.priorityTotal + "."} @priorityPoints = sanitizedStats return Q {isSuccess: yes, code: 113, message: "Successfully set priorities.", player: @buildRESTObject()} addPriority: (stat, points) -> if not @priorityPoints @priorityPoints = {dex: 1, str: 1, agi: 1, wis: 1, con: 1, int: 1} points = if _.isNumber points then points else parseInt points points = Math.round points if points is 0 return Q {isSuccess: no, code: 110, message: "You didn't specify a valid priority point amount."} if not (stat in ["dex", "str", "agi", "wis", "con", "int"]) return Q {isSuccess: no, code: 111, message: "That stat is invalid."} if points > 0 and @priorityTotal() + points > Constants.defaults.player.priorityTotal return Q {isSuccess: no, code: 112, message: "Not enough priority points remaining."} if points < 0 and @priorityPoints[stat] + points < 0 return Q {isSuccess: no, code: 112, message: "Not enough priority points to remove."} @priorityPoints[stat] += points if points > 0 return Q {isSuccess: yes, code: 113, message: "Successfully added #{points} to your #{stat} priority.", player: @buildRESTObject()} else return Q {isSuccess: yes, code: 113, message: "Successfully removed #{-points} from your #{stat} priority.", player: @buildRESTObject()} module.exports = exports = Player
[ { "context": "##\n# MIT License\n#\n# Copyright (c) 2016 Jérôme Quéré <contact@jeromequere.com>\n#\n# Permission is hereb", "end": 52, "score": 0.9998026490211487, "start": 40, "tag": "NAME", "value": "Jérôme Quéré" }, { "context": " MIT License\n#\n# Copyright (c) 2016 Jérôme Quéré ...
src/controllers/MainController.coffee
jerome-quere/la-metric-gitlab
1
## # MIT License # # Copyright (c) 2016 Jérôme Quéré <contact@jeromequere.com> # # 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. ## class MainController lametricTriggerAction: (res, lametric) -> lametric.sendIndicator() res.status(200).end() projectHookAction: (req, res, lametric) -> project = req.body.project; attrs = req.body.object_attributes; user = req.body.user; kind = req.body.object_kind; notification = null if kind == 'issue' and attrs.action == 'open' notification = icon: lametric.getIconCode 'openIssue' text: "#{user.name} opened an issue on #{project.name}" if kind == 'issue' and attrs.action == 'close' notification = icon: lametric.getIconCode 'closeIssue' text: "#{user.name} closed an issue on #{project.name}" if kind == 'pipeline' and attrs.status == 'success' notification = icon: lametric.getIconCode 'check' text: "Build on #{project.name} for #{attrs.ref} succeed in #{attrs.duration}" if notification then lametric.addNotification(notification) res.status(200).end() module.exports = MainController
74449
## # MIT License # # Copyright (c) 2016 <NAME> <<EMAIL>> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. ## class MainController lametricTriggerAction: (res, lametric) -> lametric.sendIndicator() res.status(200).end() projectHookAction: (req, res, lametric) -> project = req.body.project; attrs = req.body.object_attributes; user = req.body.user; kind = req.body.object_kind; notification = null if kind == 'issue' and attrs.action == 'open' notification = icon: lametric.getIconCode 'openIssue' text: "#{user.name} opened an issue on #{project.name}" if kind == 'issue' and attrs.action == 'close' notification = icon: lametric.getIconCode 'closeIssue' text: "#{user.name} closed an issue on #{project.name}" if kind == 'pipeline' and attrs.status == 'success' notification = icon: lametric.getIconCode 'check' text: "Build on #{project.name} for #{attrs.ref} succeed in #{attrs.duration}" if notification then lametric.addNotification(notification) res.status(200).end() module.exports = MainController
true
## # MIT License # # Copyright (c) 2016 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. ## class MainController lametricTriggerAction: (res, lametric) -> lametric.sendIndicator() res.status(200).end() projectHookAction: (req, res, lametric) -> project = req.body.project; attrs = req.body.object_attributes; user = req.body.user; kind = req.body.object_kind; notification = null if kind == 'issue' and attrs.action == 'open' notification = icon: lametric.getIconCode 'openIssue' text: "#{user.name} opened an issue on #{project.name}" if kind == 'issue' and attrs.action == 'close' notification = icon: lametric.getIconCode 'closeIssue' text: "#{user.name} closed an issue on #{project.name}" if kind == 'pipeline' and attrs.status == 'success' notification = icon: lametric.getIconCode 'check' text: "Build on #{project.name} for #{attrs.ref} succeed in #{attrs.duration}" if notification then lametric.addNotification(notification) res.status(200).end() module.exports = MainController
[ { "context": " filePath: mp3\n host: \"127.0.0.1\"\n port: master_info.source_p", "end": 1095, "score": 0.9997055530548096, "start": 1086, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "aster_info.source_port\n ...
test/slave/early_listeners.coffee
firebrandv2/FirebrandNetwork.ga
342
# When a slave starts up, it will accept incoming connections right away, # even though it won't have any workers ready to go. We need to make sure that # those early listeners end up making it through to the worker and that their # requests succeed. debug = require("debug")("sm:tests:slave_early_listeners") MasterHelper = require "../helpers/master" SlaveHelper = require "../helpers/slave" StreamListener = $src "util/stream_listener" IcecastSource = $src "util/icecast_source" _ = require "underscore" mp3 = $file "mp3/mp3-44100-128-s.mp3" describe "Slave Early Listeners", -> master_info = null slave_info = null slave = null before (done) -> MasterHelper.startMaster "mp3", (err,info) -> throw err if err master_info = info debug "Master URI is #{ master_info.slave_uri }" debug "Stream key is #{ master_info.stream_key }" # connect a source source = new IcecastSource format: "mp3" filePath: mp3 host: "127.0.0.1" port: master_info.source_port password: master_info.source_password stream: master_info.stream_key source.start (err) -> throw err if err debug "Stream source is connected." done() before (done) -> SlaveHelper.startSlave master_info.slave_uri, 0, (err,info) -> throw err if err slave_info = info slave = slave_info.slave done() listener = null it "should immediately accept a listener connection", (done) -> listener = new StreamListener "127.0.0.1", slave_info.port, master_info.stream_key # swallow anything that fires after our first response done = _.once done listener.connect (err) -> # we shouldn't get a response yet, so anything here is an error done err||new Error("Unexpected listener response") listener.once "socket", (sock) -> # give a tiny amount of time to make sure we don't get a response sock.once "connect", -> setTimeout -> expect(slave.pool.loaded_count()).to.eql 0 done() , 100 it "should get a response once a worker is ready", (done) -> this.timeout 4000 listener.once "connected", (err) -> throw err if err done() # now resize the slave to get a worker slave.pool.size = 1 slave.pool._spawn() it "should start feeding data to the listener", (done) -> this.timeout 4000 listener.once "bytes", -> done()
3002
# When a slave starts up, it will accept incoming connections right away, # even though it won't have any workers ready to go. We need to make sure that # those early listeners end up making it through to the worker and that their # requests succeed. debug = require("debug")("sm:tests:slave_early_listeners") MasterHelper = require "../helpers/master" SlaveHelper = require "../helpers/slave" StreamListener = $src "util/stream_listener" IcecastSource = $src "util/icecast_source" _ = require "underscore" mp3 = $file "mp3/mp3-44100-128-s.mp3" describe "Slave Early Listeners", -> master_info = null slave_info = null slave = null before (done) -> MasterHelper.startMaster "mp3", (err,info) -> throw err if err master_info = info debug "Master URI is #{ master_info.slave_uri }" debug "Stream key is #{ master_info.stream_key }" # connect a source source = new IcecastSource format: "mp3" filePath: mp3 host: "127.0.0.1" port: master_info.source_port password: <PASSWORD> stream: master_info.stream_key source.start (err) -> throw err if err debug "Stream source is connected." done() before (done) -> SlaveHelper.startSlave master_info.slave_uri, 0, (err,info) -> throw err if err slave_info = info slave = slave_info.slave done() listener = null it "should immediately accept a listener connection", (done) -> listener = new StreamListener "127.0.0.1", slave_info.port, master_info.stream_key # swallow anything that fires after our first response done = _.once done listener.connect (err) -> # we shouldn't get a response yet, so anything here is an error done err||new Error("Unexpected listener response") listener.once "socket", (sock) -> # give a tiny amount of time to make sure we don't get a response sock.once "connect", -> setTimeout -> expect(slave.pool.loaded_count()).to.eql 0 done() , 100 it "should get a response once a worker is ready", (done) -> this.timeout 4000 listener.once "connected", (err) -> throw err if err done() # now resize the slave to get a worker slave.pool.size = 1 slave.pool._spawn() it "should start feeding data to the listener", (done) -> this.timeout 4000 listener.once "bytes", -> done()
true
# When a slave starts up, it will accept incoming connections right away, # even though it won't have any workers ready to go. We need to make sure that # those early listeners end up making it through to the worker and that their # requests succeed. debug = require("debug")("sm:tests:slave_early_listeners") MasterHelper = require "../helpers/master" SlaveHelper = require "../helpers/slave" StreamListener = $src "util/stream_listener" IcecastSource = $src "util/icecast_source" _ = require "underscore" mp3 = $file "mp3/mp3-44100-128-s.mp3" describe "Slave Early Listeners", -> master_info = null slave_info = null slave = null before (done) -> MasterHelper.startMaster "mp3", (err,info) -> throw err if err master_info = info debug "Master URI is #{ master_info.slave_uri }" debug "Stream key is #{ master_info.stream_key }" # connect a source source = new IcecastSource format: "mp3" filePath: mp3 host: "127.0.0.1" port: master_info.source_port password: PI:PASSWORD:<PASSWORD>END_PI stream: master_info.stream_key source.start (err) -> throw err if err debug "Stream source is connected." done() before (done) -> SlaveHelper.startSlave master_info.slave_uri, 0, (err,info) -> throw err if err slave_info = info slave = slave_info.slave done() listener = null it "should immediately accept a listener connection", (done) -> listener = new StreamListener "127.0.0.1", slave_info.port, master_info.stream_key # swallow anything that fires after our first response done = _.once done listener.connect (err) -> # we shouldn't get a response yet, so anything here is an error done err||new Error("Unexpected listener response") listener.once "socket", (sock) -> # give a tiny amount of time to make sure we don't get a response sock.once "connect", -> setTimeout -> expect(slave.pool.loaded_count()).to.eql 0 done() , 100 it "should get a response once a worker is ready", (done) -> this.timeout 4000 listener.once "connected", (err) -> throw err if err done() # now resize the slave to get a worker slave.pool.size = 1 slave.pool._spawn() it "should start feeding data to the listener", (done) -> this.timeout 4000 listener.once "bytes", -> done()
[ { "context": "rom a given key\", (done) ->\n Spreadsheet.load(\"0ArtCBkZR37MmdFJqbjloVEp1OFZLWDJ6M29OcXQ1WkE\").then (data) ->\n console.log data\n ass", "end": 221, "score": 0.9489862322807312, "start": 177, "tag": "KEY", "value": "0ArtCBkZR37MmdFJqbjloVEp1OFZLWDJ6M29OcXQ1WkE" ...
test/test.coffee
distri/gdocs-spreadsheet
0
mocha.globals ['jQuery*'] Spreadsheet = require "../main" describe "Google Spreadsheet wrapper", -> it "loads spreadsheet from a given key", (done) -> Spreadsheet.load("0ArtCBkZR37MmdFJqbjloVEp1OFZLWDJ6M29OcXQ1WkE").then (data) -> console.log data assert data.Abilities assert data.Characters assert data.Passives assert data.Progressions assert data.TerrainFeatures assert(data.Abilities.length > 0) done()
145810
mocha.globals ['jQuery*'] Spreadsheet = require "../main" describe "Google Spreadsheet wrapper", -> it "loads spreadsheet from a given key", (done) -> Spreadsheet.load("<KEY>").then (data) -> console.log data assert data.Abilities assert data.Characters assert data.Passives assert data.Progressions assert data.TerrainFeatures assert(data.Abilities.length > 0) done()
true
mocha.globals ['jQuery*'] Spreadsheet = require "../main" describe "Google Spreadsheet wrapper", -> it "loads spreadsheet from a given key", (done) -> Spreadsheet.load("PI:KEY:<KEY>END_PI").then (data) -> console.log data assert data.Abilities assert data.Characters assert data.Passives assert data.Progressions assert data.TerrainFeatures assert(data.Abilities.length > 0) done()
[ { "context": "logic borrowed from node-lame: https://github.com/TooTallNate/node-lame\n\n MPEG_HEADER = new strt", "end": 320, "score": 0.9992610812187195, "start": 309, "tag": "USERNAME", "value": "TooTallNate" }, { "context": "singId3v2\n # we'll alrea...
src/streammachine/parsers/mp3.coffee
firebrandv2/FirebrandNetwork.ga
342
strtok = require('strtok2') assert = require("assert") module.exports = class MP3 extends require("stream").Writable ID3V1_LENGTH = 128 ID3V2_HEADER_LENGTH = 10 MPEG_HEADER_LENGTH = 4 FIRST_BYTE = new strtok.BufferType(1) # Mp3 parsing logic borrowed from node-lame: https://github.com/TooTallNate/node-lame MPEG_HEADER = new strtok.BufferType(MPEG_HEADER_LENGTH) REST_OF_ID3V2_HEADER = new strtok.BufferType(ID3V2_HEADER_LENGTH - MPEG_HEADER_LENGTH) REST_OF_ID3V1 = new strtok.BufferType(ID3V1_LENGTH - MPEG_HEADER_LENGTH) LAYER1_ID = 3 LAYER2_ID = 2 LAYER3_ID = 1 MPEG1_ID = 3 MPEG2_ID = 2 MPEG25_ID = 0 MODE_MONO = 3 MODE_DUAL = 2 MODE_JOINT = 1 MODE_STEREO = 0 MPEG_NAME = [ "MPEG2.5", null, "MPEG2", "MPEG1" ] LAYER_NAME = [ null, "Layer3", "Layer2", "Layer1" ] MODE_NAME = [ "Stereo", "J-Stereo", "Dual", "Mono" ] SAMPLING_RATES = [ 44100, 48000, 32000, 0 ] BITRATE_MPEG1_LAYER1 = [ 0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448 ] BITRATE_MPEG1_LAYER2 = [ 0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384 ] BITRATE_MPEG1_LAYER3 = [ 0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320 ] BITRATE_MPEG2_LAYER1 = [ 0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256 ] BITRATE_MPEG2_LAYER2A3 = [ 0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160 ] BITRATE_MAP = [ [ null, BITRATE_MPEG2_LAYER2A3, BITRATE_MPEG2_LAYER2A3, BITRATE_MPEG2_LAYER1 ], # MPEG2.5 null, [ null, BITRATE_MPEG2_LAYER2A3, BITRATE_MPEG2_LAYER2A3, BITRATE_MPEG2_LAYER1 ], # MPEG2 [ null, BITRATE_MPEG1_LAYER3, BITRATE_MPEG1_LAYER2, BITRATE_MPEG1_LAYER1 ] ] constructor: -> super # create an internal stream to pass to strtok @istream = new (require("events").EventEmitter) @outbuf = [] @_flushing = false # set up status @frameSize = -1 @beginning = true @gotFF = false @gotID3 = 0 @byteTwo = null @frameHeader = null @frameHeaderBuf = null @id3v2 = null @_parsingId3v1 = false @_parsingId3v2 = false @_finishingId3v2 = false @_id3v2_1 = null @_id3v2_2 = null @_id3v1_1 = null @once "finish", => @_flushing = setTimeout => @emit "end" , 500 _emitAndMaybeEnd = (args...) => @emit args... if @_flushing clearTimeout @_flushing @_flushing = setTimeout => @emit "end" , 500 strtok.parse @istream, (v,cb) => # -- initial request -- # if v == undefined # we need to examine each byte until we get a FF or ID3 return FIRST_BYTE # -- ID3v1 tag -- # if @_parsingId3v1 # our first byte is in @_id3v1_1 id3 = @parseId3V1(Buffer.concat([@_id3v1_1,v])) _emitAndMaybeEnd "id3v1", id3 @_id3v1_1 = null @_parsingId3v1 = false return MPEG_HEADER # -- ID3v2 tag -- # if @_parsingId3v2 # we'll already have @id3v2 started with versionMajor and # our first byte in @_id3v2_1 @id3v2.versionMinor = v[0] @id3v2.flags = v[1] # calculate the length @id3v2.length = (v[5] & 0x7f) | (( v[4] & 0x7f ) << 7) | (( v[3] & 0x7f ) << 14) | (( v[2] & 0x7f ) << 21) @_parsingId3v2 = false; @_finishingId3v2 = true; @_id3v2_2 = v; return new strtok.BufferType @id3v2.length if @_finishingId3v2 # step 3 in the ID3v2 parse... b = Buffer.concat([@_id3v2_1, @_id3v2_2, v]) _emitAndMaybeEnd 'id3v2', b @_finishingId3v2 = false return FIRST_BYTE; # -- frame header -- # if @frameSize == -1 && @frameHeader # we're on-schedule now... we've had a valid frame. # buffer should be four bytes tag = v.toString 'ascii', 0, 3 if tag == 'ID3' # parse ID3v2 tag _emitAndMaybeEnd "debug", "got an ID3" @_parsingId3v2 = true @id3v2 = versionMajor:v[3] @_id3v2_1 = v return REST_OF_ID3V2_HEADER else if tag == 'TAG' # parse ID3v1 tag _emitAndMaybeEnd "debug", "got a TAG" @_id3v1_1 = v @_parsingId3v1 = true # grab 125 bytes return REST_OF_ID3V1 else try h = @parseFrame(v) catch e # uh oh... bad news _emitAndMaybeEnd "debug", "invalid header... ", v, tag, @frameHeader @frameHeader = null return FIRST_BYTE @frameHeader = h @frameHeaderBuf = v _emitAndMaybeEnd "header", v, h @frameSize = @frameHeader.frameSize if @frameSize == 1 # problem... just start over _emitAndMaybeEnd "debug", "Invalid frame header: ", h return FIRST_BYTE else return new strtok.BufferType(@frameSize - MPEG_HEADER_LENGTH); # -- first header -- # if @gotFF and @byteTwo buf = Buffer.alloc(4) buf[0] = 0xFF buf[1] = @byteTwo buf[2] = v[0] buf[3] = v[1] try h = @parseFrame(buf) catch e # invalid header... chuck everything and try again _emitAndMaybeEnd "debug", "chucking invalid try at header: ", buf @gotFF = false @byteTwo = null return FIRST_BYTE # valid header... we're on schedule now @gotFF = false @byteTwo = null @beginning = false @frameHeader = h @frameHeaderBuf = buf _emitAndMaybeEnd "header", h @frameSize = @frameHeader.frameSize if @frameSize == 1 # problem... just start over _emitAndMaybeEnd "debug", "Invalid frame header: ", h return FIRST_BYTE else _emitAndMaybeEnd "debug", "On-tracking with frame of: ", @frameSize - MPEG_HEADER_LENGTH return new strtok.BufferType(@frameSize - MPEG_HEADER_LENGTH); if @gotFF if v[0]>>4 >= 0xE @byteTwo = v[0] # need two more bytes return new strtok.BufferType(2) else @gotFF = false if @frameSize == -1 && !@gotFF if v[0] == 0xFF # possible start of frame header. need next byte to know more @gotFF = true return FIRST_BYTE else if v[0] == 0x49 # could be the I in ID3 @gotID3 = 1 return FIRST_BYTE else if @gotID3 == 1 && v[0] == 0x44 @gotID3 = 2 return FIRST_BYTE else if @gotID3 == 2 && v[0] == 0x33 @gotID3 = 3 return FIRST_BYTE else if @gotID3 == 3 @_id3v2_1 = Buffer.from([0x49,0x44,0x33,v[0]]) @id3v2 = versionMajor:v[0] @_parsingId3v2 = true @gotID3 = 0 return REST_OF_ID3V2_HEADER else # keep looking return FIRST_BYTE # -- data frame -- # if @frameHeaderBuf frame = Buffer.alloc( @frameHeaderBuf.length + v.length ) @frameHeaderBuf.copy(frame,0) v.copy(frame,@frameHeaderBuf.length) _emitAndMaybeEnd "frame", frame, @frameHeader @frameSize = -1 return MPEG_HEADER #---------- _write: (chunk,encoding,cb) -> if @_flushing throw new Error "MP3 write while flushing." @istream.emit "data", chunk cb?() #---------- parseId3V1: (id3v1) -> id3 = {} _stripNull = (buf) -> idx = buf.toJSON().indexOf(0) buf.toString "ascii", 0, if idx == -1 then buf.length else idx # TAG: 3 bytes # title: 30 bytes id3.title = _stripNull id3v1.slice(3,33) # artist: 30 bytes id3.artist = _stripNull id3v1.slice(33,63) # album: 30 bytes id3.album = _stripNull id3v1.slice(63,93) # year: 4 bytes id3.year = _stripNull id3v1.slice(93,97) # comment: 28 - 30 bytes if id3v1[125] == 0 id3.comment = _stripNull id3v1.slice(97,125) id3.track = id3v1.readUInt8(126) else id3.track = null id3.comment = _stripNull id3v1.slice(97,127) # genre: 1 byte id3.genre = id3v1.readUInt8(127) id3 #---------- parseFrame: (b) -> assert.ok Buffer.isBuffer(b) # -- first twelve bits must be FF[EF] -- # assert.ok ( b[0] == 0xFF && (b[1] >> 4) >= 0xE ), "Buffer does not start with FF[EF]" header32 = b.readUInt32BE(0) # -- mpeg id -- # r = mpegID: (header32 >> 19) & 3 layerID: (header32 >> 17) & 3 crc16used: (header32 & 0x00010000) == 0 bitrateIndex: (header32 >> 12) & 0xF samplingRateIndex: (header32 >> 10) & 3 padding: (header32 & 0x00000200) != 0 privateBitSet: (header32 & 0x00000100) != 0 mode: (header32 >> 6) & 3 modeExtension: (header32 >> 4) & 3 copyrighted: (header32 & 0x00000008) != 0 original: (header32 & 0x00000004) == 0 emphasis: header32 & 3 # placeholders for mem allocation channels: 0 bitrateKBPS: 0 mpegName: "" layerName: "" modeName: "" samplingRateHz: 0 samplesPerFrame: 0 bytesPerSlot: 0 frameSizeRaw: 0 frameSize: 0 frames_per_sec: 0 stream_key: "" # now fill in the derived values... r.channels = if r.mode == MODE_MONO then 1 else 2 r.bitrateKBPS = BITRATE_MAP[ r.mpegID ][ r.layerID ][ r.bitrateIndex ] r.mpegName = MPEG_NAME[ r.mpegID ] r.layerName = LAYER_NAME[ r.layerID ] r.modeName = MODE_NAME[ r.mode ] r.samplingRateHz = SAMPLING_RATES[r.samplingRateIndex] if r.mpegID == MPEG2_ID r.samplingRateHz >>= 1 # 16,22,48 kHz else if r.mpegID == MPEG25_ID r.samplingRateHz >>= 2 # 8,11,24 kHz if r.layerID == LAYER1_ID # layer 1: always 384 samples/frame and 4byte-slots r.samplesPerFrame = 384; r.bytesPerSlot = 4; r.frameSizeRaw = (12 * (r.bitrateKBPS*1000) / (r.samplingRateHz*10) + (r.padding ? 1 : 0)) * 4; else # layer 2: always 1152 samples/frame # layer 3: MPEG1: 1152 samples/frame, MPEG2/2.5: 576 samples/frame r.samplesPerFrame = if (r.mpegID == MPEG1_ID) || (r.layerID == LAYER2_ID) then 1152 else 576 r.bytesPerSlot = 1 r.frameSizeRaw = (r.samplesPerFrame / 8) * (r.bitrateKBPS*1000) / r.samplingRateHz + (if r.padding then 1 else 0) # Make the frameSize be the proper floor'd byte length r.frameSize = ~~r.frameSizeRaw if (!r.frameSize) throw new Error('bad size: ' + r.frameSize) # -- compute StreamMachine-specific header bits -- # r.frames_per_sec = r.samplingRateHz / r.samplesPerFrame r.duration = (1 / r.frames_per_sec) * 1000 r.stream_key = ['mp3',r.samplingRateHz,r.bitrateKBPS,(if r.modeName in ["Stereo","J-Stereo"] then "s" else "m")].join("-") r
181191
strtok = require('strtok2') assert = require("assert") module.exports = class MP3 extends require("stream").Writable ID3V1_LENGTH = 128 ID3V2_HEADER_LENGTH = 10 MPEG_HEADER_LENGTH = 4 FIRST_BYTE = new strtok.BufferType(1) # Mp3 parsing logic borrowed from node-lame: https://github.com/TooTallNate/node-lame MPEG_HEADER = new strtok.BufferType(MPEG_HEADER_LENGTH) REST_OF_ID3V2_HEADER = new strtok.BufferType(ID3V2_HEADER_LENGTH - MPEG_HEADER_LENGTH) REST_OF_ID3V1 = new strtok.BufferType(ID3V1_LENGTH - MPEG_HEADER_LENGTH) LAYER1_ID = 3 LAYER2_ID = 2 LAYER3_ID = 1 MPEG1_ID = 3 MPEG2_ID = 2 MPEG25_ID = 0 MODE_MONO = 3 MODE_DUAL = 2 MODE_JOINT = 1 MODE_STEREO = 0 MPEG_NAME = [ "MPEG2.5", null, "MPEG2", "MPEG1" ] LAYER_NAME = [ null, "Layer3", "Layer2", "Layer1" ] MODE_NAME = [ "Stereo", "J-Stereo", "Dual", "Mono" ] SAMPLING_RATES = [ 44100, 48000, 32000, 0 ] BITRATE_MPEG1_LAYER1 = [ 0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448 ] BITRATE_MPEG1_LAYER2 = [ 0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384 ] BITRATE_MPEG1_LAYER3 = [ 0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320 ] BITRATE_MPEG2_LAYER1 = [ 0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256 ] BITRATE_MPEG2_LAYER2A3 = [ 0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160 ] BITRATE_MAP = [ [ null, BITRATE_MPEG2_LAYER2A3, BITRATE_MPEG2_LAYER2A3, BITRATE_MPEG2_LAYER1 ], # MPEG2.5 null, [ null, BITRATE_MPEG2_LAYER2A3, BITRATE_MPEG2_LAYER2A3, BITRATE_MPEG2_LAYER1 ], # MPEG2 [ null, BITRATE_MPEG1_LAYER3, BITRATE_MPEG1_LAYER2, BITRATE_MPEG1_LAYER1 ] ] constructor: -> super # create an internal stream to pass to strtok @istream = new (require("events").EventEmitter) @outbuf = [] @_flushing = false # set up status @frameSize = -1 @beginning = true @gotFF = false @gotID3 = 0 @byteTwo = null @frameHeader = null @frameHeaderBuf = null @id3v2 = null @_parsingId3v1 = false @_parsingId3v2 = false @_finishingId3v2 = false @_id3v2_1 = null @_id3v2_2 = null @_id3v1_1 = null @once "finish", => @_flushing = setTimeout => @emit "end" , 500 _emitAndMaybeEnd = (args...) => @emit args... if @_flushing clearTimeout @_flushing @_flushing = setTimeout => @emit "end" , 500 strtok.parse @istream, (v,cb) => # -- initial request -- # if v == undefined # we need to examine each byte until we get a FF or ID3 return FIRST_BYTE # -- ID3v1 tag -- # if @_parsingId3v1 # our first byte is in @_id3v1_1 id3 = @parseId3V1(Buffer.concat([@_id3v1_1,v])) _emitAndMaybeEnd "id3v1", id3 @_id3v1_1 = null @_parsingId3v1 = false return MPEG_HEADER # -- ID3v2 tag -- # if @_parsingId3v2 # we'll already have @id3v2 started with versionMajor and # our first byte in @_id3v2_1 @id3v2.versionMinor = v[0] @id3v2.flags = v[1] # calculate the length @id3v2.length = (v[5] & 0x7f) | (( v[4] & 0x7f ) << 7) | (( v[3] & 0x7f ) << 14) | (( v[2] & 0x7f ) << 21) @_parsingId3v2 = false; @_finishingId3v2 = true; @_id3v2_2 = v; return new strtok.BufferType @id3v2.length if @_finishingId3v2 # step 3 in the ID3v2 parse... b = Buffer.concat([@_id3v2_1, @_id3v2_2, v]) _emitAndMaybeEnd 'id3v2', b @_finishingId3v2 = false return FIRST_BYTE; # -- frame header -- # if @frameSize == -1 && @frameHeader # we're on-schedule now... we've had a valid frame. # buffer should be four bytes tag = v.toString 'ascii', 0, 3 if tag == 'ID3' # parse ID3v2 tag _emitAndMaybeEnd "debug", "got an ID3" @_parsingId3v2 = true @id3v2 = versionMajor:v[3] @_id3v2_1 = v return REST_OF_ID3V2_HEADER else if tag == 'TAG' # parse ID3v1 tag _emitAndMaybeEnd "debug", "got a TAG" @_id3v1_1 = v @_parsingId3v1 = true # grab 125 bytes return REST_OF_ID3V1 else try h = @parseFrame(v) catch e # uh oh... bad news _emitAndMaybeEnd "debug", "invalid header... ", v, tag, @frameHeader @frameHeader = null return FIRST_BYTE @frameHeader = h @frameHeaderBuf = v _emitAndMaybeEnd "header", v, h @frameSize = @frameHeader.frameSize if @frameSize == 1 # problem... just start over _emitAndMaybeEnd "debug", "Invalid frame header: ", h return FIRST_BYTE else return new strtok.BufferType(@frameSize - MPEG_HEADER_LENGTH); # -- first header -- # if @gotFF and @byteTwo buf = Buffer.alloc(4) buf[0] = 0xFF buf[1] = @byteTwo buf[2] = v[0] buf[3] = v[1] try h = @parseFrame(buf) catch e # invalid header... chuck everything and try again _emitAndMaybeEnd "debug", "chucking invalid try at header: ", buf @gotFF = false @byteTwo = null return FIRST_BYTE # valid header... we're on schedule now @gotFF = false @byteTwo = null @beginning = false @frameHeader = h @frameHeaderBuf = buf _emitAndMaybeEnd "header", h @frameSize = @frameHeader.frameSize if @frameSize == 1 # problem... just start over _emitAndMaybeEnd "debug", "Invalid frame header: ", h return FIRST_BYTE else _emitAndMaybeEnd "debug", "On-tracking with frame of: ", @frameSize - MPEG_HEADER_LENGTH return new strtok.BufferType(@frameSize - MPEG_HEADER_LENGTH); if @gotFF if v[0]>>4 >= 0xE @byteTwo = v[0] # need two more bytes return new strtok.BufferType(2) else @gotFF = false if @frameSize == -1 && !@gotFF if v[0] == 0xFF # possible start of frame header. need next byte to know more @gotFF = true return FIRST_BYTE else if v[0] == 0x49 # could be the I in ID3 @gotID3 = 1 return FIRST_BYTE else if @gotID3 == 1 && v[0] == 0x44 @gotID3 = 2 return FIRST_BYTE else if @gotID3 == 2 && v[0] == 0x33 @gotID3 = 3 return FIRST_BYTE else if @gotID3 == 3 @_id3v2_1 = Buffer.from([0x49,0x44,0x33,v[0]]) @id3v2 = versionMajor:v[0] @_parsingId3v2 = true @gotID3 = 0 return REST_OF_ID3V2_HEADER else # keep looking return FIRST_BYTE # -- data frame -- # if @frameHeaderBuf frame = Buffer.alloc( @frameHeaderBuf.length + v.length ) @frameHeaderBuf.copy(frame,0) v.copy(frame,@frameHeaderBuf.length) _emitAndMaybeEnd "frame", frame, @frameHeader @frameSize = -1 return MPEG_HEADER #---------- _write: (chunk,encoding,cb) -> if @_flushing throw new Error "MP3 write while flushing." @istream.emit "data", chunk cb?() #---------- parseId3V1: (id3v1) -> id3 = {} _stripNull = (buf) -> idx = buf.toJSON().indexOf(0) buf.toString "ascii", 0, if idx == -1 then buf.length else idx # TAG: 3 bytes # title: 30 bytes id3.title = _stripNull id3v1.slice(3,33) # artist: 30 bytes id3.artist = _stripNull id3v1.slice(33,63) # album: 30 bytes id3.album = _stripNull id3v1.slice(63,93) # year: 4 bytes id3.year = _stripNull id3v1.slice(93,97) # comment: 28 - 30 bytes if id3v1[125] == 0 id3.comment = _stripNull id3v1.slice(97,125) id3.track = id3v1.readUInt8(126) else id3.track = null id3.comment = _stripNull id3v1.slice(97,127) # genre: 1 byte id3.genre = id3v1.readUInt8(127) id3 #---------- parseFrame: (b) -> assert.ok Buffer.isBuffer(b) # -- first twelve bits must be FF[EF] -- # assert.ok ( b[0] == 0xFF && (b[1] >> 4) >= 0xE ), "Buffer does not start with FF[EF]" header32 = b.readUInt32BE(0) # -- mpeg id -- # r = mpegID: (header32 >> 19) & 3 layerID: (header32 >> 17) & 3 crc16used: (header32 & 0x00010000) == 0 bitrateIndex: (header32 >> 12) & 0xF samplingRateIndex: (header32 >> 10) & 3 padding: (header32 & 0x00000200) != 0 privateBitSet: (header32 & 0x00000100) != 0 mode: (header32 >> 6) & 3 modeExtension: (header32 >> 4) & 3 copyrighted: (header32 & 0x00000008) != 0 original: (header32 & 0x00000004) == 0 emphasis: header32 & 3 # placeholders for mem allocation channels: 0 bitrateKBPS: 0 mpegName: "" layerName: "" modeName: "" samplingRateHz: 0 samplesPerFrame: 0 bytesPerSlot: 0 frameSizeRaw: 0 frameSize: 0 frames_per_sec: 0 stream_key: "" # now fill in the derived values... r.channels = if r.mode == MODE_MONO then 1 else 2 r.bitrateKBPS = BITRATE_MAP[ r.mpegID ][ r.layerID ][ r.bitrateIndex ] r.mpegName = MPEG_NAME[ r.mpegID ] r.layerName = LAYER_NAME[ r.layerID ] r.modeName = MODE_NAME[ r.mode ] r.samplingRateHz = SAMPLING_RATES[r.samplingRateIndex] if r.mpegID == MPEG2_ID r.samplingRateHz >>= 1 # 16,22,48 kHz else if r.mpegID == MPEG25_ID r.samplingRateHz >>= 2 # 8,11,24 kHz if r.layerID == LAYER1_ID # layer 1: always 384 samples/frame and 4byte-slots r.samplesPerFrame = 384; r.bytesPerSlot = 4; r.frameSizeRaw = (12 * (r.bitrateKBPS*1000) / (r.samplingRateHz*10) + (r.padding ? 1 : 0)) * 4; else # layer 2: always 1152 samples/frame # layer 3: MPEG1: 1152 samples/frame, MPEG2/2.5: 576 samples/frame r.samplesPerFrame = if (r.mpegID == MPEG1_ID) || (r.layerID == LAYER2_ID) then 1152 else 576 r.bytesPerSlot = 1 r.frameSizeRaw = (r.samplesPerFrame / 8) * (r.bitrateKBPS*1000) / r.samplingRateHz + (if r.padding then 1 else 0) # Make the frameSize be the proper floor'd byte length r.frameSize = ~~r.frameSizeRaw if (!r.frameSize) throw new Error('bad size: ' + r.frameSize) # -- compute StreamMachine-specific header bits -- # r.frames_per_sec = r.samplingRateHz / r.samplesPerFrame r.duration = (1 / r.frames_per_sec) * 1000 r.stream_key = ['<KEY>',r.<KEY>,r.bitrate<KEY>,(if r.modeName in ["Stereo","J-Stereo"] then "s" else "m")].join("-") r
true
strtok = require('strtok2') assert = require("assert") module.exports = class MP3 extends require("stream").Writable ID3V1_LENGTH = 128 ID3V2_HEADER_LENGTH = 10 MPEG_HEADER_LENGTH = 4 FIRST_BYTE = new strtok.BufferType(1) # Mp3 parsing logic borrowed from node-lame: https://github.com/TooTallNate/node-lame MPEG_HEADER = new strtok.BufferType(MPEG_HEADER_LENGTH) REST_OF_ID3V2_HEADER = new strtok.BufferType(ID3V2_HEADER_LENGTH - MPEG_HEADER_LENGTH) REST_OF_ID3V1 = new strtok.BufferType(ID3V1_LENGTH - MPEG_HEADER_LENGTH) LAYER1_ID = 3 LAYER2_ID = 2 LAYER3_ID = 1 MPEG1_ID = 3 MPEG2_ID = 2 MPEG25_ID = 0 MODE_MONO = 3 MODE_DUAL = 2 MODE_JOINT = 1 MODE_STEREO = 0 MPEG_NAME = [ "MPEG2.5", null, "MPEG2", "MPEG1" ] LAYER_NAME = [ null, "Layer3", "Layer2", "Layer1" ] MODE_NAME = [ "Stereo", "J-Stereo", "Dual", "Mono" ] SAMPLING_RATES = [ 44100, 48000, 32000, 0 ] BITRATE_MPEG1_LAYER1 = [ 0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448 ] BITRATE_MPEG1_LAYER2 = [ 0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384 ] BITRATE_MPEG1_LAYER3 = [ 0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320 ] BITRATE_MPEG2_LAYER1 = [ 0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256 ] BITRATE_MPEG2_LAYER2A3 = [ 0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160 ] BITRATE_MAP = [ [ null, BITRATE_MPEG2_LAYER2A3, BITRATE_MPEG2_LAYER2A3, BITRATE_MPEG2_LAYER1 ], # MPEG2.5 null, [ null, BITRATE_MPEG2_LAYER2A3, BITRATE_MPEG2_LAYER2A3, BITRATE_MPEG2_LAYER1 ], # MPEG2 [ null, BITRATE_MPEG1_LAYER3, BITRATE_MPEG1_LAYER2, BITRATE_MPEG1_LAYER1 ] ] constructor: -> super # create an internal stream to pass to strtok @istream = new (require("events").EventEmitter) @outbuf = [] @_flushing = false # set up status @frameSize = -1 @beginning = true @gotFF = false @gotID3 = 0 @byteTwo = null @frameHeader = null @frameHeaderBuf = null @id3v2 = null @_parsingId3v1 = false @_parsingId3v2 = false @_finishingId3v2 = false @_id3v2_1 = null @_id3v2_2 = null @_id3v1_1 = null @once "finish", => @_flushing = setTimeout => @emit "end" , 500 _emitAndMaybeEnd = (args...) => @emit args... if @_flushing clearTimeout @_flushing @_flushing = setTimeout => @emit "end" , 500 strtok.parse @istream, (v,cb) => # -- initial request -- # if v == undefined # we need to examine each byte until we get a FF or ID3 return FIRST_BYTE # -- ID3v1 tag -- # if @_parsingId3v1 # our first byte is in @_id3v1_1 id3 = @parseId3V1(Buffer.concat([@_id3v1_1,v])) _emitAndMaybeEnd "id3v1", id3 @_id3v1_1 = null @_parsingId3v1 = false return MPEG_HEADER # -- ID3v2 tag -- # if @_parsingId3v2 # we'll already have @id3v2 started with versionMajor and # our first byte in @_id3v2_1 @id3v2.versionMinor = v[0] @id3v2.flags = v[1] # calculate the length @id3v2.length = (v[5] & 0x7f) | (( v[4] & 0x7f ) << 7) | (( v[3] & 0x7f ) << 14) | (( v[2] & 0x7f ) << 21) @_parsingId3v2 = false; @_finishingId3v2 = true; @_id3v2_2 = v; return new strtok.BufferType @id3v2.length if @_finishingId3v2 # step 3 in the ID3v2 parse... b = Buffer.concat([@_id3v2_1, @_id3v2_2, v]) _emitAndMaybeEnd 'id3v2', b @_finishingId3v2 = false return FIRST_BYTE; # -- frame header -- # if @frameSize == -1 && @frameHeader # we're on-schedule now... we've had a valid frame. # buffer should be four bytes tag = v.toString 'ascii', 0, 3 if tag == 'ID3' # parse ID3v2 tag _emitAndMaybeEnd "debug", "got an ID3" @_parsingId3v2 = true @id3v2 = versionMajor:v[3] @_id3v2_1 = v return REST_OF_ID3V2_HEADER else if tag == 'TAG' # parse ID3v1 tag _emitAndMaybeEnd "debug", "got a TAG" @_id3v1_1 = v @_parsingId3v1 = true # grab 125 bytes return REST_OF_ID3V1 else try h = @parseFrame(v) catch e # uh oh... bad news _emitAndMaybeEnd "debug", "invalid header... ", v, tag, @frameHeader @frameHeader = null return FIRST_BYTE @frameHeader = h @frameHeaderBuf = v _emitAndMaybeEnd "header", v, h @frameSize = @frameHeader.frameSize if @frameSize == 1 # problem... just start over _emitAndMaybeEnd "debug", "Invalid frame header: ", h return FIRST_BYTE else return new strtok.BufferType(@frameSize - MPEG_HEADER_LENGTH); # -- first header -- # if @gotFF and @byteTwo buf = Buffer.alloc(4) buf[0] = 0xFF buf[1] = @byteTwo buf[2] = v[0] buf[3] = v[1] try h = @parseFrame(buf) catch e # invalid header... chuck everything and try again _emitAndMaybeEnd "debug", "chucking invalid try at header: ", buf @gotFF = false @byteTwo = null return FIRST_BYTE # valid header... we're on schedule now @gotFF = false @byteTwo = null @beginning = false @frameHeader = h @frameHeaderBuf = buf _emitAndMaybeEnd "header", h @frameSize = @frameHeader.frameSize if @frameSize == 1 # problem... just start over _emitAndMaybeEnd "debug", "Invalid frame header: ", h return FIRST_BYTE else _emitAndMaybeEnd "debug", "On-tracking with frame of: ", @frameSize - MPEG_HEADER_LENGTH return new strtok.BufferType(@frameSize - MPEG_HEADER_LENGTH); if @gotFF if v[0]>>4 >= 0xE @byteTwo = v[0] # need two more bytes return new strtok.BufferType(2) else @gotFF = false if @frameSize == -1 && !@gotFF if v[0] == 0xFF # possible start of frame header. need next byte to know more @gotFF = true return FIRST_BYTE else if v[0] == 0x49 # could be the I in ID3 @gotID3 = 1 return FIRST_BYTE else if @gotID3 == 1 && v[0] == 0x44 @gotID3 = 2 return FIRST_BYTE else if @gotID3 == 2 && v[0] == 0x33 @gotID3 = 3 return FIRST_BYTE else if @gotID3 == 3 @_id3v2_1 = Buffer.from([0x49,0x44,0x33,v[0]]) @id3v2 = versionMajor:v[0] @_parsingId3v2 = true @gotID3 = 0 return REST_OF_ID3V2_HEADER else # keep looking return FIRST_BYTE # -- data frame -- # if @frameHeaderBuf frame = Buffer.alloc( @frameHeaderBuf.length + v.length ) @frameHeaderBuf.copy(frame,0) v.copy(frame,@frameHeaderBuf.length) _emitAndMaybeEnd "frame", frame, @frameHeader @frameSize = -1 return MPEG_HEADER #---------- _write: (chunk,encoding,cb) -> if @_flushing throw new Error "MP3 write while flushing." @istream.emit "data", chunk cb?() #---------- parseId3V1: (id3v1) -> id3 = {} _stripNull = (buf) -> idx = buf.toJSON().indexOf(0) buf.toString "ascii", 0, if idx == -1 then buf.length else idx # TAG: 3 bytes # title: 30 bytes id3.title = _stripNull id3v1.slice(3,33) # artist: 30 bytes id3.artist = _stripNull id3v1.slice(33,63) # album: 30 bytes id3.album = _stripNull id3v1.slice(63,93) # year: 4 bytes id3.year = _stripNull id3v1.slice(93,97) # comment: 28 - 30 bytes if id3v1[125] == 0 id3.comment = _stripNull id3v1.slice(97,125) id3.track = id3v1.readUInt8(126) else id3.track = null id3.comment = _stripNull id3v1.slice(97,127) # genre: 1 byte id3.genre = id3v1.readUInt8(127) id3 #---------- parseFrame: (b) -> assert.ok Buffer.isBuffer(b) # -- first twelve bits must be FF[EF] -- # assert.ok ( b[0] == 0xFF && (b[1] >> 4) >= 0xE ), "Buffer does not start with FF[EF]" header32 = b.readUInt32BE(0) # -- mpeg id -- # r = mpegID: (header32 >> 19) & 3 layerID: (header32 >> 17) & 3 crc16used: (header32 & 0x00010000) == 0 bitrateIndex: (header32 >> 12) & 0xF samplingRateIndex: (header32 >> 10) & 3 padding: (header32 & 0x00000200) != 0 privateBitSet: (header32 & 0x00000100) != 0 mode: (header32 >> 6) & 3 modeExtension: (header32 >> 4) & 3 copyrighted: (header32 & 0x00000008) != 0 original: (header32 & 0x00000004) == 0 emphasis: header32 & 3 # placeholders for mem allocation channels: 0 bitrateKBPS: 0 mpegName: "" layerName: "" modeName: "" samplingRateHz: 0 samplesPerFrame: 0 bytesPerSlot: 0 frameSizeRaw: 0 frameSize: 0 frames_per_sec: 0 stream_key: "" # now fill in the derived values... r.channels = if r.mode == MODE_MONO then 1 else 2 r.bitrateKBPS = BITRATE_MAP[ r.mpegID ][ r.layerID ][ r.bitrateIndex ] r.mpegName = MPEG_NAME[ r.mpegID ] r.layerName = LAYER_NAME[ r.layerID ] r.modeName = MODE_NAME[ r.mode ] r.samplingRateHz = SAMPLING_RATES[r.samplingRateIndex] if r.mpegID == MPEG2_ID r.samplingRateHz >>= 1 # 16,22,48 kHz else if r.mpegID == MPEG25_ID r.samplingRateHz >>= 2 # 8,11,24 kHz if r.layerID == LAYER1_ID # layer 1: always 384 samples/frame and 4byte-slots r.samplesPerFrame = 384; r.bytesPerSlot = 4; r.frameSizeRaw = (12 * (r.bitrateKBPS*1000) / (r.samplingRateHz*10) + (r.padding ? 1 : 0)) * 4; else # layer 2: always 1152 samples/frame # layer 3: MPEG1: 1152 samples/frame, MPEG2/2.5: 576 samples/frame r.samplesPerFrame = if (r.mpegID == MPEG1_ID) || (r.layerID == LAYER2_ID) then 1152 else 576 r.bytesPerSlot = 1 r.frameSizeRaw = (r.samplesPerFrame / 8) * (r.bitrateKBPS*1000) / r.samplingRateHz + (if r.padding then 1 else 0) # Make the frameSize be the proper floor'd byte length r.frameSize = ~~r.frameSizeRaw if (!r.frameSize) throw new Error('bad size: ' + r.frameSize) # -- compute StreamMachine-specific header bits -- # r.frames_per_sec = r.samplingRateHz / r.samplesPerFrame r.duration = (1 / r.frames_per_sec) * 1000 r.stream_key = ['PI:KEY:<KEY>END_PI',r.PI:KEY:<KEY>END_PI,r.bitratePI:KEY:<KEY>END_PI,(if r.modeName in ["Stereo","J-Stereo"] then "s" else "m")].join("-") r
[ { "context": "y] = inputParams[key]\n else if key is 'clipDirection' or key is 'skipSoftWrapIndentation'\n # ", "end": 1662, "score": 0.522429347038269, "start": 1653, "tag": "KEY", "value": "Direction" }, { "context": " else if key is 'clipDirection' or key is 'sk...
src/marker.coffee
aminya/text-buffer
139
{extend, isEqual, omit, pick, size} = require 'underscore-plus' {Emitter} = require 'event-kit' Delegator = require 'delegato' Point = require './point' Range = require './range' Grim = require 'grim' OptionKeys = new Set(['reversed', 'tailed', 'invalidate', 'exclusive']) # Private: Represents a buffer annotation that remains logically stationary # even as the buffer changes. This is used to represent cursors, folds, snippet # targets, misspelled words, and anything else that needs to track a logical # location in the buffer over time. # # Head and Tail: # Markers always have a *head* and sometimes have a *tail*. If you think of a # marker as an editor selection, the tail is the part that's stationary and the # head is the part that moves when the mouse is moved. A marker without a tail # always reports an empty range at the head position. A marker with a head position # greater than the tail is in a "normal" orientation. If the head precedes the # tail the marker is in a "reversed" orientation. # # Validity: # Markers are considered *valid* when they are first created. Depending on the # invalidation strategy you choose, certain changes to the buffer can cause a # marker to become invalid, for example if the text surrounding the marker is # deleted. See {TextBuffer::markRange} for invalidation strategies. module.exports = class Marker Delegator.includeInto(this) @extractParams: (inputParams) -> outputParams = {} containsCustomProperties = false if inputParams? for key in Object.keys(inputParams) if OptionKeys.has(key) outputParams[key] = inputParams[key] else if key is 'clipDirection' or key is 'skipSoftWrapIndentation' # TODO: Ignore these two keys for now. Eventually, when the # deprecation below will be gone, we can remove this conditional as # well, and just return standard marker properties. else containsCustomProperties = true outputParams.properties ?= {} outputParams.properties[key] = inputParams[key] # TODO: Remove both this deprecation and the conditional above on the # release after the one where we'll ship `DisplayLayer`. if containsCustomProperties Grim.deprecate(""" Assigning custom properties to a marker when creating/copying it is deprecated. Please, consider storing the custom properties you need in some other object in your package, keyed by the marker's id property. """) outputParams @delegatesMethods 'containsPoint', 'containsRange', 'intersectsRow', toMethod: 'getRange' constructor: (@id, @layer, range, params, exclusivitySet = false) -> {@tailed, @reversed, @valid, @invalidate, @exclusive, @properties} = params @emitter = new Emitter @tailed ?= true @reversed ?= false @valid ?= true @invalidate ?= 'overlap' @properties ?= {} @hasChangeObservers = false Object.freeze(@properties) @layer.setMarkerIsExclusive(@id, @isExclusive()) unless exclusivitySet ### Section: Event Subscription ### # Public: Invoke the given callback when the marker is destroyed. # # * `callback` {Function} to be called when the marker is destroyed. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onDidDestroy: (callback) -> @layer.markersWithDestroyListeners.add(this) @emitter.on 'did-destroy', callback # Public: Invoke the given callback when the state of the marker changes. # # * `callback` {Function} to be called when the marker changes. # * `event` {Object} with the following keys: # * `oldHeadPosition` {Point} representing the former head position # * `newHeadPosition` {Point} representing the new head position # * `oldTailPosition` {Point} representing the former tail position # * `newTailPosition` {Point} representing the new tail position # * `wasValid` {Boolean} indicating whether the marker was valid before the change # * `isValid` {Boolean} indicating whether the marker is now valid # * `hadTail` {Boolean} indicating whether the marker had a tail before the change # * `hasTail` {Boolean} indicating whether the marker now has a tail # * `oldProperties` {Object} containing the marker's custom properties before the change. # * `newProperties` {Object} containing the marker's custom properties after the change. # * `textChanged` {Boolean} indicating whether this change was caused by a textual change # to the buffer or whether the marker was manipulated directly via its public API. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onDidChange: (callback) -> unless @hasChangeObservers @previousEventState = @getSnapshot(@getRange()) @hasChangeObservers = true @layer.markersWithChangeListeners.add(this) @emitter.on 'did-change', callback # Public: Returns the current {Range} of the marker. The range is immutable. getRange: -> @layer.getMarkerRange(@id) # Public: Sets the range of the marker. # # * `range` A {Range} or range-compatible {Array}. The range will be clipped # before it is assigned. # * `params` (optional) An {Object} with the following keys: # * `reversed` {Boolean} indicating the marker will to be in a reversed # orientation. # * `exclusive` {Boolean} indicating that changes occurring at either end of # the marker will be considered *outside* the marker rather than inside. # This defaults to `false` unless the marker's invalidation strategy is # `inside` or the marker has no tail, in which case it defaults to `true`. setRange: (range, params) -> params ?= {} @update(@getRange(), {reversed: params.reversed, tailed: true, range: Range.fromObject(range, true), exclusive: params.exclusive}) # Public: Returns a {Point} representing the marker's current head position. getHeadPosition: -> if @reversed @getStartPosition() else @getEndPosition() # Public: Sets the head position of the marker. # # * `position` A {Point} or point-compatible {Array}. The position will be # clipped before it is assigned. setHeadPosition: (position) -> position = Point.fromObject(position) oldRange = @getRange() params = {} if @hasTail() if @isReversed() if position.isLessThan(oldRange.end) params.range = new Range(position, oldRange.end) else params.reversed = false params.range = new Range(oldRange.end, position) else if position.isLessThan(oldRange.start) params.reversed = true params.range = new Range(position, oldRange.start) else params.range = new Range(oldRange.start, position) else params.range = new Range(position, position) @update(oldRange, params) # Public: Returns a {Point} representing the marker's current tail position. # If the marker has no tail, the head position will be returned instead. getTailPosition: -> if @reversed @getEndPosition() else @getStartPosition() # Public: Sets the tail position of the marker. If the marker doesn't have a # tail, it will after calling this method. # # * `position` A {Point} or point-compatible {Array}. The position will be # clipped before it is assigned. setTailPosition: (position) -> position = Point.fromObject(position) oldRange = @getRange() params = {tailed: true} if @reversed if position.isLessThan(oldRange.start) params.reversed = false params.range = new Range(position, oldRange.start) else params.range = new Range(oldRange.start, position) else if position.isLessThan(oldRange.end) params.range = new Range(position, oldRange.end) else params.reversed = true params.range = new Range(oldRange.end, position) @update(oldRange, params) # Public: Returns a {Point} representing the start position of the marker, # which could be the head or tail position, depending on its orientation. getStartPosition: -> @layer.getMarkerStartPosition(@id) # Public: Returns a {Point} representing the end position of the marker, # which could be the head or tail position, depending on its orientation. getEndPosition: -> @layer.getMarkerEndPosition(@id) # Public: Removes the marker's tail. After calling the marker's head position # will be reported as its current tail position until the tail is planted # again. clearTail: -> headPosition = @getHeadPosition() @update(@getRange(), {tailed: false, reversed: false, range: Range(headPosition, headPosition)}) # Public: Plants the marker's tail at the current head position. After calling # the marker's tail position will be its head position at the time of the # call, regardless of where the marker's head is moved. plantTail: -> unless @hasTail() headPosition = @getHeadPosition() @update(@getRange(), {tailed: true, range: new Range(headPosition, headPosition)}) # Public: Returns a {Boolean} indicating whether the head precedes the tail. isReversed: -> @tailed and @reversed # Public: Returns a {Boolean} indicating whether the marker has a tail. hasTail: -> @tailed # Public: Is the marker valid? # # Returns a {Boolean}. isValid: -> not @isDestroyed() and @valid # Public: Is the marker destroyed? # # Returns a {Boolean}. isDestroyed: -> not @layer.hasMarker(@id) # Public: Returns a {Boolean} indicating whether changes that occur exactly at # the marker's head or tail cause it to move. isExclusive: -> if @exclusive? @exclusive else @getInvalidationStrategy() is 'inside' or not @hasTail() # Public: Returns a {Boolean} indicating whether this marker is equivalent to # another marker, meaning they have the same range and options. # # * `other` {Marker} other marker isEqual: (other) -> @invalidate is other.invalidate and @tailed is other.tailed and @reversed is other.reversed and @exclusive is other.exclusive and isEqual(@properties, other.properties) and @getRange().isEqual(other.getRange()) # Public: Get the invalidation strategy for this marker. # # Valid values include: `never`, `surround`, `overlap`, `inside`, and `touch`. # # Returns a {String}. getInvalidationStrategy: -> @invalidate # Public: Returns an {Object} containing any custom properties associated with # the marker. getProperties: -> @properties # Public: Merges an {Object} containing new properties into the marker's # existing properties. # # * `properties` {Object} setProperties: (properties) -> @update(@getRange(), properties: extend({}, @properties, properties)) # Public: Creates and returns a new {Marker} with the same properties as this # marker. # # * `params` {Object} copy: (options={}) -> snapshot = @getSnapshot() options = Marker.extractParams(options) @layer.createMarker(@getRange(), extend( {} snapshot, options, properties: extend({}, snapshot.properties, options.properties) )) # Public: Destroys the marker, causing it to emit the 'destroyed' event. destroy: (suppressMarkerLayerUpdateEvents) -> return if @isDestroyed() if @trackDestruction error = new Error Error.captureStackTrace(error) @destroyStackTrace = error.stack @layer.destroyMarker(this, suppressMarkerLayerUpdateEvents) @emitter.emit 'did-destroy' @emitter.clear() # Public: Compares this marker to another based on their ranges. # # * `other` {Marker} compare: (other) -> @layer.compareMarkers(@id, other.id) # Returns whether this marker matches the given parameters. The parameters # are the same as {MarkerLayer::findMarkers}. matchesParams: (params) -> for key in Object.keys(params) return false unless @matchesParam(key, params[key]) true # Returns whether this marker matches the given parameter name and value. # The parameters are the same as {MarkerLayer::findMarkers}. matchesParam: (key, value) -> switch key when 'startPosition' @getStartPosition().isEqual(value) when 'endPosition' @getEndPosition().isEqual(value) when 'containsPoint', 'containsPosition' @containsPoint(value) when 'containsRange' @containsRange(value) when 'startRow' @getStartPosition().row is value when 'endRow' @getEndPosition().row is value when 'intersectsRow' @intersectsRow(value) when 'invalidate', 'reversed', 'tailed' isEqual(@[key], value) when 'valid' @isValid() is value else isEqual(@properties[key], value) update: (oldRange, {range, reversed, tailed, valid, exclusive, properties}, textChanged=false, suppressMarkerLayerUpdateEvents=false) -> return if @isDestroyed() oldRange = Range.fromObject(oldRange) range = Range.fromObject(range) if range? wasExclusive = @isExclusive() updated = propertiesChanged = false if range? and not range.isEqual(oldRange) @layer.setMarkerRange(@id, range) updated = true if reversed? and reversed isnt @reversed @reversed = reversed updated = true if tailed? and tailed isnt @tailed @tailed = tailed updated = true if valid? and valid isnt @valid @valid = valid updated = true if exclusive? and exclusive isnt @exclusive @exclusive = exclusive updated = true if wasExclusive isnt @isExclusive() @layer.setMarkerIsExclusive(@id, @isExclusive()) updated = true if properties? and not isEqual(properties, @properties) @properties = Object.freeze(properties) propertiesChanged = true updated = true @emitChangeEvent(range ? oldRange, textChanged, propertiesChanged) @layer.markerUpdated() if updated and not suppressMarkerLayerUpdateEvents updated getSnapshot: (range, includeMarker=true) -> snapshot = {range, @properties, @reversed, @tailed, @valid, @invalidate, @exclusive} snapshot.marker = this if includeMarker Object.freeze(snapshot) toString: -> "[Marker #{@id}, #{@getRange()}]" ### Section: Private ### inspect: -> @toString() emitChangeEvent: (currentRange, textChanged, propertiesChanged) -> return unless @hasChangeObservers oldState = @previousEventState currentRange ?= @getRange() return false unless propertiesChanged or oldState.valid isnt @valid or oldState.tailed isnt @tailed or oldState.reversed isnt @reversed or oldState.range.compare(currentRange) isnt 0 newState = @previousEventState = @getSnapshot(currentRange) if oldState.reversed oldHeadPosition = oldState.range.start oldTailPosition = oldState.range.end else oldHeadPosition = oldState.range.end oldTailPosition = oldState.range.start if newState.reversed newHeadPosition = newState.range.start newTailPosition = newState.range.end else newHeadPosition = newState.range.end newTailPosition = newState.range.start @emitter.emit("did-change", { wasValid: oldState.valid, isValid: newState.valid hadTail: oldState.tailed, hasTail: newState.tailed oldProperties: oldState.properties, newProperties: newState.properties oldHeadPosition, newHeadPosition, oldTailPosition, newTailPosition textChanged }) true
75862
{extend, isEqual, omit, pick, size} = require 'underscore-plus' {Emitter} = require 'event-kit' Delegator = require 'delegato' Point = require './point' Range = require './range' Grim = require 'grim' OptionKeys = new Set(['reversed', 'tailed', 'invalidate', 'exclusive']) # Private: Represents a buffer annotation that remains logically stationary # even as the buffer changes. This is used to represent cursors, folds, snippet # targets, misspelled words, and anything else that needs to track a logical # location in the buffer over time. # # Head and Tail: # Markers always have a *head* and sometimes have a *tail*. If you think of a # marker as an editor selection, the tail is the part that's stationary and the # head is the part that moves when the mouse is moved. A marker without a tail # always reports an empty range at the head position. A marker with a head position # greater than the tail is in a "normal" orientation. If the head precedes the # tail the marker is in a "reversed" orientation. # # Validity: # Markers are considered *valid* when they are first created. Depending on the # invalidation strategy you choose, certain changes to the buffer can cause a # marker to become invalid, for example if the text surrounding the marker is # deleted. See {TextBuffer::markRange} for invalidation strategies. module.exports = class Marker Delegator.includeInto(this) @extractParams: (inputParams) -> outputParams = {} containsCustomProperties = false if inputParams? for key in Object.keys(inputParams) if OptionKeys.has(key) outputParams[key] = inputParams[key] else if key is 'clip<KEY>' or key is 'skip<KEY>' # TODO: Ignore these two keys for now. Eventually, when the # deprecation below will be gone, we can remove this conditional as # well, and just return standard marker properties. else containsCustomProperties = true outputParams.properties ?= {} outputParams.properties[key] = inputParams[key] # TODO: Remove both this deprecation and the conditional above on the # release after the one where we'll ship `DisplayLayer`. if containsCustomProperties Grim.deprecate(""" Assigning custom properties to a marker when creating/copying it is deprecated. Please, consider storing the custom properties you need in some other object in your package, keyed by the marker's id property. """) outputParams @delegatesMethods 'containsPoint', 'containsRange', 'intersectsRow', toMethod: 'getRange' constructor: (@id, @layer, range, params, exclusivitySet = false) -> {@tailed, @reversed, @valid, @invalidate, @exclusive, @properties} = params @emitter = new Emitter @tailed ?= true @reversed ?= false @valid ?= true @invalidate ?= 'overlap' @properties ?= {} @hasChangeObservers = false Object.freeze(@properties) @layer.setMarkerIsExclusive(@id, @isExclusive()) unless exclusivitySet ### Section: Event Subscription ### # Public: Invoke the given callback when the marker is destroyed. # # * `callback` {Function} to be called when the marker is destroyed. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onDidDestroy: (callback) -> @layer.markersWithDestroyListeners.add(this) @emitter.on 'did-destroy', callback # Public: Invoke the given callback when the state of the marker changes. # # * `callback` {Function} to be called when the marker changes. # * `event` {Object} with the following keys: # * `oldHeadPosition` {Point} representing the former head position # * `newHeadPosition` {Point} representing the new head position # * `oldTailPosition` {Point} representing the former tail position # * `newTailPosition` {Point} representing the new tail position # * `wasValid` {Boolean} indicating whether the marker was valid before the change # * `isValid` {Boolean} indicating whether the marker is now valid # * `hadTail` {Boolean} indicating whether the marker had a tail before the change # * `hasTail` {Boolean} indicating whether the marker now has a tail # * `oldProperties` {Object} containing the marker's custom properties before the change. # * `newProperties` {Object} containing the marker's custom properties after the change. # * `textChanged` {Boolean} indicating whether this change was caused by a textual change # to the buffer or whether the marker was manipulated directly via its public API. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onDidChange: (callback) -> unless @hasChangeObservers @previousEventState = @getSnapshot(@getRange()) @hasChangeObservers = true @layer.markersWithChangeListeners.add(this) @emitter.on 'did-change', callback # Public: Returns the current {Range} of the marker. The range is immutable. getRange: -> @layer.getMarkerRange(@id) # Public: Sets the range of the marker. # # * `range` A {Range} or range-compatible {Array}. The range will be clipped # before it is assigned. # * `params` (optional) An {Object} with the following keys: # * `reversed` {Boolean} indicating the marker will to be in a reversed # orientation. # * `exclusive` {Boolean} indicating that changes occurring at either end of # the marker will be considered *outside* the marker rather than inside. # This defaults to `false` unless the marker's invalidation strategy is # `inside` or the marker has no tail, in which case it defaults to `true`. setRange: (range, params) -> params ?= {} @update(@getRange(), {reversed: params.reversed, tailed: true, range: Range.fromObject(range, true), exclusive: params.exclusive}) # Public: Returns a {Point} representing the marker's current head position. getHeadPosition: -> if @reversed @getStartPosition() else @getEndPosition() # Public: Sets the head position of the marker. # # * `position` A {Point} or point-compatible {Array}. The position will be # clipped before it is assigned. setHeadPosition: (position) -> position = Point.fromObject(position) oldRange = @getRange() params = {} if @hasTail() if @isReversed() if position.isLessThan(oldRange.end) params.range = new Range(position, oldRange.end) else params.reversed = false params.range = new Range(oldRange.end, position) else if position.isLessThan(oldRange.start) params.reversed = true params.range = new Range(position, oldRange.start) else params.range = new Range(oldRange.start, position) else params.range = new Range(position, position) @update(oldRange, params) # Public: Returns a {Point} representing the marker's current tail position. # If the marker has no tail, the head position will be returned instead. getTailPosition: -> if @reversed @getEndPosition() else @getStartPosition() # Public: Sets the tail position of the marker. If the marker doesn't have a # tail, it will after calling this method. # # * `position` A {Point} or point-compatible {Array}. The position will be # clipped before it is assigned. setTailPosition: (position) -> position = Point.fromObject(position) oldRange = @getRange() params = {tailed: true} if @reversed if position.isLessThan(oldRange.start) params.reversed = false params.range = new Range(position, oldRange.start) else params.range = new Range(oldRange.start, position) else if position.isLessThan(oldRange.end) params.range = new Range(position, oldRange.end) else params.reversed = true params.range = new Range(oldRange.end, position) @update(oldRange, params) # Public: Returns a {Point} representing the start position of the marker, # which could be the head or tail position, depending on its orientation. getStartPosition: -> @layer.getMarkerStartPosition(@id) # Public: Returns a {Point} representing the end position of the marker, # which could be the head or tail position, depending on its orientation. getEndPosition: -> @layer.getMarkerEndPosition(@id) # Public: Removes the marker's tail. After calling the marker's head position # will be reported as its current tail position until the tail is planted # again. clearTail: -> headPosition = @getHeadPosition() @update(@getRange(), {tailed: false, reversed: false, range: Range(headPosition, headPosition)}) # Public: Plants the marker's tail at the current head position. After calling # the marker's tail position will be its head position at the time of the # call, regardless of where the marker's head is moved. plantTail: -> unless @hasTail() headPosition = @getHeadPosition() @update(@getRange(), {tailed: true, range: new Range(headPosition, headPosition)}) # Public: Returns a {Boolean} indicating whether the head precedes the tail. isReversed: -> @tailed and @reversed # Public: Returns a {Boolean} indicating whether the marker has a tail. hasTail: -> @tailed # Public: Is the marker valid? # # Returns a {Boolean}. isValid: -> not @isDestroyed() and @valid # Public: Is the marker destroyed? # # Returns a {Boolean}. isDestroyed: -> not @layer.hasMarker(@id) # Public: Returns a {Boolean} indicating whether changes that occur exactly at # the marker's head or tail cause it to move. isExclusive: -> if @exclusive? @exclusive else @getInvalidationStrategy() is 'inside' or not @hasTail() # Public: Returns a {Boolean} indicating whether this marker is equivalent to # another marker, meaning they have the same range and options. # # * `other` {Marker} other marker isEqual: (other) -> @invalidate is other.invalidate and @tailed is other.tailed and @reversed is other.reversed and @exclusive is other.exclusive and isEqual(@properties, other.properties) and @getRange().isEqual(other.getRange()) # Public: Get the invalidation strategy for this marker. # # Valid values include: `never`, `surround`, `overlap`, `inside`, and `touch`. # # Returns a {String}. getInvalidationStrategy: -> @invalidate # Public: Returns an {Object} containing any custom properties associated with # the marker. getProperties: -> @properties # Public: Merges an {Object} containing new properties into the marker's # existing properties. # # * `properties` {Object} setProperties: (properties) -> @update(@getRange(), properties: extend({}, @properties, properties)) # Public: Creates and returns a new {Marker} with the same properties as this # marker. # # * `params` {Object} copy: (options={}) -> snapshot = @getSnapshot() options = Marker.extractParams(options) @layer.createMarker(@getRange(), extend( {} snapshot, options, properties: extend({}, snapshot.properties, options.properties) )) # Public: Destroys the marker, causing it to emit the 'destroyed' event. destroy: (suppressMarkerLayerUpdateEvents) -> return if @isDestroyed() if @trackDestruction error = new Error Error.captureStackTrace(error) @destroyStackTrace = error.stack @layer.destroyMarker(this, suppressMarkerLayerUpdateEvents) @emitter.emit 'did-destroy' @emitter.clear() # Public: Compares this marker to another based on their ranges. # # * `other` {Marker} compare: (other) -> @layer.compareMarkers(@id, other.id) # Returns whether this marker matches the given parameters. The parameters # are the same as {MarkerLayer::findMarkers}. matchesParams: (params) -> for key in Object.keys(params) return false unless @matchesParam(key, params[key]) true # Returns whether this marker matches the given parameter name and value. # The parameters are the same as {MarkerLayer::findMarkers}. matchesParam: (key, value) -> switch key when 'startPosition' @getStartPosition().isEqual(value) when 'endPosition' @getEndPosition().isEqual(value) when 'containsPoint', 'containsPosition' @containsPoint(value) when 'containsRange' @containsRange(value) when 'startRow' @getStartPosition().row is value when 'endRow' @getEndPosition().row is value when 'intersectsRow' @intersectsRow(value) when 'invalidate', 'reversed', 'tailed' isEqual(@[key], value) when 'valid' @isValid() is value else isEqual(@properties[key], value) update: (oldRange, {range, reversed, tailed, valid, exclusive, properties}, textChanged=false, suppressMarkerLayerUpdateEvents=false) -> return if @isDestroyed() oldRange = Range.fromObject(oldRange) range = Range.fromObject(range) if range? wasExclusive = @isExclusive() updated = propertiesChanged = false if range? and not range.isEqual(oldRange) @layer.setMarkerRange(@id, range) updated = true if reversed? and reversed isnt @reversed @reversed = reversed updated = true if tailed? and tailed isnt @tailed @tailed = tailed updated = true if valid? and valid isnt @valid @valid = valid updated = true if exclusive? and exclusive isnt @exclusive @exclusive = exclusive updated = true if wasExclusive isnt @isExclusive() @layer.setMarkerIsExclusive(@id, @isExclusive()) updated = true if properties? and not isEqual(properties, @properties) @properties = Object.freeze(properties) propertiesChanged = true updated = true @emitChangeEvent(range ? oldRange, textChanged, propertiesChanged) @layer.markerUpdated() if updated and not suppressMarkerLayerUpdateEvents updated getSnapshot: (range, includeMarker=true) -> snapshot = {range, @properties, @reversed, @tailed, @valid, @invalidate, @exclusive} snapshot.marker = this if includeMarker Object.freeze(snapshot) toString: -> "[Marker #{@id}, #{@getRange()}]" ### Section: Private ### inspect: -> @toString() emitChangeEvent: (currentRange, textChanged, propertiesChanged) -> return unless @hasChangeObservers oldState = @previousEventState currentRange ?= @getRange() return false unless propertiesChanged or oldState.valid isnt @valid or oldState.tailed isnt @tailed or oldState.reversed isnt @reversed or oldState.range.compare(currentRange) isnt 0 newState = @previousEventState = @getSnapshot(currentRange) if oldState.reversed oldHeadPosition = oldState.range.start oldTailPosition = oldState.range.end else oldHeadPosition = oldState.range.end oldTailPosition = oldState.range.start if newState.reversed newHeadPosition = newState.range.start newTailPosition = newState.range.end else newHeadPosition = newState.range.end newTailPosition = newState.range.start @emitter.emit("did-change", { wasValid: oldState.valid, isValid: newState.valid hadTail: oldState.tailed, hasTail: newState.tailed oldProperties: oldState.properties, newProperties: newState.properties oldHeadPosition, newHeadPosition, oldTailPosition, newTailPosition textChanged }) true
true
{extend, isEqual, omit, pick, size} = require 'underscore-plus' {Emitter} = require 'event-kit' Delegator = require 'delegato' Point = require './point' Range = require './range' Grim = require 'grim' OptionKeys = new Set(['reversed', 'tailed', 'invalidate', 'exclusive']) # Private: Represents a buffer annotation that remains logically stationary # even as the buffer changes. This is used to represent cursors, folds, snippet # targets, misspelled words, and anything else that needs to track a logical # location in the buffer over time. # # Head and Tail: # Markers always have a *head* and sometimes have a *tail*. If you think of a # marker as an editor selection, the tail is the part that's stationary and the # head is the part that moves when the mouse is moved. A marker without a tail # always reports an empty range at the head position. A marker with a head position # greater than the tail is in a "normal" orientation. If the head precedes the # tail the marker is in a "reversed" orientation. # # Validity: # Markers are considered *valid* when they are first created. Depending on the # invalidation strategy you choose, certain changes to the buffer can cause a # marker to become invalid, for example if the text surrounding the marker is # deleted. See {TextBuffer::markRange} for invalidation strategies. module.exports = class Marker Delegator.includeInto(this) @extractParams: (inputParams) -> outputParams = {} containsCustomProperties = false if inputParams? for key in Object.keys(inputParams) if OptionKeys.has(key) outputParams[key] = inputParams[key] else if key is 'clipPI:KEY:<KEY>END_PI' or key is 'skipPI:KEY:<KEY>END_PI' # TODO: Ignore these two keys for now. Eventually, when the # deprecation below will be gone, we can remove this conditional as # well, and just return standard marker properties. else containsCustomProperties = true outputParams.properties ?= {} outputParams.properties[key] = inputParams[key] # TODO: Remove both this deprecation and the conditional above on the # release after the one where we'll ship `DisplayLayer`. if containsCustomProperties Grim.deprecate(""" Assigning custom properties to a marker when creating/copying it is deprecated. Please, consider storing the custom properties you need in some other object in your package, keyed by the marker's id property. """) outputParams @delegatesMethods 'containsPoint', 'containsRange', 'intersectsRow', toMethod: 'getRange' constructor: (@id, @layer, range, params, exclusivitySet = false) -> {@tailed, @reversed, @valid, @invalidate, @exclusive, @properties} = params @emitter = new Emitter @tailed ?= true @reversed ?= false @valid ?= true @invalidate ?= 'overlap' @properties ?= {} @hasChangeObservers = false Object.freeze(@properties) @layer.setMarkerIsExclusive(@id, @isExclusive()) unless exclusivitySet ### Section: Event Subscription ### # Public: Invoke the given callback when the marker is destroyed. # # * `callback` {Function} to be called when the marker is destroyed. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onDidDestroy: (callback) -> @layer.markersWithDestroyListeners.add(this) @emitter.on 'did-destroy', callback # Public: Invoke the given callback when the state of the marker changes. # # * `callback` {Function} to be called when the marker changes. # * `event` {Object} with the following keys: # * `oldHeadPosition` {Point} representing the former head position # * `newHeadPosition` {Point} representing the new head position # * `oldTailPosition` {Point} representing the former tail position # * `newTailPosition` {Point} representing the new tail position # * `wasValid` {Boolean} indicating whether the marker was valid before the change # * `isValid` {Boolean} indicating whether the marker is now valid # * `hadTail` {Boolean} indicating whether the marker had a tail before the change # * `hasTail` {Boolean} indicating whether the marker now has a tail # * `oldProperties` {Object} containing the marker's custom properties before the change. # * `newProperties` {Object} containing the marker's custom properties after the change. # * `textChanged` {Boolean} indicating whether this change was caused by a textual change # to the buffer or whether the marker was manipulated directly via its public API. # # Returns a {Disposable} on which `.dispose()` can be called to unsubscribe. onDidChange: (callback) -> unless @hasChangeObservers @previousEventState = @getSnapshot(@getRange()) @hasChangeObservers = true @layer.markersWithChangeListeners.add(this) @emitter.on 'did-change', callback # Public: Returns the current {Range} of the marker. The range is immutable. getRange: -> @layer.getMarkerRange(@id) # Public: Sets the range of the marker. # # * `range` A {Range} or range-compatible {Array}. The range will be clipped # before it is assigned. # * `params` (optional) An {Object} with the following keys: # * `reversed` {Boolean} indicating the marker will to be in a reversed # orientation. # * `exclusive` {Boolean} indicating that changes occurring at either end of # the marker will be considered *outside* the marker rather than inside. # This defaults to `false` unless the marker's invalidation strategy is # `inside` or the marker has no tail, in which case it defaults to `true`. setRange: (range, params) -> params ?= {} @update(@getRange(), {reversed: params.reversed, tailed: true, range: Range.fromObject(range, true), exclusive: params.exclusive}) # Public: Returns a {Point} representing the marker's current head position. getHeadPosition: -> if @reversed @getStartPosition() else @getEndPosition() # Public: Sets the head position of the marker. # # * `position` A {Point} or point-compatible {Array}. The position will be # clipped before it is assigned. setHeadPosition: (position) -> position = Point.fromObject(position) oldRange = @getRange() params = {} if @hasTail() if @isReversed() if position.isLessThan(oldRange.end) params.range = new Range(position, oldRange.end) else params.reversed = false params.range = new Range(oldRange.end, position) else if position.isLessThan(oldRange.start) params.reversed = true params.range = new Range(position, oldRange.start) else params.range = new Range(oldRange.start, position) else params.range = new Range(position, position) @update(oldRange, params) # Public: Returns a {Point} representing the marker's current tail position. # If the marker has no tail, the head position will be returned instead. getTailPosition: -> if @reversed @getEndPosition() else @getStartPosition() # Public: Sets the tail position of the marker. If the marker doesn't have a # tail, it will after calling this method. # # * `position` A {Point} or point-compatible {Array}. The position will be # clipped before it is assigned. setTailPosition: (position) -> position = Point.fromObject(position) oldRange = @getRange() params = {tailed: true} if @reversed if position.isLessThan(oldRange.start) params.reversed = false params.range = new Range(position, oldRange.start) else params.range = new Range(oldRange.start, position) else if position.isLessThan(oldRange.end) params.range = new Range(position, oldRange.end) else params.reversed = true params.range = new Range(oldRange.end, position) @update(oldRange, params) # Public: Returns a {Point} representing the start position of the marker, # which could be the head or tail position, depending on its orientation. getStartPosition: -> @layer.getMarkerStartPosition(@id) # Public: Returns a {Point} representing the end position of the marker, # which could be the head or tail position, depending on its orientation. getEndPosition: -> @layer.getMarkerEndPosition(@id) # Public: Removes the marker's tail. After calling the marker's head position # will be reported as its current tail position until the tail is planted # again. clearTail: -> headPosition = @getHeadPosition() @update(@getRange(), {tailed: false, reversed: false, range: Range(headPosition, headPosition)}) # Public: Plants the marker's tail at the current head position. After calling # the marker's tail position will be its head position at the time of the # call, regardless of where the marker's head is moved. plantTail: -> unless @hasTail() headPosition = @getHeadPosition() @update(@getRange(), {tailed: true, range: new Range(headPosition, headPosition)}) # Public: Returns a {Boolean} indicating whether the head precedes the tail. isReversed: -> @tailed and @reversed # Public: Returns a {Boolean} indicating whether the marker has a tail. hasTail: -> @tailed # Public: Is the marker valid? # # Returns a {Boolean}. isValid: -> not @isDestroyed() and @valid # Public: Is the marker destroyed? # # Returns a {Boolean}. isDestroyed: -> not @layer.hasMarker(@id) # Public: Returns a {Boolean} indicating whether changes that occur exactly at # the marker's head or tail cause it to move. isExclusive: -> if @exclusive? @exclusive else @getInvalidationStrategy() is 'inside' or not @hasTail() # Public: Returns a {Boolean} indicating whether this marker is equivalent to # another marker, meaning they have the same range and options. # # * `other` {Marker} other marker isEqual: (other) -> @invalidate is other.invalidate and @tailed is other.tailed and @reversed is other.reversed and @exclusive is other.exclusive and isEqual(@properties, other.properties) and @getRange().isEqual(other.getRange()) # Public: Get the invalidation strategy for this marker. # # Valid values include: `never`, `surround`, `overlap`, `inside`, and `touch`. # # Returns a {String}. getInvalidationStrategy: -> @invalidate # Public: Returns an {Object} containing any custom properties associated with # the marker. getProperties: -> @properties # Public: Merges an {Object} containing new properties into the marker's # existing properties. # # * `properties` {Object} setProperties: (properties) -> @update(@getRange(), properties: extend({}, @properties, properties)) # Public: Creates and returns a new {Marker} with the same properties as this # marker. # # * `params` {Object} copy: (options={}) -> snapshot = @getSnapshot() options = Marker.extractParams(options) @layer.createMarker(@getRange(), extend( {} snapshot, options, properties: extend({}, snapshot.properties, options.properties) )) # Public: Destroys the marker, causing it to emit the 'destroyed' event. destroy: (suppressMarkerLayerUpdateEvents) -> return if @isDestroyed() if @trackDestruction error = new Error Error.captureStackTrace(error) @destroyStackTrace = error.stack @layer.destroyMarker(this, suppressMarkerLayerUpdateEvents) @emitter.emit 'did-destroy' @emitter.clear() # Public: Compares this marker to another based on their ranges. # # * `other` {Marker} compare: (other) -> @layer.compareMarkers(@id, other.id) # Returns whether this marker matches the given parameters. The parameters # are the same as {MarkerLayer::findMarkers}. matchesParams: (params) -> for key in Object.keys(params) return false unless @matchesParam(key, params[key]) true # Returns whether this marker matches the given parameter name and value. # The parameters are the same as {MarkerLayer::findMarkers}. matchesParam: (key, value) -> switch key when 'startPosition' @getStartPosition().isEqual(value) when 'endPosition' @getEndPosition().isEqual(value) when 'containsPoint', 'containsPosition' @containsPoint(value) when 'containsRange' @containsRange(value) when 'startRow' @getStartPosition().row is value when 'endRow' @getEndPosition().row is value when 'intersectsRow' @intersectsRow(value) when 'invalidate', 'reversed', 'tailed' isEqual(@[key], value) when 'valid' @isValid() is value else isEqual(@properties[key], value) update: (oldRange, {range, reversed, tailed, valid, exclusive, properties}, textChanged=false, suppressMarkerLayerUpdateEvents=false) -> return if @isDestroyed() oldRange = Range.fromObject(oldRange) range = Range.fromObject(range) if range? wasExclusive = @isExclusive() updated = propertiesChanged = false if range? and not range.isEqual(oldRange) @layer.setMarkerRange(@id, range) updated = true if reversed? and reversed isnt @reversed @reversed = reversed updated = true if tailed? and tailed isnt @tailed @tailed = tailed updated = true if valid? and valid isnt @valid @valid = valid updated = true if exclusive? and exclusive isnt @exclusive @exclusive = exclusive updated = true if wasExclusive isnt @isExclusive() @layer.setMarkerIsExclusive(@id, @isExclusive()) updated = true if properties? and not isEqual(properties, @properties) @properties = Object.freeze(properties) propertiesChanged = true updated = true @emitChangeEvent(range ? oldRange, textChanged, propertiesChanged) @layer.markerUpdated() if updated and not suppressMarkerLayerUpdateEvents updated getSnapshot: (range, includeMarker=true) -> snapshot = {range, @properties, @reversed, @tailed, @valid, @invalidate, @exclusive} snapshot.marker = this if includeMarker Object.freeze(snapshot) toString: -> "[Marker #{@id}, #{@getRange()}]" ### Section: Private ### inspect: -> @toString() emitChangeEvent: (currentRange, textChanged, propertiesChanged) -> return unless @hasChangeObservers oldState = @previousEventState currentRange ?= @getRange() return false unless propertiesChanged or oldState.valid isnt @valid or oldState.tailed isnt @tailed or oldState.reversed isnt @reversed or oldState.range.compare(currentRange) isnt 0 newState = @previousEventState = @getSnapshot(currentRange) if oldState.reversed oldHeadPosition = oldState.range.start oldTailPosition = oldState.range.end else oldHeadPosition = oldState.range.end oldTailPosition = oldState.range.start if newState.reversed newHeadPosition = newState.range.start newTailPosition = newState.range.end else newHeadPosition = newState.range.end newTailPosition = newState.range.start @emitter.emit("did-change", { wasValid: oldState.valid, isValid: newState.valid hadTail: oldState.tailed, hasTail: newState.tailed oldProperties: oldState.properties, newProperties: newState.properties oldHeadPosition, newHeadPosition, oldTailPosition, newTailPosition textChanged }) true
[ { "context": "ponds with each roll and the total\n#\n# Author:\n# Spencer Wahl <spencer.s.wahl@gmail.com>\n\nmodule.exports = (rob", "end": 345, "score": 0.9998661875724792, "start": 333, "tag": "NAME", "value": "Spencer Wahl" }, { "context": " roll and the total\n#\n# Author:\n# ...
scripts/diceroller.coffee
muffin-crusaders/glitch
0
# Description # Lets hubot roll dice and flip coins # # Commands: # hubot flip a coin - Responds with heads or tails, chosen randomly # hubot roll a d<num> - Rolls a <num>-sided die and responds with result # hubot roll <num1>d<num2> - Rolls <num1> <num2>-sided dice and responds with each roll and the total # # Author: # Spencer Wahl <spencer.s.wahl@gmail.com> module.exports = (robot) -> coin_results = ['heads', 'tails'] robot.respond /flip a coin/i, (res) -> res.send "The coin landed on " + res.random coin_results robot.respond /roll a d(\d+)/i, (res) -> sides = parseInt(res.match[1], 10) if sides < 2 res.send "I don't think thats a thing." return result = Math.ceil(Math.random() * sides) res.send "I rolled a " + result robot.respond /roll (\d+)d(\d+)/i, (res) -> num_dice = parseInt(res.match[1], 10) sides = parseInt(res.match[2], 10) dice_rolled = 0 result = [] if sides < 2 res.send "I don't think thats a thing." else if num_dice < 1 res.send "That isn't possible." else if num_dice > 50 res.send "I don't have that many dice." else while (dice_rolled < num_dice) result.push(Math.ceil(Math.random() * sides)) dice_rolled = dice_rolled + 1 res.send report_dice result report_dice = (rolls) -> if rolls? total = 0 if rolls.length == 1 "I rolled a " + result[0] else for num in rolls total = total + num last_roll = rolls.pop() "I rolled " + rolls.join(", ") + ", and " + last_roll + ", which makes " + total + "."
96572
# Description # Lets hubot roll dice and flip coins # # Commands: # hubot flip a coin - Responds with heads or tails, chosen randomly # hubot roll a d<num> - Rolls a <num>-sided die and responds with result # hubot roll <num1>d<num2> - Rolls <num1> <num2>-sided dice and responds with each roll and the total # # Author: # <NAME> <<EMAIL>> module.exports = (robot) -> coin_results = ['heads', 'tails'] robot.respond /flip a coin/i, (res) -> res.send "The coin landed on " + res.random coin_results robot.respond /roll a d(\d+)/i, (res) -> sides = parseInt(res.match[1], 10) if sides < 2 res.send "I don't think thats a thing." return result = Math.ceil(Math.random() * sides) res.send "I rolled a " + result robot.respond /roll (\d+)d(\d+)/i, (res) -> num_dice = parseInt(res.match[1], 10) sides = parseInt(res.match[2], 10) dice_rolled = 0 result = [] if sides < 2 res.send "I don't think thats a thing." else if num_dice < 1 res.send "That isn't possible." else if num_dice > 50 res.send "I don't have that many dice." else while (dice_rolled < num_dice) result.push(Math.ceil(Math.random() * sides)) dice_rolled = dice_rolled + 1 res.send report_dice result report_dice = (rolls) -> if rolls? total = 0 if rolls.length == 1 "I rolled a " + result[0] else for num in rolls total = total + num last_roll = rolls.pop() "I rolled " + rolls.join(", ") + ", and " + last_roll + ", which makes " + total + "."
true
# Description # Lets hubot roll dice and flip coins # # Commands: # hubot flip a coin - Responds with heads or tails, chosen randomly # hubot roll a d<num> - Rolls a <num>-sided die and responds with result # hubot roll <num1>d<num2> - Rolls <num1> <num2>-sided dice and responds with each roll and the total # # Author: # PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> module.exports = (robot) -> coin_results = ['heads', 'tails'] robot.respond /flip a coin/i, (res) -> res.send "The coin landed on " + res.random coin_results robot.respond /roll a d(\d+)/i, (res) -> sides = parseInt(res.match[1], 10) if sides < 2 res.send "I don't think thats a thing." return result = Math.ceil(Math.random() * sides) res.send "I rolled a " + result robot.respond /roll (\d+)d(\d+)/i, (res) -> num_dice = parseInt(res.match[1], 10) sides = parseInt(res.match[2], 10) dice_rolled = 0 result = [] if sides < 2 res.send "I don't think thats a thing." else if num_dice < 1 res.send "That isn't possible." else if num_dice > 50 res.send "I don't have that many dice." else while (dice_rolled < num_dice) result.push(Math.ceil(Math.random() * sides)) dice_rolled = dice_rolled + 1 res.send report_dice result report_dice = (rolls) -> if rolls? total = 0 if rolls.length == 1 "I rolled a " + result[0] else for num in rolls total = total + num last_roll = rolls.pop() "I rolled " + rolls.join(", ") + ", and " + last_roll + ", which makes " + total + "."
[ { "context": " attendees: [\n email: 'test@provider.tld', details: status: 'NEEDS-ACTION'\n ", "end": 8001, "score": 0.9999276995658875, "start": 7984, "tag": "EMAIL", "value": "test@provider.tld" }, { "context": "-11-21T13:30:00.000Z'\n ...
test/vevent.coffee
RubenVerborgh/cozy-ical
0
should = require 'should' moment = require 'moment-timezone' time = require 'time' {RRule} = require 'rrule' {VEvent} = require '../src/index' {MissingFieldError, FieldConflictError} = require '../src/errors' DTSTAMP_FORMATTER = 'YYYYMMDD[T]HHmm[00Z]' describe "vEvent", -> describe "Validation", -> it "should throw an error if a mandatory property 'uid' is missing", -> options = stampDate: new Date 2014, 11, 4, 9, 30 startDate: new Date 2014, 11, 4, 9, 30 wrapper = -> event = new VEvent options wrapper.should.throw MissingFieldError it "should throw an error if a mandatory property 'stampDate' is missing", -> options = uid: 'abcd-1234' startDate: new Date 2014, 11, 4, 9, 30 wrapper = -> event = new VEvent options wrapper.should.throw MissingFieldError it "should throw an error if a mandatory property 'startDate' is missing", -> options = uid: 'abcd-1234' stampDate: new Date 2014, 11, 4, 9, 30 wrapper = -> event = new VEvent options wrapper.should.throw MissingFieldError it "should not throw an error if all mandatory properties are found", -> options = uid: 'abcd-1234' stampDate: new Date 2014, 11, 4, 9, 30 startDate: new Date 2014, 11, 4, 9, 30 wrapper = -> event = new VEvent options wrapper.should.not.throw() it "should throw an error if 'endDate' and 'duration' properties are both found", -> options = uid: 'abcd-1234' stampDate: new Date 2014, 11, 4, 9, 30 startDate: new Date 2014, 11, 4, 9, 30 endDate: new Date 2014, 11, 4, 10, 30 duration: 'PT15M' wrapper = -> event = new VEvent options wrapper.should.throw FieldConflictError describe "Creating a vEvent for punctual event without timezone", -> it "should render properly", -> options = uid: '[id-1]' stampDate: Date.UTC 2014, 11, 4, 9, 30 startDate: Date.UTC 2014, 11, 4, 9, 30 endDate: Date.UTC 2014, 11, 4, 10, 30 summary: 'Event summary' location: 'some place' created: '2014-11-10T14:00:00.000Z' lastModification: '2014-11-21T13:30:00.000Z' event = new VEvent options output = event.toString() output.should.equal """ BEGIN:VEVENT UID:#{options.uid} DTSTAMP:20141204T093000Z DTSTART:20141204T093000Z DTEND:20141204T103000Z CREATED:20141110T140000Z LAST-MODIFIED:20141121T133000Z LOCATION:#{options.location} SUMMARY:#{options.summary} END:VEVENT""".replace /\n/g, '\r\n' describe "Creating a vEvent for a punctual event with a timezone", -> it "should render properly", -> options = uid: '[id-1]' stampDate: Date.UTC 2014, 11, 4, 9, 30 startDate: Date.UTC 2014, 11, 4, 9, 30 endDate: Date.UTC 2014, 11, 4, 10, 30 summary: 'Event summary' timezone: 'Europe/Paris' event = new VEvent options output = event.toString() output.should.equal """ BEGIN:VEVENT UID:#{options.uid} DTSTAMP:20141204T093000Z DTSTART;TZID=Europe/Paris:20141204T103000 DTEND;TZID=Europe/Paris:20141204T113000 SUMMARY:#{options.summary} END:VEVENT""".replace /\n/g, '\r\n' describe "Creating a vEvent for all-day event", -> it "should render properly", -> options = uid: '[id-1]' stampDate: Date.UTC 2014, 11, 4 startDate: Date.UTC 2014, 11, 4 endDate: Date.UTC 2014, 11, 4 summary: 'Event summary' location: 'some place' allDay: true event = new VEvent options output = event.toString() output.should.equal """ BEGIN:VEVENT UID:#{options.uid} DTSTAMP:20141204T000000Z DTSTART;VALUE=DATE:20141204 DTEND;VALUE=DATE:20141204 LOCATION:#{options.location} SUMMARY:#{options.summary} END:VEVENT""".replace /\n/g, '\r\n' describe "Creating a vEvent for recurring event", -> it "should render properly", -> # defines recurrence rule ruleOptions = freq: RRule.WEEKLY interval: 2 until: new Date 2015, 1, 30 byweekday: [0, 4] options = uid: '[id-1]' stampDate: Date.UTC 2014, 11, 4 startDate: Date.UTC 2014, 11, 4 rrule: freq: ruleOptions.freq interval: ruleOptions.interval until: ruleOptions.until byweekday: ruleOptions.byweekday summary: 'Event summary' timezone: 'Europe/Paris' # `options.rrule` is not used because RRule changes it when # it proceses it (resulting in it not being able to be used afterwards) rrule = new RRule freq: ruleOptions.freq interval: ruleOptions.interval until: ruleOptions.until byweekday: ruleOptions.byweekday event = new VEvent options output = event.toString() output.should.equal """ BEGIN:VEVENT UID:#{options.uid} DTSTAMP:20141204T000000Z DTSTART;TZID=Europe/Paris:20141204T010000 RRULE:#{rrule} SUMMARY:#{options.summary} END:VEVENT""".replace /\n/g, '\r\n' describe "Creating a vEvent for recurring all-day event", -> it "should render properly", -> # defines recurrence rule ruleOptions = freq: RRule.YEARLY until: new Date 2015, 1, 30 options = uid: '[id-1]' stampDate: Date.UTC 2014, 11, 4 startDate: Date.UTC 2014, 11, 4 rrule: freq: ruleOptions.freq until: ruleOptions.until summary: 'Birthday event' timezone: 'Europe/Paris' allDay: true # `options.rrule` is not used because RRule changes it when # it proceses it (resulting in it not being able to be used afterwards) rrule = new RRule freq: ruleOptions.freq until: ruleOptions.until event = new VEvent options output = event.toString() output.should.equal """ BEGIN:VEVENT UID:#{options.uid} DTSTAMP:20141204T000000Z DTSTART;VALUE=DATE:20141204 RRULE:#{rrule} SUMMARY:#{options.summary} END:VEVENT""".replace /\n/g, '\r\n' describe "Creating a vEvent with attendees", -> it "should render properly", -> options = uid: '[id-1]' stampDate: Date.UTC 2014, 11, 4, 10, 0 startDate: Date.UTC 2014, 11, 4, 10, 0 endDate: Date.UTC 2014, 11, 4, 11, 0 summary: 'Event summary' location: 'some place' attendees: [ email: 'test@provider.tld', details: status: 'NEEDS-ACTION' ] event = new VEvent options output = event.toString() expectedEmail = options.attendees[0].email output.should.equal """ BEGIN:VEVENT UID:#{options.uid} DTSTAMP:20141204T100000Z DTSTART:20141204T100000Z DTEND:20141204T110000Z ATTENDEE;PARTSTAT=NEEDS-ACTION;CN=#{expectedEmail}:mailto:#{expectedEmail} LOCATION:#{options.location} SUMMARY:#{options.summary} END:VEVENT""".replace /\n/g, '\r\n' describe 'Timezone support for vEvents', -> it 'should support timezones, set on Date objects', -> startDate = new time.Date 2013, 5, 9, 15, 0, 0, 'Europe/Moscow' endDate = new time.Date 2013, 5, 10, 15, 0, 0, 'Europe/Moscow' vevent = new VEvent stampDate: Date.UTC 2013, 5, 9, 15 startDate: startDate endDate: endDate summary: "desc" location: "loc" uid: "3615" vevent.toString().should.equal """ BEGIN:VEVENT UID:3615 DTSTAMP:20130609T150000Z DTSTART;TZID=Europe/Moscow:20130609T150000 DTEND;TZID=Europe/Moscow:20130610T150000 LOCATION:loc SUMMARY:desc END:VEVENT""".replace /\n/g, '\r\n' it 'should support timezones, set via property', -> startDate = new time.Date 2013, 5, 9, 11, 0, 0, 'UTC' endDate = new time.Date 2013, 5, 10, 11, 0, 0, 'UTC' vevent = new VEvent stampDate: Date.UTC 2013, 5, 9, 15 startDate: startDate endDate: endDate summary: "desc" location: "loc" timezone: "Europe/Moscow" uid: "3615" vevent.toString().should.equal """ BEGIN:VEVENT UID:3615 DTSTAMP:20130609T150000Z DTSTART;TZID=Europe/Moscow:20130609T150000 DTEND;TZID=Europe/Moscow:20130610T150000 LOCATION:loc SUMMARY:desc END:VEVENT""".replace /\n/g, '\r\n' it 'should support whole day events with timezones', -> startDate = new time.Date 2013, 5, 9, 15, 0, 0 endDate = new time.Date 2013, 5, 10, 15, 0, 0 startDate.setTimezone 'Europe/Moscow' endDate.setTimezone 'Europe/Moscow' vevent = new VEvent stampDate: Date.UTC 2013, 5, 9, 15 startDate: startDate endDate: endDate summary: "desc" location: "loc" timezone: "Europe/Moscow" uid: "3615" allDay: true vevent.toString().should.equal """ BEGIN:VEVENT UID:3615 DTSTAMP:20130609T150000Z DTSTART;VALUE=DATE:20130609 DTEND;VALUE=DATE:20130610 LOCATION:loc SUMMARY:desc END:VEVENT""".replace /\n/g, '\r\n' describe "Creating a vEvent with multiline DESCRIPTION", -> it "should render properly", -> options = uid: '[id-1]' stampDate: Date.UTC 2014, 11, 4, 9, 30 startDate: Date.UTC 2014, 11, 4, 9, 30 endDate: Date.UTC 2014, 11, 4, 10, 30 summary: 'Event summary, should escape ";"' location: 'some place' description: 'Event description on, \n line 2,\n line 3.' created: '2014-11-10T14:00:00.000Z' lastModification: '2014-11-21T13:30:00.000Z' event = new VEvent options output = event.toString() output.should.equal """ BEGIN:VEVENT UID:#{options.uid} DTSTAMP:20141204T093000Z DTSTART:20141204T093000Z DTEND:20141204T103000Z CREATED:20141110T140000Z DESCRIPTION:Event description on\\, \\n line 2\\,\\n line 3. LAST-MODIFIED:20141121T133000Z LOCATION:#{options.location} SUMMARY:Event summary\\, should escape "\\;" END:VEVENT""".replace /\n/g, '\r\n' describe "Creating a vEvent with an ORGANIZER", -> it "should render properly with the simple form", -> options = uid: '[id-1]' stampDate: Date.UTC 2014, 11, 4, 9, 30 startDate: Date.UTC 2014, 11, 4, 9, 30 endDate: Date.UTC 2014, 11, 4, 10, 30 summary: 'Test' location: 'some place' created: '2014-11-10T14:00:00.000Z' lastModification: '2014-11-21T13:30:00.000Z' organizer: 'john.doe@test.com' event = new VEvent options output = event.toString() output.should.equal """ BEGIN:VEVENT UID:#{options.uid} DTSTAMP:20141204T093000Z DTSTART:20141204T093000Z DTEND:20141204T103000Z CREATED:20141110T140000Z LAST-MODIFIED:20141121T133000Z LOCATION:#{options.location} ORGANIZER:mailto:john.doe@test.com SUMMARY:Test END:VEVENT""".replace /\n/g, '\r\n' it "should render properly with the complex form", -> options = uid: '[id-1]' stampDate: Date.UTC 2014, 11, 4, 9, 30 startDate: Date.UTC 2014, 11, 4, 9, 30 endDate: Date.UTC 2014, 11, 4, 10, 30 summary: 'Test' location: 'some place' created: '2014-11-10T14:00:00.000Z' lastModification: '2014-11-21T13:30:00.000Z' organizer: displayName: 'John Doe', email: 'john.doe@test.com' event = new VEvent options output = event.toString() output.should.equal """ BEGIN:VEVENT UID:#{options.uid} DTSTAMP:20141204T093000Z DTSTART:20141204T093000Z DTEND:20141204T103000Z CREATED:20141110T140000Z LAST-MODIFIED:20141121T133000Z LOCATION:#{options.location} ORGANIZER;CN=John Doe:mailto:john.doe@test.com SUMMARY:Test END:VEVENT""".replace /\n/g, '\r\n'
164507
should = require 'should' moment = require 'moment-timezone' time = require 'time' {RRule} = require 'rrule' {VEvent} = require '../src/index' {MissingFieldError, FieldConflictError} = require '../src/errors' DTSTAMP_FORMATTER = 'YYYYMMDD[T]HHmm[00Z]' describe "vEvent", -> describe "Validation", -> it "should throw an error if a mandatory property 'uid' is missing", -> options = stampDate: new Date 2014, 11, 4, 9, 30 startDate: new Date 2014, 11, 4, 9, 30 wrapper = -> event = new VEvent options wrapper.should.throw MissingFieldError it "should throw an error if a mandatory property 'stampDate' is missing", -> options = uid: 'abcd-1234' startDate: new Date 2014, 11, 4, 9, 30 wrapper = -> event = new VEvent options wrapper.should.throw MissingFieldError it "should throw an error if a mandatory property 'startDate' is missing", -> options = uid: 'abcd-1234' stampDate: new Date 2014, 11, 4, 9, 30 wrapper = -> event = new VEvent options wrapper.should.throw MissingFieldError it "should not throw an error if all mandatory properties are found", -> options = uid: 'abcd-1234' stampDate: new Date 2014, 11, 4, 9, 30 startDate: new Date 2014, 11, 4, 9, 30 wrapper = -> event = new VEvent options wrapper.should.not.throw() it "should throw an error if 'endDate' and 'duration' properties are both found", -> options = uid: 'abcd-1234' stampDate: new Date 2014, 11, 4, 9, 30 startDate: new Date 2014, 11, 4, 9, 30 endDate: new Date 2014, 11, 4, 10, 30 duration: 'PT15M' wrapper = -> event = new VEvent options wrapper.should.throw FieldConflictError describe "Creating a vEvent for punctual event without timezone", -> it "should render properly", -> options = uid: '[id-1]' stampDate: Date.UTC 2014, 11, 4, 9, 30 startDate: Date.UTC 2014, 11, 4, 9, 30 endDate: Date.UTC 2014, 11, 4, 10, 30 summary: 'Event summary' location: 'some place' created: '2014-11-10T14:00:00.000Z' lastModification: '2014-11-21T13:30:00.000Z' event = new VEvent options output = event.toString() output.should.equal """ BEGIN:VEVENT UID:#{options.uid} DTSTAMP:20141204T093000Z DTSTART:20141204T093000Z DTEND:20141204T103000Z CREATED:20141110T140000Z LAST-MODIFIED:20141121T133000Z LOCATION:#{options.location} SUMMARY:#{options.summary} END:VEVENT""".replace /\n/g, '\r\n' describe "Creating a vEvent for a punctual event with a timezone", -> it "should render properly", -> options = uid: '[id-1]' stampDate: Date.UTC 2014, 11, 4, 9, 30 startDate: Date.UTC 2014, 11, 4, 9, 30 endDate: Date.UTC 2014, 11, 4, 10, 30 summary: 'Event summary' timezone: 'Europe/Paris' event = new VEvent options output = event.toString() output.should.equal """ BEGIN:VEVENT UID:#{options.uid} DTSTAMP:20141204T093000Z DTSTART;TZID=Europe/Paris:20141204T103000 DTEND;TZID=Europe/Paris:20141204T113000 SUMMARY:#{options.summary} END:VEVENT""".replace /\n/g, '\r\n' describe "Creating a vEvent for all-day event", -> it "should render properly", -> options = uid: '[id-1]' stampDate: Date.UTC 2014, 11, 4 startDate: Date.UTC 2014, 11, 4 endDate: Date.UTC 2014, 11, 4 summary: 'Event summary' location: 'some place' allDay: true event = new VEvent options output = event.toString() output.should.equal """ BEGIN:VEVENT UID:#{options.uid} DTSTAMP:20141204T000000Z DTSTART;VALUE=DATE:20141204 DTEND;VALUE=DATE:20141204 LOCATION:#{options.location} SUMMARY:#{options.summary} END:VEVENT""".replace /\n/g, '\r\n' describe "Creating a vEvent for recurring event", -> it "should render properly", -> # defines recurrence rule ruleOptions = freq: RRule.WEEKLY interval: 2 until: new Date 2015, 1, 30 byweekday: [0, 4] options = uid: '[id-1]' stampDate: Date.UTC 2014, 11, 4 startDate: Date.UTC 2014, 11, 4 rrule: freq: ruleOptions.freq interval: ruleOptions.interval until: ruleOptions.until byweekday: ruleOptions.byweekday summary: 'Event summary' timezone: 'Europe/Paris' # `options.rrule` is not used because RRule changes it when # it proceses it (resulting in it not being able to be used afterwards) rrule = new RRule freq: ruleOptions.freq interval: ruleOptions.interval until: ruleOptions.until byweekday: ruleOptions.byweekday event = new VEvent options output = event.toString() output.should.equal """ BEGIN:VEVENT UID:#{options.uid} DTSTAMP:20141204T000000Z DTSTART;TZID=Europe/Paris:20141204T010000 RRULE:#{rrule} SUMMARY:#{options.summary} END:VEVENT""".replace /\n/g, '\r\n' describe "Creating a vEvent for recurring all-day event", -> it "should render properly", -> # defines recurrence rule ruleOptions = freq: RRule.YEARLY until: new Date 2015, 1, 30 options = uid: '[id-1]' stampDate: Date.UTC 2014, 11, 4 startDate: Date.UTC 2014, 11, 4 rrule: freq: ruleOptions.freq until: ruleOptions.until summary: 'Birthday event' timezone: 'Europe/Paris' allDay: true # `options.rrule` is not used because RRule changes it when # it proceses it (resulting in it not being able to be used afterwards) rrule = new RRule freq: ruleOptions.freq until: ruleOptions.until event = new VEvent options output = event.toString() output.should.equal """ BEGIN:VEVENT UID:#{options.uid} DTSTAMP:20141204T000000Z DTSTART;VALUE=DATE:20141204 RRULE:#{rrule} SUMMARY:#{options.summary} END:VEVENT""".replace /\n/g, '\r\n' describe "Creating a vEvent with attendees", -> it "should render properly", -> options = uid: '[id-1]' stampDate: Date.UTC 2014, 11, 4, 10, 0 startDate: Date.UTC 2014, 11, 4, 10, 0 endDate: Date.UTC 2014, 11, 4, 11, 0 summary: 'Event summary' location: 'some place' attendees: [ email: '<EMAIL>', details: status: 'NEEDS-ACTION' ] event = new VEvent options output = event.toString() expectedEmail = options.attendees[0].email output.should.equal """ BEGIN:VEVENT UID:#{options.uid} DTSTAMP:20141204T100000Z DTSTART:20141204T100000Z DTEND:20141204T110000Z ATTENDEE;PARTSTAT=NEEDS-ACTION;CN=#{expectedEmail}:mailto:#{expectedEmail} LOCATION:#{options.location} SUMMARY:#{options.summary} END:VEVENT""".replace /\n/g, '\r\n' describe 'Timezone support for vEvents', -> it 'should support timezones, set on Date objects', -> startDate = new time.Date 2013, 5, 9, 15, 0, 0, 'Europe/Moscow' endDate = new time.Date 2013, 5, 10, 15, 0, 0, 'Europe/Moscow' vevent = new VEvent stampDate: Date.UTC 2013, 5, 9, 15 startDate: startDate endDate: endDate summary: "desc" location: "loc" uid: "3615" vevent.toString().should.equal """ BEGIN:VEVENT UID:3615 DTSTAMP:20130609T150000Z DTSTART;TZID=Europe/Moscow:20130609T150000 DTEND;TZID=Europe/Moscow:20130610T150000 LOCATION:loc SUMMARY:desc END:VEVENT""".replace /\n/g, '\r\n' it 'should support timezones, set via property', -> startDate = new time.Date 2013, 5, 9, 11, 0, 0, 'UTC' endDate = new time.Date 2013, 5, 10, 11, 0, 0, 'UTC' vevent = new VEvent stampDate: Date.UTC 2013, 5, 9, 15 startDate: startDate endDate: endDate summary: "desc" location: "loc" timezone: "Europe/Moscow" uid: "3615" vevent.toString().should.equal """ BEGIN:VEVENT UID:3615 DTSTAMP:20130609T150000Z DTSTART;TZID=Europe/Moscow:20130609T150000 DTEND;TZID=Europe/Moscow:20130610T150000 LOCATION:loc SUMMARY:desc END:VEVENT""".replace /\n/g, '\r\n' it 'should support whole day events with timezones', -> startDate = new time.Date 2013, 5, 9, 15, 0, 0 endDate = new time.Date 2013, 5, 10, 15, 0, 0 startDate.setTimezone 'Europe/Moscow' endDate.setTimezone 'Europe/Moscow' vevent = new VEvent stampDate: Date.UTC 2013, 5, 9, 15 startDate: startDate endDate: endDate summary: "desc" location: "loc" timezone: "Europe/Moscow" uid: "3615" allDay: true vevent.toString().should.equal """ BEGIN:VEVENT UID:3615 DTSTAMP:20130609T150000Z DTSTART;VALUE=DATE:20130609 DTEND;VALUE=DATE:20130610 LOCATION:loc SUMMARY:desc END:VEVENT""".replace /\n/g, '\r\n' describe "Creating a vEvent with multiline DESCRIPTION", -> it "should render properly", -> options = uid: '[id-1]' stampDate: Date.UTC 2014, 11, 4, 9, 30 startDate: Date.UTC 2014, 11, 4, 9, 30 endDate: Date.UTC 2014, 11, 4, 10, 30 summary: 'Event summary, should escape ";"' location: 'some place' description: 'Event description on, \n line 2,\n line 3.' created: '2014-11-10T14:00:00.000Z' lastModification: '2014-11-21T13:30:00.000Z' event = new VEvent options output = event.toString() output.should.equal """ BEGIN:VEVENT UID:#{options.uid} DTSTAMP:20141204T093000Z DTSTART:20141204T093000Z DTEND:20141204T103000Z CREATED:20141110T140000Z DESCRIPTION:Event description on\\, \\n line 2\\,\\n line 3. LAST-MODIFIED:20141121T133000Z LOCATION:#{options.location} SUMMARY:Event summary\\, should escape "\\;" END:VEVENT""".replace /\n/g, '\r\n' describe "Creating a vEvent with an ORGANIZER", -> it "should render properly with the simple form", -> options = uid: '[id-1]' stampDate: Date.UTC 2014, 11, 4, 9, 30 startDate: Date.UTC 2014, 11, 4, 9, 30 endDate: Date.UTC 2014, 11, 4, 10, 30 summary: 'Test' location: 'some place' created: '2014-11-10T14:00:00.000Z' lastModification: '2014-11-21T13:30:00.000Z' organizer: '<EMAIL>' event = new VEvent options output = event.toString() output.should.equal """ BEGIN:VEVENT UID:#{options.uid} DTSTAMP:20141204T093000Z DTSTART:20141204T093000Z DTEND:20141204T103000Z CREATED:20141110T140000Z LAST-MODIFIED:20141121T133000Z LOCATION:#{options.location} ORGANIZER:mailto:<EMAIL> SUMMARY:Test END:VEVENT""".replace /\n/g, '\r\n' it "should render properly with the complex form", -> options = uid: '[id-1]' stampDate: Date.UTC 2014, 11, 4, 9, 30 startDate: Date.UTC 2014, 11, 4, 9, 30 endDate: Date.UTC 2014, 11, 4, 10, 30 summary: 'Test' location: 'some place' created: '2014-11-10T14:00:00.000Z' lastModification: '2014-11-21T13:30:00.000Z' organizer: displayName: '<NAME>', email: '<EMAIL>' event = new VEvent options output = event.toString() output.should.equal """ BEGIN:VEVENT UID:#{options.uid} DTSTAMP:20141204T093000Z DTSTART:20141204T093000Z DTEND:20141204T103000Z CREATED:20141110T140000Z LAST-MODIFIED:20141121T133000Z LOCATION:#{options.location} ORGANIZER;CN=<NAME>:mailto:<EMAIL> SUMMARY:Test END:VEVENT""".replace /\n/g, '\r\n'
true
should = require 'should' moment = require 'moment-timezone' time = require 'time' {RRule} = require 'rrule' {VEvent} = require '../src/index' {MissingFieldError, FieldConflictError} = require '../src/errors' DTSTAMP_FORMATTER = 'YYYYMMDD[T]HHmm[00Z]' describe "vEvent", -> describe "Validation", -> it "should throw an error if a mandatory property 'uid' is missing", -> options = stampDate: new Date 2014, 11, 4, 9, 30 startDate: new Date 2014, 11, 4, 9, 30 wrapper = -> event = new VEvent options wrapper.should.throw MissingFieldError it "should throw an error if a mandatory property 'stampDate' is missing", -> options = uid: 'abcd-1234' startDate: new Date 2014, 11, 4, 9, 30 wrapper = -> event = new VEvent options wrapper.should.throw MissingFieldError it "should throw an error if a mandatory property 'startDate' is missing", -> options = uid: 'abcd-1234' stampDate: new Date 2014, 11, 4, 9, 30 wrapper = -> event = new VEvent options wrapper.should.throw MissingFieldError it "should not throw an error if all mandatory properties are found", -> options = uid: 'abcd-1234' stampDate: new Date 2014, 11, 4, 9, 30 startDate: new Date 2014, 11, 4, 9, 30 wrapper = -> event = new VEvent options wrapper.should.not.throw() it "should throw an error if 'endDate' and 'duration' properties are both found", -> options = uid: 'abcd-1234' stampDate: new Date 2014, 11, 4, 9, 30 startDate: new Date 2014, 11, 4, 9, 30 endDate: new Date 2014, 11, 4, 10, 30 duration: 'PT15M' wrapper = -> event = new VEvent options wrapper.should.throw FieldConflictError describe "Creating a vEvent for punctual event without timezone", -> it "should render properly", -> options = uid: '[id-1]' stampDate: Date.UTC 2014, 11, 4, 9, 30 startDate: Date.UTC 2014, 11, 4, 9, 30 endDate: Date.UTC 2014, 11, 4, 10, 30 summary: 'Event summary' location: 'some place' created: '2014-11-10T14:00:00.000Z' lastModification: '2014-11-21T13:30:00.000Z' event = new VEvent options output = event.toString() output.should.equal """ BEGIN:VEVENT UID:#{options.uid} DTSTAMP:20141204T093000Z DTSTART:20141204T093000Z DTEND:20141204T103000Z CREATED:20141110T140000Z LAST-MODIFIED:20141121T133000Z LOCATION:#{options.location} SUMMARY:#{options.summary} END:VEVENT""".replace /\n/g, '\r\n' describe "Creating a vEvent for a punctual event with a timezone", -> it "should render properly", -> options = uid: '[id-1]' stampDate: Date.UTC 2014, 11, 4, 9, 30 startDate: Date.UTC 2014, 11, 4, 9, 30 endDate: Date.UTC 2014, 11, 4, 10, 30 summary: 'Event summary' timezone: 'Europe/Paris' event = new VEvent options output = event.toString() output.should.equal """ BEGIN:VEVENT UID:#{options.uid} DTSTAMP:20141204T093000Z DTSTART;TZID=Europe/Paris:20141204T103000 DTEND;TZID=Europe/Paris:20141204T113000 SUMMARY:#{options.summary} END:VEVENT""".replace /\n/g, '\r\n' describe "Creating a vEvent for all-day event", -> it "should render properly", -> options = uid: '[id-1]' stampDate: Date.UTC 2014, 11, 4 startDate: Date.UTC 2014, 11, 4 endDate: Date.UTC 2014, 11, 4 summary: 'Event summary' location: 'some place' allDay: true event = new VEvent options output = event.toString() output.should.equal """ BEGIN:VEVENT UID:#{options.uid} DTSTAMP:20141204T000000Z DTSTART;VALUE=DATE:20141204 DTEND;VALUE=DATE:20141204 LOCATION:#{options.location} SUMMARY:#{options.summary} END:VEVENT""".replace /\n/g, '\r\n' describe "Creating a vEvent for recurring event", -> it "should render properly", -> # defines recurrence rule ruleOptions = freq: RRule.WEEKLY interval: 2 until: new Date 2015, 1, 30 byweekday: [0, 4] options = uid: '[id-1]' stampDate: Date.UTC 2014, 11, 4 startDate: Date.UTC 2014, 11, 4 rrule: freq: ruleOptions.freq interval: ruleOptions.interval until: ruleOptions.until byweekday: ruleOptions.byweekday summary: 'Event summary' timezone: 'Europe/Paris' # `options.rrule` is not used because RRule changes it when # it proceses it (resulting in it not being able to be used afterwards) rrule = new RRule freq: ruleOptions.freq interval: ruleOptions.interval until: ruleOptions.until byweekday: ruleOptions.byweekday event = new VEvent options output = event.toString() output.should.equal """ BEGIN:VEVENT UID:#{options.uid} DTSTAMP:20141204T000000Z DTSTART;TZID=Europe/Paris:20141204T010000 RRULE:#{rrule} SUMMARY:#{options.summary} END:VEVENT""".replace /\n/g, '\r\n' describe "Creating a vEvent for recurring all-day event", -> it "should render properly", -> # defines recurrence rule ruleOptions = freq: RRule.YEARLY until: new Date 2015, 1, 30 options = uid: '[id-1]' stampDate: Date.UTC 2014, 11, 4 startDate: Date.UTC 2014, 11, 4 rrule: freq: ruleOptions.freq until: ruleOptions.until summary: 'Birthday event' timezone: 'Europe/Paris' allDay: true # `options.rrule` is not used because RRule changes it when # it proceses it (resulting in it not being able to be used afterwards) rrule = new RRule freq: ruleOptions.freq until: ruleOptions.until event = new VEvent options output = event.toString() output.should.equal """ BEGIN:VEVENT UID:#{options.uid} DTSTAMP:20141204T000000Z DTSTART;VALUE=DATE:20141204 RRULE:#{rrule} SUMMARY:#{options.summary} END:VEVENT""".replace /\n/g, '\r\n' describe "Creating a vEvent with attendees", -> it "should render properly", -> options = uid: '[id-1]' stampDate: Date.UTC 2014, 11, 4, 10, 0 startDate: Date.UTC 2014, 11, 4, 10, 0 endDate: Date.UTC 2014, 11, 4, 11, 0 summary: 'Event summary' location: 'some place' attendees: [ email: 'PI:EMAIL:<EMAIL>END_PI', details: status: 'NEEDS-ACTION' ] event = new VEvent options output = event.toString() expectedEmail = options.attendees[0].email output.should.equal """ BEGIN:VEVENT UID:#{options.uid} DTSTAMP:20141204T100000Z DTSTART:20141204T100000Z DTEND:20141204T110000Z ATTENDEE;PARTSTAT=NEEDS-ACTION;CN=#{expectedEmail}:mailto:#{expectedEmail} LOCATION:#{options.location} SUMMARY:#{options.summary} END:VEVENT""".replace /\n/g, '\r\n' describe 'Timezone support for vEvents', -> it 'should support timezones, set on Date objects', -> startDate = new time.Date 2013, 5, 9, 15, 0, 0, 'Europe/Moscow' endDate = new time.Date 2013, 5, 10, 15, 0, 0, 'Europe/Moscow' vevent = new VEvent stampDate: Date.UTC 2013, 5, 9, 15 startDate: startDate endDate: endDate summary: "desc" location: "loc" uid: "3615" vevent.toString().should.equal """ BEGIN:VEVENT UID:3615 DTSTAMP:20130609T150000Z DTSTART;TZID=Europe/Moscow:20130609T150000 DTEND;TZID=Europe/Moscow:20130610T150000 LOCATION:loc SUMMARY:desc END:VEVENT""".replace /\n/g, '\r\n' it 'should support timezones, set via property', -> startDate = new time.Date 2013, 5, 9, 11, 0, 0, 'UTC' endDate = new time.Date 2013, 5, 10, 11, 0, 0, 'UTC' vevent = new VEvent stampDate: Date.UTC 2013, 5, 9, 15 startDate: startDate endDate: endDate summary: "desc" location: "loc" timezone: "Europe/Moscow" uid: "3615" vevent.toString().should.equal """ BEGIN:VEVENT UID:3615 DTSTAMP:20130609T150000Z DTSTART;TZID=Europe/Moscow:20130609T150000 DTEND;TZID=Europe/Moscow:20130610T150000 LOCATION:loc SUMMARY:desc END:VEVENT""".replace /\n/g, '\r\n' it 'should support whole day events with timezones', -> startDate = new time.Date 2013, 5, 9, 15, 0, 0 endDate = new time.Date 2013, 5, 10, 15, 0, 0 startDate.setTimezone 'Europe/Moscow' endDate.setTimezone 'Europe/Moscow' vevent = new VEvent stampDate: Date.UTC 2013, 5, 9, 15 startDate: startDate endDate: endDate summary: "desc" location: "loc" timezone: "Europe/Moscow" uid: "3615" allDay: true vevent.toString().should.equal """ BEGIN:VEVENT UID:3615 DTSTAMP:20130609T150000Z DTSTART;VALUE=DATE:20130609 DTEND;VALUE=DATE:20130610 LOCATION:loc SUMMARY:desc END:VEVENT""".replace /\n/g, '\r\n' describe "Creating a vEvent with multiline DESCRIPTION", -> it "should render properly", -> options = uid: '[id-1]' stampDate: Date.UTC 2014, 11, 4, 9, 30 startDate: Date.UTC 2014, 11, 4, 9, 30 endDate: Date.UTC 2014, 11, 4, 10, 30 summary: 'Event summary, should escape ";"' location: 'some place' description: 'Event description on, \n line 2,\n line 3.' created: '2014-11-10T14:00:00.000Z' lastModification: '2014-11-21T13:30:00.000Z' event = new VEvent options output = event.toString() output.should.equal """ BEGIN:VEVENT UID:#{options.uid} DTSTAMP:20141204T093000Z DTSTART:20141204T093000Z DTEND:20141204T103000Z CREATED:20141110T140000Z DESCRIPTION:Event description on\\, \\n line 2\\,\\n line 3. LAST-MODIFIED:20141121T133000Z LOCATION:#{options.location} SUMMARY:Event summary\\, should escape "\\;" END:VEVENT""".replace /\n/g, '\r\n' describe "Creating a vEvent with an ORGANIZER", -> it "should render properly with the simple form", -> options = uid: '[id-1]' stampDate: Date.UTC 2014, 11, 4, 9, 30 startDate: Date.UTC 2014, 11, 4, 9, 30 endDate: Date.UTC 2014, 11, 4, 10, 30 summary: 'Test' location: 'some place' created: '2014-11-10T14:00:00.000Z' lastModification: '2014-11-21T13:30:00.000Z' organizer: 'PI:EMAIL:<EMAIL>END_PI' event = new VEvent options output = event.toString() output.should.equal """ BEGIN:VEVENT UID:#{options.uid} DTSTAMP:20141204T093000Z DTSTART:20141204T093000Z DTEND:20141204T103000Z CREATED:20141110T140000Z LAST-MODIFIED:20141121T133000Z LOCATION:#{options.location} ORGANIZER:mailto:PI:EMAIL:<EMAIL>END_PI SUMMARY:Test END:VEVENT""".replace /\n/g, '\r\n' it "should render properly with the complex form", -> options = uid: '[id-1]' stampDate: Date.UTC 2014, 11, 4, 9, 30 startDate: Date.UTC 2014, 11, 4, 9, 30 endDate: Date.UTC 2014, 11, 4, 10, 30 summary: 'Test' location: 'some place' created: '2014-11-10T14:00:00.000Z' lastModification: '2014-11-21T13:30:00.000Z' organizer: displayName: 'PI:NAME:<NAME>END_PI', email: 'PI:EMAIL:<EMAIL>END_PI' event = new VEvent options output = event.toString() output.should.equal """ BEGIN:VEVENT UID:#{options.uid} DTSTAMP:20141204T093000Z DTSTART:20141204T093000Z DTEND:20141204T103000Z CREATED:20141110T140000Z LAST-MODIFIED:20141121T133000Z LOCATION:#{options.location} ORGANIZER;CN=PI:NAME:<NAME>END_PI:mailto:PI:EMAIL:<EMAIL>END_PI SUMMARY:Test END:VEVENT""".replace /\n/g, '\r\n'
[ { "context": "e when a specific event occurs.\"\n\n\t@modifierName:\"Guardian\"\n\t@description: null\n\n\tactiveInHand: false\n\tactiv", "end": 491, "score": 0.9785864949226379, "start": 483, "tag": "NAME", "value": "Guardian" } ]
app/sdk/modifiers/modifierOverwatch.coffee
willroberts/duelyst
5
EVENTS = require 'app/common/event_types' Modifier = require './modifier' ModifierOverwatchHidden = require './modifierOverwatchHidden' RevealHiddenCardAction = require 'app/sdk/actions/revealHiddenCardAction' DieAction = require 'app/sdk/actions/dieAction' class ModifierOverwatch extends Modifier type:"ModifierOverwatch" @type:"ModifierOverwatch" @isKeyworded: true @keywordDefinition:"A hidden effect which only takes place when a specific event occurs." @modifierName:"Guardian" @description: null activeInHand: false activeInDeck: false activeInSignatureCards: false activeOnBoard: true isRemovable: false maxStacks: 1 hideAsModifierType: ModifierOverwatchHidden.type fxResource: ["FX.Modifiers.ModifierOverwatch"] @createContextObject: (description,options) -> contextObject = super(options) contextObject.description = description return contextObject onEvent: (event) -> super(event) if @_private.listeningToEvents and @_private.cachedIsActive eventType = event.type if eventType == EVENTS.overwatch @onCheckForOverwatch(event) onCheckForOverwatch: (e) -> action = e.action if @getCanReactToAction(action) and @getIsActionRelevant(action) # setup for triggering @getGameSession().pushTriggeringModifierOntoStack(@) # reveal the overwatch card revealAction = new RevealHiddenCardAction(@getGameSession(), @getOwnerId(), @getRevealedCardData()) revealAction.setTarget(@getSourceCard()) @getGameSession().executeAction(revealAction) # trigger overwatch @onOverwatch(action) # remove self @getGameSession().removeModifier(@) # force stop buffering of events # the game session does this automatically # but we need it to happen directly following all the overwatch actions @getGameSession().executeAction(@getGameSession().actionStopBufferingEvents()) # stop triggering @getGameSession().popTriggeringModifierFromStack() getCanReactToAction: (action) -> # overwatch can only react on authoritative source on opponent's turn return @getGameSession().getIsRunningAsAuthoritative() and @getGameSession().getCurrentPlayerId() != @getOwnerId() and super(action) getIsActionRelevant: (action) -> # override me in sub classes to determine whether overwatch is triggered return false getRevealedCardData: ()-> sourceCard = @getSourceCard() return sourceCard && sourceCard.createCardData() onOverwatch: (action) -> # override me in sub classes to implement special behavior for when overwatch is triggered # if a minion has an overwatch buff and dies without triggering overwatch, then draw a card # onAction: (e) -> # super(e) # action = e.action # if action instanceof DieAction and action.getTarget() is @getCard() and @getCard().getIsRemoved() # deck = @getGameSession().getPlayerById(@getCard().getOwnerId()).getDeck() # if deck? # @getCard().getGameSession().executeAction(deck.actionDrawCard()) module.exports = ModifierOverwatch
195265
EVENTS = require 'app/common/event_types' Modifier = require './modifier' ModifierOverwatchHidden = require './modifierOverwatchHidden' RevealHiddenCardAction = require 'app/sdk/actions/revealHiddenCardAction' DieAction = require 'app/sdk/actions/dieAction' class ModifierOverwatch extends Modifier type:"ModifierOverwatch" @type:"ModifierOverwatch" @isKeyworded: true @keywordDefinition:"A hidden effect which only takes place when a specific event occurs." @modifierName:"<NAME>" @description: null activeInHand: false activeInDeck: false activeInSignatureCards: false activeOnBoard: true isRemovable: false maxStacks: 1 hideAsModifierType: ModifierOverwatchHidden.type fxResource: ["FX.Modifiers.ModifierOverwatch"] @createContextObject: (description,options) -> contextObject = super(options) contextObject.description = description return contextObject onEvent: (event) -> super(event) if @_private.listeningToEvents and @_private.cachedIsActive eventType = event.type if eventType == EVENTS.overwatch @onCheckForOverwatch(event) onCheckForOverwatch: (e) -> action = e.action if @getCanReactToAction(action) and @getIsActionRelevant(action) # setup for triggering @getGameSession().pushTriggeringModifierOntoStack(@) # reveal the overwatch card revealAction = new RevealHiddenCardAction(@getGameSession(), @getOwnerId(), @getRevealedCardData()) revealAction.setTarget(@getSourceCard()) @getGameSession().executeAction(revealAction) # trigger overwatch @onOverwatch(action) # remove self @getGameSession().removeModifier(@) # force stop buffering of events # the game session does this automatically # but we need it to happen directly following all the overwatch actions @getGameSession().executeAction(@getGameSession().actionStopBufferingEvents()) # stop triggering @getGameSession().popTriggeringModifierFromStack() getCanReactToAction: (action) -> # overwatch can only react on authoritative source on opponent's turn return @getGameSession().getIsRunningAsAuthoritative() and @getGameSession().getCurrentPlayerId() != @getOwnerId() and super(action) getIsActionRelevant: (action) -> # override me in sub classes to determine whether overwatch is triggered return false getRevealedCardData: ()-> sourceCard = @getSourceCard() return sourceCard && sourceCard.createCardData() onOverwatch: (action) -> # override me in sub classes to implement special behavior for when overwatch is triggered # if a minion has an overwatch buff and dies without triggering overwatch, then draw a card # onAction: (e) -> # super(e) # action = e.action # if action instanceof DieAction and action.getTarget() is @getCard() and @getCard().getIsRemoved() # deck = @getGameSession().getPlayerById(@getCard().getOwnerId()).getDeck() # if deck? # @getCard().getGameSession().executeAction(deck.actionDrawCard()) module.exports = ModifierOverwatch
true
EVENTS = require 'app/common/event_types' Modifier = require './modifier' ModifierOverwatchHidden = require './modifierOverwatchHidden' RevealHiddenCardAction = require 'app/sdk/actions/revealHiddenCardAction' DieAction = require 'app/sdk/actions/dieAction' class ModifierOverwatch extends Modifier type:"ModifierOverwatch" @type:"ModifierOverwatch" @isKeyworded: true @keywordDefinition:"A hidden effect which only takes place when a specific event occurs." @modifierName:"PI:NAME:<NAME>END_PI" @description: null activeInHand: false activeInDeck: false activeInSignatureCards: false activeOnBoard: true isRemovable: false maxStacks: 1 hideAsModifierType: ModifierOverwatchHidden.type fxResource: ["FX.Modifiers.ModifierOverwatch"] @createContextObject: (description,options) -> contextObject = super(options) contextObject.description = description return contextObject onEvent: (event) -> super(event) if @_private.listeningToEvents and @_private.cachedIsActive eventType = event.type if eventType == EVENTS.overwatch @onCheckForOverwatch(event) onCheckForOverwatch: (e) -> action = e.action if @getCanReactToAction(action) and @getIsActionRelevant(action) # setup for triggering @getGameSession().pushTriggeringModifierOntoStack(@) # reveal the overwatch card revealAction = new RevealHiddenCardAction(@getGameSession(), @getOwnerId(), @getRevealedCardData()) revealAction.setTarget(@getSourceCard()) @getGameSession().executeAction(revealAction) # trigger overwatch @onOverwatch(action) # remove self @getGameSession().removeModifier(@) # force stop buffering of events # the game session does this automatically # but we need it to happen directly following all the overwatch actions @getGameSession().executeAction(@getGameSession().actionStopBufferingEvents()) # stop triggering @getGameSession().popTriggeringModifierFromStack() getCanReactToAction: (action) -> # overwatch can only react on authoritative source on opponent's turn return @getGameSession().getIsRunningAsAuthoritative() and @getGameSession().getCurrentPlayerId() != @getOwnerId() and super(action) getIsActionRelevant: (action) -> # override me in sub classes to determine whether overwatch is triggered return false getRevealedCardData: ()-> sourceCard = @getSourceCard() return sourceCard && sourceCard.createCardData() onOverwatch: (action) -> # override me in sub classes to implement special behavior for when overwatch is triggered # if a minion has an overwatch buff and dies without triggering overwatch, then draw a card # onAction: (e) -> # super(e) # action = e.action # if action instanceof DieAction and action.getTarget() is @getCard() and @getCard().getIsRemoved() # deck = @getGameSession().getPlayerById(@getCard().getOwnerId()).getDeck() # if deck? # @getCard().getGameSession().executeAction(deck.actionDrawCard()) module.exports = ModifierOverwatch
[ { "context": "tAmqpConf() or {}\n @_responseRoutingKey = \"email_reply_saver_responses\"\n @_queriesRoutingKey = \"email_reply_saver", "end": 469, "score": 0.9952335357666016, "start": 442, "tag": "KEY", "value": "email_reply_saver_responses" }, { "context": "y_saver_re...
src/server/blip/email_reply_fetcher/amqp_saver.coffee
LaPingvino/rizzoma
88
_ = require('underscore') {Conf} = require('../../conf') {AmqpQueueListener} = require('../../common/amqp') {ParsedMail} = require('./parsed_mail') {EmailReplySaver} = require('./saver') class AmqpSaveWorker ### Слушает amqp очередь и сохраняет ответы блипов ### constructor: () -> @_logger = Conf.getLogger('amqp-email-reply-saver') connectOptions = Conf.getAmqpConf() or {} @_responseRoutingKey = "email_reply_saver_responses" @_queriesRoutingKey = "email_reply_saver_queries" listenerSettings = listenRoutingKey: @_queriesRoutingKey listenCallback: @_process listenQueueAutoDelete: false listenQueueAck: true _.extend(listenerSettings, connectOptions) @_amqp = new AmqpQueueListener(listenerSettings) run: () -> @_amqp.connect() _process: (rawMessage, headers, deliveryInfo, finish) => @_logger.info "Got save query for #{@_responseRoutingKey}_#{deliveryInfo.correlationId}" try rawMails = JSON.parse(rawMessage.data.toString()) catch e return @_sendResponse(correlationId, e, null) mails = [] for rawMail in rawMails mails.push(new ParsedMail(rawMail.from, rawMail.waveUrl, rawMail.blipId, rawMail.random, rawMail.text, rawMail.html, rawMail.headers)) saver = new EmailReplySaver() saver.save(mails, (err, res) => @_sendResponse(deliveryInfo.correlationId, err, res) @_logger.info("finished") finish?(null) ) _sendResponse: (correlationId, err, res) -> @_amqp.publish(@_responseRoutingKey, JSON.stringify({err: err, res: res}), { correlationId: correlationId }) class AmqpSaveManager ### Публикует в очередь запрос на сохранение блипов ответов и слушает очередь результатов сохранения ### constructor: () -> @_logger = Conf.getLogger('amqp-email-reply-saver') @_responseCallbacks = {} @RESPONSE_TIMEOUT = 20 connectOptions = Conf.getAmqpConf() or {} @_responseRoutingKey = "email_reply_saver_responses" @_queriesRoutingKey = "email_reply_saver_queries" listenerSettings = listenRoutingKey: @_responseRoutingKey listenCallback: @_processResponse listenQueueAutoDelete: true listenQueueAck: false _.extend(listenerSettings, connectOptions) @_amqp = new AmqpQueueListener(listenerSettings) @_amqp.connect((err) => if err @_logger.error(err) setTimeout(()-> process.exit(0) , 90 * 1000) ) _processResponse: (rawMessage, headers, deliveryInfo, finish) => @_logger.info "Got save result for #{@_responseRoutingKey}_#{deliveryInfo.correlationId}" respCallback = @_responseCallbacks[deliveryInfo.correlationId] if not respCallback @_logger.warn("Has no search callback for #{@_responseRoutingKey}_#{deliveryInfo.correlationId}") return delete @_responseCallbacks[deliveryInfo.correlationId] callback = respCallback.callback cancelTimeout = respCallback.cancelTimeout clearTimeout(cancelTimeout) try objMessage = JSON.parse rawMessage.data.toString() catch e return callback(e) callback(objMessage.err, objMessage.res) finish?(null) save: (mails, callback) -> ### Отправляет запрос по amqp на создание блипов ответа ### correlationId = Date.now() + '_' + Math.random().toString().slice(3, 8) cancelTimeout = setTimeout () => @_logger.error("Amqp save response timeout #{@_responseRoutingKey}_#{correlationId}") callback(new Error("Save response timeout"), null) , @RESPONSE_TIMEOUT * 1000 @_responseCallbacks[correlationId] = {callback: callback, cancelTimeout: cancelTimeout } @_amqp.publish(@_queriesRoutingKey, JSON.stringify(mails), { correlationId: correlationId }) module.exports = AmqpSaveWorker: AmqpSaveWorker AmqpSaveManager: AmqpSaveManager
39294
_ = require('underscore') {Conf} = require('../../conf') {AmqpQueueListener} = require('../../common/amqp') {ParsedMail} = require('./parsed_mail') {EmailReplySaver} = require('./saver') class AmqpSaveWorker ### Слушает amqp очередь и сохраняет ответы блипов ### constructor: () -> @_logger = Conf.getLogger('amqp-email-reply-saver') connectOptions = Conf.getAmqpConf() or {} @_responseRoutingKey = "<KEY>" @_queriesRoutingKey = "<KEY>" listenerSettings = listenRoutingKey: @_queriesRoutingKey listenCallback: @_process listenQueueAutoDelete: false listenQueueAck: true _.extend(listenerSettings, connectOptions) @_amqp = new AmqpQueueListener(listenerSettings) run: () -> @_amqp.connect() _process: (rawMessage, headers, deliveryInfo, finish) => @_logger.info "Got save query for #{@_responseRoutingKey}_#{deliveryInfo.correlationId}" try rawMails = JSON.parse(rawMessage.data.toString()) catch e return @_sendResponse(correlationId, e, null) mails = [] for rawMail in rawMails mails.push(new ParsedMail(rawMail.from, rawMail.waveUrl, rawMail.blipId, rawMail.random, rawMail.text, rawMail.html, rawMail.headers)) saver = new EmailReplySaver() saver.save(mails, (err, res) => @_sendResponse(deliveryInfo.correlationId, err, res) @_logger.info("finished") finish?(null) ) _sendResponse: (correlationId, err, res) -> @_amqp.publish(@_responseRoutingKey, JSON.stringify({err: err, res: res}), { correlationId: correlationId }) class AmqpSaveManager ### Публикует в очередь запрос на сохранение блипов ответов и слушает очередь результатов сохранения ### constructor: () -> @_logger = Conf.getLogger('amqp-email-reply-saver') @_responseCallbacks = {} @RESPONSE_TIMEOUT = 20 connectOptions = Conf.getAmqpConf() or {} @_responseRoutingKey = "<KEY>" @_queriesRoutingKey = "<KEY>" listenerSettings = listenRoutingKey: @_responseRoutingKey listenCallback: @_processResponse listenQueueAutoDelete: true listenQueueAck: false _.extend(listenerSettings, connectOptions) @_amqp = new AmqpQueueListener(listenerSettings) @_amqp.connect((err) => if err @_logger.error(err) setTimeout(()-> process.exit(0) , 90 * 1000) ) _processResponse: (rawMessage, headers, deliveryInfo, finish) => @_logger.info "Got save result for #{@_responseRoutingKey}_#{deliveryInfo.correlationId}" respCallback = @_responseCallbacks[deliveryInfo.correlationId] if not respCallback @_logger.warn("Has no search callback for #{@_responseRoutingKey}_#{deliveryInfo.correlationId}") return delete @_responseCallbacks[deliveryInfo.correlationId] callback = respCallback.callback cancelTimeout = respCallback.cancelTimeout clearTimeout(cancelTimeout) try objMessage = JSON.parse rawMessage.data.toString() catch e return callback(e) callback(objMessage.err, objMessage.res) finish?(null) save: (mails, callback) -> ### Отправляет запрос по amqp на создание блипов ответа ### correlationId = Date.now() + '_' + Math.random().toString().slice(3, 8) cancelTimeout = setTimeout () => @_logger.error("Amqp save response timeout #{@_responseRoutingKey}_#{correlationId}") callback(new Error("Save response timeout"), null) , @RESPONSE_TIMEOUT * 1000 @_responseCallbacks[correlationId] = {callback: callback, cancelTimeout: cancelTimeout } @_amqp.publish(@_queriesRoutingKey, JSON.stringify(mails), { correlationId: correlationId }) module.exports = AmqpSaveWorker: AmqpSaveWorker AmqpSaveManager: AmqpSaveManager
true
_ = require('underscore') {Conf} = require('../../conf') {AmqpQueueListener} = require('../../common/amqp') {ParsedMail} = require('./parsed_mail') {EmailReplySaver} = require('./saver') class AmqpSaveWorker ### Слушает amqp очередь и сохраняет ответы блипов ### constructor: () -> @_logger = Conf.getLogger('amqp-email-reply-saver') connectOptions = Conf.getAmqpConf() or {} @_responseRoutingKey = "PI:KEY:<KEY>END_PI" @_queriesRoutingKey = "PI:KEY:<KEY>END_PI" listenerSettings = listenRoutingKey: @_queriesRoutingKey listenCallback: @_process listenQueueAutoDelete: false listenQueueAck: true _.extend(listenerSettings, connectOptions) @_amqp = new AmqpQueueListener(listenerSettings) run: () -> @_amqp.connect() _process: (rawMessage, headers, deliveryInfo, finish) => @_logger.info "Got save query for #{@_responseRoutingKey}_#{deliveryInfo.correlationId}" try rawMails = JSON.parse(rawMessage.data.toString()) catch e return @_sendResponse(correlationId, e, null) mails = [] for rawMail in rawMails mails.push(new ParsedMail(rawMail.from, rawMail.waveUrl, rawMail.blipId, rawMail.random, rawMail.text, rawMail.html, rawMail.headers)) saver = new EmailReplySaver() saver.save(mails, (err, res) => @_sendResponse(deliveryInfo.correlationId, err, res) @_logger.info("finished") finish?(null) ) _sendResponse: (correlationId, err, res) -> @_amqp.publish(@_responseRoutingKey, JSON.stringify({err: err, res: res}), { correlationId: correlationId }) class AmqpSaveManager ### Публикует в очередь запрос на сохранение блипов ответов и слушает очередь результатов сохранения ### constructor: () -> @_logger = Conf.getLogger('amqp-email-reply-saver') @_responseCallbacks = {} @RESPONSE_TIMEOUT = 20 connectOptions = Conf.getAmqpConf() or {} @_responseRoutingKey = "PI:KEY:<KEY>END_PI" @_queriesRoutingKey = "PI:KEY:<KEY>END_PI" listenerSettings = listenRoutingKey: @_responseRoutingKey listenCallback: @_processResponse listenQueueAutoDelete: true listenQueueAck: false _.extend(listenerSettings, connectOptions) @_amqp = new AmqpQueueListener(listenerSettings) @_amqp.connect((err) => if err @_logger.error(err) setTimeout(()-> process.exit(0) , 90 * 1000) ) _processResponse: (rawMessage, headers, deliveryInfo, finish) => @_logger.info "Got save result for #{@_responseRoutingKey}_#{deliveryInfo.correlationId}" respCallback = @_responseCallbacks[deliveryInfo.correlationId] if not respCallback @_logger.warn("Has no search callback for #{@_responseRoutingKey}_#{deliveryInfo.correlationId}") return delete @_responseCallbacks[deliveryInfo.correlationId] callback = respCallback.callback cancelTimeout = respCallback.cancelTimeout clearTimeout(cancelTimeout) try objMessage = JSON.parse rawMessage.data.toString() catch e return callback(e) callback(objMessage.err, objMessage.res) finish?(null) save: (mails, callback) -> ### Отправляет запрос по amqp на создание блипов ответа ### correlationId = Date.now() + '_' + Math.random().toString().slice(3, 8) cancelTimeout = setTimeout () => @_logger.error("Amqp save response timeout #{@_responseRoutingKey}_#{correlationId}") callback(new Error("Save response timeout"), null) , @RESPONSE_TIMEOUT * 1000 @_responseCallbacks[correlationId] = {callback: callback, cancelTimeout: cancelTimeout } @_amqp.publish(@_queriesRoutingKey, JSON.stringify(mails), { correlationId: correlationId }) module.exports = AmqpSaveWorker: AmqpSaveWorker AmqpSaveManager: AmqpSaveManager
[ { "context": "db.save()\n\n Thread.callbacks.push\n name: 'Thread Watcher'\n cb: @node\n node: ->\n toggler", "end": 776, "score": 0.9638625979423523, "start": 770, "tag": "NAME", "value": "Thread" }, { "context": "e()\n\n Thread.callbacks.push\n name: 'Thr...
src/Monitoring/ThreadWatcher.coffee
ihavenoface/4chan-x
4
ThreadWatcher = init: -> return if !Conf['Thread Watcher'] @db = new DataBoard 'watchedThreads', @refresh, true @dialog = UI.dialog 'thread-watcher', 'top: 50px; left: 0px;', <%= importHTML('Monitoring/ThreadWatcher') %> @status = $ '#watcher-status', @dialog @list = @dialog.lastElementChild $.on d, 'QRPostSuccessful', @cb.post $.on d, '4chanXInitFinished', @ready switch g.VIEW when 'index' $.on d, 'IndexRefresh', @cb.onIndexRefresh when 'thread' $.on d, 'ThreadUpdate', @cb.onThreadRefresh now = Date.now() if (@db.data.lastChecked or 0) < now - 2 * $.HOUR @db.data.lastChecked = now ThreadWatcher.fetchAllStatus() @db.save() Thread.callbacks.push name: 'Thread Watcher' cb: @node node: -> toggler = $.el 'a', className: 'watcher-toggler' href: 'javascript:;' $.on toggler, 'click', ThreadWatcher.cb.toggle $.after $('input', @OP.nodes.post), [toggler, $.tn ' '] ready: -> $.off d, '4chanXInitFinished', ThreadWatcher.ready return unless Main.isThisPageLegit() ThreadWatcher.refresh() $.add d.body, ThreadWatcher.dialog return unless Conf['Auto Watch'] $.get 'AutoWatch', 0, ({AutoWatch}) -> return unless thread = g.BOARD.threads[AutoWatch] ThreadWatcher.add thread $.delete 'AutoWatch' cb: openAll: -> return if $.hasClass @, 'disabled' for a in $$ 'a[title]', ThreadWatcher.list $.open a.href $.event 'CloseMenu' checkThreads: -> return if $.hasClass @, 'disabled' ThreadWatcher.fetchAllStatus() pruneDeads: -> return if $.hasClass @, 'disabled' for {boardID, threadID, data} in ThreadWatcher.getAll() when data.isDead delete ThreadWatcher.db.data.boards[boardID][threadID] ThreadWatcher.db.deleteIfEmpty {boardID} ThreadWatcher.db.save() ThreadWatcher.refresh() $.event 'CloseMenu' toggle: -> ThreadWatcher.toggle Get.threadFromNode @ rm: -> [boardID, threadID] = @parentNode.dataset.fullID.split '.' ThreadWatcher.rm boardID, +threadID post: (e) -> {boardID, threadID, postID} = e.detail if postID is threadID if Conf['Auto Watch'] $.set 'AutoWatch', threadID else if Conf['Auto Watch Reply'] ThreadWatcher.add g.threads[boardID + '.' + threadID] onIndexRefresh: -> boardID = g.BOARD.ID for threadID, data of ThreadWatcher.db.data.boards[boardID] when not data.isDead and threadID not of g.BOARD.threads if Conf['Auto Prune'] ThreadWatcher.db.delete {boardID, threadID} else data.isDead = true ThreadWatcher.db.set {boardID, threadID, val: data} ThreadWatcher.refresh() onThreadRefresh: (e) -> thread = g.threads[e.detail.threadID] return unless e.detail[404] and ThreadWatcher.db.get {boardID: thread.board.ID, threadID: thread.ID} # Update 404 status. ThreadWatcher.add thread fetchCount: fetched: 0 fetching: 0 fetchAllStatus: -> return unless (threads = ThreadWatcher.getAll()).length ThreadWatcher.status.textContent = '...' for thread in threads ThreadWatcher.fetchStatus thread return fetchStatus: ({boardID, threadID, data}) -> return if data.isDead {fetchCount} = ThreadWatcher fetchCount.fetching++ $.ajax "//a.4cdn.org/#{boardID}/thread/#{threadID}.json", onloadend: -> fetchCount.fetched++ if fetchCount.fetched is fetchCount.fetching fetchCount.fetched = 0 fetchCount.fetching = 0 status = '' else status = "#{Math.round fetchCount.fetched / fetchCount.fetching * 100}%" ThreadWatcher.status.textContent = status return if @status isnt 404 if Conf['Auto Prune'] ThreadWatcher.db.delete {boardID, threadID} else data.isDead = true ThreadWatcher.db.set {boardID, threadID, val: data} ThreadWatcher.refresh() , type: 'head' getAll: -> all = [] for boardID, threads of ThreadWatcher.db.data.boards if Conf['Current Board'] and boardID isnt g.BOARD.ID continue for threadID, data of threads all.push {boardID, threadID, data} all makeLine: (boardID, threadID, data) -> x = $.el 'a', className: 'fa fa-times' href: 'javascript:;' $.on x, 'click', ThreadWatcher.cb.rm if data.isDead href = Redirect.to 'thread', {boardID, threadID} link = $.el 'a', href: href or "/#{boardID}/thread/#{threadID}" textContent: data.excerpt title: data.excerpt div = $.el 'div' fullID = "#{boardID}.#{threadID}" div.dataset.fullID = fullID $.addClass div, 'current' if g.VIEW is 'thread' and fullID is "#{g.BOARD}.#{g.THREADID}" $.addClass div, 'dead-thread' if data.isDead $.add div, [x, $.tn(' '), link] div refresh: -> nodes = [] for {boardID, threadID, data} in ThreadWatcher.getAll() nodes.push ThreadWatcher.makeLine boardID, threadID, data {list} = ThreadWatcher $.rmAll list $.add list, nodes for threadID, thread of g.BOARD.threads $.extend $('.watcher-toggler', thread.OP.nodes.post), if ThreadWatcher.db.get {boardID: thread.board.ID, threadID} className: 'watcher-toggler fa fa-bookmark' title: 'Unwatch thread' else className: 'watcher-toggler fa fa-bookmark-o' title: 'Watch thread' for refresher in ThreadWatcher.menu.refreshers refresher() return toggle: (thread) -> boardID = thread.board.ID threadID = thread.ID if ThreadWatcher.db.get {boardID, threadID} ThreadWatcher.rm boardID, threadID else ThreadWatcher.add thread add: (thread) -> data = {} boardID = thread.board.ID threadID = thread.ID if thread.isDead if Conf['Auto Prune'] and ThreadWatcher.db.get {boardID, threadID} ThreadWatcher.rm boardID, threadID return data.isDead = true data.excerpt = Get.threadExcerpt thread ThreadWatcher.db.set {boardID, threadID, val: data} ThreadWatcher.refresh() rm: (boardID, threadID) -> ThreadWatcher.db.delete {boardID, threadID} ThreadWatcher.refresh() convert: (oldFormat) -> newFormat = {} for boardID, threads of oldFormat for threadID, data of threads (newFormat[boardID] or= {})[threadID] = excerpt: data.textContent newFormat menu: refreshers: [] init: -> return if !Conf['Thread Watcher'] menu = new UI.Menu() $.on $('.menu-button', ThreadWatcher.dialog), 'click', (e) -> menu.toggle e, @, ThreadWatcher @addHeaderMenuEntry() @addMenuEntries menu addHeaderMenuEntry: -> return if g.VIEW isnt 'thread' entryEl = $.el 'a', href: 'javascript:;' Header.menu.addEntry el: entryEl order: 60 $.on entryEl, 'click', -> ThreadWatcher.toggle g.threads["#{g.BOARD}.#{g.THREADID}"] @refreshers.push -> [addClass, rmClass, text] = if $ '.current', ThreadWatcher.list ['unwatch-thread', 'watch-thread', 'Unwatch thread'] else ['watch-thread', 'unwatch-thread', 'Watch thread'] $.addClass entryEl, addClass $.rmClass entryEl, rmClass entryEl.textContent = text addMenuEntries: (menu) -> entries = [] # `Open all` entry entries.push cb: ThreadWatcher.cb.openAll entry: el: $.el 'a', textContent: 'Open all threads' refresh: -> (if ThreadWatcher.list.firstElementChild then $.rmClass else $.addClass) @el, 'disabled' # `Check 404'd threads` entry entries.push cb: ThreadWatcher.cb.checkThreads entry: el: $.el 'a', textContent: 'Check 404\'d threads' refresh: -> (if $('div:not(.dead-thread)', ThreadWatcher.list) then $.rmClass else $.addClass) @el, 'disabled' # `Prune 404'd threads` entry entries.push cb: ThreadWatcher.cb.pruneDeads entry: el: $.el 'a', textContent: 'Prune 404\'d threads' refresh: -> (if $('.dead-thread', ThreadWatcher.list) then $.rmClass else $.addClass) @el, 'disabled' # `Settings` entries: subEntries = [] for name, conf of Config.threadWatcher subEntries.push @createSubEntry name, conf[1] entries.push entry: el: $.el 'span', textContent: 'Settings' subEntries: subEntries for {entry, cb, refresh} in entries entry.el.href = 'javascript:;' if entry.el.nodeName is 'A' $.on entry.el, 'click', cb if cb @refreshers.push refresh.bind entry if refresh menu.addEntry entry return createSubEntry: (name, desc) -> entry = type: 'thread watcher' el: $.el 'label', innerHTML: "<input type=checkbox name='#{name}'> #{name}" title: desc input = entry.el.firstElementChild input.checked = Conf[name] $.on input, 'change', $.cb.checked $.on input, 'change', ThreadWatcher.refresh if name is 'Current Board' entry
132198
ThreadWatcher = init: -> return if !Conf['Thread Watcher'] @db = new DataBoard 'watchedThreads', @refresh, true @dialog = UI.dialog 'thread-watcher', 'top: 50px; left: 0px;', <%= importHTML('Monitoring/ThreadWatcher') %> @status = $ '#watcher-status', @dialog @list = @dialog.lastElementChild $.on d, 'QRPostSuccessful', @cb.post $.on d, '4chanXInitFinished', @ready switch g.VIEW when 'index' $.on d, 'IndexRefresh', @cb.onIndexRefresh when 'thread' $.on d, 'ThreadUpdate', @cb.onThreadRefresh now = Date.now() if (@db.data.lastChecked or 0) < now - 2 * $.HOUR @db.data.lastChecked = now ThreadWatcher.fetchAllStatus() @db.save() Thread.callbacks.push name: '<NAME> <NAME>' cb: @node node: -> toggler = $.el 'a', className: 'watcher-toggler' href: 'javascript:;' $.on toggler, 'click', ThreadWatcher.cb.toggle $.after $('input', @OP.nodes.post), [toggler, $.tn ' '] ready: -> $.off d, '4chanXInitFinished', ThreadWatcher.ready return unless Main.isThisPageLegit() ThreadWatcher.refresh() $.add d.body, ThreadWatcher.dialog return unless Conf['Auto Watch'] $.get 'AutoWatch', 0, ({AutoWatch}) -> return unless thread = g.BOARD.threads[AutoWatch] ThreadWatcher.add thread $.delete 'AutoWatch' cb: openAll: -> return if $.hasClass @, 'disabled' for a in $$ 'a[title]', ThreadWatcher.list $.open a.href $.event 'CloseMenu' checkThreads: -> return if $.hasClass @, 'disabled' ThreadWatcher.fetchAllStatus() pruneDeads: -> return if $.hasClass @, 'disabled' for {boardID, threadID, data} in ThreadWatcher.getAll() when data.isDead delete ThreadWatcher.db.data.boards[boardID][threadID] ThreadWatcher.db.deleteIfEmpty {boardID} ThreadWatcher.db.save() ThreadWatcher.refresh() $.event 'CloseMenu' toggle: -> ThreadWatcher.toggle Get.threadFromNode @ rm: -> [boardID, threadID] = @parentNode.dataset.fullID.split '.' ThreadWatcher.rm boardID, +threadID post: (e) -> {boardID, threadID, postID} = e.detail if postID is threadID if Conf['Auto Watch'] $.set 'AutoWatch', threadID else if Conf['Auto Watch Reply'] ThreadWatcher.add g.threads[boardID + '.' + threadID] onIndexRefresh: -> boardID = g.BOARD.ID for threadID, data of ThreadWatcher.db.data.boards[boardID] when not data.isDead and threadID not of g.BOARD.threads if Conf['Auto Prune'] ThreadWatcher.db.delete {boardID, threadID} else data.isDead = true ThreadWatcher.db.set {boardID, threadID, val: data} ThreadWatcher.refresh() onThreadRefresh: (e) -> thread = g.threads[e.detail.threadID] return unless e.detail[404] and ThreadWatcher.db.get {boardID: thread.board.ID, threadID: thread.ID} # Update 404 status. ThreadWatcher.add thread fetchCount: fetched: 0 fetching: 0 fetchAllStatus: -> return unless (threads = ThreadWatcher.getAll()).length ThreadWatcher.status.textContent = '...' for thread in threads ThreadWatcher.fetchStatus thread return fetchStatus: ({boardID, threadID, data}) -> return if data.isDead {fetchCount} = ThreadWatcher fetchCount.fetching++ $.ajax "//a.4cdn.org/#{boardID}/thread/#{threadID}.json", onloadend: -> fetchCount.fetched++ if fetchCount.fetched is fetchCount.fetching fetchCount.fetched = 0 fetchCount.fetching = 0 status = '' else status = "#{Math.round fetchCount.fetched / fetchCount.fetching * 100}%" ThreadWatcher.status.textContent = status return if @status isnt 404 if Conf['Auto Prune'] ThreadWatcher.db.delete {boardID, threadID} else data.isDead = true ThreadWatcher.db.set {boardID, threadID, val: data} ThreadWatcher.refresh() , type: 'head' getAll: -> all = [] for boardID, threads of ThreadWatcher.db.data.boards if Conf['Current Board'] and boardID isnt g.BOARD.ID continue for threadID, data of threads all.push {boardID, threadID, data} all makeLine: (boardID, threadID, data) -> x = $.el 'a', className: 'fa fa-times' href: 'javascript:;' $.on x, 'click', ThreadWatcher.cb.rm if data.isDead href = Redirect.to 'thread', {boardID, threadID} link = $.el 'a', href: href or "/#{boardID}/thread/#{threadID}" textContent: data.excerpt title: data.excerpt div = $.el 'div' fullID = "#{boardID}.#{threadID}" div.dataset.fullID = fullID $.addClass div, 'current' if g.VIEW is 'thread' and fullID is "#{g.BOARD}.#{g.THREADID}" $.addClass div, 'dead-thread' if data.isDead $.add div, [x, $.tn(' '), link] div refresh: -> nodes = [] for {boardID, threadID, data} in ThreadWatcher.getAll() nodes.push ThreadWatcher.makeLine boardID, threadID, data {list} = ThreadWatcher $.rmAll list $.add list, nodes for threadID, thread of g.BOARD.threads $.extend $('.watcher-toggler', thread.OP.nodes.post), if ThreadWatcher.db.get {boardID: thread.board.ID, threadID} className: 'watcher-toggler fa fa-bookmark' title: 'Unwatch thread' else className: 'watcher-toggler fa fa-bookmark-o' title: 'Watch thread' for refresher in ThreadWatcher.menu.refreshers refresher() return toggle: (thread) -> boardID = thread.board.ID threadID = thread.ID if ThreadWatcher.db.get {boardID, threadID} ThreadWatcher.rm boardID, threadID else ThreadWatcher.add thread add: (thread) -> data = {} boardID = thread.board.ID threadID = thread.ID if thread.isDead if Conf['Auto Prune'] and ThreadWatcher.db.get {boardID, threadID} ThreadWatcher.rm boardID, threadID return data.isDead = true data.excerpt = Get.threadExcerpt thread ThreadWatcher.db.set {boardID, threadID, val: data} ThreadWatcher.refresh() rm: (boardID, threadID) -> ThreadWatcher.db.delete {boardID, threadID} ThreadWatcher.refresh() convert: (oldFormat) -> newFormat = {} for boardID, threads of oldFormat for threadID, data of threads (newFormat[boardID] or= {})[threadID] = excerpt: data.textContent newFormat menu: refreshers: [] init: -> return if !Conf['Thread Watcher'] menu = new UI.Menu() $.on $('.menu-button', ThreadWatcher.dialog), 'click', (e) -> menu.toggle e, @, ThreadWatcher @addHeaderMenuEntry() @addMenuEntries menu addHeaderMenuEntry: -> return if g.VIEW isnt 'thread' entryEl = $.el 'a', href: 'javascript:;' Header.menu.addEntry el: entryEl order: 60 $.on entryEl, 'click', -> ThreadWatcher.toggle g.threads["#{g.BOARD}.#{g.THREADID}"] @refreshers.push -> [addClass, rmClass, text] = if $ '.current', ThreadWatcher.list ['unwatch-thread', 'watch-thread', 'Unwatch thread'] else ['watch-thread', 'unwatch-thread', 'Watch thread'] $.addClass entryEl, addClass $.rmClass entryEl, rmClass entryEl.textContent = text addMenuEntries: (menu) -> entries = [] # `Open all` entry entries.push cb: ThreadWatcher.cb.openAll entry: el: $.el 'a', textContent: 'Open all threads' refresh: -> (if ThreadWatcher.list.firstElementChild then $.rmClass else $.addClass) @el, 'disabled' # `Check 404'd threads` entry entries.push cb: ThreadWatcher.cb.checkThreads entry: el: $.el 'a', textContent: 'Check 404\'d threads' refresh: -> (if $('div:not(.dead-thread)', ThreadWatcher.list) then $.rmClass else $.addClass) @el, 'disabled' # `Prune 404'd threads` entry entries.push cb: ThreadWatcher.cb.pruneDeads entry: el: $.el 'a', textContent: 'Prune 404\'d threads' refresh: -> (if $('.dead-thread', ThreadWatcher.list) then $.rmClass else $.addClass) @el, 'disabled' # `Settings` entries: subEntries = [] for name, conf of Config.threadWatcher subEntries.push @createSubEntry name, conf[1] entries.push entry: el: $.el 'span', textContent: 'Settings' subEntries: subEntries for {entry, cb, refresh} in entries entry.el.href = 'javascript:;' if entry.el.nodeName is 'A' $.on entry.el, 'click', cb if cb @refreshers.push refresh.bind entry if refresh menu.addEntry entry return createSubEntry: (name, desc) -> entry = type: 'thread watcher' el: $.el 'label', innerHTML: "<input type=checkbox name='#{name}'> #{name}" title: desc input = entry.el.firstElementChild input.checked = Conf[name] $.on input, 'change', $.cb.checked $.on input, 'change', ThreadWatcher.refresh if name is 'Current Board' entry
true
ThreadWatcher = init: -> return if !Conf['Thread Watcher'] @db = new DataBoard 'watchedThreads', @refresh, true @dialog = UI.dialog 'thread-watcher', 'top: 50px; left: 0px;', <%= importHTML('Monitoring/ThreadWatcher') %> @status = $ '#watcher-status', @dialog @list = @dialog.lastElementChild $.on d, 'QRPostSuccessful', @cb.post $.on d, '4chanXInitFinished', @ready switch g.VIEW when 'index' $.on d, 'IndexRefresh', @cb.onIndexRefresh when 'thread' $.on d, 'ThreadUpdate', @cb.onThreadRefresh now = Date.now() if (@db.data.lastChecked or 0) < now - 2 * $.HOUR @db.data.lastChecked = now ThreadWatcher.fetchAllStatus() @db.save() Thread.callbacks.push name: 'PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI' cb: @node node: -> toggler = $.el 'a', className: 'watcher-toggler' href: 'javascript:;' $.on toggler, 'click', ThreadWatcher.cb.toggle $.after $('input', @OP.nodes.post), [toggler, $.tn ' '] ready: -> $.off d, '4chanXInitFinished', ThreadWatcher.ready return unless Main.isThisPageLegit() ThreadWatcher.refresh() $.add d.body, ThreadWatcher.dialog return unless Conf['Auto Watch'] $.get 'AutoWatch', 0, ({AutoWatch}) -> return unless thread = g.BOARD.threads[AutoWatch] ThreadWatcher.add thread $.delete 'AutoWatch' cb: openAll: -> return if $.hasClass @, 'disabled' for a in $$ 'a[title]', ThreadWatcher.list $.open a.href $.event 'CloseMenu' checkThreads: -> return if $.hasClass @, 'disabled' ThreadWatcher.fetchAllStatus() pruneDeads: -> return if $.hasClass @, 'disabled' for {boardID, threadID, data} in ThreadWatcher.getAll() when data.isDead delete ThreadWatcher.db.data.boards[boardID][threadID] ThreadWatcher.db.deleteIfEmpty {boardID} ThreadWatcher.db.save() ThreadWatcher.refresh() $.event 'CloseMenu' toggle: -> ThreadWatcher.toggle Get.threadFromNode @ rm: -> [boardID, threadID] = @parentNode.dataset.fullID.split '.' ThreadWatcher.rm boardID, +threadID post: (e) -> {boardID, threadID, postID} = e.detail if postID is threadID if Conf['Auto Watch'] $.set 'AutoWatch', threadID else if Conf['Auto Watch Reply'] ThreadWatcher.add g.threads[boardID + '.' + threadID] onIndexRefresh: -> boardID = g.BOARD.ID for threadID, data of ThreadWatcher.db.data.boards[boardID] when not data.isDead and threadID not of g.BOARD.threads if Conf['Auto Prune'] ThreadWatcher.db.delete {boardID, threadID} else data.isDead = true ThreadWatcher.db.set {boardID, threadID, val: data} ThreadWatcher.refresh() onThreadRefresh: (e) -> thread = g.threads[e.detail.threadID] return unless e.detail[404] and ThreadWatcher.db.get {boardID: thread.board.ID, threadID: thread.ID} # Update 404 status. ThreadWatcher.add thread fetchCount: fetched: 0 fetching: 0 fetchAllStatus: -> return unless (threads = ThreadWatcher.getAll()).length ThreadWatcher.status.textContent = '...' for thread in threads ThreadWatcher.fetchStatus thread return fetchStatus: ({boardID, threadID, data}) -> return if data.isDead {fetchCount} = ThreadWatcher fetchCount.fetching++ $.ajax "//a.4cdn.org/#{boardID}/thread/#{threadID}.json", onloadend: -> fetchCount.fetched++ if fetchCount.fetched is fetchCount.fetching fetchCount.fetched = 0 fetchCount.fetching = 0 status = '' else status = "#{Math.round fetchCount.fetched / fetchCount.fetching * 100}%" ThreadWatcher.status.textContent = status return if @status isnt 404 if Conf['Auto Prune'] ThreadWatcher.db.delete {boardID, threadID} else data.isDead = true ThreadWatcher.db.set {boardID, threadID, val: data} ThreadWatcher.refresh() , type: 'head' getAll: -> all = [] for boardID, threads of ThreadWatcher.db.data.boards if Conf['Current Board'] and boardID isnt g.BOARD.ID continue for threadID, data of threads all.push {boardID, threadID, data} all makeLine: (boardID, threadID, data) -> x = $.el 'a', className: 'fa fa-times' href: 'javascript:;' $.on x, 'click', ThreadWatcher.cb.rm if data.isDead href = Redirect.to 'thread', {boardID, threadID} link = $.el 'a', href: href or "/#{boardID}/thread/#{threadID}" textContent: data.excerpt title: data.excerpt div = $.el 'div' fullID = "#{boardID}.#{threadID}" div.dataset.fullID = fullID $.addClass div, 'current' if g.VIEW is 'thread' and fullID is "#{g.BOARD}.#{g.THREADID}" $.addClass div, 'dead-thread' if data.isDead $.add div, [x, $.tn(' '), link] div refresh: -> nodes = [] for {boardID, threadID, data} in ThreadWatcher.getAll() nodes.push ThreadWatcher.makeLine boardID, threadID, data {list} = ThreadWatcher $.rmAll list $.add list, nodes for threadID, thread of g.BOARD.threads $.extend $('.watcher-toggler', thread.OP.nodes.post), if ThreadWatcher.db.get {boardID: thread.board.ID, threadID} className: 'watcher-toggler fa fa-bookmark' title: 'Unwatch thread' else className: 'watcher-toggler fa fa-bookmark-o' title: 'Watch thread' for refresher in ThreadWatcher.menu.refreshers refresher() return toggle: (thread) -> boardID = thread.board.ID threadID = thread.ID if ThreadWatcher.db.get {boardID, threadID} ThreadWatcher.rm boardID, threadID else ThreadWatcher.add thread add: (thread) -> data = {} boardID = thread.board.ID threadID = thread.ID if thread.isDead if Conf['Auto Prune'] and ThreadWatcher.db.get {boardID, threadID} ThreadWatcher.rm boardID, threadID return data.isDead = true data.excerpt = Get.threadExcerpt thread ThreadWatcher.db.set {boardID, threadID, val: data} ThreadWatcher.refresh() rm: (boardID, threadID) -> ThreadWatcher.db.delete {boardID, threadID} ThreadWatcher.refresh() convert: (oldFormat) -> newFormat = {} for boardID, threads of oldFormat for threadID, data of threads (newFormat[boardID] or= {})[threadID] = excerpt: data.textContent newFormat menu: refreshers: [] init: -> return if !Conf['Thread Watcher'] menu = new UI.Menu() $.on $('.menu-button', ThreadWatcher.dialog), 'click', (e) -> menu.toggle e, @, ThreadWatcher @addHeaderMenuEntry() @addMenuEntries menu addHeaderMenuEntry: -> return if g.VIEW isnt 'thread' entryEl = $.el 'a', href: 'javascript:;' Header.menu.addEntry el: entryEl order: 60 $.on entryEl, 'click', -> ThreadWatcher.toggle g.threads["#{g.BOARD}.#{g.THREADID}"] @refreshers.push -> [addClass, rmClass, text] = if $ '.current', ThreadWatcher.list ['unwatch-thread', 'watch-thread', 'Unwatch thread'] else ['watch-thread', 'unwatch-thread', 'Watch thread'] $.addClass entryEl, addClass $.rmClass entryEl, rmClass entryEl.textContent = text addMenuEntries: (menu) -> entries = [] # `Open all` entry entries.push cb: ThreadWatcher.cb.openAll entry: el: $.el 'a', textContent: 'Open all threads' refresh: -> (if ThreadWatcher.list.firstElementChild then $.rmClass else $.addClass) @el, 'disabled' # `Check 404'd threads` entry entries.push cb: ThreadWatcher.cb.checkThreads entry: el: $.el 'a', textContent: 'Check 404\'d threads' refresh: -> (if $('div:not(.dead-thread)', ThreadWatcher.list) then $.rmClass else $.addClass) @el, 'disabled' # `Prune 404'd threads` entry entries.push cb: ThreadWatcher.cb.pruneDeads entry: el: $.el 'a', textContent: 'Prune 404\'d threads' refresh: -> (if $('.dead-thread', ThreadWatcher.list) then $.rmClass else $.addClass) @el, 'disabled' # `Settings` entries: subEntries = [] for name, conf of Config.threadWatcher subEntries.push @createSubEntry name, conf[1] entries.push entry: el: $.el 'span', textContent: 'Settings' subEntries: subEntries for {entry, cb, refresh} in entries entry.el.href = 'javascript:;' if entry.el.nodeName is 'A' $.on entry.el, 'click', cb if cb @refreshers.push refresh.bind entry if refresh menu.addEntry entry return createSubEntry: (name, desc) -> entry = type: 'thread watcher' el: $.el 'label', innerHTML: "<input type=checkbox name='#{name}'> #{name}" title: desc input = entry.el.firstElementChild input.checked = Conf[name] $.on input, 'change', $.cb.checked $.on input, 'change', ThreadWatcher.refresh if name is 'Current Board' entry
[ { "context": " to the common prefix of \"cpb-aacip-\". Supposedly, Michael Potts\n # from Sony Ci said that quoted search queries ", "end": 4052, "score": 0.9984955787658691, "start": 4039, "tag": "NAME", "value": "Michael Potts" } ]
app/assets/javascripts/sony_ci/find_media.coffee
WGBH-MLA/ams
3
class FindSonyCiMediaBehavior # Select for the search button searchButtonSelector: '#find_sony_ci_media #search' # Selector for the div that displays the feedback messages. feedbackSelector: '#find_sony_ci_media #feedback' # Selector for the text inputs that have the Sony Ci IDs. sonyCiIdInputSelector: 'input.asset_sonyci_id' # Selector for the button to add new Sony Ci IDs addNewSonyCiIdButtonSelector: '.form-group.asset_sonyci_id button.add' constructor: (@query) -> # searchHandler - search Sony Ci for records matching the query and provide # feedback to the user. searchHandler: (event) => event.preventDefault() @giveFeedback('searching...') $.ajax( context: this, url: "/sony_ci/api/find_media", data: { query: @query } ).done ( response ) -> @giveFeedback(response.length + ' records found') if response.length > 0 @addFoundRecords(response) # fetchFilenameHandler - fetches the filename from Sony Ci given a Sony Ci ID # from an input field. fetchFilenameHandler: -> $.ajax( url: "/sony_ci/api/get_filename", context: this, data: { sony_ci_id: $(this).val() } ).done(( response ) -> $(this).parent().find('.sony_ci_filename').text(response['name']) ).fail(( response ) -> $(this).parent().find('.sony_ci_filename').text("Could not find Sony Ci record") ) # Adds a message to give the user feedback on what's happening. # The element is hidden at first, so set the text and reveal it. giveFeedback: (msg) => $(@feedbackSelector).text(msg).show() addFoundRecords: (records) => # Map the sonyci_id text inputs to their values. existingSonyCiIds = $(@sonyCiIdInputSelector).map (_, element) -> $(element).val() # Map the found records to just the Sony Ci IDs. # This is not a jQuery.map function, so the index is the 2nd arg instead of # the first, like in the map function above. foundSonyCiIds = records.map (record, _) -> record['id'] # Subtract the existing Sony Ci Ids from the found Sony Ci IDs. newSonyCiIds = $(foundSonyCiIds).not(existingSonyCiIds).get(); # For each of the new found Sony Ci IDs... newSonyCiIds.forEach (sonyCiId, index) => # Insert the found Sony Ci ID into the last text input and trigger the \ # change() event, because just setting val(x) won't do it. $(@sonyCiIdInputSelector).last().val(sonyCiId).change() # If we have more Sony Ci IDs to add if newSonyCiIds.length > index # Add another Sony Ci ID field it by clicking the "Add another..." # button. $(@addNewSonyCiIdButtonSelector).click() # Hyrax will simply copy and append the last element, but we don't want # values for Sony Ci ID or Filename there, so clear them out. $(@sonyCiIdInputSelector).last().val('') $('.sony_ci_filename').last().text('') # Finally, add the handler to the change() event of the input. $(@sonyCiIdInputSelector).last().change @fetchFilenameHandler # apply - Attaches handlers to events. apply: -> # Attach the search handler to the click event of the search button. $(@searchButtonSelector).click @searchHandler # Attach the fetchFilenameHanlder to the change event of the inputs. $(@sonyCiIdInputSelector).change @fetchFilenameHandler # When the page loads... # NOTE: could not get $(document).on('turbolinks:load') to work on initial page # load; reverting to $(document).ready, which seems to work more consistently. $(document).ready -> # This regex matches the 3rd URL segment which should be the GUID. guid_query_str = window.location.href.match(/concern\/assets\/(.*)\//)[1] # Create the behavior object, passing in the GUID as the query string. # NOTE: Sony Ci API has a 20 character limit on it's search terms, so let's # just pass in the last 20 characters, which will be more unique than the 1st # 20 chars due to the common prefix of "cpb-aacip-". Supposedly, Michael Potts # from Sony Ci said that quoted search queries have no such limit, but I could # not get that to work, nor is it mentioned in the Ci API docs anywhere. behavior = new FindSonyCiMediaBehavior(guid_query_str.substr(-20)) # apply the behavior behavior.apply()
22172
class FindSonyCiMediaBehavior # Select for the search button searchButtonSelector: '#find_sony_ci_media #search' # Selector for the div that displays the feedback messages. feedbackSelector: '#find_sony_ci_media #feedback' # Selector for the text inputs that have the Sony Ci IDs. sonyCiIdInputSelector: 'input.asset_sonyci_id' # Selector for the button to add new Sony Ci IDs addNewSonyCiIdButtonSelector: '.form-group.asset_sonyci_id button.add' constructor: (@query) -> # searchHandler - search Sony Ci for records matching the query and provide # feedback to the user. searchHandler: (event) => event.preventDefault() @giveFeedback('searching...') $.ajax( context: this, url: "/sony_ci/api/find_media", data: { query: @query } ).done ( response ) -> @giveFeedback(response.length + ' records found') if response.length > 0 @addFoundRecords(response) # fetchFilenameHandler - fetches the filename from Sony Ci given a Sony Ci ID # from an input field. fetchFilenameHandler: -> $.ajax( url: "/sony_ci/api/get_filename", context: this, data: { sony_ci_id: $(this).val() } ).done(( response ) -> $(this).parent().find('.sony_ci_filename').text(response['name']) ).fail(( response ) -> $(this).parent().find('.sony_ci_filename').text("Could not find Sony Ci record") ) # Adds a message to give the user feedback on what's happening. # The element is hidden at first, so set the text and reveal it. giveFeedback: (msg) => $(@feedbackSelector).text(msg).show() addFoundRecords: (records) => # Map the sonyci_id text inputs to their values. existingSonyCiIds = $(@sonyCiIdInputSelector).map (_, element) -> $(element).val() # Map the found records to just the Sony Ci IDs. # This is not a jQuery.map function, so the index is the 2nd arg instead of # the first, like in the map function above. foundSonyCiIds = records.map (record, _) -> record['id'] # Subtract the existing Sony Ci Ids from the found Sony Ci IDs. newSonyCiIds = $(foundSonyCiIds).not(existingSonyCiIds).get(); # For each of the new found Sony Ci IDs... newSonyCiIds.forEach (sonyCiId, index) => # Insert the found Sony Ci ID into the last text input and trigger the \ # change() event, because just setting val(x) won't do it. $(@sonyCiIdInputSelector).last().val(sonyCiId).change() # If we have more Sony Ci IDs to add if newSonyCiIds.length > index # Add another Sony Ci ID field it by clicking the "Add another..." # button. $(@addNewSonyCiIdButtonSelector).click() # Hyrax will simply copy and append the last element, but we don't want # values for Sony Ci ID or Filename there, so clear them out. $(@sonyCiIdInputSelector).last().val('') $('.sony_ci_filename').last().text('') # Finally, add the handler to the change() event of the input. $(@sonyCiIdInputSelector).last().change @fetchFilenameHandler # apply - Attaches handlers to events. apply: -> # Attach the search handler to the click event of the search button. $(@searchButtonSelector).click @searchHandler # Attach the fetchFilenameHanlder to the change event of the inputs. $(@sonyCiIdInputSelector).change @fetchFilenameHandler # When the page loads... # NOTE: could not get $(document).on('turbolinks:load') to work on initial page # load; reverting to $(document).ready, which seems to work more consistently. $(document).ready -> # This regex matches the 3rd URL segment which should be the GUID. guid_query_str = window.location.href.match(/concern\/assets\/(.*)\//)[1] # Create the behavior object, passing in the GUID as the query string. # NOTE: Sony Ci API has a 20 character limit on it's search terms, so let's # just pass in the last 20 characters, which will be more unique than the 1st # 20 chars due to the common prefix of "cpb-aacip-". Supposedly, <NAME> # from Sony Ci said that quoted search queries have no such limit, but I could # not get that to work, nor is it mentioned in the Ci API docs anywhere. behavior = new FindSonyCiMediaBehavior(guid_query_str.substr(-20)) # apply the behavior behavior.apply()
true
class FindSonyCiMediaBehavior # Select for the search button searchButtonSelector: '#find_sony_ci_media #search' # Selector for the div that displays the feedback messages. feedbackSelector: '#find_sony_ci_media #feedback' # Selector for the text inputs that have the Sony Ci IDs. sonyCiIdInputSelector: 'input.asset_sonyci_id' # Selector for the button to add new Sony Ci IDs addNewSonyCiIdButtonSelector: '.form-group.asset_sonyci_id button.add' constructor: (@query) -> # searchHandler - search Sony Ci for records matching the query and provide # feedback to the user. searchHandler: (event) => event.preventDefault() @giveFeedback('searching...') $.ajax( context: this, url: "/sony_ci/api/find_media", data: { query: @query } ).done ( response ) -> @giveFeedback(response.length + ' records found') if response.length > 0 @addFoundRecords(response) # fetchFilenameHandler - fetches the filename from Sony Ci given a Sony Ci ID # from an input field. fetchFilenameHandler: -> $.ajax( url: "/sony_ci/api/get_filename", context: this, data: { sony_ci_id: $(this).val() } ).done(( response ) -> $(this).parent().find('.sony_ci_filename').text(response['name']) ).fail(( response ) -> $(this).parent().find('.sony_ci_filename').text("Could not find Sony Ci record") ) # Adds a message to give the user feedback on what's happening. # The element is hidden at first, so set the text and reveal it. giveFeedback: (msg) => $(@feedbackSelector).text(msg).show() addFoundRecords: (records) => # Map the sonyci_id text inputs to their values. existingSonyCiIds = $(@sonyCiIdInputSelector).map (_, element) -> $(element).val() # Map the found records to just the Sony Ci IDs. # This is not a jQuery.map function, so the index is the 2nd arg instead of # the first, like in the map function above. foundSonyCiIds = records.map (record, _) -> record['id'] # Subtract the existing Sony Ci Ids from the found Sony Ci IDs. newSonyCiIds = $(foundSonyCiIds).not(existingSonyCiIds).get(); # For each of the new found Sony Ci IDs... newSonyCiIds.forEach (sonyCiId, index) => # Insert the found Sony Ci ID into the last text input and trigger the \ # change() event, because just setting val(x) won't do it. $(@sonyCiIdInputSelector).last().val(sonyCiId).change() # If we have more Sony Ci IDs to add if newSonyCiIds.length > index # Add another Sony Ci ID field it by clicking the "Add another..." # button. $(@addNewSonyCiIdButtonSelector).click() # Hyrax will simply copy and append the last element, but we don't want # values for Sony Ci ID or Filename there, so clear them out. $(@sonyCiIdInputSelector).last().val('') $('.sony_ci_filename').last().text('') # Finally, add the handler to the change() event of the input. $(@sonyCiIdInputSelector).last().change @fetchFilenameHandler # apply - Attaches handlers to events. apply: -> # Attach the search handler to the click event of the search button. $(@searchButtonSelector).click @searchHandler # Attach the fetchFilenameHanlder to the change event of the inputs. $(@sonyCiIdInputSelector).change @fetchFilenameHandler # When the page loads... # NOTE: could not get $(document).on('turbolinks:load') to work on initial page # load; reverting to $(document).ready, which seems to work more consistently. $(document).ready -> # This regex matches the 3rd URL segment which should be the GUID. guid_query_str = window.location.href.match(/concern\/assets\/(.*)\//)[1] # Create the behavior object, passing in the GUID as the query string. # NOTE: Sony Ci API has a 20 character limit on it's search terms, so let's # just pass in the last 20 characters, which will be more unique than the 1st # 20 chars due to the common prefix of "cpb-aacip-". Supposedly, PI:NAME:<NAME>END_PI # from Sony Ci said that quoted search queries have no such limit, but I could # not get that to work, nor is it mentioned in the Ci API docs anywhere. behavior = new FindSonyCiMediaBehavior(guid_query_str.substr(-20)) # apply the behavior behavior.apply()
[ { "context": "y] if @props.defaultValue\n storageKey: \"add_anecdote_to_fact_#{key}_#{string_hash(@props.site_", "end": 865, "score": 0.5521479845046997, "start": 865, "tag": "KEY", "value": "" }, { "context": "ops.defaultValue\n storageKey: \"add_anecdote_to_fact_#{key...
app/backbone/views/comments/react_add_anecdote.coffee
Factlink/feedforward
0
window.ReactAddAnecdote = React.createClass displayName: 'ReactAddAnecdote' render: -> ReactAnecdoteForm onSubmit: (text) => comment = new Comment markup_format: 'anecdote' created_by: currentSession.user().toJSON() content: $.trim(text) @props.comments.unshift(comment) comment.saveWithFactAndWithState {}, success: => @props.comments.fact.getOpinionators().setInterested true window.ReactAnecdoteForm = React.createClass displayName: 'ReactAnecdoteForm' renderField: (key, label, place_holder, tooltip) -> _div [], _strong [], label ReactTooltipIcon {}, tooltip ReactTextArea ref: key placeholder: place_holder defaultValue: JSON.parse(@props.defaultValue)[key] if @props.defaultValue storageKey: "add_anecdote_to_fact_#{key}_#{string_hash(@props.site_url)}" if @props.site_url onSubmit: => @refs.signinPopover.submit(=> @_submit()) render: -> _div ['add-anecdote'], _p [], 'Do you have an experience to share that might be of value to this challenge? Write your story!' @renderField( 'introduction', 'Challenge', 'Describe your own challenge, include context and stakeholders' 'How to describe a challenge? A challenge is a situation in which you experienced a difficulty, a dilemma. You were in need of new perspectives for new actions. Describe the context (e.g. stuck on a rock in the middle of a wild river, cold) but also human context, (with a group of friends), your challenging dilemma (e.g. how to get safe to the riverbank?). Be as short and precise as possible!' ) @renderField( 'insight', 'Exploration of options', 'Describe exploration of options with stakeholders', 'Explore your options! What was around to support meeting your challenge? e.g one would swim, with a risk to drown, phone in a helicopter, with a risk to get hypothermia.' ) @renderField( 'actions', 'Actions', 'Describe the actions you and others took', 'What are actions? Actions are things you or others did to move forward. Describe a flow of actions of what happened, what did you do, what did other people do? e.g. swung the rope to the tree branch, doubled the rope, jumped. Almost drowned, others were cheering at me.' ) @renderField( 'effect', 'Impact and evaluation', 'Evaluate the outcomes for the different stakeholders: how did your actions work out, for whom?', 'What is impact and evaluation? Give an overview of what was achieved and for whom. e.g. using and swinging the rope got me safe on the dry bank, but the rope broke and left the others on the rock. I phoned in helicopter, everyone got saved but one. In the end I think could have better ...' ) _button ['button-confirm button-small add-anecdote-post-button' onClick: => @refs.signinPopover.submit(=> @_submit()) ], 'Post ' + Factlink.Global.t.anecdote ReactSigninPopover ref: 'signinPopover' _submit: -> @props.onSubmit? JSON.stringify introduction: @refs.introduction.getText() insight: @refs.insight.getText() actions: @refs.actions.getText() effect: @refs.effect.getText() @refs.introduction.updateText '' @refs.insight.updateText '' @refs.actions.updateText '' @refs.effect.updateText ''
136086
window.ReactAddAnecdote = React.createClass displayName: 'ReactAddAnecdote' render: -> ReactAnecdoteForm onSubmit: (text) => comment = new Comment markup_format: 'anecdote' created_by: currentSession.user().toJSON() content: $.trim(text) @props.comments.unshift(comment) comment.saveWithFactAndWithState {}, success: => @props.comments.fact.getOpinionators().setInterested true window.ReactAnecdoteForm = React.createClass displayName: 'ReactAnecdoteForm' renderField: (key, label, place_holder, tooltip) -> _div [], _strong [], label ReactTooltipIcon {}, tooltip ReactTextArea ref: key placeholder: place_holder defaultValue: JSON.parse(@props.defaultValue)[key] if @props.defaultValue storageKey: "add<KEY>_anecdote<KEY>_to<KEY>_fact<KEY>_#{key<KEY>}_#{string_hash(@props.site_url)}" if @props.site_url onSubmit: => @refs.signinPopover.submit(=> @_submit()) render: -> _div ['add-anecdote'], _p [], 'Do you have an experience to share that might be of value to this challenge? Write your story!' @renderField( 'introduction', 'Challenge', 'Describe your own challenge, include context and stakeholders' 'How to describe a challenge? A challenge is a situation in which you experienced a difficulty, a dilemma. You were in need of new perspectives for new actions. Describe the context (e.g. stuck on a rock in the middle of a wild river, cold) but also human context, (with a group of friends), your challenging dilemma (e.g. how to get safe to the riverbank?). Be as short and precise as possible!' ) @renderField( 'insight', 'Exploration of options', 'Describe exploration of options with stakeholders', 'Explore your options! What was around to support meeting your challenge? e.g one would swim, with a risk to drown, phone in a helicopter, with a risk to get hypothermia.' ) @renderField( 'actions', 'Actions', 'Describe the actions you and others took', 'What are actions? Actions are things you or others did to move forward. Describe a flow of actions of what happened, what did you do, what did other people do? e.g. swung the rope to the tree branch, doubled the rope, jumped. Almost drowned, others were cheering at me.' ) @renderField( 'effect', 'Impact and evaluation', 'Evaluate the outcomes for the different stakeholders: how did your actions work out, for whom?', 'What is impact and evaluation? Give an overview of what was achieved and for whom. e.g. using and swinging the rope got me safe on the dry bank, but the rope broke and left the others on the rock. I phoned in helicopter, everyone got saved but one. In the end I think could have better ...' ) _button ['button-confirm button-small add-anecdote-post-button' onClick: => @refs.signinPopover.submit(=> @_submit()) ], 'Post ' + Factlink.Global.t.anecdote ReactSigninPopover ref: 'signinPopover' _submit: -> @props.onSubmit? JSON.stringify introduction: @refs.introduction.getText() insight: @refs.insight.getText() actions: @refs.actions.getText() effect: @refs.effect.getText() @refs.introduction.updateText '' @refs.insight.updateText '' @refs.actions.updateText '' @refs.effect.updateText ''
true
window.ReactAddAnecdote = React.createClass displayName: 'ReactAddAnecdote' render: -> ReactAnecdoteForm onSubmit: (text) => comment = new Comment markup_format: 'anecdote' created_by: currentSession.user().toJSON() content: $.trim(text) @props.comments.unshift(comment) comment.saveWithFactAndWithState {}, success: => @props.comments.fact.getOpinionators().setInterested true window.ReactAnecdoteForm = React.createClass displayName: 'ReactAnecdoteForm' renderField: (key, label, place_holder, tooltip) -> _div [], _strong [], label ReactTooltipIcon {}, tooltip ReactTextArea ref: key placeholder: place_holder defaultValue: JSON.parse(@props.defaultValue)[key] if @props.defaultValue storageKey: "addPI:KEY:<KEY>END_PI_anecdotePI:KEY:<KEY>END_PI_toPI:KEY:<KEY>END_PI_factPI:KEY:<KEY>END_PI_#{keyPI:KEY:<KEY>END_PI}_#{string_hash(@props.site_url)}" if @props.site_url onSubmit: => @refs.signinPopover.submit(=> @_submit()) render: -> _div ['add-anecdote'], _p [], 'Do you have an experience to share that might be of value to this challenge? Write your story!' @renderField( 'introduction', 'Challenge', 'Describe your own challenge, include context and stakeholders' 'How to describe a challenge? A challenge is a situation in which you experienced a difficulty, a dilemma. You were in need of new perspectives for new actions. Describe the context (e.g. stuck on a rock in the middle of a wild river, cold) but also human context, (with a group of friends), your challenging dilemma (e.g. how to get safe to the riverbank?). Be as short and precise as possible!' ) @renderField( 'insight', 'Exploration of options', 'Describe exploration of options with stakeholders', 'Explore your options! What was around to support meeting your challenge? e.g one would swim, with a risk to drown, phone in a helicopter, with a risk to get hypothermia.' ) @renderField( 'actions', 'Actions', 'Describe the actions you and others took', 'What are actions? Actions are things you or others did to move forward. Describe a flow of actions of what happened, what did you do, what did other people do? e.g. swung the rope to the tree branch, doubled the rope, jumped. Almost drowned, others were cheering at me.' ) @renderField( 'effect', 'Impact and evaluation', 'Evaluate the outcomes for the different stakeholders: how did your actions work out, for whom?', 'What is impact and evaluation? Give an overview of what was achieved and for whom. e.g. using and swinging the rope got me safe on the dry bank, but the rope broke and left the others on the rock. I phoned in helicopter, everyone got saved but one. In the end I think could have better ...' ) _button ['button-confirm button-small add-anecdote-post-button' onClick: => @refs.signinPopover.submit(=> @_submit()) ], 'Post ' + Factlink.Global.t.anecdote ReactSigninPopover ref: 'signinPopover' _submit: -> @props.onSubmit? JSON.stringify introduction: @refs.introduction.getText() insight: @refs.insight.getText() actions: @refs.actions.getText() effect: @refs.effect.getText() @refs.introduction.updateText '' @refs.insight.updateText '' @refs.actions.updateText '' @refs.effect.updateText ''
[ { "context": "ox OS envíame un email.\n </li>\n <li>juanc.jara@pucp.pe</li>\n </ul>\n </div>\n", "end": 1176, "score": 0.9999097585678101, "start": 1158, "tag": "EMAIL", "value": "juanc.jara@pucp.pe" } ]
components/Vote.react.coffee
juancjara/guitar-hero-firefox-os
0
React = require 'react' {Dispatcher} = require './../dispatcher.coffee' module.exports = Vote = React.createClass handleClick: (to) -> @props.changeTab('Vote', to) render: -> className = 'vote tabs '+@props.show <div className = {className}> <div className = 'btn blue pull-left' onTouchEnd={@handleClick.bind(this, 'MainMenu')}> Menu </div> <div className = 'clear' ></div> <h2 className = 'text-center'>More apps</h2> <ul className = 'clear-list text-center'> <li> <span>Rank this app, click the start</span> <a className = 'rank' target = '_blank' href = 'https://marketplace.firefox.com/app/guitar-heroes-2/' > <span className = 'icon-star' /> </a> </li> <li> If you have any idea for a new app or you want an Android app on Firefox Market send me and email. I will do my best. </li> <li> Si tienes alguna idea para alguna app o quieres una aplicación de Android para tu Firefox OS envíame un email. </li> <li>juanc.jara@pucp.pe</li> </ul> </div>
67505
React = require 'react' {Dispatcher} = require './../dispatcher.coffee' module.exports = Vote = React.createClass handleClick: (to) -> @props.changeTab('Vote', to) render: -> className = 'vote tabs '+@props.show <div className = {className}> <div className = 'btn blue pull-left' onTouchEnd={@handleClick.bind(this, 'MainMenu')}> Menu </div> <div className = 'clear' ></div> <h2 className = 'text-center'>More apps</h2> <ul className = 'clear-list text-center'> <li> <span>Rank this app, click the start</span> <a className = 'rank' target = '_blank' href = 'https://marketplace.firefox.com/app/guitar-heroes-2/' > <span className = 'icon-star' /> </a> </li> <li> If you have any idea for a new app or you want an Android app on Firefox Market send me and email. I will do my best. </li> <li> Si tienes alguna idea para alguna app o quieres una aplicación de Android para tu Firefox OS envíame un email. </li> <li><EMAIL></li> </ul> </div>
true
React = require 'react' {Dispatcher} = require './../dispatcher.coffee' module.exports = Vote = React.createClass handleClick: (to) -> @props.changeTab('Vote', to) render: -> className = 'vote tabs '+@props.show <div className = {className}> <div className = 'btn blue pull-left' onTouchEnd={@handleClick.bind(this, 'MainMenu')}> Menu </div> <div className = 'clear' ></div> <h2 className = 'text-center'>More apps</h2> <ul className = 'clear-list text-center'> <li> <span>Rank this app, click the start</span> <a className = 'rank' target = '_blank' href = 'https://marketplace.firefox.com/app/guitar-heroes-2/' > <span className = 'icon-star' /> </a> </li> <li> If you have any idea for a new app or you want an Android app on Firefox Market send me and email. I will do my best. </li> <li> Si tienes alguna idea para alguna app o quieres una aplicación de Android para tu Firefox OS envíame un email. </li> <li>PI:EMAIL:<EMAIL>END_PI</li> </ul> </div>
[ { "context": "# @file firefly.coffee\n# @Copyright (c) 2016 Taylor Siviter\n# This source code is licensed under the MIT Lice", "end": 59, "score": 0.9998173713684082, "start": 45, "tag": "NAME", "value": "Taylor Siviter" } ]
examples/firefly/firefly.coffee
siviter-t/lampyridae.coffee
4
# @file firefly.coffee # @Copyright (c) 2016 Taylor Siviter # This source code is licensed under the MIT License. # For full information, see the LICENSE file in the project root. ### # Example usage of lampyridae.coffee ### # Only the Canvas and base Particle classes are included by default require 'particle/firefly' # By default, if there is no existing canvas with the id 'world', this will # attach '<canvas id="world"></canvas>' under the body element. canvas = new Lampyridae.Canvas 'world' Lampyridae.Firefly::speedMax = 5 # You can change proto parameters! Lampyridae.Firefly::enableGlow = true # Glow is not enabled by default Lampyridae.Firefly::glowFactor = 4 # Default is 4; rerun if changed total = 25 # Number of fireflies to spawn fireflies = [] # For keeping track of the fireflies # Reusable firefly creator - remember to tweak the total if reused. do createFireflies = () -> for i in [0...total] firefly = new Lampyridae.Firefly canvas fireflies.push firefly # An iterative update over the fireflies - remember to add it to the canvas! updateFireflies = () -> fireflies[i].update() for i in [0...total] ### # Lights, camera, action! ### canvas.addUpdate canvas.draw.clear # If you want the screen to clear between frames canvas.addUpdate updateFireflies # Update all the fireflies every frame canvas.animate() # Animate the canvas screen
59742
# @file firefly.coffee # @Copyright (c) 2016 <NAME> # This source code is licensed under the MIT License. # For full information, see the LICENSE file in the project root. ### # Example usage of lampyridae.coffee ### # Only the Canvas and base Particle classes are included by default require 'particle/firefly' # By default, if there is no existing canvas with the id 'world', this will # attach '<canvas id="world"></canvas>' under the body element. canvas = new Lampyridae.Canvas 'world' Lampyridae.Firefly::speedMax = 5 # You can change proto parameters! Lampyridae.Firefly::enableGlow = true # Glow is not enabled by default Lampyridae.Firefly::glowFactor = 4 # Default is 4; rerun if changed total = 25 # Number of fireflies to spawn fireflies = [] # For keeping track of the fireflies # Reusable firefly creator - remember to tweak the total if reused. do createFireflies = () -> for i in [0...total] firefly = new Lampyridae.Firefly canvas fireflies.push firefly # An iterative update over the fireflies - remember to add it to the canvas! updateFireflies = () -> fireflies[i].update() for i in [0...total] ### # Lights, camera, action! ### canvas.addUpdate canvas.draw.clear # If you want the screen to clear between frames canvas.addUpdate updateFireflies # Update all the fireflies every frame canvas.animate() # Animate the canvas screen
true
# @file firefly.coffee # @Copyright (c) 2016 PI:NAME:<NAME>END_PI # This source code is licensed under the MIT License. # For full information, see the LICENSE file in the project root. ### # Example usage of lampyridae.coffee ### # Only the Canvas and base Particle classes are included by default require 'particle/firefly' # By default, if there is no existing canvas with the id 'world', this will # attach '<canvas id="world"></canvas>' under the body element. canvas = new Lampyridae.Canvas 'world' Lampyridae.Firefly::speedMax = 5 # You can change proto parameters! Lampyridae.Firefly::enableGlow = true # Glow is not enabled by default Lampyridae.Firefly::glowFactor = 4 # Default is 4; rerun if changed total = 25 # Number of fireflies to spawn fireflies = [] # For keeping track of the fireflies # Reusable firefly creator - remember to tweak the total if reused. do createFireflies = () -> for i in [0...total] firefly = new Lampyridae.Firefly canvas fireflies.push firefly # An iterative update over the fireflies - remember to add it to the canvas! updateFireflies = () -> fireflies[i].update() for i in [0...total] ### # Lights, camera, action! ### canvas.addUpdate canvas.draw.clear # If you want the screen to clear between frames canvas.addUpdate updateFireflies # Update all the fireflies every frame canvas.animate() # Animate the canvas screen
[ { "context": "user: \n data: [\n id: 1\n name: \"Bob\"\n ,\n id: 2\n name: \"Sue\"\n ", "end": 482, "score": 0.9998520612716675, "start": 479, "tag": "NAME", "value": "Bob" }, { "context": " name: \"Bob\"\n ,\n id: 2\n nam...
test/spec_coffee/model_relationships_spec.coffee
kirkbowers/mvcoffee
0
MVCoffee = require("../lib/mvcoffee") theUser = class User extends MVCoffee.Model theUser.hasMany "activity" theUser.hasOne "brain" theActivity = class Activity extends MVCoffee.Model theActivity.belongsTo "user" theBrain = class Brain extends MVCoffee.Model theBrain.belongsTo "user" store = new MVCoffee.ModelStore user: User activity: Activity brain: Brain store.load mvcoffee_version: "1.0.0" models: user: data: [ id: 1 name: "Bob" , id: 2 name: "Sue" ] activity: data: [ id: 1 name: "Rake the yard" position: 2 user_id: 1 , id: 2 name: "Sweep the driveway" position: 1 user_id: 1 , id: 3 name: "Wash the cat" position: 1 user_id: 2 ] brain: data: [ id: 1 name: "gray matter" user_id: 1 ] describe "model macro methods for relationships", -> it "should define an activities method on User", -> user = new User() expect(user.activities instanceof Function).toBeTruthy() it "should define a user method on Activity", -> activity = new Activity() expect(activity.user instanceof Function).toBeTruthy() it "should not define an activities method on the super class", -> model = new MVCoffee.Model expect(model.activities).toBeUndefined() it "should not define a user method on the super class", -> model = new MVCoffee.Model expect(model.user).toBeUndefined() it "should find a model by id", -> user = User.find(1) expect(user instanceof User).toBeTruthy() expect(user.name).toBe("Bob") it "should find activities for a user", -> user = User.find(1) acts = user.activities() expect(acts instanceof Array).toBeTruthy() expect(acts.length).toBe(2) expect(acts[0].name).toBe("Rake the yard") expect(acts[1].name).toBe("Sweep the driveway") it "should find user for an activity", -> activity = Activity.find(3) user = activity.user() expect(user instanceof User).toBeTruthy() expect(user.id).toBe(2) it "should find a record using findBy", -> activity = Activity.findBy name: "Wash the cat" expect(activity instanceof Activity).toBeTruthy() expect(activity.id).toBe(3) it "should find records using where", -> activities = Activity.where user_id: 1 expect(activities.length).toBe(2) expect(activities[0].id).toBe(1) expect(activities[1].id).toBe(2) it "should define a brain method on User", -> user = new User() expect(user.brain instanceof Function).toBeTruthy() it "should define a user method on Brain", -> brain = new Brain() expect(brain.user instanceof Function).toBeTruthy() it "should find a brain for a user", -> user = User.find(1) brain = user.brain() expect(brain instanceof Object).toBeTruthy() expect(brain.name).toBe("gray matter")
33406
MVCoffee = require("../lib/mvcoffee") theUser = class User extends MVCoffee.Model theUser.hasMany "activity" theUser.hasOne "brain" theActivity = class Activity extends MVCoffee.Model theActivity.belongsTo "user" theBrain = class Brain extends MVCoffee.Model theBrain.belongsTo "user" store = new MVCoffee.ModelStore user: User activity: Activity brain: Brain store.load mvcoffee_version: "1.0.0" models: user: data: [ id: 1 name: "<NAME>" , id: 2 name: "<NAME>" ] activity: data: [ id: 1 name: "Rake the yard" position: 2 user_id: 1 , id: 2 name: "Sweep the driveway" position: 1 user_id: 1 , id: 3 name: "Wash the cat" position: 1 user_id: 2 ] brain: data: [ id: 1 name: "gray matter" user_id: 1 ] describe "model macro methods for relationships", -> it "should define an activities method on User", -> user = new User() expect(user.activities instanceof Function).toBeTruthy() it "should define a user method on Activity", -> activity = new Activity() expect(activity.user instanceof Function).toBeTruthy() it "should not define an activities method on the super class", -> model = new MVCoffee.Model expect(model.activities).toBeUndefined() it "should not define a user method on the super class", -> model = new MVCoffee.Model expect(model.user).toBeUndefined() it "should find a model by id", -> user = User.find(1) expect(user instanceof User).toBeTruthy() expect(user.name).toBe("<NAME>") it "should find activities for a user", -> user = User.find(1) acts = user.activities() expect(acts instanceof Array).toBeTruthy() expect(acts.length).toBe(2) expect(acts[0].name).toBe("Rake the yard") expect(acts[1].name).toBe("Sweep the driveway") it "should find user for an activity", -> activity = Activity.find(3) user = activity.user() expect(user instanceof User).toBeTruthy() expect(user.id).toBe(2) it "should find a record using findBy", -> activity = Activity.findBy name: "Wash the cat" expect(activity instanceof Activity).toBeTruthy() expect(activity.id).toBe(3) it "should find records using where", -> activities = Activity.where user_id: 1 expect(activities.length).toBe(2) expect(activities[0].id).toBe(1) expect(activities[1].id).toBe(2) it "should define a brain method on User", -> user = new User() expect(user.brain instanceof Function).toBeTruthy() it "should define a user method on Brain", -> brain = new Brain() expect(brain.user instanceof Function).toBeTruthy() it "should find a brain for a user", -> user = User.find(1) brain = user.brain() expect(brain instanceof Object).toBeTruthy() expect(brain.name).toBe("gray matter")
true
MVCoffee = require("../lib/mvcoffee") theUser = class User extends MVCoffee.Model theUser.hasMany "activity" theUser.hasOne "brain" theActivity = class Activity extends MVCoffee.Model theActivity.belongsTo "user" theBrain = class Brain extends MVCoffee.Model theBrain.belongsTo "user" store = new MVCoffee.ModelStore user: User activity: Activity brain: Brain store.load mvcoffee_version: "1.0.0" models: user: data: [ id: 1 name: "PI:NAME:<NAME>END_PI" , id: 2 name: "PI:NAME:<NAME>END_PI" ] activity: data: [ id: 1 name: "Rake the yard" position: 2 user_id: 1 , id: 2 name: "Sweep the driveway" position: 1 user_id: 1 , id: 3 name: "Wash the cat" position: 1 user_id: 2 ] brain: data: [ id: 1 name: "gray matter" user_id: 1 ] describe "model macro methods for relationships", -> it "should define an activities method on User", -> user = new User() expect(user.activities instanceof Function).toBeTruthy() it "should define a user method on Activity", -> activity = new Activity() expect(activity.user instanceof Function).toBeTruthy() it "should not define an activities method on the super class", -> model = new MVCoffee.Model expect(model.activities).toBeUndefined() it "should not define a user method on the super class", -> model = new MVCoffee.Model expect(model.user).toBeUndefined() it "should find a model by id", -> user = User.find(1) expect(user instanceof User).toBeTruthy() expect(user.name).toBe("PI:NAME:<NAME>END_PI") it "should find activities for a user", -> user = User.find(1) acts = user.activities() expect(acts instanceof Array).toBeTruthy() expect(acts.length).toBe(2) expect(acts[0].name).toBe("Rake the yard") expect(acts[1].name).toBe("Sweep the driveway") it "should find user for an activity", -> activity = Activity.find(3) user = activity.user() expect(user instanceof User).toBeTruthy() expect(user.id).toBe(2) it "should find a record using findBy", -> activity = Activity.findBy name: "Wash the cat" expect(activity instanceof Activity).toBeTruthy() expect(activity.id).toBe(3) it "should find records using where", -> activities = Activity.where user_id: 1 expect(activities.length).toBe(2) expect(activities[0].id).toBe(1) expect(activities[1].id).toBe(2) it "should define a brain method on User", -> user = new User() expect(user.brain instanceof Function).toBeTruthy() it "should define a user method on Brain", -> brain = new Brain() expect(brain.user instanceof Function).toBeTruthy() it "should find a brain for a user", -> user = User.find(1) brain = user.brain() expect(brain instanceof Object).toBeTruthy() expect(brain.name).toBe("gray matter")
[ { "context": "roy =>\n App.User.create id: 1, firstName: \"Lance\", done\n \n describe 'format: \"json\"', ->\n ", "end": 309, "score": 0.9998109340667725, "start": 304, "tag": "NAME", "value": "Lance" }, { "context": " assert.equal resources[0].firstName, \...
test/cases/controller/resourcefulTest.coffee
vjsingh/tower
1
require '../../config' controller = null user = null router = null describeWith = (store) -> describe "Tower.Controller.Resourceful (Tower.Store.#{store.name})", -> beforeEach (done) -> App.User.store(store) App.User.destroy => App.User.create id: 1, firstName: "Lance", done describe 'format: "json"', -> describe "success", -> test '#index', (done) -> Tower.get "index", format: "json", -> resources = JSON.parse(@body) assert.isArray resources assert.isArray @collection assert.equal typeof(@resource), "undefined" assert.equal resources.length, 1 assert.equal resources[0].firstName, "Lance" assert.equal @headers["Content-Type"], "application/json" App.User.count (error, count) => assert.equal count, 1 done() test '#new', (done) -> Tower.get 'new', format: "json", -> resource = JSON.parse(@body) assert.equal typeof(@collection), "undefined" assert.equal typeof(@resource), "object" assert.equal resource.firstName, undefined assert.equal @headers["Content-Type"], "application/json" App.User.count (error, count) => assert.equal count, 1 done() test '#create', (done) -> Tower.post 'create', format: "json", user: firstName: "Lance", -> resource = JSON.parse(@body) assert.equal resource.firstName, "Lance" assert.equal @headers["Content-Type"], "application/json" App.User.count (error, count) => assert.equal count, 2 done() test '#show', (done) -> Tower.get 'show', id: 1, format: "json", -> resource = JSON.parse(@body) assert.equal resource.firstName, "Lance" assert.equal resource.id, 1 assert.equal @headers["Content-Type"], "application/json" App.User.count (error, count) => assert.equal count, 1 done() test '#edit', (done) -> Tower.get 'edit', id: 1, format: "json", -> resource = JSON.parse(@body) assert.equal resource.firstName, "Lance" assert.equal resource.id, 1 assert.equal @headers["Content-Type"], "application/json" App.User.count (error, count) => assert.equal count, 1 done() test '#update', (done) -> Tower.put 'update', id: 1, format: "json", user: firstName: "Dane", -> resource = JSON.parse(@body) assert.equal resource.firstName, "Dane" assert.equal resource.id, 1 assert.equal @headers["Content-Type"], "application/json" App.User.find 1, (error, user) => assert.equal user.get("firstName"), "Dane" App.User.count (error, count) => assert.equal count, 1 done() test '#destroy', (done) -> Tower.destroy 'destroy', id: 1, format: "json", -> resource = JSON.parse(@body) assert.equal resource.firstName, "Lance" assert.equal resource.id, undefined assert.equal @headers["Content-Type"], "application/json" App.User.count (error, count) => assert.equal count, 0 done() describe "failure", -> test '#create' test '#update' test '#destroy' describe 'format: "html"', -> describe 'success', -> test '#index', (done) -> Tower.get 'index', -> assert.equal @body, '<h1>Hello World</h1>\n' assert.equal @headers["Content-Type"], "text/html" App.User.count (error, count) => assert.equal count, 1 done() test '#new', (done) -> Tower.get 'new', -> assert.equal @body, '<h1>New User</h1>\n' assert.equal @headers["Content-Type"], "text/html" App.User.count (error, count) => assert.equal count, 1 done() test '#create', (done) -> Tower.post 'create', user: firstName: "Lance", -> assert.equal @body, "<h1>Hello Lance</h1>\n" assert.equal @headers["Content-Type"], "text/html" App.User.count (error, count) => assert.equal count, 2 done() test '#show', (done) -> Tower.get 'show', id: 1, -> assert.equal @body, "<h1>Hello Lance</h1>\n" assert.equal @headers["Content-Type"], "text/html" App.User.count (error, count) => assert.equal count, 1 done() test '#edit', (done) -> Tower.get 'edit', -> assert.equal @body, '<h1>Editing User</h1>\n' assert.equal @headers["Content-Type"], "text/html" App.User.count (error, count) => assert.equal count, 1 done() test '#update', (done) -> Tower.put 'update', id: 1, user: firstName: "Dane", -> assert.equal @body, '<h1>Hello Dane</h1>\n' assert.equal @headers["Content-Type"], "text/html" App.User.find 1, (error, user) => assert.equal user.get("firstName"), "Dane" App.User.count (error, count) => assert.equal count, 1 done() test '#destroy', (done) -> Tower.destroy 'destroy', id: 1, -> assert.equal @body, '<h1>Hello World</h1>\n' assert.equal @headers["Content-Type"], "text/html" App.User.count (error, count) => assert.equal count, 0 done() describeWith(Tower.Store.Memory) #describeWith(Tower.Store.MongoDB)
132666
require '../../config' controller = null user = null router = null describeWith = (store) -> describe "Tower.Controller.Resourceful (Tower.Store.#{store.name})", -> beforeEach (done) -> App.User.store(store) App.User.destroy => App.User.create id: 1, firstName: "<NAME>", done describe 'format: "json"', -> describe "success", -> test '#index', (done) -> Tower.get "index", format: "json", -> resources = JSON.parse(@body) assert.isArray resources assert.isArray @collection assert.equal typeof(@resource), "undefined" assert.equal resources.length, 1 assert.equal resources[0].firstName, "<NAME>" assert.equal @headers["Content-Type"], "application/json" App.User.count (error, count) => assert.equal count, 1 done() test '#new', (done) -> Tower.get 'new', format: "json", -> resource = JSON.parse(@body) assert.equal typeof(@collection), "undefined" assert.equal typeof(@resource), "object" assert.equal resource.firstName, undefined assert.equal @headers["Content-Type"], "application/json" App.User.count (error, count) => assert.equal count, 1 done() test '#create', (done) -> Tower.post 'create', format: "json", user: firstName: "<NAME>", -> resource = JSON.parse(@body) assert.equal resource.firstName, "<NAME>" assert.equal @headers["Content-Type"], "application/json" App.User.count (error, count) => assert.equal count, 2 done() test '#show', (done) -> Tower.get 'show', id: 1, format: "json", -> resource = JSON.parse(@body) assert.equal resource.firstName, "<NAME>" assert.equal resource.id, 1 assert.equal @headers["Content-Type"], "application/json" App.User.count (error, count) => assert.equal count, 1 done() test '#edit', (done) -> Tower.get 'edit', id: 1, format: "json", -> resource = JSON.parse(@body) assert.equal resource.firstName, "<NAME>" assert.equal resource.id, 1 assert.equal @headers["Content-Type"], "application/json" App.User.count (error, count) => assert.equal count, 1 done() test '#update', (done) -> Tower.put 'update', id: 1, format: "json", user: firstName: "<NAME>", -> resource = JSON.parse(@body) assert.equal resource.firstName, "<NAME>" assert.equal resource.id, 1 assert.equal @headers["Content-Type"], "application/json" App.User.find 1, (error, user) => assert.equal user.get("firstName"), "<NAME>" App.User.count (error, count) => assert.equal count, 1 done() test '#destroy', (done) -> Tower.destroy 'destroy', id: 1, format: "json", -> resource = JSON.parse(@body) assert.equal resource.firstName, "<NAME>" assert.equal resource.id, undefined assert.equal @headers["Content-Type"], "application/json" App.User.count (error, count) => assert.equal count, 0 done() describe "failure", -> test '#create' test '#update' test '#destroy' describe 'format: "html"', -> describe 'success', -> test '#index', (done) -> Tower.get 'index', -> assert.equal @body, '<h1>Hello World</h1>\n' assert.equal @headers["Content-Type"], "text/html" App.User.count (error, count) => assert.equal count, 1 done() test '#new', (done) -> Tower.get 'new', -> assert.equal @body, '<h1>New User</h1>\n' assert.equal @headers["Content-Type"], "text/html" App.User.count (error, count) => assert.equal count, 1 done() test '#create', (done) -> Tower.post 'create', user: firstName: "<NAME>", -> assert.equal @body, "<h1>Hello <NAME></h1>\n" assert.equal @headers["Content-Type"], "text/html" App.User.count (error, count) => assert.equal count, 2 done() test '#show', (done) -> Tower.get 'show', id: 1, -> assert.equal @body, "<h1>Hello <NAME></h1>\n" assert.equal @headers["Content-Type"], "text/html" App.User.count (error, count) => assert.equal count, 1 done() test '#edit', (done) -> Tower.get 'edit', -> assert.equal @body, '<h1>Editing User</h1>\n' assert.equal @headers["Content-Type"], "text/html" App.User.count (error, count) => assert.equal count, 1 done() test '#update', (done) -> Tower.put 'update', id: 1, user: firstName: "<NAME>", -> assert.equal @body, '<h1>Hello <NAME></h1>\n' assert.equal @headers["Content-Type"], "text/html" App.User.find 1, (error, user) => assert.equal user.get("firstName"), "<NAME>" App.User.count (error, count) => assert.equal count, 1 done() test '#destroy', (done) -> Tower.destroy 'destroy', id: 1, -> assert.equal @body, '<h1>Hello World</h1>\n' assert.equal @headers["Content-Type"], "text/html" App.User.count (error, count) => assert.equal count, 0 done() describeWith(Tower.Store.Memory) #describeWith(Tower.Store.MongoDB)
true
require '../../config' controller = null user = null router = null describeWith = (store) -> describe "Tower.Controller.Resourceful (Tower.Store.#{store.name})", -> beforeEach (done) -> App.User.store(store) App.User.destroy => App.User.create id: 1, firstName: "PI:NAME:<NAME>END_PI", done describe 'format: "json"', -> describe "success", -> test '#index', (done) -> Tower.get "index", format: "json", -> resources = JSON.parse(@body) assert.isArray resources assert.isArray @collection assert.equal typeof(@resource), "undefined" assert.equal resources.length, 1 assert.equal resources[0].firstName, "PI:NAME:<NAME>END_PI" assert.equal @headers["Content-Type"], "application/json" App.User.count (error, count) => assert.equal count, 1 done() test '#new', (done) -> Tower.get 'new', format: "json", -> resource = JSON.parse(@body) assert.equal typeof(@collection), "undefined" assert.equal typeof(@resource), "object" assert.equal resource.firstName, undefined assert.equal @headers["Content-Type"], "application/json" App.User.count (error, count) => assert.equal count, 1 done() test '#create', (done) -> Tower.post 'create', format: "json", user: firstName: "PI:NAME:<NAME>END_PI", -> resource = JSON.parse(@body) assert.equal resource.firstName, "PI:NAME:<NAME>END_PI" assert.equal @headers["Content-Type"], "application/json" App.User.count (error, count) => assert.equal count, 2 done() test '#show', (done) -> Tower.get 'show', id: 1, format: "json", -> resource = JSON.parse(@body) assert.equal resource.firstName, "PI:NAME:<NAME>END_PI" assert.equal resource.id, 1 assert.equal @headers["Content-Type"], "application/json" App.User.count (error, count) => assert.equal count, 1 done() test '#edit', (done) -> Tower.get 'edit', id: 1, format: "json", -> resource = JSON.parse(@body) assert.equal resource.firstName, "PI:NAME:<NAME>END_PI" assert.equal resource.id, 1 assert.equal @headers["Content-Type"], "application/json" App.User.count (error, count) => assert.equal count, 1 done() test '#update', (done) -> Tower.put 'update', id: 1, format: "json", user: firstName: "PI:NAME:<NAME>END_PI", -> resource = JSON.parse(@body) assert.equal resource.firstName, "PI:NAME:<NAME>END_PI" assert.equal resource.id, 1 assert.equal @headers["Content-Type"], "application/json" App.User.find 1, (error, user) => assert.equal user.get("firstName"), "PI:NAME:<NAME>END_PI" App.User.count (error, count) => assert.equal count, 1 done() test '#destroy', (done) -> Tower.destroy 'destroy', id: 1, format: "json", -> resource = JSON.parse(@body) assert.equal resource.firstName, "PI:NAME:<NAME>END_PI" assert.equal resource.id, undefined assert.equal @headers["Content-Type"], "application/json" App.User.count (error, count) => assert.equal count, 0 done() describe "failure", -> test '#create' test '#update' test '#destroy' describe 'format: "html"', -> describe 'success', -> test '#index', (done) -> Tower.get 'index', -> assert.equal @body, '<h1>Hello World</h1>\n' assert.equal @headers["Content-Type"], "text/html" App.User.count (error, count) => assert.equal count, 1 done() test '#new', (done) -> Tower.get 'new', -> assert.equal @body, '<h1>New User</h1>\n' assert.equal @headers["Content-Type"], "text/html" App.User.count (error, count) => assert.equal count, 1 done() test '#create', (done) -> Tower.post 'create', user: firstName: "PI:NAME:<NAME>END_PI", -> assert.equal @body, "<h1>Hello PI:NAME:<NAME>END_PI</h1>\n" assert.equal @headers["Content-Type"], "text/html" App.User.count (error, count) => assert.equal count, 2 done() test '#show', (done) -> Tower.get 'show', id: 1, -> assert.equal @body, "<h1>Hello PI:NAME:<NAME>END_PI</h1>\n" assert.equal @headers["Content-Type"], "text/html" App.User.count (error, count) => assert.equal count, 1 done() test '#edit', (done) -> Tower.get 'edit', -> assert.equal @body, '<h1>Editing User</h1>\n' assert.equal @headers["Content-Type"], "text/html" App.User.count (error, count) => assert.equal count, 1 done() test '#update', (done) -> Tower.put 'update', id: 1, user: firstName: "PI:NAME:<NAME>END_PI", -> assert.equal @body, '<h1>Hello PI:NAME:<NAME>END_PI</h1>\n' assert.equal @headers["Content-Type"], "text/html" App.User.find 1, (error, user) => assert.equal user.get("firstName"), "PI:NAME:<NAME>END_PI" App.User.count (error, count) => assert.equal count, 1 done() test '#destroy', (done) -> Tower.destroy 'destroy', id: 1, -> assert.equal @body, '<h1>Hello World</h1>\n' assert.equal @headers["Content-Type"], "text/html" App.User.count (error, count) => assert.equal count, 0 done() describeWith(Tower.Store.Memory) #describeWith(Tower.Store.MongoDB)
[ { "context": "###\n grunt-embed\n https://github.com/callumlocke/grunt-embed\n\n Copyright 2013 Callum Locke\n Lice", "end": 50, "score": 0.9995214939117432, "start": 39, "tag": "USERNAME", "value": "callumlocke" }, { "context": "thub.com/callumlocke/grunt-embed\n\n Copyright 20...
tasks/embed.coffee
telor/grunt-embed
1
### grunt-embed https://github.com/callumlocke/grunt-embed Copyright 2013 Callum Locke Licensed under the MIT license. ### ResourceEmbedder = require 'resource-embedder' path = require 'path' module.exports = (grunt) -> grunt.registerMultiTask 'embed', 'Converts external scripts and stylesheets into embedded ones.', -> done = @async() @files.forEach (file) => srcFile = file.orig.src if typeof srcFile isnt 'string' if srcFile.length > 1 grunt.log.warn 'Multiple source files supplied; only the first will be used.' srcFile = srcFile[0] if not grunt.file.exists srcFile grunt.log.warn "Source file \"#{path.resolve(srcFile)}\" not found." else embedder = new ResourceEmbedder srcFile, @options() embedder.get (output, warnings) -> grunt.file.write file.dest, output if warnings? grunt.log.warn warning for warning in warnings grunt.log.ok "File \"#{file.dest}\" created." done()
156966
### grunt-embed https://github.com/callumlocke/grunt-embed Copyright 2013 <NAME> Licensed under the MIT license. ### ResourceEmbedder = require 'resource-embedder' path = require 'path' module.exports = (grunt) -> grunt.registerMultiTask 'embed', 'Converts external scripts and stylesheets into embedded ones.', -> done = @async() @files.forEach (file) => srcFile = file.orig.src if typeof srcFile isnt 'string' if srcFile.length > 1 grunt.log.warn 'Multiple source files supplied; only the first will be used.' srcFile = srcFile[0] if not grunt.file.exists srcFile grunt.log.warn "Source file \"#{path.resolve(srcFile)}\" not found." else embedder = new ResourceEmbedder srcFile, @options() embedder.get (output, warnings) -> grunt.file.write file.dest, output if warnings? grunt.log.warn warning for warning in warnings grunt.log.ok "File \"#{file.dest}\" created." done()
true
### grunt-embed https://github.com/callumlocke/grunt-embed Copyright 2013 PI:NAME:<NAME>END_PI Licensed under the MIT license. ### ResourceEmbedder = require 'resource-embedder' path = require 'path' module.exports = (grunt) -> grunt.registerMultiTask 'embed', 'Converts external scripts and stylesheets into embedded ones.', -> done = @async() @files.forEach (file) => srcFile = file.orig.src if typeof srcFile isnt 'string' if srcFile.length > 1 grunt.log.warn 'Multiple source files supplied; only the first will be used.' srcFile = srcFile[0] if not grunt.file.exists srcFile grunt.log.warn "Source file \"#{path.resolve(srcFile)}\" not found." else embedder = new ResourceEmbedder srcFile, @options() embedder.get (output, warnings) -> grunt.file.write file.dest, output if warnings? grunt.log.warn warning for warning in warnings grunt.log.ok "File \"#{file.dest}\" created." done()
[ { "context": "###\nnote.coffee\nCopyright (C) 2015 ender xu <xuender@gmail.com>\n\nDistributed under terms of t", "end": 43, "score": 0.9997044205665588, "start": 35, "tag": "NAME", "value": "ender xu" }, { "context": "###\nnote.coffee\nCopyright (C) 2015 ender xu <xuender@gmail.com>...
src/note/note.coffee
xuender/mindfulness
0
### note.coffee Copyright (C) 2015 ender xu <xuender@gmail.com> Distributed under terms of the MIT license. ### app.config(['$stateProvider', '$urlRouterProvider', ($stateProvider, $urlRouterProvider)-> $urlRouterProvider.otherwise("/book") $stateProvider .state('book', url: '/book' templateUrl: 'partials/note/books.html?2.html' controller: BooksCtrl ) .state('section', url: '/section' templateUrl: 'partials/note/sections.html?1.html' controller: SectionsCtrl ) .state('view', url: '/view/:sid' templateUrl: 'partials/note/section_view.html?1.html' controller: SectionViewCtrl ) ])
98938
### note.coffee Copyright (C) 2015 <NAME> <<EMAIL>> Distributed under terms of the MIT license. ### app.config(['$stateProvider', '$urlRouterProvider', ($stateProvider, $urlRouterProvider)-> $urlRouterProvider.otherwise("/book") $stateProvider .state('book', url: '/book' templateUrl: 'partials/note/books.html?2.html' controller: BooksCtrl ) .state('section', url: '/section' templateUrl: 'partials/note/sections.html?1.html' controller: SectionsCtrl ) .state('view', url: '/view/:sid' templateUrl: 'partials/note/section_view.html?1.html' controller: SectionViewCtrl ) ])
true
### note.coffee Copyright (C) 2015 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> Distributed under terms of the MIT license. ### app.config(['$stateProvider', '$urlRouterProvider', ($stateProvider, $urlRouterProvider)-> $urlRouterProvider.otherwise("/book") $stateProvider .state('book', url: '/book' templateUrl: 'partials/note/books.html?2.html' controller: BooksCtrl ) .state('section', url: '/section' templateUrl: 'partials/note/sections.html?1.html' controller: SectionsCtrl ) .state('view', url: '/view/:sid' templateUrl: 'partials/note/section_view.html?1.html' controller: SectionViewCtrl ) ])
[ { "context": "-*-\n\n# Filename: converter.coffee\n# Created by 请叫我喵 Alynx.\n# alynx.zhou@gmail.com, http://alynx.xyz/\n", "end": 92, "score": 0.5298528671264648, "start": 91, "tag": "NAME", "value": "喵" }, { "context": "*-\n\n# Filename: converter.coffee\n# Created by 请叫我喵 Alynx.\n#...
lib/converter.coffee
AlynxZhou/atom-code-music
7
#!/usr/bin/env coffee #-*- coding: utf-8 -*- # Filename: converter.coffee # Created by 请叫我喵 Alynx. # alynx.zhou@gmail.com, http://alynx.xyz/ fs = require("fs") path = require("path") NOT_COMMENT = 0 SINGLE_COMMENT = 1 MULTI_COMMENT = 2 class Converter constructor: (@oldEditor, @newEditor) -> @validArr = [ ' ', '\r', '\n', '\t', '|', '(', ')', '{', '}', '[', ']', \ '<', '>', '0', '1', '2', '3', '4', '5', '6', '7', '#1', \ '#2', '#3', '#4', '#5', '#6', '#7' ] @keySeq = [ '(1)', '(#1)', '(2)', '(#2)', '(3)', '(4)', '(#4)', '(5)', '(#5)', \ '(6)', '(#6)', '(7)', '1', '#1', '2', '#2', '3', '4', '#4', '5', '#5', \ '6', '#6', '7', '[1]', '[#1]', '[2]', '[#2]', '[3]', '[4]', '[#4]', \ '[5]', '[#5]', '[6]', '[#6]', '[7]', '{1}', '{#1}', '{2}', '{#2}', \ '{3}', '{4}', '{#4}', '{5}', '{#5}', '{6}', '{#6}', '{7}' ] @digits = ['1', '2', '3', '4', '5', '6', '7'] @blankArray = ['\n', '\r', '\t', ' '] @digitsNotes = JSON.parse( fs.readFileSync(path.join(__dirname, "digits-notes.json")) ) @line = '' @lineNum = 0 @bracketObject = '(': ')' '[': ']' '{': '}' '': '' # Keep this line! @bracketStatus = '' @commentStatus = NOT_COMMENT @chordStatus = false @chordArray = [] @noteArray = [] @rebuildLine = '' @finalJSON = [] tokenSplit: () => i = 0 while i < @line.length switch @commentStatus when SINGLE_COMMENT @chordArray[@chordArray.length - 1] += @line.charAt(i) if @line.charAt(i) is '\n' or i is @line.length - 1 @commentStatus = NOT_COMMENT if not @chordStatus @noteArray.push(@chordArray) @chordArray = [] i++ continue when MULTI_COMMENT @chordArray[@chordArray.length - 1] += @line.charAt(i) if @line.charAt(i) is '*' and @line.charAt(i + 1) is ';' @chordArray[@chordArray.length - 1] += @line.charAt(++i) @commentStatus = NOT_COMMENT if not @chordStatus @noteArray.push(@chordArray) @chordArray = [] i++ continue if @line.charAt(i) in @digits @chordArray.push(@bracketStatus + @line.charAt(i) + \ @bracketObject[@bracketStatus]) else if @line.charAt(i) is '#' and @line.charAt(i + 1) in @digits @chordArray.push(@bracketStatus + @line.charAt(i) + \ @line.charAt(++i) + @bracketObject[@bracketStatus]) else if @line.charAt(i) is ';' and @line.charAt(i + 1) is ';' @chordArray.push(@line.charAt(i) + @line.charAt(++i)) @commentStatus = SINGLE_COMMENT else if @line.charAt(i) is ';' and @line.charAt(i + 1) is '*' @chordArray.push(@line.charAt(i) + @line.charAt(++i)) @commentStatus = MULTI_COMMENT else if @line.charAt(i) in @blankArray @chordArray.push(@line.charAt(i)) else if @line.charAt(i) is @bracketObject[@bracketStatus] @bracketStatus = '' else if @line.charAt(i) of @bracketObject @bracketStatus = @line.charAt(i) else if @line.charAt(i) is '<' @chordStatus = true else if @line.charAt(i) is '>' @chordStatus = false else throw new Error("Error: Invalid character `#{@line.charAt(i)}` \ at Line #{@lineNum + 1}, Column #{i + 1}.") if @chordArray.length > 0 and not @chordStatus and \ @commentStatus is NOT_COMMENT @noteArray.push(@chordArray) @chordArray = [] i++ fixKey: () => i = 0 while i < @noteArray.length switch @noteArray[i] when '(#3)' then @noteArray[i] = '(4)' when '(#7)' then @noteArray[i] = '1' when '#3' then @noteArray[i] = '4' when '#7' then @noteArray[i] = '[1]' when '[#3]' then @noteArray[i] = '[4]' when '[#7]' then @noteArray[i] = '{1}' when '{#3}' then @noteArray[i] = '{4}' i++ moveKey: (moveStep) => i = 0 while i < @noteArray.length if @keySeq.indexOf(@noteArray[i]) isnt -1 if @keySeq.indexOf(@noteArray[i]) + moveStep \ in [0...@keySeq.length] @noteArray[i] = @keySeq[@keySeq.indexOf(@noteArray[i]) + \ moveStep] else throw new Error("Error: Cannot move #{@noteArray[i]} \ with #{moveStep} steps.") i++ checkBlank: (chordArray) => count = 0 for note in chordArray if note in @blankArray count++ return count buildJSON: () => for chord in @noteArray chordArray = [] for digit in chord if digit in @keySeq note = {"timbre": "", "pitch": "", "loudness": 1} try note["pitch"] = @digitsNotes[digit] catch e note["pitch"] = "" note["loudness"] = 1 / chord.length chordArray.push(note) if chordArray.length @finalJSON.push(chordArray) convert: () => lineCount = @oldEditor.getLineCount() while @lineNum < lineCount try @line = @oldEditor.lineTextForBufferRow(@lineNum) @tokenSplit() @fixKey() if commander.move? and commander.move isnt 0 @moveKey(commander.move) if @commentStatus isnt MULTI_COMMENT and not @chordStatus @buildJSON() @noteArray = [] @lineNum++ catch error console.error(error) if commander.move? and commander.move isnt 0 @moveKey(commander.move) if @commentStatus isnt MULTI_COMMENT and not @chordStatus @noteArray = [] @lineNum++ @newEditor.insertText(JSON.stringify(@finalJSON, null, " ")) module.exports = Converter
177579
#!/usr/bin/env coffee #-*- coding: utf-8 -*- # Filename: converter.coffee # Created by 请叫我<NAME> <NAME>. # <EMAIL>, http://alynx.xyz/ fs = require("fs") path = require("path") NOT_COMMENT = 0 SINGLE_COMMENT = 1 MULTI_COMMENT = 2 class Converter constructor: (@oldEditor, @newEditor) -> @validArr = [ ' ', '\r', '\n', '\t', '|', '(', ')', '{', '}', '[', ']', \ '<', '>', '0', '1', '2', '3', '4', '5', '6', '7', '#1', \ '#2', '#3', '#4', '#5', '#6', '#7' ] @keySeq = [ '(1)', '(#1)', '(2)', '(#2)', '(3)', '(4)', '(#4)', '(5)', '(#5)', \ '(6)', '(#6)', '(7)', '1', '#1', '2', '#2', '3', '4', '#4', '5', '#5', \ '6', '#6', '7', '[1]', '[#1]', '[2]', '[#2]', '[3]', '[4]', '[#4]', \ '[5]', '[#5]', '[6]', '[#6]', '[7]', '{1}', '{#1}', '{2}', '{#2}', \ '{3}', '{4}', '{#4}', '{5}', '{#5}', '{6}', '{#6}', '{7}' ] @digits = ['1', '2', '3', '4', '5', '6', '7'] @blankArray = ['\n', '\r', '\t', ' '] @digitsNotes = JSON.parse( fs.readFileSync(path.join(__dirname, "digits-notes.json")) ) @line = '' @lineNum = 0 @bracketObject = '(': ')' '[': ']' '{': '}' '': '' # Keep this line! @bracketStatus = '' @commentStatus = NOT_COMMENT @chordStatus = false @chordArray = [] @noteArray = [] @rebuildLine = '' @finalJSON = [] tokenSplit: () => i = 0 while i < @line.length switch @commentStatus when SINGLE_COMMENT @chordArray[@chordArray.length - 1] += @line.charAt(i) if @line.charAt(i) is '\n' or i is @line.length - 1 @commentStatus = NOT_COMMENT if not @chordStatus @noteArray.push(@chordArray) @chordArray = [] i++ continue when MULTI_COMMENT @chordArray[@chordArray.length - 1] += @line.charAt(i) if @line.charAt(i) is '*' and @line.charAt(i + 1) is ';' @chordArray[@chordArray.length - 1] += @line.charAt(++i) @commentStatus = NOT_COMMENT if not @chordStatus @noteArray.push(@chordArray) @chordArray = [] i++ continue if @line.charAt(i) in @digits @chordArray.push(@bracketStatus + @line.charAt(i) + \ @bracketObject[@bracketStatus]) else if @line.charAt(i) is '#' and @line.charAt(i + 1) in @digits @chordArray.push(@bracketStatus + @line.charAt(i) + \ @line.charAt(++i) + @bracketObject[@bracketStatus]) else if @line.charAt(i) is ';' and @line.charAt(i + 1) is ';' @chordArray.push(@line.charAt(i) + @line.charAt(++i)) @commentStatus = SINGLE_COMMENT else if @line.charAt(i) is ';' and @line.charAt(i + 1) is '*' @chordArray.push(@line.charAt(i) + @line.charAt(++i)) @commentStatus = MULTI_COMMENT else if @line.charAt(i) in @blankArray @chordArray.push(@line.charAt(i)) else if @line.charAt(i) is @bracketObject[@bracketStatus] @bracketStatus = '' else if @line.charAt(i) of @bracketObject @bracketStatus = @line.charAt(i) else if @line.charAt(i) is '<' @chordStatus = true else if @line.charAt(i) is '>' @chordStatus = false else throw new Error("Error: Invalid character `#{@line.charAt(i)}` \ at Line #{@lineNum + 1}, Column #{i + 1}.") if @chordArray.length > 0 and not @chordStatus and \ @commentStatus is NOT_COMMENT @noteArray.push(@chordArray) @chordArray = [] i++ fixKey: () => i = 0 while i < @noteArray.length switch @noteArray[i] when '(#3)' then @noteArray[i] = '(4)' when '(#7)' then @noteArray[i] = '1' when '#3' then @noteArray[i] = '4' when '#7' then @noteArray[i] = '[1]' when '[#3]' then @noteArray[i] = '[4]' when '[#7]' then @noteArray[i] = '{1}' when '{#3}' then @noteArray[i] = '{4}' i++ moveKey: (moveStep) => i = 0 while i < @noteArray.length if @keySeq.indexOf(@noteArray[i]) isnt -1 if @keySeq.indexOf(@noteArray[i]) + moveStep \ in [0...@keySeq.length] @noteArray[i] = @keySeq[@keySeq.indexOf(@noteArray[i]) + \ moveStep] else throw new Error("Error: Cannot move #{@noteArray[i]} \ with #{moveStep} steps.") i++ checkBlank: (chordArray) => count = 0 for note in chordArray if note in @blankArray count++ return count buildJSON: () => for chord in @noteArray chordArray = [] for digit in chord if digit in @keySeq note = {"timbre": "", "pitch": "", "loudness": 1} try note["pitch"] = @digitsNotes[digit] catch e note["pitch"] = "" note["loudness"] = 1 / chord.length chordArray.push(note) if chordArray.length @finalJSON.push(chordArray) convert: () => lineCount = @oldEditor.getLineCount() while @lineNum < lineCount try @line = @oldEditor.lineTextForBufferRow(@lineNum) @tokenSplit() @fixKey() if commander.move? and commander.move isnt 0 @moveKey(commander.move) if @commentStatus isnt MULTI_COMMENT and not @chordStatus @buildJSON() @noteArray = [] @lineNum++ catch error console.error(error) if commander.move? and commander.move isnt 0 @moveKey(commander.move) if @commentStatus isnt MULTI_COMMENT and not @chordStatus @noteArray = [] @lineNum++ @newEditor.insertText(JSON.stringify(@finalJSON, null, " ")) module.exports = Converter
true
#!/usr/bin/env coffee #-*- coding: utf-8 -*- # Filename: converter.coffee # Created by 请叫我PI:NAME:<NAME>END_PI PI:NAME:<NAME>END_PI. # PI:EMAIL:<EMAIL>END_PI, http://alynx.xyz/ fs = require("fs") path = require("path") NOT_COMMENT = 0 SINGLE_COMMENT = 1 MULTI_COMMENT = 2 class Converter constructor: (@oldEditor, @newEditor) -> @validArr = [ ' ', '\r', '\n', '\t', '|', '(', ')', '{', '}', '[', ']', \ '<', '>', '0', '1', '2', '3', '4', '5', '6', '7', '#1', \ '#2', '#3', '#4', '#5', '#6', '#7' ] @keySeq = [ '(1)', '(#1)', '(2)', '(#2)', '(3)', '(4)', '(#4)', '(5)', '(#5)', \ '(6)', '(#6)', '(7)', '1', '#1', '2', '#2', '3', '4', '#4', '5', '#5', \ '6', '#6', '7', '[1]', '[#1]', '[2]', '[#2]', '[3]', '[4]', '[#4]', \ '[5]', '[#5]', '[6]', '[#6]', '[7]', '{1}', '{#1}', '{2}', '{#2}', \ '{3}', '{4}', '{#4}', '{5}', '{#5}', '{6}', '{#6}', '{7}' ] @digits = ['1', '2', '3', '4', '5', '6', '7'] @blankArray = ['\n', '\r', '\t', ' '] @digitsNotes = JSON.parse( fs.readFileSync(path.join(__dirname, "digits-notes.json")) ) @line = '' @lineNum = 0 @bracketObject = '(': ')' '[': ']' '{': '}' '': '' # Keep this line! @bracketStatus = '' @commentStatus = NOT_COMMENT @chordStatus = false @chordArray = [] @noteArray = [] @rebuildLine = '' @finalJSON = [] tokenSplit: () => i = 0 while i < @line.length switch @commentStatus when SINGLE_COMMENT @chordArray[@chordArray.length - 1] += @line.charAt(i) if @line.charAt(i) is '\n' or i is @line.length - 1 @commentStatus = NOT_COMMENT if not @chordStatus @noteArray.push(@chordArray) @chordArray = [] i++ continue when MULTI_COMMENT @chordArray[@chordArray.length - 1] += @line.charAt(i) if @line.charAt(i) is '*' and @line.charAt(i + 1) is ';' @chordArray[@chordArray.length - 1] += @line.charAt(++i) @commentStatus = NOT_COMMENT if not @chordStatus @noteArray.push(@chordArray) @chordArray = [] i++ continue if @line.charAt(i) in @digits @chordArray.push(@bracketStatus + @line.charAt(i) + \ @bracketObject[@bracketStatus]) else if @line.charAt(i) is '#' and @line.charAt(i + 1) in @digits @chordArray.push(@bracketStatus + @line.charAt(i) + \ @line.charAt(++i) + @bracketObject[@bracketStatus]) else if @line.charAt(i) is ';' and @line.charAt(i + 1) is ';' @chordArray.push(@line.charAt(i) + @line.charAt(++i)) @commentStatus = SINGLE_COMMENT else if @line.charAt(i) is ';' and @line.charAt(i + 1) is '*' @chordArray.push(@line.charAt(i) + @line.charAt(++i)) @commentStatus = MULTI_COMMENT else if @line.charAt(i) in @blankArray @chordArray.push(@line.charAt(i)) else if @line.charAt(i) is @bracketObject[@bracketStatus] @bracketStatus = '' else if @line.charAt(i) of @bracketObject @bracketStatus = @line.charAt(i) else if @line.charAt(i) is '<' @chordStatus = true else if @line.charAt(i) is '>' @chordStatus = false else throw new Error("Error: Invalid character `#{@line.charAt(i)}` \ at Line #{@lineNum + 1}, Column #{i + 1}.") if @chordArray.length > 0 and not @chordStatus and \ @commentStatus is NOT_COMMENT @noteArray.push(@chordArray) @chordArray = [] i++ fixKey: () => i = 0 while i < @noteArray.length switch @noteArray[i] when '(#3)' then @noteArray[i] = '(4)' when '(#7)' then @noteArray[i] = '1' when '#3' then @noteArray[i] = '4' when '#7' then @noteArray[i] = '[1]' when '[#3]' then @noteArray[i] = '[4]' when '[#7]' then @noteArray[i] = '{1}' when '{#3}' then @noteArray[i] = '{4}' i++ moveKey: (moveStep) => i = 0 while i < @noteArray.length if @keySeq.indexOf(@noteArray[i]) isnt -1 if @keySeq.indexOf(@noteArray[i]) + moveStep \ in [0...@keySeq.length] @noteArray[i] = @keySeq[@keySeq.indexOf(@noteArray[i]) + \ moveStep] else throw new Error("Error: Cannot move #{@noteArray[i]} \ with #{moveStep} steps.") i++ checkBlank: (chordArray) => count = 0 for note in chordArray if note in @blankArray count++ return count buildJSON: () => for chord in @noteArray chordArray = [] for digit in chord if digit in @keySeq note = {"timbre": "", "pitch": "", "loudness": 1} try note["pitch"] = @digitsNotes[digit] catch e note["pitch"] = "" note["loudness"] = 1 / chord.length chordArray.push(note) if chordArray.length @finalJSON.push(chordArray) convert: () => lineCount = @oldEditor.getLineCount() while @lineNum < lineCount try @line = @oldEditor.lineTextForBufferRow(@lineNum) @tokenSplit() @fixKey() if commander.move? and commander.move isnt 0 @moveKey(commander.move) if @commentStatus isnt MULTI_COMMENT and not @chordStatus @buildJSON() @noteArray = [] @lineNum++ catch error console.error(error) if commander.move? and commander.move isnt 0 @moveKey(commander.move) if @commentStatus isnt MULTI_COMMENT and not @chordStatus @noteArray = [] @lineNum++ @newEditor.insertText(JSON.stringify(@finalJSON, null, " ")) module.exports = Converter
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9979360699653625, "start": 12, "tag": "NAME", "value": "Joyent" }, { "context": "Nov 6 09:52:22 2029 GMT\\\",\" + \"\\\"fingerprint\\\":\\\"2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7...
test/disabled/test-net-tls.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") fs = require("fs") net = require("net") have_openssl = undefined try crypto = require("crypto") have_openssl = true catch e have_openssl = false console.log "Not compiled with OPENSSL support." process.exit() caPem = fs.readFileSync(common.fixturesDir + "/test_ca.pem", "ascii") certPem = fs.readFileSync(common.fixturesDir + "/test_cert.pem", "ascii") keyPem = fs.readFileSync(common.fixturesDir + "/test_key.pem", "ascii") try credentials = crypto.createCredentials( key: keyPem cert: certPem ca: caPem ) catch e console.log "Not compiled with OPENSSL support." process.exit() testData = "TEST123" serverData = "" clientData = "" gotSecureServer = false gotSecureClient = false secureServer = net.createServer((connection) -> self = this connection.setSecure credentials connection.setEncoding "UTF8" connection.on "secure", -> gotSecureServer = true verified = connection.verifyPeer() peerDN = JSON.stringify(connection.getPeerCertificate()) assert.equal verified, true assert.equal peerDN, "{\"subject\":\"/C=UK/ST=Acknack Ltd/L=Rhys Jones" + "/O=node.js/OU=Test TLS Certificate/CN=localhost\"," + "\"issuer\":\"/C=UK/ST=Acknack Ltd/L=Rhys Jones/O=node.js" + "/OU=Test TLS Certificate/CN=localhost\"," + "\"valid_from\":\"Nov 11 09:52:22 2009 GMT\"," + "\"valid_to\":\"Nov 6 09:52:22 2029 GMT\"," + "\"fingerprint\":\"2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:" + "5A:71:38:52:EC:8A:DF\"}" return connection.on "data", (chunk) -> serverData += chunk connection.write chunk return connection.on "end", -> assert.equal serverData, testData connection.end() self.close() return return ) secureServer.listen common.PORT secureServer.on "listening", -> secureClient = net.createConnection(common.PORT) secureClient.setEncoding "UTF8" secureClient.on "connect", -> secureClient.setSecure credentials return secureClient.on "secure", -> gotSecureClient = true verified = secureClient.verifyPeer() peerDN = JSON.stringify(secureClient.getPeerCertificate()) assert.equal verified, true assert.equal peerDN, "{\"subject\":\"/C=UK/ST=Acknack Ltd/L=Rhys Jones" + "/O=node.js/OU=Test TLS Certificate/CN=localhost\"," + "\"issuer\":\"/C=UK/ST=Acknack Ltd/L=Rhys Jones/O=node.js" + "/OU=Test TLS Certificate/CN=localhost\"," + "\"valid_from\":\"Nov 11 09:52:22 2009 GMT\"," + "\"valid_to\":\"Nov 6 09:52:22 2029 GMT\"," + "\"fingerprint\":\"2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:" + "5A:71:38:52:EC:8A:DF\"}" secureClient.write testData secureClient.end() return secureClient.on "data", (chunk) -> clientData += chunk return secureClient.on "end", -> assert.equal clientData, testData return return process.on "exit", -> assert.ok gotSecureServer, "Did not get secure event for server" assert.ok gotSecureClient, "Did not get secure event for client" return
190191
# 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") fs = require("fs") net = require("net") have_openssl = undefined try crypto = require("crypto") have_openssl = true catch e have_openssl = false console.log "Not compiled with OPENSSL support." process.exit() caPem = fs.readFileSync(common.fixturesDir + "/test_ca.pem", "ascii") certPem = fs.readFileSync(common.fixturesDir + "/test_cert.pem", "ascii") keyPem = fs.readFileSync(common.fixturesDir + "/test_key.pem", "ascii") try credentials = crypto.createCredentials( key: keyPem cert: certPem ca: caPem ) catch e console.log "Not compiled with OPENSSL support." process.exit() testData = "TEST123" serverData = "" clientData = "" gotSecureServer = false gotSecureClient = false secureServer = net.createServer((connection) -> self = this connection.setSecure credentials connection.setEncoding "UTF8" connection.on "secure", -> gotSecureServer = true verified = connection.verifyPeer() peerDN = JSON.stringify(connection.getPeerCertificate()) assert.equal verified, true assert.equal peerDN, "{\"subject\":\"/C=UK/ST=Acknack Ltd/L=Rhys Jones" + "/O=node.js/OU=Test TLS Certificate/CN=localhost\"," + "\"issuer\":\"/C=UK/ST=Acknack Ltd/L=Rhys Jones/O=node.js" + "/OU=Test TLS Certificate/CN=localhost\"," + "\"valid_from\":\"Nov 11 09:52:22 2009 GMT\"," + "\"valid_to\":\"Nov 6 09:52:22 2029 GMT\"," + "\"fingerprint\":\"2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:" + "5A:71:38:52:EC:8A:DF\"}" return connection.on "data", (chunk) -> serverData += chunk connection.write chunk return connection.on "end", -> assert.equal serverData, testData connection.end() self.close() return return ) secureServer.listen common.PORT secureServer.on "listening", -> secureClient = net.createConnection(common.PORT) secureClient.setEncoding "UTF8" secureClient.on "connect", -> secureClient.setSecure credentials return secureClient.on "secure", -> gotSecureClient = true verified = secureClient.verifyPeer() peerDN = JSON.stringify(secureClient.getPeerCertificate()) assert.equal verified, true assert.equal peerDN, "{\"subject\":\"/C=UK/ST=Acknack Ltd/L=Rhys Jones" + "/O=node.js/OU=Test TLS Certificate/CN=localhost\"," + "\"issuer\":\"/C=UK/ST=Acknack Ltd/L=Rhys Jones/O=node.js" + "/OU=Test TLS Certificate/CN=localhost\"," + "\"valid_from\":\"Nov 11 09:52:22 2009 GMT\"," + "\"valid_to\":\"Nov 6 09:52:22 2029 GMT\"," + "\"fingerprint\":\"fc00:e968:6179::de52:7100:72:35:99:7A:02:" + "5A:71:38:52:EC:8A:DF\"}" secureClient.write testData secureClient.end() return secureClient.on "data", (chunk) -> clientData += chunk return secureClient.on "end", -> assert.equal clientData, testData return return process.on "exit", -> assert.ok gotSecureServer, "Did not get secure event for server" assert.ok gotSecureClient, "Did not get secure event for client" 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") fs = require("fs") net = require("net") have_openssl = undefined try crypto = require("crypto") have_openssl = true catch e have_openssl = false console.log "Not compiled with OPENSSL support." process.exit() caPem = fs.readFileSync(common.fixturesDir + "/test_ca.pem", "ascii") certPem = fs.readFileSync(common.fixturesDir + "/test_cert.pem", "ascii") keyPem = fs.readFileSync(common.fixturesDir + "/test_key.pem", "ascii") try credentials = crypto.createCredentials( key: keyPem cert: certPem ca: caPem ) catch e console.log "Not compiled with OPENSSL support." process.exit() testData = "TEST123" serverData = "" clientData = "" gotSecureServer = false gotSecureClient = false secureServer = net.createServer((connection) -> self = this connection.setSecure credentials connection.setEncoding "UTF8" connection.on "secure", -> gotSecureServer = true verified = connection.verifyPeer() peerDN = JSON.stringify(connection.getPeerCertificate()) assert.equal verified, true assert.equal peerDN, "{\"subject\":\"/C=UK/ST=Acknack Ltd/L=Rhys Jones" + "/O=node.js/OU=Test TLS Certificate/CN=localhost\"," + "\"issuer\":\"/C=UK/ST=Acknack Ltd/L=Rhys Jones/O=node.js" + "/OU=Test TLS Certificate/CN=localhost\"," + "\"valid_from\":\"Nov 11 09:52:22 2009 GMT\"," + "\"valid_to\":\"Nov 6 09:52:22 2029 GMT\"," + "\"fingerprint\":\"2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:" + "5A:71:38:52:EC:8A:DF\"}" return connection.on "data", (chunk) -> serverData += chunk connection.write chunk return connection.on "end", -> assert.equal serverData, testData connection.end() self.close() return return ) secureServer.listen common.PORT secureServer.on "listening", -> secureClient = net.createConnection(common.PORT) secureClient.setEncoding "UTF8" secureClient.on "connect", -> secureClient.setSecure credentials return secureClient.on "secure", -> gotSecureClient = true verified = secureClient.verifyPeer() peerDN = JSON.stringify(secureClient.getPeerCertificate()) assert.equal verified, true assert.equal peerDN, "{\"subject\":\"/C=UK/ST=Acknack Ltd/L=Rhys Jones" + "/O=node.js/OU=Test TLS Certificate/CN=localhost\"," + "\"issuer\":\"/C=UK/ST=Acknack Ltd/L=Rhys Jones/O=node.js" + "/OU=Test TLS Certificate/CN=localhost\"," + "\"valid_from\":\"Nov 11 09:52:22 2009 GMT\"," + "\"valid_to\":\"Nov 6 09:52:22 2029 GMT\"," + "\"fingerprint\":\"PI:IP_ADDRESS:fc00:e968:6179::de52:7100END_PI:72:35:99:7A:02:" + "5A:71:38:52:EC:8A:DF\"}" secureClient.write testData secureClient.end() return secureClient.on "data", (chunk) -> clientData += chunk return secureClient.on "end", -> assert.equal clientData, testData return return process.on "exit", -> assert.ok gotSecureServer, "Did not get secure event for server" assert.ok gotSecureClient, "Did not get secure event for client" return
[ { "context": "rink - reduce and simplify vector and mbtiles\n by Michael Strassburger <codepoet@cpan.org>\n\n CLI interface for tileshri", "end": 83, "score": 0.999869704246521, "start": 63, "tag": "NAME", "value": "Michael Strassburger" }, { "context": "ify vector and mbtiles\n b...
src/cli.coffee
rastapasta/tileshrink
27
### tileshrink - reduce and simplify vector and mbtiles by Michael Strassburger <codepoet@cpan.org> CLI interface for tileshrink ### Shrinker = require "./Shrinker" TileGrinder = require "tilegrinder" commandLineArgs = require "command-line-args" getUsage = require "command-line-usage" args = [ name: "files" type: String multiple: true defaultOption: true , name: "extent", type: Number, defaultValue: 1024, typeLabel: "[underline]{pixel}" description: "desired extent of the new layers [deault: 1024]" , name: "precision", type: Number, defaultValue: 1, typeLabel: "[underline]{float}" description: "affects the level of simplification [deault: 1]" , name: "shrink" type: Number description: "maximal zoomlevel to apply the shrinking" typeLabel: "[underline]{zoom}" , name: "include" type: Number description: "maximal zoomlevel to import untouched layers from [optional]" typeLabel: "[underline]{zoom}" , name: "output" defaultValue: "mbtiles" type: String typeLabel: "[underline]{type}" description: "[underline]{mbtiles} ([bold]{default}) or [underline]{files}" , name: "help" description: "displays this help screen" ] help = [ header: "tileshrink", content: "Reduce and simplify Vector Tile features in an MBTiles container" , header: "Examples", content: [ "$ tileshrink [bold]{--shrink} 4 [underline]{input.mbtiles} [underline]{output.mbtiles}" "$ tileshrink [bold]{--shrink} 4 [bold]{--output} files [underline]{input.mbtiles} [underline]{/foor/bar/}" ] , header: "Options" optionList: args hide: "files" , content: [ "[italic]{made with ⠀❤⠀⠀at https://github.com/rastapasta/tileshrink}" ] raw: true ] try options = commandLineArgs args catch e console.log getUsage help console.log "ERROR: #{e}" if e process.exit 1 if e or options.help or not options.files or options.files.length isnt 2 or typeof options.extent isnt "number" or typeof options.precision isnt "number" or typeof options.shrink isnt "number" or options.output not in ["mbtiles", "files"] console.log getUsage help process.exit 0 shrinker = new Shrinker extent: options.extent precision: options.precision shrink: options.shrink include: options.include grinder = new TileGrinder maxZoom: if options.include then options.include else options.shrink output: options.output console.log getUsage [ header: "tileshrink" content: [ "[bold]{reducing} zoom levels [bold]{0 to #{options.shrink}} to [bold]{#{options.extent}x#{options.extent}}" "[bold]{simplifying} lines with an precision of #{options.precision}" if options.include then "[bold]{including} untouched layers of zoom levels [bold]{#{options.shrink+1} to #{options.include}}" else "" ] ] grinder.grind options.files[0], options.files[1], (tile, z, x, y) -> shrinker.shrink tile, z, x, y
160822
### tileshrink - reduce and simplify vector and mbtiles by <NAME> <<EMAIL>> CLI interface for tileshrink ### Shrinker = require "./Shrinker" TileGrinder = require "tilegrinder" commandLineArgs = require "command-line-args" getUsage = require "command-line-usage" args = [ name: "files" type: String multiple: true defaultOption: true , name: "extent", type: Number, defaultValue: 1024, typeLabel: "[underline]{pixel}" description: "desired extent of the new layers [deault: 1024]" , name: "precision", type: Number, defaultValue: 1, typeLabel: "[underline]{float}" description: "affects the level of simplification [deault: 1]" , name: "shrink" type: Number description: "maximal zoomlevel to apply the shrinking" typeLabel: "[underline]{zoom}" , name: "include" type: Number description: "maximal zoomlevel to import untouched layers from [optional]" typeLabel: "[underline]{zoom}" , name: "output" defaultValue: "mbtiles" type: String typeLabel: "[underline]{type}" description: "[underline]{mbtiles} ([bold]{default}) or [underline]{files}" , name: "help" description: "displays this help screen" ] help = [ header: "tileshrink", content: "Reduce and simplify Vector Tile features in an MBTiles container" , header: "Examples", content: [ "$ tileshrink [bold]{--shrink} 4 [underline]{input.mbtiles} [underline]{output.mbtiles}" "$ tileshrink [bold]{--shrink} 4 [bold]{--output} files [underline]{input.mbtiles} [underline]{/foor/bar/}" ] , header: "Options" optionList: args hide: "files" , content: [ "[italic]{made with ⠀❤⠀⠀at https://github.com/rastapasta/tileshrink}" ] raw: true ] try options = commandLineArgs args catch e console.log getUsage help console.log "ERROR: #{e}" if e process.exit 1 if e or options.help or not options.files or options.files.length isnt 2 or typeof options.extent isnt "number" or typeof options.precision isnt "number" or typeof options.shrink isnt "number" or options.output not in ["mbtiles", "files"] console.log getUsage help process.exit 0 shrinker = new Shrinker extent: options.extent precision: options.precision shrink: options.shrink include: options.include grinder = new TileGrinder maxZoom: if options.include then options.include else options.shrink output: options.output console.log getUsage [ header: "tileshrink" content: [ "[bold]{reducing} zoom levels [bold]{0 to #{options.shrink}} to [bold]{#{options.extent}x#{options.extent}}" "[bold]{simplifying} lines with an precision of #{options.precision}" if options.include then "[bold]{including} untouched layers of zoom levels [bold]{#{options.shrink+1} to #{options.include}}" else "" ] ] grinder.grind options.files[0], options.files[1], (tile, z, x, y) -> shrinker.shrink tile, z, x, y
true
### tileshrink - reduce and simplify vector and mbtiles by PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> CLI interface for tileshrink ### Shrinker = require "./Shrinker" TileGrinder = require "tilegrinder" commandLineArgs = require "command-line-args" getUsage = require "command-line-usage" args = [ name: "files" type: String multiple: true defaultOption: true , name: "extent", type: Number, defaultValue: 1024, typeLabel: "[underline]{pixel}" description: "desired extent of the new layers [deault: 1024]" , name: "precision", type: Number, defaultValue: 1, typeLabel: "[underline]{float}" description: "affects the level of simplification [deault: 1]" , name: "shrink" type: Number description: "maximal zoomlevel to apply the shrinking" typeLabel: "[underline]{zoom}" , name: "include" type: Number description: "maximal zoomlevel to import untouched layers from [optional]" typeLabel: "[underline]{zoom}" , name: "output" defaultValue: "mbtiles" type: String typeLabel: "[underline]{type}" description: "[underline]{mbtiles} ([bold]{default}) or [underline]{files}" , name: "help" description: "displays this help screen" ] help = [ header: "tileshrink", content: "Reduce and simplify Vector Tile features in an MBTiles container" , header: "Examples", content: [ "$ tileshrink [bold]{--shrink} 4 [underline]{input.mbtiles} [underline]{output.mbtiles}" "$ tileshrink [bold]{--shrink} 4 [bold]{--output} files [underline]{input.mbtiles} [underline]{/foor/bar/}" ] , header: "Options" optionList: args hide: "files" , content: [ "[italic]{made with ⠀❤⠀⠀at https://github.com/rastapasta/tileshrink}" ] raw: true ] try options = commandLineArgs args catch e console.log getUsage help console.log "ERROR: #{e}" if e process.exit 1 if e or options.help or not options.files or options.files.length isnt 2 or typeof options.extent isnt "number" or typeof options.precision isnt "number" or typeof options.shrink isnt "number" or options.output not in ["mbtiles", "files"] console.log getUsage help process.exit 0 shrinker = new Shrinker extent: options.extent precision: options.precision shrink: options.shrink include: options.include grinder = new TileGrinder maxZoom: if options.include then options.include else options.shrink output: options.output console.log getUsage [ header: "tileshrink" content: [ "[bold]{reducing} zoom levels [bold]{0 to #{options.shrink}} to [bold]{#{options.extent}x#{options.extent}}" "[bold]{simplifying} lines with an precision of #{options.precision}" if options.include then "[bold]{including} untouched layers of zoom levels [bold]{#{options.shrink+1} to #{options.include}}" else "" ] ] grinder.grind options.files[0], options.files[1], (tile, z, x, y) -> shrinker.shrink tile, z, x, y
[ { "context": "ile Contents - Atom package\n * https://github.com/lieko/atom-copy-file-contents\n *\n * Copyright 2015, Eve", "end": 68, "score": 0.9993736743927002, "start": 63, "tag": "USERNAME", "value": "lieko" }, { "context": "ieko/atom-copy-file-contents\n *\n * Copyright 2015, ...
lib/copy-file-contents.coffee
lieko/atom-copy-file-content
1
### * Copy File Contents - Atom package * https://github.com/lieko/atom-copy-file-contents * * Copyright 2015, Everton Agner Ramos * https://github.com/lieko * * Licensed under the MIT license: * http://opensource.org/licenses/MIT ### copy = (filepath) -> platform = require('os').platform() switch platform when 'win32' command = "clip < #{filepath}" when 'darwin' command = "cat #{filepath} | pbcopy" else command = "xclip -i -selection c \"#{filepath}\"" console.log "[copy-file-contents][#{platform}] copy() filepath=\"#{filepath}\"" require('child_process').exec command module.exports = activate: (state) -> atom.commands.add '.tree-view .selected', 'copy-file-contents:copy': (event) -> copy @getPath?() || @getModel?().getPath?()
11218
### * Copy File Contents - Atom package * https://github.com/lieko/atom-copy-file-contents * * Copyright 2015, <NAME> * https://github.com/lieko * * Licensed under the MIT license: * http://opensource.org/licenses/MIT ### copy = (filepath) -> platform = require('os').platform() switch platform when 'win32' command = "clip < #{filepath}" when 'darwin' command = "cat #{filepath} | pbcopy" else command = "xclip -i -selection c \"#{filepath}\"" console.log "[copy-file-contents][#{platform}] copy() filepath=\"#{filepath}\"" require('child_process').exec command module.exports = activate: (state) -> atom.commands.add '.tree-view .selected', 'copy-file-contents:copy': (event) -> copy @getPath?() || @getModel?().getPath?()
true
### * Copy File Contents - Atom package * https://github.com/lieko/atom-copy-file-contents * * Copyright 2015, PI:NAME:<NAME>END_PI * https://github.com/lieko * * Licensed under the MIT license: * http://opensource.org/licenses/MIT ### copy = (filepath) -> platform = require('os').platform() switch platform when 'win32' command = "clip < #{filepath}" when 'darwin' command = "cat #{filepath} | pbcopy" else command = "xclip -i -selection c \"#{filepath}\"" console.log "[copy-file-contents][#{platform}] copy() filepath=\"#{filepath}\"" require('child_process').exec command module.exports = activate: (state) -> atom.commands.add '.tree-view .selected', 'copy-file-contents:copy': (event) -> copy @getPath?() || @getModel?().getPath?()
[ { "context": "gin.Permissions(annotator.element, {\n# user: 'Alice'\n# })\n#\n# Returns a new instance of the Permiss", "end": 433, "score": 0.9226973652839661, "start": 428, "tag": "USERNAME", "value": "Alice" }, { "context": "he\n # current user, i.e. @options.userI...
inception-html-editor/src/main/js/annotatorjs/src/plugin/permissions.coffee
CPHI-TVHS/inception
377
# Public: Plugin for setting permissions on newly created annotations as well as # managing user permissions such as viewing/editing/deleting annotions. # # element - A DOM Element upon which events are bound. When initialised by # the Annotator it is the Annotator element. # options - An Object literal containing custom options. # # Examples # # new Annotator.plugin.Permissions(annotator.element, { # user: 'Alice' # }) # # Returns a new instance of the Permissions Object. class Annotator.Plugin.Permissions extends Annotator.Plugin # A Object literal consisting of event/method pairs to be bound to # @element. See Delegator#addEvents() for details. events: 'beforeAnnotationCreated': 'addFieldsToAnnotation' # A Object literal of default options for the class. options: # Displays an "Anyone can view this annotation" checkbox in the Editor. showViewPermissionsCheckbox: true # Displays an "Anyone can edit this annotation" checkbox in the Editor. showEditPermissionsCheckbox: true # Public: Used by the plugin to determine a unique id for the @user property. # By default this accepts and returns the user String but can be over- # ridden in the @options object passed into the constructor. # # user - A String username or null if no user is set. # # Returns the String provided as user object. userId: (user) -> user # Public: Used by the plugin to determine a display name for the @user # property. By default this accepts and returns the user String but can be # over-ridden in the @options object passed into the constructor. # # user - A String username or null if no user is set. # # Returns the String provided as user object userString: (user) -> user # Public: Used by Permissions#authorize to determine whether a user can # perform an action on an annotation. Overriding this function allows # a far more complex permissions sysyem. # # By default this authorizes the action if any of three scenarios are true: # # 1) the annotation has a 'permissions' object, and either the field for # the specified action is missing, empty, or contains the userId of the # current user, i.e. @options.userId(@user) # # 2) the annotation has a 'user' property, and @options.userId(@user) matches # 'annotation.user' # # 3) the annotation has no 'permissions' or 'user' properties # # annotation - The annotation on which the action is being requested. # action - The action being requested: e.g. 'update', 'delete'. # user - The user object (or string) requesting the action. This is usually # automatically passed by Permissions#authorize as the current user (@user) # # permissions.setUser(null) # permissions.authorize('update', {}) # # => true # # permissions.setUser('alice') # permissions.authorize('update', {user: 'alice'}) # # => true # permissions.authorize('update', {user: 'bob'}) # # => false # # permissions.setUser('alice') # permissions.authorize('update', { # user: 'bob', # permissions: ['update': ['alice', 'bob']] # }) # # => true # permissions.authorize('destroy', { # user: 'bob', # permissions: [ # 'update': ['alice', 'bob'] # 'destroy': ['bob'] # ] # }) # # => false # # Returns a Boolean, true if the user is authorised for the token provided. userAuthorize: (action, annotation, user) -> # Fine-grained custom authorization if annotation.permissions tokens = annotation.permissions[action] || [] if tokens.length == 0 # Empty or missing tokens array: anyone can perform action. return true for token in tokens if this.userId(user) == token return true # No tokens matched: action should not be performed. return false # Coarse-grained authorization else if annotation.user if user return this.userId(user) == this.userId(annotation.user) else return false # No authorization info on annotation: free-for-all! true # Default user object. user: '' # Default permissions for all annotations. Anyone can do anything # (assuming default userAuthorize function). permissions: { 'read': [] 'update': [] 'delete': [] 'admin': [] } # The constructor called when a new instance of the Permissions # plugin is created. See class documentation for usage. # # element - A DOM Element upon which events are bound.. # options - An Object literal containing custom options. # # Returns an instance of the Permissions object. constructor: (element, options) -> super if @options.user this.setUser(@options.user) delete @options.user # Public: Initializes the plugin and registers fields with the # Annotator.Editor and Annotator.Viewer. # # Returns nothing. pluginInit: -> return unless Annotator.supported() self = this createCallback = (method, type) -> (field, annotation) -> self[method].call(self, type, field, annotation) # Set up user and default permissions from auth token if none currently given if !@user and @annotator.plugins.Auth @annotator.plugins.Auth.withToken(this._setAuthFromToken) if @options.showViewPermissionsCheckbox == true @annotator.editor.addField({ type: 'checkbox' label: Annotator._t('Allow anyone to <strong>view</strong> this annotation') load: createCallback('updatePermissionsField', 'read') submit: createCallback('updateAnnotationPermissions', 'read') }) if @options.showEditPermissionsCheckbox == true @annotator.editor.addField({ type: 'checkbox' label: Annotator._t('Allow anyone to <strong>edit</strong> this annotation') load: createCallback('updatePermissionsField', 'update') submit: createCallback('updateAnnotationPermissions', 'update') }) # Setup the display of annotations in the Viewer. @annotator.viewer.addField({ load: this.updateViewer }) # Add a filter to the Filter plugin if loaded. if @annotator.plugins.Filter @annotator.plugins.Filter.addFilter({ label: Annotator._t('User') property: 'user' isFiltered: (input, user) => user = @options.userString(user) return false unless input and user for keyword in (input.split /\s*/) return false if user.indexOf(keyword) == -1 return true }) # Public: Sets the Permissions#user property. # # user - A String or Object to represent the current user. # # Examples # # permissions.setUser('Alice') # # permissions.setUser({id: 35, name: 'Alice'}) # # Returns nothing. setUser: (user) -> @user = user # Event callback: Appends the @user and @options.permissions objects to the # provided annotation object. Only appends the user if one has been set. # # annotation - An annotation object. # # Examples # # annotation = {text: 'My comment'} # permissions.addFieldsToAnnotation(annotation) # console.log(annotation) # # => {text: 'My comment', permissions: {...}} # # Returns nothing. addFieldsToAnnotation: (annotation) => if annotation annotation.permissions = $.extend(true, {}, @options.permissions) if @user annotation.user = @user # Public: Determines whether the provided action can be performed on the # annotation. This uses the user-configurable 'userAuthorize' method to # determine if an annotation is annotatable. See the default method for # documentation on its behaviour. # # Returns a Boolean, true if the action can be performed on the annotation. authorize: (action, annotation, user) -> user = @user if user == undefined if @options.userAuthorize return @options.userAuthorize.call(@options, action, annotation, user) else # userAuthorize nulled out: free-for-all! return true # Field callback: Updates the state of the "anyone can…" checkboxes # # action - The action String, either "view" or "update" # field - A DOM Element containing a form input. # annotation - An annotation Object. # # Returns nothing. updatePermissionsField: (action, field, annotation) => field = $(field).show() input = field.find('input').removeAttr('disabled') # Do not show field if current user is not admin. field.hide() unless this.authorize('admin', annotation) # See if we can authorise without a user. if this.authorize(action, annotation || {}, null) input.attr('checked', 'checked') else input.removeAttr('checked') # Field callback: updates the annotation.permissions object based on the state # of the field checkbox. If it is checked then permissions are set to world # writable otherwise they use the original settings. # # action - The action String, either "view" or "update" # field - A DOM Element representing the annotation editor. # annotation - An annotation Object. # # Returns nothing. updateAnnotationPermissions: (type, field, annotation) => unless annotation.permissions annotation.permissions = $.extend(true, {}, @options.permissions) dataKey = type + '-permissions' if $(field).find('input').is(':checked') annotation.permissions[type] = [] else # Clearly, the permissions model allows for more complex entries than this, # but our UI presents a checkbox, so we can only interpret "prevent others # from viewing" as meaning "allow only me to view". This may want changing # in the future. annotation.permissions[type] = [@options.userId(@user)] # Field callback: updates the annotation viewer to inlude the display name # for the user obtained through Permissions#options.userString(). # # field - A DIV Element representing the annotation field. # annotation - An annotation Object to display. # controls - A control Object to toggle the display of annotation controls. # # Returns nothing. updateViewer: (field, annotation, controls) => field = $(field) username = @options.userString annotation.user if annotation.user and username and typeof username == 'string' user = Annotator.Util.escape(@options.userString(annotation.user)) field.html(user).addClass('annotator-user') else field.remove() if controls controls.hideEdit() unless this.authorize('update', annotation) controls.hideDelete() unless this.authorize('delete', annotation) # Sets the Permissions#user property on the basis of a received authToken. # # token - the authToken received by the Auth plugin # # Returns nothing. _setAuthFromToken: (token) => this.setUser(token.userId)
189056
# Public: Plugin for setting permissions on newly created annotations as well as # managing user permissions such as viewing/editing/deleting annotions. # # element - A DOM Element upon which events are bound. When initialised by # the Annotator it is the Annotator element. # options - An Object literal containing custom options. # # Examples # # new Annotator.plugin.Permissions(annotator.element, { # user: 'Alice' # }) # # Returns a new instance of the Permissions Object. class Annotator.Plugin.Permissions extends Annotator.Plugin # A Object literal consisting of event/method pairs to be bound to # @element. See Delegator#addEvents() for details. events: 'beforeAnnotationCreated': 'addFieldsToAnnotation' # A Object literal of default options for the class. options: # Displays an "Anyone can view this annotation" checkbox in the Editor. showViewPermissionsCheckbox: true # Displays an "Anyone can edit this annotation" checkbox in the Editor. showEditPermissionsCheckbox: true # Public: Used by the plugin to determine a unique id for the @user property. # By default this accepts and returns the user String but can be over- # ridden in the @options object passed into the constructor. # # user - A String username or null if no user is set. # # Returns the String provided as user object. userId: (user) -> user # Public: Used by the plugin to determine a display name for the @user # property. By default this accepts and returns the user String but can be # over-ridden in the @options object passed into the constructor. # # user - A String username or null if no user is set. # # Returns the String provided as user object userString: (user) -> user # Public: Used by Permissions#authorize to determine whether a user can # perform an action on an annotation. Overriding this function allows # a far more complex permissions sysyem. # # By default this authorizes the action if any of three scenarios are true: # # 1) the annotation has a 'permissions' object, and either the field for # the specified action is missing, empty, or contains the userId of the # current user, i.e. @options.userId(@user) # # 2) the annotation has a 'user' property, and @options.userId(@user) matches # 'annotation.user' # # 3) the annotation has no 'permissions' or 'user' properties # # annotation - The annotation on which the action is being requested. # action - The action being requested: e.g. 'update', 'delete'. # user - The user object (or string) requesting the action. This is usually # automatically passed by Permissions#authorize as the current user (@user) # # permissions.setUser(null) # permissions.authorize('update', {}) # # => true # # permissions.setUser('alice') # permissions.authorize('update', {user: '<NAME>'}) # # => true # permissions.authorize('update', {user: '<NAME>'}) # # => false # # permissions.setUser('alice') # permissions.authorize('update', { # user: 'bob', # permissions: ['update': ['<NAME>', 'bob']] # }) # # => true # permissions.authorize('destroy', { # user: 'bob', # permissions: [ # 'update': ['<NAME>', 'bob'] # 'destroy': ['bob'] # ] # }) # # => false # # Returns a Boolean, true if the user is authorised for the token provided. userAuthorize: (action, annotation, user) -> # Fine-grained custom authorization if annotation.permissions tokens = annotation.permissions[action] || [] if tokens.length == 0 # Empty or missing tokens array: anyone can perform action. return true for token in tokens if this.userId(user) == token return true # No tokens matched: action should not be performed. return false # Coarse-grained authorization else if annotation.user if user return this.userId(user) == this.userId(annotation.user) else return false # No authorization info on annotation: free-for-all! true # Default user object. user: '' # Default permissions for all annotations. Anyone can do anything # (assuming default userAuthorize function). permissions: { 'read': [] 'update': [] 'delete': [] 'admin': [] } # The constructor called when a new instance of the Permissions # plugin is created. See class documentation for usage. # # element - A DOM Element upon which events are bound.. # options - An Object literal containing custom options. # # Returns an instance of the Permissions object. constructor: (element, options) -> super if @options.user this.setUser(@options.user) delete @options.user # Public: Initializes the plugin and registers fields with the # Annotator.Editor and Annotator.Viewer. # # Returns nothing. pluginInit: -> return unless Annotator.supported() self = this createCallback = (method, type) -> (field, annotation) -> self[method].call(self, type, field, annotation) # Set up user and default permissions from auth token if none currently given if !@user and @annotator.plugins.Auth @annotator.plugins.Auth.withToken(this._setAuthFromToken) if @options.showViewPermissionsCheckbox == true @annotator.editor.addField({ type: 'checkbox' label: Annotator._t('Allow anyone to <strong>view</strong> this annotation') load: createCallback('updatePermissionsField', 'read') submit: createCallback('updateAnnotationPermissions', 'read') }) if @options.showEditPermissionsCheckbox == true @annotator.editor.addField({ type: 'checkbox' label: Annotator._t('Allow anyone to <strong>edit</strong> this annotation') load: createCallback('updatePermissionsField', 'update') submit: createCallback('updateAnnotationPermissions', 'update') }) # Setup the display of annotations in the Viewer. @annotator.viewer.addField({ load: this.updateViewer }) # Add a filter to the Filter plugin if loaded. if @annotator.plugins.Filter @annotator.plugins.Filter.addFilter({ label: Annotator._t('User') property: 'user' isFiltered: (input, user) => user = @options.userString(user) return false unless input and user for keyword in (input.split /\s*/) return false if user.indexOf(keyword) == -1 return true }) # Public: Sets the Permissions#user property. # # user - A String or Object to represent the current user. # # Examples # # permissions.setUser('<NAME>') # # permissions.setUser({id: 35, name: '<NAME>'}) # # Returns nothing. setUser: (user) -> @user = user # Event callback: Appends the @user and @options.permissions objects to the # provided annotation object. Only appends the user if one has been set. # # annotation - An annotation object. # # Examples # # annotation = {text: 'My comment'} # permissions.addFieldsToAnnotation(annotation) # console.log(annotation) # # => {text: 'My comment', permissions: {...}} # # Returns nothing. addFieldsToAnnotation: (annotation) => if annotation annotation.permissions = $.extend(true, {}, @options.permissions) if @user annotation.user = @user # Public: Determines whether the provided action can be performed on the # annotation. This uses the user-configurable 'userAuthorize' method to # determine if an annotation is annotatable. See the default method for # documentation on its behaviour. # # Returns a Boolean, true if the action can be performed on the annotation. authorize: (action, annotation, user) -> user = @user if user == undefined if @options.userAuthorize return @options.userAuthorize.call(@options, action, annotation, user) else # userAuthorize nulled out: free-for-all! return true # Field callback: Updates the state of the "anyone can…" checkboxes # # action - The action String, either "view" or "update" # field - A DOM Element containing a form input. # annotation - An annotation Object. # # Returns nothing. updatePermissionsField: (action, field, annotation) => field = $(field).show() input = field.find('input').removeAttr('disabled') # Do not show field if current user is not admin. field.hide() unless this.authorize('admin', annotation) # See if we can authorise without a user. if this.authorize(action, annotation || {}, null) input.attr('checked', 'checked') else input.removeAttr('checked') # Field callback: updates the annotation.permissions object based on the state # of the field checkbox. If it is checked then permissions are set to world # writable otherwise they use the original settings. # # action - The action String, either "view" or "update" # field - A DOM Element representing the annotation editor. # annotation - An annotation Object. # # Returns nothing. updateAnnotationPermissions: (type, field, annotation) => unless annotation.permissions annotation.permissions = $.extend(true, {}, @options.permissions) dataKey = type + '-permissions' if $(field).find('input').is(':checked') annotation.permissions[type] = [] else # Clearly, the permissions model allows for more complex entries than this, # but our UI presents a checkbox, so we can only interpret "prevent others # from viewing" as meaning "allow only me to view". This may want changing # in the future. annotation.permissions[type] = [@options.userId(@user)] # Field callback: updates the annotation viewer to inlude the display name # for the user obtained through Permissions#options.userString(). # # field - A DIV Element representing the annotation field. # annotation - An annotation Object to display. # controls - A control Object to toggle the display of annotation controls. # # Returns nothing. updateViewer: (field, annotation, controls) => field = $(field) username = @options.userString annotation.user if annotation.user and username and typeof username == 'string' user = Annotator.Util.escape(@options.userString(annotation.user)) field.html(user).addClass('annotator-user') else field.remove() if controls controls.hideEdit() unless this.authorize('update', annotation) controls.hideDelete() unless this.authorize('delete', annotation) # Sets the Permissions#user property on the basis of a received authToken. # # token - the authToken received by the Auth plugin # # Returns nothing. _setAuthFromToken: (token) => this.setUser(token.userId)
true
# Public: Plugin for setting permissions on newly created annotations as well as # managing user permissions such as viewing/editing/deleting annotions. # # element - A DOM Element upon which events are bound. When initialised by # the Annotator it is the Annotator element. # options - An Object literal containing custom options. # # Examples # # new Annotator.plugin.Permissions(annotator.element, { # user: 'Alice' # }) # # Returns a new instance of the Permissions Object. class Annotator.Plugin.Permissions extends Annotator.Plugin # A Object literal consisting of event/method pairs to be bound to # @element. See Delegator#addEvents() for details. events: 'beforeAnnotationCreated': 'addFieldsToAnnotation' # A Object literal of default options for the class. options: # Displays an "Anyone can view this annotation" checkbox in the Editor. showViewPermissionsCheckbox: true # Displays an "Anyone can edit this annotation" checkbox in the Editor. showEditPermissionsCheckbox: true # Public: Used by the plugin to determine a unique id for the @user property. # By default this accepts and returns the user String but can be over- # ridden in the @options object passed into the constructor. # # user - A String username or null if no user is set. # # Returns the String provided as user object. userId: (user) -> user # Public: Used by the plugin to determine a display name for the @user # property. By default this accepts and returns the user String but can be # over-ridden in the @options object passed into the constructor. # # user - A String username or null if no user is set. # # Returns the String provided as user object userString: (user) -> user # Public: Used by Permissions#authorize to determine whether a user can # perform an action on an annotation. Overriding this function allows # a far more complex permissions sysyem. # # By default this authorizes the action if any of three scenarios are true: # # 1) the annotation has a 'permissions' object, and either the field for # the specified action is missing, empty, or contains the userId of the # current user, i.e. @options.userId(@user) # # 2) the annotation has a 'user' property, and @options.userId(@user) matches # 'annotation.user' # # 3) the annotation has no 'permissions' or 'user' properties # # annotation - The annotation on which the action is being requested. # action - The action being requested: e.g. 'update', 'delete'. # user - The user object (or string) requesting the action. This is usually # automatically passed by Permissions#authorize as the current user (@user) # # permissions.setUser(null) # permissions.authorize('update', {}) # # => true # # permissions.setUser('alice') # permissions.authorize('update', {user: 'PI:NAME:<NAME>END_PI'}) # # => true # permissions.authorize('update', {user: 'PI:NAME:<NAME>END_PI'}) # # => false # # permissions.setUser('alice') # permissions.authorize('update', { # user: 'bob', # permissions: ['update': ['PI:NAME:<NAME>END_PI', 'bob']] # }) # # => true # permissions.authorize('destroy', { # user: 'bob', # permissions: [ # 'update': ['PI:NAME:<NAME>END_PI', 'bob'] # 'destroy': ['bob'] # ] # }) # # => false # # Returns a Boolean, true if the user is authorised for the token provided. userAuthorize: (action, annotation, user) -> # Fine-grained custom authorization if annotation.permissions tokens = annotation.permissions[action] || [] if tokens.length == 0 # Empty or missing tokens array: anyone can perform action. return true for token in tokens if this.userId(user) == token return true # No tokens matched: action should not be performed. return false # Coarse-grained authorization else if annotation.user if user return this.userId(user) == this.userId(annotation.user) else return false # No authorization info on annotation: free-for-all! true # Default user object. user: '' # Default permissions for all annotations. Anyone can do anything # (assuming default userAuthorize function). permissions: { 'read': [] 'update': [] 'delete': [] 'admin': [] } # The constructor called when a new instance of the Permissions # plugin is created. See class documentation for usage. # # element - A DOM Element upon which events are bound.. # options - An Object literal containing custom options. # # Returns an instance of the Permissions object. constructor: (element, options) -> super if @options.user this.setUser(@options.user) delete @options.user # Public: Initializes the plugin and registers fields with the # Annotator.Editor and Annotator.Viewer. # # Returns nothing. pluginInit: -> return unless Annotator.supported() self = this createCallback = (method, type) -> (field, annotation) -> self[method].call(self, type, field, annotation) # Set up user and default permissions from auth token if none currently given if !@user and @annotator.plugins.Auth @annotator.plugins.Auth.withToken(this._setAuthFromToken) if @options.showViewPermissionsCheckbox == true @annotator.editor.addField({ type: 'checkbox' label: Annotator._t('Allow anyone to <strong>view</strong> this annotation') load: createCallback('updatePermissionsField', 'read') submit: createCallback('updateAnnotationPermissions', 'read') }) if @options.showEditPermissionsCheckbox == true @annotator.editor.addField({ type: 'checkbox' label: Annotator._t('Allow anyone to <strong>edit</strong> this annotation') load: createCallback('updatePermissionsField', 'update') submit: createCallback('updateAnnotationPermissions', 'update') }) # Setup the display of annotations in the Viewer. @annotator.viewer.addField({ load: this.updateViewer }) # Add a filter to the Filter plugin if loaded. if @annotator.plugins.Filter @annotator.plugins.Filter.addFilter({ label: Annotator._t('User') property: 'user' isFiltered: (input, user) => user = @options.userString(user) return false unless input and user for keyword in (input.split /\s*/) return false if user.indexOf(keyword) == -1 return true }) # Public: Sets the Permissions#user property. # # user - A String or Object to represent the current user. # # Examples # # permissions.setUser('PI:NAME:<NAME>END_PI') # # permissions.setUser({id: 35, name: 'PI:NAME:<NAME>END_PI'}) # # Returns nothing. setUser: (user) -> @user = user # Event callback: Appends the @user and @options.permissions objects to the # provided annotation object. Only appends the user if one has been set. # # annotation - An annotation object. # # Examples # # annotation = {text: 'My comment'} # permissions.addFieldsToAnnotation(annotation) # console.log(annotation) # # => {text: 'My comment', permissions: {...}} # # Returns nothing. addFieldsToAnnotation: (annotation) => if annotation annotation.permissions = $.extend(true, {}, @options.permissions) if @user annotation.user = @user # Public: Determines whether the provided action can be performed on the # annotation. This uses the user-configurable 'userAuthorize' method to # determine if an annotation is annotatable. See the default method for # documentation on its behaviour. # # Returns a Boolean, true if the action can be performed on the annotation. authorize: (action, annotation, user) -> user = @user if user == undefined if @options.userAuthorize return @options.userAuthorize.call(@options, action, annotation, user) else # userAuthorize nulled out: free-for-all! return true # Field callback: Updates the state of the "anyone can…" checkboxes # # action - The action String, either "view" or "update" # field - A DOM Element containing a form input. # annotation - An annotation Object. # # Returns nothing. updatePermissionsField: (action, field, annotation) => field = $(field).show() input = field.find('input').removeAttr('disabled') # Do not show field if current user is not admin. field.hide() unless this.authorize('admin', annotation) # See if we can authorise without a user. if this.authorize(action, annotation || {}, null) input.attr('checked', 'checked') else input.removeAttr('checked') # Field callback: updates the annotation.permissions object based on the state # of the field checkbox. If it is checked then permissions are set to world # writable otherwise they use the original settings. # # action - The action String, either "view" or "update" # field - A DOM Element representing the annotation editor. # annotation - An annotation Object. # # Returns nothing. updateAnnotationPermissions: (type, field, annotation) => unless annotation.permissions annotation.permissions = $.extend(true, {}, @options.permissions) dataKey = type + '-permissions' if $(field).find('input').is(':checked') annotation.permissions[type] = [] else # Clearly, the permissions model allows for more complex entries than this, # but our UI presents a checkbox, so we can only interpret "prevent others # from viewing" as meaning "allow only me to view". This may want changing # in the future. annotation.permissions[type] = [@options.userId(@user)] # Field callback: updates the annotation viewer to inlude the display name # for the user obtained through Permissions#options.userString(). # # field - A DIV Element representing the annotation field. # annotation - An annotation Object to display. # controls - A control Object to toggle the display of annotation controls. # # Returns nothing. updateViewer: (field, annotation, controls) => field = $(field) username = @options.userString annotation.user if annotation.user and username and typeof username == 'string' user = Annotator.Util.escape(@options.userString(annotation.user)) field.html(user).addClass('annotator-user') else field.remove() if controls controls.hideEdit() unless this.authorize('update', annotation) controls.hideDelete() unless this.authorize('delete', annotation) # Sets the Permissions#user property on the basis of a received authToken. # # token - the authToken received by the Auth plugin # # Returns nothing. _setAuthFromToken: (token) => this.setUser(token.userId)
[ { "context": "###\nLottieLayer\n-\nImplementation of Hernan Torrisi & AirBnb \"Lottie-Web\" for Framer.\nby @72mena\n###\n", "end": 50, "score": 0.999867856502533, "start": 36, "tag": "NAME", "value": "Hernan Torrisi" }, { "context": "ernan Torrisi & AirBnb \"Lottie-Web\" for Framer....
src/public/framer02.framer/modules/LottieLayer.coffee
jmanhart/personal-portfolio-17
0
### LottieLayer - Implementation of Hernan Torrisi & AirBnb "Lottie-Web" for Framer. by @72mena ### # INCLUDE LIBRARY ——————————————————————————— insertScript = (localScript, webScript, name = 'JavaScript Library') -> try lib = Utils.domLoadDataSync localScript console.log "%c#{name} Successfully Included Locally", "background: #DDFFE3; color: #007814" catch e try lib = Utils.domLoadDataSync webScript console.log "%c#{name} Successfully Included from Web", "background: #DDFFE3; color: #007814" catch e throw Error("Sorry, I couldn't load #{name}") script = document.createElement "script" script.type = "text/javascript" script.innerHTML = lib head = document.getElementsByTagName("head")[0] head.appendChild script script insertScript("modules/lottie.min.js", "https://raw.githubusercontent.com/airbnb/lottie-web/master/build/player/lottie.min.js", "lottie-web") # LOTTIE LAYER ——————————————————————————— class exports.LottieLayer extends Layer @define "speed", get: -> @_properties["speed"] set: (value) -> @_properties["speed"] = value @setSpeed(value) if @built @emit "change:speed" @define "direction", get: -> @_properties["direction"] set: (value) -> @_properties["direction"] = value @setDirection(value) if @built @emit "change:direction" @define "path", get: -> @_properties["path"] set: (value) -> @_properties["path"] = value @setSettings() if @built @emit "change:path" constructor: (@options={}) -> # Defaults @options.backgroundColor ?= null @options.path ?= null @options.autoplay ?= true @options.loop ?= true @options.speed ?= 1 @options.direction ?= 1 @options.renderer ?= "svg" super @options if @options.path is null print "From LottieLayer: Setting a path to your json file is required." if @name is "" print "From LottieLayer: The 'name' attribute is required." #Shortcuts @autoplay = @options.autoplay @loop = @options.loop @renderer = @options.renderer #Vars @built = false @_animationLayer = null #Run @build() build: () -> @html = '<div id='+"#{@name}"+'></div>' @setSettings() @built = true setSettings: () -> _container = document.getElementById(@name) _container.innerHTML = "" lottieSettings = container: _container, path: @path, renderer: @renderer, autoplay: @autoplay, loop: @loop @_animationLayer = lottie.loadAnimation(lottieSettings); @setSpeed() @setDirection() play: () -> @_animationLayer.play() stop: () -> @_animationLayer.stop() pause: () -> @_animationLayer.pause() goToAndPlay: (value, isFrame) -> isFrame ?= true @_animationLayer.goToAndPlay(value, isFrame) goToAndStop: (value, isFrame) -> isFrame ?= true @_animationLayer.goToAndStop(value, isFrame) playSegments: (segments, forceFlag) -> forceFlag ?= true @_animationLayer.playSegments(segments, forceFlag) setSpeed: (speed) -> speed ?= @speed @_animationLayer.setSpeed(speed) setDirection: (direction) -> direction ?= @direction @_animationLayer.setDirection(direction) onComplete: (callback) -> if @loop @_animationLayer.addEventListener "loopComplete", callback else @_animationLayer.addEventListener "complete", callback
49105
### LottieLayer - Implementation of <NAME> & AirBnb "Lottie-Web" for Framer. by @72mena ### # INCLUDE LIBRARY ——————————————————————————— insertScript = (localScript, webScript, name = 'JavaScript Library') -> try lib = Utils.domLoadDataSync localScript console.log "%c#{name} Successfully Included Locally", "background: #DDFFE3; color: #007814" catch e try lib = Utils.domLoadDataSync webScript console.log "%c#{name} Successfully Included from Web", "background: #DDFFE3; color: #007814" catch e throw Error("Sorry, I couldn't load #{name}") script = document.createElement "script" script.type = "text/javascript" script.innerHTML = lib head = document.getElementsByTagName("head")[0] head.appendChild script script insertScript("modules/lottie.min.js", "https://raw.githubusercontent.com/airbnb/lottie-web/master/build/player/lottie.min.js", "lottie-web") # LOTTIE LAYER ——————————————————————————— class exports.LottieLayer extends Layer @define "speed", get: -> @_properties["speed"] set: (value) -> @_properties["speed"] = value @setSpeed(value) if @built @emit "change:speed" @define "direction", get: -> @_properties["direction"] set: (value) -> @_properties["direction"] = value @setDirection(value) if @built @emit "change:direction" @define "path", get: -> @_properties["path"] set: (value) -> @_properties["path"] = value @setSettings() if @built @emit "change:path" constructor: (@options={}) -> # Defaults @options.backgroundColor ?= null @options.path ?= null @options.autoplay ?= true @options.loop ?= true @options.speed ?= 1 @options.direction ?= 1 @options.renderer ?= "svg" super @options if @options.path is null print "From LottieLayer: Setting a path to your json file is required." if @name is "" print "From LottieLayer: The 'name' attribute is required." #Shortcuts @autoplay = @options.autoplay @loop = @options.loop @renderer = @options.renderer #Vars @built = false @_animationLayer = null #Run @build() build: () -> @html = '<div id='+"#{@name}"+'></div>' @setSettings() @built = true setSettings: () -> _container = document.getElementById(@name) _container.innerHTML = "" lottieSettings = container: _container, path: @path, renderer: @renderer, autoplay: @autoplay, loop: @loop @_animationLayer = lottie.loadAnimation(lottieSettings); @setSpeed() @setDirection() play: () -> @_animationLayer.play() stop: () -> @_animationLayer.stop() pause: () -> @_animationLayer.pause() goToAndPlay: (value, isFrame) -> isFrame ?= true @_animationLayer.goToAndPlay(value, isFrame) goToAndStop: (value, isFrame) -> isFrame ?= true @_animationLayer.goToAndStop(value, isFrame) playSegments: (segments, forceFlag) -> forceFlag ?= true @_animationLayer.playSegments(segments, forceFlag) setSpeed: (speed) -> speed ?= @speed @_animationLayer.setSpeed(speed) setDirection: (direction) -> direction ?= @direction @_animationLayer.setDirection(direction) onComplete: (callback) -> if @loop @_animationLayer.addEventListener "loopComplete", callback else @_animationLayer.addEventListener "complete", callback
true
### LottieLayer - Implementation of PI:NAME:<NAME>END_PI & AirBnb "Lottie-Web" for Framer. by @72mena ### # INCLUDE LIBRARY ——————————————————————————— insertScript = (localScript, webScript, name = 'JavaScript Library') -> try lib = Utils.domLoadDataSync localScript console.log "%c#{name} Successfully Included Locally", "background: #DDFFE3; color: #007814" catch e try lib = Utils.domLoadDataSync webScript console.log "%c#{name} Successfully Included from Web", "background: #DDFFE3; color: #007814" catch e throw Error("Sorry, I couldn't load #{name}") script = document.createElement "script" script.type = "text/javascript" script.innerHTML = lib head = document.getElementsByTagName("head")[0] head.appendChild script script insertScript("modules/lottie.min.js", "https://raw.githubusercontent.com/airbnb/lottie-web/master/build/player/lottie.min.js", "lottie-web") # LOTTIE LAYER ——————————————————————————— class exports.LottieLayer extends Layer @define "speed", get: -> @_properties["speed"] set: (value) -> @_properties["speed"] = value @setSpeed(value) if @built @emit "change:speed" @define "direction", get: -> @_properties["direction"] set: (value) -> @_properties["direction"] = value @setDirection(value) if @built @emit "change:direction" @define "path", get: -> @_properties["path"] set: (value) -> @_properties["path"] = value @setSettings() if @built @emit "change:path" constructor: (@options={}) -> # Defaults @options.backgroundColor ?= null @options.path ?= null @options.autoplay ?= true @options.loop ?= true @options.speed ?= 1 @options.direction ?= 1 @options.renderer ?= "svg" super @options if @options.path is null print "From LottieLayer: Setting a path to your json file is required." if @name is "" print "From LottieLayer: The 'name' attribute is required." #Shortcuts @autoplay = @options.autoplay @loop = @options.loop @renderer = @options.renderer #Vars @built = false @_animationLayer = null #Run @build() build: () -> @html = '<div id='+"#{@name}"+'></div>' @setSettings() @built = true setSettings: () -> _container = document.getElementById(@name) _container.innerHTML = "" lottieSettings = container: _container, path: @path, renderer: @renderer, autoplay: @autoplay, loop: @loop @_animationLayer = lottie.loadAnimation(lottieSettings); @setSpeed() @setDirection() play: () -> @_animationLayer.play() stop: () -> @_animationLayer.stop() pause: () -> @_animationLayer.pause() goToAndPlay: (value, isFrame) -> isFrame ?= true @_animationLayer.goToAndPlay(value, isFrame) goToAndStop: (value, isFrame) -> isFrame ?= true @_animationLayer.goToAndStop(value, isFrame) playSegments: (segments, forceFlag) -> forceFlag ?= true @_animationLayer.playSegments(segments, forceFlag) setSpeed: (speed) -> speed ?= @speed @_animationLayer.setSpeed(speed) setDirection: (direction) -> direction ?= @direction @_animationLayer.setDirection(direction) onComplete: (callback) -> if @loop @_animationLayer.addEventListener "loopComplete", callback else @_animationLayer.addEventListener "complete", callback
[ { "context": "rt 'SMTP', config\n\n # @todo https://github.com/andris9/Nodemailer/\n # \n # Rails makes this an obje", "end": 290, "score": 0.9996247291564941, "start": 283, "tag": "USERNAME", "value": "andris9" }, { "context": "s of the sender. All e-mail addresses can be p...
node_modules/tower/packages/tower-mailer/server/rendering.coffee
MagicPower2/Power
1
Tower.MailerRendering = ClassMethods: config: {} transport: -> return @_transport if @_transport config = @config = Tower.Mailer.config[Tower.env] || {} @_transport = require('nodemailer').createTransport 'SMTP', config # @todo https://github.com/andris9/Nodemailer/ # # Rails makes this an object but I don't see the use case for that now. # If you do, please tell! (since Nodemailer is doing everything with just a hash). # # from - The e-mail address of the sender. All e-mail addresses can be plain sender@server.com or formatted Sender Name <sender@server.com> # to - Comma separated list of recipients e-mail addresses that will appear on the To: field # cc - Comma separated list of recipients e-mail addresses that will appear on the Cc: field # bcc - Comma separated list of recipients e-mail addresses that will appear on the Bcc: field # replyTo - An e-mail address that will appear on the Reply-To: field # inReplyTo - The message-id this message is replying # references - Message-id list # subject - The subject of the e-mail # text - The plaintext version of the message # html - The HTML version of the message # generateTextFromHTML - if set to true uses HTML to generate plain text body part from the HTML if the text is not defined # headers - An object of additional header fields {"X-Key-Name": "key value"} (NB! values are passed as is, you should do your own encoding to 7bit if needed) # attachments - An array of attachment objects. # envelope - optional SMTP envelope, if auto generated envelope is not suitable # messageId - optional Message-Id value, random value will be generated if not set. Set to false to omit the Message-Id header # encoding - optional transfer encoding for the textual parts (defaults to "quoted-printable") # # template - path to template for rendering # locals mail: (options = {}, callback) -> @render options, (error, options) => # sendMail options, (error, response) => # https://github.com/andris9/Nodemailer/blob/master/examples/example_smtp.js @transport().sendMail options, callback render: (options, callback) => template = options.template delete options.template if template locals = options.locals || {} delete options.locals Tower.module('mint').render path: template, locals: locals, (error, result) => options.html = result callback.call(@, error, options) else callback.call(@, null, options) module.exports = Tower.MailerRendering
121740
Tower.MailerRendering = ClassMethods: config: {} transport: -> return @_transport if @_transport config = @config = Tower.Mailer.config[Tower.env] || {} @_transport = require('nodemailer').createTransport 'SMTP', config # @todo https://github.com/andris9/Nodemailer/ # # Rails makes this an object but I don't see the use case for that now. # If you do, please tell! (since Nodemailer is doing everything with just a hash). # # from - The e-mail address of the sender. All e-mail addresses can be plain <EMAIL> or formatted Sender Name <<EMAIL>> # to - Comma separated list of recipients e-mail addresses that will appear on the To: field # cc - Comma separated list of recipients e-mail addresses that will appear on the Cc: field # bcc - Comma separated list of recipients e-mail addresses that will appear on the Bcc: field # replyTo - An e-mail address that will appear on the Reply-To: field # inReplyTo - The message-id this message is replying # references - Message-id list # subject - The subject of the e-mail # text - The plaintext version of the message # html - The HTML version of the message # generateTextFromHTML - if set to true uses HTML to generate plain text body part from the HTML if the text is not defined # headers - An object of additional header fields {"X-Key-Name": "key value"} (NB! values are passed as is, you should do your own encoding to 7bit if needed) # attachments - An array of attachment objects. # envelope - optional SMTP envelope, if auto generated envelope is not suitable # messageId - optional Message-Id value, random value will be generated if not set. Set to false to omit the Message-Id header # encoding - optional transfer encoding for the textual parts (defaults to "quoted-printable") # # template - path to template for rendering # locals mail: (options = {}, callback) -> @render options, (error, options) => # sendMail options, (error, response) => # https://github.com/andris9/Nodemailer/blob/master/examples/example_smtp.js @transport().sendMail options, callback render: (options, callback) => template = options.template delete options.template if template locals = options.locals || {} delete options.locals Tower.module('mint').render path: template, locals: locals, (error, result) => options.html = result callback.call(@, error, options) else callback.call(@, null, options) module.exports = Tower.MailerRendering
true
Tower.MailerRendering = ClassMethods: config: {} transport: -> return @_transport if @_transport config = @config = Tower.Mailer.config[Tower.env] || {} @_transport = require('nodemailer').createTransport 'SMTP', config # @todo https://github.com/andris9/Nodemailer/ # # Rails makes this an object but I don't see the use case for that now. # If you do, please tell! (since Nodemailer is doing everything with just a hash). # # from - The e-mail address of the sender. All e-mail addresses can be plain PI:EMAIL:<EMAIL>END_PI or formatted Sender Name <PI:EMAIL:<EMAIL>END_PI> # to - Comma separated list of recipients e-mail addresses that will appear on the To: field # cc - Comma separated list of recipients e-mail addresses that will appear on the Cc: field # bcc - Comma separated list of recipients e-mail addresses that will appear on the Bcc: field # replyTo - An e-mail address that will appear on the Reply-To: field # inReplyTo - The message-id this message is replying # references - Message-id list # subject - The subject of the e-mail # text - The plaintext version of the message # html - The HTML version of the message # generateTextFromHTML - if set to true uses HTML to generate plain text body part from the HTML if the text is not defined # headers - An object of additional header fields {"X-Key-Name": "key value"} (NB! values are passed as is, you should do your own encoding to 7bit if needed) # attachments - An array of attachment objects. # envelope - optional SMTP envelope, if auto generated envelope is not suitable # messageId - optional Message-Id value, random value will be generated if not set. Set to false to omit the Message-Id header # encoding - optional transfer encoding for the textual parts (defaults to "quoted-printable") # # template - path to template for rendering # locals mail: (options = {}, callback) -> @render options, (error, options) => # sendMail options, (error, response) => # https://github.com/andris9/Nodemailer/blob/master/examples/example_smtp.js @transport().sendMail options, callback render: (options, callback) => template = options.template delete options.template if template locals = options.locals || {} delete options.locals Tower.module('mint').render path: template, locals: locals, (error, result) => options.html = result callback.call(@, error, options) else callback.call(@, null, options) module.exports = Tower.MailerRendering
[ { "context": " .post('/metrics')\n .basicAuth(user: 'foo@example.com', pass: 'bob')\n .delay(10)\n .reply(", "end": 300, "score": 0.9999238848686218, "start": 285, "tag": "EMAIL", "value": "foo@example.com" }, { "context": " .basicAuth(user: 'foo@examp...
test/client.coffee
autopulated/librato-node
28
require './support/test_helper' Client = require '../lib/client' nock = require 'nock' describe 'Client', -> {client} = {} describe 'with email and token', -> beforeEach -> nock('https://metrics-api.librato.com/v1') .post('/metrics') .basicAuth(user: 'foo@example.com', pass: 'bob') .delay(10) .reply(200) client = new Client email: 'foo@example.com', token: 'bob' afterEach -> nock.cleanAll() describe '::send', -> it 'sends data to Librato', (done) -> client.send {gauges: [{name: 'foo', value: 1}]}, done null describe 'Librato returns a 400', -> beforeEach -> nock('https://metrics-api.librato.com/v1') .post('/metrics') .basicAuth(user: 'foo@example.com', pass: 'bob') .reply(400, errors: {params: {name: ['is not present']}}) client = new Client email: 'foo@example.com', token: 'bob' afterEach -> nock.cleanAll() describe '::send', -> it 'throws an error with the response body', (done) -> client.send {gauges: [{name: '', value: 1}]}, (err) -> expect(err.message).to.equal "Error sending to Librato: { errors: { params: { name: [ 'is not present' ] } } } (statusCode: 400)" done() null describe 'with timeout via requestOptions', -> beforeEach -> nock('https://metrics-api.librato.com/v1') .post('/metrics') .basicAuth(user: 'foo@example.com', pass: 'bob') .socketDelay(10) .reply(200) client = new Client email: 'foo@example.com', token: 'bob', requestOptions: {timeout: 5, maxAttempts: 1} afterEach -> nock.cleanAll() describe '::send', -> it 'throws timeout error', (done) -> client.send {gauges: [{name: 'foo', value: 1}]}, (err) -> expect(err.code).to.equal 'ESOCKETTIMEDOUT' done() null describe 'with 500 from librato', -> beforeEach -> nock('https://metrics-api.librato.com/v1') .post('/metrics') .basicAuth(user: 'foo@example.com', pass: 'bob') .reply(504) nock('https://metrics-api.librato.com/v1') .post('/metrics') .basicAuth(user: 'foo@example.com', pass: 'bob') .reply(200) client = new Client email: 'foo@example.com', token: 'bob' afterEach -> nock.cleanAll() describe '::send', -> it 'retries and succeeds on the second attempt', (done) -> client.send {gauges: [{name: 'foo', value: 1}]}, done null describe 'in simulate mode', -> beforeEach -> client = new Client simulate: true describe '::send', -> it 'sends data to Librato', (done) -> client.send {gauges: [{name: 'foo', value: 1}]}, done null
57696
require './support/test_helper' Client = require '../lib/client' nock = require 'nock' describe 'Client', -> {client} = {} describe 'with email and token', -> beforeEach -> nock('https://metrics-api.librato.com/v1') .post('/metrics') .basicAuth(user: '<EMAIL>', pass: '<PASSWORD>') .delay(10) .reply(200) client = new Client email: '<EMAIL>', token: '<PASSWORD>' afterEach -> nock.cleanAll() describe '::send', -> it 'sends data to Librato', (done) -> client.send {gauges: [{name: 'foo', value: 1}]}, done null describe 'Librato returns a 400', -> beforeEach -> nock('https://metrics-api.librato.com/v1') .post('/metrics') .basicAuth(user: '<EMAIL>', pass: '<PASSWORD>') .reply(400, errors: {params: {name: ['is not present']}}) client = new Client email: '<EMAIL>', token: 'bob' afterEach -> nock.cleanAll() describe '::send', -> it 'throws an error with the response body', (done) -> client.send {gauges: [{name: '', value: 1}]}, (err) -> expect(err.message).to.equal "Error sending to Librato: { errors: { params: { name: [ 'is not present' ] } } } (statusCode: 400)" done() null describe 'with timeout via requestOptions', -> beforeEach -> nock('https://metrics-api.librato.com/v1') .post('/metrics') .basicAuth(user: '<EMAIL>', pass: '<PASSWORD>') .socketDelay(10) .reply(200) client = new Client email: '<EMAIL>', token: '<PASSWORD>', requestOptions: {timeout: 5, maxAttempts: 1} afterEach -> nock.cleanAll() describe '::send', -> it 'throws timeout error', (done) -> client.send {gauges: [{name: 'foo', value: 1}]}, (err) -> expect(err.code).to.equal 'ESOCKETTIMEDOUT' done() null describe 'with 500 from librato', -> beforeEach -> nock('https://metrics-api.librato.com/v1') .post('/metrics') .basicAuth(user: '<EMAIL>', pass: '<PASSWORD>') .reply(504) nock('https://metrics-api.librato.com/v1') .post('/metrics') .basicAuth(user: '<EMAIL>', pass: '<PASSWORD>') .reply(200) client = new Client email: '<EMAIL>', token: '<PASSWORD>' afterEach -> nock.cleanAll() describe '::send', -> it 'retries and succeeds on the second attempt', (done) -> client.send {gauges: [{name: 'foo', value: 1}]}, done null describe 'in simulate mode', -> beforeEach -> client = new Client simulate: true describe '::send', -> it 'sends data to Librato', (done) -> client.send {gauges: [{name: 'foo', value: 1}]}, done null
true
require './support/test_helper' Client = require '../lib/client' nock = require 'nock' describe 'Client', -> {client} = {} describe 'with email and token', -> beforeEach -> nock('https://metrics-api.librato.com/v1') .post('/metrics') .basicAuth(user: 'PI:EMAIL:<EMAIL>END_PI', pass: 'PI:PASSWORD:<PASSWORD>END_PI') .delay(10) .reply(200) client = new Client email: 'PI:EMAIL:<EMAIL>END_PI', token: 'PI:PASSWORD:<PASSWORD>END_PI' afterEach -> nock.cleanAll() describe '::send', -> it 'sends data to Librato', (done) -> client.send {gauges: [{name: 'foo', value: 1}]}, done null describe 'Librato returns a 400', -> beforeEach -> nock('https://metrics-api.librato.com/v1') .post('/metrics') .basicAuth(user: 'PI:EMAIL:<EMAIL>END_PI', pass: 'PI:PASSWORD:<PASSWORD>END_PI') .reply(400, errors: {params: {name: ['is not present']}}) client = new Client email: 'PI:EMAIL:<EMAIL>END_PI', token: 'bob' afterEach -> nock.cleanAll() describe '::send', -> it 'throws an error with the response body', (done) -> client.send {gauges: [{name: '', value: 1}]}, (err) -> expect(err.message).to.equal "Error sending to Librato: { errors: { params: { name: [ 'is not present' ] } } } (statusCode: 400)" done() null describe 'with timeout via requestOptions', -> beforeEach -> nock('https://metrics-api.librato.com/v1') .post('/metrics') .basicAuth(user: 'PI:EMAIL:<EMAIL>END_PI', pass: 'PI:PASSWORD:<PASSWORD>END_PI') .socketDelay(10) .reply(200) client = new Client email: 'PI:EMAIL:<EMAIL>END_PI', token: 'PI:PASSWORD:<PASSWORD>END_PI', requestOptions: {timeout: 5, maxAttempts: 1} afterEach -> nock.cleanAll() describe '::send', -> it 'throws timeout error', (done) -> client.send {gauges: [{name: 'foo', value: 1}]}, (err) -> expect(err.code).to.equal 'ESOCKETTIMEDOUT' done() null describe 'with 500 from librato', -> beforeEach -> nock('https://metrics-api.librato.com/v1') .post('/metrics') .basicAuth(user: 'PI:EMAIL:<EMAIL>END_PI', pass: 'PI:PASSWORD:<PASSWORD>END_PI') .reply(504) nock('https://metrics-api.librato.com/v1') .post('/metrics') .basicAuth(user: 'PI:EMAIL:<EMAIL>END_PI', pass: 'PI:PASSWORD:<PASSWORD>END_PI') .reply(200) client = new Client email: 'PI:EMAIL:<EMAIL>END_PI', token: 'PI:PASSWORD:<PASSWORD>END_PI' afterEach -> nock.cleanAll() describe '::send', -> it 'retries and succeeds on the second attempt', (done) -> client.send {gauges: [{name: 'foo', value: 1}]}, done null describe 'in simulate mode', -> beforeEach -> client = new Client simulate: true describe '::send', -> it 'sends data to Librato', (done) -> client.send {gauges: [{name: 'foo', value: 1}]}, done null
[ { "context": "sdf\" \n\n# database config\n# configmodule.dbHost = \"178.162.221.176\"\nconfigmodule.dbHost = \"ulea\"\nconfigmodule.dbName", "end": 549, "score": 0.9956218004226685, "start": 534, "tag": "IP_ADDRESS", "value": "178.162.221.176" }, { "context": "odule.dbUser = \"aurox...
source/configmodule/configmodule.coffee
JhonnyJason/program-editor-sources
0
configmodule = {name: "configmodule"} #log Switch log = (arg) -> if allModules.debugmodule.modulesToDebug["configmodule"]? then console.log "[configmodule]: " + arg return ##initialization function -> is automatically being called! ONLY RELY ON DOM AND VARIABLES!! NO PLUGINS NO OHTER INITIALIZATIONS!! configmodule.initialize = () -> log "configmodule.initialize" return #region the configuration Object configmodule.defaultPort = 3333 configmodule.secret = "asdf" # database config # configmodule.dbHost = "178.162.221.176" configmodule.dbHost = "ulea" configmodule.dbName = "programs_test_history" configmodule.dbUser = "aurox" configmodule.dbPassword = "dzy3TqBENvFMC85" # configmodule.dbUser = "lenny" # configmodule.dbPassword = "4564564rfvujm4564564rfvujm" configmodule.dbCaFilePath = 'ssl/server-ca.pem' configmodule.dbKeyFilePath = 'ssl/client-key.pem' configmodule.dbCertFilePath = 'ssl/client-cert.pem' #endregion export default configmodule
108906
configmodule = {name: "configmodule"} #log Switch log = (arg) -> if allModules.debugmodule.modulesToDebug["configmodule"]? then console.log "[configmodule]: " + arg return ##initialization function -> is automatically being called! ONLY RELY ON DOM AND VARIABLES!! NO PLUGINS NO OHTER INITIALIZATIONS!! configmodule.initialize = () -> log "configmodule.initialize" return #region the configuration Object configmodule.defaultPort = 3333 configmodule.secret = "asdf" # database config # configmodule.dbHost = "192.168.127.12" configmodule.dbHost = "ulea" configmodule.dbName = "programs_test_history" configmodule.dbUser = "aurox" configmodule.dbPassword = "<PASSWORD>" # configmodule.dbUser = "lenny" # configmodule.dbPassword = "<PASSWORD>" configmodule.dbCaFilePath = 'ssl/server-ca.pem' configmodule.dbKeyFilePath = 'ssl/client-key.pem' configmodule.dbCertFilePath = 'ssl/client-cert.pem' #endregion export default configmodule
true
configmodule = {name: "configmodule"} #log Switch log = (arg) -> if allModules.debugmodule.modulesToDebug["configmodule"]? then console.log "[configmodule]: " + arg return ##initialization function -> is automatically being called! ONLY RELY ON DOM AND VARIABLES!! NO PLUGINS NO OHTER INITIALIZATIONS!! configmodule.initialize = () -> log "configmodule.initialize" return #region the configuration Object configmodule.defaultPort = 3333 configmodule.secret = "asdf" # database config # configmodule.dbHost = "PI:IP_ADDRESS:192.168.127.12END_PI" configmodule.dbHost = "ulea" configmodule.dbName = "programs_test_history" configmodule.dbUser = "aurox" configmodule.dbPassword = "PI:PASSWORD:<PASSWORD>END_PI" # configmodule.dbUser = "lenny" # configmodule.dbPassword = "PI:PASSWORD:<PASSWORD>END_PI" configmodule.dbCaFilePath = 'ssl/server-ca.pem' configmodule.dbKeyFilePath = 'ssl/client-key.pem' configmodule.dbCertFilePath = 'ssl/client-cert.pem' #endregion export default configmodule
[ { "context": "ribe 'persona', ->\n filter = null\n term = 'acct:hacker@example.com'\n\n beforeEach module('h')\n beforeEach inject ($", "end": 135, "score": 0.9999220967292786, "start": 117, "tag": "EMAIL", "value": "hacker@example.com" }, { "context": "le term by request', ->\n ...
tests/js/filters-test.coffee
Treora/h
0
assert = chai.assert sinon.assert.expose assert, prefix: null describe 'persona', -> filter = null term = 'acct:hacker@example.com' beforeEach module('h') beforeEach inject ($filter) -> filter = $filter('persona') it 'should return the whole term by request', -> result = filter('acct:hacker@example.com', 'term') assert.equal result, 'acct:hacker@example.com' it 'should return the requested part', -> assert.equal filter(term), 'hacker' assert.equal filter(term, 'term'), term, assert.equal filter(term, 'username'), 'hacker' assert.equal filter(term, 'provider'), 'example.com' it 'should pass through unrecognized terms as username or term', -> assert.equal filter('bogus'), 'bogus' assert.equal filter('bogus', 'username'), 'bogus' it 'should handle error cases', -> assert.notOk filter() assert.notOk filter('bogus', 'provider') describe 'urlencode', -> filter = null beforeEach module('h') beforeEach inject ($filter) -> filter = $filter('urlencode') it 'encodes reserved characters in the term', -> assert.equal(filter('#hello world'), '%23hello%20world')
134659
assert = chai.assert sinon.assert.expose assert, prefix: null describe 'persona', -> filter = null term = 'acct:<EMAIL>' beforeEach module('h') beforeEach inject ($filter) -> filter = $filter('persona') it 'should return the whole term by request', -> result = filter('acct:<EMAIL>', 'term') assert.equal result, 'acct:<EMAIL>' it 'should return the requested part', -> assert.equal filter(term), 'hacker' assert.equal filter(term, 'term'), term, assert.equal filter(term, 'username'), 'hacker' assert.equal filter(term, 'provider'), 'example.com' it 'should pass through unrecognized terms as username or term', -> assert.equal filter('bogus'), 'bogus' assert.equal filter('bogus', 'username'), 'bogus' it 'should handle error cases', -> assert.notOk filter() assert.notOk filter('bogus', 'provider') describe 'urlencode', -> filter = null beforeEach module('h') beforeEach inject ($filter) -> filter = $filter('urlencode') it 'encodes reserved characters in the term', -> assert.equal(filter('#hello world'), '%23hello%20world')
true
assert = chai.assert sinon.assert.expose assert, prefix: null describe 'persona', -> filter = null term = 'acct:PI:EMAIL:<EMAIL>END_PI' beforeEach module('h') beforeEach inject ($filter) -> filter = $filter('persona') it 'should return the whole term by request', -> result = filter('acct:PI:EMAIL:<EMAIL>END_PI', 'term') assert.equal result, 'acct:PI:EMAIL:<EMAIL>END_PI' it 'should return the requested part', -> assert.equal filter(term), 'hacker' assert.equal filter(term, 'term'), term, assert.equal filter(term, 'username'), 'hacker' assert.equal filter(term, 'provider'), 'example.com' it 'should pass through unrecognized terms as username or term', -> assert.equal filter('bogus'), 'bogus' assert.equal filter('bogus', 'username'), 'bogus' it 'should handle error cases', -> assert.notOk filter() assert.notOk filter('bogus', 'provider') describe 'urlencode', -> filter = null beforeEach module('h') beforeEach inject ($filter) -> filter = $filter('urlencode') it 'encodes reserved characters in the term', -> assert.equal(filter('#hello world'), '%23hello%20world')
[ { "context": "\t@type:\"ModifierTamedBattlePet\"\n\n\t@modifierName: \"Tamed Battle Pet\"\n\t@description: \"Listens to owner'", "end": 162, "score": 0.5137470364570618, "start": 161, "tag": "NAME", "value": "T" } ]
app/sdk/modifiers/modifierTamedBattlePet.coffee
willroberts/duelyst
5
Modifier = require './modifier' class ModifierTamedBattlePet extends Modifier type:"ModifierTamedBattlePet" @type:"ModifierTamedBattlePet" @modifierName: "Tamed Battle Pet" @description: "Listens to owner's commands" activeInHand: false activeInDeck: false activeInSignatureCards: false activeOnBoard: true fxResource: ["FX.Modifiers.ModifierTamedBattlePet"] module.exports = ModifierTamedBattlePet
97514
Modifier = require './modifier' class ModifierTamedBattlePet extends Modifier type:"ModifierTamedBattlePet" @type:"ModifierTamedBattlePet" @modifierName: "<NAME>amed Battle Pet" @description: "Listens to owner's commands" activeInHand: false activeInDeck: false activeInSignatureCards: false activeOnBoard: true fxResource: ["FX.Modifiers.ModifierTamedBattlePet"] module.exports = ModifierTamedBattlePet
true
Modifier = require './modifier' class ModifierTamedBattlePet extends Modifier type:"ModifierTamedBattlePet" @type:"ModifierTamedBattlePet" @modifierName: "PI:NAME:<NAME>END_PIamed Battle Pet" @description: "Listens to owner's commands" activeInHand: false activeInDeck: false activeInSignatureCards: false activeOnBoard: true fxResource: ["FX.Modifiers.ModifierTamedBattlePet"] module.exports = ModifierTamedBattlePet
[ { "context": "# Copyright 2010-2019 Dan Elliott, Russell Valentine\n#\n# Licensed under the Apach", "end": 35, "score": 0.9998177886009216, "start": 24, "tag": "NAME", "value": "Dan Elliott" }, { "context": "# Copyright 2010-2019 Dan Elliott, Russell Valentine\n#\n# Licensed ...
clients/www/src/coffee/handler/isadore_settings_lut_maxtemp.coffee
bluthen/isadore_server
0
# Copyright 2010-2019 Dan Elliott, Russell Valentine # # 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 window.SettingsLUTMaxTemp constructor: () -> self=this @maxTempLightbox_ = new SettingsLUTMaxTempLightbox() $('#settings_new_lut_mc_maxtemp').click( () -> self.maxTempLightbox_.open(null, () -> self.refresh()) ) self.deleteDialog = new IsadoreDialog('#delete_lightbox', { width: 400, title: 'Delete Confirm' }) updateTable_: () -> self=this $('#settings_lut_mc_maxtemp_spinner').hide() $('#settings_lut_mc_maxtemp_table').show() tableData = [] for lut in @luts_ tableData.push([lut.name, lut.hours_per_mc, HTMLHelper.actionButtons, lut.id]) $('#settings_lut_mc_maxtemp_table').dataTable({ bDestroy: true bPaginate: false bFilter: false aaData: tableData aoColumns: [ { sTitle: 'Name' } { sTitle: 'Hrs/MCPt' } { sTitle: 'Actions', bSortable: false } { sTitle: 'data-lut_id', bVisible: false } ] fnRowCallback: (nRow, aData, ididx, ididxf) -> nRow.setAttribute('data-lut_id', aData[3]) $('td:eq(2)', nRow).addClass('action') return nRow }) $('#settings_lut_mc_maxtemp_table span.action[data-action_type="edit"]').click((event) -> self.editLUT_(event) ) $('#settings_lut_mc_maxtemp_table span.action[data-action_type="delete"]').click((event) -> self.deleteLUT_(event) ) fixHeights() editLUT_: (event) -> self=this id=parseInt($(event.currentTarget).closest('tr').attr('data-lut_id')) @maxTempLightbox_.open(id, () -> self.refresh()) deleteLUT_: (event) -> self=this id=_.parseInt($(event.currentTarget).closest('tr').attr('data-lut_id')) lut = _.findWhere(@luts_, {'id': id}) $('#delete_lightbox_delete_spinner').hide() $('#delete_lightbox_delete').show() $('#delete_lightbox_cancel').show() $('#delete_lightbox h1:first').html('Delete MC Maxtemp LUT') $('#delete_lightbox_entry_info').html('LUT Name: '+lut.name) $('#delete_lightbox_delete').unbind('click') $('#delete_lightbox_delete').click(() -> self.deleteLUTConfirmed_(lut)) $('#delete_lightbox_cancel').unbind('click') $('#delete_lightbox_cancel').click(() -> self.deleteDialog.close()) self.deleteDialog.open(); deleteLUTConfirmed_: (lut) -> self=this $('#delete_lightbox_delete').hide() $('#delete_lightbox_cancel').hide() $('#delete_lightbox_delete_spinner').show() $.ajax({ url : '../resources/luts/mc_maxtemp/'+lut.id, type : 'DELETE', dataType : 'text', success : () -> self.deleteLUTDone_() }) deleteLUTDone_: () -> self=this $('#delete_lightbox_delete_spinner').hide() $('#delete_lightbox_delete').show() $('#delete_lightbox_cancel').show() @refresh() self.deleteDialog.close() refresh: () -> self=this $('#settings_lut_mc_maxtemp_table').hide() $('#settings_lut_mc_maxtemp_spinner').show() $.ajax({ url: '../resources/luts/mc_maxtemp-fast' type: 'GET' dataType: 'json' success: (d) -> self.luts_ = d.luts self.updateTable_() }) class window.SettingsLUTMaxTempLightbox constructor: () -> self=this $('#settings_luc_mc_maxtemp_edit_hours_per_mc').numeric({ negative: false }) $('#settings_luc_mc_maxtemp_edit_more').click(() -> self.moreTable()) $('#settings_lut_mc_maxtemp_edit_save').click(() -> self.save()) self.lutDialog = new IsadoreDialog('#settings_lut_mc_maxtemp_lightbox', { width: 550, close: () -> self.close() }) empty: () -> $('#settings_luc_mc_maxtemp_edit_hours_per_mc').val('') $('#settings_luc_mc_maxtemp_edit_name').val('') $('#settings_luc_mc_maxtemp_edit_table tbody').html('') update_: (lutId) -> self=this $('#settings_lut_mc_maxtemp_edit_open_spinner').show() $('#settings_lut_mc_maxtemp_lightbox_wrapper').hide() if lutId $.ajax({ url: '../resources/luts/mc_maxtemp/'+lutId type: 'GET' dataType: 'json' success: (d) -> self.lut_ = d self.update2_() }) else self.update2_() update2_: () -> self=this if @lut_ $('#settings_luc_mc_maxtemp_edit_name').val(@lut_.name) $('#settings_luc_mc_maxtemp_edit_hours_per_mc').val(@lut_.hours_per_mc.toFixed(2)) for v in @lut_.values $('#settings_luc_mc_maxtemp_edit_table tbody').append('<tr><td><input type="text"/></td><td><input type="text"/><td></tr>') inputs = $('#settings_luc_mc_maxtemp_edit_table tbody tr:last input') $(inputs[0]).val(v.mc.toFixed(2)).numeric({ negative: false }) $(inputs[1]).val(v.maxtemp.toFixed(2)).numeric({ negative: false }) @moreTable() $('#settings_lut_mc_maxtemp_edit_open_spinner').hide() $('#settings_lut_mc_maxtemp_lightbox_wrapper').show() cbResize() moreTable: () -> self=this for i in [0..5] $('#settings_luc_mc_maxtemp_edit_table tbody').append('<tr><td><input type="text"/></td><td><input type="text"/><td></tr>') inputs = $('#settings_luc_mc_maxtemp_edit_table tbody tr:last input') $(inputs[0]).numeric({ negative: false }) $(inputs[1]).numeric({ negative: false }) cbResize() close: () -> self=this if @closeCallback_ @closeCallback_() save: () -> self=this $('#settings_lut_mc_maxtemp_lightbox .success').empty().stop().animate({ opacity: '100' }).stop() $('#settings_lut_mc_maxtemp_lightbox .errors').empty().show() name = $('#settings_luc_mc_maxtemp_edit_name').val() hours_per_mc = parseFloat($('#settings_luc_mc_maxtemp_edit_hours_per_mc').val()) if not name $('#settings_lut_mc_maxtemp_lightbox .errors').html('Name is required.').show() return if isNaN(hours_per_mc) $('#settings_lut_mc_maxtemp_lightbox .errors').html('MC/hour is required.').show() return inputs = $('#settings_luc_mc_maxtemp_edit_table tbody input') mcs=[] maxtemps=[] for i in [0..inputs.length] by 2 mc = parseFloat($(inputs[i]).val()) maxtemp = parseFloat($(inputs[i+1]).val()) if not isNaN(mc)and not isNaN(maxtemp) mcs.push(mc) maxtemps.push(maxtemp) adata = { name: name hours_per_mc: hours_per_mc mcs:mcs.join(',') maxtemps: maxtemps.join(',') } $('#settings_lut_mc_maxtemp_edit_save_spinner').show() $('#settings_lut_mc_maxtemp_edit_save').hide() $('#settings_lut_mc_maxtemp_lightbox input, #settings_luc_mc_maxtemp_edit_table button').attr('disabled', true) if not @lut_ $.ajax({ url: '../resources/luts/mc_maxtemp' type: 'POST' dataType: 'json' data: adata success: (d) -> lutId = d.xlink[0].split('/')[4] self.saveSuccess_(lutId) error: () -> self.saveFailed_() }) else $.ajax({ url: '../resources/luts/mc_maxtemp/'+@lut_.id type: 'PUT' dataType: 'text' data: adata success: (d) -> self.saveSuccess_(self.lut_.id) error: () -> self.saveFailed_() }) saveSuccess_: (lutId) -> self=this $('#settings_lut_mc_maxtemp_edit_save_spinner').hide() $('#settings_lut_mc_maxtemp_edit_save').show() $('#settings_lut_mc_maxtemp_lightbox input, #settings_luc_mc_maxtemp_edit_table button').removeAttr('disabled') $('#settings_lut_mc_maxtemp_lightbox .success').html('Saved.').show().fadeOut(3000) @empty() @update_(lutId) saveFailed_: () -> self=this $('#settings_lut_mc_maxtemp_edit_save_spinner').hide() $('#settings_lut_mc_maxtemp_edit_save').show() $('#settings_lut_mc_maxtemp_lightbox input, #settings_luc_mc_maxtemp_edit_table button').removeAttr('disabled') $('#settings_lut_mc_maxtemp_lightbox .errors').html('Error occurred during saving.').show() cbResize() open: (lutId, closeCallback) -> self=this $('#settings_lut_mc_maxtemp_lightbox .errors').empty().show() @lut_ = null @closeCallback_ = closeCallback @empty() @update_(lutId) self.lutDialog.open()
71064
# Copyright 2010-2019 <NAME>, <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class window.SettingsLUTMaxTemp constructor: () -> self=this @maxTempLightbox_ = new SettingsLUTMaxTempLightbox() $('#settings_new_lut_mc_maxtemp').click( () -> self.maxTempLightbox_.open(null, () -> self.refresh()) ) self.deleteDialog = new IsadoreDialog('#delete_lightbox', { width: 400, title: 'Delete Confirm' }) updateTable_: () -> self=this $('#settings_lut_mc_maxtemp_spinner').hide() $('#settings_lut_mc_maxtemp_table').show() tableData = [] for lut in @luts_ tableData.push([lut.name, lut.hours_per_mc, HTMLHelper.actionButtons, lut.id]) $('#settings_lut_mc_maxtemp_table').dataTable({ bDestroy: true bPaginate: false bFilter: false aaData: tableData aoColumns: [ { sTitle: 'Name' } { sTitle: 'Hrs/MCPt' } { sTitle: 'Actions', bSortable: false } { sTitle: 'data-lut_id', bVisible: false } ] fnRowCallback: (nRow, aData, ididx, ididxf) -> nRow.setAttribute('data-lut_id', aData[3]) $('td:eq(2)', nRow).addClass('action') return nRow }) $('#settings_lut_mc_maxtemp_table span.action[data-action_type="edit"]').click((event) -> self.editLUT_(event) ) $('#settings_lut_mc_maxtemp_table span.action[data-action_type="delete"]').click((event) -> self.deleteLUT_(event) ) fixHeights() editLUT_: (event) -> self=this id=parseInt($(event.currentTarget).closest('tr').attr('data-lut_id')) @maxTempLightbox_.open(id, () -> self.refresh()) deleteLUT_: (event) -> self=this id=_.parseInt($(event.currentTarget).closest('tr').attr('data-lut_id')) lut = _.findWhere(@luts_, {'id': id}) $('#delete_lightbox_delete_spinner').hide() $('#delete_lightbox_delete').show() $('#delete_lightbox_cancel').show() $('#delete_lightbox h1:first').html('Delete MC Maxtemp LUT') $('#delete_lightbox_entry_info').html('LUT Name: '+lut.name) $('#delete_lightbox_delete').unbind('click') $('#delete_lightbox_delete').click(() -> self.deleteLUTConfirmed_(lut)) $('#delete_lightbox_cancel').unbind('click') $('#delete_lightbox_cancel').click(() -> self.deleteDialog.close()) self.deleteDialog.open(); deleteLUTConfirmed_: (lut) -> self=this $('#delete_lightbox_delete').hide() $('#delete_lightbox_cancel').hide() $('#delete_lightbox_delete_spinner').show() $.ajax({ url : '../resources/luts/mc_maxtemp/'+lut.id, type : 'DELETE', dataType : 'text', success : () -> self.deleteLUTDone_() }) deleteLUTDone_: () -> self=this $('#delete_lightbox_delete_spinner').hide() $('#delete_lightbox_delete').show() $('#delete_lightbox_cancel').show() @refresh() self.deleteDialog.close() refresh: () -> self=this $('#settings_lut_mc_maxtemp_table').hide() $('#settings_lut_mc_maxtemp_spinner').show() $.ajax({ url: '../resources/luts/mc_maxtemp-fast' type: 'GET' dataType: 'json' success: (d) -> self.luts_ = d.luts self.updateTable_() }) class window.SettingsLUTMaxTempLightbox constructor: () -> self=this $('#settings_luc_mc_maxtemp_edit_hours_per_mc').numeric({ negative: false }) $('#settings_luc_mc_maxtemp_edit_more').click(() -> self.moreTable()) $('#settings_lut_mc_maxtemp_edit_save').click(() -> self.save()) self.lutDialog = new IsadoreDialog('#settings_lut_mc_maxtemp_lightbox', { width: 550, close: () -> self.close() }) empty: () -> $('#settings_luc_mc_maxtemp_edit_hours_per_mc').val('') $('#settings_luc_mc_maxtemp_edit_name').val('') $('#settings_luc_mc_maxtemp_edit_table tbody').html('') update_: (lutId) -> self=this $('#settings_lut_mc_maxtemp_edit_open_spinner').show() $('#settings_lut_mc_maxtemp_lightbox_wrapper').hide() if lutId $.ajax({ url: '../resources/luts/mc_maxtemp/'+lutId type: 'GET' dataType: 'json' success: (d) -> self.lut_ = d self.update2_() }) else self.update2_() update2_: () -> self=this if @lut_ $('#settings_luc_mc_maxtemp_edit_name').val(@lut_.name) $('#settings_luc_mc_maxtemp_edit_hours_per_mc').val(@lut_.hours_per_mc.toFixed(2)) for v in @lut_.values $('#settings_luc_mc_maxtemp_edit_table tbody').append('<tr><td><input type="text"/></td><td><input type="text"/><td></tr>') inputs = $('#settings_luc_mc_maxtemp_edit_table tbody tr:last input') $(inputs[0]).val(v.mc.toFixed(2)).numeric({ negative: false }) $(inputs[1]).val(v.maxtemp.toFixed(2)).numeric({ negative: false }) @moreTable() $('#settings_lut_mc_maxtemp_edit_open_spinner').hide() $('#settings_lut_mc_maxtemp_lightbox_wrapper').show() cbResize() moreTable: () -> self=this for i in [0..5] $('#settings_luc_mc_maxtemp_edit_table tbody').append('<tr><td><input type="text"/></td><td><input type="text"/><td></tr>') inputs = $('#settings_luc_mc_maxtemp_edit_table tbody tr:last input') $(inputs[0]).numeric({ negative: false }) $(inputs[1]).numeric({ negative: false }) cbResize() close: () -> self=this if @closeCallback_ @closeCallback_() save: () -> self=this $('#settings_lut_mc_maxtemp_lightbox .success').empty().stop().animate({ opacity: '100' }).stop() $('#settings_lut_mc_maxtemp_lightbox .errors').empty().show() name = $('#settings_luc_mc_maxtemp_edit_name').val() hours_per_mc = parseFloat($('#settings_luc_mc_maxtemp_edit_hours_per_mc').val()) if not name $('#settings_lut_mc_maxtemp_lightbox .errors').html('Name is required.').show() return if isNaN(hours_per_mc) $('#settings_lut_mc_maxtemp_lightbox .errors').html('MC/hour is required.').show() return inputs = $('#settings_luc_mc_maxtemp_edit_table tbody input') mcs=[] maxtemps=[] for i in [0..inputs.length] by 2 mc = parseFloat($(inputs[i]).val()) maxtemp = parseFloat($(inputs[i+1]).val()) if not isNaN(mc)and not isNaN(maxtemp) mcs.push(mc) maxtemps.push(maxtemp) adata = { name: name hours_per_mc: hours_per_mc mcs:mcs.join(',') maxtemps: maxtemps.join(',') } $('#settings_lut_mc_maxtemp_edit_save_spinner').show() $('#settings_lut_mc_maxtemp_edit_save').hide() $('#settings_lut_mc_maxtemp_lightbox input, #settings_luc_mc_maxtemp_edit_table button').attr('disabled', true) if not @lut_ $.ajax({ url: '../resources/luts/mc_maxtemp' type: 'POST' dataType: 'json' data: adata success: (d) -> lutId = d.xlink[0].split('/')[4] self.saveSuccess_(lutId) error: () -> self.saveFailed_() }) else $.ajax({ url: '../resources/luts/mc_maxtemp/'+@lut_.id type: 'PUT' dataType: 'text' data: adata success: (d) -> self.saveSuccess_(self.lut_.id) error: () -> self.saveFailed_() }) saveSuccess_: (lutId) -> self=this $('#settings_lut_mc_maxtemp_edit_save_spinner').hide() $('#settings_lut_mc_maxtemp_edit_save').show() $('#settings_lut_mc_maxtemp_lightbox input, #settings_luc_mc_maxtemp_edit_table button').removeAttr('disabled') $('#settings_lut_mc_maxtemp_lightbox .success').html('Saved.').show().fadeOut(3000) @empty() @update_(lutId) saveFailed_: () -> self=this $('#settings_lut_mc_maxtemp_edit_save_spinner').hide() $('#settings_lut_mc_maxtemp_edit_save').show() $('#settings_lut_mc_maxtemp_lightbox input, #settings_luc_mc_maxtemp_edit_table button').removeAttr('disabled') $('#settings_lut_mc_maxtemp_lightbox .errors').html('Error occurred during saving.').show() cbResize() open: (lutId, closeCallback) -> self=this $('#settings_lut_mc_maxtemp_lightbox .errors').empty().show() @lut_ = null @closeCallback_ = closeCallback @empty() @update_(lutId) self.lutDialog.open()
true
# Copyright 2010-2019 PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class window.SettingsLUTMaxTemp constructor: () -> self=this @maxTempLightbox_ = new SettingsLUTMaxTempLightbox() $('#settings_new_lut_mc_maxtemp').click( () -> self.maxTempLightbox_.open(null, () -> self.refresh()) ) self.deleteDialog = new IsadoreDialog('#delete_lightbox', { width: 400, title: 'Delete Confirm' }) updateTable_: () -> self=this $('#settings_lut_mc_maxtemp_spinner').hide() $('#settings_lut_mc_maxtemp_table').show() tableData = [] for lut in @luts_ tableData.push([lut.name, lut.hours_per_mc, HTMLHelper.actionButtons, lut.id]) $('#settings_lut_mc_maxtemp_table').dataTable({ bDestroy: true bPaginate: false bFilter: false aaData: tableData aoColumns: [ { sTitle: 'Name' } { sTitle: 'Hrs/MCPt' } { sTitle: 'Actions', bSortable: false } { sTitle: 'data-lut_id', bVisible: false } ] fnRowCallback: (nRow, aData, ididx, ididxf) -> nRow.setAttribute('data-lut_id', aData[3]) $('td:eq(2)', nRow).addClass('action') return nRow }) $('#settings_lut_mc_maxtemp_table span.action[data-action_type="edit"]').click((event) -> self.editLUT_(event) ) $('#settings_lut_mc_maxtemp_table span.action[data-action_type="delete"]').click((event) -> self.deleteLUT_(event) ) fixHeights() editLUT_: (event) -> self=this id=parseInt($(event.currentTarget).closest('tr').attr('data-lut_id')) @maxTempLightbox_.open(id, () -> self.refresh()) deleteLUT_: (event) -> self=this id=_.parseInt($(event.currentTarget).closest('tr').attr('data-lut_id')) lut = _.findWhere(@luts_, {'id': id}) $('#delete_lightbox_delete_spinner').hide() $('#delete_lightbox_delete').show() $('#delete_lightbox_cancel').show() $('#delete_lightbox h1:first').html('Delete MC Maxtemp LUT') $('#delete_lightbox_entry_info').html('LUT Name: '+lut.name) $('#delete_lightbox_delete').unbind('click') $('#delete_lightbox_delete').click(() -> self.deleteLUTConfirmed_(lut)) $('#delete_lightbox_cancel').unbind('click') $('#delete_lightbox_cancel').click(() -> self.deleteDialog.close()) self.deleteDialog.open(); deleteLUTConfirmed_: (lut) -> self=this $('#delete_lightbox_delete').hide() $('#delete_lightbox_cancel').hide() $('#delete_lightbox_delete_spinner').show() $.ajax({ url : '../resources/luts/mc_maxtemp/'+lut.id, type : 'DELETE', dataType : 'text', success : () -> self.deleteLUTDone_() }) deleteLUTDone_: () -> self=this $('#delete_lightbox_delete_spinner').hide() $('#delete_lightbox_delete').show() $('#delete_lightbox_cancel').show() @refresh() self.deleteDialog.close() refresh: () -> self=this $('#settings_lut_mc_maxtemp_table').hide() $('#settings_lut_mc_maxtemp_spinner').show() $.ajax({ url: '../resources/luts/mc_maxtemp-fast' type: 'GET' dataType: 'json' success: (d) -> self.luts_ = d.luts self.updateTable_() }) class window.SettingsLUTMaxTempLightbox constructor: () -> self=this $('#settings_luc_mc_maxtemp_edit_hours_per_mc').numeric({ negative: false }) $('#settings_luc_mc_maxtemp_edit_more').click(() -> self.moreTable()) $('#settings_lut_mc_maxtemp_edit_save').click(() -> self.save()) self.lutDialog = new IsadoreDialog('#settings_lut_mc_maxtemp_lightbox', { width: 550, close: () -> self.close() }) empty: () -> $('#settings_luc_mc_maxtemp_edit_hours_per_mc').val('') $('#settings_luc_mc_maxtemp_edit_name').val('') $('#settings_luc_mc_maxtemp_edit_table tbody').html('') update_: (lutId) -> self=this $('#settings_lut_mc_maxtemp_edit_open_spinner').show() $('#settings_lut_mc_maxtemp_lightbox_wrapper').hide() if lutId $.ajax({ url: '../resources/luts/mc_maxtemp/'+lutId type: 'GET' dataType: 'json' success: (d) -> self.lut_ = d self.update2_() }) else self.update2_() update2_: () -> self=this if @lut_ $('#settings_luc_mc_maxtemp_edit_name').val(@lut_.name) $('#settings_luc_mc_maxtemp_edit_hours_per_mc').val(@lut_.hours_per_mc.toFixed(2)) for v in @lut_.values $('#settings_luc_mc_maxtemp_edit_table tbody').append('<tr><td><input type="text"/></td><td><input type="text"/><td></tr>') inputs = $('#settings_luc_mc_maxtemp_edit_table tbody tr:last input') $(inputs[0]).val(v.mc.toFixed(2)).numeric({ negative: false }) $(inputs[1]).val(v.maxtemp.toFixed(2)).numeric({ negative: false }) @moreTable() $('#settings_lut_mc_maxtemp_edit_open_spinner').hide() $('#settings_lut_mc_maxtemp_lightbox_wrapper').show() cbResize() moreTable: () -> self=this for i in [0..5] $('#settings_luc_mc_maxtemp_edit_table tbody').append('<tr><td><input type="text"/></td><td><input type="text"/><td></tr>') inputs = $('#settings_luc_mc_maxtemp_edit_table tbody tr:last input') $(inputs[0]).numeric({ negative: false }) $(inputs[1]).numeric({ negative: false }) cbResize() close: () -> self=this if @closeCallback_ @closeCallback_() save: () -> self=this $('#settings_lut_mc_maxtemp_lightbox .success').empty().stop().animate({ opacity: '100' }).stop() $('#settings_lut_mc_maxtemp_lightbox .errors').empty().show() name = $('#settings_luc_mc_maxtemp_edit_name').val() hours_per_mc = parseFloat($('#settings_luc_mc_maxtemp_edit_hours_per_mc').val()) if not name $('#settings_lut_mc_maxtemp_lightbox .errors').html('Name is required.').show() return if isNaN(hours_per_mc) $('#settings_lut_mc_maxtemp_lightbox .errors').html('MC/hour is required.').show() return inputs = $('#settings_luc_mc_maxtemp_edit_table tbody input') mcs=[] maxtemps=[] for i in [0..inputs.length] by 2 mc = parseFloat($(inputs[i]).val()) maxtemp = parseFloat($(inputs[i+1]).val()) if not isNaN(mc)and not isNaN(maxtemp) mcs.push(mc) maxtemps.push(maxtemp) adata = { name: name hours_per_mc: hours_per_mc mcs:mcs.join(',') maxtemps: maxtemps.join(',') } $('#settings_lut_mc_maxtemp_edit_save_spinner').show() $('#settings_lut_mc_maxtemp_edit_save').hide() $('#settings_lut_mc_maxtemp_lightbox input, #settings_luc_mc_maxtemp_edit_table button').attr('disabled', true) if not @lut_ $.ajax({ url: '../resources/luts/mc_maxtemp' type: 'POST' dataType: 'json' data: adata success: (d) -> lutId = d.xlink[0].split('/')[4] self.saveSuccess_(lutId) error: () -> self.saveFailed_() }) else $.ajax({ url: '../resources/luts/mc_maxtemp/'+@lut_.id type: 'PUT' dataType: 'text' data: adata success: (d) -> self.saveSuccess_(self.lut_.id) error: () -> self.saveFailed_() }) saveSuccess_: (lutId) -> self=this $('#settings_lut_mc_maxtemp_edit_save_spinner').hide() $('#settings_lut_mc_maxtemp_edit_save').show() $('#settings_lut_mc_maxtemp_lightbox input, #settings_luc_mc_maxtemp_edit_table button').removeAttr('disabled') $('#settings_lut_mc_maxtemp_lightbox .success').html('Saved.').show().fadeOut(3000) @empty() @update_(lutId) saveFailed_: () -> self=this $('#settings_lut_mc_maxtemp_edit_save_spinner').hide() $('#settings_lut_mc_maxtemp_edit_save').show() $('#settings_lut_mc_maxtemp_lightbox input, #settings_luc_mc_maxtemp_edit_table button').removeAttr('disabled') $('#settings_lut_mc_maxtemp_lightbox .errors').html('Error occurred during saving.').show() cbResize() open: (lutId, closeCallback) -> self=this $('#settings_lut_mc_maxtemp_lightbox .errors').empty().show() @lut_ = null @closeCallback_ = closeCallback @empty() @update_(lutId) self.lutDialog.open()
[ { "context": " sampleData = [\n key: 'series1'\n values: [\n ", "end": 2832, "score": 0.5057478547096252, "start": 2825, "tag": "KEY", "value": "series1" }, { "context": " data = [\n key: ...
test/chart.coffee
robinfhu/forest-d3
58
describe 'Chart', -> describe 'smoke tests', -> it 'should exist', -> expect(ForestD3).to.exist expect(ForestD3.Chart).to.exist expect(ForestD3.StackedChart).to.exist expect(ForestD3.version).to.exist describe 'chart API', -> chart = null container = null beforeEach -> container = document.createElement 'div' container.style.width = '500px' container.style.height = '400px' document.body.appendChild container afterEach -> chart.destroy() it 'can accept container DOM', -> chart = new ForestD3.Chart() chart.container.should.exist chart.container container chart.container().querySelector.should.exist it 'can render an <svg> element (only once)', -> chart = new ForestD3.Chart container chart.render.should.exist svg = container.querySelector('svg') svg.should.exist it 'applies forest-d3 class to container', -> chart = new ForestD3.Chart container $(container).hasClass('forest-d3').should.be.true describe 'Scatter Chart', -> it 'draws a single point', -> sampleData = [ key: 'series1' values: [ [0,0] ] ] chart = new ForestD3.Chart container chart.data.should.exist chart.data(sampleData).render() circle = $(container).find('svg g.series path.point') circle.length.should.equal 1, 'one <path> point' it 'renders the chart frame once', -> chart = new ForestD3.Chart container chart.data([]).render().render() rect = $(container).find('svg rect.backdrop') rect.length.should.equal 1 canvas = $(container).find('svg g.canvas') canvas.length.should.equal 1 it 'renders axes', -> chart = new ForestD3.Chart container sampleData = [ key: 'series1' values: [ [0,0] [1,1] ] ] chart.data(sampleData).render() xTicks = $(container).find('.x-axis .tick') xTicks.length.should.be.greaterThan 0 yTicks = $(container).find('.y-axis .tick') yTicks.length.should.be.greaterThan 0 it 'formats x-axis tick labels', -> chart = new ForestD3.Chart container sampleData = [ key: 'series1' values: [ [ (new Date(2012, 0, 1)).getTime(), 0] [ (new Date(2012, 0, 2)).getTime(), 2] ] ] chart.xTickFormat (d)-> d3.time.format('%Y-%m-%d')(new Date d) chart.ordinal(true).data(sampleData).render() tickFormat = chart.xAxis.tickFormat() tickFormat(0).should.equal '2012-01-01' tickFormat(1).should.equal '2012-01-02' it 'renders more than one series', -> chart = new ForestD3.Chart container sampleData = [ key: 'foo' values: [ [0,0] ] , key: 'bar' values: [ [1,1] ] , key: 'maz' values: [ [2,2] ] ] chart.data(sampleData).render() series = $(container).find('g.series') series.length.should.equal 3, 'three groups' series.eq(0)[0] .getAttribute('class').should.contain 'series-foo' series.eq(1)[0] .getAttribute('class').should.contain 'series-bar' series.eq(2)[0] .getAttribute('class').should.contain 'series-maz' it 'does not render hidden series', (done)-> chart = new ForestD3.Chart container sampleData = [ key: 'foo' values: [ [0,0] ] , key: 'bar' values: [ [1,1] ] , key: 'maz' values: [ [2,2] ] ] chart.data(sampleData) chart.data().hide(['bar']) chart.render() series = $(container).find('g.series') series.length.should.equal 2, 'two series only' series.find('.series-bar').length.should.equal 0 chart.data().show('bar') chart.render() series = $(container).find('g.series') series.length.should.equal 3, 'three now' chart.data().hide('maz') chart.render() setTimeout -> series = $(container).find('g.series') series.length.should.equal 2, 'back to two series only' done() , 400 it 'keeps chart items in order', (done)-> chart = new ForestD3.Chart container sampleData = [ key: 'foo' values: [ [0,0] ] , key: 'bar' values: [ [1,1] ] , key: 'maz' values: [ [2,2] ] ] chart.data(sampleData) chart.data().hide(['bar']).render() chart.data().show('bar').render() items = $(container).find('g.series') items.get(0).getAttribute('class').should.contain 'series-foo' items.get(1).getAttribute('class').should.contain 'series-bar' items.get(2).getAttribute('class').should.contain 'series-maz' done() describe 'Marker Lines', -> it 'can render horizontal line (y-axis marker)', (done)-> data = [ key: 'marker1' label: 'Threshold' type: 'marker' value: 0 axis: 'y' ] chart = new ForestD3.Chart container chart.data(data).render() chartItems = $(container).find('g.series') chartItems.length.should.equal 1 line = chartItems.eq(0).find('line') line.length.should.equal 1, 'line exists' text = chartItems.eq(0).find('text') text.text().should.contain 'Threshold' setTimeout -> line[0].getAttribute('x1').should.equal '0' line[0].getAttribute('y1') .should.equal line[0].getAttribute('y2') done() , 300 it 'can render horizontal line (x-axis marker)', (done)-> data = [ key: 'marker1' type: 'marker' label: 'Threshold' value: 0 axis: 'x' ] chart = new ForestD3.Chart container chart.data(data).render() line = $(container).find('g.series line') text = $(container).find('g.series text') text.text().should.contain 'Threshold' setTimeout -> line[0].getAttribute('y1').should.equal '0' line[0].getAttribute('x1') .should.equal line[0].getAttribute('x2') done() , 300 describe 'Regions', -> it 'can render regions', -> data = [ key: 'region1' type: 'region' label: 'Tolerance' axis: 'x' values: [-1, 1] , key: 'region2' type: 'region' axis: 'y' values: [-1, 1] ] chart = new ForestD3.Chart container chart.data(data).render() rect = $(container).find('g.series rect') rect.length.should.equal 2, 'two rectangles' describe 'Line Chart', -> it 'can render an SVG line', -> data = [ key: 'line1' type: 'line' values: [ [0,0] [1,1] [2,4] ] ] chart = new ForestD3.Chart container chart.data(data).render() line = $(container).find('g.series path.line') line.length.should.equal 1, 'line path exists' it 'can render an SVG line and path if area=true', -> data = [ key: 'line1' type: 'line' area: true values: [ [0,0] [1,1] [2,4] ] ] chart = new ForestD3.Chart container chart.data(data).render() line = $(container).find('g.series path.line') line.length.should.equal 1, 'line path exists' area = $(container).find('g.series path.area') area.length.should.equal 1, 'area path exists' describe 'Bar Chart', -> it 'can render bar chart', -> data = [ key: 's1' type: 'bar' values: [ [0, 10] [1, 20] [2, 25] ] , key: 's2' type: 'bar' values: [ [0, 11] [1, 22] [2, 27] ] ] chart = new ForestD3.Chart container chart.data(data).render() bars1 = $(container).find('g.series-s1 rect') bars1.length.should.equal 3, 'three bars s1' bars2 = $(container).find('g.series-s2 rect') bars2.length.should.equal 3, 'three bars s2' it 'should set max width for each bar', (done)-> data = [ key: 's1' type: 'bar' values: [ ['Population', 234] ] ] chart = new ForestD3.Chart container chart.ordinal(true).data(data).render() setTimeout -> bar = $(container).find('g.series-s1 rect').get(0) width = parseFloat(bar.getAttribute('width')) width.should.be.lessThan 300 done() , 300 it 'can use reduceXTicks=false to show all x-labels', (done)-> data = series1: type: 'bar' values: [ 'January','February','March','April','May', 'June','July','August','September','October' ].map (m)-> [m, Math.random()] chart = new ForestD3.Chart container chart.reduceXTicks(false).data(data).render() setTimeout -> xTicks = $(container).find('g.x-axis .tick') xTicks.length.should.equal 10 done() , 300 it 'can class bars differently based on a function', (done)-> data = series1: type: 'bar' classed: (d)-> if d[1] > 1.0 '-highlight-bar' else '' values: [ 'January','February','March','April','May', 'June','July','August','September','October' ].map (m)-> [m, Math.random()] data.series1.values.push ['November', 1.3] chart = new ForestD3.Chart container chart.data(data).render() setTimeout -> bar = $(container).find('rect.bar.-highlight-bar') bar.length.should.equal 1 done() , 300 describe 'Changing Chart Type Dynamically', -> it 'can switch a series type dynamically', (done)-> data = series: type: 'line' values: [0..20].map -> [Math.random(), Math.random()] chart = new ForestD3.Chart container chart.data(data).duration(0).render() setTimeout -> data.series.type = 'bar' chart.data(data).render() setTimeout -> items = $(container).find('g.series') items.length.should.equal 1, 'one series' line = items.eq(0).find('path.line') line.length.should.equal 0, 'no line' done() , 200 , 200 describe 'Chart Margins', -> it 'can set chart margins', -> data = [ key: 'line1' type: 'line' values: [ [0,0] [1,1] [2,4] ] ] chart = new ForestD3.Chart container chart.margin left: 130 top: 80 bottom: 40 right: 60 chart.data(data).render() canvas = $(container).find('g.canvas') canvas.attr('transform').should.equal "translate(130, 80)" chart.margin().should.deep.equal left: 130 top: 80 bottom: 40 right: 60 chart.margin left: 83 chart.margin().should.deep.equal left: 83 top: 80 bottom: 40 right: 60 chart.margin 88,11,33,66 chart.margin().should.deep.equal top: 88 right: 11 bottom: 33 left: 66 chart.margin 99, null, null, 23 chart.margin().should.deep.equal top: 99 right: 11 bottom: 33 left: 23 it 'cannot set margins so small it creates negative width', -> container.style.width = '30px' data = [ key: 'line1' type: 'line' values: [ [0,0] [1,1] [2,4] ] ] chart = new ForestD3.Chart container chart.margin left: 130 top: 80 bottom: 40 right: 60 chart.data(data).render() chart.canvasWidth.should.be.greaterThan 30 container.style.width = '500px' describe 'Highlighting a Series', -> it 'can highlight a series', (done)-> data = [ key: 'apples' type: 'line' values: [ [0,0] [1,1] [2,4] ] , key: 'oranges' type: 'line' values: [ [0,1] [1,3] [2,4] ] ] chart = new ForestD3.Chart container chart.data(data).render() setTimeout -> chart.highlightSeries('apples') $(container).find('g.series-apples.highlight') .length.should.equal 1, 'series-apples highlighted' done() , 200
195756
describe 'Chart', -> describe 'smoke tests', -> it 'should exist', -> expect(ForestD3).to.exist expect(ForestD3.Chart).to.exist expect(ForestD3.StackedChart).to.exist expect(ForestD3.version).to.exist describe 'chart API', -> chart = null container = null beforeEach -> container = document.createElement 'div' container.style.width = '500px' container.style.height = '400px' document.body.appendChild container afterEach -> chart.destroy() it 'can accept container DOM', -> chart = new ForestD3.Chart() chart.container.should.exist chart.container container chart.container().querySelector.should.exist it 'can render an <svg> element (only once)', -> chart = new ForestD3.Chart container chart.render.should.exist svg = container.querySelector('svg') svg.should.exist it 'applies forest-d3 class to container', -> chart = new ForestD3.Chart container $(container).hasClass('forest-d3').should.be.true describe 'Scatter Chart', -> it 'draws a single point', -> sampleData = [ key: 'series1' values: [ [0,0] ] ] chart = new ForestD3.Chart container chart.data.should.exist chart.data(sampleData).render() circle = $(container).find('svg g.series path.point') circle.length.should.equal 1, 'one <path> point' it 'renders the chart frame once', -> chart = new ForestD3.Chart container chart.data([]).render().render() rect = $(container).find('svg rect.backdrop') rect.length.should.equal 1 canvas = $(container).find('svg g.canvas') canvas.length.should.equal 1 it 'renders axes', -> chart = new ForestD3.Chart container sampleData = [ key: 'series1' values: [ [0,0] [1,1] ] ] chart.data(sampleData).render() xTicks = $(container).find('.x-axis .tick') xTicks.length.should.be.greaterThan 0 yTicks = $(container).find('.y-axis .tick') yTicks.length.should.be.greaterThan 0 it 'formats x-axis tick labels', -> chart = new ForestD3.Chart container sampleData = [ key: '<KEY>' values: [ [ (new Date(2012, 0, 1)).getTime(), 0] [ (new Date(2012, 0, 2)).getTime(), 2] ] ] chart.xTickFormat (d)-> d3.time.format('%Y-%m-%d')(new Date d) chart.ordinal(true).data(sampleData).render() tickFormat = chart.xAxis.tickFormat() tickFormat(0).should.equal '2012-01-01' tickFormat(1).should.equal '2012-01-02' it 'renders more than one series', -> chart = new ForestD3.Chart container sampleData = [ key: 'foo' values: [ [0,0] ] , key: 'bar' values: [ [1,1] ] , key: 'maz' values: [ [2,2] ] ] chart.data(sampleData).render() series = $(container).find('g.series') series.length.should.equal 3, 'three groups' series.eq(0)[0] .getAttribute('class').should.contain 'series-foo' series.eq(1)[0] .getAttribute('class').should.contain 'series-bar' series.eq(2)[0] .getAttribute('class').should.contain 'series-maz' it 'does not render hidden series', (done)-> chart = new ForestD3.Chart container sampleData = [ key: 'foo' values: [ [0,0] ] , key: 'bar' values: [ [1,1] ] , key: 'maz' values: [ [2,2] ] ] chart.data(sampleData) chart.data().hide(['bar']) chart.render() series = $(container).find('g.series') series.length.should.equal 2, 'two series only' series.find('.series-bar').length.should.equal 0 chart.data().show('bar') chart.render() series = $(container).find('g.series') series.length.should.equal 3, 'three now' chart.data().hide('maz') chart.render() setTimeout -> series = $(container).find('g.series') series.length.should.equal 2, 'back to two series only' done() , 400 it 'keeps chart items in order', (done)-> chart = new ForestD3.Chart container sampleData = [ key: 'foo' values: [ [0,0] ] , key: 'bar' values: [ [1,1] ] , key: 'maz' values: [ [2,2] ] ] chart.data(sampleData) chart.data().hide(['bar']).render() chart.data().show('bar').render() items = $(container).find('g.series') items.get(0).getAttribute('class').should.contain 'series-foo' items.get(1).getAttribute('class').should.contain 'series-bar' items.get(2).getAttribute('class').should.contain 'series-maz' done() describe 'Marker Lines', -> it 'can render horizontal line (y-axis marker)', (done)-> data = [ key: '<KEY>1' label: 'Threshold' type: 'marker' value: 0 axis: 'y' ] chart = new ForestD3.Chart container chart.data(data).render() chartItems = $(container).find('g.series') chartItems.length.should.equal 1 line = chartItems.eq(0).find('line') line.length.should.equal 1, 'line exists' text = chartItems.eq(0).find('text') text.text().should.contain 'Threshold' setTimeout -> line[0].getAttribute('x1').should.equal '0' line[0].getAttribute('y1') .should.equal line[0].getAttribute('y2') done() , 300 it 'can render horizontal line (x-axis marker)', (done)-> data = [ key: 'marker1' type: 'marker' label: 'Threshold' value: 0 axis: 'x' ] chart = new ForestD3.Chart container chart.data(data).render() line = $(container).find('g.series line') text = $(container).find('g.series text') text.text().should.contain 'Threshold' setTimeout -> line[0].getAttribute('y1').should.equal '0' line[0].getAttribute('x1') .should.equal line[0].getAttribute('x2') done() , 300 describe 'Regions', -> it 'can render regions', -> data = [ key: 'region1' type: 'region' label: 'Tolerance' axis: 'x' values: [-1, 1] , key: 'region2' type: 'region' axis: 'y' values: [-1, 1] ] chart = new ForestD3.Chart container chart.data(data).render() rect = $(container).find('g.series rect') rect.length.should.equal 2, 'two rectangles' describe 'Line Chart', -> it 'can render an SVG line', -> data = [ key: 'line1' type: 'line' values: [ [0,0] [1,1] [2,4] ] ] chart = new ForestD3.Chart container chart.data(data).render() line = $(container).find('g.series path.line') line.length.should.equal 1, 'line path exists' it 'can render an SVG line and path if area=true', -> data = [ key: 'line1' type: 'line' area: true values: [ [0,0] [1,1] [2,4] ] ] chart = new ForestD3.Chart container chart.data(data).render() line = $(container).find('g.series path.line') line.length.should.equal 1, 'line path exists' area = $(container).find('g.series path.area') area.length.should.equal 1, 'area path exists' describe 'Bar Chart', -> it 'can render bar chart', -> data = [ key: 's1' type: 'bar' values: [ [0, 10] [1, 20] [2, 25] ] , key: 's2' type: 'bar' values: [ [0, 11] [1, 22] [2, 27] ] ] chart = new ForestD3.Chart container chart.data(data).render() bars1 = $(container).find('g.series-s1 rect') bars1.length.should.equal 3, 'three bars s1' bars2 = $(container).find('g.series-s2 rect') bars2.length.should.equal 3, 'three bars s2' it 'should set max width for each bar', (done)-> data = [ key: 's1' type: 'bar' values: [ ['Population', 234] ] ] chart = new ForestD3.Chart container chart.ordinal(true).data(data).render() setTimeout -> bar = $(container).find('g.series-s1 rect').get(0) width = parseFloat(bar.getAttribute('width')) width.should.be.lessThan 300 done() , 300 it 'can use reduceXTicks=false to show all x-labels', (done)-> data = series1: type: 'bar' values: [ 'January','February','March','April','May', 'June','July','August','September','October' ].map (m)-> [m, Math.random()] chart = new ForestD3.Chart container chart.reduceXTicks(false).data(data).render() setTimeout -> xTicks = $(container).find('g.x-axis .tick') xTicks.length.should.equal 10 done() , 300 it 'can class bars differently based on a function', (done)-> data = series1: type: 'bar' classed: (d)-> if d[1] > 1.0 '-highlight-bar' else '' values: [ 'January','February','March','April','May', 'June','July','August','September','October' ].map (m)-> [m, Math.random()] data.series1.values.push ['November', 1.3] chart = new ForestD3.Chart container chart.data(data).render() setTimeout -> bar = $(container).find('rect.bar.-highlight-bar') bar.length.should.equal 1 done() , 300 describe 'Changing Chart Type Dynamically', -> it 'can switch a series type dynamically', (done)-> data = series: type: 'line' values: [0..20].map -> [Math.random(), Math.random()] chart = new ForestD3.Chart container chart.data(data).duration(0).render() setTimeout -> data.series.type = 'bar' chart.data(data).render() setTimeout -> items = $(container).find('g.series') items.length.should.equal 1, 'one series' line = items.eq(0).find('path.line') line.length.should.equal 0, 'no line' done() , 200 , 200 describe 'Chart Margins', -> it 'can set chart margins', -> data = [ key: 'line1' type: 'line' values: [ [0,0] [1,1] [2,4] ] ] chart = new ForestD3.Chart container chart.margin left: 130 top: 80 bottom: 40 right: 60 chart.data(data).render() canvas = $(container).find('g.canvas') canvas.attr('transform').should.equal "translate(130, 80)" chart.margin().should.deep.equal left: 130 top: 80 bottom: 40 right: 60 chart.margin left: 83 chart.margin().should.deep.equal left: 83 top: 80 bottom: 40 right: 60 chart.margin 88,11,33,66 chart.margin().should.deep.equal top: 88 right: 11 bottom: 33 left: 66 chart.margin 99, null, null, 23 chart.margin().should.deep.equal top: 99 right: 11 bottom: 33 left: 23 it 'cannot set margins so small it creates negative width', -> container.style.width = '30px' data = [ key: 'line1' type: 'line' values: [ [0,0] [1,1] [2,4] ] ] chart = new ForestD3.Chart container chart.margin left: 130 top: 80 bottom: 40 right: 60 chart.data(data).render() chart.canvasWidth.should.be.greaterThan 30 container.style.width = '500px' describe 'Highlighting a Series', -> it 'can highlight a series', (done)-> data = [ key: 'apples' type: 'line' values: [ [0,0] [1,1] [2,4] ] , key: 'oranges' type: 'line' values: [ [0,1] [1,3] [2,4] ] ] chart = new ForestD3.Chart container chart.data(data).render() setTimeout -> chart.highlightSeries('apples') $(container).find('g.series-apples.highlight') .length.should.equal 1, 'series-apples highlighted' done() , 200
true
describe 'Chart', -> describe 'smoke tests', -> it 'should exist', -> expect(ForestD3).to.exist expect(ForestD3.Chart).to.exist expect(ForestD3.StackedChart).to.exist expect(ForestD3.version).to.exist describe 'chart API', -> chart = null container = null beforeEach -> container = document.createElement 'div' container.style.width = '500px' container.style.height = '400px' document.body.appendChild container afterEach -> chart.destroy() it 'can accept container DOM', -> chart = new ForestD3.Chart() chart.container.should.exist chart.container container chart.container().querySelector.should.exist it 'can render an <svg> element (only once)', -> chart = new ForestD3.Chart container chart.render.should.exist svg = container.querySelector('svg') svg.should.exist it 'applies forest-d3 class to container', -> chart = new ForestD3.Chart container $(container).hasClass('forest-d3').should.be.true describe 'Scatter Chart', -> it 'draws a single point', -> sampleData = [ key: 'series1' values: [ [0,0] ] ] chart = new ForestD3.Chart container chart.data.should.exist chart.data(sampleData).render() circle = $(container).find('svg g.series path.point') circle.length.should.equal 1, 'one <path> point' it 'renders the chart frame once', -> chart = new ForestD3.Chart container chart.data([]).render().render() rect = $(container).find('svg rect.backdrop') rect.length.should.equal 1 canvas = $(container).find('svg g.canvas') canvas.length.should.equal 1 it 'renders axes', -> chart = new ForestD3.Chart container sampleData = [ key: 'series1' values: [ [0,0] [1,1] ] ] chart.data(sampleData).render() xTicks = $(container).find('.x-axis .tick') xTicks.length.should.be.greaterThan 0 yTicks = $(container).find('.y-axis .tick') yTicks.length.should.be.greaterThan 0 it 'formats x-axis tick labels', -> chart = new ForestD3.Chart container sampleData = [ key: 'PI:KEY:<KEY>END_PI' values: [ [ (new Date(2012, 0, 1)).getTime(), 0] [ (new Date(2012, 0, 2)).getTime(), 2] ] ] chart.xTickFormat (d)-> d3.time.format('%Y-%m-%d')(new Date d) chart.ordinal(true).data(sampleData).render() tickFormat = chart.xAxis.tickFormat() tickFormat(0).should.equal '2012-01-01' tickFormat(1).should.equal '2012-01-02' it 'renders more than one series', -> chart = new ForestD3.Chart container sampleData = [ key: 'foo' values: [ [0,0] ] , key: 'bar' values: [ [1,1] ] , key: 'maz' values: [ [2,2] ] ] chart.data(sampleData).render() series = $(container).find('g.series') series.length.should.equal 3, 'three groups' series.eq(0)[0] .getAttribute('class').should.contain 'series-foo' series.eq(1)[0] .getAttribute('class').should.contain 'series-bar' series.eq(2)[0] .getAttribute('class').should.contain 'series-maz' it 'does not render hidden series', (done)-> chart = new ForestD3.Chart container sampleData = [ key: 'foo' values: [ [0,0] ] , key: 'bar' values: [ [1,1] ] , key: 'maz' values: [ [2,2] ] ] chart.data(sampleData) chart.data().hide(['bar']) chart.render() series = $(container).find('g.series') series.length.should.equal 2, 'two series only' series.find('.series-bar').length.should.equal 0 chart.data().show('bar') chart.render() series = $(container).find('g.series') series.length.should.equal 3, 'three now' chart.data().hide('maz') chart.render() setTimeout -> series = $(container).find('g.series') series.length.should.equal 2, 'back to two series only' done() , 400 it 'keeps chart items in order', (done)-> chart = new ForestD3.Chart container sampleData = [ key: 'foo' values: [ [0,0] ] , key: 'bar' values: [ [1,1] ] , key: 'maz' values: [ [2,2] ] ] chart.data(sampleData) chart.data().hide(['bar']).render() chart.data().show('bar').render() items = $(container).find('g.series') items.get(0).getAttribute('class').should.contain 'series-foo' items.get(1).getAttribute('class').should.contain 'series-bar' items.get(2).getAttribute('class').should.contain 'series-maz' done() describe 'Marker Lines', -> it 'can render horizontal line (y-axis marker)', (done)-> data = [ key: 'PI:KEY:<KEY>END_PI1' label: 'Threshold' type: 'marker' value: 0 axis: 'y' ] chart = new ForestD3.Chart container chart.data(data).render() chartItems = $(container).find('g.series') chartItems.length.should.equal 1 line = chartItems.eq(0).find('line') line.length.should.equal 1, 'line exists' text = chartItems.eq(0).find('text') text.text().should.contain 'Threshold' setTimeout -> line[0].getAttribute('x1').should.equal '0' line[0].getAttribute('y1') .should.equal line[0].getAttribute('y2') done() , 300 it 'can render horizontal line (x-axis marker)', (done)-> data = [ key: 'marker1' type: 'marker' label: 'Threshold' value: 0 axis: 'x' ] chart = new ForestD3.Chart container chart.data(data).render() line = $(container).find('g.series line') text = $(container).find('g.series text') text.text().should.contain 'Threshold' setTimeout -> line[0].getAttribute('y1').should.equal '0' line[0].getAttribute('x1') .should.equal line[0].getAttribute('x2') done() , 300 describe 'Regions', -> it 'can render regions', -> data = [ key: 'region1' type: 'region' label: 'Tolerance' axis: 'x' values: [-1, 1] , key: 'region2' type: 'region' axis: 'y' values: [-1, 1] ] chart = new ForestD3.Chart container chart.data(data).render() rect = $(container).find('g.series rect') rect.length.should.equal 2, 'two rectangles' describe 'Line Chart', -> it 'can render an SVG line', -> data = [ key: 'line1' type: 'line' values: [ [0,0] [1,1] [2,4] ] ] chart = new ForestD3.Chart container chart.data(data).render() line = $(container).find('g.series path.line') line.length.should.equal 1, 'line path exists' it 'can render an SVG line and path if area=true', -> data = [ key: 'line1' type: 'line' area: true values: [ [0,0] [1,1] [2,4] ] ] chart = new ForestD3.Chart container chart.data(data).render() line = $(container).find('g.series path.line') line.length.should.equal 1, 'line path exists' area = $(container).find('g.series path.area') area.length.should.equal 1, 'area path exists' describe 'Bar Chart', -> it 'can render bar chart', -> data = [ key: 's1' type: 'bar' values: [ [0, 10] [1, 20] [2, 25] ] , key: 's2' type: 'bar' values: [ [0, 11] [1, 22] [2, 27] ] ] chart = new ForestD3.Chart container chart.data(data).render() bars1 = $(container).find('g.series-s1 rect') bars1.length.should.equal 3, 'three bars s1' bars2 = $(container).find('g.series-s2 rect') bars2.length.should.equal 3, 'three bars s2' it 'should set max width for each bar', (done)-> data = [ key: 's1' type: 'bar' values: [ ['Population', 234] ] ] chart = new ForestD3.Chart container chart.ordinal(true).data(data).render() setTimeout -> bar = $(container).find('g.series-s1 rect').get(0) width = parseFloat(bar.getAttribute('width')) width.should.be.lessThan 300 done() , 300 it 'can use reduceXTicks=false to show all x-labels', (done)-> data = series1: type: 'bar' values: [ 'January','February','March','April','May', 'June','July','August','September','October' ].map (m)-> [m, Math.random()] chart = new ForestD3.Chart container chart.reduceXTicks(false).data(data).render() setTimeout -> xTicks = $(container).find('g.x-axis .tick') xTicks.length.should.equal 10 done() , 300 it 'can class bars differently based on a function', (done)-> data = series1: type: 'bar' classed: (d)-> if d[1] > 1.0 '-highlight-bar' else '' values: [ 'January','February','March','April','May', 'June','July','August','September','October' ].map (m)-> [m, Math.random()] data.series1.values.push ['November', 1.3] chart = new ForestD3.Chart container chart.data(data).render() setTimeout -> bar = $(container).find('rect.bar.-highlight-bar') bar.length.should.equal 1 done() , 300 describe 'Changing Chart Type Dynamically', -> it 'can switch a series type dynamically', (done)-> data = series: type: 'line' values: [0..20].map -> [Math.random(), Math.random()] chart = new ForestD3.Chart container chart.data(data).duration(0).render() setTimeout -> data.series.type = 'bar' chart.data(data).render() setTimeout -> items = $(container).find('g.series') items.length.should.equal 1, 'one series' line = items.eq(0).find('path.line') line.length.should.equal 0, 'no line' done() , 200 , 200 describe 'Chart Margins', -> it 'can set chart margins', -> data = [ key: 'line1' type: 'line' values: [ [0,0] [1,1] [2,4] ] ] chart = new ForestD3.Chart container chart.margin left: 130 top: 80 bottom: 40 right: 60 chart.data(data).render() canvas = $(container).find('g.canvas') canvas.attr('transform').should.equal "translate(130, 80)" chart.margin().should.deep.equal left: 130 top: 80 bottom: 40 right: 60 chart.margin left: 83 chart.margin().should.deep.equal left: 83 top: 80 bottom: 40 right: 60 chart.margin 88,11,33,66 chart.margin().should.deep.equal top: 88 right: 11 bottom: 33 left: 66 chart.margin 99, null, null, 23 chart.margin().should.deep.equal top: 99 right: 11 bottom: 33 left: 23 it 'cannot set margins so small it creates negative width', -> container.style.width = '30px' data = [ key: 'line1' type: 'line' values: [ [0,0] [1,1] [2,4] ] ] chart = new ForestD3.Chart container chart.margin left: 130 top: 80 bottom: 40 right: 60 chart.data(data).render() chart.canvasWidth.should.be.greaterThan 30 container.style.width = '500px' describe 'Highlighting a Series', -> it 'can highlight a series', (done)-> data = [ key: 'apples' type: 'line' values: [ [0,0] [1,1] [2,4] ] , key: 'oranges' type: 'line' values: [ [0,1] [1,3] [2,4] ] ] chart = new ForestD3.Chart container chart.data(data).render() setTimeout -> chart.highlightSeries('apples') $(container).find('g.series-apples.highlight') .length.should.equal 1, 'series-apples highlighted' done() , 200
[ { "context": "wse/SERVER-3229\n\t\t\t\t\tfixedKey = k.replace(/\\./g, '•').replace(/^\\$/, '฿')\n\t\t\t\t\tdoc[fixedKey] ?= v # d", "end": 214, "score": 0.575527012348175, "start": 213, "tag": "KEY", "value": "•" } ]
collections/_utils.coffee
sguignot/meteor-batch-mobile-ready
0
@CollectionUtils = fixKeysForMongo: (doc) -> if doc instanceof Object for k, v of doc if k.match(/\.|^\$/) # forbidden keys: https://jira.mongodb.org/browse/SERVER-3229 fixedKey = k.replace(/\./g, '•').replace(/^\$/, '฿') doc[fixedKey] ?= v # do not overwrite another existing key delete doc[k] CollectionUtils.fixKeysForMongo(doc[fixedKey]) else CollectionUtils.fixKeysForMongo(v) else if doc instanceof Array for e in doc CollectionUtils.fixKeysForMongo(e) return doc
44209
@CollectionUtils = fixKeysForMongo: (doc) -> if doc instanceof Object for k, v of doc if k.match(/\.|^\$/) # forbidden keys: https://jira.mongodb.org/browse/SERVER-3229 fixedKey = k.replace(/\./g, '<KEY>').replace(/^\$/, '฿') doc[fixedKey] ?= v # do not overwrite another existing key delete doc[k] CollectionUtils.fixKeysForMongo(doc[fixedKey]) else CollectionUtils.fixKeysForMongo(v) else if doc instanceof Array for e in doc CollectionUtils.fixKeysForMongo(e) return doc
true
@CollectionUtils = fixKeysForMongo: (doc) -> if doc instanceof Object for k, v of doc if k.match(/\.|^\$/) # forbidden keys: https://jira.mongodb.org/browse/SERVER-3229 fixedKey = k.replace(/\./g, 'PI:KEY:<KEY>END_PI').replace(/^\$/, '฿') doc[fixedKey] ?= v # do not overwrite another existing key delete doc[k] CollectionUtils.fixKeysForMongo(doc[fixedKey]) else CollectionUtils.fixKeysForMongo(v) else if doc instanceof Array for e in doc CollectionUtils.fixKeysForMongo(e) return doc
[ { "context": "st:27017/claru-test'\n mongo:\n url: 'mongodb://127.0.0.1:27017/claru-test'\n host: '127.0.0.1'\n port:", "end": 131, "score": 0.9996918439865112, "start": 122, "tag": "IP_ADDRESS", "value": "127.0.0.1" }, { "context": "'mongodb://127.0.0.1:27017/claru-test'\n...
server/config/testing.coffee
stevelacy/claru
0
{join} = require 'path' module.exports = database: 'mongodb://localhost:27017/claru-test' mongo: url: 'mongodb://127.0.0.1:27017/claru-test' host: '127.0.0.1' port: 27017 name: 'claru-test' token: secret: 'IhoiUHyu6gtghj' debug: false
214782
{join} = require 'path' module.exports = database: 'mongodb://localhost:27017/claru-test' mongo: url: 'mongodb://127.0.0.1:27017/claru-test' host: '127.0.0.1' port: 27017 name: 'claru-test' token: secret: '<KEY>' debug: false
true
{join} = require 'path' module.exports = database: 'mongodb://localhost:27017/claru-test' mongo: url: 'mongodb://127.0.0.1:27017/claru-test' host: '127.0.0.1' port: 27017 name: 'claru-test' token: secret: 'PI:KEY:<KEY>END_PI' debug: false
[ { "context": "vices\n\n @class bkcore.GamepadController\n @author Mahesh Kulkarni <http://twitter.com/maheshkk>\n###\nclass GamepadCo", "end": 126, "score": 0.9998844265937805, "start": 111, "tag": "NAME", "value": "Mahesh Kulkarni" }, { "context": "ler\n @author Mahesh Kulkarni <...
webInterface/game/bkcore.coffee/controllers/GamepadController.coffee
ploh007/design-project
1,017
### GamepadController (Orientation + buttons) for touch devices @class bkcore.GamepadController @author Mahesh Kulkarni <http://twitter.com/maheshkk> ### class GamepadController @isCompatible: -> return ('getGamepads' of navigator) or ('webkitGetGamepads' of navigator) ### Creates a new GamepadController ### constructor: (@buttonPressCallback) -> @active = true @leftStickArray = [] @rightStickArray = [] ### @public ### updateAvailable: -> return false if not @active gamepads = if navigator.getGamepads then navigator.getGamepads() else navigator.webkitGetGamepads() return false if not gamepads?[0] gp = gamepads[0] return if not gp.buttons? or not gp.axes? @lstickx = gp.axes[0] accel = gp.buttons[0] lt = gp.buttons[6] rt = gp.buttons[7] sel = gp.buttons[8] # API fallback @acceleration = accel.pressed ? accel @ltrigger = lt.pressed ? lt @rtrigger = rt.pressed ? rt @select = sel.pressed ? sel @buttonPressCallback this true exports = exports ? @ exports.bkcore ||= {} exports.bkcore.controllers ||= {} exports.bkcore.controllers.GamepadController = GamepadController
177897
### GamepadController (Orientation + buttons) for touch devices @class bkcore.GamepadController @author <NAME> <http://twitter.com/maheshkk> ### class GamepadController @isCompatible: -> return ('getGamepads' of navigator) or ('webkitGetGamepads' of navigator) ### Creates a new GamepadController ### constructor: (@buttonPressCallback) -> @active = true @leftStickArray = [] @rightStickArray = [] ### @public ### updateAvailable: -> return false if not @active gamepads = if navigator.getGamepads then navigator.getGamepads() else navigator.webkitGetGamepads() return false if not gamepads?[0] gp = gamepads[0] return if not gp.buttons? or not gp.axes? @lstickx = gp.axes[0] accel = gp.buttons[0] lt = gp.buttons[6] rt = gp.buttons[7] sel = gp.buttons[8] # API fallback @acceleration = accel.pressed ? accel @ltrigger = lt.pressed ? lt @rtrigger = rt.pressed ? rt @select = sel.pressed ? sel @buttonPressCallback this true exports = exports ? @ exports.bkcore ||= {} exports.bkcore.controllers ||= {} exports.bkcore.controllers.GamepadController = GamepadController
true
### GamepadController (Orientation + buttons) for touch devices @class bkcore.GamepadController @author PI:NAME:<NAME>END_PI <http://twitter.com/maheshkk> ### class GamepadController @isCompatible: -> return ('getGamepads' of navigator) or ('webkitGetGamepads' of navigator) ### Creates a new GamepadController ### constructor: (@buttonPressCallback) -> @active = true @leftStickArray = [] @rightStickArray = [] ### @public ### updateAvailable: -> return false if not @active gamepads = if navigator.getGamepads then navigator.getGamepads() else navigator.webkitGetGamepads() return false if not gamepads?[0] gp = gamepads[0] return if not gp.buttons? or not gp.axes? @lstickx = gp.axes[0] accel = gp.buttons[0] lt = gp.buttons[6] rt = gp.buttons[7] sel = gp.buttons[8] # API fallback @acceleration = accel.pressed ? accel @ltrigger = lt.pressed ? lt @rtrigger = rt.pressed ? rt @select = sel.pressed ? sel @buttonPressCallback this true exports = exports ? @ exports.bkcore ||= {} exports.bkcore.controllers ||= {} exports.bkcore.controllers.GamepadController = GamepadController
[ { "context": " expect(latexObject).to.have.property \"author\", \"Acar E, Yener B\"\n\n it \"title\", ->\n expect(latexO", "end": 1515, "score": 0.9998508095741272, "start": 1509, "tag": "NAME", "value": "Acar E" }, { "context": "t(latexObject).to.have.property \"author\", \...
test/test.coffee
jschomay/latex-to-bibtex
1
{expect} = require "chai" path = require "path" {latexToArray parseLatexItem parseLatexArray formatParsedItem formatParsedArray renderItemToTemplate renderArrayToTemplate sortBy } = require "../parse" parseRules = require "../example/parseRules" formattingRules = require "../example/formattingrules" template = require "../example/template" latexArray = latexToArray path.join(__dirname, "/../example/sample.tex"), "bibitem" describe "latexToArray", -> it "changes latex to an array", -> expect(latexArray).to.be.an "Array" expect(latexArray).to.have.length 3 expect(latexArray[0]).to.be.a "String" expect(latexArray[0]).to.have.length.gt 100 expect(latexArray[0]).to.match /^{/ describe "parseLatexItem", -> latexObject = parseLatexItem(parseRules, latexArray[0]) it "generates an object", -> expect(latexObject).to.be.an "Object" describe "with properties derived from parseRules:", -> it "tag", -> expect(latexObject).to.have.property "tag", "Acar2009" it "year", -> expect(latexObject).to.have.property "year", "2009" it.skip "publisher", -> expect(latexObject).to.have.property "publisher", "todo" it "volume", -> expect(latexObject).to.have.property "volume", "21" it.skip "number", -> expect(latexObject).to.have.property "number", "1" it "pages", -> expect(latexObject).to.have.property "pages", "6--20" it "author", -> expect(latexObject).to.have.property "author", "Acar E, Yener B" it "title", -> expect(latexObject).to.have.property "title", "Unsupervised multiway data analysis: A literature survey" it "journal", -> expect(latexObject).to.have.property "journal", "IEEE Trans Knowl Data Engin" describe "parseLatexArray", -> it "maps the raw latex array items to parsed objects", -> parsedLatex = parseLatexArray(parseRules, latexArray) expect(parsedLatex).to.be.an "Array" expect(parsedLatex).to.have.length 3 expect(parsedLatex[0]).to.have.property "year" expect(parsedLatex[1]).to.have.property "year" expect(parsedLatex[2]).to.have.property "year" describe "formatParsedItem", -> parsedItem = parseLatexItem(parseRules, latexArray[0]) formattedItem = formatParsedItem(formattingRules, parsedItem) it "returns an object", -> expect(formattedItem).to.be.an "Object" describe "with modified properties based on formatRules", -> it "tag", -> expect(formattedItem).to.have.property "tag", "Acar2009" it "year", -> expect(formattedItem).to.have.property "year", "2009" it.skip "publisher", -> expect(formattedItem).to.have.property "publisher", "todo" it "volume", -> expect(formattedItem).to.have.property "volume", "21" it.skip "number", -> expect(formattedItem).to.have.property "number", "1" it "pages", -> expect(formattedItem).to.have.property "pages", "6--20" it "author", -> expect(formattedItem).to.have.property "author", "E. Acar and B. Yener" it "title", -> expect(formattedItem).to.have.property "title", "Unsupervised Multiway Data Analysis: {A} Literature Survey" it "journal", -> expect(formattedItem).to.have.property "journal", "{IEEE} Trans Knowl Data Engin" describe "formatParsedArray", -> it "formats each item in the parsed array", -> parsedLatex = parseLatexArray(parseRules, latexArray) formattedAndParsedObject = formatParsedArray formattingRules, parsedLatex expect(formattedAndParsedObject).to.be.an "Array" expect(formattedAndParsedObject).to.have.length 3 expect(formattedAndParsedObject[0]).to.have.property "author", "E. Acar and B. Yener" expect(formattedAndParsedObject[1]).to.have.property "author", "D. G. Albertson and C. Collins and F. McCormick and J. W. Gray" expect(formattedAndParsedObject[2]).to.have.property "author", "P. Agrawal and T. Kurcon and K. T. Pilobello and J. F. Rakus and S. Koppolu and Z. Liu and B. S. Batista and W. S. Eng and K. L. Hsu and Y. Liang and L. K. Mahal" describe "renderItemToTemplate", -> it "passes the data into the template", -> parsedLatex = parseLatexArray(parseRules, latexArray) formattedAndParsedObject = formatParsedArray formattingRules, parsedLatex rendered = renderItemToTemplate template, formattedAndParsedObject[0] expected = """ @Article{Acar2009, year = "2009", month = "undefined", publisher = "undefined", volume = "21", number = "undefined", pages = "6--20", author = "E. Acar and B. Yener", title = "Unsupervised Multiway Data Analysis: {A} Literature Survey", journal = "{IEEE} Trans Knowl Data Engin", } """ expect(rendered).to.equal expected describe "renderArrayToTemplate", -> it "renders all items in array to a single string", -> parsedLatex = parseLatexArray(parseRules, latexArray) formattedAndParsedObject = formatParsedArray formattingRules, parsedLatex rendered = renderArrayToTemplate template, formattedAndParsedObject expect(rendered).to.be.a "String" expect(rendered.split("\n\n")).to.have.length 3 expect(rendered.split("\n")).to.have.length.gte 35 describe "sortBy", -> it "sorts the array by the specified tag", -> array = [ tag: "a" , tag: "c" , tag: "b" ] sortedArray = sortBy "tag", array expect(sortedArray[0].tag).to.equal "a" expect(sortedArray[1].tag).to.equal "b" expect(sortedArray[2].tag).to.equal "c"
85120
{expect} = require "chai" path = require "path" {latexToArray parseLatexItem parseLatexArray formatParsedItem formatParsedArray renderItemToTemplate renderArrayToTemplate sortBy } = require "../parse" parseRules = require "../example/parseRules" formattingRules = require "../example/formattingrules" template = require "../example/template" latexArray = latexToArray path.join(__dirname, "/../example/sample.tex"), "bibitem" describe "latexToArray", -> it "changes latex to an array", -> expect(latexArray).to.be.an "Array" expect(latexArray).to.have.length 3 expect(latexArray[0]).to.be.a "String" expect(latexArray[0]).to.have.length.gt 100 expect(latexArray[0]).to.match /^{/ describe "parseLatexItem", -> latexObject = parseLatexItem(parseRules, latexArray[0]) it "generates an object", -> expect(latexObject).to.be.an "Object" describe "with properties derived from parseRules:", -> it "tag", -> expect(latexObject).to.have.property "tag", "Acar2009" it "year", -> expect(latexObject).to.have.property "year", "2009" it.skip "publisher", -> expect(latexObject).to.have.property "publisher", "todo" it "volume", -> expect(latexObject).to.have.property "volume", "21" it.skip "number", -> expect(latexObject).to.have.property "number", "1" it "pages", -> expect(latexObject).to.have.property "pages", "6--20" it "author", -> expect(latexObject).to.have.property "author", "<NAME>, <NAME>" it "title", -> expect(latexObject).to.have.property "title", "Unsupervised multiway data analysis: A literature survey" it "journal", -> expect(latexObject).to.have.property "journal", "IEEE Trans Knowl Data Engin" describe "parseLatexArray", -> it "maps the raw latex array items to parsed objects", -> parsedLatex = parseLatexArray(parseRules, latexArray) expect(parsedLatex).to.be.an "Array" expect(parsedLatex).to.have.length 3 expect(parsedLatex[0]).to.have.property "year" expect(parsedLatex[1]).to.have.property "year" expect(parsedLatex[2]).to.have.property "year" describe "formatParsedItem", -> parsedItem = parseLatexItem(parseRules, latexArray[0]) formattedItem = formatParsedItem(formattingRules, parsedItem) it "returns an object", -> expect(formattedItem).to.be.an "Object" describe "with modified properties based on formatRules", -> it "tag", -> expect(formattedItem).to.have.property "tag", "Acar2009" it "year", -> expect(formattedItem).to.have.property "year", "2009" it.skip "publisher", -> expect(formattedItem).to.have.property "publisher", "todo" it "volume", -> expect(formattedItem).to.have.property "volume", "21" it.skip "number", -> expect(formattedItem).to.have.property "number", "1" it "pages", -> expect(formattedItem).to.have.property "pages", "6--20" it "author", -> expect(formattedItem).to.have.property "author", "<NAME> and <NAME>" it "title", -> expect(formattedItem).to.have.property "title", "Unsupervised Multiway Data Analysis: {A} Literature Survey" it "journal", -> expect(formattedItem).to.have.property "journal", "{IEEE} Trans Knowl Data Engin" describe "formatParsedArray", -> it "formats each item in the parsed array", -> parsedLatex = parseLatexArray(parseRules, latexArray) formattedAndParsedObject = formatParsedArray formattingRules, parsedLatex expect(formattedAndParsedObject).to.be.an "Array" expect(formattedAndParsedObject).to.have.length 3 expect(formattedAndParsedObject[0]).to.have.property "author", "<NAME> and <NAME>" expect(formattedAndParsedObject[1]).to.have.property "author", "<NAME> and <NAME> and <NAME> and <NAME>" expect(formattedAndParsedObject[2]).to.have.property "author", "<NAME> and <NAME> and <NAME> and <NAME> and <NAME> and <NAME> and <NAME> and <NAME> and <NAME> and <NAME> and <NAME>" describe "renderItemToTemplate", -> it "passes the data into the template", -> parsedLatex = parseLatexArray(parseRules, latexArray) formattedAndParsedObject = formatParsedArray formattingRules, parsedLatex rendered = renderItemToTemplate template, formattedAndParsedObject[0] expected = """ @Article{Acar2009, year = "2009", month = "undefined", publisher = "undefined", volume = "21", number = "undefined", pages = "6--20", author = "<NAME> and <NAME>", title = "Unsupervised Multiway Data Analysis: {A} Literature Survey", journal = "{IEEE} Trans Knowl Data Engin", } """ expect(rendered).to.equal expected describe "renderArrayToTemplate", -> it "renders all items in array to a single string", -> parsedLatex = parseLatexArray(parseRules, latexArray) formattedAndParsedObject = formatParsedArray formattingRules, parsedLatex rendered = renderArrayToTemplate template, formattedAndParsedObject expect(rendered).to.be.a "String" expect(rendered.split("\n\n")).to.have.length 3 expect(rendered.split("\n")).to.have.length.gte 35 describe "sortBy", -> it "sorts the array by the specified tag", -> array = [ tag: "a" , tag: "c" , tag: "b" ] sortedArray = sortBy "tag", array expect(sortedArray[0].tag).to.equal "a" expect(sortedArray[1].tag).to.equal "b" expect(sortedArray[2].tag).to.equal "c"
true
{expect} = require "chai" path = require "path" {latexToArray parseLatexItem parseLatexArray formatParsedItem formatParsedArray renderItemToTemplate renderArrayToTemplate sortBy } = require "../parse" parseRules = require "../example/parseRules" formattingRules = require "../example/formattingrules" template = require "../example/template" latexArray = latexToArray path.join(__dirname, "/../example/sample.tex"), "bibitem" describe "latexToArray", -> it "changes latex to an array", -> expect(latexArray).to.be.an "Array" expect(latexArray).to.have.length 3 expect(latexArray[0]).to.be.a "String" expect(latexArray[0]).to.have.length.gt 100 expect(latexArray[0]).to.match /^{/ describe "parseLatexItem", -> latexObject = parseLatexItem(parseRules, latexArray[0]) it "generates an object", -> expect(latexObject).to.be.an "Object" describe "with properties derived from parseRules:", -> it "tag", -> expect(latexObject).to.have.property "tag", "Acar2009" it "year", -> expect(latexObject).to.have.property "year", "2009" it.skip "publisher", -> expect(latexObject).to.have.property "publisher", "todo" it "volume", -> expect(latexObject).to.have.property "volume", "21" it.skip "number", -> expect(latexObject).to.have.property "number", "1" it "pages", -> expect(latexObject).to.have.property "pages", "6--20" it "author", -> expect(latexObject).to.have.property "author", "PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI" it "title", -> expect(latexObject).to.have.property "title", "Unsupervised multiway data analysis: A literature survey" it "journal", -> expect(latexObject).to.have.property "journal", "IEEE Trans Knowl Data Engin" describe "parseLatexArray", -> it "maps the raw latex array items to parsed objects", -> parsedLatex = parseLatexArray(parseRules, latexArray) expect(parsedLatex).to.be.an "Array" expect(parsedLatex).to.have.length 3 expect(parsedLatex[0]).to.have.property "year" expect(parsedLatex[1]).to.have.property "year" expect(parsedLatex[2]).to.have.property "year" describe "formatParsedItem", -> parsedItem = parseLatexItem(parseRules, latexArray[0]) formattedItem = formatParsedItem(formattingRules, parsedItem) it "returns an object", -> expect(formattedItem).to.be.an "Object" describe "with modified properties based on formatRules", -> it "tag", -> expect(formattedItem).to.have.property "tag", "Acar2009" it "year", -> expect(formattedItem).to.have.property "year", "2009" it.skip "publisher", -> expect(formattedItem).to.have.property "publisher", "todo" it "volume", -> expect(formattedItem).to.have.property "volume", "21" it.skip "number", -> expect(formattedItem).to.have.property "number", "1" it "pages", -> expect(formattedItem).to.have.property "pages", "6--20" it "author", -> expect(formattedItem).to.have.property "author", "PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI" it "title", -> expect(formattedItem).to.have.property "title", "Unsupervised Multiway Data Analysis: {A} Literature Survey" it "journal", -> expect(formattedItem).to.have.property "journal", "{IEEE} Trans Knowl Data Engin" describe "formatParsedArray", -> it "formats each item in the parsed array", -> parsedLatex = parseLatexArray(parseRules, latexArray) formattedAndParsedObject = formatParsedArray formattingRules, parsedLatex expect(formattedAndParsedObject).to.be.an "Array" expect(formattedAndParsedObject).to.have.length 3 expect(formattedAndParsedObject[0]).to.have.property "author", "PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI" expect(formattedAndParsedObject[1]).to.have.property "author", "PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI" expect(formattedAndParsedObject[2]).to.have.property "author", "PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI" describe "renderItemToTemplate", -> it "passes the data into the template", -> parsedLatex = parseLatexArray(parseRules, latexArray) formattedAndParsedObject = formatParsedArray formattingRules, parsedLatex rendered = renderItemToTemplate template, formattedAndParsedObject[0] expected = """ @Article{Acar2009, year = "2009", month = "undefined", publisher = "undefined", volume = "21", number = "undefined", pages = "6--20", author = "PI:NAME:<NAME>END_PI and PI:NAME:<NAME>END_PI", title = "Unsupervised Multiway Data Analysis: {A} Literature Survey", journal = "{IEEE} Trans Knowl Data Engin", } """ expect(rendered).to.equal expected describe "renderArrayToTemplate", -> it "renders all items in array to a single string", -> parsedLatex = parseLatexArray(parseRules, latexArray) formattedAndParsedObject = formatParsedArray formattingRules, parsedLatex rendered = renderArrayToTemplate template, formattedAndParsedObject expect(rendered).to.be.a "String" expect(rendered.split("\n\n")).to.have.length 3 expect(rendered.split("\n")).to.have.length.gte 35 describe "sortBy", -> it "sorts the array by the specified tag", -> array = [ tag: "a" , tag: "c" , tag: "b" ] sortedArray = sortBy "tag", array expect(sortedArray[0].tag).to.equal "a" expect(sortedArray[1].tag).to.equal "b" expect(sortedArray[2].tag).to.equal "c"
[ { "context": "mfabrik GmbH\n * MIT Licence\n * https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org\n#", "end": 166, "score": 0.9922515153884888, "start": 152, "tag": "USERNAME", "value": "programmfabrik" }, { "context": "@__buttonbar = new CUI.Buttonbar(...
src/elements/Tabs/Tabs.coffee
programmfabrik/coffeescript-ui
10
### * coffeescript-ui - Coffeescript User Interface System (CUI) * Copyright (c) 2013 - 2016 Programmfabrik GmbH * MIT Licence * https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org ### CUI.Template.loadTemplateText(require('./Tabs.html')); class CUI.Tabs extends CUI.SimplePane @defaults: overflow_button_tooltip: null initOpts: -> super() # @removeOpt("header_right") @removeOpt("header_center") @removeOpt("content") @removeOpt("force_footer") @removeOpt("force_header") @addOpts tabs: mandatory: true check: (v) -> CUI.util.isArray(v) and v.length > 0 #autoSizeY: # default: false # check: Boolean active_idx: check: 'Integer' appearance: check: ['normal', 'mini'] orientation: check: ['vertical', 'horizontal'] mandatory: true default: 'horizontal' onActivate: check: Function onDeactivate: check: Function #header_right: {} #footer_right: {} #footer_left: {} forceHeader: -> true forceFooter: -> true __checkOverflowButton: -> if not @__maximize_horizontal return header_dim = CUI.dom.getDimensions(@__header) # console.debug "header_dim", header_dim.scrollWidth, header_dim.clientWidth if header_dim.scrollWidth > header_dim.clientWidth @__overflowBtn.show() CUI.dom.addClass(@__pane_header.DOM, "cui-tabs-pane-header--overflow") @__dragscroll = new CUI.Dragscroll element: @__buttonbar.DOM scroll_element: @__header else @__dragscroll?.destroy() @__dragscroll = null @__overflowBtn.hide() CUI.dom.removeClass(@__pane_header.DOM, "cui-tabs-pane-header--overflow") @ init: -> super() @__tabs_bodies = new CUI.Template name: "tabs-bodies" CUI.dom.addClass(@__pane_header.DOM, "cui-tabs-pane-header") if @_appearance == 'mini' CUI.dom.addClass(@__pane_header.DOM, "cui-tabs-pane-header--mini") @removeClass('cui-pane--padded') if @_padded @addClass('cui-tabs--padded') @addClass('cui-tabs--'+@_orientation) @__buttonbar = new CUI.Buttonbar() pane_key = "center" @__pane_header.append(@__buttonbar, pane_key) @__header = @__pane_header[pane_key]() CUI.Events.listen type: "scroll" node: @__header call: (ev) => dim = CUI.dom.getDimensions(@__header) CUI.dom.setClass(@__pane_header.DOM, "cui-tabs-pane-header--scroll-at-end", dim.horizontalScrollbarAtEnd) CUI.dom.setClass(@__pane_header.DOM, "cui-tabs-pane-header--scroll-at-start", dim.horizontalScrollbarAtStart) @__overflowBtn = new CUI.Button icon: "ellipsis_h" class: "cui-tab-header-button-overflow" icon_right: false size: if @_appearance == "mini" then "mini" else undefined tooltip: text: CUI.Tabs.defaults.overflow_button_tooltip menu: items: => btns = [] for tab in @__tabs do (tab) => btns.push text: tab.getText() active: tab == @getActiveTab() onClick: => tab.activate() btns @__overflowBtn.hide() @__pane_header.prepend(@__overflowBtn, "right") @getLayout().append(@__tabs_bodies, "center") if @_appearance == "mini" @addClass("cui-tabs--mini") @__tabs = [] for tab, idx in @_tabs if not tab continue if tab instanceof CUI.Tab _tab = @addTab(tab) else if CUI.util.isPlainObject(tab) _tab = @addTab(new CUI.Tab(tab)) else CUI.util.assert(false, "new #{@__cls}", "opts.tabs[#{idx}] must be PlainObject or Tab but is #{CUI.util.getObjectClass(tab)}", opts: @opts) if @_appearance == "mini" _tab.getButton().setSize("mini") @__tabs[@_active_idx or 0].activate() CUI.dom.waitForDOMInsert(node: @getLayout()) .done => if @isDestroyed() return CUI.Events.listen node: @getLayout() type: "viewport-resize" call: => @__checkOverflowButton() CUI.util.assert( CUI.dom.isInDOM(@getLayout().DOM),"Tabs getting DOM insert event without being in DOM." ) @__checkOverflowButton() @addClass("cui-tabs") @__max_width = -1 @__max_height = -1 @ setFooterRight: (content) -> # @tabs.map.footer.css("display","") @replace(content, "footer_right") setFooterLeft: (content) -> # @tabs.map.footer.css("display","") @replace(content, "footer_left") addTab: (tab) -> CUI.util.assert(tab instanceof CUI.Tab, "#{@__cls}.addTab", "Tab must be instance of Tab but is #{CUI.util.getObjectClass(tab)}", tab: tab) if not @hasTab(tab) @__tabs.push(tab) CUI.Events.listen node: tab type: "tab_activate" call: => if @__overflowBtn.isShown() CUI.dom.scrollIntoView(tab.getButton().DOM) if not @_maximize_vertical # set left margin on first tab # console.debug "style", @__tabs[0].DOM[0], -100*CUI.util.idxInArray(tab, @__tabs)+"%" CUI.dom.setStyle(@__tabs[0].DOM, marginLeft: -100*CUI.util.idxInArray(tab, @__tabs)+"%") @__active_tab = tab CUI.dom.setAttribute(@DOM, "active-tab-idx", CUI.util.idxInArray(tab, @__tabs)) @_onActivate?(@, tab) # console.error @__uniqueId, "activate" CUI.Events.listen node: tab type: "tab_deactivate" call: => # console.error @__uniqueId, "deactivate" @__active_tab = null CUI.dom.setAttribute(@DOM, "active-tab-idx", "") @_onDeactivate?(@, tab) CUI.Events.listen node: tab type: "tab_destroy" call: => idx = @__tabs.indexOf(tab) CUI.util.removeFromArray(tab, @__tabs) idx-- @__tabs[idx]?.activate() tab_padded = tab.getSetOpt("padded") if (tab_padded != false and @_padded) or (tab_padded == true) tab.addClass("cui-tab--padded") tab.hide() tab.initButton(@) @__buttonbar.addButton(tab.getButton()) @__tabs_bodies.append(tab) tab # true or false if a tab exists hasTab: (tab_or_idx_or_name) -> @getTab(tab_or_idx_or_name) getTab: (tab_or_idx_or_name) -> found_tab = null # console.debug tab_or_idx_or_name, @, @__tabs.length if CUI.util.isString(tab_or_idx_or_name) for tab in @__tabs # console.debug tab._name, tab_or_idx_or_name if tab._name == tab_or_idx_or_name found_tab = tab break else if tab_or_idx_or_name instanceof CUI.Tab if @__tabs.indexOf(tab_or_idx_or_name) > -1 found_tab = tab_or_idx_or_name else found_tab = @__tabs[tab_or_idx_or_name] return found_tab getActiveTab: -> @__active_tab activate: (tab_or_idx_or_name) -> tab = @getTab(tab_or_idx_or_name) tab.activate() @ destroy: -> while @__tabs.length > 0 # Tab destroy triggers 'tab_destroy' event which makes the tab to be removed from the array. @__tabs[0].destroy() super()
47202
### * coffeescript-ui - Coffeescript User Interface System (CUI) * Copyright (c) 2013 - 2016 Programmfabrik GmbH * MIT Licence * https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org ### CUI.Template.loadTemplateText(require('./Tabs.html')); class CUI.Tabs extends CUI.SimplePane @defaults: overflow_button_tooltip: null initOpts: -> super() # @removeOpt("header_right") @removeOpt("header_center") @removeOpt("content") @removeOpt("force_footer") @removeOpt("force_header") @addOpts tabs: mandatory: true check: (v) -> CUI.util.isArray(v) and v.length > 0 #autoSizeY: # default: false # check: Boolean active_idx: check: 'Integer' appearance: check: ['normal', 'mini'] orientation: check: ['vertical', 'horizontal'] mandatory: true default: 'horizontal' onActivate: check: Function onDeactivate: check: Function #header_right: {} #footer_right: {} #footer_left: {} forceHeader: -> true forceFooter: -> true __checkOverflowButton: -> if not @__maximize_horizontal return header_dim = CUI.dom.getDimensions(@__header) # console.debug "header_dim", header_dim.scrollWidth, header_dim.clientWidth if header_dim.scrollWidth > header_dim.clientWidth @__overflowBtn.show() CUI.dom.addClass(@__pane_header.DOM, "cui-tabs-pane-header--overflow") @__dragscroll = new CUI.Dragscroll element: @__buttonbar.DOM scroll_element: @__header else @__dragscroll?.destroy() @__dragscroll = null @__overflowBtn.hide() CUI.dom.removeClass(@__pane_header.DOM, "cui-tabs-pane-header--overflow") @ init: -> super() @__tabs_bodies = new CUI.Template name: "tabs-bodies" CUI.dom.addClass(@__pane_header.DOM, "cui-tabs-pane-header") if @_appearance == 'mini' CUI.dom.addClass(@__pane_header.DOM, "cui-tabs-pane-header--mini") @removeClass('cui-pane--padded') if @_padded @addClass('cui-tabs--padded') @addClass('cui-tabs--'+@_orientation) @__buttonbar = new CUI.Buttonbar() pane_key = "<KEY>" @__pane_header.append(@__buttonbar, pane_key) @__header = @__pane_header[pane_key]() CUI.Events.listen type: "scroll" node: @__header call: (ev) => dim = CUI.dom.getDimensions(@__header) CUI.dom.setClass(@__pane_header.DOM, "cui-tabs-pane-header--scroll-at-end", dim.horizontalScrollbarAtEnd) CUI.dom.setClass(@__pane_header.DOM, "cui-tabs-pane-header--scroll-at-start", dim.horizontalScrollbarAtStart) @__overflowBtn = new CUI.Button icon: "ellipsis_h" class: "cui-tab-header-button-overflow" icon_right: false size: if @_appearance == "mini" then "mini" else undefined tooltip: text: CUI.Tabs.defaults.overflow_button_tooltip menu: items: => btns = [] for tab in @__tabs do (tab) => btns.push text: tab.getText() active: tab == @getActiveTab() onClick: => tab.activate() btns @__overflowBtn.hide() @__pane_header.prepend(@__overflowBtn, "right") @getLayout().append(@__tabs_bodies, "center") if @_appearance == "mini" @addClass("cui-tabs--mini") @__tabs = [] for tab, idx in @_tabs if not tab continue if tab instanceof CUI.Tab _tab = @addTab(tab) else if CUI.util.isPlainObject(tab) _tab = @addTab(new CUI.Tab(tab)) else CUI.util.assert(false, "new #{@__cls}", "opts.tabs[#{idx}] must be PlainObject or Tab but is #{CUI.util.getObjectClass(tab)}", opts: @opts) if @_appearance == "mini" _tab.getButton().setSize("mini") @__tabs[@_active_idx or 0].activate() CUI.dom.waitForDOMInsert(node: @getLayout()) .done => if @isDestroyed() return CUI.Events.listen node: @getLayout() type: "viewport-resize" call: => @__checkOverflowButton() CUI.util.assert( CUI.dom.isInDOM(@getLayout().DOM),"Tabs getting DOM insert event without being in DOM." ) @__checkOverflowButton() @addClass("cui-tabs") @__max_width = -1 @__max_height = -1 @ setFooterRight: (content) -> # @tabs.map.footer.css("display","") @replace(content, "footer_right") setFooterLeft: (content) -> # @tabs.map.footer.css("display","") @replace(content, "footer_left") addTab: (tab) -> CUI.util.assert(tab instanceof CUI.Tab, "#{@__cls}.addTab", "Tab must be instance of Tab but is #{CUI.util.getObjectClass(tab)}", tab: tab) if not @hasTab(tab) @__tabs.push(tab) CUI.Events.listen node: tab type: "tab_activate" call: => if @__overflowBtn.isShown() CUI.dom.scrollIntoView(tab.getButton().DOM) if not @_maximize_vertical # set left margin on first tab # console.debug "style", @__tabs[0].DOM[0], -100*CUI.util.idxInArray(tab, @__tabs)+"%" CUI.dom.setStyle(@__tabs[0].DOM, marginLeft: -100*CUI.util.idxInArray(tab, @__tabs)+"%") @__active_tab = tab CUI.dom.setAttribute(@DOM, "active-tab-idx", CUI.util.idxInArray(tab, @__tabs)) @_onActivate?(@, tab) # console.error @__uniqueId, "activate" CUI.Events.listen node: tab type: "tab_deactivate" call: => # console.error @__uniqueId, "deactivate" @__active_tab = null CUI.dom.setAttribute(@DOM, "active-tab-idx", "") @_onDeactivate?(@, tab) CUI.Events.listen node: tab type: "tab_destroy" call: => idx = @__tabs.indexOf(tab) CUI.util.removeFromArray(tab, @__tabs) idx-- @__tabs[idx]?.activate() tab_padded = tab.getSetOpt("padded") if (tab_padded != false and @_padded) or (tab_padded == true) tab.addClass("cui-tab--padded") tab.hide() tab.initButton(@) @__buttonbar.addButton(tab.getButton()) @__tabs_bodies.append(tab) tab # true or false if a tab exists hasTab: (tab_or_idx_or_name) -> @getTab(tab_or_idx_or_name) getTab: (tab_or_idx_or_name) -> found_tab = null # console.debug tab_or_idx_or_name, @, @__tabs.length if CUI.util.isString(tab_or_idx_or_name) for tab in @__tabs # console.debug tab._name, tab_or_idx_or_name if tab._name == tab_or_idx_or_name found_tab = tab break else if tab_or_idx_or_name instanceof CUI.Tab if @__tabs.indexOf(tab_or_idx_or_name) > -1 found_tab = tab_or_idx_or_name else found_tab = @__tabs[tab_or_idx_or_name] return found_tab getActiveTab: -> @__active_tab activate: (tab_or_idx_or_name) -> tab = @getTab(tab_or_idx_or_name) tab.activate() @ destroy: -> while @__tabs.length > 0 # Tab destroy triggers 'tab_destroy' event which makes the tab to be removed from the array. @__tabs[0].destroy() super()
true
### * coffeescript-ui - Coffeescript User Interface System (CUI) * Copyright (c) 2013 - 2016 Programmfabrik GmbH * MIT Licence * https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org ### CUI.Template.loadTemplateText(require('./Tabs.html')); class CUI.Tabs extends CUI.SimplePane @defaults: overflow_button_tooltip: null initOpts: -> super() # @removeOpt("header_right") @removeOpt("header_center") @removeOpt("content") @removeOpt("force_footer") @removeOpt("force_header") @addOpts tabs: mandatory: true check: (v) -> CUI.util.isArray(v) and v.length > 0 #autoSizeY: # default: false # check: Boolean active_idx: check: 'Integer' appearance: check: ['normal', 'mini'] orientation: check: ['vertical', 'horizontal'] mandatory: true default: 'horizontal' onActivate: check: Function onDeactivate: check: Function #header_right: {} #footer_right: {} #footer_left: {} forceHeader: -> true forceFooter: -> true __checkOverflowButton: -> if not @__maximize_horizontal return header_dim = CUI.dom.getDimensions(@__header) # console.debug "header_dim", header_dim.scrollWidth, header_dim.clientWidth if header_dim.scrollWidth > header_dim.clientWidth @__overflowBtn.show() CUI.dom.addClass(@__pane_header.DOM, "cui-tabs-pane-header--overflow") @__dragscroll = new CUI.Dragscroll element: @__buttonbar.DOM scroll_element: @__header else @__dragscroll?.destroy() @__dragscroll = null @__overflowBtn.hide() CUI.dom.removeClass(@__pane_header.DOM, "cui-tabs-pane-header--overflow") @ init: -> super() @__tabs_bodies = new CUI.Template name: "tabs-bodies" CUI.dom.addClass(@__pane_header.DOM, "cui-tabs-pane-header") if @_appearance == 'mini' CUI.dom.addClass(@__pane_header.DOM, "cui-tabs-pane-header--mini") @removeClass('cui-pane--padded') if @_padded @addClass('cui-tabs--padded') @addClass('cui-tabs--'+@_orientation) @__buttonbar = new CUI.Buttonbar() pane_key = "PI:KEY:<KEY>END_PI" @__pane_header.append(@__buttonbar, pane_key) @__header = @__pane_header[pane_key]() CUI.Events.listen type: "scroll" node: @__header call: (ev) => dim = CUI.dom.getDimensions(@__header) CUI.dom.setClass(@__pane_header.DOM, "cui-tabs-pane-header--scroll-at-end", dim.horizontalScrollbarAtEnd) CUI.dom.setClass(@__pane_header.DOM, "cui-tabs-pane-header--scroll-at-start", dim.horizontalScrollbarAtStart) @__overflowBtn = new CUI.Button icon: "ellipsis_h" class: "cui-tab-header-button-overflow" icon_right: false size: if @_appearance == "mini" then "mini" else undefined tooltip: text: CUI.Tabs.defaults.overflow_button_tooltip menu: items: => btns = [] for tab in @__tabs do (tab) => btns.push text: tab.getText() active: tab == @getActiveTab() onClick: => tab.activate() btns @__overflowBtn.hide() @__pane_header.prepend(@__overflowBtn, "right") @getLayout().append(@__tabs_bodies, "center") if @_appearance == "mini" @addClass("cui-tabs--mini") @__tabs = [] for tab, idx in @_tabs if not tab continue if tab instanceof CUI.Tab _tab = @addTab(tab) else if CUI.util.isPlainObject(tab) _tab = @addTab(new CUI.Tab(tab)) else CUI.util.assert(false, "new #{@__cls}", "opts.tabs[#{idx}] must be PlainObject or Tab but is #{CUI.util.getObjectClass(tab)}", opts: @opts) if @_appearance == "mini" _tab.getButton().setSize("mini") @__tabs[@_active_idx or 0].activate() CUI.dom.waitForDOMInsert(node: @getLayout()) .done => if @isDestroyed() return CUI.Events.listen node: @getLayout() type: "viewport-resize" call: => @__checkOverflowButton() CUI.util.assert( CUI.dom.isInDOM(@getLayout().DOM),"Tabs getting DOM insert event without being in DOM." ) @__checkOverflowButton() @addClass("cui-tabs") @__max_width = -1 @__max_height = -1 @ setFooterRight: (content) -> # @tabs.map.footer.css("display","") @replace(content, "footer_right") setFooterLeft: (content) -> # @tabs.map.footer.css("display","") @replace(content, "footer_left") addTab: (tab) -> CUI.util.assert(tab instanceof CUI.Tab, "#{@__cls}.addTab", "Tab must be instance of Tab but is #{CUI.util.getObjectClass(tab)}", tab: tab) if not @hasTab(tab) @__tabs.push(tab) CUI.Events.listen node: tab type: "tab_activate" call: => if @__overflowBtn.isShown() CUI.dom.scrollIntoView(tab.getButton().DOM) if not @_maximize_vertical # set left margin on first tab # console.debug "style", @__tabs[0].DOM[0], -100*CUI.util.idxInArray(tab, @__tabs)+"%" CUI.dom.setStyle(@__tabs[0].DOM, marginLeft: -100*CUI.util.idxInArray(tab, @__tabs)+"%") @__active_tab = tab CUI.dom.setAttribute(@DOM, "active-tab-idx", CUI.util.idxInArray(tab, @__tabs)) @_onActivate?(@, tab) # console.error @__uniqueId, "activate" CUI.Events.listen node: tab type: "tab_deactivate" call: => # console.error @__uniqueId, "deactivate" @__active_tab = null CUI.dom.setAttribute(@DOM, "active-tab-idx", "") @_onDeactivate?(@, tab) CUI.Events.listen node: tab type: "tab_destroy" call: => idx = @__tabs.indexOf(tab) CUI.util.removeFromArray(tab, @__tabs) idx-- @__tabs[idx]?.activate() tab_padded = tab.getSetOpt("padded") if (tab_padded != false and @_padded) or (tab_padded == true) tab.addClass("cui-tab--padded") tab.hide() tab.initButton(@) @__buttonbar.addButton(tab.getButton()) @__tabs_bodies.append(tab) tab # true or false if a tab exists hasTab: (tab_or_idx_or_name) -> @getTab(tab_or_idx_or_name) getTab: (tab_or_idx_or_name) -> found_tab = null # console.debug tab_or_idx_or_name, @, @__tabs.length if CUI.util.isString(tab_or_idx_or_name) for tab in @__tabs # console.debug tab._name, tab_or_idx_or_name if tab._name == tab_or_idx_or_name found_tab = tab break else if tab_or_idx_or_name instanceof CUI.Tab if @__tabs.indexOf(tab_or_idx_or_name) > -1 found_tab = tab_or_idx_or_name else found_tab = @__tabs[tab_or_idx_or_name] return found_tab getActiveTab: -> @__active_tab activate: (tab_or_idx_or_name) -> tab = @getTab(tab_or_idx_or_name) tab.activate() @ destroy: -> while @__tabs.length > 0 # Tab destroy triggers 'tab_destroy' event which makes the tab to be removed from the array. @__tabs[0].destroy() super()
[ { "context": "flag references to undeclared variables.\n# @author Mark Macdonald\n###\n\n{getAddImportFix: getFix} = require '../util", "end": 94, "score": 0.9997997283935547, "start": 80, "tag": "NAME", "value": "Mark Macdonald" } ]
src/rules/no-undef.coffee
helixbass/eslint-plugin-known-imports
4
###* # @fileoverview Rule to flag references to undeclared variables. # @author Mark Macdonald ### {getAddImportFix: getFix} = require '../utils' # ------------------------------------------------------------------------------ # Helpers # ------------------------------------------------------------------------------ ###* # Checks if the given node is the argument of a typeof operator. # @param {ASTNode} node The AST node being checked. # @returns {boolean} Whether or not the node is the argument of a typeof operator. ### hasTypeOfOperator = ({parent}) -> parent.type is 'UnaryExpression' and parent.operator is 'typeof' # ------------------------------------------------------------------------------ # Rule Definition # ------------------------------------------------------------------------------ module.exports = meta: docs: description: 'disallow the use of undeclared variables unless mentioned in `/*global */` comments' category: 'Variables' recommended: yes url: 'https://eslint.org/docs/rules/no-undef' schema: [ type: 'object' properties: typeof: type: 'boolean' # knownImports: # type: 'object' # knownImportsFile: # type: 'string' additionalProperties: no ] fixable: 'code' create: (context) -> options = context.options[0] ? {} considerTypeOf = options.typeof is yes allImports = [] lastNonlocalImport = {} ImportDeclaration: (node) -> allImports.push node 'Program:exit': (### node ###) -> globalScope = context.getScope() globalScope.through.forEach ({identifier}) -> return if not considerTypeOf and hasTypeOfOperator identifier context.report node: identifier message: "'{{name}}' is not defined." data: identifier fix: getFix { name: identifier.name context allImports lastNonlocalImport }
9691
###* # @fileoverview Rule to flag references to undeclared variables. # @author <NAME> ### {getAddImportFix: getFix} = require '../utils' # ------------------------------------------------------------------------------ # Helpers # ------------------------------------------------------------------------------ ###* # Checks if the given node is the argument of a typeof operator. # @param {ASTNode} node The AST node being checked. # @returns {boolean} Whether or not the node is the argument of a typeof operator. ### hasTypeOfOperator = ({parent}) -> parent.type is 'UnaryExpression' and parent.operator is 'typeof' # ------------------------------------------------------------------------------ # Rule Definition # ------------------------------------------------------------------------------ module.exports = meta: docs: description: 'disallow the use of undeclared variables unless mentioned in `/*global */` comments' category: 'Variables' recommended: yes url: 'https://eslint.org/docs/rules/no-undef' schema: [ type: 'object' properties: typeof: type: 'boolean' # knownImports: # type: 'object' # knownImportsFile: # type: 'string' additionalProperties: no ] fixable: 'code' create: (context) -> options = context.options[0] ? {} considerTypeOf = options.typeof is yes allImports = [] lastNonlocalImport = {} ImportDeclaration: (node) -> allImports.push node 'Program:exit': (### node ###) -> globalScope = context.getScope() globalScope.through.forEach ({identifier}) -> return if not considerTypeOf and hasTypeOfOperator identifier context.report node: identifier message: "'{{name}}' is not defined." data: identifier fix: getFix { name: identifier.name context allImports lastNonlocalImport }
true
###* # @fileoverview Rule to flag references to undeclared variables. # @author PI:NAME:<NAME>END_PI ### {getAddImportFix: getFix} = require '../utils' # ------------------------------------------------------------------------------ # Helpers # ------------------------------------------------------------------------------ ###* # Checks if the given node is the argument of a typeof operator. # @param {ASTNode} node The AST node being checked. # @returns {boolean} Whether or not the node is the argument of a typeof operator. ### hasTypeOfOperator = ({parent}) -> parent.type is 'UnaryExpression' and parent.operator is 'typeof' # ------------------------------------------------------------------------------ # Rule Definition # ------------------------------------------------------------------------------ module.exports = meta: docs: description: 'disallow the use of undeclared variables unless mentioned in `/*global */` comments' category: 'Variables' recommended: yes url: 'https://eslint.org/docs/rules/no-undef' schema: [ type: 'object' properties: typeof: type: 'boolean' # knownImports: # type: 'object' # knownImportsFile: # type: 'string' additionalProperties: no ] fixable: 'code' create: (context) -> options = context.options[0] ? {} considerTypeOf = options.typeof is yes allImports = [] lastNonlocalImport = {} ImportDeclaration: (node) -> allImports.push node 'Program:exit': (### node ###) -> globalScope = context.getScope() globalScope.through.forEach ({identifier}) -> return if not considerTypeOf and hasTypeOfOperator identifier context.report node: identifier message: "'{{name}}' is not defined." data: identifier fix: getFix { name: identifier.name context allImports lastNonlocalImport }
[ { "context": "peof are compared against a valid string\n# @author Ian Christian Myers\n###\n'use strict'\n\n#------------------------------", "end": 121, "score": 0.9998195767402649, "start": 102, "tag": "NAME", "value": "Ian Christian Myers" } ]
src/tests/rules/valid-typeof.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Ensures that the results of typeof are compared against a valid string # @author Ian Christian Myers ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/valid-typeof' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ### eslint-disable coffee/no-template-curly-in-string ### ruleTester.run 'valid-typeof', rule, valid: [ "typeof foo is 'string'" "typeof foo is 'object'" "typeof foo is 'function'" "typeof foo is 'undefined'" "typeof foo is 'boolean'" "typeof foo is 'number'" "'string' is typeof foo" "'object' is typeof foo" "'function' is typeof foo" "'undefined' is typeof foo" "'boolean' is typeof foo" "'number' is typeof foo" 'typeof foo is typeof bar' 'typeof foo is baz' 'typeof foo isnt someType' 'typeof bar != someType' 'someType is typeof bar' 'someType == typeof bar' "typeof foo == 'string'" "typeof(foo) is 'string'" "typeof(foo) isnt 'string'" "typeof(foo) == 'string'" "typeof(foo) != 'string'" "oddUse = typeof foo + 'thing'" , code: "typeof foo is 'number'" options: [requireStringLiterals: yes] , code: 'typeof foo is "number"' options: [requireStringLiterals: yes] , code: "baz = typeof foo + 'thing'" options: [requireStringLiterals: yes] , code: 'typeof foo is typeof bar' options: [requireStringLiterals: yes] , code: 'typeof foo is "string"' options: [requireStringLiterals: yes] , code: '"object" is typeof foo' options: [requireStringLiterals: yes] , code: 'typeof foo is "str#{somethingElse}"' ] invalid: [ code: "typeof foo is 'strnig'" errors: [message: 'Invalid typeof comparison value.', type: 'Literal'] , code: "'strnig' is typeof foo" errors: [message: 'Invalid typeof comparison value.', type: 'Literal'] , code: "if (typeof bar is 'umdefined') then ;" errors: [message: 'Invalid typeof comparison value.', type: 'Literal'] , code: "typeof foo isnt 'strnig'" errors: [message: 'Invalid typeof comparison value.', type: 'Literal'] , code: "'strnig' isnt typeof foo" errors: [message: 'Invalid typeof comparison value.', type: 'Literal'] , code: "if (typeof bar isnt 'umdefined') then ;" errors: [message: 'Invalid typeof comparison value.', type: 'Literal'] , code: "typeof foo != 'strnig'" errors: [message: 'Invalid typeof comparison value.', type: 'Literal'] , code: "'strnig' != typeof foo" errors: [message: 'Invalid typeof comparison value.', type: 'Literal'] , code: "if (typeof bar != 'umdefined') then ;" errors: [message: 'Invalid typeof comparison value.', type: 'Literal'] , code: "typeof foo == 'strnig'" errors: [message: 'Invalid typeof comparison value.', type: 'Literal'] , code: "'strnig' == typeof foo" errors: [message: 'Invalid typeof comparison value.', type: 'Literal'] , code: "if (typeof bar == 'umdefined') then ;" errors: [message: 'Invalid typeof comparison value.', type: 'Literal'] , code: "typeof foo == 'invalid string'" options: [requireStringLiterals: yes] errors: [message: 'Invalid typeof comparison value.', type: 'Literal'] , code: 'typeof foo == Object' options: [requireStringLiterals: yes] errors: [ message: 'Typeof comparisons should be to string literals.' type: 'Identifier' ] , code: 'typeof foo is undefined' options: [requireStringLiterals: yes] errors: [ message: 'Typeof comparisons should be to string literals.' type: 'Identifier' ] , code: 'undefined is typeof foo' options: [requireStringLiterals: yes] errors: [ message: 'Typeof comparisons should be to string literals.' type: 'Identifier' ] , code: 'undefined == typeof foo' options: [requireStringLiterals: yes] errors: [ message: 'Typeof comparisons should be to string literals.' type: 'Identifier' ] , code: 'typeof foo is "undefined#{foo}"' options: [requireStringLiterals: yes] errors: [ message: 'Typeof comparisons should be to string literals.' type: 'TemplateLiteral' ] , code: 'typeof foo is "#{string}"' options: [requireStringLiterals: yes] errors: [ message: 'Typeof comparisons should be to string literals.' type: 'TemplateLiteral' ] ]
184792
###* # @fileoverview Ensures that the results of typeof are compared against a valid string # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/valid-typeof' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ### eslint-disable coffee/no-template-curly-in-string ### ruleTester.run 'valid-typeof', rule, valid: [ "typeof foo is 'string'" "typeof foo is 'object'" "typeof foo is 'function'" "typeof foo is 'undefined'" "typeof foo is 'boolean'" "typeof foo is 'number'" "'string' is typeof foo" "'object' is typeof foo" "'function' is typeof foo" "'undefined' is typeof foo" "'boolean' is typeof foo" "'number' is typeof foo" 'typeof foo is typeof bar' 'typeof foo is baz' 'typeof foo isnt someType' 'typeof bar != someType' 'someType is typeof bar' 'someType == typeof bar' "typeof foo == 'string'" "typeof(foo) is 'string'" "typeof(foo) isnt 'string'" "typeof(foo) == 'string'" "typeof(foo) != 'string'" "oddUse = typeof foo + 'thing'" , code: "typeof foo is 'number'" options: [requireStringLiterals: yes] , code: 'typeof foo is "number"' options: [requireStringLiterals: yes] , code: "baz = typeof foo + 'thing'" options: [requireStringLiterals: yes] , code: 'typeof foo is typeof bar' options: [requireStringLiterals: yes] , code: 'typeof foo is "string"' options: [requireStringLiterals: yes] , code: '"object" is typeof foo' options: [requireStringLiterals: yes] , code: 'typeof foo is "str#{somethingElse}"' ] invalid: [ code: "typeof foo is 'strnig'" errors: [message: 'Invalid typeof comparison value.', type: 'Literal'] , code: "'strnig' is typeof foo" errors: [message: 'Invalid typeof comparison value.', type: 'Literal'] , code: "if (typeof bar is 'umdefined') then ;" errors: [message: 'Invalid typeof comparison value.', type: 'Literal'] , code: "typeof foo isnt 'strnig'" errors: [message: 'Invalid typeof comparison value.', type: 'Literal'] , code: "'strnig' isnt typeof foo" errors: [message: 'Invalid typeof comparison value.', type: 'Literal'] , code: "if (typeof bar isnt 'umdefined') then ;" errors: [message: 'Invalid typeof comparison value.', type: 'Literal'] , code: "typeof foo != 'strnig'" errors: [message: 'Invalid typeof comparison value.', type: 'Literal'] , code: "'strnig' != typeof foo" errors: [message: 'Invalid typeof comparison value.', type: 'Literal'] , code: "if (typeof bar != 'umdefined') then ;" errors: [message: 'Invalid typeof comparison value.', type: 'Literal'] , code: "typeof foo == 'strnig'" errors: [message: 'Invalid typeof comparison value.', type: 'Literal'] , code: "'strnig' == typeof foo" errors: [message: 'Invalid typeof comparison value.', type: 'Literal'] , code: "if (typeof bar == 'umdefined') then ;" errors: [message: 'Invalid typeof comparison value.', type: 'Literal'] , code: "typeof foo == 'invalid string'" options: [requireStringLiterals: yes] errors: [message: 'Invalid typeof comparison value.', type: 'Literal'] , code: 'typeof foo == Object' options: [requireStringLiterals: yes] errors: [ message: 'Typeof comparisons should be to string literals.' type: 'Identifier' ] , code: 'typeof foo is undefined' options: [requireStringLiterals: yes] errors: [ message: 'Typeof comparisons should be to string literals.' type: 'Identifier' ] , code: 'undefined is typeof foo' options: [requireStringLiterals: yes] errors: [ message: 'Typeof comparisons should be to string literals.' type: 'Identifier' ] , code: 'undefined == typeof foo' options: [requireStringLiterals: yes] errors: [ message: 'Typeof comparisons should be to string literals.' type: 'Identifier' ] , code: 'typeof foo is "undefined#{foo}"' options: [requireStringLiterals: yes] errors: [ message: 'Typeof comparisons should be to string literals.' type: 'TemplateLiteral' ] , code: 'typeof foo is "#{string}"' options: [requireStringLiterals: yes] errors: [ message: 'Typeof comparisons should be to string literals.' type: 'TemplateLiteral' ] ]
true
###* # @fileoverview Ensures that the results of typeof are compared against a valid string # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/valid-typeof' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ### eslint-disable coffee/no-template-curly-in-string ### ruleTester.run 'valid-typeof', rule, valid: [ "typeof foo is 'string'" "typeof foo is 'object'" "typeof foo is 'function'" "typeof foo is 'undefined'" "typeof foo is 'boolean'" "typeof foo is 'number'" "'string' is typeof foo" "'object' is typeof foo" "'function' is typeof foo" "'undefined' is typeof foo" "'boolean' is typeof foo" "'number' is typeof foo" 'typeof foo is typeof bar' 'typeof foo is baz' 'typeof foo isnt someType' 'typeof bar != someType' 'someType is typeof bar' 'someType == typeof bar' "typeof foo == 'string'" "typeof(foo) is 'string'" "typeof(foo) isnt 'string'" "typeof(foo) == 'string'" "typeof(foo) != 'string'" "oddUse = typeof foo + 'thing'" , code: "typeof foo is 'number'" options: [requireStringLiterals: yes] , code: 'typeof foo is "number"' options: [requireStringLiterals: yes] , code: "baz = typeof foo + 'thing'" options: [requireStringLiterals: yes] , code: 'typeof foo is typeof bar' options: [requireStringLiterals: yes] , code: 'typeof foo is "string"' options: [requireStringLiterals: yes] , code: '"object" is typeof foo' options: [requireStringLiterals: yes] , code: 'typeof foo is "str#{somethingElse}"' ] invalid: [ code: "typeof foo is 'strnig'" errors: [message: 'Invalid typeof comparison value.', type: 'Literal'] , code: "'strnig' is typeof foo" errors: [message: 'Invalid typeof comparison value.', type: 'Literal'] , code: "if (typeof bar is 'umdefined') then ;" errors: [message: 'Invalid typeof comparison value.', type: 'Literal'] , code: "typeof foo isnt 'strnig'" errors: [message: 'Invalid typeof comparison value.', type: 'Literal'] , code: "'strnig' isnt typeof foo" errors: [message: 'Invalid typeof comparison value.', type: 'Literal'] , code: "if (typeof bar isnt 'umdefined') then ;" errors: [message: 'Invalid typeof comparison value.', type: 'Literal'] , code: "typeof foo != 'strnig'" errors: [message: 'Invalid typeof comparison value.', type: 'Literal'] , code: "'strnig' != typeof foo" errors: [message: 'Invalid typeof comparison value.', type: 'Literal'] , code: "if (typeof bar != 'umdefined') then ;" errors: [message: 'Invalid typeof comparison value.', type: 'Literal'] , code: "typeof foo == 'strnig'" errors: [message: 'Invalid typeof comparison value.', type: 'Literal'] , code: "'strnig' == typeof foo" errors: [message: 'Invalid typeof comparison value.', type: 'Literal'] , code: "if (typeof bar == 'umdefined') then ;" errors: [message: 'Invalid typeof comparison value.', type: 'Literal'] , code: "typeof foo == 'invalid string'" options: [requireStringLiterals: yes] errors: [message: 'Invalid typeof comparison value.', type: 'Literal'] , code: 'typeof foo == Object' options: [requireStringLiterals: yes] errors: [ message: 'Typeof comparisons should be to string literals.' type: 'Identifier' ] , code: 'typeof foo is undefined' options: [requireStringLiterals: yes] errors: [ message: 'Typeof comparisons should be to string literals.' type: 'Identifier' ] , code: 'undefined is typeof foo' options: [requireStringLiterals: yes] errors: [ message: 'Typeof comparisons should be to string literals.' type: 'Identifier' ] , code: 'undefined == typeof foo' options: [requireStringLiterals: yes] errors: [ message: 'Typeof comparisons should be to string literals.' type: 'Identifier' ] , code: 'typeof foo is "undefined#{foo}"' options: [requireStringLiterals: yes] errors: [ message: 'Typeof comparisons should be to string literals.' type: 'TemplateLiteral' ] , code: 'typeof foo is "#{string}"' options: [requireStringLiterals: yes] errors: [ message: 'Typeof comparisons should be to string literals.' type: 'TemplateLiteral' ] ]
[ { "context": "-----\n\n(() ->\n\n\ttree = taml(\"\"\"\n\t\t---\n\t\t-\n\t\t\tname: John\n\t\t\tage: 68\n\t\t\tbody:\n\t\t\t\t-\n\t\t\t\t\tname: Judy\n\t\t\t\t\tag", "end": 874, "score": 0.9998607635498047, "start": 870, "tag": "NAME", "value": "John" }, { "context": "\t\t\tname: John...
test/tree.test.coffee
johndeighan/string-input
0
# tree.test.coffee import {undef, oneline} from '@jdeighan/coffee-utils' import {UnitTester} from '@jdeighan/coffee-utils/test' import {debug} from '@jdeighan/coffee-utils/debug' import {taml} from '@jdeighan/string-input/taml' import {TreeWalker, TreeStringifier} from '@jdeighan/string-input/tree' simple = new UnitTester() # --------------------------------------------------------------------------- class TreeTester extends UnitTester transformValue: (tree) -> debug "enter transformValue()" debug "TREE", tree stringifier = new TreeStringifier(tree) str = stringifier.get() debug "return #{oneline(str)} from transformValue()" return str normalize: (str) -> return str # disable normalize() tester = new TreeTester() # --------------------------------------------------------------------------- (() -> tree = taml(""" --- - name: John age: 68 body: - name: Judy age: 24 - name: Bob age: 34 - name: Lewis age: 40 """) tester.equal 49, tree, """ {"name":"John","age":68} {"name":"Judy","age":24} {"name":"Bob","age":34} {"name":"Lewis","age":40} """ )() # ---------------------------------------------------------------------------
38378
# tree.test.coffee import {undef, oneline} from '@jdeighan/coffee-utils' import {UnitTester} from '@jdeighan/coffee-utils/test' import {debug} from '@jdeighan/coffee-utils/debug' import {taml} from '@jdeighan/string-input/taml' import {TreeWalker, TreeStringifier} from '@jdeighan/string-input/tree' simple = new UnitTester() # --------------------------------------------------------------------------- class TreeTester extends UnitTester transformValue: (tree) -> debug "enter transformValue()" debug "TREE", tree stringifier = new TreeStringifier(tree) str = stringifier.get() debug "return #{oneline(str)} from transformValue()" return str normalize: (str) -> return str # disable normalize() tester = new TreeTester() # --------------------------------------------------------------------------- (() -> tree = taml(""" --- - name: <NAME> age: 68 body: - name: <NAME> age: 24 - name: <NAME> age: 34 - name: <NAME> age: 40 """) tester.equal 49, tree, """ {"name":"<NAME>","age":68} {"name":"<NAME>","age":24} {"name":"<NAME>","age":34} {"name":"<NAME>","age":40} """ )() # ---------------------------------------------------------------------------
true
# tree.test.coffee import {undef, oneline} from '@jdeighan/coffee-utils' import {UnitTester} from '@jdeighan/coffee-utils/test' import {debug} from '@jdeighan/coffee-utils/debug' import {taml} from '@jdeighan/string-input/taml' import {TreeWalker, TreeStringifier} from '@jdeighan/string-input/tree' simple = new UnitTester() # --------------------------------------------------------------------------- class TreeTester extends UnitTester transformValue: (tree) -> debug "enter transformValue()" debug "TREE", tree stringifier = new TreeStringifier(tree) str = stringifier.get() debug "return #{oneline(str)} from transformValue()" return str normalize: (str) -> return str # disable normalize() tester = new TreeTester() # --------------------------------------------------------------------------- (() -> tree = taml(""" --- - name: PI:NAME:<NAME>END_PI age: 68 body: - name: PI:NAME:<NAME>END_PI age: 24 - name: PI:NAME:<NAME>END_PI age: 34 - name: PI:NAME:<NAME>END_PI age: 40 """) tester.equal 49, tree, """ {"name":"PI:NAME:<NAME>END_PI","age":68} {"name":"PI:NAME:<NAME>END_PI","age":24} {"name":"PI:NAME:<NAME>END_PI","age":34} {"name":"PI:NAME:<NAME>END_PI","age":40} """ )() # ---------------------------------------------------------------------------
[ { "context": "' ' + @get('lastName')\n ).property('firstName', 'lastName')\n\n title: ( ->\n @get('fullName')\n ).propert", "end": 752, "score": 0.6885738968849182, "start": 744, "tag": "NAME", "value": "lastName" } ]
ember/app/models/resume.coffee
kjayma/rezoome
0
`import DS from 'ember-data'` Resume = DS.Model.extend primaryEmail: DS.attr('string') filename: DS.attr('string') firstName: DS.attr('string') lastName: DS.attr('string') address1: DS.attr('string') address2: DS.attr('string') city: DS.attr('string') state: DS.attr('string') zip: DS.attr('string') location: DS.attr() homePhone: DS.attr('string') mobilePhone: DS.attr('string') doctype: DS.attr('string') position: DS.attr('string') notes: DS.attr('string') created_at: DS.attr('date') updated_at: DS.attr('date') distance: DS.attr('number') otherResumes: DS.hasMany('other_resumes') content: DS.attr('file') fullName: ( -> @get('firstName') + ' ' + @get('lastName') ).property('firstName', 'lastName') title: ( -> @get('fullName') ).property('fullName') currentJob: Ember.computed 'otherResumes.resumeText', -> otherResumesSorted = Ember.ArrayProxy.createWithMixins Ember.SortableMixin, sortAscending: false sortProperties: ['lastUpdate'] content: @get('otherResumes') latest_resume = otherResumesSorted.objectAt(0) latest_text = latest_resume.get('resumeText') job_regex = /^(.*)(\d{2}|[:\-–]|to)+ *([Pp]resent|Current)(.*)$/m match = job_regex.exec(latest_text) if match if !match[1] && !match[3] job_regex = /\n.*\n.*\n(.*)\d{4} +([:\-–]|to)(.*)$/m match = job_regex.exec(latest_text) else job_regex = /^(.*)[ \/\-–]\d{4} +([:\-–]|to)(.*)$/m match = job_regex.exec(latest_text) if match return match[0] resumeTextUrl: ( -> adapterfor = @store.adapterFor('application') host = document.location.host.replace(/\:4200/,':3000') namespace = adapterfor.namespace 'http://' + host + '/' + namespace + '/resumes/textfiles/' + @get('id') ).property('id') resumesOnFile: ( -> @get('otherResumes').length ).property('otherResumes') lat: ( -> @get('location')[1] ).property('location') lng: ( -> @get('location')[0] ).property('location') resumeUploadUrl: ( -> adapterfor = @store.adapterFor('application') host = document.location.host.replace(/\:4200/,':3000') namespace = adapterfor.namespace 'http://' + host + '/' + namespace + '/resumes/' + @get('id') + '/resume_content' ).property('id') `export default Resume`
103450
`import DS from 'ember-data'` Resume = DS.Model.extend primaryEmail: DS.attr('string') filename: DS.attr('string') firstName: DS.attr('string') lastName: DS.attr('string') address1: DS.attr('string') address2: DS.attr('string') city: DS.attr('string') state: DS.attr('string') zip: DS.attr('string') location: DS.attr() homePhone: DS.attr('string') mobilePhone: DS.attr('string') doctype: DS.attr('string') position: DS.attr('string') notes: DS.attr('string') created_at: DS.attr('date') updated_at: DS.attr('date') distance: DS.attr('number') otherResumes: DS.hasMany('other_resumes') content: DS.attr('file') fullName: ( -> @get('firstName') + ' ' + @get('lastName') ).property('firstName', '<NAME>') title: ( -> @get('fullName') ).property('fullName') currentJob: Ember.computed 'otherResumes.resumeText', -> otherResumesSorted = Ember.ArrayProxy.createWithMixins Ember.SortableMixin, sortAscending: false sortProperties: ['lastUpdate'] content: @get('otherResumes') latest_resume = otherResumesSorted.objectAt(0) latest_text = latest_resume.get('resumeText') job_regex = /^(.*)(\d{2}|[:\-–]|to)+ *([Pp]resent|Current)(.*)$/m match = job_regex.exec(latest_text) if match if !match[1] && !match[3] job_regex = /\n.*\n.*\n(.*)\d{4} +([:\-–]|to)(.*)$/m match = job_regex.exec(latest_text) else job_regex = /^(.*)[ \/\-–]\d{4} +([:\-–]|to)(.*)$/m match = job_regex.exec(latest_text) if match return match[0] resumeTextUrl: ( -> adapterfor = @store.adapterFor('application') host = document.location.host.replace(/\:4200/,':3000') namespace = adapterfor.namespace 'http://' + host + '/' + namespace + '/resumes/textfiles/' + @get('id') ).property('id') resumesOnFile: ( -> @get('otherResumes').length ).property('otherResumes') lat: ( -> @get('location')[1] ).property('location') lng: ( -> @get('location')[0] ).property('location') resumeUploadUrl: ( -> adapterfor = @store.adapterFor('application') host = document.location.host.replace(/\:4200/,':3000') namespace = adapterfor.namespace 'http://' + host + '/' + namespace + '/resumes/' + @get('id') + '/resume_content' ).property('id') `export default Resume`
true
`import DS from 'ember-data'` Resume = DS.Model.extend primaryEmail: DS.attr('string') filename: DS.attr('string') firstName: DS.attr('string') lastName: DS.attr('string') address1: DS.attr('string') address2: DS.attr('string') city: DS.attr('string') state: DS.attr('string') zip: DS.attr('string') location: DS.attr() homePhone: DS.attr('string') mobilePhone: DS.attr('string') doctype: DS.attr('string') position: DS.attr('string') notes: DS.attr('string') created_at: DS.attr('date') updated_at: DS.attr('date') distance: DS.attr('number') otherResumes: DS.hasMany('other_resumes') content: DS.attr('file') fullName: ( -> @get('firstName') + ' ' + @get('lastName') ).property('firstName', 'PI:NAME:<NAME>END_PI') title: ( -> @get('fullName') ).property('fullName') currentJob: Ember.computed 'otherResumes.resumeText', -> otherResumesSorted = Ember.ArrayProxy.createWithMixins Ember.SortableMixin, sortAscending: false sortProperties: ['lastUpdate'] content: @get('otherResumes') latest_resume = otherResumesSorted.objectAt(0) latest_text = latest_resume.get('resumeText') job_regex = /^(.*)(\d{2}|[:\-–]|to)+ *([Pp]resent|Current)(.*)$/m match = job_regex.exec(latest_text) if match if !match[1] && !match[3] job_regex = /\n.*\n.*\n(.*)\d{4} +([:\-–]|to)(.*)$/m match = job_regex.exec(latest_text) else job_regex = /^(.*)[ \/\-–]\d{4} +([:\-–]|to)(.*)$/m match = job_regex.exec(latest_text) if match return match[0] resumeTextUrl: ( -> adapterfor = @store.adapterFor('application') host = document.location.host.replace(/\:4200/,':3000') namespace = adapterfor.namespace 'http://' + host + '/' + namespace + '/resumes/textfiles/' + @get('id') ).property('id') resumesOnFile: ( -> @get('otherResumes').length ).property('otherResumes') lat: ( -> @get('location')[1] ).property('location') lng: ( -> @get('location')[0] ).property('location') resumeUploadUrl: ( -> adapterfor = @store.adapterFor('application') host = document.location.host.replace(/\:4200/,':3000') namespace = adapterfor.namespace 'http://' + host + '/' + namespace + '/resumes/' + @get('id') + '/resume_content' ).property('id') `export default Resume`
[ { "context": "iew Disallow redundant return statements\n# @author Teddy Katz\n###\n'use strict'\n\n#------------------------------", "end": 78, "score": 0.9998509287834167, "start": 68, "tag": "NAME", "value": "Teddy Katz" }, { "context": " # no-else-return.\n # https://gith...
src/rules/no-useless-return.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Disallow redundant return statements # @author Teddy Katz ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ astUtils = require '../eslint-ast-utils' utils = require '../util/ast-utils' FixTracker = try require 'eslint/lib/util/fix-tracker' catch require 'eslint/lib/rules/utils/fix-tracker' #------------------------------------------------------------------------------ # Helpers #------------------------------------------------------------------------------ ###* # Removes the given element from the array. # # @param {Array} array - The source array to remove. # @param {any} element - The target item to remove. # @returns {void} ### remove = (array, element) -> index = array.indexOf element unless index is -1 then array.splice index, 1 ###* # Checks whether it can remove the given return statement or not. # # @param {ASTNode} node - The return statement node to check. # @returns {boolean} `true` if the node is removeable. ### isRemovable = (node) -> return no if ( node.parent.type is 'BlockStatement' and node.parent.parent.type is 'IfStatement' and node.parent.body.length is 1 and node is node.parent.body[0] ) astUtils.STATEMENT_LIST_PARENTS.has node.parent.type ###* # Checks whether the given return statement is in a `finally` block or not. # # @param {ASTNode} node - The return statement node to check. # @returns {boolean} `true` if the node is in a `finally` block. ### isInFinally = (node) -> currentNode = node while currentNode?.parent and not astUtils.isFunction currentNode return yes if ( currentNode.parent.type is 'TryStatement' and currentNode.parent.finalizer is currentNode ) currentNode = currentNode.parent no isAwaitOrYieldReturn = (node) -> node.parent.type in ['AwaitExpression', 'YieldExpression'] #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'disallow redundant return statements' category: 'Best Practices' recommended: no url: 'https://eslint.org/docs/rules/no-useless-return' fixable: 'code' schema: [] create: (context) -> segmentInfoMap = new WeakMap() usedUnreachableSegments = new WeakSet() scopeInfo = null ###* # Checks whether the given segment is terminated by a return statement or not. # # @param {CodePathSegment} segment - The segment to check. # @returns {boolean} `true` if the segment is terminated by a return statement, or if it's still a part of unreachable. ### isReturned = (segment) -> info = segmentInfoMap.get segment not info or info.returned ###* # Collects useless return statements from the given previous segments. # # A previous segment may be an unreachable segment. # In that case, the information object of the unreachable segment is not # initialized because `onCodePathSegmentStart` event is not notified for # unreachable segments. # This goes to the previous segments of the unreachable segment recursively # if the unreachable segment was generated by a return statement. Otherwise, # this ignores the unreachable segment. # # This behavior would simulate code paths for the case that the return # statement does not exist. # # @param {ASTNode[]} uselessReturns - The collected return statements. # @param {CodePathSegment[]} prevSegments - The previous segments to traverse. # @param {WeakSet<CodePathSegment>} [providedTraversedSegments] A set of segments that have already been traversed in this call # @returns {ASTNode[]} `uselessReturns`. ### getUselessReturns = ( uselessReturns prevSegments providedTraversedSegments ) -> traversedSegments = providedTraversedSegments or new WeakSet() for segment from prevSegments unless segment.reachable unless traversedSegments.has segment traversedSegments.add segment getUselessReturns( uselessReturns segment.allPrevSegments.filter isReturned traversedSegments ) continue uselessReturns.push ...segmentInfoMap.get(segment).uselessReturns uselessReturns ###* # Removes the return statements on the given segment from the useless return # statement list. # # This segment may be an unreachable segment. # In that case, the information object of the unreachable segment is not # initialized because `onCodePathSegmentStart` event is not notified for # unreachable segments. # This goes to the previous segments of the unreachable segment recursively # if the unreachable segment was generated by a return statement. Otherwise, # this ignores the unreachable segment. # # This behavior would simulate code paths for the case that the return # statement does not exist. # # @param {CodePathSegment} segment - The segment to get return statements. # @returns {void} ### markReturnStatementsOnSegmentAsUsed = (segment) -> unless segment.reachable usedUnreachableSegments.add segment segment.allPrevSegments .filter isReturned .filter (prevSegment) -> not usedUnreachableSegments.has prevSegment .forEach markReturnStatementsOnSegmentAsUsed return info = segmentInfoMap.get segment for node from info.uselessReturns then remove( scopeInfo.uselessReturns node ) info.uselessReturns = [] ###* # Removes the return statements on the current segments from the useless # return statement list. # # This function will be called at every statement except FunctionDeclaration, # BlockStatement, and BreakStatement. # # - FunctionDeclarations are always executed whether it's returned or not. # - BlockStatements do nothing. # - BreakStatements go the next merely. # # @returns {void} ### markReturnStatementsOnCurrentSegmentsAsUsed = -> scopeInfo.codePath.currentSegments.forEach( markReturnStatementsOnSegmentAsUsed ) #---------------------------------------------------------------------- # Public #---------------------------------------------------------------------- # Makes and pushs a new scope information. onCodePathStart: (codePath) -> scopeInfo = { upper: scopeInfo uselessReturns: [] codePath } # Reports useless return statements if exist. onCodePathEnd: -> for node from scopeInfo.uselessReturns then context.report { node loc: node.loc message: 'Unnecessary return statement.' # eslint-disable-next-line coffee/no-loop-func fix: (fixer) -> ### # Extend the replacement range to include the # entire function to avoid conflicting with # no-else-return. # https://github.com/eslint/eslint/issues/8026 ### return new FixTracker(fixer, context.getSourceCode()) .retainEnclosingFunction(node) .remove node if isRemovable node null } scopeInfo ###:### = scopeInfo.upper ### # Initializes segments. # NOTE: This event is notified for only reachable segments. ### onCodePathSegmentStart: (segment) -> info = uselessReturns: getUselessReturns [], segment.allPrevSegments returned: no # Stores the info. segmentInfoMap.set segment, info # Adds ReturnStatement node to check whether it's useless or not. ReturnStatement: (node) -> if node.argument then markReturnStatementsOnCurrentSegmentsAsUsed() return if ( node.argument or utils.isInLoop(node) or isInFinally(node) or isAwaitOrYieldReturn node ) for segment from scopeInfo.codePath.currentSegments info = segmentInfoMap.get segment if info info.uselessReturns.push node info.returned = yes scopeInfo.uselessReturns.push node ### # Registers for all statement nodes except FunctionDeclaration, BlockStatement, BreakStatement. # Removes return statements of the current segments from the useless return statement list. ### ClassDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed ContinueStatement: markReturnStatementsOnCurrentSegmentsAsUsed DebuggerStatement: markReturnStatementsOnCurrentSegmentsAsUsed DoWhileStatement: markReturnStatementsOnCurrentSegmentsAsUsed EmptyStatement: markReturnStatementsOnCurrentSegmentsAsUsed ExpressionStatement: markReturnStatementsOnCurrentSegmentsAsUsed ForInStatement: markReturnStatementsOnCurrentSegmentsAsUsed ForOfStatement: markReturnStatementsOnCurrentSegmentsAsUsed ForStatement: markReturnStatementsOnCurrentSegmentsAsUsed For: markReturnStatementsOnCurrentSegmentsAsUsed IfStatement: markReturnStatementsOnCurrentSegmentsAsUsed ImportDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed LabeledStatement: markReturnStatementsOnCurrentSegmentsAsUsed SwitchStatement: markReturnStatementsOnCurrentSegmentsAsUsed ThrowStatement: markReturnStatementsOnCurrentSegmentsAsUsed TryStatement: markReturnStatementsOnCurrentSegmentsAsUsed VariableDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed WhileStatement: markReturnStatementsOnCurrentSegmentsAsUsed WithStatement: markReturnStatementsOnCurrentSegmentsAsUsed ExportNamedDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed ExportDefaultDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed ExportAllDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed
5228
###* # @fileoverview Disallow redundant return statements # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ astUtils = require '../eslint-ast-utils' utils = require '../util/ast-utils' FixTracker = try require 'eslint/lib/util/fix-tracker' catch require 'eslint/lib/rules/utils/fix-tracker' #------------------------------------------------------------------------------ # Helpers #------------------------------------------------------------------------------ ###* # Removes the given element from the array. # # @param {Array} array - The source array to remove. # @param {any} element - The target item to remove. # @returns {void} ### remove = (array, element) -> index = array.indexOf element unless index is -1 then array.splice index, 1 ###* # Checks whether it can remove the given return statement or not. # # @param {ASTNode} node - The return statement node to check. # @returns {boolean} `true` if the node is removeable. ### isRemovable = (node) -> return no if ( node.parent.type is 'BlockStatement' and node.parent.parent.type is 'IfStatement' and node.parent.body.length is 1 and node is node.parent.body[0] ) astUtils.STATEMENT_LIST_PARENTS.has node.parent.type ###* # Checks whether the given return statement is in a `finally` block or not. # # @param {ASTNode} node - The return statement node to check. # @returns {boolean} `true` if the node is in a `finally` block. ### isInFinally = (node) -> currentNode = node while currentNode?.parent and not astUtils.isFunction currentNode return yes if ( currentNode.parent.type is 'TryStatement' and currentNode.parent.finalizer is currentNode ) currentNode = currentNode.parent no isAwaitOrYieldReturn = (node) -> node.parent.type in ['AwaitExpression', 'YieldExpression'] #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'disallow redundant return statements' category: 'Best Practices' recommended: no url: 'https://eslint.org/docs/rules/no-useless-return' fixable: 'code' schema: [] create: (context) -> segmentInfoMap = new WeakMap() usedUnreachableSegments = new WeakSet() scopeInfo = null ###* # Checks whether the given segment is terminated by a return statement or not. # # @param {CodePathSegment} segment - The segment to check. # @returns {boolean} `true` if the segment is terminated by a return statement, or if it's still a part of unreachable. ### isReturned = (segment) -> info = segmentInfoMap.get segment not info or info.returned ###* # Collects useless return statements from the given previous segments. # # A previous segment may be an unreachable segment. # In that case, the information object of the unreachable segment is not # initialized because `onCodePathSegmentStart` event is not notified for # unreachable segments. # This goes to the previous segments of the unreachable segment recursively # if the unreachable segment was generated by a return statement. Otherwise, # this ignores the unreachable segment. # # This behavior would simulate code paths for the case that the return # statement does not exist. # # @param {ASTNode[]} uselessReturns - The collected return statements. # @param {CodePathSegment[]} prevSegments - The previous segments to traverse. # @param {WeakSet<CodePathSegment>} [providedTraversedSegments] A set of segments that have already been traversed in this call # @returns {ASTNode[]} `uselessReturns`. ### getUselessReturns = ( uselessReturns prevSegments providedTraversedSegments ) -> traversedSegments = providedTraversedSegments or new WeakSet() for segment from prevSegments unless segment.reachable unless traversedSegments.has segment traversedSegments.add segment getUselessReturns( uselessReturns segment.allPrevSegments.filter isReturned traversedSegments ) continue uselessReturns.push ...segmentInfoMap.get(segment).uselessReturns uselessReturns ###* # Removes the return statements on the given segment from the useless return # statement list. # # This segment may be an unreachable segment. # In that case, the information object of the unreachable segment is not # initialized because `onCodePathSegmentStart` event is not notified for # unreachable segments. # This goes to the previous segments of the unreachable segment recursively # if the unreachable segment was generated by a return statement. Otherwise, # this ignores the unreachable segment. # # This behavior would simulate code paths for the case that the return # statement does not exist. # # @param {CodePathSegment} segment - The segment to get return statements. # @returns {void} ### markReturnStatementsOnSegmentAsUsed = (segment) -> unless segment.reachable usedUnreachableSegments.add segment segment.allPrevSegments .filter isReturned .filter (prevSegment) -> not usedUnreachableSegments.has prevSegment .forEach markReturnStatementsOnSegmentAsUsed return info = segmentInfoMap.get segment for node from info.uselessReturns then remove( scopeInfo.uselessReturns node ) info.uselessReturns = [] ###* # Removes the return statements on the current segments from the useless # return statement list. # # This function will be called at every statement except FunctionDeclaration, # BlockStatement, and BreakStatement. # # - FunctionDeclarations are always executed whether it's returned or not. # - BlockStatements do nothing. # - BreakStatements go the next merely. # # @returns {void} ### markReturnStatementsOnCurrentSegmentsAsUsed = -> scopeInfo.codePath.currentSegments.forEach( markReturnStatementsOnSegmentAsUsed ) #---------------------------------------------------------------------- # Public #---------------------------------------------------------------------- # Makes and pushs a new scope information. onCodePathStart: (codePath) -> scopeInfo = { upper: scopeInfo uselessReturns: [] codePath } # Reports useless return statements if exist. onCodePathEnd: -> for node from scopeInfo.uselessReturns then context.report { node loc: node.loc message: 'Unnecessary return statement.' # eslint-disable-next-line coffee/no-loop-func fix: (fixer) -> ### # Extend the replacement range to include the # entire function to avoid conflicting with # no-else-return. # https://github.com/eslint/eslint/issues/8026 ### return new FixTracker(fixer, context.getSourceCode()) .retainEnclosingFunction(node) .remove node if isRemovable node null } scopeInfo ###:### = scopeInfo.upper ### # Initializes segments. # NOTE: This event is notified for only reachable segments. ### onCodePathSegmentStart: (segment) -> info = uselessReturns: getUselessReturns [], segment.allPrevSegments returned: no # Stores the info. segmentInfoMap.set segment, info # Adds ReturnStatement node to check whether it's useless or not. ReturnStatement: (node) -> if node.argument then markReturnStatementsOnCurrentSegmentsAsUsed() return if ( node.argument or utils.isInLoop(node) or isInFinally(node) or isAwaitOrYieldReturn node ) for segment from scopeInfo.codePath.currentSegments info = segmentInfoMap.get segment if info info.uselessReturns.push node info.returned = yes scopeInfo.uselessReturns.push node ### # Registers for all statement nodes except FunctionDeclaration, BlockStatement, BreakStatement. # Removes return statements of the current segments from the useless return statement list. ### ClassDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed ContinueStatement: markReturnStatementsOnCurrentSegmentsAsUsed DebuggerStatement: markReturnStatementsOnCurrentSegmentsAsUsed DoWhileStatement: markReturnStatementsOnCurrentSegmentsAsUsed EmptyStatement: markReturnStatementsOnCurrentSegmentsAsUsed ExpressionStatement: markReturnStatementsOnCurrentSegmentsAsUsed ForInStatement: markReturnStatementsOnCurrentSegmentsAsUsed ForOfStatement: markReturnStatementsOnCurrentSegmentsAsUsed ForStatement: markReturnStatementsOnCurrentSegmentsAsUsed For: markReturnStatementsOnCurrentSegmentsAsUsed IfStatement: markReturnStatementsOnCurrentSegmentsAsUsed ImportDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed LabeledStatement: markReturnStatementsOnCurrentSegmentsAsUsed SwitchStatement: markReturnStatementsOnCurrentSegmentsAsUsed ThrowStatement: markReturnStatementsOnCurrentSegmentsAsUsed TryStatement: markReturnStatementsOnCurrentSegmentsAsUsed VariableDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed WhileStatement: markReturnStatementsOnCurrentSegmentsAsUsed WithStatement: markReturnStatementsOnCurrentSegmentsAsUsed ExportNamedDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed ExportDefaultDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed ExportAllDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed
true
###* # @fileoverview Disallow redundant return statements # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ astUtils = require '../eslint-ast-utils' utils = require '../util/ast-utils' FixTracker = try require 'eslint/lib/util/fix-tracker' catch require 'eslint/lib/rules/utils/fix-tracker' #------------------------------------------------------------------------------ # Helpers #------------------------------------------------------------------------------ ###* # Removes the given element from the array. # # @param {Array} array - The source array to remove. # @param {any} element - The target item to remove. # @returns {void} ### remove = (array, element) -> index = array.indexOf element unless index is -1 then array.splice index, 1 ###* # Checks whether it can remove the given return statement or not. # # @param {ASTNode} node - The return statement node to check. # @returns {boolean} `true` if the node is removeable. ### isRemovable = (node) -> return no if ( node.parent.type is 'BlockStatement' and node.parent.parent.type is 'IfStatement' and node.parent.body.length is 1 and node is node.parent.body[0] ) astUtils.STATEMENT_LIST_PARENTS.has node.parent.type ###* # Checks whether the given return statement is in a `finally` block or not. # # @param {ASTNode} node - The return statement node to check. # @returns {boolean} `true` if the node is in a `finally` block. ### isInFinally = (node) -> currentNode = node while currentNode?.parent and not astUtils.isFunction currentNode return yes if ( currentNode.parent.type is 'TryStatement' and currentNode.parent.finalizer is currentNode ) currentNode = currentNode.parent no isAwaitOrYieldReturn = (node) -> node.parent.type in ['AwaitExpression', 'YieldExpression'] #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'disallow redundant return statements' category: 'Best Practices' recommended: no url: 'https://eslint.org/docs/rules/no-useless-return' fixable: 'code' schema: [] create: (context) -> segmentInfoMap = new WeakMap() usedUnreachableSegments = new WeakSet() scopeInfo = null ###* # Checks whether the given segment is terminated by a return statement or not. # # @param {CodePathSegment} segment - The segment to check. # @returns {boolean} `true` if the segment is terminated by a return statement, or if it's still a part of unreachable. ### isReturned = (segment) -> info = segmentInfoMap.get segment not info or info.returned ###* # Collects useless return statements from the given previous segments. # # A previous segment may be an unreachable segment. # In that case, the information object of the unreachable segment is not # initialized because `onCodePathSegmentStart` event is not notified for # unreachable segments. # This goes to the previous segments of the unreachable segment recursively # if the unreachable segment was generated by a return statement. Otherwise, # this ignores the unreachable segment. # # This behavior would simulate code paths for the case that the return # statement does not exist. # # @param {ASTNode[]} uselessReturns - The collected return statements. # @param {CodePathSegment[]} prevSegments - The previous segments to traverse. # @param {WeakSet<CodePathSegment>} [providedTraversedSegments] A set of segments that have already been traversed in this call # @returns {ASTNode[]} `uselessReturns`. ### getUselessReturns = ( uselessReturns prevSegments providedTraversedSegments ) -> traversedSegments = providedTraversedSegments or new WeakSet() for segment from prevSegments unless segment.reachable unless traversedSegments.has segment traversedSegments.add segment getUselessReturns( uselessReturns segment.allPrevSegments.filter isReturned traversedSegments ) continue uselessReturns.push ...segmentInfoMap.get(segment).uselessReturns uselessReturns ###* # Removes the return statements on the given segment from the useless return # statement list. # # This segment may be an unreachable segment. # In that case, the information object of the unreachable segment is not # initialized because `onCodePathSegmentStart` event is not notified for # unreachable segments. # This goes to the previous segments of the unreachable segment recursively # if the unreachable segment was generated by a return statement. Otherwise, # this ignores the unreachable segment. # # This behavior would simulate code paths for the case that the return # statement does not exist. # # @param {CodePathSegment} segment - The segment to get return statements. # @returns {void} ### markReturnStatementsOnSegmentAsUsed = (segment) -> unless segment.reachable usedUnreachableSegments.add segment segment.allPrevSegments .filter isReturned .filter (prevSegment) -> not usedUnreachableSegments.has prevSegment .forEach markReturnStatementsOnSegmentAsUsed return info = segmentInfoMap.get segment for node from info.uselessReturns then remove( scopeInfo.uselessReturns node ) info.uselessReturns = [] ###* # Removes the return statements on the current segments from the useless # return statement list. # # This function will be called at every statement except FunctionDeclaration, # BlockStatement, and BreakStatement. # # - FunctionDeclarations are always executed whether it's returned or not. # - BlockStatements do nothing. # - BreakStatements go the next merely. # # @returns {void} ### markReturnStatementsOnCurrentSegmentsAsUsed = -> scopeInfo.codePath.currentSegments.forEach( markReturnStatementsOnSegmentAsUsed ) #---------------------------------------------------------------------- # Public #---------------------------------------------------------------------- # Makes and pushs a new scope information. onCodePathStart: (codePath) -> scopeInfo = { upper: scopeInfo uselessReturns: [] codePath } # Reports useless return statements if exist. onCodePathEnd: -> for node from scopeInfo.uselessReturns then context.report { node loc: node.loc message: 'Unnecessary return statement.' # eslint-disable-next-line coffee/no-loop-func fix: (fixer) -> ### # Extend the replacement range to include the # entire function to avoid conflicting with # no-else-return. # https://github.com/eslint/eslint/issues/8026 ### return new FixTracker(fixer, context.getSourceCode()) .retainEnclosingFunction(node) .remove node if isRemovable node null } scopeInfo ###:### = scopeInfo.upper ### # Initializes segments. # NOTE: This event is notified for only reachable segments. ### onCodePathSegmentStart: (segment) -> info = uselessReturns: getUselessReturns [], segment.allPrevSegments returned: no # Stores the info. segmentInfoMap.set segment, info # Adds ReturnStatement node to check whether it's useless or not. ReturnStatement: (node) -> if node.argument then markReturnStatementsOnCurrentSegmentsAsUsed() return if ( node.argument or utils.isInLoop(node) or isInFinally(node) or isAwaitOrYieldReturn node ) for segment from scopeInfo.codePath.currentSegments info = segmentInfoMap.get segment if info info.uselessReturns.push node info.returned = yes scopeInfo.uselessReturns.push node ### # Registers for all statement nodes except FunctionDeclaration, BlockStatement, BreakStatement. # Removes return statements of the current segments from the useless return statement list. ### ClassDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed ContinueStatement: markReturnStatementsOnCurrentSegmentsAsUsed DebuggerStatement: markReturnStatementsOnCurrentSegmentsAsUsed DoWhileStatement: markReturnStatementsOnCurrentSegmentsAsUsed EmptyStatement: markReturnStatementsOnCurrentSegmentsAsUsed ExpressionStatement: markReturnStatementsOnCurrentSegmentsAsUsed ForInStatement: markReturnStatementsOnCurrentSegmentsAsUsed ForOfStatement: markReturnStatementsOnCurrentSegmentsAsUsed ForStatement: markReturnStatementsOnCurrentSegmentsAsUsed For: markReturnStatementsOnCurrentSegmentsAsUsed IfStatement: markReturnStatementsOnCurrentSegmentsAsUsed ImportDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed LabeledStatement: markReturnStatementsOnCurrentSegmentsAsUsed SwitchStatement: markReturnStatementsOnCurrentSegmentsAsUsed ThrowStatement: markReturnStatementsOnCurrentSegmentsAsUsed TryStatement: markReturnStatementsOnCurrentSegmentsAsUsed VariableDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed WhileStatement: markReturnStatementsOnCurrentSegmentsAsUsed WithStatement: markReturnStatementsOnCurrentSegmentsAsUsed ExportNamedDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed ExportDefaultDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed ExportAllDeclaration: markReturnStatementsOnCurrentSegmentsAsUsed
[ { "context": "dateEmail { email, tfcode: tfcodeValue, password : passValue },\n success : (res) ->\n\n ", "end": 3400, "score": 0.954288899898529, "start": 3396, "tag": "PASSWORD", "value": "pass" }, { "context": "ee = 'on'\n formData.passwordConfirm =...
client/landing/site.landing/coffee/core/utils.coffee
ezgikaysi/koding
1
$ = require 'jquery' kd = require 'kd' kookies = require 'kookies' createFormData = (teamData) -> teamData ?= utils.getTeamData() formData = {} for own step, fields of teamData when not ('boolean' is typeof fields) for own field, value of fields if step is 'invite' unless formData.invitees then formData.invitees = value else formData.invitees += ",#{value}" else formData[field] = value return formData module.exports = utils = { clearKiteCaches: -> if window.localStorage? for kite in (Object.keys window.localStorage) when /^KITE_/.test kite delete window.localStorage[kite] analytics: require './analytics' getReferrer: -> match = location.pathname.match /\/R\/(.*)/ return referrer if match and referrer = match[1] getMainDomain: -> { hostname, port } = location kodingDomains = ['dev', 'sandbox', 'latest', 'koding'] prefix = hostname.split('.').shift() domain = if prefix in kodingDomains then hostname else hostname.split('.').slice(1).join('.') return "#{domain}#{if port then ':'+port else ''}" getGroupNameFromLocation: (hostname) -> { hostname } = location unless hostname ipV4Pattern = '(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.xip\.io$' subDomainPattern = '[A-Za-z0-9_]{1}[A-Za-z0-9_-]+' kodingDomains = '(?:dev|sandbox|latest|prod)' baseDomain = "#{kd.config.domains.base}".replace '.', '\\.' # e.g. [teamName.]dev|sandbox|latest|prod.koding.com teamPattern = if ///#{kodingDomains}\.#{baseDomain}$///.test hostname then ///(?:^(#{subDomainPattern})\.)?#{kodingDomains}\.#{baseDomain}$/// # e.g. [teamName.]koding.com else if ///#{baseDomain}$///.test hostname then ///(?:^(#{subDomainPattern})\.)?#{baseDomain}$/// # e.g. [teamName.]<teamMember>.koding.team else if /koding\.team$/.test hostname then ///(?:^(#{subDomainPattern})\.)?(?:#{subDomainPattern}\.)koding\.team$/// # e.g. [teamName.]<vm-ip>.xip.io else ///(?:^(#{subDomainPattern})\.)?#{ipV4Pattern}/// matches = hostname.match teamPattern teamName = matches?[1] or 'koding' return teamName checkIfGroupExists: (groupName, callback) -> $.ajax url : "/-/team/#{groupName}" type : 'post' success : (group) -> callback null, group error : (err) -> callback err getEmailValidator: (options = {}) -> { container, password, tfcode } = options container : container event : 'submit' messages : required : 'Please enter your email address.' email : 'That doesn\'t seem like a valid email address.' rules : required : yes email : yes available : (input, event) -> return if event?.which is 9 { required, email, minLength } = input.validationResults return if required or minLength input.setValidationResult 'available', null email = input.getValue() passValue = password.input.getValue() if password tfcodeValue = tfcode.input.getValue() if tfcode container.emit 'EmailIsNotAvailable' return unless input.valid utils.validateEmail { email, tfcode: tfcodeValue, password : passValue }, success : (res) -> return location.replace '/' if res is 'User is logged in!' container.emit 'EmailIsAvailable' input.setValidationResult 'available', null container.emit 'EmailValidationPassed' if res is yes error : ({ responseText }) -> return container.emit 'TwoFactorEnabled' if /TwoFactor/i.test responseText container.emit 'EmailIsNotAvailable' input.setValidationResult 'available', "Sorry, #{email} is already in use!" checkedPasswords: {} checkPasswordStrength: kd.utils.debounce 300, (password, callback) -> return callback { msg : 'No password specified!' } unless password return callback null, res if res = utils.checkedPasswords[password] $.ajax url : '/-/password-strength' type : 'POST' data : { password } success : (res) -> utils.checkedPasswords[res.password] = res callback null, res error : ({ responseJSON }) -> callback { msg : responseJSON } storeNewTeamData: (formName, formData) -> kd.team ?= {} { team } = kd team[formName] = formData localStorage.teamData = JSON.stringify team clearTeamData: -> localStorage.teamData = null kd.team = null getTeamData: -> return kd.team if kd.team return {} unless data = localStorage.teamData try team = JSON.parse data kd.team = team return team if team return {} getPreviousTeams: -> try teams = JSON.parse kookies.get 'koding-teams' return teams if teams and Object.keys(teams).length return null slugifyCompanyName: (team) -> if name = team.signup?.companyName then teamName = kd.utils.slugify name else teamName = '' return teamName createTeam: (callbacks = {}) -> formData = createFormData() formData._csrf = Cookies.get '_csrf' # manually add legacy fields - SY formData.agree = 'on' formData.passwordConfirm = formData.password formData.redirect = "#{location.protocol}//#{formData.slug}.#{location.host}?username=#{formData.username}" $.ajax url : '/-/teams/create' data : formData type : 'POST' success : callbacks.success or -> utils.clearTeamData() location.href = formData.redirect error : callbacks.error or ({ responseText }) -> new kd.NotificationView { title : responseText } routeIfInvitationTokenIsValid: (token, callbacks) -> $.ajax url : '/-/teams/validate-token' data : { token } type : 'POST' success : callbacks.success error : callbacks.error fetchTeamMembers: ({ name, limit, token }, callback) -> $.ajax url : "/-/team/#{name}/members?limit=#{limit ? 4}&token=#{token}" type : 'POST' success : (members) -> callback null, members error : ({ responseText }) -> callback { msg : responseText } validateEmail: (data, callbacks) -> $.ajax url : '/-/validate/email' type : 'POST' data : data xhrFields : { withCredentials : yes } success : callbacks.success error : callbacks.error getProfile: (email, callbacks) -> $.ajax url : "/-/profile/#{email}" type : 'GET' success : callbacks.success error : callbacks.error unsubscribeEmail: (token, email, callbacks) -> $.ajax url : "/-/unsubscribe/#{token}/#{email}" type : 'GET' success : callbacks.success error : callbacks.error joinTeam: (callbacks = {}) -> formData = createFormData() formData._csrf = Cookies.get '_csrf' # manually add legacy fields - SY formData.agree = 'on' formData.passwordConfirm = formData.password formData.redirect = '/' formData.slug = kd.config.group.slug $.ajax url : '/-/teams/join' data : formData type : 'POST' success : callbacks.success or -> location.href = formData.redirect error : callbacks.error or ({ responseText }) -> new kd.NotificationView { title : responseText } earlyAccess: (data, callbacks = {}) -> data.campaign = 'teams-early-access' $.ajax url : '/-/teams/early-access' data : data type : 'POST' success : callbacks.success or -> new kd.NotificationView title : "Thank you! We'll let you know when we launch it!" duration : 3000 error : callbacks.error or ({ responseText }) -> if responseText is 'Already applied!' responseText = "Thank you! We'll let you know when we launch it!" new kd.NotificationView title : responseText duration : 3000 usernameCheck : (username, callbacks = {}) -> $.ajax url : '/-/validate/username' type : 'POST' data : { username } success : callbacks.success error : callbacks.error verifySlug : (name, callbacks = {}) -> unless 2 < name.length return callbacks.error 'Domain name should be longer than 2 characters!' unless /^[a-z0-9][a-z0-9-]+$/.test name return callbacks.error 'Domain name is not valid, please try another one.' $.ajax url : '/-/teams/verify-domain' type : 'POST' data : { name } success : callbacks.success error : (xhr) -> callbacks.error.call this, xhr.responseText getGravatarUrl : (size = 80, hash) -> fallback = "https://koding-cdn.s3.amazonaws.com/square-avatars/default.avatar.#{size}.png" return "//gravatar.com/avatar/#{hash}?size=#{size}&d=#{fallback}&r=g" getGroupLogo : -> { group } = kd.config logo = new kd.CustomHTMLView { tagName : 'figure' } unless group logo.hide() return logo if group.customize?.logo logo.setCss 'background-image', "url(#{group.customize.logo})" logo.setCss 'background-size', 'cover' else # geoPattern = require 'geopattern' # pattern = geoPattern.generate(group.slug, generator: 'plusSigns').toDataUrl() # logo.setCss 'background-image', pattern # logo.setCss 'background-size', 'inherit' logo.hide() return logo getAllowedDomainsPartial: (domains) -> ('<i>@' + d + '</i>, ' for d in domains).join('').replace(/,\s$/, '') # Prevents recaptcha from showing up in signup form # (but not backend); Used for testing. disableRecaptcha: -> kd.config.recaptcha.enabled = no # Used to store last used OAuth, ie 'github', 'facebook' etc. between refreshes. storeLastUsedProvider: (provider) -> window.localStorage.lastUsedProvider = provider getLastUsedProvider: -> window.localStorage.lastUsedProvider removeLastUsedProvider: -> delete window.localStorage.lastUsedProvider createTeamTitlePhrase: (title) -> # doesn't duplicate the word `the` if the title already has it in the beginning # doesn't duplicate the word `team` if the title already has it at the end "#{if title.search(/^the/i) < 0 then 'the' else ''} #{title} #{if title.search(/team$/i) < 0 then 'team' else ''}" # If current url contains redirectTo query parameter, use it to redirect after login. # If current url isn't loginRoute, login is shown because no route has matched current url. # It may happen when logged out user opens a page which requires user authentication. # Redirect to this url after user is logged in getLoginRedirectPath: (loginRoute) -> { redirectTo } = kd.utils.parseQuery() return redirectTo.substring 1 if redirectTo { pathname } = location if pathname and pathname.indexOf(loginRoute) is -1 return pathname.substring 1 repositionSuffix: (input, fakeView) -> input.getElement().removeAttribute 'size' element = fakeView.getElement() element.innerHTML = input.getValue() { width } = element.getBoundingClientRect() width = if width then width + 3 else 100 input.setWidth width }
87028
$ = require 'jquery' kd = require 'kd' kookies = require 'kookies' createFormData = (teamData) -> teamData ?= utils.getTeamData() formData = {} for own step, fields of teamData when not ('boolean' is typeof fields) for own field, value of fields if step is 'invite' unless formData.invitees then formData.invitees = value else formData.invitees += ",#{value}" else formData[field] = value return formData module.exports = utils = { clearKiteCaches: -> if window.localStorage? for kite in (Object.keys window.localStorage) when /^KITE_/.test kite delete window.localStorage[kite] analytics: require './analytics' getReferrer: -> match = location.pathname.match /\/R\/(.*)/ return referrer if match and referrer = match[1] getMainDomain: -> { hostname, port } = location kodingDomains = ['dev', 'sandbox', 'latest', 'koding'] prefix = hostname.split('.').shift() domain = if prefix in kodingDomains then hostname else hostname.split('.').slice(1).join('.') return "#{domain}#{if port then ':'+port else ''}" getGroupNameFromLocation: (hostname) -> { hostname } = location unless hostname ipV4Pattern = '(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.xip\.io$' subDomainPattern = '[A-Za-z0-9_]{1}[A-Za-z0-9_-]+' kodingDomains = '(?:dev|sandbox|latest|prod)' baseDomain = "#{kd.config.domains.base}".replace '.', '\\.' # e.g. [teamName.]dev|sandbox|latest|prod.koding.com teamPattern = if ///#{kodingDomains}\.#{baseDomain}$///.test hostname then ///(?:^(#{subDomainPattern})\.)?#{kodingDomains}\.#{baseDomain}$/// # e.g. [teamName.]koding.com else if ///#{baseDomain}$///.test hostname then ///(?:^(#{subDomainPattern})\.)?#{baseDomain}$/// # e.g. [teamName.]<teamMember>.koding.team else if /koding\.team$/.test hostname then ///(?:^(#{subDomainPattern})\.)?(?:#{subDomainPattern}\.)koding\.team$/// # e.g. [teamName.]<vm-ip>.xip.io else ///(?:^(#{subDomainPattern})\.)?#{ipV4Pattern}/// matches = hostname.match teamPattern teamName = matches?[1] or 'koding' return teamName checkIfGroupExists: (groupName, callback) -> $.ajax url : "/-/team/#{groupName}" type : 'post' success : (group) -> callback null, group error : (err) -> callback err getEmailValidator: (options = {}) -> { container, password, tfcode } = options container : container event : 'submit' messages : required : 'Please enter your email address.' email : 'That doesn\'t seem like a valid email address.' rules : required : yes email : yes available : (input, event) -> return if event?.which is 9 { required, email, minLength } = input.validationResults return if required or minLength input.setValidationResult 'available', null email = input.getValue() passValue = password.input.getValue() if password tfcodeValue = tfcode.input.getValue() if tfcode container.emit 'EmailIsNotAvailable' return unless input.valid utils.validateEmail { email, tfcode: tfcodeValue, password : <PASSWORD>Value }, success : (res) -> return location.replace '/' if res is 'User is logged in!' container.emit 'EmailIsAvailable' input.setValidationResult 'available', null container.emit 'EmailValidationPassed' if res is yes error : ({ responseText }) -> return container.emit 'TwoFactorEnabled' if /TwoFactor/i.test responseText container.emit 'EmailIsNotAvailable' input.setValidationResult 'available', "Sorry, #{email} is already in use!" checkedPasswords: {} checkPasswordStrength: kd.utils.debounce 300, (password, callback) -> return callback { msg : 'No password specified!' } unless password return callback null, res if res = utils.checkedPasswords[password] $.ajax url : '/-/password-strength' type : 'POST' data : { password } success : (res) -> utils.checkedPasswords[res.password] = res callback null, res error : ({ responseJSON }) -> callback { msg : responseJSON } storeNewTeamData: (formName, formData) -> kd.team ?= {} { team } = kd team[formName] = formData localStorage.teamData = JSON.stringify team clearTeamData: -> localStorage.teamData = null kd.team = null getTeamData: -> return kd.team if kd.team return {} unless data = localStorage.teamData try team = JSON.parse data kd.team = team return team if team return {} getPreviousTeams: -> try teams = JSON.parse kookies.get 'koding-teams' return teams if teams and Object.keys(teams).length return null slugifyCompanyName: (team) -> if name = team.signup?.companyName then teamName = kd.utils.slugify name else teamName = '' return teamName createTeam: (callbacks = {}) -> formData = createFormData() formData._csrf = Cookies.get '_csrf' # manually add legacy fields - SY formData.agree = 'on' formData.passwordConfirm = <PASSWORD> formData.redirect = "#{location.protocol}//#{formData.slug}.#{location.host}?username=#{formData.username}" $.ajax url : '/-/teams/create' data : formData type : 'POST' success : callbacks.success or -> utils.clearTeamData() location.href = formData.redirect error : callbacks.error or ({ responseText }) -> new kd.NotificationView { title : responseText } routeIfInvitationTokenIsValid: (token, callbacks) -> $.ajax url : '/-/teams/validate-token' data : { token } type : 'POST' success : callbacks.success error : callbacks.error fetchTeamMembers: ({ name, limit, token }, callback) -> $.ajax url : "/-/team/#{name}/members?limit=#{limit ? 4}&token=#{token}" type : 'POST' success : (members) -> callback null, members error : ({ responseText }) -> callback { msg : responseText } validateEmail: (data, callbacks) -> $.ajax url : '/-/validate/email' type : 'POST' data : data xhrFields : { withCredentials : yes } success : callbacks.success error : callbacks.error getProfile: (email, callbacks) -> $.ajax url : "/-/profile/#{email}" type : 'GET' success : callbacks.success error : callbacks.error unsubscribeEmail: (token, email, callbacks) -> $.ajax url : "/-/unsubscribe/#{token}/#{email}" type : 'GET' success : callbacks.success error : callbacks.error joinTeam: (callbacks = {}) -> formData = createFormData() formData._csrf = Cookies.get '_csrf' # manually add legacy fields - SY formData.agree = 'on' formData.passwordConfirm = <PASSWORD> formData.redirect = '/' formData.slug = kd.config.group.slug $.ajax url : '/-/teams/join' data : formData type : 'POST' success : callbacks.success or -> location.href = formData.redirect error : callbacks.error or ({ responseText }) -> new kd.NotificationView { title : responseText } earlyAccess: (data, callbacks = {}) -> data.campaign = 'teams-early-access' $.ajax url : '/-/teams/early-access' data : data type : 'POST' success : callbacks.success or -> new kd.NotificationView title : "Thank you! We'll let you know when we launch it!" duration : 3000 error : callbacks.error or ({ responseText }) -> if responseText is 'Already applied!' responseText = "Thank you! We'll let you know when we launch it!" new kd.NotificationView title : responseText duration : 3000 usernameCheck : (username, callbacks = {}) -> $.ajax url : '/-/validate/username' type : 'POST' data : { username } success : callbacks.success error : callbacks.error verifySlug : (name, callbacks = {}) -> unless 2 < name.length return callbacks.error 'Domain name should be longer than 2 characters!' unless /^[a-z0-9][a-z0-9-]+$/.test name return callbacks.error 'Domain name is not valid, please try another one.' $.ajax url : '/-/teams/verify-domain' type : 'POST' data : { name } success : callbacks.success error : (xhr) -> callbacks.error.call this, xhr.responseText getGravatarUrl : (size = 80, hash) -> fallback = "https://koding-cdn.s3.amazonaws.com/square-avatars/default.avatar.#{size}.png" return "//gravatar.com/avatar/#{hash}?size=#{size}&d=#{fallback}&r=g" getGroupLogo : -> { group } = kd.config logo = new kd.CustomHTMLView { tagName : 'figure' } unless group logo.hide() return logo if group.customize?.logo logo.setCss 'background-image', "url(#{group.customize.logo})" logo.setCss 'background-size', 'cover' else # geoPattern = require 'geopattern' # pattern = geoPattern.generate(group.slug, generator: 'plusSigns').toDataUrl() # logo.setCss 'background-image', pattern # logo.setCss 'background-size', 'inherit' logo.hide() return logo getAllowedDomainsPartial: (domains) -> ('<i>@' + d + '</i>, ' for d in domains).join('').replace(/,\s$/, '') # Prevents recaptcha from showing up in signup form # (but not backend); Used for testing. disableRecaptcha: -> kd.config.recaptcha.enabled = no # Used to store last used OAuth, ie 'github', 'facebook' etc. between refreshes. storeLastUsedProvider: (provider) -> window.localStorage.lastUsedProvider = provider getLastUsedProvider: -> window.localStorage.lastUsedProvider removeLastUsedProvider: -> delete window.localStorage.lastUsedProvider createTeamTitlePhrase: (title) -> # doesn't duplicate the word `the` if the title already has it in the beginning # doesn't duplicate the word `team` if the title already has it at the end "#{if title.search(/^the/i) < 0 then 'the' else ''} #{title} #{if title.search(/team$/i) < 0 then 'team' else ''}" # If current url contains redirectTo query parameter, use it to redirect after login. # If current url isn't loginRoute, login is shown because no route has matched current url. # It may happen when logged out user opens a page which requires user authentication. # Redirect to this url after user is logged in getLoginRedirectPath: (loginRoute) -> { redirectTo } = kd.utils.parseQuery() return redirectTo.substring 1 if redirectTo { pathname } = location if pathname and pathname.indexOf(loginRoute) is -1 return pathname.substring 1 repositionSuffix: (input, fakeView) -> input.getElement().removeAttribute 'size' element = fakeView.getElement() element.innerHTML = input.getValue() { width } = element.getBoundingClientRect() width = if width then width + 3 else 100 input.setWidth width }
true
$ = require 'jquery' kd = require 'kd' kookies = require 'kookies' createFormData = (teamData) -> teamData ?= utils.getTeamData() formData = {} for own step, fields of teamData when not ('boolean' is typeof fields) for own field, value of fields if step is 'invite' unless formData.invitees then formData.invitees = value else formData.invitees += ",#{value}" else formData[field] = value return formData module.exports = utils = { clearKiteCaches: -> if window.localStorage? for kite in (Object.keys window.localStorage) when /^KITE_/.test kite delete window.localStorage[kite] analytics: require './analytics' getReferrer: -> match = location.pathname.match /\/R\/(.*)/ return referrer if match and referrer = match[1] getMainDomain: -> { hostname, port } = location kodingDomains = ['dev', 'sandbox', 'latest', 'koding'] prefix = hostname.split('.').shift() domain = if prefix in kodingDomains then hostname else hostname.split('.').slice(1).join('.') return "#{domain}#{if port then ':'+port else ''}" getGroupNameFromLocation: (hostname) -> { hostname } = location unless hostname ipV4Pattern = '(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.xip\.io$' subDomainPattern = '[A-Za-z0-9_]{1}[A-Za-z0-9_-]+' kodingDomains = '(?:dev|sandbox|latest|prod)' baseDomain = "#{kd.config.domains.base}".replace '.', '\\.' # e.g. [teamName.]dev|sandbox|latest|prod.koding.com teamPattern = if ///#{kodingDomains}\.#{baseDomain}$///.test hostname then ///(?:^(#{subDomainPattern})\.)?#{kodingDomains}\.#{baseDomain}$/// # e.g. [teamName.]koding.com else if ///#{baseDomain}$///.test hostname then ///(?:^(#{subDomainPattern})\.)?#{baseDomain}$/// # e.g. [teamName.]<teamMember>.koding.team else if /koding\.team$/.test hostname then ///(?:^(#{subDomainPattern})\.)?(?:#{subDomainPattern}\.)koding\.team$/// # e.g. [teamName.]<vm-ip>.xip.io else ///(?:^(#{subDomainPattern})\.)?#{ipV4Pattern}/// matches = hostname.match teamPattern teamName = matches?[1] or 'koding' return teamName checkIfGroupExists: (groupName, callback) -> $.ajax url : "/-/team/#{groupName}" type : 'post' success : (group) -> callback null, group error : (err) -> callback err getEmailValidator: (options = {}) -> { container, password, tfcode } = options container : container event : 'submit' messages : required : 'Please enter your email address.' email : 'That doesn\'t seem like a valid email address.' rules : required : yes email : yes available : (input, event) -> return if event?.which is 9 { required, email, minLength } = input.validationResults return if required or minLength input.setValidationResult 'available', null email = input.getValue() passValue = password.input.getValue() if password tfcodeValue = tfcode.input.getValue() if tfcode container.emit 'EmailIsNotAvailable' return unless input.valid utils.validateEmail { email, tfcode: tfcodeValue, password : PI:PASSWORD:<PASSWORD>END_PIValue }, success : (res) -> return location.replace '/' if res is 'User is logged in!' container.emit 'EmailIsAvailable' input.setValidationResult 'available', null container.emit 'EmailValidationPassed' if res is yes error : ({ responseText }) -> return container.emit 'TwoFactorEnabled' if /TwoFactor/i.test responseText container.emit 'EmailIsNotAvailable' input.setValidationResult 'available', "Sorry, #{email} is already in use!" checkedPasswords: {} checkPasswordStrength: kd.utils.debounce 300, (password, callback) -> return callback { msg : 'No password specified!' } unless password return callback null, res if res = utils.checkedPasswords[password] $.ajax url : '/-/password-strength' type : 'POST' data : { password } success : (res) -> utils.checkedPasswords[res.password] = res callback null, res error : ({ responseJSON }) -> callback { msg : responseJSON } storeNewTeamData: (formName, formData) -> kd.team ?= {} { team } = kd team[formName] = formData localStorage.teamData = JSON.stringify team clearTeamData: -> localStorage.teamData = null kd.team = null getTeamData: -> return kd.team if kd.team return {} unless data = localStorage.teamData try team = JSON.parse data kd.team = team return team if team return {} getPreviousTeams: -> try teams = JSON.parse kookies.get 'koding-teams' return teams if teams and Object.keys(teams).length return null slugifyCompanyName: (team) -> if name = team.signup?.companyName then teamName = kd.utils.slugify name else teamName = '' return teamName createTeam: (callbacks = {}) -> formData = createFormData() formData._csrf = Cookies.get '_csrf' # manually add legacy fields - SY formData.agree = 'on' formData.passwordConfirm = PI:PASSWORD:<PASSWORD>END_PI formData.redirect = "#{location.protocol}//#{formData.slug}.#{location.host}?username=#{formData.username}" $.ajax url : '/-/teams/create' data : formData type : 'POST' success : callbacks.success or -> utils.clearTeamData() location.href = formData.redirect error : callbacks.error or ({ responseText }) -> new kd.NotificationView { title : responseText } routeIfInvitationTokenIsValid: (token, callbacks) -> $.ajax url : '/-/teams/validate-token' data : { token } type : 'POST' success : callbacks.success error : callbacks.error fetchTeamMembers: ({ name, limit, token }, callback) -> $.ajax url : "/-/team/#{name}/members?limit=#{limit ? 4}&token=#{token}" type : 'POST' success : (members) -> callback null, members error : ({ responseText }) -> callback { msg : responseText } validateEmail: (data, callbacks) -> $.ajax url : '/-/validate/email' type : 'POST' data : data xhrFields : { withCredentials : yes } success : callbacks.success error : callbacks.error getProfile: (email, callbacks) -> $.ajax url : "/-/profile/#{email}" type : 'GET' success : callbacks.success error : callbacks.error unsubscribeEmail: (token, email, callbacks) -> $.ajax url : "/-/unsubscribe/#{token}/#{email}" type : 'GET' success : callbacks.success error : callbacks.error joinTeam: (callbacks = {}) -> formData = createFormData() formData._csrf = Cookies.get '_csrf' # manually add legacy fields - SY formData.agree = 'on' formData.passwordConfirm = PI:PASSWORD:<PASSWORD>END_PI formData.redirect = '/' formData.slug = kd.config.group.slug $.ajax url : '/-/teams/join' data : formData type : 'POST' success : callbacks.success or -> location.href = formData.redirect error : callbacks.error or ({ responseText }) -> new kd.NotificationView { title : responseText } earlyAccess: (data, callbacks = {}) -> data.campaign = 'teams-early-access' $.ajax url : '/-/teams/early-access' data : data type : 'POST' success : callbacks.success or -> new kd.NotificationView title : "Thank you! We'll let you know when we launch it!" duration : 3000 error : callbacks.error or ({ responseText }) -> if responseText is 'Already applied!' responseText = "Thank you! We'll let you know when we launch it!" new kd.NotificationView title : responseText duration : 3000 usernameCheck : (username, callbacks = {}) -> $.ajax url : '/-/validate/username' type : 'POST' data : { username } success : callbacks.success error : callbacks.error verifySlug : (name, callbacks = {}) -> unless 2 < name.length return callbacks.error 'Domain name should be longer than 2 characters!' unless /^[a-z0-9][a-z0-9-]+$/.test name return callbacks.error 'Domain name is not valid, please try another one.' $.ajax url : '/-/teams/verify-domain' type : 'POST' data : { name } success : callbacks.success error : (xhr) -> callbacks.error.call this, xhr.responseText getGravatarUrl : (size = 80, hash) -> fallback = "https://koding-cdn.s3.amazonaws.com/square-avatars/default.avatar.#{size}.png" return "//gravatar.com/avatar/#{hash}?size=#{size}&d=#{fallback}&r=g" getGroupLogo : -> { group } = kd.config logo = new kd.CustomHTMLView { tagName : 'figure' } unless group logo.hide() return logo if group.customize?.logo logo.setCss 'background-image', "url(#{group.customize.logo})" logo.setCss 'background-size', 'cover' else # geoPattern = require 'geopattern' # pattern = geoPattern.generate(group.slug, generator: 'plusSigns').toDataUrl() # logo.setCss 'background-image', pattern # logo.setCss 'background-size', 'inherit' logo.hide() return logo getAllowedDomainsPartial: (domains) -> ('<i>@' + d + '</i>, ' for d in domains).join('').replace(/,\s$/, '') # Prevents recaptcha from showing up in signup form # (but not backend); Used for testing. disableRecaptcha: -> kd.config.recaptcha.enabled = no # Used to store last used OAuth, ie 'github', 'facebook' etc. between refreshes. storeLastUsedProvider: (provider) -> window.localStorage.lastUsedProvider = provider getLastUsedProvider: -> window.localStorage.lastUsedProvider removeLastUsedProvider: -> delete window.localStorage.lastUsedProvider createTeamTitlePhrase: (title) -> # doesn't duplicate the word `the` if the title already has it in the beginning # doesn't duplicate the word `team` if the title already has it at the end "#{if title.search(/^the/i) < 0 then 'the' else ''} #{title} #{if title.search(/team$/i) < 0 then 'team' else ''}" # If current url contains redirectTo query parameter, use it to redirect after login. # If current url isn't loginRoute, login is shown because no route has matched current url. # It may happen when logged out user opens a page which requires user authentication. # Redirect to this url after user is logged in getLoginRedirectPath: (loginRoute) -> { redirectTo } = kd.utils.parseQuery() return redirectTo.substring 1 if redirectTo { pathname } = location if pathname and pathname.indexOf(loginRoute) is -1 return pathname.substring 1 repositionSuffix: (input, fakeView) -> input.getElement().removeAttribute 'size' element = fakeView.getElement() element.innerHTML = input.getValue() { width } = element.getBoundingClientRect() width = if width then width + 3 else 100 input.setWidth width }
[ { "context": "p = shell()\n app.hook 'hook_sth',\n pass: 'sth'\n , (context, handler) ->\n context.pass =", "end": 634, "score": 0.8537655472755432, "start": 631, "tag": "PASSWORD", "value": "sth" }, { "context": " , (context, handler) ->\n context.pass = 'sth...
packages/shell/test/api.hook.coffee
adaltas/node-shell
15
shell = require '../src' describe 'api.hook', -> it 'validation', -> (-> shell().hook 'hook_sth' ).should.throw 'Invalid Hook Argument: function hook expect 3 or 4 arguments name, args, hooks? and handler, got 1 arguments' it 'return value from handler', -> app = shell() app.hook 'hook_sth', {}, -> 'value is here' .should.equal 'value is here' it 'pass user context', -> app = shell() app.hook 'hook_sth', pass: 'sth' , ({pass}) -> pass.should.eql 'sth' it 'provide user register', -> app = shell() app.hook 'hook_sth', pass: 'sth' , (context, handler) -> context.pass = 'sth else' handler , ({pass}) -> pass.should.eql 'sth else'
80351
shell = require '../src' describe 'api.hook', -> it 'validation', -> (-> shell().hook 'hook_sth' ).should.throw 'Invalid Hook Argument: function hook expect 3 or 4 arguments name, args, hooks? and handler, got 1 arguments' it 'return value from handler', -> app = shell() app.hook 'hook_sth', {}, -> 'value is here' .should.equal 'value is here' it 'pass user context', -> app = shell() app.hook 'hook_sth', pass: 'sth' , ({pass}) -> pass.should.eql 'sth' it 'provide user register', -> app = shell() app.hook 'hook_sth', pass: '<PASSWORD>' , (context, handler) -> context.pass = '<PASSWORD>' handler , ({pass}) -> pass.should.eql 'sth else'
true
shell = require '../src' describe 'api.hook', -> it 'validation', -> (-> shell().hook 'hook_sth' ).should.throw 'Invalid Hook Argument: function hook expect 3 or 4 arguments name, args, hooks? and handler, got 1 arguments' it 'return value from handler', -> app = shell() app.hook 'hook_sth', {}, -> 'value is here' .should.equal 'value is here' it 'pass user context', -> app = shell() app.hook 'hook_sth', pass: 'sth' , ({pass}) -> pass.should.eql 'sth' it 'provide user register', -> app = shell() app.hook 'hook_sth', pass: 'PI:PASSWORD:<PASSWORD>END_PI' , (context, handler) -> context.pass = 'PI:PASSWORD:<PASSWORD>END_PI' handler , ({pass}) -> pass.should.eql 'sth else'
[ { "context": "me[channel] =\n player1:\n nick: from.nick\n pick: 0\n player2:\n ", "end": 1703, "score": 0.9923962950706482, "start": 1694, "tag": "USERNAME", "value": "from.nick" }, { "context": " other users!'\n version: '0.5'\n au...
plugins/rps_game.coffee
Arrogance/nerdobot
1
module.exports = -> command = @config.prefix + "rps" game = [] delay = (ms, func) => setTimeout func, ms help = (from) => @say from.nick, banner "#{@BOLD}How to play?#{@RESET}" @say from.nick, "First, you need to start a game with the command #{@BOLD}#{command} " + "start#{@RESET} and await for a challenger. If you want to join a " + "started game, simply do a #{@BOLD}#{command} join#{@RESET}." @say from.nick, "Now, you will recieve instructions to beat your challenger and win " + "the game. Also, you can check the status of the game in any moment, " + "using #{@BOLD}#{command} status#{@RESET}." @say from.nick, "The system will search for players for 4 minutes. If no players found " + "the game will be cancelled automatically. A player can also cancel a " + "game with the command #{@BOLD}#{command} cancel#{@RESET}." banner = (message) => "#{@BOLD}#{@color 'grey'}Rock#{@color 'red'} Paper#{@RESET} " + "#{@BOLD}&#{@color 'blue'} Scissors! -#{@RESET} #{message}" @addCommand 'rps', description: 'Play Rock, Paper and Scissors with friends' help: 'Use the command rps help to learn how to play' (from, message, channel) => start = => if game[channel]? @say channel, banner "The game is already started on this channel, Please, use " + "#{@BOLD}#{command} join#{@RESET} to play!" return if game[from.nick]? @say channel, banner "You are already participating in a game!" return game[channel] = [] game[channel] = player1: nick: from.nick pick: 0 player2: nick: 0 pick: 0 phase: 1 channel: channel running = game[channel] game[running.player1.nick] = running @say running.channel, banner "The player #{@BOLD}#{running.player1.nick}#{@RESET} has " + "started a game on #{running.channel}. Please, use " + "#{@BOLD}#{command} join#{@RESET} to play!" announce = "The player #{@BOLD}#{running.player1.nick}#{@RESET} is " + "searching a challenger, use #{@BOLD}#{command} join#{@RESET} " + "to play with him" game[running.channel].timer = delay 60000, => @say running.channel, banner announce game[running.channel].timer = delay 60000, => @say running.channel, banner announce game[running.channel].timer = delay 60000, => @say running.channel, banner announce game[running.channel].timer = delay 60000, => @say running.channel, banner "Canceled the game on #{running.channel} due " + "lacking of players :(" clearTimeout(game[running.channel].timer) delete game[running.channel] delete game[running.player1.nick] delete game[running.player2.nick] status = => if not game[channel]? @say channel, banner "There are not any games active on this channel, you can " + "start a game with #{@BOLD}#{command} start#{@RESET}." return running = game[channel] if running.phase == 1 @say channel, banner "The player #{@BOLD}#{running.player1.nick}#{@RESET} is " + "searching a challenger, use #{@BOLD}#{command} join#{@RESET} to " + "play with him" else if running.phase == 2 @say channel, banner "There are already a game in process, " + "#{@BOLD}#{running.player1.nick} vs " + "#{running.player2.nick}#{@RESET}." join = => if not game[channel]? @say channel, banner "There are not any games active on this channel, you can " + "start a game with #{@BOLD}#{command} start#{@RESET}." return if game[from.nick]? @say channel, banner "You are already participating in a game!" return running = game[channel] if from.nick == running.player1.nick @say channel, banner "You can't not play with yourself... wait until I find a " + "player!" return if running.phase == 2 @say channel, banner "There are already a game in process on this channel, " + "#{@BOLD}#{running.player1.nick} vs " + "#{running.player2.nick}#{@RESET}." return game[channel].phase = 2 game[channel].player2.nick = from.nick if game[channel].timer? clearTimeout(game[channel].timer) running = game[channel] @say channel, banner "The player #{@BOLD}#{running.player2.nick}#{@RESET} " + "accepted the challenge from " + "#{@BOLD}#{running.player1.nick}#{@RESET}!" @say channel, "The instructions will be delivered on private messages, stay alert!" @say running.player1.nick, banner "Game instructions" @say running.player1.nick, "You will play against #{@BOLD}#{running.player2.nick}#{@RESET} " + "this round. You need to choose between #{@BOLD}#{command} " + "rock#{@RESET}, #{@BOLD}#{command} paper#{@RESET} or " + "#{@BOLD}#{command} scissors#{@RESET} on this private chat. Once " + "both players decide, the winner will be announced on the channel." @say running.player2.nick, banner "Game instructions" @say running.player2.nick, "You will play against #{@BOLD}#{running.player1.nick}#{@RESET} " + "this round. You need to choose between #{@BOLD}#{command} " + "rock#{@RESET}, #{@BOLD}#{command} paper#{@RESET} or " + "#{@BOLD}#{command} scissors#{@RESET} on this private chat. Once " + "both players decide, the winner will be announced on the channel." game[running.player2.nick] = running pick = (message) => if channel? @notice from.nick, "This command can be only used in private" return if game[from.nick] running = game[from.nick] switch from.nick when running.player1.nick if running.player1.pick @say from.nick, "You already picked #{@BOLD}#{running.player1.pick}#{@RESET}" return switch message when "rock" game[running.channel].player1.pick = "rock" @say from.nick, "You picked #{@BOLD}#{message}#{@RESET}" when "paper" game[running.channel].player1.pick = "paper" @say from.nick, "You picked #{@BOLD}#{message}#{@RESET}" when "scissors" game[running.channel].player1.pick = "scissors" @say from.nick, "You picked #{@BOLD}#{message}#{@RESET}" else @say from.nick, "You need to choose between rock, paper or scissors" if game[running.channel].player2.pick game[game[running.channel].player1.nick] = game[running.channel] game[game[running.channel].player2.nick] = game[running.channel] decide() when running.player2.nick if running.player2.pick @say from.nick, "You already picked #{@BOLD}#{running.player2.pick}#{@RESET}" return switch message when "rock" game[running.channel].player2.pick = "rock" @say from.nick, "You picked #{@BOLD}#{message}#{@RESET}" when "paper" game[running.channel].player2.pick = "paper" @say from.nick, "You picked #{@BOLD}#{message}#{@RESET}" when "scissors" game[running.channel].player2.pick = "scissors" @say from.nick, "You picked #{@BOLD}#{message}#{@RESET}" else @say from.nick, "You need to choose between rock, paper or scissors" if game[running.channel].player1.pick game[game[running.channel].player1.nick] = game[running.channel] game[game[running.channel].player2.nick] = game[running.channel] decide() else @notice from.nick, "You are not participating in any game!" return decide = => if game[from.nick] running = game[from.nick] if running.player1.pick == "rock" if running.player2.pick == "rock" win = 3 if running.player2.pick == "paper" win = 2 if running.player2.pick == 'scissors' win = 1 if running.player1.pick == "paper" if running.player2.pick == "rock" win = 1 if running.player2.pick == "paper" win = 3 if running.player2.pick == 'scissors' win = 2 if running.player1.pick == "scissors" if running.player2.pick == "rock" win = 2 if running.player2.pick == "paper" win = 1 if running.player2.pick == 'scissors' win = 3 @say running.channel, banner "#{@BOLD}#{running.player1.nick}#{@RESET} picked " + "#{@BOLD}#{running.player1.pick}#{@RESET} versus " + "#{@BOLD}#{running.player2.nick}#{@RESET} that picked " + "#{@BOLD}#{running.player2.pick}#{@RESET}" if win == 1 @say running.channel, banner "And the winner is... #{@BOLD}#{running.player1.nick}!" else if win == 2 @say running.channel, banner "And the winner is... #{@BOLD}#{running.player2.nick}!" else if win == 3 @say running.channel, banner "And the winner is... a DRAW!" if win delete game[running.channel] delete game[running.player1.nick] delete game[running.player2.nick] cancel = => if game[from.nick] running = game[from.nick] @say running.channel, banner "Canceled the game on #{running.channel} :(" if game[channel].timer? clearTimeout(game[channel].timer) delete game[running.channel] delete game[running.player1.nick] delete game[running.player2.nick] switch message when "help" help(from) when "start" start() when "join" join() when "rock" pick "rock" when "paper" pick "paper" when "scissors" pick "scissors" when "cancel" cancel() when "status" status() else @say channel, banner "Now you can play the classic game of Rock, Paper & " + "Scissors. Use the command #{@BOLD}#{command} help#{@RESET} to " + "learn how to play!" name: 'Rock, Paper, Scissors Game' description: 'Play againts other users!' version: '0.5' authors: [ 'Tunnecino @ ignitae.com' ]
61837
module.exports = -> command = @config.prefix + "rps" game = [] delay = (ms, func) => setTimeout func, ms help = (from) => @say from.nick, banner "#{@BOLD}How to play?#{@RESET}" @say from.nick, "First, you need to start a game with the command #{@BOLD}#{command} " + "start#{@RESET} and await for a challenger. If you want to join a " + "started game, simply do a #{@BOLD}#{command} join#{@RESET}." @say from.nick, "Now, you will recieve instructions to beat your challenger and win " + "the game. Also, you can check the status of the game in any moment, " + "using #{@BOLD}#{command} status#{@RESET}." @say from.nick, "The system will search for players for 4 minutes. If no players found " + "the game will be cancelled automatically. A player can also cancel a " + "game with the command #{@BOLD}#{command} cancel#{@RESET}." banner = (message) => "#{@BOLD}#{@color 'grey'}Rock#{@color 'red'} Paper#{@RESET} " + "#{@BOLD}&#{@color 'blue'} Scissors! -#{@RESET} #{message}" @addCommand 'rps', description: 'Play Rock, Paper and Scissors with friends' help: 'Use the command rps help to learn how to play' (from, message, channel) => start = => if game[channel]? @say channel, banner "The game is already started on this channel, Please, use " + "#{@BOLD}#{command} join#{@RESET} to play!" return if game[from.nick]? @say channel, banner "You are already participating in a game!" return game[channel] = [] game[channel] = player1: nick: from.nick pick: 0 player2: nick: 0 pick: 0 phase: 1 channel: channel running = game[channel] game[running.player1.nick] = running @say running.channel, banner "The player #{@BOLD}#{running.player1.nick}#{@RESET} has " + "started a game on #{running.channel}. Please, use " + "#{@BOLD}#{command} join#{@RESET} to play!" announce = "The player #{@BOLD}#{running.player1.nick}#{@RESET} is " + "searching a challenger, use #{@BOLD}#{command} join#{@RESET} " + "to play with him" game[running.channel].timer = delay 60000, => @say running.channel, banner announce game[running.channel].timer = delay 60000, => @say running.channel, banner announce game[running.channel].timer = delay 60000, => @say running.channel, banner announce game[running.channel].timer = delay 60000, => @say running.channel, banner "Canceled the game on #{running.channel} due " + "lacking of players :(" clearTimeout(game[running.channel].timer) delete game[running.channel] delete game[running.player1.nick] delete game[running.player2.nick] status = => if not game[channel]? @say channel, banner "There are not any games active on this channel, you can " + "start a game with #{@BOLD}#{command} start#{@RESET}." return running = game[channel] if running.phase == 1 @say channel, banner "The player #{@BOLD}#{running.player1.nick}#{@RESET} is " + "searching a challenger, use #{@BOLD}#{command} join#{@RESET} to " + "play with him" else if running.phase == 2 @say channel, banner "There are already a game in process, " + "#{@BOLD}#{running.player1.nick} vs " + "#{running.player2.nick}#{@RESET}." join = => if not game[channel]? @say channel, banner "There are not any games active on this channel, you can " + "start a game with #{@BOLD}#{command} start#{@RESET}." return if game[from.nick]? @say channel, banner "You are already participating in a game!" return running = game[channel] if from.nick == running.player1.nick @say channel, banner "You can't not play with yourself... wait until I find a " + "player!" return if running.phase == 2 @say channel, banner "There are already a game in process on this channel, " + "#{@BOLD}#{running.player1.nick} vs " + "#{running.player2.nick}#{@RESET}." return game[channel].phase = 2 game[channel].player2.nick = from.nick if game[channel].timer? clearTimeout(game[channel].timer) running = game[channel] @say channel, banner "The player #{@BOLD}#{running.player2.nick}#{@RESET} " + "accepted the challenge from " + "#{@BOLD}#{running.player1.nick}#{@RESET}!" @say channel, "The instructions will be delivered on private messages, stay alert!" @say running.player1.nick, banner "Game instructions" @say running.player1.nick, "You will play against #{@BOLD}#{running.player2.nick}#{@RESET} " + "this round. You need to choose between #{@BOLD}#{command} " + "rock#{@RESET}, #{@BOLD}#{command} paper#{@RESET} or " + "#{@BOLD}#{command} scissors#{@RESET} on this private chat. Once " + "both players decide, the winner will be announced on the channel." @say running.player2.nick, banner "Game instructions" @say running.player2.nick, "You will play against #{@BOLD}#{running.player1.nick}#{@RESET} " + "this round. You need to choose between #{@BOLD}#{command} " + "rock#{@RESET}, #{@BOLD}#{command} paper#{@RESET} or " + "#{@BOLD}#{command} scissors#{@RESET} on this private chat. Once " + "both players decide, the winner will be announced on the channel." game[running.player2.nick] = running pick = (message) => if channel? @notice from.nick, "This command can be only used in private" return if game[from.nick] running = game[from.nick] switch from.nick when running.player1.nick if running.player1.pick @say from.nick, "You already picked #{@BOLD}#{running.player1.pick}#{@RESET}" return switch message when "rock" game[running.channel].player1.pick = "rock" @say from.nick, "You picked #{@BOLD}#{message}#{@RESET}" when "paper" game[running.channel].player1.pick = "paper" @say from.nick, "You picked #{@BOLD}#{message}#{@RESET}" when "scissors" game[running.channel].player1.pick = "scissors" @say from.nick, "You picked #{@BOLD}#{message}#{@RESET}" else @say from.nick, "You need to choose between rock, paper or scissors" if game[running.channel].player2.pick game[game[running.channel].player1.nick] = game[running.channel] game[game[running.channel].player2.nick] = game[running.channel] decide() when running.player2.nick if running.player2.pick @say from.nick, "You already picked #{@BOLD}#{running.player2.pick}#{@RESET}" return switch message when "rock" game[running.channel].player2.pick = "rock" @say from.nick, "You picked #{@BOLD}#{message}#{@RESET}" when "paper" game[running.channel].player2.pick = "paper" @say from.nick, "You picked #{@BOLD}#{message}#{@RESET}" when "scissors" game[running.channel].player2.pick = "scissors" @say from.nick, "You picked #{@BOLD}#{message}#{@RESET}" else @say from.nick, "You need to choose between rock, paper or scissors" if game[running.channel].player1.pick game[game[running.channel].player1.nick] = game[running.channel] game[game[running.channel].player2.nick] = game[running.channel] decide() else @notice from.nick, "You are not participating in any game!" return decide = => if game[from.nick] running = game[from.nick] if running.player1.pick == "rock" if running.player2.pick == "rock" win = 3 if running.player2.pick == "paper" win = 2 if running.player2.pick == 'scissors' win = 1 if running.player1.pick == "paper" if running.player2.pick == "rock" win = 1 if running.player2.pick == "paper" win = 3 if running.player2.pick == 'scissors' win = 2 if running.player1.pick == "scissors" if running.player2.pick == "rock" win = 2 if running.player2.pick == "paper" win = 1 if running.player2.pick == 'scissors' win = 3 @say running.channel, banner "#{@BOLD}#{running.player1.nick}#{@RESET} picked " + "#{@BOLD}#{running.player1.pick}#{@RESET} versus " + "#{@BOLD}#{running.player2.nick}#{@RESET} that picked " + "#{@BOLD}#{running.player2.pick}#{@RESET}" if win == 1 @say running.channel, banner "And the winner is... #{@BOLD}#{running.player1.nick}!" else if win == 2 @say running.channel, banner "And the winner is... #{@BOLD}#{running.player2.nick}!" else if win == 3 @say running.channel, banner "And the winner is... a DRAW!" if win delete game[running.channel] delete game[running.player1.nick] delete game[running.player2.nick] cancel = => if game[from.nick] running = game[from.nick] @say running.channel, banner "Canceled the game on #{running.channel} :(" if game[channel].timer? clearTimeout(game[channel].timer) delete game[running.channel] delete game[running.player1.nick] delete game[running.player2.nick] switch message when "help" help(from) when "start" start() when "join" join() when "rock" pick "rock" when "paper" pick "paper" when "scissors" pick "scissors" when "cancel" cancel() when "status" status() else @say channel, banner "Now you can play the classic game of Rock, Paper & " + "Scissors. Use the command #{@BOLD}#{command} help#{@RESET} to " + "learn how to play!" name: 'Rock, Paper, Scissors Game' description: 'Play againts other users!' version: '0.5' authors: [ '<NAME> @ ign<EMAIL>' ]
true
module.exports = -> command = @config.prefix + "rps" game = [] delay = (ms, func) => setTimeout func, ms help = (from) => @say from.nick, banner "#{@BOLD}How to play?#{@RESET}" @say from.nick, "First, you need to start a game with the command #{@BOLD}#{command} " + "start#{@RESET} and await for a challenger. If you want to join a " + "started game, simply do a #{@BOLD}#{command} join#{@RESET}." @say from.nick, "Now, you will recieve instructions to beat your challenger and win " + "the game. Also, you can check the status of the game in any moment, " + "using #{@BOLD}#{command} status#{@RESET}." @say from.nick, "The system will search for players for 4 minutes. If no players found " + "the game will be cancelled automatically. A player can also cancel a " + "game with the command #{@BOLD}#{command} cancel#{@RESET}." banner = (message) => "#{@BOLD}#{@color 'grey'}Rock#{@color 'red'} Paper#{@RESET} " + "#{@BOLD}&#{@color 'blue'} Scissors! -#{@RESET} #{message}" @addCommand 'rps', description: 'Play Rock, Paper and Scissors with friends' help: 'Use the command rps help to learn how to play' (from, message, channel) => start = => if game[channel]? @say channel, banner "The game is already started on this channel, Please, use " + "#{@BOLD}#{command} join#{@RESET} to play!" return if game[from.nick]? @say channel, banner "You are already participating in a game!" return game[channel] = [] game[channel] = player1: nick: from.nick pick: 0 player2: nick: 0 pick: 0 phase: 1 channel: channel running = game[channel] game[running.player1.nick] = running @say running.channel, banner "The player #{@BOLD}#{running.player1.nick}#{@RESET} has " + "started a game on #{running.channel}. Please, use " + "#{@BOLD}#{command} join#{@RESET} to play!" announce = "The player #{@BOLD}#{running.player1.nick}#{@RESET} is " + "searching a challenger, use #{@BOLD}#{command} join#{@RESET} " + "to play with him" game[running.channel].timer = delay 60000, => @say running.channel, banner announce game[running.channel].timer = delay 60000, => @say running.channel, banner announce game[running.channel].timer = delay 60000, => @say running.channel, banner announce game[running.channel].timer = delay 60000, => @say running.channel, banner "Canceled the game on #{running.channel} due " + "lacking of players :(" clearTimeout(game[running.channel].timer) delete game[running.channel] delete game[running.player1.nick] delete game[running.player2.nick] status = => if not game[channel]? @say channel, banner "There are not any games active on this channel, you can " + "start a game with #{@BOLD}#{command} start#{@RESET}." return running = game[channel] if running.phase == 1 @say channel, banner "The player #{@BOLD}#{running.player1.nick}#{@RESET} is " + "searching a challenger, use #{@BOLD}#{command} join#{@RESET} to " + "play with him" else if running.phase == 2 @say channel, banner "There are already a game in process, " + "#{@BOLD}#{running.player1.nick} vs " + "#{running.player2.nick}#{@RESET}." join = => if not game[channel]? @say channel, banner "There are not any games active on this channel, you can " + "start a game with #{@BOLD}#{command} start#{@RESET}." return if game[from.nick]? @say channel, banner "You are already participating in a game!" return running = game[channel] if from.nick == running.player1.nick @say channel, banner "You can't not play with yourself... wait until I find a " + "player!" return if running.phase == 2 @say channel, banner "There are already a game in process on this channel, " + "#{@BOLD}#{running.player1.nick} vs " + "#{running.player2.nick}#{@RESET}." return game[channel].phase = 2 game[channel].player2.nick = from.nick if game[channel].timer? clearTimeout(game[channel].timer) running = game[channel] @say channel, banner "The player #{@BOLD}#{running.player2.nick}#{@RESET} " + "accepted the challenge from " + "#{@BOLD}#{running.player1.nick}#{@RESET}!" @say channel, "The instructions will be delivered on private messages, stay alert!" @say running.player1.nick, banner "Game instructions" @say running.player1.nick, "You will play against #{@BOLD}#{running.player2.nick}#{@RESET} " + "this round. You need to choose between #{@BOLD}#{command} " + "rock#{@RESET}, #{@BOLD}#{command} paper#{@RESET} or " + "#{@BOLD}#{command} scissors#{@RESET} on this private chat. Once " + "both players decide, the winner will be announced on the channel." @say running.player2.nick, banner "Game instructions" @say running.player2.nick, "You will play against #{@BOLD}#{running.player1.nick}#{@RESET} " + "this round. You need to choose between #{@BOLD}#{command} " + "rock#{@RESET}, #{@BOLD}#{command} paper#{@RESET} or " + "#{@BOLD}#{command} scissors#{@RESET} on this private chat. Once " + "both players decide, the winner will be announced on the channel." game[running.player2.nick] = running pick = (message) => if channel? @notice from.nick, "This command can be only used in private" return if game[from.nick] running = game[from.nick] switch from.nick when running.player1.nick if running.player1.pick @say from.nick, "You already picked #{@BOLD}#{running.player1.pick}#{@RESET}" return switch message when "rock" game[running.channel].player1.pick = "rock" @say from.nick, "You picked #{@BOLD}#{message}#{@RESET}" when "paper" game[running.channel].player1.pick = "paper" @say from.nick, "You picked #{@BOLD}#{message}#{@RESET}" when "scissors" game[running.channel].player1.pick = "scissors" @say from.nick, "You picked #{@BOLD}#{message}#{@RESET}" else @say from.nick, "You need to choose between rock, paper or scissors" if game[running.channel].player2.pick game[game[running.channel].player1.nick] = game[running.channel] game[game[running.channel].player2.nick] = game[running.channel] decide() when running.player2.nick if running.player2.pick @say from.nick, "You already picked #{@BOLD}#{running.player2.pick}#{@RESET}" return switch message when "rock" game[running.channel].player2.pick = "rock" @say from.nick, "You picked #{@BOLD}#{message}#{@RESET}" when "paper" game[running.channel].player2.pick = "paper" @say from.nick, "You picked #{@BOLD}#{message}#{@RESET}" when "scissors" game[running.channel].player2.pick = "scissors" @say from.nick, "You picked #{@BOLD}#{message}#{@RESET}" else @say from.nick, "You need to choose between rock, paper or scissors" if game[running.channel].player1.pick game[game[running.channel].player1.nick] = game[running.channel] game[game[running.channel].player2.nick] = game[running.channel] decide() else @notice from.nick, "You are not participating in any game!" return decide = => if game[from.nick] running = game[from.nick] if running.player1.pick == "rock" if running.player2.pick == "rock" win = 3 if running.player2.pick == "paper" win = 2 if running.player2.pick == 'scissors' win = 1 if running.player1.pick == "paper" if running.player2.pick == "rock" win = 1 if running.player2.pick == "paper" win = 3 if running.player2.pick == 'scissors' win = 2 if running.player1.pick == "scissors" if running.player2.pick == "rock" win = 2 if running.player2.pick == "paper" win = 1 if running.player2.pick == 'scissors' win = 3 @say running.channel, banner "#{@BOLD}#{running.player1.nick}#{@RESET} picked " + "#{@BOLD}#{running.player1.pick}#{@RESET} versus " + "#{@BOLD}#{running.player2.nick}#{@RESET} that picked " + "#{@BOLD}#{running.player2.pick}#{@RESET}" if win == 1 @say running.channel, banner "And the winner is... #{@BOLD}#{running.player1.nick}!" else if win == 2 @say running.channel, banner "And the winner is... #{@BOLD}#{running.player2.nick}!" else if win == 3 @say running.channel, banner "And the winner is... a DRAW!" if win delete game[running.channel] delete game[running.player1.nick] delete game[running.player2.nick] cancel = => if game[from.nick] running = game[from.nick] @say running.channel, banner "Canceled the game on #{running.channel} :(" if game[channel].timer? clearTimeout(game[channel].timer) delete game[running.channel] delete game[running.player1.nick] delete game[running.player2.nick] switch message when "help" help(from) when "start" start() when "join" join() when "rock" pick "rock" when "paper" pick "paper" when "scissors" pick "scissors" when "cancel" cancel() when "status" status() else @say channel, banner "Now you can play the classic game of Rock, Paper & " + "Scissors. Use the command #{@BOLD}#{command} help#{@RESET} to " + "learn how to play!" name: 'Rock, Paper, Scissors Game' description: 'Play againts other users!' version: '0.5' authors: [ 'PI:NAME:<NAME>END_PI @ ignPI:EMAIL:<EMAIL>END_PI' ]
[ { "context": " account: @syno.account\n passwd: @syno.passwd\n session: sessionName\n form", "end": 440, "score": 0.9989168047904968, "start": 428, "tag": "PASSWORD", "value": "@syno.passwd" } ]
src/syno/Auth.coffee
weshouman/syno
252
# Auth API class Auth extends API # API name api = 'SYNO.API.Auth' # API version version = 3 # API path path = 'auth.cgi' # Login to Syno # `done` [Function] Callback called when the login processed is complete login: (sessionName, done)-> # API method is `login` method = 'login' # Parameters params = account: @syno.account passwd: @syno.passwd session: sessionName format: 'sid' # Set sid to null if not @syno.sessions @syno.sessions = {} if not @syno.sessions[sessionName] @syno.sessions[sessionName] = {} @syno.sessions[sessionName]['_sid'] = null # Request login @request {api, version, path, method, params}, done # Logout to syno # `done` [Function] Callback called when the logout process is complete logout: (sessionName = null, done)-> # Don't do anything if there is no session if not @syno.sessions then return null # API method is `logout` method = 'logout' # Init logout parameters params = session: @syno.session # Delete sessions if sessionName @syno.sessions[sessionName] = null else @syno.sessions = null # Request logout @request {api, version, path, method, params}, done # Handle auth specific errors error: (code)-> switch code when 400 then return 'No such account or incorrect password' when 401 then return 'Account disabled' when 402 then return 'Permission denied' when 403 then return '2-step verification code required' when 404 then return 'Failed to authenticate 2-step verification code' # No specific error, so call super function return super
64143
# Auth API class Auth extends API # API name api = 'SYNO.API.Auth' # API version version = 3 # API path path = 'auth.cgi' # Login to Syno # `done` [Function] Callback called when the login processed is complete login: (sessionName, done)-> # API method is `login` method = 'login' # Parameters params = account: @syno.account passwd: <PASSWORD> session: sessionName format: 'sid' # Set sid to null if not @syno.sessions @syno.sessions = {} if not @syno.sessions[sessionName] @syno.sessions[sessionName] = {} @syno.sessions[sessionName]['_sid'] = null # Request login @request {api, version, path, method, params}, done # Logout to syno # `done` [Function] Callback called when the logout process is complete logout: (sessionName = null, done)-> # Don't do anything if there is no session if not @syno.sessions then return null # API method is `logout` method = 'logout' # Init logout parameters params = session: @syno.session # Delete sessions if sessionName @syno.sessions[sessionName] = null else @syno.sessions = null # Request logout @request {api, version, path, method, params}, done # Handle auth specific errors error: (code)-> switch code when 400 then return 'No such account or incorrect password' when 401 then return 'Account disabled' when 402 then return 'Permission denied' when 403 then return '2-step verification code required' when 404 then return 'Failed to authenticate 2-step verification code' # No specific error, so call super function return super
true
# Auth API class Auth extends API # API name api = 'SYNO.API.Auth' # API version version = 3 # API path path = 'auth.cgi' # Login to Syno # `done` [Function] Callback called when the login processed is complete login: (sessionName, done)-> # API method is `login` method = 'login' # Parameters params = account: @syno.account passwd: PI:PASSWORD:<PASSWORD>END_PI session: sessionName format: 'sid' # Set sid to null if not @syno.sessions @syno.sessions = {} if not @syno.sessions[sessionName] @syno.sessions[sessionName] = {} @syno.sessions[sessionName]['_sid'] = null # Request login @request {api, version, path, method, params}, done # Logout to syno # `done` [Function] Callback called when the logout process is complete logout: (sessionName = null, done)-> # Don't do anything if there is no session if not @syno.sessions then return null # API method is `logout` method = 'logout' # Init logout parameters params = session: @syno.session # Delete sessions if sessionName @syno.sessions[sessionName] = null else @syno.sessions = null # Request logout @request {api, version, path, method, params}, done # Handle auth specific errors error: (code)-> switch code when 400 then return 'No such account or incorrect password' when 401 then return 'Account disabled' when 402 then return 'Permission denied' when 403 then return '2-step verification code required' when 404 then return 'Failed to authenticate 2-step verification code' # No specific error, so call super function return super
[ { "context": "保存する\n# hubot 登録内容教えて - 登録内容を表示する\n#\n# Author:\n# aha-oretama <sekine_y_529@msn.com>\n\nOperationHelper = require", "end": 378, "score": 0.9917982220649719, "start": 367, "tag": "USERNAME", "value": "aha-oretama" }, { "context": " 登録内容教えて - 登録内容を表示する\n#\n# Author:\...
scripts/amazon-ec.coffee
aha-oretama/oretamaBot
0
# Description # hubot scripts for amazon-product-api hubot # # Commands: # hubot kindle最新刊探して <title> - kindle 版の最新刊を検索して表示 # hubot comic最新刊探して <title> - コミック(kindle除く)版の最新刊を検索して表示 # hubot kindle登録して <title>[,<title>,...] - kindle 版の最新刊を探す条件を保存する # hubot comic登録して <title>[,<title>,...] - comic 版の最新刊を探す条件を保存する # hubot 登録内容教えて - 登録内容を表示する # # Author: # aha-oretama <sekine_y_529@msn.com> OperationHelper = require('apac').OperationHelper cronJob = require('cron').CronJob moment = require 'moment' _ = require 'lodash' class AmazonSearch comicNode = "2278488051" @operationHelper constructor: (associateId,id,secret)-> # コンストラクタ config = assocId: associateId awsId: id awsSecret: secret locale: 'JP' xml2jsOptions: { explicitArray: true } this.operationHelper = new OperationHelper(config) search: (query, isKindle, page, callback, nothingCallBack) -> month = moment().add(-2,'M').format('MM-YYYY') this.operationHelper.execute('ItemSearch',{ 'SearchIndex': 'Books', 'BrowseNode': comicNode, 'Power':"title-begins:#{query} and pubdate:after #{month} and binding:#{binding = if isKindle then 'kindle' else 'not kindle'}", 'ResponseGroup':'Large', 'Sort':'daterank', 'ItemPage': page }).then((response) -> console.log "debug: Raw response body: ", response.responseBody # 処理が速すぎるとときどき AWS API がエラーとなるため処理終了 if response.result.ItemSearchResponse is undefined console.log 'error: 処理が速すぎてエラーになりました' # 処理がたまらないように余裕を持たせる setTimeout((() -> amazonSearch.search(query, isKindle, page , callback, nothingCallBack)), 60000) return baseResult = response.result.ItemSearchResponse.Items[0] totalResults = parseInt baseResult.TotalResults[0], 10 totalPages = parseInt baseResult.TotalPages[0], 10 items = baseResult.Item if totalResults is 0 nothingCallBack return for item in items baseItem = item.ItemAttributes[0] callback { title: baseItem.Title[0], releaseDate: if isKindle then baseItem.ReleaseDate[0] else baseItem.PublicationDate[0], url: item.DetailPageURL[0] } if page < totalPages and page < 10 setTimeout((() -> amazonSearch.search(query, isKindle, page + 1 , callback, nothingCallBack)), 5000) ).catch((err) -> console.log("error:", err) ) amazonSearch = new AmazonSearch(process.env.AWS_ASSOCIATE_ID, process.env.AWS_ID, process.env.AWS_SECRET) newReleaseSearch = (msg,query,isKindle) -> # 検索の実行 amazonSearch.search(query, isKindle, 1, ((item) -> msg.send "#{item.title}が見つかったよー。\n発売日は #{item.releaseDate}だよー\n#{item.url}"), (() -> msg.send "#{query}は最近リリースされてないよー") ) nexWeekSearch = (msg, query , isKindle) -> nextWeek = moment().add(+1,'w').format('YYYY-MM-DD') futureTimeSearch(msg,query,isKindle, nextWeek, "来週") tomorrowSearch = (msg, query , isKindle) -> nextDay = moment().add(+1,'d').format('YYYY-MM-DD') futureTimeSearch(msg,query,isKindle, nextDay, "明日") futureTimeSearch = (msg, query, isKindle, time, timeWord) -> amazonSearch.search(query, isKindle , 1, ((item) -> msg.send "#{item.title}が#{timeWord}発売されるよー。\n #{item.url}" if item.releaseDate is time), (() -> {}) ) setBrain = (robot , msg, titlesStr, isKindle) -> # twitter とshell でプロパティが変わるため user = if msg.envelope.user.hasOwnProperty('user') then msg.envelope.user.user else msg.envelope.user.name stores = robot.brain.get(user) ? [] # 重複を除く titles = titlesStr.split(',') for title in titles if !stores.filter((item) -> item.title is title).length stores.push({title: title, kindle: isKindle}) # user のID は連番で登録する i = 1 users = robot.brain.users() while ( users[i] ) i++ # 保存 robot.brain.userForId(i, name: user) if !robot.brain.userForName(user) # user がいなければ保存 robot.brain.set user, stores robot.brain.save() showRegisteredContents( stores.reduce((previous, current) -> {title:"#{previous.title},#{current.title}"}).title, (item) -> (msg.send "登録内容は" + item) ) showRegisteredContents = (str,callback) -> while(str.length > 120) index = str.substring(0,120).lastIndexOf(',') callback(str.substring(0,index)) str = str.substring(index+1) callback(str) module.exports = (robot) -> # クーロンで来週発売と明日発売の通知を設定 send = (name,message) -> users = robot.brain.users() console.log users i = 1 timeWait = 0 while user = users[i] i++ console.log(user.name) response = new robot.Response(robot, {user : {id : -1, name : user.name, user:user.name}, text : "none", done : false}, []) stores = robot.brain.get(user.name) for store in stores timeWait += 10000 setTimeout(nexWeekSearch, timeWait, response, store.title, store.kindle) setTimeout(tomorrowSearch, timeWait + 5000, response, store.title, store.kindle) # 起動時にクーロン設定 # *(sec) *(min) *(hour) *(day) *(month) *(day of the week) new cronJob('0 0 12 * * *', () -> currentTime = new Date send "" ).start() robot.respond /kindle最新刊(\S*) (\S+)$/i, (msg) -> newReleaseSearch msg, msg.match[2], true robot.respond /comic最新刊(\S*) (\S+)$/i, (msg) -> newReleaseSearch msg, msg.match[2], false robot.respond /kindle登録(\S*) (\S+)$/i, (msg) -> setBrain(robot,msg,msg.match[2], true) robot.respond /comic登録(\S*) (\S+)$/i, (msg) -> setBrain(robot,msg,msg.match[2], false) robot.respond /登録内容(\S*)/i, (msg) -> # twitter とshell でプロパティが変わるため user = if msg.envelope.user.hasOwnProperty('user') then msg.envelope.user.user else msg.envelope.user.name # 呼び出し stores = robot.brain.get(user) showRegisteredContents( stores.reduce((previous, current) -> {title:"#{previous.title},#{current.title}"}).title, (item) -> (msg.send "登録内容は" + item) )
112107
# Description # hubot scripts for amazon-product-api hubot # # Commands: # hubot kindle最新刊探して <title> - kindle 版の最新刊を検索して表示 # hubot comic最新刊探して <title> - コミック(kindle除く)版の最新刊を検索して表示 # hubot kindle登録して <title>[,<title>,...] - kindle 版の最新刊を探す条件を保存する # hubot comic登録して <title>[,<title>,...] - comic 版の最新刊を探す条件を保存する # hubot 登録内容教えて - 登録内容を表示する # # Author: # aha-oretama <<EMAIL>> OperationHelper = require('apac').OperationHelper cronJob = require('cron').CronJob moment = require 'moment' _ = require 'lodash' class AmazonSearch comicNode = "2278488051" @operationHelper constructor: (associateId,id,secret)-> # コンストラクタ config = assocId: associateId awsId: id awsSecret: secret locale: 'JP' xml2jsOptions: { explicitArray: true } this.operationHelper = new OperationHelper(config) search: (query, isKindle, page, callback, nothingCallBack) -> month = moment().add(-2,'M').format('MM-YYYY') this.operationHelper.execute('ItemSearch',{ 'SearchIndex': 'Books', 'BrowseNode': comicNode, 'Power':"title-begins:#{query} and pubdate:after #{month} and binding:#{binding = if isKindle then 'kindle' else 'not kindle'}", 'ResponseGroup':'Large', 'Sort':'daterank', 'ItemPage': page }).then((response) -> console.log "debug: Raw response body: ", response.responseBody # 処理が速すぎるとときどき AWS API がエラーとなるため処理終了 if response.result.ItemSearchResponse is undefined console.log 'error: 処理が速すぎてエラーになりました' # 処理がたまらないように余裕を持たせる setTimeout((() -> amazonSearch.search(query, isKindle, page , callback, nothingCallBack)), 60000) return baseResult = response.result.ItemSearchResponse.Items[0] totalResults = parseInt baseResult.TotalResults[0], 10 totalPages = parseInt baseResult.TotalPages[0], 10 items = baseResult.Item if totalResults is 0 nothingCallBack return for item in items baseItem = item.ItemAttributes[0] callback { title: baseItem.Title[0], releaseDate: if isKindle then baseItem.ReleaseDate[0] else baseItem.PublicationDate[0], url: item.DetailPageURL[0] } if page < totalPages and page < 10 setTimeout((() -> amazonSearch.search(query, isKindle, page + 1 , callback, nothingCallBack)), 5000) ).catch((err) -> console.log("error:", err) ) amazonSearch = new AmazonSearch(process.env.AWS_ASSOCIATE_ID, process.env.AWS_ID, process.env.AWS_SECRET) newReleaseSearch = (msg,query,isKindle) -> # 検索の実行 amazonSearch.search(query, isKindle, 1, ((item) -> msg.send "#{item.title}が見つかったよー。\n発売日は #{item.releaseDate}だよー\n#{item.url}"), (() -> msg.send "#{query}は最近リリースされてないよー") ) nexWeekSearch = (msg, query , isKindle) -> nextWeek = moment().add(+1,'w').format('YYYY-MM-DD') futureTimeSearch(msg,query,isKindle, nextWeek, "来週") tomorrowSearch = (msg, query , isKindle) -> nextDay = moment().add(+1,'d').format('YYYY-MM-DD') futureTimeSearch(msg,query,isKindle, nextDay, "明日") futureTimeSearch = (msg, query, isKindle, time, timeWord) -> amazonSearch.search(query, isKindle , 1, ((item) -> msg.send "#{item.title}が#{timeWord}発売されるよー。\n #{item.url}" if item.releaseDate is time), (() -> {}) ) setBrain = (robot , msg, titlesStr, isKindle) -> # twitter とshell でプロパティが変わるため user = if msg.envelope.user.hasOwnProperty('user') then msg.envelope.user.user else msg.envelope.user.name stores = robot.brain.get(user) ? [] # 重複を除く titles = titlesStr.split(',') for title in titles if !stores.filter((item) -> item.title is title).length stores.push({title: title, kindle: isKindle}) # user のID は連番で登録する i = 1 users = robot.brain.users() while ( users[i] ) i++ # 保存 robot.brain.userForId(i, name: user) if !robot.brain.userForName(user) # user がいなければ保存 robot.brain.set user, stores robot.brain.save() showRegisteredContents( stores.reduce((previous, current) -> {title:"#{previous.title},#{current.title}"}).title, (item) -> (msg.send "登録内容は" + item) ) showRegisteredContents = (str,callback) -> while(str.length > 120) index = str.substring(0,120).lastIndexOf(',') callback(str.substring(0,index)) str = str.substring(index+1) callback(str) module.exports = (robot) -> # クーロンで来週発売と明日発売の通知を設定 send = (name,message) -> users = robot.brain.users() console.log users i = 1 timeWait = 0 while user = users[i] i++ console.log(user.name) response = new robot.Response(robot, {user : {id : -1, name : user<NAME>.name, user:user.name}, text : "none", done : false}, []) stores = robot.brain.get(user.name) for store in stores timeWait += 10000 setTimeout(nexWeekSearch, timeWait, response, store.title, store.kindle) setTimeout(tomorrowSearch, timeWait + 5000, response, store.title, store.kindle) # 起動時にクーロン設定 # *(sec) *(min) *(hour) *(day) *(month) *(day of the week) new cronJob('0 0 12 * * *', () -> currentTime = new Date send "" ).start() robot.respond /kindle最新刊(\S*) (\S+)$/i, (msg) -> newReleaseSearch msg, msg.match[2], true robot.respond /comic最新刊(\S*) (\S+)$/i, (msg) -> newReleaseSearch msg, msg.match[2], false robot.respond /kindle登録(\S*) (\S+)$/i, (msg) -> setBrain(robot,msg,msg.match[2], true) robot.respond /comic登録(\S*) (\S+)$/i, (msg) -> setBrain(robot,msg,msg.match[2], false) robot.respond /登録内容(\S*)/i, (msg) -> # twitter とshell でプロパティが変わるため user = if msg.envelope.user.hasOwnProperty('user') then msg.envelope.user.user else msg.envelope.user.name # 呼び出し stores = robot.brain.get(user) showRegisteredContents( stores.reduce((previous, current) -> {title:"#{previous.title},#{current.title}"}).title, (item) -> (msg.send "登録内容は" + item) )
true
# Description # hubot scripts for amazon-product-api hubot # # Commands: # hubot kindle最新刊探して <title> - kindle 版の最新刊を検索して表示 # hubot comic最新刊探して <title> - コミック(kindle除く)版の最新刊を検索して表示 # hubot kindle登録して <title>[,<title>,...] - kindle 版の最新刊を探す条件を保存する # hubot comic登録して <title>[,<title>,...] - comic 版の最新刊を探す条件を保存する # hubot 登録内容教えて - 登録内容を表示する # # Author: # aha-oretama <PI:EMAIL:<EMAIL>END_PI> OperationHelper = require('apac').OperationHelper cronJob = require('cron').CronJob moment = require 'moment' _ = require 'lodash' class AmazonSearch comicNode = "2278488051" @operationHelper constructor: (associateId,id,secret)-> # コンストラクタ config = assocId: associateId awsId: id awsSecret: secret locale: 'JP' xml2jsOptions: { explicitArray: true } this.operationHelper = new OperationHelper(config) search: (query, isKindle, page, callback, nothingCallBack) -> month = moment().add(-2,'M').format('MM-YYYY') this.operationHelper.execute('ItemSearch',{ 'SearchIndex': 'Books', 'BrowseNode': comicNode, 'Power':"title-begins:#{query} and pubdate:after #{month} and binding:#{binding = if isKindle then 'kindle' else 'not kindle'}", 'ResponseGroup':'Large', 'Sort':'daterank', 'ItemPage': page }).then((response) -> console.log "debug: Raw response body: ", response.responseBody # 処理が速すぎるとときどき AWS API がエラーとなるため処理終了 if response.result.ItemSearchResponse is undefined console.log 'error: 処理が速すぎてエラーになりました' # 処理がたまらないように余裕を持たせる setTimeout((() -> amazonSearch.search(query, isKindle, page , callback, nothingCallBack)), 60000) return baseResult = response.result.ItemSearchResponse.Items[0] totalResults = parseInt baseResult.TotalResults[0], 10 totalPages = parseInt baseResult.TotalPages[0], 10 items = baseResult.Item if totalResults is 0 nothingCallBack return for item in items baseItem = item.ItemAttributes[0] callback { title: baseItem.Title[0], releaseDate: if isKindle then baseItem.ReleaseDate[0] else baseItem.PublicationDate[0], url: item.DetailPageURL[0] } if page < totalPages and page < 10 setTimeout((() -> amazonSearch.search(query, isKindle, page + 1 , callback, nothingCallBack)), 5000) ).catch((err) -> console.log("error:", err) ) amazonSearch = new AmazonSearch(process.env.AWS_ASSOCIATE_ID, process.env.AWS_ID, process.env.AWS_SECRET) newReleaseSearch = (msg,query,isKindle) -> # 検索の実行 amazonSearch.search(query, isKindle, 1, ((item) -> msg.send "#{item.title}が見つかったよー。\n発売日は #{item.releaseDate}だよー\n#{item.url}"), (() -> msg.send "#{query}は最近リリースされてないよー") ) nexWeekSearch = (msg, query , isKindle) -> nextWeek = moment().add(+1,'w').format('YYYY-MM-DD') futureTimeSearch(msg,query,isKindle, nextWeek, "来週") tomorrowSearch = (msg, query , isKindle) -> nextDay = moment().add(+1,'d').format('YYYY-MM-DD') futureTimeSearch(msg,query,isKindle, nextDay, "明日") futureTimeSearch = (msg, query, isKindle, time, timeWord) -> amazonSearch.search(query, isKindle , 1, ((item) -> msg.send "#{item.title}が#{timeWord}発売されるよー。\n #{item.url}" if item.releaseDate is time), (() -> {}) ) setBrain = (robot , msg, titlesStr, isKindle) -> # twitter とshell でプロパティが変わるため user = if msg.envelope.user.hasOwnProperty('user') then msg.envelope.user.user else msg.envelope.user.name stores = robot.brain.get(user) ? [] # 重複を除く titles = titlesStr.split(',') for title in titles if !stores.filter((item) -> item.title is title).length stores.push({title: title, kindle: isKindle}) # user のID は連番で登録する i = 1 users = robot.brain.users() while ( users[i] ) i++ # 保存 robot.brain.userForId(i, name: user) if !robot.brain.userForName(user) # user がいなければ保存 robot.brain.set user, stores robot.brain.save() showRegisteredContents( stores.reduce((previous, current) -> {title:"#{previous.title},#{current.title}"}).title, (item) -> (msg.send "登録内容は" + item) ) showRegisteredContents = (str,callback) -> while(str.length > 120) index = str.substring(0,120).lastIndexOf(',') callback(str.substring(0,index)) str = str.substring(index+1) callback(str) module.exports = (robot) -> # クーロンで来週発売と明日発売の通知を設定 send = (name,message) -> users = robot.brain.users() console.log users i = 1 timeWait = 0 while user = users[i] i++ console.log(user.name) response = new robot.Response(robot, {user : {id : -1, name : userPI:NAME:<NAME>END_PI.name, user:user.name}, text : "none", done : false}, []) stores = robot.brain.get(user.name) for store in stores timeWait += 10000 setTimeout(nexWeekSearch, timeWait, response, store.title, store.kindle) setTimeout(tomorrowSearch, timeWait + 5000, response, store.title, store.kindle) # 起動時にクーロン設定 # *(sec) *(min) *(hour) *(day) *(month) *(day of the week) new cronJob('0 0 12 * * *', () -> currentTime = new Date send "" ).start() robot.respond /kindle最新刊(\S*) (\S+)$/i, (msg) -> newReleaseSearch msg, msg.match[2], true robot.respond /comic最新刊(\S*) (\S+)$/i, (msg) -> newReleaseSearch msg, msg.match[2], false robot.respond /kindle登録(\S*) (\S+)$/i, (msg) -> setBrain(robot,msg,msg.match[2], true) robot.respond /comic登録(\S*) (\S+)$/i, (msg) -> setBrain(robot,msg,msg.match[2], false) robot.respond /登録内容(\S*)/i, (msg) -> # twitter とshell でプロパティが変わるため user = if msg.envelope.user.hasOwnProperty('user') then msg.envelope.user.user else msg.envelope.user.name # 呼び出し stores = robot.brain.get(user) showRegisteredContents( stores.reduce((previous, current) -> {title:"#{previous.title},#{current.title}"}).title, (item) -> (msg.send "登録内容は" + item) )
[ { "context": "'href=\"https://peoplefinder.service.gov.uk/people/john-smith\">John Smith</a>' +\n '</body>')\n $(doc", "end": 379, "score": 0.997896671295166, "start": 369, "tag": "USERNAME", "value": "john-smith" }, { "context": "://peoplefinder.service.gov.uk/people/joh...
spec/javascripts/analytics/analytics_event_spec.coffee
cybersquirrel/peoplefinder
16
//= require modules/analytics_event describe 'AnalyticsEvent', -> element = null describe 'given there is "data-event-category" anchor link', -> beforeEach -> element = $('<body>' + '<a id="a_link" data-event-category="Search result" ' + 'data-event-action="Click result 1" ' + 'href="https://peoplefinder.service.gov.uk/people/john-smith">John Smith</a>' + '</body>') $(document.body).append(element) new window.AnalyticsEvent.bindLinks() afterEach -> element.remove() element = null describe 'when I click on "data-event-label" element', -> it "dispatches analytics event", -> spyOn window, 'dispatchAnalyticsEvent' $('#a_link').trigger 'click' expect(window.dispatchAnalyticsEvent).toHaveBeenCalledWith('Search result', 'Click result 1', 'John Smith')
14569
//= require modules/analytics_event describe 'AnalyticsEvent', -> element = null describe 'given there is "data-event-category" anchor link', -> beforeEach -> element = $('<body>' + '<a id="a_link" data-event-category="Search result" ' + 'data-event-action="Click result 1" ' + 'href="https://peoplefinder.service.gov.uk/people/john-smith"><NAME></a>' + '</body>') $(document.body).append(element) new window.AnalyticsEvent.bindLinks() afterEach -> element.remove() element = null describe 'when I click on "data-event-label" element', -> it "dispatches analytics event", -> spyOn window, 'dispatchAnalyticsEvent' $('#a_link').trigger 'click' expect(window.dispatchAnalyticsEvent).toHaveBeenCalledWith('Search result', 'Click result 1', '<NAME>')
true
//= require modules/analytics_event describe 'AnalyticsEvent', -> element = null describe 'given there is "data-event-category" anchor link', -> beforeEach -> element = $('<body>' + '<a id="a_link" data-event-category="Search result" ' + 'data-event-action="Click result 1" ' + 'href="https://peoplefinder.service.gov.uk/people/john-smith">PI:NAME:<NAME>END_PI</a>' + '</body>') $(document.body).append(element) new window.AnalyticsEvent.bindLinks() afterEach -> element.remove() element = null describe 'when I click on "data-event-label" element', -> it "dispatches analytics event", -> spyOn window, 'dispatchAnalyticsEvent' $('#a_link').trigger 'click' expect(window.dispatchAnalyticsEvent).toHaveBeenCalledWith('Search result', 'Click result 1', 'PI:NAME:<NAME>END_PI')
[ { "context": " username: process.env.OS_USERNAME\n # apiKey: process.env.OS_PASSWORD\n # region: process.env.OS_REGION_N", "end": 429, "score": 0.7381636500358582, "start": 418, "tag": "PASSWORD", "value": "process.env" }, { "context": "cess.env.OS_USERNAME\n # apiKey: p...
lib/storage-client.coffee
mtdev2/atom-cloud-sync
0
pkgcloud = require 'pkgcloud' fs = require 'fs' # Just placing this here to have a dummy callback. # genericCallback = (err, result) -> if err? console.error(err) else console.log(result) module.exports = class StorageClient # Cloud Storage # # Accepts a pkgcloud credential object # # Example: # creds = # provider: 'rackspace' # username: process.env.OS_USERNAME # apiKey: process.env.OS_PASSWORD # region: process.env.OS_REGION_NAME # # storage = new StorageClient(creds) # constructor: (creds) -> @client = pkgcloud.storage.createClient(creds) # Uploads filePath to objectName in container containerName. Creates the # container if necessary. # uploadFile: (filePath, containerName, objectName, cdn) -> console.log("Uploading #{filePath} into #{containerName} as #{objectName}") @client.createContainer containerName, (err, container) => throw err if err? @client.setCdnEnabled containerName, cdn, (err) => throw err if err? file = fs.createReadStream(filePath) layout = container: containerName remote: objectName file.pipe(@client.upload(layout, genericCallback)) # Upload all the files within the directory into the container, starting # them off with objectPath uploadDirectory: (container, directory, objectPath) -> console.error("Not implemented yet")
68440
pkgcloud = require 'pkgcloud' fs = require 'fs' # Just placing this here to have a dummy callback. # genericCallback = (err, result) -> if err? console.error(err) else console.log(result) module.exports = class StorageClient # Cloud Storage # # Accepts a pkgcloud credential object # # Example: # creds = # provider: 'rackspace' # username: process.env.OS_USERNAME # apiKey: <PASSWORD>.OS<KEY>_<PASSWORD> # region: process.env.OS_REGION_NAME # # storage = new StorageClient(creds) # constructor: (creds) -> @client = pkgcloud.storage.createClient(creds) # Uploads filePath to objectName in container containerName. Creates the # container if necessary. # uploadFile: (filePath, containerName, objectName, cdn) -> console.log("Uploading #{filePath} into #{containerName} as #{objectName}") @client.createContainer containerName, (err, container) => throw err if err? @client.setCdnEnabled containerName, cdn, (err) => throw err if err? file = fs.createReadStream(filePath) layout = container: containerName remote: objectName file.pipe(@client.upload(layout, genericCallback)) # Upload all the files within the directory into the container, starting # them off with objectPath uploadDirectory: (container, directory, objectPath) -> console.error("Not implemented yet")
true
pkgcloud = require 'pkgcloud' fs = require 'fs' # Just placing this here to have a dummy callback. # genericCallback = (err, result) -> if err? console.error(err) else console.log(result) module.exports = class StorageClient # Cloud Storage # # Accepts a pkgcloud credential object # # Example: # creds = # provider: 'rackspace' # username: process.env.OS_USERNAME # apiKey: PI:PASSWORD:<PASSWORD>END_PI.OSPI:KEY:<KEY>END_PI_PI:PASSWORD:<PASSWORD>END_PI # region: process.env.OS_REGION_NAME # # storage = new StorageClient(creds) # constructor: (creds) -> @client = pkgcloud.storage.createClient(creds) # Uploads filePath to objectName in container containerName. Creates the # container if necessary. # uploadFile: (filePath, containerName, objectName, cdn) -> console.log("Uploading #{filePath} into #{containerName} as #{objectName}") @client.createContainer containerName, (err, container) => throw err if err? @client.setCdnEnabled containerName, cdn, (err) => throw err if err? file = fs.createReadStream(filePath) layout = container: containerName remote: objectName file.pipe(@client.upload(layout, genericCallback)) # Upload all the files within the directory into the container, starting # them off with objectPath uploadDirectory: (container, directory, objectPath) -> console.error("Not implemented yet")
[ { "context": "s = do $('#cpasswd').val\n pass1 = do $('#npasswd1').val\n pass2 = do $('#npasswd2').val\n\n ", "end": 634, "score": 0.7671859264373779, "start": 629, "tag": "PASSWORD", "value": "asswd" }, { "context": "ass = do $('#cpasswd').val\n pass1 = do $('...
wsgi/training/static/coffee/settings.coffee
akolar/training
0
$ -> $('.settings form').submit false $('[data-action="default"]').change -> field = $(this) $.ajax url: '/settings/save/' + this.id method: 'PUT' data: { value: do field.val } success: (data, textStatus, jqXHR) -> if data.success marker = field.closest('.row').find '.saved' marker.addClass 'active' setTimeout ( -> marker.removeClass 'active' ), 2000 check_pass = -> cpass = do $('#cpasswd').val pass1 = do $('#npasswd1').val pass2 = do $('#npasswd2').val return (cpass != '') and (pass1 != '') and (pass1 == pass2) $('input[type="password"]').change -> if do check_pass $('button[data-action="set-passwd"]').removeAttr 'disabled' else $('button[data-action="set-passwd"]').attr 'disabled', '' $('button[data-action="set-passwd"]').click -> cpass = do $('#cpasswd').val pass1 = do $('#npasswd1').val pass2 = do $('#npasswd2').val $.ajax url: '/settings/save/password' method: 'PUT' data: {current: cpass, new: pass1} success: (data, textStatus, jqXHR) -> $('.text-danger').addClass 'hidden' if data.success marker = field.closest('.row').find '.saved' marker.addClass 'active' setTimeout ( -> marker.removeClass 'active' ), 2000 else $('.' + data.reason).removeClass 'hidden' $('[data-action="avatar"]').click -> data = new FormData() data.append 'avatar', $('[name="avatar"]')[0].files[0] $.ajax url: '/settings/save/avatar' method: 'POST' data: data cache: false processData: false contentType: false success: (data, textStatus, jqXHR) -> do location.reload return false $('[data-action="goals"]').change -> field = $(this) params = this.name.split('_') $.ajax url: '/goals/set/' + params[0] data: objective: params[1] value: do field.val method: 'PUT' success: (data, textStatus, jqXHR) -> console.log data
144368
$ -> $('.settings form').submit false $('[data-action="default"]').change -> field = $(this) $.ajax url: '/settings/save/' + this.id method: 'PUT' data: { value: do field.val } success: (data, textStatus, jqXHR) -> if data.success marker = field.closest('.row').find '.saved' marker.addClass 'active' setTimeout ( -> marker.removeClass 'active' ), 2000 check_pass = -> cpass = do $('#cpasswd').val pass1 = do $('#np<PASSWORD>1').val pass2 = do $('#npasswd2').val return (cpass != '') and (pass1 != '') and (pass1 == pass2) $('input[type="password"]').change -> if do check_pass $('button[data-action="set-passwd"]').removeAttr 'disabled' else $('button[data-action="set-passwd"]').attr 'disabled', '' $('button[data-action="set-passwd"]').click -> cpass = do $('#cpasswd').val pass1 = do $('#<PASSWORD>').val pass2 = do $('#<PASSWORD>').val $.ajax url: '/settings/save/password' method: 'PUT' data: {current: cpass, new: pass1} success: (data, textStatus, jqXHR) -> $('.text-danger').addClass 'hidden' if data.success marker = field.closest('.row').find '.saved' marker.addClass 'active' setTimeout ( -> marker.removeClass 'active' ), 2000 else $('.' + data.reason).removeClass 'hidden' $('[data-action="avatar"]').click -> data = new FormData() data.append 'avatar', $('[name="avatar"]')[0].files[0] $.ajax url: '/settings/save/avatar' method: 'POST' data: data cache: false processData: false contentType: false success: (data, textStatus, jqXHR) -> do location.reload return false $('[data-action="goals"]').change -> field = $(this) params = this.name.split('_') $.ajax url: '/goals/set/' + params[0] data: objective: params[1] value: do field.val method: 'PUT' success: (data, textStatus, jqXHR) -> console.log data
true
$ -> $('.settings form').submit false $('[data-action="default"]').change -> field = $(this) $.ajax url: '/settings/save/' + this.id method: 'PUT' data: { value: do field.val } success: (data, textStatus, jqXHR) -> if data.success marker = field.closest('.row').find '.saved' marker.addClass 'active' setTimeout ( -> marker.removeClass 'active' ), 2000 check_pass = -> cpass = do $('#cpasswd').val pass1 = do $('#npPI:PASSWORD:<PASSWORD>END_PI1').val pass2 = do $('#npasswd2').val return (cpass != '') and (pass1 != '') and (pass1 == pass2) $('input[type="password"]').change -> if do check_pass $('button[data-action="set-passwd"]').removeAttr 'disabled' else $('button[data-action="set-passwd"]').attr 'disabled', '' $('button[data-action="set-passwd"]').click -> cpass = do $('#cpasswd').val pass1 = do $('#PI:PASSWORD:<PASSWORD>END_PI').val pass2 = do $('#PI:PASSWORD:<PASSWORD>END_PI').val $.ajax url: '/settings/save/password' method: 'PUT' data: {current: cpass, new: pass1} success: (data, textStatus, jqXHR) -> $('.text-danger').addClass 'hidden' if data.success marker = field.closest('.row').find '.saved' marker.addClass 'active' setTimeout ( -> marker.removeClass 'active' ), 2000 else $('.' + data.reason).removeClass 'hidden' $('[data-action="avatar"]').click -> data = new FormData() data.append 'avatar', $('[name="avatar"]')[0].files[0] $.ajax url: '/settings/save/avatar' method: 'POST' data: data cache: false processData: false contentType: false success: (data, textStatus, jqXHR) -> do location.reload return false $('[data-action="goals"]').change -> field = $(this) params = this.name.split('_') $.ajax url: '/goals/set/' + params[0] data: objective: params[1] value: do field.val method: 'PUT' success: (data, textStatus, jqXHR) -> console.log data
[ { "context": "#\n# The main Coookie class\n#\n# Copyright (C) 2011 Nikolay Nemshilov\n#\nclass Cookie\n extend:\n #\n # Sets the coo", "end": 67, "score": 0.9998869299888611, "start": 50, "tag": "NAME", "value": "Nikolay Nemshilov" } ]
stl/cookie/src/cookie.coffee
lovely-io/lovely.io-stl
2
# # The main Coookie class # # Copyright (C) 2011 Nikolay Nemshilov # class Cookie extend: # # Sets the coookie # # @param {String} cookie name # @param {mixed} cookie value # @param {Object} options # @return {Cookie} object # set: (name, value, options)-> new Cookie(name, options).set(value) # # Reads a cookie by name # # @param {String} cookie name # @return {mixed|undefined} cookie value or `undefined` if not set # get: (name, options)-> new Cookie(name).get() # # Removes the cookie # # @param {String} cookie name # @param {Object} options # @return {Cookie} object # remove: (name, options)-> new Cookie(name, options).remove() # # Checks if cookies are enabled in the browser # # @return {Boolean} check result # enabled: -> Cookie.Options.document.cookie = "__t=1" Cookie.Options.document.cookie.indexOf("__t=1") isnt -1 # # Default options # Options: document: document secure: false domain: null path: null ttl: null # in days # # Basic constructor # # @param {String} cookie name # @param {Object} options # @return {Cookie} this # constructor: (name, options)-> @options = ext(ext({}, Cookie.Options), options) @name = name return @ # # Sets the cookie with the name # # @param {mixed} value # @return Cookie this # set: (data)-> data = JSON.stringify(data) if typeof(data) is 'object' data = escape(data) @options.domain && data += '; domain='+ @options.domain @options.path && data += '; path='+ @options.path @options.secure && data += '; secure' if @options.ttl date = new Date() date.setTime(date.getTime() + @options.ttl * 24 * 60 * 60 * 1000) data += '; expires='+ date.toGMTString() @options.document.cookie = "#{escape(@name)}=#{data}" return @ # # Searches for a cookie with the name # # @return {mixed} saved value or `undefined` if nothing was set # get: -> name = escape(@name) name = "(?:^|;)\\s*#{name.replace(/([.*+?\^=!:${}()|\[\]\/\\])/g, '\\$1')}=([^;]*)" data = @options.document.cookie.match(name) if data data = unescape(data[1]) try data = JSON.parse(data) catch e data || undefined # # Removes the cookie # # @return {Cookie} this # remove: -> unless @get() is undefined @options.ttl = -1 @set('') return @
109447
# # The main Coookie class # # Copyright (C) 2011 <NAME> # class Cookie extend: # # Sets the coookie # # @param {String} cookie name # @param {mixed} cookie value # @param {Object} options # @return {Cookie} object # set: (name, value, options)-> new Cookie(name, options).set(value) # # Reads a cookie by name # # @param {String} cookie name # @return {mixed|undefined} cookie value or `undefined` if not set # get: (name, options)-> new Cookie(name).get() # # Removes the cookie # # @param {String} cookie name # @param {Object} options # @return {Cookie} object # remove: (name, options)-> new Cookie(name, options).remove() # # Checks if cookies are enabled in the browser # # @return {Boolean} check result # enabled: -> Cookie.Options.document.cookie = "__t=1" Cookie.Options.document.cookie.indexOf("__t=1") isnt -1 # # Default options # Options: document: document secure: false domain: null path: null ttl: null # in days # # Basic constructor # # @param {String} cookie name # @param {Object} options # @return {Cookie} this # constructor: (name, options)-> @options = ext(ext({}, Cookie.Options), options) @name = name return @ # # Sets the cookie with the name # # @param {mixed} value # @return Cookie this # set: (data)-> data = JSON.stringify(data) if typeof(data) is 'object' data = escape(data) @options.domain && data += '; domain='+ @options.domain @options.path && data += '; path='+ @options.path @options.secure && data += '; secure' if @options.ttl date = new Date() date.setTime(date.getTime() + @options.ttl * 24 * 60 * 60 * 1000) data += '; expires='+ date.toGMTString() @options.document.cookie = "#{escape(@name)}=#{data}" return @ # # Searches for a cookie with the name # # @return {mixed} saved value or `undefined` if nothing was set # get: -> name = escape(@name) name = "(?:^|;)\\s*#{name.replace(/([.*+?\^=!:${}()|\[\]\/\\])/g, '\\$1')}=([^;]*)" data = @options.document.cookie.match(name) if data data = unescape(data[1]) try data = JSON.parse(data) catch e data || undefined # # Removes the cookie # # @return {Cookie} this # remove: -> unless @get() is undefined @options.ttl = -1 @set('') return @
true
# # The main Coookie class # # Copyright (C) 2011 PI:NAME:<NAME>END_PI # class Cookie extend: # # Sets the coookie # # @param {String} cookie name # @param {mixed} cookie value # @param {Object} options # @return {Cookie} object # set: (name, value, options)-> new Cookie(name, options).set(value) # # Reads a cookie by name # # @param {String} cookie name # @return {mixed|undefined} cookie value or `undefined` if not set # get: (name, options)-> new Cookie(name).get() # # Removes the cookie # # @param {String} cookie name # @param {Object} options # @return {Cookie} object # remove: (name, options)-> new Cookie(name, options).remove() # # Checks if cookies are enabled in the browser # # @return {Boolean} check result # enabled: -> Cookie.Options.document.cookie = "__t=1" Cookie.Options.document.cookie.indexOf("__t=1") isnt -1 # # Default options # Options: document: document secure: false domain: null path: null ttl: null # in days # # Basic constructor # # @param {String} cookie name # @param {Object} options # @return {Cookie} this # constructor: (name, options)-> @options = ext(ext({}, Cookie.Options), options) @name = name return @ # # Sets the cookie with the name # # @param {mixed} value # @return Cookie this # set: (data)-> data = JSON.stringify(data) if typeof(data) is 'object' data = escape(data) @options.domain && data += '; domain='+ @options.domain @options.path && data += '; path='+ @options.path @options.secure && data += '; secure' if @options.ttl date = new Date() date.setTime(date.getTime() + @options.ttl * 24 * 60 * 60 * 1000) data += '; expires='+ date.toGMTString() @options.document.cookie = "#{escape(@name)}=#{data}" return @ # # Searches for a cookie with the name # # @return {mixed} saved value or `undefined` if nothing was set # get: -> name = escape(@name) name = "(?:^|;)\\s*#{name.replace(/([.*+?\^=!:${}()|\[\]\/\\])/g, '\\$1')}=([^;]*)" data = @options.document.cookie.match(name) if data data = unescape(data[1]) try data = JSON.parse(data) catch e data || undefined # # Removes the cookie # # @return {Cookie} this # remove: -> unless @get() is undefined @options.ttl = -1 @set('') return @
[ { "context": "s file is part of the Konsserto package.\n *\n * (c) Jessym Reziga <jessym@konsserto.com>\n *\n * For the full copyrig", "end": 74, "score": 0.9998752474784851, "start": 61, "tag": "NAME", "value": "Jessym Reziga" }, { "context": "f the Konsserto package.\n *\n * (c) Je...
node_modules/konsserto/lib/src/Konsserto/Component/Static/Tools.coffee
konsserto/konsserto
2
### * This file is part of the Konsserto package. * * (c) Jessym Reziga <jessym@konsserto.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. ### Crypt = use('@Konsserto/Component/Static/Crypt') Q = use('q') # # Tools # # @author Jessym Reziga <jessym@konsserto.com> # class Tools @STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg @ARGUMENT_NAMES = /([^\s,]+)/g @endsWith:(stack,suffix) -> return stack.indexOf(suffix, stack.length - suffix.length) != -1 @mergeObjects:(obj1,obj2,strict = false) -> obj3 = {}; for k,v of obj1 if strict && k.indexOf('_from') == 0 continue else obj3[k] = v for k,v of obj2 if strict && k.indexOf('_from') == 0 continue else obj3[k] = v return obj3 @firstKey:(obj1) -> for k,v of obj1 return k @removeExt:(stack,ext) -> pos = stack.lastIndexOf(ext); return stack.substr(0,pos) @searchAndReplace:(oldValue,newValue,tab,lowercase) -> outTab = [] for item in tab if lowercase if item.toLowerCase() == oldValue.toLowerCase() outTab.push(newValue) else outTab.push(item) else if item == oldValue outTab.push(newValue) else outTab.push(item) return outTab @toStringObject:(obj1) -> out = '' for k,v of obj1 console.log(k+' '+v) out += k+v return out @toKeyObject:(obj1) -> return Crypt.md5(@toStringObject(obj1)) @cloneObject:(obj) -> if not obj? or typeof obj isnt 'object' return obj if obj instanceof Date return new Date(obj.getTime()) if obj instanceof RegExp flags = '' flags += 'g' if obj.global? flags += 'i' if obj.ignoreCase? flags += 'm' if obj.multiline? flags += 'y' if obj.sticky? return new RegExp(obj.source, flags) newInstance = new obj.constructor() for key of obj newInstance[key] = @cloneObject obj[key] return newInstance @extend = (a, b) -> for i of b g = b.__lookupGetter__(i) s = b.__lookupSetter__(i) if g or s a.__defineGetter__ i, g a.__defineSetter__ i, s else a[i] = b[i] return a @toArray:(object) -> tmp_array = [] for key,value of object tmp_array.push(object[key]); return tmp_array @isInt:(str) -> return (str+'').match('^([0-9]+)$') @millis:() -> now = new Date().getTime() / 1000 seconds = parseInt(now,10) return parseInt(seconds+''+Math.round((now - seconds) * 1000)) @ucfirst:(str, tolower = false) -> str += '' f = str.charAt(0).toUpperCase(); if tolower return f + str.substr(1).toLowerCase() return f + str.substr(1); @sortObject:(object) -> return `(function(s){var t={};Object.keys(s).sort().forEach(function(k){t[k]=s[k]});return t})(object)` @replaceFinalOccurence:(haystack, needle, replacement = '') -> return haystack.substr(0,haystack.lastIndexOf(needle)) + replacement @getFunctionParameters:(func) -> fnStr = func.toString().replace(Tools.STRIP_COMMENTS, '') result = fnStr.slice(fnStr.indexOf('(')+1, fnStr.indexOf(')')).match(Tools.ARGUMENT_NAMES) if !result? result = [] return result @camelCase:(input,ucfirst = false) -> words = input.split(/[-_.]/) if words? && words.length >0 out = if ucfirst then Tools.ucfirst(words.shift(),true) else words.shift() for word in words out += Tools.ucfirst(word,true) return out else return '' @call:(cb, parameters) -> func = undefined if typeof cb is "string" func = (if (typeof this[cb] is "function") then this[cb] else func = (new Function(null, "return " + cb))()) else if Object::toString.call(cb) is "[object Array]" func = (if (typeof cb[0] is "string") then eval(cb[0] + "['" + cb[1] + "']") else func = cb[0][cb[1]]) else func = cb if typeof cb is "function" throw new Error(func + " is not a valid function") if typeof func isnt "function" (if (typeof cb[0] is "string") then func.apply(eval(cb[0]), parameters) else (if (typeof cb[0] isnt "object") then func.apply(null, parameters) else func.apply(cb[0], parameters))) @strstr:(haysack,needle) -> column = 0 haystack += '' column = haystack.indexOf(needle) return if column == -1 then false else haystack.slice(column) @strtr = (string, from, to) -> length = 0 hash = new Array() tmp = "" if from.length < to.length length = from.length else length = to.length i = 0 while i < length hash[from.charAt(i)] = to.charAt(i) i++ j = 0 while j < string.length c = string.charAt(j) if hash[c] tmp = tmp + hash[string.charAt(j)] else tmp = tmp + c j++ tmp @array_unique:(array) -> unique = [] for i in [1..array.length] if (unique.indexOf(array[i]) == -1) unique.push(array[i]) return unique; @promiseWhile: (condition, body) -> done = Q.defer() _loop = () -> return done.resolve() unless condition() Q.when(body(), _loop, done.reject) Q.nextTick(_loop) return done.promise module.exports = Tools
204752
### * This file is part of the Konsserto package. * * (c) <NAME> <<EMAIL>> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. ### Crypt = use('@Konsserto/Component/Static/Crypt') Q = use('q') # # Tools # # @author <NAME> <<EMAIL>> # class Tools @STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg @ARGUMENT_NAMES = /([^\s,]+)/g @endsWith:(stack,suffix) -> return stack.indexOf(suffix, stack.length - suffix.length) != -1 @mergeObjects:(obj1,obj2,strict = false) -> obj3 = {}; for k,v of obj1 if strict && k.indexOf('_from') == 0 continue else obj3[k] = v for k,v of obj2 if strict && k.indexOf('_from') == 0 continue else obj3[k] = v return obj3 @firstKey:(obj1) -> for k,v of obj1 return k @removeExt:(stack,ext) -> pos = stack.lastIndexOf(ext); return stack.substr(0,pos) @searchAndReplace:(oldValue,newValue,tab,lowercase) -> outTab = [] for item in tab if lowercase if item.toLowerCase() == oldValue.toLowerCase() outTab.push(newValue) else outTab.push(item) else if item == oldValue outTab.push(newValue) else outTab.push(item) return outTab @toStringObject:(obj1) -> out = '' for k,v of obj1 console.log(k+' '+v) out += k+v return out @toKeyObject:(obj1) -> return Crypt.md5(@toStringObject(obj1)) @cloneObject:(obj) -> if not obj? or typeof obj isnt 'object' return obj if obj instanceof Date return new Date(obj.getTime()) if obj instanceof RegExp flags = '' flags += 'g' if obj.global? flags += 'i' if obj.ignoreCase? flags += 'm' if obj.multiline? flags += 'y' if obj.sticky? return new RegExp(obj.source, flags) newInstance = new obj.constructor() for key of obj newInstance[key] = @cloneObject obj[key] return newInstance @extend = (a, b) -> for i of b g = b.__lookupGetter__(i) s = b.__lookupSetter__(i) if g or s a.__defineGetter__ i, g a.__defineSetter__ i, s else a[i] = b[i] return a @toArray:(object) -> tmp_array = [] for key,value of object tmp_array.push(object[key]); return tmp_array @isInt:(str) -> return (str+'').match('^([0-9]+)$') @millis:() -> now = new Date().getTime() / 1000 seconds = parseInt(now,10) return parseInt(seconds+''+Math.round((now - seconds) * 1000)) @ucfirst:(str, tolower = false) -> str += '' f = str.charAt(0).toUpperCase(); if tolower return f + str.substr(1).toLowerCase() return f + str.substr(1); @sortObject:(object) -> return `(function(s){var t={};Object.keys(s).sort().forEach(function(k){t[k]=s[k]});return t})(object)` @replaceFinalOccurence:(haystack, needle, replacement = '') -> return haystack.substr(0,haystack.lastIndexOf(needle)) + replacement @getFunctionParameters:(func) -> fnStr = func.toString().replace(Tools.STRIP_COMMENTS, '') result = fnStr.slice(fnStr.indexOf('(')+1, fnStr.indexOf(')')).match(Tools.ARGUMENT_NAMES) if !result? result = [] return result @camelCase:(input,ucfirst = false) -> words = input.split(/[-_.]/) if words? && words.length >0 out = if ucfirst then Tools.ucfirst(words.shift(),true) else words.shift() for word in words out += Tools.ucfirst(word,true) return out else return '' @call:(cb, parameters) -> func = undefined if typeof cb is "string" func = (if (typeof this[cb] is "function") then this[cb] else func = (new Function(null, "return " + cb))()) else if Object::toString.call(cb) is "[object Array]" func = (if (typeof cb[0] is "string") then eval(cb[0] + "['" + cb[1] + "']") else func = cb[0][cb[1]]) else func = cb if typeof cb is "function" throw new Error(func + " is not a valid function") if typeof func isnt "function" (if (typeof cb[0] is "string") then func.apply(eval(cb[0]), parameters) else (if (typeof cb[0] isnt "object") then func.apply(null, parameters) else func.apply(cb[0], parameters))) @strstr:(haysack,needle) -> column = 0 haystack += '' column = haystack.indexOf(needle) return if column == -1 then false else haystack.slice(column) @strtr = (string, from, to) -> length = 0 hash = new Array() tmp = "" if from.length < to.length length = from.length else length = to.length i = 0 while i < length hash[from.charAt(i)] = to.charAt(i) i++ j = 0 while j < string.length c = string.charAt(j) if hash[c] tmp = tmp + hash[string.charAt(j)] else tmp = tmp + c j++ tmp @array_unique:(array) -> unique = [] for i in [1..array.length] if (unique.indexOf(array[i]) == -1) unique.push(array[i]) return unique; @promiseWhile: (condition, body) -> done = Q.defer() _loop = () -> return done.resolve() unless condition() Q.when(body(), _loop, done.reject) Q.nextTick(_loop) return done.promise module.exports = Tools
true
### * This file is part of the Konsserto package. * * (c) PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. ### Crypt = use('@Konsserto/Component/Static/Crypt') Q = use('q') # # Tools # # @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # class Tools @STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg @ARGUMENT_NAMES = /([^\s,]+)/g @endsWith:(stack,suffix) -> return stack.indexOf(suffix, stack.length - suffix.length) != -1 @mergeObjects:(obj1,obj2,strict = false) -> obj3 = {}; for k,v of obj1 if strict && k.indexOf('_from') == 0 continue else obj3[k] = v for k,v of obj2 if strict && k.indexOf('_from') == 0 continue else obj3[k] = v return obj3 @firstKey:(obj1) -> for k,v of obj1 return k @removeExt:(stack,ext) -> pos = stack.lastIndexOf(ext); return stack.substr(0,pos) @searchAndReplace:(oldValue,newValue,tab,lowercase) -> outTab = [] for item in tab if lowercase if item.toLowerCase() == oldValue.toLowerCase() outTab.push(newValue) else outTab.push(item) else if item == oldValue outTab.push(newValue) else outTab.push(item) return outTab @toStringObject:(obj1) -> out = '' for k,v of obj1 console.log(k+' '+v) out += k+v return out @toKeyObject:(obj1) -> return Crypt.md5(@toStringObject(obj1)) @cloneObject:(obj) -> if not obj? or typeof obj isnt 'object' return obj if obj instanceof Date return new Date(obj.getTime()) if obj instanceof RegExp flags = '' flags += 'g' if obj.global? flags += 'i' if obj.ignoreCase? flags += 'm' if obj.multiline? flags += 'y' if obj.sticky? return new RegExp(obj.source, flags) newInstance = new obj.constructor() for key of obj newInstance[key] = @cloneObject obj[key] return newInstance @extend = (a, b) -> for i of b g = b.__lookupGetter__(i) s = b.__lookupSetter__(i) if g or s a.__defineGetter__ i, g a.__defineSetter__ i, s else a[i] = b[i] return a @toArray:(object) -> tmp_array = [] for key,value of object tmp_array.push(object[key]); return tmp_array @isInt:(str) -> return (str+'').match('^([0-9]+)$') @millis:() -> now = new Date().getTime() / 1000 seconds = parseInt(now,10) return parseInt(seconds+''+Math.round((now - seconds) * 1000)) @ucfirst:(str, tolower = false) -> str += '' f = str.charAt(0).toUpperCase(); if tolower return f + str.substr(1).toLowerCase() return f + str.substr(1); @sortObject:(object) -> return `(function(s){var t={};Object.keys(s).sort().forEach(function(k){t[k]=s[k]});return t})(object)` @replaceFinalOccurence:(haystack, needle, replacement = '') -> return haystack.substr(0,haystack.lastIndexOf(needle)) + replacement @getFunctionParameters:(func) -> fnStr = func.toString().replace(Tools.STRIP_COMMENTS, '') result = fnStr.slice(fnStr.indexOf('(')+1, fnStr.indexOf(')')).match(Tools.ARGUMENT_NAMES) if !result? result = [] return result @camelCase:(input,ucfirst = false) -> words = input.split(/[-_.]/) if words? && words.length >0 out = if ucfirst then Tools.ucfirst(words.shift(),true) else words.shift() for word in words out += Tools.ucfirst(word,true) return out else return '' @call:(cb, parameters) -> func = undefined if typeof cb is "string" func = (if (typeof this[cb] is "function") then this[cb] else func = (new Function(null, "return " + cb))()) else if Object::toString.call(cb) is "[object Array]" func = (if (typeof cb[0] is "string") then eval(cb[0] + "['" + cb[1] + "']") else func = cb[0][cb[1]]) else func = cb if typeof cb is "function" throw new Error(func + " is not a valid function") if typeof func isnt "function" (if (typeof cb[0] is "string") then func.apply(eval(cb[0]), parameters) else (if (typeof cb[0] isnt "object") then func.apply(null, parameters) else func.apply(cb[0], parameters))) @strstr:(haysack,needle) -> column = 0 haystack += '' column = haystack.indexOf(needle) return if column == -1 then false else haystack.slice(column) @strtr = (string, from, to) -> length = 0 hash = new Array() tmp = "" if from.length < to.length length = from.length else length = to.length i = 0 while i < length hash[from.charAt(i)] = to.charAt(i) i++ j = 0 while j < string.length c = string.charAt(j) if hash[c] tmp = tmp + hash[string.charAt(j)] else tmp = tmp + c j++ tmp @array_unique:(array) -> unique = [] for i in [1..array.length] if (unique.indexOf(array[i]) == -1) unique.push(array[i]) return unique; @promiseWhile: (condition, body) -> done = Q.defer() _loop = () -> return done.resolve() unless condition() Q.when(body(), _loop, done.reject) Q.nextTick(_loop) return done.promise module.exports = Tools
[ { "context": "###\n @author Curtis M. Humphrey, Ph.D.\n \n The files adds a KO binding for Morf\n", "end": 32, "score": 0.999880313873291, "start": 14, "tag": "NAME", "value": "Curtis M. Humphrey" }, { "context": "ockoutjs\n Morf - from Morf (https://github.com/joelambert/morf)...
bower_components/kox_morf/kox_morf.coffee
CurtisHumphrey/mobile_class_2014
1
### @author Curtis M. Humphrey, Ph.D. The files adds a KO binding for Morf Dependence (from global namespace): ko - knockoutjs Morf - from Morf (https://github.com/joelambert/morf) Public API, Fired Events, or Exports export on ko as a new binding e.g., data-bind="morf: value" where value = css: "", parameters: "" from morf documentation ### define (require) -> ko = require 'knockout' Morf = require 'morf' has_morf = '__ko_has_morf' ko.bindingHandlers.morf = # This will be called once when the binding is first applied to an element, # and again whenever the associated observable changes value. # Update the DOM element based on the supplied values here. update: (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) -> element[has_morf] = false ##valueAccessor should be object {css {}, parameters {}} value = ko.utils.unwrapObservable(valueAccessor()); if value element[has_morf] = Morf.transition element, value.css, value.parameters
87692
### @author <NAME>, Ph.D. The files adds a KO binding for Morf Dependence (from global namespace): ko - knockoutjs Morf - from Morf (https://github.com/joelambert/morf) Public API, Fired Events, or Exports export on ko as a new binding e.g., data-bind="morf: value" where value = css: "", parameters: "" from morf documentation ### define (require) -> ko = require 'knockout' Morf = require 'morf' has_morf = '__ko_has_morf' ko.bindingHandlers.morf = # This will be called once when the binding is first applied to an element, # and again whenever the associated observable changes value. # Update the DOM element based on the supplied values here. update: (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) -> element[has_morf] = false ##valueAccessor should be object {css {}, parameters {}} value = ko.utils.unwrapObservable(valueAccessor()); if value element[has_morf] = Morf.transition element, value.css, value.parameters
true
### @author PI:NAME:<NAME>END_PI, Ph.D. The files adds a KO binding for Morf Dependence (from global namespace): ko - knockoutjs Morf - from Morf (https://github.com/joelambert/morf) Public API, Fired Events, or Exports export on ko as a new binding e.g., data-bind="morf: value" where value = css: "", parameters: "" from morf documentation ### define (require) -> ko = require 'knockout' Morf = require 'morf' has_morf = '__ko_has_morf' ko.bindingHandlers.morf = # This will be called once when the binding is first applied to an element, # and again whenever the associated observable changes value. # Update the DOM element based on the supplied values here. update: (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) -> element[has_morf] = false ##valueAccessor should be object {css {}, parameters {}} value = ko.utils.unwrapObservable(valueAccessor()); if value element[has_morf] = Morf.transition element, value.css, value.parameters
[ { "context": ", expireTime = null,\n isOpen = true, password = null, isExam = false,\n examPassword = null, useBlac", "end": 1220, "score": 0.9719780683517456, "start": 1216, "tag": "PASSWORD", "value": "null" }, { "context": "xpireTime\n @isOpen = isOpen\n @password ...
model.coffee
AlynxZhou/coffee-danmaku-server
6
fs = require("fs") Promise = require("bluebird") fp = require("fastify-plugin") module.exports = fp((fastify, opts, next) -> {redis} = fastify Promise.promisifyAll(redis) class Danmaku constructor: (content = "", color = "white", position = "fly", offset = Date.now()) -> @content = content @color = color @position = position @offset = offset if content instanceof Object @content = content["content"] @color = content["color"] @position = content["position"] if content["offset"]? @offset = content["offset"] else if content instanceof String @fromString(content) if @content.length > 234 @content = @content.substring(0, 234) toString: () => return JSON.stringify({ "content": @content, "color": @color, "position": @position, "offset": @offset }) fromString: (json) => obj = JSON.parse(json) @content = obj["content"] @color = obj["color"] @position = obj["position"] if obj["offset"]? @time = obj["offset"] class Channel constructor: (name, desc, expireTime = null, isOpen = true, password = null, isExam = false, examPassword = null, useBlacklist = false) -> @redis = redis @name = name @desc = desc @expireTime = expireTime @isOpen = isOpen @password = password @isExam = isExam @examPassword = examPassword @useBlacklist = useBlacklist @url = "/channel/#{@name}" @channelKey = "channel_#{@name}" @ipTime = {} @examDanmakus = [] toValue: () => return { "name": @name, "desc": @desc, "expireTime": @expireTime, "isOpen": @isOpen, "isExam": @isExam, "url": @url, "useBlacklist": @useBlacklist } isExpired: () => if @expireTime? and Date.now() > @expireTime return true return false pushDanmaku: (danmaku) => return @redis.zaddAsync(@channelKey, danmaku["offset"], danmaku.toString()) getDanmakus: (offset) => return @redis.zrangebyscoreAsync(@channelKey, offset, Date.now()) pushExamDanmaku: (danmaku) => @examDanmakus.push(danmaku) return 1 getExamDanmakus: () => edmks = @examDanmakus @examDanmakus = [] return edmks delete: () => return @redis.delAsync(@channelKey) class ChannelManager constructor: () -> @channels = [] @addChannel(new Channel("demo", "test")) addChannel: (channel) => @cleanChannels() @channels.push(channel) getChannelByName: (name) => @cleanChannels() for c in @channels if c.name is name return c return null cleanChannels: () => for i in [0...@channels.length] if @channels[i].isExpired() @channels[i].delete() @channels.splice(i, 1) listChannelValue: () => @cleanChannels() result = [] for c in @channels result.push(c.toValue()) return result toString: () => tmp = [] for c in @channels tmp.push({ "name": c.name, "desc": c.desc, "expireTime": c.expireTime, "isOpen": c.isOpen, "password": c.password, "isExam": c.isExam, "examPassword": c.examPassword, "useBlacklist": c.useBlacklist }) return JSON.stringify({"channels": tmp}, null, " ") fromString: (json) => tmp = JSON.parse(json)["channels"] if not tmp? return @channels = [] for c in tmp @addChannel(new Channel(c.name, c.desc, c.expireTime, c.isOpen, c.password, c.isExam, c.examPassword, c.useBlacklist)) if not @getChannelByName("demo")? @addChannel(new Channel("demo", "test")) fastify.decorate("channelManager", new ChannelManager()) fastify.decorate("Channel", Channel) fastify.decorate("Danmaku", Danmaku) fs.readFile("blacklist.txt", "utf8", (err, result) -> if err console.error(err) else blacklist = new RegExp(result) fastify.decorate("blacklist", blacklist) next() ) )
12808
fs = require("fs") Promise = require("bluebird") fp = require("fastify-plugin") module.exports = fp((fastify, opts, next) -> {redis} = fastify Promise.promisifyAll(redis) class Danmaku constructor: (content = "", color = "white", position = "fly", offset = Date.now()) -> @content = content @color = color @position = position @offset = offset if content instanceof Object @content = content["content"] @color = content["color"] @position = content["position"] if content["offset"]? @offset = content["offset"] else if content instanceof String @fromString(content) if @content.length > 234 @content = @content.substring(0, 234) toString: () => return JSON.stringify({ "content": @content, "color": @color, "position": @position, "offset": @offset }) fromString: (json) => obj = JSON.parse(json) @content = obj["content"] @color = obj["color"] @position = obj["position"] if obj["offset"]? @time = obj["offset"] class Channel constructor: (name, desc, expireTime = null, isOpen = true, password = <PASSWORD>, isExam = false, examPassword = null, useBlacklist = false) -> @redis = redis @name = name @desc = desc @expireTime = expireTime @isOpen = isOpen @password = <PASSWORD> @isExam = isExam @examPassword = <PASSWORD>Password @useBlacklist = useBlacklist @url = "/channel/#{@name}" @channelKey = "channel_#{@name}" @ipTime = {} @examDanmakus = [] toValue: () => return { "name": @name, "desc": @desc, "expireTime": @expireTime, "isOpen": @isOpen, "isExam": @isExam, "url": @url, "useBlacklist": @useBlacklist } isExpired: () => if @expireTime? and Date.now() > @expireTime return true return false pushDanmaku: (danmaku) => return @redis.zaddAsync(@channelKey, danmaku["offset"], danmaku.toString()) getDanmakus: (offset) => return @redis.zrangebyscoreAsync(@channelKey, offset, Date.now()) pushExamDanmaku: (danmaku) => @examDanmakus.push(danmaku) return 1 getExamDanmakus: () => edmks = @examDanmakus @examDanmakus = [] return edmks delete: () => return @redis.delAsync(@channelKey) class ChannelManager constructor: () -> @channels = [] @addChannel(new Channel("demo", "test")) addChannel: (channel) => @cleanChannels() @channels.push(channel) getChannelByName: (name) => @cleanChannels() for c in @channels if c.name is name return c return null cleanChannels: () => for i in [0...@channels.length] if @channels[i].isExpired() @channels[i].delete() @channels.splice(i, 1) listChannelValue: () => @cleanChannels() result = [] for c in @channels result.push(c.toValue()) return result toString: () => tmp = [] for c in @channels tmp.push({ "name": c.name, "desc": c.desc, "expireTime": c.expireTime, "isOpen": c.isOpen, "password": <PASSWORD>, "isExam": c.isExam, "examPassword": <PASSWORD>, "useBlacklist": c.useBlacklist }) return JSON.stringify({"channels": tmp}, null, " ") fromString: (json) => tmp = JSON.parse(json)["channels"] if not tmp? return @channels = [] for c in tmp @addChannel(new Channel(c.name, c.desc, c.expireTime, c.isOpen, c.password, c.isExam, c.examPassword, c.useBlacklist)) if not @getChannelByName("demo")? @addChannel(new Channel("demo", "test")) fastify.decorate("channelManager", new ChannelManager()) fastify.decorate("Channel", Channel) fastify.decorate("Danmaku", Danmaku) fs.readFile("blacklist.txt", "utf8", (err, result) -> if err console.error(err) else blacklist = new RegExp(result) fastify.decorate("blacklist", blacklist) next() ) )
true
fs = require("fs") Promise = require("bluebird") fp = require("fastify-plugin") module.exports = fp((fastify, opts, next) -> {redis} = fastify Promise.promisifyAll(redis) class Danmaku constructor: (content = "", color = "white", position = "fly", offset = Date.now()) -> @content = content @color = color @position = position @offset = offset if content instanceof Object @content = content["content"] @color = content["color"] @position = content["position"] if content["offset"]? @offset = content["offset"] else if content instanceof String @fromString(content) if @content.length > 234 @content = @content.substring(0, 234) toString: () => return JSON.stringify({ "content": @content, "color": @color, "position": @position, "offset": @offset }) fromString: (json) => obj = JSON.parse(json) @content = obj["content"] @color = obj["color"] @position = obj["position"] if obj["offset"]? @time = obj["offset"] class Channel constructor: (name, desc, expireTime = null, isOpen = true, password = PI:PASSWORD:<PASSWORD>END_PI, isExam = false, examPassword = null, useBlacklist = false) -> @redis = redis @name = name @desc = desc @expireTime = expireTime @isOpen = isOpen @password = PI:PASSWORD:<PASSWORD>END_PI @isExam = isExam @examPassword = PI:PASSWORD:<PASSWORD>END_PIPassword @useBlacklist = useBlacklist @url = "/channel/#{@name}" @channelKey = "channel_#{@name}" @ipTime = {} @examDanmakus = [] toValue: () => return { "name": @name, "desc": @desc, "expireTime": @expireTime, "isOpen": @isOpen, "isExam": @isExam, "url": @url, "useBlacklist": @useBlacklist } isExpired: () => if @expireTime? and Date.now() > @expireTime return true return false pushDanmaku: (danmaku) => return @redis.zaddAsync(@channelKey, danmaku["offset"], danmaku.toString()) getDanmakus: (offset) => return @redis.zrangebyscoreAsync(@channelKey, offset, Date.now()) pushExamDanmaku: (danmaku) => @examDanmakus.push(danmaku) return 1 getExamDanmakus: () => edmks = @examDanmakus @examDanmakus = [] return edmks delete: () => return @redis.delAsync(@channelKey) class ChannelManager constructor: () -> @channels = [] @addChannel(new Channel("demo", "test")) addChannel: (channel) => @cleanChannels() @channels.push(channel) getChannelByName: (name) => @cleanChannels() for c in @channels if c.name is name return c return null cleanChannels: () => for i in [0...@channels.length] if @channels[i].isExpired() @channels[i].delete() @channels.splice(i, 1) listChannelValue: () => @cleanChannels() result = [] for c in @channels result.push(c.toValue()) return result toString: () => tmp = [] for c in @channels tmp.push({ "name": c.name, "desc": c.desc, "expireTime": c.expireTime, "isOpen": c.isOpen, "password": PI:PASSWORD:<PASSWORD>END_PI, "isExam": c.isExam, "examPassword": PI:PASSWORD:<PASSWORD>END_PI, "useBlacklist": c.useBlacklist }) return JSON.stringify({"channels": tmp}, null, " ") fromString: (json) => tmp = JSON.parse(json)["channels"] if not tmp? return @channels = [] for c in tmp @addChannel(new Channel(c.name, c.desc, c.expireTime, c.isOpen, c.password, c.isExam, c.examPassword, c.useBlacklist)) if not @getChannelByName("demo")? @addChannel(new Channel("demo", "test")) fastify.decorate("channelManager", new ChannelManager()) fastify.decorate("Channel", Channel) fastify.decorate("Danmaku", Danmaku) fs.readFile("blacklist.txt", "utf8", (err, result) -> if err console.error(err) else blacklist = new RegExp(result) fastify.decorate("blacklist", blacklist) next() ) )
[ { "context": "\"rsync\",\n options:\n src: \".\"\n host: \"tim@tbranyen.com\"\n recursive: true\n syncDestIgnoreExcl: ", "end": 127, "score": 0.9999300241470337, "start": 111, "tag": "EMAIL", "value": "tim@tbranyen.com" } ]
build/tasks/rsync.coffee
tbranyen/tbranyen.com
3
module.exports = -> @loadNpmTasks "grunt-rsync" @config "rsync", options: src: "." host: "tim@tbranyen.com" recursive: true syncDestIgnoreExcl: true exclude: [ "/.git" "/node_modules" "/content" ] staging: options: dest: "/var/sites/tbranyen.com/subdomains/staging." production: options: dest: "/var/sites/tbranyen.com/www"
121721
module.exports = -> @loadNpmTasks "grunt-rsync" @config "rsync", options: src: "." host: "<EMAIL>" recursive: true syncDestIgnoreExcl: true exclude: [ "/.git" "/node_modules" "/content" ] staging: options: dest: "/var/sites/tbranyen.com/subdomains/staging." production: options: dest: "/var/sites/tbranyen.com/www"
true
module.exports = -> @loadNpmTasks "grunt-rsync" @config "rsync", options: src: "." host: "PI:EMAIL:<EMAIL>END_PI" recursive: true syncDestIgnoreExcl: true exclude: [ "/.git" "/node_modules" "/content" ] staging: options: dest: "/var/sites/tbranyen.com/subdomains/staging." production: options: dest: "/var/sites/tbranyen.com/www"
[ { "context": "\n\nApollos.company.upsert {name: \"Dapper Ink\"},\n $set:\n name: \"Dapper Ink\"\n description", "end": 43, "score": 0.8976413607597351, "start": 33, "tag": "NAME", "value": "Dapper Ink" }, { "context": "y.upsert {name: \"Dapper Ink\"},\n $set:\n name: \"Dap...
_source/server/startup/company.coffee
jbaxleyiii/dapperink
0
Apollos.company.upsert {name: "Dapper Ink"}, $set: name: "Dapper Ink" description: "Welcome to Dapper Ink. We're your one-stop-shop for all things print and design. Working in the beautiful upstate of South Carolina since 2007, we serve our local and regional community by providing top notch artwork and printed goods. With small minimums and complimentary design services, we're the perfect match for providing apparel and accessories for schools, greeks, small businesses, summer camps, and local events. We pride ourselves on creative designs, timely service, and great customer experiences. Almost all of our work is handled start to finish in house, which guarantees our careful attention to detail throughout production." social: [ { name: "facebook" link: "https://www.facebook.com/DapperInk" } { name: "twitter" link: "https://twitter.com/DapperInk" } { name: "instagram" link: "https://instagram.com/DapperInk/" } ] location: street: "207 Wade Hampton Boulevard" city: "Greenville" state: "SC" zip: "29609" phone: "(864) 551-3115" email: "hello@dapperink.com" contactEmail: "hello@dapperink.com" adminEmail: "matt@dapperink.com" services: [ { name: "screen printing" label: "Screen Printing" template: "service" url: [ "/" "/apparel" "/screen-printing" "/screen%20printing" ] } { name: "letter press" label: "Letter Press" template: "service" url: [ "/letterpress" "/letter-press" "/letter%20press" ] } { name: "custom printing" label: "Custom Printing" template: "service" url: [ "/customprinting" "/custom-printing" "/custom%20printing" ] } ]
102952
Apollos.company.upsert {name: "<NAME>"}, $set: name: "<NAME>" description: "Welcome to <NAME>. We're your one-stop-shop for all things print and design. Working in the beautiful upstate of South Carolina since 2007, we serve our local and regional community by providing top notch artwork and printed goods. With small minimums and complimentary design services, we're the perfect match for providing apparel and accessories for schools, greeks, small businesses, summer camps, and local events. We pride ourselves on creative designs, timely service, and great customer experiences. Almost all of our work is handled start to finish in house, which guarantees our careful attention to detail throughout production." social: [ { name: "facebook" link: "https://www.facebook.com/DapperInk" } { name: "twitter" link: "https://twitter.com/DapperInk" } { name: "instagram" link: "https://instagram.com/DapperInk/" } ] location: street: "207 Wade Hampton Boulevard" city: "Greenville" state: "SC" zip: "29609" phone: "(864) 551-3115" email: "<EMAIL>" contactEmail: "<EMAIL>" adminEmail: "<EMAIL>" services: [ { name: "screen printing" label: "Screen Printing" template: "service" url: [ "/" "/apparel" "/screen-printing" "/screen%20printing" ] } { name: "letter press" label: "Letter Press" template: "service" url: [ "/letterpress" "/letter-press" "/letter%20press" ] } { name: "custom printing" label: "Custom Printing" template: "service" url: [ "/customprinting" "/custom-printing" "/custom%20printing" ] } ]
true
Apollos.company.upsert {name: "PI:NAME:<NAME>END_PI"}, $set: name: "PI:NAME:<NAME>END_PI" description: "Welcome to PI:NAME:<NAME>END_PI. We're your one-stop-shop for all things print and design. Working in the beautiful upstate of South Carolina since 2007, we serve our local and regional community by providing top notch artwork and printed goods. With small minimums and complimentary design services, we're the perfect match for providing apparel and accessories for schools, greeks, small businesses, summer camps, and local events. We pride ourselves on creative designs, timely service, and great customer experiences. Almost all of our work is handled start to finish in house, which guarantees our careful attention to detail throughout production." social: [ { name: "facebook" link: "https://www.facebook.com/DapperInk" } { name: "twitter" link: "https://twitter.com/DapperInk" } { name: "instagram" link: "https://instagram.com/DapperInk/" } ] location: street: "207 Wade Hampton Boulevard" city: "Greenville" state: "SC" zip: "29609" phone: "(864) 551-3115" email: "PI:EMAIL:<EMAIL>END_PI" contactEmail: "PI:EMAIL:<EMAIL>END_PI" adminEmail: "PI:EMAIL:<EMAIL>END_PI" services: [ { name: "screen printing" label: "Screen Printing" template: "service" url: [ "/" "/apparel" "/screen-printing" "/screen%20printing" ] } { name: "letter press" label: "Letter Press" template: "service" url: [ "/letterpress" "/letter-press" "/letter%20press" ] } { name: "custom printing" label: "Custom Printing" template: "service" url: [ "/customprinting" "/custom-printing" "/custom%20printing" ] } ]
[ { "context": "ion : false\n port: 587\n auth :\n user: 'postmaster@sandboxc57ee3cd15174479a4cbb190a16016aa.mailgun.org'\n pass: '1e6d200349ec37b81317c862cb7d24a3'\ne", "end": 438, "score": 0.999775230884552, "start": 376, "tag": "EMAIL", "value": "postmaster@sandboxc57ee3cd15...
api/src/logger.coffee
MollardMichael/scrumble
27
moment = require 'moment' nodemailer = require 'nodemailer' smtpTransport = require 'nodemailer-smtp-transport' if process.env.SMTP_HOST and process.env.SMTP_USER and process.env.SMTP_PASS and process.env.EMAIL_CONTACT smtpTransport = nodemailer.createTransport smtpTransport host : 'smtp.mailgun.org' secureConnection : false port: 587 auth : user: 'postmaster@sandboxc57ee3cd15174479a4cbb190a16016aa.mailgun.org' pass: '1e6d200349ec37b81317c862cb7d24a3' else smtpTransport = sendMail: -> return module.exports = log: console.log error: console.error info: console.info warning: console.warn logRequest: (req) -> console.info "[#{moment().format()}][#{req.method}] #{req.originalUrl}" email: (subject, content, next) -> console.log "[#{moment().format()}][POST EMAIL] #{subject}" smtpTransport.sendMail from: 'alerts@scrumble.io' to: process.env.EMAIL_CONTACT subject: subject text: content , (er) -> if er console.error er next()
182445
moment = require 'moment' nodemailer = require 'nodemailer' smtpTransport = require 'nodemailer-smtp-transport' if process.env.SMTP_HOST and process.env.SMTP_USER and process.env.SMTP_PASS and process.env.EMAIL_CONTACT smtpTransport = nodemailer.createTransport smtpTransport host : 'smtp.mailgun.org' secureConnection : false port: 587 auth : user: '<EMAIL>' pass: '<PASSWORD>' else smtpTransport = sendMail: -> return module.exports = log: console.log error: console.error info: console.info warning: console.warn logRequest: (req) -> console.info "[#{moment().format()}][#{req.method}] #{req.originalUrl}" email: (subject, content, next) -> console.log "[#{moment().format()}][POST EMAIL] #{subject}" smtpTransport.sendMail from: '<EMAIL>' to: process.env.EMAIL_CONTACT subject: subject text: content , (er) -> if er console.error er next()
true
moment = require 'moment' nodemailer = require 'nodemailer' smtpTransport = require 'nodemailer-smtp-transport' if process.env.SMTP_HOST and process.env.SMTP_USER and process.env.SMTP_PASS and process.env.EMAIL_CONTACT smtpTransport = nodemailer.createTransport smtpTransport host : 'smtp.mailgun.org' secureConnection : false port: 587 auth : user: 'PI:EMAIL:<EMAIL>END_PI' pass: 'PI:PASSWORD:<PASSWORD>END_PI' else smtpTransport = sendMail: -> return module.exports = log: console.log error: console.error info: console.info warning: console.warn logRequest: (req) -> console.info "[#{moment().format()}][#{req.method}] #{req.originalUrl}" email: (subject, content, next) -> console.log "[#{moment().format()}][POST EMAIL] #{subject}" smtpTransport.sendMail from: 'PI:EMAIL:<EMAIL>END_PI' to: process.env.EMAIL_CONTACT subject: subject text: content , (er) -> if er console.error er next()
[ { "context": "---------------------------------\n# Copyright 2013 Patrick Mueller\n#\n# Licensed under the Apache License, Version 2.", "end": 1449, "score": 0.9998195767402649, "start": 1434, "tag": "NAME", "value": "Patrick Mueller" } ]
test/test-dirs.coffee
pmuellr/cat-source-map
1
# Licensed under the Apache License. See footer for details. path = require "path" _ = require "underscore" expect = require "expect.js" utils = require "./utils" csm = require "../lib/cat-source-map" testName = (path.basename __filename).split(".")[0] testDir = path.join "tmp", testName #------------------------------------------------------------------------------- describe "directory support", -> before -> utils.cleanDir testDir cd testDir mkdir "-p", "src" cp "../../*sample*", "src" after -> cd "../.." it "should handle one JavaScript files in a subdirectory", (done) -> utils.coffeec "src/sample_01.coffee" utils.cat_source_map "src/sample_01.js src/sample_01_c.js" cp "src/sample_01_c.js.map.json", "." cmp = utils.compareMaps testName, "sample_01_c" expect(cmp).to.be true done() it "should handle two CoffeeScript files in a subdirectory", (done) -> utils.coffeec "--map src/sample_01.coffee" utils.coffeec "--map src/sample_02.coffee" utils.cat_source_map "src/sample_01.js src/sample_02.js src/sample_01_02_c.js" cp "src/sample_01_02_c.js.map.json", "." cmp = utils.compareMaps testName, "sample_01_02_c" expect(cmp).to.be true done() #------------------------------------------------------------------------------- # Copyright 2013 Patrick Mueller # # 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. #-------------------------------------------------------------------------------
184481
# Licensed under the Apache License. See footer for details. path = require "path" _ = require "underscore" expect = require "expect.js" utils = require "./utils" csm = require "../lib/cat-source-map" testName = (path.basename __filename).split(".")[0] testDir = path.join "tmp", testName #------------------------------------------------------------------------------- describe "directory support", -> before -> utils.cleanDir testDir cd testDir mkdir "-p", "src" cp "../../*sample*", "src" after -> cd "../.." it "should handle one JavaScript files in a subdirectory", (done) -> utils.coffeec "src/sample_01.coffee" utils.cat_source_map "src/sample_01.js src/sample_01_c.js" cp "src/sample_01_c.js.map.json", "." cmp = utils.compareMaps testName, "sample_01_c" expect(cmp).to.be true done() it "should handle two CoffeeScript files in a subdirectory", (done) -> utils.coffeec "--map src/sample_01.coffee" utils.coffeec "--map src/sample_02.coffee" utils.cat_source_map "src/sample_01.js src/sample_02.js src/sample_01_02_c.js" cp "src/sample_01_02_c.js.map.json", "." cmp = utils.compareMaps testName, "sample_01_02_c" expect(cmp).to.be true done() #------------------------------------------------------------------------------- # Copyright 2013 <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #-------------------------------------------------------------------------------
true
# Licensed under the Apache License. See footer for details. path = require "path" _ = require "underscore" expect = require "expect.js" utils = require "./utils" csm = require "../lib/cat-source-map" testName = (path.basename __filename).split(".")[0] testDir = path.join "tmp", testName #------------------------------------------------------------------------------- describe "directory support", -> before -> utils.cleanDir testDir cd testDir mkdir "-p", "src" cp "../../*sample*", "src" after -> cd "../.." it "should handle one JavaScript files in a subdirectory", (done) -> utils.coffeec "src/sample_01.coffee" utils.cat_source_map "src/sample_01.js src/sample_01_c.js" cp "src/sample_01_c.js.map.json", "." cmp = utils.compareMaps testName, "sample_01_c" expect(cmp).to.be true done() it "should handle two CoffeeScript files in a subdirectory", (done) -> utils.coffeec "--map src/sample_01.coffee" utils.coffeec "--map src/sample_02.coffee" utils.cat_source_map "src/sample_01.js src/sample_02.js src/sample_01_02_c.js" cp "src/sample_01_02_c.js.map.json", "." cmp = utils.compareMaps testName, "sample_01_02_c" expect(cmp).to.be true done() #------------------------------------------------------------------------------- # Copyright 2013 PI:NAME:<NAME>END_PI # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #-------------------------------------------------------------------------------
[ { "context": " undefined, dev\n\n API.mail.send\n to: 'alert@cottagelabs.com'\n subject: 'User fix complete'\n tex", "end": 2142, "score": 0.9999259114265442, "start": 2121, "tag": "EMAIL", "value": "alert@cottagelabs.com" } ]
noddy/service/v2/scripts/cleanusers.coffee
oaworks/API
2
API.add 'service/oab/scripts/useres', get: action: () -> dev = if this.queryParams.live is true then false else true counter = 0 cased = 0 dups = 0 _ck = (rec) -> counter += 1 try eml = rec.email ? rec.emails[0].address cased += 1 if eml.toLowerCase() isnt eml dups += 1 if Users.count(undefined, 'email:"' + eml + '" OR emails.address:"' + eml + '"', dev) > 1 console.log counter, cased, dups Users.each '*', undefined, _ck, undefined, undefined, undefined, dev return total: counter, cased: cased, duplicates: dups '''API.add 'service/oab/scripts/cleanusers', get: #roleRequired: 'root' action: () -> dev = if this.queryParams.live is true then false else true action = if this.queryParams.action? then true else false processed = 0 fixed = 0 _process = (rec) -> processed += 1 upd = {} if rec.service?.openaccessbutton?.ill?.config? if rec.service.openaccessbutton.ill.config.pilot is '$DELETE' upd['service.openaccessbutton.ill.config.pilot'] = '$DELETE' if rec.service.openaccessbutton.ill.config.live is '$DELETE' upd['service.openaccessbutton.ill.config.live'] = '$DELETE' if rec.service?.openaccessbutton?.deposit?.config? if rec.service.openaccessbutton.deposit.config.pilot is '$DELETE' upd['service.openaccessbutton.deposit.config.pilot'] = '$DELETE' if rec.service.openaccessbutton.deposit.config.live is '$DELETE' upd['service.openaccessbutton.deposit.config.live'] = '$DELETE' if not _.isEmpty upd fixed += 1 Users.update(rec._id, upd, undefined, undefined, undefined, undefined, dev) if action Users.each 'service.openaccessbutton.deposit.config.pilot:* OR service.openaccessbutton.deposit.config.live:* OR service.openaccessbutton.ill.config.pilot:* OR service.openaccessbutton.ill.config.live:*', _process, undefined, undefined, undefined, undefined, dev API.mail.send to: 'alert@cottagelabs.com' subject: 'User fix complete' text: 'Users processed: ' + processed + '\n\nUsers found and fixed: ' + fixed return dev: dev, action: action, processed: processed, fixed: fixed '''
14154
API.add 'service/oab/scripts/useres', get: action: () -> dev = if this.queryParams.live is true then false else true counter = 0 cased = 0 dups = 0 _ck = (rec) -> counter += 1 try eml = rec.email ? rec.emails[0].address cased += 1 if eml.toLowerCase() isnt eml dups += 1 if Users.count(undefined, 'email:"' + eml + '" OR emails.address:"' + eml + '"', dev) > 1 console.log counter, cased, dups Users.each '*', undefined, _ck, undefined, undefined, undefined, dev return total: counter, cased: cased, duplicates: dups '''API.add 'service/oab/scripts/cleanusers', get: #roleRequired: 'root' action: () -> dev = if this.queryParams.live is true then false else true action = if this.queryParams.action? then true else false processed = 0 fixed = 0 _process = (rec) -> processed += 1 upd = {} if rec.service?.openaccessbutton?.ill?.config? if rec.service.openaccessbutton.ill.config.pilot is '$DELETE' upd['service.openaccessbutton.ill.config.pilot'] = '$DELETE' if rec.service.openaccessbutton.ill.config.live is '$DELETE' upd['service.openaccessbutton.ill.config.live'] = '$DELETE' if rec.service?.openaccessbutton?.deposit?.config? if rec.service.openaccessbutton.deposit.config.pilot is '$DELETE' upd['service.openaccessbutton.deposit.config.pilot'] = '$DELETE' if rec.service.openaccessbutton.deposit.config.live is '$DELETE' upd['service.openaccessbutton.deposit.config.live'] = '$DELETE' if not _.isEmpty upd fixed += 1 Users.update(rec._id, upd, undefined, undefined, undefined, undefined, dev) if action Users.each 'service.openaccessbutton.deposit.config.pilot:* OR service.openaccessbutton.deposit.config.live:* OR service.openaccessbutton.ill.config.pilot:* OR service.openaccessbutton.ill.config.live:*', _process, undefined, undefined, undefined, undefined, dev API.mail.send to: '<EMAIL>' subject: 'User fix complete' text: 'Users processed: ' + processed + '\n\nUsers found and fixed: ' + fixed return dev: dev, action: action, processed: processed, fixed: fixed '''
true
API.add 'service/oab/scripts/useres', get: action: () -> dev = if this.queryParams.live is true then false else true counter = 0 cased = 0 dups = 0 _ck = (rec) -> counter += 1 try eml = rec.email ? rec.emails[0].address cased += 1 if eml.toLowerCase() isnt eml dups += 1 if Users.count(undefined, 'email:"' + eml + '" OR emails.address:"' + eml + '"', dev) > 1 console.log counter, cased, dups Users.each '*', undefined, _ck, undefined, undefined, undefined, dev return total: counter, cased: cased, duplicates: dups '''API.add 'service/oab/scripts/cleanusers', get: #roleRequired: 'root' action: () -> dev = if this.queryParams.live is true then false else true action = if this.queryParams.action? then true else false processed = 0 fixed = 0 _process = (rec) -> processed += 1 upd = {} if rec.service?.openaccessbutton?.ill?.config? if rec.service.openaccessbutton.ill.config.pilot is '$DELETE' upd['service.openaccessbutton.ill.config.pilot'] = '$DELETE' if rec.service.openaccessbutton.ill.config.live is '$DELETE' upd['service.openaccessbutton.ill.config.live'] = '$DELETE' if rec.service?.openaccessbutton?.deposit?.config? if rec.service.openaccessbutton.deposit.config.pilot is '$DELETE' upd['service.openaccessbutton.deposit.config.pilot'] = '$DELETE' if rec.service.openaccessbutton.deposit.config.live is '$DELETE' upd['service.openaccessbutton.deposit.config.live'] = '$DELETE' if not _.isEmpty upd fixed += 1 Users.update(rec._id, upd, undefined, undefined, undefined, undefined, dev) if action Users.each 'service.openaccessbutton.deposit.config.pilot:* OR service.openaccessbutton.deposit.config.live:* OR service.openaccessbutton.ill.config.pilot:* OR service.openaccessbutton.ill.config.live:*', _process, undefined, undefined, undefined, undefined, dev API.mail.send to: 'PI:EMAIL:<EMAIL>END_PI' subject: 'User fix complete' text: 'Users processed: ' + processed + '\n\nUsers found and fixed: ' + fixed return dev: dev, action: action, processed: processed, fixed: fixed '''
[ { "context": "ing: false\n \"exception-reporting\":\n userId: \"5516c064-1a60-ca2e-7b05-71c5e27ee570\"\n \"one-dark-ui\": {}\n \"one-light-ui\": {}\n \"tree", "end": 642, "score": 0.6314547061920166, "start": 607, "tag": "PASSWORD", "value": "516c064-1a60-ca2e-7b05-71c5e27ee570" } ]
config.cson
MattMS/my_atom_settings
0
"*": core: audioBeep: false autoHideMenuBar: true disabledPackages: [ "vim-surround" "vim-mode" ] excludeVcsIgnoredPaths: true packagesWithKeymapsDisabled: [ "emmet" ] telemetryConsent: "limited" themes: [ "one-dark-ui" "solarized-dark-syntax" ] warnOnLargeFileLimit: 4 "easy-motion-redux": {} editor: fontFamily: "Ubuntu Mono" fontSize: 16 invisibles: {} showLineNumbers: false softTabs: false softWrap: true tabLength: 4 zoomFontWhenCtrlScrolling: false "exception-reporting": userId: "5516c064-1a60-ca2e-7b05-71c5e27ee570" "one-dark-ui": {} "one-light-ui": {} "tree-view": hideVcsIgnoredFiles: true "vim-mode-plus": flashOnOperate: false flashOnSearch: false flashOnUndoRedo: false flashScreenOnSearchHasNoMatch: false ignoreCaseForSearchCurrentWord: true incrementalSearch: true stayOnTransformString: true stayOnYank: true useClipboardAsDefaultRegister: true useSmartcaseForSearch: true welcome: showOnStartup: false ".python.source": editor: softTabs: false tabLength: 4
91638
"*": core: audioBeep: false autoHideMenuBar: true disabledPackages: [ "vim-surround" "vim-mode" ] excludeVcsIgnoredPaths: true packagesWithKeymapsDisabled: [ "emmet" ] telemetryConsent: "limited" themes: [ "one-dark-ui" "solarized-dark-syntax" ] warnOnLargeFileLimit: 4 "easy-motion-redux": {} editor: fontFamily: "Ubuntu Mono" fontSize: 16 invisibles: {} showLineNumbers: false softTabs: false softWrap: true tabLength: 4 zoomFontWhenCtrlScrolling: false "exception-reporting": userId: "5<PASSWORD>" "one-dark-ui": {} "one-light-ui": {} "tree-view": hideVcsIgnoredFiles: true "vim-mode-plus": flashOnOperate: false flashOnSearch: false flashOnUndoRedo: false flashScreenOnSearchHasNoMatch: false ignoreCaseForSearchCurrentWord: true incrementalSearch: true stayOnTransformString: true stayOnYank: true useClipboardAsDefaultRegister: true useSmartcaseForSearch: true welcome: showOnStartup: false ".python.source": editor: softTabs: false tabLength: 4
true
"*": core: audioBeep: false autoHideMenuBar: true disabledPackages: [ "vim-surround" "vim-mode" ] excludeVcsIgnoredPaths: true packagesWithKeymapsDisabled: [ "emmet" ] telemetryConsent: "limited" themes: [ "one-dark-ui" "solarized-dark-syntax" ] warnOnLargeFileLimit: 4 "easy-motion-redux": {} editor: fontFamily: "Ubuntu Mono" fontSize: 16 invisibles: {} showLineNumbers: false softTabs: false softWrap: true tabLength: 4 zoomFontWhenCtrlScrolling: false "exception-reporting": userId: "5PI:PASSWORD:<PASSWORD>END_PI" "one-dark-ui": {} "one-light-ui": {} "tree-view": hideVcsIgnoredFiles: true "vim-mode-plus": flashOnOperate: false flashOnSearch: false flashOnUndoRedo: false flashScreenOnSearchHasNoMatch: false ignoreCaseForSearchCurrentWord: true incrementalSearch: true stayOnTransformString: true stayOnYank: true useClipboardAsDefaultRegister: true useSmartcaseForSearch: true welcome: showOnStartup: false ".python.source": editor: softTabs: false tabLength: 4
[ { "context": "Mocha-cakes Reference ========\nhttps://github.com/quangv/mocha-cakes\nhttps://github.com/visionmedia/should", "end": 349, "score": 0.9995520710945129, "start": 343, "tag": "USERNAME", "value": "quangv" }, { "context": "/github.com/quangv/mocha-cakes\nhttps://github.com...
src/test/simulator_spec.coffee
NicMcPhee/whooping-crane-model
0
'use strict' require 'mocha-cakes' ModelParameters = require '../lib/model_parameters' Clock = require '../lib/clock' Bird = require '../lib/bird' Nesting = require '../lib/nesting' Population = require '../lib/population' Simulator = require '../lib/simulator' ### ======== A Handy Little Mocha-cakes Reference ======== https://github.com/quangv/mocha-cakes https://github.com/visionmedia/should.js https://github.com/visionmedia/mocha Mocha-cakes: Feature, Scenario: maps to describe Given, When, Then: maps to it, but if first message argument is ommited, it'll be a describe And, But, I: maps to it, but if first message argument is ommited, it'll be a describe Mocha hooks: before ()-> # before describe after ()-> # after describe beforeEach ()-> # before each it afterEach ()-> # after each it Should assertions: should.exist('hello') should.fail('expected an error!') true.should.be.ok true.should.be.true false.should.be.false (()-> arguments)(1,2,3).should.be.arguments [1,2,3].should.eql([1,2,3]) should.strictEqual(undefined, value) user.age.should.be.within(5, 50) username.should.match(/^\w+$/) user.should.be.a('object') [].should.be.an.instanceOf(Array) user.should.have.property('age', 15) user.age.should.be.above(5) user.age.should.be.below(100) user.pets.should.have.length(5) res.should.have.status(200) #res.statusCode should be 200 res.should.be.json res.should.be.html res.should.have.header('Content-Length', '123') [].should.be.empty [1,2,3].should.include(3) 'foo bar baz'.should.include('foo') { name: 'TJ', pet: tobi }.user.should.include({ pet: tobi, name: 'TJ' }) { foo: 'bar', baz: 'raz' }.should.have.keys('foo', 'bar') (()-> throw new Error('failed to baz')).should.throwError(/^fail.+/) user.should.have.property('pets').with.lengthOf(4) user.should.be.a('object').and.have.property('name', 'tj') ### Feature "Simulation", "In order to model crane populations", "as a modeler", "I need to be able to run the annual simulation loop", -> Scenario "Run one generation, all one-year old", -> before -> Clock.reset() numInitialBirds = 200 simulator = null expectedMortality = numInitialBirds * ModelParameters.matureMortalityRate expectedNewPopSize = numInitialBirds - expectedMortality Given "I construct a population of #{numInitialBirds} \ early nesting birds", -> population = new Population(0) population.addBird(new Bird(Bird.EARLY)) for [0...numInitialBirds] simulator = new Simulator(population) When "I run the simulation for one year", -> simulator.advanceOneYear() Then "the clock has advanced a year", -> Clock.currentYear.should.eql 1 And "the population size is approximately #{expectedNewPopSize}", -> population = simulator.getPopulation() population.birds().length.should.be.approximately expectedNewPopSize, 0.1 * expectedNewPopSize And "no birds are paired", -> population = simulator.getPopulation() population.matingPairs().length.should.eql 0 And "all birds are one year old", -> population = simulator.getPopulation() birds = population.birds() for b in birds b.age().should.eql 1 Scenario false, "Run one generation, all mature early nesters", -> before -> Clock.reset() numInitialBirds = 200 numInitialNests = numInitialBirds // 2 simulator = null expectedNumNewBirds = 6 expectedSurvivingNewBirds = expectedNumNewBirds * (1 - ModelParameters.firstYearMortalityRate) expectedMortality = expectedNumNewBirds * ModelParameters.firstYearMortalityRate + numInitialBirds * ModelParameters.matureMortalityRate expectedNewPopSize = numInitialBirds + expectedNumNewBirds - expectedMortality brokenNestProbability = ModelParameters.matureMortalityRate + (1 - ModelParameters.matureMortalityRate) * ModelParameters.matureMortalityRate expectedBrokenNests = numInitialNests * brokenNestProbability expectedRemainingNests = numInitialNests - expectedBrokenNests expectedUnpairedBirds = expectedSurvivingNewBirds + expectedBrokenNests Given "I construct a population of #{numInitialBirds} \ early nesting birds", -> population = new Population(0) population.addBird(new Bird(Bird.EARLY)) for [0...numInitialBirds] simulator = new Simulator(population) And "I advance the clock #{ModelParameters.pairingAge} years", -> Clock.setYear(ModelParameters.pairingAge) Clock.currentYear.should.eql ModelParameters.pairingAge When "I run the simulation for one year", -> simulator.advanceOneYear() Then "the clock has advanced a year", -> Clock.currentYear.should.eql (ModelParameters.pairingAge+1) And "the population size is approximately #{expectedNewPopSize}", -> population = simulator.getPopulation() population.birds().length.should.be.approximately expectedNewPopSize, 0.1 * expectedNewPopSize And "most of the birds are paired", -> population = simulator.getPopulation() population.matingPairs().length.should.be.approximately( expectedRemainingNests, 0.33 * expectedRemainingNests) population.unpairedBirds().length.should.be.approximately( expectedUnpairedBirds, 0.33 * expectedUnpairedBirds) And "about #{expectedSurvivingNewBirds} birds to have age 0", -> population = simulator.getPopulation() newborns = population.birds().filter((b) -> b.age() is 0) newborns.length.should.be.approximately expectedSurvivingNewBirds, 2 And "several newborns are captive born", -> population = simulator.getPopulation() captiveNewborns = population.birds().filter( (b) -> b.age() is 0 and b.isCaptive()) captiveNewborns.length.should.be.approximately( expectedSurvivingNewBirds, 0.75 * expectedSurvivingNewBirds) And "a few newborns are wild born", -> population = simulator.getPopulation() wildNewborns = population.birds().filter( (b) -> b.age() is 0 and b.isWild()) expected = numInitialNests * ModelParameters.collectionProbability * ModelParameters.renestingProbability * ModelParameters.eggConversionRate * (1 - ModelParameters.firstYearMortalityRate) wildNewborns.length.should.be.approximately(expected, 0.75 * expected) Scenario "Run one generation, all mature late nesters", -> before -> Clock.reset() numInitialBirds = 200 numInitialNests = numInitialBirds // 2 simulator = null expectedNumNewBirds = numInitialNests * ModelParameters.nestingProbability * ModelParameters.eggConversionRate expectedSurvivingNewBirds = expectedNumNewBirds expectedMortality = numInitialBirds * ModelParameters.matureMortalityRate expectedNewPopSize = numInitialBirds + expectedNumNewBirds - expectedMortality brokenNestProbability = ModelParameters.matureMortalityRate + (1 - ModelParameters.matureMortalityRate) * ModelParameters.matureMortalityRate expectedBrokenNests = numInitialNests * brokenNestProbability expectedRemainingNests = numInitialNests - expectedBrokenNests expectedUnpairedBirds = expectedSurvivingNewBirds + expectedBrokenNests Given "I construct a population of #{numInitialBirds} \ early nesting birds", -> population = new Population(0) population.addBird(new Bird(Bird.LATE)) for [0...numInitialBirds] simulator = new Simulator(population) And "I advance the clock #{ModelParameters.pairingAge} years", -> Clock.setYear(ModelParameters.pairingAge) Clock.currentYear.should.eql ModelParameters.pairingAge When "I run the simulation for one year", -> simulator.advanceOneYear() Then "the clock has advanced a year", -> Clock.currentYear.should.eql (ModelParameters.pairingAge+1) And "the population size is approximately #{expectedNewPopSize}", -> population = simulator.getPopulation() population.birds().length.should.be.approximately expectedNewPopSize, 0.1 * expectedNewPopSize And "most of the birds are paired", -> population = simulator.getPopulation() population.matingPairs().length.should.be.approximately( expectedRemainingNests, 0.33 * expectedRemainingNests) population.unpairedBirds().length.should.be.approximately( expectedUnpairedBirds, 0.33 * expectedUnpairedBirds) And "about #{expectedSurvivingNewBirds} birds to have age 0", -> population = simulator.getPopulation() newborns = population.birds().filter((b) -> b.age() is 0) newborns.length.should.be.approximately expectedSurvivingNewBirds, 0.5 * expectedSurvivingNewBirds And "all newborns are wild born", -> population = simulator.getPopulation() newborns = population.birds().filter((b) -> b.age() is 0) newborns.every((b) -> b.howReared().should.eql Bird.WILD_REARED) Scenario "Smoke test of 10 generations", -> before -> Clock.reset() numInitialBirds = 200 simulator = null Given "I construct a population of #{numInitialBirds}, \ half early and half late", -> population = new Population(0) population.addBird(new Bird(Bird.EARLY)) for [0...numInitialBirds // 2] population.addBird(new Bird(Bird.LATE)) for [0...numInitialBirds // 2] simulator = new Simulator(population) When "I run the simulation 10 generations", -> simulator.advanceOneYear() for [0...10] Then "I should still have some birds", -> population = simulator.getPopulation() # console.log(population) population.birds().length.should.be.above 0
139478
'use strict' require 'mocha-cakes' ModelParameters = require '../lib/model_parameters' Clock = require '../lib/clock' Bird = require '../lib/bird' Nesting = require '../lib/nesting' Population = require '../lib/population' Simulator = require '../lib/simulator' ### ======== A Handy Little Mocha-cakes Reference ======== https://github.com/quangv/mocha-cakes https://github.com/visionmedia/should.js https://github.com/visionmedia/mocha Mocha-cakes: Feature, Scenario: maps to describe Given, When, Then: maps to it, but if first message argument is ommited, it'll be a describe And, But, I: maps to it, but if first message argument is ommited, it'll be a describe Mocha hooks: before ()-> # before describe after ()-> # after describe beforeEach ()-> # before each it afterEach ()-> # after each it Should assertions: should.exist('hello') should.fail('expected an error!') true.should.be.ok true.should.be.true false.should.be.false (()-> arguments)(1,2,3).should.be.arguments [1,2,3].should.eql([1,2,3]) should.strictEqual(undefined, value) user.age.should.be.within(5, 50) username.should.match(/^\w+$/) user.should.be.a('object') [].should.be.an.instanceOf(Array) user.should.have.property('age', 15) user.age.should.be.above(5) user.age.should.be.below(100) user.pets.should.have.length(5) res.should.have.status(200) #res.statusCode should be 200 res.should.be.json res.should.be.html res.should.have.header('Content-Length', '123') [].should.be.empty [1,2,3].should.include(3) 'foo bar baz'.should.include('foo') { name: '<NAME>', pet: tobi }.user.should.include({ pet: tobi, name: '<NAME>' }) { foo: 'bar', baz: 'raz' }.should.have.keys('foo', 'bar') (()-> throw new Error('failed to baz')).should.throwError(/^fail.+/) user.should.have.property('pets').with.lengthOf(4) user.should.be.a('object').and.have.property('name', '<NAME>') ### Feature "Simulation", "In order to model crane populations", "as a modeler", "I need to be able to run the annual simulation loop", -> Scenario "Run one generation, all one-year old", -> before -> Clock.reset() numInitialBirds = 200 simulator = null expectedMortality = numInitialBirds * ModelParameters.matureMortalityRate expectedNewPopSize = numInitialBirds - expectedMortality Given "I construct a population of #{numInitialBirds} \ early nesting birds", -> population = new Population(0) population.addBird(new Bird(Bird.EARLY)) for [0...numInitialBirds] simulator = new Simulator(population) When "I run the simulation for one year", -> simulator.advanceOneYear() Then "the clock has advanced a year", -> Clock.currentYear.should.eql 1 And "the population size is approximately #{expectedNewPopSize}", -> population = simulator.getPopulation() population.birds().length.should.be.approximately expectedNewPopSize, 0.1 * expectedNewPopSize And "no birds are paired", -> population = simulator.getPopulation() population.matingPairs().length.should.eql 0 And "all birds are one year old", -> population = simulator.getPopulation() birds = population.birds() for b in birds b.age().should.eql 1 Scenario false, "Run one generation, all mature early nesters", -> before -> Clock.reset() numInitialBirds = 200 numInitialNests = numInitialBirds // 2 simulator = null expectedNumNewBirds = 6 expectedSurvivingNewBirds = expectedNumNewBirds * (1 - ModelParameters.firstYearMortalityRate) expectedMortality = expectedNumNewBirds * ModelParameters.firstYearMortalityRate + numInitialBirds * ModelParameters.matureMortalityRate expectedNewPopSize = numInitialBirds + expectedNumNewBirds - expectedMortality brokenNestProbability = ModelParameters.matureMortalityRate + (1 - ModelParameters.matureMortalityRate) * ModelParameters.matureMortalityRate expectedBrokenNests = numInitialNests * brokenNestProbability expectedRemainingNests = numInitialNests - expectedBrokenNests expectedUnpairedBirds = expectedSurvivingNewBirds + expectedBrokenNests Given "I construct a population of #{numInitialBirds} \ early nesting birds", -> population = new Population(0) population.addBird(new Bird(Bird.EARLY)) for [0...numInitialBirds] simulator = new Simulator(population) And "I advance the clock #{ModelParameters.pairingAge} years", -> Clock.setYear(ModelParameters.pairingAge) Clock.currentYear.should.eql ModelParameters.pairingAge When "I run the simulation for one year", -> simulator.advanceOneYear() Then "the clock has advanced a year", -> Clock.currentYear.should.eql (ModelParameters.pairingAge+1) And "the population size is approximately #{expectedNewPopSize}", -> population = simulator.getPopulation() population.birds().length.should.be.approximately expectedNewPopSize, 0.1 * expectedNewPopSize And "most of the birds are paired", -> population = simulator.getPopulation() population.matingPairs().length.should.be.approximately( expectedRemainingNests, 0.33 * expectedRemainingNests) population.unpairedBirds().length.should.be.approximately( expectedUnpairedBirds, 0.33 * expectedUnpairedBirds) And "about #{expectedSurvivingNewBirds} birds to have age 0", -> population = simulator.getPopulation() newborns = population.birds().filter((b) -> b.age() is 0) newborns.length.should.be.approximately expectedSurvivingNewBirds, 2 And "several newborns are captive born", -> population = simulator.getPopulation() captiveNewborns = population.birds().filter( (b) -> b.age() is 0 and b.isCaptive()) captiveNewborns.length.should.be.approximately( expectedSurvivingNewBirds, 0.75 * expectedSurvivingNewBirds) And "a few newborns are wild born", -> population = simulator.getPopulation() wildNewborns = population.birds().filter( (b) -> b.age() is 0 and b.isWild()) expected = numInitialNests * ModelParameters.collectionProbability * ModelParameters.renestingProbability * ModelParameters.eggConversionRate * (1 - ModelParameters.firstYearMortalityRate) wildNewborns.length.should.be.approximately(expected, 0.75 * expected) Scenario "Run one generation, all mature late nesters", -> before -> Clock.reset() numInitialBirds = 200 numInitialNests = numInitialBirds // 2 simulator = null expectedNumNewBirds = numInitialNests * ModelParameters.nestingProbability * ModelParameters.eggConversionRate expectedSurvivingNewBirds = expectedNumNewBirds expectedMortality = numInitialBirds * ModelParameters.matureMortalityRate expectedNewPopSize = numInitialBirds + expectedNumNewBirds - expectedMortality brokenNestProbability = ModelParameters.matureMortalityRate + (1 - ModelParameters.matureMortalityRate) * ModelParameters.matureMortalityRate expectedBrokenNests = numInitialNests * brokenNestProbability expectedRemainingNests = numInitialNests - expectedBrokenNests expectedUnpairedBirds = expectedSurvivingNewBirds + expectedBrokenNests Given "I construct a population of #{numInitialBirds} \ early nesting birds", -> population = new Population(0) population.addBird(new Bird(Bird.LATE)) for [0...numInitialBirds] simulator = new Simulator(population) And "I advance the clock #{ModelParameters.pairingAge} years", -> Clock.setYear(ModelParameters.pairingAge) Clock.currentYear.should.eql ModelParameters.pairingAge When "I run the simulation for one year", -> simulator.advanceOneYear() Then "the clock has advanced a year", -> Clock.currentYear.should.eql (ModelParameters.pairingAge+1) And "the population size is approximately #{expectedNewPopSize}", -> population = simulator.getPopulation() population.birds().length.should.be.approximately expectedNewPopSize, 0.1 * expectedNewPopSize And "most of the birds are paired", -> population = simulator.getPopulation() population.matingPairs().length.should.be.approximately( expectedRemainingNests, 0.33 * expectedRemainingNests) population.unpairedBirds().length.should.be.approximately( expectedUnpairedBirds, 0.33 * expectedUnpairedBirds) And "about #{expectedSurvivingNewBirds} birds to have age 0", -> population = simulator.getPopulation() newborns = population.birds().filter((b) -> b.age() is 0) newborns.length.should.be.approximately expectedSurvivingNewBirds, 0.5 * expectedSurvivingNewBirds And "all newborns are wild born", -> population = simulator.getPopulation() newborns = population.birds().filter((b) -> b.age() is 0) newborns.every((b) -> b.howReared().should.eql Bird.WILD_REARED) Scenario "Smoke test of 10 generations", -> before -> Clock.reset() numInitialBirds = 200 simulator = null Given "I construct a population of #{numInitialBirds}, \ half early and half late", -> population = new Population(0) population.addBird(new Bird(Bird.EARLY)) for [0...numInitialBirds // 2] population.addBird(new Bird(Bird.LATE)) for [0...numInitialBirds // 2] simulator = new Simulator(population) When "I run the simulation 10 generations", -> simulator.advanceOneYear() for [0...10] Then "I should still have some birds", -> population = simulator.getPopulation() # console.log(population) population.birds().length.should.be.above 0
true
'use strict' require 'mocha-cakes' ModelParameters = require '../lib/model_parameters' Clock = require '../lib/clock' Bird = require '../lib/bird' Nesting = require '../lib/nesting' Population = require '../lib/population' Simulator = require '../lib/simulator' ### ======== A Handy Little Mocha-cakes Reference ======== https://github.com/quangv/mocha-cakes https://github.com/visionmedia/should.js https://github.com/visionmedia/mocha Mocha-cakes: Feature, Scenario: maps to describe Given, When, Then: maps to it, but if first message argument is ommited, it'll be a describe And, But, I: maps to it, but if first message argument is ommited, it'll be a describe Mocha hooks: before ()-> # before describe after ()-> # after describe beforeEach ()-> # before each it afterEach ()-> # after each it Should assertions: should.exist('hello') should.fail('expected an error!') true.should.be.ok true.should.be.true false.should.be.false (()-> arguments)(1,2,3).should.be.arguments [1,2,3].should.eql([1,2,3]) should.strictEqual(undefined, value) user.age.should.be.within(5, 50) username.should.match(/^\w+$/) user.should.be.a('object') [].should.be.an.instanceOf(Array) user.should.have.property('age', 15) user.age.should.be.above(5) user.age.should.be.below(100) user.pets.should.have.length(5) res.should.have.status(200) #res.statusCode should be 200 res.should.be.json res.should.be.html res.should.have.header('Content-Length', '123') [].should.be.empty [1,2,3].should.include(3) 'foo bar baz'.should.include('foo') { name: 'PI:NAME:<NAME>END_PI', pet: tobi }.user.should.include({ pet: tobi, name: 'PI:NAME:<NAME>END_PI' }) { foo: 'bar', baz: 'raz' }.should.have.keys('foo', 'bar') (()-> throw new Error('failed to baz')).should.throwError(/^fail.+/) user.should.have.property('pets').with.lengthOf(4) user.should.be.a('object').and.have.property('name', 'PI:NAME:<NAME>END_PI') ### Feature "Simulation", "In order to model crane populations", "as a modeler", "I need to be able to run the annual simulation loop", -> Scenario "Run one generation, all one-year old", -> before -> Clock.reset() numInitialBirds = 200 simulator = null expectedMortality = numInitialBirds * ModelParameters.matureMortalityRate expectedNewPopSize = numInitialBirds - expectedMortality Given "I construct a population of #{numInitialBirds} \ early nesting birds", -> population = new Population(0) population.addBird(new Bird(Bird.EARLY)) for [0...numInitialBirds] simulator = new Simulator(population) When "I run the simulation for one year", -> simulator.advanceOneYear() Then "the clock has advanced a year", -> Clock.currentYear.should.eql 1 And "the population size is approximately #{expectedNewPopSize}", -> population = simulator.getPopulation() population.birds().length.should.be.approximately expectedNewPopSize, 0.1 * expectedNewPopSize And "no birds are paired", -> population = simulator.getPopulation() population.matingPairs().length.should.eql 0 And "all birds are one year old", -> population = simulator.getPopulation() birds = population.birds() for b in birds b.age().should.eql 1 Scenario false, "Run one generation, all mature early nesters", -> before -> Clock.reset() numInitialBirds = 200 numInitialNests = numInitialBirds // 2 simulator = null expectedNumNewBirds = 6 expectedSurvivingNewBirds = expectedNumNewBirds * (1 - ModelParameters.firstYearMortalityRate) expectedMortality = expectedNumNewBirds * ModelParameters.firstYearMortalityRate + numInitialBirds * ModelParameters.matureMortalityRate expectedNewPopSize = numInitialBirds + expectedNumNewBirds - expectedMortality brokenNestProbability = ModelParameters.matureMortalityRate + (1 - ModelParameters.matureMortalityRate) * ModelParameters.matureMortalityRate expectedBrokenNests = numInitialNests * brokenNestProbability expectedRemainingNests = numInitialNests - expectedBrokenNests expectedUnpairedBirds = expectedSurvivingNewBirds + expectedBrokenNests Given "I construct a population of #{numInitialBirds} \ early nesting birds", -> population = new Population(0) population.addBird(new Bird(Bird.EARLY)) for [0...numInitialBirds] simulator = new Simulator(population) And "I advance the clock #{ModelParameters.pairingAge} years", -> Clock.setYear(ModelParameters.pairingAge) Clock.currentYear.should.eql ModelParameters.pairingAge When "I run the simulation for one year", -> simulator.advanceOneYear() Then "the clock has advanced a year", -> Clock.currentYear.should.eql (ModelParameters.pairingAge+1) And "the population size is approximately #{expectedNewPopSize}", -> population = simulator.getPopulation() population.birds().length.should.be.approximately expectedNewPopSize, 0.1 * expectedNewPopSize And "most of the birds are paired", -> population = simulator.getPopulation() population.matingPairs().length.should.be.approximately( expectedRemainingNests, 0.33 * expectedRemainingNests) population.unpairedBirds().length.should.be.approximately( expectedUnpairedBirds, 0.33 * expectedUnpairedBirds) And "about #{expectedSurvivingNewBirds} birds to have age 0", -> population = simulator.getPopulation() newborns = population.birds().filter((b) -> b.age() is 0) newborns.length.should.be.approximately expectedSurvivingNewBirds, 2 And "several newborns are captive born", -> population = simulator.getPopulation() captiveNewborns = population.birds().filter( (b) -> b.age() is 0 and b.isCaptive()) captiveNewborns.length.should.be.approximately( expectedSurvivingNewBirds, 0.75 * expectedSurvivingNewBirds) And "a few newborns are wild born", -> population = simulator.getPopulation() wildNewborns = population.birds().filter( (b) -> b.age() is 0 and b.isWild()) expected = numInitialNests * ModelParameters.collectionProbability * ModelParameters.renestingProbability * ModelParameters.eggConversionRate * (1 - ModelParameters.firstYearMortalityRate) wildNewborns.length.should.be.approximately(expected, 0.75 * expected) Scenario "Run one generation, all mature late nesters", -> before -> Clock.reset() numInitialBirds = 200 numInitialNests = numInitialBirds // 2 simulator = null expectedNumNewBirds = numInitialNests * ModelParameters.nestingProbability * ModelParameters.eggConversionRate expectedSurvivingNewBirds = expectedNumNewBirds expectedMortality = numInitialBirds * ModelParameters.matureMortalityRate expectedNewPopSize = numInitialBirds + expectedNumNewBirds - expectedMortality brokenNestProbability = ModelParameters.matureMortalityRate + (1 - ModelParameters.matureMortalityRate) * ModelParameters.matureMortalityRate expectedBrokenNests = numInitialNests * brokenNestProbability expectedRemainingNests = numInitialNests - expectedBrokenNests expectedUnpairedBirds = expectedSurvivingNewBirds + expectedBrokenNests Given "I construct a population of #{numInitialBirds} \ early nesting birds", -> population = new Population(0) population.addBird(new Bird(Bird.LATE)) for [0...numInitialBirds] simulator = new Simulator(population) And "I advance the clock #{ModelParameters.pairingAge} years", -> Clock.setYear(ModelParameters.pairingAge) Clock.currentYear.should.eql ModelParameters.pairingAge When "I run the simulation for one year", -> simulator.advanceOneYear() Then "the clock has advanced a year", -> Clock.currentYear.should.eql (ModelParameters.pairingAge+1) And "the population size is approximately #{expectedNewPopSize}", -> population = simulator.getPopulation() population.birds().length.should.be.approximately expectedNewPopSize, 0.1 * expectedNewPopSize And "most of the birds are paired", -> population = simulator.getPopulation() population.matingPairs().length.should.be.approximately( expectedRemainingNests, 0.33 * expectedRemainingNests) population.unpairedBirds().length.should.be.approximately( expectedUnpairedBirds, 0.33 * expectedUnpairedBirds) And "about #{expectedSurvivingNewBirds} birds to have age 0", -> population = simulator.getPopulation() newborns = population.birds().filter((b) -> b.age() is 0) newborns.length.should.be.approximately expectedSurvivingNewBirds, 0.5 * expectedSurvivingNewBirds And "all newborns are wild born", -> population = simulator.getPopulation() newborns = population.birds().filter((b) -> b.age() is 0) newborns.every((b) -> b.howReared().should.eql Bird.WILD_REARED) Scenario "Smoke test of 10 generations", -> before -> Clock.reset() numInitialBirds = 200 simulator = null Given "I construct a population of #{numInitialBirds}, \ half early and half late", -> population = new Population(0) population.addBird(new Bird(Bird.EARLY)) for [0...numInitialBirds // 2] population.addBird(new Bird(Bird.LATE)) for [0...numInitialBirds // 2] simulator = new Simulator(population) When "I run the simulation 10 generations", -> simulator.advanceOneYear() for [0...10] Then "I should still have some birds", -> population = simulator.getPopulation() # console.log(population) population.birds().length.should.be.above 0
[ { "context": "l '#new_prisoner',\n 'prisoner[first_name]': 'Jimmy'\n 'prisoner[last_name]': 'Harris'\n 'pri", "end": 704, "score": 0.9998365640640259, "start": 699, "tag": "NAME", "value": "Jimmy" }, { "context": "rst_name]': 'Jimmy'\n 'prisoner[last_name]': 'Harr...
tests/full_process.coffee
ministryofjustice/prison-visits
9
casper.test.on 'fail', -> casper.capture 'tests/failure.png' outputImages = if casper.cli.get('images') is 'on' then true else false casper.test.begin 'Prison Visit Booking: Step 1 - prisoner details', (test) -> casper.start 'http://localhost:3000' casper.viewport 1024, 768 casper.then -> @fillSelectors '#new_prisoner', '.js-native-date__date-input': '1977-02-18' , false casper.then -> test.assertField 'prisoner[prison_name]', '' test.assertField 'prisoner[date_of_birth(3i)]', '18' test.assertField 'prisoner[date_of_birth(2i)]', '2' test.assertField 'prisoner[date_of_birth(1i)]', '1977' @fill '#new_prisoner', 'prisoner[first_name]': 'Jimmy' 'prisoner[last_name]': 'Harris' 'prisoner[number]': 'a1234bc' 'prisoner[prison_name]': 'Rochester' , false @capture 'tests/prisoner_details_valid.png' if outputImages casper.then -> @click '.button-primary' casper.then -> test.assertUrlMatch /localhost:3000\/visitor-details/, 'we should have progressed to visitors' test.comment 'Prison Visit Booking: Step 2 - visitors' test.assertVisible '#first_name_0' @fillSelectors '#new_visit', '.js-native-date__date-input': '1975-06-24' , false casper.then -> test.assertField 'visit[visitor][][date_of_birth(3i)]', '24' test.assertField 'visit[visitor][][date_of_birth(2i)]', '6' test.assertField 'visit[visitor][][date_of_birth(1i)]', '1975' @fill '#new_visit', 'visit[visitor][][first_name]': 'Sue' 'visit[visitor][][last_name]': 'Denim' 'visit[visitor][][email]': 'sue@denim.com' 'visit[visitor][][phone]': '0123 456 789' , false @capture 'tests/visitor_details_valid.png' if outputImages casper.then -> @click '.button-primary' casper.then -> test.assertUrlMatch /localhost:3000\/choose-date-and-time/, 'we should have progressed to choose date and time' test.comment 'Prison Visit Booking: Step 3 - choose a session' @click '.BookingCalendar-day--bookable .BookingCalendar-dayLink' test.assertTextExists 'Choose a second date', 'slot help is present' @click '.day-slots.is-active input' @capture 'tests/choose-date-and-time.png' if outputImages casper.then -> @clickLabel 'Continue' casper.then -> test.assertUrlMatch /localhost:3000\/check-your-request/, 'we should have progressed to check your request' casper.then -> test.comment 'Prison Visit Booking: Step 4 - check your request' test.assertTextExists 'Jimmy Harris', 'prisoner name is present' test.assertTextExists 'Sue Denim', 'visitor name is present' @capture 'tests/check-your-request.png' if outputImages casper.then -> @click '.button-primary' casper.then -> test.assertUrlMatch /localhost:3000\/request-sent/, 'we should have progressed to request confirmation' @capture 'tests/request_sent.png' if outputImages casper.run -> test.done()
16639
casper.test.on 'fail', -> casper.capture 'tests/failure.png' outputImages = if casper.cli.get('images') is 'on' then true else false casper.test.begin 'Prison Visit Booking: Step 1 - prisoner details', (test) -> casper.start 'http://localhost:3000' casper.viewport 1024, 768 casper.then -> @fillSelectors '#new_prisoner', '.js-native-date__date-input': '1977-02-18' , false casper.then -> test.assertField 'prisoner[prison_name]', '' test.assertField 'prisoner[date_of_birth(3i)]', '18' test.assertField 'prisoner[date_of_birth(2i)]', '2' test.assertField 'prisoner[date_of_birth(1i)]', '1977' @fill '#new_prisoner', 'prisoner[first_name]': '<NAME>' 'prisoner[last_name]': '<NAME>' 'prisoner[number]': 'a1234bc' 'prisoner[prison_name]': '<NAME>' , false @capture 'tests/prisoner_details_valid.png' if outputImages casper.then -> @click '.button-primary' casper.then -> test.assertUrlMatch /localhost:3000\/visitor-details/, 'we should have progressed to visitors' test.comment 'Prison Visit Booking: Step 2 - visitors' test.assertVisible '#first_name_0' @fillSelectors '#new_visit', '.js-native-date__date-input': '1975-06-24' , false casper.then -> test.assertField 'visit[visitor][][date_of_birth(3i)]', '24' test.assertField 'visit[visitor][][date_of_birth(2i)]', '6' test.assertField 'visit[visitor][][date_of_birth(1i)]', '1975' @fill '#new_visit', 'visit[visitor][][first_name]': '<NAME>' 'visit[visitor][][last_name]': '<NAME>' 'visit[visitor][][email]': '<EMAIL>' 'visit[visitor][][phone]': '0123 456 789' , false @capture 'tests/visitor_details_valid.png' if outputImages casper.then -> @click '.button-primary' casper.then -> test.assertUrlMatch /localhost:3000\/choose-date-and-time/, 'we should have progressed to choose date and time' test.comment 'Prison Visit Booking: Step 3 - choose a session' @click '.BookingCalendar-day--bookable .BookingCalendar-dayLink' test.assertTextExists 'Choose a second date', 'slot help is present' @click '.day-slots.is-active input' @capture 'tests/choose-date-and-time.png' if outputImages casper.then -> @clickLabel 'Continue' casper.then -> test.assertUrlMatch /localhost:3000\/check-your-request/, 'we should have progressed to check your request' casper.then -> test.comment 'Prison Visit Booking: Step 4 - check your request' test.assertTextExists '<NAME>', 'prisoner name is present' test.assertTextExists '<NAME>', 'visitor name is present' @capture 'tests/check-your-request.png' if outputImages casper.then -> @click '.button-primary' casper.then -> test.assertUrlMatch /localhost:3000\/request-sent/, 'we should have progressed to request confirmation' @capture 'tests/request_sent.png' if outputImages casper.run -> test.done()
true
casper.test.on 'fail', -> casper.capture 'tests/failure.png' outputImages = if casper.cli.get('images') is 'on' then true else false casper.test.begin 'Prison Visit Booking: Step 1 - prisoner details', (test) -> casper.start 'http://localhost:3000' casper.viewport 1024, 768 casper.then -> @fillSelectors '#new_prisoner', '.js-native-date__date-input': '1977-02-18' , false casper.then -> test.assertField 'prisoner[prison_name]', '' test.assertField 'prisoner[date_of_birth(3i)]', '18' test.assertField 'prisoner[date_of_birth(2i)]', '2' test.assertField 'prisoner[date_of_birth(1i)]', '1977' @fill '#new_prisoner', 'prisoner[first_name]': 'PI:NAME:<NAME>END_PI' 'prisoner[last_name]': 'PI:NAME:<NAME>END_PI' 'prisoner[number]': 'a1234bc' 'prisoner[prison_name]': 'PI:NAME:<NAME>END_PI' , false @capture 'tests/prisoner_details_valid.png' if outputImages casper.then -> @click '.button-primary' casper.then -> test.assertUrlMatch /localhost:3000\/visitor-details/, 'we should have progressed to visitors' test.comment 'Prison Visit Booking: Step 2 - visitors' test.assertVisible '#first_name_0' @fillSelectors '#new_visit', '.js-native-date__date-input': '1975-06-24' , false casper.then -> test.assertField 'visit[visitor][][date_of_birth(3i)]', '24' test.assertField 'visit[visitor][][date_of_birth(2i)]', '6' test.assertField 'visit[visitor][][date_of_birth(1i)]', '1975' @fill '#new_visit', 'visit[visitor][][first_name]': 'PI:NAME:<NAME>END_PI' 'visit[visitor][][last_name]': 'PI:NAME:<NAME>END_PI' 'visit[visitor][][email]': 'PI:EMAIL:<EMAIL>END_PI' 'visit[visitor][][phone]': '0123 456 789' , false @capture 'tests/visitor_details_valid.png' if outputImages casper.then -> @click '.button-primary' casper.then -> test.assertUrlMatch /localhost:3000\/choose-date-and-time/, 'we should have progressed to choose date and time' test.comment 'Prison Visit Booking: Step 3 - choose a session' @click '.BookingCalendar-day--bookable .BookingCalendar-dayLink' test.assertTextExists 'Choose a second date', 'slot help is present' @click '.day-slots.is-active input' @capture 'tests/choose-date-and-time.png' if outputImages casper.then -> @clickLabel 'Continue' casper.then -> test.assertUrlMatch /localhost:3000\/check-your-request/, 'we should have progressed to check your request' casper.then -> test.comment 'Prison Visit Booking: Step 4 - check your request' test.assertTextExists 'PI:NAME:<NAME>END_PI', 'prisoner name is present' test.assertTextExists 'PI:NAME:<NAME>END_PI', 'visitor name is present' @capture 'tests/check-your-request.png' if outputImages casper.then -> @click '.button-primary' casper.then -> test.assertUrlMatch /localhost:3000\/request-sent/, 'we should have progressed to request confirmation' @capture 'tests/request_sent.png' if outputImages casper.run -> test.done()
[ { "context": " columns: [\n {data: 'email'}\n {data: 'full_name'}\n {data: 'role'}\n {data: 'status'}\n ", "end": 237, "score": 0.9611555933952332, "start": 228, "tag": "NAME", "value": "full_name" } ]
app/assets/javascripts/user.coffee
wagura-maurice/glowing-umbrella
0
ready = -> $('#users-table').dataTable processing: true serverSide: true ajax: $('#users-table').data('source') pagingType: 'full_numbers' stateSave: true columns: [ {data: 'email'} {data: 'full_name'} {data: 'role'} {data: 'status'} ] $(document).ready(ready) $(document).on('turbolinks:load', ready)
195268
ready = -> $('#users-table').dataTable processing: true serverSide: true ajax: $('#users-table').data('source') pagingType: 'full_numbers' stateSave: true columns: [ {data: 'email'} {data: '<NAME>'} {data: 'role'} {data: 'status'} ] $(document).ready(ready) $(document).on('turbolinks:load', ready)
true
ready = -> $('#users-table').dataTable processing: true serverSide: true ajax: $('#users-table').data('source') pagingType: 'full_numbers' stateSave: true columns: [ {data: 'email'} {data: 'PI:NAME:<NAME>END_PI'} {data: 'role'} {data: 'status'} ] $(document).ready(ready) $(document).on('turbolinks:load', ready)
[ { "context": " type: 'artwork',\n artist: name: 'Van Gogh', slug: 'van-gogh'\n partner: name: 'Part", "end": 861, "score": 0.9998332858085632, "start": 853, "tag": "NAME", "value": "Van Gogh" } ]
components/article/test/image_set.coffee
kanaabe/microgravity
0
_ = require 'underscore' benv = require 'benv' sinon = require 'sinon' Backbone = require 'backbone' fixtures = require '../../../test/helpers/fixtures.coffee' sd = require('sharify').data { resolve } = require 'path' { fabricate } = require 'antigravity' describe 'ImageSetView', -> before (done) -> benv.setup => benv.expose $: benv.require 'jquery' Element: window.Element Backbone.$ = $ @ImageSetView = benv.requireWithJadeify( resolve(__dirname, '../client/image_set') ['template' ] ) @ImageSetView.__set__ 'resize', (url) -> url @ImageSetView.__set__ 'Flickity', sinon.stub() @user = sinon.stub() @items = [ { type: 'image', caption: 'This is a caption', url: 'http://image.com/img.png' } { type: 'artwork', artist: name: 'Van Gogh', slug: 'van-gogh' partner: name: 'Partner Gallery' title: 'Starry Night' image: 'http://partnergallery.com/image.png' slug: 'van-gogh-starry-night' date: '1999' } ] done() after -> benv.teardown() beforeEach -> sinon.stub Backbone, 'sync' @view = new @ImageSetView el: $('body') items: @items user: @user afterEach -> Backbone.sync.restore() describe 'slideshow sets up flickity', -> it 'calls flickity', -> @ImageSetView.__get__('Flickity').called.should.be.ok describe '#close', -> it 'enables scrolling', -> @view.close() $('body').hasClass('is-scrolling-disabled').should.be.false() it 'destroys the view', -> @view.close() @view.$el.html().should.not.containEql '.image-set-modal' describe '#setupFollowButton', -> it 'creates a follow button for artists', -> $('.artist-follow').data('state').should.containEql 'follow' describe '#render', -> it 'renders a regular image', -> @view.render() @view.$el.html().should.containEql '1/2' @view.$el.html().should.containEql 'This is a caption' @view.$el.html().should.containEql 'http://image.com/img.png' it 'renders an artwork', -> @view.render() @view.$el.html().should.containEql '2/2' @view.$el.html().should.containEql 'Starry Night' @view.$el.html().should.containEql 'Partner Gallery' @view.$el.html().should.containEql 'van-gogh-starry-night' @view.$el.html().should.containEql '1999' @view.$el.html().should.containEql 'http://partnergallery.com/image.png' it 'disables vertical scroll on open', -> $('body').hasClass('is-scrolling-disabled').should.be.true()
192585
_ = require 'underscore' benv = require 'benv' sinon = require 'sinon' Backbone = require 'backbone' fixtures = require '../../../test/helpers/fixtures.coffee' sd = require('sharify').data { resolve } = require 'path' { fabricate } = require 'antigravity' describe 'ImageSetView', -> before (done) -> benv.setup => benv.expose $: benv.require 'jquery' Element: window.Element Backbone.$ = $ @ImageSetView = benv.requireWithJadeify( resolve(__dirname, '../client/image_set') ['template' ] ) @ImageSetView.__set__ 'resize', (url) -> url @ImageSetView.__set__ 'Flickity', sinon.stub() @user = sinon.stub() @items = [ { type: 'image', caption: 'This is a caption', url: 'http://image.com/img.png' } { type: 'artwork', artist: name: '<NAME>', slug: 'van-gogh' partner: name: 'Partner Gallery' title: 'Starry Night' image: 'http://partnergallery.com/image.png' slug: 'van-gogh-starry-night' date: '1999' } ] done() after -> benv.teardown() beforeEach -> sinon.stub Backbone, 'sync' @view = new @ImageSetView el: $('body') items: @items user: @user afterEach -> Backbone.sync.restore() describe 'slideshow sets up flickity', -> it 'calls flickity', -> @ImageSetView.__get__('Flickity').called.should.be.ok describe '#close', -> it 'enables scrolling', -> @view.close() $('body').hasClass('is-scrolling-disabled').should.be.false() it 'destroys the view', -> @view.close() @view.$el.html().should.not.containEql '.image-set-modal' describe '#setupFollowButton', -> it 'creates a follow button for artists', -> $('.artist-follow').data('state').should.containEql 'follow' describe '#render', -> it 'renders a regular image', -> @view.render() @view.$el.html().should.containEql '1/2' @view.$el.html().should.containEql 'This is a caption' @view.$el.html().should.containEql 'http://image.com/img.png' it 'renders an artwork', -> @view.render() @view.$el.html().should.containEql '2/2' @view.$el.html().should.containEql 'Starry Night' @view.$el.html().should.containEql 'Partner Gallery' @view.$el.html().should.containEql 'van-gogh-starry-night' @view.$el.html().should.containEql '1999' @view.$el.html().should.containEql 'http://partnergallery.com/image.png' it 'disables vertical scroll on open', -> $('body').hasClass('is-scrolling-disabled').should.be.true()
true
_ = require 'underscore' benv = require 'benv' sinon = require 'sinon' Backbone = require 'backbone' fixtures = require '../../../test/helpers/fixtures.coffee' sd = require('sharify').data { resolve } = require 'path' { fabricate } = require 'antigravity' describe 'ImageSetView', -> before (done) -> benv.setup => benv.expose $: benv.require 'jquery' Element: window.Element Backbone.$ = $ @ImageSetView = benv.requireWithJadeify( resolve(__dirname, '../client/image_set') ['template' ] ) @ImageSetView.__set__ 'resize', (url) -> url @ImageSetView.__set__ 'Flickity', sinon.stub() @user = sinon.stub() @items = [ { type: 'image', caption: 'This is a caption', url: 'http://image.com/img.png' } { type: 'artwork', artist: name: 'PI:NAME:<NAME>END_PI', slug: 'van-gogh' partner: name: 'Partner Gallery' title: 'Starry Night' image: 'http://partnergallery.com/image.png' slug: 'van-gogh-starry-night' date: '1999' } ] done() after -> benv.teardown() beforeEach -> sinon.stub Backbone, 'sync' @view = new @ImageSetView el: $('body') items: @items user: @user afterEach -> Backbone.sync.restore() describe 'slideshow sets up flickity', -> it 'calls flickity', -> @ImageSetView.__get__('Flickity').called.should.be.ok describe '#close', -> it 'enables scrolling', -> @view.close() $('body').hasClass('is-scrolling-disabled').should.be.false() it 'destroys the view', -> @view.close() @view.$el.html().should.not.containEql '.image-set-modal' describe '#setupFollowButton', -> it 'creates a follow button for artists', -> $('.artist-follow').data('state').should.containEql 'follow' describe '#render', -> it 'renders a regular image', -> @view.render() @view.$el.html().should.containEql '1/2' @view.$el.html().should.containEql 'This is a caption' @view.$el.html().should.containEql 'http://image.com/img.png' it 'renders an artwork', -> @view.render() @view.$el.html().should.containEql '2/2' @view.$el.html().should.containEql 'Starry Night' @view.$el.html().should.containEql 'Partner Gallery' @view.$el.html().should.containEql 'van-gogh-starry-night' @view.$el.html().should.containEql '1999' @view.$el.html().should.containEql 'http://partnergallery.com/image.png' it 'disables vertical scroll on open', -> $('body').hasClass('is-scrolling-disabled').should.be.true()
[ { "context": "mentShader: [\r\n\r\n \"// The 'Storm Shader' by Dmytry Lavrov, Copyright 2012 (http://dmytry.com/) with permiss", "end": 1732, "score": 0.9998976588249207, "start": 1719, "tag": "NAME", "value": "Dmytry Lavrov" }, { "context": "ght 2012 (http://dmytry.com/) with...
project/develop/coffee/ifl/shaders/IFLTornadoShader.coffee
GyanaPrasannaa/oz-experiment
0
class IFLTornadoShader uniforms: null constructor:-> @uniforms = "tDiffuse": { type: "t", value: null } "time": { type: "f", value: 0 } "resolution": { type: "v2", value: new THREE.Vector2(0,0) } "camera_matrix": { type: "m4", value: new THREE.Matrix4() } "tornado_bounding_radius": { type: "f", value: 80.0 } "light_harshness": { type: "f", value: 0.3 } "light_darkness": { type: "f", value: 1.0 } "cloud_edge_sharpness": { type: "f", value: 1.0 } "storm_tint": { type: "v3", value: new THREE.Vector3(1,1,1) } "final_colour_scale": { type: "f", value: 10.0 } "gamma_correction": { type: "f", value: 1.7 } "environment_rotation": { type: "f", value: 0.2 } "storm_alpha_correction": { type: "f", value: 1.7 } "tornado_density": { type: "f", value: 0.2 } "tornado_height": { type: "f", value: 120.0 } "spin_speed": { type: "f", value: 0.2 } "base_step_scaling": { type: "f", value: 0.7 } "min_step_size": { type: "f", value: 1.0 } "cam_fov": { type: "f", value: 60.0 } "dist_approx": { type: "f", value: 1.0 } vertexShader: [ "varying vec2 vUv;" "void main() {" "vUv = uv;" "gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);" "}" ].join("\n") fragmentShader: [ "// The 'Storm Shader' by Dmytry Lavrov, Copyright 2012 (http://dmytry.com/) with permission from Moritz Helmsteadter at The Max Plank Institute" "// is licensed under a Creative Commons attribution license http://creativecommons.org/licenses/by/3.0" "// free to share and remix for any purpose as long as it includes this note." "#ifdef GL_ES" "precision mediump float;" "#endif" "// change these to 0 to disable specific features" "#define BENT 0" "#define FAKE_DIRECTIONAL_LIGHT 0" "#define ENVIRONMENT_TEXTURE 1" "#define NEGATE_Z 1 /// set to 1 for production viewer to match opengl convention" "#define USE_BOUNDING_VOLUME 1" "uniform float cam_fov;" "const float pi=3.141592654;" "#if BENT" "const float bend_height=50.0;" "const float bend_displacement=20.0;/// Watch out for bounding volume. The tornado's radius is about 25 units." "#endif" "uniform float tornado_bounding_radius; /// = max(pow(tornado_height,1.5)*0.03, bend_displacement)+10;" "uniform float light_harshness;/// adjust these two parameters to chage the look of tornado." "uniform float light_darkness;" "uniform float cloud_edge_sharpness;/// decrease to make fuzzier edge." "uniform vec3 storm_tint;" "uniform float final_colour_scale;" "uniform float gamma_correction;" "uniform float environment_rotation;" "uniform float storm_alpha_correction;" "uniform float tornado_density;" "uniform float tornado_height;" "uniform float spin_speed;" "const int number_of_steps=180;/// number of isosurface raytracing steps" "uniform float base_step_scaling;/// Larger values allow for faster rendering but cause rendering artifacts. When stepping the isosurface, the value is multiplied by this number to obtain the distance of each step" "uniform float min_step_size;/// Minimal step size, this value is added to the step size, larger values allow to speed up the rendering at expense of artifacts." "uniform float dist_approx;" "// input values passed into this shader" "uniform float time;/// use for blinking effects" "uniform vec2 resolution;/// screen resolution" "uniform mat4 camera_matrix; /// transform from camera to the world (not from the world to the camera" "const vec3 towards_sun=vec3(1,5.0,1.0);" "#if ENVIRONMENT_TEXTURE" "uniform sampler2D tDiffuse;" "#endif" "float hash( float n )" "{" "return fract(sin(n)*43758.5453);" "}" "float snoise( in vec3 x )" "{" "vec3 p = floor(x);" "vec3 f = fract(x);" "f = f*f*(3.0-2.0*f);" "float n = p.x + p.y*57.0+p.z*137.0;" "float res = 1.0-2.0*mix(" "mix(mix( hash(n+ 0.0), hash(n+ 1.0),f.x), mix( hash(n+ 57.0), hash(n+ 58.0),f.x),f.y)," "mix(mix( hash(n+ 137.0), hash(n+ 138.0),f.x), mix( hash(n+ 57.0+137.0), hash(n+ 58.0+137.0),f.x),f.y)," "f.z" ");" "return res;" "}" "mat2 Spin(float angle){" "return mat2(cos(angle),-sin(angle),sin(angle),cos(angle));" "}" "float ridged(float f){" "return 1.0-2.0*abs(f);" "}" "float sigmoid(float f){" "if(f<0.0)return 0.0;" "if(f>1.0)return 1.0;" "return f*f*(3.0-f*2.0);" "}" "float Shape(vec3 q)/// the isosurface shape function, the surface is at o(q)=0" "{ " "float t=time;" "if(q.z<0.0)return length(q);" "#if BENT" "q.x+=sigmoid(1.0-q.z/bend_height)*bend_displacement;" "#endif" "vec3 spin_pos=vec3(Spin(t-sqrt(q.z))*q.xy,q.z-t*5.0);" "float zcurve=pow(q.z,1.5)*0.03;" "float v1=clamp(zcurve*0.2,0.1,1.0)*snoise(spin_pos*vec3(0.1,0.1,0.1))*5.0;" "float v=abs(length(q.xy)-zcurve)-5.5-v1;" "v=v-ridged(snoise(vec3(Spin(t*1.5+0.1*q.z)*q.xy,q.z-t*4.0)*0.3))*1.2;" "//v+=max(0.0,q.z-tornado_height);" "return v;" "}" "vec2 TextureCoord(vec3 q){" "#if BENT" "q.x+=sigmoid(1.0-q.z/bend_height)*bend_displacement;" "#endif" "//return vec2(atan(q.y,q.x)*(0.5/pi), 1.0-q.z/tornado_height);" "return vec2(mod(atan(q.y,q.x)*(0.5/pi)+environment_rotation,1.0), mod(1.0-q.z/tornado_height,1.0));" "}" "//Normalized gradient of the field at the point q , used as surface normal" "vec3 GetNormal(vec3 q)" "{" "vec3 f=vec3(0.5,0.0,0.0);" "float b=Shape(q);" "return normalize(vec3(Shape(q+f.xyy)-b, Shape(q+f.yxy)-b, Shape(q+f.yyx)-b));" "}" "void Fog_(float dist, out vec3 colour, out vec3 multiplier){/// calculates fog colour, and the multiplier for the colour of item behind the fog. If you do two intervals consecutively it will calculate the result correctly." "vec3 fog=exp(-dist*vec3(0.03,0.05,0.1)*0.2);" "colour=vec3(1.0)-fog;" "multiplier=fog;/// (1.0-a)+a*(1.0-b + b*x) = 1.0-a+a-ab+abx = 1.0-ab+abx" "}" "void FogStep(float dist, vec3 fog_absorb, vec3 fog_reemit, inout vec3 colour, inout vec3 multiplier){/// calculates fog colour, and the multiplier for the colour of item behind the fog. If you do two intervals consecutively it will calculate the result correctly." "vec3 fog=exp(-dist*fog_absorb);" "colour+=multiplier*(storm_tint-fog)*fog_reemit;" "multiplier*=fog;/// (1.0-a)+a*(1.0-b + b*x) = 1.0-a+a-ab+abx = 1.0-ab+abx" "}" "bool RayCylinderIntersect(vec3 org, vec3 dir, out float min_dist, out float max_dist){ " "vec2 p=org.xy;" "vec2 d=dir.xy;" "float r=tornado_bounding_radius;" "float a=dot(d,d)+1.0E-10;/// A in quadratic formula , with a small constant to avoid division by zero issue" "float det, b;" "b = -dot(p,d); /// -B/2 in quadratic formula" "/// AC = (p.x*p.x + p.y*p.y + p.z*p.z)*dd + r*r*dd " "det=(b*b) - dot(p,p)*a + r*r*a;/// B^2/4 - AC = determinant / 4" "if (det<0.0){" "return false;" "}" "det= sqrt(det); /// already divided by 2 here" "min_dist= (b - det)/a; /// still needs to be divided by A" "max_dist= (b + det)/a; " "if(max_dist>0.0){" "return true;" "}else{" "return false;" "}" "}" "void RaytraceFoggy(vec3 org, vec3 dir, float min_dist, float max_dist, inout vec3 colour, inout vec3 multiplier){" "vec3 q=org+dir*min_dist;" "vec3 pp;" "float d=0.0;" "float old_d=d;" "float dist=min_dist;" "#if ENVIRONMENT_TEXTURE" "vec3 tx_colour = vec3(0.0, 0.0, 0.0);" "float rrr=180.0/5.0;" "for(int i=0;i<5;i++)" "tx_colour += texture2D(tDiffuse, TextureCoord(org+dir*(min_dist+min_step_size*rrr*dist_approx))).xyz;" "tx_colour = (tx_colour / 5.0) * 0.35;" "#endif" "float step_scaling=base_step_scaling;" "float extra_step=min_step_size;" "for(int i=0;i<number_of_steps;i++)" "{" "old_d=d;" "float density=-Shape(q);" "d=max(density*step_scaling,0.0);" "float step_dist=d+extra_step;" "if(density>0.0){" "float d2=-Shape(q+towards_sun);" "//float brightness=exp(-0.7*clamp(d2,-10.0,20.0));" "float v=-0.6*density;" "#if FAKE_DIRECTIONAL_LIGHT" "v-=clamp(d2*light_harshness,0.0,light_darkness);" "#endif" "float brightness=exp(v);" "vec3 fog_colour=vec3(brightness);" "#if ENVIRONMENT_TEXTURE" "//vec3 tx_colour=texture2D(tDiffuse, TextureCoord(q)).xyz;" "fog_colour *= tx_colour;" "#endif" "//FogStep(step_dist*0.2, clamp(density*cloud_edge_sharpness, 0.0, 1.0)*vec3(1,1,1), fog_colour, colour, multiplier);" "FogStep(step_dist*tornado_density, clamp(density*cloud_edge_sharpness, 0.0, 1.0)*vec3(1,1,1), fog_colour, colour, multiplier);" "}" "if(dist>max_dist || multiplier.x<0.01){" "return;" "}" "dist+=step_dist; " "q=org+dist*dir;" "} " "return;" "}" "void main(void)" "{" "vec2 p = -1.0 + 2.0 * gl_FragCoord.xy / resolution.xy;" "p.y *= resolution.y/resolution.x;" "float dirz=1.0/tan(cam_fov*0.5*pi/180.0);" "#if NEGATE_Z" "dirz=-dirz;" "#endif" "//dirz=-2.5;" "vec3 dir=normalize(vec3(p.x,p.y,dirz));" "dir=(camera_matrix*vec4(dir,0.0)).xyz;" "//Raymarching the isosurface:" "float dist;" "vec3 multiplier=vec3(1.0);" "vec3 color=vec3(0.0);" "vec3 org=camera_matrix[3].xyz;/// origin of the ray" "float min_dist=0.0, max_dist=1.0E4;" "#if USE_BOUNDING_VOLUME" "if(!RayCylinderIntersect(org, dir, min_dist, max_dist)) {" "discard;" "return;" "}" "min_dist=max(min_dist,0.0);" "#endif" "RaytraceFoggy(org, dir, min_dist, max_dist, color, multiplier);" "vec3 col = pow(color, vec3(gamma_correction))*final_colour_scale;" "float a = 1.0 - (multiplier.r);" "gl_FragColor = vec4(col, pow(a, storm_alpha_correction));" "}" ].join("\n")
183151
class IFLTornadoShader uniforms: null constructor:-> @uniforms = "tDiffuse": { type: "t", value: null } "time": { type: "f", value: 0 } "resolution": { type: "v2", value: new THREE.Vector2(0,0) } "camera_matrix": { type: "m4", value: new THREE.Matrix4() } "tornado_bounding_radius": { type: "f", value: 80.0 } "light_harshness": { type: "f", value: 0.3 } "light_darkness": { type: "f", value: 1.0 } "cloud_edge_sharpness": { type: "f", value: 1.0 } "storm_tint": { type: "v3", value: new THREE.Vector3(1,1,1) } "final_colour_scale": { type: "f", value: 10.0 } "gamma_correction": { type: "f", value: 1.7 } "environment_rotation": { type: "f", value: 0.2 } "storm_alpha_correction": { type: "f", value: 1.7 } "tornado_density": { type: "f", value: 0.2 } "tornado_height": { type: "f", value: 120.0 } "spin_speed": { type: "f", value: 0.2 } "base_step_scaling": { type: "f", value: 0.7 } "min_step_size": { type: "f", value: 1.0 } "cam_fov": { type: "f", value: 60.0 } "dist_approx": { type: "f", value: 1.0 } vertexShader: [ "varying vec2 vUv;" "void main() {" "vUv = uv;" "gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);" "}" ].join("\n") fragmentShader: [ "// The 'Storm Shader' by <NAME>, Copyright 2012 (http://dmytry.com/) with permission from <NAME> at The Max Plank Institute" "// is licensed under a Creative Commons attribution license http://creativecommons.org/licenses/by/3.0" "// free to share and remix for any purpose as long as it includes this note." "#ifdef GL_ES" "precision mediump float;" "#endif" "// change these to 0 to disable specific features" "#define BENT 0" "#define FAKE_DIRECTIONAL_LIGHT 0" "#define ENVIRONMENT_TEXTURE 1" "#define NEGATE_Z 1 /// set to 1 for production viewer to match opengl convention" "#define USE_BOUNDING_VOLUME 1" "uniform float cam_fov;" "const float pi=3.141592654;" "#if BENT" "const float bend_height=50.0;" "const float bend_displacement=20.0;/// Watch out for bounding volume. The tornado's radius is about 25 units." "#endif" "uniform float tornado_bounding_radius; /// = max(pow(tornado_height,1.5)*0.03, bend_displacement)+10;" "uniform float light_harshness;/// adjust these two parameters to chage the look of tornado." "uniform float light_darkness;" "uniform float cloud_edge_sharpness;/// decrease to make fuzzier edge." "uniform vec3 storm_tint;" "uniform float final_colour_scale;" "uniform float gamma_correction;" "uniform float environment_rotation;" "uniform float storm_alpha_correction;" "uniform float tornado_density;" "uniform float tornado_height;" "uniform float spin_speed;" "const int number_of_steps=180;/// number of isosurface raytracing steps" "uniform float base_step_scaling;/// Larger values allow for faster rendering but cause rendering artifacts. When stepping the isosurface, the value is multiplied by this number to obtain the distance of each step" "uniform float min_step_size;/// Minimal step size, this value is added to the step size, larger values allow to speed up the rendering at expense of artifacts." "uniform float dist_approx;" "// input values passed into this shader" "uniform float time;/// use for blinking effects" "uniform vec2 resolution;/// screen resolution" "uniform mat4 camera_matrix; /// transform from camera to the world (not from the world to the camera" "const vec3 towards_sun=vec3(1,5.0,1.0);" "#if ENVIRONMENT_TEXTURE" "uniform sampler2D tDiffuse;" "#endif" "float hash( float n )" "{" "return fract(sin(n)*43758.5453);" "}" "float snoise( in vec3 x )" "{" "vec3 p = floor(x);" "vec3 f = fract(x);" "f = f*f*(3.0-2.0*f);" "float n = p.x + p.y*57.0+p.z*137.0;" "float res = 1.0-2.0*mix(" "mix(mix( hash(n+ 0.0), hash(n+ 1.0),f.x), mix( hash(n+ 57.0), hash(n+ 58.0),f.x),f.y)," "mix(mix( hash(n+ 137.0), hash(n+ 138.0),f.x), mix( hash(n+ 57.0+137.0), hash(n+ 58.0+137.0),f.x),f.y)," "f.z" ");" "return res;" "}" "mat2 Spin(float angle){" "return mat2(cos(angle),-sin(angle),sin(angle),cos(angle));" "}" "float ridged(float f){" "return 1.0-2.0*abs(f);" "}" "float sigmoid(float f){" "if(f<0.0)return 0.0;" "if(f>1.0)return 1.0;" "return f*f*(3.0-f*2.0);" "}" "float Shape(vec3 q)/// the isosurface shape function, the surface is at o(q)=0" "{ " "float t=time;" "if(q.z<0.0)return length(q);" "#if BENT" "q.x+=sigmoid(1.0-q.z/bend_height)*bend_displacement;" "#endif" "vec3 spin_pos=vec3(Spin(t-sqrt(q.z))*q.xy,q.z-t*5.0);" "float zcurve=pow(q.z,1.5)*0.03;" "float v1=clamp(zcurve*0.2,0.1,1.0)*snoise(spin_pos*vec3(0.1,0.1,0.1))*5.0;" "float v=abs(length(q.xy)-zcurve)-5.5-v1;" "v=v-ridged(snoise(vec3(Spin(t*1.5+0.1*q.z)*q.xy,q.z-t*4.0)*0.3))*1.2;" "//v+=max(0.0,q.z-tornado_height);" "return v;" "}" "vec2 TextureCoord(vec3 q){" "#if BENT" "q.x+=sigmoid(1.0-q.z/bend_height)*bend_displacement;" "#endif" "//return vec2(atan(q.y,q.x)*(0.5/pi), 1.0-q.z/tornado_height);" "return vec2(mod(atan(q.y,q.x)*(0.5/pi)+environment_rotation,1.0), mod(1.0-q.z/tornado_height,1.0));" "}" "//Normalized gradient of the field at the point q , used as surface normal" "vec3 GetNormal(vec3 q)" "{" "vec3 f=vec3(0.5,0.0,0.0);" "float b=Shape(q);" "return normalize(vec3(Shape(q+f.xyy)-b, Shape(q+f.yxy)-b, Shape(q+f.yyx)-b));" "}" "void Fog_(float dist, out vec3 colour, out vec3 multiplier){/// calculates fog colour, and the multiplier for the colour of item behind the fog. If you do two intervals consecutively it will calculate the result correctly." "vec3 fog=exp(-dist*vec3(0.03,0.05,0.1)*0.2);" "colour=vec3(1.0)-fog;" "multiplier=fog;/// (1.0-a)+a*(1.0-b + b*x) = 1.0-a+a-ab+abx = 1.0-ab+abx" "}" "void FogStep(float dist, vec3 fog_absorb, vec3 fog_reemit, inout vec3 colour, inout vec3 multiplier){/// calculates fog colour, and the multiplier for the colour of item behind the fog. If you do two intervals consecutively it will calculate the result correctly." "vec3 fog=exp(-dist*fog_absorb);" "colour+=multiplier*(storm_tint-fog)*fog_reemit;" "multiplier*=fog;/// (1.0-a)+a*(1.0-b + b*x) = 1.0-a+a-ab+abx = 1.0-ab+abx" "}" "bool RayCylinderIntersect(vec3 org, vec3 dir, out float min_dist, out float max_dist){ " "vec2 p=org.xy;" "vec2 d=dir.xy;" "float r=tornado_bounding_radius;" "float a=dot(d,d)+1.0E-10;/// A in quadratic formula , with a small constant to avoid division by zero issue" "float det, b;" "b = -dot(p,d); /// -B/2 in quadratic formula" "/// AC = (p.x*p.x + p.y*p.y + p.z*p.z)*dd + r*r*dd " "det=(b*b) - dot(p,p)*a + r*r*a;/// B^2/4 - AC = determinant / 4" "if (det<0.0){" "return false;" "}" "det= sqrt(det); /// already divided by 2 here" "min_dist= (b - det)/a; /// still needs to be divided by A" "max_dist= (b + det)/a; " "if(max_dist>0.0){" "return true;" "}else{" "return false;" "}" "}" "void RaytraceFoggy(vec3 org, vec3 dir, float min_dist, float max_dist, inout vec3 colour, inout vec3 multiplier){" "vec3 q=org+dir*min_dist;" "vec3 pp;" "float d=0.0;" "float old_d=d;" "float dist=min_dist;" "#if ENVIRONMENT_TEXTURE" "vec3 tx_colour = vec3(0.0, 0.0, 0.0);" "float rrr=180.0/5.0;" "for(int i=0;i<5;i++)" "tx_colour += texture2D(tDiffuse, TextureCoord(org+dir*(min_dist+min_step_size*rrr*dist_approx))).xyz;" "tx_colour = (tx_colour / 5.0) * 0.35;" "#endif" "float step_scaling=base_step_scaling;" "float extra_step=min_step_size;" "for(int i=0;i<number_of_steps;i++)" "{" "old_d=d;" "float density=-Shape(q);" "d=max(density*step_scaling,0.0);" "float step_dist=d+extra_step;" "if(density>0.0){" "float d2=-Shape(q+towards_sun);" "//float brightness=exp(-0.7*clamp(d2,-10.0,20.0));" "float v=-0.6*density;" "#if FAKE_DIRECTIONAL_LIGHT" "v-=clamp(d2*light_harshness,0.0,light_darkness);" "#endif" "float brightness=exp(v);" "vec3 fog_colour=vec3(brightness);" "#if ENVIRONMENT_TEXTURE" "//vec3 tx_colour=texture2D(tDiffuse, TextureCoord(q)).xyz;" "fog_colour *= tx_colour;" "#endif" "//FogStep(step_dist*0.2, clamp(density*cloud_edge_sharpness, 0.0, 1.0)*vec3(1,1,1), fog_colour, colour, multiplier);" "FogStep(step_dist*tornado_density, clamp(density*cloud_edge_sharpness, 0.0, 1.0)*vec3(1,1,1), fog_colour, colour, multiplier);" "}" "if(dist>max_dist || multiplier.x<0.01){" "return;" "}" "dist+=step_dist; " "q=org+dist*dir;" "} " "return;" "}" "void main(void)" "{" "vec2 p = -1.0 + 2.0 * gl_FragCoord.xy / resolution.xy;" "p.y *= resolution.y/resolution.x;" "float dirz=1.0/tan(cam_fov*0.5*pi/180.0);" "#if NEGATE_Z" "dirz=-dirz;" "#endif" "//dirz=-2.5;" "vec3 dir=normalize(vec3(p.x,p.y,dirz));" "dir=(camera_matrix*vec4(dir,0.0)).xyz;" "//Raymarching the isosurface:" "float dist;" "vec3 multiplier=vec3(1.0);" "vec3 color=vec3(0.0);" "vec3 org=camera_matrix[3].xyz;/// origin of the ray" "float min_dist=0.0, max_dist=1.0E4;" "#if USE_BOUNDING_VOLUME" "if(!RayCylinderIntersect(org, dir, min_dist, max_dist)) {" "discard;" "return;" "}" "min_dist=max(min_dist,0.0);" "#endif" "RaytraceFoggy(org, dir, min_dist, max_dist, color, multiplier);" "vec3 col = pow(color, vec3(gamma_correction))*final_colour_scale;" "float a = 1.0 - (multiplier.r);" "gl_FragColor = vec4(col, pow(a, storm_alpha_correction));" "}" ].join("\n")
true
class IFLTornadoShader uniforms: null constructor:-> @uniforms = "tDiffuse": { type: "t", value: null } "time": { type: "f", value: 0 } "resolution": { type: "v2", value: new THREE.Vector2(0,0) } "camera_matrix": { type: "m4", value: new THREE.Matrix4() } "tornado_bounding_radius": { type: "f", value: 80.0 } "light_harshness": { type: "f", value: 0.3 } "light_darkness": { type: "f", value: 1.0 } "cloud_edge_sharpness": { type: "f", value: 1.0 } "storm_tint": { type: "v3", value: new THREE.Vector3(1,1,1) } "final_colour_scale": { type: "f", value: 10.0 } "gamma_correction": { type: "f", value: 1.7 } "environment_rotation": { type: "f", value: 0.2 } "storm_alpha_correction": { type: "f", value: 1.7 } "tornado_density": { type: "f", value: 0.2 } "tornado_height": { type: "f", value: 120.0 } "spin_speed": { type: "f", value: 0.2 } "base_step_scaling": { type: "f", value: 0.7 } "min_step_size": { type: "f", value: 1.0 } "cam_fov": { type: "f", value: 60.0 } "dist_approx": { type: "f", value: 1.0 } vertexShader: [ "varying vec2 vUv;" "void main() {" "vUv = uv;" "gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);" "}" ].join("\n") fragmentShader: [ "// The 'Storm Shader' by PI:NAME:<NAME>END_PI, Copyright 2012 (http://dmytry.com/) with permission from PI:NAME:<NAME>END_PI at The Max Plank Institute" "// is licensed under a Creative Commons attribution license http://creativecommons.org/licenses/by/3.0" "// free to share and remix for any purpose as long as it includes this note." "#ifdef GL_ES" "precision mediump float;" "#endif" "// change these to 0 to disable specific features" "#define BENT 0" "#define FAKE_DIRECTIONAL_LIGHT 0" "#define ENVIRONMENT_TEXTURE 1" "#define NEGATE_Z 1 /// set to 1 for production viewer to match opengl convention" "#define USE_BOUNDING_VOLUME 1" "uniform float cam_fov;" "const float pi=3.141592654;" "#if BENT" "const float bend_height=50.0;" "const float bend_displacement=20.0;/// Watch out for bounding volume. The tornado's radius is about 25 units." "#endif" "uniform float tornado_bounding_radius; /// = max(pow(tornado_height,1.5)*0.03, bend_displacement)+10;" "uniform float light_harshness;/// adjust these two parameters to chage the look of tornado." "uniform float light_darkness;" "uniform float cloud_edge_sharpness;/// decrease to make fuzzier edge." "uniform vec3 storm_tint;" "uniform float final_colour_scale;" "uniform float gamma_correction;" "uniform float environment_rotation;" "uniform float storm_alpha_correction;" "uniform float tornado_density;" "uniform float tornado_height;" "uniform float spin_speed;" "const int number_of_steps=180;/// number of isosurface raytracing steps" "uniform float base_step_scaling;/// Larger values allow for faster rendering but cause rendering artifacts. When stepping the isosurface, the value is multiplied by this number to obtain the distance of each step" "uniform float min_step_size;/// Minimal step size, this value is added to the step size, larger values allow to speed up the rendering at expense of artifacts." "uniform float dist_approx;" "// input values passed into this shader" "uniform float time;/// use for blinking effects" "uniform vec2 resolution;/// screen resolution" "uniform mat4 camera_matrix; /// transform from camera to the world (not from the world to the camera" "const vec3 towards_sun=vec3(1,5.0,1.0);" "#if ENVIRONMENT_TEXTURE" "uniform sampler2D tDiffuse;" "#endif" "float hash( float n )" "{" "return fract(sin(n)*43758.5453);" "}" "float snoise( in vec3 x )" "{" "vec3 p = floor(x);" "vec3 f = fract(x);" "f = f*f*(3.0-2.0*f);" "float n = p.x + p.y*57.0+p.z*137.0;" "float res = 1.0-2.0*mix(" "mix(mix( hash(n+ 0.0), hash(n+ 1.0),f.x), mix( hash(n+ 57.0), hash(n+ 58.0),f.x),f.y)," "mix(mix( hash(n+ 137.0), hash(n+ 138.0),f.x), mix( hash(n+ 57.0+137.0), hash(n+ 58.0+137.0),f.x),f.y)," "f.z" ");" "return res;" "}" "mat2 Spin(float angle){" "return mat2(cos(angle),-sin(angle),sin(angle),cos(angle));" "}" "float ridged(float f){" "return 1.0-2.0*abs(f);" "}" "float sigmoid(float f){" "if(f<0.0)return 0.0;" "if(f>1.0)return 1.0;" "return f*f*(3.0-f*2.0);" "}" "float Shape(vec3 q)/// the isosurface shape function, the surface is at o(q)=0" "{ " "float t=time;" "if(q.z<0.0)return length(q);" "#if BENT" "q.x+=sigmoid(1.0-q.z/bend_height)*bend_displacement;" "#endif" "vec3 spin_pos=vec3(Spin(t-sqrt(q.z))*q.xy,q.z-t*5.0);" "float zcurve=pow(q.z,1.5)*0.03;" "float v1=clamp(zcurve*0.2,0.1,1.0)*snoise(spin_pos*vec3(0.1,0.1,0.1))*5.0;" "float v=abs(length(q.xy)-zcurve)-5.5-v1;" "v=v-ridged(snoise(vec3(Spin(t*1.5+0.1*q.z)*q.xy,q.z-t*4.0)*0.3))*1.2;" "//v+=max(0.0,q.z-tornado_height);" "return v;" "}" "vec2 TextureCoord(vec3 q){" "#if BENT" "q.x+=sigmoid(1.0-q.z/bend_height)*bend_displacement;" "#endif" "//return vec2(atan(q.y,q.x)*(0.5/pi), 1.0-q.z/tornado_height);" "return vec2(mod(atan(q.y,q.x)*(0.5/pi)+environment_rotation,1.0), mod(1.0-q.z/tornado_height,1.0));" "}" "//Normalized gradient of the field at the point q , used as surface normal" "vec3 GetNormal(vec3 q)" "{" "vec3 f=vec3(0.5,0.0,0.0);" "float b=Shape(q);" "return normalize(vec3(Shape(q+f.xyy)-b, Shape(q+f.yxy)-b, Shape(q+f.yyx)-b));" "}" "void Fog_(float dist, out vec3 colour, out vec3 multiplier){/// calculates fog colour, and the multiplier for the colour of item behind the fog. If you do two intervals consecutively it will calculate the result correctly." "vec3 fog=exp(-dist*vec3(0.03,0.05,0.1)*0.2);" "colour=vec3(1.0)-fog;" "multiplier=fog;/// (1.0-a)+a*(1.0-b + b*x) = 1.0-a+a-ab+abx = 1.0-ab+abx" "}" "void FogStep(float dist, vec3 fog_absorb, vec3 fog_reemit, inout vec3 colour, inout vec3 multiplier){/// calculates fog colour, and the multiplier for the colour of item behind the fog. If you do two intervals consecutively it will calculate the result correctly." "vec3 fog=exp(-dist*fog_absorb);" "colour+=multiplier*(storm_tint-fog)*fog_reemit;" "multiplier*=fog;/// (1.0-a)+a*(1.0-b + b*x) = 1.0-a+a-ab+abx = 1.0-ab+abx" "}" "bool RayCylinderIntersect(vec3 org, vec3 dir, out float min_dist, out float max_dist){ " "vec2 p=org.xy;" "vec2 d=dir.xy;" "float r=tornado_bounding_radius;" "float a=dot(d,d)+1.0E-10;/// A in quadratic formula , with a small constant to avoid division by zero issue" "float det, b;" "b = -dot(p,d); /// -B/2 in quadratic formula" "/// AC = (p.x*p.x + p.y*p.y + p.z*p.z)*dd + r*r*dd " "det=(b*b) - dot(p,p)*a + r*r*a;/// B^2/4 - AC = determinant / 4" "if (det<0.0){" "return false;" "}" "det= sqrt(det); /// already divided by 2 here" "min_dist= (b - det)/a; /// still needs to be divided by A" "max_dist= (b + det)/a; " "if(max_dist>0.0){" "return true;" "}else{" "return false;" "}" "}" "void RaytraceFoggy(vec3 org, vec3 dir, float min_dist, float max_dist, inout vec3 colour, inout vec3 multiplier){" "vec3 q=org+dir*min_dist;" "vec3 pp;" "float d=0.0;" "float old_d=d;" "float dist=min_dist;" "#if ENVIRONMENT_TEXTURE" "vec3 tx_colour = vec3(0.0, 0.0, 0.0);" "float rrr=180.0/5.0;" "for(int i=0;i<5;i++)" "tx_colour += texture2D(tDiffuse, TextureCoord(org+dir*(min_dist+min_step_size*rrr*dist_approx))).xyz;" "tx_colour = (tx_colour / 5.0) * 0.35;" "#endif" "float step_scaling=base_step_scaling;" "float extra_step=min_step_size;" "for(int i=0;i<number_of_steps;i++)" "{" "old_d=d;" "float density=-Shape(q);" "d=max(density*step_scaling,0.0);" "float step_dist=d+extra_step;" "if(density>0.0){" "float d2=-Shape(q+towards_sun);" "//float brightness=exp(-0.7*clamp(d2,-10.0,20.0));" "float v=-0.6*density;" "#if FAKE_DIRECTIONAL_LIGHT" "v-=clamp(d2*light_harshness,0.0,light_darkness);" "#endif" "float brightness=exp(v);" "vec3 fog_colour=vec3(brightness);" "#if ENVIRONMENT_TEXTURE" "//vec3 tx_colour=texture2D(tDiffuse, TextureCoord(q)).xyz;" "fog_colour *= tx_colour;" "#endif" "//FogStep(step_dist*0.2, clamp(density*cloud_edge_sharpness, 0.0, 1.0)*vec3(1,1,1), fog_colour, colour, multiplier);" "FogStep(step_dist*tornado_density, clamp(density*cloud_edge_sharpness, 0.0, 1.0)*vec3(1,1,1), fog_colour, colour, multiplier);" "}" "if(dist>max_dist || multiplier.x<0.01){" "return;" "}" "dist+=step_dist; " "q=org+dist*dir;" "} " "return;" "}" "void main(void)" "{" "vec2 p = -1.0 + 2.0 * gl_FragCoord.xy / resolution.xy;" "p.y *= resolution.y/resolution.x;" "float dirz=1.0/tan(cam_fov*0.5*pi/180.0);" "#if NEGATE_Z" "dirz=-dirz;" "#endif" "//dirz=-2.5;" "vec3 dir=normalize(vec3(p.x,p.y,dirz));" "dir=(camera_matrix*vec4(dir,0.0)).xyz;" "//Raymarching the isosurface:" "float dist;" "vec3 multiplier=vec3(1.0);" "vec3 color=vec3(0.0);" "vec3 org=camera_matrix[3].xyz;/// origin of the ray" "float min_dist=0.0, max_dist=1.0E4;" "#if USE_BOUNDING_VOLUME" "if(!RayCylinderIntersect(org, dir, min_dist, max_dist)) {" "discard;" "return;" "}" "min_dist=max(min_dist,0.0);" "#endif" "RaytraceFoggy(org, dir, min_dist, max_dist, color, multiplier);" "vec3 col = pow(color, vec3(gamma_correction))*final_colour_scale;" "float a = 1.0 - (multiplier.r);" "gl_FragColor = vec4(col, pow(a, storm_alpha_correction));" "}" ].join("\n")
[ { "context": "enderd = soyerInst.render( \"test.test2\", { name: \"soyer\" } )\n\t\t\t_renderd.should.equal( \"Hello soyer\" )\n\t\t", "end": 992, "score": 0.9803107976913452, "start": 987, "tag": "NAME", "value": "soyer" }, { "context": "name: \"soyer\" } )\n\t\t\t_renderd.should.eq...
_src/test/test.coffee
mpneuried/soyer
2
_ = require("lodash") path = require "path" should = require('should') Soyer = require("../lib/soyer/") _Cnf = path: path.resolve( __dirname, "./tmpls/" ) pathLang: path.resolve( __dirname, "./tmplsLang/" ) describe 'SOYER-TEST', -> before ( done )-> done() return after ( done )-> done() return describe 'No language support', -> soyerInst = null it 'get a soyer instance', ( done )-> soyerInst = new Soyer languagesupport: false path: _Cnf.path soyerInst.should.be.an.instanceOf Soyer done() return it 'load templates', ( done )-> soyerInst.load ( err, success )-> should.not.exist( err ) success.should.be.ok done() return return it 'render a test template', ( done )-> _renderd = soyerInst.render( "test.test1", {} ) _renderd.should.equal( "Hello World" ) done() return it 'render a test template with params', ( done )-> _renderd = soyerInst.render( "test.test2", { name: "soyer" } ) _renderd.should.equal( "Hello soyer" ) done() return return describe 'With language support', -> soyerInst = null it 'get a soyer instance', ( done )-> soyerInst = new Soyer languagesupport: true path: _Cnf.pathLang soyerInst.should.be.an.instanceOf Soyer done() return it 'load templates', ( done )-> soyerInst.load ( err, success )-> should.not.exist( err ) success.should.be.ok done() return return it 'render a test template in english', ( done )-> _renderd = soyerInst.render( "test.test1", "en-us", {} ) _renderd.should.equal( "Hello World" ) done() return it 'render a test template in german', ( done )-> _renderd = soyerInst.render( "test.test1", "de-de", {} ) _renderd.should.equal( "Hallo Welt" ) done() return it 'render a test template with params in english', ( done )-> _renderd = soyerInst.render( "test.test2", "en-us", { name: "soyer" } ) _renderd.should.equal( "Hello soyer" ) done() return it 'render a test template with params in german', ( done )-> _renderd = soyerInst.render( "test.test2", "de-de", { name: "soyer" } ) _renderd.should.equal( "Hallo soyer" ) done() return return describe 'Helper Methods', -> _h = Soyer.helper it 'get language out of browser header-string `accepted-language`', ( done )-> tests = "en,fr-fr;q=0.8,fr;q=0.6,de-de;q=0.4,de;q=0.2": "en-us" "fr-fr;q=0.8": "en-us" "de": "de-de" "en": "en-us" "fr": "en-us" for _browserstring, res of tests _h.extractLanguage( _browserstring ).should.equal( res ) done() it 'get language out of browser header-string `accepted-language` with different default', ( done )-> tests = "en,fr-fr;q=0.8,fr;q=0.6,de-de;q=0.4,de;q=0.2": "en-us" "fr-fr;q=0.8": "de-de" "de": "de-de" "en": "en-us" "fr": "de-de" _h.setDefaultLanguage( "de-de" ) _h.getDefaultLanguage().should.equal( "de-de" ) for _browserstring, res of tests _h.extractLanguage( _browserstring ).should.equal( res ) done() it 'get language out of browser header-string `accepted-language` with new language', ( done )-> tests = "en,fr-fr;q=0.8,fr;q=0.6,de-de;q=0.4,de;q=0.2": "en-us" "fr-fr;q=0.8": "fr-fr" "de": "de-de" "en": "en-us" "fr": "fr-fr" LangMapping = "fr-fr": "fr-fr" "fr": "fr-fr" expLangMapping = "de-de": "de-de" "de": "de-de" "en-us": "en-us" "en-gb": "en-us" "en": "en-us" "fr-fr": "fr-fr" "fr": "fr-fr" _h.setLanguageMapping( LangMapping ) _h.getLanguageMapping().should.eql( expLangMapping ) for _browserstring, res of tests _h.extractLanguage( _browserstring ).should.equal( res ) done() it 'fail by setting a unknown default language', ( done )-> try _h.setDefaultLanguage( "ab-cd" ) catch e e.message.should.equal( "soyer-helper: Default language not found in `LanguageMapping`" ) done() return
193755
_ = require("lodash") path = require "path" should = require('should') Soyer = require("../lib/soyer/") _Cnf = path: path.resolve( __dirname, "./tmpls/" ) pathLang: path.resolve( __dirname, "./tmplsLang/" ) describe 'SOYER-TEST', -> before ( done )-> done() return after ( done )-> done() return describe 'No language support', -> soyerInst = null it 'get a soyer instance', ( done )-> soyerInst = new Soyer languagesupport: false path: _Cnf.path soyerInst.should.be.an.instanceOf Soyer done() return it 'load templates', ( done )-> soyerInst.load ( err, success )-> should.not.exist( err ) success.should.be.ok done() return return it 'render a test template', ( done )-> _renderd = soyerInst.render( "test.test1", {} ) _renderd.should.equal( "Hello World" ) done() return it 'render a test template with params', ( done )-> _renderd = soyerInst.render( "test.test2", { name: "<NAME>" } ) _renderd.should.equal( "Hello <NAME>" ) done() return return describe 'With language support', -> soyerInst = null it 'get a soyer instance', ( done )-> soyerInst = new Soyer languagesupport: true path: _Cnf.pathLang soyerInst.should.be.an.instanceOf Soyer done() return it 'load templates', ( done )-> soyerInst.load ( err, success )-> should.not.exist( err ) success.should.be.ok done() return return it 'render a test template in english', ( done )-> _renderd = soyerInst.render( "test.test1", "en-us", {} ) _renderd.should.equal( "Hello World" ) done() return it 'render a test template in german', ( done )-> _renderd = soyerInst.render( "test.test1", "de-de", {} ) _renderd.should.equal( "<NAME>" ) done() return it 'render a test template with params in english', ( done )-> _renderd = soyerInst.render( "test.test2", "en-us", { name: "<NAME>" } ) _renderd.should.equal( "Hello <NAME>" ) done() return it 'render a test template with params in german', ( done )-> _renderd = soyerInst.render( "test.test2", "de-de", { name: "<NAME>" } ) _renderd.should.equal( "<NAME>" ) done() return return describe 'Helper Methods', -> _h = Soyer.helper it 'get language out of browser header-string `accepted-language`', ( done )-> tests = "en,fr-fr;q=0.8,fr;q=0.6,de-de;q=0.4,de;q=0.2": "en-us" "fr-fr;q=0.8": "en-us" "de": "de-de" "en": "en-us" "fr": "en-us" for _browserstring, res of tests _h.extractLanguage( _browserstring ).should.equal( res ) done() it 'get language out of browser header-string `accepted-language` with different default', ( done )-> tests = "en,fr-fr;q=0.8,fr;q=0.6,de-de;q=0.4,de;q=0.2": "en-us" "fr-fr;q=0.8": "de-de" "de": "de-de" "en": "en-us" "fr": "de-de" _h.setDefaultLanguage( "de-de" ) _h.getDefaultLanguage().should.equal( "de-de" ) for _browserstring, res of tests _h.extractLanguage( _browserstring ).should.equal( res ) done() it 'get language out of browser header-string `accepted-language` with new language', ( done )-> tests = "en,fr-fr;q=0.8,fr;q=0.6,de-de;q=0.4,de;q=0.2": "en-us" "fr-fr;q=0.8": "fr-fr" "de": "de-de" "en": "en-us" "fr": "fr-fr" LangMapping = "fr-fr": "fr-fr" "fr": "fr-fr" expLangMapping = "de-de": "de-de" "de": "de-de" "en-us": "en-us" "en-gb": "en-us" "en": "en-us" "fr-fr": "fr-fr" "fr": "fr-fr" _h.setLanguageMapping( LangMapping ) _h.getLanguageMapping().should.eql( expLangMapping ) for _browserstring, res of tests _h.extractLanguage( _browserstring ).should.equal( res ) done() it 'fail by setting a unknown default language', ( done )-> try _h.setDefaultLanguage( "ab-cd" ) catch e e.message.should.equal( "soyer-helper: Default language not found in `LanguageMapping`" ) done() return
true
_ = require("lodash") path = require "path" should = require('should') Soyer = require("../lib/soyer/") _Cnf = path: path.resolve( __dirname, "./tmpls/" ) pathLang: path.resolve( __dirname, "./tmplsLang/" ) describe 'SOYER-TEST', -> before ( done )-> done() return after ( done )-> done() return describe 'No language support', -> soyerInst = null it 'get a soyer instance', ( done )-> soyerInst = new Soyer languagesupport: false path: _Cnf.path soyerInst.should.be.an.instanceOf Soyer done() return it 'load templates', ( done )-> soyerInst.load ( err, success )-> should.not.exist( err ) success.should.be.ok done() return return it 'render a test template', ( done )-> _renderd = soyerInst.render( "test.test1", {} ) _renderd.should.equal( "Hello World" ) done() return it 'render a test template with params', ( done )-> _renderd = soyerInst.render( "test.test2", { name: "PI:NAME:<NAME>END_PI" } ) _renderd.should.equal( "Hello PI:NAME:<NAME>END_PI" ) done() return return describe 'With language support', -> soyerInst = null it 'get a soyer instance', ( done )-> soyerInst = new Soyer languagesupport: true path: _Cnf.pathLang soyerInst.should.be.an.instanceOf Soyer done() return it 'load templates', ( done )-> soyerInst.load ( err, success )-> should.not.exist( err ) success.should.be.ok done() return return it 'render a test template in english', ( done )-> _renderd = soyerInst.render( "test.test1", "en-us", {} ) _renderd.should.equal( "Hello World" ) done() return it 'render a test template in german', ( done )-> _renderd = soyerInst.render( "test.test1", "de-de", {} ) _renderd.should.equal( "PI:NAME:<NAME>END_PI" ) done() return it 'render a test template with params in english', ( done )-> _renderd = soyerInst.render( "test.test2", "en-us", { name: "PI:NAME:<NAME>END_PI" } ) _renderd.should.equal( "Hello PI:NAME:<NAME>END_PI" ) done() return it 'render a test template with params in german', ( done )-> _renderd = soyerInst.render( "test.test2", "de-de", { name: "PI:NAME:<NAME>END_PI" } ) _renderd.should.equal( "PI:NAME:<NAME>END_PI" ) done() return return describe 'Helper Methods', -> _h = Soyer.helper it 'get language out of browser header-string `accepted-language`', ( done )-> tests = "en,fr-fr;q=0.8,fr;q=0.6,de-de;q=0.4,de;q=0.2": "en-us" "fr-fr;q=0.8": "en-us" "de": "de-de" "en": "en-us" "fr": "en-us" for _browserstring, res of tests _h.extractLanguage( _browserstring ).should.equal( res ) done() it 'get language out of browser header-string `accepted-language` with different default', ( done )-> tests = "en,fr-fr;q=0.8,fr;q=0.6,de-de;q=0.4,de;q=0.2": "en-us" "fr-fr;q=0.8": "de-de" "de": "de-de" "en": "en-us" "fr": "de-de" _h.setDefaultLanguage( "de-de" ) _h.getDefaultLanguage().should.equal( "de-de" ) for _browserstring, res of tests _h.extractLanguage( _browserstring ).should.equal( res ) done() it 'get language out of browser header-string `accepted-language` with new language', ( done )-> tests = "en,fr-fr;q=0.8,fr;q=0.6,de-de;q=0.4,de;q=0.2": "en-us" "fr-fr;q=0.8": "fr-fr" "de": "de-de" "en": "en-us" "fr": "fr-fr" LangMapping = "fr-fr": "fr-fr" "fr": "fr-fr" expLangMapping = "de-de": "de-de" "de": "de-de" "en-us": "en-us" "en-gb": "en-us" "en": "en-us" "fr-fr": "fr-fr" "fr": "fr-fr" _h.setLanguageMapping( LangMapping ) _h.getLanguageMapping().should.eql( expLangMapping ) for _browserstring, res of tests _h.extractLanguage( _browserstring ).should.equal( res ) done() it 'fail by setting a unknown default language', ( done )-> try _h.setDefaultLanguage( "ab-cd" ) catch e e.message.should.equal( "soyer-helper: Default language not found in `LanguageMapping`" ) done() return
[ { "context": "ngoose.model(\"User\")\n user = new User {\"email\": \"zjj@163.com\", \"password\": \"12345678\", \"confirmPassword\": \"123", "end": 497, "score": 0.9999241232872009, "start": 486, "tag": "EMAIL", "value": "zjj@163.com" }, { "context": " = new User {\"email\": \"zjj@1...
test_node/07.coffee
ZengJunyong/mean-140921
0
mongoose = require 'mongoose' mongoose.set 'debug', true # change to false if don't want log on console mongoose.connect 'mongodb://localhost/mean-dev', {}, (err)-> if err console.error 'Error:', err.message return console.error '**Could not connect to MongoDB. Please ensure mongod is running and restart MEAN app.**' console.log 'Connected MongoDB sucessfully' require '../packages/users/server/models/user' User = mongoose.model("User") user = new User {"email": "zjj@163.com", "password": "12345678", "confirmPassword": "12345678", "username": "jj", "name": "杰"} user.provider = "local" user.roles = ["authenticated"] user.save (err, data, count) -> console.log {err, data, count} if err switch err.code when 11000, 11001 console.log 400, [ msg: "Username already taken" param: "username" ] else modelErrors = [] if err.errors for x of err.errors modelErrors.push param: x msg: err.errors[x].message value: err.errors[x].value console.log 400, modelErrors return console.log 200, 'save user and login successfully' # TODO: why there is a field called __v?
86743
mongoose = require 'mongoose' mongoose.set 'debug', true # change to false if don't want log on console mongoose.connect 'mongodb://localhost/mean-dev', {}, (err)-> if err console.error 'Error:', err.message return console.error '**Could not connect to MongoDB. Please ensure mongod is running and restart MEAN app.**' console.log 'Connected MongoDB sucessfully' require '../packages/users/server/models/user' User = mongoose.model("User") user = new User {"email": "<EMAIL>", "password": "<PASSWORD>", "confirmPassword": "<PASSWORD>", "username": "jj", "name": "杰"} user.provider = "local" user.roles = ["authenticated"] user.save (err, data, count) -> console.log {err, data, count} if err switch err.code when 11000, 11001 console.log 400, [ msg: "Username already taken" param: "username" ] else modelErrors = [] if err.errors for x of err.errors modelErrors.push param: x msg: err.errors[x].message value: err.errors[x].value console.log 400, modelErrors return console.log 200, 'save user and login successfully' # TODO: why there is a field called __v?
true
mongoose = require 'mongoose' mongoose.set 'debug', true # change to false if don't want log on console mongoose.connect 'mongodb://localhost/mean-dev', {}, (err)-> if err console.error 'Error:', err.message return console.error '**Could not connect to MongoDB. Please ensure mongod is running and restart MEAN app.**' console.log 'Connected MongoDB sucessfully' require '../packages/users/server/models/user' User = mongoose.model("User") user = new User {"email": "PI:EMAIL:<EMAIL>END_PI", "password": "PI:PASSWORD:<PASSWORD>END_PI", "confirmPassword": "PI:PASSWORD:<PASSWORD>END_PI", "username": "jj", "name": "杰"} user.provider = "local" user.roles = ["authenticated"] user.save (err, data, count) -> console.log {err, data, count} if err switch err.code when 11000, 11001 console.log 400, [ msg: "Username already taken" param: "username" ] else modelErrors = [] if err.errors for x of err.errors modelErrors.push param: x msg: err.errors[x].message value: err.errors[x].value console.log 400, modelErrors return console.log 200, 'save user and login successfully' # TODO: why there is a field called __v?
[ { "context": "# author Alex Robson\n# copyright appendTo, 2012\n#\n# license MIT\n# Crea", "end": 20, "score": 0.9998421669006348, "start": 9, "tag": "NAME", "value": "Alex Robson" }, { "context": "2012\n#\n# license MIT\n# Created February 2, 2012 by Alex Robson\n\nspawnBunny = requ...
examples/node-to-erlang/rest-api/topology.coffee
arobson/vorperl
1
# author Alex Robson # copyright appendTo, 2012 # # license MIT # Created February 2, 2012 by Alex Robson spawnBunny = require('./rabbit').broker sys = require 'util' uuid = require 'uuid-lib' Reservations = () -> self = this accumulator = 0 declareExchange = (x) -> broker.exchange x.name, x.opts , onExchangeComplete declarePublishingExchanges = () -> exchanges= [ { name: nodeId, opts: {type: "direct", autoDelete: true}}, { name: "reservation", opts: {type: "fanout"}} ] self.remaining = exchanges.length declareExchange(x) for x in exchanges declareReceivingQueues = () -> broker.queue( nodeId, { autoDelete: true }, (q) -> broker.bind nodeId, nodeId, "" broker.subscribe nodeId, onMessage ) onExchangeComplete = () -> if (self.remaining -= 1) == 0 then declareReceivingQueues() console.log "#{self.remaining} exchanges left to declare" onMessage = (message, headers, deliveryInfo) -> if (callback = self.callbacks[headers.replyTo]) callback message.result else console.log "Received a message that can't be processed." registerCallback = (id, callback) -> self.callbacks[id] = callback reservation = ( exchange, command, user, resourceId, onResponse) -> #a = new Date() id = uuid.create().value registerCallback id, onResponse message = messageType: command userId: user broker.send exchange, "", message, correlationId: resourceId replyTo: nodeId messageId: id #accumulator += new Date() - a #console.log "******* #{accumulator}" self.reserve = (resourceId, user, onResponse) -> reservation "reservation", "reserve", user, resourceId, onResponse self.release = (resourceId, user, onResponse) -> reservation "reservation", "release", user, resourceId, onResponse self.status = (resourceId, user, onResponse) -> reservation "reservation", "status", user, resourceId, onResponse self = this self.callbacks = {} broker = {} spawnBunny (x) -> broker = x declarePublishingExchanges() console.log "#{broker}" nodeId = 'api.' + uuid.create().value self exports.reservations = new Reservations()
89357
# author <NAME> # copyright appendTo, 2012 # # license MIT # Created February 2, 2012 by <NAME> spawnBunny = require('./rabbit').broker sys = require 'util' uuid = require 'uuid-lib' Reservations = () -> self = this accumulator = 0 declareExchange = (x) -> broker.exchange x.name, x.opts , onExchangeComplete declarePublishingExchanges = () -> exchanges= [ { name: nodeId, opts: {type: "direct", autoDelete: true}}, { name: "reservation", opts: {type: "fanout"}} ] self.remaining = exchanges.length declareExchange(x) for x in exchanges declareReceivingQueues = () -> broker.queue( nodeId, { autoDelete: true }, (q) -> broker.bind nodeId, nodeId, "" broker.subscribe nodeId, onMessage ) onExchangeComplete = () -> if (self.remaining -= 1) == 0 then declareReceivingQueues() console.log "#{self.remaining} exchanges left to declare" onMessage = (message, headers, deliveryInfo) -> if (callback = self.callbacks[headers.replyTo]) callback message.result else console.log "Received a message that can't be processed." registerCallback = (id, callback) -> self.callbacks[id] = callback reservation = ( exchange, command, user, resourceId, onResponse) -> #a = new Date() id = uuid.create().value registerCallback id, onResponse message = messageType: command userId: user broker.send exchange, "", message, correlationId: resourceId replyTo: nodeId messageId: id #accumulator += new Date() - a #console.log "******* #{accumulator}" self.reserve = (resourceId, user, onResponse) -> reservation "reservation", "reserve", user, resourceId, onResponse self.release = (resourceId, user, onResponse) -> reservation "reservation", "release", user, resourceId, onResponse self.status = (resourceId, user, onResponse) -> reservation "reservation", "status", user, resourceId, onResponse self = this self.callbacks = {} broker = {} spawnBunny (x) -> broker = x declarePublishingExchanges() console.log "#{broker}" nodeId = 'api.' + uuid.create().value self exports.reservations = new Reservations()
true
# author PI:NAME:<NAME>END_PI # copyright appendTo, 2012 # # license MIT # Created February 2, 2012 by PI:NAME:<NAME>END_PI spawnBunny = require('./rabbit').broker sys = require 'util' uuid = require 'uuid-lib' Reservations = () -> self = this accumulator = 0 declareExchange = (x) -> broker.exchange x.name, x.opts , onExchangeComplete declarePublishingExchanges = () -> exchanges= [ { name: nodeId, opts: {type: "direct", autoDelete: true}}, { name: "reservation", opts: {type: "fanout"}} ] self.remaining = exchanges.length declareExchange(x) for x in exchanges declareReceivingQueues = () -> broker.queue( nodeId, { autoDelete: true }, (q) -> broker.bind nodeId, nodeId, "" broker.subscribe nodeId, onMessage ) onExchangeComplete = () -> if (self.remaining -= 1) == 0 then declareReceivingQueues() console.log "#{self.remaining} exchanges left to declare" onMessage = (message, headers, deliveryInfo) -> if (callback = self.callbacks[headers.replyTo]) callback message.result else console.log "Received a message that can't be processed." registerCallback = (id, callback) -> self.callbacks[id] = callback reservation = ( exchange, command, user, resourceId, onResponse) -> #a = new Date() id = uuid.create().value registerCallback id, onResponse message = messageType: command userId: user broker.send exchange, "", message, correlationId: resourceId replyTo: nodeId messageId: id #accumulator += new Date() - a #console.log "******* #{accumulator}" self.reserve = (resourceId, user, onResponse) -> reservation "reservation", "reserve", user, resourceId, onResponse self.release = (resourceId, user, onResponse) -> reservation "reservation", "release", user, resourceId, onResponse self.status = (resourceId, user, onResponse) -> reservation "reservation", "status", user, resourceId, onResponse self = this self.callbacks = {} broker = {} spawnBunny (x) -> broker = x declarePublishingExchanges() console.log "#{broker}" nodeId = 'api.' + uuid.create().value self exports.reservations = new Reservations()
[ { "context": "态为解析:\"+status\n RongIMLib.RongIMClient.connect \"BIG85AHHpMAXYvnD2DSgnLrkPG6U/xPk3zvPIWf9le1hEGTTL55/U07yY3a+mzGazeB0RzEl9Y46MnCyDLVMAw==\",\n onSuccess:(userId)->\n console.", "end": 777, "score": 0.9990614056587219, "start": 687, "tag": "KEY", "value": "...
test/spec/webSqlProviderSpec.coffee
nojsja/rongcloud-web-im-sdk-v2
98
describe "RongIMClient",-> RongIMLib.RongIMClient.init("8luwapkvucoil",new RongIMLib.WebSQLDataProvider) RongIMLib.RongIMClient.setOnReceiveMessageListener onReceived: (message) -> console.log message.content.content console.log message RongIMLib.RongIMClient.setConnectionStatusListener onChanged: (status) -> switch status when RongIMLib.ConnectionStatus.CONNECTED console.log "链接成功" when RongIMLib.ConnectionStatus.CONNECTING console.log "正在链接" when RongIMLib.ConnectionStatus.DISCONNECTED console.log "断开连接" else console.log "状态为解析:"+status RongIMLib.RongIMClient.connect "BIG85AHHpMAXYvnD2DSgnLrkPG6U/xPk3zvPIWf9le1hEGTTL55/U07yY3a+mzGazeB0RzEl9Y46MnCyDLVMAw==", onSuccess:(userId)-> console.log("loginSuccess,userId."+userId) onError:(error)-> switch error when RongIMLib.ConnectionState.SERVER_UNAVAILABLE console.log "SERVER_UNAVAILABLE" when RongIMLib.ConnectionState.TOKEN_INCORRECT console.log "token 无效" else console.log error it "sendMessage",(done)-> setTimeout(-> message = RongIMLib.TextMessage.obtain "rongcloud" #message = new EmptyMessage({Name:'悲伤2015',Age:18,Address:"beijing"}); RongIMLib.RongIMClient.getInstance().sendMessage RongIMLib.ConversationType.PRIVATE, "1005", message, onSuccess: (data)-> console.log JSON.stringify(data) done() onError: (errorcode)-> console.log errorcode ,1000)
47267
describe "RongIMClient",-> RongIMLib.RongIMClient.init("8luwapkvucoil",new RongIMLib.WebSQLDataProvider) RongIMLib.RongIMClient.setOnReceiveMessageListener onReceived: (message) -> console.log message.content.content console.log message RongIMLib.RongIMClient.setConnectionStatusListener onChanged: (status) -> switch status when RongIMLib.ConnectionStatus.CONNECTED console.log "链接成功" when RongIMLib.ConnectionStatus.CONNECTING console.log "正在链接" when RongIMLib.ConnectionStatus.DISCONNECTED console.log "断开连接" else console.log "状态为解析:"+status RongIMLib.RongIMClient.connect "<KEY> onSuccess:(userId)-> console.log("loginSuccess,userId."+userId) onError:(error)-> switch error when RongIMLib.ConnectionState.SERVER_UNAVAILABLE console.log "SERVER_UNAVAILABLE" when RongIMLib.ConnectionState.TOKEN_INCORRECT console.log "token 无效" else console.log error it "sendMessage",(done)-> setTimeout(-> message = RongIMLib.TextMessage.obtain "rongcloud" #message = new EmptyMessage({Name:'<NAME>',Age:18,Address:"beijing"}); RongIMLib.RongIMClient.getInstance().sendMessage RongIMLib.ConversationType.PRIVATE, "1005", message, onSuccess: (data)-> console.log JSON.stringify(data) done() onError: (errorcode)-> console.log errorcode ,1000)
true
describe "RongIMClient",-> RongIMLib.RongIMClient.init("8luwapkvucoil",new RongIMLib.WebSQLDataProvider) RongIMLib.RongIMClient.setOnReceiveMessageListener onReceived: (message) -> console.log message.content.content console.log message RongIMLib.RongIMClient.setConnectionStatusListener onChanged: (status) -> switch status when RongIMLib.ConnectionStatus.CONNECTED console.log "链接成功" when RongIMLib.ConnectionStatus.CONNECTING console.log "正在链接" when RongIMLib.ConnectionStatus.DISCONNECTED console.log "断开连接" else console.log "状态为解析:"+status RongIMLib.RongIMClient.connect "PI:KEY:<KEY>END_PI onSuccess:(userId)-> console.log("loginSuccess,userId."+userId) onError:(error)-> switch error when RongIMLib.ConnectionState.SERVER_UNAVAILABLE console.log "SERVER_UNAVAILABLE" when RongIMLib.ConnectionState.TOKEN_INCORRECT console.log "token 无效" else console.log error it "sendMessage",(done)-> setTimeout(-> message = RongIMLib.TextMessage.obtain "rongcloud" #message = new EmptyMessage({Name:'PI:NAME:<NAME>END_PI',Age:18,Address:"beijing"}); RongIMLib.RongIMClient.getInstance().sendMessage RongIMLib.ConversationType.PRIVATE, "1005", message, onSuccess: (data)-> console.log JSON.stringify(data) done() onError: (errorcode)-> console.log errorcode ,1000)
[ { "context": "onnector_startup', 'Connector starting',\n {user: 'varuna'}\nLOG 'info', 'connector_startup', 'Connector sta", "end": 100, "score": 0.9918544292449951, "start": 94, "tag": "USERNAME", "value": "varuna" }, { "context": "onnector_startup', 'Connector starting',\n {user: '...
test.coffee
vpj/log.js
0
LOG = (require './log').log LOG 'debug', 'connector_startup', 'Connector starting', {user: 'varuna'} LOG 'info', 'connector_startup', 'Connector starting' LOG 'warn', 'connector_startup', 'Connector starting', {user: 'varuna'} {stack: false} LOG 'error', 'connector_startup', 'Connector starting', {user: 'varuna'} {stack: false} LOG 'stat', 'connector_startup', 'Connector starting', {} {stack: false} LOG 'info', 'connector_startup', 'Connector starting', {user: {email: "vpj@test.com", age: 27}} {stack: true}
30889
LOG = (require './log').log LOG 'debug', 'connector_startup', 'Connector starting', {user: 'varuna'} LOG 'info', 'connector_startup', 'Connector starting' LOG 'warn', 'connector_startup', 'Connector starting', {user: 'varuna'} {stack: false} LOG 'error', 'connector_startup', 'Connector starting', {user: 'varuna'} {stack: false} LOG 'stat', 'connector_startup', 'Connector starting', {} {stack: false} LOG 'info', 'connector_startup', 'Connector starting', {user: {email: "<EMAIL>", age: 27}} {stack: true}
true
LOG = (require './log').log LOG 'debug', 'connector_startup', 'Connector starting', {user: 'varuna'} LOG 'info', 'connector_startup', 'Connector starting' LOG 'warn', 'connector_startup', 'Connector starting', {user: 'varuna'} {stack: false} LOG 'error', 'connector_startup', 'Connector starting', {user: 'varuna'} {stack: false} LOG 'stat', 'connector_startup', 'Connector starting', {} {stack: false} LOG 'info', 'connector_startup', 'Connector starting', {user: {email: "PI:EMAIL:<EMAIL>END_PI", age: 27}} {stack: true}