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": "s\n# hubot coprhd cli exec --help\n#\n# Author:\n# victorockeiro@gmail.com\n\nfs = require 'fs'\ncoprhd_bin = \"/opt/storageos", "end": 304, "score": 0.9999216794967651, "start": 281, "tag": "EMAIL", "value": "victorockeiro@gmail.com" } ]
src/coprhd.coffee
victorock/hubot-coprhd
0
# Description # A hubot script to interact with Storage Infrastructure. # # Configuration: # HUBOT_COPRHD_DEV - DEV Mode, no authentication required. # HUBOT_COPRHD_ROLE - Role to access CoprHD (using hubot-auth) # # Commands # hubot coprhd cli exec --help # # Author: # victorockeiro@gmail.com fs = require 'fs' coprhd_bin = "/opt/storageos/bin/cli/viprcli" if !(fs.existsSync coprhd_bin) && !(process.env.HUBOT_COPRHD_DEV) console.log "Missing #{coprhd_bin} file" console.log "Confirm if the package is installed properly" process.exit(1) ## Function: Wrapper for the Command-line coprhdCli = (options) -> exec = require('child_process').exec exec ("#{coprhd_bin} #{options}"), (error, stdout, stderr) -> console.error "coprhd: #{error}" if error console.error "coprhd: #{stderr}" if stderr console.log "coprhd: #{stdout}" if stdout return [ error, stdout, stderr ] ## Function: Check if user can access canAccess = (robot, user) -> return true if process.env.HUBOT_COPRHD_DEV if robot.auth.isAdmin(user) return true role = process.env.HUBOT_COPRHD_ROLE if role && robot.auth.hasRole(user, role) return true else return false module.exports = (robot) -> robot.commands.push "hubot coprhd cli exec <command>" robot.respond /((client|cli) exec) (.*)$/i, (msg) -> unless canAccess(robot, msg.envelope.user) msg.reply "You cannot access this feature. Please contact an admin." return args = msg.match[2].trim() msg.reply "executing..." [ error, stdout, stderr ] = coprhdCli( "#{command}" ) msg.reply "Error: #{error}" if error msg.reply "Stderr: #{stderr}" if stderr msg.reply "#{stdout}" if stdout msg.reply "Done :)"
188460
# Description # A hubot script to interact with Storage Infrastructure. # # Configuration: # HUBOT_COPRHD_DEV - DEV Mode, no authentication required. # HUBOT_COPRHD_ROLE - Role to access CoprHD (using hubot-auth) # # Commands # hubot coprhd cli exec --help # # Author: # <EMAIL> fs = require 'fs' coprhd_bin = "/opt/storageos/bin/cli/viprcli" if !(fs.existsSync coprhd_bin) && !(process.env.HUBOT_COPRHD_DEV) console.log "Missing #{coprhd_bin} file" console.log "Confirm if the package is installed properly" process.exit(1) ## Function: Wrapper for the Command-line coprhdCli = (options) -> exec = require('child_process').exec exec ("#{coprhd_bin} #{options}"), (error, stdout, stderr) -> console.error "coprhd: #{error}" if error console.error "coprhd: #{stderr}" if stderr console.log "coprhd: #{stdout}" if stdout return [ error, stdout, stderr ] ## Function: Check if user can access canAccess = (robot, user) -> return true if process.env.HUBOT_COPRHD_DEV if robot.auth.isAdmin(user) return true role = process.env.HUBOT_COPRHD_ROLE if role && robot.auth.hasRole(user, role) return true else return false module.exports = (robot) -> robot.commands.push "hubot coprhd cli exec <command>" robot.respond /((client|cli) exec) (.*)$/i, (msg) -> unless canAccess(robot, msg.envelope.user) msg.reply "You cannot access this feature. Please contact an admin." return args = msg.match[2].trim() msg.reply "executing..." [ error, stdout, stderr ] = coprhdCli( "#{command}" ) msg.reply "Error: #{error}" if error msg.reply "Stderr: #{stderr}" if stderr msg.reply "#{stdout}" if stdout msg.reply "Done :)"
true
# Description # A hubot script to interact with Storage Infrastructure. # # Configuration: # HUBOT_COPRHD_DEV - DEV Mode, no authentication required. # HUBOT_COPRHD_ROLE - Role to access CoprHD (using hubot-auth) # # Commands # hubot coprhd cli exec --help # # Author: # PI:EMAIL:<EMAIL>END_PI fs = require 'fs' coprhd_bin = "/opt/storageos/bin/cli/viprcli" if !(fs.existsSync coprhd_bin) && !(process.env.HUBOT_COPRHD_DEV) console.log "Missing #{coprhd_bin} file" console.log "Confirm if the package is installed properly" process.exit(1) ## Function: Wrapper for the Command-line coprhdCli = (options) -> exec = require('child_process').exec exec ("#{coprhd_bin} #{options}"), (error, stdout, stderr) -> console.error "coprhd: #{error}" if error console.error "coprhd: #{stderr}" if stderr console.log "coprhd: #{stdout}" if stdout return [ error, stdout, stderr ] ## Function: Check if user can access canAccess = (robot, user) -> return true if process.env.HUBOT_COPRHD_DEV if robot.auth.isAdmin(user) return true role = process.env.HUBOT_COPRHD_ROLE if role && robot.auth.hasRole(user, role) return true else return false module.exports = (robot) -> robot.commands.push "hubot coprhd cli exec <command>" robot.respond /((client|cli) exec) (.*)$/i, (msg) -> unless canAccess(robot, msg.envelope.user) msg.reply "You cannot access this feature. Please contact an admin." return args = msg.match[2].trim() msg.reply "executing..." [ error, stdout, stderr ] = coprhdCli( "#{command}" ) msg.reply "Error: #{error}" if error msg.reply "Stderr: #{stderr}" if stderr msg.reply "#{stdout}" if stdout msg.reply "Done :)"
[ { "context": "s string formatted as an hexadecimal value (i.e. '01294b7431234b5323f5588ce7d02703'\n @throw If the seed length is not 32 or if it", "end": 4393, "score": 0.9993296265602112, "start": 4361, "tag": "KEY", "value": "01294b7431234b5323f5588ce7d02703" }, { "context": "s ...
app/src/fup/firmware_update_request.coffee
romanornr/ledger-wallet-crw
173
ledger.fup ?= {} States = Undefined: 0 Erasing: 1 Unlocking: 2 SeedingKeycard: 3 LoadingOldApplication: 4 ReloadingBootloaderFromOs: 5 LoadingBootloader: 6 LoadingReloader: 7 LoadingBootloaderReloader: 8 LoadingOs: 9 InitializingOs: 10 Done: 11 Modes = Os: 0 Bootloader: 1 Errors = UnableToRetrieveVersion: ledger.errors.UnableToRetrieveVersion InvalidSeedSize: ledger.errors.InvalidSeedSize InvalidSeedFormat: ledger.errors.InvalidSeedFormat InconsistentState: ledger.errors.InconsistentState FailedToInitOs: ledger.errors.FailedToInitOs CommunicationError: ledger.errors.CommunicationError UnsupportedFirmware: ledger.errors.UnsupportedFirmware ErrorDongleMayHaveASeed: ledger.errors.ErrorDongleMayHaveASeed ErrorDueToCardPersonalization: ledger.errors.ErrorDueToCardPersonalization HigherVersion: ledger.errors.HigherVersion WrongPinCode: ledger.errors.WrongPinCode ExchangeTimeout = 200 ### FirmwareUpdateRequest performs dongle firmware updates. Once started it will listen the {DonglesManager} in order to catch connected dongles and update them. Only one instance of FirmwareUpdateRequest should be alive at the same time. (This is ensured by the {ledger.fup.FirmwareUpdater}) @event plug Emitted when the user must plug its dongle in @event unplug Emitted when the user must unplug its dongle @event stateChanged Emitted when the current state has changed. The event holds a data formatted like this: {oldState: ..., newState: ...} @event setKeyCardSeed Emitted once the key card seed is provided @event needsUserApproval Emitted once the request needs a user input to continue @event erasureStep Emitted each time the erasure step is trying to reset the dongle. The event holds the number of remaining steps before erasing is done. @event error Emitted once an error is throw. The event holds a data formatted like this: {cause: ...} ### class ledger.fup.FirmwareUpdateRequest extends @EventEmitter @States: States @Modes: Modes @Errors: Errors @ExchangeTimeout: ExchangeTimeout constructor: (firmwareUpdater, osLoader) -> @_id = _.uniqueId("fup") @_fup = firmwareUpdater @_getOsLoader ||= -> ledger.fup.updates[osLoader] @_keyCardSeed = null @_isRunning = no @_currentState = States.Undefined @_isNeedingUserApproval = no @_lastMode = Modes.Os @_dongleVersion = null @_isOsLoaded = no @_approvedStates = [] @_stateCache = {} # This holds the state related data @_exchangeNeedsExtraTimeout = no @_isWaitForDongleSilent = no @_isCancelled = no @_logger = ledger.utils.Logger.getLoggerByTag('FirmwareUpdateRequest') @_lastOriginalKey = undefined @_pinCode = undefined @_forceDongleErasure = no @_cardManager = new ledger.fup.CardManager() ### Stops all current tasks and listened events. ### cancel: () -> unless @_isCancelled @off() @_isRunning = no @_onProgress = null @_isCancelled = yes @_getCard()?.disconnect() @_fup._cancelRequest(this) @_cardManager.stopWaiting() onProgress: (callback) -> @_onProgress = callback hasGrantedErasurePermission: -> _.contains(@_approvedStates, "erasure") ### Approves the current request state and continue its execution. ### approveDongleErasure: -> @_approve 'erasure' approveCurrentState: -> @_setIsNeedingUserApproval no isNeedingUserApproval: -> @_isNeedingUserApproval ### ### unlockWithPinCode: (pin) -> @_pinCode = pin @_approve 'pincode' forceDongleErasure: -> if @_currentState is States.Unlocking @_forceDongleErasure = yes @_approve 'pincode' ### Gets the current dongle version @return [String] The current dongle version ### getDongleVersion: -> ledger.fup.utils.versionToString(@_dongleVersion) ### Gets the version to update @return [String] The target version ### getTargetVersion: -> ledger.fup.utils.versionToString(ledger.fup.versions.Nano.CurrentVersion.Os) getDongleFirmware: -> @_dongleVersion.getFirmwareInformation() ### Sets the key card seed used during the firmware update process. The seed must be a 32 characters string formatted as an hexadecimal value. @param [String] keyCardSeed A 32 characters string formatted as an hexadecimal value (i.e. '01294b7431234b5323f5588ce7d02703' @throw If the seed length is not 32 or if it is malformed ### setKeyCardSeed: (keyCardSeed) -> seed = @_keyCardSeedToByteString(keyCardSeed) throw seed.getError() if seed.isFailure() @_keyCardSeed = seed.getValue() @_approve('keycard') @emit "setKeyCardSeed" ### ### startUpdate: -> return if @_isRunning @_isRunning = yes @_currentState = States.Undefined @_handleCurrentState() isRunning: -> @_isRunning ### Checks if a given keycard seed is valid or not. The seed must be a 32 characters string formatted as an hexadecimal value. @param [String] keyCardSeed A 32 characters string formatted as an hexadecimal value (i.e. '01294b7431234b5323f5588ce7d02703' ### checkIfKeyCardSeedIsValid: (keyCardSeed) -> @_keyCardSeedToByteString(keyCardSeed).isSuccess() _keyCardSeedToByteString: (keyCardSeed) -> Try => throw new Error(Errors.InvalidSeedSize) if not keyCardSeed? or !(keyCardSeed.length is 32 or keyCardSeed.length is 80) seed = new ByteString(keyCardSeed, HEX) throw new Error(Errors.InvalidSeedFormat) if !seed? or !(seed.length is 16 or seed?.length is 40) seed ### Gets the current state. @return [ledger.fup.FirmwareUpdateRequest.States] The current request state ### getCurrentState: -> @_currentState ### Checks if the current request has a key card seed or not. @return [Boolean] Yes if the key card seed has been setup ### hasKeyCardSeed: () -> if @_keyCardSeed? then yes else no _waitForConnectedDongle: (silent = no) -> timeout = @emitAfter('plug', if !silent then 0 else 200) @_cardManager.waitForInsertion(silent).then ({card, mode}) => clearTimeout(timeout) @_resetOriginalKey() @_lastMode = mode @_card = new ledger.fup.Card(card) @_setCurrentState(States.Undefined) @_handleCurrentState() card .done() _waitForDisconnectDongle: (silent = no) -> timeout = @emitAfter('unplug', if !silent then 0 else 500) @_cardManager.waitForDisconnection(silent).then => clearTimeout(timeout) @_card = null _waitForPowerCycle: (callback = undefined, silent = no) -> @_waitForDisconnectDongle(silent).then(=> @_waitForConnectedDongle(silent)) _handleCurrentState: () -> # If there is no dongle wait for one return @_waitForConnectedDongle(yes) unless @_card? @_logger.info("Handle current state", lastMode: @_lastMode, currentState: @_currentState) if @_currentState is States.Undefined @_dongleVersion = null # Otherwise handle the current by calling the right method depending on the last mode and the state if @_lastMode is Modes.Os switch @_currentState when States.Undefined @_findOriginalKey() .then => @_processInitStageOs() .fail (error) => @_logger.error(error) .done() when States.ReloadingBootloaderFromOs then do @_processReloadBootloaderFromOs when States.InitializingOs then do @_processInitOs when States.Erasing then do @_processErasing when States.Unlocking then do @_processUnlocking when States.SeedingKeycard then do @_processSeedingKeycard else @_failure(Errors.InconsistentState) else switch @_currentState when States.Undefined then @_findOriginalKey().then(=> do @_processInitStageBootloader).fail(=> @_failure(Errors.CommunicationError)).done() when States.LoadingOs then do @_processLoadOs when States.LoadingBootloader then do @_processLoadBootloader when States.LoadingBootloaderReloader then do @_processLoadBootloaderReloader else @_failure(Errors.InconsistentState) _processInitStageOs: -> @_logger.info("Process init stage OS") if @_isApproved('erase') @_setCurrentState(States.Erasing) @_handleCurrentState() return @_getVersion().then (version) => @_dongleVersion = version firmware = version.getFirmwareInformation() checkVersion = => if version.equals(ledger.fup.versions.Nano.CurrentVersion.Os) if @_isOsLoaded @_setCurrentState(States.InitializingOs) @_handleCurrentState() else @_checkReloadRecoveryAndHandleState(firmware) else if version.gt(ledger.fup.versions.Nano.CurrentVersion.Os) @_failure(Errors.HigherVersion) else index = 0 while index < ledger.fup.updates.OS_INIT.length and !version.equals(ledger.fup.updates.OS_INIT[index][0]) index += 1 if index isnt ledger.fup.updates.OS_INIT.length @_processLoadingScript(ledger.fup.updates.OS_INIT[index][1], States.LoadingOldApplication, true) .then => @_checkReloadRecoveryAndHandleState(firmware) .fail (ex) => switch ex.message when 'timeout' @_waitForPowerCycle() else @_failure(Errors.CommunicationError) else @_checkReloadRecoveryAndHandleState(firmware) if !firmware.hasSubFirmwareSupport() and !@_keyCardSeed? @_setCurrentState(States.SeedingKeycard) @_handleCurrentState() else if !firmware.hasSubFirmwareSupport() @_card.getRemainingPinAttempt().then => @_setCurrentState(States.Erasing) @_handleCurrentState() .fail => checkVersion() else checkVersion() .fail => @_failure(Errors.UnableToRetrieveVersion) .done() _checkReloadRecoveryAndHandleState: (firmware) -> handleState = (state) => @_setCurrentState(state) @_handleCurrentState() return if firmware.hasRecoveryFlashingSupport() @_getCard().exchange_async(new ByteString("E02280000100", HEX)).then => if ((@_getCard().SW & 0xFFF0) == 0x63C0) && (@_getCard().SW != 0x63C0) handleState(States.Unlocking) else handleState(States.ReloadingBootloaderFromOs) else handleState(States.ReloadingBootloaderFromOs) return _processErasing: -> @_waitForUserApproval('erasure') .then => unless @_stateCache.pincode? getRandomChar = -> "0123456789".charAt(_.random(10)) @_stateCache.pincode = getRandomChar() + getRandomChar() pincode = @_stateCache.pincode @_card.unlockWithPinCode(pincode).then => @emit "erasureStep", 3 @_waitForPowerCycle() .fail (error) => @emit "erasureStep", if error?.remaining? then error.remaining else 3 @_waitForPowerCycle() .done() .fail (err) => @_failure(Errors.CommunicationError) .done() _processUnlocking: -> @_provisioned = no @_waitForUserApproval('pincode') .then => if @_forceDongleErasure @_setCurrentState(States.Erasing) @_handleCurrentState() else if @_pinCode.length is 0 @_setCurrentState(States.ReloadingBootloaderFromOs) @_handleCurrentState() return pin = new ByteString(@_pinCode, ASCII) @_getCard().exchange_async(new ByteString("E0220000" + Convert.toHexByte(pin.length), HEX).concat(pin)).then (result) => if @_getCard().SW is 0x9000 @_provisioned = yes @_setCurrentState(States.ReloadingBootloaderFromOs) @_handleCurrentState() return else throw Errors.WrongPinCode .fail => @_removeUserApproval('pincode') @_failure(Errors.WrongPinCode) .done() _processSeedingKeycard: -> @_waitForUserApproval('keycard') .then => @_setCurrentState(States.Undefined) @_handleCurrentState() .done() _tryToInitializeOs: -> continueInitOs = => @_setCurrentState(States.InitializingOs) @_handleCurrentState() if !@_keyCardSeed? @_setCurrentState(States.SeedingKeycard) @_waitForUserApproval('keycard') .then => @_setCurrentState(States.Undefined) do continueInitOs .done() else do continueInitOs _processInitOs: -> index = 0 while index < ledger.fup.updates.OS_INIT.length and !ledger.fup.utils.compareVersions(ledger.fup.versions.Nano.CurrentVersion.Os, ledger.fup.updates.OS_INIT[index][0]).eq() index += 1 currentInitScript = INIT_LW_1104 moddedInitScript = [] for i in [0...currentInitScript.length] moddedInitScript.push currentInitScript[i] if i is currentInitScript.length - 2 and @_keyCardSeed? moddedInitScript.push "D026000011" + "04" + @_keyCardSeed.bytes(0, 16).toString(HEX) moddedInitScript.push("D02A000018" + @_keyCardSeed.bytes(16).toString(HEX)) if @_keyCardSeed.length > 16 @_processLoadingScript moddedInitScript, States.InitializingOs, yes .then => @_success() @_isOsLoaded = no .fail (ex) => unless @_handleLoadingScriptError(ex) @_failure(Errors.FailedToInitOs) _processReloadBootloaderFromOs: -> @_removeUserApproval('erasure') @_removeUserApproval('pincode') @_waitForUserApproval('reloadbootloader') .then => @_removeUserApproval('reloadbootloader') index = 0 while index < ledger.fup.updates.BL_RELOADER.length and !@_dongleVersion.equals(ledger.fup.updates.BL_RELOADER[index][0]) index += 1 if index is ledger.fup.updates.BL_RELOADER.length @_failure(Errors.UnsupportedFirmware) return @_isWaitForDongleSilent = yes @_processLoadingScript ledger.fup.updates.BL_RELOADER[index][1], States.ReloadingBootloaderFromOs .then => @_waitForPowerCycle(null, yes) .fail (e) => unless @_handleLoadingScriptError(e) switch @_getCard().SW when 0x6985 l "Failed procces RELOAD BL FROM OS" @_processInitOs() return when 0x6faa then @_failure(Errors.ErrorDueToCardPersonalization) else @_failure(Errors.CommunicationError) @_waitForDisconnectDongle() .fail (err) -> console.error(err) _processInitStageBootloader: -> @_logger.info("Process init stage BL") @_lastVersion = null @_getVersion().then (version) => if version.equals(ledger.fup.versions.Nano.CurrentVersion.Bootloader) @_setCurrentState(States.LoadingOs) @_handleCurrentState() else continueInitStageBootloader = => if version.equals(ledger.fup.versions.Nano.CurrentVersion.Reloader) @_setCurrentState(States.LoadingBootloader) @_handleCurrentState() else SEND_RACE_BL = (1 << 16) + (3 << 8) + (11) @_exchangeNeedsExtraTimeout = version[1] < SEND_RACE_BL @_setCurrentState(States.LoadingBootloaderReloader) @_handleCurrentState() if !@_keyCardSeed? @_setCurrentState(States.SeedingKeycard) @_waitForUserApproval('keycard') .then => @_setCurrentState(States.Undefined) do continueInitStageBootloader .done() else do continueInitStageBootloader .fail => return @_failure(Errors.UnableToRetrieveVersion) .done() _processLoadOs: -> @_isOsLoaded = no @_findOriginalKey().then (offset) => @_isWaitForDongleSilent = yes @_processLoadingScript(@_getOsLoader()[offset], States.LoadingOs).then (result) => @_isOsLoaded = yes _.delay (=> @_waitForPowerCycle(null, yes)), 200 .fail (ex) => @_handleLoadingScriptError(ex) .fail (e) => @_isWaitForDongleSilent = no @_setCurrentState(States.Undefined) _processLoadBootloader: -> @_findOriginalKey().then (offset) => @_processLoadingScript(ledger.fup.updates.BL_LOADER[offset], States.LoadingBootloader) .then => @_waitForPowerCycle(null, yes) .fail (ex) => @_handleLoadingScriptError(ex) _processLoadBootloaderReloader: -> @_findOriginalKey().then (offset) => @_processLoadingScript(ledger.fup.updates.RELOADER_FROM_BL[offset], States.LoadingBootloaderReloader) .then => @_waitForPowerCycle(null, yes) .fail (ex) => @_handleLoadingScriptError(ex) _failure: (reason) -> @emit "error", cause: ledger.errors.new(reason) @_waitForPowerCycle() return _success: -> @_setCurrentState(States.Done, {provisioned: @_provisioned}) _.defer => @cancel() _attemptToFailDonglePinCode: (pincode) -> deferred = Q.defer() @_card.unlockWithPinCode pincode, (isUnlocked, error) => if isUnlocked or error.code isnt ledger.errors.WrongPinCode @emit "erasureStep", 3 @_waitForPowerCycle().then -> deferred.reject() else @emit "erasureStep", error.retryCount @_waitForPowerCycle() .then => @_dongle.getState (state) => deferred.resolve(state is ledger.dongle.States.BLANK or state is ledger.dongle.States.FROZEN) deferred.promise _setCurrentState: (newState, data = {}) -> oldState = @_currentState @_currentState = newState @emit 'stateChanged', _({oldState, newState}).extend(data) _setIsNeedingUserApproval: (value) -> if @_isNeedingUserApproval isnt value @_isNeedingUserApproval = value if @_isNeedingUserApproval is true @_deferredApproval = Q.defer() _.defer => @emit 'needsUserApproval' else defferedApproval = @_deferredApproval @_deferredApproval = null defferedApproval.resolve() return _approve: (approvalName) -> l "Approve ", approvalName, " waiting for ", @_deferredApproval?.approvalName if @_deferredApproval?.approvalName is approvalName @_setIsNeedingUserApproval no else @_approvedStates.push approvalName _cancelApproval: -> if @_isNeedingUserApproval @_isNeedingUserApproval = no defferedApproval = @_deferredApproval @_deferredApproval = null defferedApproval.reject("cancelled") _waitForUserApproval: (approvalName) -> if _.contains(@_approvedStates, approvalName) Q() else @_setIsNeedingUserApproval yes @_deferredApproval.approvalName = approvalName @_deferredApproval.promise.then => @_approvedStates.push approvalName _isApproved: (approvalName) -> _.contains(@_approvedStates, approvalName) _removeUserApproval: (approvalName) -> @_approvedStates = _(@_approvedStates).without(approvalName) return _processLoadingScript: (adpus, state, ignoreSW, offset = 0) -> d = ledger.defer() @_doProcessLoadingScript(adpus, state, ignoreSW, offset).then(-> d.resolve()).fail((ex) -> d.reject(ex)) d.promise _doProcessLoadingScript: (adpus, state, ignoreSW, offset, forceTimeout = no) -> @_notifyProgress(state, offset, adpus.length) if offset >= adpus.length @_exchangeNeedsExtraTimeout = no return try # BL not responding hack if state is States.ReloadingBootloaderFromOs and offset is adpus.length - 1 @_getCard().exchange_async(new ByteString(adpus[offset], HEX)) ledger.delay(1000).then => @_doProcessLoadingScript(adpus, state, ignoreSW, offset + 1) else _(@_getCard().exchange_async(new ByteString(adpus[offset], HEX))) .smartTimeout(500, 'timeout') .then => if ignoreSW or @_getCard().SW == 0x9000 if @_exchangeNeedsExtraTimeout or forceTimeout deferred = Q.defer() _.delay (=> deferred.resolve(@_doProcessLoadingScript(adpus, state, ignoreSW, offset + 1))), ExchangeTimeout deferred.promise else @_doProcessLoadingScript(adpus, state, ignoreSW, offset + 1) else @_exchangeNeedsExtraTimeout = no if forceTimeout is no @_doProcessLoadingScript(adpus, state, ignoreSW, offset, yes) else throw new Error('Unexpected status ' + @_getCard().SW) .fail (ex) => throw ex if ex?.message is 'timeout' return @_doProcessLoadingScript(adpus, state, ignoreSW, offset + 1) if offset is adpus.length - 1 @_exchangeNeedsExtraTimeout = no if forceTimeout is no @_doProcessLoadingScript(adpus, state, ignoreSW, offset, yes) else throw new Error("ADPU sending failed " + ex) catch ex e ex _handleLoadingScriptError: (ex) -> switch ex.message when 'timeout' @_waitForPowerCycle() else @_failure(Errors.CommunicationError) return _findOriginalKey: -> if @_lastOriginalKey? ledger.defer().resolve(@_lastOriginalKey).promise else _(@_getCard().exchange_async(new ByteString("F001010000", HEX), [0x9000])) .smartTimeout(500) .then (result) => l "CUST ID IS ", result.toString(HEX) if result?.toString? return if @_getCard().SW isnt 0x9000 or !result? for blCustomerId, offset in ledger.fup.updates.BL_CUSTOMER_ID when result.equals(blCustomerId) l "OFFSET IS", offset @_lastOriginalKey = offset return offset @_lastOriginalKey = undefined return .fail (er) => e "Failed findOriginalKey", er @_lastOriginalKey = undefined return _resetOriginalKey: -> @_lastOriginalKey = undefined _getCard: -> @_card?.getCard() _getVersion: -> return ledger.defer().resolve(@_dongleVersion).promise if @_dongleVersion? (if @_lastMode is Modes.Bootloader @_card.getVersion(Modes.Bootloader, yes) else @_card.getVersion(Modes.Os, no)).then (version) => @_dongleVersion = version _notifyProgress: (state, offset, total) -> _.defer => @_onProgress?(state, offset, total)
10140
ledger.fup ?= {} States = Undefined: 0 Erasing: 1 Unlocking: 2 SeedingKeycard: 3 LoadingOldApplication: 4 ReloadingBootloaderFromOs: 5 LoadingBootloader: 6 LoadingReloader: 7 LoadingBootloaderReloader: 8 LoadingOs: 9 InitializingOs: 10 Done: 11 Modes = Os: 0 Bootloader: 1 Errors = UnableToRetrieveVersion: ledger.errors.UnableToRetrieveVersion InvalidSeedSize: ledger.errors.InvalidSeedSize InvalidSeedFormat: ledger.errors.InvalidSeedFormat InconsistentState: ledger.errors.InconsistentState FailedToInitOs: ledger.errors.FailedToInitOs CommunicationError: ledger.errors.CommunicationError UnsupportedFirmware: ledger.errors.UnsupportedFirmware ErrorDongleMayHaveASeed: ledger.errors.ErrorDongleMayHaveASeed ErrorDueToCardPersonalization: ledger.errors.ErrorDueToCardPersonalization HigherVersion: ledger.errors.HigherVersion WrongPinCode: ledger.errors.WrongPinCode ExchangeTimeout = 200 ### FirmwareUpdateRequest performs dongle firmware updates. Once started it will listen the {DonglesManager} in order to catch connected dongles and update them. Only one instance of FirmwareUpdateRequest should be alive at the same time. (This is ensured by the {ledger.fup.FirmwareUpdater}) @event plug Emitted when the user must plug its dongle in @event unplug Emitted when the user must unplug its dongle @event stateChanged Emitted when the current state has changed. The event holds a data formatted like this: {oldState: ..., newState: ...} @event setKeyCardSeed Emitted once the key card seed is provided @event needsUserApproval Emitted once the request needs a user input to continue @event erasureStep Emitted each time the erasure step is trying to reset the dongle. The event holds the number of remaining steps before erasing is done. @event error Emitted once an error is throw. The event holds a data formatted like this: {cause: ...} ### class ledger.fup.FirmwareUpdateRequest extends @EventEmitter @States: States @Modes: Modes @Errors: Errors @ExchangeTimeout: ExchangeTimeout constructor: (firmwareUpdater, osLoader) -> @_id = _.uniqueId("fup") @_fup = firmwareUpdater @_getOsLoader ||= -> ledger.fup.updates[osLoader] @_keyCardSeed = null @_isRunning = no @_currentState = States.Undefined @_isNeedingUserApproval = no @_lastMode = Modes.Os @_dongleVersion = null @_isOsLoaded = no @_approvedStates = [] @_stateCache = {} # This holds the state related data @_exchangeNeedsExtraTimeout = no @_isWaitForDongleSilent = no @_isCancelled = no @_logger = ledger.utils.Logger.getLoggerByTag('FirmwareUpdateRequest') @_lastOriginalKey = undefined @_pinCode = undefined @_forceDongleErasure = no @_cardManager = new ledger.fup.CardManager() ### Stops all current tasks and listened events. ### cancel: () -> unless @_isCancelled @off() @_isRunning = no @_onProgress = null @_isCancelled = yes @_getCard()?.disconnect() @_fup._cancelRequest(this) @_cardManager.stopWaiting() onProgress: (callback) -> @_onProgress = callback hasGrantedErasurePermission: -> _.contains(@_approvedStates, "erasure") ### Approves the current request state and continue its execution. ### approveDongleErasure: -> @_approve 'erasure' approveCurrentState: -> @_setIsNeedingUserApproval no isNeedingUserApproval: -> @_isNeedingUserApproval ### ### unlockWithPinCode: (pin) -> @_pinCode = pin @_approve 'pincode' forceDongleErasure: -> if @_currentState is States.Unlocking @_forceDongleErasure = yes @_approve 'pincode' ### Gets the current dongle version @return [String] The current dongle version ### getDongleVersion: -> ledger.fup.utils.versionToString(@_dongleVersion) ### Gets the version to update @return [String] The target version ### getTargetVersion: -> ledger.fup.utils.versionToString(ledger.fup.versions.Nano.CurrentVersion.Os) getDongleFirmware: -> @_dongleVersion.getFirmwareInformation() ### Sets the key card seed used during the firmware update process. The seed must be a 32 characters string formatted as an hexadecimal value. @param [String] keyCardSeed A 32 characters string formatted as an hexadecimal value (i.e. '<KEY>' @throw If the seed length is not 32 or if it is malformed ### setKeyCardSeed: (keyCardSeed) -> seed = @_keyCardSeedToByteString(keyCardSeed) throw seed.getError() if seed.isFailure() @_keyCardSeed = seed.getValue() @_approve('keycard') @emit "setKeyCardSeed" ### ### startUpdate: -> return if @_isRunning @_isRunning = yes @_currentState = States.Undefined @_handleCurrentState() isRunning: -> @_isRunning ### Checks if a given keycard seed is valid or not. The seed must be a 32 characters string formatted as an hexadecimal value. @param [String] keyCardSeed A 32 characters string formatted as an hexadecimal value (i.e. '<KEY>' ### checkIfKeyCardSeedIsValid: (keyCardSeed) -> @_keyCardSeedToByteString(keyCardSeed).isSuccess() _keyCardSeedToByteString: (keyCardSeed) -> Try => throw new Error(Errors.InvalidSeedSize) if not keyCardSeed? or !(keyCardSeed.length is 32 or keyCardSeed.length is 80) seed = new ByteString(keyCardSeed, HEX) throw new Error(Errors.InvalidSeedFormat) if !seed? or !(seed.length is 16 or seed?.length is 40) seed ### Gets the current state. @return [ledger.fup.FirmwareUpdateRequest.States] The current request state ### getCurrentState: -> @_currentState ### Checks if the current request has a key card seed or not. @return [Boolean] Yes if the key card seed has been setup ### hasKeyCardSeed: () -> if @_keyCardSeed? then yes else no _waitForConnectedDongle: (silent = no) -> timeout = @emitAfter('plug', if !silent then 0 else 200) @_cardManager.waitForInsertion(silent).then ({card, mode}) => clearTimeout(timeout) @_resetOriginalKey() @_lastMode = mode @_card = new ledger.fup.Card(card) @_setCurrentState(States.Undefined) @_handleCurrentState() card .done() _waitForDisconnectDongle: (silent = no) -> timeout = @emitAfter('unplug', if !silent then 0 else 500) @_cardManager.waitForDisconnection(silent).then => clearTimeout(timeout) @_card = null _waitForPowerCycle: (callback = undefined, silent = no) -> @_waitForDisconnectDongle(silent).then(=> @_waitForConnectedDongle(silent)) _handleCurrentState: () -> # If there is no dongle wait for one return @_waitForConnectedDongle(yes) unless @_card? @_logger.info("Handle current state", lastMode: @_lastMode, currentState: @_currentState) if @_currentState is States.Undefined @_dongleVersion = null # Otherwise handle the current by calling the right method depending on the last mode and the state if @_lastMode is Modes.Os switch @_currentState when States.Undefined @_findOriginalKey() .then => @_processInitStageOs() .fail (error) => @_logger.error(error) .done() when States.ReloadingBootloaderFromOs then do @_processReloadBootloaderFromOs when States.InitializingOs then do @_processInitOs when States.Erasing then do @_processErasing when States.Unlocking then do @_processUnlocking when States.SeedingKeycard then do @_processSeedingKeycard else @_failure(Errors.InconsistentState) else switch @_currentState when States.Undefined then @_findOriginalKey().then(=> do @_processInitStageBootloader).fail(=> @_failure(Errors.CommunicationError)).done() when States.LoadingOs then do @_processLoadOs when States.LoadingBootloader then do @_processLoadBootloader when States.LoadingBootloaderReloader then do @_processLoadBootloaderReloader else @_failure(Errors.InconsistentState) _processInitStageOs: -> @_logger.info("Process init stage OS") if @_isApproved('erase') @_setCurrentState(States.Erasing) @_handleCurrentState() return @_getVersion().then (version) => @_dongleVersion = version firmware = version.getFirmwareInformation() checkVersion = => if version.equals(ledger.fup.versions.Nano.CurrentVersion.Os) if @_isOsLoaded @_setCurrentState(States.InitializingOs) @_handleCurrentState() else @_checkReloadRecoveryAndHandleState(firmware) else if version.gt(ledger.fup.versions.Nano.CurrentVersion.Os) @_failure(Errors.HigherVersion) else index = 0 while index < ledger.fup.updates.OS_INIT.length and !version.equals(ledger.fup.updates.OS_INIT[index][0]) index += 1 if index isnt ledger.fup.updates.OS_INIT.length @_processLoadingScript(ledger.fup.updates.OS_INIT[index][1], States.LoadingOldApplication, true) .then => @_checkReloadRecoveryAndHandleState(firmware) .fail (ex) => switch ex.message when 'timeout' @_waitForPowerCycle() else @_failure(Errors.CommunicationError) else @_checkReloadRecoveryAndHandleState(firmware) if !firmware.hasSubFirmwareSupport() and !@_keyCardSeed? @_setCurrentState(States.SeedingKeycard) @_handleCurrentState() else if !firmware.hasSubFirmwareSupport() @_card.getRemainingPinAttempt().then => @_setCurrentState(States.Erasing) @_handleCurrentState() .fail => checkVersion() else checkVersion() .fail => @_failure(Errors.UnableToRetrieveVersion) .done() _checkReloadRecoveryAndHandleState: (firmware) -> handleState = (state) => @_setCurrentState(state) @_handleCurrentState() return if firmware.hasRecoveryFlashingSupport() @_getCard().exchange_async(new ByteString("E02280000100", HEX)).then => if ((@_getCard().SW & 0xFFF0) == 0x63C0) && (@_getCard().SW != 0x63C0) handleState(States.Unlocking) else handleState(States.ReloadingBootloaderFromOs) else handleState(States.ReloadingBootloaderFromOs) return _processErasing: -> @_waitForUserApproval('erasure') .then => unless @_stateCache.pincode? getRandomChar = -> "0123456789".charAt(_.random(10)) @_stateCache.pincode = getRandomChar() + getRandomChar() pincode = @_stateCache.pincode @_card.unlockWithPinCode(pincode).then => @emit "erasureStep", 3 @_waitForPowerCycle() .fail (error) => @emit "erasureStep", if error?.remaining? then error.remaining else 3 @_waitForPowerCycle() .done() .fail (err) => @_failure(Errors.CommunicationError) .done() _processUnlocking: -> @_provisioned = no @_waitForUserApproval('pincode') .then => if @_forceDongleErasure @_setCurrentState(States.Erasing) @_handleCurrentState() else if @_pinCode.length is 0 @_setCurrentState(States.ReloadingBootloaderFromOs) @_handleCurrentState() return pin = new ByteString(@_pinCode, ASCII) @_getCard().exchange_async(new ByteString("E0220000" + Convert.toHexByte(pin.length), HEX).concat(pin)).then (result) => if @_getCard().SW is 0x9000 @_provisioned = yes @_setCurrentState(States.ReloadingBootloaderFromOs) @_handleCurrentState() return else throw Errors.WrongPinCode .fail => @_removeUserApproval('pincode') @_failure(Errors.WrongPinCode) .done() _processSeedingKeycard: -> @_waitForUserApproval('keycard') .then => @_setCurrentState(States.Undefined) @_handleCurrentState() .done() _tryToInitializeOs: -> continueInitOs = => @_setCurrentState(States.InitializingOs) @_handleCurrentState() if !@_keyCardSeed? @_setCurrentState(States.SeedingKeycard) @_waitForUserApproval('keycard') .then => @_setCurrentState(States.Undefined) do continueInitOs .done() else do continueInitOs _processInitOs: -> index = 0 while index < ledger.fup.updates.OS_INIT.length and !ledger.fup.utils.compareVersions(ledger.fup.versions.Nano.CurrentVersion.Os, ledger.fup.updates.OS_INIT[index][0]).eq() index += 1 currentInitScript = INIT_LW_1104 moddedInitScript = [] for i in [0...currentInitScript.length] moddedInitScript.push currentInitScript[i] if i is currentInitScript.length - 2 and @_keyCardSeed? moddedInitScript.push "D026000011" + "04" + @_keyCardSeed.bytes(0, 16).toString(HEX) moddedInitScript.push("D02A000018" + @_keyCardSeed.bytes(16).toString(HEX)) if @_keyCardSeed.length > 16 @_processLoadingScript moddedInitScript, States.InitializingOs, yes .then => @_success() @_isOsLoaded = no .fail (ex) => unless @_handleLoadingScriptError(ex) @_failure(Errors.FailedToInitOs) _processReloadBootloaderFromOs: -> @_removeUserApproval('erasure') @_removeUserApproval('pincode') @_waitForUserApproval('reloadbootloader') .then => @_removeUserApproval('reloadbootloader') index = 0 while index < ledger.fup.updates.BL_RELOADER.length and !@_dongleVersion.equals(ledger.fup.updates.BL_RELOADER[index][0]) index += 1 if index is ledger.fup.updates.BL_RELOADER.length @_failure(Errors.UnsupportedFirmware) return @_isWaitForDongleSilent = yes @_processLoadingScript ledger.fup.updates.BL_RELOADER[index][1], States.ReloadingBootloaderFromOs .then => @_waitForPowerCycle(null, yes) .fail (e) => unless @_handleLoadingScriptError(e) switch @_getCard().SW when 0x6985 l "Failed procces RELOAD BL FROM OS" @_processInitOs() return when 0x6faa then @_failure(Errors.ErrorDueToCardPersonalization) else @_failure(Errors.CommunicationError) @_waitForDisconnectDongle() .fail (err) -> console.error(err) _processInitStageBootloader: -> @_logger.info("Process init stage BL") @_lastVersion = null @_getVersion().then (version) => if version.equals(ledger.fup.versions.Nano.CurrentVersion.Bootloader) @_setCurrentState(States.LoadingOs) @_handleCurrentState() else continueInitStageBootloader = => if version.equals(ledger.fup.versions.Nano.CurrentVersion.Reloader) @_setCurrentState(States.LoadingBootloader) @_handleCurrentState() else SEND_RACE_BL = (1 << 16) + (3 << 8) + (11) @_exchangeNeedsExtraTimeout = version[1] < SEND_RACE_BL @_setCurrentState(States.LoadingBootloaderReloader) @_handleCurrentState() if !@_keyCardSeed? @_setCurrentState(States.SeedingKeycard) @_waitForUserApproval('keycard') .then => @_setCurrentState(States.Undefined) do continueInitStageBootloader .done() else do continueInitStageBootloader .fail => return @_failure(Errors.UnableToRetrieveVersion) .done() _processLoadOs: -> @_isOsLoaded = no @_findOriginalKey().then (offset) => @_isWaitForDongleSilent = yes @_processLoadingScript(@_getOsLoader()[offset], States.LoadingOs).then (result) => @_isOsLoaded = yes _.delay (=> @_waitForPowerCycle(null, yes)), 200 .fail (ex) => @_handleLoadingScriptError(ex) .fail (e) => @_isWaitForDongleSilent = no @_setCurrentState(States.Undefined) _processLoadBootloader: -> @_findOriginalKey().then (offset) => @_processLoadingScript(ledger.fup.updates.BL_LOADER[offset], States.LoadingBootloader) .then => @_waitForPowerCycle(null, yes) .fail (ex) => @_handleLoadingScriptError(ex) _processLoadBootloaderReloader: -> @_findOriginalKey().then (offset) => @_processLoadingScript(ledger.fup.updates.RELOADER_FROM_BL[offset], States.LoadingBootloaderReloader) .then => @_waitForPowerCycle(null, yes) .fail (ex) => @_handleLoadingScriptError(ex) _failure: (reason) -> @emit "error", cause: ledger.errors.new(reason) @_waitForPowerCycle() return _success: -> @_setCurrentState(States.Done, {provisioned: @_provisioned}) _.defer => @cancel() _attemptToFailDonglePinCode: (pincode) -> deferred = Q.defer() @_card.unlockWithPinCode pincode, (isUnlocked, error) => if isUnlocked or error.code isnt ledger.errors.WrongPinCode @emit "erasureStep", 3 @_waitForPowerCycle().then -> deferred.reject() else @emit "erasureStep", error.retryCount @_waitForPowerCycle() .then => @_dongle.getState (state) => deferred.resolve(state is ledger.dongle.States.BLANK or state is ledger.dongle.States.FROZEN) deferred.promise _setCurrentState: (newState, data = {}) -> oldState = @_currentState @_currentState = newState @emit 'stateChanged', _({oldState, newState}).extend(data) _setIsNeedingUserApproval: (value) -> if @_isNeedingUserApproval isnt value @_isNeedingUserApproval = value if @_isNeedingUserApproval is true @_deferredApproval = Q.defer() _.defer => @emit 'needsUserApproval' else defferedApproval = @_deferredApproval @_deferredApproval = null defferedApproval.resolve() return _approve: (approvalName) -> l "Approve ", approvalName, " waiting for ", @_deferredApproval?.approvalName if @_deferredApproval?.approvalName is approvalName @_setIsNeedingUserApproval no else @_approvedStates.push approvalName _cancelApproval: -> if @_isNeedingUserApproval @_isNeedingUserApproval = no defferedApproval = @_deferredApproval @_deferredApproval = null defferedApproval.reject("cancelled") _waitForUserApproval: (approvalName) -> if _.contains(@_approvedStates, approvalName) Q() else @_setIsNeedingUserApproval yes @_deferredApproval.approvalName = approvalName @_deferredApproval.promise.then => @_approvedStates.push approvalName _isApproved: (approvalName) -> _.contains(@_approvedStates, approvalName) _removeUserApproval: (approvalName) -> @_approvedStates = _(@_approvedStates).without(approvalName) return _processLoadingScript: (adpus, state, ignoreSW, offset = 0) -> d = ledger.defer() @_doProcessLoadingScript(adpus, state, ignoreSW, offset).then(-> d.resolve()).fail((ex) -> d.reject(ex)) d.promise _doProcessLoadingScript: (adpus, state, ignoreSW, offset, forceTimeout = no) -> @_notifyProgress(state, offset, adpus.length) if offset >= adpus.length @_exchangeNeedsExtraTimeout = no return try # BL not responding hack if state is States.ReloadingBootloaderFromOs and offset is adpus.length - 1 @_getCard().exchange_async(new ByteString(adpus[offset], HEX)) ledger.delay(1000).then => @_doProcessLoadingScript(adpus, state, ignoreSW, offset + 1) else _(@_getCard().exchange_async(new ByteString(adpus[offset], HEX))) .smartTimeout(500, 'timeout') .then => if ignoreSW or @_getCard().SW == 0x9000 if @_exchangeNeedsExtraTimeout or forceTimeout deferred = Q.defer() _.delay (=> deferred.resolve(@_doProcessLoadingScript(adpus, state, ignoreSW, offset + 1))), ExchangeTimeout deferred.promise else @_doProcessLoadingScript(adpus, state, ignoreSW, offset + 1) else @_exchangeNeedsExtraTimeout = no if forceTimeout is no @_doProcessLoadingScript(adpus, state, ignoreSW, offset, yes) else throw new Error('Unexpected status ' + @_getCard().SW) .fail (ex) => throw ex if ex?.message is 'timeout' return @_doProcessLoadingScript(adpus, state, ignoreSW, offset + 1) if offset is adpus.length - 1 @_exchangeNeedsExtraTimeout = no if forceTimeout is no @_doProcessLoadingScript(adpus, state, ignoreSW, offset, yes) else throw new Error("ADPU sending failed " + ex) catch ex e ex _handleLoadingScriptError: (ex) -> switch ex.message when 'timeout' @_waitForPowerCycle() else @_failure(Errors.CommunicationError) return _findOriginalKey: -> if @_lastOriginalKey? ledger.defer().resolve(@_lastOriginalKey).promise else _(@_getCard().exchange_async(new ByteString("F001010000", HEX), [0x9000])) .smartTimeout(500) .then (result) => l "CUST ID IS ", result.toString(HEX) if result?.toString? return if @_getCard().SW isnt 0x9000 or !result? for blCustomerId, offset in ledger.fup.updates.BL_CUSTOMER_ID when result.equals(blCustomerId) l "OFFSET IS", offset @_lastOriginalKey = offset return offset @_lastOriginalKey = undefined return .fail (er) => e "Failed findOriginalKey", er @_lastOriginalKey = undefined return _resetOriginalKey: -> @_lastOriginalKey = undefined _getCard: -> @_card?.getCard() _getVersion: -> return ledger.defer().resolve(@_dongleVersion).promise if @_dongleVersion? (if @_lastMode is Modes.Bootloader @_card.getVersion(Modes.Bootloader, yes) else @_card.getVersion(Modes.Os, no)).then (version) => @_dongleVersion = version _notifyProgress: (state, offset, total) -> _.defer => @_onProgress?(state, offset, total)
true
ledger.fup ?= {} States = Undefined: 0 Erasing: 1 Unlocking: 2 SeedingKeycard: 3 LoadingOldApplication: 4 ReloadingBootloaderFromOs: 5 LoadingBootloader: 6 LoadingReloader: 7 LoadingBootloaderReloader: 8 LoadingOs: 9 InitializingOs: 10 Done: 11 Modes = Os: 0 Bootloader: 1 Errors = UnableToRetrieveVersion: ledger.errors.UnableToRetrieveVersion InvalidSeedSize: ledger.errors.InvalidSeedSize InvalidSeedFormat: ledger.errors.InvalidSeedFormat InconsistentState: ledger.errors.InconsistentState FailedToInitOs: ledger.errors.FailedToInitOs CommunicationError: ledger.errors.CommunicationError UnsupportedFirmware: ledger.errors.UnsupportedFirmware ErrorDongleMayHaveASeed: ledger.errors.ErrorDongleMayHaveASeed ErrorDueToCardPersonalization: ledger.errors.ErrorDueToCardPersonalization HigherVersion: ledger.errors.HigherVersion WrongPinCode: ledger.errors.WrongPinCode ExchangeTimeout = 200 ### FirmwareUpdateRequest performs dongle firmware updates. Once started it will listen the {DonglesManager} in order to catch connected dongles and update them. Only one instance of FirmwareUpdateRequest should be alive at the same time. (This is ensured by the {ledger.fup.FirmwareUpdater}) @event plug Emitted when the user must plug its dongle in @event unplug Emitted when the user must unplug its dongle @event stateChanged Emitted when the current state has changed. The event holds a data formatted like this: {oldState: ..., newState: ...} @event setKeyCardSeed Emitted once the key card seed is provided @event needsUserApproval Emitted once the request needs a user input to continue @event erasureStep Emitted each time the erasure step is trying to reset the dongle. The event holds the number of remaining steps before erasing is done. @event error Emitted once an error is throw. The event holds a data formatted like this: {cause: ...} ### class ledger.fup.FirmwareUpdateRequest extends @EventEmitter @States: States @Modes: Modes @Errors: Errors @ExchangeTimeout: ExchangeTimeout constructor: (firmwareUpdater, osLoader) -> @_id = _.uniqueId("fup") @_fup = firmwareUpdater @_getOsLoader ||= -> ledger.fup.updates[osLoader] @_keyCardSeed = null @_isRunning = no @_currentState = States.Undefined @_isNeedingUserApproval = no @_lastMode = Modes.Os @_dongleVersion = null @_isOsLoaded = no @_approvedStates = [] @_stateCache = {} # This holds the state related data @_exchangeNeedsExtraTimeout = no @_isWaitForDongleSilent = no @_isCancelled = no @_logger = ledger.utils.Logger.getLoggerByTag('FirmwareUpdateRequest') @_lastOriginalKey = undefined @_pinCode = undefined @_forceDongleErasure = no @_cardManager = new ledger.fup.CardManager() ### Stops all current tasks and listened events. ### cancel: () -> unless @_isCancelled @off() @_isRunning = no @_onProgress = null @_isCancelled = yes @_getCard()?.disconnect() @_fup._cancelRequest(this) @_cardManager.stopWaiting() onProgress: (callback) -> @_onProgress = callback hasGrantedErasurePermission: -> _.contains(@_approvedStates, "erasure") ### Approves the current request state and continue its execution. ### approveDongleErasure: -> @_approve 'erasure' approveCurrentState: -> @_setIsNeedingUserApproval no isNeedingUserApproval: -> @_isNeedingUserApproval ### ### unlockWithPinCode: (pin) -> @_pinCode = pin @_approve 'pincode' forceDongleErasure: -> if @_currentState is States.Unlocking @_forceDongleErasure = yes @_approve 'pincode' ### Gets the current dongle version @return [String] The current dongle version ### getDongleVersion: -> ledger.fup.utils.versionToString(@_dongleVersion) ### Gets the version to update @return [String] The target version ### getTargetVersion: -> ledger.fup.utils.versionToString(ledger.fup.versions.Nano.CurrentVersion.Os) getDongleFirmware: -> @_dongleVersion.getFirmwareInformation() ### Sets the key card seed used during the firmware update process. The seed must be a 32 characters string formatted as an hexadecimal value. @param [String] keyCardSeed A 32 characters string formatted as an hexadecimal value (i.e. 'PI:KEY:<KEY>END_PI' @throw If the seed length is not 32 or if it is malformed ### setKeyCardSeed: (keyCardSeed) -> seed = @_keyCardSeedToByteString(keyCardSeed) throw seed.getError() if seed.isFailure() @_keyCardSeed = seed.getValue() @_approve('keycard') @emit "setKeyCardSeed" ### ### startUpdate: -> return if @_isRunning @_isRunning = yes @_currentState = States.Undefined @_handleCurrentState() isRunning: -> @_isRunning ### Checks if a given keycard seed is valid or not. The seed must be a 32 characters string formatted as an hexadecimal value. @param [String] keyCardSeed A 32 characters string formatted as an hexadecimal value (i.e. 'PI:KEY:<KEY>END_PI' ### checkIfKeyCardSeedIsValid: (keyCardSeed) -> @_keyCardSeedToByteString(keyCardSeed).isSuccess() _keyCardSeedToByteString: (keyCardSeed) -> Try => throw new Error(Errors.InvalidSeedSize) if not keyCardSeed? or !(keyCardSeed.length is 32 or keyCardSeed.length is 80) seed = new ByteString(keyCardSeed, HEX) throw new Error(Errors.InvalidSeedFormat) if !seed? or !(seed.length is 16 or seed?.length is 40) seed ### Gets the current state. @return [ledger.fup.FirmwareUpdateRequest.States] The current request state ### getCurrentState: -> @_currentState ### Checks if the current request has a key card seed or not. @return [Boolean] Yes if the key card seed has been setup ### hasKeyCardSeed: () -> if @_keyCardSeed? then yes else no _waitForConnectedDongle: (silent = no) -> timeout = @emitAfter('plug', if !silent then 0 else 200) @_cardManager.waitForInsertion(silent).then ({card, mode}) => clearTimeout(timeout) @_resetOriginalKey() @_lastMode = mode @_card = new ledger.fup.Card(card) @_setCurrentState(States.Undefined) @_handleCurrentState() card .done() _waitForDisconnectDongle: (silent = no) -> timeout = @emitAfter('unplug', if !silent then 0 else 500) @_cardManager.waitForDisconnection(silent).then => clearTimeout(timeout) @_card = null _waitForPowerCycle: (callback = undefined, silent = no) -> @_waitForDisconnectDongle(silent).then(=> @_waitForConnectedDongle(silent)) _handleCurrentState: () -> # If there is no dongle wait for one return @_waitForConnectedDongle(yes) unless @_card? @_logger.info("Handle current state", lastMode: @_lastMode, currentState: @_currentState) if @_currentState is States.Undefined @_dongleVersion = null # Otherwise handle the current by calling the right method depending on the last mode and the state if @_lastMode is Modes.Os switch @_currentState when States.Undefined @_findOriginalKey() .then => @_processInitStageOs() .fail (error) => @_logger.error(error) .done() when States.ReloadingBootloaderFromOs then do @_processReloadBootloaderFromOs when States.InitializingOs then do @_processInitOs when States.Erasing then do @_processErasing when States.Unlocking then do @_processUnlocking when States.SeedingKeycard then do @_processSeedingKeycard else @_failure(Errors.InconsistentState) else switch @_currentState when States.Undefined then @_findOriginalKey().then(=> do @_processInitStageBootloader).fail(=> @_failure(Errors.CommunicationError)).done() when States.LoadingOs then do @_processLoadOs when States.LoadingBootloader then do @_processLoadBootloader when States.LoadingBootloaderReloader then do @_processLoadBootloaderReloader else @_failure(Errors.InconsistentState) _processInitStageOs: -> @_logger.info("Process init stage OS") if @_isApproved('erase') @_setCurrentState(States.Erasing) @_handleCurrentState() return @_getVersion().then (version) => @_dongleVersion = version firmware = version.getFirmwareInformation() checkVersion = => if version.equals(ledger.fup.versions.Nano.CurrentVersion.Os) if @_isOsLoaded @_setCurrentState(States.InitializingOs) @_handleCurrentState() else @_checkReloadRecoveryAndHandleState(firmware) else if version.gt(ledger.fup.versions.Nano.CurrentVersion.Os) @_failure(Errors.HigherVersion) else index = 0 while index < ledger.fup.updates.OS_INIT.length and !version.equals(ledger.fup.updates.OS_INIT[index][0]) index += 1 if index isnt ledger.fup.updates.OS_INIT.length @_processLoadingScript(ledger.fup.updates.OS_INIT[index][1], States.LoadingOldApplication, true) .then => @_checkReloadRecoveryAndHandleState(firmware) .fail (ex) => switch ex.message when 'timeout' @_waitForPowerCycle() else @_failure(Errors.CommunicationError) else @_checkReloadRecoveryAndHandleState(firmware) if !firmware.hasSubFirmwareSupport() and !@_keyCardSeed? @_setCurrentState(States.SeedingKeycard) @_handleCurrentState() else if !firmware.hasSubFirmwareSupport() @_card.getRemainingPinAttempt().then => @_setCurrentState(States.Erasing) @_handleCurrentState() .fail => checkVersion() else checkVersion() .fail => @_failure(Errors.UnableToRetrieveVersion) .done() _checkReloadRecoveryAndHandleState: (firmware) -> handleState = (state) => @_setCurrentState(state) @_handleCurrentState() return if firmware.hasRecoveryFlashingSupport() @_getCard().exchange_async(new ByteString("E02280000100", HEX)).then => if ((@_getCard().SW & 0xFFF0) == 0x63C0) && (@_getCard().SW != 0x63C0) handleState(States.Unlocking) else handleState(States.ReloadingBootloaderFromOs) else handleState(States.ReloadingBootloaderFromOs) return _processErasing: -> @_waitForUserApproval('erasure') .then => unless @_stateCache.pincode? getRandomChar = -> "0123456789".charAt(_.random(10)) @_stateCache.pincode = getRandomChar() + getRandomChar() pincode = @_stateCache.pincode @_card.unlockWithPinCode(pincode).then => @emit "erasureStep", 3 @_waitForPowerCycle() .fail (error) => @emit "erasureStep", if error?.remaining? then error.remaining else 3 @_waitForPowerCycle() .done() .fail (err) => @_failure(Errors.CommunicationError) .done() _processUnlocking: -> @_provisioned = no @_waitForUserApproval('pincode') .then => if @_forceDongleErasure @_setCurrentState(States.Erasing) @_handleCurrentState() else if @_pinCode.length is 0 @_setCurrentState(States.ReloadingBootloaderFromOs) @_handleCurrentState() return pin = new ByteString(@_pinCode, ASCII) @_getCard().exchange_async(new ByteString("E0220000" + Convert.toHexByte(pin.length), HEX).concat(pin)).then (result) => if @_getCard().SW is 0x9000 @_provisioned = yes @_setCurrentState(States.ReloadingBootloaderFromOs) @_handleCurrentState() return else throw Errors.WrongPinCode .fail => @_removeUserApproval('pincode') @_failure(Errors.WrongPinCode) .done() _processSeedingKeycard: -> @_waitForUserApproval('keycard') .then => @_setCurrentState(States.Undefined) @_handleCurrentState() .done() _tryToInitializeOs: -> continueInitOs = => @_setCurrentState(States.InitializingOs) @_handleCurrentState() if !@_keyCardSeed? @_setCurrentState(States.SeedingKeycard) @_waitForUserApproval('keycard') .then => @_setCurrentState(States.Undefined) do continueInitOs .done() else do continueInitOs _processInitOs: -> index = 0 while index < ledger.fup.updates.OS_INIT.length and !ledger.fup.utils.compareVersions(ledger.fup.versions.Nano.CurrentVersion.Os, ledger.fup.updates.OS_INIT[index][0]).eq() index += 1 currentInitScript = INIT_LW_1104 moddedInitScript = [] for i in [0...currentInitScript.length] moddedInitScript.push currentInitScript[i] if i is currentInitScript.length - 2 and @_keyCardSeed? moddedInitScript.push "D026000011" + "04" + @_keyCardSeed.bytes(0, 16).toString(HEX) moddedInitScript.push("D02A000018" + @_keyCardSeed.bytes(16).toString(HEX)) if @_keyCardSeed.length > 16 @_processLoadingScript moddedInitScript, States.InitializingOs, yes .then => @_success() @_isOsLoaded = no .fail (ex) => unless @_handleLoadingScriptError(ex) @_failure(Errors.FailedToInitOs) _processReloadBootloaderFromOs: -> @_removeUserApproval('erasure') @_removeUserApproval('pincode') @_waitForUserApproval('reloadbootloader') .then => @_removeUserApproval('reloadbootloader') index = 0 while index < ledger.fup.updates.BL_RELOADER.length and !@_dongleVersion.equals(ledger.fup.updates.BL_RELOADER[index][0]) index += 1 if index is ledger.fup.updates.BL_RELOADER.length @_failure(Errors.UnsupportedFirmware) return @_isWaitForDongleSilent = yes @_processLoadingScript ledger.fup.updates.BL_RELOADER[index][1], States.ReloadingBootloaderFromOs .then => @_waitForPowerCycle(null, yes) .fail (e) => unless @_handleLoadingScriptError(e) switch @_getCard().SW when 0x6985 l "Failed procces RELOAD BL FROM OS" @_processInitOs() return when 0x6faa then @_failure(Errors.ErrorDueToCardPersonalization) else @_failure(Errors.CommunicationError) @_waitForDisconnectDongle() .fail (err) -> console.error(err) _processInitStageBootloader: -> @_logger.info("Process init stage BL") @_lastVersion = null @_getVersion().then (version) => if version.equals(ledger.fup.versions.Nano.CurrentVersion.Bootloader) @_setCurrentState(States.LoadingOs) @_handleCurrentState() else continueInitStageBootloader = => if version.equals(ledger.fup.versions.Nano.CurrentVersion.Reloader) @_setCurrentState(States.LoadingBootloader) @_handleCurrentState() else SEND_RACE_BL = (1 << 16) + (3 << 8) + (11) @_exchangeNeedsExtraTimeout = version[1] < SEND_RACE_BL @_setCurrentState(States.LoadingBootloaderReloader) @_handleCurrentState() if !@_keyCardSeed? @_setCurrentState(States.SeedingKeycard) @_waitForUserApproval('keycard') .then => @_setCurrentState(States.Undefined) do continueInitStageBootloader .done() else do continueInitStageBootloader .fail => return @_failure(Errors.UnableToRetrieveVersion) .done() _processLoadOs: -> @_isOsLoaded = no @_findOriginalKey().then (offset) => @_isWaitForDongleSilent = yes @_processLoadingScript(@_getOsLoader()[offset], States.LoadingOs).then (result) => @_isOsLoaded = yes _.delay (=> @_waitForPowerCycle(null, yes)), 200 .fail (ex) => @_handleLoadingScriptError(ex) .fail (e) => @_isWaitForDongleSilent = no @_setCurrentState(States.Undefined) _processLoadBootloader: -> @_findOriginalKey().then (offset) => @_processLoadingScript(ledger.fup.updates.BL_LOADER[offset], States.LoadingBootloader) .then => @_waitForPowerCycle(null, yes) .fail (ex) => @_handleLoadingScriptError(ex) _processLoadBootloaderReloader: -> @_findOriginalKey().then (offset) => @_processLoadingScript(ledger.fup.updates.RELOADER_FROM_BL[offset], States.LoadingBootloaderReloader) .then => @_waitForPowerCycle(null, yes) .fail (ex) => @_handleLoadingScriptError(ex) _failure: (reason) -> @emit "error", cause: ledger.errors.new(reason) @_waitForPowerCycle() return _success: -> @_setCurrentState(States.Done, {provisioned: @_provisioned}) _.defer => @cancel() _attemptToFailDonglePinCode: (pincode) -> deferred = Q.defer() @_card.unlockWithPinCode pincode, (isUnlocked, error) => if isUnlocked or error.code isnt ledger.errors.WrongPinCode @emit "erasureStep", 3 @_waitForPowerCycle().then -> deferred.reject() else @emit "erasureStep", error.retryCount @_waitForPowerCycle() .then => @_dongle.getState (state) => deferred.resolve(state is ledger.dongle.States.BLANK or state is ledger.dongle.States.FROZEN) deferred.promise _setCurrentState: (newState, data = {}) -> oldState = @_currentState @_currentState = newState @emit 'stateChanged', _({oldState, newState}).extend(data) _setIsNeedingUserApproval: (value) -> if @_isNeedingUserApproval isnt value @_isNeedingUserApproval = value if @_isNeedingUserApproval is true @_deferredApproval = Q.defer() _.defer => @emit 'needsUserApproval' else defferedApproval = @_deferredApproval @_deferredApproval = null defferedApproval.resolve() return _approve: (approvalName) -> l "Approve ", approvalName, " waiting for ", @_deferredApproval?.approvalName if @_deferredApproval?.approvalName is approvalName @_setIsNeedingUserApproval no else @_approvedStates.push approvalName _cancelApproval: -> if @_isNeedingUserApproval @_isNeedingUserApproval = no defferedApproval = @_deferredApproval @_deferredApproval = null defferedApproval.reject("cancelled") _waitForUserApproval: (approvalName) -> if _.contains(@_approvedStates, approvalName) Q() else @_setIsNeedingUserApproval yes @_deferredApproval.approvalName = approvalName @_deferredApproval.promise.then => @_approvedStates.push approvalName _isApproved: (approvalName) -> _.contains(@_approvedStates, approvalName) _removeUserApproval: (approvalName) -> @_approvedStates = _(@_approvedStates).without(approvalName) return _processLoadingScript: (adpus, state, ignoreSW, offset = 0) -> d = ledger.defer() @_doProcessLoadingScript(adpus, state, ignoreSW, offset).then(-> d.resolve()).fail((ex) -> d.reject(ex)) d.promise _doProcessLoadingScript: (adpus, state, ignoreSW, offset, forceTimeout = no) -> @_notifyProgress(state, offset, adpus.length) if offset >= adpus.length @_exchangeNeedsExtraTimeout = no return try # BL not responding hack if state is States.ReloadingBootloaderFromOs and offset is adpus.length - 1 @_getCard().exchange_async(new ByteString(adpus[offset], HEX)) ledger.delay(1000).then => @_doProcessLoadingScript(adpus, state, ignoreSW, offset + 1) else _(@_getCard().exchange_async(new ByteString(adpus[offset], HEX))) .smartTimeout(500, 'timeout') .then => if ignoreSW or @_getCard().SW == 0x9000 if @_exchangeNeedsExtraTimeout or forceTimeout deferred = Q.defer() _.delay (=> deferred.resolve(@_doProcessLoadingScript(adpus, state, ignoreSW, offset + 1))), ExchangeTimeout deferred.promise else @_doProcessLoadingScript(adpus, state, ignoreSW, offset + 1) else @_exchangeNeedsExtraTimeout = no if forceTimeout is no @_doProcessLoadingScript(adpus, state, ignoreSW, offset, yes) else throw new Error('Unexpected status ' + @_getCard().SW) .fail (ex) => throw ex if ex?.message is 'timeout' return @_doProcessLoadingScript(adpus, state, ignoreSW, offset + 1) if offset is adpus.length - 1 @_exchangeNeedsExtraTimeout = no if forceTimeout is no @_doProcessLoadingScript(adpus, state, ignoreSW, offset, yes) else throw new Error("ADPU sending failed " + ex) catch ex e ex _handleLoadingScriptError: (ex) -> switch ex.message when 'timeout' @_waitForPowerCycle() else @_failure(Errors.CommunicationError) return _findOriginalKey: -> if @_lastOriginalKey? ledger.defer().resolve(@_lastOriginalKey).promise else _(@_getCard().exchange_async(new ByteString("F001010000", HEX), [0x9000])) .smartTimeout(500) .then (result) => l "CUST ID IS ", result.toString(HEX) if result?.toString? return if @_getCard().SW isnt 0x9000 or !result? for blCustomerId, offset in ledger.fup.updates.BL_CUSTOMER_ID when result.equals(blCustomerId) l "OFFSET IS", offset @_lastOriginalKey = offset return offset @_lastOriginalKey = undefined return .fail (er) => e "Failed findOriginalKey", er @_lastOriginalKey = undefined return _resetOriginalKey: -> @_lastOriginalKey = undefined _getCard: -> @_card?.getCard() _getVersion: -> return ledger.defer().resolve(@_dongleVersion).promise if @_dongleVersion? (if @_lastMode is Modes.Bootloader @_card.getVersion(Modes.Bootloader, yes) else @_card.getVersion(Modes.Os, no)).then (version) => @_dongleVersion = version _notifyProgress: (state, offset, total) -> _.defer => @_onProgress?(state, offset, total)
[ { "context": "on trigger the transitionstart event\n#\n# @author Olivier Bossel <olivier.bossel@gmail.com>\n# @created 22.01.16\n#", "end": 171, "score": 0.9998778700828552, "start": 157, "tag": "NAME", "value": "Olivier Bossel" }, { "context": "ansitionstart event\n#\n# @author ...
node_modules/sugarcss/coffee/sugar-transitionstart.coffee
hagsey/nlpt2
0
### # Sugar-transitionstart.js # # This little js file allow you to make your element that have a transition trigger the transitionstart event # # @author Olivier Bossel <olivier.bossel@gmail.com> # @created 22.01.16 # @updated 22.01.16 # @version 1.0.0 ### ((factory) -> if typeof define == 'function' and define.amd # AMD. Register as an anonymous module. define [ ], factory else if typeof exports == 'object' # Node/CommonJS factory() else # Browser globals factory() return ) () -> window.SugarTransitionStart = # track if already inited _inited : false # enabled enabled : true ### Init ### init : () -> # update inited state @_inited = true # wait until the dom is loaded if document.readyState == 'interactive' then @_init() else document.addEventListener 'DOMContentLoaded', (e) => @_init() ### Internal init ### _init : -> # do nothing if not enabled return if not @enabled # listen animations start document.addEventListener("transitionend", @_onTransitionEnd, false); document.addEventListener("oTransitionEnd", @_onTransitionEnd, false); document.addEventListener("webkitTransitionEnd", @_onTransitionEnd, false); ### On animation start ### _onTransitionEnd : (e) -> if e.elapsedTime == 0.000001 console.log 'transitionstart' e.target.dispatchEvent(new CustomEvent('transitionstart', { bubbles : true, cancelable : true })); # init the filter SugarTransitionStart.init() # return the Sugar object SugarTransitionStart
104756
### # Sugar-transitionstart.js # # This little js file allow you to make your element that have a transition trigger the transitionstart event # # @author <NAME> <<EMAIL>> # @created 22.01.16 # @updated 22.01.16 # @version 1.0.0 ### ((factory) -> if typeof define == 'function' and define.amd # AMD. Register as an anonymous module. define [ ], factory else if typeof exports == 'object' # Node/CommonJS factory() else # Browser globals factory() return ) () -> window.SugarTransitionStart = # track if already inited _inited : false # enabled enabled : true ### Init ### init : () -> # update inited state @_inited = true # wait until the dom is loaded if document.readyState == 'interactive' then @_init() else document.addEventListener 'DOMContentLoaded', (e) => @_init() ### Internal init ### _init : -> # do nothing if not enabled return if not @enabled # listen animations start document.addEventListener("transitionend", @_onTransitionEnd, false); document.addEventListener("oTransitionEnd", @_onTransitionEnd, false); document.addEventListener("webkitTransitionEnd", @_onTransitionEnd, false); ### On animation start ### _onTransitionEnd : (e) -> if e.elapsedTime == 0.000001 console.log 'transitionstart' e.target.dispatchEvent(new CustomEvent('transitionstart', { bubbles : true, cancelable : true })); # init the filter SugarTransitionStart.init() # return the Sugar object SugarTransitionStart
true
### # Sugar-transitionstart.js # # This little js file allow you to make your element that have a transition trigger the transitionstart event # # @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # @created 22.01.16 # @updated 22.01.16 # @version 1.0.0 ### ((factory) -> if typeof define == 'function' and define.amd # AMD. Register as an anonymous module. define [ ], factory else if typeof exports == 'object' # Node/CommonJS factory() else # Browser globals factory() return ) () -> window.SugarTransitionStart = # track if already inited _inited : false # enabled enabled : true ### Init ### init : () -> # update inited state @_inited = true # wait until the dom is loaded if document.readyState == 'interactive' then @_init() else document.addEventListener 'DOMContentLoaded', (e) => @_init() ### Internal init ### _init : -> # do nothing if not enabled return if not @enabled # listen animations start document.addEventListener("transitionend", @_onTransitionEnd, false); document.addEventListener("oTransitionEnd", @_onTransitionEnd, false); document.addEventListener("webkitTransitionEnd", @_onTransitionEnd, false); ### On animation start ### _onTransitionEnd : (e) -> if e.elapsedTime == 0.000001 console.log 'transitionstart' e.target.dispatchEvent(new CustomEvent('transitionstart', { bubbles : true, cancelable : true })); # init the filter SugarTransitionStart.init() # return the Sugar object SugarTransitionStart
[ { "context": "dryrun, context} = opts\n if not key? then key = _uniqueId(\"var_\")\n context ?= {}\n if _.isFunction(fns", "end": 7831, "score": 0.9894078373908997, "start": 7822, "tag": "KEY", "value": "_uniqueId" }, { "context": "} = opts\n if not key? then key = _uniqu...
src/data.coffee
Polychart/polychart2
64
### Data Object --------- Polychart wrapper around a data set. This is contains the data structure required for poly.chart(). Data object that either contains JSON format of a dataset, or knows how to retrieve data from some source. ### poly.data = (blob) -> type = undefined data = undefined meta = undefined if _.isObject(blob) and 'data' of blob and (((len=_.keys(blob).length) < 7 and 'meta' of blob) or len < 5) data = blob.data meta = blob.meta else data = blob switch _getDataType(data) when 'json-object', 'json-grid', 'json-array' poly.data.json(data, meta, type) when 'url' poly.data.url(data, meta, type) when 'csv' poly.data.csv(data, meta) when 'api' poly.data.api(data) else throw poly.error.data "Unknown data format." poly.data.json = (data, meta, type) -> new FrontendData {data, meta, type} poly.data.csv = (data, meta) -> new FrontendData {data, meta, 'csv'} poly.data.url = (url, computeBackend, limit) -> new BackendData {url, computeBackend, limit} ### Data format which takes an API-facing function. Signature: poly.data.api = ((requestParams, (err, result) -> undefined) -> undefined) -> polyjsData ### poly.data.api = (apiFun) -> new ApiData {apiFun} ### Helper functions ### _getDataType = (data) -> if _.isArray data if _.isArray data[0] 'json-grid' else 'json-array' else if _.isObject data 'json-object' else if _.isString data if poly.isURI data 'url' else 'csv' else if _.isFunction data 'api' else throw poly.error.data "Unknown data format." _getArray = (json, meta) -> # array of objects [{foo:2, bar:4}, {foo:2, bar:3}, ...] if json.length > 0 keys = _.union _.keys(meta), _.keys(json[0]) first100 = json[0..99] for key in keys meta[key] ?= {} if not meta[key].type meta[key].type = poly.type.impute _.pluck(first100, key) for item in json for key in keys item[key] = poly.type.coerce item[key], meta[key] key = keys raw = json else key = _.keys(meta) raw = [] {key, raw, meta} _getArrayOfArrays = (json, meta) -> # array of arrays [[1,2,3],[1,2,3],...] retobj = [] if json.length > 0 keys = if meta and _.isArray(meta) meta else if meta and _.isObject(meta) _.keys(meta) else _.keys(json[0]) if _.isArray(meta) or not _.isObject(meta) meta = {} first100 = json[0..99] for key, i in keys meta[key] ?= {} if not meta[key].type meta[key].type = poly.type.impute _.pluck(first100, i) for item in json newitem = {} for value, i in item key = keys[i] newitem[key] = poly.type.coerce value, meta[key] retobj.push(newitem) key = keys raw = retobj else key = _.keys(meta) raw = [] {key, raw, meta} _getObject = (json, meta) -> # assoc array { foo: [1,2,..], bar: [1,2,...] } keys = _.keys(json) raw = [] for key in keys meta[key] ?= {} if not meta[key].type meta[key].type = poly.type.impute json[key][0..99] if keys.length > 0 len = json[keys[0]].length if len > 0 for i in [0..len-1] obj = {} for k in keys obj[k] = poly.type.coerce json[k][i], meta[k] raw.push(obj) key = keys {key, raw, meta} _getCSV = (str, meta) -> _getArray poly.csv.parse(str), meta ### Classes ### class AbstractData isData: true constructor: () -> @raw = null @meta = {} @key = [] @subscribed = [] @computeBackend = false update: () -> fn() for fn in @subscribed subscribe: (h) -> if _.indexOf(@subscribed, h) is -1 @subscribed.push h unsubscribe: (h) -> @subscribed.splice _.indexOf(@subscribed, h), 1 keys: () -> @key rename: () -> false # throw not implemented? renameMany: () -> false # throw not implemented? remove: () -> false # throw not implemented? filter: () -> false # throw not implemented? sort: () -> false # throw not implemented? derive: () -> false # throw not implemented? get: (key) -> if @raw _.pluck @raw, key else throw poly.error.data "Data has not been fetched or is undefined." len: () -> if @raw @raw.length else throw poly.error.data "Data has not been fetched or is undefined." getObject: (i) -> if @raw @raw[i] else throw poly.error.data "Data has not been fetched or is undefined." max: (key) -> _.max @get(key) min: (key) -> _.min @get(key) getMeta: (key) -> if @meta then @meta[key] else undefined type: (key) -> if key of @meta t = @meta[key].type return if t is 'num' then 'number' else t throw poly.error.defn "Data does not have column #{key}." class FrontendData extends AbstractData constructor: (params) -> super() @_setData params getData: (callback, dataSpec) -> if not dataSpec? callback null, @ return poly.data.frontendProcess dataSpec, @, (err, dataObj) -> # There is a bit of a difficulty here... in other parts of this # function, a PolyJS Data Object is returned. Here, we don't do # that, which is ugly. But if we do turn the dataObj into a PolyJS # Data Obj, then we might lose metaData info like binning, etc # also true @ BackendData.getData() dataObj.raw = dataObj.data callback(err, dataObj) update: (params) -> @_setData params super() _setData: (blob) -> if _.isObject(blob) and _.keys(blob).length < 4 and 'data' of blob data = blob.data meta = blob.meta ? {} else data = blob meta = {} {@key, @raw, @meta} = switch blob.type ? _getDataType(data) when 'json-object' then _getObject data, meta when 'json-grid' then _getArrayOfArrays data, meta when 'json-array' then _getArray data, meta when 'csv' then _getCSV data, meta else throw poly.error.data "Unknown data format." @data = @raw # hack? _checkRename: (from, to) -> if to is '' throw poly.error.defn "Column names cannot be an empty string" if _.indexOf(@key, from) is -1 throw poly.error.defn "The key #{from} doesn't exist!" if _.indexOf(@key, to) isnt -1 throw poly.error.defn "The key #{to} already exists!" rename: (from, to, checked=false) -> from = from.toString() to = to.toString() if from is to then return true if not checked then @_checkRename from, to for item in @raw item[to] = item[from] delete item[from] k = _.indexOf(@key, from) @key[k] = to @meta[to] = @meta[from] delete @meta[from] true renameMany: (map) -> for from, to of map if from isnt to @_checkRename from, to for from, to of map if from isnt to @rename from, to, true true remove: (key) -> index = _.indexOf(@key, key) if index is '-1' return false #throw poly.error.defn "The key #{key} doesn't exist!" @key.splice index, 1 delete @meta[key] for item in @raw delete item[key] true filter: (strfn) -> fn = if _.isFunction strfn strfn else if _.isString strfn new Function('d', "with(d) { return #{strfn};}") else () -> true newdata = [] for item in @raw if fn item newdata.push item newobj = poly.data.json newdata, @meta newobj sort: (key, desc) -> type = @type key newdata =_.clone(@raw) sortfn = poly.type.compare(type) newdata.sort (a,b) -> sortfn a[key], b[key] if desc then newdata.reverse() newobj = poly.data.json newdata, @meta newobj derive: (fnstr, key, opts) -> opts ?= {} {dryrun, context} = opts if not key? then key = _uniqueId("var_") context ?= {} if _.isFunction(fnstr) compute = fnstr hasFnStr = false else hasFnStr = true compute = new Function('d', "with(this) { with(d) { return #{fnstr or '""'};}}") for item in @raw value = compute.call context,item if _.isFunction value throw poly.error.defn "Derivation function returned another function." item[key] = value if dryrun then return success:true, values: _.pluck @raw[0..10], key if not (key in @key) @key.push key @meta[key] = type : poly.type.impute _.pluck(@raw[0..100], key) derived: true if hasFnStr then @meta[key].formula = fnstr key class BackendData extends AbstractData constructor: (params) -> super() {@url, @computeBackend, @limit} = params @computeBackend ?= false # retrieve data from backend # @callback - the callback function once data is retrieved # @params - additional parameters to send to the backend getData: (callback, dataSpec) => if @raw? and (not @computeBackend) if not dataSpec? return callback null, @ poly.data.frontendProcess dataSpec, @, (err, dataObj) -> # see note @ FrontendData.getData() dataObj.raw = dataObj.data callback(err, dataObj) return chr = if _.indexOf(@url, "?") is -1 then '?' else '&' url = @url if @limit url += "#{chr}limit=#{@limit}" if dataSpec url += "&spec=#{encodeURIComponent(JSON.stringify(dataSpec))}" poly.text url, (blob) => try blob = JSON.parse(blob) catch e # Guess "blob" is not a JSON object! # NOTE: DON'T THROW AN ERROR! COULD BE A STRING! # TODO: refactor this. repeat code from poly.data if _.isObject(blob) and _.keys(blob).length < 4 and 'data' of blob data = blob.data meta = blob.meta ? {} else data = blob meta = {} {@key, @raw, @meta} = switch _getDataType(data) when 'json-object' then _getObject data, meta when 'json-grid' then _getArrayOfArrays data, meta when 'json-array' then _getArray data, meta when 'csv' then _getCSV data, meta else throw poly.error.data "Unknown data format." @data = @raw # hack? callback null, @ update: (params) -> @raw = null super() renameMany: (obj) -> _.keys(obj).length == 0 # Too similar to Backend Data. Perhaps refactor with data mixins. class ApiData extends AbstractData constructor: (params) -> super() {@apiFun} = params @computeBackend = true getData: (callback, dataSpec) => @apiFun dataSpec, (err, blob) => if err? then return callback err, null if _.isString(blob) try blob = JSON.parse(blob) catch e error = null try # Need to merge this with above code data = blob.data meta = blob.meta ? {} {@key, @raw, @meta} = switch _getDataType(data) when 'json-object' then _getObject data, meta when 'json-grid' then _getArrayOfArrays data, meta when 'json-array' then _getArray data, meta when 'csv' then _getCSV data, meta else throw poly.error.data "Unknown data format." @data = @raw catch e error = e callback error, @ update: (params) -> @raw = null super() renameMany: (obj) -> _.keys(obj).length == 0
34674
### Data Object --------- Polychart wrapper around a data set. This is contains the data structure required for poly.chart(). Data object that either contains JSON format of a dataset, or knows how to retrieve data from some source. ### poly.data = (blob) -> type = undefined data = undefined meta = undefined if _.isObject(blob) and 'data' of blob and (((len=_.keys(blob).length) < 7 and 'meta' of blob) or len < 5) data = blob.data meta = blob.meta else data = blob switch _getDataType(data) when 'json-object', 'json-grid', 'json-array' poly.data.json(data, meta, type) when 'url' poly.data.url(data, meta, type) when 'csv' poly.data.csv(data, meta) when 'api' poly.data.api(data) else throw poly.error.data "Unknown data format." poly.data.json = (data, meta, type) -> new FrontendData {data, meta, type} poly.data.csv = (data, meta) -> new FrontendData {data, meta, 'csv'} poly.data.url = (url, computeBackend, limit) -> new BackendData {url, computeBackend, limit} ### Data format which takes an API-facing function. Signature: poly.data.api = ((requestParams, (err, result) -> undefined) -> undefined) -> polyjsData ### poly.data.api = (apiFun) -> new ApiData {apiFun} ### Helper functions ### _getDataType = (data) -> if _.isArray data if _.isArray data[0] 'json-grid' else 'json-array' else if _.isObject data 'json-object' else if _.isString data if poly.isURI data 'url' else 'csv' else if _.isFunction data 'api' else throw poly.error.data "Unknown data format." _getArray = (json, meta) -> # array of objects [{foo:2, bar:4}, {foo:2, bar:3}, ...] if json.length > 0 keys = _.union _.keys(meta), _.keys(json[0]) first100 = json[0..99] for key in keys meta[key] ?= {} if not meta[key].type meta[key].type = poly.type.impute _.pluck(first100, key) for item in json for key in keys item[key] = poly.type.coerce item[key], meta[key] key = keys raw = json else key = _.keys(meta) raw = [] {key, raw, meta} _getArrayOfArrays = (json, meta) -> # array of arrays [[1,2,3],[1,2,3],...] retobj = [] if json.length > 0 keys = if meta and _.isArray(meta) meta else if meta and _.isObject(meta) _.keys(meta) else _.keys(json[0]) if _.isArray(meta) or not _.isObject(meta) meta = {} first100 = json[0..99] for key, i in keys meta[key] ?= {} if not meta[key].type meta[key].type = poly.type.impute _.pluck(first100, i) for item in json newitem = {} for value, i in item key = keys[i] newitem[key] = poly.type.coerce value, meta[key] retobj.push(newitem) key = keys raw = retobj else key = _.keys(meta) raw = [] {key, raw, meta} _getObject = (json, meta) -> # assoc array { foo: [1,2,..], bar: [1,2,...] } keys = _.keys(json) raw = [] for key in keys meta[key] ?= {} if not meta[key].type meta[key].type = poly.type.impute json[key][0..99] if keys.length > 0 len = json[keys[0]].length if len > 0 for i in [0..len-1] obj = {} for k in keys obj[k] = poly.type.coerce json[k][i], meta[k] raw.push(obj) key = keys {key, raw, meta} _getCSV = (str, meta) -> _getArray poly.csv.parse(str), meta ### Classes ### class AbstractData isData: true constructor: () -> @raw = null @meta = {} @key = [] @subscribed = [] @computeBackend = false update: () -> fn() for fn in @subscribed subscribe: (h) -> if _.indexOf(@subscribed, h) is -1 @subscribed.push h unsubscribe: (h) -> @subscribed.splice _.indexOf(@subscribed, h), 1 keys: () -> @key rename: () -> false # throw not implemented? renameMany: () -> false # throw not implemented? remove: () -> false # throw not implemented? filter: () -> false # throw not implemented? sort: () -> false # throw not implemented? derive: () -> false # throw not implemented? get: (key) -> if @raw _.pluck @raw, key else throw poly.error.data "Data has not been fetched or is undefined." len: () -> if @raw @raw.length else throw poly.error.data "Data has not been fetched or is undefined." getObject: (i) -> if @raw @raw[i] else throw poly.error.data "Data has not been fetched or is undefined." max: (key) -> _.max @get(key) min: (key) -> _.min @get(key) getMeta: (key) -> if @meta then @meta[key] else undefined type: (key) -> if key of @meta t = @meta[key].type return if t is 'num' then 'number' else t throw poly.error.defn "Data does not have column #{key}." class FrontendData extends AbstractData constructor: (params) -> super() @_setData params getData: (callback, dataSpec) -> if not dataSpec? callback null, @ return poly.data.frontendProcess dataSpec, @, (err, dataObj) -> # There is a bit of a difficulty here... in other parts of this # function, a PolyJS Data Object is returned. Here, we don't do # that, which is ugly. But if we do turn the dataObj into a PolyJS # Data Obj, then we might lose metaData info like binning, etc # also true @ BackendData.getData() dataObj.raw = dataObj.data callback(err, dataObj) update: (params) -> @_setData params super() _setData: (blob) -> if _.isObject(blob) and _.keys(blob).length < 4 and 'data' of blob data = blob.data meta = blob.meta ? {} else data = blob meta = {} {@key, @raw, @meta} = switch blob.type ? _getDataType(data) when 'json-object' then _getObject data, meta when 'json-grid' then _getArrayOfArrays data, meta when 'json-array' then _getArray data, meta when 'csv' then _getCSV data, meta else throw poly.error.data "Unknown data format." @data = @raw # hack? _checkRename: (from, to) -> if to is '' throw poly.error.defn "Column names cannot be an empty string" if _.indexOf(@key, from) is -1 throw poly.error.defn "The key #{from} doesn't exist!" if _.indexOf(@key, to) isnt -1 throw poly.error.defn "The key #{to} already exists!" rename: (from, to, checked=false) -> from = from.toString() to = to.toString() if from is to then return true if not checked then @_checkRename from, to for item in @raw item[to] = item[from] delete item[from] k = _.indexOf(@key, from) @key[k] = to @meta[to] = @meta[from] delete @meta[from] true renameMany: (map) -> for from, to of map if from isnt to @_checkRename from, to for from, to of map if from isnt to @rename from, to, true true remove: (key) -> index = _.indexOf(@key, key) if index is '-1' return false #throw poly.error.defn "The key #{key} doesn't exist!" @key.splice index, 1 delete @meta[key] for item in @raw delete item[key] true filter: (strfn) -> fn = if _.isFunction strfn strfn else if _.isString strfn new Function('d', "with(d) { return #{strfn};}") else () -> true newdata = [] for item in @raw if fn item newdata.push item newobj = poly.data.json newdata, @meta newobj sort: (key, desc) -> type = @type key newdata =_.clone(@raw) sortfn = poly.type.compare(type) newdata.sort (a,b) -> sortfn a[key], b[key] if desc then newdata.reverse() newobj = poly.data.json newdata, @meta newobj derive: (fnstr, key, opts) -> opts ?= {} {dryrun, context} = opts if not key? then key = <KEY>("var<KEY>_") context ?= {} if _.isFunction(fnstr) compute = fnstr hasFnStr = false else hasFnStr = true compute = new Function('d', "with(this) { with(d) { return #{fnstr or '""'};}}") for item in @raw value = compute.call context,item if _.isFunction value throw poly.error.defn "Derivation function returned another function." item[key] = value if dryrun then return success:true, values: _.pluck @raw[0..10], key if not (key in @key) @key.push key @meta[key] = type : poly.type.impute _.pluck(@raw[0..100], key) derived: true if hasFnStr then @meta[key].formula = fnstr key class BackendData extends AbstractData constructor: (params) -> super() {@url, @computeBackend, @limit} = params @computeBackend ?= false # retrieve data from backend # @callback - the callback function once data is retrieved # @params - additional parameters to send to the backend getData: (callback, dataSpec) => if @raw? and (not @computeBackend) if not dataSpec? return callback null, @ poly.data.frontendProcess dataSpec, @, (err, dataObj) -> # see note @ FrontendData.getData() dataObj.raw = dataObj.data callback(err, dataObj) return chr = if _.indexOf(@url, "?") is -1 then '?' else '&' url = @url if @limit url += "#{chr}limit=#{@limit}" if dataSpec url += "&spec=#{encodeURIComponent(JSON.stringify(dataSpec))}" poly.text url, (blob) => try blob = JSON.parse(blob) catch e # Guess "blob" is not a JSON object! # NOTE: DON'T THROW AN ERROR! COULD BE A STRING! # TODO: refactor this. repeat code from poly.data if _.isObject(blob) and _.keys(blob).length < 4 and 'data' of blob data = blob.data meta = blob.meta ? {} else data = blob meta = {} {@key, @raw, @meta} = switch _getDataType(data) when 'json-object' then _getObject data, meta when 'json-grid' then _getArrayOfArrays data, meta when 'json-array' then _getArray data, meta when 'csv' then _getCSV data, meta else throw poly.error.data "Unknown data format." @data = @raw # hack? callback null, @ update: (params) -> @raw = null super() renameMany: (obj) -> _.keys(obj).length == 0 # Too similar to Backend Data. Perhaps refactor with data mixins. class ApiData extends AbstractData constructor: (params) -> super() {@apiFun} = params @computeBackend = true getData: (callback, dataSpec) => @apiFun dataSpec, (err, blob) => if err? then return callback err, null if _.isString(blob) try blob = JSON.parse(blob) catch e error = null try # Need to merge this with above code data = blob.data meta = blob.meta ? {} {@key, @raw, @meta} = switch _getDataType(data) when 'json-object' then _getObject data, meta when 'json-grid' then _getArrayOfArrays data, meta when 'json-array' then _getArray data, meta when 'csv' then _getCSV data, meta else throw poly.error.data "Unknown data format." @data = @raw catch e error = e callback error, @ update: (params) -> @raw = null super() renameMany: (obj) -> _.keys(obj).length == 0
true
### Data Object --------- Polychart wrapper around a data set. This is contains the data structure required for poly.chart(). Data object that either contains JSON format of a dataset, or knows how to retrieve data from some source. ### poly.data = (blob) -> type = undefined data = undefined meta = undefined if _.isObject(blob) and 'data' of blob and (((len=_.keys(blob).length) < 7 and 'meta' of blob) or len < 5) data = blob.data meta = blob.meta else data = blob switch _getDataType(data) when 'json-object', 'json-grid', 'json-array' poly.data.json(data, meta, type) when 'url' poly.data.url(data, meta, type) when 'csv' poly.data.csv(data, meta) when 'api' poly.data.api(data) else throw poly.error.data "Unknown data format." poly.data.json = (data, meta, type) -> new FrontendData {data, meta, type} poly.data.csv = (data, meta) -> new FrontendData {data, meta, 'csv'} poly.data.url = (url, computeBackend, limit) -> new BackendData {url, computeBackend, limit} ### Data format which takes an API-facing function. Signature: poly.data.api = ((requestParams, (err, result) -> undefined) -> undefined) -> polyjsData ### poly.data.api = (apiFun) -> new ApiData {apiFun} ### Helper functions ### _getDataType = (data) -> if _.isArray data if _.isArray data[0] 'json-grid' else 'json-array' else if _.isObject data 'json-object' else if _.isString data if poly.isURI data 'url' else 'csv' else if _.isFunction data 'api' else throw poly.error.data "Unknown data format." _getArray = (json, meta) -> # array of objects [{foo:2, bar:4}, {foo:2, bar:3}, ...] if json.length > 0 keys = _.union _.keys(meta), _.keys(json[0]) first100 = json[0..99] for key in keys meta[key] ?= {} if not meta[key].type meta[key].type = poly.type.impute _.pluck(first100, key) for item in json for key in keys item[key] = poly.type.coerce item[key], meta[key] key = keys raw = json else key = _.keys(meta) raw = [] {key, raw, meta} _getArrayOfArrays = (json, meta) -> # array of arrays [[1,2,3],[1,2,3],...] retobj = [] if json.length > 0 keys = if meta and _.isArray(meta) meta else if meta and _.isObject(meta) _.keys(meta) else _.keys(json[0]) if _.isArray(meta) or not _.isObject(meta) meta = {} first100 = json[0..99] for key, i in keys meta[key] ?= {} if not meta[key].type meta[key].type = poly.type.impute _.pluck(first100, i) for item in json newitem = {} for value, i in item key = keys[i] newitem[key] = poly.type.coerce value, meta[key] retobj.push(newitem) key = keys raw = retobj else key = _.keys(meta) raw = [] {key, raw, meta} _getObject = (json, meta) -> # assoc array { foo: [1,2,..], bar: [1,2,...] } keys = _.keys(json) raw = [] for key in keys meta[key] ?= {} if not meta[key].type meta[key].type = poly.type.impute json[key][0..99] if keys.length > 0 len = json[keys[0]].length if len > 0 for i in [0..len-1] obj = {} for k in keys obj[k] = poly.type.coerce json[k][i], meta[k] raw.push(obj) key = keys {key, raw, meta} _getCSV = (str, meta) -> _getArray poly.csv.parse(str), meta ### Classes ### class AbstractData isData: true constructor: () -> @raw = null @meta = {} @key = [] @subscribed = [] @computeBackend = false update: () -> fn() for fn in @subscribed subscribe: (h) -> if _.indexOf(@subscribed, h) is -1 @subscribed.push h unsubscribe: (h) -> @subscribed.splice _.indexOf(@subscribed, h), 1 keys: () -> @key rename: () -> false # throw not implemented? renameMany: () -> false # throw not implemented? remove: () -> false # throw not implemented? filter: () -> false # throw not implemented? sort: () -> false # throw not implemented? derive: () -> false # throw not implemented? get: (key) -> if @raw _.pluck @raw, key else throw poly.error.data "Data has not been fetched or is undefined." len: () -> if @raw @raw.length else throw poly.error.data "Data has not been fetched or is undefined." getObject: (i) -> if @raw @raw[i] else throw poly.error.data "Data has not been fetched or is undefined." max: (key) -> _.max @get(key) min: (key) -> _.min @get(key) getMeta: (key) -> if @meta then @meta[key] else undefined type: (key) -> if key of @meta t = @meta[key].type return if t is 'num' then 'number' else t throw poly.error.defn "Data does not have column #{key}." class FrontendData extends AbstractData constructor: (params) -> super() @_setData params getData: (callback, dataSpec) -> if not dataSpec? callback null, @ return poly.data.frontendProcess dataSpec, @, (err, dataObj) -> # There is a bit of a difficulty here... in other parts of this # function, a PolyJS Data Object is returned. Here, we don't do # that, which is ugly. But if we do turn the dataObj into a PolyJS # Data Obj, then we might lose metaData info like binning, etc # also true @ BackendData.getData() dataObj.raw = dataObj.data callback(err, dataObj) update: (params) -> @_setData params super() _setData: (blob) -> if _.isObject(blob) and _.keys(blob).length < 4 and 'data' of blob data = blob.data meta = blob.meta ? {} else data = blob meta = {} {@key, @raw, @meta} = switch blob.type ? _getDataType(data) when 'json-object' then _getObject data, meta when 'json-grid' then _getArrayOfArrays data, meta when 'json-array' then _getArray data, meta when 'csv' then _getCSV data, meta else throw poly.error.data "Unknown data format." @data = @raw # hack? _checkRename: (from, to) -> if to is '' throw poly.error.defn "Column names cannot be an empty string" if _.indexOf(@key, from) is -1 throw poly.error.defn "The key #{from} doesn't exist!" if _.indexOf(@key, to) isnt -1 throw poly.error.defn "The key #{to} already exists!" rename: (from, to, checked=false) -> from = from.toString() to = to.toString() if from is to then return true if not checked then @_checkRename from, to for item in @raw item[to] = item[from] delete item[from] k = _.indexOf(@key, from) @key[k] = to @meta[to] = @meta[from] delete @meta[from] true renameMany: (map) -> for from, to of map if from isnt to @_checkRename from, to for from, to of map if from isnt to @rename from, to, true true remove: (key) -> index = _.indexOf(@key, key) if index is '-1' return false #throw poly.error.defn "The key #{key} doesn't exist!" @key.splice index, 1 delete @meta[key] for item in @raw delete item[key] true filter: (strfn) -> fn = if _.isFunction strfn strfn else if _.isString strfn new Function('d', "with(d) { return #{strfn};}") else () -> true newdata = [] for item in @raw if fn item newdata.push item newobj = poly.data.json newdata, @meta newobj sort: (key, desc) -> type = @type key newdata =_.clone(@raw) sortfn = poly.type.compare(type) newdata.sort (a,b) -> sortfn a[key], b[key] if desc then newdata.reverse() newobj = poly.data.json newdata, @meta newobj derive: (fnstr, key, opts) -> opts ?= {} {dryrun, context} = opts if not key? then key = PI:KEY:<KEY>END_PI("varPI:KEY:<KEY>END_PI_") context ?= {} if _.isFunction(fnstr) compute = fnstr hasFnStr = false else hasFnStr = true compute = new Function('d', "with(this) { with(d) { return #{fnstr or '""'};}}") for item in @raw value = compute.call context,item if _.isFunction value throw poly.error.defn "Derivation function returned another function." item[key] = value if dryrun then return success:true, values: _.pluck @raw[0..10], key if not (key in @key) @key.push key @meta[key] = type : poly.type.impute _.pluck(@raw[0..100], key) derived: true if hasFnStr then @meta[key].formula = fnstr key class BackendData extends AbstractData constructor: (params) -> super() {@url, @computeBackend, @limit} = params @computeBackend ?= false # retrieve data from backend # @callback - the callback function once data is retrieved # @params - additional parameters to send to the backend getData: (callback, dataSpec) => if @raw? and (not @computeBackend) if not dataSpec? return callback null, @ poly.data.frontendProcess dataSpec, @, (err, dataObj) -> # see note @ FrontendData.getData() dataObj.raw = dataObj.data callback(err, dataObj) return chr = if _.indexOf(@url, "?") is -1 then '?' else '&' url = @url if @limit url += "#{chr}limit=#{@limit}" if dataSpec url += "&spec=#{encodeURIComponent(JSON.stringify(dataSpec))}" poly.text url, (blob) => try blob = JSON.parse(blob) catch e # Guess "blob" is not a JSON object! # NOTE: DON'T THROW AN ERROR! COULD BE A STRING! # TODO: refactor this. repeat code from poly.data if _.isObject(blob) and _.keys(blob).length < 4 and 'data' of blob data = blob.data meta = blob.meta ? {} else data = blob meta = {} {@key, @raw, @meta} = switch _getDataType(data) when 'json-object' then _getObject data, meta when 'json-grid' then _getArrayOfArrays data, meta when 'json-array' then _getArray data, meta when 'csv' then _getCSV data, meta else throw poly.error.data "Unknown data format." @data = @raw # hack? callback null, @ update: (params) -> @raw = null super() renameMany: (obj) -> _.keys(obj).length == 0 # Too similar to Backend Data. Perhaps refactor with data mixins. class ApiData extends AbstractData constructor: (params) -> super() {@apiFun} = params @computeBackend = true getData: (callback, dataSpec) => @apiFun dataSpec, (err, blob) => if err? then return callback err, null if _.isString(blob) try blob = JSON.parse(blob) catch e error = null try # Need to merge this with above code data = blob.data meta = blob.meta ? {} {@key, @raw, @meta} = switch _getDataType(data) when 'json-object' then _getObject data, meta when 'json-grid' then _getArrayOfArrays data, meta when 'json-array' then _getArray data, meta when 'csv' then _getCSV data, meta else throw poly.error.data "Unknown data format." @data = @raw catch e error = e callback error, @ update: (params) -> @raw = null super() renameMany: (obj) -> _.keys(obj).length == 0
[ { "context": " rich text editing jQuery UI widget\n# (c) 2011 Henri Bergius, IKS Consortium\n# Hallo may be freely distrib", "end": 79, "score": 0.9998701810836792, "start": 66, "tag": "NAME", "value": "Henri Bergius" } ]
src/plugins/spellcheck.coffee
git-j/hallo
0
# Hallo - a rich text editing jQuery UI widget # (c) 2011 Henri Bergius, IKS Consortium # Hallo may be freely distributed under the MIT license # spellcheck plugin # requires bjspell and getStyleObject # and is needed for older browsers or qt-webkit # execute on load: # , utils.getJavaScript("lib/hallojs/bjspell.js") # , utils.getJavaScript("lib/hallojs/jquery.getStyleObject.js") # window.spellcheck = BJSpell("lib/hallojs/" + language + ".js", function(){ # //console.log('spellcheck loaded:' + language); # }); ((jQuery) -> jQuery.widget 'IKS.hallospellcheck', name: 'spellcheck' # used for icon, executed as execCommand spellcheck_interval: 0 # timeout_id spellcheck_timeout: 300 # ms after keypress the spellcheck should run spellcheck_proxy: null # proxy to keep this initialized: false # events are bound debug: false # display spellcheck progress options: editable: null toolbar: null uuid: '' buttonCssClass: null _init: () -> @options.editable.element.bind 'halloactivated', => @enable() enable: () -> try wke.spellcheckWord('refeus') @initialized = true catch @initialized = false console.log(@initialized) if @debug return execute: () -> # on click toolbar button return if ( !@initialized ) console.log('toggle spellcheck') if debug @options.editable.element[0].spellcheck = !@options.editable.element[0].spellcheck @options.editable.element.blur() @options.editable.element.focus() setup: () -> # on activate toolbar (focus in) console.log(@initialized) if debug return if ( @initialized ) @enable() populateToolbar: (toolbar) -> buttonset = jQuery "<span class=\"#{@widgetName}\"></span>" contentId = "#{@options.uuid}-#{@widgetName}-data" toolbar.append @_prepareButtons contentId _prepareButtons: (contentId) -> # build buttonset with single instance buttonset = jQuery "<span class=\"#{@widgetName}\"></span>" buttonset.append @_prepareButton => @execute() buttonset.hallobuttonset() _prepareButton: (action) -> # build button to be displayed with halloactionbutton # apply translated tooltips buttonElement = jQuery '<span></span>' button_label = @name if ( window.action_list && window.action_list['hallojs_' + @name] != undefined ) button_label = window.action_list['hallojs_' + @name].title buttonElement.halloactionbutton uuid: @options.uuid editable: @options.editable label: button_label icon: 'icon-text-height' command: @name target: @name setup: @setup cssClass: @options.buttonCssClass action: action buttonElement )(jQuery)
160004
# Hallo - a rich text editing jQuery UI widget # (c) 2011 <NAME>, IKS Consortium # Hallo may be freely distributed under the MIT license # spellcheck plugin # requires bjspell and getStyleObject # and is needed for older browsers or qt-webkit # execute on load: # , utils.getJavaScript("lib/hallojs/bjspell.js") # , utils.getJavaScript("lib/hallojs/jquery.getStyleObject.js") # window.spellcheck = BJSpell("lib/hallojs/" + language + ".js", function(){ # //console.log('spellcheck loaded:' + language); # }); ((jQuery) -> jQuery.widget 'IKS.hallospellcheck', name: 'spellcheck' # used for icon, executed as execCommand spellcheck_interval: 0 # timeout_id spellcheck_timeout: 300 # ms after keypress the spellcheck should run spellcheck_proxy: null # proxy to keep this initialized: false # events are bound debug: false # display spellcheck progress options: editable: null toolbar: null uuid: '' buttonCssClass: null _init: () -> @options.editable.element.bind 'halloactivated', => @enable() enable: () -> try wke.spellcheckWord('refeus') @initialized = true catch @initialized = false console.log(@initialized) if @debug return execute: () -> # on click toolbar button return if ( !@initialized ) console.log('toggle spellcheck') if debug @options.editable.element[0].spellcheck = !@options.editable.element[0].spellcheck @options.editable.element.blur() @options.editable.element.focus() setup: () -> # on activate toolbar (focus in) console.log(@initialized) if debug return if ( @initialized ) @enable() populateToolbar: (toolbar) -> buttonset = jQuery "<span class=\"#{@widgetName}\"></span>" contentId = "#{@options.uuid}-#{@widgetName}-data" toolbar.append @_prepareButtons contentId _prepareButtons: (contentId) -> # build buttonset with single instance buttonset = jQuery "<span class=\"#{@widgetName}\"></span>" buttonset.append @_prepareButton => @execute() buttonset.hallobuttonset() _prepareButton: (action) -> # build button to be displayed with halloactionbutton # apply translated tooltips buttonElement = jQuery '<span></span>' button_label = @name if ( window.action_list && window.action_list['hallojs_' + @name] != undefined ) button_label = window.action_list['hallojs_' + @name].title buttonElement.halloactionbutton uuid: @options.uuid editable: @options.editable label: button_label icon: 'icon-text-height' command: @name target: @name setup: @setup cssClass: @options.buttonCssClass action: action buttonElement )(jQuery)
true
# Hallo - a rich text editing jQuery UI widget # (c) 2011 PI:NAME:<NAME>END_PI, IKS Consortium # Hallo may be freely distributed under the MIT license # spellcheck plugin # requires bjspell and getStyleObject # and is needed for older browsers or qt-webkit # execute on load: # , utils.getJavaScript("lib/hallojs/bjspell.js") # , utils.getJavaScript("lib/hallojs/jquery.getStyleObject.js") # window.spellcheck = BJSpell("lib/hallojs/" + language + ".js", function(){ # //console.log('spellcheck loaded:' + language); # }); ((jQuery) -> jQuery.widget 'IKS.hallospellcheck', name: 'spellcheck' # used for icon, executed as execCommand spellcheck_interval: 0 # timeout_id spellcheck_timeout: 300 # ms after keypress the spellcheck should run spellcheck_proxy: null # proxy to keep this initialized: false # events are bound debug: false # display spellcheck progress options: editable: null toolbar: null uuid: '' buttonCssClass: null _init: () -> @options.editable.element.bind 'halloactivated', => @enable() enable: () -> try wke.spellcheckWord('refeus') @initialized = true catch @initialized = false console.log(@initialized) if @debug return execute: () -> # on click toolbar button return if ( !@initialized ) console.log('toggle spellcheck') if debug @options.editable.element[0].spellcheck = !@options.editable.element[0].spellcheck @options.editable.element.blur() @options.editable.element.focus() setup: () -> # on activate toolbar (focus in) console.log(@initialized) if debug return if ( @initialized ) @enable() populateToolbar: (toolbar) -> buttonset = jQuery "<span class=\"#{@widgetName}\"></span>" contentId = "#{@options.uuid}-#{@widgetName}-data" toolbar.append @_prepareButtons contentId _prepareButtons: (contentId) -> # build buttonset with single instance buttonset = jQuery "<span class=\"#{@widgetName}\"></span>" buttonset.append @_prepareButton => @execute() buttonset.hallobuttonset() _prepareButton: (action) -> # build button to be displayed with halloactionbutton # apply translated tooltips buttonElement = jQuery '<span></span>' button_label = @name if ( window.action_list && window.action_list['hallojs_' + @name] != undefined ) button_label = window.action_list['hallojs_' + @name].title buttonElement.halloactionbutton uuid: @options.uuid editable: @options.editable label: button_label icon: 'icon-text-height' command: @name target: @name setup: @setup cssClass: @options.buttonCssClass action: action buttonElement )(jQuery)
[ { "context": "###\nCopyright (c) 2002-2013 \"Neo Technology,\"\nNetwork Engine for Objects in Lund AB [http://n", "end": 43, "score": 0.5370814204216003, "start": 33, "tag": "NAME", "value": "Technology" } ]
community/server/src/main/coffeescript/neo4j/webadmin/modules/databrowser/visualization/views/AbstractFilterView.coffee
rebaze/neo4j
1
### Copyright (c) 2002-2013 "Neo Technology," Network Engine for Objects in Lund AB [http://neotechnology.com] This file is part of Neo4j. Neo4j is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ### define( ['neo4j/webadmin/utils/ItemUrlResolver' 'ribcage/View'], (ItemUrlResolver, View) -> class AbstractFilterView extends View tagName : 'li' initialize : (opts) => @filter = opts.filter @filters = opts.filters render : () => return this deleteFilter : () -> @filters.remove @filter @remove() )
169764
### Copyright (c) 2002-2013 "Neo <NAME>," Network Engine for Objects in Lund AB [http://neotechnology.com] This file is part of Neo4j. Neo4j is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ### define( ['neo4j/webadmin/utils/ItemUrlResolver' 'ribcage/View'], (ItemUrlResolver, View) -> class AbstractFilterView extends View tagName : 'li' initialize : (opts) => @filter = opts.filter @filters = opts.filters render : () => return this deleteFilter : () -> @filters.remove @filter @remove() )
true
### Copyright (c) 2002-2013 "Neo PI:NAME:<NAME>END_PI," Network Engine for Objects in Lund AB [http://neotechnology.com] This file is part of Neo4j. Neo4j is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ### define( ['neo4j/webadmin/utils/ItemUrlResolver' 'ribcage/View'], (ItemUrlResolver, View) -> class AbstractFilterView extends View tagName : 'li' initialize : (opts) => @filter = opts.filter @filters = opts.filters render : () => return this deleteFilter : () -> @filters.remove @filter @remove() )
[ { "context": "tool, mouse, snapper) ->\n $scope.author = \"Antonio\"\n\n _plane = plane\n\n\n menu = Menu.bu", "end": 319, "score": 0.9985799193382263, "start": 312, "tag": "NAME", "value": "Antonio" } ]
src/scripts/main.coffee
aziis98/Geometric
1
remote = require 'remote' ipc = require 'ipc' Menu = remote.require 'menu' _plane = undefined angular.module('geometric', [ 'toolbar', 'gcanvas', 'structure', 'infobar', 'handler' ]) .controller 'geomCtrl', ($scope, $rootScope, $interval, $timeout, plane, tool, mouse, snapper) -> $scope.author = "Antonio" _plane = plane menu = Menu.buildFromTemplate [ { label: 'File' submenu: [ { label: 'Save' click: (item, focusedWindow) -> console.log 'Saving...\n' for primitive in plane.primitives console.log primitive.typename + ' : ' + primitive.renderer } { label: 'Settings' click: (item, focusedWindow) -> ipc.send('settings.toggle') } ] } { label: 'View', submenu: [ { label: 'Reload' accelerator: 'CmdOrCtrl+R' click: (item, focusedWindow) -> if focusedWindow focusedWindow.reload() } { label: 'Toggle Full Screen' accelerator: (-> if process.platform is 'darwin' return 'Ctrl+Command+F' else return 'F11' )() click: (item, focusedWindow) -> if focusedWindow focusedWindow.setFullScreen(!focusedWindow.isFullScreen()) } { label: 'Toggle Developer Tools' accelerator: (-> if (process.platform == 'darwin') return 'Alt+Command+I' else return 'Ctrl+Shift+I' )() click: (item, focusedWindow) -> if (focusedWindow) focusedWindow.toggleDevTools() } ] } ] Menu.setApplicationMenu menu $ -> $('body').on 'selectstart', false $(document).keyup (e) -> if e.which == 27 tool.id = 'none' tool.preview = undefined if e.which == 13 $rootScope.$emit 'actionComplete' offset = $('.gcanvas').offset() $(document).mousemove (e) -> mouse.px = mouse.x mouse.py = mouse.y mouse.x = e.pageX - offset.left mouse.y = e.pageY - offset.top mouse.button = e.which if mouse.button == 2 # middle maybe plane.translation.x += mouse.x - mouse.px plane.translation.y += mouse.y - mouse.py if tool.dragging snapper.updateGuides() if tool.dragged.nosnap tool.dragged.x = snapper.pure.x tool.dragged.y = snapper.pure.y else tool.dragged.x = snapper.x tool.dragged.y = snapper.y $(document).mousedown (e) -> mouse.button = e.which if mouse.button == 3 pts = tool.nearList.filter (primitive) -> primitive.typename is 'PPoint' if pts.length > 0 and pts[0]._dist <= 9 and pts[0].isUndependant() and pts[0].options.visible tool.dragging = true tool.dragged = pts[0] $(document).mouseup (e) -> if tool.dragging tool.dragging = false tool.dragged = undefined $(document).on 'click','input[type=text]', -> @select() mouse.vw = $('.gcanvas').width() mouse.vh = $('.gcanvas').height() $(window).resize (e) -> mouse.vw = $('.gcanvas').width() mouse.vh = $('.gcanvas').height() _plane.addPrimitive new PPoint(100, 100) _plane.addPrimitive new PPoint(200, 200)
41932
remote = require 'remote' ipc = require 'ipc' Menu = remote.require 'menu' _plane = undefined angular.module('geometric', [ 'toolbar', 'gcanvas', 'structure', 'infobar', 'handler' ]) .controller 'geomCtrl', ($scope, $rootScope, $interval, $timeout, plane, tool, mouse, snapper) -> $scope.author = "<NAME>" _plane = plane menu = Menu.buildFromTemplate [ { label: 'File' submenu: [ { label: 'Save' click: (item, focusedWindow) -> console.log 'Saving...\n' for primitive in plane.primitives console.log primitive.typename + ' : ' + primitive.renderer } { label: 'Settings' click: (item, focusedWindow) -> ipc.send('settings.toggle') } ] } { label: 'View', submenu: [ { label: 'Reload' accelerator: 'CmdOrCtrl+R' click: (item, focusedWindow) -> if focusedWindow focusedWindow.reload() } { label: 'Toggle Full Screen' accelerator: (-> if process.platform is 'darwin' return 'Ctrl+Command+F' else return 'F11' )() click: (item, focusedWindow) -> if focusedWindow focusedWindow.setFullScreen(!focusedWindow.isFullScreen()) } { label: 'Toggle Developer Tools' accelerator: (-> if (process.platform == 'darwin') return 'Alt+Command+I' else return 'Ctrl+Shift+I' )() click: (item, focusedWindow) -> if (focusedWindow) focusedWindow.toggleDevTools() } ] } ] Menu.setApplicationMenu menu $ -> $('body').on 'selectstart', false $(document).keyup (e) -> if e.which == 27 tool.id = 'none' tool.preview = undefined if e.which == 13 $rootScope.$emit 'actionComplete' offset = $('.gcanvas').offset() $(document).mousemove (e) -> mouse.px = mouse.x mouse.py = mouse.y mouse.x = e.pageX - offset.left mouse.y = e.pageY - offset.top mouse.button = e.which if mouse.button == 2 # middle maybe plane.translation.x += mouse.x - mouse.px plane.translation.y += mouse.y - mouse.py if tool.dragging snapper.updateGuides() if tool.dragged.nosnap tool.dragged.x = snapper.pure.x tool.dragged.y = snapper.pure.y else tool.dragged.x = snapper.x tool.dragged.y = snapper.y $(document).mousedown (e) -> mouse.button = e.which if mouse.button == 3 pts = tool.nearList.filter (primitive) -> primitive.typename is 'PPoint' if pts.length > 0 and pts[0]._dist <= 9 and pts[0].isUndependant() and pts[0].options.visible tool.dragging = true tool.dragged = pts[0] $(document).mouseup (e) -> if tool.dragging tool.dragging = false tool.dragged = undefined $(document).on 'click','input[type=text]', -> @select() mouse.vw = $('.gcanvas').width() mouse.vh = $('.gcanvas').height() $(window).resize (e) -> mouse.vw = $('.gcanvas').width() mouse.vh = $('.gcanvas').height() _plane.addPrimitive new PPoint(100, 100) _plane.addPrimitive new PPoint(200, 200)
true
remote = require 'remote' ipc = require 'ipc' Menu = remote.require 'menu' _plane = undefined angular.module('geometric', [ 'toolbar', 'gcanvas', 'structure', 'infobar', 'handler' ]) .controller 'geomCtrl', ($scope, $rootScope, $interval, $timeout, plane, tool, mouse, snapper) -> $scope.author = "PI:NAME:<NAME>END_PI" _plane = plane menu = Menu.buildFromTemplate [ { label: 'File' submenu: [ { label: 'Save' click: (item, focusedWindow) -> console.log 'Saving...\n' for primitive in plane.primitives console.log primitive.typename + ' : ' + primitive.renderer } { label: 'Settings' click: (item, focusedWindow) -> ipc.send('settings.toggle') } ] } { label: 'View', submenu: [ { label: 'Reload' accelerator: 'CmdOrCtrl+R' click: (item, focusedWindow) -> if focusedWindow focusedWindow.reload() } { label: 'Toggle Full Screen' accelerator: (-> if process.platform is 'darwin' return 'Ctrl+Command+F' else return 'F11' )() click: (item, focusedWindow) -> if focusedWindow focusedWindow.setFullScreen(!focusedWindow.isFullScreen()) } { label: 'Toggle Developer Tools' accelerator: (-> if (process.platform == 'darwin') return 'Alt+Command+I' else return 'Ctrl+Shift+I' )() click: (item, focusedWindow) -> if (focusedWindow) focusedWindow.toggleDevTools() } ] } ] Menu.setApplicationMenu menu $ -> $('body').on 'selectstart', false $(document).keyup (e) -> if e.which == 27 tool.id = 'none' tool.preview = undefined if e.which == 13 $rootScope.$emit 'actionComplete' offset = $('.gcanvas').offset() $(document).mousemove (e) -> mouse.px = mouse.x mouse.py = mouse.y mouse.x = e.pageX - offset.left mouse.y = e.pageY - offset.top mouse.button = e.which if mouse.button == 2 # middle maybe plane.translation.x += mouse.x - mouse.px plane.translation.y += mouse.y - mouse.py if tool.dragging snapper.updateGuides() if tool.dragged.nosnap tool.dragged.x = snapper.pure.x tool.dragged.y = snapper.pure.y else tool.dragged.x = snapper.x tool.dragged.y = snapper.y $(document).mousedown (e) -> mouse.button = e.which if mouse.button == 3 pts = tool.nearList.filter (primitive) -> primitive.typename is 'PPoint' if pts.length > 0 and pts[0]._dist <= 9 and pts[0].isUndependant() and pts[0].options.visible tool.dragging = true tool.dragged = pts[0] $(document).mouseup (e) -> if tool.dragging tool.dragging = false tool.dragged = undefined $(document).on 'click','input[type=text]', -> @select() mouse.vw = $('.gcanvas').width() mouse.vh = $('.gcanvas').height() $(window).resize (e) -> mouse.vw = $('.gcanvas').width() mouse.vh = $('.gcanvas').height() _plane.addPrimitive new PPoint(100, 100) _plane.addPrimitive new PPoint(200, 200)
[ { "context": "til\n\n The MIT License (MIT)\n\n Copyright (c) 2014 Yasuhiro Okuno\n\n Permission is hereby granted, free of charge, ", "end": 88, "score": 0.9998705983161926, "start": 74, "tag": "NAME", "value": "Yasuhiro Okuno" } ]
coffee_lib/crowdutil/helper/crhelper.coffee
koma75/crowdutil
1
### @license crowdutil The MIT License (MIT) Copyright (c) 2014 Yasuhiro Okuno 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. ### async = require 'async' findGroup = (crowd, opts, callback) -> opts = opts || {} name = opts.name || "*" query = 'name="' + name + '"' crowd.search('group', query, callback) findUser = (crowd, opts, callback) -> opts = opts || {} uid = opts.uid || "*" fname = opts.fname || "*" lname = opts.lname || "*" email = opts.email || "*" query = "name=\"#{uid}\"" query = "#{query} and firstName=\"#{fname}\"" query = "#{query} and lastName=\"#{lname}\"" query = "#{query} and email=\"#{email}\"" crowd.search('user', query, callback) listUsersGroup = (crowd, uid, callback) -> if uid == "" || typeof uid == "undefined" setTimeout(() -> myErr = new Error("invalid user name") callback(myErr, null) , 0) else crowd.user.groups(uid, callback) findGroupMembers = (crowd, group, callback) -> if group == "" || typeof group == "undefined" setTimeout(() -> myErr = new Error("findGroupMembers: invalid input") callback(myErr, null) , 0) else crowd.groups.directmembers(group, callback) addUserToGroup = (crowd, uid, group, callback) -> if ( uid == "" || typeof uid == "undefined" || group == "" || typeof group == "undefined" ) setTimeout(() -> myErr = new Error("addUserToGroup: invalid input") callback(myErr, null) , 0) else crowd.groups.addmember(uid, group, callback) return rmUserFromGroup = (crowd, uid, group, callback) -> if ( uid == "" || typeof uid == "undefined" || group == "" || typeof group == "undefined" ) setTimeout(() -> myErr = new Error("rmUserFromGroup: invalide input") callback(myErr, null) , 0) else crowd.groups.removemember(uid, group, callback) return emptyGroup = (crowd, group, limit, callback) -> findGroupMembers(crowd, group, (err, res) -> if err callback(err) return logger.debug res # res [ 'uid1' , 'uid2' ] async.eachLimit(res, limit (user, uDone) -> rmUserFromGroup(crowd, user, group, (err) -> if err logger.warn err.message else logger.info group + ' - ' + user uDone() # ignore error ) return , (err) -> if err callback(err) else logger.info "DONE emptying " + group callback() return ) ) return updateUser = (crowd, uid, update, callback) -> # if nothing is detected as changed, don't bother updating changed = false # MUST NOT change username since this creates a lot of confusion # with uid based links delete update.name # find the user crowd.user.find(uid, (err, userInfo) -> if err callback(err) else # update user info with update object logger.debug "found #{uid}:\n#{JSON.stringify(userInfo,null,2)}" for k,v of update if userInfo[k] != v logger.debug "updating #{uid}:#{k} with #{v}" changed = true userInfo[k] = v if changed # If anything has changed, call the update logger.debug "updating #{uid}:\n#{JSON.stringify(userInfo,null,2)}" crowd.user.update(uid, userInfo, (err, res) -> if err callback(err) else # SUCCESS callback() ) else # Nothing was different. logger.debug "nothing to update for #{uid}" callback() ) # # Initialize Global variables # if typeof global.crowdutil == 'undefined' global.crowdutil = {} if typeof global.crowdutil.crhelper == 'undefined' global.crowdutil.crhelper = {} if typeof global.crowdutil.crhelper.defaultCrowd == 'undefined' global.crowdutil.crhelper.defaultCrowd = null if typeof global.crowdutil.crhelper.crowds == 'undefined' global.crowdutil.crhelper.crowds = {} getCROWD = (directory) -> logger.trace "getCROWD" cfg = require global.crowdutil_cfg AtlassianCrowd = require '../../atlassian-crowd-ext/atlassian-crowd-ext' crowd = null if !cfg['directories'][directory] logger.debug("getCROWD: using default directory") directory = global.crowdutil.crhelper.defaultCrowd || cfg['defaultDirectory'] logger.debug( "getCROWD: using #{directory}" ) logger.debug( "getCROWD: #{JSON.stringify(cfg['directories'][directory],null,2)}" ) crowd = new AtlassianCrowd( cfg['directories'][directory] ) return crowd setDefaultCrowd = (crowd) -> if typeof crowd == 'string' global.crowdutil.crhelper.defaultCrowd = crowd return ### exports ### exports.findUser = findUser exports.findGroup = findGroup exports.listUsersGroup = listUsersGroup exports.findGroupMembers = findGroupMembers exports.addUserToGroup = addUserToGroup exports.rmUserFromGroup = rmUserFromGroup exports.emptyGroup = emptyGroup exports.getCROWD = getCROWD exports.setDefaultCrowd = setDefaultCrowd exports.updateUser = updateUser
208979
### @license crowdutil The MIT License (MIT) Copyright (c) 2014 <NAME> 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. ### async = require 'async' findGroup = (crowd, opts, callback) -> opts = opts || {} name = opts.name || "*" query = 'name="' + name + '"' crowd.search('group', query, callback) findUser = (crowd, opts, callback) -> opts = opts || {} uid = opts.uid || "*" fname = opts.fname || "*" lname = opts.lname || "*" email = opts.email || "*" query = "name=\"#{uid}\"" query = "#{query} and firstName=\"#{fname}\"" query = "#{query} and lastName=\"#{lname}\"" query = "#{query} and email=\"#{email}\"" crowd.search('user', query, callback) listUsersGroup = (crowd, uid, callback) -> if uid == "" || typeof uid == "undefined" setTimeout(() -> myErr = new Error("invalid user name") callback(myErr, null) , 0) else crowd.user.groups(uid, callback) findGroupMembers = (crowd, group, callback) -> if group == "" || typeof group == "undefined" setTimeout(() -> myErr = new Error("findGroupMembers: invalid input") callback(myErr, null) , 0) else crowd.groups.directmembers(group, callback) addUserToGroup = (crowd, uid, group, callback) -> if ( uid == "" || typeof uid == "undefined" || group == "" || typeof group == "undefined" ) setTimeout(() -> myErr = new Error("addUserToGroup: invalid input") callback(myErr, null) , 0) else crowd.groups.addmember(uid, group, callback) return rmUserFromGroup = (crowd, uid, group, callback) -> if ( uid == "" || typeof uid == "undefined" || group == "" || typeof group == "undefined" ) setTimeout(() -> myErr = new Error("rmUserFromGroup: invalide input") callback(myErr, null) , 0) else crowd.groups.removemember(uid, group, callback) return emptyGroup = (crowd, group, limit, callback) -> findGroupMembers(crowd, group, (err, res) -> if err callback(err) return logger.debug res # res [ 'uid1' , 'uid2' ] async.eachLimit(res, limit (user, uDone) -> rmUserFromGroup(crowd, user, group, (err) -> if err logger.warn err.message else logger.info group + ' - ' + user uDone() # ignore error ) return , (err) -> if err callback(err) else logger.info "DONE emptying " + group callback() return ) ) return updateUser = (crowd, uid, update, callback) -> # if nothing is detected as changed, don't bother updating changed = false # MUST NOT change username since this creates a lot of confusion # with uid based links delete update.name # find the user crowd.user.find(uid, (err, userInfo) -> if err callback(err) else # update user info with update object logger.debug "found #{uid}:\n#{JSON.stringify(userInfo,null,2)}" for k,v of update if userInfo[k] != v logger.debug "updating #{uid}:#{k} with #{v}" changed = true userInfo[k] = v if changed # If anything has changed, call the update logger.debug "updating #{uid}:\n#{JSON.stringify(userInfo,null,2)}" crowd.user.update(uid, userInfo, (err, res) -> if err callback(err) else # SUCCESS callback() ) else # Nothing was different. logger.debug "nothing to update for #{uid}" callback() ) # # Initialize Global variables # if typeof global.crowdutil == 'undefined' global.crowdutil = {} if typeof global.crowdutil.crhelper == 'undefined' global.crowdutil.crhelper = {} if typeof global.crowdutil.crhelper.defaultCrowd == 'undefined' global.crowdutil.crhelper.defaultCrowd = null if typeof global.crowdutil.crhelper.crowds == 'undefined' global.crowdutil.crhelper.crowds = {} getCROWD = (directory) -> logger.trace "getCROWD" cfg = require global.crowdutil_cfg AtlassianCrowd = require '../../atlassian-crowd-ext/atlassian-crowd-ext' crowd = null if !cfg['directories'][directory] logger.debug("getCROWD: using default directory") directory = global.crowdutil.crhelper.defaultCrowd || cfg['defaultDirectory'] logger.debug( "getCROWD: using #{directory}" ) logger.debug( "getCROWD: #{JSON.stringify(cfg['directories'][directory],null,2)}" ) crowd = new AtlassianCrowd( cfg['directories'][directory] ) return crowd setDefaultCrowd = (crowd) -> if typeof crowd == 'string' global.crowdutil.crhelper.defaultCrowd = crowd return ### exports ### exports.findUser = findUser exports.findGroup = findGroup exports.listUsersGroup = listUsersGroup exports.findGroupMembers = findGroupMembers exports.addUserToGroup = addUserToGroup exports.rmUserFromGroup = rmUserFromGroup exports.emptyGroup = emptyGroup exports.getCROWD = getCROWD exports.setDefaultCrowd = setDefaultCrowd exports.updateUser = updateUser
true
### @license crowdutil The MIT License (MIT) Copyright (c) 2014 PI:NAME:<NAME>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. ### async = require 'async' findGroup = (crowd, opts, callback) -> opts = opts || {} name = opts.name || "*" query = 'name="' + name + '"' crowd.search('group', query, callback) findUser = (crowd, opts, callback) -> opts = opts || {} uid = opts.uid || "*" fname = opts.fname || "*" lname = opts.lname || "*" email = opts.email || "*" query = "name=\"#{uid}\"" query = "#{query} and firstName=\"#{fname}\"" query = "#{query} and lastName=\"#{lname}\"" query = "#{query} and email=\"#{email}\"" crowd.search('user', query, callback) listUsersGroup = (crowd, uid, callback) -> if uid == "" || typeof uid == "undefined" setTimeout(() -> myErr = new Error("invalid user name") callback(myErr, null) , 0) else crowd.user.groups(uid, callback) findGroupMembers = (crowd, group, callback) -> if group == "" || typeof group == "undefined" setTimeout(() -> myErr = new Error("findGroupMembers: invalid input") callback(myErr, null) , 0) else crowd.groups.directmembers(group, callback) addUserToGroup = (crowd, uid, group, callback) -> if ( uid == "" || typeof uid == "undefined" || group == "" || typeof group == "undefined" ) setTimeout(() -> myErr = new Error("addUserToGroup: invalid input") callback(myErr, null) , 0) else crowd.groups.addmember(uid, group, callback) return rmUserFromGroup = (crowd, uid, group, callback) -> if ( uid == "" || typeof uid == "undefined" || group == "" || typeof group == "undefined" ) setTimeout(() -> myErr = new Error("rmUserFromGroup: invalide input") callback(myErr, null) , 0) else crowd.groups.removemember(uid, group, callback) return emptyGroup = (crowd, group, limit, callback) -> findGroupMembers(crowd, group, (err, res) -> if err callback(err) return logger.debug res # res [ 'uid1' , 'uid2' ] async.eachLimit(res, limit (user, uDone) -> rmUserFromGroup(crowd, user, group, (err) -> if err logger.warn err.message else logger.info group + ' - ' + user uDone() # ignore error ) return , (err) -> if err callback(err) else logger.info "DONE emptying " + group callback() return ) ) return updateUser = (crowd, uid, update, callback) -> # if nothing is detected as changed, don't bother updating changed = false # MUST NOT change username since this creates a lot of confusion # with uid based links delete update.name # find the user crowd.user.find(uid, (err, userInfo) -> if err callback(err) else # update user info with update object logger.debug "found #{uid}:\n#{JSON.stringify(userInfo,null,2)}" for k,v of update if userInfo[k] != v logger.debug "updating #{uid}:#{k} with #{v}" changed = true userInfo[k] = v if changed # If anything has changed, call the update logger.debug "updating #{uid}:\n#{JSON.stringify(userInfo,null,2)}" crowd.user.update(uid, userInfo, (err, res) -> if err callback(err) else # SUCCESS callback() ) else # Nothing was different. logger.debug "nothing to update for #{uid}" callback() ) # # Initialize Global variables # if typeof global.crowdutil == 'undefined' global.crowdutil = {} if typeof global.crowdutil.crhelper == 'undefined' global.crowdutil.crhelper = {} if typeof global.crowdutil.crhelper.defaultCrowd == 'undefined' global.crowdutil.crhelper.defaultCrowd = null if typeof global.crowdutil.crhelper.crowds == 'undefined' global.crowdutil.crhelper.crowds = {} getCROWD = (directory) -> logger.trace "getCROWD" cfg = require global.crowdutil_cfg AtlassianCrowd = require '../../atlassian-crowd-ext/atlassian-crowd-ext' crowd = null if !cfg['directories'][directory] logger.debug("getCROWD: using default directory") directory = global.crowdutil.crhelper.defaultCrowd || cfg['defaultDirectory'] logger.debug( "getCROWD: using #{directory}" ) logger.debug( "getCROWD: #{JSON.stringify(cfg['directories'][directory],null,2)}" ) crowd = new AtlassianCrowd( cfg['directories'][directory] ) return crowd setDefaultCrowd = (crowd) -> if typeof crowd == 'string' global.crowdutil.crhelper.defaultCrowd = crowd return ### exports ### exports.findUser = findUser exports.findGroup = findGroup exports.listUsersGroup = listUsersGroup exports.findGroupMembers = findGroupMembers exports.addUserToGroup = addUserToGroup exports.rmUserFromGroup = rmUserFromGroup exports.emptyGroup = emptyGroup exports.getCROWD = getCROWD exports.setDefaultCrowd = setDefaultCrowd exports.updateUser = updateUser
[ { "context": " id={'task_id_' + task.id}\n key={'task_id_' + task.id}\n task={task}\n pa", "end": 1615, "score": 0.9632431268692017, "start": 1596, "tag": "KEY", "value": "task_id_' + task.id" } ]
hbw/app/assets/javascripts/hbw/components/entity_tasks.js.jsx.coffee
napramirez/homs
0
modulejs.define( 'HBWEntityTasks', ['React', 'HBWEntityTask', 'HBWCallbacksMixin'], (React, Task, CallbacksMixin) -> React.createClass PANEL_CLASS: 'hbw-entity-task-list-panel' mixins: [CallbacksMixin] getInitialState: -> error: null chosenTaskID: @props.chosenTaskID or @selectFirstTaskId() componentWillReceiveProps: (nextProps) -> @setState(chosenTaskID: nextProps.chosenTaskID) selectFirstTaskId: -> if @props.tasks.length > 0 @trigger('hbw:task-clicked', @props.tasks[0]) @props.tasks[0].id else @trigger('hbw:task-clicked', null) null render: -> classes = 'hbw-entity-task-list' # classes += ' ' + this.props.form.css_class processName = @getProcessName() `<div className={classes}> <div className={'panel panel-group ' + this.PANEL_CLASS}> {processName && <div className='process-name'>{processName}</div>} {this.iterateTasks(this.props.tasks, this.state.chosenTaskID)} </div> </div>` iterateTasks: (tasks, chosenTaskID) -> taskAlreadyExpanded = false # only one task should show its form - to be expanded props = @props tasks.map((task) => if taskAlreadyExpanded collapsed = true else collapsed = (task.id != @props.chosenTaskID and task.processInstanceId != props.processInstanceId) taskAlreadyExpanded = !collapsed `<Task id={'task_id_' + task.id} key={'task_id_' + task.id} task={task} parentClass={this.PANEL_CLASS} env={props.env} taskId={task.id} entityCode={props.entityCode} entityTypeCode={props.entityTypeCode} entityClassCode={props.entityClassCode} collapsed={collapsed} />` ) getProcessName: -> if @props.tasks.length > 0 @props.tasks[0].process_name else null )
96307
modulejs.define( 'HBWEntityTasks', ['React', 'HBWEntityTask', 'HBWCallbacksMixin'], (React, Task, CallbacksMixin) -> React.createClass PANEL_CLASS: 'hbw-entity-task-list-panel' mixins: [CallbacksMixin] getInitialState: -> error: null chosenTaskID: @props.chosenTaskID or @selectFirstTaskId() componentWillReceiveProps: (nextProps) -> @setState(chosenTaskID: nextProps.chosenTaskID) selectFirstTaskId: -> if @props.tasks.length > 0 @trigger('hbw:task-clicked', @props.tasks[0]) @props.tasks[0].id else @trigger('hbw:task-clicked', null) null render: -> classes = 'hbw-entity-task-list' # classes += ' ' + this.props.form.css_class processName = @getProcessName() `<div className={classes}> <div className={'panel panel-group ' + this.PANEL_CLASS}> {processName && <div className='process-name'>{processName}</div>} {this.iterateTasks(this.props.tasks, this.state.chosenTaskID)} </div> </div>` iterateTasks: (tasks, chosenTaskID) -> taskAlreadyExpanded = false # only one task should show its form - to be expanded props = @props tasks.map((task) => if taskAlreadyExpanded collapsed = true else collapsed = (task.id != @props.chosenTaskID and task.processInstanceId != props.processInstanceId) taskAlreadyExpanded = !collapsed `<Task id={'task_id_' + task.id} key={'<KEY>} task={task} parentClass={this.PANEL_CLASS} env={props.env} taskId={task.id} entityCode={props.entityCode} entityTypeCode={props.entityTypeCode} entityClassCode={props.entityClassCode} collapsed={collapsed} />` ) getProcessName: -> if @props.tasks.length > 0 @props.tasks[0].process_name else null )
true
modulejs.define( 'HBWEntityTasks', ['React', 'HBWEntityTask', 'HBWCallbacksMixin'], (React, Task, CallbacksMixin) -> React.createClass PANEL_CLASS: 'hbw-entity-task-list-panel' mixins: [CallbacksMixin] getInitialState: -> error: null chosenTaskID: @props.chosenTaskID or @selectFirstTaskId() componentWillReceiveProps: (nextProps) -> @setState(chosenTaskID: nextProps.chosenTaskID) selectFirstTaskId: -> if @props.tasks.length > 0 @trigger('hbw:task-clicked', @props.tasks[0]) @props.tasks[0].id else @trigger('hbw:task-clicked', null) null render: -> classes = 'hbw-entity-task-list' # classes += ' ' + this.props.form.css_class processName = @getProcessName() `<div className={classes}> <div className={'panel panel-group ' + this.PANEL_CLASS}> {processName && <div className='process-name'>{processName}</div>} {this.iterateTasks(this.props.tasks, this.state.chosenTaskID)} </div> </div>` iterateTasks: (tasks, chosenTaskID) -> taskAlreadyExpanded = false # only one task should show its form - to be expanded props = @props tasks.map((task) => if taskAlreadyExpanded collapsed = true else collapsed = (task.id != @props.chosenTaskID and task.processInstanceId != props.processInstanceId) taskAlreadyExpanded = !collapsed `<Task id={'task_id_' + task.id} key={'PI:KEY:<KEY>END_PI} task={task} parentClass={this.PANEL_CLASS} env={props.env} taskId={task.id} entityCode={props.entityCode} entityTypeCode={props.entityTypeCode} entityClassCode={props.entityClassCode} collapsed={collapsed} />` ) getProcessName: -> if @props.tasks.length > 0 @props.tasks[0].process_name else null )
[ { "context": " # object as key\n objectKey = {key: \"object\"}\n objectVal = {someObject: \"that's me\"}\n ", "end": 865, "score": 0.8447446823120117, "start": 859, "tag": "KEY", "value": "object" } ]
hash/test.coffee
jneuendorf/js_utils
1
describe "Hash", () -> beforeEach () -> @hash = new JSUtils.Hash() @hash.put 1, "2" @hash.put 2, "3" @hashEq = new JSUtils.Hash( null 42 (key1, key2) -> return key1[0] + key1[1] is key2[0] + key2[1] ) it "get & put", () -> # GET expect @hash.get(1) .toBe "2" expect @hash.get(["a", "b"]) .toBe undefined # PUT expect @hash.get(2) .toBe "3" # replace @hash.put 2, "4" expect @hash.get(2) .toBe "4" # array as key arr = ["a", "b"] @hash.put arr, "3" expect @hash.get(arr) .toBe "3" expect @hash.get(["a", "b"]) .toBeUndefined() # object as key objectKey = {key: "object"} objectVal = {someObject: "that's me"} @hash.put objectKey, objectVal expect @hash.get(objectKey) .toBe objectVal # special equals-function: any key with the same sum of the first two elements is considered equal! @hashEq.put [1, 2], 3 expect @hashEq.get [1, 2] .toBe 3 expect @hashEq.get [2, 1] .toBe 3 @hashEq.put [3, 0], 3 expect @hashEq.get [3, 0] .toBe 3 expect @hashEq.get [2, 1] .toBe 3 it "remove", () -> arr = ["a", "b"] @hash.put arr, "3" @hash.remove 1 expect @hash.get(1) .toBeUndefined() expect @hash.get(2) .toBe "3" @hashEq.put [1, 2], 3 @hashEq.remove [2, 1] # NOTE: 42 here because this value was defined as the defaultValue of this.hashEq expect @hashEq.get [1, 2] .toBe 42 it "empty", () -> arr = ["a", "b"] @hash.put arr, "3" @hash.empty() expect @hash.keys.length .toBe 0 expect @hash.values.length .toBe 0 it "items", () -> arr = ["a", "b"] @hash.put arr, "3" expect @hash.items() .toEqual [ [1, "2"] [2, "3"] [["a", "b"], "3"] ] it "has (== hasKey)", () -> arr = ["a", "b"] @hash.put arr, "3" expect @hash.has 1 .toBe true expect @hash.has 2 .toBe true expect @hash.has arr .toBe true expect @hash.has ["a", "b"] .toBe false expect @hash.has 3 .toBe false it "size", () -> expect @hash.size() .toBe 2 obj = {a: 10, b: 20} @hash.put obj expect @hash.size() .toBe 3 @hash.put {x: 1e3, y: 0.4}, "value" expect @hash.size() .toBe 4 @hash.remove(obj) expect @hash.size() .toBe 3 it "getKeys", () -> expect @hash.getKeys().length .toBe @hash.keys.length expect @hash.getKeys() .toEqual @hash.keys expect @hash.getKeys() is @hash.keys .toBe false expect @hash.getKeys(false) is @hash.keys .toBe true it "getValues", () -> expect @hash.getValues().length .toBe @hash.values.length expect @hash.getValues() .toEqual @hash.values expect @hash.getValues() is @hash.values .toBe false expect @hash.getValues(false) is @hash.values .toBe true it "getKeysForValue", () -> @hash.put 3, "3" expect @hash.getKeysForValue("3") .toEqual [2, 3] it "JSUtils.Hash.fromObject", () -> hash = JSUtils.Hash.fromObject { a: 10 "myKey": ["a", 22] } expect hash.getKeys() .toEqual ["a", "myKey"] expect hash.getValues() .toEqual [10, ["a", 22]] it "toObject", () -> hash = JSUtils.Hash.fromObject { a: 10 "myKey": ["a", 22] } expect hash.toObject() .toEqual { a: 10 myKey: ["a", 22] } it "clone", () -> expect {k: @hash.clone().getKeys(), v: @hash.clone().getValues()} .toEqual {k: @hash.getKeys(), v: @hash.getValues()} expect @hash.clone() is @hash .toBe false it "invert", () -> inverted = @hash.invert() expect inverted.getKeys() .toEqual ["2", "3"] expect inverted.getValues() .toEqual [1, 2] it "each", () -> maxIdx = null @hash.each (key, val, idx) => expect key .toBe @hash.getKeys()[idx] expect val .toBe @hash.getValues()[idx] maxIdx = idx expect maxIdx .toBe @hash.size() - 1 # iterate in certain order result = [] @hash.each( (key, val, idx) -> result.push [key, val] (a, b) -> return b - a ) expect result .toEqual [[2, "3"], [1, "2"]]
65771
describe "Hash", () -> beforeEach () -> @hash = new JSUtils.Hash() @hash.put 1, "2" @hash.put 2, "3" @hashEq = new JSUtils.Hash( null 42 (key1, key2) -> return key1[0] + key1[1] is key2[0] + key2[1] ) it "get & put", () -> # GET expect @hash.get(1) .toBe "2" expect @hash.get(["a", "b"]) .toBe undefined # PUT expect @hash.get(2) .toBe "3" # replace @hash.put 2, "4" expect @hash.get(2) .toBe "4" # array as key arr = ["a", "b"] @hash.put arr, "3" expect @hash.get(arr) .toBe "3" expect @hash.get(["a", "b"]) .toBeUndefined() # object as key objectKey = {key: "<KEY>"} objectVal = {someObject: "that's me"} @hash.put objectKey, objectVal expect @hash.get(objectKey) .toBe objectVal # special equals-function: any key with the same sum of the first two elements is considered equal! @hashEq.put [1, 2], 3 expect @hashEq.get [1, 2] .toBe 3 expect @hashEq.get [2, 1] .toBe 3 @hashEq.put [3, 0], 3 expect @hashEq.get [3, 0] .toBe 3 expect @hashEq.get [2, 1] .toBe 3 it "remove", () -> arr = ["a", "b"] @hash.put arr, "3" @hash.remove 1 expect @hash.get(1) .toBeUndefined() expect @hash.get(2) .toBe "3" @hashEq.put [1, 2], 3 @hashEq.remove [2, 1] # NOTE: 42 here because this value was defined as the defaultValue of this.hashEq expect @hashEq.get [1, 2] .toBe 42 it "empty", () -> arr = ["a", "b"] @hash.put arr, "3" @hash.empty() expect @hash.keys.length .toBe 0 expect @hash.values.length .toBe 0 it "items", () -> arr = ["a", "b"] @hash.put arr, "3" expect @hash.items() .toEqual [ [1, "2"] [2, "3"] [["a", "b"], "3"] ] it "has (== hasKey)", () -> arr = ["a", "b"] @hash.put arr, "3" expect @hash.has 1 .toBe true expect @hash.has 2 .toBe true expect @hash.has arr .toBe true expect @hash.has ["a", "b"] .toBe false expect @hash.has 3 .toBe false it "size", () -> expect @hash.size() .toBe 2 obj = {a: 10, b: 20} @hash.put obj expect @hash.size() .toBe 3 @hash.put {x: 1e3, y: 0.4}, "value" expect @hash.size() .toBe 4 @hash.remove(obj) expect @hash.size() .toBe 3 it "getKeys", () -> expect @hash.getKeys().length .toBe @hash.keys.length expect @hash.getKeys() .toEqual @hash.keys expect @hash.getKeys() is @hash.keys .toBe false expect @hash.getKeys(false) is @hash.keys .toBe true it "getValues", () -> expect @hash.getValues().length .toBe @hash.values.length expect @hash.getValues() .toEqual @hash.values expect @hash.getValues() is @hash.values .toBe false expect @hash.getValues(false) is @hash.values .toBe true it "getKeysForValue", () -> @hash.put 3, "3" expect @hash.getKeysForValue("3") .toEqual [2, 3] it "JSUtils.Hash.fromObject", () -> hash = JSUtils.Hash.fromObject { a: 10 "myKey": ["a", 22] } expect hash.getKeys() .toEqual ["a", "myKey"] expect hash.getValues() .toEqual [10, ["a", 22]] it "toObject", () -> hash = JSUtils.Hash.fromObject { a: 10 "myKey": ["a", 22] } expect hash.toObject() .toEqual { a: 10 myKey: ["a", 22] } it "clone", () -> expect {k: @hash.clone().getKeys(), v: @hash.clone().getValues()} .toEqual {k: @hash.getKeys(), v: @hash.getValues()} expect @hash.clone() is @hash .toBe false it "invert", () -> inverted = @hash.invert() expect inverted.getKeys() .toEqual ["2", "3"] expect inverted.getValues() .toEqual [1, 2] it "each", () -> maxIdx = null @hash.each (key, val, idx) => expect key .toBe @hash.getKeys()[idx] expect val .toBe @hash.getValues()[idx] maxIdx = idx expect maxIdx .toBe @hash.size() - 1 # iterate in certain order result = [] @hash.each( (key, val, idx) -> result.push [key, val] (a, b) -> return b - a ) expect result .toEqual [[2, "3"], [1, "2"]]
true
describe "Hash", () -> beforeEach () -> @hash = new JSUtils.Hash() @hash.put 1, "2" @hash.put 2, "3" @hashEq = new JSUtils.Hash( null 42 (key1, key2) -> return key1[0] + key1[1] is key2[0] + key2[1] ) it "get & put", () -> # GET expect @hash.get(1) .toBe "2" expect @hash.get(["a", "b"]) .toBe undefined # PUT expect @hash.get(2) .toBe "3" # replace @hash.put 2, "4" expect @hash.get(2) .toBe "4" # array as key arr = ["a", "b"] @hash.put arr, "3" expect @hash.get(arr) .toBe "3" expect @hash.get(["a", "b"]) .toBeUndefined() # object as key objectKey = {key: "PI:KEY:<KEY>END_PI"} objectVal = {someObject: "that's me"} @hash.put objectKey, objectVal expect @hash.get(objectKey) .toBe objectVal # special equals-function: any key with the same sum of the first two elements is considered equal! @hashEq.put [1, 2], 3 expect @hashEq.get [1, 2] .toBe 3 expect @hashEq.get [2, 1] .toBe 3 @hashEq.put [3, 0], 3 expect @hashEq.get [3, 0] .toBe 3 expect @hashEq.get [2, 1] .toBe 3 it "remove", () -> arr = ["a", "b"] @hash.put arr, "3" @hash.remove 1 expect @hash.get(1) .toBeUndefined() expect @hash.get(2) .toBe "3" @hashEq.put [1, 2], 3 @hashEq.remove [2, 1] # NOTE: 42 here because this value was defined as the defaultValue of this.hashEq expect @hashEq.get [1, 2] .toBe 42 it "empty", () -> arr = ["a", "b"] @hash.put arr, "3" @hash.empty() expect @hash.keys.length .toBe 0 expect @hash.values.length .toBe 0 it "items", () -> arr = ["a", "b"] @hash.put arr, "3" expect @hash.items() .toEqual [ [1, "2"] [2, "3"] [["a", "b"], "3"] ] it "has (== hasKey)", () -> arr = ["a", "b"] @hash.put arr, "3" expect @hash.has 1 .toBe true expect @hash.has 2 .toBe true expect @hash.has arr .toBe true expect @hash.has ["a", "b"] .toBe false expect @hash.has 3 .toBe false it "size", () -> expect @hash.size() .toBe 2 obj = {a: 10, b: 20} @hash.put obj expect @hash.size() .toBe 3 @hash.put {x: 1e3, y: 0.4}, "value" expect @hash.size() .toBe 4 @hash.remove(obj) expect @hash.size() .toBe 3 it "getKeys", () -> expect @hash.getKeys().length .toBe @hash.keys.length expect @hash.getKeys() .toEqual @hash.keys expect @hash.getKeys() is @hash.keys .toBe false expect @hash.getKeys(false) is @hash.keys .toBe true it "getValues", () -> expect @hash.getValues().length .toBe @hash.values.length expect @hash.getValues() .toEqual @hash.values expect @hash.getValues() is @hash.values .toBe false expect @hash.getValues(false) is @hash.values .toBe true it "getKeysForValue", () -> @hash.put 3, "3" expect @hash.getKeysForValue("3") .toEqual [2, 3] it "JSUtils.Hash.fromObject", () -> hash = JSUtils.Hash.fromObject { a: 10 "myKey": ["a", 22] } expect hash.getKeys() .toEqual ["a", "myKey"] expect hash.getValues() .toEqual [10, ["a", 22]] it "toObject", () -> hash = JSUtils.Hash.fromObject { a: 10 "myKey": ["a", 22] } expect hash.toObject() .toEqual { a: 10 myKey: ["a", 22] } it "clone", () -> expect {k: @hash.clone().getKeys(), v: @hash.clone().getValues()} .toEqual {k: @hash.getKeys(), v: @hash.getValues()} expect @hash.clone() is @hash .toBe false it "invert", () -> inverted = @hash.invert() expect inverted.getKeys() .toEqual ["2", "3"] expect inverted.getValues() .toEqual [1, 2] it "each", () -> maxIdx = null @hash.each (key, val, idx) => expect key .toBe @hash.getKeys()[idx] expect val .toBe @hash.getValues()[idx] maxIdx = idx expect maxIdx .toBe @hash.size() - 1 # iterate in certain order result = [] @hash.each( (key, val, idx) -> result.push [key, val] (a, b) -> return b - a ) expect result .toEqual [[2, "3"], [1, "2"]]
[ { "context": "# Note: Turkish locale by fiatux.com\nuploadcare.namespace 'uploadcare.locale.translati", "end": 36, "score": 0.700548529624939, "start": 26, "tag": "EMAIL", "value": "fiatux.com" } ]
app/assets/javascripts/uploadcare/locale/tr.js.coffee
uniiverse/uploadcare-widget
0
# Note: Turkish locale by fiatux.com uploadcare.namespace 'uploadcare.locale.translations', (ns) -> ns.tr = uploading: 'Yükleniyor... Lütfen bekleyin.' loadingInfo: 'Bilgiler yükleniyor...' errors: default: 'Hata' baddata: 'Geçersiz değer' size: 'Dosya çok büyük' upload: 'Yüklenemedi' user: 'Yükleme iptal edildi' info: 'Bilgiler getirilemedi' image: 'Sadece resim dosyası yüklenebilir' createGroup: 'Dosya grubu yaratılamıyor' deleted: 'Dosya silinmiş' draghere: 'Buraya bir dosya bırakın' file: other: '%1 dosya' buttons: cancel: 'İptal' remove: 'Kaldır' choose: files: one: 'Dosya Seçin' other: 'Dosya Seçin' images: one: 'Resim Dosyası Seçin' other: 'Resim Dosyası Seçin' dialog: done: 'Bitti' showFiles: 'Dosyaları Göster' tabs: names: preview: 'Önizleme' file: 'Bilgisayar' url: 'Dış Bağlantılar' file: drag: 'Braya bir dosya bakın' nodrop: 'Bilgisayarınızdan dosya yükleyin' or: 'or' button: 'Bilgisayardan bir dosya seç' also: 'Diğer yükleme seçenekleri' url: title: 'Webden dosyalar' line1: 'Webden herhangi bir dosya seçin.' line2: 'Dosya bağlantısını sağlayın.' input: 'Bağlantınızı buraya yapıştırın...' button: 'Yükle' preview: unknownName: 'bilinmeyen' change: 'İptal' back: 'Geri' done: 'Ekle' unknown: title: 'Yükleniyor... Önizleme için lütfen bekleyin.' done: 'Önizlemeyi geç ve kabul et' regular: title: 'Bu dosya eklensin mi?' line1: 'Yukarıdaki dosyayı eklemek üzeresiniz.' line2: 'Lütfen onaylayın.' image: title: 'Bu görsel eklensin mi?' change: 'İptal' crop: title: 'Bu görseli kes ve ekle' done: 'Bitti' error: default: title: 'Aman!' text: 'Yükleme sırasında bir hata oluştu.' back: 'Lütfen tekrar deneyin.' image: title: 'Sadece resim dosyaları kabul edilmektedir.' text: 'Lütfen başka bir dosya ile tekrar deneyin.' back: 'Resim dosyası seç' size: title: 'Seçtiğiniz dosya limitleri aşıyor.' text: 'Lütfen başka bir dosya ile tekrar deneyin.' loadImage: title: 'Hata' text: 'Resim dosyası yüklenemedi' multiple: title: '%files% dosya seçtiniz' question: 'Bu dosyaların hepsini eklemek istiyor musunuz?' tooManyFiles: 'Fazla sayıda dosya seçtiniz, en fazla %max% dosya olabilir.' tooFewFiles: '%files% dosya seçtiniz, en az %min% dosya olmalıdır.' clear: 'Hepsini kaldır' done: 'Bitti' footer: text: 'Dosya yükleme, saklama ve işleme servisi' uploadcare.namespace 'uploadcare.locale.pluralize', (ns) -> ns.tr = (n) -> return 'other'
100128
# Note: Turkish locale by <EMAIL> uploadcare.namespace 'uploadcare.locale.translations', (ns) -> ns.tr = uploading: 'Yükleniyor... Lütfen bekleyin.' loadingInfo: 'Bilgiler yükleniyor...' errors: default: 'Hata' baddata: 'Geçersiz değer' size: 'Dosya çok büyük' upload: 'Yüklenemedi' user: 'Yükleme iptal edildi' info: 'Bilgiler getirilemedi' image: 'Sadece resim dosyası yüklenebilir' createGroup: 'Dosya grubu yaratılamıyor' deleted: 'Dosya silinmiş' draghere: 'Buraya bir dosya bırakın' file: other: '%1 dosya' buttons: cancel: 'İptal' remove: 'Kaldır' choose: files: one: 'Dosya Seçin' other: 'Dosya Seçin' images: one: 'Resim Dosyası Seçin' other: 'Resim Dosyası Seçin' dialog: done: 'Bitti' showFiles: 'Dosyaları Göster' tabs: names: preview: 'Önizleme' file: 'Bilgisayar' url: 'Dış Bağlantılar' file: drag: 'Braya bir dosya bakın' nodrop: 'Bilgisayarınızdan dosya yükleyin' or: 'or' button: 'Bilgisayardan bir dosya seç' also: 'Diğer yükleme seçenekleri' url: title: 'Webden dosyalar' line1: 'Webden herhangi bir dosya seçin.' line2: 'Dosya bağlantısını sağlayın.' input: 'Bağlantınızı buraya yapıştırın...' button: 'Yükle' preview: unknownName: 'bilinmeyen' change: 'İptal' back: 'Geri' done: 'Ekle' unknown: title: 'Yükleniyor... Önizleme için lütfen bekleyin.' done: 'Önizlemeyi geç ve kabul et' regular: title: 'Bu dosya eklensin mi?' line1: 'Yukarıdaki dosyayı eklemek üzeresiniz.' line2: 'Lütfen onaylayın.' image: title: 'Bu görsel eklensin mi?' change: 'İptal' crop: title: 'Bu görseli kes ve ekle' done: 'Bitti' error: default: title: 'Aman!' text: 'Yükleme sırasında bir hata oluştu.' back: 'Lütfen tekrar deneyin.' image: title: 'Sadece resim dosyaları kabul edilmektedir.' text: 'Lütfen başka bir dosya ile tekrar deneyin.' back: 'Resim dosyası seç' size: title: 'Seçtiğiniz dosya limitleri aşıyor.' text: 'Lütfen başka bir dosya ile tekrar deneyin.' loadImage: title: 'Hata' text: 'Resim dosyası yüklenemedi' multiple: title: '%files% dosya seçtiniz' question: 'Bu dosyaların hepsini eklemek istiyor musunuz?' tooManyFiles: 'Fazla sayıda dosya seçtiniz, en fazla %max% dosya olabilir.' tooFewFiles: '%files% dosya seçtiniz, en az %min% dosya olmalıdır.' clear: 'Hepsini kaldır' done: 'Bitti' footer: text: 'Dosya yükleme, saklama ve işleme servisi' uploadcare.namespace 'uploadcare.locale.pluralize', (ns) -> ns.tr = (n) -> return 'other'
true
# Note: Turkish locale by PI:EMAIL:<EMAIL>END_PI uploadcare.namespace 'uploadcare.locale.translations', (ns) -> ns.tr = uploading: 'Yükleniyor... Lütfen bekleyin.' loadingInfo: 'Bilgiler yükleniyor...' errors: default: 'Hata' baddata: 'Geçersiz değer' size: 'Dosya çok büyük' upload: 'Yüklenemedi' user: 'Yükleme iptal edildi' info: 'Bilgiler getirilemedi' image: 'Sadece resim dosyası yüklenebilir' createGroup: 'Dosya grubu yaratılamıyor' deleted: 'Dosya silinmiş' draghere: 'Buraya bir dosya bırakın' file: other: '%1 dosya' buttons: cancel: 'İptal' remove: 'Kaldır' choose: files: one: 'Dosya Seçin' other: 'Dosya Seçin' images: one: 'Resim Dosyası Seçin' other: 'Resim Dosyası Seçin' dialog: done: 'Bitti' showFiles: 'Dosyaları Göster' tabs: names: preview: 'Önizleme' file: 'Bilgisayar' url: 'Dış Bağlantılar' file: drag: 'Braya bir dosya bakın' nodrop: 'Bilgisayarınızdan dosya yükleyin' or: 'or' button: 'Bilgisayardan bir dosya seç' also: 'Diğer yükleme seçenekleri' url: title: 'Webden dosyalar' line1: 'Webden herhangi bir dosya seçin.' line2: 'Dosya bağlantısını sağlayın.' input: 'Bağlantınızı buraya yapıştırın...' button: 'Yükle' preview: unknownName: 'bilinmeyen' change: 'İptal' back: 'Geri' done: 'Ekle' unknown: title: 'Yükleniyor... Önizleme için lütfen bekleyin.' done: 'Önizlemeyi geç ve kabul et' regular: title: 'Bu dosya eklensin mi?' line1: 'Yukarıdaki dosyayı eklemek üzeresiniz.' line2: 'Lütfen onaylayın.' image: title: 'Bu görsel eklensin mi?' change: 'İptal' crop: title: 'Bu görseli kes ve ekle' done: 'Bitti' error: default: title: 'Aman!' text: 'Yükleme sırasında bir hata oluştu.' back: 'Lütfen tekrar deneyin.' image: title: 'Sadece resim dosyaları kabul edilmektedir.' text: 'Lütfen başka bir dosya ile tekrar deneyin.' back: 'Resim dosyası seç' size: title: 'Seçtiğiniz dosya limitleri aşıyor.' text: 'Lütfen başka bir dosya ile tekrar deneyin.' loadImage: title: 'Hata' text: 'Resim dosyası yüklenemedi' multiple: title: '%files% dosya seçtiniz' question: 'Bu dosyaların hepsini eklemek istiyor musunuz?' tooManyFiles: 'Fazla sayıda dosya seçtiniz, en fazla %max% dosya olabilir.' tooFewFiles: '%files% dosya seçtiniz, en az %min% dosya olmalıdır.' clear: 'Hepsini kaldır' done: 'Bitti' footer: text: 'Dosya yükleme, saklama ve işleme servisi' uploadcare.namespace 'uploadcare.locale.pluralize', (ns) -> ns.tr = (n) -> return 'other'
[ { "context": "Over\"\n contact: \"Contact\"\n twitter_follow: \"Volgen\"\n\n forms:\n name: \"Naam\"\n email: \"Email\"\n ", "end": 572, "score": 0.9977166652679443, "start": 566, "tag": "USERNAME", "value": "Volgen" }, { "context": "olor: \"Tovenaar Kleding Kleur\"\n ...
app/locale/nl.coffee
lwatiker/codecombat
1
module.exports = nativeDescription: "Nederlands", englishDescription: "Dutch", translation: common: loading: "Aan het laden..." modal: close: "Sluiten" okay: "Oké" not_found: page_not_found: "Pagina niet gevonden" nav: # Header sign_up: "Account Maken" log_in: "Inloggen" log_out: "Uitloggen" play: "Spelen" # editor: "" blog: "Blog" forum: "Forum" admin: "Admin" # Footer home: "Home" contribute: "Bijdragen" legal: "Legaal" about: "Over" contact: "Contact" twitter_follow: "Volgen" forms: name: "Naam" email: "Email" message: "Bericht" cancel: "Annuleren" login: log_in: "Inloggen" sign_up: "nieuw account aanmaken" or: ", of " recover: "account herstellen" signup: description: "Het is gratis. We hebben maar een paar dingen nodig en dan kan je aan de slag:" email_announcements: "Ontvang aankondigingen via email" coppa: "13+ of niet uit de VS" coppa_why: "(Waarom?)" creating: "Account aanmaken..." sign_up: "Aanmelden" or: "of " log_in: "inloggen met wachtwoord" home: slogan: "Leer programmeren in JavaScript door het spelen van een spel" no_ie: "CodeCombat werkt niet in IE8 of ouder. Sorry!" no_mobile: "CodeCombat is niet gemaakt voor mobiele apparaten en werkt misschien niet!" play: "Speel" play: choose_your_level: "Kies Je Level" adventurer_prefix: "Je kunt meteen naar een van de levels hieronder springen, of de levels bespreken op " adventurer_forum: "het Avonturiersforum" adventurer_suffix: "." campaign_beginner: "Beginnercampagne" campaign_beginner_description: "... waarin je de toverkunst van programmeren leert." campaign_dev: "Willekeurige moeilijkere levels" campaign_dev_description: "... waarin je de interface leert kennen terwijl je wat moeilijkers doet." campaign_multiplayer: "Multiplayer Arena's" campaign_multiplayer_description: "... waarin je direct tegen andere spelers speelt." campaign_player_created: "Door-spelers-gemaakt" campaign_player_created_description: "... waarin je ten strijde trekt tegen de creativiteit van andere <a href=\"/contribute#artisan\">Ambachtelijke Tovenaars</a>." level_difficulty: "Moeilijkheidsgraad: " contact: contact_us: "Contact opnemen met CodeCombat" welcome: "Goed om van je te horen! Gebruik dit formulier om ons een e-mail te sturen." contribute_prefix: "Als je interesse hebt om bij te dragen, bekijk onze " contribute_page: "pagina over bijdragen" contribute_suffix: "!" forum_prefix: "Voor iets publiekelijks, probeer dan " forum_page: "ons forum" forum_suffix: "." sending: "Verzenden..." send: "Feedback Verzonden" diplomat_suggestion: title: "Help CodeCombat vertalen!" sub_heading: "We hebben je taalvaardigheden nodig." pitch_body: "We ontwikkelen CodeCombat in het Engels, maar we hebben al spelers van over de hele wereld. Veel van hen willen in het Nederlands spelen, maar kunnen geen Engels. Dus als je beiden spreekt, overweeg a.u.b. om je aan te melden als Diplomaat en help zowel de CodeCombat website als alle levels te vertalen naar het Nederlands." missing_translations: "Totdat we alles hebben vertaald naar het Nederlands zul je Engels zien waar Nederlands niet beschikbaar is." learn_more: "Meer informatie over het zijn van een Diplomaat" subscribe_as_diplomat: "Abonneren als Diplomaat" account_settings: title: "Account Instellingen" not_logged_in: "Log in of maak een account om je instellingen aan te passen." autosave: "Aanpassingen Worden Automatisch Opgeslagen" me_tab: "Ik" picture_tab: "Afbeelding" wizard_tab: "Tovenaar" password_tab: "Wachtwoord" emails_tab: "Emails" language_tab: "Taal" gravatar_select: "Select which Gravatar photo to use" # gravatar_add_photos: "" gravatar_add_more_photos: "Voeg meer afbeeldingen toe aan je Gravatar account om ze hier te gebruiken." wizard_color: "Tovenaar Kleding Kleur" new_password: "Nieuw Wachtwoord" new_password_verify: "Verifieer" email_subscriptions: "Email Abonnementen" email_announcements: "Aankondegingen" email_announcements_description: "Verkrijg emails over het laatste nieuws en de ontwikkelingen bij CodeCombat." # contributor_emails: "" contribute_prefix: "We zoeken mensen om bij ons feest aan te voegen! Bekijk de " contribute_page: "contributie pagina" contribute_suffix: " om meer te weten te komen." # email_toggle: "" language: "Taal" saving: "Opslaan..." error_saving: "Fout Tijdens Het Opslaan" saved: "Aanpassingen Opgeslagen" password_mismatch: "Het wachtwoord komt niet overeen." account_profile: edit_settings: "Instellingen Aanpassen" profile_for_prefix: "Profiel voor " profile_for_suffix: "" profile: "Profiel" user_not_found: "Geen gebruiker gevonden. Controleer de URL?" # gravatar_not_found_mine: "" gravatar_signup_prefix: "Registreer op " gravatar_signup_suffix: "" gravatar_not_found_other: "Alas, there's no profile associated with this person's email address." gravatar_contact: "Contact" gravatar_websites: "Websites" gravatar_accounts: "Zoals Gezien Op" gravatar_profile_link: "Volledig Gravatar Profiel" play_level: level_load_error: "Level kon niet geladen worden." done: "Klaar" grid: "Raster" # customize_wizard: "" # home: "" guide: "Handleiding" multiplayer: "Multiplayer" restart: "Herstarten" goals: "Doelen" # action_timeline: "" click_to_select: "Klik op een eenheid om deze te selecteren." reload_title: "Alle Code Herladen?" reload_really: "Weet je zeker dat je dit level tot het begin wilt herladen?" reload_confirm: "Herlaad Alles" # victory_title_prefix: "" # victory_title_suffix: "" # victory_sign_up: "" # victory_sign_up_poke: "" # victory_rate_the_level: "" victory_play_next_level: "Speel Volgend Level" # victory_go_home: "" victory_review: "Vertel ons meer!" victory_hour_of_code_done: "Ben Je Klaar?" # victory_hour_of_code_done_yes: "" multiplayer_title: "Multiplayer Instellingen" # multiplayer_link_description: "Give this link to anyone to have them join you." multiplayer_hint_label: "Hint:" multiplayer_hint: " Klik de link om alles te selecteren, druk dan op Apple-C of Ctrl-C om de link te kopiëren." # multiplayer_coming_soon: "" guide_title: "Handleiding" # tome_minion_spells: "" # tome_read_only_spells: "" tome_other_units: "Andere Eenheden" # tome_cast_button_castable: "" # tome_cast_button_casting: "" # tome_cast_button_cast: "" # tome_autocast_delay: "" tome_autocast_1: "1 seconde" tome_autocast_3: "3 seconde" tome_autocast_5: "5 seconde" tome_autocast_manual: "Handmatig" tome_select_spell: "Selecteer een Spreuk" tome_select_a_thang: "Selecteer Iemand voor " tome_available_spells: "Beschikbare spreuken" # hud_continue: ""
90345
module.exports = nativeDescription: "Nederlands", englishDescription: "Dutch", translation: common: loading: "Aan het laden..." modal: close: "Sluiten" okay: "Oké" not_found: page_not_found: "Pagina niet gevonden" nav: # Header sign_up: "Account Maken" log_in: "Inloggen" log_out: "Uitloggen" play: "Spelen" # editor: "" blog: "Blog" forum: "Forum" admin: "Admin" # Footer home: "Home" contribute: "Bijdragen" legal: "Legaal" about: "Over" contact: "Contact" twitter_follow: "Volgen" forms: name: "Naam" email: "Email" message: "Bericht" cancel: "Annuleren" login: log_in: "Inloggen" sign_up: "nieuw account aanmaken" or: ", of " recover: "account herstellen" signup: description: "Het is gratis. We hebben maar een paar dingen nodig en dan kan je aan de slag:" email_announcements: "Ontvang aankondigingen via email" coppa: "13+ of niet uit de VS" coppa_why: "(Waarom?)" creating: "Account aanmaken..." sign_up: "Aanmelden" or: "of " log_in: "inloggen met wachtwoord" home: slogan: "Leer programmeren in JavaScript door het spelen van een spel" no_ie: "CodeCombat werkt niet in IE8 of ouder. Sorry!" no_mobile: "CodeCombat is niet gemaakt voor mobiele apparaten en werkt misschien niet!" play: "Speel" play: choose_your_level: "Kies Je Level" adventurer_prefix: "Je kunt meteen naar een van de levels hieronder springen, of de levels bespreken op " adventurer_forum: "het Avonturiersforum" adventurer_suffix: "." campaign_beginner: "Beginnercampagne" campaign_beginner_description: "... waarin je de toverkunst van programmeren leert." campaign_dev: "Willekeurige moeilijkere levels" campaign_dev_description: "... waarin je de interface leert kennen terwijl je wat moeilijkers doet." campaign_multiplayer: "Multiplayer Arena's" campaign_multiplayer_description: "... waarin je direct tegen andere spelers speelt." campaign_player_created: "Door-spelers-gemaakt" campaign_player_created_description: "... waarin je ten strijde trekt tegen de creativiteit van andere <a href=\"/contribute#artisan\">Ambachtelijke Tovenaars</a>." level_difficulty: "Moeilijkheidsgraad: " contact: contact_us: "Contact opnemen met CodeCombat" welcome: "Goed om van je te horen! Gebruik dit formulier om ons een e-mail te sturen." contribute_prefix: "Als je interesse hebt om bij te dragen, bekijk onze " contribute_page: "pagina over bijdragen" contribute_suffix: "!" forum_prefix: "Voor iets publiekelijks, probeer dan " forum_page: "ons forum" forum_suffix: "." sending: "Verzenden..." send: "Feedback Verzonden" diplomat_suggestion: title: "Help CodeCombat vertalen!" sub_heading: "We hebben je taalvaardigheden nodig." pitch_body: "We ontwikkelen CodeCombat in het Engels, maar we hebben al spelers van over de hele wereld. Veel van hen willen in het Nederlands spelen, maar kunnen geen Engels. Dus als je beiden spreekt, overweeg a.u.b. om je aan te melden als Diplomaat en help zowel de CodeCombat website als alle levels te vertalen naar het Nederlands." missing_translations: "Totdat we alles hebben vertaald naar het Nederlands zul je Engels zien waar Nederlands niet beschikbaar is." learn_more: "Meer informatie over het zijn van een Diplomaat" subscribe_as_diplomat: "Abonneren als Diplomaat" account_settings: title: "Account Instellingen" not_logged_in: "Log in of maak een account om je instellingen aan te passen." autosave: "Aanpassingen Worden Automatisch Opgeslagen" me_tab: "Ik" picture_tab: "Afbeelding" wizard_tab: "Tovenaar" password_tab: "Wachtwoord" emails_tab: "Emails" language_tab: "Taal" gravatar_select: "Select which Gravatar photo to use" # gravatar_add_photos: "" gravatar_add_more_photos: "Voeg meer afbeeldingen toe aan je Gravatar account om ze hier te gebruiken." wizard_color: "Tovenaar Kleding Kleur" new_password: "<PASSWORD>" new_password_verify: "<PASSWORD>" email_subscriptions: "Email Abonnementen" email_announcements: "Aankondegingen" email_announcements_description: "Verkrijg emails over het laatste nieuws en de ontwikkelingen bij CodeCombat." # contributor_emails: "" contribute_prefix: "We zoeken mensen om bij ons feest aan te voegen! Bekijk de " contribute_page: "contributie pagina" contribute_suffix: " om meer te weten te komen." # email_toggle: "" language: "Taal" saving: "Opslaan..." error_saving: "Fout Tijdens Het Opslaan" saved: "Aanpassingen Opgeslagen" password_mismatch: "Het wachtwoord komt niet overeen." account_profile: edit_settings: "Instellingen Aanpassen" profile_for_prefix: "<NAME> voor " profile_for_suffix: "" profile: "<NAME>" user_not_found: "Geen gebruiker gevonden. Controleer de URL?" # gravatar_not_found_mine: "" gravatar_signup_prefix: "Registreer op " gravatar_signup_suffix: "" gravatar_not_found_other: "Alas, there's no profile associated with this person's email address." gravatar_contact: "Contact" gravatar_websites: "Websites" gravatar_accounts: "Zoals Gezien Op" gravatar_profile_link: "Volledig Gravatar <NAME>" play_level: level_load_error: "Level kon niet geladen worden." done: "Klaar" grid: "Raster" # customize_wizard: "" # home: "" guide: "Handleiding" multiplayer: "Multiplayer" restart: "Herstarten" goals: "Doelen" # action_timeline: "" click_to_select: "Klik op een eenheid om deze te selecteren." reload_title: "Alle Code Herladen?" reload_really: "Weet je zeker dat je dit level tot het begin wilt herladen?" reload_confirm: "Herlaad Alles" # victory_title_prefix: "" # victory_title_suffix: "" # victory_sign_up: "" # victory_sign_up_poke: "" # victory_rate_the_level: "" victory_play_next_level: "Speel Volgend Level" # victory_go_home: "" victory_review: "Vertel ons meer!" victory_hour_of_code_done: "Ben Je Klaar?" # victory_hour_of_code_done_yes: "" multiplayer_title: "Multiplayer Instellingen" # multiplayer_link_description: "Give this link to anyone to have them join you." multiplayer_hint_label: "Hint:" multiplayer_hint: " Klik de link om alles te selecteren, druk dan op Apple-C of Ctrl-C om de link te kopiëren." # multiplayer_coming_soon: "" guide_title: "Handleiding" # tome_minion_spells: "" # tome_read_only_spells: "" tome_other_units: "Andere Eenheden" # tome_cast_button_castable: "" # tome_cast_button_casting: "" # tome_cast_button_cast: "" # tome_autocast_delay: "" tome_autocast_1: "1 seconde" tome_autocast_3: "3 seconde" tome_autocast_5: "5 seconde" tome_autocast_manual: "Handmatig" tome_select_spell: "Selecteer een Spreuk" tome_select_a_thang: "Selecteer Iemand voor " tome_available_spells: "Beschikbare spreuken" # hud_continue: ""
true
module.exports = nativeDescription: "Nederlands", englishDescription: "Dutch", translation: common: loading: "Aan het laden..." modal: close: "Sluiten" okay: "Oké" not_found: page_not_found: "Pagina niet gevonden" nav: # Header sign_up: "Account Maken" log_in: "Inloggen" log_out: "Uitloggen" play: "Spelen" # editor: "" blog: "Blog" forum: "Forum" admin: "Admin" # Footer home: "Home" contribute: "Bijdragen" legal: "Legaal" about: "Over" contact: "Contact" twitter_follow: "Volgen" forms: name: "Naam" email: "Email" message: "Bericht" cancel: "Annuleren" login: log_in: "Inloggen" sign_up: "nieuw account aanmaken" or: ", of " recover: "account herstellen" signup: description: "Het is gratis. We hebben maar een paar dingen nodig en dan kan je aan de slag:" email_announcements: "Ontvang aankondigingen via email" coppa: "13+ of niet uit de VS" coppa_why: "(Waarom?)" creating: "Account aanmaken..." sign_up: "Aanmelden" or: "of " log_in: "inloggen met wachtwoord" home: slogan: "Leer programmeren in JavaScript door het spelen van een spel" no_ie: "CodeCombat werkt niet in IE8 of ouder. Sorry!" no_mobile: "CodeCombat is niet gemaakt voor mobiele apparaten en werkt misschien niet!" play: "Speel" play: choose_your_level: "Kies Je Level" adventurer_prefix: "Je kunt meteen naar een van de levels hieronder springen, of de levels bespreken op " adventurer_forum: "het Avonturiersforum" adventurer_suffix: "." campaign_beginner: "Beginnercampagne" campaign_beginner_description: "... waarin je de toverkunst van programmeren leert." campaign_dev: "Willekeurige moeilijkere levels" campaign_dev_description: "... waarin je de interface leert kennen terwijl je wat moeilijkers doet." campaign_multiplayer: "Multiplayer Arena's" campaign_multiplayer_description: "... waarin je direct tegen andere spelers speelt." campaign_player_created: "Door-spelers-gemaakt" campaign_player_created_description: "... waarin je ten strijde trekt tegen de creativiteit van andere <a href=\"/contribute#artisan\">Ambachtelijke Tovenaars</a>." level_difficulty: "Moeilijkheidsgraad: " contact: contact_us: "Contact opnemen met CodeCombat" welcome: "Goed om van je te horen! Gebruik dit formulier om ons een e-mail te sturen." contribute_prefix: "Als je interesse hebt om bij te dragen, bekijk onze " contribute_page: "pagina over bijdragen" contribute_suffix: "!" forum_prefix: "Voor iets publiekelijks, probeer dan " forum_page: "ons forum" forum_suffix: "." sending: "Verzenden..." send: "Feedback Verzonden" diplomat_suggestion: title: "Help CodeCombat vertalen!" sub_heading: "We hebben je taalvaardigheden nodig." pitch_body: "We ontwikkelen CodeCombat in het Engels, maar we hebben al spelers van over de hele wereld. Veel van hen willen in het Nederlands spelen, maar kunnen geen Engels. Dus als je beiden spreekt, overweeg a.u.b. om je aan te melden als Diplomaat en help zowel de CodeCombat website als alle levels te vertalen naar het Nederlands." missing_translations: "Totdat we alles hebben vertaald naar het Nederlands zul je Engels zien waar Nederlands niet beschikbaar is." learn_more: "Meer informatie over het zijn van een Diplomaat" subscribe_as_diplomat: "Abonneren als Diplomaat" account_settings: title: "Account Instellingen" not_logged_in: "Log in of maak een account om je instellingen aan te passen." autosave: "Aanpassingen Worden Automatisch Opgeslagen" me_tab: "Ik" picture_tab: "Afbeelding" wizard_tab: "Tovenaar" password_tab: "Wachtwoord" emails_tab: "Emails" language_tab: "Taal" gravatar_select: "Select which Gravatar photo to use" # gravatar_add_photos: "" gravatar_add_more_photos: "Voeg meer afbeeldingen toe aan je Gravatar account om ze hier te gebruiken." wizard_color: "Tovenaar Kleding Kleur" new_password: "PI:PASSWORD:<PASSWORD>END_PI" new_password_verify: "PI:PASSWORD:<PASSWORD>END_PI" email_subscriptions: "Email Abonnementen" email_announcements: "Aankondegingen" email_announcements_description: "Verkrijg emails over het laatste nieuws en de ontwikkelingen bij CodeCombat." # contributor_emails: "" contribute_prefix: "We zoeken mensen om bij ons feest aan te voegen! Bekijk de " contribute_page: "contributie pagina" contribute_suffix: " om meer te weten te komen." # email_toggle: "" language: "Taal" saving: "Opslaan..." error_saving: "Fout Tijdens Het Opslaan" saved: "Aanpassingen Opgeslagen" password_mismatch: "Het wachtwoord komt niet overeen." account_profile: edit_settings: "Instellingen Aanpassen" profile_for_prefix: "PI:NAME:<NAME>END_PI voor " profile_for_suffix: "" profile: "PI:NAME:<NAME>END_PI" user_not_found: "Geen gebruiker gevonden. Controleer de URL?" # gravatar_not_found_mine: "" gravatar_signup_prefix: "Registreer op " gravatar_signup_suffix: "" gravatar_not_found_other: "Alas, there's no profile associated with this person's email address." gravatar_contact: "Contact" gravatar_websites: "Websites" gravatar_accounts: "Zoals Gezien Op" gravatar_profile_link: "Volledig Gravatar PI:NAME:<NAME>END_PI" play_level: level_load_error: "Level kon niet geladen worden." done: "Klaar" grid: "Raster" # customize_wizard: "" # home: "" guide: "Handleiding" multiplayer: "Multiplayer" restart: "Herstarten" goals: "Doelen" # action_timeline: "" click_to_select: "Klik op een eenheid om deze te selecteren." reload_title: "Alle Code Herladen?" reload_really: "Weet je zeker dat je dit level tot het begin wilt herladen?" reload_confirm: "Herlaad Alles" # victory_title_prefix: "" # victory_title_suffix: "" # victory_sign_up: "" # victory_sign_up_poke: "" # victory_rate_the_level: "" victory_play_next_level: "Speel Volgend Level" # victory_go_home: "" victory_review: "Vertel ons meer!" victory_hour_of_code_done: "Ben Je Klaar?" # victory_hour_of_code_done_yes: "" multiplayer_title: "Multiplayer Instellingen" # multiplayer_link_description: "Give this link to anyone to have them join you." multiplayer_hint_label: "Hint:" multiplayer_hint: " Klik de link om alles te selecteren, druk dan op Apple-C of Ctrl-C om de link te kopiëren." # multiplayer_coming_soon: "" guide_title: "Handleiding" # tome_minion_spells: "" # tome_read_only_spells: "" tome_other_units: "Andere Eenheden" # tome_cast_button_castable: "" # tome_cast_button_casting: "" # tome_cast_button_cast: "" # tome_autocast_delay: "" tome_autocast_1: "1 seconde" tome_autocast_3: "3 seconde" tome_autocast_5: "5 seconde" tome_autocast_manual: "Handmatig" tome_select_spell: "Selecteer een Spreuk" tome_select_a_thang: "Selecteer Iemand voor " tome_available_spells: "Beschikbare spreuken" # hud_continue: ""
[ { "context": "calhost'\n username: process.env.USERNAME || 'admin'\n password: process.env.PASSWORD || '9999'\n ", "end": 344, "score": 0.9962547421455383, "start": 339, "tag": "USERNAME", "value": "admin" }, { "context": "e: process.env.USERNAME || 'admin'\n password:...
test/device.coffee
unm4sk1g/onvif
1
synthTest = not process.env.HOSTNAME assert = require 'assert' onvif = require('../lib/onvif') serverMockup = require('./serverMockup') if synthTest util = require('util') describe 'Device', () -> cam = null before (done) -> options = { hostname: process.env.HOSTNAME || 'localhost' username: process.env.USERNAME || 'admin' password: process.env.PASSWORD || '9999' port: if process.env.PORT then parseInt(process.env.PORT) else 10101 } cam = new onvif.Cam options, done describe 'getNTP', () -> it 'should return NTP settings', (done) -> cam.getNTP (err, data) -> assert.equal err, null done() describe 'setNTP', () -> if synthTest it 'should set NTP with ipv4', (done) -> cam.setNTP { fromDHCP: false type: 'IPv4' ipv4Address: 'localhost' }, (err) -> assert.equal err, null done() it 'should set NTP with ipv6', (done) -> cam.setNTP { fromDHCP: false type: 'IPv6' ipv6Address: '::1/128' dnsName: '8.8.8.8' }, (err) -> assert.equal err, null done() it 'should set NTP from DHCP', (done) -> cam.setNTP { fromDHCP: true }, (err) -> assert.equal err, null done()
104103
synthTest = not process.env.HOSTNAME assert = require 'assert' onvif = require('../lib/onvif') serverMockup = require('./serverMockup') if synthTest util = require('util') describe 'Device', () -> cam = null before (done) -> options = { hostname: process.env.HOSTNAME || 'localhost' username: process.env.USERNAME || 'admin' password: <PASSWORD> || '<PASSWORD>' port: if process.env.PORT then parseInt(process.env.PORT) else 10101 } cam = new onvif.Cam options, done describe 'getNTP', () -> it 'should return NTP settings', (done) -> cam.getNTP (err, data) -> assert.equal err, null done() describe 'setNTP', () -> if synthTest it 'should set NTP with ipv4', (done) -> cam.setNTP { fromDHCP: false type: 'IPv4' ipv4Address: 'localhost' }, (err) -> assert.equal err, null done() it 'should set NTP with ipv6', (done) -> cam.setNTP { fromDHCP: false type: 'IPv6' ipv6Address: '::1/128' dnsName: '8.8.8.8' }, (err) -> assert.equal err, null done() it 'should set NTP from DHCP', (done) -> cam.setNTP { fromDHCP: true }, (err) -> assert.equal err, null done()
true
synthTest = not process.env.HOSTNAME assert = require 'assert' onvif = require('../lib/onvif') serverMockup = require('./serverMockup') if synthTest util = require('util') describe 'Device', () -> cam = null before (done) -> options = { hostname: process.env.HOSTNAME || 'localhost' username: process.env.USERNAME || 'admin' password: PI:PASSWORD:<PASSWORD>END_PI || 'PI:PASSWORD:<PASSWORD>END_PI' port: if process.env.PORT then parseInt(process.env.PORT) else 10101 } cam = new onvif.Cam options, done describe 'getNTP', () -> it 'should return NTP settings', (done) -> cam.getNTP (err, data) -> assert.equal err, null done() describe 'setNTP', () -> if synthTest it 'should set NTP with ipv4', (done) -> cam.setNTP { fromDHCP: false type: 'IPv4' ipv4Address: 'localhost' }, (err) -> assert.equal err, null done() it 'should set NTP with ipv6', (done) -> cam.setNTP { fromDHCP: false type: 'IPv6' ipv6Address: '::1/128' dnsName: '8.8.8.8' }, (err) -> assert.equal err, null done() it 'should set NTP from DHCP', (done) -> cam.setNTP { fromDHCP: true }, (err) -> assert.equal err, null done()
[ { "context": "ogging: true\n logFn: @logFn\n username: 'username'\n password: 'password'\n\n serverOptions.da", "end": 396, "score": 0.9991405606269836, "start": 388, "tag": "USERNAME", "value": "username" }, { "context": "logFn\n username: 'username'\n pa...
test/integration/update-from-docker-hub-spec.coffee
octoblu/deploy-state-service
1
request = require 'request' moment = require 'moment' Database = require '../database' Server = require '../../src/server' describe 'Update From Docker Hub', -> beforeEach (done) -> @db = new Database @db.drop done beforeEach (done) -> @logFn = sinon.spy() serverOptions = port: undefined, disableLogging: true logFn: @logFn username: 'username' password: 'password' serverOptions.database = @db.database @server = new Server serverOptions @server.run => @serverPort = @server.address().port done() afterEach -> @server.destroy() describe 'on POST /deployments/docker-hub', -> describe 'when the deployment does NOT exist', -> beforeEach (done) -> options = uri: '/deployments/docker-hub' baseUrl: "http://localhost:#{@serverPort}" auth: username: 'username' password: 'password' json: push_data: tag: "v1.0.0" repository: name: 'the-service' namespace: 'the-owner' repo_name: 'the-owner/the-service' request.post options, (error, @response, @body) => done error it 'should return a 201', -> expect(@response.statusCode).to.equal 201 describe 'when the deployment exists', -> describe 'when the build does NOT exist', -> beforeEach (done) -> deployment = tag: 'v1.0.0' repo: 'the-service' owner: 'the-owner' createdAt: moment('2001-01-01').toDate() build: { passing: false "travis-ci": { passing: true } } cluster: {} @db.deployments.insert deployment, done beforeEach (done) -> options = uri: '/deployments/docker-hub' baseUrl: "http://localhost:#{@serverPort}" auth: username: 'username' password: 'password' json: push_data: tag: "v1.0.0" repository: name: 'the-service' namespace: 'the-owner' repo_name: 'the-owner/the-service' request.post options, (error, @response, @body) => done error it 'should return a 201', -> expect(@response.statusCode).to.equal 201 describe 'when the database record is checked', -> beforeEach (done) -> query = { owner: 'the-owner', repo: 'the-service', tag: 'v1.0.0' } @db.deployments.findOne query, (error, @record) => done error it 'should have the dockerUrl', -> expect(@record.build.dockerUrl).to.equal 'the-owner/the-service:v1.0.0' it 'should be passing', -> expect(@record.build.passing).to.be.true it 'should have a docker set to passed', -> expect(@record.build["docker"].passing).to.be.true it 'should have a valid created at date for docker', -> expect(moment(@record.build["docker"].createdAt).isBefore(moment())).to.be.true expect(moment(@record.build["docker"].createdAt).isAfter(moment().subtract(1, 'minute'))).to.be.true describe 'when the build exists', -> beforeEach (done) -> deployment = tag: 'v1.0.0' repo: 'the-service' owner: 'the-owner' createdAt: moment('2001-01-01').toDate() build: { passing: false, "docker": { passing: false } "travis-ci": { passing: true } } cluster: {} @db.deployments.insert deployment, done beforeEach (done) -> options = uri: '/deployments/docker-hub' baseUrl: "http://localhost:#{@serverPort}" auth: username: 'username' password: 'password' json: push_data: tag: "v1.0.0" repository: name: 'the-service' namespace: 'the-owner' repo_name: 'the-owner/the-service' request.post options, (error, @response, @body) => done error it 'should return a 201', -> expect(@response.statusCode).to.equal 201 describe 'when the database record is checked', -> beforeEach (done) -> query = { owner: 'the-owner', repo: 'the-service', tag: 'v1.0.0' } @db.deployments.findOne query, (error, @record) => done error it 'should have the dockerUrl', -> expect(@record.build.dockerUrl).to.equal 'the-owner/the-service:v1.0.0' it 'should be passing', -> expect(@record.build.passing).to.be.true it 'should have a docker set to passed', -> expect(@record.build["docker"].passing).to.be.true it 'should have a valid created at date for docker', -> expect(moment(@record.build["docker"].createdAt).isBefore(moment())).to.be.true expect(moment(@record.build["docker"].createdAt).isAfter(moment().subtract(1, 'minute'))).to.be.true
92508
request = require 'request' moment = require 'moment' Database = require '../database' Server = require '../../src/server' describe 'Update From Docker Hub', -> beforeEach (done) -> @db = new Database @db.drop done beforeEach (done) -> @logFn = sinon.spy() serverOptions = port: undefined, disableLogging: true logFn: @logFn username: 'username' password: '<PASSWORD>' serverOptions.database = @db.database @server = new Server serverOptions @server.run => @serverPort = @server.address().port done() afterEach -> @server.destroy() describe 'on POST /deployments/docker-hub', -> describe 'when the deployment does NOT exist', -> beforeEach (done) -> options = uri: '/deployments/docker-hub' baseUrl: "http://localhost:#{@serverPort}" auth: username: 'username' password: '<PASSWORD>' json: push_data: tag: "v1.0.0" repository: name: 'the-service' namespace: 'the-owner' repo_name: 'the-owner/the-service' request.post options, (error, @response, @body) => done error it 'should return a 201', -> expect(@response.statusCode).to.equal 201 describe 'when the deployment exists', -> describe 'when the build does NOT exist', -> beforeEach (done) -> deployment = tag: 'v1.0.0' repo: 'the-service' owner: 'the-owner' createdAt: moment('2001-01-01').toDate() build: { passing: false "travis-ci": { passing: true } } cluster: {} @db.deployments.insert deployment, done beforeEach (done) -> options = uri: '/deployments/docker-hub' baseUrl: "http://localhost:#{@serverPort}" auth: username: 'username' password: '<PASSWORD>' json: push_data: tag: "v1.0.0" repository: name: 'the-service' namespace: 'the-owner' repo_name: 'the-owner/the-service' request.post options, (error, @response, @body) => done error it 'should return a 201', -> expect(@response.statusCode).to.equal 201 describe 'when the database record is checked', -> beforeEach (done) -> query = { owner: 'the-owner', repo: 'the-service', tag: 'v1.0.0' } @db.deployments.findOne query, (error, @record) => done error it 'should have the dockerUrl', -> expect(@record.build.dockerUrl).to.equal 'the-owner/the-service:v1.0.0' it 'should be passing', -> expect(@record.build.passing).to.be.true it 'should have a docker set to passed', -> expect(@record.build["docker"].passing).to.be.true it 'should have a valid created at date for docker', -> expect(moment(@record.build["docker"].createdAt).isBefore(moment())).to.be.true expect(moment(@record.build["docker"].createdAt).isAfter(moment().subtract(1, 'minute'))).to.be.true describe 'when the build exists', -> beforeEach (done) -> deployment = tag: 'v1.0.0' repo: 'the-service' owner: 'the-owner' createdAt: moment('2001-01-01').toDate() build: { passing: false, "docker": { passing: false } "travis-ci": { passing: true } } cluster: {} @db.deployments.insert deployment, done beforeEach (done) -> options = uri: '/deployments/docker-hub' baseUrl: "http://localhost:#{@serverPort}" auth: username: 'username' password: '<PASSWORD>' json: push_data: tag: "v1.0.0" repository: name: 'the-service' namespace: 'the-owner' repo_name: 'the-owner/the-service' request.post options, (error, @response, @body) => done error it 'should return a 201', -> expect(@response.statusCode).to.equal 201 describe 'when the database record is checked', -> beforeEach (done) -> query = { owner: 'the-owner', repo: 'the-service', tag: 'v1.0.0' } @db.deployments.findOne query, (error, @record) => done error it 'should have the dockerUrl', -> expect(@record.build.dockerUrl).to.equal 'the-owner/the-service:v1.0.0' it 'should be passing', -> expect(@record.build.passing).to.be.true it 'should have a docker set to passed', -> expect(@record.build["docker"].passing).to.be.true it 'should have a valid created at date for docker', -> expect(moment(@record.build["docker"].createdAt).isBefore(moment())).to.be.true expect(moment(@record.build["docker"].createdAt).isAfter(moment().subtract(1, 'minute'))).to.be.true
true
request = require 'request' moment = require 'moment' Database = require '../database' Server = require '../../src/server' describe 'Update From Docker Hub', -> beforeEach (done) -> @db = new Database @db.drop done beforeEach (done) -> @logFn = sinon.spy() serverOptions = port: undefined, disableLogging: true logFn: @logFn username: 'username' password: 'PI:PASSWORD:<PASSWORD>END_PI' serverOptions.database = @db.database @server = new Server serverOptions @server.run => @serverPort = @server.address().port done() afterEach -> @server.destroy() describe 'on POST /deployments/docker-hub', -> describe 'when the deployment does NOT exist', -> beforeEach (done) -> options = uri: '/deployments/docker-hub' baseUrl: "http://localhost:#{@serverPort}" auth: username: 'username' password: 'PI:PASSWORD:<PASSWORD>END_PI' json: push_data: tag: "v1.0.0" repository: name: 'the-service' namespace: 'the-owner' repo_name: 'the-owner/the-service' request.post options, (error, @response, @body) => done error it 'should return a 201', -> expect(@response.statusCode).to.equal 201 describe 'when the deployment exists', -> describe 'when the build does NOT exist', -> beforeEach (done) -> deployment = tag: 'v1.0.0' repo: 'the-service' owner: 'the-owner' createdAt: moment('2001-01-01').toDate() build: { passing: false "travis-ci": { passing: true } } cluster: {} @db.deployments.insert deployment, done beforeEach (done) -> options = uri: '/deployments/docker-hub' baseUrl: "http://localhost:#{@serverPort}" auth: username: 'username' password: 'PI:PASSWORD:<PASSWORD>END_PI' json: push_data: tag: "v1.0.0" repository: name: 'the-service' namespace: 'the-owner' repo_name: 'the-owner/the-service' request.post options, (error, @response, @body) => done error it 'should return a 201', -> expect(@response.statusCode).to.equal 201 describe 'when the database record is checked', -> beforeEach (done) -> query = { owner: 'the-owner', repo: 'the-service', tag: 'v1.0.0' } @db.deployments.findOne query, (error, @record) => done error it 'should have the dockerUrl', -> expect(@record.build.dockerUrl).to.equal 'the-owner/the-service:v1.0.0' it 'should be passing', -> expect(@record.build.passing).to.be.true it 'should have a docker set to passed', -> expect(@record.build["docker"].passing).to.be.true it 'should have a valid created at date for docker', -> expect(moment(@record.build["docker"].createdAt).isBefore(moment())).to.be.true expect(moment(@record.build["docker"].createdAt).isAfter(moment().subtract(1, 'minute'))).to.be.true describe 'when the build exists', -> beforeEach (done) -> deployment = tag: 'v1.0.0' repo: 'the-service' owner: 'the-owner' createdAt: moment('2001-01-01').toDate() build: { passing: false, "docker": { passing: false } "travis-ci": { passing: true } } cluster: {} @db.deployments.insert deployment, done beforeEach (done) -> options = uri: '/deployments/docker-hub' baseUrl: "http://localhost:#{@serverPort}" auth: username: 'username' password: 'PI:PASSWORD:<PASSWORD>END_PI' json: push_data: tag: "v1.0.0" repository: name: 'the-service' namespace: 'the-owner' repo_name: 'the-owner/the-service' request.post options, (error, @response, @body) => done error it 'should return a 201', -> expect(@response.statusCode).to.equal 201 describe 'when the database record is checked', -> beforeEach (done) -> query = { owner: 'the-owner', repo: 'the-service', tag: 'v1.0.0' } @db.deployments.findOne query, (error, @record) => done error it 'should have the dockerUrl', -> expect(@record.build.dockerUrl).to.equal 'the-owner/the-service:v1.0.0' it 'should be passing', -> expect(@record.build.passing).to.be.true it 'should have a docker set to passed', -> expect(@record.build["docker"].passing).to.be.true it 'should have a valid created at date for docker', -> expect(moment(@record.build["docker"].createdAt).isBefore(moment())).to.be.true expect(moment(@record.build["docker"].createdAt).isAfter(moment().subtract(1, 'minute'))).to.be.true
[ { "context": " # # \"Crow\"\n # # \"Flamingo\"\n # \"Gouldian Finch\"\n \"House Finch\"\n \"Kingfisher\"\n ", "end": 226, "score": 0.7830753326416016, "start": 213, "tag": "NAME", "value": "ouldian Finch" }, { "context": "\"Kookaburra\"\n \"M...
lib/birds-settings.coffee
katie7r/atom-birds-syntax
4
settings = config: scheme: type: 'string' default: 'Pigeon' enum: [ # # "Bluejay" # # "Cardinal" # "Chickadee" # # "Crow" # # "Flamingo" # "Gouldian Finch" "House Finch" "Kingfisher" "Kookaburra" "Magpie" # "Orchard Oriole" # "Peafowl" "Pigeon" # # "Rooster" "Toucan" ] style: type: 'string' default: 'Dark' enum: ["Dark", "Light"] matchUserInterfaceTheme: type: 'boolean' default: true description: "When enabled the style will be matched to the current UI theme by default." module.exports = settings
82201
settings = config: scheme: type: 'string' default: 'Pigeon' enum: [ # # "Bluejay" # # "Cardinal" # "Chickadee" # # "Crow" # # "Flamingo" # "G<NAME>" "House Finch" "Kingfisher" "Kookaburra" "Magpie" # "Orchard O<NAME>" # "Peafowl" "Pigeon" # # "R<NAME>er" "Toucan" ] style: type: 'string' default: 'Dark' enum: ["Dark", "Light"] matchUserInterfaceTheme: type: 'boolean' default: true description: "When enabled the style will be matched to the current UI theme by default." module.exports = settings
true
settings = config: scheme: type: 'string' default: 'Pigeon' enum: [ # # "Bluejay" # # "Cardinal" # "Chickadee" # # "Crow" # # "Flamingo" # "GPI:NAME:<NAME>END_PI" "House Finch" "Kingfisher" "Kookaburra" "Magpie" # "Orchard OPI:NAME:<NAME>END_PI" # "Peafowl" "Pigeon" # # "RPI:NAME:<NAME>END_PIer" "Toucan" ] style: type: 'string' default: 'Dark' enum: ["Dark", "Light"] matchUserInterfaceTheme: type: 'boolean' default: true description: "When enabled the style will be matched to the current UI theme by default." module.exports = settings
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9981265664100647, "start": 12, "tag": "NAME", "value": "Joyent" }, { "context": "ire(\"child_process\").fork\nLOCAL_BROADCAST_HOST = \"224.0.0.114\"\nTIMEOUT = 5000\nmessages ...
test/internet/test-dgram-multicast-multi-process.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") dgram = require("dgram") util = require("util") assert = require("assert") Buffer = require("buffer").Buffer fork = require("child_process").fork LOCAL_BROADCAST_HOST = "224.0.0.114" TIMEOUT = 5000 messages = [ new Buffer("First message to send") new Buffer("Second message to send") new Buffer("Third message to send") new Buffer("Fourth message to send") ] if process.argv[2] isnt "child" #exit the test if it doesn't succeed within TIMEOUT #launch child processes #handle the death of workers # don't consider this the true death if the # worker has finished successfully # or if the exit code is 0 #all child process are listening, so start sending # FIXME a libuv limitation makes it necessary to bind() # before calling any of the set*() functions - the bind() # call is what creates the actual socket... # The socket is actually created async now killChildren = (children) -> Object.keys(children).forEach (key) -> child = children[key] child.kill() return return workers = {} listeners = 3 listening = 0 dead = 0 i = 0 done = 0 timer = null timer = setTimeout(-> console.error "[PARENT] Responses were not received within %d ms.", TIMEOUT console.error "[PARENT] Fail" killChildren workers process.exit 1 return , TIMEOUT) x = 0 while x < listeners (-> worker = fork(process.argv[1], ["child"]) workers[worker.pid] = worker worker.messagesReceived = [] worker.on "exit", (code, signal) -> return if worker.isDone or code is 0 dead += 1 console.error "[PARENT] Worker %d died. %d dead of %d", worker.pid, dead, listeners if dead is listeners console.error "[PARENT] All workers have died." console.error "[PARENT] Fail" killChildren workers process.exit 1 return worker.on "message", (msg) -> if msg.listening listening += 1 sendSocket.sendNext() if listening is listeners else if msg.message worker.messagesReceived.push msg.message if worker.messagesReceived.length is messages.length done += 1 worker.isDone = true console.error "[PARENT] %d received %d messages total.", worker.pid, worker.messagesReceived.length if done is listeners console.error "[PARENT] All workers have received the " + "required number of messages. Will now compare." Object.keys(workers).forEach (pid) -> worker = workers[pid] count = 0 worker.messagesReceived.forEach (buf) -> i = 0 while i < messages.length if buf.toString() is messages[i].toString() count++ break ++i return console.error "[PARENT] %d received %d matching messages.", worker.pid, count assert.equal count, messages.length, "A worker received an invalid multicast message" return clearTimeout timer console.error "[PARENT] Success" killChildren workers return return ) x x++ sendSocket = dgram.createSocket("udp4") sendSocket.bind() sendSocket.on "listening", -> sendSocket.setTTL 1 sendSocket.setBroadcast true sendSocket.setMulticastTTL 1 sendSocket.setMulticastLoopback true return sendSocket.on "close", -> console.error "[PARENT] sendSocket closed" return sendSocket.sendNext = -> buf = messages[i++] unless buf try sendSocket.close() return sendSocket.send buf, 0, buf.length, common.PORT, LOCAL_BROADCAST_HOST, (err) -> throw err if err console.error "[PARENT] sent %s to %s:%s", util.inspect(buf.toString()), LOCAL_BROADCAST_HOST, common.PORT process.nextTick sendSocket.sendNext return return if process.argv[2] is "child" receivedMessages = [] listenSocket = dgram.createSocket( type: "udp4" reuseAddr: true ) listenSocket.on "message", (buf, rinfo) -> console.error "[CHILD] %s received %s from %j", process.pid, util.inspect(buf.toString()), rinfo receivedMessages.push buf process.send message: buf.toString() if receivedMessages.length is messages.length listenSocket.dropMembership LOCAL_BROADCAST_HOST process.nextTick -> # TODO should be changed to below. # listenSocket.dropMembership(LOCAL_BROADCAST_HOST, function() { listenSocket.close() return return listenSocket.on "close", -> #HACK: Wait to exit the process to ensure that the parent #process has had time to receive all messages via process.send() #This may be indicitave of some other issue. setTimeout (-> process.exit() return ), 1000 return listenSocket.on "listening", -> process.send listening: true return listenSocket.bind common.PORT listenSocket.on "listening", -> listenSocket.addMembership LOCAL_BROADCAST_HOST return
86792
# 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") dgram = require("dgram") util = require("util") assert = require("assert") Buffer = require("buffer").Buffer fork = require("child_process").fork LOCAL_BROADCAST_HOST = "192.168.3.11" TIMEOUT = 5000 messages = [ new Buffer("First message to send") new Buffer("Second message to send") new Buffer("Third message to send") new Buffer("Fourth message to send") ] if process.argv[2] isnt "child" #exit the test if it doesn't succeed within TIMEOUT #launch child processes #handle the death of workers # don't consider this the true death if the # worker has finished successfully # or if the exit code is 0 #all child process are listening, so start sending # FIXME a libuv limitation makes it necessary to bind() # before calling any of the set*() functions - the bind() # call is what creates the actual socket... # The socket is actually created async now killChildren = (children) -> Object.keys(children).forEach (key) -> child = children[key] child.kill() return return workers = {} listeners = 3 listening = 0 dead = 0 i = 0 done = 0 timer = null timer = setTimeout(-> console.error "[PARENT] Responses were not received within %d ms.", TIMEOUT console.error "[PARENT] Fail" killChildren workers process.exit 1 return , TIMEOUT) x = 0 while x < listeners (-> worker = fork(process.argv[1], ["child"]) workers[worker.pid] = worker worker.messagesReceived = [] worker.on "exit", (code, signal) -> return if worker.isDone or code is 0 dead += 1 console.error "[PARENT] Worker %d died. %d dead of %d", worker.pid, dead, listeners if dead is listeners console.error "[PARENT] All workers have died." console.error "[PARENT] Fail" killChildren workers process.exit 1 return worker.on "message", (msg) -> if msg.listening listening += 1 sendSocket.sendNext() if listening is listeners else if msg.message worker.messagesReceived.push msg.message if worker.messagesReceived.length is messages.length done += 1 worker.isDone = true console.error "[PARENT] %d received %d messages total.", worker.pid, worker.messagesReceived.length if done is listeners console.error "[PARENT] All workers have received the " + "required number of messages. Will now compare." Object.keys(workers).forEach (pid) -> worker = workers[pid] count = 0 worker.messagesReceived.forEach (buf) -> i = 0 while i < messages.length if buf.toString() is messages[i].toString() count++ break ++i return console.error "[PARENT] %d received %d matching messages.", worker.pid, count assert.equal count, messages.length, "A worker received an invalid multicast message" return clearTimeout timer console.error "[PARENT] Success" killChildren workers return return ) x x++ sendSocket = dgram.createSocket("udp4") sendSocket.bind() sendSocket.on "listening", -> sendSocket.setTTL 1 sendSocket.setBroadcast true sendSocket.setMulticastTTL 1 sendSocket.setMulticastLoopback true return sendSocket.on "close", -> console.error "[PARENT] sendSocket closed" return sendSocket.sendNext = -> buf = messages[i++] unless buf try sendSocket.close() return sendSocket.send buf, 0, buf.length, common.PORT, LOCAL_BROADCAST_HOST, (err) -> throw err if err console.error "[PARENT] sent %s to %s:%s", util.inspect(buf.toString()), LOCAL_BROADCAST_HOST, common.PORT process.nextTick sendSocket.sendNext return return if process.argv[2] is "child" receivedMessages = [] listenSocket = dgram.createSocket( type: "udp4" reuseAddr: true ) listenSocket.on "message", (buf, rinfo) -> console.error "[CHILD] %s received %s from %j", process.pid, util.inspect(buf.toString()), rinfo receivedMessages.push buf process.send message: buf.toString() if receivedMessages.length is messages.length listenSocket.dropMembership LOCAL_BROADCAST_HOST process.nextTick -> # TODO should be changed to below. # listenSocket.dropMembership(LOCAL_BROADCAST_HOST, function() { listenSocket.close() return return listenSocket.on "close", -> #HACK: Wait to exit the process to ensure that the parent #process has had time to receive all messages via process.send() #This may be indicitave of some other issue. setTimeout (-> process.exit() return ), 1000 return listenSocket.on "listening", -> process.send listening: true return listenSocket.bind common.PORT listenSocket.on "listening", -> listenSocket.addMembership LOCAL_BROADCAST_HOST 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") dgram = require("dgram") util = require("util") assert = require("assert") Buffer = require("buffer").Buffer fork = require("child_process").fork LOCAL_BROADCAST_HOST = "PI:IP_ADDRESS:192.168.3.11END_PI" TIMEOUT = 5000 messages = [ new Buffer("First message to send") new Buffer("Second message to send") new Buffer("Third message to send") new Buffer("Fourth message to send") ] if process.argv[2] isnt "child" #exit the test if it doesn't succeed within TIMEOUT #launch child processes #handle the death of workers # don't consider this the true death if the # worker has finished successfully # or if the exit code is 0 #all child process are listening, so start sending # FIXME a libuv limitation makes it necessary to bind() # before calling any of the set*() functions - the bind() # call is what creates the actual socket... # The socket is actually created async now killChildren = (children) -> Object.keys(children).forEach (key) -> child = children[key] child.kill() return return workers = {} listeners = 3 listening = 0 dead = 0 i = 0 done = 0 timer = null timer = setTimeout(-> console.error "[PARENT] Responses were not received within %d ms.", TIMEOUT console.error "[PARENT] Fail" killChildren workers process.exit 1 return , TIMEOUT) x = 0 while x < listeners (-> worker = fork(process.argv[1], ["child"]) workers[worker.pid] = worker worker.messagesReceived = [] worker.on "exit", (code, signal) -> return if worker.isDone or code is 0 dead += 1 console.error "[PARENT] Worker %d died. %d dead of %d", worker.pid, dead, listeners if dead is listeners console.error "[PARENT] All workers have died." console.error "[PARENT] Fail" killChildren workers process.exit 1 return worker.on "message", (msg) -> if msg.listening listening += 1 sendSocket.sendNext() if listening is listeners else if msg.message worker.messagesReceived.push msg.message if worker.messagesReceived.length is messages.length done += 1 worker.isDone = true console.error "[PARENT] %d received %d messages total.", worker.pid, worker.messagesReceived.length if done is listeners console.error "[PARENT] All workers have received the " + "required number of messages. Will now compare." Object.keys(workers).forEach (pid) -> worker = workers[pid] count = 0 worker.messagesReceived.forEach (buf) -> i = 0 while i < messages.length if buf.toString() is messages[i].toString() count++ break ++i return console.error "[PARENT] %d received %d matching messages.", worker.pid, count assert.equal count, messages.length, "A worker received an invalid multicast message" return clearTimeout timer console.error "[PARENT] Success" killChildren workers return return ) x x++ sendSocket = dgram.createSocket("udp4") sendSocket.bind() sendSocket.on "listening", -> sendSocket.setTTL 1 sendSocket.setBroadcast true sendSocket.setMulticastTTL 1 sendSocket.setMulticastLoopback true return sendSocket.on "close", -> console.error "[PARENT] sendSocket closed" return sendSocket.sendNext = -> buf = messages[i++] unless buf try sendSocket.close() return sendSocket.send buf, 0, buf.length, common.PORT, LOCAL_BROADCAST_HOST, (err) -> throw err if err console.error "[PARENT] sent %s to %s:%s", util.inspect(buf.toString()), LOCAL_BROADCAST_HOST, common.PORT process.nextTick sendSocket.sendNext return return if process.argv[2] is "child" receivedMessages = [] listenSocket = dgram.createSocket( type: "udp4" reuseAddr: true ) listenSocket.on "message", (buf, rinfo) -> console.error "[CHILD] %s received %s from %j", process.pid, util.inspect(buf.toString()), rinfo receivedMessages.push buf process.send message: buf.toString() if receivedMessages.length is messages.length listenSocket.dropMembership LOCAL_BROADCAST_HOST process.nextTick -> # TODO should be changed to below. # listenSocket.dropMembership(LOCAL_BROADCAST_HOST, function() { listenSocket.close() return return listenSocket.on "close", -> #HACK: Wait to exit the process to ensure that the parent #process has had time to receive all messages via process.send() #This may be indicitave of some other issue. setTimeout (-> process.exit() return ), 1000 return listenSocket.on "listening", -> process.send listening: true return listenSocket.bind common.PORT listenSocket.on "listening", -> listenSocket.addMembership LOCAL_BROADCAST_HOST return
[ { "context": "\n\t##############################\n\t# LISTS\n\t\n\t@LIST_ADD:\n\t\taction: 'Add to list'\n\t\tlabel: 'L'\n\t\tkey: '", "end": 415, "score": 0.6918577551841736, "start": 415, "tag": "USERNAME", "value": "" }, { "context": "ion: 'Add to list'\n\t\tlabel: 'L'\n\t\tkey: '...
src/coffee/Keymap.coffee
donmccurdy/powerline
0
class Keymap ############################## # NAVIGATION @UP: action: 'Select Above' label: '↑' key: ['up', 'shift+up'] @DOWN: action: 'Select Below' label: '↓' key: ['down', 'shift+down'] @LEFT: action: 'Select Left' label: '←' key: ['left', 'shift+left'] @RIGHT: action: 'Select Right' label: '→' key: ['right', 'shift+right'] ############################## # LISTS @LIST_ADD: action: 'Add to list' label: 'L' key: 'l' @LIST_MOVE: action: 'Move to list' label: 'Shift + L' key: 'shift+l' @LIST_REMOVE: action: 'Remove from list' label: 'E' key: 'e' @LIST_OPEN: action: 'Goto list' label: 'G' key: 'g' ############################## # UTILITY @SEARCH: action: 'Search' label: '/' key: '/' @SELECT_ALL: action: 'Select All' label: 'Control/Command + A' key: ['ctrl+a', 'meta+a'] @SHOW_ACTIONS: action: 'More Actions' label: '.' key: '.' @SHOW_DETAILS: action: 'Show Details' label: 'Spacebar' key: 'space' @UNDO: action: 'Undo' label: 'Control/Command + Z' key: ['ctrl+z', 'meta+z'] @REDO: action: 'Redo' label: 'Control/Command + Shift + Z' key: ['ctrl+shift+z', 'cmd+shift+z']
205057
class Keymap ############################## # NAVIGATION @UP: action: 'Select Above' label: '↑' key: ['up', 'shift+up'] @DOWN: action: 'Select Below' label: '↓' key: ['down', 'shift+down'] @LEFT: action: 'Select Left' label: '←' key: ['left', 'shift+left'] @RIGHT: action: 'Select Right' label: '→' key: ['right', 'shift+right'] ############################## # LISTS @LIST_ADD: action: 'Add to list' label: 'L' key: 'l' @LIST_MOVE: action: 'Move to list' label: 'Shift + L' key: 'shift+l' @LIST_REMOVE: action: 'Remove from list' label: 'E' key: 'e' @LIST_OPEN: action: 'Goto list' label: 'G' key: 'g' ############################## # UTILITY @SEARCH: action: 'Search' label: '/' key: '/' @SELECT_ALL: action: 'Select All' label: 'Control/Command + A' key: ['ctrl+a', 'meta+a'] @SHOW_ACTIONS: action: 'More Actions' label: '.' key: '.' @SHOW_DETAILS: action: 'Show Details' label: 'Spacebar' key: 'space' @UNDO: action: 'Undo' label: 'Control/Command + Z' key: ['ctrl<KEY>+z', 'meta<KEY>+z'] @REDO: action: 'Redo' label: 'Control/Command + Shift + Z' key: ['ctrl+shift+z', 'cmd+<KEY>+z']
true
class Keymap ############################## # NAVIGATION @UP: action: 'Select Above' label: '↑' key: ['up', 'shift+up'] @DOWN: action: 'Select Below' label: '↓' key: ['down', 'shift+down'] @LEFT: action: 'Select Left' label: '←' key: ['left', 'shift+left'] @RIGHT: action: 'Select Right' label: '→' key: ['right', 'shift+right'] ############################## # LISTS @LIST_ADD: action: 'Add to list' label: 'L' key: 'l' @LIST_MOVE: action: 'Move to list' label: 'Shift + L' key: 'shift+l' @LIST_REMOVE: action: 'Remove from list' label: 'E' key: 'e' @LIST_OPEN: action: 'Goto list' label: 'G' key: 'g' ############################## # UTILITY @SEARCH: action: 'Search' label: '/' key: '/' @SELECT_ALL: action: 'Select All' label: 'Control/Command + A' key: ['ctrl+a', 'meta+a'] @SHOW_ACTIONS: action: 'More Actions' label: '.' key: '.' @SHOW_DETAILS: action: 'Show Details' label: 'Spacebar' key: 'space' @UNDO: action: 'Undo' label: 'Control/Command + Z' key: ['ctrlPI:KEY:<KEY>END_PI+z', 'metaPI:KEY:<KEY>END_PI+z'] @REDO: action: 'Redo' label: 'Control/Command + Shift + Z' key: ['ctrl+shift+z', 'cmd+PI:KEY:<KEY>END_PI+z']
[ { "context": "/\n countries : [\"ie\", \"kr\", \"kp\", \"nz\", \"tw\", \"my\", \"ph\",\n \"sg\", \"th\", \"uk\", \"us\"]\n sep : \",\"", "end": 1136, "score": 0.8611155152320862, "start": 1134, "tag": "NAME", "value": "my" } ]
formats.coffee
GuillaumeLeclerc/numberParsing
12
module.exports = [ { reg : /-?([0-9]+(?:\.[0-9]+)?)/ countries : ["au", "ca", "cn", "in", "ie", "is", "jp", "kr", "kb", "lu", "my", "mx", "np", "pk", "nz", "sg", "ph", "sg", "tz", "ch", "tw", "uk", "us"] sep : "" decimalSep : "." } { reg : /-?([0-9]+(?:,[0-9]+)?)/ countries : ["al", "ao", "am", "az", "by", "be", "bo", "br", "cm", "co", "cr", "hr", "fr", "de", "gr", "id", "it", "nl", "ro", "ru", "se", "es", "tn"] sep : "" decimalSep : "," } { reg : /-?([0-9]{1,3}(?: [0-9]{3})*(?:,[0-9]+)?)/ countries : ["fr", "ru", "it", "es", "cz", "de", "bg", "al", "at", "pl", "ro", "ca", "pt", "gr", "nl"] sep : " " decimalSep : "," } { reg : /-?([0-9]{1,3}(?: [0-9]{3})*(?:\.[0-9]+)?)/ countries : ["ca", "cn"] sep : " " decimalSep : '.' } { reg : /-?([0-9]{1,3}(?:,[0-9]{3})*(?:\.[0-9]+)?)/ countries : ["au", "cn", "hk", "ie", "il", "jp", "kr", "kp", "uk", "us", "tw", "sg", "th"] sep : "," decimalSep : '.' } { reg : /-?([0-9]{1,3}(?:,[0-9]{3})*(?:·[0-9]+)?)/ countries : ["ie", "kr", "kp", "nz", "tw", "my", "ph", "sg", "th", "uk", "us"] sep : "," decimalSep : "·" } { reg : /-?([0-9]{1,3}(?:\.[0-9]{3})*(?:,[0-9]+)?)/ countries : ["tr", "at", "br", "dn", "de", "gr", "id", "it", "nl", "pt", "ro", "ru", "si", "es"] sep : "." decimalSep : "," } { reg : /-?([0-9]{1,3}(?:˙[0-9]{3})*(?:,[0-9]+)?)/ countries : ["it"] sep : "˙" decimalSep : "," } { reg : /-?([0-9]{1,3}(?:'[0-9]{3})*(?:,[0-9]+)?)/ countries : ["ch"] sep : "'" decimalSep : "," } { reg : /-?([0-9]{1,3}(?:'[0-9]{3})*(?:\.[0-9]+)?)/ countries : ["ch"] sep : "'" decimalSep : "." } { reg : /-?([0-9]{1,3}(?:\.[0-9]{3})*(?:'[0-9]+)?)/ countries : ["es"] sep : "." decimalSep : "'" } ]
159932
module.exports = [ { reg : /-?([0-9]+(?:\.[0-9]+)?)/ countries : ["au", "ca", "cn", "in", "ie", "is", "jp", "kr", "kb", "lu", "my", "mx", "np", "pk", "nz", "sg", "ph", "sg", "tz", "ch", "tw", "uk", "us"] sep : "" decimalSep : "." } { reg : /-?([0-9]+(?:,[0-9]+)?)/ countries : ["al", "ao", "am", "az", "by", "be", "bo", "br", "cm", "co", "cr", "hr", "fr", "de", "gr", "id", "it", "nl", "ro", "ru", "se", "es", "tn"] sep : "" decimalSep : "," } { reg : /-?([0-9]{1,3}(?: [0-9]{3})*(?:,[0-9]+)?)/ countries : ["fr", "ru", "it", "es", "cz", "de", "bg", "al", "at", "pl", "ro", "ca", "pt", "gr", "nl"] sep : " " decimalSep : "," } { reg : /-?([0-9]{1,3}(?: [0-9]{3})*(?:\.[0-9]+)?)/ countries : ["ca", "cn"] sep : " " decimalSep : '.' } { reg : /-?([0-9]{1,3}(?:,[0-9]{3})*(?:\.[0-9]+)?)/ countries : ["au", "cn", "hk", "ie", "il", "jp", "kr", "kp", "uk", "us", "tw", "sg", "th"] sep : "," decimalSep : '.' } { reg : /-?([0-9]{1,3}(?:,[0-9]{3})*(?:·[0-9]+)?)/ countries : ["ie", "kr", "kp", "nz", "tw", "<NAME>", "ph", "sg", "th", "uk", "us"] sep : "," decimalSep : "·" } { reg : /-?([0-9]{1,3}(?:\.[0-9]{3})*(?:,[0-9]+)?)/ countries : ["tr", "at", "br", "dn", "de", "gr", "id", "it", "nl", "pt", "ro", "ru", "si", "es"] sep : "." decimalSep : "," } { reg : /-?([0-9]{1,3}(?:˙[0-9]{3})*(?:,[0-9]+)?)/ countries : ["it"] sep : "˙" decimalSep : "," } { reg : /-?([0-9]{1,3}(?:'[0-9]{3})*(?:,[0-9]+)?)/ countries : ["ch"] sep : "'" decimalSep : "," } { reg : /-?([0-9]{1,3}(?:'[0-9]{3})*(?:\.[0-9]+)?)/ countries : ["ch"] sep : "'" decimalSep : "." } { reg : /-?([0-9]{1,3}(?:\.[0-9]{3})*(?:'[0-9]+)?)/ countries : ["es"] sep : "." decimalSep : "'" } ]
true
module.exports = [ { reg : /-?([0-9]+(?:\.[0-9]+)?)/ countries : ["au", "ca", "cn", "in", "ie", "is", "jp", "kr", "kb", "lu", "my", "mx", "np", "pk", "nz", "sg", "ph", "sg", "tz", "ch", "tw", "uk", "us"] sep : "" decimalSep : "." } { reg : /-?([0-9]+(?:,[0-9]+)?)/ countries : ["al", "ao", "am", "az", "by", "be", "bo", "br", "cm", "co", "cr", "hr", "fr", "de", "gr", "id", "it", "nl", "ro", "ru", "se", "es", "tn"] sep : "" decimalSep : "," } { reg : /-?([0-9]{1,3}(?: [0-9]{3})*(?:,[0-9]+)?)/ countries : ["fr", "ru", "it", "es", "cz", "de", "bg", "al", "at", "pl", "ro", "ca", "pt", "gr", "nl"] sep : " " decimalSep : "," } { reg : /-?([0-9]{1,3}(?: [0-9]{3})*(?:\.[0-9]+)?)/ countries : ["ca", "cn"] sep : " " decimalSep : '.' } { reg : /-?([0-9]{1,3}(?:,[0-9]{3})*(?:\.[0-9]+)?)/ countries : ["au", "cn", "hk", "ie", "il", "jp", "kr", "kp", "uk", "us", "tw", "sg", "th"] sep : "," decimalSep : '.' } { reg : /-?([0-9]{1,3}(?:,[0-9]{3})*(?:·[0-9]+)?)/ countries : ["ie", "kr", "kp", "nz", "tw", "PI:NAME:<NAME>END_PI", "ph", "sg", "th", "uk", "us"] sep : "," decimalSep : "·" } { reg : /-?([0-9]{1,3}(?:\.[0-9]{3})*(?:,[0-9]+)?)/ countries : ["tr", "at", "br", "dn", "de", "gr", "id", "it", "nl", "pt", "ro", "ru", "si", "es"] sep : "." decimalSep : "," } { reg : /-?([0-9]{1,3}(?:˙[0-9]{3})*(?:,[0-9]+)?)/ countries : ["it"] sep : "˙" decimalSep : "," } { reg : /-?([0-9]{1,3}(?:'[0-9]{3})*(?:,[0-9]+)?)/ countries : ["ch"] sep : "'" decimalSep : "," } { reg : /-?([0-9]{1,3}(?:'[0-9]{3})*(?:\.[0-9]+)?)/ countries : ["ch"] sep : "'" decimalSep : "." } { reg : /-?([0-9]{1,3}(?:\.[0-9]{3})*(?:'[0-9]+)?)/ countries : ["es"] sep : "." decimalSep : "'" } ]
[ { "context": "ntWidget\n\n setting = {}\n setting.key = \"dates-picker\"\n\n scope.setting = setting\n scope.calen", "end": 757, "score": 0.8036906123161316, "start": 745, "tag": "KEY", "value": "dates-picker" } ]
src/components/widgets-settings/dates-picker/dates-picker.directive.coffee
agranado2k/impac-angular
7
# TODO: dates-picker should be a common component. Template compiling should be revised. module = angular.module('impac.components.widgets-settings.dates-picker',[]) module.directive('settingDatesPicker', ($templateCache, $filter, ImpacWidgetsSvc, $timeout, $compile) -> return { restrict: 'A', scope: { parentWidget: '=?' deferred: '=' fromDate: '=from' toDate: '=to' keepToday: '=' onUse: '&?' onChangeCb: '&?onChange' minDate: '=?' updateOnPick: '=?' template: '=?' period: '=?' }, template: $templateCache.get('widgets-settings/dates-picker.tmpl.html'), link: (scope, element) -> w = scope.parentWidget setting = {} setting.key = "dates-picker" scope.setting = setting scope.calendarFrom = opened: false value: new Date(new Date().getFullYear(), 0, 1) toggle: -> scope.calendarFrom.opened = !scope.calendarFrom.opened scope.calendarTo.opened = false scope.calendarTo = opened: false value: new Date() toggle: -> scope.calendarFrom.opened = false scope.calendarTo.opened = !scope.calendarTo.opened scope.template ||= """ <div style="display: flex; flex-wrap: wrap;"> <div style="display: flex; flex-grow: 1; justify-content: space-around; margin: 2px 0px;"> <span class="sdp-from-label" style="padding-top: 3px; min-width: 32px; flex-grow: 1; text-align: center;" translate>impac.widget.settings.dates_picker.from</span> <from-date style="flex-grow: 2;"> </div> <div style="display: flex; flex-grow: 1; justify-content: space-around; margin: 2px 0px;"> <span class="sdp-to-label" style="padding-top: 3px; min-width: 32px; flex-grow: 1; text-align: center;" translate>impac.widget.settings.dates_picker.to</span> <to-date style="flex-grow: 2;"> </div> </div> """ fromDateHtml = """ <div style="display: inline-block;"> <button class="btn btn-sm btn-default date-button" ng-click="calendarFrom.toggle()" uib-datepicker-popup ng-model="calendarFrom.value" is-open="calendarFrom.opened" ng-change="onChange()" min-date="minDate" max-date="calendarFrom.value" ng-focus="onUse()" ATTRS> {{ calendarFrom.value | momentDate : setting.key }} </button> </div> """ toDateHtml = """ <div style="display: inline-block;"> <button class="btn btn-sm btn-default date-button" ng-click="calendarTo.toggle()" uib-datepicker-popup ng-model="calendarTo.value" is-open="calendarTo.opened" ng-change="onChange()" min-date="calendarTo.value" ng-focus="onUse()" ATTRS> {{ calendarTo.value | momentDate : setting.key }} </button> </div> """ applyHtml = """<button class="btn btn-sm btn-success" uib-tooltip="{{'impac.widget.settings.dates_picker.tooltip.apply_changes' | translate}}" ng-show="changed && !parentWidget.isEditMode" ng-click="applyChanges()" ng-focus="onUse()" > <i class="fa fa-check"/> </button> """ # First element triggers onUser() when clicked scope.template = scope.template.replace(/>/, " ng-click='onUse()'>") # Custom attributes (style...) for from and to dates scope.template = scope.template.replace(/<from-date([^>]*)>/g, "#{fromDateHtml.replace('ATTRS', '$1')}") scope.template = scope.template.replace(/<to-date([^>]*)>/g, "#{toDateHtml.replace('ATTRS', '$1')}") scope.template = scope.template.replace(/<apply([^>]*)>/g, "#{applyHtml.replace('ATTRS', '$1')}") templatesContainer = element.find('#template-container') templatesContainer.html(scope.template).show() $compile(templatesContainer.contents())(scope) setting.initialize = -> # timeout to make sure that the fromDate and toDate are propagated to the directive if updated in widget.initContext() $timeout -> scope.changed = false # TODO: widget directives parse dates into strings (with $filter('date')), pass it into this directive, then it gets parsed into a date for display. Maybe it could accept a date directly? Maybe we could use moment.js in this component for neater parsing to avoid syntax like below? if Date.parse(scope.fromDate) parsedFrom = scope.fromDate.split('-') y = parsedFrom[0] m = parsedFrom[1] - 1 d = parsedFrom[2] scope.calendarFrom.value = new Date(y,m,d) else scope.calendarFrom.value = new Date(new Date().getFullYear(), 0, 1) if Date.parse(scope.toDate) && !scope.keepToday parsedTo = scope.toDate.split('-') y = parsedTo[0] m = parsedTo[1] - 1 d = parsedTo[2] scope.calendarTo.value = new Date(y,m,d) else scope.calendarTo.value = new Date() isToToday = -> (scope.calendarTo.value.getFullYear() == new Date().getFullYear()) && (scope.calendarTo.value.getMonth() == new Date().getMonth()) && (scope.calendarTo.value.getDate() == new Date().getDate()) setting.toMetadata = -> return { hist_parameters: from: $filter('date')(scope.calendarFrom.value, 'yyyy-MM-dd') to: $filter('date')(scope.calendarTo.value, 'yyyy-MM-dd') period: scope.period || "RANGE" keep_today: isToToday() } scope.onChange = -> scope.showApplyButton() scope.onChangeCb()(buildDates()) unless _.isUndefined(scope.onChangeCb) buildDates = -> { from: $filter('date')(scope.calendarFrom.value, 'yyyy-MM-dd') to: $filter('date')(scope.calendarTo.value, 'yyyy-MM-dd') keepToday: isToToday() } scope.showApplyButton = -> if scope.updateOnPick scope.applyChanges() else scope.changed = true scope.applyChanges = -> ImpacWidgetsSvc.updateWidgetSettings(w, true) scope.changed = false scope.showTitle = -> element.hasClass('part') w.settings.push(setting) if w # Setting is ready: trigger load content # ------------------------------------ scope.deferred.resolve(setting) } )
210378
# TODO: dates-picker should be a common component. Template compiling should be revised. module = angular.module('impac.components.widgets-settings.dates-picker',[]) module.directive('settingDatesPicker', ($templateCache, $filter, ImpacWidgetsSvc, $timeout, $compile) -> return { restrict: 'A', scope: { parentWidget: '=?' deferred: '=' fromDate: '=from' toDate: '=to' keepToday: '=' onUse: '&?' onChangeCb: '&?onChange' minDate: '=?' updateOnPick: '=?' template: '=?' period: '=?' }, template: $templateCache.get('widgets-settings/dates-picker.tmpl.html'), link: (scope, element) -> w = scope.parentWidget setting = {} setting.key = "<KEY>" scope.setting = setting scope.calendarFrom = opened: false value: new Date(new Date().getFullYear(), 0, 1) toggle: -> scope.calendarFrom.opened = !scope.calendarFrom.opened scope.calendarTo.opened = false scope.calendarTo = opened: false value: new Date() toggle: -> scope.calendarFrom.opened = false scope.calendarTo.opened = !scope.calendarTo.opened scope.template ||= """ <div style="display: flex; flex-wrap: wrap;"> <div style="display: flex; flex-grow: 1; justify-content: space-around; margin: 2px 0px;"> <span class="sdp-from-label" style="padding-top: 3px; min-width: 32px; flex-grow: 1; text-align: center;" translate>impac.widget.settings.dates_picker.from</span> <from-date style="flex-grow: 2;"> </div> <div style="display: flex; flex-grow: 1; justify-content: space-around; margin: 2px 0px;"> <span class="sdp-to-label" style="padding-top: 3px; min-width: 32px; flex-grow: 1; text-align: center;" translate>impac.widget.settings.dates_picker.to</span> <to-date style="flex-grow: 2;"> </div> </div> """ fromDateHtml = """ <div style="display: inline-block;"> <button class="btn btn-sm btn-default date-button" ng-click="calendarFrom.toggle()" uib-datepicker-popup ng-model="calendarFrom.value" is-open="calendarFrom.opened" ng-change="onChange()" min-date="minDate" max-date="calendarFrom.value" ng-focus="onUse()" ATTRS> {{ calendarFrom.value | momentDate : setting.key }} </button> </div> """ toDateHtml = """ <div style="display: inline-block;"> <button class="btn btn-sm btn-default date-button" ng-click="calendarTo.toggle()" uib-datepicker-popup ng-model="calendarTo.value" is-open="calendarTo.opened" ng-change="onChange()" min-date="calendarTo.value" ng-focus="onUse()" ATTRS> {{ calendarTo.value | momentDate : setting.key }} </button> </div> """ applyHtml = """<button class="btn btn-sm btn-success" uib-tooltip="{{'impac.widget.settings.dates_picker.tooltip.apply_changes' | translate}}" ng-show="changed && !parentWidget.isEditMode" ng-click="applyChanges()" ng-focus="onUse()" > <i class="fa fa-check"/> </button> """ # First element triggers onUser() when clicked scope.template = scope.template.replace(/>/, " ng-click='onUse()'>") # Custom attributes (style...) for from and to dates scope.template = scope.template.replace(/<from-date([^>]*)>/g, "#{fromDateHtml.replace('ATTRS', '$1')}") scope.template = scope.template.replace(/<to-date([^>]*)>/g, "#{toDateHtml.replace('ATTRS', '$1')}") scope.template = scope.template.replace(/<apply([^>]*)>/g, "#{applyHtml.replace('ATTRS', '$1')}") templatesContainer = element.find('#template-container') templatesContainer.html(scope.template).show() $compile(templatesContainer.contents())(scope) setting.initialize = -> # timeout to make sure that the fromDate and toDate are propagated to the directive if updated in widget.initContext() $timeout -> scope.changed = false # TODO: widget directives parse dates into strings (with $filter('date')), pass it into this directive, then it gets parsed into a date for display. Maybe it could accept a date directly? Maybe we could use moment.js in this component for neater parsing to avoid syntax like below? if Date.parse(scope.fromDate) parsedFrom = scope.fromDate.split('-') y = parsedFrom[0] m = parsedFrom[1] - 1 d = parsedFrom[2] scope.calendarFrom.value = new Date(y,m,d) else scope.calendarFrom.value = new Date(new Date().getFullYear(), 0, 1) if Date.parse(scope.toDate) && !scope.keepToday parsedTo = scope.toDate.split('-') y = parsedTo[0] m = parsedTo[1] - 1 d = parsedTo[2] scope.calendarTo.value = new Date(y,m,d) else scope.calendarTo.value = new Date() isToToday = -> (scope.calendarTo.value.getFullYear() == new Date().getFullYear()) && (scope.calendarTo.value.getMonth() == new Date().getMonth()) && (scope.calendarTo.value.getDate() == new Date().getDate()) setting.toMetadata = -> return { hist_parameters: from: $filter('date')(scope.calendarFrom.value, 'yyyy-MM-dd') to: $filter('date')(scope.calendarTo.value, 'yyyy-MM-dd') period: scope.period || "RANGE" keep_today: isToToday() } scope.onChange = -> scope.showApplyButton() scope.onChangeCb()(buildDates()) unless _.isUndefined(scope.onChangeCb) buildDates = -> { from: $filter('date')(scope.calendarFrom.value, 'yyyy-MM-dd') to: $filter('date')(scope.calendarTo.value, 'yyyy-MM-dd') keepToday: isToToday() } scope.showApplyButton = -> if scope.updateOnPick scope.applyChanges() else scope.changed = true scope.applyChanges = -> ImpacWidgetsSvc.updateWidgetSettings(w, true) scope.changed = false scope.showTitle = -> element.hasClass('part') w.settings.push(setting) if w # Setting is ready: trigger load content # ------------------------------------ scope.deferred.resolve(setting) } )
true
# TODO: dates-picker should be a common component. Template compiling should be revised. module = angular.module('impac.components.widgets-settings.dates-picker',[]) module.directive('settingDatesPicker', ($templateCache, $filter, ImpacWidgetsSvc, $timeout, $compile) -> return { restrict: 'A', scope: { parentWidget: '=?' deferred: '=' fromDate: '=from' toDate: '=to' keepToday: '=' onUse: '&?' onChangeCb: '&?onChange' minDate: '=?' updateOnPick: '=?' template: '=?' period: '=?' }, template: $templateCache.get('widgets-settings/dates-picker.tmpl.html'), link: (scope, element) -> w = scope.parentWidget setting = {} setting.key = "PI:KEY:<KEY>END_PI" scope.setting = setting scope.calendarFrom = opened: false value: new Date(new Date().getFullYear(), 0, 1) toggle: -> scope.calendarFrom.opened = !scope.calendarFrom.opened scope.calendarTo.opened = false scope.calendarTo = opened: false value: new Date() toggle: -> scope.calendarFrom.opened = false scope.calendarTo.opened = !scope.calendarTo.opened scope.template ||= """ <div style="display: flex; flex-wrap: wrap;"> <div style="display: flex; flex-grow: 1; justify-content: space-around; margin: 2px 0px;"> <span class="sdp-from-label" style="padding-top: 3px; min-width: 32px; flex-grow: 1; text-align: center;" translate>impac.widget.settings.dates_picker.from</span> <from-date style="flex-grow: 2;"> </div> <div style="display: flex; flex-grow: 1; justify-content: space-around; margin: 2px 0px;"> <span class="sdp-to-label" style="padding-top: 3px; min-width: 32px; flex-grow: 1; text-align: center;" translate>impac.widget.settings.dates_picker.to</span> <to-date style="flex-grow: 2;"> </div> </div> """ fromDateHtml = """ <div style="display: inline-block;"> <button class="btn btn-sm btn-default date-button" ng-click="calendarFrom.toggle()" uib-datepicker-popup ng-model="calendarFrom.value" is-open="calendarFrom.opened" ng-change="onChange()" min-date="minDate" max-date="calendarFrom.value" ng-focus="onUse()" ATTRS> {{ calendarFrom.value | momentDate : setting.key }} </button> </div> """ toDateHtml = """ <div style="display: inline-block;"> <button class="btn btn-sm btn-default date-button" ng-click="calendarTo.toggle()" uib-datepicker-popup ng-model="calendarTo.value" is-open="calendarTo.opened" ng-change="onChange()" min-date="calendarTo.value" ng-focus="onUse()" ATTRS> {{ calendarTo.value | momentDate : setting.key }} </button> </div> """ applyHtml = """<button class="btn btn-sm btn-success" uib-tooltip="{{'impac.widget.settings.dates_picker.tooltip.apply_changes' | translate}}" ng-show="changed && !parentWidget.isEditMode" ng-click="applyChanges()" ng-focus="onUse()" > <i class="fa fa-check"/> </button> """ # First element triggers onUser() when clicked scope.template = scope.template.replace(/>/, " ng-click='onUse()'>") # Custom attributes (style...) for from and to dates scope.template = scope.template.replace(/<from-date([^>]*)>/g, "#{fromDateHtml.replace('ATTRS', '$1')}") scope.template = scope.template.replace(/<to-date([^>]*)>/g, "#{toDateHtml.replace('ATTRS', '$1')}") scope.template = scope.template.replace(/<apply([^>]*)>/g, "#{applyHtml.replace('ATTRS', '$1')}") templatesContainer = element.find('#template-container') templatesContainer.html(scope.template).show() $compile(templatesContainer.contents())(scope) setting.initialize = -> # timeout to make sure that the fromDate and toDate are propagated to the directive if updated in widget.initContext() $timeout -> scope.changed = false # TODO: widget directives parse dates into strings (with $filter('date')), pass it into this directive, then it gets parsed into a date for display. Maybe it could accept a date directly? Maybe we could use moment.js in this component for neater parsing to avoid syntax like below? if Date.parse(scope.fromDate) parsedFrom = scope.fromDate.split('-') y = parsedFrom[0] m = parsedFrom[1] - 1 d = parsedFrom[2] scope.calendarFrom.value = new Date(y,m,d) else scope.calendarFrom.value = new Date(new Date().getFullYear(), 0, 1) if Date.parse(scope.toDate) && !scope.keepToday parsedTo = scope.toDate.split('-') y = parsedTo[0] m = parsedTo[1] - 1 d = parsedTo[2] scope.calendarTo.value = new Date(y,m,d) else scope.calendarTo.value = new Date() isToToday = -> (scope.calendarTo.value.getFullYear() == new Date().getFullYear()) && (scope.calendarTo.value.getMonth() == new Date().getMonth()) && (scope.calendarTo.value.getDate() == new Date().getDate()) setting.toMetadata = -> return { hist_parameters: from: $filter('date')(scope.calendarFrom.value, 'yyyy-MM-dd') to: $filter('date')(scope.calendarTo.value, 'yyyy-MM-dd') period: scope.period || "RANGE" keep_today: isToToday() } scope.onChange = -> scope.showApplyButton() scope.onChangeCb()(buildDates()) unless _.isUndefined(scope.onChangeCb) buildDates = -> { from: $filter('date')(scope.calendarFrom.value, 'yyyy-MM-dd') to: $filter('date')(scope.calendarTo.value, 'yyyy-MM-dd') keepToday: isToToday() } scope.showApplyButton = -> if scope.updateOnPick scope.applyChanges() else scope.changed = true scope.applyChanges = -> ImpacWidgetsSvc.updateWidgetSettings(w, true) scope.changed = false scope.showTitle = -> element.hasClass('part') w.settings.push(setting) if w # Setting is ready: trigger load content # ------------------------------------ scope.deferred.resolve(setting) } )
[ { "context": "le:'comment about a delicate truth'\n reader:'su ning'\n stars: 2 \n content:'it is wonderfulex", "end": 2119, "score": 0.9946322441101074, "start": 2112, "tag": "NAME", "value": "su ning" }, { "context": "ent of new york'\n stars:4\n reader...
coffees/test-link-of-nohm-api.coffee
android1and1/easti
0
assert = require 'assert' nohm = require 'nohm' Nohm = nohm.Nohm NohmModel = nohm.NohmModel # keep global db-like variables. CommentModel = undefined ArticleModel = undefined cdb = undefined adb = undefined class Article extends NohmModel @modelName = 'article' @idGenerator = 'increment' @definitions = title: type:'string' unique:true validations:['notEmpty'] intro: type:'string' validations:['notEmpty'] content: type:'string' visits: type:'integer' defaultValue:0 class Comment extends NohmModel @modelName = 'comment' @idGenerator = 'increment' @definitions = reader: type:'string' index:true validations:[ 'notEmpty' ] title: type:'string' unique:true validations:['notEmpty'] stars: type:'integer' validations:[ 'notEmpty' (newv)-> result = false if typeof parseInt(newv) is 'number' and parseInt(newv)<= 5 result = true return Promise.resolve result ] content: type:'string' describe 'Link Behaviour Of Nohm API:',-> before -> client = (require 'redis').createClient() client.on 'error',(err)-> console.error err.message throw TypeError 'No Redis Server Connection' client.on 'connect',-> Nohm.setClient @ Nohm.setPrefix 'laofu' # register class CommentModel = Nohm.register Comment ArticleModel = Nohm.register Article #cdb == Comment DB,adb == Article DB cdb = await Nohm.factory 'comment' adb = await Nohm.factory 'article' # before new test,clear the db. await Nohm.purgeDb @ it 'create 1 comment and 1 article,should successfully::',-> adb.property title:'a delicate truth' intro:'len zhan' content:'at word II ,in britian da shi guan.' res = await adb.validate undefined,false if res await adb.save() else console.log adb.errors cdb.property title:'comment about a delicate truth' reader:'su ning' stars: 2 content:'it is wonderfulexperien while reading this story.' res = await cdb.validate undefined,false if res await cdb.save() else console.log cdb.errors # till here,means 1 article and 1 comment is created. assert.ok res it 'comment id 1 should has correctly inf::',-> properties = await cdb.load 1 assert properties.title is 'comment about a delicate truth' properties = await adb.load 1 assert properties.title is 'a delicate truth' describe 'adb id1 link 2 comments should success::',-> before -> adb = await Nohm.factory 'article',1 # this instance created at step1(test1). cdb = await Nohm.factory 'comment',1 # this instance created at step1(test1). it 'article id1 current has no links::',-> num = await adb.numLinks 'comment' assert.equal num,0 it 'article id1 link comments id1 and id2 should success::',-> cdb2 = new CommentModel cdb2.property title:'comment of new york' stars:4 reader: 'tony' content:' Great Stroy,i like it.' # cdb2 will be saved after adb save(). adb.link cdb adb.link cdb2 await adb.save() num = await adb.numLinks 'comment' assert.equal num,2
211689
assert = require 'assert' nohm = require 'nohm' Nohm = nohm.Nohm NohmModel = nohm.NohmModel # keep global db-like variables. CommentModel = undefined ArticleModel = undefined cdb = undefined adb = undefined class Article extends NohmModel @modelName = 'article' @idGenerator = 'increment' @definitions = title: type:'string' unique:true validations:['notEmpty'] intro: type:'string' validations:['notEmpty'] content: type:'string' visits: type:'integer' defaultValue:0 class Comment extends NohmModel @modelName = 'comment' @idGenerator = 'increment' @definitions = reader: type:'string' index:true validations:[ 'notEmpty' ] title: type:'string' unique:true validations:['notEmpty'] stars: type:'integer' validations:[ 'notEmpty' (newv)-> result = false if typeof parseInt(newv) is 'number' and parseInt(newv)<= 5 result = true return Promise.resolve result ] content: type:'string' describe 'Link Behaviour Of Nohm API:',-> before -> client = (require 'redis').createClient() client.on 'error',(err)-> console.error err.message throw TypeError 'No Redis Server Connection' client.on 'connect',-> Nohm.setClient @ Nohm.setPrefix 'laofu' # register class CommentModel = Nohm.register Comment ArticleModel = Nohm.register Article #cdb == Comment DB,adb == Article DB cdb = await Nohm.factory 'comment' adb = await Nohm.factory 'article' # before new test,clear the db. await Nohm.purgeDb @ it 'create 1 comment and 1 article,should successfully::',-> adb.property title:'a delicate truth' intro:'len zhan' content:'at word II ,in britian da shi guan.' res = await adb.validate undefined,false if res await adb.save() else console.log adb.errors cdb.property title:'comment about a delicate truth' reader:'<NAME>' stars: 2 content:'it is wonderfulexperien while reading this story.' res = await cdb.validate undefined,false if res await cdb.save() else console.log cdb.errors # till here,means 1 article and 1 comment is created. assert.ok res it 'comment id 1 should has correctly inf::',-> properties = await cdb.load 1 assert properties.title is 'comment about a delicate truth' properties = await adb.load 1 assert properties.title is 'a delicate truth' describe 'adb id1 link 2 comments should success::',-> before -> adb = await Nohm.factory 'article',1 # this instance created at step1(test1). cdb = await Nohm.factory 'comment',1 # this instance created at step1(test1). it 'article id1 current has no links::',-> num = await adb.numLinks 'comment' assert.equal num,0 it 'article id1 link comments id1 and id2 should success::',-> cdb2 = new CommentModel cdb2.property title:'comment of new york' stars:4 reader: '<NAME>' content:' <NAME>,i like it.' # cdb2 will be saved after adb save(). adb.link cdb adb.link cdb2 await adb.save() num = await adb.numLinks 'comment' assert.equal num,2
true
assert = require 'assert' nohm = require 'nohm' Nohm = nohm.Nohm NohmModel = nohm.NohmModel # keep global db-like variables. CommentModel = undefined ArticleModel = undefined cdb = undefined adb = undefined class Article extends NohmModel @modelName = 'article' @idGenerator = 'increment' @definitions = title: type:'string' unique:true validations:['notEmpty'] intro: type:'string' validations:['notEmpty'] content: type:'string' visits: type:'integer' defaultValue:0 class Comment extends NohmModel @modelName = 'comment' @idGenerator = 'increment' @definitions = reader: type:'string' index:true validations:[ 'notEmpty' ] title: type:'string' unique:true validations:['notEmpty'] stars: type:'integer' validations:[ 'notEmpty' (newv)-> result = false if typeof parseInt(newv) is 'number' and parseInt(newv)<= 5 result = true return Promise.resolve result ] content: type:'string' describe 'Link Behaviour Of Nohm API:',-> before -> client = (require 'redis').createClient() client.on 'error',(err)-> console.error err.message throw TypeError 'No Redis Server Connection' client.on 'connect',-> Nohm.setClient @ Nohm.setPrefix 'laofu' # register class CommentModel = Nohm.register Comment ArticleModel = Nohm.register Article #cdb == Comment DB,adb == Article DB cdb = await Nohm.factory 'comment' adb = await Nohm.factory 'article' # before new test,clear the db. await Nohm.purgeDb @ it 'create 1 comment and 1 article,should successfully::',-> adb.property title:'a delicate truth' intro:'len zhan' content:'at word II ,in britian da shi guan.' res = await adb.validate undefined,false if res await adb.save() else console.log adb.errors cdb.property title:'comment about a delicate truth' reader:'PI:NAME:<NAME>END_PI' stars: 2 content:'it is wonderfulexperien while reading this story.' res = await cdb.validate undefined,false if res await cdb.save() else console.log cdb.errors # till here,means 1 article and 1 comment is created. assert.ok res it 'comment id 1 should has correctly inf::',-> properties = await cdb.load 1 assert properties.title is 'comment about a delicate truth' properties = await adb.load 1 assert properties.title is 'a delicate truth' describe 'adb id1 link 2 comments should success::',-> before -> adb = await Nohm.factory 'article',1 # this instance created at step1(test1). cdb = await Nohm.factory 'comment',1 # this instance created at step1(test1). it 'article id1 current has no links::',-> num = await adb.numLinks 'comment' assert.equal num,0 it 'article id1 link comments id1 and id2 should success::',-> cdb2 = new CommentModel cdb2.property title:'comment of new york' stars:4 reader: 'PI:NAME:<NAME>END_PI' content:' PI:NAME:<NAME>END_PI,i like it.' # cdb2 will be saved after adb save(). adb.link cdb adb.link cdb2 await adb.save() num = await adb.numLinks 'comment' assert.equal num,2
[ { "context": "e41ed1ef17d7541845d0e5ef506f2a94c651c836e53dde7621fda8897890f0251e1f6dbc0e713b41f13e73c2cf031aea2e888fe54f3bd656d727a83fddb\",\n private_key_hex: \"52173306ca0f862e8", "end": 1744, "score": 0.984695553779602, "start": 1671, "tag": "KEY", "value": "fda8897890f0251e1f6...
programs/web_wallet/test/crypto/test/fixtures/mailmessage.coffee
larkx/LarkX
0
class Fixtures before: signed_messages: [ # "hex" was obtained from bitcoin_client mail API hex: "077375626a656374c50231323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839300a31323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839300a31323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839300a31323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839300a31323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839300a31323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839300a656e64206f66207472616e736d697373696f6e0000000000000000000000000000000000000000001fef84ce41ed1ef17d7541845d0e5ef506f2a94c651c836e53dde7621fda8897890f0251e1f6dbc0e713b41f13e73c2cf031aea2e888fe54f3bd656d727a83fddb" subject: "subject" body: """ 12345678901234567890123456789012345678901234567890 12345678901234567890123456789012345678901234567890 12345678901234567890123456789012345678901234567890 12345678901234567890123456789012345678901234567890 12345678901234567890123456789012345678901234567890 12345678901234567890123456789012345678901234567890 end of transmission """ reply_to_hex: "0000000000000000000000000000000000000000" attachments: [] signature_hex: "1fef84ce41ed1ef17d7541845d0e5ef506f2a94c651c836e53dde7621fda8897890f0251e1f6dbc0e713b41f13e73c2cf031aea2e888fe54f3bd656d727a83fddb", private_key_hex: "52173306ca0f862e8fbf8e7479e749b9859fa78588e0e5414ec14fc8ae51a58b" ] exports.Fixtures=Fixtures
103258
class Fixtures before: signed_messages: [ # "hex" was obtained from bitcoin_client mail API hex: "077375626a656374c50231323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839300a31323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839300a31323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839300a31323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839300a31323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839300a31323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839300a656e64206f66207472616e736d697373696f6e0000000000000000000000000000000000000000001fef84ce41ed1ef17d7541845d0e5ef506f2a94c651c836e53dde7621fda8897890f0251e1f6dbc0e713b41f13e73c2cf031aea2e888fe54f3bd656d727a83fddb" subject: "subject" body: """ 12345678901234567890123456789012345678901234567890 12345678901234567890123456789012345678901234567890 12345678901234567890123456789012345678901234567890 12345678901234567890123456789012345678901234567890 12345678901234567890123456789012345678901234567890 12345678901234567890123456789012345678901234567890 end of transmission """ reply_to_hex: "0000000000000000000000000000000000000000" attachments: [] signature_hex: "1fef84ce41ed1ef17d7541845d0e5ef506f2a94c651c836e53dde7621<KEY>", private_key_hex: "<KEY>" ] exports.Fixtures=Fixtures
true
class Fixtures before: signed_messages: [ # "hex" was obtained from bitcoin_client mail API hex: "077375626a656374c50231323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839300a31323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839300a31323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839300a31323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839300a31323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839300a31323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839300a656e64206f66207472616e736d697373696f6e0000000000000000000000000000000000000000001fef84ce41ed1ef17d7541845d0e5ef506f2a94c651c836e53dde7621fda8897890f0251e1f6dbc0e713b41f13e73c2cf031aea2e888fe54f3bd656d727a83fddb" subject: "subject" body: """ 12345678901234567890123456789012345678901234567890 12345678901234567890123456789012345678901234567890 12345678901234567890123456789012345678901234567890 12345678901234567890123456789012345678901234567890 12345678901234567890123456789012345678901234567890 12345678901234567890123456789012345678901234567890 end of transmission """ reply_to_hex: "0000000000000000000000000000000000000000" attachments: [] signature_hex: "1fef84ce41ed1ef17d7541845d0e5ef506f2a94c651c836e53dde7621PI:KEY:<KEY>END_PI", private_key_hex: "PI:KEY:<KEY>END_PI" ] exports.Fixtures=Fixtures
[ { "context": "se invite, used for invite links.\"\"\"\n\nusers: {\n \"herb\": {}\n \"basil\": {}\n \"rose\": {}\n \"lily\": {}\n}\n\nt", "end": 80, "score": 0.9975311756134033, "start": 76, "tag": "USERNAME", "value": "herb" }, { "context": "ed for invite links.\"\"\"\n\nusers: {...
teamchains/inputs/multiple_use_invite.iced
keybase/keybase-test-vectors
4
description: """Multiple use invite, used for invite links.""" users: { "herb": {} "basil": {} "rose": {} "lily": {} } teams: { "cabal": { links: [{ type: "root" members: owner: ["herb"] }, { type: "invite" signer: "herb" invites: writer: [{ id: "54eafff3400b5bcd8b40bff3d225ab27", name: "YmFzZTY0IGV4YW1wbGUgc3RyCg==", type: "invitelink" max_uses: 10 }] }, { type: "change_membership" signer: "herb" members: writer: ["basil"] used_invites: [ { id: "54eafff3400b5bcd8b40bff3d225ab27" uv: "basil" } ] }, { type: "change_membership" signer: "herb" members: writer: ["rose", "lily"] used_invites: [ { id: "54eafff3400b5bcd8b40bff3d225ab27" uv: "rose" }, { id: "54eafff3400b5bcd8b40bff3d225ab27" uv: "lily" } ] }] } } sessions: [ loads: [ error: false ] ]
121992
description: """Multiple use invite, used for invite links.""" users: { "herb": {} "basil": {} "<NAME>": {} "<NAME>": {} } teams: { "cabal": { links: [{ type: "root" members: owner: ["herb"] }, { type: "invite" signer: "herb" invites: writer: [{ id: "<KEY>", name: "<KEY> type: "invitelink" max_uses: 10 }] }, { type: "change_membership" signer: "her<NAME>" members: writer: ["<NAME> <KEY>"] used_invites: [ { id: "<KEY>" uv: "basil" } ] }, { type: "change_membership" signer: "herb" members: writer: ["<NAME>", "<NAME>"] used_invites: [ { id: "<KEY>" uv: "rose" }, { id: "<KEY>" uv: "lily" } ] }] } } sessions: [ loads: [ error: false ] ]
true
description: """Multiple use invite, used for invite links.""" users: { "herb": {} "basil": {} "PI:NAME:<NAME>END_PI": {} "PI:NAME:<NAME>END_PI": {} } teams: { "cabal": { links: [{ type: "root" members: owner: ["herb"] }, { type: "invite" signer: "herb" invites: writer: [{ id: "PI:KEY:<KEY>END_PI", name: "PI:KEY:<KEY>END_PI type: "invitelink" max_uses: 10 }] }, { type: "change_membership" signer: "herPI:NAME:<NAME>END_PI" members: writer: ["PI:NAME:<NAME>END_PI PI:KEY:<KEY>END_PI"] used_invites: [ { id: "PI:KEY:<KEY>END_PI" uv: "basil" } ] }, { type: "change_membership" signer: "herb" members: writer: ["PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI"] used_invites: [ { id: "PI:KEY:<KEY>END_PI" uv: "rose" }, { id: "PI:KEY:<KEY>END_PI" uv: "lily" } ] }] } } sessions: [ loads: [ error: false ] ]
[ { "context": "###\nCopyright (c) 2014, Groupon\nAll rights reserved.\n\nRedistribution and use in s", "end": 31, "score": 0.9520426392555237, "start": 24, "tag": "NAME", "value": "Groupon" } ]
src/server/models/model.coffee
Mefiso/greenscreen
729
### Copyright (c) 2014, Groupon All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.### db = require "../db" _ = require "underscore" module.exports = class Model @all: (cb) -> db.allWithType @type, (err, docs) => return cb(err) if err channels = docs.map (doc) => new this(doc) cb(null, channels) @findById: (id, cb) -> db.get id, (err, doc) => return cb(err) if err cb(null, new this(doc)) save: (cb=->) -> attrs = {} for own k,v of this if !_(["id", "rev"]).contains(k) && !/^\$/.test k attrs[k] = v if @id db.save @id, @rev, attrs, (err, res) -> return cb(err) if err @rev = res.rev cb() else db.save attrs, (err, res) => return cb(err) if err @id = res.id @rev = res.rev cb() update: (data, cb=->) -> this[k] = v for k,v of data @save(cb) destroy: (cb=->) -> db.remove @id, @rev, cb
106940
### Copyright (c) 2014, <NAME> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.### db = require "../db" _ = require "underscore" module.exports = class Model @all: (cb) -> db.allWithType @type, (err, docs) => return cb(err) if err channels = docs.map (doc) => new this(doc) cb(null, channels) @findById: (id, cb) -> db.get id, (err, doc) => return cb(err) if err cb(null, new this(doc)) save: (cb=->) -> attrs = {} for own k,v of this if !_(["id", "rev"]).contains(k) && !/^\$/.test k attrs[k] = v if @id db.save @id, @rev, attrs, (err, res) -> return cb(err) if err @rev = res.rev cb() else db.save attrs, (err, res) => return cb(err) if err @id = res.id @rev = res.rev cb() update: (data, cb=->) -> this[k] = v for k,v of data @save(cb) destroy: (cb=->) -> db.remove @id, @rev, cb
true
### Copyright (c) 2014, PI:NAME:<NAME>END_PI All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.### db = require "../db" _ = require "underscore" module.exports = class Model @all: (cb) -> db.allWithType @type, (err, docs) => return cb(err) if err channels = docs.map (doc) => new this(doc) cb(null, channels) @findById: (id, cb) -> db.get id, (err, doc) => return cb(err) if err cb(null, new this(doc)) save: (cb=->) -> attrs = {} for own k,v of this if !_(["id", "rev"]).contains(k) && !/^\$/.test k attrs[k] = v if @id db.save @id, @rev, attrs, (err, res) -> return cb(err) if err @rev = res.rev cb() else db.save attrs, (err, res) => return cb(err) if err @id = res.id @rev = res.rev cb() update: (data, cb=->) -> this[k] = v for k,v of data @save(cb) destroy: (cb=->) -> db.remove @id, @rev, cb
[ { "context": " dimensions, cross-browser compatible\n# Thanks to: Stefano Gargiulo\ngetViewportSize = ->\n x = 0\n y = 0\n if window.", "end": 990, "score": 0.9998912215232849, "start": 974, "tag": "NAME", "value": "Stefano Gargiulo" } ]
vminpoly.coffee
fisherw/vminpoly
360
XMLHttpFactories = [ -> new XMLHttpRequest(), -> new ActiveXObject("Msxml2.XMLHTTP"), -> new ActiveXObject("Msxml3.XMLHTTP"), -> new ActiveXObject("Microsoft.XMLHTTP")] createXMLHTTPObject = -> xmlhttp = false i = 0 while i < XMLHttpFactories.length try xmlhttp = XMLHttpFactories[i++]() catch e continue break xmlhttp ##toCamelCase = (s) -> ## s.replace(/-([a-z])/g, (g) -> ## return g[1].toUpperCase() ajax = (url, onload) -> xmlhttp = createXMLHTTPObject() xmlhttp.onreadystatechange = -> unless xmlhttp.readyState is 4 return unless xmlhttp.status is 200 || url.match(/^file:\/\/\//) throw "Error!" console.log "INFO: processing #{url}" onload xmlhttp.responseText return try xmlhttp.open "GET", url, true xmlhttp.send() catch e console.log "ERROR: #{e.message} (#{e.type}) when accessing #{url}" return # get window dimensions, cross-browser compatible # Thanks to: Stefano Gargiulo getViewportSize = -> x = 0 y = 0 if window.innerHeight # all except Explorer < 9 x = window.innerWidth y = window.innerHeight else if document.documentElement and document.documentElement.clientHeight # Explorer 6 Strict Mode x = document.documentElement.clientWidth y = document.documentElement.clientHeight else if document.body # other Explorers < 9 x = document.body.clientWidth y = document.body.clientHeight width: x height: y browserSupportsUnitsNatively = -> # Append Test element test_element = document.createElement('div') test_element.id = "vminpolyTests" body = document.getElementsByTagName('body')[0] body.appendChild test_element # Append test style block style_block = document.createElement('style') head = document.getElementsByTagName('head')[0] head.appendChild style_block test_results = testVWSupport(test_element, style_block) and testVWSupport(test_element, style_block) and testVMinSupport(test_element, style_block) body.removeChild test_element head.removeChild style_block test_results testElementStyle = (element) -> if window.getComputedStyle getComputedStyle(element, null) else element.currentStyle applyStyleTest = (style_block, style) -> new_style = "#vminpolyTests { #{style}; }" if style_block.styleSheet style_block.styleSheet.cssText = new_style else test_style = document.createTextNode new_style style_block.appendChild test_style clearStyleTests = (style_block) -> if style_block.styleSheet style_block.styleSheet.cssText = '' else style_block.innerHTML = '' testVHSupport = (element, style_block) -> # Set height of element applyStyleTest(style_block, 'height: 50vh') # Parse page height to compare height = parseInt(window.innerHeight / 2, 10) # Computed style comp_style = parseInt(testElementStyle(element).height, 10) # Remove current test style clearStyleTests style_block # return result comp_style is height testVWSupport = (element, style_block) -> # Set width of element applyStyleTest(style_block, 'width: 50vw') # Parse page width to compare width = parseInt(window.innerWidth / 2, 10) # Computed style comp_style = parseInt(testElementStyle(element).width, 10) # Remove current test style clearStyleTests style_block # return result comp_style is width testVMinSupport = (element, style_block) -> # Set width of the element applyStyleTest(style_block, 'width: 50vmin') # docElement has to be defined, can you believe it docElement = document.documentElement # find minimum calculation sizes one_vw = docElement.clientWidth / 100 one_vh = docElement.clientHeight / 100 actual_vmin = parseInt(Math.min(one_vw, one_vh)*50,10) # Computed width comp_width = parseInt(testElementStyle(element).width, 10) # Remove current test style clearStyleTests style_block # return result actual_vmin is comp_width initLayoutEngine = () -> analyzeStyleRule = (rule) -> declarations = [] for declaration in rule.value hasDimension = false for token in declaration.value if token.tokenType is 'DIMENSION' and (token.unit is 'vmin' or token.unit is 'vh' or token.unit is 'vw') hasDimension = true if hasDimension declarations.push declaration rule.value = declarations declarations analyzeStylesheet = (sheet) -> rules = [] for rule in sheet.value switch rule.type when 'STYLE-RULE' decs = analyzeStyleRule rule unless decs.length is 0 rules.push rule when 'AT-RULE' atRules = analyzeStylesheet rule unless atRules.length is 0 rules.push rule sheet.value = rules rules onresize = -> vpDims = getViewportSize() dims = vh: vpDims.height / 100 vw: vpDims.width / 100 dims.vmin = Math.min dims.vh, dims.vw vpAspectRatio = vpDims.width / vpDims.height map = (a, f) -> if a.map? a.map f else a1 = [] for e in a a1.push f e a1 generateRuleCode = (rule) -> declarations = [] ruleCss = (map rule.selector, (o) -> if o.toSourceString? then o.toSourceString() else '').join '' ruleCss += "{" for declaration in rule.value ruleCss += declaration.name ruleCss += ":" for token in declaration.value if token.tokenType is 'DIMENSION' and (token.unit is 'vmin' or token.unit is 'vh' or token.unit is 'vw') ruleCss += "#{Math.floor(token.num*dims[token.unit])}px" else ruleCss += token.toSourceString() ruleCss += ";" ruleCss += "}\r" ruleCss generateSheetCode = (sheet) -> sheetCss = '' for rule in sheet.value switch rule.type when 'STYLE-RULE' sheetCss += generateRuleCode rule when 'AT-RULE' if rule.name is 'media' prelude = '' mar = false nums = [] for t in rule.prelude if t.name is '(' prelude += '(' for t1 in t.value source = if t1.toSourceString? then t1.toSourceString() else '' if t1.tokenType is 'IDENT' and source is 'max-aspect-ratio' mar = true if t1.tokenType is 'NUMBER' nums.push parseInt source prelude += source #prelude += (map t.value, (o) -> if o.toSourceString? then o.toSourceString() else '').join '' #prelude += t.value.join '' prelude += ')' else prelude += t.toSourceString() if vpAspectRatio < nums[0] / nums[1] sheetCss += generateSheetCode rule else prelude = '' for t in rule.prelude if t.name is '(' prelude += '(' prelude += (map t.value, (o) -> if o.toSourceString? then o.toSourceString() else '').join '' #prelude += t.value.join '' prelude += ')' else prelude += t.toSourceString() sheetCss += "@#{rule.name} #{prelude} {" sheetCss += generateSheetCode rule sheetCss += '}\n' sheetCss css = '' for url, sheet of sheets css += generateSheetCode sheet if styleElement.styleSheet? styleElement.styleSheet.cssText = css else styleElement.innerHTML = css sheets = {} styleElement = document.createElement 'style' head = document.getElementsByTagName('head')[0] head.appendChild styleElement links = document.getElementsByTagName 'link' innerSheetCount = 0; outerSheetCount = 0; for i in links unless i.rel is 'stylesheet' continue innerSheetCount++; ajax i.href, (cssText) -> tokenlist = tokenize cssText sheet = parse tokenlist analyzeStylesheet sheet sheets[i.href] = sheet outerSheetCount++ if outerSheetCount is innerSheetCount window.onresize() return window.onresize = onresize return initLayoutEngine() unless browserSupportsUnitsNatively()
27886
XMLHttpFactories = [ -> new XMLHttpRequest(), -> new ActiveXObject("Msxml2.XMLHTTP"), -> new ActiveXObject("Msxml3.XMLHTTP"), -> new ActiveXObject("Microsoft.XMLHTTP")] createXMLHTTPObject = -> xmlhttp = false i = 0 while i < XMLHttpFactories.length try xmlhttp = XMLHttpFactories[i++]() catch e continue break xmlhttp ##toCamelCase = (s) -> ## s.replace(/-([a-z])/g, (g) -> ## return g[1].toUpperCase() ajax = (url, onload) -> xmlhttp = createXMLHTTPObject() xmlhttp.onreadystatechange = -> unless xmlhttp.readyState is 4 return unless xmlhttp.status is 200 || url.match(/^file:\/\/\//) throw "Error!" console.log "INFO: processing #{url}" onload xmlhttp.responseText return try xmlhttp.open "GET", url, true xmlhttp.send() catch e console.log "ERROR: #{e.message} (#{e.type}) when accessing #{url}" return # get window dimensions, cross-browser compatible # Thanks to: <NAME> getViewportSize = -> x = 0 y = 0 if window.innerHeight # all except Explorer < 9 x = window.innerWidth y = window.innerHeight else if document.documentElement and document.documentElement.clientHeight # Explorer 6 Strict Mode x = document.documentElement.clientWidth y = document.documentElement.clientHeight else if document.body # other Explorers < 9 x = document.body.clientWidth y = document.body.clientHeight width: x height: y browserSupportsUnitsNatively = -> # Append Test element test_element = document.createElement('div') test_element.id = "vminpolyTests" body = document.getElementsByTagName('body')[0] body.appendChild test_element # Append test style block style_block = document.createElement('style') head = document.getElementsByTagName('head')[0] head.appendChild style_block test_results = testVWSupport(test_element, style_block) and testVWSupport(test_element, style_block) and testVMinSupport(test_element, style_block) body.removeChild test_element head.removeChild style_block test_results testElementStyle = (element) -> if window.getComputedStyle getComputedStyle(element, null) else element.currentStyle applyStyleTest = (style_block, style) -> new_style = "#vminpolyTests { #{style}; }" if style_block.styleSheet style_block.styleSheet.cssText = new_style else test_style = document.createTextNode new_style style_block.appendChild test_style clearStyleTests = (style_block) -> if style_block.styleSheet style_block.styleSheet.cssText = '' else style_block.innerHTML = '' testVHSupport = (element, style_block) -> # Set height of element applyStyleTest(style_block, 'height: 50vh') # Parse page height to compare height = parseInt(window.innerHeight / 2, 10) # Computed style comp_style = parseInt(testElementStyle(element).height, 10) # Remove current test style clearStyleTests style_block # return result comp_style is height testVWSupport = (element, style_block) -> # Set width of element applyStyleTest(style_block, 'width: 50vw') # Parse page width to compare width = parseInt(window.innerWidth / 2, 10) # Computed style comp_style = parseInt(testElementStyle(element).width, 10) # Remove current test style clearStyleTests style_block # return result comp_style is width testVMinSupport = (element, style_block) -> # Set width of the element applyStyleTest(style_block, 'width: 50vmin') # docElement has to be defined, can you believe it docElement = document.documentElement # find minimum calculation sizes one_vw = docElement.clientWidth / 100 one_vh = docElement.clientHeight / 100 actual_vmin = parseInt(Math.min(one_vw, one_vh)*50,10) # Computed width comp_width = parseInt(testElementStyle(element).width, 10) # Remove current test style clearStyleTests style_block # return result actual_vmin is comp_width initLayoutEngine = () -> analyzeStyleRule = (rule) -> declarations = [] for declaration in rule.value hasDimension = false for token in declaration.value if token.tokenType is 'DIMENSION' and (token.unit is 'vmin' or token.unit is 'vh' or token.unit is 'vw') hasDimension = true if hasDimension declarations.push declaration rule.value = declarations declarations analyzeStylesheet = (sheet) -> rules = [] for rule in sheet.value switch rule.type when 'STYLE-RULE' decs = analyzeStyleRule rule unless decs.length is 0 rules.push rule when 'AT-RULE' atRules = analyzeStylesheet rule unless atRules.length is 0 rules.push rule sheet.value = rules rules onresize = -> vpDims = getViewportSize() dims = vh: vpDims.height / 100 vw: vpDims.width / 100 dims.vmin = Math.min dims.vh, dims.vw vpAspectRatio = vpDims.width / vpDims.height map = (a, f) -> if a.map? a.map f else a1 = [] for e in a a1.push f e a1 generateRuleCode = (rule) -> declarations = [] ruleCss = (map rule.selector, (o) -> if o.toSourceString? then o.toSourceString() else '').join '' ruleCss += "{" for declaration in rule.value ruleCss += declaration.name ruleCss += ":" for token in declaration.value if token.tokenType is 'DIMENSION' and (token.unit is 'vmin' or token.unit is 'vh' or token.unit is 'vw') ruleCss += "#{Math.floor(token.num*dims[token.unit])}px" else ruleCss += token.toSourceString() ruleCss += ";" ruleCss += "}\r" ruleCss generateSheetCode = (sheet) -> sheetCss = '' for rule in sheet.value switch rule.type when 'STYLE-RULE' sheetCss += generateRuleCode rule when 'AT-RULE' if rule.name is 'media' prelude = '' mar = false nums = [] for t in rule.prelude if t.name is '(' prelude += '(' for t1 in t.value source = if t1.toSourceString? then t1.toSourceString() else '' if t1.tokenType is 'IDENT' and source is 'max-aspect-ratio' mar = true if t1.tokenType is 'NUMBER' nums.push parseInt source prelude += source #prelude += (map t.value, (o) -> if o.toSourceString? then o.toSourceString() else '').join '' #prelude += t.value.join '' prelude += ')' else prelude += t.toSourceString() if vpAspectRatio < nums[0] / nums[1] sheetCss += generateSheetCode rule else prelude = '' for t in rule.prelude if t.name is '(' prelude += '(' prelude += (map t.value, (o) -> if o.toSourceString? then o.toSourceString() else '').join '' #prelude += t.value.join '' prelude += ')' else prelude += t.toSourceString() sheetCss += "@#{rule.name} #{prelude} {" sheetCss += generateSheetCode rule sheetCss += '}\n' sheetCss css = '' for url, sheet of sheets css += generateSheetCode sheet if styleElement.styleSheet? styleElement.styleSheet.cssText = css else styleElement.innerHTML = css sheets = {} styleElement = document.createElement 'style' head = document.getElementsByTagName('head')[0] head.appendChild styleElement links = document.getElementsByTagName 'link' innerSheetCount = 0; outerSheetCount = 0; for i in links unless i.rel is 'stylesheet' continue innerSheetCount++; ajax i.href, (cssText) -> tokenlist = tokenize cssText sheet = parse tokenlist analyzeStylesheet sheet sheets[i.href] = sheet outerSheetCount++ if outerSheetCount is innerSheetCount window.onresize() return window.onresize = onresize return initLayoutEngine() unless browserSupportsUnitsNatively()
true
XMLHttpFactories = [ -> new XMLHttpRequest(), -> new ActiveXObject("Msxml2.XMLHTTP"), -> new ActiveXObject("Msxml3.XMLHTTP"), -> new ActiveXObject("Microsoft.XMLHTTP")] createXMLHTTPObject = -> xmlhttp = false i = 0 while i < XMLHttpFactories.length try xmlhttp = XMLHttpFactories[i++]() catch e continue break xmlhttp ##toCamelCase = (s) -> ## s.replace(/-([a-z])/g, (g) -> ## return g[1].toUpperCase() ajax = (url, onload) -> xmlhttp = createXMLHTTPObject() xmlhttp.onreadystatechange = -> unless xmlhttp.readyState is 4 return unless xmlhttp.status is 200 || url.match(/^file:\/\/\//) throw "Error!" console.log "INFO: processing #{url}" onload xmlhttp.responseText return try xmlhttp.open "GET", url, true xmlhttp.send() catch e console.log "ERROR: #{e.message} (#{e.type}) when accessing #{url}" return # get window dimensions, cross-browser compatible # Thanks to: PI:NAME:<NAME>END_PI getViewportSize = -> x = 0 y = 0 if window.innerHeight # all except Explorer < 9 x = window.innerWidth y = window.innerHeight else if document.documentElement and document.documentElement.clientHeight # Explorer 6 Strict Mode x = document.documentElement.clientWidth y = document.documentElement.clientHeight else if document.body # other Explorers < 9 x = document.body.clientWidth y = document.body.clientHeight width: x height: y browserSupportsUnitsNatively = -> # Append Test element test_element = document.createElement('div') test_element.id = "vminpolyTests" body = document.getElementsByTagName('body')[0] body.appendChild test_element # Append test style block style_block = document.createElement('style') head = document.getElementsByTagName('head')[0] head.appendChild style_block test_results = testVWSupport(test_element, style_block) and testVWSupport(test_element, style_block) and testVMinSupport(test_element, style_block) body.removeChild test_element head.removeChild style_block test_results testElementStyle = (element) -> if window.getComputedStyle getComputedStyle(element, null) else element.currentStyle applyStyleTest = (style_block, style) -> new_style = "#vminpolyTests { #{style}; }" if style_block.styleSheet style_block.styleSheet.cssText = new_style else test_style = document.createTextNode new_style style_block.appendChild test_style clearStyleTests = (style_block) -> if style_block.styleSheet style_block.styleSheet.cssText = '' else style_block.innerHTML = '' testVHSupport = (element, style_block) -> # Set height of element applyStyleTest(style_block, 'height: 50vh') # Parse page height to compare height = parseInt(window.innerHeight / 2, 10) # Computed style comp_style = parseInt(testElementStyle(element).height, 10) # Remove current test style clearStyleTests style_block # return result comp_style is height testVWSupport = (element, style_block) -> # Set width of element applyStyleTest(style_block, 'width: 50vw') # Parse page width to compare width = parseInt(window.innerWidth / 2, 10) # Computed style comp_style = parseInt(testElementStyle(element).width, 10) # Remove current test style clearStyleTests style_block # return result comp_style is width testVMinSupport = (element, style_block) -> # Set width of the element applyStyleTest(style_block, 'width: 50vmin') # docElement has to be defined, can you believe it docElement = document.documentElement # find minimum calculation sizes one_vw = docElement.clientWidth / 100 one_vh = docElement.clientHeight / 100 actual_vmin = parseInt(Math.min(one_vw, one_vh)*50,10) # Computed width comp_width = parseInt(testElementStyle(element).width, 10) # Remove current test style clearStyleTests style_block # return result actual_vmin is comp_width initLayoutEngine = () -> analyzeStyleRule = (rule) -> declarations = [] for declaration in rule.value hasDimension = false for token in declaration.value if token.tokenType is 'DIMENSION' and (token.unit is 'vmin' or token.unit is 'vh' or token.unit is 'vw') hasDimension = true if hasDimension declarations.push declaration rule.value = declarations declarations analyzeStylesheet = (sheet) -> rules = [] for rule in sheet.value switch rule.type when 'STYLE-RULE' decs = analyzeStyleRule rule unless decs.length is 0 rules.push rule when 'AT-RULE' atRules = analyzeStylesheet rule unless atRules.length is 0 rules.push rule sheet.value = rules rules onresize = -> vpDims = getViewportSize() dims = vh: vpDims.height / 100 vw: vpDims.width / 100 dims.vmin = Math.min dims.vh, dims.vw vpAspectRatio = vpDims.width / vpDims.height map = (a, f) -> if a.map? a.map f else a1 = [] for e in a a1.push f e a1 generateRuleCode = (rule) -> declarations = [] ruleCss = (map rule.selector, (o) -> if o.toSourceString? then o.toSourceString() else '').join '' ruleCss += "{" for declaration in rule.value ruleCss += declaration.name ruleCss += ":" for token in declaration.value if token.tokenType is 'DIMENSION' and (token.unit is 'vmin' or token.unit is 'vh' or token.unit is 'vw') ruleCss += "#{Math.floor(token.num*dims[token.unit])}px" else ruleCss += token.toSourceString() ruleCss += ";" ruleCss += "}\r" ruleCss generateSheetCode = (sheet) -> sheetCss = '' for rule in sheet.value switch rule.type when 'STYLE-RULE' sheetCss += generateRuleCode rule when 'AT-RULE' if rule.name is 'media' prelude = '' mar = false nums = [] for t in rule.prelude if t.name is '(' prelude += '(' for t1 in t.value source = if t1.toSourceString? then t1.toSourceString() else '' if t1.tokenType is 'IDENT' and source is 'max-aspect-ratio' mar = true if t1.tokenType is 'NUMBER' nums.push parseInt source prelude += source #prelude += (map t.value, (o) -> if o.toSourceString? then o.toSourceString() else '').join '' #prelude += t.value.join '' prelude += ')' else prelude += t.toSourceString() if vpAspectRatio < nums[0] / nums[1] sheetCss += generateSheetCode rule else prelude = '' for t in rule.prelude if t.name is '(' prelude += '(' prelude += (map t.value, (o) -> if o.toSourceString? then o.toSourceString() else '').join '' #prelude += t.value.join '' prelude += ')' else prelude += t.toSourceString() sheetCss += "@#{rule.name} #{prelude} {" sheetCss += generateSheetCode rule sheetCss += '}\n' sheetCss css = '' for url, sheet of sheets css += generateSheetCode sheet if styleElement.styleSheet? styleElement.styleSheet.cssText = css else styleElement.innerHTML = css sheets = {} styleElement = document.createElement 'style' head = document.getElementsByTagName('head')[0] head.appendChild styleElement links = document.getElementsByTagName 'link' innerSheetCount = 0; outerSheetCount = 0; for i in links unless i.rel is 'stylesheet' continue innerSheetCount++; ajax i.href, (cssText) -> tokenlist = tokenize cssText sheet = parse tokenlist analyzeStylesheet sheet sheets[i.href] = sheet outerSheetCount++ if outerSheetCount is innerSheetCount window.onresize() return window.onresize = onresize return initLayoutEngine() unless browserSupportsUnitsNatively()
[ { "context": "\t@calendar = `{{{calendar}}}`\n\t\t@weekday_keys = [\"sun\", \"mon\", \"tue\", \"wed\", \"thu\", \"fri\", \"sat\"]\n\t\t@methods = # ignoring u, l, g, j, A\n\t\t\t'G': 'er", "end": 274, "score": 0.9976433515548706, "start": 227, "tag": "KEY", "value": "sun\", \"mon\", \"tue\",...
js/lib/mustache/calendars/datetime.coffee
caniszczyk/twitter-cldr-rb
0
# Copyright 2012 Twitter, Inc # http://www.apache.org/licenses/LICENSE-2.0 TwitterCldr.DateTimeFormatter = class DateTimeFormatter constructor: -> @tokens = `{{{tokens}}}` @calendar = `{{{calendar}}}` @weekday_keys = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"] @methods = # ignoring u, l, g, j, A 'G': 'era' 'y': 'year' 'Y': 'year_of_week_of_year' 'Q': 'quarter' 'q': 'quarter_stand_alone' 'M': 'month' 'L': 'month_stand_alone' 'w': 'week_of_year' 'W': 'week_of_month' 'd': 'day' 'D': 'day_of_month' 'F': 'day_of_week_in_month' 'E': 'weekday' 'e': 'weekday_local' 'c': 'weekday_local_stand_alone' 'a': 'period' 'h': 'hour' 'H': 'hour' 'K': 'hour' 'k': 'hour' 'm': 'minute' 's': 'second' 'S': 'second_fraction' 'z': 'timezone' 'Z': 'timezone' 'v': 'timezone_generic_non_location' 'V': 'timezone_metazone' format: (obj, options) -> format_token = (token) => result = "" switch token.type when "pattern" return this.result_for_token(token, obj) else if token.value.length > 0 && token.value[0] == "'" && token.value[token.value.length - 1] == "'" return token.value.substring(1, token.value.length - 1) else return token.value tokens = this.get_tokens(obj, options) return (format_token(token) for token in tokens).join("") get_tokens: (obj, options) -> return @tokens[options.format || "date_time"][options.type || "default"] result_for_token: (token, date) -> return this[@methods[token.value[0]]](date, token.value, token.value.length) era: (date, pattern, length) -> switch length when 1, 2, 3 choices = @calendar["eras"]["abbr"] else choices = @calendar["eras"]["name"] index = if (date.getFullYear() < 0) then 0 else 1 return choices[index] year: (date, pattern, length) -> year = date.getFullYear().toString() if length == 2 if year.length != 1 year = year.slice(-2) if length > 1 year = ("0000" + year).slice(-length) return year year_of_week_of_year: (date, pattern, length) -> throw 'not implemented' day_of_week_in_month: (date, pattern, length) -> # e.g. 2nd Wed in July throw 'not implemented' quarter: (date, pattern, length) -> # the bitwise OR is used here to truncate the decimal produced by the / 3 quarter = ((date.getMonth() / 3) | 0) + 1 switch length when 1 return quarter.toString() when 2 return ("0000" + quarter.toString()).slice(-length) when 3 return @calendar.quarters.format.abbreviated[quarter] when 4 return @calendar.quarters.format.wide[quarter] quarter_stand_alone: (date, pattern, length) -> quarter = (date.getMonth() - 1) / 3 + 1 switch length when 1 return quarter.toString() when 2 return ("0000" + quarter.toString()).slice(-length) when 3 throw 'not yet implemented (requires cldr\'s "multiple inheritance")' when 4 throw 'not yet implemented (requires cldr\'s "multiple inheritance")' when 5 return @calendar.quarters['stand-alone'].narrow[quarter] month: (date, pattern, length) -> month_str = (date.getMonth() + 1).toString() switch length when 1 return month_str when 2 return ("0000" + month_str).slice(-length) when 3 return @calendar.months.format.abbreviated[month_str] when 4 return @calendar.months.format.wide[month_str] when 5 throw 'not yet implemented (requires cldr\'s "multiple inheritance")' else throw "Unknown date format" month_stand_alone: (date, pattern, length) -> switch length when 1 return date.getMonth().toString() when 2 return ("0000" + date.getMonth().toString()).slice(-length) when 3 throw 'not yet implemented (requires cldr\'s "multiple inheritance")' when 4 throw 'not yet implemented (requires cldr\'s "multiple inheritance")' when 5 return @calendar.months['stand-alone'].narrow[date.month] else throw "Unknown date format" day: (date, pattern, length) -> switch length when 1 return date.getDate().toString() when 2 return ("0000" + date.getDate().toString()).slice(-length) weekday: (date, pattern, length) -> key = @weekday_keys[date.getDay()] switch length when 1, 2, 3 return @calendar.days.format.abbreviated[key] when 4 return @calendar.days.format.wide[key] when 5 return @calendar.days['stand-alone'].narrow[key] weekday_local: (date, pattern, length) -> # "Like E except adds a numeric value depending on the local starting day of the week" # CLDR does not contain data as to which day is the first day of the week, so we will assume Monday (Ruby default) switch length when 1, 2 day = date.getDay() return (if day == 0 then "7" else day.toString()) else return this.weekday(date, pattern, length) weekday_local_stand_alone: (date, pattern, length) -> switch length when 1 return this.weekday_local(date, pattern, length) else return this.weekday(date, pattern, length) period: (time, pattern, length) -> if time.getHours() > 11 return @calendar.periods.format.wide["pm"] else return @calendar.periods.format.wide["am"] hour: (time, pattern, length) -> hour = time.getHours() switch pattern[0] when 'h' if hour > 12 hour = hour - 12 else if hour == 0 hour = 12 when 'K' if hour > 11 hour = hour - 12 when 'k' if hour == 0 hour = 24 if length == 1 return hour.toString() else return ("000000" + hour.toString()).slice(-length) minute: (time, pattern, length) -> if length == 1 return time.getMinutes().toString() else return ("000000" + time.getMinutes().toString()).slice(-length) second: (time, pattern, length) -> if length == 1 return time.getSeconds().toString() else return ("000000" + time.getSeconds().toString()).slice(-length) second_fraction: (time, pattern, length) -> if length > 6 throw 'can not use the S format with more than 6 digits' return ("000000" + Math.round(Math.pow(time.getMilliseconds() * 100.0, 6 - length)).toString()).slice(-length) timezone: (time, pattern, length) -> hours = ("00" + (time.getTimezoneOffset() / 60).toString()).slice(-2) minutes = ("00" + (time.getTimezoneOffset() % 60).toString()).slice(-2) switch length when 1, 2, 3 return "-" + hours + ":" + minutes else return "UTC -" + hours + ":" + minutes timezone_generic_non_location: (time, pattern, length) -> throw 'not yet implemented (requires timezone translation data")'
169997
# Copyright 2012 Twitter, Inc # http://www.apache.org/licenses/LICENSE-2.0 TwitterCldr.DateTimeFormatter = class DateTimeFormatter constructor: -> @tokens = `{{{tokens}}}` @calendar = `{{{calendar}}}` @weekday_keys = ["<KEY> @methods = # ignoring u, l, g, j, A 'G': 'era' 'y': 'year' 'Y': 'year_of_week_of_year' 'Q': 'quarter' 'q': 'quarter_stand_alone' 'M': 'month' 'L': 'month_stand_alone' 'w': 'week_of_year' 'W': 'week_of_month' 'd': 'day' 'D': 'day_of_month' 'F': 'day_of_week_in_month' 'E': 'weekday' 'e': 'weekday_local' 'c': 'weekday_local_stand_alone' 'a': 'period' 'h': 'hour' 'H': 'hour' 'K': 'hour' 'k': 'hour' 'm': 'minute' 's': 'second' 'S': 'second_fraction' 'z': 'timezone' 'Z': 'timezone' 'v': 'timezone_generic_non_location' 'V': 'timezone_metazone' format: (obj, options) -> format_token = (token) => result = "" switch token.type when "pattern" return this.result_for_token(token, obj) else if token.value.length > 0 && token.value[0] == "'" && token.value[token.value.length - 1] == "'" return token.value.substring(1, token.value.length - 1) else return token.value tokens = this.get_tokens(obj, options) return (format_token(token) for token in tokens).join("") get_tokens: (obj, options) -> return @tokens[options.format || "date_time"][options.type || "default"] result_for_token: (token, date) -> return this[@methods[token.value[0]]](date, token.value, token.value.length) era: (date, pattern, length) -> switch length when 1, 2, 3 choices = @calendar["eras"]["abbr"] else choices = @calendar["eras"]["name"] index = if (date.getFullYear() < 0) then 0 else 1 return choices[index] year: (date, pattern, length) -> year = date.getFullYear().toString() if length == 2 if year.length != 1 year = year.slice(-2) if length > 1 year = ("0000" + year).slice(-length) return year year_of_week_of_year: (date, pattern, length) -> throw 'not implemented' day_of_week_in_month: (date, pattern, length) -> # e.g. 2nd Wed in July throw 'not implemented' quarter: (date, pattern, length) -> # the bitwise OR is used here to truncate the decimal produced by the / 3 quarter = ((date.getMonth() / 3) | 0) + 1 switch length when 1 return quarter.toString() when 2 return ("0000" + quarter.toString()).slice(-length) when 3 return @calendar.quarters.format.abbreviated[quarter] when 4 return @calendar.quarters.format.wide[quarter] quarter_stand_alone: (date, pattern, length) -> quarter = (date.getMonth() - 1) / 3 + 1 switch length when 1 return quarter.toString() when 2 return ("0000" + quarter.toString()).slice(-length) when 3 throw 'not yet implemented (requires cldr\'s "multiple inheritance")' when 4 throw 'not yet implemented (requires cldr\'s "multiple inheritance")' when 5 return @calendar.quarters['stand-alone'].narrow[quarter] month: (date, pattern, length) -> month_str = (date.getMonth() + 1).toString() switch length when 1 return month_str when 2 return ("0000" + month_str).slice(-length) when 3 return @calendar.months.format.abbreviated[month_str] when 4 return @calendar.months.format.wide[month_str] when 5 throw 'not yet implemented (requires cldr\'s "multiple inheritance")' else throw "Unknown date format" month_stand_alone: (date, pattern, length) -> switch length when 1 return date.getMonth().toString() when 2 return ("0000" + date.getMonth().toString()).slice(-length) when 3 throw 'not yet implemented (requires cldr\'s "multiple inheritance")' when 4 throw 'not yet implemented (requires cldr\'s "multiple inheritance")' when 5 return @calendar.months['stand-alone'].narrow[date.month] else throw "Unknown date format" day: (date, pattern, length) -> switch length when 1 return date.getDate().toString() when 2 return ("0000" + date.getDate().toString()).slice(-length) weekday: (date, pattern, length) -> key = <KEY>date.<KEY> switch length when 1, 2, 3 return @calendar.days.format.abbreviated[key] when 4 return @calendar.days.format.wide[key] when 5 return @calendar.days['stand-alone'].narrow[key] weekday_local: (date, pattern, length) -> # "Like E except adds a numeric value depending on the local starting day of the week" # CLDR does not contain data as to which day is the first day of the week, so we will assume Monday (Ruby default) switch length when 1, 2 day = date.getDay() return (if day == 0 then "7" else day.toString()) else return this.weekday(date, pattern, length) weekday_local_stand_alone: (date, pattern, length) -> switch length when 1 return this.weekday_local(date, pattern, length) else return this.weekday(date, pattern, length) period: (time, pattern, length) -> if time.getHours() > 11 return @calendar.periods.format.wide["pm"] else return @calendar.periods.format.wide["am"] hour: (time, pattern, length) -> hour = time.getHours() switch pattern[0] when 'h' if hour > 12 hour = hour - 12 else if hour == 0 hour = 12 when 'K' if hour > 11 hour = hour - 12 when 'k' if hour == 0 hour = 24 if length == 1 return hour.toString() else return ("000000" + hour.toString()).slice(-length) minute: (time, pattern, length) -> if length == 1 return time.getMinutes().toString() else return ("000000" + time.getMinutes().toString()).slice(-length) second: (time, pattern, length) -> if length == 1 return time.getSeconds().toString() else return ("000000" + time.getSeconds().toString()).slice(-length) second_fraction: (time, pattern, length) -> if length > 6 throw 'can not use the S format with more than 6 digits' return ("000000" + Math.round(Math.pow(time.getMilliseconds() * 100.0, 6 - length)).toString()).slice(-length) timezone: (time, pattern, length) -> hours = ("00" + (time.getTimezoneOffset() / 60).toString()).slice(-2) minutes = ("00" + (time.getTimezoneOffset() % 60).toString()).slice(-2) switch length when 1, 2, 3 return "-" + hours + ":" + minutes else return "UTC -" + hours + ":" + minutes timezone_generic_non_location: (time, pattern, length) -> throw 'not yet implemented (requires timezone translation data")'
true
# Copyright 2012 Twitter, Inc # http://www.apache.org/licenses/LICENSE-2.0 TwitterCldr.DateTimeFormatter = class DateTimeFormatter constructor: -> @tokens = `{{{tokens}}}` @calendar = `{{{calendar}}}` @weekday_keys = ["PI:KEY:<KEY>END_PI @methods = # ignoring u, l, g, j, A 'G': 'era' 'y': 'year' 'Y': 'year_of_week_of_year' 'Q': 'quarter' 'q': 'quarter_stand_alone' 'M': 'month' 'L': 'month_stand_alone' 'w': 'week_of_year' 'W': 'week_of_month' 'd': 'day' 'D': 'day_of_month' 'F': 'day_of_week_in_month' 'E': 'weekday' 'e': 'weekday_local' 'c': 'weekday_local_stand_alone' 'a': 'period' 'h': 'hour' 'H': 'hour' 'K': 'hour' 'k': 'hour' 'm': 'minute' 's': 'second' 'S': 'second_fraction' 'z': 'timezone' 'Z': 'timezone' 'v': 'timezone_generic_non_location' 'V': 'timezone_metazone' format: (obj, options) -> format_token = (token) => result = "" switch token.type when "pattern" return this.result_for_token(token, obj) else if token.value.length > 0 && token.value[0] == "'" && token.value[token.value.length - 1] == "'" return token.value.substring(1, token.value.length - 1) else return token.value tokens = this.get_tokens(obj, options) return (format_token(token) for token in tokens).join("") get_tokens: (obj, options) -> return @tokens[options.format || "date_time"][options.type || "default"] result_for_token: (token, date) -> return this[@methods[token.value[0]]](date, token.value, token.value.length) era: (date, pattern, length) -> switch length when 1, 2, 3 choices = @calendar["eras"]["abbr"] else choices = @calendar["eras"]["name"] index = if (date.getFullYear() < 0) then 0 else 1 return choices[index] year: (date, pattern, length) -> year = date.getFullYear().toString() if length == 2 if year.length != 1 year = year.slice(-2) if length > 1 year = ("0000" + year).slice(-length) return year year_of_week_of_year: (date, pattern, length) -> throw 'not implemented' day_of_week_in_month: (date, pattern, length) -> # e.g. 2nd Wed in July throw 'not implemented' quarter: (date, pattern, length) -> # the bitwise OR is used here to truncate the decimal produced by the / 3 quarter = ((date.getMonth() / 3) | 0) + 1 switch length when 1 return quarter.toString() when 2 return ("0000" + quarter.toString()).slice(-length) when 3 return @calendar.quarters.format.abbreviated[quarter] when 4 return @calendar.quarters.format.wide[quarter] quarter_stand_alone: (date, pattern, length) -> quarter = (date.getMonth() - 1) / 3 + 1 switch length when 1 return quarter.toString() when 2 return ("0000" + quarter.toString()).slice(-length) when 3 throw 'not yet implemented (requires cldr\'s "multiple inheritance")' when 4 throw 'not yet implemented (requires cldr\'s "multiple inheritance")' when 5 return @calendar.quarters['stand-alone'].narrow[quarter] month: (date, pattern, length) -> month_str = (date.getMonth() + 1).toString() switch length when 1 return month_str when 2 return ("0000" + month_str).slice(-length) when 3 return @calendar.months.format.abbreviated[month_str] when 4 return @calendar.months.format.wide[month_str] when 5 throw 'not yet implemented (requires cldr\'s "multiple inheritance")' else throw "Unknown date format" month_stand_alone: (date, pattern, length) -> switch length when 1 return date.getMonth().toString() when 2 return ("0000" + date.getMonth().toString()).slice(-length) when 3 throw 'not yet implemented (requires cldr\'s "multiple inheritance")' when 4 throw 'not yet implemented (requires cldr\'s "multiple inheritance")' when 5 return @calendar.months['stand-alone'].narrow[date.month] else throw "Unknown date format" day: (date, pattern, length) -> switch length when 1 return date.getDate().toString() when 2 return ("0000" + date.getDate().toString()).slice(-length) weekday: (date, pattern, length) -> key = PI:KEY:<KEY>END_PIdate.PI:KEY:<KEY>END_PI switch length when 1, 2, 3 return @calendar.days.format.abbreviated[key] when 4 return @calendar.days.format.wide[key] when 5 return @calendar.days['stand-alone'].narrow[key] weekday_local: (date, pattern, length) -> # "Like E except adds a numeric value depending on the local starting day of the week" # CLDR does not contain data as to which day is the first day of the week, so we will assume Monday (Ruby default) switch length when 1, 2 day = date.getDay() return (if day == 0 then "7" else day.toString()) else return this.weekday(date, pattern, length) weekday_local_stand_alone: (date, pattern, length) -> switch length when 1 return this.weekday_local(date, pattern, length) else return this.weekday(date, pattern, length) period: (time, pattern, length) -> if time.getHours() > 11 return @calendar.periods.format.wide["pm"] else return @calendar.periods.format.wide["am"] hour: (time, pattern, length) -> hour = time.getHours() switch pattern[0] when 'h' if hour > 12 hour = hour - 12 else if hour == 0 hour = 12 when 'K' if hour > 11 hour = hour - 12 when 'k' if hour == 0 hour = 24 if length == 1 return hour.toString() else return ("000000" + hour.toString()).slice(-length) minute: (time, pattern, length) -> if length == 1 return time.getMinutes().toString() else return ("000000" + time.getMinutes().toString()).slice(-length) second: (time, pattern, length) -> if length == 1 return time.getSeconds().toString() else return ("000000" + time.getSeconds().toString()).slice(-length) second_fraction: (time, pattern, length) -> if length > 6 throw 'can not use the S format with more than 6 digits' return ("000000" + Math.round(Math.pow(time.getMilliseconds() * 100.0, 6 - length)).toString()).slice(-length) timezone: (time, pattern, length) -> hours = ("00" + (time.getTimezoneOffset() / 60).toString()).slice(-2) minutes = ("00" + (time.getTimezoneOffset() % 60).toString()).slice(-2) switch length when 1, 2, 3 return "-" + hours + ":" + minutes else return "UTC -" + hours + ":" + minutes timezone_generic_non_location: (time, pattern, length) -> throw 'not yet implemented (requires timezone translation data")'
[ { "context": "'fileTypes': [\n 'arnoldc'\n]\n'name': 'ArnoldC'\n'patterns': [\n {\n 'match': '(HEY\\ CHRISTMAS\\", "end": 45, "score": 0.9712295532226562, "start": 38, "tag": "NAME", "value": "ArnoldC" } ]
grammars/arnoldc.cson
mpgirro/atom-language-arnoldc
0
'fileTypes': [ 'arnoldc' ] 'name': 'ArnoldC' 'patterns': [ { 'match': '(HEY\ CHRISTMAS\ TREE|YOU\ SET\ US\ UP|YOU\ HAVE\ BEEN\ TERMINATED|GET\ TO\ THE\ CHOPPER|ENOUGH\ TALK|HERE\ IS\ MY\ INVITATION|GET\ UP|LET\ OFF\ SOME\ STEAM\ BENNET|HASTA\ LA\ VISTA\,\ BABY)' 'name': 'keyword.control.arnoldc' } { 'match': '(TALK\ TO\ THE\ HAND|YOU\ ARE\ NOT\ YOU\ YOU\ ARE\ ME|HE\ HAD\ TO\ SPLIT|YOU\'RE\ FIRED|GET\ DOWN|GET\ YOUR\ ASS\ TO\ MARS|DO\ IT\ NOW|I\ LET\ HIM\ GO|CONSIDER\ THAT\ A\ DIVORCE|KNOCK\ KNOCK)' 'name': 'keyword.control.arnoldc' } { 'match': '(YOU\ SET\ US\ UP)' 'name': 'constant.numeric.arnoldc' } { 'match': '\s[0-9]+' 'name': 'constant.numeric.arnoldc' } { 'match': '".*"' 'name': 'string.quoted.double' } { 'match': '(@I\ LIED|@NO\ PROBLEMO)' 'name': 'support.constant' } { 'match': 'LISTEN\ TO\ ME\ VERY\ CAREFULLY|IT\'S\ SHOWTIME' 'name': 'entity.name.function' } { 'match': 'STICK\ AROUND|CHILL|BECAUSE\ I\'M\ GOING\ TO\ SAY\ PLEASE|YOU\ HAVE\ NO\ RESPECT\ FOR\ LOGIC|BULLSHIT' 'name': 'storage.type' } { 'match': 'I\ NEED\ YOUR\ CLOTHES\ YOUR\ BOOTS\ AND\ YOUR\ MOTORCYCLE|GIVE\ THESE\ PEOPLE\ AIR|I\'LL\ BE\ BACK' 'name': 'variable.parameter' } ] 'scopeName': 'source.arnoldc'
60046
'fileTypes': [ 'arnoldc' ] 'name': '<NAME>' 'patterns': [ { 'match': '(HEY\ CHRISTMAS\ TREE|YOU\ SET\ US\ UP|YOU\ HAVE\ BEEN\ TERMINATED|GET\ TO\ THE\ CHOPPER|ENOUGH\ TALK|HERE\ IS\ MY\ INVITATION|GET\ UP|LET\ OFF\ SOME\ STEAM\ BENNET|HASTA\ LA\ VISTA\,\ BABY)' 'name': 'keyword.control.arnoldc' } { 'match': '(TALK\ TO\ THE\ HAND|YOU\ ARE\ NOT\ YOU\ YOU\ ARE\ ME|HE\ HAD\ TO\ SPLIT|YOU\'RE\ FIRED|GET\ DOWN|GET\ YOUR\ ASS\ TO\ MARS|DO\ IT\ NOW|I\ LET\ HIM\ GO|CONSIDER\ THAT\ A\ DIVORCE|KNOCK\ KNOCK)' 'name': 'keyword.control.arnoldc' } { 'match': '(YOU\ SET\ US\ UP)' 'name': 'constant.numeric.arnoldc' } { 'match': '\s[0-9]+' 'name': 'constant.numeric.arnoldc' } { 'match': '".*"' 'name': 'string.quoted.double' } { 'match': '(@I\ LIED|@NO\ PROBLEMO)' 'name': 'support.constant' } { 'match': 'LISTEN\ TO\ ME\ VERY\ CAREFULLY|IT\'S\ SHOWTIME' 'name': 'entity.name.function' } { 'match': 'STICK\ AROUND|CHILL|BECAUSE\ I\'M\ GOING\ TO\ SAY\ PLEASE|YOU\ HAVE\ NO\ RESPECT\ FOR\ LOGIC|BULLSHIT' 'name': 'storage.type' } { 'match': 'I\ NEED\ YOUR\ CLOTHES\ YOUR\ BOOTS\ AND\ YOUR\ MOTORCYCLE|GIVE\ THESE\ PEOPLE\ AIR|I\'LL\ BE\ BACK' 'name': 'variable.parameter' } ] 'scopeName': 'source.arnoldc'
true
'fileTypes': [ 'arnoldc' ] 'name': 'PI:NAME:<NAME>END_PI' 'patterns': [ { 'match': '(HEY\ CHRISTMAS\ TREE|YOU\ SET\ US\ UP|YOU\ HAVE\ BEEN\ TERMINATED|GET\ TO\ THE\ CHOPPER|ENOUGH\ TALK|HERE\ IS\ MY\ INVITATION|GET\ UP|LET\ OFF\ SOME\ STEAM\ BENNET|HASTA\ LA\ VISTA\,\ BABY)' 'name': 'keyword.control.arnoldc' } { 'match': '(TALK\ TO\ THE\ HAND|YOU\ ARE\ NOT\ YOU\ YOU\ ARE\ ME|HE\ HAD\ TO\ SPLIT|YOU\'RE\ FIRED|GET\ DOWN|GET\ YOUR\ ASS\ TO\ MARS|DO\ IT\ NOW|I\ LET\ HIM\ GO|CONSIDER\ THAT\ A\ DIVORCE|KNOCK\ KNOCK)' 'name': 'keyword.control.arnoldc' } { 'match': '(YOU\ SET\ US\ UP)' 'name': 'constant.numeric.arnoldc' } { 'match': '\s[0-9]+' 'name': 'constant.numeric.arnoldc' } { 'match': '".*"' 'name': 'string.quoted.double' } { 'match': '(@I\ LIED|@NO\ PROBLEMO)' 'name': 'support.constant' } { 'match': 'LISTEN\ TO\ ME\ VERY\ CAREFULLY|IT\'S\ SHOWTIME' 'name': 'entity.name.function' } { 'match': 'STICK\ AROUND|CHILL|BECAUSE\ I\'M\ GOING\ TO\ SAY\ PLEASE|YOU\ HAVE\ NO\ RESPECT\ FOR\ LOGIC|BULLSHIT' 'name': 'storage.type' } { 'match': 'I\ NEED\ YOUR\ CLOTHES\ YOUR\ BOOTS\ AND\ YOUR\ MOTORCYCLE|GIVE\ THESE\ PEOPLE\ AIR|I\'LL\ BE\ BACK' 'name': 'variable.parameter' } ] 'scopeName': 'source.arnoldc'
[ { "context": "nditions =\n asc: [\"Title\"]\n desc: [\"Name\"]\n\n scope = controller.resourceClass()\n ", "end": 4387, "score": 0.5063925385475159, "start": 4383, "tag": "NAME", "value": "Name" }, { "context": "1, model1) =>\n App.Parent.create title:...
test/controllers/resourceTest.coffee
komola/salad
2
describe "App.Controller mixin resource", -> describe "#buildConditionsFromParameters", -> it "should translate GET parameters to where conditions", -> controller = new App.TodosController() gtParameters = title: "Test" createdAt: ">2013-07-15T09:09:09.000Z" encodedGtParameters = title: "Test" createdAt: "%3E2013-07-15T09:09:09.000Z" ltParameters = title: "Test" createdAt: "<2013-07-15T09:09:09.000Z" encodedLtParameters = title: "Test" createdAt: "%3C2013-07-15T09:09:09.000Z" shouldGtConditions = where: title: "Test" createdAt: gt: "2013-07-15T09:09:09.000Z" shouldLtConditions = where: title: "Test" createdAt: lt: "2013-07-15T09:09:09.000Z" conditionsGtHash = controller.buildConditionsFromParameters gtParameters conditionsLtHash = controller.buildConditionsFromParameters ltParameters encodedGtHash = controller.buildConditionsFromParameters encodedGtParameters encodedLtHash = controller.buildConditionsFromParameters encodedLtParameters conditionsGtHash.should.eql shouldGtConditions conditionsLtHash.should.eql shouldLtConditions encodedGtHash.should.eql shouldGtConditions encodedLtHash.should.eql shouldLtConditions return null it "should translate GET parameters to contains conditions", -> controller = new App.TodosController() parameters = title: ":a" shouldConditions = contains: [title: ["a"]] conditionsHash = controller.buildConditionsFromParameters parameters conditionsHash.should.eql shouldConditions return null it "should translate GET parameters to sort conditions", -> controller = new App.TodosController() parameters = sort: "Title,-Name" shouldConditions = asc: ["Title"] desc: ["Name"] conditionsHash = controller.buildConditionsFromParameters parameters conditionsHash.should.eql shouldConditions return null it "should translate GET parameters to limit conditions", -> controller = new App.TodosController() parameters = limit: 5000 shouldConditions = limit: "5000" conditionsHash = controller.buildConditionsFromParameters parameters conditionsHash.should.eql shouldConditions return null it "should translate GET parameters to offset conditions", -> controller = new App.TodosController() parameters = offset: 5000 shouldConditions = offset: "5000" conditionsHash = controller.buildConditionsFromParameters parameters conditionsHash.should.eql shouldConditions return null it "should translate GET parameters to includes", -> controller = new App.TodosController() parameters = includes: "chargingstations,chargingplugs" shouldConditions = includes: ["chargingstations","chargingplugs"] conditionsHash = controller.buildConditionsFromParameters parameters conditionsHash.should.eql shouldConditions return null describe "#applyConditionsToScope", -> it "should add where to scope", -> controller = new App.ParentsController() shouldConditions = where: title: "Test" createdAt: gt: "2013-07-15T09:09:09.000Z" scope = controller.resourceClass() scope = controller.applyConditionsToScope(scope,shouldConditions) secondScope = controller.resourceClass() whereConditions = title: "Test" createdAt: gt: "2013-07-15T09:09:09.000Z" secondScope = secondScope.where(whereConditions) scope.should.eql secondScope return null it "should add contains to scope", -> controller = new App.ShopsController() shouldConditions = contains: ["title": ["a"]] scope = controller.resourceClass() scope = controller.applyConditionsToScope(scope,shouldConditions) secondScope = controller.resourceClass() secondScope = secondScope.contains "title", "a" scope.should.eql secondScope return null it "should add asc and desc to scope", -> controller = new App.ParentsController() shouldConditions = asc: ["Title"] desc: ["Name"] scope = controller.resourceClass() scope = controller.applyConditionsToScope(scope,shouldConditions) secondScope = controller.resourceClass() secondScope = secondScope.asc("Title").desc("Name") scope.should.eql secondScope return null it "should add limit to scope", -> controller = new App.ParentsController() shouldConditions = limit: 500 scope = controller.resourceClass() scope = controller.applyConditionsToScope(scope,shouldConditions) secondScope = controller.resourceClass() secondScope = secondScope.limit(500) scope.should.eql secondScope return null it "should add offset to scope", -> controller = new App.ParentsController() shouldConditions = offset: 50 scope = controller.resourceClass() scope = controller.applyConditionsToScope(scope,shouldConditions) secondScope = controller.resourceClass() secondScope = secondScope.offset(50) scope.should.eql secondScope return null it "should add includes to scope", -> controller = new App.ParentsController() shouldConditions = includes: ["children"] scope = controller.resourceClass() scope = controller.applyConditionsToScope(scope,shouldConditions) secondScope = controller.resourceClass() secondScope = secondScope.includes([App.Child]) scope.should.eql secondScope return null describe "#scope", -> it "should filter based on where (equality) and ignore unknown attributes", (done) -> App.Parent.create title: "Hello", (err, model) => App.Parent.create title: "Hey", (err, model) => agent.get(":3001/parents.json?title=Hey&asdas=hi") .then (res) -> res.body.length.should.equal 1 res.body[0].title.should.equal "Hey" done() #it "should filter based on array values" # it "should filter based on array values", (done) -> # return done() # # App.Shop.create title: ['a', 'b', 'c'], (err, model) => # App.Shop.create title: ['d', 'e', 'f'], (err, model) => # App.Shop.create title: ['a', 'g', 'h'], (err, model) => # agent.get(":3001/shops.json?title=:a") # .then (err, res) -> # res.body.length.should.equal 2 # # agent.get(":3001/shops.json?title=:a,b") # .then (err, res) -> # res.body.length.should.equal 1 # # done() it "should filter based on where (greather than)", (done) -> beforeDate = new Date() wait = (time, fun) => setTimeout fun, time wait 0, => App.Parent.create title: "Hello", (err1, model1) => App.Parent.create title: "Hey", (err2, model2) => afterDate = new Date() agent.get(":3001/parents.json?createdAt=>#{beforeDate.toISOString()}") .then (res) -> res.body.length.should.equal 2 agent.get(":3001/parents.json?createdAt=>#{afterDate.toISOString()}") .then (res) -> res.body.length.should.equal 0 done() it "should filter based on where (less than)", (done) -> beforeDate = new Date() App.Parent.create title: "Hello", (err, model) => App.Parent.create title: "Hey", (err, model) => afterDate = new Date() agent.get(":3001/parents.json?createdAt=<#{beforeDate.toISOString()}") .then (res) -> res.body.length.should.equal 0 agent.get(":3001/parents.json?createdAt=<#{afterDate.toISOString()}") .then (res) -> res.body.length.should.equal 2 done() it "should sort based on sort param", (done) -> App.Parent.create title: "Hello", (err, model) => App.Parent.create title: "Hey", (err, model) => agent.get(":3001/parents.json?sort=-title") .then (res) -> res.body.length.should.equal 2 res.body[0].title.should.equal "Hey" agent.get(":3001/parents.json?sort=title") .then (res) -> res.body.length.should.equal 2 res.body[0].title.should.equal "Hello" done() it "should limit and offset based on params", (done) -> App.Parent.create title: "Hello", (err, model) => App.Parent.create title: "Hey", (err, model) => agent.get(":3001/parents.json?limit=1&offset=0") .then (res) -> res.body.length.should.equal 1 res.body[0].title.should.equal "Hello" agent.get(":3001/parents.json?offset=1&limit=1") .then (res) -> res.body.length.should.equal 1 res.body[0].title.should.equal "Hey" done() it "should include associated objects based on includes param", (done) -> App.Parent.create title: "Parent", (err, parent) => parent.getChildren().create title: "Child", (err, child) -> agent.get(":3001/parents.json") .then (res) -> res.body.length.should.equal 1 res.body[0].title.should.equal "Parent" agent.get(":3001/parents.json?includes=children") .then (res) -> res.body.length.should.equal 1 res.body[0].should.have.property "children" done() it "should only include objects which are associated", (done) -> App.Parent.create title: "Parent", (err, parent) => parent.getChildren().create title: "Child", (err, child) -> agent.get(":3001/parents.json") .then (res) -> res.body.length.should.equal 1 res.body[0].title.should.equal "Parent" agent.get(":3001/parents.json?includes=Todo") .then (res) -> res.body.length.should.equal 1 done() it "should only include objects which exists", (done) -> App.Parent.create title: "Parent", (err, parent) => parent.getChildren().create title: "Child", (err, child) -> agent.get(":3001/parents.json") .then (res) -> res.body.length.should.equal 1 res.body[0].title.should.equal "Parent" agent.get(":3001/parents.json?includes=House") .then (res) -> res.body.length.should.equal 1 done()
174457
describe "App.Controller mixin resource", -> describe "#buildConditionsFromParameters", -> it "should translate GET parameters to where conditions", -> controller = new App.TodosController() gtParameters = title: "Test" createdAt: ">2013-07-15T09:09:09.000Z" encodedGtParameters = title: "Test" createdAt: "%3E2013-07-15T09:09:09.000Z" ltParameters = title: "Test" createdAt: "<2013-07-15T09:09:09.000Z" encodedLtParameters = title: "Test" createdAt: "%3C2013-07-15T09:09:09.000Z" shouldGtConditions = where: title: "Test" createdAt: gt: "2013-07-15T09:09:09.000Z" shouldLtConditions = where: title: "Test" createdAt: lt: "2013-07-15T09:09:09.000Z" conditionsGtHash = controller.buildConditionsFromParameters gtParameters conditionsLtHash = controller.buildConditionsFromParameters ltParameters encodedGtHash = controller.buildConditionsFromParameters encodedGtParameters encodedLtHash = controller.buildConditionsFromParameters encodedLtParameters conditionsGtHash.should.eql shouldGtConditions conditionsLtHash.should.eql shouldLtConditions encodedGtHash.should.eql shouldGtConditions encodedLtHash.should.eql shouldLtConditions return null it "should translate GET parameters to contains conditions", -> controller = new App.TodosController() parameters = title: ":a" shouldConditions = contains: [title: ["a"]] conditionsHash = controller.buildConditionsFromParameters parameters conditionsHash.should.eql shouldConditions return null it "should translate GET parameters to sort conditions", -> controller = new App.TodosController() parameters = sort: "Title,-Name" shouldConditions = asc: ["Title"] desc: ["Name"] conditionsHash = controller.buildConditionsFromParameters parameters conditionsHash.should.eql shouldConditions return null it "should translate GET parameters to limit conditions", -> controller = new App.TodosController() parameters = limit: 5000 shouldConditions = limit: "5000" conditionsHash = controller.buildConditionsFromParameters parameters conditionsHash.should.eql shouldConditions return null it "should translate GET parameters to offset conditions", -> controller = new App.TodosController() parameters = offset: 5000 shouldConditions = offset: "5000" conditionsHash = controller.buildConditionsFromParameters parameters conditionsHash.should.eql shouldConditions return null it "should translate GET parameters to includes", -> controller = new App.TodosController() parameters = includes: "chargingstations,chargingplugs" shouldConditions = includes: ["chargingstations","chargingplugs"] conditionsHash = controller.buildConditionsFromParameters parameters conditionsHash.should.eql shouldConditions return null describe "#applyConditionsToScope", -> it "should add where to scope", -> controller = new App.ParentsController() shouldConditions = where: title: "Test" createdAt: gt: "2013-07-15T09:09:09.000Z" scope = controller.resourceClass() scope = controller.applyConditionsToScope(scope,shouldConditions) secondScope = controller.resourceClass() whereConditions = title: "Test" createdAt: gt: "2013-07-15T09:09:09.000Z" secondScope = secondScope.where(whereConditions) scope.should.eql secondScope return null it "should add contains to scope", -> controller = new App.ShopsController() shouldConditions = contains: ["title": ["a"]] scope = controller.resourceClass() scope = controller.applyConditionsToScope(scope,shouldConditions) secondScope = controller.resourceClass() secondScope = secondScope.contains "title", "a" scope.should.eql secondScope return null it "should add asc and desc to scope", -> controller = new App.ParentsController() shouldConditions = asc: ["Title"] desc: ["<NAME>"] scope = controller.resourceClass() scope = controller.applyConditionsToScope(scope,shouldConditions) secondScope = controller.resourceClass() secondScope = secondScope.asc("Title").desc("Name") scope.should.eql secondScope return null it "should add limit to scope", -> controller = new App.ParentsController() shouldConditions = limit: 500 scope = controller.resourceClass() scope = controller.applyConditionsToScope(scope,shouldConditions) secondScope = controller.resourceClass() secondScope = secondScope.limit(500) scope.should.eql secondScope return null it "should add offset to scope", -> controller = new App.ParentsController() shouldConditions = offset: 50 scope = controller.resourceClass() scope = controller.applyConditionsToScope(scope,shouldConditions) secondScope = controller.resourceClass() secondScope = secondScope.offset(50) scope.should.eql secondScope return null it "should add includes to scope", -> controller = new App.ParentsController() shouldConditions = includes: ["children"] scope = controller.resourceClass() scope = controller.applyConditionsToScope(scope,shouldConditions) secondScope = controller.resourceClass() secondScope = secondScope.includes([App.Child]) scope.should.eql secondScope return null describe "#scope", -> it "should filter based on where (equality) and ignore unknown attributes", (done) -> App.Parent.create title: "Hello", (err, model) => App.Parent.create title: "Hey", (err, model) => agent.get(":3001/parents.json?title=Hey&asdas=hi") .then (res) -> res.body.length.should.equal 1 res.body[0].title.should.equal "Hey" done() #it "should filter based on array values" # it "should filter based on array values", (done) -> # return done() # # App.Shop.create title: ['a', 'b', 'c'], (err, model) => # App.Shop.create title: ['d', 'e', 'f'], (err, model) => # App.Shop.create title: ['a', 'g', 'h'], (err, model) => # agent.get(":3001/shops.json?title=:a") # .then (err, res) -> # res.body.length.should.equal 2 # # agent.get(":3001/shops.json?title=:a,b") # .then (err, res) -> # res.body.length.should.equal 1 # # done() it "should filter based on where (greather than)", (done) -> beforeDate = new Date() wait = (time, fun) => setTimeout fun, time wait 0, => App.Parent.create title: "Hello", (err1, model1) => App.Parent.create title: "<NAME>", (err2, model2) => afterDate = new Date() agent.get(":3001/parents.json?createdAt=>#{beforeDate.toISOString()}") .then (res) -> res.body.length.should.equal 2 agent.get(":3001/parents.json?createdAt=>#{afterDate.toISOString()}") .then (res) -> res.body.length.should.equal 0 done() it "should filter based on where (less than)", (done) -> beforeDate = new Date() App.Parent.create title: "Hello", (err, model) => App.Parent.create title: "<NAME>", (err, model) => afterDate = new Date() agent.get(":3001/parents.json?createdAt=<#{beforeDate.toISOString()}") .then (res) -> res.body.length.should.equal 0 agent.get(":3001/parents.json?createdAt=<#{afterDate.toISOString()}") .then (res) -> res.body.length.should.equal 2 done() it "should sort based on sort param", (done) -> App.Parent.create title: "Hello", (err, model) => App.Parent.create title: "H<NAME>", (err, model) => agent.get(":3001/parents.json?sort=-title") .then (res) -> res.body.length.should.equal 2 res.body[0].title.should.equal "Hey" agent.get(":3001/parents.json?sort=title") .then (res) -> res.body.length.should.equal 2 res.body[0].title.should.equal "Hello" done() it "should limit and offset based on params", (done) -> App.Parent.create title: "Hello", (err, model) => App.Parent.create title: "Hey", (err, model) => agent.get(":3001/parents.json?limit=1&offset=0") .then (res) -> res.body.length.should.equal 1 res.body[0].title.should.equal "Hello" agent.get(":3001/parents.json?offset=1&limit=1") .then (res) -> res.body.length.should.equal 1 res.body[0].title.should.equal "Hey" done() it "should include associated objects based on includes param", (done) -> App.Parent.create title: "Parent", (err, parent) => parent.getChildren().create title: "Child", (err, child) -> agent.get(":3001/parents.json") .then (res) -> res.body.length.should.equal 1 res.body[0].title.should.equal "Parent" agent.get(":3001/parents.json?includes=children") .then (res) -> res.body.length.should.equal 1 res.body[0].should.have.property "children" done() it "should only include objects which are associated", (done) -> App.Parent.create title: "Parent", (err, parent) => parent.getChildren().create title: "Child", (err, child) -> agent.get(":3001/parents.json") .then (res) -> res.body.length.should.equal 1 res.body[0].title.should.equal "Parent" agent.get(":3001/parents.json?includes=Todo") .then (res) -> res.body.length.should.equal 1 done() it "should only include objects which exists", (done) -> App.Parent.create title: "Parent", (err, parent) => parent.getChildren().create title: "Child", (err, child) -> agent.get(":3001/parents.json") .then (res) -> res.body.length.should.equal 1 res.body[0].title.should.equal "Parent" agent.get(":3001/parents.json?includes=House") .then (res) -> res.body.length.should.equal 1 done()
true
describe "App.Controller mixin resource", -> describe "#buildConditionsFromParameters", -> it "should translate GET parameters to where conditions", -> controller = new App.TodosController() gtParameters = title: "Test" createdAt: ">2013-07-15T09:09:09.000Z" encodedGtParameters = title: "Test" createdAt: "%3E2013-07-15T09:09:09.000Z" ltParameters = title: "Test" createdAt: "<2013-07-15T09:09:09.000Z" encodedLtParameters = title: "Test" createdAt: "%3C2013-07-15T09:09:09.000Z" shouldGtConditions = where: title: "Test" createdAt: gt: "2013-07-15T09:09:09.000Z" shouldLtConditions = where: title: "Test" createdAt: lt: "2013-07-15T09:09:09.000Z" conditionsGtHash = controller.buildConditionsFromParameters gtParameters conditionsLtHash = controller.buildConditionsFromParameters ltParameters encodedGtHash = controller.buildConditionsFromParameters encodedGtParameters encodedLtHash = controller.buildConditionsFromParameters encodedLtParameters conditionsGtHash.should.eql shouldGtConditions conditionsLtHash.should.eql shouldLtConditions encodedGtHash.should.eql shouldGtConditions encodedLtHash.should.eql shouldLtConditions return null it "should translate GET parameters to contains conditions", -> controller = new App.TodosController() parameters = title: ":a" shouldConditions = contains: [title: ["a"]] conditionsHash = controller.buildConditionsFromParameters parameters conditionsHash.should.eql shouldConditions return null it "should translate GET parameters to sort conditions", -> controller = new App.TodosController() parameters = sort: "Title,-Name" shouldConditions = asc: ["Title"] desc: ["Name"] conditionsHash = controller.buildConditionsFromParameters parameters conditionsHash.should.eql shouldConditions return null it "should translate GET parameters to limit conditions", -> controller = new App.TodosController() parameters = limit: 5000 shouldConditions = limit: "5000" conditionsHash = controller.buildConditionsFromParameters parameters conditionsHash.should.eql shouldConditions return null it "should translate GET parameters to offset conditions", -> controller = new App.TodosController() parameters = offset: 5000 shouldConditions = offset: "5000" conditionsHash = controller.buildConditionsFromParameters parameters conditionsHash.should.eql shouldConditions return null it "should translate GET parameters to includes", -> controller = new App.TodosController() parameters = includes: "chargingstations,chargingplugs" shouldConditions = includes: ["chargingstations","chargingplugs"] conditionsHash = controller.buildConditionsFromParameters parameters conditionsHash.should.eql shouldConditions return null describe "#applyConditionsToScope", -> it "should add where to scope", -> controller = new App.ParentsController() shouldConditions = where: title: "Test" createdAt: gt: "2013-07-15T09:09:09.000Z" scope = controller.resourceClass() scope = controller.applyConditionsToScope(scope,shouldConditions) secondScope = controller.resourceClass() whereConditions = title: "Test" createdAt: gt: "2013-07-15T09:09:09.000Z" secondScope = secondScope.where(whereConditions) scope.should.eql secondScope return null it "should add contains to scope", -> controller = new App.ShopsController() shouldConditions = contains: ["title": ["a"]] scope = controller.resourceClass() scope = controller.applyConditionsToScope(scope,shouldConditions) secondScope = controller.resourceClass() secondScope = secondScope.contains "title", "a" scope.should.eql secondScope return null it "should add asc and desc to scope", -> controller = new App.ParentsController() shouldConditions = asc: ["Title"] desc: ["PI:NAME:<NAME>END_PI"] scope = controller.resourceClass() scope = controller.applyConditionsToScope(scope,shouldConditions) secondScope = controller.resourceClass() secondScope = secondScope.asc("Title").desc("Name") scope.should.eql secondScope return null it "should add limit to scope", -> controller = new App.ParentsController() shouldConditions = limit: 500 scope = controller.resourceClass() scope = controller.applyConditionsToScope(scope,shouldConditions) secondScope = controller.resourceClass() secondScope = secondScope.limit(500) scope.should.eql secondScope return null it "should add offset to scope", -> controller = new App.ParentsController() shouldConditions = offset: 50 scope = controller.resourceClass() scope = controller.applyConditionsToScope(scope,shouldConditions) secondScope = controller.resourceClass() secondScope = secondScope.offset(50) scope.should.eql secondScope return null it "should add includes to scope", -> controller = new App.ParentsController() shouldConditions = includes: ["children"] scope = controller.resourceClass() scope = controller.applyConditionsToScope(scope,shouldConditions) secondScope = controller.resourceClass() secondScope = secondScope.includes([App.Child]) scope.should.eql secondScope return null describe "#scope", -> it "should filter based on where (equality) and ignore unknown attributes", (done) -> App.Parent.create title: "Hello", (err, model) => App.Parent.create title: "Hey", (err, model) => agent.get(":3001/parents.json?title=Hey&asdas=hi") .then (res) -> res.body.length.should.equal 1 res.body[0].title.should.equal "Hey" done() #it "should filter based on array values" # it "should filter based on array values", (done) -> # return done() # # App.Shop.create title: ['a', 'b', 'c'], (err, model) => # App.Shop.create title: ['d', 'e', 'f'], (err, model) => # App.Shop.create title: ['a', 'g', 'h'], (err, model) => # agent.get(":3001/shops.json?title=:a") # .then (err, res) -> # res.body.length.should.equal 2 # # agent.get(":3001/shops.json?title=:a,b") # .then (err, res) -> # res.body.length.should.equal 1 # # done() it "should filter based on where (greather than)", (done) -> beforeDate = new Date() wait = (time, fun) => setTimeout fun, time wait 0, => App.Parent.create title: "Hello", (err1, model1) => App.Parent.create title: "PI:NAME:<NAME>END_PI", (err2, model2) => afterDate = new Date() agent.get(":3001/parents.json?createdAt=>#{beforeDate.toISOString()}") .then (res) -> res.body.length.should.equal 2 agent.get(":3001/parents.json?createdAt=>#{afterDate.toISOString()}") .then (res) -> res.body.length.should.equal 0 done() it "should filter based on where (less than)", (done) -> beforeDate = new Date() App.Parent.create title: "Hello", (err, model) => App.Parent.create title: "PI:NAME:<NAME>END_PI", (err, model) => afterDate = new Date() agent.get(":3001/parents.json?createdAt=<#{beforeDate.toISOString()}") .then (res) -> res.body.length.should.equal 0 agent.get(":3001/parents.json?createdAt=<#{afterDate.toISOString()}") .then (res) -> res.body.length.should.equal 2 done() it "should sort based on sort param", (done) -> App.Parent.create title: "Hello", (err, model) => App.Parent.create title: "HPI:NAME:<NAME>END_PI", (err, model) => agent.get(":3001/parents.json?sort=-title") .then (res) -> res.body.length.should.equal 2 res.body[0].title.should.equal "Hey" agent.get(":3001/parents.json?sort=title") .then (res) -> res.body.length.should.equal 2 res.body[0].title.should.equal "Hello" done() it "should limit and offset based on params", (done) -> App.Parent.create title: "Hello", (err, model) => App.Parent.create title: "Hey", (err, model) => agent.get(":3001/parents.json?limit=1&offset=0") .then (res) -> res.body.length.should.equal 1 res.body[0].title.should.equal "Hello" agent.get(":3001/parents.json?offset=1&limit=1") .then (res) -> res.body.length.should.equal 1 res.body[0].title.should.equal "Hey" done() it "should include associated objects based on includes param", (done) -> App.Parent.create title: "Parent", (err, parent) => parent.getChildren().create title: "Child", (err, child) -> agent.get(":3001/parents.json") .then (res) -> res.body.length.should.equal 1 res.body[0].title.should.equal "Parent" agent.get(":3001/parents.json?includes=children") .then (res) -> res.body.length.should.equal 1 res.body[0].should.have.property "children" done() it "should only include objects which are associated", (done) -> App.Parent.create title: "Parent", (err, parent) => parent.getChildren().create title: "Child", (err, child) -> agent.get(":3001/parents.json") .then (res) -> res.body.length.should.equal 1 res.body[0].title.should.equal "Parent" agent.get(":3001/parents.json?includes=Todo") .then (res) -> res.body.length.should.equal 1 done() it "should only include objects which exists", (done) -> App.Parent.create title: "Parent", (err, parent) => parent.getChildren().create title: "Child", (err, child) -> agent.get(":3001/parents.json") .then (res) -> res.body.length.should.equal 1 res.body[0].title.should.equal "Parent" agent.get(":3001/parents.json?includes=House") .then (res) -> res.body.length.should.equal 1 done()
[ { "context": "ire \"../../../lib/config\"\n\ngapi.server.setApiKey \"AIzaSyB14Ua7k5_wusxHTQEH3sqmglO7MHjHPCI\"\ngapi.server.load \"plus\", \"v1\", ->\n request = ga", "end": 134, "score": 0.9997470378875732, "start": 95, "tag": "KEY", "value": "AIzaSyB14Ua7k5_wusxHTQEH3sqmglO7MHjHPCI" }, ...
static/node_modules/gapi/test/plus/activities/list.coffee
nohharri/chator
4
gapi = require "../../../index" config = require "../../../lib/config" gapi.server.setApiKey "AIzaSyB14Ua7k5_wusxHTQEH3sqmglO7MHjHPCI" gapi.server.load "plus", "v1", -> request = gapi.server.plus.activities.list userId: '102147307918874735077', collection: 'public', maxResults: '1' describe "calling activities.list({userId: '102147307918874735077', collection: 'public', maxResults: '1'})", -> it "should add /plus/v1/people/102147307918874735077/activities/public?key=AIzaSyB14Ua7k5_wusxHTQEH3sqmglO7MHjHPCI&alt=json&maxResults=1 to config.requestOptions.path", -> config.requestOptions.path.should.equal "/plus/v1/people/102147307918874735077/activities/public?key=AIzaSyB14Ua7k5_wusxHTQEH3sqmglO7MHjHPCI&alt=json&maxResults=1" it "should return execute function", -> request.should.have.property 'execute' request.execute.should.be.a 'function' describe "calling execute with a callback", -> it "should make a request and return an object to the callback", (done) -> request.execute (resp) -> resp.should.be.a 'object' #resp.should.not.have.property 'error' done()
32185
gapi = require "../../../index" config = require "../../../lib/config" gapi.server.setApiKey "<KEY>" gapi.server.load "plus", "v1", -> request = gapi.server.plus.activities.list userId: '102147307918874735077', collection: 'public', maxResults: '1' describe "calling activities.list({userId: '102147307918874735077', collection: 'public', maxResults: '1'})", -> it "should add /plus/v1/people/<KEY>47307918874735077/activities/public?key=<KEY>&alt=json&maxResults=1 to config.requestOptions.path", -> config.requestOptions.path.should.equal "/plus/v1/people/102147307918874735077/activities/public?key=<KEY>&alt=json&maxResults=1" it "should return execute function", -> request.should.have.property 'execute' request.execute.should.be.a 'function' describe "calling execute with a callback", -> it "should make a request and return an object to the callback", (done) -> request.execute (resp) -> resp.should.be.a 'object' #resp.should.not.have.property 'error' done()
true
gapi = require "../../../index" config = require "../../../lib/config" gapi.server.setApiKey "PI:KEY:<KEY>END_PI" gapi.server.load "plus", "v1", -> request = gapi.server.plus.activities.list userId: '102147307918874735077', collection: 'public', maxResults: '1' describe "calling activities.list({userId: '102147307918874735077', collection: 'public', maxResults: '1'})", -> it "should add /plus/v1/people/PI:KEY:<KEY>END_PI47307918874735077/activities/public?key=PI:KEY:<KEY>END_PI&alt=json&maxResults=1 to config.requestOptions.path", -> config.requestOptions.path.should.equal "/plus/v1/people/102147307918874735077/activities/public?key=PI:KEY:<KEY>END_PI&alt=json&maxResults=1" it "should return execute function", -> request.should.have.property 'execute' request.execute.should.be.a 'function' describe "calling execute with a callback", -> it "should make a request and return an object to the callback", (done) -> request.execute (resp) -> resp.should.be.a 'object' #resp.should.not.have.property 'error' done()
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9987263679504395, "start": 12, "tag": "NAME", "value": "Joyent" }, { "context": " common.PORT, ->\n cmd = \"curl --insecure https://127.0.0.1:\" + common.PORT + \"/\"\n cons...
test/simple/test-https-simple.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. unless process.versions.openssl console.error "Skipping because node compiled without OpenSSL." process.exit 0 common = require("../common") assert = require("assert") fs = require("fs") exec = require("child_process").exec https = require("https") options = key: fs.readFileSync(common.fixturesDir + "/keys/agent1-key.pem") cert: fs.readFileSync(common.fixturesDir + "/keys/agent1-cert.pem") reqCount = 0 body = "hello world\n" server = https.createServer(options, (req, res) -> reqCount++ console.log "got request" res.writeHead 200, "content-type": "text/plain" res.end body return ) server.listen common.PORT, -> cmd = "curl --insecure https://127.0.0.1:" + common.PORT + "/" console.error "executing %j", cmd exec cmd, (err, stdout, stderr) -> throw err if err common.error common.inspect(stdout) assert.equal body, stdout # Do the same thing now without --insecure # The connection should not be accepted. cmd = "curl https://127.0.0.1:" + common.PORT + "/" console.error "executing %j", cmd exec cmd, (err, stdout, stderr) -> assert.ok err server.close() return return return process.on "exit", -> assert.equal 1, reqCount return
11485
# 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. unless process.versions.openssl console.error "Skipping because node compiled without OpenSSL." process.exit 0 common = require("../common") assert = require("assert") fs = require("fs") exec = require("child_process").exec https = require("https") options = key: fs.readFileSync(common.fixturesDir + "/keys/agent1-key.pem") cert: fs.readFileSync(common.fixturesDir + "/keys/agent1-cert.pem") reqCount = 0 body = "hello world\n" server = https.createServer(options, (req, res) -> reqCount++ console.log "got request" res.writeHead 200, "content-type": "text/plain" res.end body return ) server.listen common.PORT, -> cmd = "curl --insecure https://127.0.0.1:" + common.PORT + "/" console.error "executing %j", cmd exec cmd, (err, stdout, stderr) -> throw err if err common.error common.inspect(stdout) assert.equal body, stdout # Do the same thing now without --insecure # The connection should not be accepted. cmd = "curl https://127.0.0.1:" + common.PORT + "/" console.error "executing %j", cmd exec cmd, (err, stdout, stderr) -> assert.ok err server.close() return return return process.on "exit", -> assert.equal 1, reqCount 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. unless process.versions.openssl console.error "Skipping because node compiled without OpenSSL." process.exit 0 common = require("../common") assert = require("assert") fs = require("fs") exec = require("child_process").exec https = require("https") options = key: fs.readFileSync(common.fixturesDir + "/keys/agent1-key.pem") cert: fs.readFileSync(common.fixturesDir + "/keys/agent1-cert.pem") reqCount = 0 body = "hello world\n" server = https.createServer(options, (req, res) -> reqCount++ console.log "got request" res.writeHead 200, "content-type": "text/plain" res.end body return ) server.listen common.PORT, -> cmd = "curl --insecure https://127.0.0.1:" + common.PORT + "/" console.error "executing %j", cmd exec cmd, (err, stdout, stderr) -> throw err if err common.error common.inspect(stdout) assert.equal body, stdout # Do the same thing now without --insecure # The connection should not be accepted. cmd = "curl https://127.0.0.1:" + common.PORT + "/" console.error "executing %j", cmd exec cmd, (err, stdout, stderr) -> assert.ok err server.close() return return return process.on "exit", -> assert.equal 1, reqCount return
[ { "context": "###\n * 测试 Promise\n * @author jackie Lin <dashi_lin@163.com>\n###\npromise = null\ndescribe '", "end": 39, "score": 0.9997403621673584, "start": 29, "tag": "NAME", "value": "jackie Lin" }, { "context": "###\n * 测试 Promise\n * @author jackie Lin <dashi_lin@163.com>\n###...
test/test.coffee
JackieLin/promise
3
### * 测试 Promise * @author jackie Lin <dashi_lin@163.com> ### promise = null describe 'Promise', -> it '#new Promise', -> promise = new Promise (resolve, reject)-> window.setTimeout -> resolve 111 , 1000 it 'then test normal', -> # normal promise promise.then (res)-> return 333 .then (res) -> (res).should.be.exactly 333 it 'then test promise', (done)-> promise.then (res)-> 333 .then (res) -> (res).should.be.exactly 333 333 .then (res)-> new Promise (resolve, reject)-> window.setTimeout -> resolve 222 , 500 .then (res) -> (res).should.be.exactly 222 444 .done (res) -> res .then (res) -> (res).should.be.exactly 444 res .done (res) -> done() it 'promise fail', (done)-> new Promise (resolve, reject) -> reject 'error' .fail (res) -> (res).should.be.exactly 'error' done()
129509
### * 测试 Promise * @author <NAME> <<EMAIL>> ### promise = null describe 'Promise', -> it '#new Promise', -> promise = new Promise (resolve, reject)-> window.setTimeout -> resolve 111 , 1000 it 'then test normal', -> # normal promise promise.then (res)-> return 333 .then (res) -> (res).should.be.exactly 333 it 'then test promise', (done)-> promise.then (res)-> 333 .then (res) -> (res).should.be.exactly 333 333 .then (res)-> new Promise (resolve, reject)-> window.setTimeout -> resolve 222 , 500 .then (res) -> (res).should.be.exactly 222 444 .done (res) -> res .then (res) -> (res).should.be.exactly 444 res .done (res) -> done() it 'promise fail', (done)-> new Promise (resolve, reject) -> reject 'error' .fail (res) -> (res).should.be.exactly 'error' done()
true
### * 测试 Promise * @author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> ### promise = null describe 'Promise', -> it '#new Promise', -> promise = new Promise (resolve, reject)-> window.setTimeout -> resolve 111 , 1000 it 'then test normal', -> # normal promise promise.then (res)-> return 333 .then (res) -> (res).should.be.exactly 333 it 'then test promise', (done)-> promise.then (res)-> 333 .then (res) -> (res).should.be.exactly 333 333 .then (res)-> new Promise (resolve, reject)-> window.setTimeout -> resolve 222 , 500 .then (res) -> (res).should.be.exactly 222 444 .done (res) -> res .then (res) -> (res).should.be.exactly 444 res .done (res) -> done() it 'promise fail', (done)-> new Promise (resolve, reject) -> reject 'error' .fail (res) -> (res).should.be.exactly 'error' done()
[ { "context": " ->\n options ?= new Object\n options.key ?= 'connect.sid'\n options.store ?= new session.MemoryStore\n ", "end": 543, "score": 0.999232292175293, "start": 532, "tag": "KEY", "value": "connect.sid" } ]
node_modules/express.io/lib/index.coffee
bradyuen/nodejs
4
connect = require 'express/node_modules/connect' express = require 'express' io = require 'socket.io' http = require 'http' https = require 'https' async = require 'async' middleware = require './middleware' _ = require 'underscore' RequestIO = require('./request').RequestIO RoomIO = require('./room').RoomIO express.io = io express.io.routeForward = middleware.routeForward session = express.session delete express.session sessionConfig = new Object express.session = (options) -> options ?= new Object options.key ?= 'connect.sid' options.store ?= new session.MemoryStore options.cookie ?= new Object sessionConfig = options return session options for key, value of session express.session[key] = value express.application.http = -> @server = http.createServer this return this express.application.https = (options) -> @server = https.createServer options, this return this express.application.io = (options) -> options ?= new Object defaultOptions = log:false _.extend options, defaultOptions @io = io.listen @server, options @io.router = new Object @io.middleware = [] @io.route = (route, next, options) -> if options?.trigger is true if route.indexOf ':' is -1 @router[route] next else split = route.split ':' @router[split[0]][split[1]] next if _.isFunction next @router[route] = next else for key, value of next @router["#{route}:#{key}"] = value @io.configure => @io.set 'authorization', (data, next) => unless sessionConfig.store? return async.forEachSeries @io.middleware, (callback, next) -> callback(data, next) , (error) -> return next error if error? next null, true cookieParser = express.cookieParser() cookieParser data, null, (error) -> return next error if error? rawCookie = data.cookies[sessionConfig.key] unless rawCookie? request = headers: cookie: data.query.cookie return cookieParser request, null, (error) -> data.cookies = request.cookies rawCookie = data.cookies[sessionConfig.key] return next "No cookie present", false unless rawCookie? sessionId = connect.utils.parseSignedCookie rawCookie, sessionConfig.secret data.sessionID = sessionId sessionConfig.store.get sessionId, (error, session) -> return next error if error? data.session = new connect.session.Session data, session next null, true sessionId = connect.utils.parseSignedCookie rawCookie, sessionConfig.secret data.sessionID = sessionId sessionConfig.store.get sessionId, (error, session) -> return next error if error? data.session = new connect.session.Session data, session next null, true @io.use = (callback) => @io.middleware.push callback @io.sockets.on 'connection', (socket) => initRoutes socket, @io @io.broadcast = => args = Array.prototype.slice.call arguments, 0 @io.sockets.emit.apply @io.sockets, args @io.room = (room) => new RoomIO(room, @io.sockets) @stack.push route: '' handle: (request, response, next) => request.io = route: (route) => ioRequest = new Object for key, value of request ioRequest[key] = value ioRequest.io = broadcast: @io.broadcast respond: => args = Array.prototype.slice.call arguments, 0 response.json.apply response, args route: (route) => @io.route route, ioRequest, trigger: true data: request.body @io.route route, ioRequest, trigger: true broadcast: @io.broadcast next() return this listen = express.application.listen express.application.listen = -> args = Array.prototype.slice.call arguments, 0 if @server? @server.listen.apply @server, args else listen.apply this, args initRoutes = (socket, io) -> setRoute = (key, callback) -> socket.on key, (data, respond) -> if typeof data is 'function' respond = data data = undefined request = data: data session: socket.handshake.session sessionID: socket.handshake.sessionID sessionStore: sessionConfig.store socket: socket headers: socket.handshake.headers cookies: socket.handshake.cookies handshake: socket.handshake session = socket.handshake.session request.session = new connect.session.Session request, session if session? socket.handshake.session = request.session request.io = new RequestIO(socket, request, io) request.io.respond = respond request.io.respond ?= -> callback request for key, value of io.router setRoute(key, value) module.exports = express
129998
connect = require 'express/node_modules/connect' express = require 'express' io = require 'socket.io' http = require 'http' https = require 'https' async = require 'async' middleware = require './middleware' _ = require 'underscore' RequestIO = require('./request').RequestIO RoomIO = require('./room').RoomIO express.io = io express.io.routeForward = middleware.routeForward session = express.session delete express.session sessionConfig = new Object express.session = (options) -> options ?= new Object options.key ?= '<KEY>' options.store ?= new session.MemoryStore options.cookie ?= new Object sessionConfig = options return session options for key, value of session express.session[key] = value express.application.http = -> @server = http.createServer this return this express.application.https = (options) -> @server = https.createServer options, this return this express.application.io = (options) -> options ?= new Object defaultOptions = log:false _.extend options, defaultOptions @io = io.listen @server, options @io.router = new Object @io.middleware = [] @io.route = (route, next, options) -> if options?.trigger is true if route.indexOf ':' is -1 @router[route] next else split = route.split ':' @router[split[0]][split[1]] next if _.isFunction next @router[route] = next else for key, value of next @router["#{route}:#{key}"] = value @io.configure => @io.set 'authorization', (data, next) => unless sessionConfig.store? return async.forEachSeries @io.middleware, (callback, next) -> callback(data, next) , (error) -> return next error if error? next null, true cookieParser = express.cookieParser() cookieParser data, null, (error) -> return next error if error? rawCookie = data.cookies[sessionConfig.key] unless rawCookie? request = headers: cookie: data.query.cookie return cookieParser request, null, (error) -> data.cookies = request.cookies rawCookie = data.cookies[sessionConfig.key] return next "No cookie present", false unless rawCookie? sessionId = connect.utils.parseSignedCookie rawCookie, sessionConfig.secret data.sessionID = sessionId sessionConfig.store.get sessionId, (error, session) -> return next error if error? data.session = new connect.session.Session data, session next null, true sessionId = connect.utils.parseSignedCookie rawCookie, sessionConfig.secret data.sessionID = sessionId sessionConfig.store.get sessionId, (error, session) -> return next error if error? data.session = new connect.session.Session data, session next null, true @io.use = (callback) => @io.middleware.push callback @io.sockets.on 'connection', (socket) => initRoutes socket, @io @io.broadcast = => args = Array.prototype.slice.call arguments, 0 @io.sockets.emit.apply @io.sockets, args @io.room = (room) => new RoomIO(room, @io.sockets) @stack.push route: '' handle: (request, response, next) => request.io = route: (route) => ioRequest = new Object for key, value of request ioRequest[key] = value ioRequest.io = broadcast: @io.broadcast respond: => args = Array.prototype.slice.call arguments, 0 response.json.apply response, args route: (route) => @io.route route, ioRequest, trigger: true data: request.body @io.route route, ioRequest, trigger: true broadcast: @io.broadcast next() return this listen = express.application.listen express.application.listen = -> args = Array.prototype.slice.call arguments, 0 if @server? @server.listen.apply @server, args else listen.apply this, args initRoutes = (socket, io) -> setRoute = (key, callback) -> socket.on key, (data, respond) -> if typeof data is 'function' respond = data data = undefined request = data: data session: socket.handshake.session sessionID: socket.handshake.sessionID sessionStore: sessionConfig.store socket: socket headers: socket.handshake.headers cookies: socket.handshake.cookies handshake: socket.handshake session = socket.handshake.session request.session = new connect.session.Session request, session if session? socket.handshake.session = request.session request.io = new RequestIO(socket, request, io) request.io.respond = respond request.io.respond ?= -> callback request for key, value of io.router setRoute(key, value) module.exports = express
true
connect = require 'express/node_modules/connect' express = require 'express' io = require 'socket.io' http = require 'http' https = require 'https' async = require 'async' middleware = require './middleware' _ = require 'underscore' RequestIO = require('./request').RequestIO RoomIO = require('./room').RoomIO express.io = io express.io.routeForward = middleware.routeForward session = express.session delete express.session sessionConfig = new Object express.session = (options) -> options ?= new Object options.key ?= 'PI:KEY:<KEY>END_PI' options.store ?= new session.MemoryStore options.cookie ?= new Object sessionConfig = options return session options for key, value of session express.session[key] = value express.application.http = -> @server = http.createServer this return this express.application.https = (options) -> @server = https.createServer options, this return this express.application.io = (options) -> options ?= new Object defaultOptions = log:false _.extend options, defaultOptions @io = io.listen @server, options @io.router = new Object @io.middleware = [] @io.route = (route, next, options) -> if options?.trigger is true if route.indexOf ':' is -1 @router[route] next else split = route.split ':' @router[split[0]][split[1]] next if _.isFunction next @router[route] = next else for key, value of next @router["#{route}:#{key}"] = value @io.configure => @io.set 'authorization', (data, next) => unless sessionConfig.store? return async.forEachSeries @io.middleware, (callback, next) -> callback(data, next) , (error) -> return next error if error? next null, true cookieParser = express.cookieParser() cookieParser data, null, (error) -> return next error if error? rawCookie = data.cookies[sessionConfig.key] unless rawCookie? request = headers: cookie: data.query.cookie return cookieParser request, null, (error) -> data.cookies = request.cookies rawCookie = data.cookies[sessionConfig.key] return next "No cookie present", false unless rawCookie? sessionId = connect.utils.parseSignedCookie rawCookie, sessionConfig.secret data.sessionID = sessionId sessionConfig.store.get sessionId, (error, session) -> return next error if error? data.session = new connect.session.Session data, session next null, true sessionId = connect.utils.parseSignedCookie rawCookie, sessionConfig.secret data.sessionID = sessionId sessionConfig.store.get sessionId, (error, session) -> return next error if error? data.session = new connect.session.Session data, session next null, true @io.use = (callback) => @io.middleware.push callback @io.sockets.on 'connection', (socket) => initRoutes socket, @io @io.broadcast = => args = Array.prototype.slice.call arguments, 0 @io.sockets.emit.apply @io.sockets, args @io.room = (room) => new RoomIO(room, @io.sockets) @stack.push route: '' handle: (request, response, next) => request.io = route: (route) => ioRequest = new Object for key, value of request ioRequest[key] = value ioRequest.io = broadcast: @io.broadcast respond: => args = Array.prototype.slice.call arguments, 0 response.json.apply response, args route: (route) => @io.route route, ioRequest, trigger: true data: request.body @io.route route, ioRequest, trigger: true broadcast: @io.broadcast next() return this listen = express.application.listen express.application.listen = -> args = Array.prototype.slice.call arguments, 0 if @server? @server.listen.apply @server, args else listen.apply this, args initRoutes = (socket, io) -> setRoute = (key, callback) -> socket.on key, (data, respond) -> if typeof data is 'function' respond = data data = undefined request = data: data session: socket.handshake.session sessionID: socket.handshake.sessionID sessionStore: sessionConfig.store socket: socket headers: socket.handshake.headers cookies: socket.handshake.cookies handshake: socket.handshake session = socket.handshake.session request.session = new connect.session.Session request, session if session? socket.handshake.session = request.session request.io = new RequestIO(socket, request, io) request.io.respond = respond request.io.respond ?= -> callback request for key, value of io.router setRoute(key, value) module.exports = express
[ { "context": "# @file testAll.coffee\n# @Copyright (c) 2016 Taylor Siviter\n# This source code is licensed under the MIT Lice", "end": 59, "score": 0.999764621257782, "start": 45, "tag": "NAME", "value": "Taylor Siviter" } ]
test/testExample.coffee
siviter-t/lampyridae.coffee
4
# @file testAll.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. require 'particle/firefly' describe 'Testing an example', -> canvas = null before (done) -> canvas = new Lampyridae.Canvas 'world' Lampyridae.Firefly::speedMax = 10 # Lampyridae.Firefly::enableGlow = true # Lampyridae.Firefly::glowFactor = 10 numOfBugs = 5 bugs = [] createBugs = () -> for i in [0...numOfBugs] bug = new Lampyridae.Firefly canvas, {bound: "periodic"} bugs.push bug return update = () -> bugs[i].update() for i in [0...numOfBugs] return time = 10000 randBlendOn = true randBlend = () => idx = Math.round(Lampyridae.rand(0, (Lampyridae.Draw::blendTypes.length) - 1)) t = Lampyridae.Draw::blendTypes[idx] canvas.draw.setGlobalBlending t # Lampyridae.Log.out "Blending = #{t}" if randBlendOn then canvas.schedule time, -> randBlend() createBugs() canvas.addUpdate canvas.draw.clear canvas.addUpdate update canvas.animate() # canvas.schedule 5000, -> canvas.pause() # canvas.schedule 6000, -> Lampyridae.Firefly::opacity = 0.01 # canvas.schedule 6000, -> Lampyridae.Firefly::hueMin = 240 # canvas.schedule 6000, -> Lampyridae.Firefly::hueMax = 360 # canvas.schedule 6000, -> Lampyridae.Firefly::radiusMax = 50 # canvas.schedule 6500, -> createBugs() # canvas.schedule 6500, -> numOfBugs = 50 # canvas.schedule 7000, -> canvas.pause() # canvas.schedule 8000, => randBlend() # canvas.schedule 8000, -> canvas.draw.setGlobalBlending "destination-out" # canvas.schedule 10000, -> canvas.removeUpdate canvas.draw.clear done() it 'A <canvas> tag should exist', -> should.exist document.getElementById('world') it 'A Canvas object should be attached to the <canvas> tag', -> canvas.element.should.equal document.getElementById('world') it 'and should have a drawable 2d context', -> canvas.has2DContext().should.equal true
22673
# @file testAll.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. require 'particle/firefly' describe 'Testing an example', -> canvas = null before (done) -> canvas = new Lampyridae.Canvas 'world' Lampyridae.Firefly::speedMax = 10 # Lampyridae.Firefly::enableGlow = true # Lampyridae.Firefly::glowFactor = 10 numOfBugs = 5 bugs = [] createBugs = () -> for i in [0...numOfBugs] bug = new Lampyridae.Firefly canvas, {bound: "periodic"} bugs.push bug return update = () -> bugs[i].update() for i in [0...numOfBugs] return time = 10000 randBlendOn = true randBlend = () => idx = Math.round(Lampyridae.rand(0, (Lampyridae.Draw::blendTypes.length) - 1)) t = Lampyridae.Draw::blendTypes[idx] canvas.draw.setGlobalBlending t # Lampyridae.Log.out "Blending = #{t}" if randBlendOn then canvas.schedule time, -> randBlend() createBugs() canvas.addUpdate canvas.draw.clear canvas.addUpdate update canvas.animate() # canvas.schedule 5000, -> canvas.pause() # canvas.schedule 6000, -> Lampyridae.Firefly::opacity = 0.01 # canvas.schedule 6000, -> Lampyridae.Firefly::hueMin = 240 # canvas.schedule 6000, -> Lampyridae.Firefly::hueMax = 360 # canvas.schedule 6000, -> Lampyridae.Firefly::radiusMax = 50 # canvas.schedule 6500, -> createBugs() # canvas.schedule 6500, -> numOfBugs = 50 # canvas.schedule 7000, -> canvas.pause() # canvas.schedule 8000, => randBlend() # canvas.schedule 8000, -> canvas.draw.setGlobalBlending "destination-out" # canvas.schedule 10000, -> canvas.removeUpdate canvas.draw.clear done() it 'A <canvas> tag should exist', -> should.exist document.getElementById('world') it 'A Canvas object should be attached to the <canvas> tag', -> canvas.element.should.equal document.getElementById('world') it 'and should have a drawable 2d context', -> canvas.has2DContext().should.equal true
true
# @file testAll.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. require 'particle/firefly' describe 'Testing an example', -> canvas = null before (done) -> canvas = new Lampyridae.Canvas 'world' Lampyridae.Firefly::speedMax = 10 # Lampyridae.Firefly::enableGlow = true # Lampyridae.Firefly::glowFactor = 10 numOfBugs = 5 bugs = [] createBugs = () -> for i in [0...numOfBugs] bug = new Lampyridae.Firefly canvas, {bound: "periodic"} bugs.push bug return update = () -> bugs[i].update() for i in [0...numOfBugs] return time = 10000 randBlendOn = true randBlend = () => idx = Math.round(Lampyridae.rand(0, (Lampyridae.Draw::blendTypes.length) - 1)) t = Lampyridae.Draw::blendTypes[idx] canvas.draw.setGlobalBlending t # Lampyridae.Log.out "Blending = #{t}" if randBlendOn then canvas.schedule time, -> randBlend() createBugs() canvas.addUpdate canvas.draw.clear canvas.addUpdate update canvas.animate() # canvas.schedule 5000, -> canvas.pause() # canvas.schedule 6000, -> Lampyridae.Firefly::opacity = 0.01 # canvas.schedule 6000, -> Lampyridae.Firefly::hueMin = 240 # canvas.schedule 6000, -> Lampyridae.Firefly::hueMax = 360 # canvas.schedule 6000, -> Lampyridae.Firefly::radiusMax = 50 # canvas.schedule 6500, -> createBugs() # canvas.schedule 6500, -> numOfBugs = 50 # canvas.schedule 7000, -> canvas.pause() # canvas.schedule 8000, => randBlend() # canvas.schedule 8000, -> canvas.draw.setGlobalBlending "destination-out" # canvas.schedule 10000, -> canvas.removeUpdate canvas.draw.clear done() it 'A <canvas> tag should exist', -> should.exist document.getElementById('world') it 'A Canvas object should be attached to the <canvas> tag', -> canvas.element.should.equal document.getElementById('world') it 'and should have a drawable 2d context', -> canvas.has2DContext().should.equal true
[ { "context": "malsListData = [\n id: 1, animal: 'tiger', name: 'Vee'\n,\n id: 2, animal: 'lion', name: 'Simba'\n,\n id:", "end": 70, "score": 0.7999870181083679, "start": 67, "tag": "NAME", "value": "Vee" }, { "context": "r', name: 'Vee'\n,\n id: 2, animal: 'lion', name: 'Simba'\...
exercises/08.fetching.cjsx
soyjavi/react-kitchensink
1
"use strict" animalsListData = [ id: 1, animal: 'tiger', name: 'Vee' , id: 2, animal: 'lion', name: 'Simba' , id: 3, animal: 'dog', name: 'Buck' , id: 4, animal: 'sealion', name: 'Seel' ] AnimalsList = React.createClass getInitialState: -> animals: [] componentDidMount: -> @_fetchAsync() render: -> if @state.animals.length is 0 <div> No animals! <br /> <a href="#fetch" onClick={@handleFetchClick}>Fetch</a> </div> else <div> <ul> { for animal, index in @state.animals <li key={index}>{animal.name} the {animal.animal}</li> } </ul> <a href="#reset" onClick={@handleResetClick}>Reset</a> <a href="#reset" onClick={@handlePushClick}>Push</a> </div> handleResetClick: (event) -> event.preventDefault() @setState animals: [] handlePushClick: (event) -> event.preventDefault() @state.animals.push id: 5, animal: 'cat', name: 'Dexter' @setState @state.animals handleFetchClick: (event) -> event.preventDefault() @_fetchAsync() _fetchAsync: -> setTimeout (=> @setState animals: animalsListData), 2000 React.render <AnimalsList />, document.getElementById('08-fetching')
207842
"use strict" animalsListData = [ id: 1, animal: 'tiger', name: '<NAME>' , id: 2, animal: 'lion', name: '<NAME>' , id: 3, animal: 'dog', name: '<NAME>' , id: 4, animal: 'sealion', name: '<NAME>el' ] AnimalsList = React.createClass getInitialState: -> animals: [] componentDidMount: -> @_fetchAsync() render: -> if @state.animals.length is 0 <div> No animals! <br /> <a href="#fetch" onClick={@handleFetchClick}>Fetch</a> </div> else <div> <ul> { for animal, index in @state.animals <li key={index}>{animal.name} the {animal.animal}</li> } </ul> <a href="#reset" onClick={@handleResetClick}>Reset</a> <a href="#reset" onClick={@handlePushClick}>Push</a> </div> handleResetClick: (event) -> event.preventDefault() @setState animals: [] handlePushClick: (event) -> event.preventDefault() @state.animals.push id: 5, animal: 'cat', name: '<NAME>' @setState @state.animals handleFetchClick: (event) -> event.preventDefault() @_fetchAsync() _fetchAsync: -> setTimeout (=> @setState animals: animalsListData), 2000 React.render <AnimalsList />, document.getElementById('08-fetching')
true
"use strict" animalsListData = [ id: 1, animal: 'tiger', name: 'PI:NAME:<NAME>END_PI' , id: 2, animal: 'lion', name: 'PI:NAME:<NAME>END_PI' , id: 3, animal: 'dog', name: 'PI:NAME:<NAME>END_PI' , id: 4, animal: 'sealion', name: 'PI:NAME:<NAME>END_PIel' ] AnimalsList = React.createClass getInitialState: -> animals: [] componentDidMount: -> @_fetchAsync() render: -> if @state.animals.length is 0 <div> No animals! <br /> <a href="#fetch" onClick={@handleFetchClick}>Fetch</a> </div> else <div> <ul> { for animal, index in @state.animals <li key={index}>{animal.name} the {animal.animal}</li> } </ul> <a href="#reset" onClick={@handleResetClick}>Reset</a> <a href="#reset" onClick={@handlePushClick}>Push</a> </div> handleResetClick: (event) -> event.preventDefault() @setState animals: [] handlePushClick: (event) -> event.preventDefault() @state.animals.push id: 5, animal: 'cat', name: 'PI:NAME:<NAME>END_PI' @setState @state.animals handleFetchClick: (event) -> event.preventDefault() @_fetchAsync() _fetchAsync: -> setTimeout (=> @setState animals: animalsListData), 2000 React.render <AnimalsList />, document.getElementById('08-fetching')
[ { "context": "memberId\n\n ContactItem\n key: _memberId\n _teamId: @props._teamId\n ", "end": 850, "score": 0.5145905017852783, "start": 844, "tag": "KEY", "value": "member" } ]
talk-web/client/app/group-details.coffee
ikingye/talk-os
3,084
React = require 'react' cx = require 'classnames' Immutable = require 'immutable' orders = require '../util/orders' lang = require '../locales/lang' Permission = require '../module/permission' ContactItem = React.createFactory require './contact-item' { div, span, button } = React.DOM T = React.PropTypes l = lang.getText module.exports = React.createClass displayName: 'group-details' propTypes: _teamId: T.string.isRequired group: T.instanceOf(Immutable.Map).isRequired contacts: T.instanceOf(Immutable.List).isRequired render: -> div className: 'group-details flex-vert', div className: 'list thin-scroll', @props.group.get('_memberIds').map (_memberId) => member = @props.contacts.find (contact) -> contact.get('_id') is _memberId ContactItem key: _memberId _teamId: @props._teamId contact: member showAction: false
181363
React = require 'react' cx = require 'classnames' Immutable = require 'immutable' orders = require '../util/orders' lang = require '../locales/lang' Permission = require '../module/permission' ContactItem = React.createFactory require './contact-item' { div, span, button } = React.DOM T = React.PropTypes l = lang.getText module.exports = React.createClass displayName: 'group-details' propTypes: _teamId: T.string.isRequired group: T.instanceOf(Immutable.Map).isRequired contacts: T.instanceOf(Immutable.List).isRequired render: -> div className: 'group-details flex-vert', div className: 'list thin-scroll', @props.group.get('_memberIds').map (_memberId) => member = @props.contacts.find (contact) -> contact.get('_id') is _memberId ContactItem key: _<KEY>Id _teamId: @props._teamId contact: member showAction: false
true
React = require 'react' cx = require 'classnames' Immutable = require 'immutable' orders = require '../util/orders' lang = require '../locales/lang' Permission = require '../module/permission' ContactItem = React.createFactory require './contact-item' { div, span, button } = React.DOM T = React.PropTypes l = lang.getText module.exports = React.createClass displayName: 'group-details' propTypes: _teamId: T.string.isRequired group: T.instanceOf(Immutable.Map).isRequired contacts: T.instanceOf(Immutable.List).isRequired render: -> div className: 'group-details flex-vert', div className: 'list thin-scroll', @props.group.get('_memberIds').map (_memberId) => member = @props.contacts.find (contact) -> contact.get('_id') is _memberId ContactItem key: _PI:KEY:<KEY>END_PIId _teamId: @props._teamId contact: member showAction: false
[ { "context": "e-break-on-single-newline': ->\n keyPath = 'dyndoc-viewer.breakOnSingleNewline'\n atom.config.set(keyPath,!atom.config.get", "end": 2358, "score": 0.9970970153808594, "start": 2324, "tag": "KEY", "value": "dyndoc-viewer.breakOnSingleNewline" } ]
lib/main.coffee
rcqls/atom-dyndoc-viewer
0
url = require 'url' path = require 'path' fs = require 'fs' dyndoc_viewer = null DyndocViewer = require './dyndoc-viewer' #null # Defer until used rendererCoffee = require './render-coffee' rendererDyndoc = require './render-dyndoc' DyndocRunner = require './dyndoc-runner' #rendererDyndoc = null # Defer until user choose mode local or server createDyndocViewer = (state) -> DyndocViewer ?= require './dyndoc-viewer' dyndoc_viewer = new DyndocViewer(state) isDyndocViewer = (object) -> DyndocViewer ?= require './dyndoc-viewer' object instanceof DyndocViewer atom.deserializers.add name: 'DyndocViewer' deserialize: (state) -> createDyndocViewer(state) if state.constructor is Object module.exports = config: dyndoc: type: 'string' default: 'local' # or 'server' dyndocHome: type: 'string' default: if fs.existsSync(path.join process.env["HOME"],".dyndoc_home") then String(fs.readFileSync(path.join process.env["HOME"],".dyndoc_home")).trim() else path.join process.env["HOME"],"dyndoc" addToPath: type: 'string' default: '/usr/local/bin:' + path.join(process.env["HOME"],"bin") # you can add anoter path with ":" localServer: type: 'boolean' default: true localServerUrl: type: 'string' default: 'localhost' localServerPort: type: 'integer' default: 7777 remoteServerUrl: type: 'string' default: 'sagag6.upmf-grenoble.fr' remoteServerPort: type: 'integer' default: 5555 breakOnSingleNewline: type: 'boolean' default: false liveUpdate: type: 'boolean' default: true grammars: type: 'array' default: [ 'source.dyndoc' 'source.gfm' 'text.html.basic' 'text.html.textile' ] activate: -> atom.commands.add 'atom-workspace', 'dyndoc-viewer:eval': => @eval() 'dyndoc-viewer:compile': => @compile() 'dyndoc-viewer:atom-dyndoc': => @atomDyndoc() 'dyndoc-viewer:coffee': => @coffee() 'dyndoc-viewer:toggle': => @toggle() 'dyndoc-viewer:start': => @startServer() 'dyndoc-viewer:kill': => @killServer() 'dyndoc-viewer:toggle-break-on-single-newline': -> keyPath = 'dyndoc-viewer.breakOnSingleNewline' atom.config.set(keyPath,!atom.config.get(keyPath)) #atom.workspaceView.on 'dyndoc-viewer:preview-file', (event) => # @previewFile(event) atom.workspace.registerOpener (uriToOpen) -> try {protocol, host, pathname} = url.parse(uriToOpen) catch error return return unless protocol is 'dyndoc-viewer:' try pathname = decodeURI(pathname) if pathname catch error return if host is 'editor' createDyndocViewer(editorId: pathname.substring(1)) else createDyndocViewer(filePath: pathname) DyndocRunner.start() deactivate: -> DyndocRunner.stop() coffee: -> selection = atom.workspace.getActiveEditor().getSelection() text = selection.getText() console.log rendererCoffee.eval text atomDyndoc: -> selection = atom.workspace.getActiveEditor().getSelection() text = selection.getText() if text == "" text = atom.workspace.getActiveEditor().getText() #util = require 'util' text='[#require]Tools/Atom\n[#main][#>]{#atomInit#}\n'+text ##console.log "text: "+text text=text.replace /\#\{/g,"__AROBAS_ATOM__{" rendererDyndoc.eval text, atom.workspace.getActiveEditor().getPath(), (error, content) -> if error console.log "err: "+content else #console.log "before:" + content content=content.replace /__DIESE_ATOM__/g, '#' content=content.replace /__AROBAS_ATOM__\{/g, '#{' # console.log "echo:" + content #fs = require "fs" #fs.writeFile "/Users/remy/test_atom.coffee", content, (error) -> # console.error("Error writing file", error) if error rendererCoffee.eval content eval: -> return unless dyndoc_viewer selection = atom.workspace.getActiveEditor().getSelection() text = selection.getText() if text == "" text = atom.workspace.getActiveEditor().getText() dyndoc_viewer.render(text) #res = renderer.toText text, "toto", (error, content) -> # if error # console.log "err: "+content # else # console.log "echo:" + content compile: -> dyn_file = atom.workspace.activePaneItem.getPath() console.log("compile dyn_file:"+dyn_file) DyndocRunner.compile dyn_file startServer: -> DyndocRunner.start() killServer: -> DyndocRunner.stop() toggle: -> if isDyndocViewer(atom.workspace.activePaneItem) atom.workspace.destroyActivePaneItem() return editor = atom.workspace.getActiveEditor() return unless editor? #grammars = atom.config.get('dyndoc-viewer.grammars') ? [] #return unless editor.getGrammar().scopeName in grammars @addPreviewForEditor(editor) unless @removePreviewForEditor(editor) uriForEditor: (editor) -> "dyndoc-viewer://editor/#{editor.id}" removePreviewForEditor: (editor) -> uri = @uriForEditor(editor) console.log(uri) previewPane = atom.workspace.paneForUri(uri) console.log("preview-pane: "+previewPane) if previewPane? previewPane.destroyItem(previewPane.itemForUri(uri)) true else false addPreviewForEditor: (editor) -> uri = @uriForEditor(editor) previousActivePane = atom.workspace.getActivePane() atom.workspace.open(uri, split: 'right', searchAllPanes: true).done (DyndocViewer) -> if isDyndocViewer(DyndocViewer) #DyndocViewer.renderDyndoc() previousActivePane.activate() # previewFile: ({target}) -> # filePath = $(target).view()?.getPath?() #Maybe to replace with: filePath = target.dataset.path # return unless filePath # for editor in atom.workspace.getEditors() when editor.getPath() is filePath # @addPreviewForEditor(editor) # return # atom.workspace.open "dyndoc-viewer://#{encodeURI(filePath)}", searchAllPanes: true
208657
url = require 'url' path = require 'path' fs = require 'fs' dyndoc_viewer = null DyndocViewer = require './dyndoc-viewer' #null # Defer until used rendererCoffee = require './render-coffee' rendererDyndoc = require './render-dyndoc' DyndocRunner = require './dyndoc-runner' #rendererDyndoc = null # Defer until user choose mode local or server createDyndocViewer = (state) -> DyndocViewer ?= require './dyndoc-viewer' dyndoc_viewer = new DyndocViewer(state) isDyndocViewer = (object) -> DyndocViewer ?= require './dyndoc-viewer' object instanceof DyndocViewer atom.deserializers.add name: 'DyndocViewer' deserialize: (state) -> createDyndocViewer(state) if state.constructor is Object module.exports = config: dyndoc: type: 'string' default: 'local' # or 'server' dyndocHome: type: 'string' default: if fs.existsSync(path.join process.env["HOME"],".dyndoc_home") then String(fs.readFileSync(path.join process.env["HOME"],".dyndoc_home")).trim() else path.join process.env["HOME"],"dyndoc" addToPath: type: 'string' default: '/usr/local/bin:' + path.join(process.env["HOME"],"bin") # you can add anoter path with ":" localServer: type: 'boolean' default: true localServerUrl: type: 'string' default: 'localhost' localServerPort: type: 'integer' default: 7777 remoteServerUrl: type: 'string' default: 'sagag6.upmf-grenoble.fr' remoteServerPort: type: 'integer' default: 5555 breakOnSingleNewline: type: 'boolean' default: false liveUpdate: type: 'boolean' default: true grammars: type: 'array' default: [ 'source.dyndoc' 'source.gfm' 'text.html.basic' 'text.html.textile' ] activate: -> atom.commands.add 'atom-workspace', 'dyndoc-viewer:eval': => @eval() 'dyndoc-viewer:compile': => @compile() 'dyndoc-viewer:atom-dyndoc': => @atomDyndoc() 'dyndoc-viewer:coffee': => @coffee() 'dyndoc-viewer:toggle': => @toggle() 'dyndoc-viewer:start': => @startServer() 'dyndoc-viewer:kill': => @killServer() 'dyndoc-viewer:toggle-break-on-single-newline': -> keyPath = '<KEY>' atom.config.set(keyPath,!atom.config.get(keyPath)) #atom.workspaceView.on 'dyndoc-viewer:preview-file', (event) => # @previewFile(event) atom.workspace.registerOpener (uriToOpen) -> try {protocol, host, pathname} = url.parse(uriToOpen) catch error return return unless protocol is 'dyndoc-viewer:' try pathname = decodeURI(pathname) if pathname catch error return if host is 'editor' createDyndocViewer(editorId: pathname.substring(1)) else createDyndocViewer(filePath: pathname) DyndocRunner.start() deactivate: -> DyndocRunner.stop() coffee: -> selection = atom.workspace.getActiveEditor().getSelection() text = selection.getText() console.log rendererCoffee.eval text atomDyndoc: -> selection = atom.workspace.getActiveEditor().getSelection() text = selection.getText() if text == "" text = atom.workspace.getActiveEditor().getText() #util = require 'util' text='[#require]Tools/Atom\n[#main][#>]{#atomInit#}\n'+text ##console.log "text: "+text text=text.replace /\#\{/g,"__AROBAS_ATOM__{" rendererDyndoc.eval text, atom.workspace.getActiveEditor().getPath(), (error, content) -> if error console.log "err: "+content else #console.log "before:" + content content=content.replace /__DIESE_ATOM__/g, '#' content=content.replace /__AROBAS_ATOM__\{/g, '#{' # console.log "echo:" + content #fs = require "fs" #fs.writeFile "/Users/remy/test_atom.coffee", content, (error) -> # console.error("Error writing file", error) if error rendererCoffee.eval content eval: -> return unless dyndoc_viewer selection = atom.workspace.getActiveEditor().getSelection() text = selection.getText() if text == "" text = atom.workspace.getActiveEditor().getText() dyndoc_viewer.render(text) #res = renderer.toText text, "toto", (error, content) -> # if error # console.log "err: "+content # else # console.log "echo:" + content compile: -> dyn_file = atom.workspace.activePaneItem.getPath() console.log("compile dyn_file:"+dyn_file) DyndocRunner.compile dyn_file startServer: -> DyndocRunner.start() killServer: -> DyndocRunner.stop() toggle: -> if isDyndocViewer(atom.workspace.activePaneItem) atom.workspace.destroyActivePaneItem() return editor = atom.workspace.getActiveEditor() return unless editor? #grammars = atom.config.get('dyndoc-viewer.grammars') ? [] #return unless editor.getGrammar().scopeName in grammars @addPreviewForEditor(editor) unless @removePreviewForEditor(editor) uriForEditor: (editor) -> "dyndoc-viewer://editor/#{editor.id}" removePreviewForEditor: (editor) -> uri = @uriForEditor(editor) console.log(uri) previewPane = atom.workspace.paneForUri(uri) console.log("preview-pane: "+previewPane) if previewPane? previewPane.destroyItem(previewPane.itemForUri(uri)) true else false addPreviewForEditor: (editor) -> uri = @uriForEditor(editor) previousActivePane = atom.workspace.getActivePane() atom.workspace.open(uri, split: 'right', searchAllPanes: true).done (DyndocViewer) -> if isDyndocViewer(DyndocViewer) #DyndocViewer.renderDyndoc() previousActivePane.activate() # previewFile: ({target}) -> # filePath = $(target).view()?.getPath?() #Maybe to replace with: filePath = target.dataset.path # return unless filePath # for editor in atom.workspace.getEditors() when editor.getPath() is filePath # @addPreviewForEditor(editor) # return # atom.workspace.open "dyndoc-viewer://#{encodeURI(filePath)}", searchAllPanes: true
true
url = require 'url' path = require 'path' fs = require 'fs' dyndoc_viewer = null DyndocViewer = require './dyndoc-viewer' #null # Defer until used rendererCoffee = require './render-coffee' rendererDyndoc = require './render-dyndoc' DyndocRunner = require './dyndoc-runner' #rendererDyndoc = null # Defer until user choose mode local or server createDyndocViewer = (state) -> DyndocViewer ?= require './dyndoc-viewer' dyndoc_viewer = new DyndocViewer(state) isDyndocViewer = (object) -> DyndocViewer ?= require './dyndoc-viewer' object instanceof DyndocViewer atom.deserializers.add name: 'DyndocViewer' deserialize: (state) -> createDyndocViewer(state) if state.constructor is Object module.exports = config: dyndoc: type: 'string' default: 'local' # or 'server' dyndocHome: type: 'string' default: if fs.existsSync(path.join process.env["HOME"],".dyndoc_home") then String(fs.readFileSync(path.join process.env["HOME"],".dyndoc_home")).trim() else path.join process.env["HOME"],"dyndoc" addToPath: type: 'string' default: '/usr/local/bin:' + path.join(process.env["HOME"],"bin") # you can add anoter path with ":" localServer: type: 'boolean' default: true localServerUrl: type: 'string' default: 'localhost' localServerPort: type: 'integer' default: 7777 remoteServerUrl: type: 'string' default: 'sagag6.upmf-grenoble.fr' remoteServerPort: type: 'integer' default: 5555 breakOnSingleNewline: type: 'boolean' default: false liveUpdate: type: 'boolean' default: true grammars: type: 'array' default: [ 'source.dyndoc' 'source.gfm' 'text.html.basic' 'text.html.textile' ] activate: -> atom.commands.add 'atom-workspace', 'dyndoc-viewer:eval': => @eval() 'dyndoc-viewer:compile': => @compile() 'dyndoc-viewer:atom-dyndoc': => @atomDyndoc() 'dyndoc-viewer:coffee': => @coffee() 'dyndoc-viewer:toggle': => @toggle() 'dyndoc-viewer:start': => @startServer() 'dyndoc-viewer:kill': => @killServer() 'dyndoc-viewer:toggle-break-on-single-newline': -> keyPath = 'PI:KEY:<KEY>END_PI' atom.config.set(keyPath,!atom.config.get(keyPath)) #atom.workspaceView.on 'dyndoc-viewer:preview-file', (event) => # @previewFile(event) atom.workspace.registerOpener (uriToOpen) -> try {protocol, host, pathname} = url.parse(uriToOpen) catch error return return unless protocol is 'dyndoc-viewer:' try pathname = decodeURI(pathname) if pathname catch error return if host is 'editor' createDyndocViewer(editorId: pathname.substring(1)) else createDyndocViewer(filePath: pathname) DyndocRunner.start() deactivate: -> DyndocRunner.stop() coffee: -> selection = atom.workspace.getActiveEditor().getSelection() text = selection.getText() console.log rendererCoffee.eval text atomDyndoc: -> selection = atom.workspace.getActiveEditor().getSelection() text = selection.getText() if text == "" text = atom.workspace.getActiveEditor().getText() #util = require 'util' text='[#require]Tools/Atom\n[#main][#>]{#atomInit#}\n'+text ##console.log "text: "+text text=text.replace /\#\{/g,"__AROBAS_ATOM__{" rendererDyndoc.eval text, atom.workspace.getActiveEditor().getPath(), (error, content) -> if error console.log "err: "+content else #console.log "before:" + content content=content.replace /__DIESE_ATOM__/g, '#' content=content.replace /__AROBAS_ATOM__\{/g, '#{' # console.log "echo:" + content #fs = require "fs" #fs.writeFile "/Users/remy/test_atom.coffee", content, (error) -> # console.error("Error writing file", error) if error rendererCoffee.eval content eval: -> return unless dyndoc_viewer selection = atom.workspace.getActiveEditor().getSelection() text = selection.getText() if text == "" text = atom.workspace.getActiveEditor().getText() dyndoc_viewer.render(text) #res = renderer.toText text, "toto", (error, content) -> # if error # console.log "err: "+content # else # console.log "echo:" + content compile: -> dyn_file = atom.workspace.activePaneItem.getPath() console.log("compile dyn_file:"+dyn_file) DyndocRunner.compile dyn_file startServer: -> DyndocRunner.start() killServer: -> DyndocRunner.stop() toggle: -> if isDyndocViewer(atom.workspace.activePaneItem) atom.workspace.destroyActivePaneItem() return editor = atom.workspace.getActiveEditor() return unless editor? #grammars = atom.config.get('dyndoc-viewer.grammars') ? [] #return unless editor.getGrammar().scopeName in grammars @addPreviewForEditor(editor) unless @removePreviewForEditor(editor) uriForEditor: (editor) -> "dyndoc-viewer://editor/#{editor.id}" removePreviewForEditor: (editor) -> uri = @uriForEditor(editor) console.log(uri) previewPane = atom.workspace.paneForUri(uri) console.log("preview-pane: "+previewPane) if previewPane? previewPane.destroyItem(previewPane.itemForUri(uri)) true else false addPreviewForEditor: (editor) -> uri = @uriForEditor(editor) previousActivePane = atom.workspace.getActivePane() atom.workspace.open(uri, split: 'right', searchAllPanes: true).done (DyndocViewer) -> if isDyndocViewer(DyndocViewer) #DyndocViewer.renderDyndoc() previousActivePane.activate() # previewFile: ({target}) -> # filePath = $(target).view()?.getPath?() #Maybe to replace with: filePath = target.dataset.path # return unless filePath # for editor in atom.workspace.getEditors() when editor.getPath() is filePath # @addPreviewForEditor(editor) # return # atom.workspace.open "dyndoc-viewer://#{encodeURI(filePath)}", searchAllPanes: true
[ { "context": "\n# }\n#\n\nclass SuggestedTriggerRepository\n KEY = 'suggested-triggers'\n\n constructor: (@brain) ->\n @cache = []\n ", "end": 186, "score": 0.9027900695800781, "start": 168, "tag": "KEY", "value": "suggested-triggers" } ]
support/suggested_trigger_repository.coffee
lawsonjt/liona
9
# # record structure # { # id: 'x3jrja', # name: '!foo', # phrase: '...', # created_at: ..., # author: '...' # } # class SuggestedTriggerRepository KEY = 'suggested-triggers' constructor: (@brain) -> @cache = [] @brain.on 'loaded', => braindata = brain.data._private[KEY] @cache = braindata if braindata find: (key) -> @all().filter((u) -> u.id.toLowerCase() is key.toLowerCase())?[0] save: (data) -> @cache = @all data.name @cache.push data @set @cache data create: (name, phrase, user) -> @save @new name, phrase, user new: (name, phrase, user) -> name: name, created_at: Date.now(), phrase: phrase, author: user, id: Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 6) remove: (key) -> @set @all key all: (without) -> without && (@cache.filter (u) -> u.id.toLowerCase() isnt without.toLowerCase()) || @cache set: (data) -> @brain.set KEY, data module.exports = SuggestedTriggerRepository
179244
# # record structure # { # id: 'x3jrja', # name: '!foo', # phrase: '...', # created_at: ..., # author: '...' # } # class SuggestedTriggerRepository KEY = '<KEY>' constructor: (@brain) -> @cache = [] @brain.on 'loaded', => braindata = brain.data._private[KEY] @cache = braindata if braindata find: (key) -> @all().filter((u) -> u.id.toLowerCase() is key.toLowerCase())?[0] save: (data) -> @cache = @all data.name @cache.push data @set @cache data create: (name, phrase, user) -> @save @new name, phrase, user new: (name, phrase, user) -> name: name, created_at: Date.now(), phrase: phrase, author: user, id: Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 6) remove: (key) -> @set @all key all: (without) -> without && (@cache.filter (u) -> u.id.toLowerCase() isnt without.toLowerCase()) || @cache set: (data) -> @brain.set KEY, data module.exports = SuggestedTriggerRepository
true
# # record structure # { # id: 'x3jrja', # name: '!foo', # phrase: '...', # created_at: ..., # author: '...' # } # class SuggestedTriggerRepository KEY = 'PI:KEY:<KEY>END_PI' constructor: (@brain) -> @cache = [] @brain.on 'loaded', => braindata = brain.data._private[KEY] @cache = braindata if braindata find: (key) -> @all().filter((u) -> u.id.toLowerCase() is key.toLowerCase())?[0] save: (data) -> @cache = @all data.name @cache.push data @set @cache data create: (name, phrase, user) -> @save @new name, phrase, user new: (name, phrase, user) -> name: name, created_at: Date.now(), phrase: phrase, author: user, id: Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 6) remove: (key) -> @set @all key all: (without) -> without && (@cache.filter (u) -> u.id.toLowerCase() isnt without.toLowerCase()) || @cache set: (data) -> @brain.set KEY, data module.exports = SuggestedTriggerRepository
[ { "context": "text' className={userEmailClassName} placeholder='mail@example.com' value={inviteInput.get 'email'} onChange={@props", "end": 672, "score": 0.999904990196228, "start": 656, "tag": "EMAIL", "value": "mail@example.com" }, { "context": "nformationLabel = ({ canEdit }) ->\n...
client/home/lib/myteam/components/hometeamsendinvites/view.coffee
lionheart1022/koding
0
kd = require 'kd' React = require 'app/react' List = require 'app/components/list' CheckBox = require 'app/components/common/checkbox' module.exports = class HomeTeamSendInvitesView extends React.Component numberOfSections: -> 1 numberOfRowsInSection: -> @props.inputValues?.size or 0 renderSectionHeaderAtIndex: -> null renderRowAtIndex: (sectionIndex, rowIndex) -> inviteInput = @props.inputValues.toList().get(rowIndex) checked = inviteInput.get('canEdit') userEmailClassName = 'kdinput text user-email' <div className='kdview invite-inputs'> <input type='text' className={userEmailClassName} placeholder='mail@example.com' value={inviteInput.get 'email'} onChange={@props.onInputChange.bind(this, rowIndex, 'email')} /> <input type='text' className='kdinput text firstname' placeholder='Optional' value={inviteInput.get 'firstName'} onChange={@props.onInputChange.bind(this, rowIndex, 'firstName')}/> <input type='text' className='kdinput text lastname' placeholder='Optional' value={inviteInput.get 'lastName'} onChange={@props.onInputChange.bind(this, rowIndex, 'lastName')}/> <CheckBoxOrEmpty canEdit={@props.canEdit} checked={checked} onChange={@props.onInputChange.bind(this, rowIndex, 'canEdit')} onClick={@props.onInputChange.bind(null, rowIndex, 'canEdit', { target: { value: not checked}})}/> </div> renderEmptySectionAtIndex: -> <div> No data found</div> render: -> <div> <InformationLabel canEdit={@props.canEdit} /> <div className='input-wrapper'> <List numberOfSections={@bound 'numberOfSections'} numberOfRowsInSection={@bound 'numberOfRowsInSection'} renderSectionHeaderAtIndex={@bound 'renderSectionHeaderAtIndex'} renderRowAtIndex={@bound 'renderRowAtIndex'} renderEmptySectionAtIndex={@bound 'renderEmptySectionAtIndex'} /> </div> <fieldset className='HomeAppView--ActionBar'> <GenericButton title='SEND INVITES' className={'custom-link-view HomeAppView--button primary fr'} callback={@props.onSendInvites}/> <GenericButton title='UPLOAD CSV' className={'custom-link-view HomeAppView--button ft'} callback={@props.onUploadCSV} /> </fieldset> </div> CheckBoxOrEmpty = ({ canEdit, checked, onChange, onClick }) -> if canEdit <CheckBox checked={checked} onChange={onChange} onClick={onClick} /> else <div></div> InformationLabel = ({ canEdit }) -> lastname = 'Last Name' <div className='information'> <div className='invite-labels'> <label>Email</label> <label>First Name</label> <label> <span className='lastname'>Last Name</span> <AdminLabel canEdit={canEdit} /> </label> </div> </div> AdminLabel = ({ canEdit }) -> if canEdit then <span>Admin</span> else <span></span> GenericButton = ({ className, title, callback }) -> <a className={className} href='#' onClick={callback}> <span className='title'>{title}</span> </a>
64587
kd = require 'kd' React = require 'app/react' List = require 'app/components/list' CheckBox = require 'app/components/common/checkbox' module.exports = class HomeTeamSendInvitesView extends React.Component numberOfSections: -> 1 numberOfRowsInSection: -> @props.inputValues?.size or 0 renderSectionHeaderAtIndex: -> null renderRowAtIndex: (sectionIndex, rowIndex) -> inviteInput = @props.inputValues.toList().get(rowIndex) checked = inviteInput.get('canEdit') userEmailClassName = 'kdinput text user-email' <div className='kdview invite-inputs'> <input type='text' className={userEmailClassName} placeholder='<EMAIL>' value={inviteInput.get 'email'} onChange={@props.onInputChange.bind(this, rowIndex, 'email')} /> <input type='text' className='kdinput text firstname' placeholder='Optional' value={inviteInput.get 'firstName'} onChange={@props.onInputChange.bind(this, rowIndex, 'firstName')}/> <input type='text' className='kdinput text lastname' placeholder='Optional' value={inviteInput.get 'lastName'} onChange={@props.onInputChange.bind(this, rowIndex, 'lastName')}/> <CheckBoxOrEmpty canEdit={@props.canEdit} checked={checked} onChange={@props.onInputChange.bind(this, rowIndex, 'canEdit')} onClick={@props.onInputChange.bind(null, rowIndex, 'canEdit', { target: { value: not checked}})}/> </div> renderEmptySectionAtIndex: -> <div> No data found</div> render: -> <div> <InformationLabel canEdit={@props.canEdit} /> <div className='input-wrapper'> <List numberOfSections={@bound 'numberOfSections'} numberOfRowsInSection={@bound 'numberOfRowsInSection'} renderSectionHeaderAtIndex={@bound 'renderSectionHeaderAtIndex'} renderRowAtIndex={@bound 'renderRowAtIndex'} renderEmptySectionAtIndex={@bound 'renderEmptySectionAtIndex'} /> </div> <fieldset className='HomeAppView--ActionBar'> <GenericButton title='SEND INVITES' className={'custom-link-view HomeAppView--button primary fr'} callback={@props.onSendInvites}/> <GenericButton title='UPLOAD CSV' className={'custom-link-view HomeAppView--button ft'} callback={@props.onUploadCSV} /> </fieldset> </div> CheckBoxOrEmpty = ({ canEdit, checked, onChange, onClick }) -> if canEdit <CheckBox checked={checked} onChange={onChange} onClick={onClick} /> else <div></div> InformationLabel = ({ canEdit }) -> lastname = '<NAME>' <div className='information'> <div className='invite-labels'> <label>Email</label> <label>First Name</label> <label> <span className='lastname'>Last Name</span> <AdminLabel canEdit={canEdit} /> </label> </div> </div> AdminLabel = ({ canEdit }) -> if canEdit then <span>Admin</span> else <span></span> GenericButton = ({ className, title, callback }) -> <a className={className} href='#' onClick={callback}> <span className='title'>{title}</span> </a>
true
kd = require 'kd' React = require 'app/react' List = require 'app/components/list' CheckBox = require 'app/components/common/checkbox' module.exports = class HomeTeamSendInvitesView extends React.Component numberOfSections: -> 1 numberOfRowsInSection: -> @props.inputValues?.size or 0 renderSectionHeaderAtIndex: -> null renderRowAtIndex: (sectionIndex, rowIndex) -> inviteInput = @props.inputValues.toList().get(rowIndex) checked = inviteInput.get('canEdit') userEmailClassName = 'kdinput text user-email' <div className='kdview invite-inputs'> <input type='text' className={userEmailClassName} placeholder='PI:EMAIL:<EMAIL>END_PI' value={inviteInput.get 'email'} onChange={@props.onInputChange.bind(this, rowIndex, 'email')} /> <input type='text' className='kdinput text firstname' placeholder='Optional' value={inviteInput.get 'firstName'} onChange={@props.onInputChange.bind(this, rowIndex, 'firstName')}/> <input type='text' className='kdinput text lastname' placeholder='Optional' value={inviteInput.get 'lastName'} onChange={@props.onInputChange.bind(this, rowIndex, 'lastName')}/> <CheckBoxOrEmpty canEdit={@props.canEdit} checked={checked} onChange={@props.onInputChange.bind(this, rowIndex, 'canEdit')} onClick={@props.onInputChange.bind(null, rowIndex, 'canEdit', { target: { value: not checked}})}/> </div> renderEmptySectionAtIndex: -> <div> No data found</div> render: -> <div> <InformationLabel canEdit={@props.canEdit} /> <div className='input-wrapper'> <List numberOfSections={@bound 'numberOfSections'} numberOfRowsInSection={@bound 'numberOfRowsInSection'} renderSectionHeaderAtIndex={@bound 'renderSectionHeaderAtIndex'} renderRowAtIndex={@bound 'renderRowAtIndex'} renderEmptySectionAtIndex={@bound 'renderEmptySectionAtIndex'} /> </div> <fieldset className='HomeAppView--ActionBar'> <GenericButton title='SEND INVITES' className={'custom-link-view HomeAppView--button primary fr'} callback={@props.onSendInvites}/> <GenericButton title='UPLOAD CSV' className={'custom-link-view HomeAppView--button ft'} callback={@props.onUploadCSV} /> </fieldset> </div> CheckBoxOrEmpty = ({ canEdit, checked, onChange, onClick }) -> if canEdit <CheckBox checked={checked} onChange={onChange} onClick={onClick} /> else <div></div> InformationLabel = ({ canEdit }) -> lastname = 'PI:NAME:<NAME>END_PI' <div className='information'> <div className='invite-labels'> <label>Email</label> <label>First Name</label> <label> <span className='lastname'>Last Name</span> <AdminLabel canEdit={canEdit} /> </label> </div> </div> AdminLabel = ({ canEdit }) -> if canEdit then <span>Admin</span> else <span></span> GenericButton = ({ className, title, callback }) -> <a className={className} href='#' onClick={callback}> <span className='title'>{title}</span> </a>
[ { "context": "t_key: 'prj1', client_id: 'id1', client_secret: 's1', props: {}}\n {project_key: 'prj2', client_i", "end": 857, "score": 0.6373029947280884, "start": 856, "tag": "KEY", "value": "1" }, { "context": "t_key: 'prj2', client_id: 'id2', client_secret: 's2', props: {}}\n...
src/spec/util.spec.coffee
sphereio/sphere-message-processing
0
Q = require 'q' {_} = require 'underscore' util = require '../lib/util' describe 'util.parseProjectsCredentials', -> mockCredentialsConfig = forProjectKey: (key) -> project_key: key client_id: "mock_client_id" client_secret: "mock_client_secret" it 'should return an empty array if input is undfined', () -> expect(util.parseProjectsCredentials(mockCredentialsConfig, undefined)).toEqual [] it 'should parse single element', () -> expect(util.parseProjectsCredentials(mockCredentialsConfig, "prj:id:secret")).toEqual [ {project_key: 'prj', client_id: 'id', client_secret: 'secret', props: {}} ] it 'should parse multiple elements', () -> expect(util.parseProjectsCredentials(mockCredentialsConfig, 'prj1:id1:s1,prj2:id2:s2')).toEqual [ {project_key: 'prj1', client_id: 'id1', client_secret: 's1', props: {}} {project_key: 'prj2', client_id: 'id2', client_secret: 's2', props: {}} ]
99478
Q = require 'q' {_} = require 'underscore' util = require '../lib/util' describe 'util.parseProjectsCredentials', -> mockCredentialsConfig = forProjectKey: (key) -> project_key: key client_id: "mock_client_id" client_secret: "mock_client_secret" it 'should return an empty array if input is undfined', () -> expect(util.parseProjectsCredentials(mockCredentialsConfig, undefined)).toEqual [] it 'should parse single element', () -> expect(util.parseProjectsCredentials(mockCredentialsConfig, "prj:id:secret")).toEqual [ {project_key: 'prj', client_id: 'id', client_secret: 'secret', props: {}} ] it 'should parse multiple elements', () -> expect(util.parseProjectsCredentials(mockCredentialsConfig, 'prj1:id1:s1,prj2:id2:s2')).toEqual [ {project_key: 'prj1', client_id: 'id1', client_secret: 's<KEY>', props: {}} {project_key: 'prj2', client_id: 'id2', client_secret: 's<KEY>', props: {}} ]
true
Q = require 'q' {_} = require 'underscore' util = require '../lib/util' describe 'util.parseProjectsCredentials', -> mockCredentialsConfig = forProjectKey: (key) -> project_key: key client_id: "mock_client_id" client_secret: "mock_client_secret" it 'should return an empty array if input is undfined', () -> expect(util.parseProjectsCredentials(mockCredentialsConfig, undefined)).toEqual [] it 'should parse single element', () -> expect(util.parseProjectsCredentials(mockCredentialsConfig, "prj:id:secret")).toEqual [ {project_key: 'prj', client_id: 'id', client_secret: 'secret', props: {}} ] it 'should parse multiple elements', () -> expect(util.parseProjectsCredentials(mockCredentialsConfig, 'prj1:id1:s1,prj2:id2:s2')).toEqual [ {project_key: 'prj1', client_id: 'id1', client_secret: 'sPI:KEY:<KEY>END_PI', props: {}} {project_key: 'prj2', client_id: 'id2', client_secret: 'sPI:KEY:<KEY>END_PI', props: {}} ]
[ { "context": "LaTeX and the Terminal.\n#\n# Copyright (C) 2014, William Stein\n#\n# This program is free software: you can red", "end": 217, "score": 0.9998446702957153, "start": 204, "tag": "NAME", "value": "William Stein" } ]
.sagemathcloud/console_server_child.coffee
febman/elastic-3D-model
0
############################################################################### # # SageMathCloud: A collaborative web-based interface to Sage, IPython, LaTeX and the Terminal. # # Copyright (C) 2014, William Stein # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################### pty = require 'pty.js' message = require 'message' {defaults, required} = require 'misc' {setrlimit} = require 'posix' process.on 'message', (opts, socket) -> opts = defaults opts, rows : required cols : required command : required args : required path : undefined term_opts = name : 'xterm' rows : opts.rows cols : opts.cols if opts.path? term_opts.cwd = opts.path if opts.home? term_opts.home = opts.home misc = require('misc') #console.log("about to pty.fork with: opts.command=#{opts.command}, opts.args=#{misc.to_json(opts.args)}, term_opts=#{misc.to_json(term_opts)}") term = pty.fork(opts.command, opts.args, term_opts) # See http://invisible-island.net/xterm/ctlseqs/ctlseqs.txt # CSI Ps ; Ps ; Ps t # CSI[4];[height];[width]t CSI = String.fromCharCode(0x9b) resize_sequence = undefined parse_resize = (data) -> i = data.indexOf('t') if i == -1 resize_sequence += data return data.length else # Got complete sequence s = (resize_sequence + data.slice(0,i)).slice(3) resize_sequence = undefined j = s.indexOf(';') if j != -1 rows = parseInt(s.slice(0,j)) cols = parseInt(s.slice(j+1)) term.resize(cols, rows) return i+1 CSI_code = (data) -> s = data.toString('ascii') if resize_sequence? start = 0 end = parse_resize(s) else i = s.lastIndexOf(CSI) if i != -1 resize_sequence = '' start = i end = start + parse_resize(s.slice(i)) if start? # skip data consumed in CSI data = data.slice(0,start) + data.slice(end+1) return data socket.on 'data', (data) -> data = CSI_code(data) term.write data term.on 'data', (data) -> socket.write data term.on 'exit', () -> socket.end() socket.on 'end', () -> # If the hub connection dies, there is no point in # letting this process continue running, since it can't send # its output anywhere. So we terminate. process.exit(1)
26740
############################################################################### # # SageMathCloud: A collaborative web-based interface to Sage, IPython, LaTeX and the Terminal. # # Copyright (C) 2014, <NAME> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################### pty = require 'pty.js' message = require 'message' {defaults, required} = require 'misc' {setrlimit} = require 'posix' process.on 'message', (opts, socket) -> opts = defaults opts, rows : required cols : required command : required args : required path : undefined term_opts = name : 'xterm' rows : opts.rows cols : opts.cols if opts.path? term_opts.cwd = opts.path if opts.home? term_opts.home = opts.home misc = require('misc') #console.log("about to pty.fork with: opts.command=#{opts.command}, opts.args=#{misc.to_json(opts.args)}, term_opts=#{misc.to_json(term_opts)}") term = pty.fork(opts.command, opts.args, term_opts) # See http://invisible-island.net/xterm/ctlseqs/ctlseqs.txt # CSI Ps ; Ps ; Ps t # CSI[4];[height];[width]t CSI = String.fromCharCode(0x9b) resize_sequence = undefined parse_resize = (data) -> i = data.indexOf('t') if i == -1 resize_sequence += data return data.length else # Got complete sequence s = (resize_sequence + data.slice(0,i)).slice(3) resize_sequence = undefined j = s.indexOf(';') if j != -1 rows = parseInt(s.slice(0,j)) cols = parseInt(s.slice(j+1)) term.resize(cols, rows) return i+1 CSI_code = (data) -> s = data.toString('ascii') if resize_sequence? start = 0 end = parse_resize(s) else i = s.lastIndexOf(CSI) if i != -1 resize_sequence = '' start = i end = start + parse_resize(s.slice(i)) if start? # skip data consumed in CSI data = data.slice(0,start) + data.slice(end+1) return data socket.on 'data', (data) -> data = CSI_code(data) term.write data term.on 'data', (data) -> socket.write data term.on 'exit', () -> socket.end() socket.on 'end', () -> # If the hub connection dies, there is no point in # letting this process continue running, since it can't send # its output anywhere. So we terminate. process.exit(1)
true
############################################################################### # # SageMathCloud: A collaborative web-based interface to Sage, IPython, LaTeX and the Terminal. # # Copyright (C) 2014, PI:NAME:<NAME>END_PI # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################### pty = require 'pty.js' message = require 'message' {defaults, required} = require 'misc' {setrlimit} = require 'posix' process.on 'message', (opts, socket) -> opts = defaults opts, rows : required cols : required command : required args : required path : undefined term_opts = name : 'xterm' rows : opts.rows cols : opts.cols if opts.path? term_opts.cwd = opts.path if opts.home? term_opts.home = opts.home misc = require('misc') #console.log("about to pty.fork with: opts.command=#{opts.command}, opts.args=#{misc.to_json(opts.args)}, term_opts=#{misc.to_json(term_opts)}") term = pty.fork(opts.command, opts.args, term_opts) # See http://invisible-island.net/xterm/ctlseqs/ctlseqs.txt # CSI Ps ; Ps ; Ps t # CSI[4];[height];[width]t CSI = String.fromCharCode(0x9b) resize_sequence = undefined parse_resize = (data) -> i = data.indexOf('t') if i == -1 resize_sequence += data return data.length else # Got complete sequence s = (resize_sequence + data.slice(0,i)).slice(3) resize_sequence = undefined j = s.indexOf(';') if j != -1 rows = parseInt(s.slice(0,j)) cols = parseInt(s.slice(j+1)) term.resize(cols, rows) return i+1 CSI_code = (data) -> s = data.toString('ascii') if resize_sequence? start = 0 end = parse_resize(s) else i = s.lastIndexOf(CSI) if i != -1 resize_sequence = '' start = i end = start + parse_resize(s.slice(i)) if start? # skip data consumed in CSI data = data.slice(0,start) + data.slice(end+1) return data socket.on 'data', (data) -> data = CSI_code(data) term.write data term.on 'data', (data) -> socket.write data term.on 'exit', () -> socket.end() socket.on 'end', () -> # If the hub connection dies, there is no point in # letting this process continue running, since it can't send # its output anywhere. So we terminate. process.exit(1)
[ { "context": "# 开发模式下的监控模块\n# @date 2015年11月23日17:37:08\n# @author pjg <iampjg@gmail.com>\n# @link http://pjg.pw\n# @versi", "end": 59, "score": 0.9996052980422974, "start": 56, "tag": "USERNAME", "value": "pjg" }, { "context": "下的监控模块\n# @date 2015年11月23日17:37:08\n# @author pjg <iam...
node_modules/vbuilder/lib/watchCtl/index.coffee
duolaimi/v.builder.site
0
###* # 开发模式下的监控模块 # @date 2015年11月23日17:37:08 # @author pjg <iampjg@gmail.com> # @link http://pjg.pw # @version $Id$ ### fs = require "fs" path = require "path" _ = require "lodash" gutil = require "gulp-util" color = gutil.colors Watch = require "gulp-watch" # JS语法检测 jshint = require "jshint" JSHINT = jshint.JSHINT # 载入构建类库 Tools = require "../utils" SpCtl = require "../spCtl" CssCtl = require "../cssCtl" JsCtl = require "../jsCtl" TplCtl = require "../tplCtl" HtmlCtl = require "../htmlCtl" FontsCtl = require "../fontsCtl" ImgCtl = require "../imgCtl" # 读取Cache缓存 opts = global.Cache["gOpts"] # 初始化构建类库 spCtl = new SpCtl(opts) cssCtl = new CssCtl(opts) jsCtl = new JsCtl(opts) tplCtl = new TplCtl(opts) htmlCtl = new HtmlCtl(opts) fontsCtl = new FontsCtl(opts) imgCtl = new ImgCtl(opts) # 一些扩展工具 Utils = getCache: -> _cache = {} maps = ["img","css","js","jsHash","jsSource","spMap"] if not _.has(global.Cache,"cssMap") and not _.has(global.Cache,"jsMap") # Tools.getMap("cache") cacheFile = opts.mapPath + "cache.json" if fs.existsSync(cacheFile) try _cache = JSON.parse(fs.readFileSync(cacheFile), "utf8") global.Cache = _.assign(global.Cache,_cache) catch e maps.forEach (val,key)-> Tools.getMap(val) else maps.forEach (val,key)-> Tools.getMap(val) # JS语法检测 jsHint: (file)-> try gutil.log color.cyan("jshint.JS语法检测开始-->") _source = fs.readFileSync(file, "utf8") # console.log _source !!JSHINT(_source) JSHINT.errors.filter (error)-> if error gutil.log color.magenta(file.replace(opts.root,'')),"error in line -->",color.magenta(error.line) gutil.log color.yellow(error.reason) gutil.log color.cyan("jshint.JS语法检测结束") catch e console.log e # 判断监控文件的类型 getType: (dir)-> _path = dir.replace(/\\/g,"/").replace(/\/\//g,"/") return (_path.split(opts.srcPath)[1]).split("/")[0] # less to CSS less: (cb)-> _cb = cb or -> cssCtl.less2css(_cb,!0) # pngs to sprite img sprite: (file,cb)-> _folder = (file.split('sprite/')[1]).split('/')[0] spCtl.outputOne(_folder,cb) # build html tpl tpl: (file,cb)-> _folder = (file.split('tpl/')[1]).split('/')[0] tplCtl.convertHtmlToJs(_folder,cb) html: (cb)-> htmlCtl.combine(cb) # build js to dist dir js: (file,cb)-> this.jsHint(file) if file.indexOf('_tpl/') == -1 jsCtl.toAmd(file,cb) msg: (fileName)-> gutil.log "'" + color.cyan(fileName) + "'","build success." fonts:(cb)-> fontsCtl.copyDebug cb img: (cb)-> imgCtl.init cb ### # 开发的监控API ### watcher = (cb)-> _this = @ _list = [] # 监控的文件 _files = [ "#{opts.srcPath}/less/**/*.less" "#{opts.srcPath}/sprite/**/*.png" "#{opts.srcPath}/html/**/*.html" "#{opts.srcPath}/js/**/*.js" "#{opts.srcPath}/tpl/**/*.html" "#{opts.srcPath}/img/*.{gif,jpg,png,svg}" "#{opts.srcPath}/img/**/*.{gif,jpg,png,svg}" "!.DS_Store" ] _filePaths = [] opts.fontExt.forEach (value,index)-> _filePaths.push "#{opts.srcPath}/fonts/**/*.#{value}" _files = _files.concat _filePaths Utils.getCache() # for item of global.Cache # console.log item Watch _files,(file)-> try _event = file.event if _event isnt "undefined" _filePath = file.path.replace(/\\/g,"/") if _filePath not in _list _list.push(_filePath) gutil.log "'" + color.cyan(file.relative) + "'","was #{_event}" _type = Utils.getType(_filePath) # console.log "type ==>",_type switch _type when "sprite" Utils.sprite _filePath,-> Utils.msg(file.relative) when "less" Utils.less -> Utils.msg("CSS") when "html" Utils.html -> Utils.msg("HTML template") when "js" Utils.js _filePath,-> Utils.msg(file.relative) when "tpl" Utils.tpl _filePath,-> Utils.msg(file.relative) when "img" Utils.img -> Utils.msg('img copy') when "fonts" Utils.fonts -> Utils.msg('font copy') # clear watch list after 3 seconds clearTimeout watch_timer if watch_timer watch_timer = setTimeout -> _list = [] ,3000 catch err console.log err module.exports = watcher
61706
###* # 开发模式下的监控模块 # @date 2015年11月23日17:37:08 # @author pjg <<EMAIL>> # @link http://pjg.pw # @version $Id$ ### fs = require "fs" path = require "path" _ = require "lodash" gutil = require "gulp-util" color = gutil.colors Watch = require "gulp-watch" # JS语法检测 jshint = require "jshint" JSHINT = jshint.JSHINT # 载入构建类库 Tools = require "../utils" SpCtl = require "../spCtl" CssCtl = require "../cssCtl" JsCtl = require "../jsCtl" TplCtl = require "../tplCtl" HtmlCtl = require "../htmlCtl" FontsCtl = require "../fontsCtl" ImgCtl = require "../imgCtl" # 读取Cache缓存 opts = global.Cache["gOpts"] # 初始化构建类库 spCtl = new SpCtl(opts) cssCtl = new CssCtl(opts) jsCtl = new JsCtl(opts) tplCtl = new TplCtl(opts) htmlCtl = new HtmlCtl(opts) fontsCtl = new FontsCtl(opts) imgCtl = new ImgCtl(opts) # 一些扩展工具 Utils = getCache: -> _cache = {} maps = ["img","css","js","jsHash","jsSource","spMap"] if not _.has(global.Cache,"cssMap") and not _.has(global.Cache,"jsMap") # Tools.getMap("cache") cacheFile = opts.mapPath + "cache.json" if fs.existsSync(cacheFile) try _cache = JSON.parse(fs.readFileSync(cacheFile), "utf8") global.Cache = _.assign(global.Cache,_cache) catch e maps.forEach (val,key)-> Tools.getMap(val) else maps.forEach (val,key)-> Tools.getMap(val) # JS语法检测 jsHint: (file)-> try gutil.log color.cyan("jshint.JS语法检测开始-->") _source = fs.readFileSync(file, "utf8") # console.log _source !!JSHINT(_source) JSHINT.errors.filter (error)-> if error gutil.log color.magenta(file.replace(opts.root,'')),"error in line -->",color.magenta(error.line) gutil.log color.yellow(error.reason) gutil.log color.cyan("jshint.JS语法检测结束") catch e console.log e # 判断监控文件的类型 getType: (dir)-> _path = dir.replace(/\\/g,"/").replace(/\/\//g,"/") return (_path.split(opts.srcPath)[1]).split("/")[0] # less to CSS less: (cb)-> _cb = cb or -> cssCtl.less2css(_cb,!0) # pngs to sprite img sprite: (file,cb)-> _folder = (file.split('sprite/')[1]).split('/')[0] spCtl.outputOne(_folder,cb) # build html tpl tpl: (file,cb)-> _folder = (file.split('tpl/')[1]).split('/')[0] tplCtl.convertHtmlToJs(_folder,cb) html: (cb)-> htmlCtl.combine(cb) # build js to dist dir js: (file,cb)-> this.jsHint(file) if file.indexOf('_tpl/') == -1 jsCtl.toAmd(file,cb) msg: (fileName)-> gutil.log "'" + color.cyan(fileName) + "'","build success." fonts:(cb)-> fontsCtl.copyDebug cb img: (cb)-> imgCtl.init cb ### # 开发的监控API ### watcher = (cb)-> _this = @ _list = [] # 监控的文件 _files = [ "#{opts.srcPath}/less/**/*.less" "#{opts.srcPath}/sprite/**/*.png" "#{opts.srcPath}/html/**/*.html" "#{opts.srcPath}/js/**/*.js" "#{opts.srcPath}/tpl/**/*.html" "#{opts.srcPath}/img/*.{gif,jpg,png,svg}" "#{opts.srcPath}/img/**/*.{gif,jpg,png,svg}" "!.DS_Store" ] _filePaths = [] opts.fontExt.forEach (value,index)-> _filePaths.push "#{opts.srcPath}/fonts/**/*.#{value}" _files = _files.concat _filePaths Utils.getCache() # for item of global.Cache # console.log item Watch _files,(file)-> try _event = file.event if _event isnt "undefined" _filePath = file.path.replace(/\\/g,"/") if _filePath not in _list _list.push(_filePath) gutil.log "'" + color.cyan(file.relative) + "'","was #{_event}" _type = Utils.getType(_filePath) # console.log "type ==>",_type switch _type when "sprite" Utils.sprite _filePath,-> Utils.msg(file.relative) when "less" Utils.less -> Utils.msg("CSS") when "html" Utils.html -> Utils.msg("HTML template") when "js" Utils.js _filePath,-> Utils.msg(file.relative) when "tpl" Utils.tpl _filePath,-> Utils.msg(file.relative) when "img" Utils.img -> Utils.msg('img copy') when "fonts" Utils.fonts -> Utils.msg('font copy') # clear watch list after 3 seconds clearTimeout watch_timer if watch_timer watch_timer = setTimeout -> _list = [] ,3000 catch err console.log err module.exports = watcher
true
###* # 开发模式下的监控模块 # @date 2015年11月23日17:37:08 # @author pjg <PI:EMAIL:<EMAIL>END_PI> # @link http://pjg.pw # @version $Id$ ### fs = require "fs" path = require "path" _ = require "lodash" gutil = require "gulp-util" color = gutil.colors Watch = require "gulp-watch" # JS语法检测 jshint = require "jshint" JSHINT = jshint.JSHINT # 载入构建类库 Tools = require "../utils" SpCtl = require "../spCtl" CssCtl = require "../cssCtl" JsCtl = require "../jsCtl" TplCtl = require "../tplCtl" HtmlCtl = require "../htmlCtl" FontsCtl = require "../fontsCtl" ImgCtl = require "../imgCtl" # 读取Cache缓存 opts = global.Cache["gOpts"] # 初始化构建类库 spCtl = new SpCtl(opts) cssCtl = new CssCtl(opts) jsCtl = new JsCtl(opts) tplCtl = new TplCtl(opts) htmlCtl = new HtmlCtl(opts) fontsCtl = new FontsCtl(opts) imgCtl = new ImgCtl(opts) # 一些扩展工具 Utils = getCache: -> _cache = {} maps = ["img","css","js","jsHash","jsSource","spMap"] if not _.has(global.Cache,"cssMap") and not _.has(global.Cache,"jsMap") # Tools.getMap("cache") cacheFile = opts.mapPath + "cache.json" if fs.existsSync(cacheFile) try _cache = JSON.parse(fs.readFileSync(cacheFile), "utf8") global.Cache = _.assign(global.Cache,_cache) catch e maps.forEach (val,key)-> Tools.getMap(val) else maps.forEach (val,key)-> Tools.getMap(val) # JS语法检测 jsHint: (file)-> try gutil.log color.cyan("jshint.JS语法检测开始-->") _source = fs.readFileSync(file, "utf8") # console.log _source !!JSHINT(_source) JSHINT.errors.filter (error)-> if error gutil.log color.magenta(file.replace(opts.root,'')),"error in line -->",color.magenta(error.line) gutil.log color.yellow(error.reason) gutil.log color.cyan("jshint.JS语法检测结束") catch e console.log e # 判断监控文件的类型 getType: (dir)-> _path = dir.replace(/\\/g,"/").replace(/\/\//g,"/") return (_path.split(opts.srcPath)[1]).split("/")[0] # less to CSS less: (cb)-> _cb = cb or -> cssCtl.less2css(_cb,!0) # pngs to sprite img sprite: (file,cb)-> _folder = (file.split('sprite/')[1]).split('/')[0] spCtl.outputOne(_folder,cb) # build html tpl tpl: (file,cb)-> _folder = (file.split('tpl/')[1]).split('/')[0] tplCtl.convertHtmlToJs(_folder,cb) html: (cb)-> htmlCtl.combine(cb) # build js to dist dir js: (file,cb)-> this.jsHint(file) if file.indexOf('_tpl/') == -1 jsCtl.toAmd(file,cb) msg: (fileName)-> gutil.log "'" + color.cyan(fileName) + "'","build success." fonts:(cb)-> fontsCtl.copyDebug cb img: (cb)-> imgCtl.init cb ### # 开发的监控API ### watcher = (cb)-> _this = @ _list = [] # 监控的文件 _files = [ "#{opts.srcPath}/less/**/*.less" "#{opts.srcPath}/sprite/**/*.png" "#{opts.srcPath}/html/**/*.html" "#{opts.srcPath}/js/**/*.js" "#{opts.srcPath}/tpl/**/*.html" "#{opts.srcPath}/img/*.{gif,jpg,png,svg}" "#{opts.srcPath}/img/**/*.{gif,jpg,png,svg}" "!.DS_Store" ] _filePaths = [] opts.fontExt.forEach (value,index)-> _filePaths.push "#{opts.srcPath}/fonts/**/*.#{value}" _files = _files.concat _filePaths Utils.getCache() # for item of global.Cache # console.log item Watch _files,(file)-> try _event = file.event if _event isnt "undefined" _filePath = file.path.replace(/\\/g,"/") if _filePath not in _list _list.push(_filePath) gutil.log "'" + color.cyan(file.relative) + "'","was #{_event}" _type = Utils.getType(_filePath) # console.log "type ==>",_type switch _type when "sprite" Utils.sprite _filePath,-> Utils.msg(file.relative) when "less" Utils.less -> Utils.msg("CSS") when "html" Utils.html -> Utils.msg("HTML template") when "js" Utils.js _filePath,-> Utils.msg(file.relative) when "tpl" Utils.tpl _filePath,-> Utils.msg(file.relative) when "img" Utils.img -> Utils.msg('img copy') when "fonts" Utils.fonts -> Utils.msg('font copy') # clear watch list after 3 seconds clearTimeout watch_timer if watch_timer watch_timer = setTimeout -> _list = [] ,3000 catch err console.log err module.exports = watcher
[ { "context": "t:alert(0);' # removes javascript\n 'mailto:hello@kermit.cc' # removes email\n '#inpage-anchor'\n ", "end": 306, "score": 0.9999081492424011, "start": 291, "tag": "EMAIL", "value": "hello@kermit.cc" }, { "context": "ocalPath base, \"https://raw.githu...
src/kermit/util/tools.spec.coffee
open-medicine-initiative/webcherries
6
{obj, uri, files} = require './tools' describe 'Tools collection', -> describe ' has uri utilities', -> it ' #clean(base, urls) to clean sets of URLs ', -> base = "http://kermit.cc/base/" uncleaned = [ 'javascript:alert(0);' # removes javascript 'mailto:hello@kermit.cc' # removes email '#inpage-anchor' '//kermit.cc/other/path/not/under/base' '/relative/path/to/base' 'some/page/under/base/index.html' 'some/page/under/base/index.html?q=includesQueryWithParams&param=value' ] expected = [ 'http://kermit.cc/other/path/not/under/base' 'http://kermit.cc/relative/path/to/base' 'http://kermit.cc/base/some/page/under/base/index.html' 'http://kermit.cc/base/some/page/under/base/index.html?q=includesQueryWithParams&param=value' ] cleaned = uri.cleanAll base, uncleaned expect(cleaned).to.contain expectedUrl for expectedUrl in expected it ' #toLocalPath(basedir, url) translates URLs to file identifiers for local storage ', -> base = "/tmp" expect(uri.toLocalPath base, "http://example.co.uk").to.equal "#{base}/co.uk/example/index.html" expect(uri.toLocalPath base, "http://example.co.uk/somepage").to.equal "#{base}/co.uk/example/somepage/index.html" expect(uri.toLocalPath base, "https://medialize.github.io/URI.js/docs.html#accessors-tld").to.equal "#{base}/io/github/medialize/URI.js/docs.html" expect(uri.toLocalPath base, "http://github.com/some/other/../directory/help.html").to.equal "#{base}/com/github/some/directory/help.html" expect(uri.toLocalPath base, "https://raw.githubusercontent.com/moll/js-must/master/lib/es6.js").to.equal "#{base}/com/githubusercontent/raw/moll/js-must/master/lib/es6.js" expect(uri.toLocalPath base, "https://github.com/moll/js-must/blob/v0.13.0-beta2/lib/index.js").to.equal "#{base}/com/github/moll/js-must/blob/v0.13.0-beta2/lib/index.js" expect(uri.toLocalPath base, "https://en.wikipedia.org/wiki/Web_scraping").to.equal "#{base}/org/wikipedia/en/wiki/Web_scraping/index.html" expect(uri.toLocalPath base, "http://upload.wikimedia.org/wikipedia/commons/thumb/b/bd/Ambox_globe_content.svg/48px-Ambox_globe_content.svg.png").to.equal "#{base}/org/wikimedia/upload/wikipedia/commons/thumb/b/bd/Ambox_globe_content.svg/48px-Ambox_globe_content.svg.png" expect(uri.toLocalPath base, "http://en.wikipedia.org/wiki/index.php?title=Web_scraping&amp;action=edit&amp;section=1").to.equal "#{base}/org/wikipedia/en/wiki/index[title=Web_scraping&action=edit&section=1].php" expect(uri.toLocalPath base, "http://en.wikipedia.org/wiki/Talk:Web_scraping").to.equal "#{base}/org/wikipedia/en/wiki/Talk:Web_scraping/index.html" expect(uri.toLocalPath base, "http://en.wikipedia.org/wiki/EBay vs. Bidder%27s Edge").to.equal "#{base}/org/wikipedia/en/wiki/EBay vs. Bidder's Edge/index.html" expect(uri.toLocalPath base, "https://en.wikipedia.org/wiki/Nokogiri_(software)").to.equal "#{base}/org/wikipedia/en/wiki/Nokogiri_(software)/index.html" expect(uri.toLocalPath base, "https://en.wikipedia.org/wiki/Yahoo!_Query_Language").to.equal "#{base}/org/wikipedia/en/wiki/Yahoo!_Query_Language/index.html" describe ' file utilities', -> it ' # provides method for checking file existence', -> expect(files.exists './fixtures/queuesys/b5hg6ued.items.db').to.be true
119348
{obj, uri, files} = require './tools' describe 'Tools collection', -> describe ' has uri utilities', -> it ' #clean(base, urls) to clean sets of URLs ', -> base = "http://kermit.cc/base/" uncleaned = [ 'javascript:alert(0);' # removes javascript 'mailto:<EMAIL>' # removes email '#inpage-anchor' '//kermit.cc/other/path/not/under/base' '/relative/path/to/base' 'some/page/under/base/index.html' 'some/page/under/base/index.html?q=includesQueryWithParams&param=value' ] expected = [ 'http://kermit.cc/other/path/not/under/base' 'http://kermit.cc/relative/path/to/base' 'http://kermit.cc/base/some/page/under/base/index.html' 'http://kermit.cc/base/some/page/under/base/index.html?q=includesQueryWithParams&param=value' ] cleaned = uri.cleanAll base, uncleaned expect(cleaned).to.contain expectedUrl for expectedUrl in expected it ' #toLocalPath(basedir, url) translates URLs to file identifiers for local storage ', -> base = "/tmp" expect(uri.toLocalPath base, "http://example.co.uk").to.equal "#{base}/co.uk/example/index.html" expect(uri.toLocalPath base, "http://example.co.uk/somepage").to.equal "#{base}/co.uk/example/somepage/index.html" expect(uri.toLocalPath base, "https://medialize.github.io/URI.js/docs.html#accessors-tld").to.equal "#{base}/io/github/medialize/URI.js/docs.html" expect(uri.toLocalPath base, "http://github.com/some/other/../directory/help.html").to.equal "#{base}/com/github/some/directory/help.html" expect(uri.toLocalPath base, "https://raw.githubusercontent.com/moll/js-must/master/lib/es6.js").to.equal "#{base}/com/githubusercontent/raw/moll/js-must/master/lib/es6.js" expect(uri.toLocalPath base, "https://github.com/moll/js-must/blob/v0.13.0-beta2/lib/index.js").to.equal "#{base}/com/github/moll/js-must/blob/v0.13.0-beta2/lib/index.js" expect(uri.toLocalPath base, "https://en.wikipedia.org/wiki/Web_scraping").to.equal "#{base}/org/wikipedia/en/wiki/Web_scraping/index.html" expect(uri.toLocalPath base, "http://upload.wikimedia.org/wikipedia/commons/thumb/b/bd/Ambox_globe_content.svg/48px-Ambox_globe_content.svg.png").to.equal "#{base}/org/wikimedia/upload/wikipedia/commons/thumb/b/bd/Ambox_globe_content.svg/48px-Ambox_globe_content.svg.png" expect(uri.toLocalPath base, "http://en.wikipedia.org/wiki/index.php?title=Web_scraping&amp;action=edit&amp;section=1").to.equal "#{base}/org/wikipedia/en/wiki/index[title=Web_scraping&action=edit&section=1].php" expect(uri.toLocalPath base, "http://en.wikipedia.org/wiki/Talk:Web_scraping").to.equal "#{base}/org/wikipedia/en/wiki/Talk:Web_scraping/index.html" expect(uri.toLocalPath base, "http://en.wikipedia.org/wiki/EBay vs. Bidder%27s Edge").to.equal "#{base}/org/wikipedia/en/wiki/EBay vs. Bidder's Edge/index.html" expect(uri.toLocalPath base, "https://en.wikipedia.org/wiki/Nokogiri_(software)").to.equal "#{base}/org/wikipedia/en/wiki/Nokogiri_(software)/index.html" expect(uri.toLocalPath base, "https://en.wikipedia.org/wiki/Yahoo!_Query_Language").to.equal "#{base}/org/wikipedia/en/wiki/Yahoo!_Query_Language/index.html" describe ' file utilities', -> it ' # provides method for checking file existence', -> expect(files.exists './fixtures/queuesys/b5hg6ued.items.db').to.be true
true
{obj, uri, files} = require './tools' describe 'Tools collection', -> describe ' has uri utilities', -> it ' #clean(base, urls) to clean sets of URLs ', -> base = "http://kermit.cc/base/" uncleaned = [ 'javascript:alert(0);' # removes javascript 'mailto:PI:EMAIL:<EMAIL>END_PI' # removes email '#inpage-anchor' '//kermit.cc/other/path/not/under/base' '/relative/path/to/base' 'some/page/under/base/index.html' 'some/page/under/base/index.html?q=includesQueryWithParams&param=value' ] expected = [ 'http://kermit.cc/other/path/not/under/base' 'http://kermit.cc/relative/path/to/base' 'http://kermit.cc/base/some/page/under/base/index.html' 'http://kermit.cc/base/some/page/under/base/index.html?q=includesQueryWithParams&param=value' ] cleaned = uri.cleanAll base, uncleaned expect(cleaned).to.contain expectedUrl for expectedUrl in expected it ' #toLocalPath(basedir, url) translates URLs to file identifiers for local storage ', -> base = "/tmp" expect(uri.toLocalPath base, "http://example.co.uk").to.equal "#{base}/co.uk/example/index.html" expect(uri.toLocalPath base, "http://example.co.uk/somepage").to.equal "#{base}/co.uk/example/somepage/index.html" expect(uri.toLocalPath base, "https://medialize.github.io/URI.js/docs.html#accessors-tld").to.equal "#{base}/io/github/medialize/URI.js/docs.html" expect(uri.toLocalPath base, "http://github.com/some/other/../directory/help.html").to.equal "#{base}/com/github/some/directory/help.html" expect(uri.toLocalPath base, "https://raw.githubusercontent.com/moll/js-must/master/lib/es6.js").to.equal "#{base}/com/githubusercontent/raw/moll/js-must/master/lib/es6.js" expect(uri.toLocalPath base, "https://github.com/moll/js-must/blob/v0.13.0-beta2/lib/index.js").to.equal "#{base}/com/github/moll/js-must/blob/v0.13.0-beta2/lib/index.js" expect(uri.toLocalPath base, "https://en.wikipedia.org/wiki/Web_scraping").to.equal "#{base}/org/wikipedia/en/wiki/Web_scraping/index.html" expect(uri.toLocalPath base, "http://upload.wikimedia.org/wikipedia/commons/thumb/b/bd/Ambox_globe_content.svg/48px-Ambox_globe_content.svg.png").to.equal "#{base}/org/wikimedia/upload/wikipedia/commons/thumb/b/bd/Ambox_globe_content.svg/48px-Ambox_globe_content.svg.png" expect(uri.toLocalPath base, "http://en.wikipedia.org/wiki/index.php?title=Web_scraping&amp;action=edit&amp;section=1").to.equal "#{base}/org/wikipedia/en/wiki/index[title=Web_scraping&action=edit&section=1].php" expect(uri.toLocalPath base, "http://en.wikipedia.org/wiki/Talk:Web_scraping").to.equal "#{base}/org/wikipedia/en/wiki/Talk:Web_scraping/index.html" expect(uri.toLocalPath base, "http://en.wikipedia.org/wiki/EBay vs. Bidder%27s Edge").to.equal "#{base}/org/wikipedia/en/wiki/EBay vs. Bidder's Edge/index.html" expect(uri.toLocalPath base, "https://en.wikipedia.org/wiki/Nokogiri_(software)").to.equal "#{base}/org/wikipedia/en/wiki/Nokogiri_(software)/index.html" expect(uri.toLocalPath base, "https://en.wikipedia.org/wiki/Yahoo!_Query_Language").to.equal "#{base}/org/wikipedia/en/wiki/Yahoo!_Query_Language/index.html" describe ' file utilities', -> it ' # provides method for checking file existence', -> expect(files.exists './fixtures/queuesys/b5hg6ued.items.db').to.be true
[ { "context": "ource: jsonp.coffee\n###\n\n###\n * \n * Copyright 2017 Al Carruth\n * \n * Licensed under the Apache License, Version", "end": 70, "score": 0.9998121857643127, "start": 60, "tag": "NAME", "value": "Al Carruth" }, { "context": "method send() ###\n send: =>\n w...
src/jsonp.coffee
alcarruth/JSONP_Controller
0
###* * source: jsonp.coffee ### ### * * Copyright 2017 Al Carruth * * 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. * ### ___dummy___ = 'ignore this !-)' ### Class JSONP_Controller ### ###* * A JSONP_Controller instance can be used to make a jsonp request to an api server. * @constructor * @param {string} base_URL - the base url for the server * @param {string} cb_Prefix - used in naming the jsonp callback function ### class JSONP_Controller ### constructor ### constructor: (@base_URL, @cb_Prefix) -> @cb_Prefix = @cb_Prefix || 'jsonp_Callback_' ### seq_ID is appended to the cb_Prefix ### @seq_ID = 0 ### collect the requests for later inspection (maybe?) ### @requests = [] ###* * method make_Request() * returns a JSONP_Request object * @param {object} obj - query, success, error, msec ### make_Request: (obj) => ### the call back function name, unique to this call ### cb_Name = @cb_Prefix + @seq_ID++ ### ADD 'CALLBACK' TO provided query object ### obj.query.callback = cb_Name ### construct the url from the base_URL and the query object ### url = @base_URL keys = Object.keys(obj.query) url += (key+'='+obj.query[key] for key in keys).join('&') url = encodeURI(url) request = new JSONP_Request(obj.success, obj.error, obj.msec, cb_Name, url) @requests.push(request) return request ### Class JSONP_Request ### ###* * A JSONP_Request object is used to make a jsonp request to an api server. * @constructor * @param {function} success - executed upon successful jsonp response * @param {function} error - executed upon timeout * @param {int} msec - timeout delay in milliseconds * @param {string} cb_Name * @param {string} url - the url for jsonp call ### class JSONP_Request ### constructor ### constructor: (@success, @error, @msec, @cb_Name, @url) -> ### the parent node to be ### @head = document.getElementsByTagName('head')[0] ### the script element that enables this request ### @elt = document.createElement('script') @elt.type = 'text/javascript' @elt.async = true @elt.src = @url ### the below might be useful later, idk ### @elt.id = @cb_Name @elt.className = 'jsonp-request' @elt.request = this ### method callback() ### callback: (data) => window.clearTimeout(@timeout) @success(data) ### method send() ### send: => window[@cb_Name] = @callback @timeout = window.setTimeout(@error, @msec) ### appending @elt triggers the call to fetch the jsonp script ### @head.appendChild(@elt) if window? window.JSONP_Controller = JSONP_Controller
123681
###* * source: jsonp.coffee ### ### * * Copyright 2017 <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. * ### ___dummy___ = 'ignore this !-)' ### Class JSONP_Controller ### ###* * A JSONP_Controller instance can be used to make a jsonp request to an api server. * @constructor * @param {string} base_URL - the base url for the server * @param {string} cb_Prefix - used in naming the jsonp callback function ### class JSONP_Controller ### constructor ### constructor: (@base_URL, @cb_Prefix) -> @cb_Prefix = @cb_Prefix || 'jsonp_Callback_' ### seq_ID is appended to the cb_Prefix ### @seq_ID = 0 ### collect the requests for later inspection (maybe?) ### @requests = [] ###* * method make_Request() * returns a JSONP_Request object * @param {object} obj - query, success, error, msec ### make_Request: (obj) => ### the call back function name, unique to this call ### cb_Name = @cb_Prefix + @seq_ID++ ### ADD 'CALLBACK' TO provided query object ### obj.query.callback = cb_Name ### construct the url from the base_URL and the query object ### url = @base_URL keys = Object.keys(obj.query) url += (key+'='+obj.query[key] for key in keys).join('&') url = encodeURI(url) request = new JSONP_Request(obj.success, obj.error, obj.msec, cb_Name, url) @requests.push(request) return request ### Class JSONP_Request ### ###* * A JSONP_Request object is used to make a jsonp request to an api server. * @constructor * @param {function} success - executed upon successful jsonp response * @param {function} error - executed upon timeout * @param {int} msec - timeout delay in milliseconds * @param {string} cb_Name * @param {string} url - the url for jsonp call ### class JSONP_Request ### constructor ### constructor: (@success, @error, @msec, @cb_Name, @url) -> ### the parent node to be ### @head = document.getElementsByTagName('head')[0] ### the script element that enables this request ### @elt = document.createElement('script') @elt.type = 'text/javascript' @elt.async = true @elt.src = @url ### the below might be useful later, idk ### @elt.id = @cb_Name @elt.className = 'jsonp-request' @elt.request = this ### method callback() ### callback: (data) => window.clearTimeout(@timeout) @success(data) ### method send() ### send: => window[@cb_Name] = @callback @timeout = window.setTimeout(@error, @msec) ### appending @elt triggers the call to fetch the jsonp script ### @head.appendChild(@elt) if window? window.JSONP_Controller = JSONP_Controller
true
###* * source: jsonp.coffee ### ### * * Copyright 2017 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. * ### ___dummy___ = 'ignore this !-)' ### Class JSONP_Controller ### ###* * A JSONP_Controller instance can be used to make a jsonp request to an api server. * @constructor * @param {string} base_URL - the base url for the server * @param {string} cb_Prefix - used in naming the jsonp callback function ### class JSONP_Controller ### constructor ### constructor: (@base_URL, @cb_Prefix) -> @cb_Prefix = @cb_Prefix || 'jsonp_Callback_' ### seq_ID is appended to the cb_Prefix ### @seq_ID = 0 ### collect the requests for later inspection (maybe?) ### @requests = [] ###* * method make_Request() * returns a JSONP_Request object * @param {object} obj - query, success, error, msec ### make_Request: (obj) => ### the call back function name, unique to this call ### cb_Name = @cb_Prefix + @seq_ID++ ### ADD 'CALLBACK' TO provided query object ### obj.query.callback = cb_Name ### construct the url from the base_URL and the query object ### url = @base_URL keys = Object.keys(obj.query) url += (key+'='+obj.query[key] for key in keys).join('&') url = encodeURI(url) request = new JSONP_Request(obj.success, obj.error, obj.msec, cb_Name, url) @requests.push(request) return request ### Class JSONP_Request ### ###* * A JSONP_Request object is used to make a jsonp request to an api server. * @constructor * @param {function} success - executed upon successful jsonp response * @param {function} error - executed upon timeout * @param {int} msec - timeout delay in milliseconds * @param {string} cb_Name * @param {string} url - the url for jsonp call ### class JSONP_Request ### constructor ### constructor: (@success, @error, @msec, @cb_Name, @url) -> ### the parent node to be ### @head = document.getElementsByTagName('head')[0] ### the script element that enables this request ### @elt = document.createElement('script') @elt.type = 'text/javascript' @elt.async = true @elt.src = @url ### the below might be useful later, idk ### @elt.id = @cb_Name @elt.className = 'jsonp-request' @elt.request = this ### method callback() ### callback: (data) => window.clearTimeout(@timeout) @success(data) ### method send() ### send: => window[@cb_Name] = @callback @timeout = window.setTimeout(@error, @msec) ### appending @elt triggers the call to fetch the jsonp script ### @head.appendChild(@elt) if window? window.JSONP_Controller = JSONP_Controller
[ { "context": " User({\n anonymous: false\n name: 'healthcheck'\n nameLower: 'healthcheck'\n slug: 'heal", "end": 375, "score": 0.5613493919372559, "start": 370, "tag": "NAME", "value": "check" }, { "context": "lthcheck'\n slug: 'healthcheck'\n email: 'ro...
server/middleware/healthcheck.coffee
adamcsillag/codecombat
2
wrap = require 'co-express' errors = require '../commons/errors' module.exports = wrap (req, res) -> User = require '../models/User' user = yield User.findOne({}) throw new errors.InternalServerError('No users found') unless user hcUser = yield User.findOne(slug: 'healthcheck') if not hcUser hcUser = new User({ anonymous: false name: 'healthcheck' nameLower: 'healthcheck' slug: 'healthcheck' email: 'rob+healthcheck@codecombat.com' emailLower: 'rob+healthcheck@codecombat.com' }) hcUser.set 'testGroupNumber', Math.floor(Math.random() * 256) # also in app/core/auth yield hcUser.save() activity = hcUser.trackActivity('healthcheck', 1) yield hcUser.update({activity: activity}) res.status(200).send('OK')
181467
wrap = require 'co-express' errors = require '../commons/errors' module.exports = wrap (req, res) -> User = require '../models/User' user = yield User.findOne({}) throw new errors.InternalServerError('No users found') unless user hcUser = yield User.findOne(slug: 'healthcheck') if not hcUser hcUser = new User({ anonymous: false name: 'health<NAME>' nameLower: 'healthcheck' slug: 'healthcheck' email: '<EMAIL>' emailLower: '<EMAIL>' }) hcUser.set 'testGroupNumber', Math.floor(Math.random() * 256) # also in app/core/auth yield hcUser.save() activity = hcUser.trackActivity('healthcheck', 1) yield hcUser.update({activity: activity}) res.status(200).send('OK')
true
wrap = require 'co-express' errors = require '../commons/errors' module.exports = wrap (req, res) -> User = require '../models/User' user = yield User.findOne({}) throw new errors.InternalServerError('No users found') unless user hcUser = yield User.findOne(slug: 'healthcheck') if not hcUser hcUser = new User({ anonymous: false name: 'healthPI:NAME:<NAME>END_PI' nameLower: 'healthcheck' slug: 'healthcheck' email: 'PI:EMAIL:<EMAIL>END_PI' emailLower: 'PI:EMAIL:<EMAIL>END_PI' }) hcUser.set 'testGroupNumber', Math.floor(Math.random() * 256) # also in app/core/auth yield hcUser.save() activity = hcUser.trackActivity('healthcheck', 1) yield hcUser.update({activity: activity}) res.status(200).send('OK')
[ { "context": "ls type=\"pets\" test=\"yeah\"><dog type=\"dumb\"><name>Rufus</name><breed>labrador</breed></dog><dog><name>Mar", "end": 181, "score": 0.998879611492157, "start": 176, "tag": "NAME", "value": "Rufus" }, { "context": "fus</name><breed>labrador</breed></dog><dog><name>Mar...
bench.coffee
contra/xmlson
1
xmlson = require './' Benchmark = require 'benchmark' tiny = "<foo/>" simple = "<foo bar='baz'>quux</foo>" standard = '<animals type="pets" test="yeah"><dog type="dumb"><name>Rufus</name><breed>labrador</breed></dog><dog><name>Marty</name><breed>whippet</breed></dog><dog/><cat name="Matilda"/></animals>' complex = '<iq id="123456" type="set" to="call57@test.net/1" from="9001@cool.com/1"><say xmlns="urn:xmpp:tropo:say:1" voice="allison"><audio src="http://acme.com/greeting.mp3">Thanks for calling ACME company</audio><audio src="http://acme.com/package-shipped.mp3">Your package was shipped on</audio><say-as interpret-as="date">12/01/2011</say-as></say></iq>' tinyjs = xmlson.toJSON tiny simplejs = xmlson.toJSON simple standardjs = xmlson.toJSON standard complexjs = xmlson.toJSON complex suite = new Benchmark.Suite 'xmlson' suite.on "error", (event, bench) -> throw bench.error suite.on "cycle", (event, bench) -> console.log String bench suite.add "xmlson.toJSON(tiny)", -> xmlson.toJSON tiny suite.add "xmlson.toJSON(simple)", -> xmlson.toJSON simple suite.add "xmlson.toJSON(standard)", -> xmlson.toJSON standard suite.add "xmlson.toJSON(complex)", -> xmlson.toJSON complex suite.add "xmlson.toXML(tiny)", -> xmlson.toXML tinyjs suite.add "xmlson.toXML(simple)", -> xmlson.toXML simplejs suite.add "xmlson.toXML(standard)", -> xmlson.toXML standardjs suite.add "xmlson.toXML(complex)", -> xmlson.toXML complexjs suite.run()
41645
xmlson = require './' Benchmark = require 'benchmark' tiny = "<foo/>" simple = "<foo bar='baz'>quux</foo>" standard = '<animals type="pets" test="yeah"><dog type="dumb"><name><NAME></name><breed>labrador</breed></dog><dog><name><NAME></name><breed>whippet</breed></dog><dog/><cat name="<NAME>ilda"/></animals>' complex = '<iq id="123456" type="set" to="call<EMAIL>/1" from="9<EMAIL>/1"><say xmlns="urn:xmpp:tropo:say:1" voice="allison"><audio src="http://acme.com/greeting.mp3">Thanks for calling ACME company</audio><audio src="http://acme.com/package-shipped.mp3">Your package was shipped on</audio><say-as interpret-as="date">12/01/2011</say-as></say></iq>' tinyjs = xmlson.toJSON tiny simplejs = xmlson.toJSON simple standardjs = xmlson.toJSON standard complexjs = xmlson.toJSON complex suite = new Benchmark.Suite 'xmlson' suite.on "error", (event, bench) -> throw bench.error suite.on "cycle", (event, bench) -> console.log String bench suite.add "xmlson.toJSON(tiny)", -> xmlson.toJSON tiny suite.add "xmlson.toJSON(simple)", -> xmlson.toJSON simple suite.add "xmlson.toJSON(standard)", -> xmlson.toJSON standard suite.add "xmlson.toJSON(complex)", -> xmlson.toJSON complex suite.add "xmlson.toXML(tiny)", -> xmlson.toXML tinyjs suite.add "xmlson.toXML(simple)", -> xmlson.toXML simplejs suite.add "xmlson.toXML(standard)", -> xmlson.toXML standardjs suite.add "xmlson.toXML(complex)", -> xmlson.toXML complexjs suite.run()
true
xmlson = require './' Benchmark = require 'benchmark' tiny = "<foo/>" simple = "<foo bar='baz'>quux</foo>" standard = '<animals type="pets" test="yeah"><dog type="dumb"><name>PI:NAME:<NAME>END_PI</name><breed>labrador</breed></dog><dog><name>PI:NAME:<NAME>END_PI</name><breed>whippet</breed></dog><dog/><cat name="PI:NAME:<NAME>END_PIilda"/></animals>' complex = '<iq id="123456" type="set" to="callPI:EMAIL:<EMAIL>END_PI/1" from="9PI:EMAIL:<EMAIL>END_PI/1"><say xmlns="urn:xmpp:tropo:say:1" voice="allison"><audio src="http://acme.com/greeting.mp3">Thanks for calling ACME company</audio><audio src="http://acme.com/package-shipped.mp3">Your package was shipped on</audio><say-as interpret-as="date">12/01/2011</say-as></say></iq>' tinyjs = xmlson.toJSON tiny simplejs = xmlson.toJSON simple standardjs = xmlson.toJSON standard complexjs = xmlson.toJSON complex suite = new Benchmark.Suite 'xmlson' suite.on "error", (event, bench) -> throw bench.error suite.on "cycle", (event, bench) -> console.log String bench suite.add "xmlson.toJSON(tiny)", -> xmlson.toJSON tiny suite.add "xmlson.toJSON(simple)", -> xmlson.toJSON simple suite.add "xmlson.toJSON(standard)", -> xmlson.toJSON standard suite.add "xmlson.toJSON(complex)", -> xmlson.toJSON complex suite.add "xmlson.toXML(tiny)", -> xmlson.toXML tinyjs suite.add "xmlson.toXML(simple)", -> xmlson.toXML simplejs suite.add "xmlson.toXML(standard)", -> xmlson.toXML standardjs suite.add "xmlson.toXML(complex)", -> xmlson.toXML complexjs suite.run()
[ { "context": " hubot prs - Same as \"hubot pr\".\n#\n# Author:\n# helious (David Posey)\n# davedash (Dave Dash)\n\nasync = r", "end": 847, "score": 0.99945467710495, "start": 840, "tag": "USERNAME", "value": "helious" }, { "context": "rs - Same as \"hubot pr\".\n#\n# Author:\n#...
scripts/github-pull-requests.coffee
helious/hubot-github-pull-requests.coffee
1
# Description: # A way to list all currently open PRs on GitHub. # # Dependencies: # "async": "~1.4.2", # "bluebird": "~2.10.0", # "octonode": "> 0.6.0 < 0.8.0" # # Configuration: # GITHUB_PRS_OAUTH_TOKEN = # (Required) A GitHub OAuth token generated from your account. # GITHUB_PRS_USER = # (Required if GITHUB_PRS_TEAM_ID is not set) A GitHub username. # GITHUB_PRS_TEAM_ID = # (Required if GITHUB_PRS_USER is not set) A GitHub Team ID returned from GitHub's API. Takes precedence over GITHUB_PRS_USER. # GITHUB_PRS_REPO_OWNER_FILTER = # (Optional) A string that contains the names of users you'd like to filter by. (Helpful when you have a lot of forks on your repos that you don't care about.) # # Commands: # hubot pr - Returns a list of open PR links from GitHub. # hubot prs - Same as "hubot pr". # # Author: # helious (David Posey) # davedash (Dave Dash) async = require 'async' Promise = require 'bluebird' Octonode = Promise.promisifyAll(require 'octonode') module.exports = (robot) -> robot.respond /(pr\b|prs)/i, (msg) -> getAllRepos = (done) -> getReposByPage = (page) -> userGitHub = if process.env.GITHUB_PRS_TEAM_ID? gitHub.team process.env.GITHUB_PRS_TEAM_ID else gitHub.user process.env.GITHUB_PRS_USER repoIsDesired = (repoOwner) -> repoOwners = process.env.GITHUB_PRS_REPO_OWNER_FILTER return true unless repoOwners repoOwners? and repoOwners.indexOf(repoOwner) > -1 userGitHub .reposAsync(per_page: 100, page: page) .then (data) -> reposByPage = data[0] for repo in reposByPage repoOwner = repo.full_name.split('/')[0] repos.push repo if repoIsDesired(repoOwner) if reposByPage.length is 100 getReposByPage page + 1 else done() getReposByPage 1 getAllPullRequests = -> getPullRequests = (done, repo) -> gitHubRepo = gitHub.repo repo prs = [] gitHubRepo .prsAsync() .then (data) -> postToChat = (pr) -> lastUpdated = (date) -> pluralize = (amount, unit) -> if amount "#{ amount } #{ unit }#{ if amount > 1 then 's' else '' }" else '' difference = Date.now() - Date.parse(date) days = Math.floor difference / 1000 / 60 / 60 / 24 hours = Math.floor(difference / 1000 / 60 / 60) - 24 * days minutes = Math.floor(difference / 1000 / 60) - 24 * 60 * days - 60 * hours hasValidTime = "#{ days }#{ hours }#{ minutes }" isnt '' timeString = if hasValidTime then "#{ pluralize days, 'day' } #{ pluralize hours, 'hour' } #{ pluralize minutes, 'minute' } ago".trim() else 'just now' "last updated #{ timeString }" number = pr.number url = pr.html_url title = pr.title updatedAt = pr.updated_at user = pr.user.login people = user if pr.assignee people = "#{ user }->#{ pr.assignee.login }" if robot.adapterName is 'slack' msg.send ":octocat: #{ title } - #{ people } - #{ url } - #{ lastUpdated updatedAt }" else msg.send "/me - #{ repo } - ##{ number } - #{ title } - #{ people } - #{ url } - #{ lastUpdated updatedAt }" prs = data[0] postToChat pr for pr in prs .then -> done null, prs.length parallelifyGetPullRequests = (repo) -> (done) -> getPullRequests(done, repo.full_name) parallelGetPullRequests = [] for repo in repos parallelGetPullRequests.push parallelifyGetPullRequests(repo) async.parallel parallelGetPullRequests, (err, results) -> pullRequestCount = if results.length > 0 then results.reduce (a, b) -> a + b else 0 isSingular = pullRequestCount is 1 msg.send "There #{ if isSingular then 'is' else 'are' } #{ pullRequestCount } open Pull Request#{ if isSingular then '.' else 's.' }" gitHub = if process.env.GITHUB_PRS_GHE_API_URL? Octonode.client(process.env.GITHUB_PRS_OAUTH_TOKEN, hostname: process.env.GITHUB_PRS_GHE_API_URL) else Octonode.client(process.env.GITHUB_PRS_OAUTH_TOKEN) repos = [] getAllRepos getAllPullRequests
171926
# Description: # A way to list all currently open PRs on GitHub. # # Dependencies: # "async": "~1.4.2", # "bluebird": "~2.10.0", # "octonode": "> 0.6.0 < 0.8.0" # # Configuration: # GITHUB_PRS_OAUTH_TOKEN = # (Required) A GitHub OAuth token generated from your account. # GITHUB_PRS_USER = # (Required if GITHUB_PRS_TEAM_ID is not set) A GitHub username. # GITHUB_PRS_TEAM_ID = # (Required if GITHUB_PRS_USER is not set) A GitHub Team ID returned from GitHub's API. Takes precedence over GITHUB_PRS_USER. # GITHUB_PRS_REPO_OWNER_FILTER = # (Optional) A string that contains the names of users you'd like to filter by. (Helpful when you have a lot of forks on your repos that you don't care about.) # # Commands: # hubot pr - Returns a list of open PR links from GitHub. # hubot prs - Same as "hubot pr". # # Author: # helious (<NAME>) # davedash (<NAME>) async = require 'async' Promise = require 'bluebird' Octonode = Promise.promisifyAll(require 'octonode') module.exports = (robot) -> robot.respond /(pr\b|prs)/i, (msg) -> getAllRepos = (done) -> getReposByPage = (page) -> userGitHub = if process.env.GITHUB_PRS_TEAM_ID? gitHub.team process.env.GITHUB_PRS_TEAM_ID else gitHub.user process.env.GITHUB_PRS_USER repoIsDesired = (repoOwner) -> repoOwners = process.env.GITHUB_PRS_REPO_OWNER_FILTER return true unless repoOwners repoOwners? and repoOwners.indexOf(repoOwner) > -1 userGitHub .reposAsync(per_page: 100, page: page) .then (data) -> reposByPage = data[0] for repo in reposByPage repoOwner = repo.full_name.split('/')[0] repos.push repo if repoIsDesired(repoOwner) if reposByPage.length is 100 getReposByPage page + 1 else done() getReposByPage 1 getAllPullRequests = -> getPullRequests = (done, repo) -> gitHubRepo = gitHub.repo repo prs = [] gitHubRepo .prsAsync() .then (data) -> postToChat = (pr) -> lastUpdated = (date) -> pluralize = (amount, unit) -> if amount "#{ amount } #{ unit }#{ if amount > 1 then 's' else '' }" else '' difference = Date.now() - Date.parse(date) days = Math.floor difference / 1000 / 60 / 60 / 24 hours = Math.floor(difference / 1000 / 60 / 60) - 24 * days minutes = Math.floor(difference / 1000 / 60) - 24 * 60 * days - 60 * hours hasValidTime = "#{ days }#{ hours }#{ minutes }" isnt '' timeString = if hasValidTime then "#{ pluralize days, 'day' } #{ pluralize hours, 'hour' } #{ pluralize minutes, 'minute' } ago".trim() else 'just now' "last updated #{ timeString }" number = pr.number url = pr.html_url title = pr.title updatedAt = pr.updated_at user = pr.user.login people = user if pr.assignee people = "#{ user }->#{ pr.assignee.login }" if robot.adapterName is 'slack' msg.send ":octocat: #{ title } - #{ people } - #{ url } - #{ lastUpdated updatedAt }" else msg.send "/me - #{ repo } - ##{ number } - #{ title } - #{ people } - #{ url } - #{ lastUpdated updatedAt }" prs = data[0] postToChat pr for pr in prs .then -> done null, prs.length parallelifyGetPullRequests = (repo) -> (done) -> getPullRequests(done, repo.full_name) parallelGetPullRequests = [] for repo in repos parallelGetPullRequests.push parallelifyGetPullRequests(repo) async.parallel parallelGetPullRequests, (err, results) -> pullRequestCount = if results.length > 0 then results.reduce (a, b) -> a + b else 0 isSingular = pullRequestCount is 1 msg.send "There #{ if isSingular then 'is' else 'are' } #{ pullRequestCount } open Pull Request#{ if isSingular then '.' else 's.' }" gitHub = if process.env.GITHUB_PRS_GHE_API_URL? Octonode.client(process.env.GITHUB_PRS_OAUTH_TOKEN, hostname: process.env.GITHUB_PRS_GHE_API_URL) else Octonode.client(process.env.GITHUB_PRS_OAUTH_TOKEN) repos = [] getAllRepos getAllPullRequests
true
# Description: # A way to list all currently open PRs on GitHub. # # Dependencies: # "async": "~1.4.2", # "bluebird": "~2.10.0", # "octonode": "> 0.6.0 < 0.8.0" # # Configuration: # GITHUB_PRS_OAUTH_TOKEN = # (Required) A GitHub OAuth token generated from your account. # GITHUB_PRS_USER = # (Required if GITHUB_PRS_TEAM_ID is not set) A GitHub username. # GITHUB_PRS_TEAM_ID = # (Required if GITHUB_PRS_USER is not set) A GitHub Team ID returned from GitHub's API. Takes precedence over GITHUB_PRS_USER. # GITHUB_PRS_REPO_OWNER_FILTER = # (Optional) A string that contains the names of users you'd like to filter by. (Helpful when you have a lot of forks on your repos that you don't care about.) # # Commands: # hubot pr - Returns a list of open PR links from GitHub. # hubot prs - Same as "hubot pr". # # Author: # helious (PI:NAME:<NAME>END_PI) # davedash (PI:NAME:<NAME>END_PI) async = require 'async' Promise = require 'bluebird' Octonode = Promise.promisifyAll(require 'octonode') module.exports = (robot) -> robot.respond /(pr\b|prs)/i, (msg) -> getAllRepos = (done) -> getReposByPage = (page) -> userGitHub = if process.env.GITHUB_PRS_TEAM_ID? gitHub.team process.env.GITHUB_PRS_TEAM_ID else gitHub.user process.env.GITHUB_PRS_USER repoIsDesired = (repoOwner) -> repoOwners = process.env.GITHUB_PRS_REPO_OWNER_FILTER return true unless repoOwners repoOwners? and repoOwners.indexOf(repoOwner) > -1 userGitHub .reposAsync(per_page: 100, page: page) .then (data) -> reposByPage = data[0] for repo in reposByPage repoOwner = repo.full_name.split('/')[0] repos.push repo if repoIsDesired(repoOwner) if reposByPage.length is 100 getReposByPage page + 1 else done() getReposByPage 1 getAllPullRequests = -> getPullRequests = (done, repo) -> gitHubRepo = gitHub.repo repo prs = [] gitHubRepo .prsAsync() .then (data) -> postToChat = (pr) -> lastUpdated = (date) -> pluralize = (amount, unit) -> if amount "#{ amount } #{ unit }#{ if amount > 1 then 's' else '' }" else '' difference = Date.now() - Date.parse(date) days = Math.floor difference / 1000 / 60 / 60 / 24 hours = Math.floor(difference / 1000 / 60 / 60) - 24 * days minutes = Math.floor(difference / 1000 / 60) - 24 * 60 * days - 60 * hours hasValidTime = "#{ days }#{ hours }#{ minutes }" isnt '' timeString = if hasValidTime then "#{ pluralize days, 'day' } #{ pluralize hours, 'hour' } #{ pluralize minutes, 'minute' } ago".trim() else 'just now' "last updated #{ timeString }" number = pr.number url = pr.html_url title = pr.title updatedAt = pr.updated_at user = pr.user.login people = user if pr.assignee people = "#{ user }->#{ pr.assignee.login }" if robot.adapterName is 'slack' msg.send ":octocat: #{ title } - #{ people } - #{ url } - #{ lastUpdated updatedAt }" else msg.send "/me - #{ repo } - ##{ number } - #{ title } - #{ people } - #{ url } - #{ lastUpdated updatedAt }" prs = data[0] postToChat pr for pr in prs .then -> done null, prs.length parallelifyGetPullRequests = (repo) -> (done) -> getPullRequests(done, repo.full_name) parallelGetPullRequests = [] for repo in repos parallelGetPullRequests.push parallelifyGetPullRequests(repo) async.parallel parallelGetPullRequests, (err, results) -> pullRequestCount = if results.length > 0 then results.reduce (a, b) -> a + b else 0 isSingular = pullRequestCount is 1 msg.send "There #{ if isSingular then 'is' else 'are' } #{ pullRequestCount } open Pull Request#{ if isSingular then '.' else 's.' }" gitHub = if process.env.GITHUB_PRS_GHE_API_URL? Octonode.client(process.env.GITHUB_PRS_OAUTH_TOKEN, hostname: process.env.GITHUB_PRS_GHE_API_URL) else Octonode.client(process.env.GITHUB_PRS_OAUTH_TOKEN) repos = [] getAllRepos getAllPullRequests
[ { "context": "# VexTab Artist\n# Copyright 2012 Mohit Cheppudira <mohit@muthanna.com>\n#\n# This class is responsibl", "end": 49, "score": 0.9998893141746521, "start": 33, "tag": "NAME", "value": "Mohit Cheppudira" }, { "context": " VexTab Artist\n# Copyright 2012 Mohit Cheppudira <m...
src/artist.coffee
TheodoreChu/vextab
1
# VexTab Artist # Copyright 2012 Mohit Cheppudira <mohit@muthanna.com> # # This class is responsible for rendering the elements # parsed by Vex.Flow.VexTab. import Vex from 'vexflow' import * as _ from 'lodash' class Artist @DEBUG = false L = (args...) -> console?.log("(Vex.Flow.Artist)", args...) if Artist.DEBUG @NOLOGO = false constructor: (@x, @y, @width, options) -> @options = font_face: "Arial" font_size: 10 font_style: null bottom_spacing: 20 + (if Artist.NOLOGO then 0 else 10) tab_stave_lower_spacing: 10 note_stave_lower_spacing: 0 scale: 1.0 _.extend(@options, options) if options? @reset() reset: -> @tuning = new Vex.Flow.Tuning() @key_manager = new Vex.Flow.KeyManager("C") @music_api = new Vex.Flow.Music() # User customizations @customizations = "font-size": @options.font_size "font-face": @options.font_face "font-style": @options.font_style "annotation-position": "bottom" "scale": @options.scale "width": @width "stave-distance": 0 "space": 0 "player": "false" "tempo": 120 "instrument": "acoustic_grand_piano" "accidentals": "standard" # standard / cautionary "tab-stems": "false" "tab-stem-direction": "up" "beam-rests": "true" "beam-stemlets": "true" "beam-middle-only": "false" "connector-space": 5 # Generated elements @staves = [] @tab_articulations = [] @stave_articulations = [] # Voices for player @player_voices = [] # Current state @last_y = @y @current_duration = "q" @current_clef = "treble" @current_bends = {} @current_octave_shift = 0 @bend_start_index = null @bend_start_strings = null @rendered = false @renderer_context = null attachPlayer: (player) -> @player = player setOptions: (options) -> L "setOptions: ", options # Set @customizations valid_options = _.keys(@customizations) for k, v of options if k in valid_options @customizations[k] = v else throw new Vex.RERR("ArtistError", "Invalid option '#{k}'") @last_y += parseInt(@customizations.space, 10) @last_y += 15 if @customizations.player is "true" getPlayerData: -> voices: @player_voices context: @renderer_context scale: @customizations.scale parseBool = (str) -> return (str == "true") formatAndRender = (ctx, tab, score, text_notes, customizations, options) -> tab_stave = tab.stave if tab? score_stave = score.stave if score? tab_voices = [] score_voices = [] text_voices = [] beams = [] format_stave = null text_stave = null beam_config = beam_rests: parseBool(customizations["beam-rests"]) show_stemlets: parseBool(customizations["beam-stemlets"]) beam_middle_only: parseBool(customizations["beam-middle-only"]) groups: options.beam_groups if tab? multi_voice = if (tab.voices.length > 1) then true else false for notes, i in tab.voices continue if _.isEmpty(notes) _.each(notes, (note) -> note.setStave(tab_stave)) voice = new Vex.Flow.Voice(Vex.Flow.TIME4_4). setMode(Vex.Flow.Voice.Mode.SOFT) voice.addTickables notes tab_voices.push voice if customizations["tab-stems"] == "true" if multi_voice beam_config.stem_direction = if i == 0 then 1 else -1 else beam_config.stem_direction = if customizations["tab-stem-direction"] == "down" then -1 else 1 beam_config.beam_rests = false beams = beams.concat(Vex.Flow.Beam.generateBeams(voice.getTickables(), beam_config)) format_stave = tab_stave text_stave = tab_stave beam_config.beam_rests = parseBool(customizations["beam-rests"]) if score? multi_voice = if (score.voices.length > 1) then true else false for notes, i in score.voices continue if _.isEmpty(notes) stem_direction = if i == 0 then 1 else -1 _.each(notes, (note) -> note.setStave(score_stave)) voice = new Vex.Flow.Voice(Vex.Flow.TIME4_4). setMode(Vex.Flow.Voice.Mode.SOFT) voice.addTickables notes score_voices.push voice if multi_voice beam_config.stem_direction = stem_direction beams = beams.concat(Vex.Flow.Beam.generateBeams(notes, beam_config)) else beam_config.stem_direction = null beams = beams.concat(Vex.Flow.Beam.generateBeams(notes, beam_config)) format_stave = score_stave text_stave = score_stave for notes in text_notes continue if _.isEmpty(notes) _.each(notes, (voice) -> voice.setStave(text_stave)) voice = new Vex.Flow.Voice(Vex.Flow.TIME4_4). setMode(Vex.Flow.Voice.Mode.SOFT) voice.addTickables notes text_voices.push voice if format_stave? format_voices = [] formatter = new Vex.Flow.Formatter() align_rests = false if tab? formatter.joinVoices(tab_voices) unless _.isEmpty(tab_voices) format_voices = tab_voices if score? formatter.joinVoices(score_voices) unless _.isEmpty(score_voices) format_voices = format_voices.concat(score_voices) align_rests = true if score_voices.length > 1 if not _.isEmpty(text_notes) and not _.isEmpty(text_voices) formatter.joinVoices(text_voices) format_voices = format_voices.concat(text_voices) formatter.formatToStave(format_voices, format_stave, {align_rests: align_rests}) unless _.isEmpty(format_voices) _.each(tab_voices, (voice) -> voice.draw(ctx, tab_stave)) if tab? _.each(score_voices, (voice) -> voice.draw(ctx, score_stave)) if score? _.each(beams, (beam) -> beam.setContext(ctx).draw()) _.each(text_voices, (voice) -> voice.draw(ctx, text_stave)) if not _.isEmpty(text_notes) if tab? and score? (new Vex.Flow.StaveConnector(score.stave, tab.stave)) .setType(Vex.Flow.StaveConnector.type.BRACKET) .setContext(ctx).draw() if score? then score_voices else tab_voices render: (renderer) -> L "Render: ", @options @closeBends() renderer.resize(@customizations.width * @customizations.scale, (@last_y + @options.bottom_spacing) * @customizations.scale) ctx = renderer.getContext() ctx.scale(@customizations.scale, @customizations.scale) ctx.clear() ctx.setFont(@options.font_face, @options.font_size, "") @renderer_context = ctx setBar = (stave, notes) -> last_note = _.last(notes) if last_note instanceof Vex.Flow.BarNote notes.pop() stave.setEndBarType(last_note.getType()) for stave in @staves L "Rendering staves." # If the last note is a bar, then remove it and render it as a stave modifier. setBar(stave.tab, stave.tab_notes) if stave.tab? setBar(stave.note, stave.note_notes) if stave.note? stave.tab.setContext(ctx).draw() if stave.tab? stave.note.setContext(ctx).draw() if stave.note? stave.tab_voices.push(stave.tab_notes) stave.note_voices.push(stave.note_notes) voices = formatAndRender(ctx, if stave.tab? then {stave: stave.tab, voices: stave.tab_voices} else null, if stave.note? then {stave: stave.note, voices: stave.note_voices} else null, stave.text_voices, @customizations, {beam_groups: stave.beam_groups}) @player_voices.push(voices) L "Rendering tab articulations." for articulation in @tab_articulations articulation.setContext(ctx).draw() L "Rendering note articulations." for articulation in @stave_articulations articulation.setContext(ctx).draw() if @player? if @customizations.player is "true" @player.setTempo(parseInt(@customizations.tempo, 10)) @player.setInstrument(@customizations.instrument) @player.render() else @player.removeControls() @rendered = true unless Artist.NOLOGO LOGO = "vexflow.com" width = ctx.measureText(LOGO).width ctx.save() ctx.setFont("Times", 10, "italic") ctx.fillText(LOGO, (@customizations.width - width) / 2, @last_y + 25) ctx.restore() isRendered: -> @rendered draw: (renderer) -> @render renderer # Given a fret/string pair, returns a note, octave, and required accidentals # based on current guitar tuning and stave key. The accidentals may be different # for repeats of the same notes because they get set (or cancelled) by the Key # Manager. getNoteForFret: (fret, string) -> spec = @tuning.getNoteForFret(fret, string) spec_props = Vex.Flow.keyProperties(spec) selected_note = @key_manager.selectNote(spec_props.key) accidental = null # Do we need to specify an explicit accidental? switch @customizations.accidentals when "standard" if selected_note.change accidental = if selected_note.accidental? then selected_note.accidental else "n" when "cautionary" if selected_note.change accidental = if selected_note.accidental? then selected_note.accidental else "n" else accidental = if selected_note.accidental? then selected_note.accidental + "_c" else throw new Vex.RERR("ArtistError", "Invalid value for option 'accidentals': #{@customizations.accidentals}") new_note = selected_note.note new_octave = spec_props.octave # TODO(0xfe): This logic should probably be in the KeyManager code old_root = @music_api.getNoteParts(spec_props.key).root new_root = @music_api.getNoteParts(selected_note.note).root # Figure out if there's an octave shift based on what the Key # Manager just told us about the note. if new_root == "b" and old_root == "c" new_octave-- else if new_root == "c" and old_root == "b" new_octave++ return [new_note, new_octave, accidental] getNoteForABC: (abc, string) -> key = abc.key octave = string accidental = abc.accidental accidental += "_#{abc.accidental_type}" if abc.accidental_type? return [key, octave, accidental] addStaveNote: (note_params) -> params = is_rest: false play_note: null _.extend(params, note_params) stave_notes = _.last(@staves).note_notes stave_note = new Vex.Flow.StaveNote({ keys: params.spec duration: @current_duration + (if params.is_rest then "r" else "") clef: if params.is_rest then "treble" else @current_clef auto_stem: if params.is_rest then false else true }) for acc, index in params.accidentals if acc? parts = acc.split("_") new_accidental = new Vex.Flow.Accidental(parts[0]) if parts.length > 1 and parts[1] == "c" new_accidental.setAsCautionary() stave_note.addAccidental(index, new_accidental) if @current_duration[@current_duration.length - 1] == "d" stave_note.addDotToAll() stave_note.setPlayNote(params.play_note) if params.play_note? stave_notes.push stave_note addTabNote: (spec, play_note=null) -> tab_notes = _.last(@staves).tab_notes new_tab_note = new Vex.Flow.TabNote({ positions: spec, duration: @current_duration }, (@customizations["tab-stems"] == "true") ) new_tab_note.setPlayNote(play_note) if play_note? tab_notes.push new_tab_note if @current_duration[@current_duration.length - 1] == "d" new_tab_note.addDot() makeDuration = (time, dot) -> time + (if dot then "d" else "") setDuration: (time, dot=false) -> t = time.split(/\s+/) L "setDuration: ", t[0], dot @current_duration = makeDuration(t[0], dot) addBar: (type) -> L "addBar: ", type @closeBends() @key_manager.reset() stave = _.last(@staves) TYPE = Vex.Flow.Barline.type type = switch type when "single" TYPE.SINGLE when "double" TYPE.DOUBLE when "end" TYPE.END when "repeat-begin" TYPE.REPEAT_BEGIN when "repeat-end" TYPE.REPEAT_END when "repeat-both" TYPE.REPEAT_BOTH else TYPE.SINGLE bar_note = new Vex.Flow.BarNote().setType(type) stave.tab_notes.push(bar_note) stave.note_notes.push(bar_note) if stave.note? makeBend = (from_fret, to_fret) -> direction = Vex.Flow.Bend.UP text = "" if parseInt(from_fret, 10) > parseInt(to_fret, 10) direction = Vex.Flow.Bend.DOWN else text = switch Math.abs(to_fret - from_fret) when 1 then "1/2" when 2 then "Full" when 3 then "1 1/2" else "Bend to #{to_fret}" return {type: direction, text: text} openBends: (first_note, last_note, first_indices, last_indices) -> L "openBends", first_note, last_note, first_indices, last_indices tab_notes = _.last(@staves).tab_notes start_note = first_note start_indices = first_indices if _.isEmpty(@current_bends) @bend_start_index = tab_notes.length - 2 @bend_start_strings = first_indices else start_note = tab_notes[@bend_start_index] start_indices = @bend_start_strings first_frets = start_note.getPositions() last_frets = last_note.getPositions() for index, i in start_indices last_index = last_indices[i] from_fret = first_note.getPositions()[first_indices[i]] to_fret = last_frets[last_index] @current_bends[index] ?= [] @current_bends[index].push makeBend(from_fret.fret, to_fret.fret) # Close and apply all the bends to the last N notes. closeBends: (offset=1) -> return unless @bend_start_index? L "closeBends(#{offset})" tab_notes = _.last(@staves).tab_notes for k, v of @current_bends phrase = [] for bend in v phrase.push bend tab_notes[@bend_start_index].addModifier( new Vex.Flow.Bend(null, null, phrase), k) # Replace bent notes with ghosts (make them invisible) for tab_note in tab_notes[@bend_start_index+1..((tab_notes.length - 2) + offset)] tab_note.setGhost(true) @current_bends = {} @bend_start_index = null makeTuplets: (tuplets, notes) -> L "makeTuplets", tuplets, notes notes ?= tuplets return unless _.last(@staves).note stave_notes = _.last(@staves).note_notes tab_notes = _.last(@staves).tab_notes throw new Vex.RERR("ArtistError", "Not enough notes for tuplet") if stave_notes.length < notes modifier = new Vex.Flow.Tuplet(stave_notes[stave_notes.length - notes..], {num_notes: tuplets}) @stave_articulations.push modifier # Creating a Vex.Flow.Tuplet corrects the ticks for the notes, so it needs to # be created whether or not it gets rendered. Below, if tab stems are not required # the created tuplet is simply thrown away. tab_modifier = new Vex.Flow.Tuplet(tab_notes[tab_notes.length - notes..], {num_notes: tuplets}) if @customizations["tab-stems"] == "true" @tab_articulations.push tab_modifier getFingering = (text) -> text.match(/^\.fingering\/([^.]+)\./) makeFingering: (text) -> parts = getFingering(text) POS = Vex.Flow.Modifier.Position fingers = [] fingering = [] if parts? fingers = (p.trim() for p in parts[1].split(/-/)) else return null badFingering = -> new Vex.RERR("ArtistError", "Bad fingering: #{parts[1]}") for finger in fingers pieces = finger.match(/(\d+):([ablr]):([fs]):([^-.]+)/) throw badFingering() unless pieces? note_number = parseInt(pieces[1], 10) - 1 position = POS.RIGHT switch pieces[2] when "l" position = POS.LEFT when "r" position = POS.RIGHT when "a" position = POS.ABOVE when "b" position = POS.BELOW modifier = null number = pieces[4] switch pieces[3] when "s" modifier = new Vex.Flow.StringNumber(number).setPosition(position) when "f" modifier = new Vex.Flow.FretHandFinger(number).setPosition(position) fingering.push({num: note_number, modifier: modifier}) return fingering getStrokeParts = (text) -> text.match(/^\.stroke\/([^.]+)\./) makeStroke: (text) -> parts = getStrokeParts(text) TYPE = Vex.Flow.Stroke.Type type = null if parts? switch parts[1] when "bu" type = TYPE.BRUSH_UP when "bd" type = TYPE.BRUSH_DOWN when "ru" type = TYPE.ROLL_UP when "rd" type = TYPE.ROLL_DOWN when "qu" type = TYPE.RASQUEDO_UP when "qd" type = TYPE.RASQUEDO_DOWN else throw new Vex.RERR("ArtistError", "Invalid stroke type: #{parts[1]}") return new Vex.Flow.Stroke(type) else return null getScoreArticulationParts = (text) -> text.match(/^\.(a[^\/]*)\/(t|b)[^.]*\./) makeScoreArticulation: (text) -> parts = getScoreArticulationParts(text) if parts? type = parts[1] position = parts[2] POSTYPE = Vex.Flow.Modifier.Position pos = if position is "t" then POSTYPE.ABOVE else POSTYPE.BELOW return new Vex.Flow.Articulation(type).setPosition(pos) else return null makeAnnotation: (text) -> font_face = @customizations["font-face"] font_size = @customizations["font-size"] font_style = @customizations["font-style"] aposition = @customizations["annotation-position"] VJUST = Vex.Flow.Annotation.VerticalJustify default_vjust = if aposition is "top" then VJUST.TOP else VJUST.BOTTOM makeIt = (text, just=default_vjust) -> new Vex.Flow.Annotation(text). setFont(font_face, font_size, font_style). setVerticalJustification(just) parts = text.match(/^\.([^-]*)-([^-]*)-([^.]*)\.(.*)/) if parts? font_face = parts[1] font_size = parts[2] font_style = parts[3] text = parts[4] return if text then makeIt(text) else null parts = text.match(/^\.([^.]*)\.(.*)/) if parts? just = default_vjust text = parts[2] switch parts[1] when "big" font_style = "bold" font_size = "14" when "italic", "italics" font_face = "Times" font_style = "italic" when "medium" font_size = "12" when "top" just = VJUST.TOP @customizations["annotation-position"] = "top" when "bottom" just = VJUST.BOTTOM @customizations["annotation-position"] = "bottom" return if text then makeIt(text, just) else null return makeIt(text) addAnnotations: (annotations) -> stave = _.last(@staves) stave_notes = stave.note_notes tab_notes = stave.tab_notes if annotations.length > tab_notes.length throw new Vex.RERR("ArtistError", "More annotations than note elements") # Add text annotations if stave.tab for tab_note, i in tab_notes[tab_notes.length - annotations.length..] if getScoreArticulationParts(annotations[i]) score_articulation = @makeScoreArticulation(annotations[i]) tab_note.addModifier(score_articulation, 0) else if getStrokeParts(annotations[i]) stroke = @makeStroke(annotations[i]) tab_note.addModifier(stroke, 0) else annotation = @makeAnnotation(annotations[i]) tab_note.addModifier(@makeAnnotation(annotations[i]), 0) if annotation else for note, i in stave_notes[stave_notes.length - annotations.length..] unless getScoreArticulationParts(annotations[i]) annotation = @makeAnnotation(annotations[i]) note.addAnnotation(0, @makeAnnotation(annotations[i])) if annotation # Add glyph articulations, strokes, or fingerings on score if stave.note for note, i in stave_notes[stave_notes.length - annotations.length..] score_articulation = @makeScoreArticulation(annotations[i]) note.addArticulation(0, score_articulation) if score_articulation? stroke = @makeStroke(annotations[i]) note.addStroke(0, stroke) if stroke? fingerings = @makeFingering(annotations[i]) if fingerings? try (note.addModifier(fingering.num, fingering.modifier) for fingering in fingerings) catch e throw new Vex.RERR("ArtistError", "Bad note number in fingering: #{annotations[i]}") addTabArticulation: (type, first_note, last_note, first_indices, last_indices) -> L "addTabArticulations: ", type, first_note, last_note, first_indices, last_indices if type == "t" last_note.addModifier( new Vex.Flow.Annotation("T"). setVerticalJustification(Vex.Flow.Annotation.VerticalJustify.BOTTOM)) if _.isEmpty(first_indices) and _.isEmpty(last_indices) then return articulation = null if type == "s" articulation = new Vex.Flow.TabSlide({ first_note: first_note last_note: last_note first_indices: first_indices last_indices: last_indices }) if type in ["h", "p"] articulation = new Vex.Flow.TabTie({ first_note: first_note last_note: last_note first_indices: first_indices last_indices: last_indices }, type.toUpperCase()) if type in ["T", "t"] articulation = new Vex.Flow.TabTie({ first_note: first_note last_note: last_note first_indices: first_indices last_indices: last_indices }, " ") if type == "b" @openBends(first_note, last_note, first_indices, last_indices) @tab_articulations.push articulation if articulation? addStaveArticulation: (type, first_note, last_note, first_indices, last_indices) -> L "addStaveArticulations: ", type, first_note, last_note, first_indices, last_indices articulation = null if type in ["b", "s", "h", "p", "t", "T"] articulation = new Vex.Flow.StaveTie({ first_note: first_note last_note: last_note first_indices: first_indices last_indices: last_indices }) @stave_articulations.push articulation if articulation? # This gets the previous (second-to-last) non-bar non-ghost note. getPreviousNoteIndex: -> tab_notes = _.last(@staves).tab_notes index = 2 while index <= tab_notes.length note = tab_notes[tab_notes.length - index] return (tab_notes.length - index) if note instanceof Vex.Flow.TabNote index++ return -1 addDecorator: (decorator) -> L "addDecorator: ", decorator return unless decorator? stave = _.last(@staves) tab_notes = stave.tab_notes score_notes = stave.note_notes modifier = null score_modifier = null if decorator == "v" modifier = new Vex.Flow.Vibrato() if decorator == "V" modifier = new Vex.Flow.Vibrato().setHarsh(true) if decorator == "u" modifier = new Vex.Flow.Articulation("a|").setPosition(Vex.Flow.Modifier.Position.BELOW) score_modifier = new Vex.Flow.Articulation("a|").setPosition(Vex.Flow.Modifier.Position.BELOW) if decorator == "d" modifier = new Vex.Flow.Articulation("am").setPosition(Vex.Flow.Modifier.Position.BELOW) score_modifier = new Vex.Flow.Articulation("am").setPosition(Vex.Flow.Modifier.Position.BELOW) _.last(tab_notes).addModifier(modifier, 0) if modifier? _.last(score_notes)?.addArticulation(0, score_modifier) if score_modifier? addArticulations: (articulations) -> L "addArticulations: ", articulations stave = _.last(@staves) tab_notes = stave.tab_notes stave_notes = stave.note_notes if _.isEmpty(tab_notes) or _.isEmpty(articulations) @closeBends(0) return current_tab_note = _.last(tab_notes) has_bends = false for valid_articulation in ["b", "s", "h", "p", "t", "T", "v", "V"] indices = (i for art, i in articulations when art? and art == valid_articulation) if _.isEmpty(indices) then continue if valid_articulation is "b" then has_bends = true prev_index = @getPreviousNoteIndex() if prev_index is -1 prev_tab_note = null prev_indices = null else prev_tab_note = tab_notes[prev_index] # Figure out which strings the articulations are on this_strings = (n.str for n, i in current_tab_note.getPositions() when i in indices) # Only allows articulations where both notes are on the same strings valid_strings = (pos.str for pos, i in prev_tab_note.getPositions() when pos.str in this_strings) # Get indices of articulated notes on previous chord prev_indices = (i for n, i in prev_tab_note.getPositions() when n.str in valid_strings) # Get indices of articulated notes on current chord current_indices = (i for n, i in current_tab_note.getPositions() when n.str in valid_strings) if stave.tab? @addTabArticulation(valid_articulation, prev_tab_note, current_tab_note, prev_indices, current_indices) if stave.note? @addStaveArticulation(valid_articulation, stave_notes[prev_index], _.last(stave_notes), prev_indices, current_indices) @closeBends(0) unless has_bends addRest: (params) -> L "addRest: ", params @closeBends() if params["position"] == 0 @addStaveNote spec: ["r/4"] accidentals: [] is_rest: true else position = @tuning.getNoteForFret((parseInt(params["position"], 10) + 5) * 2, 6) @addStaveNote spec: [position] accidentals: [] is_rest: true tab_notes = _.last(@staves).tab_notes if @customizations["tab-stems"] == "true" tab_note = new Vex.Flow.StaveNote({ keys: [position || "r/4"] duration: @current_duration + "r" clef: "treble" auto_stem: false }) if @current_duration[@current_duration.length - 1] == "d" tab_note.addDot(0) tab_notes.push tab_note else tab_notes.push new Vex.Flow.GhostNote(@current_duration) addChord: (chord, chord_articulation, chord_decorator) -> return if _.isEmpty(chord) L "addChord: ", chord stave = _.last(@staves) specs = [] # The stave note specs play_notes = [] # Notes to be played by audio players accidentals = [] # The stave accidentals articulations = [] # Articulations (ties, bends, taps) decorators = [] # Decorators (vibratos, harmonics) tab_specs = [] # The tab notes durations = [] # The duration of each position num_notes = 0 # Chords are complicated, because they can contain little # lines one each string. We need to keep track of the motion # of each line so we know which tick they belong in. current_string = _.first(chord).string current_position = 0 for note in chord num_notes++ if note.abc? or note.string != current_string current_position = 0 current_string = note.string unless specs[current_position]? # New position. Create new element arrays for this # position. specs[current_position] = [] play_notes[current_position] = [] accidentals[current_position] = [] tab_specs[current_position] = [] articulations[current_position] = [] decorators[current_position] = [] [new_note, new_octave, accidental] = [null, null, null] play_note = null if note.abc? octave = if note.octave? then note.octave else note.string [new_note, new_octave, accidental] = @getNoteForABC(note.abc, octave) if accidental? acc = accidental.split("_")[0] else acc = "" play_note = "#{new_note}#{acc}" note.fret = 'X' unless note.fret? else if note.fret? [new_note, new_octave, accidental] = @getNoteForFret(note.fret, note.string) play_note = @tuning.getNoteForFret(note.fret, note.string).split("/")[0] else throw new Vex.RERR("ArtistError", "No note specified") play_octave = parseInt(new_octave, 10) + @current_octave_shift current_duration = if note.time? then {time: note.time, dot: note.dot} else null specs[current_position].push "#{new_note}/#{new_octave}" play_notes[current_position].push "#{play_note}/#{play_octave}" accidentals[current_position].push accidental tab_specs[current_position].push {fret: note.fret, str: note.string} articulations[current_position].push note.articulation if note.articulation? durations[current_position] = current_duration decorators[current_position] = note.decorator if note.decorator? current_position++ for spec, i in specs saved_duration = @current_duration @setDuration(durations[i].time, durations[i].dot) if durations[i]? @addTabNote tab_specs[i], play_notes[i] @addStaveNote {spec: spec, accidentals: accidentals[i], play_note: play_notes[i]} if stave.note? @addArticulations articulations[i] @addDecorator decorators[i] if decorators[i]? if chord_articulation? art = [] art.push chord_articulation for num in [1..num_notes] @addArticulations art @addDecorator chord_decorator if chord_decorator? addNote: (note) -> @addChord([note]) addTextVoice: -> _.last(@staves).text_voices.push [] setTextFont: (font) -> if font? parts = font.match(/([^-]*)-([^-]*)-([^.]*)/) if parts? @customizations["font-face"] = parts[1] @customizations["font-size"] = parseInt(parts[2], 10) @customizations["font-style"] = parts[3] addTextNote: (text, position=0, justification="center", smooth=true, ignore_ticks=false) -> voices = _.last(@staves).text_voices throw new Vex.RERR("ArtistError", "Can't add text note without text voice") if _.isEmpty(voices) font_face = @customizations["font-face"] font_size = @customizations["font-size"] font_style = @customizations["font-style"] just = switch justification when "center" Vex.Flow.TextNote.Justification.CENTER when "left" Vex.Flow.TextNote.Justification.LEFT when "right" Vex.Flow.TextNote.Justification.RIGHT else Vex.Flow.TextNote.Justification.CENTER duration = if ignore_ticks then "b" else @current_duration struct = text: text duration: duration smooth: smooth ignore_ticks: ignore_ticks font: family: font_face size: font_size weight: font_style if text[0] == "#" struct.glyph = text[1..] note = new Vex.Flow.TextNote(struct). setLine(position).setJustification(just) _.last(voices).push(note) addVoice: (options) -> @closeBends() stave = _.last(@staves) return @addStave(options) unless stave? unless _.isEmpty(stave.tab_notes) stave.tab_voices.push(stave.tab_notes) stave.tab_notes = [] unless _.isEmpty(stave.note_notes) stave.note_voices.push(stave.note_notes) stave.note_notes = [] addStave: (element, options) -> opts = tuning: "standard" clef: "treble" key: "C" notation: if element == "tabstave" then "false" else "true" tablature: if element == "stave" then "false" else "true" strings: 6 _.extend(opts, options) L "addStave: ", element, opts tab_stave = null note_stave = null # This is used to line up tablature and notation. start_x = @x + @customizations["connector-space"] tabstave_start_x = 40 if opts.notation is "true" note_stave = new Vex.Flow.Stave(start_x, @last_y, @customizations.width - 20, {left_bar: false}) note_stave.addClef(opts.clef) if opts.clef isnt "none" note_stave.addKeySignature(opts.key) note_stave.addTimeSignature(opts.time) if opts.time? @last_y += note_stave.getHeight() + @options.note_stave_lower_spacing + parseInt(@customizations["stave-distance"], 10) tabstave_start_x = note_stave.getNoteStartX() @current_clef = if opts.clef is "none" then "treble" else opts.clef if opts.tablature is "true" tab_stave = new Vex.Flow.TabStave(start_x, @last_y, @customizations.width - 20, {left_bar: false}).setNumLines(opts.strings) tab_stave.addTabGlyph() if opts.clef isnt "none" tab_stave.setNoteStartX(tabstave_start_x) @last_y += tab_stave.getHeight() + @options.tab_stave_lower_spacing @closeBends() beam_groups = Vex.Flow.Beam.getDefaultBeamGroups(opts.time) @staves.push { tab: tab_stave, note: note_stave, tab_voices: [], note_voices: [], tab_notes: [], note_notes: [], text_voices: [], beam_groups: beam_groups } @tuning.setTuning(opts.tuning) @key_manager.setKey(opts.key) return runCommand: (line, _l=0, _c=0) -> L "runCommand: ", line words = line.split(/\s+/) switch words[0] when "octave-shift" @current_octave_shift = parseInt(words[1], 10) L "Octave shift: ", @current_octave_shift else throw new Vex.RERR("ArtistError", "Invalid command '#{words[0]}' at line #{_l} column #{_c}") export default Artist
90446
# VexTab Artist # Copyright 2012 <NAME> <<EMAIL>> # # This class is responsible for rendering the elements # parsed by Vex.Flow.VexTab. import Vex from 'vexflow' import * as _ from 'lodash' class Artist @DEBUG = false L = (args...) -> console?.log("(Vex.Flow.Artist)", args...) if Artist.DEBUG @NOLOGO = false constructor: (@x, @y, @width, options) -> @options = font_face: "Arial" font_size: 10 font_style: null bottom_spacing: 20 + (if Artist.NOLOGO then 0 else 10) tab_stave_lower_spacing: 10 note_stave_lower_spacing: 0 scale: 1.0 _.extend(@options, options) if options? @reset() reset: -> @tuning = new Vex.Flow.Tuning() @key_manager = new Vex.Flow.KeyManager("C") @music_api = new Vex.Flow.Music() # User customizations @customizations = "font-size": @options.font_size "font-face": @options.font_face "font-style": @options.font_style "annotation-position": "bottom" "scale": @options.scale "width": @width "stave-distance": 0 "space": 0 "player": "false" "tempo": 120 "instrument": "acoustic_grand_piano" "accidentals": "standard" # standard / cautionary "tab-stems": "false" "tab-stem-direction": "up" "beam-rests": "true" "beam-stemlets": "true" "beam-middle-only": "false" "connector-space": 5 # Generated elements @staves = [] @tab_articulations = [] @stave_articulations = [] # Voices for player @player_voices = [] # Current state @last_y = @y @current_duration = "q" @current_clef = "treble" @current_bends = {} @current_octave_shift = 0 @bend_start_index = null @bend_start_strings = null @rendered = false @renderer_context = null attachPlayer: (player) -> @player = player setOptions: (options) -> L "setOptions: ", options # Set @customizations valid_options = _.keys(@customizations) for k, v of options if k in valid_options @customizations[k] = v else throw new Vex.RERR("ArtistError", "Invalid option '#{k}'") @last_y += parseInt(@customizations.space, 10) @last_y += 15 if @customizations.player is "true" getPlayerData: -> voices: @player_voices context: @renderer_context scale: @customizations.scale parseBool = (str) -> return (str == "true") formatAndRender = (ctx, tab, score, text_notes, customizations, options) -> tab_stave = tab.stave if tab? score_stave = score.stave if score? tab_voices = [] score_voices = [] text_voices = [] beams = [] format_stave = null text_stave = null beam_config = beam_rests: parseBool(customizations["beam-rests"]) show_stemlets: parseBool(customizations["beam-stemlets"]) beam_middle_only: parseBool(customizations["beam-middle-only"]) groups: options.beam_groups if tab? multi_voice = if (tab.voices.length > 1) then true else false for notes, i in tab.voices continue if _.isEmpty(notes) _.each(notes, (note) -> note.setStave(tab_stave)) voice = new Vex.Flow.Voice(Vex.Flow.TIME4_4). setMode(Vex.Flow.Voice.Mode.SOFT) voice.addTickables notes tab_voices.push voice if customizations["tab-stems"] == "true" if multi_voice beam_config.stem_direction = if i == 0 then 1 else -1 else beam_config.stem_direction = if customizations["tab-stem-direction"] == "down" then -1 else 1 beam_config.beam_rests = false beams = beams.concat(Vex.Flow.Beam.generateBeams(voice.getTickables(), beam_config)) format_stave = tab_stave text_stave = tab_stave beam_config.beam_rests = parseBool(customizations["beam-rests"]) if score? multi_voice = if (score.voices.length > 1) then true else false for notes, i in score.voices continue if _.isEmpty(notes) stem_direction = if i == 0 then 1 else -1 _.each(notes, (note) -> note.setStave(score_stave)) voice = new Vex.Flow.Voice(Vex.Flow.TIME4_4). setMode(Vex.Flow.Voice.Mode.SOFT) voice.addTickables notes score_voices.push voice if multi_voice beam_config.stem_direction = stem_direction beams = beams.concat(Vex.Flow.Beam.generateBeams(notes, beam_config)) else beam_config.stem_direction = null beams = beams.concat(Vex.Flow.Beam.generateBeams(notes, beam_config)) format_stave = score_stave text_stave = score_stave for notes in text_notes continue if _.isEmpty(notes) _.each(notes, (voice) -> voice.setStave(text_stave)) voice = new Vex.Flow.Voice(Vex.Flow.TIME4_4). setMode(Vex.Flow.Voice.Mode.SOFT) voice.addTickables notes text_voices.push voice if format_stave? format_voices = [] formatter = new Vex.Flow.Formatter() align_rests = false if tab? formatter.joinVoices(tab_voices) unless _.isEmpty(tab_voices) format_voices = tab_voices if score? formatter.joinVoices(score_voices) unless _.isEmpty(score_voices) format_voices = format_voices.concat(score_voices) align_rests = true if score_voices.length > 1 if not _.isEmpty(text_notes) and not _.isEmpty(text_voices) formatter.joinVoices(text_voices) format_voices = format_voices.concat(text_voices) formatter.formatToStave(format_voices, format_stave, {align_rests: align_rests}) unless _.isEmpty(format_voices) _.each(tab_voices, (voice) -> voice.draw(ctx, tab_stave)) if tab? _.each(score_voices, (voice) -> voice.draw(ctx, score_stave)) if score? _.each(beams, (beam) -> beam.setContext(ctx).draw()) _.each(text_voices, (voice) -> voice.draw(ctx, text_stave)) if not _.isEmpty(text_notes) if tab? and score? (new Vex.Flow.StaveConnector(score.stave, tab.stave)) .setType(Vex.Flow.StaveConnector.type.BRACKET) .setContext(ctx).draw() if score? then score_voices else tab_voices render: (renderer) -> L "Render: ", @options @closeBends() renderer.resize(@customizations.width * @customizations.scale, (@last_y + @options.bottom_spacing) * @customizations.scale) ctx = renderer.getContext() ctx.scale(@customizations.scale, @customizations.scale) ctx.clear() ctx.setFont(@options.font_face, @options.font_size, "") @renderer_context = ctx setBar = (stave, notes) -> last_note = _.last(notes) if last_note instanceof Vex.Flow.BarNote notes.pop() stave.setEndBarType(last_note.getType()) for stave in @staves L "Rendering staves." # If the last note is a bar, then remove it and render it as a stave modifier. setBar(stave.tab, stave.tab_notes) if stave.tab? setBar(stave.note, stave.note_notes) if stave.note? stave.tab.setContext(ctx).draw() if stave.tab? stave.note.setContext(ctx).draw() if stave.note? stave.tab_voices.push(stave.tab_notes) stave.note_voices.push(stave.note_notes) voices = formatAndRender(ctx, if stave.tab? then {stave: stave.tab, voices: stave.tab_voices} else null, if stave.note? then {stave: stave.note, voices: stave.note_voices} else null, stave.text_voices, @customizations, {beam_groups: stave.beam_groups}) @player_voices.push(voices) L "Rendering tab articulations." for articulation in @tab_articulations articulation.setContext(ctx).draw() L "Rendering note articulations." for articulation in @stave_articulations articulation.setContext(ctx).draw() if @player? if @customizations.player is "true" @player.setTempo(parseInt(@customizations.tempo, 10)) @player.setInstrument(@customizations.instrument) @player.render() else @player.removeControls() @rendered = true unless Artist.NOLOGO LOGO = "vexflow.com" width = ctx.measureText(LOGO).width ctx.save() ctx.setFont("Times", 10, "italic") ctx.fillText(LOGO, (@customizations.width - width) / 2, @last_y + 25) ctx.restore() isRendered: -> @rendered draw: (renderer) -> @render renderer # Given a fret/string pair, returns a note, octave, and required accidentals # based on current guitar tuning and stave key. The accidentals may be different # for repeats of the same notes because they get set (or cancelled) by the Key # Manager. getNoteForFret: (fret, string) -> spec = @tuning.getNoteForFret(fret, string) spec_props = Vex.Flow.keyProperties(spec) selected_note = @key_manager.selectNote(spec_props.key) accidental = null # Do we need to specify an explicit accidental? switch @customizations.accidentals when "standard" if selected_note.change accidental = if selected_note.accidental? then selected_note.accidental else "n" when "cautionary" if selected_note.change accidental = if selected_note.accidental? then selected_note.accidental else "n" else accidental = if selected_note.accidental? then selected_note.accidental + "_c" else throw new Vex.RERR("ArtistError", "Invalid value for option 'accidentals': #{@customizations.accidentals}") new_note = selected_note.note new_octave = spec_props.octave # TODO(0xfe): This logic should probably be in the KeyManager code old_root = @music_api.getNoteParts(spec_props.key).root new_root = @music_api.getNoteParts(selected_note.note).root # Figure out if there's an octave shift based on what the Key # Manager just told us about the note. if new_root == "b" and old_root == "c" new_octave-- else if new_root == "c" and old_root == "b" new_octave++ return [new_note, new_octave, accidental] getNoteForABC: (abc, string) -> key = abc.key octave = string accidental = abc.accidental accidental += "_#{abc.accidental_type}" if abc.accidental_type? return [key, octave, accidental] addStaveNote: (note_params) -> params = is_rest: false play_note: null _.extend(params, note_params) stave_notes = _.last(@staves).note_notes stave_note = new Vex.Flow.StaveNote({ keys: params.spec duration: @current_duration + (if params.is_rest then "r" else "") clef: if params.is_rest then "treble" else @current_clef auto_stem: if params.is_rest then false else true }) for acc, index in params.accidentals if acc? parts = acc.split("_") new_accidental = new Vex.Flow.Accidental(parts[0]) if parts.length > 1 and parts[1] == "c" new_accidental.setAsCautionary() stave_note.addAccidental(index, new_accidental) if @current_duration[@current_duration.length - 1] == "d" stave_note.addDotToAll() stave_note.setPlayNote(params.play_note) if params.play_note? stave_notes.push stave_note addTabNote: (spec, play_note=null) -> tab_notes = _.last(@staves).tab_notes new_tab_note = new Vex.Flow.TabNote({ positions: spec, duration: @current_duration }, (@customizations["tab-stems"] == "true") ) new_tab_note.setPlayNote(play_note) if play_note? tab_notes.push new_tab_note if @current_duration[@current_duration.length - 1] == "d" new_tab_note.addDot() makeDuration = (time, dot) -> time + (if dot then "d" else "") setDuration: (time, dot=false) -> t = time.split(/\s+/) L "setDuration: ", t[0], dot @current_duration = makeDuration(t[0], dot) addBar: (type) -> L "addBar: ", type @closeBends() @key_manager.reset() stave = _.last(@staves) TYPE = Vex.Flow.Barline.type type = switch type when "single" TYPE.SINGLE when "double" TYPE.DOUBLE when "end" TYPE.END when "repeat-begin" TYPE.REPEAT_BEGIN when "repeat-end" TYPE.REPEAT_END when "repeat-both" TYPE.REPEAT_BOTH else TYPE.SINGLE bar_note = new Vex.Flow.BarNote().setType(type) stave.tab_notes.push(bar_note) stave.note_notes.push(bar_note) if stave.note? makeBend = (from_fret, to_fret) -> direction = Vex.Flow.Bend.UP text = "" if parseInt(from_fret, 10) > parseInt(to_fret, 10) direction = Vex.Flow.Bend.DOWN else text = switch Math.abs(to_fret - from_fret) when 1 then "1/2" when 2 then "Full" when 3 then "1 1/2" else "Bend to #{to_fret}" return {type: direction, text: text} openBends: (first_note, last_note, first_indices, last_indices) -> L "openBends", first_note, last_note, first_indices, last_indices tab_notes = _.last(@staves).tab_notes start_note = first_note start_indices = first_indices if _.isEmpty(@current_bends) @bend_start_index = tab_notes.length - 2 @bend_start_strings = first_indices else start_note = tab_notes[@bend_start_index] start_indices = @bend_start_strings first_frets = start_note.getPositions() last_frets = last_note.getPositions() for index, i in start_indices last_index = last_indices[i] from_fret = first_note.getPositions()[first_indices[i]] to_fret = last_frets[last_index] @current_bends[index] ?= [] @current_bends[index].push makeBend(from_fret.fret, to_fret.fret) # Close and apply all the bends to the last N notes. closeBends: (offset=1) -> return unless @bend_start_index? L "closeBends(#{offset})" tab_notes = _.last(@staves).tab_notes for k, v of @current_bends phrase = [] for bend in v phrase.push bend tab_notes[@bend_start_index].addModifier( new Vex.Flow.Bend(null, null, phrase), k) # Replace bent notes with ghosts (make them invisible) for tab_note in tab_notes[@bend_start_index+1..((tab_notes.length - 2) + offset)] tab_note.setGhost(true) @current_bends = {} @bend_start_index = null makeTuplets: (tuplets, notes) -> L "makeTuplets", tuplets, notes notes ?= tuplets return unless _.last(@staves).note stave_notes = _.last(@staves).note_notes tab_notes = _.last(@staves).tab_notes throw new Vex.RERR("ArtistError", "Not enough notes for tuplet") if stave_notes.length < notes modifier = new Vex.Flow.Tuplet(stave_notes[stave_notes.length - notes..], {num_notes: tuplets}) @stave_articulations.push modifier # Creating a Vex.Flow.Tuplet corrects the ticks for the notes, so it needs to # be created whether or not it gets rendered. Below, if tab stems are not required # the created tuplet is simply thrown away. tab_modifier = new Vex.Flow.Tuplet(tab_notes[tab_notes.length - notes..], {num_notes: tuplets}) if @customizations["tab-stems"] == "true" @tab_articulations.push tab_modifier getFingering = (text) -> text.match(/^\.fingering\/([^.]+)\./) makeFingering: (text) -> parts = getFingering(text) POS = Vex.Flow.Modifier.Position fingers = [] fingering = [] if parts? fingers = (p.trim() for p in parts[1].split(/-/)) else return null badFingering = -> new Vex.RERR("ArtistError", "Bad fingering: #{parts[1]}") for finger in fingers pieces = finger.match(/(\d+):([ablr]):([fs]):([^-.]+)/) throw badFingering() unless pieces? note_number = parseInt(pieces[1], 10) - 1 position = POS.RIGHT switch pieces[2] when "l" position = POS.LEFT when "r" position = POS.RIGHT when "a" position = POS.ABOVE when "b" position = POS.BELOW modifier = null number = pieces[4] switch pieces[3] when "s" modifier = new Vex.Flow.StringNumber(number).setPosition(position) when "f" modifier = new Vex.Flow.FretHandFinger(number).setPosition(position) fingering.push({num: note_number, modifier: modifier}) return fingering getStrokeParts = (text) -> text.match(/^\.stroke\/([^.]+)\./) makeStroke: (text) -> parts = getStrokeParts(text) TYPE = Vex.Flow.Stroke.Type type = null if parts? switch parts[1] when "bu" type = TYPE.BRUSH_UP when "bd" type = TYPE.BRUSH_DOWN when "ru" type = TYPE.ROLL_UP when "rd" type = TYPE.ROLL_DOWN when "qu" type = TYPE.RASQUEDO_UP when "qd" type = TYPE.RASQUEDO_DOWN else throw new Vex.RERR("ArtistError", "Invalid stroke type: #{parts[1]}") return new Vex.Flow.Stroke(type) else return null getScoreArticulationParts = (text) -> text.match(/^\.(a[^\/]*)\/(t|b)[^.]*\./) makeScoreArticulation: (text) -> parts = getScoreArticulationParts(text) if parts? type = parts[1] position = parts[2] POSTYPE = Vex.Flow.Modifier.Position pos = if position is "t" then POSTYPE.ABOVE else POSTYPE.BELOW return new Vex.Flow.Articulation(type).setPosition(pos) else return null makeAnnotation: (text) -> font_face = @customizations["font-face"] font_size = @customizations["font-size"] font_style = @customizations["font-style"] aposition = @customizations["annotation-position"] VJUST = Vex.Flow.Annotation.VerticalJustify default_vjust = if aposition is "top" then VJUST.TOP else VJUST.BOTTOM makeIt = (text, just=default_vjust) -> new Vex.Flow.Annotation(text). setFont(font_face, font_size, font_style). setVerticalJustification(just) parts = text.match(/^\.([^-]*)-([^-]*)-([^.]*)\.(.*)/) if parts? font_face = parts[1] font_size = parts[2] font_style = parts[3] text = parts[4] return if text then makeIt(text) else null parts = text.match(/^\.([^.]*)\.(.*)/) if parts? just = default_vjust text = parts[2] switch parts[1] when "big" font_style = "bold" font_size = "14" when "italic", "italics" font_face = "Times" font_style = "italic" when "medium" font_size = "12" when "top" just = VJUST.TOP @customizations["annotation-position"] = "top" when "bottom" just = VJUST.BOTTOM @customizations["annotation-position"] = "bottom" return if text then makeIt(text, just) else null return makeIt(text) addAnnotations: (annotations) -> stave = _.last(@staves) stave_notes = stave.note_notes tab_notes = stave.tab_notes if annotations.length > tab_notes.length throw new Vex.RERR("ArtistError", "More annotations than note elements") # Add text annotations if stave.tab for tab_note, i in tab_notes[tab_notes.length - annotations.length..] if getScoreArticulationParts(annotations[i]) score_articulation = @makeScoreArticulation(annotations[i]) tab_note.addModifier(score_articulation, 0) else if getStrokeParts(annotations[i]) stroke = @makeStroke(annotations[i]) tab_note.addModifier(stroke, 0) else annotation = @makeAnnotation(annotations[i]) tab_note.addModifier(@makeAnnotation(annotations[i]), 0) if annotation else for note, i in stave_notes[stave_notes.length - annotations.length..] unless getScoreArticulationParts(annotations[i]) annotation = @makeAnnotation(annotations[i]) note.addAnnotation(0, @makeAnnotation(annotations[i])) if annotation # Add glyph articulations, strokes, or fingerings on score if stave.note for note, i in stave_notes[stave_notes.length - annotations.length..] score_articulation = @makeScoreArticulation(annotations[i]) note.addArticulation(0, score_articulation) if score_articulation? stroke = @makeStroke(annotations[i]) note.addStroke(0, stroke) if stroke? fingerings = @makeFingering(annotations[i]) if fingerings? try (note.addModifier(fingering.num, fingering.modifier) for fingering in fingerings) catch e throw new Vex.RERR("ArtistError", "Bad note number in fingering: #{annotations[i]}") addTabArticulation: (type, first_note, last_note, first_indices, last_indices) -> L "addTabArticulations: ", type, first_note, last_note, first_indices, last_indices if type == "t" last_note.addModifier( new Vex.Flow.Annotation("T"). setVerticalJustification(Vex.Flow.Annotation.VerticalJustify.BOTTOM)) if _.isEmpty(first_indices) and _.isEmpty(last_indices) then return articulation = null if type == "s" articulation = new Vex.Flow.TabSlide({ first_note: first_note last_note: last_note first_indices: first_indices last_indices: last_indices }) if type in ["h", "p"] articulation = new Vex.Flow.TabTie({ first_note: first_note last_note: last_note first_indices: first_indices last_indices: last_indices }, type.toUpperCase()) if type in ["T", "t"] articulation = new Vex.Flow.TabTie({ first_note: first_note last_note: last_note first_indices: first_indices last_indices: last_indices }, " ") if type == "b" @openBends(first_note, last_note, first_indices, last_indices) @tab_articulations.push articulation if articulation? addStaveArticulation: (type, first_note, last_note, first_indices, last_indices) -> L "addStaveArticulations: ", type, first_note, last_note, first_indices, last_indices articulation = null if type in ["b", "s", "h", "p", "t", "T"] articulation = new Vex.Flow.StaveTie({ first_note: first_note last_note: last_note first_indices: first_indices last_indices: last_indices }) @stave_articulations.push articulation if articulation? # This gets the previous (second-to-last) non-bar non-ghost note. getPreviousNoteIndex: -> tab_notes = _.last(@staves).tab_notes index = 2 while index <= tab_notes.length note = tab_notes[tab_notes.length - index] return (tab_notes.length - index) if note instanceof Vex.Flow.TabNote index++ return -1 addDecorator: (decorator) -> L "addDecorator: ", decorator return unless decorator? stave = _.last(@staves) tab_notes = stave.tab_notes score_notes = stave.note_notes modifier = null score_modifier = null if decorator == "v" modifier = new Vex.Flow.Vibrato() if decorator == "V" modifier = new Vex.Flow.Vibrato().setHarsh(true) if decorator == "u" modifier = new Vex.Flow.Articulation("a|").setPosition(Vex.Flow.Modifier.Position.BELOW) score_modifier = new Vex.Flow.Articulation("a|").setPosition(Vex.Flow.Modifier.Position.BELOW) if decorator == "d" modifier = new Vex.Flow.Articulation("am").setPosition(Vex.Flow.Modifier.Position.BELOW) score_modifier = new Vex.Flow.Articulation("am").setPosition(Vex.Flow.Modifier.Position.BELOW) _.last(tab_notes).addModifier(modifier, 0) if modifier? _.last(score_notes)?.addArticulation(0, score_modifier) if score_modifier? addArticulations: (articulations) -> L "addArticulations: ", articulations stave = _.last(@staves) tab_notes = stave.tab_notes stave_notes = stave.note_notes if _.isEmpty(tab_notes) or _.isEmpty(articulations) @closeBends(0) return current_tab_note = _.last(tab_notes) has_bends = false for valid_articulation in ["b", "s", "h", "p", "t", "T", "v", "V"] indices = (i for art, i in articulations when art? and art == valid_articulation) if _.isEmpty(indices) then continue if valid_articulation is "b" then has_bends = true prev_index = @getPreviousNoteIndex() if prev_index is -1 prev_tab_note = null prev_indices = null else prev_tab_note = tab_notes[prev_index] # Figure out which strings the articulations are on this_strings = (n.str for n, i in current_tab_note.getPositions() when i in indices) # Only allows articulations where both notes are on the same strings valid_strings = (pos.str for pos, i in prev_tab_note.getPositions() when pos.str in this_strings) # Get indices of articulated notes on previous chord prev_indices = (i for n, i in prev_tab_note.getPositions() when n.str in valid_strings) # Get indices of articulated notes on current chord current_indices = (i for n, i in current_tab_note.getPositions() when n.str in valid_strings) if stave.tab? @addTabArticulation(valid_articulation, prev_tab_note, current_tab_note, prev_indices, current_indices) if stave.note? @addStaveArticulation(valid_articulation, stave_notes[prev_index], _.last(stave_notes), prev_indices, current_indices) @closeBends(0) unless has_bends addRest: (params) -> L "addRest: ", params @closeBends() if params["position"] == 0 @addStaveNote spec: ["r/4"] accidentals: [] is_rest: true else position = @tuning.getNoteForFret((parseInt(params["position"], 10) + 5) * 2, 6) @addStaveNote spec: [position] accidentals: [] is_rest: true tab_notes = _.last(@staves).tab_notes if @customizations["tab-stems"] == "true" tab_note = new Vex.Flow.StaveNote({ keys: [position || "r/4"] duration: @current_duration + "r" clef: "treble" auto_stem: false }) if @current_duration[@current_duration.length - 1] == "d" tab_note.addDot(0) tab_notes.push tab_note else tab_notes.push new Vex.Flow.GhostNote(@current_duration) addChord: (chord, chord_articulation, chord_decorator) -> return if _.isEmpty(chord) L "addChord: ", chord stave = _.last(@staves) specs = [] # The stave note specs play_notes = [] # Notes to be played by audio players accidentals = [] # The stave accidentals articulations = [] # Articulations (ties, bends, taps) decorators = [] # Decorators (vibratos, harmonics) tab_specs = [] # The tab notes durations = [] # The duration of each position num_notes = 0 # Chords are complicated, because they can contain little # lines one each string. We need to keep track of the motion # of each line so we know which tick they belong in. current_string = _.first(chord).string current_position = 0 for note in chord num_notes++ if note.abc? or note.string != current_string current_position = 0 current_string = note.string unless specs[current_position]? # New position. Create new element arrays for this # position. specs[current_position] = [] play_notes[current_position] = [] accidentals[current_position] = [] tab_specs[current_position] = [] articulations[current_position] = [] decorators[current_position] = [] [new_note, new_octave, accidental] = [null, null, null] play_note = null if note.abc? octave = if note.octave? then note.octave else note.string [new_note, new_octave, accidental] = @getNoteForABC(note.abc, octave) if accidental? acc = accidental.split("_")[0] else acc = "" play_note = "#{new_note}#{acc}" note.fret = 'X' unless note.fret? else if note.fret? [new_note, new_octave, accidental] = @getNoteForFret(note.fret, note.string) play_note = @tuning.getNoteForFret(note.fret, note.string).split("/")[0] else throw new Vex.RERR("ArtistError", "No note specified") play_octave = parseInt(new_octave, 10) + @current_octave_shift current_duration = if note.time? then {time: note.time, dot: note.dot} else null specs[current_position].push "#{new_note}/#{new_octave}" play_notes[current_position].push "#{play_note}/#{play_octave}" accidentals[current_position].push accidental tab_specs[current_position].push {fret: note.fret, str: note.string} articulations[current_position].push note.articulation if note.articulation? durations[current_position] = current_duration decorators[current_position] = note.decorator if note.decorator? current_position++ for spec, i in specs saved_duration = @current_duration @setDuration(durations[i].time, durations[i].dot) if durations[i]? @addTabNote tab_specs[i], play_notes[i] @addStaveNote {spec: spec, accidentals: accidentals[i], play_note: play_notes[i]} if stave.note? @addArticulations articulations[i] @addDecorator decorators[i] if decorators[i]? if chord_articulation? art = [] art.push chord_articulation for num in [1..num_notes] @addArticulations art @addDecorator chord_decorator if chord_decorator? addNote: (note) -> @addChord([note]) addTextVoice: -> _.last(@staves).text_voices.push [] setTextFont: (font) -> if font? parts = font.match(/([^-]*)-([^-]*)-([^.]*)/) if parts? @customizations["font-face"] = parts[1] @customizations["font-size"] = parseInt(parts[2], 10) @customizations["font-style"] = parts[3] addTextNote: (text, position=0, justification="center", smooth=true, ignore_ticks=false) -> voices = _.last(@staves).text_voices throw new Vex.RERR("ArtistError", "Can't add text note without text voice") if _.isEmpty(voices) font_face = @customizations["font-face"] font_size = @customizations["font-size"] font_style = @customizations["font-style"] just = switch justification when "center" Vex.Flow.TextNote.Justification.CENTER when "left" Vex.Flow.TextNote.Justification.LEFT when "right" Vex.Flow.TextNote.Justification.RIGHT else Vex.Flow.TextNote.Justification.CENTER duration = if ignore_ticks then "b" else @current_duration struct = text: text duration: duration smooth: smooth ignore_ticks: ignore_ticks font: family: font_face size: font_size weight: font_style if text[0] == "#" struct.glyph = text[1..] note = new Vex.Flow.TextNote(struct). setLine(position).setJustification(just) _.last(voices).push(note) addVoice: (options) -> @closeBends() stave = _.last(@staves) return @addStave(options) unless stave? unless _.isEmpty(stave.tab_notes) stave.tab_voices.push(stave.tab_notes) stave.tab_notes = [] unless _.isEmpty(stave.note_notes) stave.note_voices.push(stave.note_notes) stave.note_notes = [] addStave: (element, options) -> opts = tuning: "standard" clef: "treble" key: "<KEY>" notation: if element == "tabstave" then "false" else "true" tablature: if element == "stave" then "false" else "true" strings: 6 _.extend(opts, options) L "addStave: ", element, opts tab_stave = null note_stave = null # This is used to line up tablature and notation. start_x = @x + @customizations["connector-space"] tabstave_start_x = 40 if opts.notation is "true" note_stave = new Vex.Flow.Stave(start_x, @last_y, @customizations.width - 20, {left_bar: false}) note_stave.addClef(opts.clef) if opts.clef isnt "none" note_stave.addKeySignature(opts.key) note_stave.addTimeSignature(opts.time) if opts.time? @last_y += note_stave.getHeight() + @options.note_stave_lower_spacing + parseInt(@customizations["stave-distance"], 10) tabstave_start_x = note_stave.getNoteStartX() @current_clef = if opts.clef is "none" then "treble" else opts.clef if opts.tablature is "true" tab_stave = new Vex.Flow.TabStave(start_x, @last_y, @customizations.width - 20, {left_bar: false}).setNumLines(opts.strings) tab_stave.addTabGlyph() if opts.clef isnt "none" tab_stave.setNoteStartX(tabstave_start_x) @last_y += tab_stave.getHeight() + @options.tab_stave_lower_spacing @closeBends() beam_groups = Vex.Flow.Beam.getDefaultBeamGroups(opts.time) @staves.push { tab: tab_stave, note: note_stave, tab_voices: [], note_voices: [], tab_notes: [], note_notes: [], text_voices: [], beam_groups: beam_groups } @tuning.setTuning(opts.tuning) @key_manager.setKey(opts.key) return runCommand: (line, _l=0, _c=0) -> L "runCommand: ", line words = line.split(/\s+/) switch words[0] when "octave-shift" @current_octave_shift = parseInt(words[1], 10) L "Octave shift: ", @current_octave_shift else throw new Vex.RERR("ArtistError", "Invalid command '#{words[0]}' at line #{_l} column #{_c}") export default Artist
true
# VexTab Artist # Copyright 2012 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> # # This class is responsible for rendering the elements # parsed by Vex.Flow.VexTab. import Vex from 'vexflow' import * as _ from 'lodash' class Artist @DEBUG = false L = (args...) -> console?.log("(Vex.Flow.Artist)", args...) if Artist.DEBUG @NOLOGO = false constructor: (@x, @y, @width, options) -> @options = font_face: "Arial" font_size: 10 font_style: null bottom_spacing: 20 + (if Artist.NOLOGO then 0 else 10) tab_stave_lower_spacing: 10 note_stave_lower_spacing: 0 scale: 1.0 _.extend(@options, options) if options? @reset() reset: -> @tuning = new Vex.Flow.Tuning() @key_manager = new Vex.Flow.KeyManager("C") @music_api = new Vex.Flow.Music() # User customizations @customizations = "font-size": @options.font_size "font-face": @options.font_face "font-style": @options.font_style "annotation-position": "bottom" "scale": @options.scale "width": @width "stave-distance": 0 "space": 0 "player": "false" "tempo": 120 "instrument": "acoustic_grand_piano" "accidentals": "standard" # standard / cautionary "tab-stems": "false" "tab-stem-direction": "up" "beam-rests": "true" "beam-stemlets": "true" "beam-middle-only": "false" "connector-space": 5 # Generated elements @staves = [] @tab_articulations = [] @stave_articulations = [] # Voices for player @player_voices = [] # Current state @last_y = @y @current_duration = "q" @current_clef = "treble" @current_bends = {} @current_octave_shift = 0 @bend_start_index = null @bend_start_strings = null @rendered = false @renderer_context = null attachPlayer: (player) -> @player = player setOptions: (options) -> L "setOptions: ", options # Set @customizations valid_options = _.keys(@customizations) for k, v of options if k in valid_options @customizations[k] = v else throw new Vex.RERR("ArtistError", "Invalid option '#{k}'") @last_y += parseInt(@customizations.space, 10) @last_y += 15 if @customizations.player is "true" getPlayerData: -> voices: @player_voices context: @renderer_context scale: @customizations.scale parseBool = (str) -> return (str == "true") formatAndRender = (ctx, tab, score, text_notes, customizations, options) -> tab_stave = tab.stave if tab? score_stave = score.stave if score? tab_voices = [] score_voices = [] text_voices = [] beams = [] format_stave = null text_stave = null beam_config = beam_rests: parseBool(customizations["beam-rests"]) show_stemlets: parseBool(customizations["beam-stemlets"]) beam_middle_only: parseBool(customizations["beam-middle-only"]) groups: options.beam_groups if tab? multi_voice = if (tab.voices.length > 1) then true else false for notes, i in tab.voices continue if _.isEmpty(notes) _.each(notes, (note) -> note.setStave(tab_stave)) voice = new Vex.Flow.Voice(Vex.Flow.TIME4_4). setMode(Vex.Flow.Voice.Mode.SOFT) voice.addTickables notes tab_voices.push voice if customizations["tab-stems"] == "true" if multi_voice beam_config.stem_direction = if i == 0 then 1 else -1 else beam_config.stem_direction = if customizations["tab-stem-direction"] == "down" then -1 else 1 beam_config.beam_rests = false beams = beams.concat(Vex.Flow.Beam.generateBeams(voice.getTickables(), beam_config)) format_stave = tab_stave text_stave = tab_stave beam_config.beam_rests = parseBool(customizations["beam-rests"]) if score? multi_voice = if (score.voices.length > 1) then true else false for notes, i in score.voices continue if _.isEmpty(notes) stem_direction = if i == 0 then 1 else -1 _.each(notes, (note) -> note.setStave(score_stave)) voice = new Vex.Flow.Voice(Vex.Flow.TIME4_4). setMode(Vex.Flow.Voice.Mode.SOFT) voice.addTickables notes score_voices.push voice if multi_voice beam_config.stem_direction = stem_direction beams = beams.concat(Vex.Flow.Beam.generateBeams(notes, beam_config)) else beam_config.stem_direction = null beams = beams.concat(Vex.Flow.Beam.generateBeams(notes, beam_config)) format_stave = score_stave text_stave = score_stave for notes in text_notes continue if _.isEmpty(notes) _.each(notes, (voice) -> voice.setStave(text_stave)) voice = new Vex.Flow.Voice(Vex.Flow.TIME4_4). setMode(Vex.Flow.Voice.Mode.SOFT) voice.addTickables notes text_voices.push voice if format_stave? format_voices = [] formatter = new Vex.Flow.Formatter() align_rests = false if tab? formatter.joinVoices(tab_voices) unless _.isEmpty(tab_voices) format_voices = tab_voices if score? formatter.joinVoices(score_voices) unless _.isEmpty(score_voices) format_voices = format_voices.concat(score_voices) align_rests = true if score_voices.length > 1 if not _.isEmpty(text_notes) and not _.isEmpty(text_voices) formatter.joinVoices(text_voices) format_voices = format_voices.concat(text_voices) formatter.formatToStave(format_voices, format_stave, {align_rests: align_rests}) unless _.isEmpty(format_voices) _.each(tab_voices, (voice) -> voice.draw(ctx, tab_stave)) if tab? _.each(score_voices, (voice) -> voice.draw(ctx, score_stave)) if score? _.each(beams, (beam) -> beam.setContext(ctx).draw()) _.each(text_voices, (voice) -> voice.draw(ctx, text_stave)) if not _.isEmpty(text_notes) if tab? and score? (new Vex.Flow.StaveConnector(score.stave, tab.stave)) .setType(Vex.Flow.StaveConnector.type.BRACKET) .setContext(ctx).draw() if score? then score_voices else tab_voices render: (renderer) -> L "Render: ", @options @closeBends() renderer.resize(@customizations.width * @customizations.scale, (@last_y + @options.bottom_spacing) * @customizations.scale) ctx = renderer.getContext() ctx.scale(@customizations.scale, @customizations.scale) ctx.clear() ctx.setFont(@options.font_face, @options.font_size, "") @renderer_context = ctx setBar = (stave, notes) -> last_note = _.last(notes) if last_note instanceof Vex.Flow.BarNote notes.pop() stave.setEndBarType(last_note.getType()) for stave in @staves L "Rendering staves." # If the last note is a bar, then remove it and render it as a stave modifier. setBar(stave.tab, stave.tab_notes) if stave.tab? setBar(stave.note, stave.note_notes) if stave.note? stave.tab.setContext(ctx).draw() if stave.tab? stave.note.setContext(ctx).draw() if stave.note? stave.tab_voices.push(stave.tab_notes) stave.note_voices.push(stave.note_notes) voices = formatAndRender(ctx, if stave.tab? then {stave: stave.tab, voices: stave.tab_voices} else null, if stave.note? then {stave: stave.note, voices: stave.note_voices} else null, stave.text_voices, @customizations, {beam_groups: stave.beam_groups}) @player_voices.push(voices) L "Rendering tab articulations." for articulation in @tab_articulations articulation.setContext(ctx).draw() L "Rendering note articulations." for articulation in @stave_articulations articulation.setContext(ctx).draw() if @player? if @customizations.player is "true" @player.setTempo(parseInt(@customizations.tempo, 10)) @player.setInstrument(@customizations.instrument) @player.render() else @player.removeControls() @rendered = true unless Artist.NOLOGO LOGO = "vexflow.com" width = ctx.measureText(LOGO).width ctx.save() ctx.setFont("Times", 10, "italic") ctx.fillText(LOGO, (@customizations.width - width) / 2, @last_y + 25) ctx.restore() isRendered: -> @rendered draw: (renderer) -> @render renderer # Given a fret/string pair, returns a note, octave, and required accidentals # based on current guitar tuning and stave key. The accidentals may be different # for repeats of the same notes because they get set (or cancelled) by the Key # Manager. getNoteForFret: (fret, string) -> spec = @tuning.getNoteForFret(fret, string) spec_props = Vex.Flow.keyProperties(spec) selected_note = @key_manager.selectNote(spec_props.key) accidental = null # Do we need to specify an explicit accidental? switch @customizations.accidentals when "standard" if selected_note.change accidental = if selected_note.accidental? then selected_note.accidental else "n" when "cautionary" if selected_note.change accidental = if selected_note.accidental? then selected_note.accidental else "n" else accidental = if selected_note.accidental? then selected_note.accidental + "_c" else throw new Vex.RERR("ArtistError", "Invalid value for option 'accidentals': #{@customizations.accidentals}") new_note = selected_note.note new_octave = spec_props.octave # TODO(0xfe): This logic should probably be in the KeyManager code old_root = @music_api.getNoteParts(spec_props.key).root new_root = @music_api.getNoteParts(selected_note.note).root # Figure out if there's an octave shift based on what the Key # Manager just told us about the note. if new_root == "b" and old_root == "c" new_octave-- else if new_root == "c" and old_root == "b" new_octave++ return [new_note, new_octave, accidental] getNoteForABC: (abc, string) -> key = abc.key octave = string accidental = abc.accidental accidental += "_#{abc.accidental_type}" if abc.accidental_type? return [key, octave, accidental] addStaveNote: (note_params) -> params = is_rest: false play_note: null _.extend(params, note_params) stave_notes = _.last(@staves).note_notes stave_note = new Vex.Flow.StaveNote({ keys: params.spec duration: @current_duration + (if params.is_rest then "r" else "") clef: if params.is_rest then "treble" else @current_clef auto_stem: if params.is_rest then false else true }) for acc, index in params.accidentals if acc? parts = acc.split("_") new_accidental = new Vex.Flow.Accidental(parts[0]) if parts.length > 1 and parts[1] == "c" new_accidental.setAsCautionary() stave_note.addAccidental(index, new_accidental) if @current_duration[@current_duration.length - 1] == "d" stave_note.addDotToAll() stave_note.setPlayNote(params.play_note) if params.play_note? stave_notes.push stave_note addTabNote: (spec, play_note=null) -> tab_notes = _.last(@staves).tab_notes new_tab_note = new Vex.Flow.TabNote({ positions: spec, duration: @current_duration }, (@customizations["tab-stems"] == "true") ) new_tab_note.setPlayNote(play_note) if play_note? tab_notes.push new_tab_note if @current_duration[@current_duration.length - 1] == "d" new_tab_note.addDot() makeDuration = (time, dot) -> time + (if dot then "d" else "") setDuration: (time, dot=false) -> t = time.split(/\s+/) L "setDuration: ", t[0], dot @current_duration = makeDuration(t[0], dot) addBar: (type) -> L "addBar: ", type @closeBends() @key_manager.reset() stave = _.last(@staves) TYPE = Vex.Flow.Barline.type type = switch type when "single" TYPE.SINGLE when "double" TYPE.DOUBLE when "end" TYPE.END when "repeat-begin" TYPE.REPEAT_BEGIN when "repeat-end" TYPE.REPEAT_END when "repeat-both" TYPE.REPEAT_BOTH else TYPE.SINGLE bar_note = new Vex.Flow.BarNote().setType(type) stave.tab_notes.push(bar_note) stave.note_notes.push(bar_note) if stave.note? makeBend = (from_fret, to_fret) -> direction = Vex.Flow.Bend.UP text = "" if parseInt(from_fret, 10) > parseInt(to_fret, 10) direction = Vex.Flow.Bend.DOWN else text = switch Math.abs(to_fret - from_fret) when 1 then "1/2" when 2 then "Full" when 3 then "1 1/2" else "Bend to #{to_fret}" return {type: direction, text: text} openBends: (first_note, last_note, first_indices, last_indices) -> L "openBends", first_note, last_note, first_indices, last_indices tab_notes = _.last(@staves).tab_notes start_note = first_note start_indices = first_indices if _.isEmpty(@current_bends) @bend_start_index = tab_notes.length - 2 @bend_start_strings = first_indices else start_note = tab_notes[@bend_start_index] start_indices = @bend_start_strings first_frets = start_note.getPositions() last_frets = last_note.getPositions() for index, i in start_indices last_index = last_indices[i] from_fret = first_note.getPositions()[first_indices[i]] to_fret = last_frets[last_index] @current_bends[index] ?= [] @current_bends[index].push makeBend(from_fret.fret, to_fret.fret) # Close and apply all the bends to the last N notes. closeBends: (offset=1) -> return unless @bend_start_index? L "closeBends(#{offset})" tab_notes = _.last(@staves).tab_notes for k, v of @current_bends phrase = [] for bend in v phrase.push bend tab_notes[@bend_start_index].addModifier( new Vex.Flow.Bend(null, null, phrase), k) # Replace bent notes with ghosts (make them invisible) for tab_note in tab_notes[@bend_start_index+1..((tab_notes.length - 2) + offset)] tab_note.setGhost(true) @current_bends = {} @bend_start_index = null makeTuplets: (tuplets, notes) -> L "makeTuplets", tuplets, notes notes ?= tuplets return unless _.last(@staves).note stave_notes = _.last(@staves).note_notes tab_notes = _.last(@staves).tab_notes throw new Vex.RERR("ArtistError", "Not enough notes for tuplet") if stave_notes.length < notes modifier = new Vex.Flow.Tuplet(stave_notes[stave_notes.length - notes..], {num_notes: tuplets}) @stave_articulations.push modifier # Creating a Vex.Flow.Tuplet corrects the ticks for the notes, so it needs to # be created whether or not it gets rendered. Below, if tab stems are not required # the created tuplet is simply thrown away. tab_modifier = new Vex.Flow.Tuplet(tab_notes[tab_notes.length - notes..], {num_notes: tuplets}) if @customizations["tab-stems"] == "true" @tab_articulations.push tab_modifier getFingering = (text) -> text.match(/^\.fingering\/([^.]+)\./) makeFingering: (text) -> parts = getFingering(text) POS = Vex.Flow.Modifier.Position fingers = [] fingering = [] if parts? fingers = (p.trim() for p in parts[1].split(/-/)) else return null badFingering = -> new Vex.RERR("ArtistError", "Bad fingering: #{parts[1]}") for finger in fingers pieces = finger.match(/(\d+):([ablr]):([fs]):([^-.]+)/) throw badFingering() unless pieces? note_number = parseInt(pieces[1], 10) - 1 position = POS.RIGHT switch pieces[2] when "l" position = POS.LEFT when "r" position = POS.RIGHT when "a" position = POS.ABOVE when "b" position = POS.BELOW modifier = null number = pieces[4] switch pieces[3] when "s" modifier = new Vex.Flow.StringNumber(number).setPosition(position) when "f" modifier = new Vex.Flow.FretHandFinger(number).setPosition(position) fingering.push({num: note_number, modifier: modifier}) return fingering getStrokeParts = (text) -> text.match(/^\.stroke\/([^.]+)\./) makeStroke: (text) -> parts = getStrokeParts(text) TYPE = Vex.Flow.Stroke.Type type = null if parts? switch parts[1] when "bu" type = TYPE.BRUSH_UP when "bd" type = TYPE.BRUSH_DOWN when "ru" type = TYPE.ROLL_UP when "rd" type = TYPE.ROLL_DOWN when "qu" type = TYPE.RASQUEDO_UP when "qd" type = TYPE.RASQUEDO_DOWN else throw new Vex.RERR("ArtistError", "Invalid stroke type: #{parts[1]}") return new Vex.Flow.Stroke(type) else return null getScoreArticulationParts = (text) -> text.match(/^\.(a[^\/]*)\/(t|b)[^.]*\./) makeScoreArticulation: (text) -> parts = getScoreArticulationParts(text) if parts? type = parts[1] position = parts[2] POSTYPE = Vex.Flow.Modifier.Position pos = if position is "t" then POSTYPE.ABOVE else POSTYPE.BELOW return new Vex.Flow.Articulation(type).setPosition(pos) else return null makeAnnotation: (text) -> font_face = @customizations["font-face"] font_size = @customizations["font-size"] font_style = @customizations["font-style"] aposition = @customizations["annotation-position"] VJUST = Vex.Flow.Annotation.VerticalJustify default_vjust = if aposition is "top" then VJUST.TOP else VJUST.BOTTOM makeIt = (text, just=default_vjust) -> new Vex.Flow.Annotation(text). setFont(font_face, font_size, font_style). setVerticalJustification(just) parts = text.match(/^\.([^-]*)-([^-]*)-([^.]*)\.(.*)/) if parts? font_face = parts[1] font_size = parts[2] font_style = parts[3] text = parts[4] return if text then makeIt(text) else null parts = text.match(/^\.([^.]*)\.(.*)/) if parts? just = default_vjust text = parts[2] switch parts[1] when "big" font_style = "bold" font_size = "14" when "italic", "italics" font_face = "Times" font_style = "italic" when "medium" font_size = "12" when "top" just = VJUST.TOP @customizations["annotation-position"] = "top" when "bottom" just = VJUST.BOTTOM @customizations["annotation-position"] = "bottom" return if text then makeIt(text, just) else null return makeIt(text) addAnnotations: (annotations) -> stave = _.last(@staves) stave_notes = stave.note_notes tab_notes = stave.tab_notes if annotations.length > tab_notes.length throw new Vex.RERR("ArtistError", "More annotations than note elements") # Add text annotations if stave.tab for tab_note, i in tab_notes[tab_notes.length - annotations.length..] if getScoreArticulationParts(annotations[i]) score_articulation = @makeScoreArticulation(annotations[i]) tab_note.addModifier(score_articulation, 0) else if getStrokeParts(annotations[i]) stroke = @makeStroke(annotations[i]) tab_note.addModifier(stroke, 0) else annotation = @makeAnnotation(annotations[i]) tab_note.addModifier(@makeAnnotation(annotations[i]), 0) if annotation else for note, i in stave_notes[stave_notes.length - annotations.length..] unless getScoreArticulationParts(annotations[i]) annotation = @makeAnnotation(annotations[i]) note.addAnnotation(0, @makeAnnotation(annotations[i])) if annotation # Add glyph articulations, strokes, or fingerings on score if stave.note for note, i in stave_notes[stave_notes.length - annotations.length..] score_articulation = @makeScoreArticulation(annotations[i]) note.addArticulation(0, score_articulation) if score_articulation? stroke = @makeStroke(annotations[i]) note.addStroke(0, stroke) if stroke? fingerings = @makeFingering(annotations[i]) if fingerings? try (note.addModifier(fingering.num, fingering.modifier) for fingering in fingerings) catch e throw new Vex.RERR("ArtistError", "Bad note number in fingering: #{annotations[i]}") addTabArticulation: (type, first_note, last_note, first_indices, last_indices) -> L "addTabArticulations: ", type, first_note, last_note, first_indices, last_indices if type == "t" last_note.addModifier( new Vex.Flow.Annotation("T"). setVerticalJustification(Vex.Flow.Annotation.VerticalJustify.BOTTOM)) if _.isEmpty(first_indices) and _.isEmpty(last_indices) then return articulation = null if type == "s" articulation = new Vex.Flow.TabSlide({ first_note: first_note last_note: last_note first_indices: first_indices last_indices: last_indices }) if type in ["h", "p"] articulation = new Vex.Flow.TabTie({ first_note: first_note last_note: last_note first_indices: first_indices last_indices: last_indices }, type.toUpperCase()) if type in ["T", "t"] articulation = new Vex.Flow.TabTie({ first_note: first_note last_note: last_note first_indices: first_indices last_indices: last_indices }, " ") if type == "b" @openBends(first_note, last_note, first_indices, last_indices) @tab_articulations.push articulation if articulation? addStaveArticulation: (type, first_note, last_note, first_indices, last_indices) -> L "addStaveArticulations: ", type, first_note, last_note, first_indices, last_indices articulation = null if type in ["b", "s", "h", "p", "t", "T"] articulation = new Vex.Flow.StaveTie({ first_note: first_note last_note: last_note first_indices: first_indices last_indices: last_indices }) @stave_articulations.push articulation if articulation? # This gets the previous (second-to-last) non-bar non-ghost note. getPreviousNoteIndex: -> tab_notes = _.last(@staves).tab_notes index = 2 while index <= tab_notes.length note = tab_notes[tab_notes.length - index] return (tab_notes.length - index) if note instanceof Vex.Flow.TabNote index++ return -1 addDecorator: (decorator) -> L "addDecorator: ", decorator return unless decorator? stave = _.last(@staves) tab_notes = stave.tab_notes score_notes = stave.note_notes modifier = null score_modifier = null if decorator == "v" modifier = new Vex.Flow.Vibrato() if decorator == "V" modifier = new Vex.Flow.Vibrato().setHarsh(true) if decorator == "u" modifier = new Vex.Flow.Articulation("a|").setPosition(Vex.Flow.Modifier.Position.BELOW) score_modifier = new Vex.Flow.Articulation("a|").setPosition(Vex.Flow.Modifier.Position.BELOW) if decorator == "d" modifier = new Vex.Flow.Articulation("am").setPosition(Vex.Flow.Modifier.Position.BELOW) score_modifier = new Vex.Flow.Articulation("am").setPosition(Vex.Flow.Modifier.Position.BELOW) _.last(tab_notes).addModifier(modifier, 0) if modifier? _.last(score_notes)?.addArticulation(0, score_modifier) if score_modifier? addArticulations: (articulations) -> L "addArticulations: ", articulations stave = _.last(@staves) tab_notes = stave.tab_notes stave_notes = stave.note_notes if _.isEmpty(tab_notes) or _.isEmpty(articulations) @closeBends(0) return current_tab_note = _.last(tab_notes) has_bends = false for valid_articulation in ["b", "s", "h", "p", "t", "T", "v", "V"] indices = (i for art, i in articulations when art? and art == valid_articulation) if _.isEmpty(indices) then continue if valid_articulation is "b" then has_bends = true prev_index = @getPreviousNoteIndex() if prev_index is -1 prev_tab_note = null prev_indices = null else prev_tab_note = tab_notes[prev_index] # Figure out which strings the articulations are on this_strings = (n.str for n, i in current_tab_note.getPositions() when i in indices) # Only allows articulations where both notes are on the same strings valid_strings = (pos.str for pos, i in prev_tab_note.getPositions() when pos.str in this_strings) # Get indices of articulated notes on previous chord prev_indices = (i for n, i in prev_tab_note.getPositions() when n.str in valid_strings) # Get indices of articulated notes on current chord current_indices = (i for n, i in current_tab_note.getPositions() when n.str in valid_strings) if stave.tab? @addTabArticulation(valid_articulation, prev_tab_note, current_tab_note, prev_indices, current_indices) if stave.note? @addStaveArticulation(valid_articulation, stave_notes[prev_index], _.last(stave_notes), prev_indices, current_indices) @closeBends(0) unless has_bends addRest: (params) -> L "addRest: ", params @closeBends() if params["position"] == 0 @addStaveNote spec: ["r/4"] accidentals: [] is_rest: true else position = @tuning.getNoteForFret((parseInt(params["position"], 10) + 5) * 2, 6) @addStaveNote spec: [position] accidentals: [] is_rest: true tab_notes = _.last(@staves).tab_notes if @customizations["tab-stems"] == "true" tab_note = new Vex.Flow.StaveNote({ keys: [position || "r/4"] duration: @current_duration + "r" clef: "treble" auto_stem: false }) if @current_duration[@current_duration.length - 1] == "d" tab_note.addDot(0) tab_notes.push tab_note else tab_notes.push new Vex.Flow.GhostNote(@current_duration) addChord: (chord, chord_articulation, chord_decorator) -> return if _.isEmpty(chord) L "addChord: ", chord stave = _.last(@staves) specs = [] # The stave note specs play_notes = [] # Notes to be played by audio players accidentals = [] # The stave accidentals articulations = [] # Articulations (ties, bends, taps) decorators = [] # Decorators (vibratos, harmonics) tab_specs = [] # The tab notes durations = [] # The duration of each position num_notes = 0 # Chords are complicated, because they can contain little # lines one each string. We need to keep track of the motion # of each line so we know which tick they belong in. current_string = _.first(chord).string current_position = 0 for note in chord num_notes++ if note.abc? or note.string != current_string current_position = 0 current_string = note.string unless specs[current_position]? # New position. Create new element arrays for this # position. specs[current_position] = [] play_notes[current_position] = [] accidentals[current_position] = [] tab_specs[current_position] = [] articulations[current_position] = [] decorators[current_position] = [] [new_note, new_octave, accidental] = [null, null, null] play_note = null if note.abc? octave = if note.octave? then note.octave else note.string [new_note, new_octave, accidental] = @getNoteForABC(note.abc, octave) if accidental? acc = accidental.split("_")[0] else acc = "" play_note = "#{new_note}#{acc}" note.fret = 'X' unless note.fret? else if note.fret? [new_note, new_octave, accidental] = @getNoteForFret(note.fret, note.string) play_note = @tuning.getNoteForFret(note.fret, note.string).split("/")[0] else throw new Vex.RERR("ArtistError", "No note specified") play_octave = parseInt(new_octave, 10) + @current_octave_shift current_duration = if note.time? then {time: note.time, dot: note.dot} else null specs[current_position].push "#{new_note}/#{new_octave}" play_notes[current_position].push "#{play_note}/#{play_octave}" accidentals[current_position].push accidental tab_specs[current_position].push {fret: note.fret, str: note.string} articulations[current_position].push note.articulation if note.articulation? durations[current_position] = current_duration decorators[current_position] = note.decorator if note.decorator? current_position++ for spec, i in specs saved_duration = @current_duration @setDuration(durations[i].time, durations[i].dot) if durations[i]? @addTabNote tab_specs[i], play_notes[i] @addStaveNote {spec: spec, accidentals: accidentals[i], play_note: play_notes[i]} if stave.note? @addArticulations articulations[i] @addDecorator decorators[i] if decorators[i]? if chord_articulation? art = [] art.push chord_articulation for num in [1..num_notes] @addArticulations art @addDecorator chord_decorator if chord_decorator? addNote: (note) -> @addChord([note]) addTextVoice: -> _.last(@staves).text_voices.push [] setTextFont: (font) -> if font? parts = font.match(/([^-]*)-([^-]*)-([^.]*)/) if parts? @customizations["font-face"] = parts[1] @customizations["font-size"] = parseInt(parts[2], 10) @customizations["font-style"] = parts[3] addTextNote: (text, position=0, justification="center", smooth=true, ignore_ticks=false) -> voices = _.last(@staves).text_voices throw new Vex.RERR("ArtistError", "Can't add text note without text voice") if _.isEmpty(voices) font_face = @customizations["font-face"] font_size = @customizations["font-size"] font_style = @customizations["font-style"] just = switch justification when "center" Vex.Flow.TextNote.Justification.CENTER when "left" Vex.Flow.TextNote.Justification.LEFT when "right" Vex.Flow.TextNote.Justification.RIGHT else Vex.Flow.TextNote.Justification.CENTER duration = if ignore_ticks then "b" else @current_duration struct = text: text duration: duration smooth: smooth ignore_ticks: ignore_ticks font: family: font_face size: font_size weight: font_style if text[0] == "#" struct.glyph = text[1..] note = new Vex.Flow.TextNote(struct). setLine(position).setJustification(just) _.last(voices).push(note) addVoice: (options) -> @closeBends() stave = _.last(@staves) return @addStave(options) unless stave? unless _.isEmpty(stave.tab_notes) stave.tab_voices.push(stave.tab_notes) stave.tab_notes = [] unless _.isEmpty(stave.note_notes) stave.note_voices.push(stave.note_notes) stave.note_notes = [] addStave: (element, options) -> opts = tuning: "standard" clef: "treble" key: "PI:KEY:<KEY>END_PI" notation: if element == "tabstave" then "false" else "true" tablature: if element == "stave" then "false" else "true" strings: 6 _.extend(opts, options) L "addStave: ", element, opts tab_stave = null note_stave = null # This is used to line up tablature and notation. start_x = @x + @customizations["connector-space"] tabstave_start_x = 40 if opts.notation is "true" note_stave = new Vex.Flow.Stave(start_x, @last_y, @customizations.width - 20, {left_bar: false}) note_stave.addClef(opts.clef) if opts.clef isnt "none" note_stave.addKeySignature(opts.key) note_stave.addTimeSignature(opts.time) if opts.time? @last_y += note_stave.getHeight() + @options.note_stave_lower_spacing + parseInt(@customizations["stave-distance"], 10) tabstave_start_x = note_stave.getNoteStartX() @current_clef = if opts.clef is "none" then "treble" else opts.clef if opts.tablature is "true" tab_stave = new Vex.Flow.TabStave(start_x, @last_y, @customizations.width - 20, {left_bar: false}).setNumLines(opts.strings) tab_stave.addTabGlyph() if opts.clef isnt "none" tab_stave.setNoteStartX(tabstave_start_x) @last_y += tab_stave.getHeight() + @options.tab_stave_lower_spacing @closeBends() beam_groups = Vex.Flow.Beam.getDefaultBeamGroups(opts.time) @staves.push { tab: tab_stave, note: note_stave, tab_voices: [], note_voices: [], tab_notes: [], note_notes: [], text_voices: [], beam_groups: beam_groups } @tuning.setTuning(opts.tuning) @key_manager.setKey(opts.key) return runCommand: (line, _l=0, _c=0) -> L "runCommand: ", line words = line.split(/\s+/) switch words[0] when "octave-shift" @current_octave_shift = parseInt(words[1], 10) L "Octave shift: ", @current_octave_shift else throw new Vex.RERR("ArtistError", "Invalid command '#{words[0]}' at line #{_l} column #{_c}") export default Artist
[ { "context": "odosSinos #NovoHamburgo from:ComusaNH',\n# key: 'bc254ea08faf45c216fada14d64edf71',\n# secret: '99cbd9758755f8e9e55aa2be5acb75da'\n", "end": 705, "score": 0.9996774792671204, "start": 673, "tag": "KEY", "value": "bc254ea08faf45c216fada14d64edf71" }, { "context": " '...
lib/index.coffee
paulodiovani/sinos-river-scraper-twitter
1
# # Index # # The main module exports a series of methods that pass a # Readable Stream to the callback function. TweetsSearch = require('./tweets').TweetsSearch Parser = require('./parser') DEFAULT_QUERY = '#RiodosSinos #NovoHamburgo from:ComusaNH' # ## Search tweets # # - `options` Search options # - `key` Twitter consumer key # - `secret` Twitter consumer secret # - `query` Search query # - `cb` Callback function to receive a Readable Stream # # ### Usage # # ```javascript # var sinos = require('sinos-river-level-twitter'); # # //search tweets with level data # sinos.search({ # query: '#RiodosSinos #NovoHamburgo from:ComusaNH', # key: 'bc254ea08faf45c216fada14d64edf71', # secret: '99cbd9758755f8e9e55aa2be5acb75da' # }, function(tweets) { # //tweets is a readable stream where every tweet emits data # tweets.on('error', console.err); # tweets.on('data', function(tweet) { # console.log('Level in %s is %sm', data.tweet.created_at, data.measure.meters); # }); # }); # ``` exports.search = (options, cb) -> options.query = DEFAULT_QUERY if options.query is true cb new TweetsSearch(options).pipe(new Parser())
138494
# # Index # # The main module exports a series of methods that pass a # Readable Stream to the callback function. TweetsSearch = require('./tweets').TweetsSearch Parser = require('./parser') DEFAULT_QUERY = '#RiodosSinos #NovoHamburgo from:ComusaNH' # ## Search tweets # # - `options` Search options # - `key` Twitter consumer key # - `secret` Twitter consumer secret # - `query` Search query # - `cb` Callback function to receive a Readable Stream # # ### Usage # # ```javascript # var sinos = require('sinos-river-level-twitter'); # # //search tweets with level data # sinos.search({ # query: '#RiodosSinos #NovoHamburgo from:ComusaNH', # key: '<KEY>', # secret: '<KEY>' # }, function(tweets) { # //tweets is a readable stream where every tweet emits data # tweets.on('error', console.err); # tweets.on('data', function(tweet) { # console.log('Level in %s is %sm', data.tweet.created_at, data.measure.meters); # }); # }); # ``` exports.search = (options, cb) -> options.query = DEFAULT_QUERY if options.query is true cb new TweetsSearch(options).pipe(new Parser())
true
# # Index # # The main module exports a series of methods that pass a # Readable Stream to the callback function. TweetsSearch = require('./tweets').TweetsSearch Parser = require('./parser') DEFAULT_QUERY = '#RiodosSinos #NovoHamburgo from:ComusaNH' # ## Search tweets # # - `options` Search options # - `key` Twitter consumer key # - `secret` Twitter consumer secret # - `query` Search query # - `cb` Callback function to receive a Readable Stream # # ### Usage # # ```javascript # var sinos = require('sinos-river-level-twitter'); # # //search tweets with level data # sinos.search({ # query: '#RiodosSinos #NovoHamburgo from:ComusaNH', # key: 'PI:KEY:<KEY>END_PI', # secret: 'PI:KEY:<KEY>END_PI' # }, function(tweets) { # //tweets is a readable stream where every tweet emits data # tweets.on('error', console.err); # tweets.on('data', function(tweet) { # console.log('Level in %s is %sm', data.tweet.created_at, data.measure.meters); # }); # }); # ``` exports.search = (options, cb) -> options.query = DEFAULT_QUERY if options.query is true cb new TweetsSearch(options).pipe(new Parser())
[ { "context": "ns links to it\n#\n# Notes:\n# None\n#\n# Author:\n# JD Courtoy\n\nMEMEGEN_API_URL = \"http://memegen.link\"\n\nmodule.", "end": 399, "score": 0.9997605085372925, "start": 389, "tag": "NAME", "value": "JD Courtoy" } ]
scripts/memegen.coffee
nc2/bb-bot
0
# Description # A Hubot script for creating memes from templates using memegen.link. # # Configuration: # None # # Commands: # hubot meme list - Returns available meme templates from Memegen.link and their respective URLs (keys) # hubot meme <template> top: <text> bottom: <text> - Creates a <template> meme using <text> and returns links to it # # Notes: # None # # Author: # JD Courtoy MEMEGEN_API_URL = "http://memegen.link" module.exports = (robot) -> _templateCache = null robot.respond /meme list/i, (res) -> return res.send(_templateCache) if _templateCache? _queryApi res, "/templates/", (data) -> _templateCache = "" for template, url of data key = url.split "/" key = key[key.length - 1] _templateCache += "#{template} | Key: #{key} | Example: http://memegen.link/#{key}/hello/world.jpg\n" res.send _templateCache robot.respond /meme (\w+) top: (.+) bottom: (.+)/i, (res) -> template = res.match[1] topText = _sanitize(res.match[2]) bottomText = _sanitize(res.match[3]) _queryApi res, "/#{template}/#{topText}/#{bottomText}", (data) -> res.send "#{data.direct.visible}" robot.error (err, res) -> robot.logger.error "hubot-memegen: (#{err})" if (res?) res.reply "DOES NOT COMPUTE" _sanitize = (str) -> str = str.replace(/\s+/g, '-') str = str.replace(/"/g, '') str = str.replace(/\?/g, '~q') str.toLowerCase() _queryApi = (msg, parts, handler) -> robot.http("#{MEMEGEN_API_URL}#{parts}") .get() (err, res, body) -> robot.logger.info "#{MEMEGEN_API_URL}#{parts} #{body}" if err robot.emit 'error', err if res.statusCode isnt 200 and res.statusCode isnt 302 msg.reply "The memegen API appears to be down, or I haven't been taught how to talk to it. Try again later, please." robot.logger.error "hubot-memegen: #{body} (#{err})" return handler JSON.parse(body)
150472
# Description # A Hubot script for creating memes from templates using memegen.link. # # Configuration: # None # # Commands: # hubot meme list - Returns available meme templates from Memegen.link and their respective URLs (keys) # hubot meme <template> top: <text> bottom: <text> - Creates a <template> meme using <text> and returns links to it # # Notes: # None # # Author: # <NAME> MEMEGEN_API_URL = "http://memegen.link" module.exports = (robot) -> _templateCache = null robot.respond /meme list/i, (res) -> return res.send(_templateCache) if _templateCache? _queryApi res, "/templates/", (data) -> _templateCache = "" for template, url of data key = url.split "/" key = key[key.length - 1] _templateCache += "#{template} | Key: #{key} | Example: http://memegen.link/#{key}/hello/world.jpg\n" res.send _templateCache robot.respond /meme (\w+) top: (.+) bottom: (.+)/i, (res) -> template = res.match[1] topText = _sanitize(res.match[2]) bottomText = _sanitize(res.match[3]) _queryApi res, "/#{template}/#{topText}/#{bottomText}", (data) -> res.send "#{data.direct.visible}" robot.error (err, res) -> robot.logger.error "hubot-memegen: (#{err})" if (res?) res.reply "DOES NOT COMPUTE" _sanitize = (str) -> str = str.replace(/\s+/g, '-') str = str.replace(/"/g, '') str = str.replace(/\?/g, '~q') str.toLowerCase() _queryApi = (msg, parts, handler) -> robot.http("#{MEMEGEN_API_URL}#{parts}") .get() (err, res, body) -> robot.logger.info "#{MEMEGEN_API_URL}#{parts} #{body}" if err robot.emit 'error', err if res.statusCode isnt 200 and res.statusCode isnt 302 msg.reply "The memegen API appears to be down, or I haven't been taught how to talk to it. Try again later, please." robot.logger.error "hubot-memegen: #{body} (#{err})" return handler JSON.parse(body)
true
# Description # A Hubot script for creating memes from templates using memegen.link. # # Configuration: # None # # Commands: # hubot meme list - Returns available meme templates from Memegen.link and their respective URLs (keys) # hubot meme <template> top: <text> bottom: <text> - Creates a <template> meme using <text> and returns links to it # # Notes: # None # # Author: # PI:NAME:<NAME>END_PI MEMEGEN_API_URL = "http://memegen.link" module.exports = (robot) -> _templateCache = null robot.respond /meme list/i, (res) -> return res.send(_templateCache) if _templateCache? _queryApi res, "/templates/", (data) -> _templateCache = "" for template, url of data key = url.split "/" key = key[key.length - 1] _templateCache += "#{template} | Key: #{key} | Example: http://memegen.link/#{key}/hello/world.jpg\n" res.send _templateCache robot.respond /meme (\w+) top: (.+) bottom: (.+)/i, (res) -> template = res.match[1] topText = _sanitize(res.match[2]) bottomText = _sanitize(res.match[3]) _queryApi res, "/#{template}/#{topText}/#{bottomText}", (data) -> res.send "#{data.direct.visible}" robot.error (err, res) -> robot.logger.error "hubot-memegen: (#{err})" if (res?) res.reply "DOES NOT COMPUTE" _sanitize = (str) -> str = str.replace(/\s+/g, '-') str = str.replace(/"/g, '') str = str.replace(/\?/g, '~q') str.toLowerCase() _queryApi = (msg, parts, handler) -> robot.http("#{MEMEGEN_API_URL}#{parts}") .get() (err, res, body) -> robot.logger.info "#{MEMEGEN_API_URL}#{parts} #{body}" if err robot.emit 'error', err if res.statusCode isnt 200 and res.statusCode isnt 302 msg.reply "The memegen API appears to be down, or I haven't been taught how to talk to it. Try again later, please." robot.logger.error "hubot-memegen: #{body} (#{err})" return handler JSON.parse(body)
[ { "context": "LOG\", message\n getDevices: -> [\n { deviceId: \"FAKEDEVICEID779BA001D1B7A638EB320103F0EF\", kind: \"audioinput\", label: \"iPad Micro\", groupI", "end": 925, "score": 0.990100085735321, "start": 885, "tag": "KEY", "value": "FAKEDEVICEID779BA001D1B7A638EB320103F0EF" }, ...
src/js/OT.coffee
cadesalaberry/cordova-plugin-opentok
1
# TB Object: # Methods: # TB.checkSystemRequirements() :number # TB.initPublisher( apiKey:String [, replaceElementId:String] [, properties:Object] ):Publisher # TB.initSession( apiKey, sessionId ):Session # TB.log( message ) # TB.off( type:String, listener:Function ) # TB.on( type:String, listener:Function ) # Methods that doesn't do anything: # TB.setLogLevel(logLevel:String) # TB.upgradeSystemRequirements() window.cordovaOT = checkSystemRequirements: -> return 1 initPublisher: (one, two, callback) -> return new TBPublisher( one, two, callback ) initSession: (apiKey, sessionId ) -> if( not sessionId? ) then @showError( "cordovaOT.initSession takes 2 parameters, your API Key and Session ID" ) return new TBSession(apiKey, sessionId) log: (message) -> pdebug "TB LOG", message getDevices: -> [ { deviceId: "FAKEDEVICEID779BA001D1B7A638EB320103F0EF", kind: "audioinput", label: "iPad Micro", groupId: "" }, { deviceId: "FAKEDEVICEID08BADAB2A7D7EB3FEDB0BA373C06", kind: "videoinput", label: "Front Camera", groupId: "" }, { deviceId: "FAKEDEVICEID82EF36372A93FBCFB2CEB8900CEB", kind: "videoinput", label: "Back Camera", groupId: "" }, ] getUserMedia: -> Promise.resolve({ getVideoTracks: -> [{ name: 'Fake video track', stop: -> true }], getAudioTracks: -> [{ name: 'Fake audio track', stop: -> true }], getTracks: -> [ { name: 'Fake audio track', stop: -> true }, { name: 'Fake video track', stop: -> true }, ], }) # accept the devices permissions off: (event, handler) -> #todo on: (event, handler) -> if(event=="exception") # TB object only dispatches one type of event console.log("JS: TB Exception Handler added") Cordova.exec(handler, TBError, OTPlugin, "exceptionHandler", [] ) setLogLevel: (a) -> console.log("Log Level Set") upgradeSystemRequirements: -> return {} updateViews: -> TBUpdateObjects() # helpers getHelper: -> if(typeof(jasmine)=="undefined" || !jasmine || !jasmine['getEnv']) window.jasmine = { getEnv: -> return } this.OTHelper = this.OTHelper || OTHelpers.noConflict() return this.OTHelper # deprecating showError: (a) -> alert(a) addEventListener: (event, handler) -> @on( event, handler ) removeEventListener: (type, handler ) -> @off( type, handler ) window.addEventListener "orientationchange", (-> setTimeout (-> cordovaOT.updateViews() return ), 1000 return ), false
13902
# TB Object: # Methods: # TB.checkSystemRequirements() :number # TB.initPublisher( apiKey:String [, replaceElementId:String] [, properties:Object] ):Publisher # TB.initSession( apiKey, sessionId ):Session # TB.log( message ) # TB.off( type:String, listener:Function ) # TB.on( type:String, listener:Function ) # Methods that doesn't do anything: # TB.setLogLevel(logLevel:String) # TB.upgradeSystemRequirements() window.cordovaOT = checkSystemRequirements: -> return 1 initPublisher: (one, two, callback) -> return new TBPublisher( one, two, callback ) initSession: (apiKey, sessionId ) -> if( not sessionId? ) then @showError( "cordovaOT.initSession takes 2 parameters, your API Key and Session ID" ) return new TBSession(apiKey, sessionId) log: (message) -> pdebug "TB LOG", message getDevices: -> [ { deviceId: "<KEY>", kind: "audioinput", label: "iPad Micro", groupId: "" }, { deviceId: "<KEY>", kind: "videoinput", label: "Front Camera", groupId: "" }, { deviceId: "<KEY>", kind: "videoinput", label: "Back Camera", groupId: "" }, ] getUserMedia: -> Promise.resolve({ getVideoTracks: -> [{ name: 'Fake video track', stop: -> true }], getAudioTracks: -> [{ name: 'Fake audio track', stop: -> true }], getTracks: -> [ { name: 'Fake audio track', stop: -> true }, { name: 'Fake video track', stop: -> true }, ], }) # accept the devices permissions off: (event, handler) -> #todo on: (event, handler) -> if(event=="exception") # TB object only dispatches one type of event console.log("JS: TB Exception Handler added") Cordova.exec(handler, TBError, OTPlugin, "exceptionHandler", [] ) setLogLevel: (a) -> console.log("Log Level Set") upgradeSystemRequirements: -> return {} updateViews: -> TBUpdateObjects() # helpers getHelper: -> if(typeof(jasmine)=="undefined" || !jasmine || !jasmine['getEnv']) window.jasmine = { getEnv: -> return } this.OTHelper = this.OTHelper || OTHelpers.noConflict() return this.OTHelper # deprecating showError: (a) -> alert(a) addEventListener: (event, handler) -> @on( event, handler ) removeEventListener: (type, handler ) -> @off( type, handler ) window.addEventListener "orientationchange", (-> setTimeout (-> cordovaOT.updateViews() return ), 1000 return ), false
true
# TB Object: # Methods: # TB.checkSystemRequirements() :number # TB.initPublisher( apiKey:String [, replaceElementId:String] [, properties:Object] ):Publisher # TB.initSession( apiKey, sessionId ):Session # TB.log( message ) # TB.off( type:String, listener:Function ) # TB.on( type:String, listener:Function ) # Methods that doesn't do anything: # TB.setLogLevel(logLevel:String) # TB.upgradeSystemRequirements() window.cordovaOT = checkSystemRequirements: -> return 1 initPublisher: (one, two, callback) -> return new TBPublisher( one, two, callback ) initSession: (apiKey, sessionId ) -> if( not sessionId? ) then @showError( "cordovaOT.initSession takes 2 parameters, your API Key and Session ID" ) return new TBSession(apiKey, sessionId) log: (message) -> pdebug "TB LOG", message getDevices: -> [ { deviceId: "PI:KEY:<KEY>END_PI", kind: "audioinput", label: "iPad Micro", groupId: "" }, { deviceId: "PI:KEY:<KEY>END_PI", kind: "videoinput", label: "Front Camera", groupId: "" }, { deviceId: "PI:KEY:<KEY>END_PI", kind: "videoinput", label: "Back Camera", groupId: "" }, ] getUserMedia: -> Promise.resolve({ getVideoTracks: -> [{ name: 'Fake video track', stop: -> true }], getAudioTracks: -> [{ name: 'Fake audio track', stop: -> true }], getTracks: -> [ { name: 'Fake audio track', stop: -> true }, { name: 'Fake video track', stop: -> true }, ], }) # accept the devices permissions off: (event, handler) -> #todo on: (event, handler) -> if(event=="exception") # TB object only dispatches one type of event console.log("JS: TB Exception Handler added") Cordova.exec(handler, TBError, OTPlugin, "exceptionHandler", [] ) setLogLevel: (a) -> console.log("Log Level Set") upgradeSystemRequirements: -> return {} updateViews: -> TBUpdateObjects() # helpers getHelper: -> if(typeof(jasmine)=="undefined" || !jasmine || !jasmine['getEnv']) window.jasmine = { getEnv: -> return } this.OTHelper = this.OTHelper || OTHelpers.noConflict() return this.OTHelper # deprecating showError: (a) -> alert(a) addEventListener: (event, handler) -> @on( event, handler ) removeEventListener: (type, handler ) -> @off( type, handler ) window.addEventListener "orientationchange", (-> setTimeout (-> cordovaOT.updateViews() return ), 1000 return ), false
[ { "context": "corporates code from [markmon](https://github.com/yyjhao/markmon)\n# covered by the following terms:\n#\n# Co", "end": 70, "score": 0.9992825984954834, "start": 64, "tag": "USERNAME", "value": "yyjhao" }, { "context": "ed by the following terms:\n#\n# Copyright (c) 2014...
lib/update-preview.coffee
abejfehr/markdown-preview-katex
20
# This file incorporates code from [markmon](https://github.com/yyjhao/markmon) # covered by the following terms: # # Copyright (c) 2014, Yao Yujian, http://yjyao.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. "use strict" WrappedDomTree = require './wrapped-dom-tree' module.exports = class UpdatePreview # @param dom A DOM element object # https://developer.mozilla.org/en-US/docs/Web/API/element constructor: (dom) -> @tree = new WrappedDomTree dom, true @htmlStr = "" update: (htmlStr, renderLaTeX) -> if htmlStr is @htmlStr return firstTime = @htmlStr is "" @htmlStr = htmlStr newDom = document.createElement "div" newDom.className = "update-preview" newDom.innerHTML = htmlStr newTree = new WrappedDomTree newDom r = @tree.diffTo newTree newTree.removeSelf() if firstTime r.possibleReplace = null r.last = null if renderLaTeX r.inserted = r.inserted.map (elm) -> while elm and !elm.innerHTML elm = elm.parentElement elm r.inserted = r.inserted.filter (elm) -> !!elm return r
103063
# This file incorporates code from [markmon](https://github.com/yyjhao/markmon) # covered by the following terms: # # Copyright (c) 2014, <NAME>, http://yjyao.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. "use strict" WrappedDomTree = require './wrapped-dom-tree' module.exports = class UpdatePreview # @param dom A DOM element object # https://developer.mozilla.org/en-US/docs/Web/API/element constructor: (dom) -> @tree = new WrappedDomTree dom, true @htmlStr = "" update: (htmlStr, renderLaTeX) -> if htmlStr is @htmlStr return firstTime = @htmlStr is "" @htmlStr = htmlStr newDom = document.createElement "div" newDom.className = "update-preview" newDom.innerHTML = htmlStr newTree = new WrappedDomTree newDom r = @tree.diffTo newTree newTree.removeSelf() if firstTime r.possibleReplace = null r.last = null if renderLaTeX r.inserted = r.inserted.map (elm) -> while elm and !elm.innerHTML elm = elm.parentElement elm r.inserted = r.inserted.filter (elm) -> !!elm return r
true
# This file incorporates code from [markmon](https://github.com/yyjhao/markmon) # covered by the following terms: # # Copyright (c) 2014, PI:NAME:<NAME>END_PI, http://yjyao.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. "use strict" WrappedDomTree = require './wrapped-dom-tree' module.exports = class UpdatePreview # @param dom A DOM element object # https://developer.mozilla.org/en-US/docs/Web/API/element constructor: (dom) -> @tree = new WrappedDomTree dom, true @htmlStr = "" update: (htmlStr, renderLaTeX) -> if htmlStr is @htmlStr return firstTime = @htmlStr is "" @htmlStr = htmlStr newDom = document.createElement "div" newDom.className = "update-preview" newDom.innerHTML = htmlStr newTree = new WrappedDomTree newDom r = @tree.diffTo newTree newTree.removeSelf() if firstTime r.possibleReplace = null r.last = null if renderLaTeX r.inserted = r.inserted.map (elm) -> while elm and !elm.innerHTML elm = elm.parentElement elm r.inserted = r.inserted.filter (elm) -> !!elm return r
[ { "context": "class DropShadow\n @shouldParse: (key) -> key is 'dsdw'\n\n BLEND_MODES = {\n norm: 'normal',\n dark: 'da", "end": 171, "score": 0.9681181311607361, "start": 167, "tag": "KEY", "value": "dsdw" } ]
lib/psd/layer_info/effect_info/drop_shadow.coffee
fzx-design/Trims-psd-resolving
0
Descriptor = require '../../descriptor.coffee' EffectLayer = require '../effect_layer_info.coffee' module.exports = class DropShadow @shouldParse: (key) -> key is 'dsdw' BLEND_MODES = { norm: 'normal', dark: 'darken', lite: 'lighten', hue: 'hue', sat: 'saturation', colr: 'color', lum: 'luminosity', mul: 'multiply', scrn: 'screen', diss: 'dissolve', over: 'overlay', hLit: 'hard_light', sLit: 'soft_light', diff: 'difference', smud: 'exclusion', div: 'color_dodge', idiv: 'color_burn', lbrn: 'linear_burn', lddg: 'linear_dodge', vLit: 'vivid_light', lLit: 'linear_light', pLit: 'pin_light', hMix: 'hard_mix', pass: 'passthru', dkCl: 'darker_color', lgCl: 'lighter_color', fsub: 'subtract', fdiv: 'divide' } constructor: (file,size) -> #super(size) @file = file @version = null #4 @blur = null #4 @intensity = null #4 @angle = null #4 @distance = null #4 @color = null # 2 + 4*2 @blendmode = null # 4 sig 4 key @enbled = null #1 @angleInAll = null #1 @opacity = null #1 @nativeColor = null #2 + 4*2 console.log("size : " + size) @end = @file.tell() + size parse: -> @version = @file.readInt() @blur = @file.readInt()/65536 @intensity = @file.readInt()/65536 @angle = @file.readInt()/65536 @distance = @file.readInt()/65536 @color = @file.readSpaceColor() @file.seek 4, true @blendmode = BLEND_MODES[@file.readString(4).trim()] @enbled = @file.readBoolean() @angleInAll = @file.readByte() @opacity = Math.round(@file.readByte()/2.55) @nativeColor = @file.readSpaceColor() @file.seek @end export: -> version: @version blur: @blur intensity: @intensity angle: @angle distance: @distance color: @color blendmode: @blendmode enbled: @enbled angleInAll: @angleInAll opacity: @opacity nativeColor: @nativeColor
117621
Descriptor = require '../../descriptor.coffee' EffectLayer = require '../effect_layer_info.coffee' module.exports = class DropShadow @shouldParse: (key) -> key is '<KEY>' BLEND_MODES = { norm: 'normal', dark: 'darken', lite: 'lighten', hue: 'hue', sat: 'saturation', colr: 'color', lum: 'luminosity', mul: 'multiply', scrn: 'screen', diss: 'dissolve', over: 'overlay', hLit: 'hard_light', sLit: 'soft_light', diff: 'difference', smud: 'exclusion', div: 'color_dodge', idiv: 'color_burn', lbrn: 'linear_burn', lddg: 'linear_dodge', vLit: 'vivid_light', lLit: 'linear_light', pLit: 'pin_light', hMix: 'hard_mix', pass: 'passthru', dkCl: 'darker_color', lgCl: 'lighter_color', fsub: 'subtract', fdiv: 'divide' } constructor: (file,size) -> #super(size) @file = file @version = null #4 @blur = null #4 @intensity = null #4 @angle = null #4 @distance = null #4 @color = null # 2 + 4*2 @blendmode = null # 4 sig 4 key @enbled = null #1 @angleInAll = null #1 @opacity = null #1 @nativeColor = null #2 + 4*2 console.log("size : " + size) @end = @file.tell() + size parse: -> @version = @file.readInt() @blur = @file.readInt()/65536 @intensity = @file.readInt()/65536 @angle = @file.readInt()/65536 @distance = @file.readInt()/65536 @color = @file.readSpaceColor() @file.seek 4, true @blendmode = BLEND_MODES[@file.readString(4).trim()] @enbled = @file.readBoolean() @angleInAll = @file.readByte() @opacity = Math.round(@file.readByte()/2.55) @nativeColor = @file.readSpaceColor() @file.seek @end export: -> version: @version blur: @blur intensity: @intensity angle: @angle distance: @distance color: @color blendmode: @blendmode enbled: @enbled angleInAll: @angleInAll opacity: @opacity nativeColor: @nativeColor
true
Descriptor = require '../../descriptor.coffee' EffectLayer = require '../effect_layer_info.coffee' module.exports = class DropShadow @shouldParse: (key) -> key is 'PI:KEY:<KEY>END_PI' BLEND_MODES = { norm: 'normal', dark: 'darken', lite: 'lighten', hue: 'hue', sat: 'saturation', colr: 'color', lum: 'luminosity', mul: 'multiply', scrn: 'screen', diss: 'dissolve', over: 'overlay', hLit: 'hard_light', sLit: 'soft_light', diff: 'difference', smud: 'exclusion', div: 'color_dodge', idiv: 'color_burn', lbrn: 'linear_burn', lddg: 'linear_dodge', vLit: 'vivid_light', lLit: 'linear_light', pLit: 'pin_light', hMix: 'hard_mix', pass: 'passthru', dkCl: 'darker_color', lgCl: 'lighter_color', fsub: 'subtract', fdiv: 'divide' } constructor: (file,size) -> #super(size) @file = file @version = null #4 @blur = null #4 @intensity = null #4 @angle = null #4 @distance = null #4 @color = null # 2 + 4*2 @blendmode = null # 4 sig 4 key @enbled = null #1 @angleInAll = null #1 @opacity = null #1 @nativeColor = null #2 + 4*2 console.log("size : " + size) @end = @file.tell() + size parse: -> @version = @file.readInt() @blur = @file.readInt()/65536 @intensity = @file.readInt()/65536 @angle = @file.readInt()/65536 @distance = @file.readInt()/65536 @color = @file.readSpaceColor() @file.seek 4, true @blendmode = BLEND_MODES[@file.readString(4).trim()] @enbled = @file.readBoolean() @angleInAll = @file.readByte() @opacity = Math.round(@file.readByte()/2.55) @nativeColor = @file.readSpaceColor() @file.seek @end export: -> version: @version blur: @blur intensity: @intensity angle: @angle distance: @distance color: @color blendmode: @blendmode enbled: @enbled angleInAll: @angleInAll opacity: @opacity nativeColor: @nativeColor
[ { "context": "/PEM--/grunt-svg2storeicons\n#\n# Copyright (c) 2013 Pierre-Eric Marchandet (PEM-- <pemarchandet@gmail.com>)\n# Licensed under", "end": 120, "score": 0.999873161315918, "start": 98, "tag": "NAME", "value": "Pierre-Eric Marchandet" }, { "context": "Copyright (c) 2013 Pie...
test/testReducedSet.coffee
gruntjs-updater/grunt-svg2storeicons
0
### # grunt-svg2storeicons # https://github.com/PEM--/grunt-svg2storeicons # # Copyright (c) 2013 Pierre-Eric Marchandet (PEM-- <pemarchandet@gmail.com>) # Licensed under the MIT licence. ### 'use strict' assert = require 'assert' fs = require 'fs' path = require 'path' EXPECTED_DEST = path.join 'tmp', 'reduced_set' PROFILES = (require '../lib/profiles') prjName: 'Test' EXPECTED_FILES = [] for key in ['blackberry'] dir = PROFILES[key].dir for icon in PROFILES[key].icons EXPECTED_FILES.push path.join EXPECTED_DEST, dir, icon.name describe 'Reduced set', -> it 'should only create icons for only one profile (blackberry)', -> for file in EXPECTED_FILES assert.equal true, (fs.statSync file).isFile() assert.equal 1, (fs.readdirSync EXPECTED_DEST).length assert.equal 1, (fs.readdirSync path.join EXPECTED_DEST, 'res', 'icon').length assert.equal 'blackberry', (fs.readdirSync path.join EXPECTED_DEST, 'res', 'icon')[0]
186338
### # grunt-svg2storeicons # https://github.com/PEM--/grunt-svg2storeicons # # Copyright (c) 2013 <NAME> (PEM-- <<EMAIL>>) # Licensed under the MIT licence. ### 'use strict' assert = require 'assert' fs = require 'fs' path = require 'path' EXPECTED_DEST = path.join 'tmp', 'reduced_set' PROFILES = (require '../lib/profiles') prjName: 'Test' EXPECTED_FILES = [] for key in ['<KEY>'] dir = PROFILES[key].dir for icon in PROFILES[key].icons EXPECTED_FILES.push path.join EXPECTED_DEST, dir, icon.name describe 'Reduced set', -> it 'should only create icons for only one profile (blackberry)', -> for file in EXPECTED_FILES assert.equal true, (fs.statSync file).isFile() assert.equal 1, (fs.readdirSync EXPECTED_DEST).length assert.equal 1, (fs.readdirSync path.join EXPECTED_DEST, 'res', 'icon').length assert.equal 'blackberry', (fs.readdirSync path.join EXPECTED_DEST, 'res', 'icon')[0]
true
### # grunt-svg2storeicons # https://github.com/PEM--/grunt-svg2storeicons # # Copyright (c) 2013 PI:NAME:<NAME>END_PI (PEM-- <PI:EMAIL:<EMAIL>END_PI>) # Licensed under the MIT licence. ### 'use strict' assert = require 'assert' fs = require 'fs' path = require 'path' EXPECTED_DEST = path.join 'tmp', 'reduced_set' PROFILES = (require '../lib/profiles') prjName: 'Test' EXPECTED_FILES = [] for key in ['PI:KEY:<KEY>END_PI'] dir = PROFILES[key].dir for icon in PROFILES[key].icons EXPECTED_FILES.push path.join EXPECTED_DEST, dir, icon.name describe 'Reduced set', -> it 'should only create icons for only one profile (blackberry)', -> for file in EXPECTED_FILES assert.equal true, (fs.statSync file).isFile() assert.equal 1, (fs.readdirSync EXPECTED_DEST).length assert.equal 1, (fs.readdirSync path.join EXPECTED_DEST, 'res', 'icon').length assert.equal 'blackberry', (fs.readdirSync path.join EXPECTED_DEST, 'res', 'icon')[0]
[ { "context": "# Made with Framer\n# By Jay Stakelon\n# www.framerjs.com\n\n# This imports all the layers", "end": 36, "score": 0.9998812079429626, "start": 24, "tag": "NAME", "value": "Jay Stakelon" } ]
examples/facebook-ios-player.framer/app.coffee
benjamindenboer/Framer-VideoPlayer
1
# Made with Framer # By Jay Stakelon # www.framerjs.com # This imports all the layers for "facebook" into facebookLayers imports = Framer.Importer.load "imported/facebook" # Set device background Framer.Device.background.style.background = "linear-gradient(0deg, #384778 0%, #4f6ba5 100%)" Framer.Defaults.Animation = curve: "ease-out" time: .3 {VideoPlayer} = require "videoplayer" {Bars} = require "bars" # we'll add all of our controls to this later detailControlsArray = [imports.hd] # setup and static elements isFeed = true isControlsShowing = false detailBg = new Layer width: Screen.width height: Screen.height backgroundColor: "#000" opacity: 0 detailControls = new Layer width: 750, height: 100, maxY: Screen.height, opacity: 0 image: "images/overlay-detail.png" doneButton = new Layer width: 104, height: 54, maxX: Screen.width-30, y: 50, opacity: 0 image: "images/done.png" overlayControlsArray = [detailControls, doneButton] # create and position the VideoPlayer video = new VideoPlayer video: "video-480.m4v" width: 735 height: 412 constrainToButton: true autoplay: true muted: true video.centerX() video.y = 782 video.originalFrame = video.frame # put a drop shadow on the feed video video.shadowColor = "rgba(0,0,0,.5)" video.shadowY = 4 video.shadowBlur = 10 # set play and pause button images video.playButtonImage = "images/fb-playbutton.png" video.pauseButtonImage = "images/fb-pausebutton.png" video.playButton.width = video.playButton.height = 42 video.playButton.visible = false video.playButton.x = 20 # make bouncy bars in the feed bars = new Bars barPadding: 2 barWith: 8 bars.maxX = video.maxX - 10 bars.maxY = video.maxY - 10 bars.opacity = .7 video.on "video:ended", -> bars.opacity = 0 # transition from feed to detail view toDetailView = -> isFeed = false video.player.muted = false unless video.isPlaying then video.player.play() video.animate properties: x: 0 midY: Screen.height/2 width: 750 height: 422 shadowY: 0 shadowBlur: 0 curve: "spring(200,22,1)" video.videoLayer.animate properties: width: 750 height: 422 bars.opacity = 0 detailBg.scaleY = 0 detailBg.opacity = 1 detailBg.animate properties: scaleY: 1 for layer in overlayControlsArray layer.animateStop() layer.animate delay: .3 time: .1 properties: opacity: 1 isControlsShowing = true video.progressBar.y = Screen.height/2 + video.height/2 - 17 video.timeElapsed.y = video.progressBar.y - 15 video.timeLeft.y = video.progressBar.y - 15 video.playButton.superLayer = null video.playButton.visible = true video.playButton.y = video.progressBar.y - 22 imports.hd.x = 692 imports.hd.y = video.timeLeft.y + 7 imports.hd.bringToFront() video.progressBar.opacity = video.timeLeft.opacity = video.timeElapsed.opacity = video.playButton.opacity = imports.hd.opacity = 0 showControls(true, true) Utils.delay .5, -> video.draggable.enabled = true video.draggable.momentum = false video.on Events.DragStart, startVideoDrag video.on Events.DragMove, moveVideoDrag video.on Events.DragEnd, endVideoDrag # transition from detail view back to feed toFeedView = -> isFeed = true video.player.muted = true video.animate properties: x: video.originalFrame.x y: video.originalFrame.y width: video.originalFrame.width height: video.originalFrame.height shadowY: 4 shadowBlur: 10 curve: "spring(200,22,1)" video.videoLayer.animate properties: width: video.originalFrame.width height: video.originalFrame.height unless video.player.paused bars.animate properties: opacity: .7 delay: .25 detailBg.animate properties: opacity: 0 for layer in overlayControlsArray layer.animate properties: opacity: 0 hideControls() video.draggable.enabled = false video.off Events.DragStart, startVideoDrag video.off Events.DragMove, moveVideoDrag video.off Events.DragEnd, endVideoDrag # instead of using shyControls = true, show controls by hand showControls = (isDelay, skipdetailControls) -> isControlsShowing = true delay = if isDelay then .75 else 0 controlsArray = unless skipdetailControls then detailControlsArray.concat overlayControlsArray else detailControlsArray for layer in controlsArray layer.animateStop() layer.animate delay: delay properties: opacity: 1 # instead of using shyControls = true, hide controls by hand hideControls = -> isControlsShowing = false controlsArray = detailControlsArray.concat overlayControlsArray for layer in controlsArray layer.animateStop() layer.animate time: .1 properties: opacity: 0 # manage transitions toggleControls = -> if isControlsShowing then hideControls() else showControls() video.on Events.Click, -> if isFeed toDetailView() else toggleControls() doneButton.on Events.Click, -> unless isFeed then toFeedView() # show, position and customize the progress bar video.showProgress = true video.progressBar.width = 420 video.progressBar.height = 2 video.progressBar.backgroundColor = "#555259" video.progressBar.knobSize = 34 video.progressBar.borderRadius = 0 video.progressBar.knob.backgroundColor = "#fff" video.progressBar.fill.backgroundColor = "#fff" video.progressBar.x = 155 # time display style should be set before showing timestamps video.timeStyle = { "font-size": "20px", "color": "#fff" } # show and position elapsed time video.showTimeElapsed = true video.timeElapsed.x = 84 # show and position total video time video.showTimeLeft = true video.timeLeft.x = video.progressBar.maxX + 28 # add controls to our array detailControlsArray.push video.progressBar detailControlsArray.push video.playButton detailControlsArray.push video.timeElapsed detailControlsArray.push video.timeLeft layer.opacity = 0 for layer in detailControlsArray # video drag methods for bonus points startVideoDrag = (evt) -> offset = if evt.targetTouches then evt.targetTouches[0].screenY - 460 else evt.offsetY if offset > 320 video.draggable.vertical = video.draggable.horizontal = 0 else video.draggable.vertical = video.draggable.horizontal = 1 moveVideoDrag = (evt)-> if isControlsShowing then hideControls() abs = Math.abs (video.midY - Screen.height/2) opacity = Utils.modulate abs, [0, 500], [1, 0] detailBg.opacity = opacity endVideoDrag = -> if Math.abs(video.midY - Screen.height/2) > 100 toFeedView() else if video.draggable.isMoving detailBg.animate properties: opacity: 1 time: .1 video.animate properties: x: 0 midY: Screen.height/2 curve: "spring(200,22,1)"
2261
# Made with Framer # By <NAME> # www.framerjs.com # This imports all the layers for "facebook" into facebookLayers imports = Framer.Importer.load "imported/facebook" # Set device background Framer.Device.background.style.background = "linear-gradient(0deg, #384778 0%, #4f6ba5 100%)" Framer.Defaults.Animation = curve: "ease-out" time: .3 {VideoPlayer} = require "videoplayer" {Bars} = require "bars" # we'll add all of our controls to this later detailControlsArray = [imports.hd] # setup and static elements isFeed = true isControlsShowing = false detailBg = new Layer width: Screen.width height: Screen.height backgroundColor: "#000" opacity: 0 detailControls = new Layer width: 750, height: 100, maxY: Screen.height, opacity: 0 image: "images/overlay-detail.png" doneButton = new Layer width: 104, height: 54, maxX: Screen.width-30, y: 50, opacity: 0 image: "images/done.png" overlayControlsArray = [detailControls, doneButton] # create and position the VideoPlayer video = new VideoPlayer video: "video-480.m4v" width: 735 height: 412 constrainToButton: true autoplay: true muted: true video.centerX() video.y = 782 video.originalFrame = video.frame # put a drop shadow on the feed video video.shadowColor = "rgba(0,0,0,.5)" video.shadowY = 4 video.shadowBlur = 10 # set play and pause button images video.playButtonImage = "images/fb-playbutton.png" video.pauseButtonImage = "images/fb-pausebutton.png" video.playButton.width = video.playButton.height = 42 video.playButton.visible = false video.playButton.x = 20 # make bouncy bars in the feed bars = new Bars barPadding: 2 barWith: 8 bars.maxX = video.maxX - 10 bars.maxY = video.maxY - 10 bars.opacity = .7 video.on "video:ended", -> bars.opacity = 0 # transition from feed to detail view toDetailView = -> isFeed = false video.player.muted = false unless video.isPlaying then video.player.play() video.animate properties: x: 0 midY: Screen.height/2 width: 750 height: 422 shadowY: 0 shadowBlur: 0 curve: "spring(200,22,1)" video.videoLayer.animate properties: width: 750 height: 422 bars.opacity = 0 detailBg.scaleY = 0 detailBg.opacity = 1 detailBg.animate properties: scaleY: 1 for layer in overlayControlsArray layer.animateStop() layer.animate delay: .3 time: .1 properties: opacity: 1 isControlsShowing = true video.progressBar.y = Screen.height/2 + video.height/2 - 17 video.timeElapsed.y = video.progressBar.y - 15 video.timeLeft.y = video.progressBar.y - 15 video.playButton.superLayer = null video.playButton.visible = true video.playButton.y = video.progressBar.y - 22 imports.hd.x = 692 imports.hd.y = video.timeLeft.y + 7 imports.hd.bringToFront() video.progressBar.opacity = video.timeLeft.opacity = video.timeElapsed.opacity = video.playButton.opacity = imports.hd.opacity = 0 showControls(true, true) Utils.delay .5, -> video.draggable.enabled = true video.draggable.momentum = false video.on Events.DragStart, startVideoDrag video.on Events.DragMove, moveVideoDrag video.on Events.DragEnd, endVideoDrag # transition from detail view back to feed toFeedView = -> isFeed = true video.player.muted = true video.animate properties: x: video.originalFrame.x y: video.originalFrame.y width: video.originalFrame.width height: video.originalFrame.height shadowY: 4 shadowBlur: 10 curve: "spring(200,22,1)" video.videoLayer.animate properties: width: video.originalFrame.width height: video.originalFrame.height unless video.player.paused bars.animate properties: opacity: .7 delay: .25 detailBg.animate properties: opacity: 0 for layer in overlayControlsArray layer.animate properties: opacity: 0 hideControls() video.draggable.enabled = false video.off Events.DragStart, startVideoDrag video.off Events.DragMove, moveVideoDrag video.off Events.DragEnd, endVideoDrag # instead of using shyControls = true, show controls by hand showControls = (isDelay, skipdetailControls) -> isControlsShowing = true delay = if isDelay then .75 else 0 controlsArray = unless skipdetailControls then detailControlsArray.concat overlayControlsArray else detailControlsArray for layer in controlsArray layer.animateStop() layer.animate delay: delay properties: opacity: 1 # instead of using shyControls = true, hide controls by hand hideControls = -> isControlsShowing = false controlsArray = detailControlsArray.concat overlayControlsArray for layer in controlsArray layer.animateStop() layer.animate time: .1 properties: opacity: 0 # manage transitions toggleControls = -> if isControlsShowing then hideControls() else showControls() video.on Events.Click, -> if isFeed toDetailView() else toggleControls() doneButton.on Events.Click, -> unless isFeed then toFeedView() # show, position and customize the progress bar video.showProgress = true video.progressBar.width = 420 video.progressBar.height = 2 video.progressBar.backgroundColor = "#555259" video.progressBar.knobSize = 34 video.progressBar.borderRadius = 0 video.progressBar.knob.backgroundColor = "#fff" video.progressBar.fill.backgroundColor = "#fff" video.progressBar.x = 155 # time display style should be set before showing timestamps video.timeStyle = { "font-size": "20px", "color": "#fff" } # show and position elapsed time video.showTimeElapsed = true video.timeElapsed.x = 84 # show and position total video time video.showTimeLeft = true video.timeLeft.x = video.progressBar.maxX + 28 # add controls to our array detailControlsArray.push video.progressBar detailControlsArray.push video.playButton detailControlsArray.push video.timeElapsed detailControlsArray.push video.timeLeft layer.opacity = 0 for layer in detailControlsArray # video drag methods for bonus points startVideoDrag = (evt) -> offset = if evt.targetTouches then evt.targetTouches[0].screenY - 460 else evt.offsetY if offset > 320 video.draggable.vertical = video.draggable.horizontal = 0 else video.draggable.vertical = video.draggable.horizontal = 1 moveVideoDrag = (evt)-> if isControlsShowing then hideControls() abs = Math.abs (video.midY - Screen.height/2) opacity = Utils.modulate abs, [0, 500], [1, 0] detailBg.opacity = opacity endVideoDrag = -> if Math.abs(video.midY - Screen.height/2) > 100 toFeedView() else if video.draggable.isMoving detailBg.animate properties: opacity: 1 time: .1 video.animate properties: x: 0 midY: Screen.height/2 curve: "spring(200,22,1)"
true
# Made with Framer # By PI:NAME:<NAME>END_PI # www.framerjs.com # This imports all the layers for "facebook" into facebookLayers imports = Framer.Importer.load "imported/facebook" # Set device background Framer.Device.background.style.background = "linear-gradient(0deg, #384778 0%, #4f6ba5 100%)" Framer.Defaults.Animation = curve: "ease-out" time: .3 {VideoPlayer} = require "videoplayer" {Bars} = require "bars" # we'll add all of our controls to this later detailControlsArray = [imports.hd] # setup and static elements isFeed = true isControlsShowing = false detailBg = new Layer width: Screen.width height: Screen.height backgroundColor: "#000" opacity: 0 detailControls = new Layer width: 750, height: 100, maxY: Screen.height, opacity: 0 image: "images/overlay-detail.png" doneButton = new Layer width: 104, height: 54, maxX: Screen.width-30, y: 50, opacity: 0 image: "images/done.png" overlayControlsArray = [detailControls, doneButton] # create and position the VideoPlayer video = new VideoPlayer video: "video-480.m4v" width: 735 height: 412 constrainToButton: true autoplay: true muted: true video.centerX() video.y = 782 video.originalFrame = video.frame # put a drop shadow on the feed video video.shadowColor = "rgba(0,0,0,.5)" video.shadowY = 4 video.shadowBlur = 10 # set play and pause button images video.playButtonImage = "images/fb-playbutton.png" video.pauseButtonImage = "images/fb-pausebutton.png" video.playButton.width = video.playButton.height = 42 video.playButton.visible = false video.playButton.x = 20 # make bouncy bars in the feed bars = new Bars barPadding: 2 barWith: 8 bars.maxX = video.maxX - 10 bars.maxY = video.maxY - 10 bars.opacity = .7 video.on "video:ended", -> bars.opacity = 0 # transition from feed to detail view toDetailView = -> isFeed = false video.player.muted = false unless video.isPlaying then video.player.play() video.animate properties: x: 0 midY: Screen.height/2 width: 750 height: 422 shadowY: 0 shadowBlur: 0 curve: "spring(200,22,1)" video.videoLayer.animate properties: width: 750 height: 422 bars.opacity = 0 detailBg.scaleY = 0 detailBg.opacity = 1 detailBg.animate properties: scaleY: 1 for layer in overlayControlsArray layer.animateStop() layer.animate delay: .3 time: .1 properties: opacity: 1 isControlsShowing = true video.progressBar.y = Screen.height/2 + video.height/2 - 17 video.timeElapsed.y = video.progressBar.y - 15 video.timeLeft.y = video.progressBar.y - 15 video.playButton.superLayer = null video.playButton.visible = true video.playButton.y = video.progressBar.y - 22 imports.hd.x = 692 imports.hd.y = video.timeLeft.y + 7 imports.hd.bringToFront() video.progressBar.opacity = video.timeLeft.opacity = video.timeElapsed.opacity = video.playButton.opacity = imports.hd.opacity = 0 showControls(true, true) Utils.delay .5, -> video.draggable.enabled = true video.draggable.momentum = false video.on Events.DragStart, startVideoDrag video.on Events.DragMove, moveVideoDrag video.on Events.DragEnd, endVideoDrag # transition from detail view back to feed toFeedView = -> isFeed = true video.player.muted = true video.animate properties: x: video.originalFrame.x y: video.originalFrame.y width: video.originalFrame.width height: video.originalFrame.height shadowY: 4 shadowBlur: 10 curve: "spring(200,22,1)" video.videoLayer.animate properties: width: video.originalFrame.width height: video.originalFrame.height unless video.player.paused bars.animate properties: opacity: .7 delay: .25 detailBg.animate properties: opacity: 0 for layer in overlayControlsArray layer.animate properties: opacity: 0 hideControls() video.draggable.enabled = false video.off Events.DragStart, startVideoDrag video.off Events.DragMove, moveVideoDrag video.off Events.DragEnd, endVideoDrag # instead of using shyControls = true, show controls by hand showControls = (isDelay, skipdetailControls) -> isControlsShowing = true delay = if isDelay then .75 else 0 controlsArray = unless skipdetailControls then detailControlsArray.concat overlayControlsArray else detailControlsArray for layer in controlsArray layer.animateStop() layer.animate delay: delay properties: opacity: 1 # instead of using shyControls = true, hide controls by hand hideControls = -> isControlsShowing = false controlsArray = detailControlsArray.concat overlayControlsArray for layer in controlsArray layer.animateStop() layer.animate time: .1 properties: opacity: 0 # manage transitions toggleControls = -> if isControlsShowing then hideControls() else showControls() video.on Events.Click, -> if isFeed toDetailView() else toggleControls() doneButton.on Events.Click, -> unless isFeed then toFeedView() # show, position and customize the progress bar video.showProgress = true video.progressBar.width = 420 video.progressBar.height = 2 video.progressBar.backgroundColor = "#555259" video.progressBar.knobSize = 34 video.progressBar.borderRadius = 0 video.progressBar.knob.backgroundColor = "#fff" video.progressBar.fill.backgroundColor = "#fff" video.progressBar.x = 155 # time display style should be set before showing timestamps video.timeStyle = { "font-size": "20px", "color": "#fff" } # show and position elapsed time video.showTimeElapsed = true video.timeElapsed.x = 84 # show and position total video time video.showTimeLeft = true video.timeLeft.x = video.progressBar.maxX + 28 # add controls to our array detailControlsArray.push video.progressBar detailControlsArray.push video.playButton detailControlsArray.push video.timeElapsed detailControlsArray.push video.timeLeft layer.opacity = 0 for layer in detailControlsArray # video drag methods for bonus points startVideoDrag = (evt) -> offset = if evt.targetTouches then evt.targetTouches[0].screenY - 460 else evt.offsetY if offset > 320 video.draggable.vertical = video.draggable.horizontal = 0 else video.draggable.vertical = video.draggable.horizontal = 1 moveVideoDrag = (evt)-> if isControlsShowing then hideControls() abs = Math.abs (video.midY - Screen.height/2) opacity = Utils.modulate abs, [0, 500], [1, 0] detailBg.opacity = opacity endVideoDrag = -> if Math.abs(video.midY - Screen.height/2) > 100 toFeedView() else if video.draggable.isMoving detailBg.animate properties: opacity: 1 time: .1 video.animate properties: x: 0 midY: Screen.height/2 curve: "spring(200,22,1)"
[ { "context": " if(winningPlayer.daburu)\n flags.push(\"Daburu Riichi\")\n if(\"Ippatsu\" in @oneRoundTracker[winningP", "end": 14071, "score": 0.7938785552978516, "start": 14059, "tag": "NAME", "value": "aburu Riichi" }, { "context": " else\n flags.push(...
akagiGame.coffee
Kuba663/Akagi-Bot
1
gamePieces = require('./akagiTiles.coffee') playerObject = require('./akagiPlayer.coffee') score = require('./akagiScoring.coffee') test = require('./akagiTest.coffee') Promise = require('promise') _ = require('lodash') class MessageSender #Way to make sending messages to both players and the observation channel easier. constructor: (@playerOrObserver, whichType) -> if whichType == "player" @player = true @playerNumber = @playerOrObserver.playerNumber else @player = false @playerNumber = 0 sendMessage: (text) -> if(@player) @playerOrObserver.sendMessage(text) else @playerOrObserver.send(text) namedTiles:-> if(@player) return @playerOrObserver.namedTiles else return true class MahjongGame #A four player game of Mahjong constructor: (playerChannels, server, gameSettings) -> if("TestGame" in gameSettings) @wall = new gamePieces.Wall(test.testWall) else @wall = new gamePieces.Wall() @counter = 0 #Put down when east winds a round, increasing point values. @riichiSticks = [] #Used to keep track when a player calls riichi @pendingRiichiPoints = false #Keeps track of who just called riichi, so that once we are sure the next round has started, then they can have their stick added to the pile. @oneRoundTracker = [[],[],[],[]] #Keeps track of all the special things that can give points if done within one go around @kuikae = [] #Keeps track of what tiles cannot be discarded after calling chi or pon. @lastDiscard = false #Keeps track of the last tile discarded this game. @winningPlayer = [] @players = [ new playerObject(playerChannels[1],1), new playerObject(playerChannels[2],2), new playerObject(playerChannels[3],3), new playerObject(playerChannels[4],4) ] @gameObservationChannel = playerChannels[0] @messageRecievers = [] @messageRecievers.push(new MessageSender(@gameObservationChannel,"observer")) for player in @players @messageRecievers.push(new MessageSender(player,"player")) @startRoundOne() getPlayerByPlayerNumber:(playerNumber) -> #Returns the player who's player number is the chosen number for player in @players if(player.playerNumber == parseInt(playerNumber,10)) return player startRoundOne: -> #Randomize starting locations, then assign each player a seat. @players = _.shuffle(@players) @eastPlayer = @players[0] @southPlayer = @players[1] @westPlayer = @players[2] @northPlayer = @players[3] #Make player know own winds @eastPlayer.setWind("East") @southPlayer.setWind("South") @westPlayer.setWind("West") @northPlayer.setWind("North") #Makes sure we know who plays after who @eastPlayer.setNextPlayer(@southPlayer.playerNumber) @southPlayer.setNextPlayer(@westPlayer.playerNumber) @westPlayer.setNextPlayer(@northPlayer.playerNumber) @northPlayer.setNextPlayer(@eastPlayer.playerNumber) @prevailingWind = "East" @dealer = @eastPlayer @startRound() startRound: -> @turn = @dealer.playerNumber @phase = 'discard' @wall.doraFlip() @kuikae = [] @pendingRiichiPoints = false @lastDiscard = false for player in @messageRecievers player.sendMessage("New Round Start") player.sendMessage("Prevailing wind is #{@prevailingWind}.") player.sendMessage("Dora is #{@wall.printDora()}.") for player in @players player.hand.startDraw(@wall) player.roundStart(@wall) if(player.wind == "East") player.sendMessage("You are the first player. Please discard a tile.") @oneRoundTracker = [["First Round"],["First Round"],["First Round"],["First Round"]] newRound: -> if @winningPlayer.length == 0 || "East" in _.map(@winningPlayer,(x)->x.wind) @counter += 1 else @counter = 0 if("East" not in _.map(@winningPlayer,(x)->x.wind)) for player in @players player.rotateWind() for player in @messageRecievers player.sendMessage("The winds have rotated.") if @eastPlayer.wind == "East" if(@prevailingWind == "East") @prevailingWind = "South" else @endGame() return 0 @wall = new gamePieces.Wall() @winningPlayer = [] for player in @players player.resetHand() if player.wind == "East" @dealer = player @startRound() #Starts a new game of Mahjong. startNewGame: -> for folk in @messageRecievers folk.sendMessage("A new game of mahjong is starting. Seats and play order will be randomized, and all points reset to 30000.") folk.sendMessage("-----------------------------------------------------------------------------------------------------------") for player in @players player.roundPoints = 30000 player.resetHand() @wall = new gamePieces.Wall() @winningPlayer = [] @counter = 0 @startRoundOne() #Sends out all the appropriate messages when the game ends endGame: -> winOrder = _.sortBy(@players, (x) -> -1*x.roundPoints) @phase = "GameOver" placements = {"First":[],"Second":[],"Third":[],"Fourth":[]} ranks = ["First","Second","Third","Fourth"] for player in winOrder for rank in ranks if(placements[rank].length == 0 || placements[rank][0].roundPoints == player.roundPoints) placements[rank].push(player) break for winner in placements["First"] winner.sendMessage("You win!") if(@riichiSticks.length > 0) winner.roundPoints += 1000*@riichiSticks.length/placements["First"].length winner.sendMessage("As the winner, you recieve the remaining riichi sticks and thus gain #{1000*@riichiSticks.length/placements["First"].length} points.") @riichiSticks = [] for player in @messageRecievers player.sendMessage("The game has ended.") if(placements["First"].length == 1) player.sendMessage("First place was player #{placements["First"][0].playerNumber} with #{placements["First"][0].roundPoints} points.") else player.sendMessage("The following players tied for first with #{placements["First"][0].roundPoints}: #{_.map(placements["First"],(x)->x.playerNumber)}") if(placements["Second"].length == 1) player.sendMessage("Second place was player #{placements["Second"][0].playerNumber} with #{placements["Second"][0].roundPoints} points.") else if(placements["Second"].length > 1) player.sendMessage("The following players tied for second with #{placements["Second"][0].roundPoints}: #{_.map(placements["Second"],(x)->x.playerNumber)}") if(placements["Third"].length == 1) player.sendMessage("Third place was player #{placements["Third"][0].playerNumber} with #{placements["Third"][0].roundPoints} points.") else if(placements["Third"].length > 1) player.sendMessage("The following players tied for third with #{placements["Third"][0].roundPoints}: #{_.map(placements["Third"],(x)->x.playerNumber)}") if(placements["Fourth"].length == 1) player.sendMessage("Fourth place was player #{placements["Fourth"][0].playerNumber} with #{placements["Fourth"][0].roundPoints} points.") #Uma calculations umaPoints = [15000,5000,-5000,-15000] for rank in ranks accumulatedPoints = 0 for x in placements[rank] accumulatedPoints += umaPoints.shift() for x in placements[rank] x.roundPoints += accumulatedPoints/placements[rank].length for player in @messageRecievers player.sendMessage("After factoring in uma, here are the final point values.") if(placements["First"].length == 1) player.sendMessage("First place was player #{placements["First"][0].playerNumber} with #{placements["First"][0].roundPoints} points.") else player.sendMessage("The following players tied for first with #{placements["First"][0].roundPoints}: #{_.map(placements["First"],(x)->x.playerNumber)}") if(placements["Second"].length == 1) player.sendMessage("Second place was player #{placements["Second"][0].playerNumber} with #{placements["Second"][0].roundPoints} points.") else if(placements["Second"].length > 1) player.sendMessage("The following players tied for second with #{placements["Second"][0].roundPoints}: #{_.map(placements["Second"],(x)->x.playerNumber)}") if(placements["Third"].length == 1) player.sendMessage("Third place was player #{placements["Third"][0].playerNumber} with #{placements["Third"][0].roundPoints} points.") else if(placements["Third"].length > 1) player.sendMessage("The following players tied for third with #{placements["Third"][0].roundPoints}: #{_.map(placements["Third"],(x)->x.playerNumber)}") if(placements["Fourth"].length == 1) player.sendMessage("Fourth place was player #{placements["Fourth"][0].playerNumber} with #{placements["Fourth"][0].roundPoints} points.") player.sendMessage("Congratulations to the winning player(s)!") if(player.player) player.sendMessage("Type 'end game' to remove all game channels, or 'play again' to start a new game with the same players.") #Called when the round ends with no winner. exaustiveDraw: -> @winningPlayer = _.filter(@players,(x)->score.tenpaiWith(x.hand).length != 0) for player in @messageRecievers player.sendMessage("The round has ended in an exaustive draw.") if(@winningPlayer.length == 0) player.sendMessage("No players were in tenpai.") else player.sendMessage("The following players were in tenpai: #{x.playerNumber for x in @winningPlayer}") player.sendMessage("The tenpai hands looked like this: #{"#{x.playerNumber} - #{x.hand.printHand(player.tileNames)}" for x in @winningPlayer}") if(player.playerNumber in _.map(@winningPlayer,(x)->x.playerNumber)) player.playerOrObserver.roundPoints += 3000/@winningPlayer.length player.sendMessage("Because you were in tenpai, you gain #{3000/@winningPlayer.length} points.") else if(player.playerNumber != 0) player.playerOrObserver.roundPoints -= 3000/(4-@winningPlayer.length) player.sendMessage("Because you were not in tenpai, you pay #{3000/(4-@winningPlayer.length)} points.") player.sendMessage("The round is over. To start the next round, type next.") @phase = "finished" #Put the stick into the pot, once the next turn has started. Also, adds discarded tile, to possible temporary furiten list. confirmNextTurn: -> if(@pendingRiichiPoints) @riichiSticks.push(@pendingRiichiPoints) for player in @players if player.playerNumber == @pendingRiichiPoints player.roundPoints -= 1000 @pendingRiichiPoints = false for player in @players player.tilesSinceLastDraw.push(@lastDiscard) #Used to empty the round tracker if someone makes a call interuptRound: -> @oneRoundTracker = [[],[],[],[]] #Removes all one round counters for one player once it gets back to them. endGoAround:(playerTurn) -> @oneRoundTracker[playerTurn.playerNumber-1] = [] drawTile:(playerToDraw) -> if(@turn == playerToDraw.playerNumber) if(@phase != "draw") playerToDraw.sendMessage("It is not the draw phase.") else playerToDraw.wallDraw(@wall) @phase = "discard" @confirmNextTurn() if(!playerToDraw.riichiCalled()) playerToDraw.tilesSinceLastDraw = [] if(playerToDraw.wantsHelp) tenpaiDiscards = score.tenpaiWithout(playerToDraw.hand) if(score.getPossibleHands(playerToDraw.hand).length > 0) playerToDraw.sendMessage("You have a completed hand. You may call Tsumo if you have any yaku.") else if(tenpaiDiscards.length > 0) playerToDraw.sendMessage("You can be in tenpai by discarding any of the following tiles:") playerToDraw.sendMessage((tile.getName(playerToDraw.namedTiles) for tile in tenpaiDiscards)) if(@wall.wallFinished) @oneRoundTracker[playerToDraw.playerNumber - 1].push("Haitei") for player in @messageRecievers if player.playerNumber != playerToDraw.playerNumber player.sendMessage("Player #{playerToDraw.playerNumber} has drawn a tile.") if(@wall.wallFinished) player.sendMessage("This is the last draw of the game. The game will end after the discard.") else playerToDraw.sendMessage("It is not your turn.") #checks whether someone is furiten or not furiten:(player) -> tenpai = score.tenpaiWith(player.hand) furitenBecause = [] for tile in tenpai for discard in player.discardPile.contains if(tile.getTextName() == discard.getTextName()) furitenBecause.push(tile) for discard in player.tilesSinceLastDraw if(tile.getTextName() == discard.getTextName()) furitenBecause.push(tile) if(furitenBecause.length == 0) return false else return furitenBecause #checks and sets liability for 4 winds/3 dragon hands liabilityChecker:(playerCalling,playerLiable) -> if(_.filter(playerCalling.hand.calledMelds,(x)->x.suit() == "dragon").length == 3 || _.filter(playerCalling.hand.calledMelds,(x)->x.suit() == "wind").length == 4) playerCalling.liablePlayer = playerLiable.playerNumber for player in @messageRecievers if(player.playerNumber != playerLiable.playerNumber) player.sendMessage("Player #{playerLiable.playerNumber} is now liable for the cost of the potential Dai Sangen or Dai Suushii.") else player.sendMessage("You are now liable for the cost of the potential Dai Sangen or Dai Suushii") #Calculates all the flags for non hand based points in the game. winFlagCalculator:(winningPlayer,winType) -> flags = [] if(winningPlayer.riichiCalled()) flags.push("Riichi") if(winningPlayer.daburu) flags.push("Daburu Riichi") if("Ippatsu" in @oneRoundTracker[winningPlayer.playerNumber - 1]) flags.push("Ippatsu") if("First Round" in @oneRoundTracker[winningPlayer.playerNumber-1]) if(winType == "Ron") flags.push("Renho") else if(winningPlayer.playerNumber == @dealer.playerNumber) flags.push("Tenho") else flags.push("Chiho") if("Rinshan Kaihou" in @oneRoundTracker[winningPlayer.playerNumber-1]) flags.push("Rinshan Kaihou") if(winType == "Ron") if(Array.isArray(@phase) && @phase[0] in ["extendKaning","extendRon"]) flags.push("Chan Kan") if(@wall.wallFinished && @phase in ["react","roning"]) flags.push("Houtei") if("Haitei" in @oneRoundTracker[winningPlayer.playerNumber-1]) flags.push("Haitei") console.log(flags) return new score.gameFlags(winningPlayer.wind,@prevailingWind,flags) ron:(playerToRon) -> if(@turn == playerToRon.nextPlayer && (@phase in ["draw","react"] || (Array.isArray(@phase) && @phase[0] not in ["concealedKaning","extendKaning","concealedRon","extendRon"]))) playerToRon.sendMessage("Cannot Ron off of own discard.") else if(@turn == playerToRon.playerNumber && (@phase == "discard"||(Array.isArray(@phase) && @phase[0] in ["concealedKaning","extendKaning","concealedRon","extendRon"]))) playerToRon.sendMessage("During your turn, use Tsumo, instead of Ron.") else if(@furiten(playerToRon)) playerToRon.sendMessage("You may not Ron, because you are in furiten.") else if(Array.isArray(@phase) && @phase[0] in ["concealedKaning","concealedRon"] && !score.thirteenOrphans(playerToRon.hand,@phase[1])) playerToRon.sendMessage("You may only call Ron off of a concealed Kan, if you are winning via the thirteen orphans hand.") else if(Array.isArray(@phase) && @phase[0] in ["concealedRon","extendRon","roning"] && playerToRon.playerNumber in @phase[2]) playerToRon.sendMessage("You have already declared Ron.") else if(Array.isArray(@phase) && @phase[0] in ["concealedKaning","concealedRon","extendKaning","extendRon"]) discarder = _.find(@players,(x)=> @turn == x.playerNumber) discardedTile = @phase[1] else discarder = _.find(@players,(x)=> @turn == x.nextPlayer) discardedTile = discarder.discardPile.contains[-1..][0] testHand = _.cloneDeep(playerToRon.hand) testHand.contains.push(discardedTile) testHand.lastTileDrawn = discardedTile testHand.draw(null,0) testHand.lastTileFrom = discarder.playerNumber scoreMax = score.scoreMahjongHand(testHand,@winFlagCalculator(playerToRon,"Ron"),[@wall.dora,@wall.urDora]) if(scoreMax[0] == 0) playerToRon.sendMessage(scoreMax[1]) else playerToRon.hand = testHand for player in @messageRecievers if(player.playerNumber == playerToRon.playerNumber) player.sendMessage("You have declared Ron.") else player.sendMessage("Player #{playerToRon.playerNumber} has declared Ron.") if(Array.isArray(@phase)) if(@phase[0] in ["concealedKaning","concealedRon"]) state = "concealedRon" else if(@phase[0] in ["extendKaning","extendRon"]) state = "extendRon" else state = "roning" #Figure out who all has declared ron thus far. if(@phase[0] in ["concealedRon","extendRon","roning"]) ronGroup = @phase[2].concat(playerToRon.playerNumber) else ronGroup = [playerToRon.playerNumber] else state = "roning" ronGroup = [playerToRon.playerNumber] @phase = [state,discardedTile,ronGroup] ronAfterFive = new Promise((resolve,reject) => setTimeout(-> resolve("Time has Passed") ,5000)) ronAfterFive .then((message)=> if(_.isEqual(@phase,[state,discardedTile,ronGroup])) riichiBet = @riichiSticks.length winnerOrder = [] winnerOrder.push(_.find(@players,(x)->discarder.nextPlayer == x.playerNumber)) winnerOrder.push(_.find(@players,(x)->winnerOrder[0].nextPlayer==x.playerNumber)) winnerOrder.push(_.find(@players,(x)->winnerOrder[1].nextPlayer==x.playerNumber)) winnerOrder = _.filter(winnerOrder,(x)=>x.playerNumber in @phase[2]) for winner in winnerOrder if(winner.riichiCalled()) winner.roundPoints+=1000 winner.sendMessage("Riichi bet returned to you.") riichiBet -= 1 if(riichiBet>0) winnerOrder[0].roundPoints+=1000*riichiBet winner.sendMessage("Remaining riichi bets give you #{1000*riichiBet} points.") @riichiSticks = [] for winner in winnerOrder scoreMax = score.scoreMahjongHand(winner.hand,@winFlagCalculator(playerToRon,"Ron"),[@wall.dora,@wall.urDora]) if(playerToRon.wind == "East") pointsGained = _roundUpToClosestHundred(6*scoreMax[0])+@counter*300 pointsLost = _roundUpToClosestHundred(6*scoreMax[0]) else pointsGained = _roundUpToClosestHundred(4*scoreMax[0])+@counter*300 pointsLost = _roundUpToClosestHundred(4*scoreMax[0]) if(winner.liablePlayer && winner.liablePlayer != discarder.playerNumber) pointsLost = pointsLost/2 for player in @messageRecievers if(player.playerNumber == winner.playerNumber) player.playerOrObserver.roundPoints += pointsGained player.sendMessage("You have won from Ron.") player.sendMessage("You receive #{pointsGained} points.") else player.sendMessage("Player #{winner.playerNumber} has won via Ron.") if(player.playerNumber == winner.liablePlayer) player.playerOrObserver.roundPoints -= pointsLost player.sendMessage("Because you were liable for this hand, you pay #{pointsLost} points.") if(discarder.playerNumber == player.playerNumber) player.playerOrObserver.roundPoints -= pointsLost+300*@counter player.sendMessage("Because you discarded the winning tile, you pay #{pointsLost+300*@counter} points.") player.sendMessage("The winning hand contained the following yaku: #{scoreMax[1]}") player.sendMessage("The winning hand was: #{winner.hand.printHand(player.namedTiles)}") player.sendMessage("The dora indicators were: #{@wall.printDora(player.namedTiles)}") if(winner.riichiCalled()) player.sendMessage("The ur dora indicators were: #{@wall.printUrDora(player.namedTiles)}") for player in @players player.sendMessage("The round is over. To start the next round, type next.") @winningPlayer = winnerOrder @phase = "finished" ) .catch(console.error) tsumo:(playerToTsumo) -> if(@turn!=playerToTsumo.playerNumber) playerToTsumo.sendMessage("Not your turn.") else if(@phase!="discard") playerToTsumo.sendMessage("You don't have enough tiles.") else scoreMax = score.scoreMahjongHand(playerToTsumo.hand, @winFlagCalculator(playerToTsumo,"Tsumo"), [@wall.dora,@wall.urDora]) if(scoreMax[0] == 0) playerToTsumo.sendMessage(scoreMax[1]) else for player in @players #CalculatePoints if(playerToTsumo.wind == "East") if(playerToTsumo.liablePlayer) if player.playerNumber = playerToTsumo.liablePlayer pointsLost = _roundUpToClosestHundred(6*scoreMax[0])+@counter*100 else if player.playerNumber == playerToTsumo.playerNumber pointsGained = _roundUpToClosestHundred(6*scoreMax[0])+@counter*100+@riichiSticks.length*1000 else pointsLost = 0 else if player.playerNumber != @turn pointsLost = _roundUpToClosestHundred(2*scoreMax[0])+@counter*100 else pointsGained = 3*_roundUpToClosestHundred(2*scoreMax[0])+@counter*300+@riichiSticks.length*1000 else if(playerToTsumo.liablePlayer) if player.playerNumber = playerToTsumo.liablePlayer pointsLost = _roundUpToClosestHundred(4*scoreMax[0])+@counter*100 else if player.playerNumber == playerToTsumo.playerNumber pointsGained = _roundUpToClosestHundred(4*scoreMax[0])+@counter*100+@riichiSticks.length*1000 else pointsLost = 0 else if player.wind == "East" pointsLost = _roundUpToClosestHundred(2*scoreMax[0])+@counter*100 else if player.playerNumber != @turn pointsLost = _roundUpToClosestHundred(scoreMax[0])+@counter*100 else pointsGained = _roundUpToClosestHundred(2*scoreMax[0])+2*_roundUpToClosestHundred(scoreMax[0])+@counter*300+@riichiSticks.length*1000 @riichiSticks = [] #Say points if(player.playerNumber != @turn) player.roundPoints -= pointsLost player.sendMessage("Player #{playerToTsumo.playerNumber} has won from self draw.") player.sendMessage("You pay out #{pointsLost} points.") else player.roundPoints += pointsGained player.sendMessage("You have won on self draw.") player.sendMessage("You receive #{pointsGained} points.") @gameObservationChannel.send("Player #{playerToTsumo.playerNumber} has won from self draw.") for player in @messageRecievers player.sendMessage("The winning hand contained the following yaku: #{scoreMax[1]}") player.sendMessage("The winning hand was: #{playerToTsumo.hand.printHand(player.namedTiles)}") player.sendMessage("The dora indicators were: #{@wall.printDora(player.namedTiles)}") if(playerToTsumo.riichiCalled()) player.sendMessage("The ur dora indicators were: #{@wall.printUrDora(player.namedTiles)}") if(player.player) player.sendMessage("The round is over. To start the next round, type next.") @winningPlayer = [playerToTsumo] @phase = "finished" chiTile:(playerToChi, tile1, tile2) -> if(playerToChi.playerNumber != @turn) playerToChi.sendMessage("May only Chi when you are next in turn order.") else if(playerToChi.riichiCalled()) playerToChi.sendMessage("May not Chi after declaring Riichi.") else if(@wall.wallFinished) playerToChi.sendMessage("May not call Chi on the last turn.") else if(@phase in ["draw","react"]) if(_.findIndex(playerToChi.hand.uncalled(),(x) -> _.isEqual(tile1, x)) != -1 && _.findIndex(playerToChi.hand.uncalled(),(x) -> _.isEqual(tile2, x)) != -1) discarder = _.find(@players,(x)=> @turn == x.nextPlayer) toChi = discarder.discardPile.contains[-1..][0] _chiable = (t1,t2,t3) -> if(t1.suit!=t2.suit || t2.suit!=t3.suit) return false sortedValues = [t1.value,t2.value,t3.value].sort() if(sortedValues[0]+1 == sortedValues[1] && sortedValues[1]+1 == sortedValues[2]) return true else return false if(_chiable(toChi,tile1,tile2)) @phase = ["chiing",playerToChi.playerNumber] for player in @messageRecievers if(player.playerNumber != playerToChi.playerNumber) player.sendMessage("Player #{playerToChi.playerNumber} has declared Chi.") else player.sendMessage("You have declared Chi.") chiAfterFive = new Promise((resolve,reject) => setTimeout(-> resolve("Time has Passed") ,5000)) chiAfterFive .then((message)=> if(_.isEqual(@phase,["chiing",playerToChi.playerNumber])) @phase = "discard" @confirmNextTurn() @interuptRound() @kuikae.push(toChi) if(tile1.value > toChi.value && tile2.value > toChi.value) @kuikae.push(new gamePieces.Tile(toChi.suit,toChi.value+3)) else if(tile1.value < toChi.value && tile2.value < toChi.value) @kuikae.push(new gamePieces.Tile(toChi.suit,toChi.value-3)) for player in @players if(@turn == player.nextPlayer) playerToChi.hand.draw(player.discardPile) playerToChi.hand.calledMelds.push(new gamePieces.Meld([toChi,tile1,tile2],player.playerNumber)) player.sendMessage("Player #{playerToChi.playerNumber}'s Chi has completed.") else if(player.playerNumber == playerToChi.playerNumber) player.sendMessage("Your Chi has completed. Please discard a tile.") else player.sendMessage("Player #{playerToChi.playerNumber}'s Chi has completed.") @gameObservationChannel.send("Player #{playerToChi.playerNumber}'s Chi has completed.") ) .catch(console.error) else playerToChi.sendMessage("Tiles specified do not create a legal meld.") else playerToChi.sendMessage("Hand doesn't contain tiles specified.") else if(Array.isArray(@phase)) playerToChi.sendMessage("Chi has lower priority than Pon, Kan, and Ron.") else playerToChi.sendMessage("Wrong time to Chi") #Finds out if the tiles in a concealed pung onlyPung:(hand,tile) -> withoutDraw = _.cloneDeep(hand) withoutDraw.discard(tile.getTextName()) waits = score.tenpaiWith(withoutDraw) for win in waits testHand = _.cloneDeep(withoutDraw) testHand.lastTileDrawn = win testHand.contains.push(win) melds = score.getPossibleHands(testHand) for meld in melds if(meld.type == "Chow" && meld.containsTile(tile)) return false return true selfKanTiles:(playerToKan,tileToKan) -> uncalledKanTiles = _.filter(playerToKan.hand.uncalled(),(x) -> _.isEqual(x,tileToKan)).length if(@turn != playerToKan.playerNumber) playerToKan.sendMessage("It is not your turn.") else if(@phase != "discard") playerToKan.sendMessage("One can only self Kan during one's own turn after one has drawn.") else if(@wall.dora.length == 5) playerToKan.sendMessage("There can only be 4 Kans per game.") else if(@wall.wallFinished) playerToKan.sendMessage("May not call Kan on the last turn.") else if(uncalledKanTiles < 1) playerToKan.sendMessage("No tiles to Kan with.") else if(uncalledKanTiles in [2,3]) playerToKan.sendMessage("Wrong number of tiles to Kan with.") else if(uncalledKanTiles == 4 && playerToKan.riichiCalled() && !@onlyPung(playerToKan.hand,tileToKan)) playerToKan.sendMessage("You can't call Kan with this tile, because it changes the structure of the hand.") else if(uncalledKanTiles == 4) @phase = ["concealedKaning",tileToKan] for player in @messageRecievers if(player.playerNumber != playerToKan.playerNumber) player.sendMessage("Player #{playerToKan.playerNumber} has declared a concealed Kan on #{tileToKan.getName(player.namedTiles)}.") else player.sendMessage("You have declared a concealed Kan on #{tileToKan.getName(player.namedTiles)}.") for player in @players if(player.wantsHelp && player.nextPlayer != @turn) if(score.thirteenOrphans(player.hand,tileToKan)) player.sendMessage("You may Ron off of this concealed kong, as long as you are not furiten.") concealAfterFive = new Promise((resolve,reject) => setTimeout(-> resolve("Time has Passed") ,5000)) concealAfterFive .then((message)=> if(_.isEqual(@phase,["concealedKaning",tileToKan])) @phase = "discard" @interuptRound() @oneRoundTracker[playerToKan.playerNumber-1].push("Rinshan Kaihou") playerToKan.hand.calledMelds.push(new gamePieces.Meld([tileToKan,tileToKan,tileToKan,tileToKan])) drawnTile = playerToKan.hand.draw(@wall)[0] @wall.doraFlip() for player in @messageRecievers if(player.playerNumber!=playerToKan.playerNumber) player.sendMessage("Player #{playerToKan.playerNumber} has completed their Kan.") else player.sendMessage("You have completed your Kan.") player.sendMessage("Your deadwall draw is #{drawnTile.getName(player.namedTiles)}.") player.sendMessage("The Dora Tiles are now: #{@wall.printDora(player.namedTiles)}") @turn = playerToKan.playerNumber ) .catch(console.error) else pungToExtend = _.filter(playerToKan.hand.calledMelds,(x) -> x.type == "Pung" && x.suit() == tileToKan.suit && x.value() == tileToKan.value) if(pungToExtend.length == 1) pungToExtend = pungToExtend[0] @phase = ["extendKaning",tileToKan] for player in @messageRecievers if(player.playerNumber != playerToKan.playerNumber) player.sendMessage("Player #{playerToKan.playerNumber} has declared an extended Kan on #{tileToKan.getName(player.namedTiles)}.") else player.sendMessage("You have declared an extended Kan on #{tileToKan.getName(player.namedTiles)}.") for player in @players if(player.wantsHelp && player.nextPlayer != @turn) if(_.some(score.tenpaiWith(player.hand),(x)->_.isEqual(x,discarded))) player.sendMessage("You may rob the kong and Ron, as long as you are not furiten.") extendAfterFive = new Promise((resolve,reject) => setTimeout(-> resolve("Time has Passed") ,5000)) extendAfterFive .then((message)=> if(_.isEqual(@phase,["extendKaning",tileToKan])) @phase = "discard" @interuptRound() @oneRoundTracker[playerToKan.playerNumber-1].push("Rinshan Kaihou") for meld in playerToKan.hand.calledMelds if(meld.type == "Pung" && meld.suit() == tileToKan.suit && meld.value() == tileToKan.value) meld.makeKong() drawnTile = playerToKan.hand.draw(@wall)[0] @wall.doraFlip() for player in @messageRecievers if(player.playerNumber!=playerToKan.playerNumber) player.sendMessage("Player #{playerToKan.playerNumber} has completed their Kan.") else player.sendMessage("You have completed your Kan.") player.sendMessage("Your deadwall draw is #{drawnTile.getName(player.namedTiles)}.") player.sendMessage("The Dora Tiles are now: #{@wall.printDora(player.namedTiles)}") @turn = playerToKan.playerNumber ) .catch(console.error) else playerToKan.sendMessage("Don't have Pung to extend into Kong.") openKanTiles:(playerToKan) -> if(playerToKan.riichiCalled()) playerToKan.sendMessage("You can't call tiles, except to win, after declaring Riichi.") else if(Array.isArray(@phase) && @phase[0] == "roning") playerToKan.sendMessage("Kan has lower priority than Ron.") else if(@wall.dora.length == 5) playerToKan.sendMessage("There can only be 4 Kans per game.") else if(@wall.wallFinished) playerToKan.sendMessage("May not call Kan on the last turn.") else if(Array.isArray(@phase) && @phase[0] == "chiing" && playerToPon.playerNumber == @phase[1]) playerToKan.sendMessage("One cannot Kan if one has already declared Chi.") else if((Array.isArray(@phase) && @phase[0] == "chiing") || @phase in ["react","draw"]) discarder = _.find(@players,(x)=> @turn == x.nextPlayer) toKan = discarder.discardPile.contains[-1..][0] if(_.filter(playerToKan.hand.uncalled(),(x) -> _.isEqual(x,toKan)).length == 3) @phase = ["callKaning",playerToKan.playerNumber] for player in @messageRecievers if(player.playerNumber!= playerToKan.playerNumber) player.sendMessage("Player #{playerToKan.playerNumber} has declared Kan.") else player.sendMessage("You have declared Kan.") kanAfterFive = new Promise((resolve,reject) => setTimeout(-> resolve("Time has Passed") ,5000)) kanAfterFive .then((message)=> if(_.isEqual(@phase,["callKaning",playerToKan.playerNumber])) @phase = "discard" @confirmNextTurn() @interuptRound() @oneRoundTracker[playerToKan.playerNumber-1].push("Rinshan Kaihou") playerToKan.hand.draw(discarder.discardPile) playerToKan.hand.calledMelds.push(new gamePieces.Meld([toKan,toKan,toKan,toKan],discarder.playerNumber)) if(toKan.isHonor()) @liabilityChecker(playerToKan,discarder) drawnTile = playerToKan.hand.draw(@wall)[0] @wall.doraFlip() for player in @messageRecievers if(player.playerNumber!=playerToKan.playerNumber) player.sendMessage("Player #{playerToKan.playerNumber} has completed their Kan.") else player.sendMessage("You have completed your Kan.") player.sendMessage("Your deadwall draw is #{drawnTile.getName(player.namedTiles)}.") player.sendMessage("The Dora Tiles are now: #{@wall.printDora(player.namedTiles)}") @turn = playerToKan.playerNumber ) .catch(console.error) else playerToKan.sendMessage("You don't have correct tiles to Kan.") else playerToKan.sendMessage("Wrong time to Kan.") ponTile:(playerToPon) -> if(playerToPon.riichiCalled()) playerToPon.sendMessage("You may not Pon after declaring Riichi.") else if(@wall.wallFinished) playerToPon.sendMessage("May not call Pon on the last turn.") else if(Array.isArray(@phase) && @phase[0] == "Chi" && @phase[1] == playerToPon.playerNumber) playerToPon.sendMessage("Can't call Pon if you already called Chi.") else if((@phase in ["react","draw"] || (Array.isArray(@phase) && @phase[0] == "chiing")) && @turn != playerToPon.nextPlayer) discarder = _.find(@players,(x)=> @turn == x.nextPlayer) toPon = discarder.discardPile.contains[-1..][0] if(_.findIndex(playerToPon.hand.uncalled(),(x)->_.isEqual(toPon,x))!=_.findLastIndex(playerToPon.hand.uncalled(),(x)->_.isEqual(toPon,x))) @phase = ["poning",playerToPon.playerNumber] for player in @messageRecievers if(player.playerNumber != playerToPon.playerNumber) player.sendMessage("Player #{playerToPon.playerNumber} has declared Pon.") else player.sendMessage("You have declared Pon.") fiveSecondsToPon = new Promise((resolve,reject) => setTimeout(-> resolve("Time has Passed") ,5000)) fiveSecondsToPon .then((message)=> if(_.isEqual(@phase,["poning",playerToPon.playerNumber])) @phase = "discard" @confirmNextTurn() @interuptRound() @kuikae.push(toPon) for player in @players if(@turn == player.nextPlayer) playerToPon.hand.draw(player.discardPile) playerToPon.hand.calledMelds.push(new gamePieces.Meld([toPon,toPon,toPon],player.playerNumber)) player.sendMessage("Player #{playerToPon.playerNumber}'s Pon has completed.") if(player.playerNumber == playerToPon.playerNumber) player.sendMessage("Your Pon has completed. Please discard a tile.") else player.sendMessage("Player #{playerToPon.playerNumber}'s Pon has completed.") @gameObservationChannel.send("Player #{playerToPon.playerNumber}'s Pon has completed.") @turn = playerToPon.playerNumber if(toPon.isHonor()) @liabilityChecker(playerToPon,discarder) ) .catch(console.error) else playerToPon.sendMessage("Don't have correct tiles.") else if(Array.isArray(@phase) && @phase[0] == "roning") playerToPon.sendMessage("Pon has lower priorty than Ron.") else playerToPon.sendMessage("Wrong time to Pon.") discardTile:(playerToDiscard,tileToDiscard,riichi = false) -> if(@turn == playerToDiscard.playerNumber) if(@phase != "discard") playerToDiscard.sendMessage("It is not the discard phase.") else if(riichi && playerToDiscard.hand.isConcealed() == false) playerToDiscard.sendMessage("You may only riichi with a concealed hand.") else if(playerToDiscard.riichiCalled() && tileToDiscard != playerToDiscard.hand.lastTileDrawn.getTextName()) playerToDiscard.sendMessage("Once you have declared Riichi, you must always discard the drawn tile.") else if(riichi && @wall.leftInWall() < 4) playerToDiscard.sendMessage("You can't call riichi if there are less than four tiles remaining in the wall.") else if(riichi && !_.some(score.tenpaiWithout(playerToDiscard.hand),(x)->x.getTextName()==tileToDiscard)) playerToDiscard.sendMessage("You would not be in tenpai if you discarded that tile to call Riichi.") else if(_.some(@kuikae,(x)->x.getTextName()==tileToDiscard)) playerToDiscard.sendMessage("May not discard the same tile just called, or the opposite end of the chow just called.") else discarded = playerToDiscard.discardTile(tileToDiscard) if(discarded) if(riichi) if("First Round" in @oneRoundTracker[playerToDiscard.playerNumber-1]) playerToDiscard.daburu = true outtext = "declared daburu riichi with" else outtext = "declared riichi with" playerToDiscard.discardPile.declareRiichi() @pendingRiichiPoints = playerToDiscard.playerNumber else outtext = "discarded" @lastDiscard = discarded @endGoAround(playerToDiscard) if(riichi) @oneRoundTracker[playerToDiscard.playerNumber-1].push("Ippatsu") for player in @messageRecievers if(player.playerNumber != playerToDiscard.playerNumber) player.sendMessage("Player #{playerToDiscard.playerNumber} #{outtext} a #{discarded.getName(player.namedTiles)}.") else player.sendMessage("You #{outtext} a #{discarded.getName(player.namedTiles)}.") @turn = playerToDiscard.nextPlayer @phase = "react" @kuikae = [] for player in @players if(player.wantsHelp && player.nextPlayer != @turn) calls = player.hand.whichCalls(@lastDiscard) if(player.playerNumber != @turn) calls = _.filter(calls,(x)->x != "Chi") if(calls.length > 0) player.sendMessage("You may call #{calls} on this tile.") if(_.some(score.tenpaiWith(player.hand),(x)->_.isEqual(x,discarded))) player.sendMessage("You may Ron off of this discard, as long as you are not furiten.") nextTurnAfterFive = new Promise((resolve, reject) => setTimeout(-> resolve("Time has Passed") ,5000)) nextTurnAfterFive .then((message)=> if(@phase == "react") if(!@wall.wallFinished) @phase = "draw" for player in @players if(@turn == player.playerNumber) player.sendMessage("It is your turn. You may draw a tile.") else @exaustiveDraw() ) .catch(console.error) else playerToDiscard.sendMessage("You don't have that tile.") else playerToDiscard.sendMessage("It is not your turn.") _roundUpToClosestHundred = (inScore) -> if (inScore%100)!=0 return (inScore//100+1)*100 else inScore module.exports = MahjongGame
35438
gamePieces = require('./akagiTiles.coffee') playerObject = require('./akagiPlayer.coffee') score = require('./akagiScoring.coffee') test = require('./akagiTest.coffee') Promise = require('promise') _ = require('lodash') class MessageSender #Way to make sending messages to both players and the observation channel easier. constructor: (@playerOrObserver, whichType) -> if whichType == "player" @player = true @playerNumber = @playerOrObserver.playerNumber else @player = false @playerNumber = 0 sendMessage: (text) -> if(@player) @playerOrObserver.sendMessage(text) else @playerOrObserver.send(text) namedTiles:-> if(@player) return @playerOrObserver.namedTiles else return true class MahjongGame #A four player game of Mahjong constructor: (playerChannels, server, gameSettings) -> if("TestGame" in gameSettings) @wall = new gamePieces.Wall(test.testWall) else @wall = new gamePieces.Wall() @counter = 0 #Put down when east winds a round, increasing point values. @riichiSticks = [] #Used to keep track when a player calls riichi @pendingRiichiPoints = false #Keeps track of who just called riichi, so that once we are sure the next round has started, then they can have their stick added to the pile. @oneRoundTracker = [[],[],[],[]] #Keeps track of all the special things that can give points if done within one go around @kuikae = [] #Keeps track of what tiles cannot be discarded after calling chi or pon. @lastDiscard = false #Keeps track of the last tile discarded this game. @winningPlayer = [] @players = [ new playerObject(playerChannels[1],1), new playerObject(playerChannels[2],2), new playerObject(playerChannels[3],3), new playerObject(playerChannels[4],4) ] @gameObservationChannel = playerChannels[0] @messageRecievers = [] @messageRecievers.push(new MessageSender(@gameObservationChannel,"observer")) for player in @players @messageRecievers.push(new MessageSender(player,"player")) @startRoundOne() getPlayerByPlayerNumber:(playerNumber) -> #Returns the player who's player number is the chosen number for player in @players if(player.playerNumber == parseInt(playerNumber,10)) return player startRoundOne: -> #Randomize starting locations, then assign each player a seat. @players = _.shuffle(@players) @eastPlayer = @players[0] @southPlayer = @players[1] @westPlayer = @players[2] @northPlayer = @players[3] #Make player know own winds @eastPlayer.setWind("East") @southPlayer.setWind("South") @westPlayer.setWind("West") @northPlayer.setWind("North") #Makes sure we know who plays after who @eastPlayer.setNextPlayer(@southPlayer.playerNumber) @southPlayer.setNextPlayer(@westPlayer.playerNumber) @westPlayer.setNextPlayer(@northPlayer.playerNumber) @northPlayer.setNextPlayer(@eastPlayer.playerNumber) @prevailingWind = "East" @dealer = @eastPlayer @startRound() startRound: -> @turn = @dealer.playerNumber @phase = 'discard' @wall.doraFlip() @kuikae = [] @pendingRiichiPoints = false @lastDiscard = false for player in @messageRecievers player.sendMessage("New Round Start") player.sendMessage("Prevailing wind is #{@prevailingWind}.") player.sendMessage("Dora is #{@wall.printDora()}.") for player in @players player.hand.startDraw(@wall) player.roundStart(@wall) if(player.wind == "East") player.sendMessage("You are the first player. Please discard a tile.") @oneRoundTracker = [["First Round"],["First Round"],["First Round"],["First Round"]] newRound: -> if @winningPlayer.length == 0 || "East" in _.map(@winningPlayer,(x)->x.wind) @counter += 1 else @counter = 0 if("East" not in _.map(@winningPlayer,(x)->x.wind)) for player in @players player.rotateWind() for player in @messageRecievers player.sendMessage("The winds have rotated.") if @eastPlayer.wind == "East" if(@prevailingWind == "East") @prevailingWind = "South" else @endGame() return 0 @wall = new gamePieces.Wall() @winningPlayer = [] for player in @players player.resetHand() if player.wind == "East" @dealer = player @startRound() #Starts a new game of Mahjong. startNewGame: -> for folk in @messageRecievers folk.sendMessage("A new game of mahjong is starting. Seats and play order will be randomized, and all points reset to 30000.") folk.sendMessage("-----------------------------------------------------------------------------------------------------------") for player in @players player.roundPoints = 30000 player.resetHand() @wall = new gamePieces.Wall() @winningPlayer = [] @counter = 0 @startRoundOne() #Sends out all the appropriate messages when the game ends endGame: -> winOrder = _.sortBy(@players, (x) -> -1*x.roundPoints) @phase = "GameOver" placements = {"First":[],"Second":[],"Third":[],"Fourth":[]} ranks = ["First","Second","Third","Fourth"] for player in winOrder for rank in ranks if(placements[rank].length == 0 || placements[rank][0].roundPoints == player.roundPoints) placements[rank].push(player) break for winner in placements["First"] winner.sendMessage("You win!") if(@riichiSticks.length > 0) winner.roundPoints += 1000*@riichiSticks.length/placements["First"].length winner.sendMessage("As the winner, you recieve the remaining riichi sticks and thus gain #{1000*@riichiSticks.length/placements["First"].length} points.") @riichiSticks = [] for player in @messageRecievers player.sendMessage("The game has ended.") if(placements["First"].length == 1) player.sendMessage("First place was player #{placements["First"][0].playerNumber} with #{placements["First"][0].roundPoints} points.") else player.sendMessage("The following players tied for first with #{placements["First"][0].roundPoints}: #{_.map(placements["First"],(x)->x.playerNumber)}") if(placements["Second"].length == 1) player.sendMessage("Second place was player #{placements["Second"][0].playerNumber} with #{placements["Second"][0].roundPoints} points.") else if(placements["Second"].length > 1) player.sendMessage("The following players tied for second with #{placements["Second"][0].roundPoints}: #{_.map(placements["Second"],(x)->x.playerNumber)}") if(placements["Third"].length == 1) player.sendMessage("Third place was player #{placements["Third"][0].playerNumber} with #{placements["Third"][0].roundPoints} points.") else if(placements["Third"].length > 1) player.sendMessage("The following players tied for third with #{placements["Third"][0].roundPoints}: #{_.map(placements["Third"],(x)->x.playerNumber)}") if(placements["Fourth"].length == 1) player.sendMessage("Fourth place was player #{placements["Fourth"][0].playerNumber} with #{placements["Fourth"][0].roundPoints} points.") #Uma calculations umaPoints = [15000,5000,-5000,-15000] for rank in ranks accumulatedPoints = 0 for x in placements[rank] accumulatedPoints += umaPoints.shift() for x in placements[rank] x.roundPoints += accumulatedPoints/placements[rank].length for player in @messageRecievers player.sendMessage("After factoring in uma, here are the final point values.") if(placements["First"].length == 1) player.sendMessage("First place was player #{placements["First"][0].playerNumber} with #{placements["First"][0].roundPoints} points.") else player.sendMessage("The following players tied for first with #{placements["First"][0].roundPoints}: #{_.map(placements["First"],(x)->x.playerNumber)}") if(placements["Second"].length == 1) player.sendMessage("Second place was player #{placements["Second"][0].playerNumber} with #{placements["Second"][0].roundPoints} points.") else if(placements["Second"].length > 1) player.sendMessage("The following players tied for second with #{placements["Second"][0].roundPoints}: #{_.map(placements["Second"],(x)->x.playerNumber)}") if(placements["Third"].length == 1) player.sendMessage("Third place was player #{placements["Third"][0].playerNumber} with #{placements["Third"][0].roundPoints} points.") else if(placements["Third"].length > 1) player.sendMessage("The following players tied for third with #{placements["Third"][0].roundPoints}: #{_.map(placements["Third"],(x)->x.playerNumber)}") if(placements["Fourth"].length == 1) player.sendMessage("Fourth place was player #{placements["Fourth"][0].playerNumber} with #{placements["Fourth"][0].roundPoints} points.") player.sendMessage("Congratulations to the winning player(s)!") if(player.player) player.sendMessage("Type 'end game' to remove all game channels, or 'play again' to start a new game with the same players.") #Called when the round ends with no winner. exaustiveDraw: -> @winningPlayer = _.filter(@players,(x)->score.tenpaiWith(x.hand).length != 0) for player in @messageRecievers player.sendMessage("The round has ended in an exaustive draw.") if(@winningPlayer.length == 0) player.sendMessage("No players were in tenpai.") else player.sendMessage("The following players were in tenpai: #{x.playerNumber for x in @winningPlayer}") player.sendMessage("The tenpai hands looked like this: #{"#{x.playerNumber} - #{x.hand.printHand(player.tileNames)}" for x in @winningPlayer}") if(player.playerNumber in _.map(@winningPlayer,(x)->x.playerNumber)) player.playerOrObserver.roundPoints += 3000/@winningPlayer.length player.sendMessage("Because you were in tenpai, you gain #{3000/@winningPlayer.length} points.") else if(player.playerNumber != 0) player.playerOrObserver.roundPoints -= 3000/(4-@winningPlayer.length) player.sendMessage("Because you were not in tenpai, you pay #{3000/(4-@winningPlayer.length)} points.") player.sendMessage("The round is over. To start the next round, type next.") @phase = "finished" #Put the stick into the pot, once the next turn has started. Also, adds discarded tile, to possible temporary furiten list. confirmNextTurn: -> if(@pendingRiichiPoints) @riichiSticks.push(@pendingRiichiPoints) for player in @players if player.playerNumber == @pendingRiichiPoints player.roundPoints -= 1000 @pendingRiichiPoints = false for player in @players player.tilesSinceLastDraw.push(@lastDiscard) #Used to empty the round tracker if someone makes a call interuptRound: -> @oneRoundTracker = [[],[],[],[]] #Removes all one round counters for one player once it gets back to them. endGoAround:(playerTurn) -> @oneRoundTracker[playerTurn.playerNumber-1] = [] drawTile:(playerToDraw) -> if(@turn == playerToDraw.playerNumber) if(@phase != "draw") playerToDraw.sendMessage("It is not the draw phase.") else playerToDraw.wallDraw(@wall) @phase = "discard" @confirmNextTurn() if(!playerToDraw.riichiCalled()) playerToDraw.tilesSinceLastDraw = [] if(playerToDraw.wantsHelp) tenpaiDiscards = score.tenpaiWithout(playerToDraw.hand) if(score.getPossibleHands(playerToDraw.hand).length > 0) playerToDraw.sendMessage("You have a completed hand. You may call Tsumo if you have any yaku.") else if(tenpaiDiscards.length > 0) playerToDraw.sendMessage("You can be in tenpai by discarding any of the following tiles:") playerToDraw.sendMessage((tile.getName(playerToDraw.namedTiles) for tile in tenpaiDiscards)) if(@wall.wallFinished) @oneRoundTracker[playerToDraw.playerNumber - 1].push("Haitei") for player in @messageRecievers if player.playerNumber != playerToDraw.playerNumber player.sendMessage("Player #{playerToDraw.playerNumber} has drawn a tile.") if(@wall.wallFinished) player.sendMessage("This is the last draw of the game. The game will end after the discard.") else playerToDraw.sendMessage("It is not your turn.") #checks whether someone is furiten or not furiten:(player) -> tenpai = score.tenpaiWith(player.hand) furitenBecause = [] for tile in tenpai for discard in player.discardPile.contains if(tile.getTextName() == discard.getTextName()) furitenBecause.push(tile) for discard in player.tilesSinceLastDraw if(tile.getTextName() == discard.getTextName()) furitenBecause.push(tile) if(furitenBecause.length == 0) return false else return furitenBecause #checks and sets liability for 4 winds/3 dragon hands liabilityChecker:(playerCalling,playerLiable) -> if(_.filter(playerCalling.hand.calledMelds,(x)->x.suit() == "dragon").length == 3 || _.filter(playerCalling.hand.calledMelds,(x)->x.suit() == "wind").length == 4) playerCalling.liablePlayer = playerLiable.playerNumber for player in @messageRecievers if(player.playerNumber != playerLiable.playerNumber) player.sendMessage("Player #{playerLiable.playerNumber} is now liable for the cost of the potential Dai Sangen or Dai Suushii.") else player.sendMessage("You are now liable for the cost of the potential Dai Sangen or Dai Suushii") #Calculates all the flags for non hand based points in the game. winFlagCalculator:(winningPlayer,winType) -> flags = [] if(winningPlayer.riichiCalled()) flags.push("Riichi") if(winningPlayer.daburu) flags.push("D<NAME>") if("Ippatsu" in @oneRoundTracker[winningPlayer.playerNumber - 1]) flags.push("Ippatsu") if("First Round" in @oneRoundTracker[winningPlayer.playerNumber-1]) if(winType == "Ron") flags.push("Renho") else if(winningPlayer.playerNumber == @dealer.playerNumber) flags.push("Tenho") else flags.push("Chiho") if("<NAME>" in @oneRoundTracker[winningPlayer.playerNumber-1]) flags.push("<NAME>") if(winType == "Ron") if(Array.isArray(@phase) && @phase[0] in ["extendKaning","extendRon"]) flags.push("Chan <NAME>an") if(@wall.wallFinished && @phase in ["react","roning"]) flags.push("Houtei") if("Haitei" in @oneRoundTracker[winningPlayer.playerNumber-1]) flags.push("Haitei") console.log(flags) return new score.gameFlags(winningPlayer.wind,@prevailingWind,flags) ron:(playerToRon) -> if(@turn == playerToRon.nextPlayer && (@phase in ["draw","react"] || (Array.isArray(@phase) && @phase[0] not in ["concealedKaning","extendKaning","concealedRon","extendRon"]))) playerToRon.sendMessage("Cannot Ron off of own discard.") else if(@turn == playerToRon.playerNumber && (@phase == "discard"||(Array.isArray(@phase) && @phase[0] in ["concealedKaning","extendKaning","concealedRon","extendRon"]))) playerToRon.sendMessage("During your turn, use Tsumo, instead of Ron.") else if(@furiten(playerToRon)) playerToRon.sendMessage("You may not Ron, because you are in furiten.") else if(Array.isArray(@phase) && @phase[0] in ["concealedKaning","concealedRon"] && !score.thirteenOrphans(playerToRon.hand,@phase[1])) playerToRon.sendMessage("You may only call Ron off of a concealed Kan, if you are winning via the thirteen orphans hand.") else if(Array.isArray(@phase) && @phase[0] in ["concealedRon","extendRon","roning"] && playerToRon.playerNumber in @phase[2]) playerToRon.sendMessage("You have already declared Ron.") else if(Array.isArray(@phase) && @phase[0] in ["concealedKaning","concealedRon","extendKaning","extendRon"]) discarder = _.find(@players,(x)=> @turn == x.playerNumber) discardedTile = @phase[1] else discarder = _.find(@players,(x)=> @turn == x.nextPlayer) discardedTile = discarder.discardPile.contains[-1..][0] testHand = _.cloneDeep(playerToRon.hand) testHand.contains.push(discardedTile) testHand.lastTileDrawn = discardedTile testHand.draw(null,0) testHand.lastTileFrom = discarder.playerNumber scoreMax = score.scoreMahjongHand(testHand,@winFlagCalculator(playerToRon,"Ron"),[@wall.dora,@wall.urDora]) if(scoreMax[0] == 0) playerToRon.sendMessage(scoreMax[1]) else playerToRon.hand = testHand for player in @messageRecievers if(player.playerNumber == playerToRon.playerNumber) player.sendMessage("You have declared Ron.") else player.sendMessage("Player #{playerToRon.playerNumber} has declared Ron.") if(Array.isArray(@phase)) if(@phase[0] in ["concealedKaning","concealedRon"]) state = "concealedRon" else if(@phase[0] in ["extendKaning","extendRon"]) state = "extendRon" else state = "roning" #Figure out who all has declared ron thus far. if(@phase[0] in ["concealedRon","extendRon","roning"]) ronGroup = @phase[2].concat(playerToRon.playerNumber) else ronGroup = [playerToRon.playerNumber] else state = "roning" ronGroup = [playerToRon.playerNumber] @phase = [state,discardedTile,ronGroup] ronAfterFive = new Promise((resolve,reject) => setTimeout(-> resolve("Time has Passed") ,5000)) ronAfterFive .then((message)=> if(_.isEqual(@phase,[state,discardedTile,ronGroup])) riichiBet = @riichiSticks.length winnerOrder = [] winnerOrder.push(_.find(@players,(x)->discarder.nextPlayer == x.playerNumber)) winnerOrder.push(_.find(@players,(x)->winnerOrder[0].nextPlayer==x.playerNumber)) winnerOrder.push(_.find(@players,(x)->winnerOrder[1].nextPlayer==x.playerNumber)) winnerOrder = _.filter(winnerOrder,(x)=>x.playerNumber in @phase[2]) for winner in winnerOrder if(winner.riichiCalled()) winner.roundPoints+=1000 winner.sendMessage("Riichi bet returned to you.") riichiBet -= 1 if(riichiBet>0) winnerOrder[0].roundPoints+=1000*riichiBet winner.sendMessage("Remaining riichi bets give you #{1000*riichiBet} points.") @riichiSticks = [] for winner in winnerOrder scoreMax = score.scoreMahjongHand(winner.hand,@winFlagCalculator(playerToRon,"Ron"),[@wall.dora,@wall.urDora]) if(playerToRon.wind == "East") pointsGained = _roundUpToClosestHundred(6*scoreMax[0])+@counter*300 pointsLost = _roundUpToClosestHundred(6*scoreMax[0]) else pointsGained = _roundUpToClosestHundred(4*scoreMax[0])+@counter*300 pointsLost = _roundUpToClosestHundred(4*scoreMax[0]) if(winner.liablePlayer && winner.liablePlayer != discarder.playerNumber) pointsLost = pointsLost/2 for player in @messageRecievers if(player.playerNumber == winner.playerNumber) player.playerOrObserver.roundPoints += pointsGained player.sendMessage("You have won from Ron.") player.sendMessage("You receive #{pointsGained} points.") else player.sendMessage("Player #{winner.playerNumber} has won via Ron.") if(player.playerNumber == winner.liablePlayer) player.playerOrObserver.roundPoints -= pointsLost player.sendMessage("Because you were liable for this hand, you pay #{pointsLost} points.") if(discarder.playerNumber == player.playerNumber) player.playerOrObserver.roundPoints -= pointsLost+300*@counter player.sendMessage("Because you discarded the winning tile, you pay #{pointsLost+300*@counter} points.") player.sendMessage("The winning hand contained the following yaku: #{scoreMax[1]}") player.sendMessage("The winning hand was: #{winner.hand.printHand(player.namedTiles)}") player.sendMessage("The dora indicators were: #{@wall.printDora(player.namedTiles)}") if(winner.riichiCalled()) player.sendMessage("The ur dora indicators were: #{@wall.printUrDora(player.namedTiles)}") for player in @players player.sendMessage("The round is over. To start the next round, type next.") @winningPlayer = winnerOrder @phase = "finished" ) .catch(console.error) tsumo:(playerToTsumo) -> if(@turn!=playerToTsumo.playerNumber) playerToTsumo.sendMessage("Not your turn.") else if(@phase!="discard") playerToTsumo.sendMessage("You don't have enough tiles.") else scoreMax = score.scoreMahjongHand(playerToTsumo.hand, @winFlagCalculator(playerToTsumo,"Tsumo"), [@wall.dora,@wall.urDora]) if(scoreMax[0] == 0) playerToTsumo.sendMessage(scoreMax[1]) else for player in @players #CalculatePoints if(playerToTsumo.wind == "East") if(playerToTsumo.liablePlayer) if player.playerNumber = playerToTsumo.liablePlayer pointsLost = _roundUpToClosestHundred(6*scoreMax[0])+@counter*100 else if player.playerNumber == playerToTsumo.playerNumber pointsGained = _roundUpToClosestHundred(6*scoreMax[0])+@counter*100+@riichiSticks.length*1000 else pointsLost = 0 else if player.playerNumber != @turn pointsLost = _roundUpToClosestHundred(2*scoreMax[0])+@counter*100 else pointsGained = 3*_roundUpToClosestHundred(2*scoreMax[0])+@counter*300+@riichiSticks.length*1000 else if(playerToTsumo.liablePlayer) if player.playerNumber = playerToTsumo.liablePlayer pointsLost = _roundUpToClosestHundred(4*scoreMax[0])+@counter*100 else if player.playerNumber == playerToTsumo.playerNumber pointsGained = _roundUpToClosestHundred(4*scoreMax[0])+@counter*100+@riichiSticks.length*1000 else pointsLost = 0 else if player.wind == "East" pointsLost = _roundUpToClosestHundred(2*scoreMax[0])+@counter*100 else if player.playerNumber != @turn pointsLost = _roundUpToClosestHundred(scoreMax[0])+@counter*100 else pointsGained = _roundUpToClosestHundred(2*scoreMax[0])+2*_roundUpToClosestHundred(scoreMax[0])+@counter*300+@riichiSticks.length*1000 @riichiSticks = [] #Say points if(player.playerNumber != @turn) player.roundPoints -= pointsLost player.sendMessage("Player #{playerToTsumo.playerNumber} has won from self draw.") player.sendMessage("You pay out #{pointsLost} points.") else player.roundPoints += pointsGained player.sendMessage("You have won on self draw.") player.sendMessage("You receive #{pointsGained} points.") @gameObservationChannel.send("Player #{playerToTsumo.playerNumber} has won from self draw.") for player in @messageRecievers player.sendMessage("The winning hand contained the following yaku: #{scoreMax[1]}") player.sendMessage("The winning hand was: #{playerToTsumo.hand.printHand(player.namedTiles)}") player.sendMessage("The dora indicators were: #{@wall.printDora(player.namedTiles)}") if(playerToTsumo.riichiCalled()) player.sendMessage("The ur dora indicators were: #{@wall.printUrDora(player.namedTiles)}") if(player.player) player.sendMessage("The round is over. To start the next round, type next.") @winningPlayer = [playerToTsumo] @phase = "finished" chiTile:(playerToChi, tile1, tile2) -> if(playerToChi.playerNumber != @turn) playerToChi.sendMessage("May only Chi when you are next in turn order.") else if(playerToChi.riichiCalled()) playerToChi.sendMessage("May not Chi after declaring Riichi.") else if(@wall.wallFinished) playerToChi.sendMessage("May not call Chi on the last turn.") else if(@phase in ["draw","react"]) if(_.findIndex(playerToChi.hand.uncalled(),(x) -> _.isEqual(tile1, x)) != -1 && _.findIndex(playerToChi.hand.uncalled(),(x) -> _.isEqual(tile2, x)) != -1) discarder = _.find(@players,(x)=> @turn == x.nextPlayer) toChi = discarder.discardPile.contains[-1..][0] _chiable = (t1,t2,t3) -> if(t1.suit!=t2.suit || t2.suit!=t3.suit) return false sortedValues = [t1.value,t2.value,t3.value].sort() if(sortedValues[0]+1 == sortedValues[1] && sortedValues[1]+1 == sortedValues[2]) return true else return false if(_chiable(toChi,tile1,tile2)) @phase = ["chiing",playerToChi.playerNumber] for player in @messageRecievers if(player.playerNumber != playerToChi.playerNumber) player.sendMessage("Player #{playerToChi.playerNumber} has declared Chi.") else player.sendMessage("You have declared Chi.") chiAfterFive = new Promise((resolve,reject) => setTimeout(-> resolve("Time has Passed") ,5000)) chiAfterFive .then((message)=> if(_.isEqual(@phase,["chiing",playerToChi.playerNumber])) @phase = "discard" @confirmNextTurn() @interuptRound() @kuikae.push(toChi) if(tile1.value > toChi.value && tile2.value > toChi.value) @kuikae.push(new gamePieces.Tile(toChi.suit,toChi.value+3)) else if(tile1.value < toChi.value && tile2.value < toChi.value) @kuikae.push(new gamePieces.Tile(toChi.suit,toChi.value-3)) for player in @players if(@turn == player.nextPlayer) playerToChi.hand.draw(player.discardPile) playerToChi.hand.calledMelds.push(new gamePieces.Meld([toChi,tile1,tile2],player.playerNumber)) player.sendMessage("Player #{playerToChi.playerNumber}'s Chi has completed.") else if(player.playerNumber == playerToChi.playerNumber) player.sendMessage("Your Chi has completed. Please discard a tile.") else player.sendMessage("Player #{playerToChi.playerNumber}'s Chi has completed.") @gameObservationChannel.send("Player #{playerToChi.playerNumber}'s Chi has completed.") ) .catch(console.error) else playerToChi.sendMessage("Tiles specified do not create a legal meld.") else playerToChi.sendMessage("Hand doesn't contain tiles specified.") else if(Array.isArray(@phase)) playerToChi.sendMessage("Chi has lower priority than Pon, Kan, and Ron.") else playerToChi.sendMessage("Wrong time to Chi") #Finds out if the tiles in a concealed pung onlyPung:(hand,tile) -> withoutDraw = _.cloneDeep(hand) withoutDraw.discard(tile.getTextName()) waits = score.tenpaiWith(withoutDraw) for win in waits testHand = _.cloneDeep(withoutDraw) testHand.lastTileDrawn = win testHand.contains.push(win) melds = score.getPossibleHands(testHand) for meld in melds if(meld.type == "Chow" && meld.containsTile(tile)) return false return true selfKanTiles:(playerToKan,tileToKan) -> uncalledKanTiles = _.filter(playerToKan.hand.uncalled(),(x) -> _.isEqual(x,tileToKan)).length if(@turn != playerToKan.playerNumber) playerToKan.sendMessage("It is not your turn.") else if(@phase != "discard") playerToKan.sendMessage("One can only self Kan during one's own turn after one has drawn.") else if(@wall.dora.length == 5) playerToKan.sendMessage("There can only be 4 Kans per game.") else if(@wall.wallFinished) playerToKan.sendMessage("May not call Kan on the last turn.") else if(uncalledKanTiles < 1) playerToKan.sendMessage("No tiles to Kan with.") else if(uncalledKanTiles in [2,3]) playerToKan.sendMessage("Wrong number of tiles to Kan with.") else if(uncalledKanTiles == 4 && playerToKan.riichiCalled() && !@onlyPung(playerToKan.hand,tileToKan)) playerToKan.sendMessage("You can't call Kan with this tile, because it changes the structure of the hand.") else if(uncalledKanTiles == 4) @phase = ["concealedKaning",tileToKan] for player in @messageRecievers if(player.playerNumber != playerToKan.playerNumber) player.sendMessage("Player #{playerToKan.playerNumber} has declared a concealed Kan on #{tileToKan.getName(player.namedTiles)}.") else player.sendMessage("You have declared a concealed Kan on #{tileToKan.getName(player.namedTiles)}.") for player in @players if(player.wantsHelp && player.nextPlayer != @turn) if(score.thirteenOrphans(player.hand,tileToKan)) player.sendMessage("You may Ron off of this concealed kong, as long as you are not furiten.") concealAfterFive = new Promise((resolve,reject) => setTimeout(-> resolve("Time has Passed") ,5000)) concealAfterFive .then((message)=> if(_.isEqual(@phase,["concealedKaning",tileToKan])) @phase = "discard" @interuptRound() @oneRoundTracker[playerToKan.playerNumber-1].push("<NAME>") playerToKan.hand.calledMelds.push(new gamePieces.Meld([tileToKan,tileToKan,tileToKan,tileToKan])) drawnTile = playerToKan.hand.draw(@wall)[0] @wall.doraFlip() for player in @messageRecievers if(player.playerNumber!=playerToKan.playerNumber) player.sendMessage("Player #{playerToKan.playerNumber} has completed their Kan.") else player.sendMessage("You have completed your Kan.") player.sendMessage("Your deadwall draw is #{drawnTile.getName(player.namedTiles)}.") player.sendMessage("The Dora Tiles are now: #{@wall.printDora(player.namedTiles)}") @turn = playerToKan.playerNumber ) .catch(console.error) else pungToExtend = _.filter(playerToKan.hand.calledMelds,(x) -> x.type == "Pung" && x.suit() == tileToKan.suit && x.value() == tileToKan.value) if(pungToExtend.length == 1) pungToExtend = pungToExtend[0] @phase = ["extendKaning",tileToKan] for player in @messageRecievers if(player.playerNumber != playerToKan.playerNumber) player.sendMessage("Player #{playerToKan.playerNumber} has declared an extended Kan on #{tileToKan.getName(player.namedTiles)}.") else player.sendMessage("You have declared an extended Kan on #{tileToKan.getName(player.namedTiles)}.") for player in @players if(player.wantsHelp && player.nextPlayer != @turn) if(_.some(score.tenpaiWith(player.hand),(x)->_.isEqual(x,discarded))) player.sendMessage("You may rob the kong and Ron, as long as you are not furiten.") extendAfterFive = new Promise((resolve,reject) => setTimeout(-> resolve("Time has Passed") ,5000)) extendAfterFive .then((message)=> if(_.isEqual(@phase,["extendKaning",tileToKan])) @phase = "discard" @interuptRound() @oneRoundTracker[playerToKan.playerNumber-1].push("<NAME>") for meld in playerToKan.hand.calledMelds if(meld.type == "Pung" && meld.suit() == tileToKan.suit && meld.value() == tileToKan.value) meld.makeKong() drawnTile = playerToKan.hand.draw(@wall)[0] @wall.doraFlip() for player in @messageRecievers if(player.playerNumber!=playerToKan.playerNumber) player.sendMessage("Player #{playerToKan.playerNumber} has completed their Kan.") else player.sendMessage("You have completed your Kan.") player.sendMessage("Your deadwall draw is #{drawnTile.getName(player.namedTiles)}.") player.sendMessage("The Dora Tiles are now: #{@wall.printDora(player.namedTiles)}") @turn = playerToKan.playerNumber ) .catch(console.error) else playerToKan.sendMessage("Don't have Pung to extend into Kong.") openKanTiles:(playerToKan) -> if(playerToKan.riichiCalled()) playerToKan.sendMessage("You can't call tiles, except to win, after declaring Riichi.") else if(Array.isArray(@phase) && @phase[0] == "roning") playerToKan.sendMessage("Kan has lower priority than Ron.") else if(@wall.dora.length == 5) playerToKan.sendMessage("There can only be 4 Kans per game.") else if(@wall.wallFinished) playerToKan.sendMessage("May not call Kan on the last turn.") else if(Array.isArray(@phase) && @phase[0] == "chiing" && playerToPon.playerNumber == @phase[1]) playerToKan.sendMessage("One cannot Kan if one has already declared Chi.") else if((Array.isArray(@phase) && @phase[0] == "chiing") || @phase in ["react","draw"]) discarder = _.find(@players,(x)=> @turn == x.nextPlayer) toKan = discarder.discardPile.contains[-1..][0] if(_.filter(playerToKan.hand.uncalled(),(x) -> _.isEqual(x,toKan)).length == 3) @phase = ["callKaning",playerToKan.playerNumber] for player in @messageRecievers if(player.playerNumber!= playerToKan.playerNumber) player.sendMessage("Player #{playerToKan.playerNumber} has declared Kan.") else player.sendMessage("You have declared Kan.") kanAfterFive = new Promise((resolve,reject) => setTimeout(-> resolve("Time has Passed") ,5000)) kanAfterFive .then((message)=> if(_.isEqual(@phase,["callKaning",playerToKan.playerNumber])) @phase = "discard" @confirmNextTurn() @interuptRound() @oneRoundTracker[playerToKan.playerNumber-1].push("<NAME>") playerToKan.hand.draw(discarder.discardPile) playerToKan.hand.calledMelds.push(new gamePieces.Meld([toKan,toKan,toKan,toKan],discarder.playerNumber)) if(toKan.isHonor()) @liabilityChecker(playerToKan,discarder) drawnTile = playerToKan.hand.draw(@wall)[0] @wall.doraFlip() for player in @messageRecievers if(player.playerNumber!=playerToKan.playerNumber) player.sendMessage("Player #{playerToKan.playerNumber} has completed their Kan.") else player.sendMessage("You have completed your Kan.") player.sendMessage("Your deadwall draw is #{drawnTile.getName(player.namedTiles)}.") player.sendMessage("The Dora Tiles are now: #{@wall.printDora(player.namedTiles)}") @turn = playerToKan.playerNumber ) .catch(console.error) else playerToKan.sendMessage("You don't have correct tiles to Kan.") else playerToKan.sendMessage("Wrong time to Kan.") ponTile:(playerToPon) -> if(playerToPon.riichiCalled()) playerToPon.sendMessage("You may not Pon after declaring Riichi.") else if(@wall.wallFinished) playerToPon.sendMessage("May not call Pon on the last turn.") else if(Array.isArray(@phase) && @phase[0] == "Chi" && @phase[1] == playerToPon.playerNumber) playerToPon.sendMessage("Can't call Pon if you already called Chi.") else if((@phase in ["react","draw"] || (Array.isArray(@phase) && @phase[0] == "chiing")) && @turn != playerToPon.nextPlayer) discarder = _.find(@players,(x)=> @turn == x.nextPlayer) toPon = discarder.discardPile.contains[-1..][0] if(_.findIndex(playerToPon.hand.uncalled(),(x)->_.isEqual(toPon,x))!=_.findLastIndex(playerToPon.hand.uncalled(),(x)->_.isEqual(toPon,x))) @phase = ["poning",playerToPon.playerNumber] for player in @messageRecievers if(player.playerNumber != playerToPon.playerNumber) player.sendMessage("Player #{playerToPon.playerNumber} has declared Pon.") else player.sendMessage("You have declared Pon.") fiveSecondsToPon = new Promise((resolve,reject) => setTimeout(-> resolve("Time has Passed") ,5000)) fiveSecondsToPon .then((message)=> if(_.isEqual(@phase,["poning",playerToPon.playerNumber])) @phase = "discard" @confirmNextTurn() @interuptRound() @kuikae.push(toPon) for player in @players if(@turn == player.nextPlayer) playerToPon.hand.draw(player.discardPile) playerToPon.hand.calledMelds.push(new gamePieces.Meld([toPon,toPon,toPon],player.playerNumber)) player.sendMessage("Player #{playerToPon.playerNumber}'s Pon has completed.") if(player.playerNumber == playerToPon.playerNumber) player.sendMessage("Your Pon has completed. Please discard a tile.") else player.sendMessage("Player #{playerToPon.playerNumber}'s Pon has completed.") @gameObservationChannel.send("Player #{playerToPon.playerNumber}'s Pon has completed.") @turn = playerToPon.playerNumber if(toPon.isHonor()) @liabilityChecker(playerToPon,discarder) ) .catch(console.error) else playerToPon.sendMessage("Don't have correct tiles.") else if(Array.isArray(@phase) && @phase[0] == "roning") playerToPon.sendMessage("Pon has lower priorty than Ron.") else playerToPon.sendMessage("Wrong time to Pon.") discardTile:(playerToDiscard,tileToDiscard,riichi = false) -> if(@turn == playerToDiscard.playerNumber) if(@phase != "discard") playerToDiscard.sendMessage("It is not the discard phase.") else if(riichi && playerToDiscard.hand.isConcealed() == false) playerToDiscard.sendMessage("You may only riichi with a concealed hand.") else if(playerToDiscard.riichiCalled() && tileToDiscard != playerToDiscard.hand.lastTileDrawn.getTextName()) playerToDiscard.sendMessage("Once you have declared Riichi, you must always discard the drawn tile.") else if(riichi && @wall.leftInWall() < 4) playerToDiscard.sendMessage("You can't call riichi if there are less than four tiles remaining in the wall.") else if(riichi && !_.some(score.tenpaiWithout(playerToDiscard.hand),(x)->x.getTextName()==tileToDiscard)) playerToDiscard.sendMessage("You would not be in tenpai if you discarded that tile to call Riichi.") else if(_.some(@kuikae,(x)->x.getTextName()==tileToDiscard)) playerToDiscard.sendMessage("May not discard the same tile just called, or the opposite end of the chow just called.") else discarded = playerToDiscard.discardTile(tileToDiscard) if(discarded) if(riichi) if("First Round" in @oneRoundTracker[playerToDiscard.playerNumber-1]) playerToDiscard.daburu = true outtext = "declared daburu riichi with" else outtext = "declared riichi with" playerToDiscard.discardPile.declareRiichi() @pendingRiichiPoints = playerToDiscard.playerNumber else outtext = "discarded" @lastDiscard = discarded @endGoAround(playerToDiscard) if(riichi) @oneRoundTracker[playerToDiscard.playerNumber-1].push("Ippatsu") for player in @messageRecievers if(player.playerNumber != playerToDiscard.playerNumber) player.sendMessage("Player #{playerToDiscard.playerNumber} #{outtext} a #{discarded.getName(player.namedTiles)}.") else player.sendMessage("You #{outtext} a #{discarded.getName(player.namedTiles)}.") @turn = playerToDiscard.nextPlayer @phase = "react" @kuikae = [] for player in @players if(player.wantsHelp && player.nextPlayer != @turn) calls = player.hand.whichCalls(@lastDiscard) if(player.playerNumber != @turn) calls = _.filter(calls,(x)->x != "Chi") if(calls.length > 0) player.sendMessage("You may call #{calls} on this tile.") if(_.some(score.tenpaiWith(player.hand),(x)->_.isEqual(x,discarded))) player.sendMessage("You may Ron off of this discard, as long as you are not furiten.") nextTurnAfterFive = new Promise((resolve, reject) => setTimeout(-> resolve("Time has Passed") ,5000)) nextTurnAfterFive .then((message)=> if(@phase == "react") if(!@wall.wallFinished) @phase = "draw" for player in @players if(@turn == player.playerNumber) player.sendMessage("It is your turn. You may draw a tile.") else @exaustiveDraw() ) .catch(console.error) else playerToDiscard.sendMessage("You don't have that tile.") else playerToDiscard.sendMessage("It is not your turn.") _roundUpToClosestHundred = (inScore) -> if (inScore%100)!=0 return (inScore//100+1)*100 else inScore module.exports = MahjongGame
true
gamePieces = require('./akagiTiles.coffee') playerObject = require('./akagiPlayer.coffee') score = require('./akagiScoring.coffee') test = require('./akagiTest.coffee') Promise = require('promise') _ = require('lodash') class MessageSender #Way to make sending messages to both players and the observation channel easier. constructor: (@playerOrObserver, whichType) -> if whichType == "player" @player = true @playerNumber = @playerOrObserver.playerNumber else @player = false @playerNumber = 0 sendMessage: (text) -> if(@player) @playerOrObserver.sendMessage(text) else @playerOrObserver.send(text) namedTiles:-> if(@player) return @playerOrObserver.namedTiles else return true class MahjongGame #A four player game of Mahjong constructor: (playerChannels, server, gameSettings) -> if("TestGame" in gameSettings) @wall = new gamePieces.Wall(test.testWall) else @wall = new gamePieces.Wall() @counter = 0 #Put down when east winds a round, increasing point values. @riichiSticks = [] #Used to keep track when a player calls riichi @pendingRiichiPoints = false #Keeps track of who just called riichi, so that once we are sure the next round has started, then they can have their stick added to the pile. @oneRoundTracker = [[],[],[],[]] #Keeps track of all the special things that can give points if done within one go around @kuikae = [] #Keeps track of what tiles cannot be discarded after calling chi or pon. @lastDiscard = false #Keeps track of the last tile discarded this game. @winningPlayer = [] @players = [ new playerObject(playerChannels[1],1), new playerObject(playerChannels[2],2), new playerObject(playerChannels[3],3), new playerObject(playerChannels[4],4) ] @gameObservationChannel = playerChannels[0] @messageRecievers = [] @messageRecievers.push(new MessageSender(@gameObservationChannel,"observer")) for player in @players @messageRecievers.push(new MessageSender(player,"player")) @startRoundOne() getPlayerByPlayerNumber:(playerNumber) -> #Returns the player who's player number is the chosen number for player in @players if(player.playerNumber == parseInt(playerNumber,10)) return player startRoundOne: -> #Randomize starting locations, then assign each player a seat. @players = _.shuffle(@players) @eastPlayer = @players[0] @southPlayer = @players[1] @westPlayer = @players[2] @northPlayer = @players[3] #Make player know own winds @eastPlayer.setWind("East") @southPlayer.setWind("South") @westPlayer.setWind("West") @northPlayer.setWind("North") #Makes sure we know who plays after who @eastPlayer.setNextPlayer(@southPlayer.playerNumber) @southPlayer.setNextPlayer(@westPlayer.playerNumber) @westPlayer.setNextPlayer(@northPlayer.playerNumber) @northPlayer.setNextPlayer(@eastPlayer.playerNumber) @prevailingWind = "East" @dealer = @eastPlayer @startRound() startRound: -> @turn = @dealer.playerNumber @phase = 'discard' @wall.doraFlip() @kuikae = [] @pendingRiichiPoints = false @lastDiscard = false for player in @messageRecievers player.sendMessage("New Round Start") player.sendMessage("Prevailing wind is #{@prevailingWind}.") player.sendMessage("Dora is #{@wall.printDora()}.") for player in @players player.hand.startDraw(@wall) player.roundStart(@wall) if(player.wind == "East") player.sendMessage("You are the first player. Please discard a tile.") @oneRoundTracker = [["First Round"],["First Round"],["First Round"],["First Round"]] newRound: -> if @winningPlayer.length == 0 || "East" in _.map(@winningPlayer,(x)->x.wind) @counter += 1 else @counter = 0 if("East" not in _.map(@winningPlayer,(x)->x.wind)) for player in @players player.rotateWind() for player in @messageRecievers player.sendMessage("The winds have rotated.") if @eastPlayer.wind == "East" if(@prevailingWind == "East") @prevailingWind = "South" else @endGame() return 0 @wall = new gamePieces.Wall() @winningPlayer = [] for player in @players player.resetHand() if player.wind == "East" @dealer = player @startRound() #Starts a new game of Mahjong. startNewGame: -> for folk in @messageRecievers folk.sendMessage("A new game of mahjong is starting. Seats and play order will be randomized, and all points reset to 30000.") folk.sendMessage("-----------------------------------------------------------------------------------------------------------") for player in @players player.roundPoints = 30000 player.resetHand() @wall = new gamePieces.Wall() @winningPlayer = [] @counter = 0 @startRoundOne() #Sends out all the appropriate messages when the game ends endGame: -> winOrder = _.sortBy(@players, (x) -> -1*x.roundPoints) @phase = "GameOver" placements = {"First":[],"Second":[],"Third":[],"Fourth":[]} ranks = ["First","Second","Third","Fourth"] for player in winOrder for rank in ranks if(placements[rank].length == 0 || placements[rank][0].roundPoints == player.roundPoints) placements[rank].push(player) break for winner in placements["First"] winner.sendMessage("You win!") if(@riichiSticks.length > 0) winner.roundPoints += 1000*@riichiSticks.length/placements["First"].length winner.sendMessage("As the winner, you recieve the remaining riichi sticks and thus gain #{1000*@riichiSticks.length/placements["First"].length} points.") @riichiSticks = [] for player in @messageRecievers player.sendMessage("The game has ended.") if(placements["First"].length == 1) player.sendMessage("First place was player #{placements["First"][0].playerNumber} with #{placements["First"][0].roundPoints} points.") else player.sendMessage("The following players tied for first with #{placements["First"][0].roundPoints}: #{_.map(placements["First"],(x)->x.playerNumber)}") if(placements["Second"].length == 1) player.sendMessage("Second place was player #{placements["Second"][0].playerNumber} with #{placements["Second"][0].roundPoints} points.") else if(placements["Second"].length > 1) player.sendMessage("The following players tied for second with #{placements["Second"][0].roundPoints}: #{_.map(placements["Second"],(x)->x.playerNumber)}") if(placements["Third"].length == 1) player.sendMessage("Third place was player #{placements["Third"][0].playerNumber} with #{placements["Third"][0].roundPoints} points.") else if(placements["Third"].length > 1) player.sendMessage("The following players tied for third with #{placements["Third"][0].roundPoints}: #{_.map(placements["Third"],(x)->x.playerNumber)}") if(placements["Fourth"].length == 1) player.sendMessage("Fourth place was player #{placements["Fourth"][0].playerNumber} with #{placements["Fourth"][0].roundPoints} points.") #Uma calculations umaPoints = [15000,5000,-5000,-15000] for rank in ranks accumulatedPoints = 0 for x in placements[rank] accumulatedPoints += umaPoints.shift() for x in placements[rank] x.roundPoints += accumulatedPoints/placements[rank].length for player in @messageRecievers player.sendMessage("After factoring in uma, here are the final point values.") if(placements["First"].length == 1) player.sendMessage("First place was player #{placements["First"][0].playerNumber} with #{placements["First"][0].roundPoints} points.") else player.sendMessage("The following players tied for first with #{placements["First"][0].roundPoints}: #{_.map(placements["First"],(x)->x.playerNumber)}") if(placements["Second"].length == 1) player.sendMessage("Second place was player #{placements["Second"][0].playerNumber} with #{placements["Second"][0].roundPoints} points.") else if(placements["Second"].length > 1) player.sendMessage("The following players tied for second with #{placements["Second"][0].roundPoints}: #{_.map(placements["Second"],(x)->x.playerNumber)}") if(placements["Third"].length == 1) player.sendMessage("Third place was player #{placements["Third"][0].playerNumber} with #{placements["Third"][0].roundPoints} points.") else if(placements["Third"].length > 1) player.sendMessage("The following players tied for third with #{placements["Third"][0].roundPoints}: #{_.map(placements["Third"],(x)->x.playerNumber)}") if(placements["Fourth"].length == 1) player.sendMessage("Fourth place was player #{placements["Fourth"][0].playerNumber} with #{placements["Fourth"][0].roundPoints} points.") player.sendMessage("Congratulations to the winning player(s)!") if(player.player) player.sendMessage("Type 'end game' to remove all game channels, or 'play again' to start a new game with the same players.") #Called when the round ends with no winner. exaustiveDraw: -> @winningPlayer = _.filter(@players,(x)->score.tenpaiWith(x.hand).length != 0) for player in @messageRecievers player.sendMessage("The round has ended in an exaustive draw.") if(@winningPlayer.length == 0) player.sendMessage("No players were in tenpai.") else player.sendMessage("The following players were in tenpai: #{x.playerNumber for x in @winningPlayer}") player.sendMessage("The tenpai hands looked like this: #{"#{x.playerNumber} - #{x.hand.printHand(player.tileNames)}" for x in @winningPlayer}") if(player.playerNumber in _.map(@winningPlayer,(x)->x.playerNumber)) player.playerOrObserver.roundPoints += 3000/@winningPlayer.length player.sendMessage("Because you were in tenpai, you gain #{3000/@winningPlayer.length} points.") else if(player.playerNumber != 0) player.playerOrObserver.roundPoints -= 3000/(4-@winningPlayer.length) player.sendMessage("Because you were not in tenpai, you pay #{3000/(4-@winningPlayer.length)} points.") player.sendMessage("The round is over. To start the next round, type next.") @phase = "finished" #Put the stick into the pot, once the next turn has started. Also, adds discarded tile, to possible temporary furiten list. confirmNextTurn: -> if(@pendingRiichiPoints) @riichiSticks.push(@pendingRiichiPoints) for player in @players if player.playerNumber == @pendingRiichiPoints player.roundPoints -= 1000 @pendingRiichiPoints = false for player in @players player.tilesSinceLastDraw.push(@lastDiscard) #Used to empty the round tracker if someone makes a call interuptRound: -> @oneRoundTracker = [[],[],[],[]] #Removes all one round counters for one player once it gets back to them. endGoAround:(playerTurn) -> @oneRoundTracker[playerTurn.playerNumber-1] = [] drawTile:(playerToDraw) -> if(@turn == playerToDraw.playerNumber) if(@phase != "draw") playerToDraw.sendMessage("It is not the draw phase.") else playerToDraw.wallDraw(@wall) @phase = "discard" @confirmNextTurn() if(!playerToDraw.riichiCalled()) playerToDraw.tilesSinceLastDraw = [] if(playerToDraw.wantsHelp) tenpaiDiscards = score.tenpaiWithout(playerToDraw.hand) if(score.getPossibleHands(playerToDraw.hand).length > 0) playerToDraw.sendMessage("You have a completed hand. You may call Tsumo if you have any yaku.") else if(tenpaiDiscards.length > 0) playerToDraw.sendMessage("You can be in tenpai by discarding any of the following tiles:") playerToDraw.sendMessage((tile.getName(playerToDraw.namedTiles) for tile in tenpaiDiscards)) if(@wall.wallFinished) @oneRoundTracker[playerToDraw.playerNumber - 1].push("Haitei") for player in @messageRecievers if player.playerNumber != playerToDraw.playerNumber player.sendMessage("Player #{playerToDraw.playerNumber} has drawn a tile.") if(@wall.wallFinished) player.sendMessage("This is the last draw of the game. The game will end after the discard.") else playerToDraw.sendMessage("It is not your turn.") #checks whether someone is furiten or not furiten:(player) -> tenpai = score.tenpaiWith(player.hand) furitenBecause = [] for tile in tenpai for discard in player.discardPile.contains if(tile.getTextName() == discard.getTextName()) furitenBecause.push(tile) for discard in player.tilesSinceLastDraw if(tile.getTextName() == discard.getTextName()) furitenBecause.push(tile) if(furitenBecause.length == 0) return false else return furitenBecause #checks and sets liability for 4 winds/3 dragon hands liabilityChecker:(playerCalling,playerLiable) -> if(_.filter(playerCalling.hand.calledMelds,(x)->x.suit() == "dragon").length == 3 || _.filter(playerCalling.hand.calledMelds,(x)->x.suit() == "wind").length == 4) playerCalling.liablePlayer = playerLiable.playerNumber for player in @messageRecievers if(player.playerNumber != playerLiable.playerNumber) player.sendMessage("Player #{playerLiable.playerNumber} is now liable for the cost of the potential Dai Sangen or Dai Suushii.") else player.sendMessage("You are now liable for the cost of the potential Dai Sangen or Dai Suushii") #Calculates all the flags for non hand based points in the game. winFlagCalculator:(winningPlayer,winType) -> flags = [] if(winningPlayer.riichiCalled()) flags.push("Riichi") if(winningPlayer.daburu) flags.push("DPI:NAME:<NAME>END_PI") if("Ippatsu" in @oneRoundTracker[winningPlayer.playerNumber - 1]) flags.push("Ippatsu") if("First Round" in @oneRoundTracker[winningPlayer.playerNumber-1]) if(winType == "Ron") flags.push("Renho") else if(winningPlayer.playerNumber == @dealer.playerNumber) flags.push("Tenho") else flags.push("Chiho") if("PI:NAME:<NAME>END_PI" in @oneRoundTracker[winningPlayer.playerNumber-1]) flags.push("PI:NAME:<NAME>END_PI") if(winType == "Ron") if(Array.isArray(@phase) && @phase[0] in ["extendKaning","extendRon"]) flags.push("Chan PI:NAME:<NAME>END_PIan") if(@wall.wallFinished && @phase in ["react","roning"]) flags.push("Houtei") if("Haitei" in @oneRoundTracker[winningPlayer.playerNumber-1]) flags.push("Haitei") console.log(flags) return new score.gameFlags(winningPlayer.wind,@prevailingWind,flags) ron:(playerToRon) -> if(@turn == playerToRon.nextPlayer && (@phase in ["draw","react"] || (Array.isArray(@phase) && @phase[0] not in ["concealedKaning","extendKaning","concealedRon","extendRon"]))) playerToRon.sendMessage("Cannot Ron off of own discard.") else if(@turn == playerToRon.playerNumber && (@phase == "discard"||(Array.isArray(@phase) && @phase[0] in ["concealedKaning","extendKaning","concealedRon","extendRon"]))) playerToRon.sendMessage("During your turn, use Tsumo, instead of Ron.") else if(@furiten(playerToRon)) playerToRon.sendMessage("You may not Ron, because you are in furiten.") else if(Array.isArray(@phase) && @phase[0] in ["concealedKaning","concealedRon"] && !score.thirteenOrphans(playerToRon.hand,@phase[1])) playerToRon.sendMessage("You may only call Ron off of a concealed Kan, if you are winning via the thirteen orphans hand.") else if(Array.isArray(@phase) && @phase[0] in ["concealedRon","extendRon","roning"] && playerToRon.playerNumber in @phase[2]) playerToRon.sendMessage("You have already declared Ron.") else if(Array.isArray(@phase) && @phase[0] in ["concealedKaning","concealedRon","extendKaning","extendRon"]) discarder = _.find(@players,(x)=> @turn == x.playerNumber) discardedTile = @phase[1] else discarder = _.find(@players,(x)=> @turn == x.nextPlayer) discardedTile = discarder.discardPile.contains[-1..][0] testHand = _.cloneDeep(playerToRon.hand) testHand.contains.push(discardedTile) testHand.lastTileDrawn = discardedTile testHand.draw(null,0) testHand.lastTileFrom = discarder.playerNumber scoreMax = score.scoreMahjongHand(testHand,@winFlagCalculator(playerToRon,"Ron"),[@wall.dora,@wall.urDora]) if(scoreMax[0] == 0) playerToRon.sendMessage(scoreMax[1]) else playerToRon.hand = testHand for player in @messageRecievers if(player.playerNumber == playerToRon.playerNumber) player.sendMessage("You have declared Ron.") else player.sendMessage("Player #{playerToRon.playerNumber} has declared Ron.") if(Array.isArray(@phase)) if(@phase[0] in ["concealedKaning","concealedRon"]) state = "concealedRon" else if(@phase[0] in ["extendKaning","extendRon"]) state = "extendRon" else state = "roning" #Figure out who all has declared ron thus far. if(@phase[0] in ["concealedRon","extendRon","roning"]) ronGroup = @phase[2].concat(playerToRon.playerNumber) else ronGroup = [playerToRon.playerNumber] else state = "roning" ronGroup = [playerToRon.playerNumber] @phase = [state,discardedTile,ronGroup] ronAfterFive = new Promise((resolve,reject) => setTimeout(-> resolve("Time has Passed") ,5000)) ronAfterFive .then((message)=> if(_.isEqual(@phase,[state,discardedTile,ronGroup])) riichiBet = @riichiSticks.length winnerOrder = [] winnerOrder.push(_.find(@players,(x)->discarder.nextPlayer == x.playerNumber)) winnerOrder.push(_.find(@players,(x)->winnerOrder[0].nextPlayer==x.playerNumber)) winnerOrder.push(_.find(@players,(x)->winnerOrder[1].nextPlayer==x.playerNumber)) winnerOrder = _.filter(winnerOrder,(x)=>x.playerNumber in @phase[2]) for winner in winnerOrder if(winner.riichiCalled()) winner.roundPoints+=1000 winner.sendMessage("Riichi bet returned to you.") riichiBet -= 1 if(riichiBet>0) winnerOrder[0].roundPoints+=1000*riichiBet winner.sendMessage("Remaining riichi bets give you #{1000*riichiBet} points.") @riichiSticks = [] for winner in winnerOrder scoreMax = score.scoreMahjongHand(winner.hand,@winFlagCalculator(playerToRon,"Ron"),[@wall.dora,@wall.urDora]) if(playerToRon.wind == "East") pointsGained = _roundUpToClosestHundred(6*scoreMax[0])+@counter*300 pointsLost = _roundUpToClosestHundred(6*scoreMax[0]) else pointsGained = _roundUpToClosestHundred(4*scoreMax[0])+@counter*300 pointsLost = _roundUpToClosestHundred(4*scoreMax[0]) if(winner.liablePlayer && winner.liablePlayer != discarder.playerNumber) pointsLost = pointsLost/2 for player in @messageRecievers if(player.playerNumber == winner.playerNumber) player.playerOrObserver.roundPoints += pointsGained player.sendMessage("You have won from Ron.") player.sendMessage("You receive #{pointsGained} points.") else player.sendMessage("Player #{winner.playerNumber} has won via Ron.") if(player.playerNumber == winner.liablePlayer) player.playerOrObserver.roundPoints -= pointsLost player.sendMessage("Because you were liable for this hand, you pay #{pointsLost} points.") if(discarder.playerNumber == player.playerNumber) player.playerOrObserver.roundPoints -= pointsLost+300*@counter player.sendMessage("Because you discarded the winning tile, you pay #{pointsLost+300*@counter} points.") player.sendMessage("The winning hand contained the following yaku: #{scoreMax[1]}") player.sendMessage("The winning hand was: #{winner.hand.printHand(player.namedTiles)}") player.sendMessage("The dora indicators were: #{@wall.printDora(player.namedTiles)}") if(winner.riichiCalled()) player.sendMessage("The ur dora indicators were: #{@wall.printUrDora(player.namedTiles)}") for player in @players player.sendMessage("The round is over. To start the next round, type next.") @winningPlayer = winnerOrder @phase = "finished" ) .catch(console.error) tsumo:(playerToTsumo) -> if(@turn!=playerToTsumo.playerNumber) playerToTsumo.sendMessage("Not your turn.") else if(@phase!="discard") playerToTsumo.sendMessage("You don't have enough tiles.") else scoreMax = score.scoreMahjongHand(playerToTsumo.hand, @winFlagCalculator(playerToTsumo,"Tsumo"), [@wall.dora,@wall.urDora]) if(scoreMax[0] == 0) playerToTsumo.sendMessage(scoreMax[1]) else for player in @players #CalculatePoints if(playerToTsumo.wind == "East") if(playerToTsumo.liablePlayer) if player.playerNumber = playerToTsumo.liablePlayer pointsLost = _roundUpToClosestHundred(6*scoreMax[0])+@counter*100 else if player.playerNumber == playerToTsumo.playerNumber pointsGained = _roundUpToClosestHundred(6*scoreMax[0])+@counter*100+@riichiSticks.length*1000 else pointsLost = 0 else if player.playerNumber != @turn pointsLost = _roundUpToClosestHundred(2*scoreMax[0])+@counter*100 else pointsGained = 3*_roundUpToClosestHundred(2*scoreMax[0])+@counter*300+@riichiSticks.length*1000 else if(playerToTsumo.liablePlayer) if player.playerNumber = playerToTsumo.liablePlayer pointsLost = _roundUpToClosestHundred(4*scoreMax[0])+@counter*100 else if player.playerNumber == playerToTsumo.playerNumber pointsGained = _roundUpToClosestHundred(4*scoreMax[0])+@counter*100+@riichiSticks.length*1000 else pointsLost = 0 else if player.wind == "East" pointsLost = _roundUpToClosestHundred(2*scoreMax[0])+@counter*100 else if player.playerNumber != @turn pointsLost = _roundUpToClosestHundred(scoreMax[0])+@counter*100 else pointsGained = _roundUpToClosestHundred(2*scoreMax[0])+2*_roundUpToClosestHundred(scoreMax[0])+@counter*300+@riichiSticks.length*1000 @riichiSticks = [] #Say points if(player.playerNumber != @turn) player.roundPoints -= pointsLost player.sendMessage("Player #{playerToTsumo.playerNumber} has won from self draw.") player.sendMessage("You pay out #{pointsLost} points.") else player.roundPoints += pointsGained player.sendMessage("You have won on self draw.") player.sendMessage("You receive #{pointsGained} points.") @gameObservationChannel.send("Player #{playerToTsumo.playerNumber} has won from self draw.") for player in @messageRecievers player.sendMessage("The winning hand contained the following yaku: #{scoreMax[1]}") player.sendMessage("The winning hand was: #{playerToTsumo.hand.printHand(player.namedTiles)}") player.sendMessage("The dora indicators were: #{@wall.printDora(player.namedTiles)}") if(playerToTsumo.riichiCalled()) player.sendMessage("The ur dora indicators were: #{@wall.printUrDora(player.namedTiles)}") if(player.player) player.sendMessage("The round is over. To start the next round, type next.") @winningPlayer = [playerToTsumo] @phase = "finished" chiTile:(playerToChi, tile1, tile2) -> if(playerToChi.playerNumber != @turn) playerToChi.sendMessage("May only Chi when you are next in turn order.") else if(playerToChi.riichiCalled()) playerToChi.sendMessage("May not Chi after declaring Riichi.") else if(@wall.wallFinished) playerToChi.sendMessage("May not call Chi on the last turn.") else if(@phase in ["draw","react"]) if(_.findIndex(playerToChi.hand.uncalled(),(x) -> _.isEqual(tile1, x)) != -1 && _.findIndex(playerToChi.hand.uncalled(),(x) -> _.isEqual(tile2, x)) != -1) discarder = _.find(@players,(x)=> @turn == x.nextPlayer) toChi = discarder.discardPile.contains[-1..][0] _chiable = (t1,t2,t3) -> if(t1.suit!=t2.suit || t2.suit!=t3.suit) return false sortedValues = [t1.value,t2.value,t3.value].sort() if(sortedValues[0]+1 == sortedValues[1] && sortedValues[1]+1 == sortedValues[2]) return true else return false if(_chiable(toChi,tile1,tile2)) @phase = ["chiing",playerToChi.playerNumber] for player in @messageRecievers if(player.playerNumber != playerToChi.playerNumber) player.sendMessage("Player #{playerToChi.playerNumber} has declared Chi.") else player.sendMessage("You have declared Chi.") chiAfterFive = new Promise((resolve,reject) => setTimeout(-> resolve("Time has Passed") ,5000)) chiAfterFive .then((message)=> if(_.isEqual(@phase,["chiing",playerToChi.playerNumber])) @phase = "discard" @confirmNextTurn() @interuptRound() @kuikae.push(toChi) if(tile1.value > toChi.value && tile2.value > toChi.value) @kuikae.push(new gamePieces.Tile(toChi.suit,toChi.value+3)) else if(tile1.value < toChi.value && tile2.value < toChi.value) @kuikae.push(new gamePieces.Tile(toChi.suit,toChi.value-3)) for player in @players if(@turn == player.nextPlayer) playerToChi.hand.draw(player.discardPile) playerToChi.hand.calledMelds.push(new gamePieces.Meld([toChi,tile1,tile2],player.playerNumber)) player.sendMessage("Player #{playerToChi.playerNumber}'s Chi has completed.") else if(player.playerNumber == playerToChi.playerNumber) player.sendMessage("Your Chi has completed. Please discard a tile.") else player.sendMessage("Player #{playerToChi.playerNumber}'s Chi has completed.") @gameObservationChannel.send("Player #{playerToChi.playerNumber}'s Chi has completed.") ) .catch(console.error) else playerToChi.sendMessage("Tiles specified do not create a legal meld.") else playerToChi.sendMessage("Hand doesn't contain tiles specified.") else if(Array.isArray(@phase)) playerToChi.sendMessage("Chi has lower priority than Pon, Kan, and Ron.") else playerToChi.sendMessage("Wrong time to Chi") #Finds out if the tiles in a concealed pung onlyPung:(hand,tile) -> withoutDraw = _.cloneDeep(hand) withoutDraw.discard(tile.getTextName()) waits = score.tenpaiWith(withoutDraw) for win in waits testHand = _.cloneDeep(withoutDraw) testHand.lastTileDrawn = win testHand.contains.push(win) melds = score.getPossibleHands(testHand) for meld in melds if(meld.type == "Chow" && meld.containsTile(tile)) return false return true selfKanTiles:(playerToKan,tileToKan) -> uncalledKanTiles = _.filter(playerToKan.hand.uncalled(),(x) -> _.isEqual(x,tileToKan)).length if(@turn != playerToKan.playerNumber) playerToKan.sendMessage("It is not your turn.") else if(@phase != "discard") playerToKan.sendMessage("One can only self Kan during one's own turn after one has drawn.") else if(@wall.dora.length == 5) playerToKan.sendMessage("There can only be 4 Kans per game.") else if(@wall.wallFinished) playerToKan.sendMessage("May not call Kan on the last turn.") else if(uncalledKanTiles < 1) playerToKan.sendMessage("No tiles to Kan with.") else if(uncalledKanTiles in [2,3]) playerToKan.sendMessage("Wrong number of tiles to Kan with.") else if(uncalledKanTiles == 4 && playerToKan.riichiCalled() && !@onlyPung(playerToKan.hand,tileToKan)) playerToKan.sendMessage("You can't call Kan with this tile, because it changes the structure of the hand.") else if(uncalledKanTiles == 4) @phase = ["concealedKaning",tileToKan] for player in @messageRecievers if(player.playerNumber != playerToKan.playerNumber) player.sendMessage("Player #{playerToKan.playerNumber} has declared a concealed Kan on #{tileToKan.getName(player.namedTiles)}.") else player.sendMessage("You have declared a concealed Kan on #{tileToKan.getName(player.namedTiles)}.") for player in @players if(player.wantsHelp && player.nextPlayer != @turn) if(score.thirteenOrphans(player.hand,tileToKan)) player.sendMessage("You may Ron off of this concealed kong, as long as you are not furiten.") concealAfterFive = new Promise((resolve,reject) => setTimeout(-> resolve("Time has Passed") ,5000)) concealAfterFive .then((message)=> if(_.isEqual(@phase,["concealedKaning",tileToKan])) @phase = "discard" @interuptRound() @oneRoundTracker[playerToKan.playerNumber-1].push("PI:NAME:<NAME>END_PI") playerToKan.hand.calledMelds.push(new gamePieces.Meld([tileToKan,tileToKan,tileToKan,tileToKan])) drawnTile = playerToKan.hand.draw(@wall)[0] @wall.doraFlip() for player in @messageRecievers if(player.playerNumber!=playerToKan.playerNumber) player.sendMessage("Player #{playerToKan.playerNumber} has completed their Kan.") else player.sendMessage("You have completed your Kan.") player.sendMessage("Your deadwall draw is #{drawnTile.getName(player.namedTiles)}.") player.sendMessage("The Dora Tiles are now: #{@wall.printDora(player.namedTiles)}") @turn = playerToKan.playerNumber ) .catch(console.error) else pungToExtend = _.filter(playerToKan.hand.calledMelds,(x) -> x.type == "Pung" && x.suit() == tileToKan.suit && x.value() == tileToKan.value) if(pungToExtend.length == 1) pungToExtend = pungToExtend[0] @phase = ["extendKaning",tileToKan] for player in @messageRecievers if(player.playerNumber != playerToKan.playerNumber) player.sendMessage("Player #{playerToKan.playerNumber} has declared an extended Kan on #{tileToKan.getName(player.namedTiles)}.") else player.sendMessage("You have declared an extended Kan on #{tileToKan.getName(player.namedTiles)}.") for player in @players if(player.wantsHelp && player.nextPlayer != @turn) if(_.some(score.tenpaiWith(player.hand),(x)->_.isEqual(x,discarded))) player.sendMessage("You may rob the kong and Ron, as long as you are not furiten.") extendAfterFive = new Promise((resolve,reject) => setTimeout(-> resolve("Time has Passed") ,5000)) extendAfterFive .then((message)=> if(_.isEqual(@phase,["extendKaning",tileToKan])) @phase = "discard" @interuptRound() @oneRoundTracker[playerToKan.playerNumber-1].push("PI:NAME:<NAME>END_PI") for meld in playerToKan.hand.calledMelds if(meld.type == "Pung" && meld.suit() == tileToKan.suit && meld.value() == tileToKan.value) meld.makeKong() drawnTile = playerToKan.hand.draw(@wall)[0] @wall.doraFlip() for player in @messageRecievers if(player.playerNumber!=playerToKan.playerNumber) player.sendMessage("Player #{playerToKan.playerNumber} has completed their Kan.") else player.sendMessage("You have completed your Kan.") player.sendMessage("Your deadwall draw is #{drawnTile.getName(player.namedTiles)}.") player.sendMessage("The Dora Tiles are now: #{@wall.printDora(player.namedTiles)}") @turn = playerToKan.playerNumber ) .catch(console.error) else playerToKan.sendMessage("Don't have Pung to extend into Kong.") openKanTiles:(playerToKan) -> if(playerToKan.riichiCalled()) playerToKan.sendMessage("You can't call tiles, except to win, after declaring Riichi.") else if(Array.isArray(@phase) && @phase[0] == "roning") playerToKan.sendMessage("Kan has lower priority than Ron.") else if(@wall.dora.length == 5) playerToKan.sendMessage("There can only be 4 Kans per game.") else if(@wall.wallFinished) playerToKan.sendMessage("May not call Kan on the last turn.") else if(Array.isArray(@phase) && @phase[0] == "chiing" && playerToPon.playerNumber == @phase[1]) playerToKan.sendMessage("One cannot Kan if one has already declared Chi.") else if((Array.isArray(@phase) && @phase[0] == "chiing") || @phase in ["react","draw"]) discarder = _.find(@players,(x)=> @turn == x.nextPlayer) toKan = discarder.discardPile.contains[-1..][0] if(_.filter(playerToKan.hand.uncalled(),(x) -> _.isEqual(x,toKan)).length == 3) @phase = ["callKaning",playerToKan.playerNumber] for player in @messageRecievers if(player.playerNumber!= playerToKan.playerNumber) player.sendMessage("Player #{playerToKan.playerNumber} has declared Kan.") else player.sendMessage("You have declared Kan.") kanAfterFive = new Promise((resolve,reject) => setTimeout(-> resolve("Time has Passed") ,5000)) kanAfterFive .then((message)=> if(_.isEqual(@phase,["callKaning",playerToKan.playerNumber])) @phase = "discard" @confirmNextTurn() @interuptRound() @oneRoundTracker[playerToKan.playerNumber-1].push("PI:NAME:<NAME>END_PI") playerToKan.hand.draw(discarder.discardPile) playerToKan.hand.calledMelds.push(new gamePieces.Meld([toKan,toKan,toKan,toKan],discarder.playerNumber)) if(toKan.isHonor()) @liabilityChecker(playerToKan,discarder) drawnTile = playerToKan.hand.draw(@wall)[0] @wall.doraFlip() for player in @messageRecievers if(player.playerNumber!=playerToKan.playerNumber) player.sendMessage("Player #{playerToKan.playerNumber} has completed their Kan.") else player.sendMessage("You have completed your Kan.") player.sendMessage("Your deadwall draw is #{drawnTile.getName(player.namedTiles)}.") player.sendMessage("The Dora Tiles are now: #{@wall.printDora(player.namedTiles)}") @turn = playerToKan.playerNumber ) .catch(console.error) else playerToKan.sendMessage("You don't have correct tiles to Kan.") else playerToKan.sendMessage("Wrong time to Kan.") ponTile:(playerToPon) -> if(playerToPon.riichiCalled()) playerToPon.sendMessage("You may not Pon after declaring Riichi.") else if(@wall.wallFinished) playerToPon.sendMessage("May not call Pon on the last turn.") else if(Array.isArray(@phase) && @phase[0] == "Chi" && @phase[1] == playerToPon.playerNumber) playerToPon.sendMessage("Can't call Pon if you already called Chi.") else if((@phase in ["react","draw"] || (Array.isArray(@phase) && @phase[0] == "chiing")) && @turn != playerToPon.nextPlayer) discarder = _.find(@players,(x)=> @turn == x.nextPlayer) toPon = discarder.discardPile.contains[-1..][0] if(_.findIndex(playerToPon.hand.uncalled(),(x)->_.isEqual(toPon,x))!=_.findLastIndex(playerToPon.hand.uncalled(),(x)->_.isEqual(toPon,x))) @phase = ["poning",playerToPon.playerNumber] for player in @messageRecievers if(player.playerNumber != playerToPon.playerNumber) player.sendMessage("Player #{playerToPon.playerNumber} has declared Pon.") else player.sendMessage("You have declared Pon.") fiveSecondsToPon = new Promise((resolve,reject) => setTimeout(-> resolve("Time has Passed") ,5000)) fiveSecondsToPon .then((message)=> if(_.isEqual(@phase,["poning",playerToPon.playerNumber])) @phase = "discard" @confirmNextTurn() @interuptRound() @kuikae.push(toPon) for player in @players if(@turn == player.nextPlayer) playerToPon.hand.draw(player.discardPile) playerToPon.hand.calledMelds.push(new gamePieces.Meld([toPon,toPon,toPon],player.playerNumber)) player.sendMessage("Player #{playerToPon.playerNumber}'s Pon has completed.") if(player.playerNumber == playerToPon.playerNumber) player.sendMessage("Your Pon has completed. Please discard a tile.") else player.sendMessage("Player #{playerToPon.playerNumber}'s Pon has completed.") @gameObservationChannel.send("Player #{playerToPon.playerNumber}'s Pon has completed.") @turn = playerToPon.playerNumber if(toPon.isHonor()) @liabilityChecker(playerToPon,discarder) ) .catch(console.error) else playerToPon.sendMessage("Don't have correct tiles.") else if(Array.isArray(@phase) && @phase[0] == "roning") playerToPon.sendMessage("Pon has lower priorty than Ron.") else playerToPon.sendMessage("Wrong time to Pon.") discardTile:(playerToDiscard,tileToDiscard,riichi = false) -> if(@turn == playerToDiscard.playerNumber) if(@phase != "discard") playerToDiscard.sendMessage("It is not the discard phase.") else if(riichi && playerToDiscard.hand.isConcealed() == false) playerToDiscard.sendMessage("You may only riichi with a concealed hand.") else if(playerToDiscard.riichiCalled() && tileToDiscard != playerToDiscard.hand.lastTileDrawn.getTextName()) playerToDiscard.sendMessage("Once you have declared Riichi, you must always discard the drawn tile.") else if(riichi && @wall.leftInWall() < 4) playerToDiscard.sendMessage("You can't call riichi if there are less than four tiles remaining in the wall.") else if(riichi && !_.some(score.tenpaiWithout(playerToDiscard.hand),(x)->x.getTextName()==tileToDiscard)) playerToDiscard.sendMessage("You would not be in tenpai if you discarded that tile to call Riichi.") else if(_.some(@kuikae,(x)->x.getTextName()==tileToDiscard)) playerToDiscard.sendMessage("May not discard the same tile just called, or the opposite end of the chow just called.") else discarded = playerToDiscard.discardTile(tileToDiscard) if(discarded) if(riichi) if("First Round" in @oneRoundTracker[playerToDiscard.playerNumber-1]) playerToDiscard.daburu = true outtext = "declared daburu riichi with" else outtext = "declared riichi with" playerToDiscard.discardPile.declareRiichi() @pendingRiichiPoints = playerToDiscard.playerNumber else outtext = "discarded" @lastDiscard = discarded @endGoAround(playerToDiscard) if(riichi) @oneRoundTracker[playerToDiscard.playerNumber-1].push("Ippatsu") for player in @messageRecievers if(player.playerNumber != playerToDiscard.playerNumber) player.sendMessage("Player #{playerToDiscard.playerNumber} #{outtext} a #{discarded.getName(player.namedTiles)}.") else player.sendMessage("You #{outtext} a #{discarded.getName(player.namedTiles)}.") @turn = playerToDiscard.nextPlayer @phase = "react" @kuikae = [] for player in @players if(player.wantsHelp && player.nextPlayer != @turn) calls = player.hand.whichCalls(@lastDiscard) if(player.playerNumber != @turn) calls = _.filter(calls,(x)->x != "Chi") if(calls.length > 0) player.sendMessage("You may call #{calls} on this tile.") if(_.some(score.tenpaiWith(player.hand),(x)->_.isEqual(x,discarded))) player.sendMessage("You may Ron off of this discard, as long as you are not furiten.") nextTurnAfterFive = new Promise((resolve, reject) => setTimeout(-> resolve("Time has Passed") ,5000)) nextTurnAfterFive .then((message)=> if(@phase == "react") if(!@wall.wallFinished) @phase = "draw" for player in @players if(@turn == player.playerNumber) player.sendMessage("It is your turn. You may draw a tile.") else @exaustiveDraw() ) .catch(console.error) else playerToDiscard.sendMessage("You don't have that tile.") else playerToDiscard.sendMessage("It is not your turn.") _roundUpToClosestHundred = (inScore) -> if (inScore%100)!=0 return (inScore//100+1)*100 else inScore module.exports = MahjongGame
[ { "context": "# Copyright Joyent, Inc. and other Node contributors.\n#\n# Permission", "end": 18, "score": 0.9984017014503479, "start": 12, "tag": "NAME", "value": "Joyent" } ]
test/simple/test-http-pipe-fs.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") http = require("http") fs = require("fs") path = require("path") file = path.join(common.tmpDir, "http-pipe-fs-test.txt") requests = 0 server = http.createServer((req, res) -> ++requests stream = fs.createWriteStream(file) req.pipe stream stream.on "close", -> res.writeHead 200 res.end() return return ).listen(common.PORT, -> http.globalAgent.maxSockets = 1 i = 0 while i < 2 ((i) -> req = http.request( port: common.PORT method: "POST" headers: "Content-Length": 5 , (res) -> res.on "end", -> common.debug "res" + i + " end" server.close() if i is 2 return res.resume() return ) req.on "socket", (s) -> common.debug "req" + i + " start" return req.end "12345" return ) i + 1 ++i return ) process.on "exit", -> assert.equal requests, 2 return
128610
# 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") http = require("http") fs = require("fs") path = require("path") file = path.join(common.tmpDir, "http-pipe-fs-test.txt") requests = 0 server = http.createServer((req, res) -> ++requests stream = fs.createWriteStream(file) req.pipe stream stream.on "close", -> res.writeHead 200 res.end() return return ).listen(common.PORT, -> http.globalAgent.maxSockets = 1 i = 0 while i < 2 ((i) -> req = http.request( port: common.PORT method: "POST" headers: "Content-Length": 5 , (res) -> res.on "end", -> common.debug "res" + i + " end" server.close() if i is 2 return res.resume() return ) req.on "socket", (s) -> common.debug "req" + i + " start" return req.end "12345" return ) i + 1 ++i return ) process.on "exit", -> assert.equal requests, 2 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") http = require("http") fs = require("fs") path = require("path") file = path.join(common.tmpDir, "http-pipe-fs-test.txt") requests = 0 server = http.createServer((req, res) -> ++requests stream = fs.createWriteStream(file) req.pipe stream stream.on "close", -> res.writeHead 200 res.end() return return ).listen(common.PORT, -> http.globalAgent.maxSockets = 1 i = 0 while i < 2 ((i) -> req = http.request( port: common.PORT method: "POST" headers: "Content-Length": 5 , (res) -> res.on "end", -> common.debug "res" + i + " end" server.close() if i is 2 return res.resume() return ) req.on "socket", (s) -> common.debug "req" + i + " start" return req.end "12345" return ) i + 1 ++i return ) process.on "exit", -> assert.equal requests, 2 return
[ { "context": "ties to edit entries in a table view.\n\n @author Sebastian Sachtleben\n###\nclass TableView extends BaseView\n\t\n\ttemplate:", "end": 188, "score": 0.9998863339424133, "start": 168, "tag": "NAME", "value": "Sebastian Sachtleben" } ]
app/assets/javascripts/shared/views/tableView.coffee
ssachtleben/herowar
1
BaseView = require 'views/baseView' templates = require 'templates' ### The TableView provides basic functionalities to edit entries in a table view. @author Sebastian Sachtleben ### class TableView extends BaseView template: templates.get 'table.tmpl' allowCreate: true entryView: 'views/tableEntryView' events: 'click .create-link' : 'createEntry' initialize: (options) -> super options @model.fetch() bindEvents: -> @listenTo @model, 'add remove change reset', @render if @model getTemplateData: -> json = super() tableHeaders = [] tableFields = [] if _.isObject @fields for own key, value of @fields tableHeaders.push key tableFields.push value tableHeaders.push 'Actions' json.tableHeaders = tableHeaders json.tableFields = tableFields.join ',' json.entity = @tableEntity json.entryView = @entryView json.allowCreate = @allowCreate json.colspan = tableFields.length + 1 json createEntry: (event) -> event?.preventDefault() return TableView
26085
BaseView = require 'views/baseView' templates = require 'templates' ### The TableView provides basic functionalities to edit entries in a table view. @author <NAME> ### class TableView extends BaseView template: templates.get 'table.tmpl' allowCreate: true entryView: 'views/tableEntryView' events: 'click .create-link' : 'createEntry' initialize: (options) -> super options @model.fetch() bindEvents: -> @listenTo @model, 'add remove change reset', @render if @model getTemplateData: -> json = super() tableHeaders = [] tableFields = [] if _.isObject @fields for own key, value of @fields tableHeaders.push key tableFields.push value tableHeaders.push 'Actions' json.tableHeaders = tableHeaders json.tableFields = tableFields.join ',' json.entity = @tableEntity json.entryView = @entryView json.allowCreate = @allowCreate json.colspan = tableFields.length + 1 json createEntry: (event) -> event?.preventDefault() return TableView
true
BaseView = require 'views/baseView' templates = require 'templates' ### The TableView provides basic functionalities to edit entries in a table view. @author PI:NAME:<NAME>END_PI ### class TableView extends BaseView template: templates.get 'table.tmpl' allowCreate: true entryView: 'views/tableEntryView' events: 'click .create-link' : 'createEntry' initialize: (options) -> super options @model.fetch() bindEvents: -> @listenTo @model, 'add remove change reset', @render if @model getTemplateData: -> json = super() tableHeaders = [] tableFields = [] if _.isObject @fields for own key, value of @fields tableHeaders.push key tableFields.push value tableHeaders.push 'Actions' json.tableHeaders = tableHeaders json.tableFields = tableFields.join ',' json.entity = @tableEntity json.entryView = @entryView json.allowCreate = @allowCreate json.colspan = tableFields.length + 1 json createEntry: (event) -> event?.preventDefault() return TableView
[ { "context": "returnValue field of the response object.\r\n@author Nathan Klick\r\n@copyright QRef 2012\r\n###\r\nclass ChecklistVersio", "end": 704, "score": 0.9998630285263062, "start": 692, "tag": "NAME", "value": "Nathan Klick" } ]
Workspace/QRef/NodeServer/src/router/routes/rpc/aircraft/ChecklistVersionRoute.coffee
qrefdev/qref
0
RpcRoute = require('../../../RpcRoute') QRefDatabase = require('../../../../db/QRefDatabase') RpcResponse = require('../../../../serialization/RpcResponse') UserAuth = require('../../../../security/UserAuth') https = require('https') async = require('async') ### Service route that returns the next available version of a given checklist. @example Service Methods (see {ChecklistVersionRpcRequest}) Request Format: application/json Response Format: application/json POST /services/rpc/aircraft/checklist/version @BODY - (Required) ChecklistVersionRpcRequest Returns the next available version number in the returnValue field of the response object. @author Nathan Klick @copyright QRef 2012 ### class ChecklistVersionRoute extends RpcRoute constructor: () -> super [{ method: 'POST', path: '/checklist/version' }, { method: 'GET', path: '/checklist/version' }] post: (req, res) => if not @.isValidRequest(req) resp = new RpcResponse(null) resp.failure('Bad Request', 400) res.json(resp, 200) return manufacturerId = req.body.manufacturer modelId = req.body.model db = QRefDatabase.instance() db.AircraftManufacturer.findById(manufacturerId, (err, mfr) -> if err? resp = new RpcResponse(null) resp.failure('Internal Error', 500) res.json(resp, 200) return if not mfr? resp = new RpcResponse(null) resp.failure('Manufacturer Not Found', 404) res.json(resp, 200) return db.AircraftModel.findOne() .where('_id') .equals(modelId) .where('manufacturer') .equals(mfr._id) .exec((err, mdl) -> if err? resp = new RpcResponse(null) resp.failure('Internal Error', 500) res.json(resp, 200) return if not mdl? resp = new RpcResponse(null) resp.failure('Model Not Found', 404) res.json(resp, 200) return db.AircraftChecklist.findOne() .where('model') .equals(mdl._id) .where('manufacturer') .equals(mfr._id) .where('user') .equals(null) .sort('-version') .exec((err, record) -> if err? resp = new RpcResponse(null) resp.failure('Internal Error', 500) res.json(resp, 200) return if not record? resp = new RpcResponse(1) res.json(resp, 200) return resp = new RpcResponse(record.version + 1) res.json(resp, 200) ) ) ) isValidRequest: (req) -> if req.body? and req.body?.mode? and req.body.mode == 'rpc' and req.body?.manufacturer? and req.body?.model? true else false module.exports = new ChecklistVersionRoute()
60908
RpcRoute = require('../../../RpcRoute') QRefDatabase = require('../../../../db/QRefDatabase') RpcResponse = require('../../../../serialization/RpcResponse') UserAuth = require('../../../../security/UserAuth') https = require('https') async = require('async') ### Service route that returns the next available version of a given checklist. @example Service Methods (see {ChecklistVersionRpcRequest}) Request Format: application/json Response Format: application/json POST /services/rpc/aircraft/checklist/version @BODY - (Required) ChecklistVersionRpcRequest Returns the next available version number in the returnValue field of the response object. @author <NAME> @copyright QRef 2012 ### class ChecklistVersionRoute extends RpcRoute constructor: () -> super [{ method: 'POST', path: '/checklist/version' }, { method: 'GET', path: '/checklist/version' }] post: (req, res) => if not @.isValidRequest(req) resp = new RpcResponse(null) resp.failure('Bad Request', 400) res.json(resp, 200) return manufacturerId = req.body.manufacturer modelId = req.body.model db = QRefDatabase.instance() db.AircraftManufacturer.findById(manufacturerId, (err, mfr) -> if err? resp = new RpcResponse(null) resp.failure('Internal Error', 500) res.json(resp, 200) return if not mfr? resp = new RpcResponse(null) resp.failure('Manufacturer Not Found', 404) res.json(resp, 200) return db.AircraftModel.findOne() .where('_id') .equals(modelId) .where('manufacturer') .equals(mfr._id) .exec((err, mdl) -> if err? resp = new RpcResponse(null) resp.failure('Internal Error', 500) res.json(resp, 200) return if not mdl? resp = new RpcResponse(null) resp.failure('Model Not Found', 404) res.json(resp, 200) return db.AircraftChecklist.findOne() .where('model') .equals(mdl._id) .where('manufacturer') .equals(mfr._id) .where('user') .equals(null) .sort('-version') .exec((err, record) -> if err? resp = new RpcResponse(null) resp.failure('Internal Error', 500) res.json(resp, 200) return if not record? resp = new RpcResponse(1) res.json(resp, 200) return resp = new RpcResponse(record.version + 1) res.json(resp, 200) ) ) ) isValidRequest: (req) -> if req.body? and req.body?.mode? and req.body.mode == 'rpc' and req.body?.manufacturer? and req.body?.model? true else false module.exports = new ChecklistVersionRoute()
true
RpcRoute = require('../../../RpcRoute') QRefDatabase = require('../../../../db/QRefDatabase') RpcResponse = require('../../../../serialization/RpcResponse') UserAuth = require('../../../../security/UserAuth') https = require('https') async = require('async') ### Service route that returns the next available version of a given checklist. @example Service Methods (see {ChecklistVersionRpcRequest}) Request Format: application/json Response Format: application/json POST /services/rpc/aircraft/checklist/version @BODY - (Required) ChecklistVersionRpcRequest Returns the next available version number in the returnValue field of the response object. @author PI:NAME:<NAME>END_PI @copyright QRef 2012 ### class ChecklistVersionRoute extends RpcRoute constructor: () -> super [{ method: 'POST', path: '/checklist/version' }, { method: 'GET', path: '/checklist/version' }] post: (req, res) => if not @.isValidRequest(req) resp = new RpcResponse(null) resp.failure('Bad Request', 400) res.json(resp, 200) return manufacturerId = req.body.manufacturer modelId = req.body.model db = QRefDatabase.instance() db.AircraftManufacturer.findById(manufacturerId, (err, mfr) -> if err? resp = new RpcResponse(null) resp.failure('Internal Error', 500) res.json(resp, 200) return if not mfr? resp = new RpcResponse(null) resp.failure('Manufacturer Not Found', 404) res.json(resp, 200) return db.AircraftModel.findOne() .where('_id') .equals(modelId) .where('manufacturer') .equals(mfr._id) .exec((err, mdl) -> if err? resp = new RpcResponse(null) resp.failure('Internal Error', 500) res.json(resp, 200) return if not mdl? resp = new RpcResponse(null) resp.failure('Model Not Found', 404) res.json(resp, 200) return db.AircraftChecklist.findOne() .where('model') .equals(mdl._id) .where('manufacturer') .equals(mfr._id) .where('user') .equals(null) .sort('-version') .exec((err, record) -> if err? resp = new RpcResponse(null) resp.failure('Internal Error', 500) res.json(resp, 200) return if not record? resp = new RpcResponse(1) res.json(resp, 200) return resp = new RpcResponse(record.version + 1) res.json(resp, 200) ) ) ) isValidRequest: (req) -> if req.body? and req.body?.mode? and req.body.mode == 'rpc' and req.body?.manufacturer? and req.body?.model? true else false module.exports = new ChecklistVersionRoute()
[ { "context": "ing object properties on separate lines.\n# @author Vitor Balocco\n###\n\n'use strict'\n\n#-----------------------------", "end": 105, "score": 0.99920654296875, "start": 92, "tag": "NAME", "value": "Vitor Balocco" } ]
src/rules/object-property-newline.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Rule to enforce placing object properties on separate lines. # @author Vitor Balocco ### 'use strict' #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'enforce placing object properties on separate lines' category: 'Stylistic Issues' recommended: no url: 'https://eslint.org/docs/rules/object-property-newline' schema: [ type: 'object' properties: allowAllPropertiesOnSameLine: type: 'boolean' allowMultiplePropertiesPerLine: # Deprecated type: 'boolean' additionalProperties: no ] # fixable: 'whitespace' create: (context) -> allowSameLine = context.options[0] and (Boolean(context.options[0].allowAllPropertiesOnSameLine) or Boolean context.options[0].allowMultiplePropertiesPerLine) # Deprecated errorMessage = if allowSameLine "Object properties must go on a new line if they aren't all on the same line." else 'Object properties must go on a new line.' sourceCode = context.getSourceCode() ObjectExpression: (node) -> return unless node.properties.length if allowSameLine if node.properties.length > 1 firstTokenOfFirstProperty = sourceCode.getFirstToken( node.properties[0] ) lastTokenOfLastProperty = sourceCode.getLastToken( node.properties[node.properties.length - 1] ) # All keys and values are on the same line return if ( firstTokenOfFirstProperty.loc.end.line is lastTokenOfLastProperty.loc.start.line ) for i in [1...node.properties.length] lastTokenOfPreviousProperty = sourceCode.getLastToken( node.properties[i - 1] ) firstTokenOfCurrentProperty = sourceCode.getFirstToken( node.properties[i] ) if ( lastTokenOfPreviousProperty.loc.end.line is firstTokenOfCurrentProperty.loc.start.line ) context.report { node loc: firstTokenOfCurrentProperty.loc.start message: errorMessage # fix: (fixer) -> # comma = sourceCode.getTokenBefore firstTokenOfCurrentProperty # rangeAfterComma = [ # comma.range[1] # firstTokenOfCurrentProperty.range[0] # ] # # Don't perform a fix if there are any comments between the comma and the next property. # return null if sourceCode.text # .slice(rangeAfterComma[0], rangeAfterComma[1]) # .trim() # fixer.replaceTextRange rangeAfterComma, '\n' }
100052
###* # @fileoverview Rule to enforce placing object properties on separate lines. # @author <NAME> ### 'use strict' #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'enforce placing object properties on separate lines' category: 'Stylistic Issues' recommended: no url: 'https://eslint.org/docs/rules/object-property-newline' schema: [ type: 'object' properties: allowAllPropertiesOnSameLine: type: 'boolean' allowMultiplePropertiesPerLine: # Deprecated type: 'boolean' additionalProperties: no ] # fixable: 'whitespace' create: (context) -> allowSameLine = context.options[0] and (Boolean(context.options[0].allowAllPropertiesOnSameLine) or Boolean context.options[0].allowMultiplePropertiesPerLine) # Deprecated errorMessage = if allowSameLine "Object properties must go on a new line if they aren't all on the same line." else 'Object properties must go on a new line.' sourceCode = context.getSourceCode() ObjectExpression: (node) -> return unless node.properties.length if allowSameLine if node.properties.length > 1 firstTokenOfFirstProperty = sourceCode.getFirstToken( node.properties[0] ) lastTokenOfLastProperty = sourceCode.getLastToken( node.properties[node.properties.length - 1] ) # All keys and values are on the same line return if ( firstTokenOfFirstProperty.loc.end.line is lastTokenOfLastProperty.loc.start.line ) for i in [1...node.properties.length] lastTokenOfPreviousProperty = sourceCode.getLastToken( node.properties[i - 1] ) firstTokenOfCurrentProperty = sourceCode.getFirstToken( node.properties[i] ) if ( lastTokenOfPreviousProperty.loc.end.line is firstTokenOfCurrentProperty.loc.start.line ) context.report { node loc: firstTokenOfCurrentProperty.loc.start message: errorMessage # fix: (fixer) -> # comma = sourceCode.getTokenBefore firstTokenOfCurrentProperty # rangeAfterComma = [ # comma.range[1] # firstTokenOfCurrentProperty.range[0] # ] # # Don't perform a fix if there are any comments between the comma and the next property. # return null if sourceCode.text # .slice(rangeAfterComma[0], rangeAfterComma[1]) # .trim() # fixer.replaceTextRange rangeAfterComma, '\n' }
true
###* # @fileoverview Rule to enforce placing object properties on separate lines. # @author PI:NAME:<NAME>END_PI ### 'use strict' #------------------------------------------------------------------------------ # Rule Definition #------------------------------------------------------------------------------ module.exports = meta: docs: description: 'enforce placing object properties on separate lines' category: 'Stylistic Issues' recommended: no url: 'https://eslint.org/docs/rules/object-property-newline' schema: [ type: 'object' properties: allowAllPropertiesOnSameLine: type: 'boolean' allowMultiplePropertiesPerLine: # Deprecated type: 'boolean' additionalProperties: no ] # fixable: 'whitespace' create: (context) -> allowSameLine = context.options[0] and (Boolean(context.options[0].allowAllPropertiesOnSameLine) or Boolean context.options[0].allowMultiplePropertiesPerLine) # Deprecated errorMessage = if allowSameLine "Object properties must go on a new line if they aren't all on the same line." else 'Object properties must go on a new line.' sourceCode = context.getSourceCode() ObjectExpression: (node) -> return unless node.properties.length if allowSameLine if node.properties.length > 1 firstTokenOfFirstProperty = sourceCode.getFirstToken( node.properties[0] ) lastTokenOfLastProperty = sourceCode.getLastToken( node.properties[node.properties.length - 1] ) # All keys and values are on the same line return if ( firstTokenOfFirstProperty.loc.end.line is lastTokenOfLastProperty.loc.start.line ) for i in [1...node.properties.length] lastTokenOfPreviousProperty = sourceCode.getLastToken( node.properties[i - 1] ) firstTokenOfCurrentProperty = sourceCode.getFirstToken( node.properties[i] ) if ( lastTokenOfPreviousProperty.loc.end.line is firstTokenOfCurrentProperty.loc.start.line ) context.report { node loc: firstTokenOfCurrentProperty.loc.start message: errorMessage # fix: (fixer) -> # comma = sourceCode.getTokenBefore firstTokenOfCurrentProperty # rangeAfterComma = [ # comma.range[1] # firstTokenOfCurrentProperty.range[0] # ] # # Don't perform a fix if there are any comments between the comma and the next property. # return null if sourceCode.text # .slice(rangeAfterComma[0], rangeAfterComma[1]) # .trim() # fixer.replaceTextRange rangeAfterComma, '\n' }
[ { "context": "entID: '32d29cd28dc740123247',\n clientSecret: 'c1597b8d29b53ce352d88decae82320629ccdf59',\n callbackURL: 'http://localhost:3000/auth/gi", "end": 746, "score": 0.9994918704032898, "start": 706, "tag": "KEY", "value": "c1597b8d29b53ce352d88decae82320629ccdf59" } ]
src/config/passport.coffee
marinoscar/NodeExpressAuth
0
localStrategy = require('passport-local').Strategy GitHubStrategy = require('passport-github').Strategy UserStore = require '../services/userStore' module.exports = (passport) -> #configure forms authentication passport.use('local', new localStrategy((username, password, done) -> store = new UserStore() user = store.find(username) if user is null return done(null, false, {message: 'Invalid user'}) if user.password isnt password return done(null, false, {message: 'Invalid password'}) done(null, user) ) ) #configure GitHub authentication passport.use('github', new GitHubStrategy({ clientID: '32d29cd28dc740123247', clientSecret: 'c1597b8d29b53ce352d88decae82320629ccdf59', callbackURL: 'http://localhost:3000/auth/github/callback' }, (accessToken, refreshToken, profile, done) -> #here is where we store the bearing token to use it for any future requests console.log("access token: #{accessToken}") userStore = new UserStore() user = userStore.createInstance() user.profile = profile user.data = JSON.parse(profile._raw) return done(null, user) ) ) passport.serializeUser((user, done) -> console.log('Serializing ' + user.providerKey) done(null, user.providerKey) ) passport.deserializeUser((obj, done) -> console.log('Deserializing ' + obj) store = new UserStore() user = store.findByKey(obj) done(null, user) )
30307
localStrategy = require('passport-local').Strategy GitHubStrategy = require('passport-github').Strategy UserStore = require '../services/userStore' module.exports = (passport) -> #configure forms authentication passport.use('local', new localStrategy((username, password, done) -> store = new UserStore() user = store.find(username) if user is null return done(null, false, {message: 'Invalid user'}) if user.password isnt password return done(null, false, {message: 'Invalid password'}) done(null, user) ) ) #configure GitHub authentication passport.use('github', new GitHubStrategy({ clientID: '32d29cd28dc740123247', clientSecret: '<KEY>', callbackURL: 'http://localhost:3000/auth/github/callback' }, (accessToken, refreshToken, profile, done) -> #here is where we store the bearing token to use it for any future requests console.log("access token: #{accessToken}") userStore = new UserStore() user = userStore.createInstance() user.profile = profile user.data = JSON.parse(profile._raw) return done(null, user) ) ) passport.serializeUser((user, done) -> console.log('Serializing ' + user.providerKey) done(null, user.providerKey) ) passport.deserializeUser((obj, done) -> console.log('Deserializing ' + obj) store = new UserStore() user = store.findByKey(obj) done(null, user) )
true
localStrategy = require('passport-local').Strategy GitHubStrategy = require('passport-github').Strategy UserStore = require '../services/userStore' module.exports = (passport) -> #configure forms authentication passport.use('local', new localStrategy((username, password, done) -> store = new UserStore() user = store.find(username) if user is null return done(null, false, {message: 'Invalid user'}) if user.password isnt password return done(null, false, {message: 'Invalid password'}) done(null, user) ) ) #configure GitHub authentication passport.use('github', new GitHubStrategy({ clientID: '32d29cd28dc740123247', clientSecret: 'PI:KEY:<KEY>END_PI', callbackURL: 'http://localhost:3000/auth/github/callback' }, (accessToken, refreshToken, profile, done) -> #here is where we store the bearing token to use it for any future requests console.log("access token: #{accessToken}") userStore = new UserStore() user = userStore.createInstance() user.profile = profile user.data = JSON.parse(profile._raw) return done(null, user) ) ) passport.serializeUser((user, done) -> console.log('Serializing ' + user.providerKey) done(null, user.providerKey) ) passport.deserializeUser((obj, done) -> console.log('Deserializing ' + obj) store = new UserStore() user = store.findByKey(obj) done(null, user) )
[ { "context": "or':\n 'ID': @userId\n 'Password': @password\n 'Track':\n '$': action: 'Get', ve", "end": 542, "score": 0.8565049171447754, "start": 533, "tag": "PASSWORD", "value": "@password" } ]
src/dhl.coffee
tom9890/shipit
0
{Builder, Parser} = require 'xml2js' moment = require 'moment' {titleCase, upperCaseFirst, lowerCase} = require 'change-case' {ShipperClient} = require './shipper' class DhlClient extends ShipperClient constructor: ({@userId, @password}, @options) -> super @parser = new Parser() @builder = new Builder(renderOpts: pretty: false) generateRequest: (trk) -> @builder.buildObject 'ECommerce': '$': action: 'Request', version: '1.1' 'Requestor': 'ID': @userId 'Password': @password 'Track': '$': action: 'Get', version: '1.0' 'Shipment': 'TrackingNbr': trk validateResponse: (response, cb) -> handleResponse = (xmlErr, trackResult) -> return cb(xmlErr) if xmlErr? or !trackResult? shipment = trackResult['ECommerce']?['Track']?[0]?['Shipment']?[0] return cb(error: 'could not find shipment') unless shipment? trackStatus = shipment['Result']?[0] statusCode = trackStatus?['Code']?[0] statusDesc = trackStatus?['Desc']?[0] return cb(error: "unexpected track status code=#{statusCode} desc=#{statusDesc}") unless statusCode is "0" cb null, shipment @parser.reset() @parser.parseString response, handleResponse getEta: (shipment) -> getService: (shipment) -> description = shipment['Service']?[0]?['Desc']?[0] if description? then titleCase description getWeight: (shipment) -> weight = shipment['Weight']?[0] if weight? then "#{weight} LB" presentTimestamp: (dateString, timeString) -> return unless dateString? formatSpec = if timeString? then 'YYYY-MM-DD HH:mm' else 'YYYY-MM-DD' inputString = if timeString? then "#{dateString} #{timeString}" else dateString moment(inputString, formatSpec).toDate() presentAddress: (rawAddress) -> return unless rawAddress? city = rawAddress['City']?[0] stateCode = rawAddress['State']?[0] countryCode = rawAddress['Country']?[0] city = city.replace(' HUB', '') @presentLocation {city, stateCode, countryCode} STATUS_MAP = 'BA': ShipperClient.STATUS_TYPES.OUT_FOR_DELIVERY 'BD': ShipperClient.STATUS_TYPES.OUT_FOR_DELIVERY 'BN': ShipperClient.STATUS_TYPES.OUT_FOR_DELIVERY 'BT': ShipperClient.STATUS_TYPES.OUT_FOR_DELIVERY 'OD': ShipperClient.STATUS_TYPES.OUT_FOR_DELIVERY 'ED': ShipperClient.STATUS_TYPES.OUT_FOR_DELIVERY 'AD': ShipperClient.STATUS_TYPES.DELAYED 'CC': ShipperClient.STATUS_TYPES.EN_ROUTE 'DH': ShipperClient.STATUS_TYPES.EN_ROUTE 'GH': ShipperClient.STATUS_TYPES.EN_ROUTE 'HA': ShipperClient.STATUS_TYPES.EN_ROUTE 'IB': ShipperClient.STATUS_TYPES.EN_ROUTE 'LD': ShipperClient.STATUS_TYPES.DELIVERED 'ND': ShipperClient.STATUS_TYPES.DELAYED 'NL': ShipperClient.STATUS_TYPES.DELAYED 'OB': ShipperClient.STATUS_TYPES.EN_ROUTE 'OH': ShipperClient.STATUS_TYPES.SHIPPING 'PA': ShipperClient.STATUS_TYPES.DELIVERED 'PT': ShipperClient.STATUS_TYPES.EN_ROUTE 'RF': ShipperClient.STATUS_TYPES.DELAYED 'DF': ShipperClient.STATUS_TYPES.EN_ROUTE 'TB': ShipperClient.STATUS_TYPES.EN_ROUTE 'TG': ShipperClient.STATUS_TYPES.DELAYED 'AA': ShipperClient.STATUS_TYPES.EN_ROUTE 'AD': ShipperClient.STATUS_TYPES.EN_ROUTE 'AF': ShipperClient.STATUS_TYPES.EN_ROUTE 'AP': ShipperClient.STATUS_TYPES.SHIPPING 'EO': ShipperClient.STATUS_TYPES.EN_ROUTE 'EP': ShipperClient.STATUS_TYPES.SHIPPING 'FD': ShipperClient.STATUS_TYPES.EN_ROUTE 'HL': ShipperClient.STATUS_TYPES.DELIVERED 'IT': ShipperClient.STATUS_TYPES.EN_ROUTE 'LO': ShipperClient.STATUS_TYPES.EN_ROUTE 'OC': ShipperClient.STATUS_TYPES.SHIPPING 'DL': ShipperClient.STATUS_TYPES.DELIVERED 'DP': ShipperClient.STATUS_TYPES.EN_ROUTE 'DS': ShipperClient.STATUS_TYPES.EN_ROUTE 'PF': ShipperClient.STATUS_TYPES.EN_ROUTE 'PL': ShipperClient.STATUS_TYPES.EN_ROUTE 'TU': ShipperClient.STATUS_TYPES.EN_ROUTE 'PU': ShipperClient.STATUS_TYPES.EN_ROUTE 'SF': ShipperClient.STATUS_TYPES.EN_ROUTE 'AR': ShipperClient.STATUS_TYPES.EN_ROUTE 'CD': ShipperClient.STATUS_TYPES.EN_ROUTE 'DE': ShipperClient.STATUS_TYPES.DELAYED 'CA': ShipperClient.STATUS_TYPES.DELAYED 'CH': ShipperClient.STATUS_TYPES.DELAYED 'DY': ShipperClient.STATUS_TYPES.DELAYED 'SE': ShipperClient.STATUS_TYPES.DELAYED 'AX': ShipperClient.STATUS_TYPES.EN_ROUTE 'OF': ShipperClient.STATUS_TYPES.EN_ROUTE 'PO': ShipperClient.STATUS_TYPES.EN_ROUTE 'DI': ShipperClient.STATUS_TYPES.EN_ROUTE presentStatus: (status) -> STATUS_MAP[status] or ShipperClient.STATUS_TYPES.UNKNOWN getActivitiesAndStatus: (shipment) -> activities = [] status = null rawActivities = shipment['TrackingHistory']?[0]?['Status'] for rawActivity in rawActivities or [] location = @presentAddress rawActivity['Location']?[0] timestamp = @presentTimestamp rawActivity['Date']?[0], rawActivity['Time']?[0] details = rawActivity['StatusDesc']?[0]?['_'] if details? and location? and timestamp? details = if details.slice(-1) is '.' then details[..-2] else details activity = {timestamp, location, details} activities.push activity if !status status = @presentStatus rawActivity['Disposition']?[0] {activities, status} getDestination: (shipment) -> destination = shipment['DestinationDescr']?[0]?['Location']?[0] return unless destination? fields = destination.split /,/ newFields = [] for field in fields or [] field = field.trim() newFields.push(if field.length > 2 then titleCase(field) else field) return newFields.join(', ') if newFields?.length requestOptions: ({trackingNumber}) -> method: 'POST' uri: 'http://eCommerce.Airborne.com/APILanding.asp' body: @generateRequest trackingNumber module.exports = {DhlClient}
38220
{Builder, Parser} = require 'xml2js' moment = require 'moment' {titleCase, upperCaseFirst, lowerCase} = require 'change-case' {ShipperClient} = require './shipper' class DhlClient extends ShipperClient constructor: ({@userId, @password}, @options) -> super @parser = new Parser() @builder = new Builder(renderOpts: pretty: false) generateRequest: (trk) -> @builder.buildObject 'ECommerce': '$': action: 'Request', version: '1.1' 'Requestor': 'ID': @userId 'Password': <PASSWORD> 'Track': '$': action: 'Get', version: '1.0' 'Shipment': 'TrackingNbr': trk validateResponse: (response, cb) -> handleResponse = (xmlErr, trackResult) -> return cb(xmlErr) if xmlErr? or !trackResult? shipment = trackResult['ECommerce']?['Track']?[0]?['Shipment']?[0] return cb(error: 'could not find shipment') unless shipment? trackStatus = shipment['Result']?[0] statusCode = trackStatus?['Code']?[0] statusDesc = trackStatus?['Desc']?[0] return cb(error: "unexpected track status code=#{statusCode} desc=#{statusDesc}") unless statusCode is "0" cb null, shipment @parser.reset() @parser.parseString response, handleResponse getEta: (shipment) -> getService: (shipment) -> description = shipment['Service']?[0]?['Desc']?[0] if description? then titleCase description getWeight: (shipment) -> weight = shipment['Weight']?[0] if weight? then "#{weight} LB" presentTimestamp: (dateString, timeString) -> return unless dateString? formatSpec = if timeString? then 'YYYY-MM-DD HH:mm' else 'YYYY-MM-DD' inputString = if timeString? then "#{dateString} #{timeString}" else dateString moment(inputString, formatSpec).toDate() presentAddress: (rawAddress) -> return unless rawAddress? city = rawAddress['City']?[0] stateCode = rawAddress['State']?[0] countryCode = rawAddress['Country']?[0] city = city.replace(' HUB', '') @presentLocation {city, stateCode, countryCode} STATUS_MAP = 'BA': ShipperClient.STATUS_TYPES.OUT_FOR_DELIVERY 'BD': ShipperClient.STATUS_TYPES.OUT_FOR_DELIVERY 'BN': ShipperClient.STATUS_TYPES.OUT_FOR_DELIVERY 'BT': ShipperClient.STATUS_TYPES.OUT_FOR_DELIVERY 'OD': ShipperClient.STATUS_TYPES.OUT_FOR_DELIVERY 'ED': ShipperClient.STATUS_TYPES.OUT_FOR_DELIVERY 'AD': ShipperClient.STATUS_TYPES.DELAYED 'CC': ShipperClient.STATUS_TYPES.EN_ROUTE 'DH': ShipperClient.STATUS_TYPES.EN_ROUTE 'GH': ShipperClient.STATUS_TYPES.EN_ROUTE 'HA': ShipperClient.STATUS_TYPES.EN_ROUTE 'IB': ShipperClient.STATUS_TYPES.EN_ROUTE 'LD': ShipperClient.STATUS_TYPES.DELIVERED 'ND': ShipperClient.STATUS_TYPES.DELAYED 'NL': ShipperClient.STATUS_TYPES.DELAYED 'OB': ShipperClient.STATUS_TYPES.EN_ROUTE 'OH': ShipperClient.STATUS_TYPES.SHIPPING 'PA': ShipperClient.STATUS_TYPES.DELIVERED 'PT': ShipperClient.STATUS_TYPES.EN_ROUTE 'RF': ShipperClient.STATUS_TYPES.DELAYED 'DF': ShipperClient.STATUS_TYPES.EN_ROUTE 'TB': ShipperClient.STATUS_TYPES.EN_ROUTE 'TG': ShipperClient.STATUS_TYPES.DELAYED 'AA': ShipperClient.STATUS_TYPES.EN_ROUTE 'AD': ShipperClient.STATUS_TYPES.EN_ROUTE 'AF': ShipperClient.STATUS_TYPES.EN_ROUTE 'AP': ShipperClient.STATUS_TYPES.SHIPPING 'EO': ShipperClient.STATUS_TYPES.EN_ROUTE 'EP': ShipperClient.STATUS_TYPES.SHIPPING 'FD': ShipperClient.STATUS_TYPES.EN_ROUTE 'HL': ShipperClient.STATUS_TYPES.DELIVERED 'IT': ShipperClient.STATUS_TYPES.EN_ROUTE 'LO': ShipperClient.STATUS_TYPES.EN_ROUTE 'OC': ShipperClient.STATUS_TYPES.SHIPPING 'DL': ShipperClient.STATUS_TYPES.DELIVERED 'DP': ShipperClient.STATUS_TYPES.EN_ROUTE 'DS': ShipperClient.STATUS_TYPES.EN_ROUTE 'PF': ShipperClient.STATUS_TYPES.EN_ROUTE 'PL': ShipperClient.STATUS_TYPES.EN_ROUTE 'TU': ShipperClient.STATUS_TYPES.EN_ROUTE 'PU': ShipperClient.STATUS_TYPES.EN_ROUTE 'SF': ShipperClient.STATUS_TYPES.EN_ROUTE 'AR': ShipperClient.STATUS_TYPES.EN_ROUTE 'CD': ShipperClient.STATUS_TYPES.EN_ROUTE 'DE': ShipperClient.STATUS_TYPES.DELAYED 'CA': ShipperClient.STATUS_TYPES.DELAYED 'CH': ShipperClient.STATUS_TYPES.DELAYED 'DY': ShipperClient.STATUS_TYPES.DELAYED 'SE': ShipperClient.STATUS_TYPES.DELAYED 'AX': ShipperClient.STATUS_TYPES.EN_ROUTE 'OF': ShipperClient.STATUS_TYPES.EN_ROUTE 'PO': ShipperClient.STATUS_TYPES.EN_ROUTE 'DI': ShipperClient.STATUS_TYPES.EN_ROUTE presentStatus: (status) -> STATUS_MAP[status] or ShipperClient.STATUS_TYPES.UNKNOWN getActivitiesAndStatus: (shipment) -> activities = [] status = null rawActivities = shipment['TrackingHistory']?[0]?['Status'] for rawActivity in rawActivities or [] location = @presentAddress rawActivity['Location']?[0] timestamp = @presentTimestamp rawActivity['Date']?[0], rawActivity['Time']?[0] details = rawActivity['StatusDesc']?[0]?['_'] if details? and location? and timestamp? details = if details.slice(-1) is '.' then details[..-2] else details activity = {timestamp, location, details} activities.push activity if !status status = @presentStatus rawActivity['Disposition']?[0] {activities, status} getDestination: (shipment) -> destination = shipment['DestinationDescr']?[0]?['Location']?[0] return unless destination? fields = destination.split /,/ newFields = [] for field in fields or [] field = field.trim() newFields.push(if field.length > 2 then titleCase(field) else field) return newFields.join(', ') if newFields?.length requestOptions: ({trackingNumber}) -> method: 'POST' uri: 'http://eCommerce.Airborne.com/APILanding.asp' body: @generateRequest trackingNumber module.exports = {DhlClient}
true
{Builder, Parser} = require 'xml2js' moment = require 'moment' {titleCase, upperCaseFirst, lowerCase} = require 'change-case' {ShipperClient} = require './shipper' class DhlClient extends ShipperClient constructor: ({@userId, @password}, @options) -> super @parser = new Parser() @builder = new Builder(renderOpts: pretty: false) generateRequest: (trk) -> @builder.buildObject 'ECommerce': '$': action: 'Request', version: '1.1' 'Requestor': 'ID': @userId 'Password': PI:PASSWORD:<PASSWORD>END_PI 'Track': '$': action: 'Get', version: '1.0' 'Shipment': 'TrackingNbr': trk validateResponse: (response, cb) -> handleResponse = (xmlErr, trackResult) -> return cb(xmlErr) if xmlErr? or !trackResult? shipment = trackResult['ECommerce']?['Track']?[0]?['Shipment']?[0] return cb(error: 'could not find shipment') unless shipment? trackStatus = shipment['Result']?[0] statusCode = trackStatus?['Code']?[0] statusDesc = trackStatus?['Desc']?[0] return cb(error: "unexpected track status code=#{statusCode} desc=#{statusDesc}") unless statusCode is "0" cb null, shipment @parser.reset() @parser.parseString response, handleResponse getEta: (shipment) -> getService: (shipment) -> description = shipment['Service']?[0]?['Desc']?[0] if description? then titleCase description getWeight: (shipment) -> weight = shipment['Weight']?[0] if weight? then "#{weight} LB" presentTimestamp: (dateString, timeString) -> return unless dateString? formatSpec = if timeString? then 'YYYY-MM-DD HH:mm' else 'YYYY-MM-DD' inputString = if timeString? then "#{dateString} #{timeString}" else dateString moment(inputString, formatSpec).toDate() presentAddress: (rawAddress) -> return unless rawAddress? city = rawAddress['City']?[0] stateCode = rawAddress['State']?[0] countryCode = rawAddress['Country']?[0] city = city.replace(' HUB', '') @presentLocation {city, stateCode, countryCode} STATUS_MAP = 'BA': ShipperClient.STATUS_TYPES.OUT_FOR_DELIVERY 'BD': ShipperClient.STATUS_TYPES.OUT_FOR_DELIVERY 'BN': ShipperClient.STATUS_TYPES.OUT_FOR_DELIVERY 'BT': ShipperClient.STATUS_TYPES.OUT_FOR_DELIVERY 'OD': ShipperClient.STATUS_TYPES.OUT_FOR_DELIVERY 'ED': ShipperClient.STATUS_TYPES.OUT_FOR_DELIVERY 'AD': ShipperClient.STATUS_TYPES.DELAYED 'CC': ShipperClient.STATUS_TYPES.EN_ROUTE 'DH': ShipperClient.STATUS_TYPES.EN_ROUTE 'GH': ShipperClient.STATUS_TYPES.EN_ROUTE 'HA': ShipperClient.STATUS_TYPES.EN_ROUTE 'IB': ShipperClient.STATUS_TYPES.EN_ROUTE 'LD': ShipperClient.STATUS_TYPES.DELIVERED 'ND': ShipperClient.STATUS_TYPES.DELAYED 'NL': ShipperClient.STATUS_TYPES.DELAYED 'OB': ShipperClient.STATUS_TYPES.EN_ROUTE 'OH': ShipperClient.STATUS_TYPES.SHIPPING 'PA': ShipperClient.STATUS_TYPES.DELIVERED 'PT': ShipperClient.STATUS_TYPES.EN_ROUTE 'RF': ShipperClient.STATUS_TYPES.DELAYED 'DF': ShipperClient.STATUS_TYPES.EN_ROUTE 'TB': ShipperClient.STATUS_TYPES.EN_ROUTE 'TG': ShipperClient.STATUS_TYPES.DELAYED 'AA': ShipperClient.STATUS_TYPES.EN_ROUTE 'AD': ShipperClient.STATUS_TYPES.EN_ROUTE 'AF': ShipperClient.STATUS_TYPES.EN_ROUTE 'AP': ShipperClient.STATUS_TYPES.SHIPPING 'EO': ShipperClient.STATUS_TYPES.EN_ROUTE 'EP': ShipperClient.STATUS_TYPES.SHIPPING 'FD': ShipperClient.STATUS_TYPES.EN_ROUTE 'HL': ShipperClient.STATUS_TYPES.DELIVERED 'IT': ShipperClient.STATUS_TYPES.EN_ROUTE 'LO': ShipperClient.STATUS_TYPES.EN_ROUTE 'OC': ShipperClient.STATUS_TYPES.SHIPPING 'DL': ShipperClient.STATUS_TYPES.DELIVERED 'DP': ShipperClient.STATUS_TYPES.EN_ROUTE 'DS': ShipperClient.STATUS_TYPES.EN_ROUTE 'PF': ShipperClient.STATUS_TYPES.EN_ROUTE 'PL': ShipperClient.STATUS_TYPES.EN_ROUTE 'TU': ShipperClient.STATUS_TYPES.EN_ROUTE 'PU': ShipperClient.STATUS_TYPES.EN_ROUTE 'SF': ShipperClient.STATUS_TYPES.EN_ROUTE 'AR': ShipperClient.STATUS_TYPES.EN_ROUTE 'CD': ShipperClient.STATUS_TYPES.EN_ROUTE 'DE': ShipperClient.STATUS_TYPES.DELAYED 'CA': ShipperClient.STATUS_TYPES.DELAYED 'CH': ShipperClient.STATUS_TYPES.DELAYED 'DY': ShipperClient.STATUS_TYPES.DELAYED 'SE': ShipperClient.STATUS_TYPES.DELAYED 'AX': ShipperClient.STATUS_TYPES.EN_ROUTE 'OF': ShipperClient.STATUS_TYPES.EN_ROUTE 'PO': ShipperClient.STATUS_TYPES.EN_ROUTE 'DI': ShipperClient.STATUS_TYPES.EN_ROUTE presentStatus: (status) -> STATUS_MAP[status] or ShipperClient.STATUS_TYPES.UNKNOWN getActivitiesAndStatus: (shipment) -> activities = [] status = null rawActivities = shipment['TrackingHistory']?[0]?['Status'] for rawActivity in rawActivities or [] location = @presentAddress rawActivity['Location']?[0] timestamp = @presentTimestamp rawActivity['Date']?[0], rawActivity['Time']?[0] details = rawActivity['StatusDesc']?[0]?['_'] if details? and location? and timestamp? details = if details.slice(-1) is '.' then details[..-2] else details activity = {timestamp, location, details} activities.push activity if !status status = @presentStatus rawActivity['Disposition']?[0] {activities, status} getDestination: (shipment) -> destination = shipment['DestinationDescr']?[0]?['Location']?[0] return unless destination? fields = destination.split /,/ newFields = [] for field in fields or [] field = field.trim() newFields.push(if field.length > 2 then titleCase(field) else field) return newFields.join(', ') if newFields?.length requestOptions: ({trackingNumber}) -> method: 'POST' uri: 'http://eCommerce.Airborne.com/APILanding.asp' body: @generateRequest trackingNumber module.exports = {DhlClient}
[ { "context": "'36.000'\n process.env.HUBOT_LYFT_CLIENT_TOKEN='foobarbaz'\n Date.now = mockDateNow\n @room = helper.cr", "end": 544, "score": 0.9947757720947266, "start": 535, "tag": "PASSWORD", "value": "foobarbaz" }, { "context": "on')\n\n selfRoom = @room\n selfRoom....
test/lyft-slack-test.coffee
stephenyeargin/hubot-lyft
0
Helper = require 'hubot-test-helper' chai = require 'chai' nock = require 'nock' fs = require 'fs' expect = chai.expect helper = new Helper [ 'adapters/slack.coffee', '../src/lyft.coffee' ] # Alter time as test runs originalDateNow = Date.now mockDateNow = () -> return Date.parse('Tue Mar 06 2018 23:01:27 GMT-0600 (CST)') describe 'hubot-lyft for slack', -> beforeEach -> process.env.HUBOT_LYFT_DEFAULT_LONGITUDE='-86.000' process.env.HUBOT_LYFT_DEFAULT_LATITUDE='36.000' process.env.HUBOT_LYFT_CLIENT_TOKEN='foobarbaz' Date.now = mockDateNow @room = helper.createRoom() nock.disableNetConnect() afterEach -> delete process.env.HUBOT_LYFT_DEFAULT_LONGITUDE delete process.env.HUBOT_LYFT_DEFAULT_LATITUDE delete process.env.HUBOT_LYFT_CLIENT_TOKEN Date.now = originalDateNow @room.destroy() nock.cleanAll() it 'retrieves the current lyft availability', (done) -> options = reqheaders: authorization: "Bearer foobarbaz" nock('https://api.lyft.com', options) .get('/v1/ridetypes') .query( lat: '36.000' lng: '-86.000' ) .reply 200, fs.readFileSync('test/fixtures/ridetypes.json') nock('https://api.lyft.com', options) .get('/v1/eta') .query( lat: '36.000' lng: '-86.000' ) .reply 200, fs.readFileSync('test/fixtures/eta.json') selfRoom = @room selfRoom.user.say('alice', '@hubot lyft') setTimeout(() -> try expect(selfRoom.messages).to.eql [ ['alice', '@hubot lyft'] [ 'hubot' { "attachments": [ { "color": "#FF00BF", "fallback": "Lyft Line: Seats 2, arrives in 2 minute(s)", "fields": [ { "short": true, "title": "Arrives", "value": "2 minute(s)" }, { "short": true, "title": "Seats", "value": 2 }, { "short": true, "title": "Base Charge", "value": "$2.00" }, { "short": true, "title": "Cost per Mile", "value": "$1.15" }, { "short": true, "title": "Cost per Minute", "value": "$0.23" }, { "short": true, "title": "Trust & Service Fee", "value": "$1.55" }, { "short": true, "title": "Cancel Penalty", "value": "$5.00" } ], "thumb_url": "https://s3.amazonaws.com/api.lyft.com/assets/car_standard.png", "title": "Lyft Line" }, { "color": "#FF00BF", "fallback": "Lyft: Seats 4, arrives in 2 minute(s)", "fields": [ { "short": true, "title": "Arrives", "value": "2 minute(s)" }, { "short": true, "title": "Seats", "value": 4 }, { "short": true, "title": "Base Charge", "value": "$2.00" }, { "short": true, "title": "Cost per Mile", "value": "$1.15" }, { "short": true, "title": "Cost per Minute", "value": "$0.23" }, { "short": true, "title": "Trust & Service Fee", "value": "$1.55" }, { "short": true, "title": "Cancel Penalty", "value": "$5.00" } ], "thumb_url": "https://s3.amazonaws.com/api.lyft.com/assets/car_standard.png", "title": "Lyft" }, { "color": "#FF00BF", "fallback": "Lyft Plus: Seats 6, arrives in 11 minute(s)", "fields": [ { "short": true, "title": "Arrives", "value": "11 minute(s)" }, { "short": true, "title": "Seats", "value": 6 }, { "short": true, "title": "Base Charge", "value": "$3.00" }, { "short": true, "title": "Cost per Mile", "value": "$2.00" }, { "short": true, "title": "Cost per Minute", "value": "$0.30" }, { "short": true, "title": "Trust & Service Fee", "value": "$1.55" }, { "short": true, "title": "Cancel Penalty", "value": "$5.00" } ], "thumb_url": "https://s3.amazonaws.com/api.lyft.com/assets/car_plus.png", "title": "Lyft Plus" } ] } ] ] done() catch err done err return , 1000)
7556
Helper = require 'hubot-test-helper' chai = require 'chai' nock = require 'nock' fs = require 'fs' expect = chai.expect helper = new Helper [ 'adapters/slack.coffee', '../src/lyft.coffee' ] # Alter time as test runs originalDateNow = Date.now mockDateNow = () -> return Date.parse('Tue Mar 06 2018 23:01:27 GMT-0600 (CST)') describe 'hubot-lyft for slack', -> beforeEach -> process.env.HUBOT_LYFT_DEFAULT_LONGITUDE='-86.000' process.env.HUBOT_LYFT_DEFAULT_LATITUDE='36.000' process.env.HUBOT_LYFT_CLIENT_TOKEN='<PASSWORD>' Date.now = mockDateNow @room = helper.createRoom() nock.disableNetConnect() afterEach -> delete process.env.HUBOT_LYFT_DEFAULT_LONGITUDE delete process.env.HUBOT_LYFT_DEFAULT_LATITUDE delete process.env.HUBOT_LYFT_CLIENT_TOKEN Date.now = originalDateNow @room.destroy() nock.cleanAll() it 'retrieves the current lyft availability', (done) -> options = reqheaders: authorization: "Bearer foobarbaz" nock('https://api.lyft.com', options) .get('/v1/ridetypes') .query( lat: '36.000' lng: '-86.000' ) .reply 200, fs.readFileSync('test/fixtures/ridetypes.json') nock('https://api.lyft.com', options) .get('/v1/eta') .query( lat: '36.000' lng: '-86.000' ) .reply 200, fs.readFileSync('test/fixtures/eta.json') selfRoom = @room selfRoom.user.say('alice', '@hubot lyft') setTimeout(() -> try expect(selfRoom.messages).to.eql [ ['alice', '@hubot lyft'] [ 'hubot' { "attachments": [ { "color": "#FF00BF", "fallback": "Lyft Line: Seats 2, arrives in 2 minute(s)", "fields": [ { "short": true, "title": "Arrives", "value": "2 minute(s)" }, { "short": true, "title": "Seats", "value": 2 }, { "short": true, "title": "Base Charge", "value": "$2.00" }, { "short": true, "title": "Cost per Mile", "value": "$1.15" }, { "short": true, "title": "Cost per Minute", "value": "$0.23" }, { "short": true, "title": "Trust & Service Fee", "value": "$1.55" }, { "short": true, "title": "Cancel Penalty", "value": "$5.00" } ], "thumb_url": "https://s3.amazonaws.com/api.lyft.com/assets/car_standard.png", "title": "Lyft Line" }, { "color": "#FF00BF", "fallback": "Lyft: Seats 4, arrives in 2 minute(s)", "fields": [ { "short": true, "title": "Arrives", "value": "2 minute(s)" }, { "short": true, "title": "Seats", "value": 4 }, { "short": true, "title": "Base Charge", "value": "$2.00" }, { "short": true, "title": "Cost per Mile", "value": "$1.15" }, { "short": true, "title": "Cost per Minute", "value": "$0.23" }, { "short": true, "title": "Trust & Service Fee", "value": "$1.55" }, { "short": true, "title": "Cancel Penalty", "value": "$5.00" } ], "thumb_url": "https://s3.amazonaws.com/api.lyft.com/assets/car_standard.png", "title": "Lyft" }, { "color": "#FF00BF", "fallback": "Lyft Plus: Seats 6, arrives in 11 minute(s)", "fields": [ { "short": true, "title": "Arrives", "value": "11 minute(s)" }, { "short": true, "title": "Seats", "value": 6 }, { "short": true, "title": "Base Charge", "value": "$3.00" }, { "short": true, "title": "Cost per Mile", "value": "$2.00" }, { "short": true, "title": "Cost per Minute", "value": "$0.30" }, { "short": true, "title": "Trust & Service Fee", "value": "$1.55" }, { "short": true, "title": "Cancel Penalty", "value": "$5.00" } ], "thumb_url": "https://s3.amazonaws.com/api.lyft.com/assets/car_plus.png", "title": "Lyft Plus" } ] } ] ] done() catch err done err return , 1000)
true
Helper = require 'hubot-test-helper' chai = require 'chai' nock = require 'nock' fs = require 'fs' expect = chai.expect helper = new Helper [ 'adapters/slack.coffee', '../src/lyft.coffee' ] # Alter time as test runs originalDateNow = Date.now mockDateNow = () -> return Date.parse('Tue Mar 06 2018 23:01:27 GMT-0600 (CST)') describe 'hubot-lyft for slack', -> beforeEach -> process.env.HUBOT_LYFT_DEFAULT_LONGITUDE='-86.000' process.env.HUBOT_LYFT_DEFAULT_LATITUDE='36.000' process.env.HUBOT_LYFT_CLIENT_TOKEN='PI:PASSWORD:<PASSWORD>END_PI' Date.now = mockDateNow @room = helper.createRoom() nock.disableNetConnect() afterEach -> delete process.env.HUBOT_LYFT_DEFAULT_LONGITUDE delete process.env.HUBOT_LYFT_DEFAULT_LATITUDE delete process.env.HUBOT_LYFT_CLIENT_TOKEN Date.now = originalDateNow @room.destroy() nock.cleanAll() it 'retrieves the current lyft availability', (done) -> options = reqheaders: authorization: "Bearer foobarbaz" nock('https://api.lyft.com', options) .get('/v1/ridetypes') .query( lat: '36.000' lng: '-86.000' ) .reply 200, fs.readFileSync('test/fixtures/ridetypes.json') nock('https://api.lyft.com', options) .get('/v1/eta') .query( lat: '36.000' lng: '-86.000' ) .reply 200, fs.readFileSync('test/fixtures/eta.json') selfRoom = @room selfRoom.user.say('alice', '@hubot lyft') setTimeout(() -> try expect(selfRoom.messages).to.eql [ ['alice', '@hubot lyft'] [ 'hubot' { "attachments": [ { "color": "#FF00BF", "fallback": "Lyft Line: Seats 2, arrives in 2 minute(s)", "fields": [ { "short": true, "title": "Arrives", "value": "2 minute(s)" }, { "short": true, "title": "Seats", "value": 2 }, { "short": true, "title": "Base Charge", "value": "$2.00" }, { "short": true, "title": "Cost per Mile", "value": "$1.15" }, { "short": true, "title": "Cost per Minute", "value": "$0.23" }, { "short": true, "title": "Trust & Service Fee", "value": "$1.55" }, { "short": true, "title": "Cancel Penalty", "value": "$5.00" } ], "thumb_url": "https://s3.amazonaws.com/api.lyft.com/assets/car_standard.png", "title": "Lyft Line" }, { "color": "#FF00BF", "fallback": "Lyft: Seats 4, arrives in 2 minute(s)", "fields": [ { "short": true, "title": "Arrives", "value": "2 minute(s)" }, { "short": true, "title": "Seats", "value": 4 }, { "short": true, "title": "Base Charge", "value": "$2.00" }, { "short": true, "title": "Cost per Mile", "value": "$1.15" }, { "short": true, "title": "Cost per Minute", "value": "$0.23" }, { "short": true, "title": "Trust & Service Fee", "value": "$1.55" }, { "short": true, "title": "Cancel Penalty", "value": "$5.00" } ], "thumb_url": "https://s3.amazonaws.com/api.lyft.com/assets/car_standard.png", "title": "Lyft" }, { "color": "#FF00BF", "fallback": "Lyft Plus: Seats 6, arrives in 11 minute(s)", "fields": [ { "short": true, "title": "Arrives", "value": "11 minute(s)" }, { "short": true, "title": "Seats", "value": 6 }, { "short": true, "title": "Base Charge", "value": "$3.00" }, { "short": true, "title": "Cost per Mile", "value": "$2.00" }, { "short": true, "title": "Cost per Minute", "value": "$0.30" }, { "short": true, "title": "Trust & Service Fee", "value": "$1.55" }, { "short": true, "title": "Cancel Penalty", "value": "$5.00" } ], "thumb_url": "https://s3.amazonaws.com/api.lyft.com/assets/car_plus.png", "title": "Lyft Plus" } ] } ] ] done() catch err done err return , 1000)
[ { "context": "ient_id = '4b5a6ab7eea4c6aaee37'\nclient_secret = '769602c9c4a0944a5386e883db4670e436f3af5a'\n\nmodule.exports = (done)->\n login (user, pass)-", "end": 188, "score": 0.9997039437294006, "start": 148, "tag": "KEY", "value": "769602c9c4a0944a5386e883db4670e436f3af5a" } ]
src/register.coffee
mralexgray/ghfm
0
fs = require 'fs' path = require 'path' prompt = require 'prompt' request = require 'request' client_id = '4b5a6ab7eea4c6aaee37' client_secret = '769602c9c4a0944a5386e883db4670e436f3af5a' module.exports = (done)-> login (user, pass)-> url = 'https://api.github.com/authorizations/clients/' + client_id options = headers: 'User-Agent': 'GHFM' auth: {user, pass} body: JSON.stringify note: 'GHFM - Github Flavored Markdown Previewer' scopes: ['public_repo'] client_secret: client_secret request.put url, options, (req, res)-> if ~'401 Unauthorized 403 Forbidden'.indexOf(res.headers.status) console.log 'Incorrect credentials, try again' return module.exports done fs.writeFileSync path.join(__dirname, 'user.oauth.json'), res.body done() login = (done)-> msg = """ > Data will no be stored and you can revoke access at any time at: #{'https://github.com/settings/applications'.green} """.grey console.log "Enter your Github crendentials \n#{msg}" prompt.start() schema = properties: username: pattern: /.+/, required: true password: hidden: true, pattern: /.+/ required: true prompt.get schema, (err, res)-> done res.username, res.password
192057
fs = require 'fs' path = require 'path' prompt = require 'prompt' request = require 'request' client_id = '4b5a6ab7eea4c6aaee37' client_secret = '<KEY>' module.exports = (done)-> login (user, pass)-> url = 'https://api.github.com/authorizations/clients/' + client_id options = headers: 'User-Agent': 'GHFM' auth: {user, pass} body: JSON.stringify note: 'GHFM - Github Flavored Markdown Previewer' scopes: ['public_repo'] client_secret: client_secret request.put url, options, (req, res)-> if ~'401 Unauthorized 403 Forbidden'.indexOf(res.headers.status) console.log 'Incorrect credentials, try again' return module.exports done fs.writeFileSync path.join(__dirname, 'user.oauth.json'), res.body done() login = (done)-> msg = """ > Data will no be stored and you can revoke access at any time at: #{'https://github.com/settings/applications'.green} """.grey console.log "Enter your Github crendentials \n#{msg}" prompt.start() schema = properties: username: pattern: /.+/, required: true password: hidden: true, pattern: /.+/ required: true prompt.get schema, (err, res)-> done res.username, res.password
true
fs = require 'fs' path = require 'path' prompt = require 'prompt' request = require 'request' client_id = '4b5a6ab7eea4c6aaee37' client_secret = 'PI:KEY:<KEY>END_PI' module.exports = (done)-> login (user, pass)-> url = 'https://api.github.com/authorizations/clients/' + client_id options = headers: 'User-Agent': 'GHFM' auth: {user, pass} body: JSON.stringify note: 'GHFM - Github Flavored Markdown Previewer' scopes: ['public_repo'] client_secret: client_secret request.put url, options, (req, res)-> if ~'401 Unauthorized 403 Forbidden'.indexOf(res.headers.status) console.log 'Incorrect credentials, try again' return module.exports done fs.writeFileSync path.join(__dirname, 'user.oauth.json'), res.body done() login = (done)-> msg = """ > Data will no be stored and you can revoke access at any time at: #{'https://github.com/settings/applications'.green} """.grey console.log "Enter your Github crendentials \n#{msg}" prompt.start() schema = properties: username: pattern: /.+/, required: true password: hidden: true, pattern: /.+/ required: true prompt.get schema, (err, res)-> done res.username, res.password
[ { "context": "tion:\n databaseUrl: 'mongodb://mongo_dev_user1:zJYBZWPEcvKkuGpYJxHoTKRGGc8G4bdqftzgqQbybEYsFThosN@ds031088.", "end": 239, "score": 0.9697708487510681, "start": 229, "tag": "EMAIL", "value": "zJYBZWPEcv" }, { "context": "atabaseUrl: 'mongodb://mongo_dev_user1:zJYBZWP...
config/config.coffee
ethanmick/fastchat-server
7
module.exports = dev: databaseUrl: 'mongodb://localhost/dev' baseUrl: 'localhost' test: databaseUrl: 'mongodb://localhost/test' baseUrl: 'localhost' production: databaseUrl: 'mongodb://mongo_dev_user1:zJYBZWPEcvKkuGpYJxHoTKRGGc8G4bdqftzgqQbybEYsFThosN@ds031088.mongolab.com:31088/MongoLab-92' baseUrl: 'https://www.fastchat.io/' config = dev if process.env.NODE_ENV switch process.env.NODE_ENV when 'production' config = production when 'staging' config = staging module.exports = config
80833
module.exports = dev: databaseUrl: 'mongodb://localhost/dev' baseUrl: 'localhost' test: databaseUrl: 'mongodb://localhost/test' baseUrl: 'localhost' production: databaseUrl: 'mongodb://mongo_dev_user1:<EMAIL>K<EMAIL>zgq<EMAIL>by<EMAIL>:31088/MongoLab-92' baseUrl: 'https://www.fastchat.io/' config = dev if process.env.NODE_ENV switch process.env.NODE_ENV when 'production' config = production when 'staging' config = staging module.exports = config
true
module.exports = dev: databaseUrl: 'mongodb://localhost/dev' baseUrl: 'localhost' test: databaseUrl: 'mongodb://localhost/test' baseUrl: 'localhost' production: databaseUrl: 'mongodb://mongo_dev_user1:PI:EMAIL:<EMAIL>END_PIKPI:EMAIL:<EMAIL>END_PIzgqPI:EMAIL:<EMAIL>END_PIbyPI:EMAIL:<EMAIL>END_PI:31088/MongoLab-92' baseUrl: 'https://www.fastchat.io/' config = dev if process.env.NODE_ENV switch process.env.NODE_ENV when 'production' config = production when 'staging' config = staging module.exports = config
[ { "context": "oveshark', ->\n trackTitle = '꿈에'\n artistName = '박정현'\n\n describe 'Grooveshark.getStreamingUrl(...)', ", "end": 175, "score": 0.9998415112495422, "start": 172, "tag": "NAME", "value": "박정현" } ]
node_modules/grooveshark-streaming/test/Grooveshark.test.coffee
samkreter/MusicChoose
3
should = require 'should' Tinysong = require '../lib/Tinysong' Grooveshark = require '../lib/Grooveshark' describe 'Grooveshark', -> trackTitle = '꿈에' artistName = '박정현' describe 'Grooveshark.getStreamingUrl(...)', -> it 'should be done', (done) -> Tinysong.getSongInfo trackTitle, artistName, (err, songInfo) -> should.not.exist err should.exist songInfo Grooveshark.getStreamingUrl songInfo.SongID, (err, streamUrl) -> should.not.exist err should.exist streamUrl done()
122534
should = require 'should' Tinysong = require '../lib/Tinysong' Grooveshark = require '../lib/Grooveshark' describe 'Grooveshark', -> trackTitle = '꿈에' artistName = '<NAME>' describe 'Grooveshark.getStreamingUrl(...)', -> it 'should be done', (done) -> Tinysong.getSongInfo trackTitle, artistName, (err, songInfo) -> should.not.exist err should.exist songInfo Grooveshark.getStreamingUrl songInfo.SongID, (err, streamUrl) -> should.not.exist err should.exist streamUrl done()
true
should = require 'should' Tinysong = require '../lib/Tinysong' Grooveshark = require '../lib/Grooveshark' describe 'Grooveshark', -> trackTitle = '꿈에' artistName = 'PI:NAME:<NAME>END_PI' describe 'Grooveshark.getStreamingUrl(...)', -> it 'should be done', (done) -> Tinysong.getSongInfo trackTitle, artistName, (err, songInfo) -> should.not.exist err should.exist songInfo Grooveshark.getStreamingUrl songInfo.SongID, (err, streamUrl) -> should.not.exist err should.exist streamUrl done()
[ { "context": "ndexOf selectedId\n key = if ua.isMac then '⌘I' else 'Ctrl-I'\n if index == -1\n di", "end": 17507, "score": 0.8434537053108215, "start": 17504, "tag": "KEY", "value": "⌘I'" }, { "context": "ectedId\n key = if ua.isMac then '⌘I' else 'Ctrl-...
src/public/lib/views/console.coffee
tonistiigi/styler
18
define (require, exports, module) -> TreeOutline = require 'lib/views/ui/treeoutline' StyleInfo = require 'lib/views/ui/styleinfo' OutlineInfo = require 'lib/views/outlineinfo' OutputSwitch = require 'lib/views/outputswitch' Resizer = require 'lib/views/ui/resizer' {StateList, FoldList, PseudoList} = require 'lib/models' {node, highlightSelector, swapNodes, parallel} = require 'lib/utils' {addMouseWheelListener, stopEvent} = require 'ace/lib/event' {addKeyboardListener, listenKey} = require 'lib/keyboard' ua = require 'ace/lib/useragent' ConsoleView = Backbone.View.extend className: 'app' template: require 'lib/templates/console' events: 'click .tool-back': 'showProjectList' 'click .tool-settings': 'showSettings' 'click .tool-refresh': 'reloadOutline' 'click .tool-identify': 'identifyClient' 'click .tool-inspect': 'startInspector' 'click .tool-edit': 'editProject' 'click .tool-embed': 'toggleApplicationMode' 'click .tool-sidebyside': 'toggleIframeMode' initialize: (opt) -> _.bindAll @, 'onResize', 'toggleApplicationMode', 'onBeforeUnload', 'onConsoleDeactivated', 'onConsoleActivated', 'onClientMessage', 'toggleInfobar', 'onStartupData', 'toggleUpdateMode', 'toggleTabSettings', 'toggleSidebar', 'onInspectorResult', 'onElementSelected', 'onEmbedMessage' app.console = @ @usesPostMessage = false app.socket.on 'activate', @onConsoleActivated app.socket.on 'deactivate', @onConsoleDeactivated app.socket.on 'clientmessage', @onClientMessage app.socket.on 'startupdata', @onStartupData @project = opt.project @project.on 'clients:add', (client) => @loadClient client if @project.getClients().length == 1 && !@client # Embed detection. if self != top window.addEventListener 'message', @onEmbedMessage , false top.postMessage 'getEmbedMode', '*' # Keyboard commands. addKeyboardListener 'global', window listenKey null, 'toggle-window-mode', exec: @toggleApplicationMode listenKey null, 'toggle-iframe-container', exec: => @callClient 'toggleIframe', {} listenKey null, 'focus-tree', exec: => @outline.el.focus() listenKey null, 'focus-styleinfo', exec: => @styleInfo.el.focus() listenKey null, 'focus-editor', exec: => @editor.focus() listenKey null, 'focus-clientswitch', exec: => @clientPicker.el.focus() listenKey null, 'settings', exec: => @showSettings() listenKey null, 'select-focused-selector', exec: => @selectFocusedSelectorElement() listenKey null, 'select-focused-selector-reverse', exec: => @selectFocusedSelectorElement true listenKey null, 'back-to-project-list', exec: => @showProjectList() listenKey null, 'toggle-infobar', exec: @toggleInfobar listenKey null, 'toggle-update-mode', exec: @toggleUpdateMode listenKey null, 'toggle-tab-mode', exec: @toggleTabSettings listenKey null, 'toggle-left-pane', exec: @toggleSidebar # Make DOM elements and subviews. @$el.html(@template).addClass 'no-client-loaded' @clientPicker = new OutputSwitch model: @project, el: @$('.client-select-sidebar')[0] @clientPicker.on 'change', @onClientChange, @ @clientPicker2 = new OutputSwitch model: @project, el: @$('.client-select-toolbar')[0] @clientPicker2.on 'change', @onClientChange, @ @outline = new TreeOutline el: @$('.elements-outline')[0] @outline.on 'load', @onOutlineLoaded, @ @outline.on 'select', _.throttle (_.bind @onElementSelected), 300 @outline.on 'fold', @onFold, @ @outline.on 'unfold', @onUnfold, @ @outline.on 'focus:styleinfo', => @styleInfo.el.focus() @styleInfo.moveHighlight 1 unless @styleInfo.highlightElement? @styleInfo = new StyleInfo el: @$('.styleinfo')[0] @styleInfo.on 'open', @openFile, @ @styleInfo.on 'focus:outline', => @outline.el.focus() @outlineInfo = new OutlineInfo el: @$('.infobar-outline')[0] @on 'change:pseudo', (pseudo) => @setElementPseudo pseudo.elementId, pseudo.get('pseudos') (new Resizer el: @$('.resizer-vertical')[0], name: 'vresizer', target: @$('.styleinfo')[0]) .on 'resize', @onResize (new Resizer el: @$('.resizer-horizontal')[0], name: 'hresizer', target: @$('.sidebar')[0]) .on 'resize', @onResize swapNodes @$('.sidebar')[0], @$('.main-content')[0] if app.Settings.get 'sidebar_right' @$('.sidebar-toggle').on 'click', @toggleSidebar baseUrl = @project.get 'baseurl' @$('.no-clients-fallback .url').text(baseUrl) .on 'click', -> window.open baseUrl @loadClient opt.client # Disable elastic scrolling + back swiping. $(document.body).addClass 'no-scrolling' addMouseWheelListener document, (e) -> stopEvent e if e.wheelX != 0 # Page unload control. $(window).on 'beforeunload', @onBeforeUnload if !ua.isGecko @captureCommandStart = _.bind @captureCommandKey, @, false @captureCommandEnd = _.bind @captureCommandKey, @, true window.addEventListener 'keydown', @captureCommandStart, true window.addEventListener 'keyup', @captureCommandEnd, true Backbone.history.onbeforeunload = => block = @checkUnsavedFiles => Backbone.history.onbeforeunload = null window.history.back() if block # Add ID to the title so extensions can use it for focus switching. oldTitle = document.title.replace /\s?\(\d+\)$/, '' document.title = oldTitle + " (#{@project.id})" tm('console') # Load defer components. _.delay -> require ['lib/editor/statsmanager'], (stats) -> app.stats = stats , 1000 if app.Settings.get 'fpsstats' require ['vendor/stats'], => stats = new Stats() statsElement = stats.getDomElement() $(statsElement).addClass 'fpsstats' @$el.append statsElement setInterval -> stats.update() , 1000 / 60 _.delay => require ['lib/views/commandline'], (CommandLine) => new CommandLine el: @$('.cli-container')[0] , 1000 activateConsole: -> tm('activateConsole') app.socket.emit 'activate', @project.id, @client?.id if @state @initState() else states = new StateList null, backend: 'state-' + @project.id if __data.states states.reset __data.states @state = states.at 0 console.log @state @initState() __data.states = null else states.fetch success: => @state = states.at(0) @initState() initState: -> tm('initstate') sp = @state.get 'scrollPos' @outline.scrollPosition = sp if sp # TODO: just plain wrong to do it this way. # TODO: these need localStorage fallbacks to avoid flicker. @state.on 'change:infobarVisible', @renderInforbarVisibility, @ @renderInforbarVisibility() @state.on 'change:outlineLock', @renderFocusLocking, @ @renderFocusLocking() @state.on 'change:leftPaneVisible', @renderSidebarVisibility, @ @renderSidebarVisibility() _.defer => require ['lib/views/editor'], (EditorView) => tm('editorload') unless @editor @editor = new EditorView el: @$('.editor-container')[0] @editor.on 'change:focusedselector', @onFocusedSelectorChange, @ @$('.infobar-toggle').on 'click', @toggleInfobar @$('.locking-toggle').on 'click', => @state.save outlineLock: !@state.get 'outlineLock' @usesPostMessage = false @callClientPostMessage 'getSessionId', {}, (resp) => if parseInt(resp.sessionId, 10) == @client.get 'session_id' @usesPostMessage = true _.delay => @reloadOutline() if @getMedia() != 'screen' @callClient 'setMedia', {value: @getMedia()}, -> @trigger 'change:media' , 50 onConsoleActivated: -> tm('activated') @active = true onConsoleDeactivated: -> @backupData() @active = false require ['lib/views/warning-screen'], (WarningScreen) => top.postMessage 'close-iframe', '*' if @embed new WarningScreen name: 'warning_overload' @destroy() destroy: -> @unloadClient() app.socket.emit 'deactivate' if @active app.socket.removeListener 'activate', @onConsoleActivated app.socket.removeListener 'deactivate', @onConsoleDeactivated app.socket.removeListener 'clientmessage', @onClientMessage app.socket.removeListener 'startupdata', @onStartupData $(document.body).removeClass 'no-scrolling' $(window).off 'beforeunload', @onBeforeUnload window.removeEventListener 'keydown', @captureCommandStart, true window.removeEventListener 'keyup', @captureCommandEnd, true document.title = '' + document.title.replace /\s*?\(\d+\)$/, '' @editor?.destroy() app.console = null toggleSidebar: -> @state.save leftPaneVisible: !@state.get 'leftPaneVisible' _.delay => @editor.onResize() , 1000 toggleInfobar: -> @state.save infobarVisible: !@state.get 'infobarVisible' toggleUpdateMode: -> @project.save mode: (if @project.get('mode') then 0 else 1) toggleTabSettings: -> tabSize = @project.get 'tabSize' softTabs = @project.get 'softTabs' switch tabSize when 2 then tabSize = 3 when 3 then tabSize = 4 when 4 then tabSize = 8 when 8 tabSize = 2 softTabs = !softTabs @project.save tabSize: tabSize, softTabs: softTabs toggleApplicationMode: -> @callClient 'toggleApplicationMode', null, -> window.close() toggleIframeMode: -> top.postMessage 'toggleIframeMode', '*' if @embed onEmbedMessage: (e) -> if e.data.embedInfo if e.data.iframeMode @embedSideBySide = e.data.iframeMode == 'sidebyside' if e.data.baseURL @embed = e.data.baseURL == @project.get('baseurl') @renderEmbedMode() renderEmbedMode: -> if @embed @$('.tool-embed').addClass 'is-selected' @$('.tool-sidebyside').show().toggleClass 'is-selected', !!@embedSideBySide else @$('.tool-embed').toggle @client && @client.get('embed') @$('.tool-sidebyside').hide() renderInforbarVisibility: -> @$el.toggleClass 'has-infobar', @state.get 'infobarVisible' renderFocusLocking: -> @$('.locking-toggle').toggleClass 'is-locked', @state.get 'outlineLock' renderSidebarVisibility: -> leftPaneVisible = @state.get 'leftPaneVisible' @$el .toggleClass('no-sidebar', !leftPaneVisible) .toggleClass('has-sidebar', leftPaneVisible) showProjectList: -> @checkUnsavedFiles => if @client?.get('project') app.router.navigate 'project/' + @client.get('project'), trigger: true else app.router.navigate '', trigger: true editProject: -> @checkUnsavedFiles => app.router.navigate 'edit/' + @project.id, trigger: true startInspector: -> @callClient 'startInspector', {}, @onInspectorResult window.opener?.focus() if @usesPostMessage app.socket.emit 'callClient', @client.id, 'focus' onInspectorResult: (data) -> @_dontInspectOutline = true @_wasSelectFromInspect = true @outline.select data.id app.socket.emit 'callClient', @client.id, 'focus', title: @project.id showSettings: -> app.app.showSettings() identifyClient: -> @callClient 'identify', msg: @client.get('useragent'), -> app.socket.emit 'callclient', @client.id, 'focus' reloadOutline: -> tm('reload') @callClient 'getDOMTree', {}, (data) => @_wasSilentRefresh = false @outline.setTreeData data.tree tm('treedata') captureCommandKey: (release, e) -> if e.keyCode == (if ua.isMac then 91 else 17) @iscommandkey = !release else if e.keyCode == 87 @iswkey = !release else if e.keyCode == 16 @isshiftkey = !release onBeforeUnload: (e) -> confirm_keyboard_close = app.Settings.get 'confirm_keyboard_close' if @iscommandkey && confirm_keyboard_close && @editor.tabs.size() && !@isshiftkey @iscommandkey = false return [ 'Possibly incorrect action was detected! Closing editor tabs with' if ua.isMac then ' ⌘W' else 'Ctrl-W' 'is not supported by your browser. Use alternative keyboard command' if ua.isMac then '⌃W' else 'Alt-W' 'instead. If you like the default behaviour of your browser you can turn off this message from the settings or include Shift key in your command.'].join ' ' confirm_unsaved_close = app.Settings.get 'confirm_unsaved_close' unsavedTabs = @editor.getUnsavedTabs() return unless unsavedTabs.length && confirm_unsaved_close fileNames = _.map unsavedTabs, (tab) -> tab.get 'name' 'You have unsaved changes in file(s): ' + fileNames.join(', ') + '. Closing the window will destroy the changes.' checkUnsavedFiles: (cb) -> confirmUnsavedClose = app.Settings.get 'confirm_unsaved_close' return unless @editor unsaved = @editor.getUnsavedTabs() unless unsaved.length && confirmUnsavedClose cb() return false names = _.map unsaved, (tab) -> tab.get 'name' require ['lib/views/ui/popup'], (Popup) => new Popup msg: 'You have unsaved changes in file(s): ' + names.join(', ') + '. Do you want to save those changes?' buttons: [ (id:'no', txt: 'Don\'t save', exec: => cb()) (id:'cancel', txt: 'Cancel', exec: => @editor.focus()) (id:'yes', txt: 'Save all', highlight: true, exec: => @editor.saveAll => cb()) ] return true onStartupData: (data) -> @startupData = data @editor?.tabs.each (tab) -> @tab.tryLoadStartupData() backupData: -> unsavedData = @editor?.tabs.map (tab) -> url: tab.get 'url' position: tab.session.selection.getCursor() data: tab.session.getValue() scrollTop: tab.session.getScrollTop() scrollLeft: tab.session.getScrollLeft() app.socket.emit 'backup', unsavedData if unsavedData.length openFile: (url, selector=null, index=0, property=null) -> @editor.openFile url, selector, index, property getCurrentFile: -> @editor?.tabs.selectedTab()?.get 'url' isLiveMode: -> !!@project.get 'mode' onResize: -> @outline.onResize() @editor.onResize() onClientConnectedChange: (client) -> @activateConsole() if client.get 'connected' onClientRemoved: (client) -> _.delay => # Wait until client is actually removed. clients = @project.getClients() if clients.length app.router.navigate '' + clients[0].get('session_id'), trigger: true else app.router.navigate '' + @project.id, trigger: true unloadClient: -> if @client @client.off 'change:connected', @onClientConnectedChange, @ @client.off 'remove', @onClientRemoved, @ @clearElementPseudos() @clearClientMedia() @callClient 'setMedia', value: 'screen', -> loadClient: (client) -> @_wasSilentRefresh = false @clientPicker.select client @clientPicker2.select client if client @$('.sidebar').removeClass 'no-clients' else @outline.setTreeData [] @styleInfo.setStyleData 0, [], [] @$('.sidebar').addClass 'no-clients' @unloadClient() @client = client @client?.on 'change:connected', @onClientConnectedChange, @ @client?.on 'remove', @onClientRemoved, @ @renderEmbedMode() @activateConsole() onClientChange: (client) -> return if !client || client?.id == @client?.id app.router.navigate '' + client.get('session_id'), trigger: true @trigger 'change:client' onFocusedSelectorChange: (selector, selectFirst = false) -> @focusedSelector = selector console.log 'selectorchange', selector @elementsForSelector selector, (ids) => console.log 'done' @outline.highlight ids @focusedSelectorElements = ids @outline.select ids[0] if (selectFirst or @state.get('outlineLock')) and ids.length @processFocus() @trigger 'change:focusedselector' processFocus: -> selectedId = @outline.selectedId() dfocus = @$('.editor-info > .selected-rule') dfocus.addClass 'is-visible' dselector = dfocus.find('.selector') dinfo = dfocus.find('.selector-elements') dhint = dfocus.find('.selection-hint') dhintinner = dhint.find('.inner') dselector.empty() dselector.append if @focusedSelector then highlightSelector @focusedSelector else '' haselements = !!@focusedSelectorElements?.length if haselements dinfo.show() dhint.show() index = @focusedSelectorElements.indexOf selectedId key = if ua.isMac then '⌘I' else 'Ctrl-I' if index == -1 dinfo.text @focusedSelectorElements.length + ' element' + (if @focusedSelectorElements.length > 1 then 's' else '') + ' match' + (if @focusedSelectorElements.length > 1 then '' else 'es') dhintinner.text "#{key} to select" dfocus.closest('.infobar').removeClass 'is-binded' else dfocus.closest('.infobar').addClass 'is-binded' if @focusedSelectorElements.length == 1 dinfo.text 'selected' dhint.hide() else dinfo.text "#{index+1} of #{@focusedSelectorElements.length}" dhintinner.text "#{key} for next" else dinfo.text 'No elements match' dhint.hide() dinfo.hide() dfocus.closest('.infobar').removeClass 'is-binded' unless @focusedSelector dfocus.removeClass 'visible' dfocus.closest('.infobar').removeClass 'is-binded' selectFocusedSelectorElement: (reverse=false) -> return unless @focusedSelector && @focusedSelectorElements?.length index = @focusedSelectorElements.indexOf @outline.selectedId() if index == -1 || @focusedSelectorElements.length == 1 @outline.select @focusedSelectorElements[0] else if reverse then index-- else index++ index = @focusedSelectorElements.length - 1 if index < 0 index = 0 if index >= @focusedSelectorElements.length @outline.select @focusedSelectorElements[index] onElementSelected: (i) -> @serializeElement i.id, (selector) => @state.save selectedItem: selector or null @trigger 'load:selector', i.id, selector @selector = selector @getStyles i.id if (@_wasSelectFromInspect && !@state.get 'leftPaneVisible') || i.openFirst @styleInfo.openStyleAtIndex 0 @_wasSelectFromInspect = false @callClient 'showInspectArea', id: i.id unless @_dontInspectOutline @_dontInspectOutline = false @processFocus() onOutlineLoaded: -> @initPseudos -> @initFolds => if (selectedItem = @state.get 'selectedItem') != null @unserializeElement selectedItem, (id) => if id == -1 && @_wasSilentRefresh == true @callClient 'getLastStyledElement', {}, (resp) => @selectElement resp.lastStyledElement else @selectElement id else @selectElement -1 selectElement: (elementId) -> @_dontInspectOutline = true if elementId != -1 @outline.select elementId, false else @outline.selectAt 0 @outline.restoreScrollPosition() serializeElement: (elementId, cb) -> @callClient 'serializeElement', id: elementId, (resp) -> cb resp unserializeElement: (selector, cb) -> @callClient 'unserializeElement', selector, (resp) -> cb if resp then resp.id else -1 selectParentAtIndex: (index) -> @outline.selectParent index if index elementsForSelector: (selector, cb) -> if @client @callClient 'elementsForSelector', selector:selector, (data) -> cb data.ids else _.defer -> cb null getStyles: (id) -> @callClient 'getStyles', id: id, (resp) => @styleInfo.selectedElement = id @styleInfo.setStyleData id, resp.styles, resp.nearby, @selector rules = ([sdata.file, sdata.selector] for sdata in resp.styles when sdata.file) @trigger 'load:styles', id, rules @processFocus() @editor.highlight rules @$el.removeClass 'no-client-loaded' onStylesChanged: (data) -> if @styleInfo.selectedElement == data.id @serializeElement data.id, (selector) => @styleInfo.setStyleData data.id, data.styles, data.nearby, selector getMedia: -> @media || 'screen' setMedia: (@media) -> @trigger 'change:media' @callClient 'setMedia', {value: @media}, -> clearClientMedia: -> @callClient 'setMedia', {value: 'screen'}, -> ## Fake pseudo-classes management. initPseudos: (cb) -> unless @pseudos @pseudos = new PseudoList null, backend: 'pseudos-' + @project.id @pseudos.on 'change', (pseudo) => @trigger 'change:pseudo', pseudo @pseudos.fetch success: => return cb() unless @pseudos.size() parallel @pseudos.toArray(), (pseudo, done) => @unserializeElement pseudo.get('selector'), (id) => if id == -1 || !pseudo.get('pseudos').length pseudo.destroy() else pseudo.elementId = id @trigger 'change:pseudo', pseudo done() , => cb() setPseudoValue: (id, dataClass, bool) -> pseudo = @pseudos.find (p) -> p.elementId == id if pseudo classes = pseudo.get('pseudos') bool ?= !_.include classes, dataClass if bool pseudo.save pseudos: _.union classes, dataClass else pseudo.save pseudos: _.without classes, dataClass else if bool != false @serializeElement id, (data) => @pseudos.create (selector: data, pseudos: [dataClass]), wait: true, success: (pseudo) => pseudo.elementId = id @trigger 'change:pseudo', pseudo setElementPseudo: (id, pseudos) -> @callClient 'setElementPseudo', id: id, pseudos: pseudos, => @getStyles @outline.selectedId() clearElementPseudos: -> @callClient 'clearPseudos', {}, -> ## Outline folds management. initFolds: (cb) -> @folds = new FoldList null, backend: 'folds-' + @project.id @folds.fetch success: => return cb() unless @folds.size() parallel @folds.toArray(), (f, done) => @unserializeElement f.toJSON(), (id) => if id == -1 f.destroy() else if -1 != index = @outline.getIndex id if f.get('type') == 'fold' @outline.foldAt index, true else @outline.unfoldAt index, true done() , cb getFold: (data) -> @folds.find (f) -> data && data.selector == f.get('selector') and data.length == f.get('length') and data.index == f.get('index') onFold: (item) -> @serializeElement item.id, (data) => if data && !@getFold data data.type = 'fold' @folds.create data onUnfold: (item) -> @serializeElement item.id, (data) => if data if f = @getFold data f?.destroy() else data.type = 'unfold' @folds.create data callAPI: (name, params, cb) -> return unless @active app.socket.emit 'callAPI', name, params, cb callClient: (name, param, cb) -> return unless @client?.get 'connected' if @usesPostMessage @callClientPostMessage name, param, cb else app.socket.emit 'callclient', @client.id, name, param, cb callClientPostMessage: (name, param, cb) -> window.opener?.postMessage? (name: name, param: param, callbackId: @getPostMessageId cb), @project.get('baseurl') getPostMessageId: do -> callbacks = {} receive = (e) -> data = e.data return if data?.name != 'messageResponse' id = data?.callbackId if id [func, view] = callbacks[id] func? data.data if (view.project.get('baseurl').indexOf e.origin) == 0 window.addEventListener 'message', receive, false (func) -> id = ~~ (Math.random() * 1e8) # TODO: Remove passing in view. callbacks[id] = [func, this] return id onClientMessage: (name, data) -> switch name when 'inspect' @onInspectorResult data when 'change:styles' @onStylesChanged data when 'change:dom' @_wasSilentRefresh = true @outline.setTreeData data.tree when 'change:media' @setMedia data.media module.exports = ConsoleView
78810
define (require, exports, module) -> TreeOutline = require 'lib/views/ui/treeoutline' StyleInfo = require 'lib/views/ui/styleinfo' OutlineInfo = require 'lib/views/outlineinfo' OutputSwitch = require 'lib/views/outputswitch' Resizer = require 'lib/views/ui/resizer' {StateList, FoldList, PseudoList} = require 'lib/models' {node, highlightSelector, swapNodes, parallel} = require 'lib/utils' {addMouseWheelListener, stopEvent} = require 'ace/lib/event' {addKeyboardListener, listenKey} = require 'lib/keyboard' ua = require 'ace/lib/useragent' ConsoleView = Backbone.View.extend className: 'app' template: require 'lib/templates/console' events: 'click .tool-back': 'showProjectList' 'click .tool-settings': 'showSettings' 'click .tool-refresh': 'reloadOutline' 'click .tool-identify': 'identifyClient' 'click .tool-inspect': 'startInspector' 'click .tool-edit': 'editProject' 'click .tool-embed': 'toggleApplicationMode' 'click .tool-sidebyside': 'toggleIframeMode' initialize: (opt) -> _.bindAll @, 'onResize', 'toggleApplicationMode', 'onBeforeUnload', 'onConsoleDeactivated', 'onConsoleActivated', 'onClientMessage', 'toggleInfobar', 'onStartupData', 'toggleUpdateMode', 'toggleTabSettings', 'toggleSidebar', 'onInspectorResult', 'onElementSelected', 'onEmbedMessage' app.console = @ @usesPostMessage = false app.socket.on 'activate', @onConsoleActivated app.socket.on 'deactivate', @onConsoleDeactivated app.socket.on 'clientmessage', @onClientMessage app.socket.on 'startupdata', @onStartupData @project = opt.project @project.on 'clients:add', (client) => @loadClient client if @project.getClients().length == 1 && !@client # Embed detection. if self != top window.addEventListener 'message', @onEmbedMessage , false top.postMessage 'getEmbedMode', '*' # Keyboard commands. addKeyboardListener 'global', window listenKey null, 'toggle-window-mode', exec: @toggleApplicationMode listenKey null, 'toggle-iframe-container', exec: => @callClient 'toggleIframe', {} listenKey null, 'focus-tree', exec: => @outline.el.focus() listenKey null, 'focus-styleinfo', exec: => @styleInfo.el.focus() listenKey null, 'focus-editor', exec: => @editor.focus() listenKey null, 'focus-clientswitch', exec: => @clientPicker.el.focus() listenKey null, 'settings', exec: => @showSettings() listenKey null, 'select-focused-selector', exec: => @selectFocusedSelectorElement() listenKey null, 'select-focused-selector-reverse', exec: => @selectFocusedSelectorElement true listenKey null, 'back-to-project-list', exec: => @showProjectList() listenKey null, 'toggle-infobar', exec: @toggleInfobar listenKey null, 'toggle-update-mode', exec: @toggleUpdateMode listenKey null, 'toggle-tab-mode', exec: @toggleTabSettings listenKey null, 'toggle-left-pane', exec: @toggleSidebar # Make DOM elements and subviews. @$el.html(@template).addClass 'no-client-loaded' @clientPicker = new OutputSwitch model: @project, el: @$('.client-select-sidebar')[0] @clientPicker.on 'change', @onClientChange, @ @clientPicker2 = new OutputSwitch model: @project, el: @$('.client-select-toolbar')[0] @clientPicker2.on 'change', @onClientChange, @ @outline = new TreeOutline el: @$('.elements-outline')[0] @outline.on 'load', @onOutlineLoaded, @ @outline.on 'select', _.throttle (_.bind @onElementSelected), 300 @outline.on 'fold', @onFold, @ @outline.on 'unfold', @onUnfold, @ @outline.on 'focus:styleinfo', => @styleInfo.el.focus() @styleInfo.moveHighlight 1 unless @styleInfo.highlightElement? @styleInfo = new StyleInfo el: @$('.styleinfo')[0] @styleInfo.on 'open', @openFile, @ @styleInfo.on 'focus:outline', => @outline.el.focus() @outlineInfo = new OutlineInfo el: @$('.infobar-outline')[0] @on 'change:pseudo', (pseudo) => @setElementPseudo pseudo.elementId, pseudo.get('pseudos') (new Resizer el: @$('.resizer-vertical')[0], name: 'vresizer', target: @$('.styleinfo')[0]) .on 'resize', @onResize (new Resizer el: @$('.resizer-horizontal')[0], name: 'hresizer', target: @$('.sidebar')[0]) .on 'resize', @onResize swapNodes @$('.sidebar')[0], @$('.main-content')[0] if app.Settings.get 'sidebar_right' @$('.sidebar-toggle').on 'click', @toggleSidebar baseUrl = @project.get 'baseurl' @$('.no-clients-fallback .url').text(baseUrl) .on 'click', -> window.open baseUrl @loadClient opt.client # Disable elastic scrolling + back swiping. $(document.body).addClass 'no-scrolling' addMouseWheelListener document, (e) -> stopEvent e if e.wheelX != 0 # Page unload control. $(window).on 'beforeunload', @onBeforeUnload if !ua.isGecko @captureCommandStart = _.bind @captureCommandKey, @, false @captureCommandEnd = _.bind @captureCommandKey, @, true window.addEventListener 'keydown', @captureCommandStart, true window.addEventListener 'keyup', @captureCommandEnd, true Backbone.history.onbeforeunload = => block = @checkUnsavedFiles => Backbone.history.onbeforeunload = null window.history.back() if block # Add ID to the title so extensions can use it for focus switching. oldTitle = document.title.replace /\s?\(\d+\)$/, '' document.title = oldTitle + " (#{@project.id})" tm('console') # Load defer components. _.delay -> require ['lib/editor/statsmanager'], (stats) -> app.stats = stats , 1000 if app.Settings.get 'fpsstats' require ['vendor/stats'], => stats = new Stats() statsElement = stats.getDomElement() $(statsElement).addClass 'fpsstats' @$el.append statsElement setInterval -> stats.update() , 1000 / 60 _.delay => require ['lib/views/commandline'], (CommandLine) => new CommandLine el: @$('.cli-container')[0] , 1000 activateConsole: -> tm('activateConsole') app.socket.emit 'activate', @project.id, @client?.id if @state @initState() else states = new StateList null, backend: 'state-' + @project.id if __data.states states.reset __data.states @state = states.at 0 console.log @state @initState() __data.states = null else states.fetch success: => @state = states.at(0) @initState() initState: -> tm('initstate') sp = @state.get 'scrollPos' @outline.scrollPosition = sp if sp # TODO: just plain wrong to do it this way. # TODO: these need localStorage fallbacks to avoid flicker. @state.on 'change:infobarVisible', @renderInforbarVisibility, @ @renderInforbarVisibility() @state.on 'change:outlineLock', @renderFocusLocking, @ @renderFocusLocking() @state.on 'change:leftPaneVisible', @renderSidebarVisibility, @ @renderSidebarVisibility() _.defer => require ['lib/views/editor'], (EditorView) => tm('editorload') unless @editor @editor = new EditorView el: @$('.editor-container')[0] @editor.on 'change:focusedselector', @onFocusedSelectorChange, @ @$('.infobar-toggle').on 'click', @toggleInfobar @$('.locking-toggle').on 'click', => @state.save outlineLock: !@state.get 'outlineLock' @usesPostMessage = false @callClientPostMessage 'getSessionId', {}, (resp) => if parseInt(resp.sessionId, 10) == @client.get 'session_id' @usesPostMessage = true _.delay => @reloadOutline() if @getMedia() != 'screen' @callClient 'setMedia', {value: @getMedia()}, -> @trigger 'change:media' , 50 onConsoleActivated: -> tm('activated') @active = true onConsoleDeactivated: -> @backupData() @active = false require ['lib/views/warning-screen'], (WarningScreen) => top.postMessage 'close-iframe', '*' if @embed new WarningScreen name: 'warning_overload' @destroy() destroy: -> @unloadClient() app.socket.emit 'deactivate' if @active app.socket.removeListener 'activate', @onConsoleActivated app.socket.removeListener 'deactivate', @onConsoleDeactivated app.socket.removeListener 'clientmessage', @onClientMessage app.socket.removeListener 'startupdata', @onStartupData $(document.body).removeClass 'no-scrolling' $(window).off 'beforeunload', @onBeforeUnload window.removeEventListener 'keydown', @captureCommandStart, true window.removeEventListener 'keyup', @captureCommandEnd, true document.title = '' + document.title.replace /\s*?\(\d+\)$/, '' @editor?.destroy() app.console = null toggleSidebar: -> @state.save leftPaneVisible: !@state.get 'leftPaneVisible' _.delay => @editor.onResize() , 1000 toggleInfobar: -> @state.save infobarVisible: !@state.get 'infobarVisible' toggleUpdateMode: -> @project.save mode: (if @project.get('mode') then 0 else 1) toggleTabSettings: -> tabSize = @project.get 'tabSize' softTabs = @project.get 'softTabs' switch tabSize when 2 then tabSize = 3 when 3 then tabSize = 4 when 4 then tabSize = 8 when 8 tabSize = 2 softTabs = !softTabs @project.save tabSize: tabSize, softTabs: softTabs toggleApplicationMode: -> @callClient 'toggleApplicationMode', null, -> window.close() toggleIframeMode: -> top.postMessage 'toggleIframeMode', '*' if @embed onEmbedMessage: (e) -> if e.data.embedInfo if e.data.iframeMode @embedSideBySide = e.data.iframeMode == 'sidebyside' if e.data.baseURL @embed = e.data.baseURL == @project.get('baseurl') @renderEmbedMode() renderEmbedMode: -> if @embed @$('.tool-embed').addClass 'is-selected' @$('.tool-sidebyside').show().toggleClass 'is-selected', !!@embedSideBySide else @$('.tool-embed').toggle @client && @client.get('embed') @$('.tool-sidebyside').hide() renderInforbarVisibility: -> @$el.toggleClass 'has-infobar', @state.get 'infobarVisible' renderFocusLocking: -> @$('.locking-toggle').toggleClass 'is-locked', @state.get 'outlineLock' renderSidebarVisibility: -> leftPaneVisible = @state.get 'leftPaneVisible' @$el .toggleClass('no-sidebar', !leftPaneVisible) .toggleClass('has-sidebar', leftPaneVisible) showProjectList: -> @checkUnsavedFiles => if @client?.get('project') app.router.navigate 'project/' + @client.get('project'), trigger: true else app.router.navigate '', trigger: true editProject: -> @checkUnsavedFiles => app.router.navigate 'edit/' + @project.id, trigger: true startInspector: -> @callClient 'startInspector', {}, @onInspectorResult window.opener?.focus() if @usesPostMessage app.socket.emit 'callClient', @client.id, 'focus' onInspectorResult: (data) -> @_dontInspectOutline = true @_wasSelectFromInspect = true @outline.select data.id app.socket.emit 'callClient', @client.id, 'focus', title: @project.id showSettings: -> app.app.showSettings() identifyClient: -> @callClient 'identify', msg: @client.get('useragent'), -> app.socket.emit 'callclient', @client.id, 'focus' reloadOutline: -> tm('reload') @callClient 'getDOMTree', {}, (data) => @_wasSilentRefresh = false @outline.setTreeData data.tree tm('treedata') captureCommandKey: (release, e) -> if e.keyCode == (if ua.isMac then 91 else 17) @iscommandkey = !release else if e.keyCode == 87 @iswkey = !release else if e.keyCode == 16 @isshiftkey = !release onBeforeUnload: (e) -> confirm_keyboard_close = app.Settings.get 'confirm_keyboard_close' if @iscommandkey && confirm_keyboard_close && @editor.tabs.size() && !@isshiftkey @iscommandkey = false return [ 'Possibly incorrect action was detected! Closing editor tabs with' if ua.isMac then ' ⌘W' else 'Ctrl-W' 'is not supported by your browser. Use alternative keyboard command' if ua.isMac then '⌃W' else 'Alt-W' 'instead. If you like the default behaviour of your browser you can turn off this message from the settings or include Shift key in your command.'].join ' ' confirm_unsaved_close = app.Settings.get 'confirm_unsaved_close' unsavedTabs = @editor.getUnsavedTabs() return unless unsavedTabs.length && confirm_unsaved_close fileNames = _.map unsavedTabs, (tab) -> tab.get 'name' 'You have unsaved changes in file(s): ' + fileNames.join(', ') + '. Closing the window will destroy the changes.' checkUnsavedFiles: (cb) -> confirmUnsavedClose = app.Settings.get 'confirm_unsaved_close' return unless @editor unsaved = @editor.getUnsavedTabs() unless unsaved.length && confirmUnsavedClose cb() return false names = _.map unsaved, (tab) -> tab.get 'name' require ['lib/views/ui/popup'], (Popup) => new Popup msg: 'You have unsaved changes in file(s): ' + names.join(', ') + '. Do you want to save those changes?' buttons: [ (id:'no', txt: 'Don\'t save', exec: => cb()) (id:'cancel', txt: 'Cancel', exec: => @editor.focus()) (id:'yes', txt: 'Save all', highlight: true, exec: => @editor.saveAll => cb()) ] return true onStartupData: (data) -> @startupData = data @editor?.tabs.each (tab) -> @tab.tryLoadStartupData() backupData: -> unsavedData = @editor?.tabs.map (tab) -> url: tab.get 'url' position: tab.session.selection.getCursor() data: tab.session.getValue() scrollTop: tab.session.getScrollTop() scrollLeft: tab.session.getScrollLeft() app.socket.emit 'backup', unsavedData if unsavedData.length openFile: (url, selector=null, index=0, property=null) -> @editor.openFile url, selector, index, property getCurrentFile: -> @editor?.tabs.selectedTab()?.get 'url' isLiveMode: -> !!@project.get 'mode' onResize: -> @outline.onResize() @editor.onResize() onClientConnectedChange: (client) -> @activateConsole() if client.get 'connected' onClientRemoved: (client) -> _.delay => # Wait until client is actually removed. clients = @project.getClients() if clients.length app.router.navigate '' + clients[0].get('session_id'), trigger: true else app.router.navigate '' + @project.id, trigger: true unloadClient: -> if @client @client.off 'change:connected', @onClientConnectedChange, @ @client.off 'remove', @onClientRemoved, @ @clearElementPseudos() @clearClientMedia() @callClient 'setMedia', value: 'screen', -> loadClient: (client) -> @_wasSilentRefresh = false @clientPicker.select client @clientPicker2.select client if client @$('.sidebar').removeClass 'no-clients' else @outline.setTreeData [] @styleInfo.setStyleData 0, [], [] @$('.sidebar').addClass 'no-clients' @unloadClient() @client = client @client?.on 'change:connected', @onClientConnectedChange, @ @client?.on 'remove', @onClientRemoved, @ @renderEmbedMode() @activateConsole() onClientChange: (client) -> return if !client || client?.id == @client?.id app.router.navigate '' + client.get('session_id'), trigger: true @trigger 'change:client' onFocusedSelectorChange: (selector, selectFirst = false) -> @focusedSelector = selector console.log 'selectorchange', selector @elementsForSelector selector, (ids) => console.log 'done' @outline.highlight ids @focusedSelectorElements = ids @outline.select ids[0] if (selectFirst or @state.get('outlineLock')) and ids.length @processFocus() @trigger 'change:focusedselector' processFocus: -> selectedId = @outline.selectedId() dfocus = @$('.editor-info > .selected-rule') dfocus.addClass 'is-visible' dselector = dfocus.find('.selector') dinfo = dfocus.find('.selector-elements') dhint = dfocus.find('.selection-hint') dhintinner = dhint.find('.inner') dselector.empty() dselector.append if @focusedSelector then highlightSelector @focusedSelector else '' haselements = !!@focusedSelectorElements?.length if haselements dinfo.show() dhint.show() index = @focusedSelectorElements.indexOf selectedId key = if ua.isMac then '<KEY> else '<KEY>' if index == -1 dinfo.text @focusedSelectorElements.length + ' element' + (if @focusedSelectorElements.length > 1 then 's' else '') + ' match' + (if @focusedSelectorElements.length > 1 then '' else 'es') dhintinner.text "#{key} to select" dfocus.closest('.infobar').removeClass 'is-binded' else dfocus.closest('.infobar').addClass 'is-binded' if @focusedSelectorElements.length == 1 dinfo.text 'selected' dhint.hide() else dinfo.text "#{index+1} of #{@focusedSelectorElements.length}" dhintinner.text "#{key} for next" else dinfo.text 'No elements match' dhint.hide() dinfo.hide() dfocus.closest('.infobar').removeClass 'is-binded' unless @focusedSelector dfocus.removeClass 'visible' dfocus.closest('.infobar').removeClass 'is-binded' selectFocusedSelectorElement: (reverse=false) -> return unless @focusedSelector && @focusedSelectorElements?.length index = @focusedSelectorElements.indexOf @outline.selectedId() if index == -1 || @focusedSelectorElements.length == 1 @outline.select @focusedSelectorElements[0] else if reverse then index-- else index++ index = @focusedSelectorElements.length - 1 if index < 0 index = 0 if index >= @focusedSelectorElements.length @outline.select @focusedSelectorElements[index] onElementSelected: (i) -> @serializeElement i.id, (selector) => @state.save selectedItem: selector or null @trigger 'load:selector', i.id, selector @selector = selector @getStyles i.id if (@_wasSelectFromInspect && !@state.get 'leftPaneVisible') || i.openFirst @styleInfo.openStyleAtIndex 0 @_wasSelectFromInspect = false @callClient 'showInspectArea', id: i.id unless @_dontInspectOutline @_dontInspectOutline = false @processFocus() onOutlineLoaded: -> @initPseudos -> @initFolds => if (selectedItem = @state.get 'selectedItem') != null @unserializeElement selectedItem, (id) => if id == -1 && @_wasSilentRefresh == true @callClient 'getLastStyledElement', {}, (resp) => @selectElement resp.lastStyledElement else @selectElement id else @selectElement -1 selectElement: (elementId) -> @_dontInspectOutline = true if elementId != -1 @outline.select elementId, false else @outline.selectAt 0 @outline.restoreScrollPosition() serializeElement: (elementId, cb) -> @callClient 'serializeElement', id: elementId, (resp) -> cb resp unserializeElement: (selector, cb) -> @callClient 'unserializeElement', selector, (resp) -> cb if resp then resp.id else -1 selectParentAtIndex: (index) -> @outline.selectParent index if index elementsForSelector: (selector, cb) -> if @client @callClient 'elementsForSelector', selector:selector, (data) -> cb data.ids else _.defer -> cb null getStyles: (id) -> @callClient 'getStyles', id: id, (resp) => @styleInfo.selectedElement = id @styleInfo.setStyleData id, resp.styles, resp.nearby, @selector rules = ([sdata.file, sdata.selector] for sdata in resp.styles when sdata.file) @trigger 'load:styles', id, rules @processFocus() @editor.highlight rules @$el.removeClass 'no-client-loaded' onStylesChanged: (data) -> if @styleInfo.selectedElement == data.id @serializeElement data.id, (selector) => @styleInfo.setStyleData data.id, data.styles, data.nearby, selector getMedia: -> @media || 'screen' setMedia: (@media) -> @trigger 'change:media' @callClient 'setMedia', {value: @media}, -> clearClientMedia: -> @callClient 'setMedia', {value: 'screen'}, -> ## Fake pseudo-classes management. initPseudos: (cb) -> unless @pseudos @pseudos = new PseudoList null, backend: 'pseudos-' + @project.id @pseudos.on 'change', (pseudo) => @trigger 'change:pseudo', pseudo @pseudos.fetch success: => return cb() unless @pseudos.size() parallel @pseudos.toArray(), (pseudo, done) => @unserializeElement pseudo.get('selector'), (id) => if id == -1 || !pseudo.get('pseudos').length pseudo.destroy() else pseudo.elementId = id @trigger 'change:pseudo', pseudo done() , => cb() setPseudoValue: (id, dataClass, bool) -> pseudo = @pseudos.find (p) -> p.elementId == id if pseudo classes = pseudo.get('pseudos') bool ?= !_.include classes, dataClass if bool pseudo.save pseudos: _.union classes, dataClass else pseudo.save pseudos: _.without classes, dataClass else if bool != false @serializeElement id, (data) => @pseudos.create (selector: data, pseudos: [dataClass]), wait: true, success: (pseudo) => pseudo.elementId = id @trigger 'change:pseudo', pseudo setElementPseudo: (id, pseudos) -> @callClient 'setElementPseudo', id: id, pseudos: pseudos, => @getStyles @outline.selectedId() clearElementPseudos: -> @callClient 'clearPseudos', {}, -> ## Outline folds management. initFolds: (cb) -> @folds = new FoldList null, backend: 'folds-' + @project.id @folds.fetch success: => return cb() unless @folds.size() parallel @folds.toArray(), (f, done) => @unserializeElement f.toJSON(), (id) => if id == -1 f.destroy() else if -1 != index = @outline.getIndex id if f.get('type') == 'fold' @outline.foldAt index, true else @outline.unfoldAt index, true done() , cb getFold: (data) -> @folds.find (f) -> data && data.selector == f.get('selector') and data.length == f.get('length') and data.index == f.get('index') onFold: (item) -> @serializeElement item.id, (data) => if data && !@getFold data data.type = 'fold' @folds.create data onUnfold: (item) -> @serializeElement item.id, (data) => if data if f = @getFold data f?.destroy() else data.type = 'unfold' @folds.create data callAPI: (name, params, cb) -> return unless @active app.socket.emit 'callAPI', name, params, cb callClient: (name, param, cb) -> return unless @client?.get 'connected' if @usesPostMessage @callClientPostMessage name, param, cb else app.socket.emit 'callclient', @client.id, name, param, cb callClientPostMessage: (name, param, cb) -> window.opener?.postMessage? (name: name, param: param, callbackId: @getPostMessageId cb), @project.get('baseurl') getPostMessageId: do -> callbacks = {} receive = (e) -> data = e.data return if data?.name != 'messageResponse' id = data?.callbackId if id [func, view] = callbacks[id] func? data.data if (view.project.get('baseurl').indexOf e.origin) == 0 window.addEventListener 'message', receive, false (func) -> id = ~~ (Math.random() * 1e8) # TODO: Remove passing in view. callbacks[id] = [func, this] return id onClientMessage: (name, data) -> switch name when 'inspect' @onInspectorResult data when 'change:styles' @onStylesChanged data when 'change:dom' @_wasSilentRefresh = true @outline.setTreeData data.tree when 'change:media' @setMedia data.media module.exports = ConsoleView
true
define (require, exports, module) -> TreeOutline = require 'lib/views/ui/treeoutline' StyleInfo = require 'lib/views/ui/styleinfo' OutlineInfo = require 'lib/views/outlineinfo' OutputSwitch = require 'lib/views/outputswitch' Resizer = require 'lib/views/ui/resizer' {StateList, FoldList, PseudoList} = require 'lib/models' {node, highlightSelector, swapNodes, parallel} = require 'lib/utils' {addMouseWheelListener, stopEvent} = require 'ace/lib/event' {addKeyboardListener, listenKey} = require 'lib/keyboard' ua = require 'ace/lib/useragent' ConsoleView = Backbone.View.extend className: 'app' template: require 'lib/templates/console' events: 'click .tool-back': 'showProjectList' 'click .tool-settings': 'showSettings' 'click .tool-refresh': 'reloadOutline' 'click .tool-identify': 'identifyClient' 'click .tool-inspect': 'startInspector' 'click .tool-edit': 'editProject' 'click .tool-embed': 'toggleApplicationMode' 'click .tool-sidebyside': 'toggleIframeMode' initialize: (opt) -> _.bindAll @, 'onResize', 'toggleApplicationMode', 'onBeforeUnload', 'onConsoleDeactivated', 'onConsoleActivated', 'onClientMessage', 'toggleInfobar', 'onStartupData', 'toggleUpdateMode', 'toggleTabSettings', 'toggleSidebar', 'onInspectorResult', 'onElementSelected', 'onEmbedMessage' app.console = @ @usesPostMessage = false app.socket.on 'activate', @onConsoleActivated app.socket.on 'deactivate', @onConsoleDeactivated app.socket.on 'clientmessage', @onClientMessage app.socket.on 'startupdata', @onStartupData @project = opt.project @project.on 'clients:add', (client) => @loadClient client if @project.getClients().length == 1 && !@client # Embed detection. if self != top window.addEventListener 'message', @onEmbedMessage , false top.postMessage 'getEmbedMode', '*' # Keyboard commands. addKeyboardListener 'global', window listenKey null, 'toggle-window-mode', exec: @toggleApplicationMode listenKey null, 'toggle-iframe-container', exec: => @callClient 'toggleIframe', {} listenKey null, 'focus-tree', exec: => @outline.el.focus() listenKey null, 'focus-styleinfo', exec: => @styleInfo.el.focus() listenKey null, 'focus-editor', exec: => @editor.focus() listenKey null, 'focus-clientswitch', exec: => @clientPicker.el.focus() listenKey null, 'settings', exec: => @showSettings() listenKey null, 'select-focused-selector', exec: => @selectFocusedSelectorElement() listenKey null, 'select-focused-selector-reverse', exec: => @selectFocusedSelectorElement true listenKey null, 'back-to-project-list', exec: => @showProjectList() listenKey null, 'toggle-infobar', exec: @toggleInfobar listenKey null, 'toggle-update-mode', exec: @toggleUpdateMode listenKey null, 'toggle-tab-mode', exec: @toggleTabSettings listenKey null, 'toggle-left-pane', exec: @toggleSidebar # Make DOM elements and subviews. @$el.html(@template).addClass 'no-client-loaded' @clientPicker = new OutputSwitch model: @project, el: @$('.client-select-sidebar')[0] @clientPicker.on 'change', @onClientChange, @ @clientPicker2 = new OutputSwitch model: @project, el: @$('.client-select-toolbar')[0] @clientPicker2.on 'change', @onClientChange, @ @outline = new TreeOutline el: @$('.elements-outline')[0] @outline.on 'load', @onOutlineLoaded, @ @outline.on 'select', _.throttle (_.bind @onElementSelected), 300 @outline.on 'fold', @onFold, @ @outline.on 'unfold', @onUnfold, @ @outline.on 'focus:styleinfo', => @styleInfo.el.focus() @styleInfo.moveHighlight 1 unless @styleInfo.highlightElement? @styleInfo = new StyleInfo el: @$('.styleinfo')[0] @styleInfo.on 'open', @openFile, @ @styleInfo.on 'focus:outline', => @outline.el.focus() @outlineInfo = new OutlineInfo el: @$('.infobar-outline')[0] @on 'change:pseudo', (pseudo) => @setElementPseudo pseudo.elementId, pseudo.get('pseudos') (new Resizer el: @$('.resizer-vertical')[0], name: 'vresizer', target: @$('.styleinfo')[0]) .on 'resize', @onResize (new Resizer el: @$('.resizer-horizontal')[0], name: 'hresizer', target: @$('.sidebar')[0]) .on 'resize', @onResize swapNodes @$('.sidebar')[0], @$('.main-content')[0] if app.Settings.get 'sidebar_right' @$('.sidebar-toggle').on 'click', @toggleSidebar baseUrl = @project.get 'baseurl' @$('.no-clients-fallback .url').text(baseUrl) .on 'click', -> window.open baseUrl @loadClient opt.client # Disable elastic scrolling + back swiping. $(document.body).addClass 'no-scrolling' addMouseWheelListener document, (e) -> stopEvent e if e.wheelX != 0 # Page unload control. $(window).on 'beforeunload', @onBeforeUnload if !ua.isGecko @captureCommandStart = _.bind @captureCommandKey, @, false @captureCommandEnd = _.bind @captureCommandKey, @, true window.addEventListener 'keydown', @captureCommandStart, true window.addEventListener 'keyup', @captureCommandEnd, true Backbone.history.onbeforeunload = => block = @checkUnsavedFiles => Backbone.history.onbeforeunload = null window.history.back() if block # Add ID to the title so extensions can use it for focus switching. oldTitle = document.title.replace /\s?\(\d+\)$/, '' document.title = oldTitle + " (#{@project.id})" tm('console') # Load defer components. _.delay -> require ['lib/editor/statsmanager'], (stats) -> app.stats = stats , 1000 if app.Settings.get 'fpsstats' require ['vendor/stats'], => stats = new Stats() statsElement = stats.getDomElement() $(statsElement).addClass 'fpsstats' @$el.append statsElement setInterval -> stats.update() , 1000 / 60 _.delay => require ['lib/views/commandline'], (CommandLine) => new CommandLine el: @$('.cli-container')[0] , 1000 activateConsole: -> tm('activateConsole') app.socket.emit 'activate', @project.id, @client?.id if @state @initState() else states = new StateList null, backend: 'state-' + @project.id if __data.states states.reset __data.states @state = states.at 0 console.log @state @initState() __data.states = null else states.fetch success: => @state = states.at(0) @initState() initState: -> tm('initstate') sp = @state.get 'scrollPos' @outline.scrollPosition = sp if sp # TODO: just plain wrong to do it this way. # TODO: these need localStorage fallbacks to avoid flicker. @state.on 'change:infobarVisible', @renderInforbarVisibility, @ @renderInforbarVisibility() @state.on 'change:outlineLock', @renderFocusLocking, @ @renderFocusLocking() @state.on 'change:leftPaneVisible', @renderSidebarVisibility, @ @renderSidebarVisibility() _.defer => require ['lib/views/editor'], (EditorView) => tm('editorload') unless @editor @editor = new EditorView el: @$('.editor-container')[0] @editor.on 'change:focusedselector', @onFocusedSelectorChange, @ @$('.infobar-toggle').on 'click', @toggleInfobar @$('.locking-toggle').on 'click', => @state.save outlineLock: !@state.get 'outlineLock' @usesPostMessage = false @callClientPostMessage 'getSessionId', {}, (resp) => if parseInt(resp.sessionId, 10) == @client.get 'session_id' @usesPostMessage = true _.delay => @reloadOutline() if @getMedia() != 'screen' @callClient 'setMedia', {value: @getMedia()}, -> @trigger 'change:media' , 50 onConsoleActivated: -> tm('activated') @active = true onConsoleDeactivated: -> @backupData() @active = false require ['lib/views/warning-screen'], (WarningScreen) => top.postMessage 'close-iframe', '*' if @embed new WarningScreen name: 'warning_overload' @destroy() destroy: -> @unloadClient() app.socket.emit 'deactivate' if @active app.socket.removeListener 'activate', @onConsoleActivated app.socket.removeListener 'deactivate', @onConsoleDeactivated app.socket.removeListener 'clientmessage', @onClientMessage app.socket.removeListener 'startupdata', @onStartupData $(document.body).removeClass 'no-scrolling' $(window).off 'beforeunload', @onBeforeUnload window.removeEventListener 'keydown', @captureCommandStart, true window.removeEventListener 'keyup', @captureCommandEnd, true document.title = '' + document.title.replace /\s*?\(\d+\)$/, '' @editor?.destroy() app.console = null toggleSidebar: -> @state.save leftPaneVisible: !@state.get 'leftPaneVisible' _.delay => @editor.onResize() , 1000 toggleInfobar: -> @state.save infobarVisible: !@state.get 'infobarVisible' toggleUpdateMode: -> @project.save mode: (if @project.get('mode') then 0 else 1) toggleTabSettings: -> tabSize = @project.get 'tabSize' softTabs = @project.get 'softTabs' switch tabSize when 2 then tabSize = 3 when 3 then tabSize = 4 when 4 then tabSize = 8 when 8 tabSize = 2 softTabs = !softTabs @project.save tabSize: tabSize, softTabs: softTabs toggleApplicationMode: -> @callClient 'toggleApplicationMode', null, -> window.close() toggleIframeMode: -> top.postMessage 'toggleIframeMode', '*' if @embed onEmbedMessage: (e) -> if e.data.embedInfo if e.data.iframeMode @embedSideBySide = e.data.iframeMode == 'sidebyside' if e.data.baseURL @embed = e.data.baseURL == @project.get('baseurl') @renderEmbedMode() renderEmbedMode: -> if @embed @$('.tool-embed').addClass 'is-selected' @$('.tool-sidebyside').show().toggleClass 'is-selected', !!@embedSideBySide else @$('.tool-embed').toggle @client && @client.get('embed') @$('.tool-sidebyside').hide() renderInforbarVisibility: -> @$el.toggleClass 'has-infobar', @state.get 'infobarVisible' renderFocusLocking: -> @$('.locking-toggle').toggleClass 'is-locked', @state.get 'outlineLock' renderSidebarVisibility: -> leftPaneVisible = @state.get 'leftPaneVisible' @$el .toggleClass('no-sidebar', !leftPaneVisible) .toggleClass('has-sidebar', leftPaneVisible) showProjectList: -> @checkUnsavedFiles => if @client?.get('project') app.router.navigate 'project/' + @client.get('project'), trigger: true else app.router.navigate '', trigger: true editProject: -> @checkUnsavedFiles => app.router.navigate 'edit/' + @project.id, trigger: true startInspector: -> @callClient 'startInspector', {}, @onInspectorResult window.opener?.focus() if @usesPostMessage app.socket.emit 'callClient', @client.id, 'focus' onInspectorResult: (data) -> @_dontInspectOutline = true @_wasSelectFromInspect = true @outline.select data.id app.socket.emit 'callClient', @client.id, 'focus', title: @project.id showSettings: -> app.app.showSettings() identifyClient: -> @callClient 'identify', msg: @client.get('useragent'), -> app.socket.emit 'callclient', @client.id, 'focus' reloadOutline: -> tm('reload') @callClient 'getDOMTree', {}, (data) => @_wasSilentRefresh = false @outline.setTreeData data.tree tm('treedata') captureCommandKey: (release, e) -> if e.keyCode == (if ua.isMac then 91 else 17) @iscommandkey = !release else if e.keyCode == 87 @iswkey = !release else if e.keyCode == 16 @isshiftkey = !release onBeforeUnload: (e) -> confirm_keyboard_close = app.Settings.get 'confirm_keyboard_close' if @iscommandkey && confirm_keyboard_close && @editor.tabs.size() && !@isshiftkey @iscommandkey = false return [ 'Possibly incorrect action was detected! Closing editor tabs with' if ua.isMac then ' ⌘W' else 'Ctrl-W' 'is not supported by your browser. Use alternative keyboard command' if ua.isMac then '⌃W' else 'Alt-W' 'instead. If you like the default behaviour of your browser you can turn off this message from the settings or include Shift key in your command.'].join ' ' confirm_unsaved_close = app.Settings.get 'confirm_unsaved_close' unsavedTabs = @editor.getUnsavedTabs() return unless unsavedTabs.length && confirm_unsaved_close fileNames = _.map unsavedTabs, (tab) -> tab.get 'name' 'You have unsaved changes in file(s): ' + fileNames.join(', ') + '. Closing the window will destroy the changes.' checkUnsavedFiles: (cb) -> confirmUnsavedClose = app.Settings.get 'confirm_unsaved_close' return unless @editor unsaved = @editor.getUnsavedTabs() unless unsaved.length && confirmUnsavedClose cb() return false names = _.map unsaved, (tab) -> tab.get 'name' require ['lib/views/ui/popup'], (Popup) => new Popup msg: 'You have unsaved changes in file(s): ' + names.join(', ') + '. Do you want to save those changes?' buttons: [ (id:'no', txt: 'Don\'t save', exec: => cb()) (id:'cancel', txt: 'Cancel', exec: => @editor.focus()) (id:'yes', txt: 'Save all', highlight: true, exec: => @editor.saveAll => cb()) ] return true onStartupData: (data) -> @startupData = data @editor?.tabs.each (tab) -> @tab.tryLoadStartupData() backupData: -> unsavedData = @editor?.tabs.map (tab) -> url: tab.get 'url' position: tab.session.selection.getCursor() data: tab.session.getValue() scrollTop: tab.session.getScrollTop() scrollLeft: tab.session.getScrollLeft() app.socket.emit 'backup', unsavedData if unsavedData.length openFile: (url, selector=null, index=0, property=null) -> @editor.openFile url, selector, index, property getCurrentFile: -> @editor?.tabs.selectedTab()?.get 'url' isLiveMode: -> !!@project.get 'mode' onResize: -> @outline.onResize() @editor.onResize() onClientConnectedChange: (client) -> @activateConsole() if client.get 'connected' onClientRemoved: (client) -> _.delay => # Wait until client is actually removed. clients = @project.getClients() if clients.length app.router.navigate '' + clients[0].get('session_id'), trigger: true else app.router.navigate '' + @project.id, trigger: true unloadClient: -> if @client @client.off 'change:connected', @onClientConnectedChange, @ @client.off 'remove', @onClientRemoved, @ @clearElementPseudos() @clearClientMedia() @callClient 'setMedia', value: 'screen', -> loadClient: (client) -> @_wasSilentRefresh = false @clientPicker.select client @clientPicker2.select client if client @$('.sidebar').removeClass 'no-clients' else @outline.setTreeData [] @styleInfo.setStyleData 0, [], [] @$('.sidebar').addClass 'no-clients' @unloadClient() @client = client @client?.on 'change:connected', @onClientConnectedChange, @ @client?.on 'remove', @onClientRemoved, @ @renderEmbedMode() @activateConsole() onClientChange: (client) -> return if !client || client?.id == @client?.id app.router.navigate '' + client.get('session_id'), trigger: true @trigger 'change:client' onFocusedSelectorChange: (selector, selectFirst = false) -> @focusedSelector = selector console.log 'selectorchange', selector @elementsForSelector selector, (ids) => console.log 'done' @outline.highlight ids @focusedSelectorElements = ids @outline.select ids[0] if (selectFirst or @state.get('outlineLock')) and ids.length @processFocus() @trigger 'change:focusedselector' processFocus: -> selectedId = @outline.selectedId() dfocus = @$('.editor-info > .selected-rule') dfocus.addClass 'is-visible' dselector = dfocus.find('.selector') dinfo = dfocus.find('.selector-elements') dhint = dfocus.find('.selection-hint') dhintinner = dhint.find('.inner') dselector.empty() dselector.append if @focusedSelector then highlightSelector @focusedSelector else '' haselements = !!@focusedSelectorElements?.length if haselements dinfo.show() dhint.show() index = @focusedSelectorElements.indexOf selectedId key = if ua.isMac then 'PI:KEY:<KEY>END_PI else 'PI:KEY:<KEY>END_PI' if index == -1 dinfo.text @focusedSelectorElements.length + ' element' + (if @focusedSelectorElements.length > 1 then 's' else '') + ' match' + (if @focusedSelectorElements.length > 1 then '' else 'es') dhintinner.text "#{key} to select" dfocus.closest('.infobar').removeClass 'is-binded' else dfocus.closest('.infobar').addClass 'is-binded' if @focusedSelectorElements.length == 1 dinfo.text 'selected' dhint.hide() else dinfo.text "#{index+1} of #{@focusedSelectorElements.length}" dhintinner.text "#{key} for next" else dinfo.text 'No elements match' dhint.hide() dinfo.hide() dfocus.closest('.infobar').removeClass 'is-binded' unless @focusedSelector dfocus.removeClass 'visible' dfocus.closest('.infobar').removeClass 'is-binded' selectFocusedSelectorElement: (reverse=false) -> return unless @focusedSelector && @focusedSelectorElements?.length index = @focusedSelectorElements.indexOf @outline.selectedId() if index == -1 || @focusedSelectorElements.length == 1 @outline.select @focusedSelectorElements[0] else if reverse then index-- else index++ index = @focusedSelectorElements.length - 1 if index < 0 index = 0 if index >= @focusedSelectorElements.length @outline.select @focusedSelectorElements[index] onElementSelected: (i) -> @serializeElement i.id, (selector) => @state.save selectedItem: selector or null @trigger 'load:selector', i.id, selector @selector = selector @getStyles i.id if (@_wasSelectFromInspect && !@state.get 'leftPaneVisible') || i.openFirst @styleInfo.openStyleAtIndex 0 @_wasSelectFromInspect = false @callClient 'showInspectArea', id: i.id unless @_dontInspectOutline @_dontInspectOutline = false @processFocus() onOutlineLoaded: -> @initPseudos -> @initFolds => if (selectedItem = @state.get 'selectedItem') != null @unserializeElement selectedItem, (id) => if id == -1 && @_wasSilentRefresh == true @callClient 'getLastStyledElement', {}, (resp) => @selectElement resp.lastStyledElement else @selectElement id else @selectElement -1 selectElement: (elementId) -> @_dontInspectOutline = true if elementId != -1 @outline.select elementId, false else @outline.selectAt 0 @outline.restoreScrollPosition() serializeElement: (elementId, cb) -> @callClient 'serializeElement', id: elementId, (resp) -> cb resp unserializeElement: (selector, cb) -> @callClient 'unserializeElement', selector, (resp) -> cb if resp then resp.id else -1 selectParentAtIndex: (index) -> @outline.selectParent index if index elementsForSelector: (selector, cb) -> if @client @callClient 'elementsForSelector', selector:selector, (data) -> cb data.ids else _.defer -> cb null getStyles: (id) -> @callClient 'getStyles', id: id, (resp) => @styleInfo.selectedElement = id @styleInfo.setStyleData id, resp.styles, resp.nearby, @selector rules = ([sdata.file, sdata.selector] for sdata in resp.styles when sdata.file) @trigger 'load:styles', id, rules @processFocus() @editor.highlight rules @$el.removeClass 'no-client-loaded' onStylesChanged: (data) -> if @styleInfo.selectedElement == data.id @serializeElement data.id, (selector) => @styleInfo.setStyleData data.id, data.styles, data.nearby, selector getMedia: -> @media || 'screen' setMedia: (@media) -> @trigger 'change:media' @callClient 'setMedia', {value: @media}, -> clearClientMedia: -> @callClient 'setMedia', {value: 'screen'}, -> ## Fake pseudo-classes management. initPseudos: (cb) -> unless @pseudos @pseudos = new PseudoList null, backend: 'pseudos-' + @project.id @pseudos.on 'change', (pseudo) => @trigger 'change:pseudo', pseudo @pseudos.fetch success: => return cb() unless @pseudos.size() parallel @pseudos.toArray(), (pseudo, done) => @unserializeElement pseudo.get('selector'), (id) => if id == -1 || !pseudo.get('pseudos').length pseudo.destroy() else pseudo.elementId = id @trigger 'change:pseudo', pseudo done() , => cb() setPseudoValue: (id, dataClass, bool) -> pseudo = @pseudos.find (p) -> p.elementId == id if pseudo classes = pseudo.get('pseudos') bool ?= !_.include classes, dataClass if bool pseudo.save pseudos: _.union classes, dataClass else pseudo.save pseudos: _.without classes, dataClass else if bool != false @serializeElement id, (data) => @pseudos.create (selector: data, pseudos: [dataClass]), wait: true, success: (pseudo) => pseudo.elementId = id @trigger 'change:pseudo', pseudo setElementPseudo: (id, pseudos) -> @callClient 'setElementPseudo', id: id, pseudos: pseudos, => @getStyles @outline.selectedId() clearElementPseudos: -> @callClient 'clearPseudos', {}, -> ## Outline folds management. initFolds: (cb) -> @folds = new FoldList null, backend: 'folds-' + @project.id @folds.fetch success: => return cb() unless @folds.size() parallel @folds.toArray(), (f, done) => @unserializeElement f.toJSON(), (id) => if id == -1 f.destroy() else if -1 != index = @outline.getIndex id if f.get('type') == 'fold' @outline.foldAt index, true else @outline.unfoldAt index, true done() , cb getFold: (data) -> @folds.find (f) -> data && data.selector == f.get('selector') and data.length == f.get('length') and data.index == f.get('index') onFold: (item) -> @serializeElement item.id, (data) => if data && !@getFold data data.type = 'fold' @folds.create data onUnfold: (item) -> @serializeElement item.id, (data) => if data if f = @getFold data f?.destroy() else data.type = 'unfold' @folds.create data callAPI: (name, params, cb) -> return unless @active app.socket.emit 'callAPI', name, params, cb callClient: (name, param, cb) -> return unless @client?.get 'connected' if @usesPostMessage @callClientPostMessage name, param, cb else app.socket.emit 'callclient', @client.id, name, param, cb callClientPostMessage: (name, param, cb) -> window.opener?.postMessage? (name: name, param: param, callbackId: @getPostMessageId cb), @project.get('baseurl') getPostMessageId: do -> callbacks = {} receive = (e) -> data = e.data return if data?.name != 'messageResponse' id = data?.callbackId if id [func, view] = callbacks[id] func? data.data if (view.project.get('baseurl').indexOf e.origin) == 0 window.addEventListener 'message', receive, false (func) -> id = ~~ (Math.random() * 1e8) # TODO: Remove passing in view. callbacks[id] = [func, this] return id onClientMessage: (name, data) -> switch name when 'inspect' @onInspectorResult data when 'change:styles' @onStylesChanged data when 'change:dom' @_wasSilentRefresh = true @outline.setTreeData data.tree when 'change:media' @setMedia data.media module.exports = ConsoleView
[ { "context": " baseUrl,\n json: true,\n auth: {\n username,\n password,\n },\n }\n debug 'get ", "end": 762, "score": 0.98984694480896, "start": 754, "tag": "USERNAME", "value": "username" }, { "context": "lace 'quay.io/', ''\n deployment.deploy...
src/governator-service.coffee
octoblu/deploy-state-util
0
_ = require 'lodash' url = require 'url' async = require 'async' request = require 'request' moment = require 'moment' debug = require('debug')('deploy-state-util:governator-service') class GovernatorService constructor: ({ config }) -> @governators = config['governators'] getStatuses: ({ repo, owner, tag }, callback) => _getStatus = async.apply(@getStatus, { repo, owner, tag }) async.mapValues @governators, _getStatus, callback getStatus: ({ repo, owner, tag }, { hostname, username, password }, cluster, callback) => baseUrl = url.format { hostname: hostname protocol: 'https' slashes: true } options = { uri: '/status', baseUrl, json: true, auth: { username, password, }, } debug 'get governator', options request.get options, (error, response, body) => debug 'got governator', { baseUrl, body, error, statusCode: response?.statusCode } return callback error if error? deploys = _.pickBy body, (value, key) => startsWith = _.startsWith key, "governator:/#{owner}/#{repo}" endsWith = true endsWith = _.endsWith key, ":#{tag}" if tag? return startsWith and endsWith debug 'deploys', deploys callback null, @formatAll deploys formatAll: (deployments) => deployments = _.map deployments, @format deployments = _.sortBy deployments, 'deployAtFull' return deployments format: (deployment) => deployment = _.cloneDeep deployment deployment.deployAtSince = moment.unix(deployment.deployAt).fromNow() [govKey, etcdKey, dockerUrl, tag ] = deployment.key.split(':') slug = dockerUrl.replace 'quay.io/', '' deployment.deploymentKey = "#{slug}:#{tag}" return deployment module.exports = GovernatorService
210794
_ = require 'lodash' url = require 'url' async = require 'async' request = require 'request' moment = require 'moment' debug = require('debug')('deploy-state-util:governator-service') class GovernatorService constructor: ({ config }) -> @governators = config['governators'] getStatuses: ({ repo, owner, tag }, callback) => _getStatus = async.apply(@getStatus, { repo, owner, tag }) async.mapValues @governators, _getStatus, callback getStatus: ({ repo, owner, tag }, { hostname, username, password }, cluster, callback) => baseUrl = url.format { hostname: hostname protocol: 'https' slashes: true } options = { uri: '/status', baseUrl, json: true, auth: { username, password, }, } debug 'get governator', options request.get options, (error, response, body) => debug 'got governator', { baseUrl, body, error, statusCode: response?.statusCode } return callback error if error? deploys = _.pickBy body, (value, key) => startsWith = _.startsWith key, "governator:/#{owner}/#{repo}" endsWith = true endsWith = _.endsWith key, ":#{tag}" if tag? return startsWith and endsWith debug 'deploys', deploys callback null, @formatAll deploys formatAll: (deployments) => deployments = _.map deployments, @format deployments = _.sortBy deployments, 'deployAtFull' return deployments format: (deployment) => deployment = _.cloneDeep deployment deployment.deployAtSince = moment.unix(deployment.deployAt).fromNow() [govKey, etcdKey, dockerUrl, tag ] = deployment.key.split(':') slug = dockerUrl.replace 'quay.io/', '' deployment.deploymentKey = <KEY> return deployment module.exports = GovernatorService
true
_ = require 'lodash' url = require 'url' async = require 'async' request = require 'request' moment = require 'moment' debug = require('debug')('deploy-state-util:governator-service') class GovernatorService constructor: ({ config }) -> @governators = config['governators'] getStatuses: ({ repo, owner, tag }, callback) => _getStatus = async.apply(@getStatus, { repo, owner, tag }) async.mapValues @governators, _getStatus, callback getStatus: ({ repo, owner, tag }, { hostname, username, password }, cluster, callback) => baseUrl = url.format { hostname: hostname protocol: 'https' slashes: true } options = { uri: '/status', baseUrl, json: true, auth: { username, password, }, } debug 'get governator', options request.get options, (error, response, body) => debug 'got governator', { baseUrl, body, error, statusCode: response?.statusCode } return callback error if error? deploys = _.pickBy body, (value, key) => startsWith = _.startsWith key, "governator:/#{owner}/#{repo}" endsWith = true endsWith = _.endsWith key, ":#{tag}" if tag? return startsWith and endsWith debug 'deploys', deploys callback null, @formatAll deploys formatAll: (deployments) => deployments = _.map deployments, @format deployments = _.sortBy deployments, 'deployAtFull' return deployments format: (deployment) => deployment = _.cloneDeep deployment deployment.deployAtSince = moment.unix(deployment.deployAt).fromNow() [govKey, etcdKey, dockerUrl, tag ] = deployment.key.split(':') slug = dockerUrl.replace 'quay.io/', '' deployment.deploymentKey = PI:KEY:<KEY>END_PI return deployment module.exports = GovernatorService
[ { "context": " \n record = new App.User(firstName: \"James\")\n record.set('batch', new Tower.StoreBatc", "end": 281, "score": 0.9996885657310486, "start": 276, "tag": "NAME", "value": "James" } ]
test/cases/store/shared/transactionTest.coffee
jivagoalves/tower
1
### describeWith = (store) -> describe "Tower.StoreBatch (Tower.Store.#{store.className()})", -> record = null batch = null beforeEach (done) -> store.clean => App.User.store(store) record = new App.User(firstName: "James") record.set('batch', new Tower.StoreBatch) batch = record.get('batch') done() test 'record.withBatch', (done) -> record.withBatch (t) => assert.ok t instanceof Tower.StoreBatch, 'batch instanceof Tower.StoreBatch' done() test '#buckets', (done) -> buckets = batch.buckets assert.ok buckets, 'buckets' assert.ok batch.getBucket('clean'), 'buckets.clean' assert.ok batch.getBucket('created'), 'buckets.created' assert.ok batch.getBucket('updated'), 'buckets.updated' assert.ok batch.getBucket('deleted'), 'buckets.deleted' done() test '#addToBucket', (done) -> assert.ok !batch.getBucket('clean').get(record.constructor) batch.addToBucket('clean', record) assert.ok batch.getBucket('clean').get(record.constructor) done() describe 'with record in clean bucket', -> beforeEach (done) -> batch.addToBucket('clean', record) done() test '#removeFromBucket', (done) -> assert.isFalse batch.getBucket('clean').get(record.constructor).isEmpty() batch.removeFromBucket('clean', record) assert.isTrue batch.getBucket('clean').get(record.constructor).isEmpty() done() test '#recordBecameDirty("updated")', (done) -> batch.recordBecameDirty("updated", record) assert.isTrue batch.getBucket('clean').get(record.constructor).isEmpty() assert.isFalse batch.getBucket('updated').get(record.constructor).isEmpty() done() test '#recordBecameClean("clean")', (done) -> batch.recordBecameClean('clean', record) assert.isTrue batch.getBucket('clean').get(record.constructor).isEmpty() done() test '#adopt', (done) -> adopter = new Tower.StoreBatch adopter.adopt(record) assert.isTrue batch.getBucket('clean').get(record.constructor).isEmpty(), 'batch lost record' assert.isFalse adopter.getBucket('clean').get(record.constructor).isEmpty(), 'adopted batch' done() describeWith(Tower.StoreMemory) ###
6709
### describeWith = (store) -> describe "Tower.StoreBatch (Tower.Store.#{store.className()})", -> record = null batch = null beforeEach (done) -> store.clean => App.User.store(store) record = new App.User(firstName: "<NAME>") record.set('batch', new Tower.StoreBatch) batch = record.get('batch') done() test 'record.withBatch', (done) -> record.withBatch (t) => assert.ok t instanceof Tower.StoreBatch, 'batch instanceof Tower.StoreBatch' done() test '#buckets', (done) -> buckets = batch.buckets assert.ok buckets, 'buckets' assert.ok batch.getBucket('clean'), 'buckets.clean' assert.ok batch.getBucket('created'), 'buckets.created' assert.ok batch.getBucket('updated'), 'buckets.updated' assert.ok batch.getBucket('deleted'), 'buckets.deleted' done() test '#addToBucket', (done) -> assert.ok !batch.getBucket('clean').get(record.constructor) batch.addToBucket('clean', record) assert.ok batch.getBucket('clean').get(record.constructor) done() describe 'with record in clean bucket', -> beforeEach (done) -> batch.addToBucket('clean', record) done() test '#removeFromBucket', (done) -> assert.isFalse batch.getBucket('clean').get(record.constructor).isEmpty() batch.removeFromBucket('clean', record) assert.isTrue batch.getBucket('clean').get(record.constructor).isEmpty() done() test '#recordBecameDirty("updated")', (done) -> batch.recordBecameDirty("updated", record) assert.isTrue batch.getBucket('clean').get(record.constructor).isEmpty() assert.isFalse batch.getBucket('updated').get(record.constructor).isEmpty() done() test '#recordBecameClean("clean")', (done) -> batch.recordBecameClean('clean', record) assert.isTrue batch.getBucket('clean').get(record.constructor).isEmpty() done() test '#adopt', (done) -> adopter = new Tower.StoreBatch adopter.adopt(record) assert.isTrue batch.getBucket('clean').get(record.constructor).isEmpty(), 'batch lost record' assert.isFalse adopter.getBucket('clean').get(record.constructor).isEmpty(), 'adopted batch' done() describeWith(Tower.StoreMemory) ###
true
### describeWith = (store) -> describe "Tower.StoreBatch (Tower.Store.#{store.className()})", -> record = null batch = null beforeEach (done) -> store.clean => App.User.store(store) record = new App.User(firstName: "PI:NAME:<NAME>END_PI") record.set('batch', new Tower.StoreBatch) batch = record.get('batch') done() test 'record.withBatch', (done) -> record.withBatch (t) => assert.ok t instanceof Tower.StoreBatch, 'batch instanceof Tower.StoreBatch' done() test '#buckets', (done) -> buckets = batch.buckets assert.ok buckets, 'buckets' assert.ok batch.getBucket('clean'), 'buckets.clean' assert.ok batch.getBucket('created'), 'buckets.created' assert.ok batch.getBucket('updated'), 'buckets.updated' assert.ok batch.getBucket('deleted'), 'buckets.deleted' done() test '#addToBucket', (done) -> assert.ok !batch.getBucket('clean').get(record.constructor) batch.addToBucket('clean', record) assert.ok batch.getBucket('clean').get(record.constructor) done() describe 'with record in clean bucket', -> beforeEach (done) -> batch.addToBucket('clean', record) done() test '#removeFromBucket', (done) -> assert.isFalse batch.getBucket('clean').get(record.constructor).isEmpty() batch.removeFromBucket('clean', record) assert.isTrue batch.getBucket('clean').get(record.constructor).isEmpty() done() test '#recordBecameDirty("updated")', (done) -> batch.recordBecameDirty("updated", record) assert.isTrue batch.getBucket('clean').get(record.constructor).isEmpty() assert.isFalse batch.getBucket('updated').get(record.constructor).isEmpty() done() test '#recordBecameClean("clean")', (done) -> batch.recordBecameClean('clean', record) assert.isTrue batch.getBucket('clean').get(record.constructor).isEmpty() done() test '#adopt', (done) -> adopter = new Tower.StoreBatch adopter.adopt(record) assert.isTrue batch.getBucket('clean').get(record.constructor).isEmpty(), 'batch lost record' assert.isFalse adopter.getBucket('clean').get(record.constructor).isEmpty(), 'adopted batch' done() describeWith(Tower.StoreMemory) ###
[ { "context": "###!\n# Bubble Slider\n# https://github.com/dahjson/bubble-slider\n# Copyright (c) Daniel Johnson\n###\n", "end": 49, "score": 0.9995904564857483, "start": 42, "tag": "USERNAME", "value": "dahjson" }, { "context": "//github.com/dahjson/bubble-slider\n# Copyright (c) Dan...
vendor/bubble-slider-master/src/jquery.bubble-slider.coffee
blackout-games/rugby
1
###! # Bubble Slider # https://github.com/dahjson/bubble-slider # Copyright (c) Daniel Johnson ### (($) -> # avoid conflicts with $ class BubbleSlider constructor: (@element, options) -> # hide input field @element.hide() # get input field settings @min = @element.attr('min') ? options.min @max = @element.attr('max') ? options.max @step = @element.attr('step') ? options.step @value = @element.attr('value') ? (options.max - options.min) / 2 + options.min @decimals = @element.data('decimals') ? options.decimals @prefix = @element.data('prefix') ? options.prefix @postfix = @element.data('postfix') ? options.postfix @toggleBubble = @element.data('toggle-bubble') ? options.toggleBubble @toggleLimit = @element.data('toggle-limit') ? options.toggleLimit @bubbleColor = @element.data('bubble-color') ? options.bubbleColor @bubbleFontScale = @element.data('bubble-font-scale') ? options.bubbleFontScale @bubbleFontColor = @element.data('bubble-font-color') ? options.bubbleFontColor @thumbScale = @element.data('thumb-scale') ? options.thumbScale @thumbColor = @element.data('thumb-color') ? options.thumbColor @thumbFontScale = @element.data('thumb-font-scale') ? options.thumbFontScale @thumbFontColor = @element.data('thumb-font-color') ? options.thumbFontColor @trackScale = @element.data('track-scale') ? options.trackScale @trackColor = @element.data('track-color') ? options.trackColor # convert strings to numbers @min = parseFloat(@removeCommas(@min)) @max = parseFloat(@removeCommas(@max)) @step = parseFloat(@removeCommas(@step)) @value = parseFloat(@removeCommas(@value)) @decimals = parseFloat(@removeCommas(@decimals)) @toggleLimit = parseFloat(@removeCommas(@toggleLimit)) @bubbleFontScale = parseFloat(@removeCommas(@bubbleFontScale)) @thumbScale = parseFloat(@removeCommas(@thumbScale)) @thumbFontScale = parseFloat(@removeCommas(@thumbFontScale)) @trackScale = parseFloat(@removeCommas(@trackScale)) # create slider elements @slider = $('<div>').addClass('bubble-slider-wrap').insertAfter(@element) @minus = $('<div><span>-</span></div>').addClass('bubble-slider-minus').appendTo(@slider) @plus = $('<div><span>+</span></div>').addClass('bubble-slider-plus').appendTo(@slider) @track = $('<div>').addClass('bubble-slider-track').appendTo(@slider) @thumb = $('<div><span>').addClass('bubble-slider-thumb').appendTo(@track) @bubble = $('<div><span>').addClass('bubble-slider-bubble').appendTo(@thumb) @bubbleArrow = $('<div>').addClass('bubble-slider-bubble-arrow').prependTo(@bubble) # span elements @thumbSpan = @thumb.find('span').first() @bubbleSpan = @bubble.find('span').first() # size and scale elements if @bubbleFontScale != 1 @bubble.css( 'font-size': parseFloat(@bubble.css('font-size')) * @bubbleFontScale + 'px' 'border-radius': parseFloat(@bubble.css('border-radius')) * @bubbleFontScale + 'px' ) @bubbleArrow.css( 'width': parseFloat(@bubbleArrow.css('width')) * @bubbleFontScale + 'px' 'height': parseFloat(@bubbleArrow.css('height')) * @bubbleFontScale + 'px' ) if @thumbScale != 1 @thumb.css( 'width': parseFloat(@thumb.css('width')) * @thumbScale + 'px' 'height': parseFloat(@thumb.css('height')) * @thumbScale + 'px' ) if @thumbFontScale != 1 @thumbSpan.css( 'font-size': parseFloat(@thumbSpan.css('font-size')) * @thumbFontScale + 'px' ) if @trackScale != 1 @minus.css( 'width': Math.round(parseFloat(@minus.css('width')) * @trackScale) + 'px' 'height': Math.round(parseFloat(@minus.css('height')) * @trackScale) + 'px' 'font-size': Math.round(parseFloat(@minus.css('font-size')) * @trackScale) + 'px' ) @plus.css( 'width': Math.round(parseFloat(@plus.css('width')) * @trackScale) + 'px' 'height': Math.round(parseFloat(@plus.css('height')) * @trackScale) + 'px' 'font-size': Math.round(parseFloat(@plus.css('font-size')) * @trackScale) + 'px' ) @track.css( 'left': parseFloat(@minus.outerWidth()) + (@minus.outerWidth() * 0.2) + 'px' 'right': parseFloat(@plus.outerWidth()) + (@plus.outerWidth()* 0.2) + 'px' ) # adjust margin spacing if @bubbleFontScale != 1 or @thumbScale != 1 or @trackScale != 1 trackHeight = if @thumb.outerHeight() > @plus.outerHeight() then @thumb.outerHeight() else @plus.outerHeight() bubbleHeight = @bubble.outerHeight() @slider.css( 'margin': parseFloat(trackHeight) + parseFloat(bubbleHeight) + 'px auto' ) # colorize elements if @bubbleColor @bubbleArrow.css('background', @bubbleColor) @bubble.css('background', @bubbleColor) if @bubbleFontColor @bubbleSpan.css('color', @bubbleFontColor) if @thumbColor @minus.css('color', @thumbColor) @plus.css('color', @thumbColor) @thumb.css('background', @thumbColor) if @thumbFontColor @thumbSpan.css('color', @thumbFontColor) if @trackColor @minus.css('border-color', @trackColor) @plus.css('border-color', @trackColor) @track.css('background', @trackColor) # other initial settings @dragging = false @thumbOffset = @thumb.outerWidth() / 2 # set number value and thumb position @setValue(@value) @positionThumb(@value) # set initial bubble state if @toggleBubble and @value.toString().length <= @toggleLimit @bubble.hide() @thumbSpan.show() else @thumbSpan.hide() # disables default touch actions for IE on thumb @thumb.css('-ms-touch-action', 'none') # thumb events (mouse and touch) @thumb.on 'mousedown touchstart', (event) => if not @dragging event.preventDefault() @dragging = true @bubbleState(true) $('html') .on 'mousemove touchmove', (event) => if @dragging event.preventDefault() if event.type is 'touchmove' @dragThumb(event.originalEvent.touches[0].pageX) else @dragThumb(event.originalEvent.pageX) .on 'mouseup touchend', (event) => if @dragging event.preventDefault() @dragging = false @bubbleState(false) # minus button @minus.on 'click', (event) => event.preventDefault() newValue = @value - @step newValue = Math.max(@min, newValue) @setValue(newValue) @positionThumb(newValue) # plus button @plus.on 'click', (event) => event.preventDefault() newValue = @value + @step newValue = Math.min(@max, newValue) @setValue(newValue) @positionThumb(newValue) # adjust for window resize $(window).on 'resize onorientationchange', => @positionThumb(@value) # drag slider thumb dragThumb: (pageX) -> minPosition = @track.offset().left + @thumbOffset maxPosition = @track.offset().left + @track.innerWidth() - @thumbOffset # find new position for thumb newPosition = Math.max(minPosition, pageX) newPosition = Math.min(maxPosition, newPosition) @setValue(@calcValue()) # set slider number # set the new thumb position @thumb.offset({ left: newPosition - @thumbOffset }) # calculate value for slider calcValue: -> trackRatio = @normalize(@thumb.position().left, 0, @track.innerWidth() - @thumbOffset * 2) trackRatio * (@max - @min) + @min # set new value for slider setValue: (value) -> @value = Math.round((value - @min) / @step) * @step + @min # find step value @element.val(@value) # update hidden input number modValue = @prefix + @addCommas(@value.toFixed(@decimals)) + @postfix # modified number value @thumbSpan.text(modValue) # update thumb number @bubbleSpan.text(modValue) # update bubble number # position the thumb positionThumb: (value) -> thumbRatio = @normalize(value, @min, @max) # set the new thumb position @thumb.offset( left: Math.round(thumbRatio * (@track.innerWidth() - @thumbOffset * 2) + @track.offset().left) ) # toggle bubble on or off bubbleState: (state) -> if @toggleBubble if state @bubble.stop(true, true).fadeIn(300) @thumbSpan.stop(true, true).fadeOut(200) else if @value.toString().length <= @toggleLimit @bubble.stop(true, true).fadeOut(300) @thumbSpan.stop(true, true).fadeIn(200) # normalize number scaled 0 - 1 normalize: (number, min, max) -> (number - min) / (max - min) # add commas to number addCommas: (num) -> num.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") # remove commas from number removeCommas: (num) -> num.toString().replace(/,/g, '') # jQuery plugin $.fn.bubbleSlider = (options) -> # default options for plugin defaults = min: 0 max: 100 step: 1 value: 50 decimals: 0 prefix: '' postfix: '' toggleBubble: false toggleLimit: 3 bubbleColor: '' bubbleFontScale: 1 bubbleFontColor: '' thumbScale: 1 thumbColor: '' thumbFontScale: 1 thumbFontColor: '' trackScale: 1 trackColor: '' # merge defaults with user defaults and options settings = $.extend({}, defaults, $.fn.bubbleSlider.defaults, options) # instantiate class instance new BubbleSlider($(this), settings) # execute code $ -> # attach to elements with class name $('.bubble-slider').each -> $(this).bubbleSlider() ) @jQuery
156157
###! # Bubble Slider # https://github.com/dahjson/bubble-slider # Copyright (c) <NAME> ### (($) -> # avoid conflicts with $ class BubbleSlider constructor: (@element, options) -> # hide input field @element.hide() # get input field settings @min = @element.attr('min') ? options.min @max = @element.attr('max') ? options.max @step = @element.attr('step') ? options.step @value = @element.attr('value') ? (options.max - options.min) / 2 + options.min @decimals = @element.data('decimals') ? options.decimals @prefix = @element.data('prefix') ? options.prefix @postfix = @element.data('postfix') ? options.postfix @toggleBubble = @element.data('toggle-bubble') ? options.toggleBubble @toggleLimit = @element.data('toggle-limit') ? options.toggleLimit @bubbleColor = @element.data('bubble-color') ? options.bubbleColor @bubbleFontScale = @element.data('bubble-font-scale') ? options.bubbleFontScale @bubbleFontColor = @element.data('bubble-font-color') ? options.bubbleFontColor @thumbScale = @element.data('thumb-scale') ? options.thumbScale @thumbColor = @element.data('thumb-color') ? options.thumbColor @thumbFontScale = @element.data('thumb-font-scale') ? options.thumbFontScale @thumbFontColor = @element.data('thumb-font-color') ? options.thumbFontColor @trackScale = @element.data('track-scale') ? options.trackScale @trackColor = @element.data('track-color') ? options.trackColor # convert strings to numbers @min = parseFloat(@removeCommas(@min)) @max = parseFloat(@removeCommas(@max)) @step = parseFloat(@removeCommas(@step)) @value = parseFloat(@removeCommas(@value)) @decimals = parseFloat(@removeCommas(@decimals)) @toggleLimit = parseFloat(@removeCommas(@toggleLimit)) @bubbleFontScale = parseFloat(@removeCommas(@bubbleFontScale)) @thumbScale = parseFloat(@removeCommas(@thumbScale)) @thumbFontScale = parseFloat(@removeCommas(@thumbFontScale)) @trackScale = parseFloat(@removeCommas(@trackScale)) # create slider elements @slider = $('<div>').addClass('bubble-slider-wrap').insertAfter(@element) @minus = $('<div><span>-</span></div>').addClass('bubble-slider-minus').appendTo(@slider) @plus = $('<div><span>+</span></div>').addClass('bubble-slider-plus').appendTo(@slider) @track = $('<div>').addClass('bubble-slider-track').appendTo(@slider) @thumb = $('<div><span>').addClass('bubble-slider-thumb').appendTo(@track) @bubble = $('<div><span>').addClass('bubble-slider-bubble').appendTo(@thumb) @bubbleArrow = $('<div>').addClass('bubble-slider-bubble-arrow').prependTo(@bubble) # span elements @thumbSpan = @thumb.find('span').first() @bubbleSpan = @bubble.find('span').first() # size and scale elements if @bubbleFontScale != 1 @bubble.css( 'font-size': parseFloat(@bubble.css('font-size')) * @bubbleFontScale + 'px' 'border-radius': parseFloat(@bubble.css('border-radius')) * @bubbleFontScale + 'px' ) @bubbleArrow.css( 'width': parseFloat(@bubbleArrow.css('width')) * @bubbleFontScale + 'px' 'height': parseFloat(@bubbleArrow.css('height')) * @bubbleFontScale + 'px' ) if @thumbScale != 1 @thumb.css( 'width': parseFloat(@thumb.css('width')) * @thumbScale + 'px' 'height': parseFloat(@thumb.css('height')) * @thumbScale + 'px' ) if @thumbFontScale != 1 @thumbSpan.css( 'font-size': parseFloat(@thumbSpan.css('font-size')) * @thumbFontScale + 'px' ) if @trackScale != 1 @minus.css( 'width': Math.round(parseFloat(@minus.css('width')) * @trackScale) + 'px' 'height': Math.round(parseFloat(@minus.css('height')) * @trackScale) + 'px' 'font-size': Math.round(parseFloat(@minus.css('font-size')) * @trackScale) + 'px' ) @plus.css( 'width': Math.round(parseFloat(@plus.css('width')) * @trackScale) + 'px' 'height': Math.round(parseFloat(@plus.css('height')) * @trackScale) + 'px' 'font-size': Math.round(parseFloat(@plus.css('font-size')) * @trackScale) + 'px' ) @track.css( 'left': parseFloat(@minus.outerWidth()) + (@minus.outerWidth() * 0.2) + 'px' 'right': parseFloat(@plus.outerWidth()) + (@plus.outerWidth()* 0.2) + 'px' ) # adjust margin spacing if @bubbleFontScale != 1 or @thumbScale != 1 or @trackScale != 1 trackHeight = if @thumb.outerHeight() > @plus.outerHeight() then @thumb.outerHeight() else @plus.outerHeight() bubbleHeight = @bubble.outerHeight() @slider.css( 'margin': parseFloat(trackHeight) + parseFloat(bubbleHeight) + 'px auto' ) # colorize elements if @bubbleColor @bubbleArrow.css('background', @bubbleColor) @bubble.css('background', @bubbleColor) if @bubbleFontColor @bubbleSpan.css('color', @bubbleFontColor) if @thumbColor @minus.css('color', @thumbColor) @plus.css('color', @thumbColor) @thumb.css('background', @thumbColor) if @thumbFontColor @thumbSpan.css('color', @thumbFontColor) if @trackColor @minus.css('border-color', @trackColor) @plus.css('border-color', @trackColor) @track.css('background', @trackColor) # other initial settings @dragging = false @thumbOffset = @thumb.outerWidth() / 2 # set number value and thumb position @setValue(@value) @positionThumb(@value) # set initial bubble state if @toggleBubble and @value.toString().length <= @toggleLimit @bubble.hide() @thumbSpan.show() else @thumbSpan.hide() # disables default touch actions for IE on thumb @thumb.css('-ms-touch-action', 'none') # thumb events (mouse and touch) @thumb.on 'mousedown touchstart', (event) => if not @dragging event.preventDefault() @dragging = true @bubbleState(true) $('html') .on 'mousemove touchmove', (event) => if @dragging event.preventDefault() if event.type is 'touchmove' @dragThumb(event.originalEvent.touches[0].pageX) else @dragThumb(event.originalEvent.pageX) .on 'mouseup touchend', (event) => if @dragging event.preventDefault() @dragging = false @bubbleState(false) # minus button @minus.on 'click', (event) => event.preventDefault() newValue = @value - @step newValue = Math.max(@min, newValue) @setValue(newValue) @positionThumb(newValue) # plus button @plus.on 'click', (event) => event.preventDefault() newValue = @value + @step newValue = Math.min(@max, newValue) @setValue(newValue) @positionThumb(newValue) # adjust for window resize $(window).on 'resize onorientationchange', => @positionThumb(@value) # drag slider thumb dragThumb: (pageX) -> minPosition = @track.offset().left + @thumbOffset maxPosition = @track.offset().left + @track.innerWidth() - @thumbOffset # find new position for thumb newPosition = Math.max(minPosition, pageX) newPosition = Math.min(maxPosition, newPosition) @setValue(@calcValue()) # set slider number # set the new thumb position @thumb.offset({ left: newPosition - @thumbOffset }) # calculate value for slider calcValue: -> trackRatio = @normalize(@thumb.position().left, 0, @track.innerWidth() - @thumbOffset * 2) trackRatio * (@max - @min) + @min # set new value for slider setValue: (value) -> @value = Math.round((value - @min) / @step) * @step + @min # find step value @element.val(@value) # update hidden input number modValue = @prefix + @addCommas(@value.toFixed(@decimals)) + @postfix # modified number value @thumbSpan.text(modValue) # update thumb number @bubbleSpan.text(modValue) # update bubble number # position the thumb positionThumb: (value) -> thumbRatio = @normalize(value, @min, @max) # set the new thumb position @thumb.offset( left: Math.round(thumbRatio * (@track.innerWidth() - @thumbOffset * 2) + @track.offset().left) ) # toggle bubble on or off bubbleState: (state) -> if @toggleBubble if state @bubble.stop(true, true).fadeIn(300) @thumbSpan.stop(true, true).fadeOut(200) else if @value.toString().length <= @toggleLimit @bubble.stop(true, true).fadeOut(300) @thumbSpan.stop(true, true).fadeIn(200) # normalize number scaled 0 - 1 normalize: (number, min, max) -> (number - min) / (max - min) # add commas to number addCommas: (num) -> num.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") # remove commas from number removeCommas: (num) -> num.toString().replace(/,/g, '') # jQuery plugin $.fn.bubbleSlider = (options) -> # default options for plugin defaults = min: 0 max: 100 step: 1 value: 50 decimals: 0 prefix: '' postfix: '' toggleBubble: false toggleLimit: 3 bubbleColor: '' bubbleFontScale: 1 bubbleFontColor: '' thumbScale: 1 thumbColor: '' thumbFontScale: 1 thumbFontColor: '' trackScale: 1 trackColor: '' # merge defaults with user defaults and options settings = $.extend({}, defaults, $.fn.bubbleSlider.defaults, options) # instantiate class instance new BubbleSlider($(this), settings) # execute code $ -> # attach to elements with class name $('.bubble-slider').each -> $(this).bubbleSlider() ) @jQuery
true
###! # Bubble Slider # https://github.com/dahjson/bubble-slider # Copyright (c) PI:NAME:<NAME>END_PI ### (($) -> # avoid conflicts with $ class BubbleSlider constructor: (@element, options) -> # hide input field @element.hide() # get input field settings @min = @element.attr('min') ? options.min @max = @element.attr('max') ? options.max @step = @element.attr('step') ? options.step @value = @element.attr('value') ? (options.max - options.min) / 2 + options.min @decimals = @element.data('decimals') ? options.decimals @prefix = @element.data('prefix') ? options.prefix @postfix = @element.data('postfix') ? options.postfix @toggleBubble = @element.data('toggle-bubble') ? options.toggleBubble @toggleLimit = @element.data('toggle-limit') ? options.toggleLimit @bubbleColor = @element.data('bubble-color') ? options.bubbleColor @bubbleFontScale = @element.data('bubble-font-scale') ? options.bubbleFontScale @bubbleFontColor = @element.data('bubble-font-color') ? options.bubbleFontColor @thumbScale = @element.data('thumb-scale') ? options.thumbScale @thumbColor = @element.data('thumb-color') ? options.thumbColor @thumbFontScale = @element.data('thumb-font-scale') ? options.thumbFontScale @thumbFontColor = @element.data('thumb-font-color') ? options.thumbFontColor @trackScale = @element.data('track-scale') ? options.trackScale @trackColor = @element.data('track-color') ? options.trackColor # convert strings to numbers @min = parseFloat(@removeCommas(@min)) @max = parseFloat(@removeCommas(@max)) @step = parseFloat(@removeCommas(@step)) @value = parseFloat(@removeCommas(@value)) @decimals = parseFloat(@removeCommas(@decimals)) @toggleLimit = parseFloat(@removeCommas(@toggleLimit)) @bubbleFontScale = parseFloat(@removeCommas(@bubbleFontScale)) @thumbScale = parseFloat(@removeCommas(@thumbScale)) @thumbFontScale = parseFloat(@removeCommas(@thumbFontScale)) @trackScale = parseFloat(@removeCommas(@trackScale)) # create slider elements @slider = $('<div>').addClass('bubble-slider-wrap').insertAfter(@element) @minus = $('<div><span>-</span></div>').addClass('bubble-slider-minus').appendTo(@slider) @plus = $('<div><span>+</span></div>').addClass('bubble-slider-plus').appendTo(@slider) @track = $('<div>').addClass('bubble-slider-track').appendTo(@slider) @thumb = $('<div><span>').addClass('bubble-slider-thumb').appendTo(@track) @bubble = $('<div><span>').addClass('bubble-slider-bubble').appendTo(@thumb) @bubbleArrow = $('<div>').addClass('bubble-slider-bubble-arrow').prependTo(@bubble) # span elements @thumbSpan = @thumb.find('span').first() @bubbleSpan = @bubble.find('span').first() # size and scale elements if @bubbleFontScale != 1 @bubble.css( 'font-size': parseFloat(@bubble.css('font-size')) * @bubbleFontScale + 'px' 'border-radius': parseFloat(@bubble.css('border-radius')) * @bubbleFontScale + 'px' ) @bubbleArrow.css( 'width': parseFloat(@bubbleArrow.css('width')) * @bubbleFontScale + 'px' 'height': parseFloat(@bubbleArrow.css('height')) * @bubbleFontScale + 'px' ) if @thumbScale != 1 @thumb.css( 'width': parseFloat(@thumb.css('width')) * @thumbScale + 'px' 'height': parseFloat(@thumb.css('height')) * @thumbScale + 'px' ) if @thumbFontScale != 1 @thumbSpan.css( 'font-size': parseFloat(@thumbSpan.css('font-size')) * @thumbFontScale + 'px' ) if @trackScale != 1 @minus.css( 'width': Math.round(parseFloat(@minus.css('width')) * @trackScale) + 'px' 'height': Math.round(parseFloat(@minus.css('height')) * @trackScale) + 'px' 'font-size': Math.round(parseFloat(@minus.css('font-size')) * @trackScale) + 'px' ) @plus.css( 'width': Math.round(parseFloat(@plus.css('width')) * @trackScale) + 'px' 'height': Math.round(parseFloat(@plus.css('height')) * @trackScale) + 'px' 'font-size': Math.round(parseFloat(@plus.css('font-size')) * @trackScale) + 'px' ) @track.css( 'left': parseFloat(@minus.outerWidth()) + (@minus.outerWidth() * 0.2) + 'px' 'right': parseFloat(@plus.outerWidth()) + (@plus.outerWidth()* 0.2) + 'px' ) # adjust margin spacing if @bubbleFontScale != 1 or @thumbScale != 1 or @trackScale != 1 trackHeight = if @thumb.outerHeight() > @plus.outerHeight() then @thumb.outerHeight() else @plus.outerHeight() bubbleHeight = @bubble.outerHeight() @slider.css( 'margin': parseFloat(trackHeight) + parseFloat(bubbleHeight) + 'px auto' ) # colorize elements if @bubbleColor @bubbleArrow.css('background', @bubbleColor) @bubble.css('background', @bubbleColor) if @bubbleFontColor @bubbleSpan.css('color', @bubbleFontColor) if @thumbColor @minus.css('color', @thumbColor) @plus.css('color', @thumbColor) @thumb.css('background', @thumbColor) if @thumbFontColor @thumbSpan.css('color', @thumbFontColor) if @trackColor @minus.css('border-color', @trackColor) @plus.css('border-color', @trackColor) @track.css('background', @trackColor) # other initial settings @dragging = false @thumbOffset = @thumb.outerWidth() / 2 # set number value and thumb position @setValue(@value) @positionThumb(@value) # set initial bubble state if @toggleBubble and @value.toString().length <= @toggleLimit @bubble.hide() @thumbSpan.show() else @thumbSpan.hide() # disables default touch actions for IE on thumb @thumb.css('-ms-touch-action', 'none') # thumb events (mouse and touch) @thumb.on 'mousedown touchstart', (event) => if not @dragging event.preventDefault() @dragging = true @bubbleState(true) $('html') .on 'mousemove touchmove', (event) => if @dragging event.preventDefault() if event.type is 'touchmove' @dragThumb(event.originalEvent.touches[0].pageX) else @dragThumb(event.originalEvent.pageX) .on 'mouseup touchend', (event) => if @dragging event.preventDefault() @dragging = false @bubbleState(false) # minus button @minus.on 'click', (event) => event.preventDefault() newValue = @value - @step newValue = Math.max(@min, newValue) @setValue(newValue) @positionThumb(newValue) # plus button @plus.on 'click', (event) => event.preventDefault() newValue = @value + @step newValue = Math.min(@max, newValue) @setValue(newValue) @positionThumb(newValue) # adjust for window resize $(window).on 'resize onorientationchange', => @positionThumb(@value) # drag slider thumb dragThumb: (pageX) -> minPosition = @track.offset().left + @thumbOffset maxPosition = @track.offset().left + @track.innerWidth() - @thumbOffset # find new position for thumb newPosition = Math.max(minPosition, pageX) newPosition = Math.min(maxPosition, newPosition) @setValue(@calcValue()) # set slider number # set the new thumb position @thumb.offset({ left: newPosition - @thumbOffset }) # calculate value for slider calcValue: -> trackRatio = @normalize(@thumb.position().left, 0, @track.innerWidth() - @thumbOffset * 2) trackRatio * (@max - @min) + @min # set new value for slider setValue: (value) -> @value = Math.round((value - @min) / @step) * @step + @min # find step value @element.val(@value) # update hidden input number modValue = @prefix + @addCommas(@value.toFixed(@decimals)) + @postfix # modified number value @thumbSpan.text(modValue) # update thumb number @bubbleSpan.text(modValue) # update bubble number # position the thumb positionThumb: (value) -> thumbRatio = @normalize(value, @min, @max) # set the new thumb position @thumb.offset( left: Math.round(thumbRatio * (@track.innerWidth() - @thumbOffset * 2) + @track.offset().left) ) # toggle bubble on or off bubbleState: (state) -> if @toggleBubble if state @bubble.stop(true, true).fadeIn(300) @thumbSpan.stop(true, true).fadeOut(200) else if @value.toString().length <= @toggleLimit @bubble.stop(true, true).fadeOut(300) @thumbSpan.stop(true, true).fadeIn(200) # normalize number scaled 0 - 1 normalize: (number, min, max) -> (number - min) / (max - min) # add commas to number addCommas: (num) -> num.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") # remove commas from number removeCommas: (num) -> num.toString().replace(/,/g, '') # jQuery plugin $.fn.bubbleSlider = (options) -> # default options for plugin defaults = min: 0 max: 100 step: 1 value: 50 decimals: 0 prefix: '' postfix: '' toggleBubble: false toggleLimit: 3 bubbleColor: '' bubbleFontScale: 1 bubbleFontColor: '' thumbScale: 1 thumbColor: '' thumbFontScale: 1 thumbFontColor: '' trackScale: 1 trackColor: '' # merge defaults with user defaults and options settings = $.extend({}, defaults, $.fn.bubbleSlider.defaults, options) # instantiate class instance new BubbleSlider($(this), settings) # execute code $ -> # attach to elements with class name $('.bubble-slider').each -> $(this).bubbleSlider() ) @jQuery
[ { "context": " ->\n user = new NgParseUser username: 'mario', password: 'pass'\n user.username.shou", "end": 2045, "score": 0.99964439868927, "start": 2040, "tag": "USERNAME", "value": "mario" }, { "context": "r = new NgParseUser username: 'mario', password: 'pa...
test/User.spec.coffee
leonardfactory/ng-parse
1
describe 'NgParse.User', -> NgParseUser = null NgParseRequest = null ngParseRequestConfig = null $httpBackend = null $http = null locker = null beforeEach -> angular.mock.module 'ngParse', ($provide) -> $provide.value 'ngParseRequestConfig', appId: 'appId' restApiKey: 'restApiKey' parseUrl: '/' # Simple mock for localStorage $provide.value 'locker', storage: {} driver: -> @ namespace: -> @ put: (key, val) -> @storage[key] = val get: (key, defaultsTo = null) -> if @storage[key]? then @storage[key] else defaultsTo has: (key) -> @storage[key]? forget: (key) -> @storage[key] = null # Extremely important in order to avoid bad errors caused by CoffeeScript. return inject (_NgParseUser_, $injector) -> NgParseUser = _NgParseUser_ NgParseRequest = $injector.get 'NgParseRequest' $httpBackend = $injector.get '$httpBackend' $http = $injector.get '$http' locker = $injector.get 'locker' ngParseRequestConfig = $injector.get 'ngParseRequestConfig' afterEach -> $httpBackend.verifyNoOutstandingExpectation() $httpBackend.verifyNoOutstandingRequest() # Attributes # describe 'Attributes', -> it 'should have attributes inherited from NgParse.Object', -> NgParseUser.totalAttrNames.should.contain 'objectId' it 'should have custom attributes', -> NgParseUser.totalAttrNames.should.have.length 7 NgParseUser.totalAttrNames.should.contain.members ['username', 'email', 'password'] it 'instances should have attributes set', -> user = new NgParseUser username: 'mario', password: 'pass' user.username.should.be.equal 'mario' user.password.should.be.equal 'pass' # Save # describe 'Save', -> beforeEach -> $httpBackend .when 'PUT', "/users/user_id" .respond objectId: 'user_id' it 'should save correctly the user (using the right URL)', -> user = new NgParseUser objectId: 'user_id' user.username = 'mario' user.dirty.should.have.members ['username'] $httpBackend.expectPUT "/users/user_id" user.save() $httpBackend.flush() user.dirty.should.be.empty # Login # describe 'Login', -> beforeEach -> $httpBackend.expectGET('/login?password=test&username=test').respond 201, sessionToken: 'testToken' objectId: 'user_id' NgParseUser.login 'test', 'test' $httpBackend.flush() it 'should grab sessionToken from a correct request', -> NgParseUser.current.should.not.be.null NgParseUser.current._sessionToken.should.be.equal 'testToken' it 'should save sessionToken and correct id in localStorage', -> currentUser = locker.get 'currentUser' currentUser.should.have.keys ['sessionToken', 'objectId'] currentUser.sessionToken.should.be.equal 'testToken' currentUser.objectId.should.be.equal 'user_id' it 'should save correct `current` static variable', -> NgParseUser.current.should.be.an.instanceof NgParseUser NgParseUser.current.objectId.should.be.equal 'user_id' it 'should set sessionToken inside ngParseRequestConfig', -> ngParseRequestConfig.sessionToken.should.be.equal 'testToken' # Logout # describe 'Logout', -> beforeEach -> $httpBackend.expectGET('/login?password=test&username=test').respond 201, sessionToken: 'testToken' objectId: 'user_id' NgParseUser.login 'test', 'test' $httpBackend.flush() it 'should remove `current` static variable and updating `logged` static property', -> NgParseUser.logged().should.be.true NgParseUser.logout() should.not.exist NgParseUser.current NgParseUser.logged().should.be.false it 'should remove sessionToken', -> NgParseUser.logout() should.not.exist ngParseRequestConfig.sessionToken it 'should remove current user data from localStorage', -> NgParseUser.logout() currentUser = locker.get 'currentUser' should.not.exist currentUser # Signup # describe 'Signup', -> beforeEach -> inject ($rootScope) => @$rootScope = $rootScope $httpBackend .when 'POST', "/users/" .respond objectId: 'user_id' sessionToken: 'testSignupToken' @user = new NgParseUser @user.username = 'username' @user.password = 'password' it 'should not allow registration if username is not set', -> wrongUser = new NgParseUser wrongUser.password = 'password' wrongUser.signup().catch (error) => @error = error @$rootScope.$apply() # Resolve promise @error.should.be.equal "Can't register without username and password set" it 'should not allow register if password is not set', -> wrongUser = new NgParseUser wrongUser.username = 'username' wrongUser.signup().catch (error) => @error = error @$rootScope.$apply() # Resolve promise @error.should.be.equal "Can't register without username and password set" it 'should call signup correctly', -> (-> @user.signup() ).should.not.throw it 'should set sessionToken', -> @user.signup() $httpBackend.flush() @user.should.be.equal NgParseUser.current @user._sessionToken.should.be.equal 'testSignupToken' it 'should save into local storage', -> @user.signup() $httpBackend.flush() locker.has('currentUser').should.be.true locker.get('currentUser').should.be.deep.equal sessionToken: 'testSignupToken', objectId: 'user_id' it 'should return a promise', -> promise = @user.signup() $httpBackend.flush() promise.should.respondTo 'then' # Current user general # describe 'Current user', -> beforeEach -> $httpBackend .when 'GET', '/users/me' .respond objectId: 'user_id' it 'should be set to null if not logged', -> should.equal NgParseUser.current, null it 'should fetch the user from `me` path', -> user = new NgParseUser user._sessionToken = 'testToken' $httpBackend.expectGET '/users/me' user.me() $httpBackend.flush() user.objectId.should.be.equal 'user_id' it 'should load user from localStorage', -> locker.put 'currentUser', sessionToken: 'testToken' objectId: 'user_id' $httpBackend.expectGET '/users/me' NgParseUser.checkIfLogged() $httpBackend.flush() NgParseUser.current.should.not.be.null NgParseUser.current.objectId.should.be.equal 'user_id' NgParseUser.current._sessionToken.should.be.equal 'testToken' NgParseUser.logged().should.be.true ngParseRequestConfig.sessionToken.should.be.equal 'testToken'
86462
describe 'NgParse.User', -> NgParseUser = null NgParseRequest = null ngParseRequestConfig = null $httpBackend = null $http = null locker = null beforeEach -> angular.mock.module 'ngParse', ($provide) -> $provide.value 'ngParseRequestConfig', appId: 'appId' restApiKey: 'restApiKey' parseUrl: '/' # Simple mock for localStorage $provide.value 'locker', storage: {} driver: -> @ namespace: -> @ put: (key, val) -> @storage[key] = val get: (key, defaultsTo = null) -> if @storage[key]? then @storage[key] else defaultsTo has: (key) -> @storage[key]? forget: (key) -> @storage[key] = null # Extremely important in order to avoid bad errors caused by CoffeeScript. return inject (_NgParseUser_, $injector) -> NgParseUser = _NgParseUser_ NgParseRequest = $injector.get 'NgParseRequest' $httpBackend = $injector.get '$httpBackend' $http = $injector.get '$http' locker = $injector.get 'locker' ngParseRequestConfig = $injector.get 'ngParseRequestConfig' afterEach -> $httpBackend.verifyNoOutstandingExpectation() $httpBackend.verifyNoOutstandingRequest() # Attributes # describe 'Attributes', -> it 'should have attributes inherited from NgParse.Object', -> NgParseUser.totalAttrNames.should.contain 'objectId' it 'should have custom attributes', -> NgParseUser.totalAttrNames.should.have.length 7 NgParseUser.totalAttrNames.should.contain.members ['username', 'email', 'password'] it 'instances should have attributes set', -> user = new NgParseUser username: 'mario', password: '<PASSWORD>' user.username.should.be.equal 'mario' user.password.should.be.equal '<PASSWORD>' # Save # describe 'Save', -> beforeEach -> $httpBackend .when 'PUT', "/users/user_id" .respond objectId: 'user_id' it 'should save correctly the user (using the right URL)', -> user = new NgParseUser objectId: 'user_id' user.username = 'mario' user.dirty.should.have.members ['username'] $httpBackend.expectPUT "/users/user_id" user.save() $httpBackend.flush() user.dirty.should.be.empty # Login # describe 'Login', -> beforeEach -> $httpBackend.expectGET('/login?password=<PASSWORD>&username=test').respond 201, sessionToken: 'test<PASSWORD>' objectId: 'user_id' NgParseUser.login 'test', 'test' $httpBackend.flush() it 'should grab sessionToken from a correct request', -> NgParseUser.current.should.not.be.null NgParseUser.current._sessionToken.should.be.equal 'testToken' it 'should save sessionToken and correct id in localStorage', -> currentUser = locker.get 'currentUser' currentUser.should.have.keys ['sessionToken', 'objectId'] currentUser.sessionToken.should.be.equal 'testToken' currentUser.objectId.should.be.equal 'user_id' it 'should save correct `current` static variable', -> NgParseUser.current.should.be.an.instanceof NgParseUser NgParseUser.current.objectId.should.be.equal 'user_id' it 'should set sessionToken inside ngParseRequestConfig', -> ngParseRequestConfig.sessionToken.should.be.equal 'testToken' # Logout # describe 'Logout', -> beforeEach -> $httpBackend.expectGET('/login?password=<PASSWORD>&username=test').respond 201, sessionToken: 'testToken' objectId: 'user_id' NgParseUser.login 'test', 'test' $httpBackend.flush() it 'should remove `current` static variable and updating `logged` static property', -> NgParseUser.logged().should.be.true NgParseUser.logout() should.not.exist NgParseUser.current NgParseUser.logged().should.be.false it 'should remove sessionToken', -> NgParseUser.logout() should.not.exist ngParseRequestConfig.sessionToken it 'should remove current user data from localStorage', -> NgParseUser.logout() currentUser = locker.get 'currentUser' should.not.exist currentUser # Signup # describe 'Signup', -> beforeEach -> inject ($rootScope) => @$rootScope = $rootScope $httpBackend .when 'POST', "/users/" .respond objectId: 'user_id' sessionToken: 'testSignupToken' @user = new NgParseUser @user.username = 'username' @user.password = '<PASSWORD>' it 'should not allow registration if username is not set', -> wrongUser = new NgParseUser wrongUser.password = '<PASSWORD>' wrongUser.signup().catch (error) => @error = error @$rootScope.$apply() # Resolve promise @error.should.be.equal "Can't register without username and password set" it 'should not allow register if password is not set', -> wrongUser = new NgParseUser wrongUser.username = 'username' wrongUser.signup().catch (error) => @error = error @$rootScope.$apply() # Resolve promise @error.should.be.equal "Can't register without username and password set" it 'should call signup correctly', -> (-> @user.signup() ).should.not.throw it 'should set sessionToken', -> @user.signup() $httpBackend.flush() @user.should.be.equal NgParseUser.current @user._sessionToken.should.be.equal 'testSignupToken' it 'should save into local storage', -> @user.signup() $httpBackend.flush() locker.has('currentUser').should.be.true locker.get('currentUser').should.be.deep.equal sessionToken: 'testSignupToken', objectId: 'user_id' it 'should return a promise', -> promise = @user.signup() $httpBackend.flush() promise.should.respondTo 'then' # Current user general # describe 'Current user', -> beforeEach -> $httpBackend .when 'GET', '/users/me' .respond objectId: 'user_id' it 'should be set to null if not logged', -> should.equal NgParseUser.current, null it 'should fetch the user from `me` path', -> user = new NgParseUser user._sessionToken = '<PASSWORD>' $httpBackend.expectGET '/users/me' user.me() $httpBackend.flush() user.objectId.should.be.equal 'user_id' it 'should load user from localStorage', -> locker.put 'currentUser', sessionToken: '<PASSWORD>' objectId: 'user_id' $httpBackend.expectGET '/users/me' NgParseUser.checkIfLogged() $httpBackend.flush() NgParseUser.current.should.not.be.null NgParseUser.current.objectId.should.be.equal 'user_id' NgParseUser.current._sessionToken.should.be.equal 'testToken' NgParseUser.logged().should.be.true ngParseRequestConfig.sessionToken.should.be.equal 'testToken'
true
describe 'NgParse.User', -> NgParseUser = null NgParseRequest = null ngParseRequestConfig = null $httpBackend = null $http = null locker = null beforeEach -> angular.mock.module 'ngParse', ($provide) -> $provide.value 'ngParseRequestConfig', appId: 'appId' restApiKey: 'restApiKey' parseUrl: '/' # Simple mock for localStorage $provide.value 'locker', storage: {} driver: -> @ namespace: -> @ put: (key, val) -> @storage[key] = val get: (key, defaultsTo = null) -> if @storage[key]? then @storage[key] else defaultsTo has: (key) -> @storage[key]? forget: (key) -> @storage[key] = null # Extremely important in order to avoid bad errors caused by CoffeeScript. return inject (_NgParseUser_, $injector) -> NgParseUser = _NgParseUser_ NgParseRequest = $injector.get 'NgParseRequest' $httpBackend = $injector.get '$httpBackend' $http = $injector.get '$http' locker = $injector.get 'locker' ngParseRequestConfig = $injector.get 'ngParseRequestConfig' afterEach -> $httpBackend.verifyNoOutstandingExpectation() $httpBackend.verifyNoOutstandingRequest() # Attributes # describe 'Attributes', -> it 'should have attributes inherited from NgParse.Object', -> NgParseUser.totalAttrNames.should.contain 'objectId' it 'should have custom attributes', -> NgParseUser.totalAttrNames.should.have.length 7 NgParseUser.totalAttrNames.should.contain.members ['username', 'email', 'password'] it 'instances should have attributes set', -> user = new NgParseUser username: 'mario', password: 'PI:PASSWORD:<PASSWORD>END_PI' user.username.should.be.equal 'mario' user.password.should.be.equal 'PI:PASSWORD:<PASSWORD>END_PI' # Save # describe 'Save', -> beforeEach -> $httpBackend .when 'PUT', "/users/user_id" .respond objectId: 'user_id' it 'should save correctly the user (using the right URL)', -> user = new NgParseUser objectId: 'user_id' user.username = 'mario' user.dirty.should.have.members ['username'] $httpBackend.expectPUT "/users/user_id" user.save() $httpBackend.flush() user.dirty.should.be.empty # Login # describe 'Login', -> beforeEach -> $httpBackend.expectGET('/login?password=PI:PASSWORD:<PASSWORD>END_PI&username=test').respond 201, sessionToken: 'testPI:PASSWORD:<PASSWORD>END_PI' objectId: 'user_id' NgParseUser.login 'test', 'test' $httpBackend.flush() it 'should grab sessionToken from a correct request', -> NgParseUser.current.should.not.be.null NgParseUser.current._sessionToken.should.be.equal 'testToken' it 'should save sessionToken and correct id in localStorage', -> currentUser = locker.get 'currentUser' currentUser.should.have.keys ['sessionToken', 'objectId'] currentUser.sessionToken.should.be.equal 'testToken' currentUser.objectId.should.be.equal 'user_id' it 'should save correct `current` static variable', -> NgParseUser.current.should.be.an.instanceof NgParseUser NgParseUser.current.objectId.should.be.equal 'user_id' it 'should set sessionToken inside ngParseRequestConfig', -> ngParseRequestConfig.sessionToken.should.be.equal 'testToken' # Logout # describe 'Logout', -> beforeEach -> $httpBackend.expectGET('/login?password=PI:PASSWORD:<PASSWORD>END_PI&username=test').respond 201, sessionToken: 'testToken' objectId: 'user_id' NgParseUser.login 'test', 'test' $httpBackend.flush() it 'should remove `current` static variable and updating `logged` static property', -> NgParseUser.logged().should.be.true NgParseUser.logout() should.not.exist NgParseUser.current NgParseUser.logged().should.be.false it 'should remove sessionToken', -> NgParseUser.logout() should.not.exist ngParseRequestConfig.sessionToken it 'should remove current user data from localStorage', -> NgParseUser.logout() currentUser = locker.get 'currentUser' should.not.exist currentUser # Signup # describe 'Signup', -> beforeEach -> inject ($rootScope) => @$rootScope = $rootScope $httpBackend .when 'POST', "/users/" .respond objectId: 'user_id' sessionToken: 'testSignupToken' @user = new NgParseUser @user.username = 'username' @user.password = 'PI:PASSWORD:<PASSWORD>END_PI' it 'should not allow registration if username is not set', -> wrongUser = new NgParseUser wrongUser.password = 'PI:PASSWORD:<PASSWORD>END_PI' wrongUser.signup().catch (error) => @error = error @$rootScope.$apply() # Resolve promise @error.should.be.equal "Can't register without username and password set" it 'should not allow register if password is not set', -> wrongUser = new NgParseUser wrongUser.username = 'username' wrongUser.signup().catch (error) => @error = error @$rootScope.$apply() # Resolve promise @error.should.be.equal "Can't register without username and password set" it 'should call signup correctly', -> (-> @user.signup() ).should.not.throw it 'should set sessionToken', -> @user.signup() $httpBackend.flush() @user.should.be.equal NgParseUser.current @user._sessionToken.should.be.equal 'testSignupToken' it 'should save into local storage', -> @user.signup() $httpBackend.flush() locker.has('currentUser').should.be.true locker.get('currentUser').should.be.deep.equal sessionToken: 'testSignupToken', objectId: 'user_id' it 'should return a promise', -> promise = @user.signup() $httpBackend.flush() promise.should.respondTo 'then' # Current user general # describe 'Current user', -> beforeEach -> $httpBackend .when 'GET', '/users/me' .respond objectId: 'user_id' it 'should be set to null if not logged', -> should.equal NgParseUser.current, null it 'should fetch the user from `me` path', -> user = new NgParseUser user._sessionToken = 'PI:PASSWORD:<PASSWORD>END_PI' $httpBackend.expectGET '/users/me' user.me() $httpBackend.flush() user.objectId.should.be.equal 'user_id' it 'should load user from localStorage', -> locker.put 'currentUser', sessionToken: 'PI:PASSWORD:<PASSWORD>END_PI' objectId: 'user_id' $httpBackend.expectGET '/users/me' NgParseUser.checkIfLogged() $httpBackend.flush() NgParseUser.current.should.not.be.null NgParseUser.current.objectId.should.be.equal 'user_id' NgParseUser.current._sessionToken.should.be.equal 'testToken' NgParseUser.logged().should.be.true ngParseRequestConfig.sessionToken.should.be.equal 'testToken'
[ { "context": "\n# [Docco](https://github.com/jashkenas/docco) \n# =====\n# > Refactored by [@Amit Portnoy]", "end": 39, "score": 0.9995958805084229, "start": 30, "tag": "USERNAME", "value": "jashkenas" }, { "context": "ub.com/jashkenas/docco) \n# =====\n# > Refactored by [@Amit Portn...
lib/docco.coffee
amitport/gulp-wrap-docco
2
# [Docco](https://github.com/jashkenas/docco) # ===== # > Refactored by [@Amit Portnoy](https://github.com/amitport) # # **Docco** is a quick-and-dirty documentation generator, written in # [Literate CoffeeScript](http://coffeescript.org/#literate). # It produces an HTML document that displays your comments intermingled with your # code. All prose is passed through # [Markdown](http://daringfireball.net/projects/markdown/syntax), and code is # passed through [Highlight.js](http://highlightjs.org/) syntax highlighting. # This page is the result of running Docco against its own # [source file](https://github.com/jashkenas/docco/blob/master/docco.litcoffee). fs = require 'fs' path = require 'path' marked = require 'marked' highlightjs = require 'highlight.js' highlightjs.configure tabReplace: ' ' marked.setOptions smartypants: yes languages = JSON.parse fs.readFileSync("#{__dirname}/languages.json") for ext, l of languages l.commentMatcher = ///^\s*#{l.symbol}\s?/// l.commentFilter = /(^#![/]|^\s*#\{)/ module.exports = (filename, contents) -> # ### configure ext = path.extname(filename) language = languages[ext] if not language throw new Error('Docco cannot find a language associated with files with a \'' + ext + '\' extension') if language and language.name is 'markdown' codeExt = path.extname(path.basename(filename, ext)) if codeExt and codeLang = languages[codeExt] language = name: codeLang.name symbol: codeLang.symbol literate: yes # ### parse lines = contents.split '\n' sections = [] hasCode = docsText = codeText = '' save = -> sections.push {docsText, codeText} hasCode = docsText = codeText = '' if language.literate isText = maybeCode = yes for line, i in lines lines[i] = if maybeCode and match = /^([ ]{4}|[ ]{0,3}\t)/.exec line isText = no line[match[0].length..] else if maybeCode = /^\s*$/.test line if isText then language.symbol else '' else isText = yes language.symbol + ' ' + line for line in lines if line.match(language.commentMatcher) and not line.match(language.commentFilter) save() if hasCode docsText += (line = line.replace(language.commentMatcher, '')) + '\n' save() if /^(---+|===+)$/.test line else hasCode = yes #console.log (/^(\t.*)/.exec(line))?[0].replace /\t/, '\\t-' codeText += line + '\n' save() # ### format sections marked.setOptions { highlight: (code, lang) -> lang or= language.name if highlightjs.getLanguage(lang) highlightjs.fixMarkup(highlightjs.highlight(lang, code).value) else console.warn "docco: couldn't highlight code block with unknown language '#{lang}' in #{source}" code } for section, i in sections code = highlightjs.fixMarkup(highlightjs.highlight(language.name, section.codeText).value) code = code.replace(/\s+$/, '') section.codeHtml = "<div class='highlight'><pre>#{code}</pre></div>" section.docsHtml = marked(section.docsText) {sections}
46824
# [Docco](https://github.com/jashkenas/docco) # ===== # > Refactored by <NAME>](https://github.com/amitport) # # **Docco** is a quick-and-dirty documentation generator, written in # [Literate CoffeeScript](http://coffeescript.org/#literate). # It produces an HTML document that displays your comments intermingled with your # code. All prose is passed through # [Markdown](http://daringfireball.net/projects/markdown/syntax), and code is # passed through [Highlight.js](http://highlightjs.org/) syntax highlighting. # This page is the result of running Docco against its own # [source file](https://github.com/jashkenas/docco/blob/master/docco.litcoffee). fs = require 'fs' path = require 'path' marked = require 'marked' highlightjs = require 'highlight.js' highlightjs.configure tabReplace: ' ' marked.setOptions smartypants: yes languages = JSON.parse fs.readFileSync("#{__dirname}/languages.json") for ext, l of languages l.commentMatcher = ///^\s*#{l.symbol}\s?/// l.commentFilter = /(^#![/]|^\s*#\{)/ module.exports = (filename, contents) -> # ### configure ext = path.extname(filename) language = languages[ext] if not language throw new Error('Docco cannot find a language associated with files with a \'' + ext + '\' extension') if language and language.name is 'markdown' codeExt = path.extname(path.basename(filename, ext)) if codeExt and codeLang = languages[codeExt] language = name: codeLang.name symbol: codeLang.symbol literate: yes # ### parse lines = contents.split '\n' sections = [] hasCode = docsText = codeText = '' save = -> sections.push {docsText, codeText} hasCode = docsText = codeText = '' if language.literate isText = maybeCode = yes for line, i in lines lines[i] = if maybeCode and match = /^([ ]{4}|[ ]{0,3}\t)/.exec line isText = no line[match[0].length..] else if maybeCode = /^\s*$/.test line if isText then language.symbol else '' else isText = yes language.symbol + ' ' + line for line in lines if line.match(language.commentMatcher) and not line.match(language.commentFilter) save() if hasCode docsText += (line = line.replace(language.commentMatcher, '')) + '\n' save() if /^(---+|===+)$/.test line else hasCode = yes #console.log (/^(\t.*)/.exec(line))?[0].replace /\t/, '\\t-' codeText += line + '\n' save() # ### format sections marked.setOptions { highlight: (code, lang) -> lang or= language.name if highlightjs.getLanguage(lang) highlightjs.fixMarkup(highlightjs.highlight(lang, code).value) else console.warn "docco: couldn't highlight code block with unknown language '#{lang}' in #{source}" code } for section, i in sections code = highlightjs.fixMarkup(highlightjs.highlight(language.name, section.codeText).value) code = code.replace(/\s+$/, '') section.codeHtml = "<div class='highlight'><pre>#{code}</pre></div>" section.docsHtml = marked(section.docsText) {sections}
true
# [Docco](https://github.com/jashkenas/docco) # ===== # > Refactored by PI:NAME:<NAME>END_PI](https://github.com/amitport) # # **Docco** is a quick-and-dirty documentation generator, written in # [Literate CoffeeScript](http://coffeescript.org/#literate). # It produces an HTML document that displays your comments intermingled with your # code. All prose is passed through # [Markdown](http://daringfireball.net/projects/markdown/syntax), and code is # passed through [Highlight.js](http://highlightjs.org/) syntax highlighting. # This page is the result of running Docco against its own # [source file](https://github.com/jashkenas/docco/blob/master/docco.litcoffee). fs = require 'fs' path = require 'path' marked = require 'marked' highlightjs = require 'highlight.js' highlightjs.configure tabReplace: ' ' marked.setOptions smartypants: yes languages = JSON.parse fs.readFileSync("#{__dirname}/languages.json") for ext, l of languages l.commentMatcher = ///^\s*#{l.symbol}\s?/// l.commentFilter = /(^#![/]|^\s*#\{)/ module.exports = (filename, contents) -> # ### configure ext = path.extname(filename) language = languages[ext] if not language throw new Error('Docco cannot find a language associated with files with a \'' + ext + '\' extension') if language and language.name is 'markdown' codeExt = path.extname(path.basename(filename, ext)) if codeExt and codeLang = languages[codeExt] language = name: codeLang.name symbol: codeLang.symbol literate: yes # ### parse lines = contents.split '\n' sections = [] hasCode = docsText = codeText = '' save = -> sections.push {docsText, codeText} hasCode = docsText = codeText = '' if language.literate isText = maybeCode = yes for line, i in lines lines[i] = if maybeCode and match = /^([ ]{4}|[ ]{0,3}\t)/.exec line isText = no line[match[0].length..] else if maybeCode = /^\s*$/.test line if isText then language.symbol else '' else isText = yes language.symbol + ' ' + line for line in lines if line.match(language.commentMatcher) and not line.match(language.commentFilter) save() if hasCode docsText += (line = line.replace(language.commentMatcher, '')) + '\n' save() if /^(---+|===+)$/.test line else hasCode = yes #console.log (/^(\t.*)/.exec(line))?[0].replace /\t/, '\\t-' codeText += line + '\n' save() # ### format sections marked.setOptions { highlight: (code, lang) -> lang or= language.name if highlightjs.getLanguage(lang) highlightjs.fixMarkup(highlightjs.highlight(lang, code).value) else console.warn "docco: couldn't highlight code block with unknown language '#{lang}' in #{source}" code } for section, i in sections code = highlightjs.fixMarkup(highlightjs.highlight(language.name, section.codeText).value) code = code.replace(/\s+$/, '') section.codeHtml = "<div class='highlight'><pre>#{code}</pre></div>" section.docsHtml = marked(section.docsText) {sections}
[ { "context": "ngoose.Schema\n userName : String\n passWord : String\n email : String\n role : String\n adm", "end": 147, "score": 0.574726402759552, "start": 141, "tag": "PASSWORD", "value": "String" } ]
schemas/users.coffee
ruicky/node-wiki
99
mongoose = require 'mongoose' # # 创建用户的shcema # @type {mongoose} # UserSchema = new mongoose.Schema userName : String passWord : String email : String role : String admin : Boolean meta : createAt : type : Date default : Date.now() updateAt : type : Date, default : Date.now() # # 给save方法添加预处理 # UserSchema.pre 'save', (next) -> if this.isNew this.meta.createAt = this.meta.updateAt = Date.now() else this.meta.updateAt = Date.now() next() return # # 绑定静态方法 # @type {Object} # UserSchema.statics = fetch : (cb) -> @.find {} .sort 'meta.updateAt' .exec cb findBy : (id,cb) -> #console.log(id); @.find _id:id .sort 'meta.updateAt' .exec cb findByEmail : (id,cb) -> #console.log(id); @.find email:id .sort 'meta.updateAt' .exec cb module.exports = UserSchema
33980
mongoose = require 'mongoose' # # 创建用户的shcema # @type {mongoose} # UserSchema = new mongoose.Schema userName : String passWord : <PASSWORD> email : String role : String admin : Boolean meta : createAt : type : Date default : Date.now() updateAt : type : Date, default : Date.now() # # 给save方法添加预处理 # UserSchema.pre 'save', (next) -> if this.isNew this.meta.createAt = this.meta.updateAt = Date.now() else this.meta.updateAt = Date.now() next() return # # 绑定静态方法 # @type {Object} # UserSchema.statics = fetch : (cb) -> @.find {} .sort 'meta.updateAt' .exec cb findBy : (id,cb) -> #console.log(id); @.find _id:id .sort 'meta.updateAt' .exec cb findByEmail : (id,cb) -> #console.log(id); @.find email:id .sort 'meta.updateAt' .exec cb module.exports = UserSchema
true
mongoose = require 'mongoose' # # 创建用户的shcema # @type {mongoose} # UserSchema = new mongoose.Schema userName : String passWord : PI:PASSWORD:<PASSWORD>END_PI email : String role : String admin : Boolean meta : createAt : type : Date default : Date.now() updateAt : type : Date, default : Date.now() # # 给save方法添加预处理 # UserSchema.pre 'save', (next) -> if this.isNew this.meta.createAt = this.meta.updateAt = Date.now() else this.meta.updateAt = Date.now() next() return # # 绑定静态方法 # @type {Object} # UserSchema.statics = fetch : (cb) -> @.find {} .sort 'meta.updateAt' .exec cb findBy : (id,cb) -> #console.log(id); @.find _id:id .sort 'meta.updateAt' .exec cb findByEmail : (id,cb) -> #console.log(id); @.find email:id .sort 'meta.updateAt' .exec cb module.exports = UserSchema
[ { "context": "###\n# Copyright (C) 2012 jareiko / http://www.jareiko.net/\n###\n\ndefine [\n 'THREE'", "end": 32, "score": 0.9990600943565369, "start": 25, "tag": "USERNAME", "value": "jareiko" }, { "context": "r tx in [txCenter-3..txCenter+3]\n key = tx + ',' + ty\n ...
server/public/scripts/client/scenery.coffee
triggerrally/triggerrally.github.io
1
### # Copyright (C) 2012 jareiko / http://www.jareiko.net/ ### define [ 'THREE' 'cs!client/array_geometry' 'cs!util/quiver' ], (THREE, array_geometry, quiver) -> RenderScenery: class RenderScenery constructor: (@scene, @scenery, @loadFunc) -> @fadeSpeed = 2 @layers = (@createLayer l for l in @scenery.layers) createLayer: (src) -> meshes = [] tiles = Object.create null render = src.config.render @loadFunc render["scene-r54"] or render["scene"], (result) -> for mesh in result.scene.children geom = new array_geometry.ArrayGeometry() geom.addGeometry mesh.geometry #geom.material = mesh.material mesh.geometry = geom meshes.push mesh return { src, tiles, meshes } createTile: (layer, tx, ty, skipFadeIn) -> entities = layer.src.getTile(tx, ty) return null unless entities renderConfig = layer.src.config.render tile = new THREE.Object3D tile.position.x = (tx + 0.5) * layer.src.cache.gridSize tile.position.y = (ty + 0.5) * layer.src.cache.gridSize tile.opacity = if skipFadeIn then 1 else 0 if entities.length > 0 for object in layer.meshes # We merge copies of each object into a single mesh. mergedGeom = new array_geometry.ArrayGeometry() mesh = new THREE.Mesh object.geometry for entity in entities mesh.scale.copy object.scale if renderConfig.scale? then mesh.scale.multiplyScalar renderConfig.scale mesh.scale.multiplyScalar entity.scale mesh.position.sub entity.position, tile.position mesh.rotation.add object.rotation, entity.rotation mergedGeom.mergeMesh mesh mergedGeom.updateOffsets() # Clone the material so that we can adjust opacity per tile. material = object.material.clone() material.opacity = tile.opacity # Force all objects to be transparent so we can fade them in and out. material.transparent = yes # material.blending = THREE.NormalBlending mesh = new THREE.Mesh mergedGeom, material mesh.doubleSided = object.doubleSided mesh.castShadow = object.castShadow mesh.receiveShadow = object.receiveShadow tile.add mesh return tile removeTile: (layer, key) -> @scene.remove layer.tiles[key] for mesh in layer.tiles[key] mesh.dispose() delete layer.tiles[key] return update: (camera, delta) -> added = no addAll = no fadeAmount = @fadeSpeed * delta # TODO: This shouldn't be done every frame. It should be notified of changes. for layer, i in @scenery.layers @layers[i] or= @createLayer layer continue unless @layers[i].src isnt layer keys = (key for key of @layers[i].tiles) @removeTile @layers[i], key for key in keys @layers[i].src = layer addAll = yes # TODO: Remove layers that have disappeared from @scenery. for layer in @layers continue unless layer.meshes.length > 0 # Check that we have something to draw. visibleTiles = {} txCenter = Math.floor(camera.position.x / layer.src.cache.gridSize) tyCenter = Math.floor(camera.position.y / layer.src.cache.gridSize) for ty in [tyCenter-3..tyCenter+3] for tx in [txCenter-3..txCenter+3] key = tx + ',' + ty visibleTiles[key] = yes tile = layer.tiles[key] if not tile and (addAll or not added) tile = @createTile layer, tx, ty, addAll added = yes if tile layer.tiles[key] = tile @scene.add tile if tile and tile.opacity < 1 tile.opacity = Math.min 1, tile.opacity + fadeAmount for mesh in tile.children mesh.material.opacity = tile.opacity toRemove = (key for key of layer.tiles when not visibleTiles[key]) for key in toRemove tile = layer.tiles[key] tile.opacity -= fadeAmount if tile.opacity > 0 for mesh in tile.children mesh.material.opacity = tile.opacity else @removeTile layer, key return
200682
### # Copyright (C) 2012 jareiko / http://www.jareiko.net/ ### define [ 'THREE' 'cs!client/array_geometry' 'cs!util/quiver' ], (THREE, array_geometry, quiver) -> RenderScenery: class RenderScenery constructor: (@scene, @scenery, @loadFunc) -> @fadeSpeed = 2 @layers = (@createLayer l for l in @scenery.layers) createLayer: (src) -> meshes = [] tiles = Object.create null render = src.config.render @loadFunc render["scene-r54"] or render["scene"], (result) -> for mesh in result.scene.children geom = new array_geometry.ArrayGeometry() geom.addGeometry mesh.geometry #geom.material = mesh.material mesh.geometry = geom meshes.push mesh return { src, tiles, meshes } createTile: (layer, tx, ty, skipFadeIn) -> entities = layer.src.getTile(tx, ty) return null unless entities renderConfig = layer.src.config.render tile = new THREE.Object3D tile.position.x = (tx + 0.5) * layer.src.cache.gridSize tile.position.y = (ty + 0.5) * layer.src.cache.gridSize tile.opacity = if skipFadeIn then 1 else 0 if entities.length > 0 for object in layer.meshes # We merge copies of each object into a single mesh. mergedGeom = new array_geometry.ArrayGeometry() mesh = new THREE.Mesh object.geometry for entity in entities mesh.scale.copy object.scale if renderConfig.scale? then mesh.scale.multiplyScalar renderConfig.scale mesh.scale.multiplyScalar entity.scale mesh.position.sub entity.position, tile.position mesh.rotation.add object.rotation, entity.rotation mergedGeom.mergeMesh mesh mergedGeom.updateOffsets() # Clone the material so that we can adjust opacity per tile. material = object.material.clone() material.opacity = tile.opacity # Force all objects to be transparent so we can fade them in and out. material.transparent = yes # material.blending = THREE.NormalBlending mesh = new THREE.Mesh mergedGeom, material mesh.doubleSided = object.doubleSided mesh.castShadow = object.castShadow mesh.receiveShadow = object.receiveShadow tile.add mesh return tile removeTile: (layer, key) -> @scene.remove layer.tiles[key] for mesh in layer.tiles[key] mesh.dispose() delete layer.tiles[key] return update: (camera, delta) -> added = no addAll = no fadeAmount = @fadeSpeed * delta # TODO: This shouldn't be done every frame. It should be notified of changes. for layer, i in @scenery.layers @layers[i] or= @createLayer layer continue unless @layers[i].src isnt layer keys = (key for key of @layers[i].tiles) @removeTile @layers[i], key for key in keys @layers[i].src = layer addAll = yes # TODO: Remove layers that have disappeared from @scenery. for layer in @layers continue unless layer.meshes.length > 0 # Check that we have something to draw. visibleTiles = {} txCenter = Math.floor(camera.position.x / layer.src.cache.gridSize) tyCenter = Math.floor(camera.position.y / layer.src.cache.gridSize) for ty in [tyCenter-3..tyCenter+3] for tx in [txCenter-3..txCenter+3] key = <KEY> visibleTiles[key] = yes tile = layer.tiles[key] if not tile and (addAll or not added) tile = @createTile layer, tx, ty, addAll added = yes if tile layer.tiles[key] = tile @scene.add tile if tile and tile.opacity < 1 tile.opacity = Math.min 1, tile.opacity + fadeAmount for mesh in tile.children mesh.material.opacity = tile.opacity toRemove = (key for key of layer.tiles when not visibleTiles[key]) for key in toRemove tile = layer.tiles[key] tile.opacity -= fadeAmount if tile.opacity > 0 for mesh in tile.children mesh.material.opacity = tile.opacity else @removeTile layer, key return
true
### # Copyright (C) 2012 jareiko / http://www.jareiko.net/ ### define [ 'THREE' 'cs!client/array_geometry' 'cs!util/quiver' ], (THREE, array_geometry, quiver) -> RenderScenery: class RenderScenery constructor: (@scene, @scenery, @loadFunc) -> @fadeSpeed = 2 @layers = (@createLayer l for l in @scenery.layers) createLayer: (src) -> meshes = [] tiles = Object.create null render = src.config.render @loadFunc render["scene-r54"] or render["scene"], (result) -> for mesh in result.scene.children geom = new array_geometry.ArrayGeometry() geom.addGeometry mesh.geometry #geom.material = mesh.material mesh.geometry = geom meshes.push mesh return { src, tiles, meshes } createTile: (layer, tx, ty, skipFadeIn) -> entities = layer.src.getTile(tx, ty) return null unless entities renderConfig = layer.src.config.render tile = new THREE.Object3D tile.position.x = (tx + 0.5) * layer.src.cache.gridSize tile.position.y = (ty + 0.5) * layer.src.cache.gridSize tile.opacity = if skipFadeIn then 1 else 0 if entities.length > 0 for object in layer.meshes # We merge copies of each object into a single mesh. mergedGeom = new array_geometry.ArrayGeometry() mesh = new THREE.Mesh object.geometry for entity in entities mesh.scale.copy object.scale if renderConfig.scale? then mesh.scale.multiplyScalar renderConfig.scale mesh.scale.multiplyScalar entity.scale mesh.position.sub entity.position, tile.position mesh.rotation.add object.rotation, entity.rotation mergedGeom.mergeMesh mesh mergedGeom.updateOffsets() # Clone the material so that we can adjust opacity per tile. material = object.material.clone() material.opacity = tile.opacity # Force all objects to be transparent so we can fade them in and out. material.transparent = yes # material.blending = THREE.NormalBlending mesh = new THREE.Mesh mergedGeom, material mesh.doubleSided = object.doubleSided mesh.castShadow = object.castShadow mesh.receiveShadow = object.receiveShadow tile.add mesh return tile removeTile: (layer, key) -> @scene.remove layer.tiles[key] for mesh in layer.tiles[key] mesh.dispose() delete layer.tiles[key] return update: (camera, delta) -> added = no addAll = no fadeAmount = @fadeSpeed * delta # TODO: This shouldn't be done every frame. It should be notified of changes. for layer, i in @scenery.layers @layers[i] or= @createLayer layer continue unless @layers[i].src isnt layer keys = (key for key of @layers[i].tiles) @removeTile @layers[i], key for key in keys @layers[i].src = layer addAll = yes # TODO: Remove layers that have disappeared from @scenery. for layer in @layers continue unless layer.meshes.length > 0 # Check that we have something to draw. visibleTiles = {} txCenter = Math.floor(camera.position.x / layer.src.cache.gridSize) tyCenter = Math.floor(camera.position.y / layer.src.cache.gridSize) for ty in [tyCenter-3..tyCenter+3] for tx in [txCenter-3..txCenter+3] key = PI:KEY:<KEY>END_PI visibleTiles[key] = yes tile = layer.tiles[key] if not tile and (addAll or not added) tile = @createTile layer, tx, ty, addAll added = yes if tile layer.tiles[key] = tile @scene.add tile if tile and tile.opacity < 1 tile.opacity = Math.min 1, tile.opacity + fadeAmount for mesh in tile.children mesh.material.opacity = tile.opacity toRemove = (key for key of layer.tiles when not visibleTiles[key]) for key in toRemove tile = layer.tiles[key] tile.opacity -= fadeAmount if tile.opacity > 0 for mesh in tile.children mesh.material.opacity = tile.opacity else @removeTile layer, key return
[ { "context": "# Copyright (C) 2013 John Judnich\n# Released under The MIT License - see \"LICENSE\" ", "end": 33, "score": 0.9998623132705688, "start": 21, "tag": "NAME", "value": "John Judnich" } ]
shaders/StarfieldShader.coffee
anandprabhakar0507/Kosmos
46
# Copyright (C) 2013 John Judnich # Released under The MIT License - see "LICENSE" file for details. frag = """ precision mediump float; varying vec3 vUVA; varying vec4 vColor; void main(void) { // compute star color based on intensity = 1/dist^2 from center of sprite vec2 dv = vUVA.xy; float d = dot(dv, dv); float lum = 1.0 / (d*100.0); // fall off at a max radius, since 1/dist^2 goes on infinitely d = clamp(d * 4.0, 0.0, 1.0); lum *= 1.0 - d*d; gl_FragColor.xyz = clamp(vColor.xyz*lum, 0.0, 1.0) * vUVA.z * vColor.a; } """ vert = """ attribute vec4 aPos; attribute vec3 aUV; // third component marks one vertex for blur extrusion uniform mat4 projMat; uniform mat4 modelViewMat; uniform vec3 starSizeAndViewRangeAndBlur; //uniform mat4 modelMat; //uniform mat4 viewMat; varying vec3 vUVA; varying vec4 vColor; void main(void) { // determine star size float starSize = starSizeAndViewRangeAndBlur.x; //starSize = starSize * (cos(aPos.w*1000.0) * 0.5 + 1.0); // modulate size by simple PRNG // compute vertex position so quad is always camera-facing vec4 pos = vec4(aPos.xyz, 1.0); vec2 offset = aUV.xy * starSize; //pos = viewMat * modelMat * pos; pos = modelViewMat * pos; pos.xy += offset; // motion blur pos.z *= 1.0 + aUV.z * starSizeAndViewRangeAndBlur.z; // fade out distant stars float dist = length(pos.xyz); float alpha = clamp((1.0 - (dist / starSizeAndViewRangeAndBlur.y)) * 3.0, 0.0, 1.0); // the UV coordinates are used to render the actual star radial gradient, // and alpha is used to modulate intensity of distant stars as they fade out vUVA = vec3(aUV.xy, alpha); // compute star color parameter // this is just an arbitrary hand-tweaked interpolation between blue/white/red // favoring mostly blue and white with some red vColor.xyz = vec3( 1.0 - aPos.w, aPos.w*2.0*(1.0-aPos.w), 4.0 * aPos.w ) * 0.5 + 0.5; // dim stars to account for extra motion blur lit pixels vColor.w = max(0.33, 1.0 - sqrt(abs(starSizeAndViewRangeAndBlur.z))*1.5); // red/blue shift vColor.xyz += vec3(-starSizeAndViewRangeAndBlur.z, -abs(starSizeAndViewRangeAndBlur.z), starSizeAndViewRangeAndBlur.z); // output position, or degenerate triangle if star is beyond view range if (alpha > 0.0) { gl_Position = projMat * pos; // fix subpixel flickering by adding slight screenspace size gl_Position.xy += aUV.xy * max(0.0, gl_Position.z) / 300.0; // distant stars more colorful vColor = clamp(vColor, 0.0, 1.0 + gl_Position.z * 0.001); } else { gl_Position = vec4(0, 0, 0, 0); } } """ xgl.addProgram("starfield", vert, frag)
113335
# Copyright (C) 2013 <NAME> # Released under The MIT License - see "LICENSE" file for details. frag = """ precision mediump float; varying vec3 vUVA; varying vec4 vColor; void main(void) { // compute star color based on intensity = 1/dist^2 from center of sprite vec2 dv = vUVA.xy; float d = dot(dv, dv); float lum = 1.0 / (d*100.0); // fall off at a max radius, since 1/dist^2 goes on infinitely d = clamp(d * 4.0, 0.0, 1.0); lum *= 1.0 - d*d; gl_FragColor.xyz = clamp(vColor.xyz*lum, 0.0, 1.0) * vUVA.z * vColor.a; } """ vert = """ attribute vec4 aPos; attribute vec3 aUV; // third component marks one vertex for blur extrusion uniform mat4 projMat; uniform mat4 modelViewMat; uniform vec3 starSizeAndViewRangeAndBlur; //uniform mat4 modelMat; //uniform mat4 viewMat; varying vec3 vUVA; varying vec4 vColor; void main(void) { // determine star size float starSize = starSizeAndViewRangeAndBlur.x; //starSize = starSize * (cos(aPos.w*1000.0) * 0.5 + 1.0); // modulate size by simple PRNG // compute vertex position so quad is always camera-facing vec4 pos = vec4(aPos.xyz, 1.0); vec2 offset = aUV.xy * starSize; //pos = viewMat * modelMat * pos; pos = modelViewMat * pos; pos.xy += offset; // motion blur pos.z *= 1.0 + aUV.z * starSizeAndViewRangeAndBlur.z; // fade out distant stars float dist = length(pos.xyz); float alpha = clamp((1.0 - (dist / starSizeAndViewRangeAndBlur.y)) * 3.0, 0.0, 1.0); // the UV coordinates are used to render the actual star radial gradient, // and alpha is used to modulate intensity of distant stars as they fade out vUVA = vec3(aUV.xy, alpha); // compute star color parameter // this is just an arbitrary hand-tweaked interpolation between blue/white/red // favoring mostly blue and white with some red vColor.xyz = vec3( 1.0 - aPos.w, aPos.w*2.0*(1.0-aPos.w), 4.0 * aPos.w ) * 0.5 + 0.5; // dim stars to account for extra motion blur lit pixels vColor.w = max(0.33, 1.0 - sqrt(abs(starSizeAndViewRangeAndBlur.z))*1.5); // red/blue shift vColor.xyz += vec3(-starSizeAndViewRangeAndBlur.z, -abs(starSizeAndViewRangeAndBlur.z), starSizeAndViewRangeAndBlur.z); // output position, or degenerate triangle if star is beyond view range if (alpha > 0.0) { gl_Position = projMat * pos; // fix subpixel flickering by adding slight screenspace size gl_Position.xy += aUV.xy * max(0.0, gl_Position.z) / 300.0; // distant stars more colorful vColor = clamp(vColor, 0.0, 1.0 + gl_Position.z * 0.001); } else { gl_Position = vec4(0, 0, 0, 0); } } """ xgl.addProgram("starfield", vert, frag)
true
# Copyright (C) 2013 PI:NAME:<NAME>END_PI # Released under The MIT License - see "LICENSE" file for details. frag = """ precision mediump float; varying vec3 vUVA; varying vec4 vColor; void main(void) { // compute star color based on intensity = 1/dist^2 from center of sprite vec2 dv = vUVA.xy; float d = dot(dv, dv); float lum = 1.0 / (d*100.0); // fall off at a max radius, since 1/dist^2 goes on infinitely d = clamp(d * 4.0, 0.0, 1.0); lum *= 1.0 - d*d; gl_FragColor.xyz = clamp(vColor.xyz*lum, 0.0, 1.0) * vUVA.z * vColor.a; } """ vert = """ attribute vec4 aPos; attribute vec3 aUV; // third component marks one vertex for blur extrusion uniform mat4 projMat; uniform mat4 modelViewMat; uniform vec3 starSizeAndViewRangeAndBlur; //uniform mat4 modelMat; //uniform mat4 viewMat; varying vec3 vUVA; varying vec4 vColor; void main(void) { // determine star size float starSize = starSizeAndViewRangeAndBlur.x; //starSize = starSize * (cos(aPos.w*1000.0) * 0.5 + 1.0); // modulate size by simple PRNG // compute vertex position so quad is always camera-facing vec4 pos = vec4(aPos.xyz, 1.0); vec2 offset = aUV.xy * starSize; //pos = viewMat * modelMat * pos; pos = modelViewMat * pos; pos.xy += offset; // motion blur pos.z *= 1.0 + aUV.z * starSizeAndViewRangeAndBlur.z; // fade out distant stars float dist = length(pos.xyz); float alpha = clamp((1.0 - (dist / starSizeAndViewRangeAndBlur.y)) * 3.0, 0.0, 1.0); // the UV coordinates are used to render the actual star radial gradient, // and alpha is used to modulate intensity of distant stars as they fade out vUVA = vec3(aUV.xy, alpha); // compute star color parameter // this is just an arbitrary hand-tweaked interpolation between blue/white/red // favoring mostly blue and white with some red vColor.xyz = vec3( 1.0 - aPos.w, aPos.w*2.0*(1.0-aPos.w), 4.0 * aPos.w ) * 0.5 + 0.5; // dim stars to account for extra motion blur lit pixels vColor.w = max(0.33, 1.0 - sqrt(abs(starSizeAndViewRangeAndBlur.z))*1.5); // red/blue shift vColor.xyz += vec3(-starSizeAndViewRangeAndBlur.z, -abs(starSizeAndViewRangeAndBlur.z), starSizeAndViewRangeAndBlur.z); // output position, or degenerate triangle if star is beyond view range if (alpha > 0.0) { gl_Position = projMat * pos; // fix subpixel flickering by adding slight screenspace size gl_Position.xy += aUV.xy * max(0.0, gl_Position.z) / 300.0; // distant stars more colorful vColor = clamp(vColor, 0.0, 1.0 + gl_Position.z * 0.001); } else { gl_Position = vec4(0, 0, 0, 0); } } """ xgl.addProgram("starfield", vert, frag)
[ { "context": "ed.\n#\n\n# Based on Github.js 0.7.0\n#\n# (c) 2012 Michael Aufreiter, Development Seed\n# Github.js is freely distr", "end": 259, "score": 0.9998656511306763, "start": 242, "tag": "NAME", "value": "Michael Aufreiter" }, { "context": "ails and documentation:\n# ...
public/js/octokit/octokit.coffee
alfredo-pozo/DynamoDictionary
11
# Github Promise API # ====== # # This class provides a Promise API for accessing GitHub. # Most methods return a Promise object whose value is resolved when `.then(doneFn, failFn)` # is called. # # Based on Github.js 0.7.0 # # (c) 2012 Michael Aufreiter, Development Seed # Github.js is freely distributable under the MIT license. # For all details and documentation: # http://substance.io/michael/github # Underscore shim # ========= # # The following code is a shim for the underscore.js functions this code relise on _ = {} _.isEmpty = (object) -> Object.keys(object).length == 0 _.isArray = Array.isArray or (obj) -> toString.call(obj) is'[object Array]' _.defaults = (object, values) -> for key in Object.keys(values) do (key) -> object[key] ?= values[key] _.each = (object, fn) -> return if not object if _.isArray(object) object.forEach(fn) arr = [] for key in Object.keys(object) do (key) -> fn(object[key]) _.pairs = (object) -> arr = [] for key in Object.keys(object) do (key) -> arr.push([key, object[key]]) return arr _.map = (object, fn) -> if _.isArray(object) return object.map(fn) arr = [] for key in Object.keys(object) do (key) -> arr.push(fn(object[key])) arr _.last = (object, n) -> len = object.length object.slice(len - n, len) _.select = (object, fn) -> object.filter(fn) _.extend = (object, template) -> for key in Object.keys(template) do (key) -> object[key] = template[key] object _.toArray = (object) -> return Array.prototype.slice.call(object) # Generate a Github class # ========= # # Depending on how this is loaded (nodejs, requirejs, globals) # the actual underscore, jQuery.ajax/Deferred, and base64 encode functions may differ. makeOctokit = (newPromise, allPromises, XMLHttpRequest, base64encode, userAgent) => # Simple jQuery.ajax() shim that returns a promise for a xhr object ajax = (options) -> return newPromise (resolve, reject) -> xhr = new XMLHttpRequest() xhr.dataType = options.dataType xhr.overrideMimeType?(options.mimeType) xhr.open(options.type, options.url) if options.data and 'GET' != options.type xhr.setRequestHeader('Content-Type', options.contentType) for name, value of options.headers xhr.setRequestHeader(name, value) xhr.onreadystatechange = () -> if 4 == xhr.readyState options.statusCode?[xhr.status]?() if xhr.status >= 200 and xhr.status < 300 or xhr.status == 304 resolve(xhr) else reject(xhr) xhr.send(options.data) # Returns an always-resolved promise (like `Promise.resolve(val)` ) resolvedPromise = (val) -> return newPromise (resolve, reject) -> resolve(val) # Returns an always-rejected promise (like `Promise.reject(err)` ) rejectedPromise = (err) -> return newPromise (resolve, reject) -> reject(err) class Octokit constructor: (clientOptions={}) -> # Provide an option to override the default URL _.defaults clientOptions, rootURL: 'https://api.github.com' useETags: true usePostInsteadOfPatch: false _client = @ # Useful for other classes (like Repo) to get the current Client object # These are updated whenever a request is made _listeners = [] # To support ETag caching cache the responses. class ETagResponse constructor: (@eTag, @data, @status) -> # Cached responses are stored in this object keyed by `path` _cachedETags = {} # Send simple progress notifications notifyStart = (promise, path) -> promise.notify? {type:'start', path:path} notifyEnd = (promise, path) -> promise.notify? {type:'end', path:path} # HTTP Request Abstraction # ======= # _request = (method, path, data, options={raw:false, isBase64:false, isBoolean:false}) -> if 'PATCH' == method and clientOptions.usePostInsteadOfPatch method = 'POST' # Only prefix the path when it does not begin with http. # This is so pagination works (which provides absolute URLs). path = "#{clientOptions.rootURL}#{path}" if not /^http/.test(path) # Support binary data by overriding the response mimeType mimeType = undefined mimeType = 'text/plain; charset=x-user-defined' if options.isBase64 headers = { 'Accept': 'application/vnd.github.raw' } # Set the `User-Agent` because it is required and NodeJS # does not send one by default. # See http://developer.github.com/v3/#user-agent-required headers['User-Agent'] = userAgent if userAgent # Send the ETag if re-requesting a URL if path of _cachedETags headers['If-None-Match'] = _cachedETags[path].eTag else # The browser will sneak in a 'If-Modified-Since' header if the GET has been requested before # but for some reason the cached response does not seem to be available # in the jqXHR object. # So, the first time a URL is requested set this date to 0 so we always get a response the 1st time # a URL is requested. headers['If-Modified-Since'] = 'Thu, 01 Jan 1970 00:00:00 GMT' if (clientOptions.token) or (clientOptions.username and clientOptions.password) if clientOptions.token auth = "token #{clientOptions.token}" else auth = 'Basic ' + base64encode("#{clientOptions.username}:#{clientOptions.password}") headers['Authorization'] = auth promise = newPromise (resolve, reject) -> ajaxConfig = # Be sure to **not** blow the cache with a random number # (GitHub will respond with 5xx or CORS errors) url: path type: method contentType: 'application/json' mimeType: mimeType headers: headers processData: false # Don't convert to QueryString data: !options.raw and data and JSON.stringify(data) or data dataType: 'json' unless options.raw # If the request is a boolean yes/no question GitHub will indicate # via the HTTP Status of 204 (No Content) or 404 instead of a 200. if options.isBoolean ajaxConfig.statusCode = # a Boolean 'yes' 204: () => resolve(true) # a Boolean 'no' 404: () => resolve(false) xhrPromise = ajax(ajaxConfig) always = (jqXHR) => notifyEnd(@, path) # Fire listeners when the request completes or fails rateLimit = parseFloat(jqXHR.getResponseHeader 'X-RateLimit-Limit') rateLimitRemaining = parseFloat(jqXHR.getResponseHeader 'X-RateLimit-Remaining') for listener in _listeners listener(rateLimitRemaining, rateLimit, method, path, data, options) # Return the result and Base64 encode it if `options.isBase64` flag is set. xhrPromise.then (jqXHR) -> always(jqXHR) # If the response was a 304 then return the cached version if 304 == jqXHR.status if clientOptions.useETags and _cachedETags[path] eTagResponse = _cachedETags[path] resolve(eTagResponse.data, eTagResponse.status, jqXHR) else resolve(jqXHR.responseText, status, jqXHR) # If it was a boolean question and the server responded with 204 # return true. else if 204 == jqXHR.status and options.isBoolean resolve(true, status, jqXHR) else if jqXHR.responseText and 'json' == ajaxConfig.dataType data = JSON.parse(jqXHR.responseText) # Only JSON responses have next/prev/first/last link headers # Add them to data so the resolved value is iterable valOptions = {} # Parse the Link headers # of the form `<http://a.com>; rel="next", <https://b.com?a=b&c=d>; rel="previous"` links = jqXHR.getResponseHeader('Link') _.each links?.split(','), (part) -> [discard, href, rel] = part.match(/<([^>]+)>;\ rel="([^"]+)"/) # Name the functions `nextPage`, `previousPage`, `firstPage`, `lastPage` valOptions["#{rel}Page"] = () -> _request('GET', href, null, options) # Add the pagination functions on the JSON since Promises resolve one value _.extend(data, valOptions) else data = jqXHR.responseText # Convert the response to a Base64 encoded string if 'GET' == method and options.isBase64 # Convert raw data to binary chopping off the higher-order bytes in each char. # Useful for Base64 encoding. converted = '' for i in [0..data.length] converted += String.fromCharCode(data.charCodeAt(i) & 0xff) data = converted # Cache the response to reuse later if 'GET' == method and jqXHR.getResponseHeader('ETag') and clientOptions.useETags eTag = jqXHR.getResponseHeader('ETag') _cachedETags[path] = new ETagResponse(eTag, data, jqXHR.status) resolve(data, jqXHR.status, jqXHR) # Parse the error if one occurs onError = (jqXHR) -> always(jqXHR) # If the request was for a Boolean then a 404 should be treated as a "false" if options.isBoolean and 404 == jqXHR.status resolve(false) else if jqXHR.getResponseHeader('Content-Type') != 'application/json; charset=utf-8' err = new Error(jqXHR.responseText) err['status'] = jqXHR.status err['__jqXHR'] = jqXHR reject(err) else err = new Error("Github error: #{jqXHR.responseText}") if jqXHR.responseText json = JSON.parse(jqXHR.responseText) else # In the case of 404 errors, `responseText` is an empty string json = '' # XXX: should be body or something else probably err['error'] = json err['status'] = jqXHR.status err['__jqXHR'] = jqXHR reject(err) # Depending on the Promise implementation, the `catch` method may be `.catch` or `.fail` xhrPromise.catch?(onError) or xhrPromise.fail(onError) notifyStart(promise, path) # Return the promise return promise # Converts a dictionary to a query string. # Internal helper method toQueryString = (options) -> # Returns '' if `options` is empty so this string can always be appended to a URL return '' if _.isEmpty(options) params = [] _.each _.pairs(options), ([key, value]) -> params.push "#{key}=#{encodeURIComponent(value)}" return "?#{params.join('&')}" # Clear the local cache # ------- @clearCache = clearCache = () -> _cachedETags = {} ## Get the local cache # ------- @getCache = getCache = () -> _cachedETags ## Set the local cache # ------- @setCache = setCache = (cachedETags) -> # check if argument is valid. unless cachedETags != null and typeof cachedETags == 'object' throw new Error 'BUG: argument of method "setCache" should be an object' else _cachedETags = cachedETags # Add a listener that fires when the `rateLimitRemaining` changes as a result of # communicating with github. @onRateLimitChanged = (listener) -> _listeners.push listener # Random zen quote (test the API) # ------- @getZen = () -> # Send `data` to `null` and the `raw` flag to `true` _request 'GET', '/zen', null, {raw:true} # Get all users # ------- @getAllUsers = (since=null) -> options = {} options.since = since if since _request 'GET', '/users', options # List public repositories for an Organization # ------- @getOrgRepos = (orgName, type='all') -> _request 'GET', "/orgs/#{orgName}/repos?type=#{type}&per_page=1000&sort=updated&direction=desc", null # Get public Gists on all of GitHub # ------- @getPublicGists = (since=null) -> options = null # Converts a Date object to a string getDate = (time) -> return time.toISOString() if Date == time.constructor return time options = {since: getDate(since)} if since _request 'GET', '/gists/public', options # List Public Events on all of GitHub # ------- @getPublicEvents = () -> _request 'GET', '/events', null # List unread notifications for authenticated user # ------- # Optional arguments: # # - `all`: `true` to show notifications marked as read. # - `participating`: `true` to show only notifications in which the user is directly participating or mentioned. # - `since`: Optional time. @getNotifications = (options={}) -> # Converts a Date object to a string getDate = (time) -> return time.toISOString() if Date == time.constructor return time options.since = getDate(options.since) if options.since queryString = toQueryString(options) _request 'GET', "/notifications#{queryString}", null # Github Users API # ======= class User # Store the username constructor: (_username=null) -> # Private var that stores the root path. # Use a different URL if this user is the authenticated user if _username _rootPath = "/users/#{_username}" else _rootPath = "/user" # Retrieve user information # ------- _cachedInfo = null @getInfo = (force=false) -> _cachedInfo = null if force if _cachedInfo return resolvedPromise(_cachedInfo) _request('GET', "#{_rootPath}", null) # Squirrel away the user info .then (info) -> _cachedInfo = info # List user repositories # ------- @getRepos = (type='all', sort='pushed', direction='desc') -> _request 'GET', "#{_rootPath}/repos?type=#{type}&per_page=1000&sort=#{sort}&direction=#{direction}", null # List user organizations # ------- @getOrgs = () -> _request 'GET', "#{_rootPath}/orgs", null # List a user's gists # ------- @getGists = () -> _request 'GET', "#{_rootPath}/gists", null # List followers of a user # ------- @getFollowers = () -> _request 'GET', "#{_rootPath}/followers", null # List who this user is following # ------- @getFollowing = () -> _request 'GET', "#{_rootPath}/following", null # Check if this user is following another user # ------- @isFollowing = (user) -> _request 'GET', "#{_rootPath}/following/#{user}", null, {isBoolean:true} # List public keys for a user # ------- @getPublicKeys = () -> _request 'GET', "#{_rootPath}/keys", null # Get Received events for this user # ------- @getReceivedEvents = (onlyPublic) -> throw new Error 'BUG: This does not work for authenticated users yet!' if not _username isPublic = '' isPublic = '/public' if onlyPublic _request 'GET', "/users/#{_username}/received_events#{isPublic}", null # Get all events for this user # ------- @getEvents = (onlyPublic) -> throw new Error 'BUG: This does not work for authenticated users yet!' if not _username isPublic = '' isPublic = '/public' if onlyPublic _request 'GET', "/users/#{_username}/events#{isPublic}", null # Authenticated User API # ======= class AuthenticatedUser extends User constructor: () -> super() # Update the authenticated user # ------- # # Valid options: # - `name`: String # - `email` : Publicly visible email address # - `blog`: String # - `company`: String # - `location`: String # - `hireable`: Boolean # - `bio`: String @updateInfo = (options) -> _request 'PATCH', '/user', options # List authenticated user's gists # ------- @getGists = () -> _request 'GET', '/gists', null # Follow a user # ------- @follow = (username) -> _request 'PUT', "/user/following/#{username}", null # Unfollow user # ------- @unfollow = (username) -> _request 'DELETE', "/user/following/#{username}", null # Get Emails associated with this user # ------- @getEmails = () -> _request 'GET', '/user/emails', null # Add Emails associated with this user # ------- @addEmail = (emails) -> emails = [emails] if !_.isArray(emails) _request 'POST', '/user/emails', emails # Remove Emails associated with this user # ------- @addEmail = (emails) -> emails = [emails] if !_.isArray(emails) _request 'DELETE', '/user/emails', emails # Get a single public key # ------- @getPublicKey = (id) -> _request 'GET', "/user/keys/#{id}", null # Add a public key # ------- @addPublicKey = (title, key) -> _request 'POST', "/user/keys", {title: title, key: key} # Update a public key # ------- @updatePublicKey = (id, options) -> _request 'PATCH', "/user/keys/#{id}", options # Create a repository # ------- # # Optional parameters: # - `description`: String # - `homepage`: String # - `private`: boolean (Default `false`) # - `has_issues`: boolean (Default `true`) # - `has_wiki`: boolean (Default `true`) # - `has_downloads`: boolean (Default `true`) # - `auto_init`: boolean (Default `false`) @createRepo = (name, options={}) -> options.name = name _request 'POST', "/user/repos", options # Get Received events for this authenticated user # ------- @getReceivedEvents = (username, page = 1) -> currentPage = '?page=' + page _request 'GET', '/users/' + username + '/received_events' + currentPage, null @getStars = () -> _request 'GET', "/user/starred" @putStar = (owner, repo) -> _request 'PUT', "/user/starred/#{owner}/#{repo}" @deleteStar = (owner, repo) -> _request 'DELETE', "/user/starred/#{owner}/#{repo}" # Organization API # ======= class Team constructor: (@id) -> @getInfo = () -> _request 'GET', "/teams/#{@id}", null # - `name` # - `permission` @updateTeam = (options) -> _request 'PATCH', "/teams/#{@id}", options @remove = () -> _request 'DELETE', "/teams/#{@id}" @getMembers = () -> _request 'GET', "/teams/#{@id}/members" @isMember = (user) -> _request 'GET', "/teams/#{@id}/members/#{user}", null, {isBoolean:true} @addMember = (user) -> _request 'PUT', "/teams/#{@id}/members/#{user}" @removeMember = (user) -> _request 'DELETE', "/teams/#{@id}/members/#{user}" @getRepos = () -> _request 'GET', "/teams/#{@id}/repos" @addRepo = (orgName, repoName) -> _request 'PUT', "/teams/#{@id}/repos/#{orgName}/#{repoName}" @removeRepo = (orgName, repoName) -> _request 'DELETE', "/teams/#{@id}/repos/#{orgName}/#{repoName}" class Organization constructor: (@name) -> @getInfo = () -> _request 'GET', "/orgs/#{@name}", null # - `billing_email`: Billing email address. This address is not publicized. # - `company` # - `email` # - `location` # - `name` @updateInfo = (options) -> _request 'PATCH', "/orgs/#{@name}", options @getTeams = () -> _request 'GET', "/orgs/#{@name}/teams", null # `permission` can be one of `pull`, `push`, or `admin` @createTeam = (name, repoNames=null, permission='pull') -> options = {name: name, permission: permission} options.repo_names = repoNames if repoNames _request 'POST', "/orgs/#{@name}/teams", options @getMembers = () -> _request 'GET', "/orgs/#{@name}/members", null @isMember = (user) -> _request 'GET', "/orgs/#{@name}/members/#{user}", null, {isBoolean:true} @removeMember = (user) -> _request 'DELETE', "/orgs/#{@name}/members/#{user}", null # Create a repository # ------- # # Optional parameters are the same as `.getUser().createRepo()` with one addition: # - `team_id`: number @createRepo = (name, options={}) -> options.name = name _request 'POST', "/orgs/#{@name}/repos", options # List repos for an organisation # ------- @getRepos = () -> _request 'GET', "/orgs/#{@name}/repos?type=all", null # Repository API # ======= # Low-level class for manipulating a Git Repository # ------- class GitRepo constructor: (@repoUser, @repoName) -> _repoPath = "/repos/#{@repoUser}/#{@repoName}" # Delete this Repository # ------- # **Note:** This is here instead of on the `Repository` object # so it is less likely to accidentally be used. @deleteRepo = () -> _request 'DELETE', "#{_repoPath}" # Uses the cache if branch has not been changed # ------- @_updateTree = (branch) -> @getRef("heads/#{branch}") # Get a particular reference # ------- @getRef = (ref) -> _request('GET', "#{_repoPath}/git/refs/#{ref}", null) .then (res) => return res.object.sha # Create a new reference # -------- # # { # "ref": "refs/heads/my-new-branch-name", # "sha": "827efc6d56897b048c772eb4087f854f46256132" # } @createRef = (options) -> _request 'POST', "#{_repoPath}/git/refs", options # Delete a reference # -------- # # repo.deleteRef('heads/gh-pages') # repo.deleteRef('tags/v1.0') @deleteRef = (ref) -> _request 'DELETE', "#{_repoPath}/git/refs/#{ref}", @options # List all branches of a repository # ------- @getBranches = () -> _request('GET', "#{_repoPath}/git/refs/heads", null) .then (heads) => return _.map(heads, (head) -> _.last head.ref.split("/") ) # Retrieve the contents of a blob # ------- @getBlob = (sha, isBase64) -> _request 'GET', "#{_repoPath}/git/blobs/#{sha}", null, {raw:true, isBase64:isBase64} # For a given file path, get the corresponding sha (blob for files, tree for dirs) # ------- @getSha = (branch, path) -> # Just use head if path is empty return @getRef("heads/#{branch}") if path is '' @getTree(branch, {recursive:true}) .then (tree) => file = _.select(tree, (file) -> file.path is path )[0] return file?.sha if file?.sha # Return a promise that has failed if no sha was found return rejectedPromise {message: 'SHA_NOT_FOUND'} # Get contents (file/dir) # ------- @getContents = (path, sha=null) -> queryString = '' if sha != null queryString = toQueryString({ref:sha}) _request('GET', "#{_repoPath}/contents/#{path}#{queryString}", null, {raw:true}) .then (contents) => return contents # Remove a file from the tree # ------- @removeFile = (path, message, sha, branch) -> params = message: message sha: sha branch: branch _request 'DELETE', "#{_repoPath}/contents/#{path}", params, null # Retrieve the tree a commit points to # ------- # Optionally set recursive to true @getTree = (tree, options=null) -> queryString = toQueryString(options) _request('GET', "#{_repoPath}/git/trees/#{tree}#{queryString}", null) .then (res) => return res.tree # Post a new blob object, getting a blob SHA back # ------- @postBlob = (content, isBase64) -> if typeof (content) is 'string' # Base64 encode the content if it is binary (isBase64) content = base64encode(content) if isBase64 content = content: content encoding: 'utf-8' content.encoding = 'base64' if isBase64 _request('POST', "#{_repoPath}/git/blobs", content) .then (res) => return res.sha # Update an existing tree adding a new blob object getting a tree SHA back # ------- # `newTree` is of the form: # # [ { # path: path # mode: '100644' # type: 'blob' # sha: blob # } ] @updateTreeMany = (baseTree, newTree) -> data = base_tree: baseTree tree: newTree _request('POST', "#{_repoPath}/git/trees", data) .then (res) => return res.sha # Post a new tree object having a file path pointer replaced # with a new blob SHA getting a tree SHA back # ------- @postTree = (tree) -> _request('POST', "#{_repoPath}/git/trees", {tree: tree}) .then (res) => return res.sha # Create a new commit object with the current commit SHA as the parent # and the new tree SHA, getting a commit SHA back # ------- @commit = (parents, tree, message) -> parents = [parents] if not _.isArray(parents) data = message: message parents: parents tree: tree _request('POST', "#{_repoPath}/git/commits", data) .then((commit) -> return commit.sha) # Update the reference of your head to point to the new commit SHA # ------- @updateHead = (head, commit, force=false) -> options = {sha:commit} options.force = true if force _request 'PATCH', "#{_repoPath}/git/refs/heads/#{head}", options # Get a single commit # -------------------- @getCommit = (sha) -> _request('GET', "#{_repoPath}/commits/#{sha}", null) # List commits on a repository. # ------- # Takes an object of optional paramaters: # # - `sha`: SHA or branch to start listing commits from # - `path`: Only commits containing this file path will be returned # - `author`: GitHub login, name, or email by which to filter by commit author # - `since`: ISO 8601 date - only commits after this date will be returned # - `until`: ISO 8601 date - only commits before this date will be returned @getCommits = (options={}) -> options = _.extend {}, options # Converts a Date object to a string getDate = (time) -> return time.toISOString() if Date == time.constructor return time options.since = getDate(options.since) if options.since options.until = getDate(options.until) if options.until queryString = toQueryString(options) _request('GET', "#{_repoPath}/commits#{queryString}", null) # Branch Class # ------- # Provides common methods that may require several git operations. class Branch constructor: (git, getRef) -> # Private variables _git = git _getRef = getRef or -> throw new Error 'BUG: No way to fetch branch ref!' # Get a single commit # -------------------- @getCommit = (sha) -> _git.getCommit(sha) # List commits on a branch. # ------- # Takes an object of optional paramaters: # # - `path`: Only commits containing this file path will be returned # - `author`: GitHub login, name, or email by which to filter by commit author # - `since`: ISO 8601 date - only commits after this date will be returned # - `until`: ISO 8601 date - only commits before this date will be returned @getCommits = (options={}) -> options = _.extend {}, options # Limit to the current branch _getRef() .then (branch) -> options.sha = branch _git.getCommits(options) # Creates a new branch based on the current reference of this branch # ------- @createBranch = (newBranchName) -> _getRef() .then (branch) => _git.getSha(branch, '') .then (sha) => _git.createRef({sha:sha, ref:"refs/heads/#{newBranchName}"}) # Read file at given path # ------- # Set `isBase64=true` to get back a base64 encoded binary file @read = (path, isBase64) -> _getRef() .then (branch) => _git.getSha(branch, path) .then (sha) => _git.getBlob(sha, isBase64) # Return both the commit hash and the content .then (bytes) => return {sha:sha, content:bytes} # Get contents at given path # ------- @contents = (path) -> _getRef() .then (branch) => _git.getSha(branch, '') .then (sha) => _git.getContents(path, sha) .then (contents) => return contents # Remove a file from the tree # ------- # Optionally provide the sha of the file so it is not accidentally # deleted if the repo has changed in the meantime. @remove = (path, message="Removed #{path}", sha=null) -> _getRef() .then (branch) => if sha _git.removeFile(path, message, sha, branch) else _git.getSha(branch, path) .then (sha) => _git.removeFile(path, message, sha, branch) # Move a file to a new location # ------- @move = (path, newPath, message="Moved #{path}") -> _getRef() .then (branch) => _git._updateTree(branch) .then (latestCommit) => _git.getTree(latestCommit, {recursive:true}) .then (tree) => # Update Tree _.each tree, (ref) -> ref.path = newPath if ref.path is path delete ref.sha if ref.type is 'tree' _git.postTree(tree) .then (rootTree) => _git.commit(latestCommit, rootTree, message) .then (commit) => _git.updateHead(branch, commit) .then (res) => return res # Finally, return the result # Write file contents to a given branch and path # ------- # To write base64 encoded data set `isBase64==true` # # Optionally takes a `parentCommitSha` which will be used as the # parent of this commit @write = (path, content, message="Changed #{path}", isBase64, parentCommitSha=null) -> contents = {} contents[path] = content: content isBase64: isBase64 @writeMany(contents, message, parentCommitSha) # Write the contents of multiple files to a given branch # ------- # Each file can also be binary. # # In general `contents` is a map where the key is the path and the value is `{content:'Hello World!', isBase64:false}`. # In the case of non-base64 encoded files the value may be a string instead. # # Example: # # contents = { # 'hello.txt': 'Hello World!', # 'path/to/hello2.txt': { content: 'Ahoy!', isBase64: false} # } # # Optionally takes an array of `parentCommitShas` which will be used as the # parents of this commit. @writeMany = (contents, message="Changed Multiple", parentCommitShas=null) -> # This method: # # 0. Finds the latest commit if one is not provided # 1. Asynchronously send new blobs for each file # 2. Use the return of the new Blob Post to return an entry in the new Commit Tree # 3. Wait on all the new blobs to finish # 4. Commit and update the branch _getRef() .then (branch) => # See below for Step 0. afterParentCommitShas = (parentCommitShas) => # 1. Asynchronously send all the files as new blobs. promises = _.map _.pairs(contents), ([path, data]) -> # `data` can be an object or a string. # If it is a string assume isBase64 is false and the string is the content content = data.content or data isBase64 = data.isBase64 or false _git.postBlob(content, isBase64) .then (blob) => # 2. return an entry in the new Commit Tree return { path: path mode: '100644' type: 'blob' sha: blob } # 3. Wait on all the new blobs to finish # Different Promise APIs implement this differently. For example: # - Promise uses `Promise.all([...])` # - jQuery uses `jQuery.when(p1, p2, p3, ...)` allPromises(promises) .then (newTrees) => _git.updateTreeMany(parentCommitShas, newTrees) .then (tree) => # 4. Commit and update the branch _git.commit(parentCommitShas, tree, message) .then (commitSha) => _git.updateHead(branch, commitSha) .then (res) => # Finally, return the result return res.object # Return something that has a `.sha` to match the signature for read # 0. Finds the latest commit if one is not provided if parentCommitShas return afterParentCommitShas(parentCommitShas) else return _git._updateTree(branch).then(afterParentCommitShas) # Repository Class # ------- # Provides methods for operating on the entire repository # and ways to operate on a `Branch`. class Repository constructor: (@options) -> # Private fields _user = @options.user _repo = @options.name # Set the `git` instance variable @git = new GitRepo(_user, _repo) @repoPath = "/repos/#{_user}/#{_repo}" @currentTree = branch: null sha: null @updateInfo = (options) -> _request 'PATCH', @repoPath, options # List all branches of a repository # ------- @getBranches = () -> @git.getBranches() # Get a branch of a repository # ------- @getBranch = (branchName=null) -> if branchName getRef = () => return resolvedPromise(branchName) return new Branch(@git, getRef) else return @getDefaultBranch() # Get the default branch of a repository # ------- @getDefaultBranch = () -> # Calls getInfo() to get the default branch name getRef = => @getInfo() .then (info) => return info.default_branch new Branch(@git, getRef) @setDefaultBranch = (branchName) -> @updateInfo {name: _repo, default_branch: branchName} # Get repository information # ------- @getInfo = () -> _request 'GET', @repoPath, null # Get contents # -------- @getContents = (branch, path) -> _request 'GET', "#{@repoPath}/contents?ref=#{branch}", {path: path} # Fork repository # ------- @fork = (organization) -> if organization _request 'POST', "#{@repoPath}/forks", organization: organization else _request 'POST', "#{@repoPath}/forks", null # Create pull request # -------- @createPullRequest = (options) -> _request 'POST', "#{@repoPath}/pulls", options # Get recent commits to the repository # -------- # Takes an object of optional paramaters: # # - `path`: Only commits containing this file path will be returned # - `author`: GitHub login, name, or email by which to filter by commit author # - `since`: ISO 8601 date - only commits after this date will be returned # - `until`: ISO 8601 date - only commits before this date will be returned @getCommits = (options) -> @git.getCommits(options) # List repository events # ------- @getEvents = () -> _request 'GET', "#{@repoPath}/events", null # List Issue events for a Repository # ------- @getIssueEvents = () -> _request 'GET', "#{@repoPath}/issues/events", null # List events for a network of Repositories # ------- @getNetworkEvents = () -> _request 'GET', "/networks/#{_user}/#{_repo}/events", null # List unread notifications for authenticated user # ------- # Optional arguments: # # - `all`: `true` to show notifications marked as read. # - `participating`: `true` to show only notifications in which # the user is directly participating or mentioned. # - `since`: Optional time. @getNotifications = (options={}) -> # Converts a Date object to a string getDate = (time) -> return time.toISOString() if Date == time.constructor return time options.since = getDate(options.since) if options.since queryString = toQueryString(options) _request 'GET', "#{@repoPath}/notifications#{queryString}", null # List Collaborators # ------- # When authenticating as an organization owner of an # organization-owned repository, all organization owners # are included in the list of collaborators. # Otherwise, only users with access to the repository are # returned in the collaborators list. @getCollaborators = () -> _request 'GET', "#{@repoPath}/collaborators", null @addCollaborator = (username) -> throw new Error 'BUG: username is required' if not username _request 'PUT', "#{@repoPath}/collaborators/#{username}", null, {isBoolean:true} @removeCollaborator = (username) -> throw new Error 'BUG: username is required' if not username _request 'DELETE', "#{@repoPath}/collaborators/#{username}", null, {isBoolean:true} @isCollaborator = (username=null) -> throw new Error 'BUG: username is required' if not username _request 'GET', "#{@repoPath}/collaborators/#{username}", null, {isBoolean:true} # Can Collaborate # ------- # True if the authenticated user has permission # to commit to this repository. @canCollaborate = () -> # Short-circuit if no credentials provided if not (clientOptions.password or clientOptions.token) return resolvedPromise(false) _client.getLogin() .then (login) => if not login return false else return @isCollaborator(login) .then null, (err) => # Problem logging in (maybe bad username/password) return false # List all hooks # ------- @getHooks = () -> _request 'GET', "#{@repoPath}/hooks", null # Get single hook # ------- @getHook = (id) -> _request 'GET', "#{@repoPath}/hooks/#{id}", null # Create a new hook # ------- # # - `name` (Required string) : The name of the service that is being called. # (See /hooks for the list of valid hook names.) # - `config` (Required hash) : A Hash containing key/value pairs to provide settings for this hook. # These settings vary between the services and are defined in the github-services repo. # - `events` (Optional array) : Determines what events the hook is triggered for. Default: ["push"]. # - `active` (Optional boolean) : Determines whether the hook is actually triggered on pushes. @createHook = (name, config, events=['push'], active=true) -> data = name: name config: config events: events active: active _request 'POST', "#{@repoPath}/hooks", data # Edit a hook # ------- # # - `config` (Optional hash) : A Hash containing key/value pairs to provide settings for this hook. # Modifying this will replace the entire config object. # These settings vary between the services and are defined in the github-services repo. # - `events` (Optional array) : Determines what events the hook is triggered for. # This replaces the entire array of events. Default: ["push"]. # - `addEvents` (Optional array) : Determines a list of events to be added to the list of events that the Hook triggers for. # - `removeEvents` (Optional array) : Determines a list of events to be removed from the list of events that the Hook triggers for. # - `active` (Optional boolean) : Determines whether the hook is actually triggered on pushes. @editHook = (id, config=null, events=null, addEvents=null, removeEvents=null, active=null) -> data = {} data.config = config if config != null data.events = events if events != null data.add_events = addEvents if addEvents != null data.remove_events = removeEvents if removeEvents != null data.active = active if active != null _request 'PATCH', "#{@repoPath}/hooks/#{id}", data # Test a `push` hook # ------- # This will trigger the hook with the latest push to the current # repository if the hook is subscribed to push events. # If the hook is not subscribed to push events, the server will # respond with 204 but no test POST will be generated. @testHook = (id) -> _request 'POST', "#{@repoPath}/hooks/#{id}/tests", null # Delete a hook # ------- @deleteHook = (id) -> _request 'DELETE', "#{@repoPath}/hooks/#{id}", null # List all Languages # ------- @getLanguages = -> _request 'GET', "#{@repoPath}/languages", null # List all releases # ------- @getReleases = () -> _request 'GET', "#{@repoPath}/releases", null # Gist API # ------- class Gist constructor: (@options) -> id = @options.id _gistPath = "/gists/#{id}" # Read the gist # -------- @read = () -> _request 'GET', _gistPath, null # Create the gist # -------- # # Files contains a hash with the filename as the key and # `{content: 'File Contents Here'}` as the value. # # Example: # # { "file1.txt": { # "content": "String file contents" # } # } @create = (files, isPublic=false, description=null) -> options = isPublic: isPublic files: files options.description = description if description? _request 'POST', "/gists", options # Delete the gist # -------- @delete = () -> _request 'DELETE', _gistPath, null # Fork a gist # -------- @fork = () -> _request 'POST', "#{_gistPath}/forks", null # Update a gist with the new stuff # -------- # `files` are files that make up this gist. # The key of which should be an optional string filename # and the value another optional hash with parameters: # # - `content`: Optional string - Updated file contents # - `filename`: Optional string - New name for this file. # # **NOTE:** All files from the previous version of the gist are carried # over by default if not included in the hash. Deletes can be performed # by including the filename with a null hash. @update = (files, description=null) -> options = {files: files} options.description = description if description? _request 'PATCH', _gistPath, options # Star a gist # ------- @star = () -> _request 'PUT', "#{_gistPath}/star" # Unstar a gist # ------- @unstar = () -> _request 'DELETE', "#{_gistPath}/star" # Check if a gist is starred # ------- @isStarred = () -> _request 'GET', "#{_gistPath}", null, {isBoolean:true} # Top Level API # ------- @getRepo = (user, repo) -> throw new Error('BUG! user argument is required') if not user throw new Error('BUG! repo argument is required') if not repo new Repository( user: user name: repo ) @getOrg = (name) -> new Organization(name) # API for viewing info for arbitrary users or the current user # if no arguments are provided. @getUser = (login=null) -> if login return new User(login) else if clientOptions.password or clientOptions.token return new AuthenticatedUser() else return null @getGist = (id) -> new Gist(id: id) # Returns the login of the current user. # When using OAuth this is unknown but is necessary to # determine if the current user has commit access to a # repository @getLogin = () -> # 3 cases: # 1. No authentication provided # 2. Username (and password) provided # 3. OAuth token provided if clientOptions.password or clientOptions.token return new User().getInfo() .then (info) -> return info.login else return resolvedPromise(null) # Return the class for assignment return Octokit # Register with nodejs, requirejs, or as a global # ------- # Depending on the context this file is called, register it appropriately if exports? # Use native promises if Harmony is on Promise = @Promise or require('es6-promise').Promise XMLHttpRequest = @XMLHttpRequest or require('xmlhttprequest').XMLHttpRequest newPromise = (fn) -> return new Promise(fn) allPromises = (promises) -> return Promise.all.call(Promise, promises) # Encode using native Base64 encode = @btoa or (str) -> buffer = new Buffer(str, 'binary') return buffer.toString('base64') Octokit = makeOctokit(newPromise, allPromises, XMLHttpRequest, encode, 'octokit') # `User-Agent` (for nodejs) exports.new = (options) -> new Octokit(options) else # Octokit is being used in the browser. # Find a Promise API and register with `define` (if available) # Register Octokit once a Promise API is loaded. # In the case of angular, this may be async. createGlobalAndAMD = (newPromise, allPromises) => if @define? @define 'octokit', [], () => return makeOctokit(newPromise, allPromises, @XMLHttpRequest, @btoa) else Octokit = makeOctokit(newPromise, allPromises, @XMLHttpRequest, @btoa) # Assign to a global `Octokit` @Octokit = Octokit @Github = Octokit # Determine the correct Promise factory. # Try to use libraries before native Promises since most Promise users # are already using a library. # # Try in the following order: # - Q Promise # - angularjs Promise # - jQuery Promise # - native Promise or a polyfill if @Q newPromise = (fn) => deferred = @Q.defer() resolve = (val) -> deferred.resolve(val) reject = (err) -> deferred.reject(err) fn(resolve, reject) return deferred.promise allPromises = (promises) -> @Q.all(promises) createGlobalAndAMD(newPromise, allPromises) else if @angular # Details on Angular Promises: http://docs.angularjs.org/api/ng/service/$q injector = angular.injector(['ng']) injector.invoke ($q) -> newPromise = (fn) -> deferred = $q.defer() resolve = (val) -> deferred.resolve(val) reject = (err) -> deferred.reject(err) fn(resolve, reject) return deferred.promise allPromises = (promises) -> $q.all(promises) createGlobalAndAMD(newPromise, allPromises) else if @jQuery?.Deferred newPromise = (fn) => promise = @jQuery.Deferred() resolve = (val) -> promise.resolve(val) reject = (val) -> promise.reject(val) fn(resolve, reject) return promise.promise() allPromises = (promises) => # `jQuery.when` is a little odd. # - It accepts each promise as an argument (instead of an array of promises) # - Each resolved value is an argument (instead of an array of values) # # So, convert the array of promises to args and then the resolved args to an array return @jQuery.when(promises...).then((promises...) -> return promises) createGlobalAndAMD(newPromise, allPromises) else if @Promise newPromise = (fn) => return new @Promise (resolve, reject) -> # Some browsers (like node-webkit 0.8.6) contain an older implementation # of Promises that provide 1 argument (a `PromiseResolver`). if resolve.fulfill fn(resolve.resolve.bind(resolve), resolve.reject.bind(resolve)) else fn(arguments...) allPromises = (promises) => @Promise.all.call(@Promise, promises) createGlobalAndAMD(newPromise, allPromises) else # Otherwise, throw an error err = (msg) -> console?.error?(msg) throw new Error(msg) err('A Promise API was not found. Supported libraries that have Promises are jQuery, angularjs, and https://github.com/jakearchibald/es6-promise')
144170
# Github Promise API # ====== # # This class provides a Promise API for accessing GitHub. # Most methods return a Promise object whose value is resolved when `.then(doneFn, failFn)` # is called. # # Based on Github.js 0.7.0 # # (c) 2012 <NAME>, Development Seed # Github.js is freely distributable under the MIT license. # For all details and documentation: # http://substance.io/michael/github # Underscore shim # ========= # # The following code is a shim for the underscore.js functions this code relise on _ = {} _.isEmpty = (object) -> Object.keys(object).length == 0 _.isArray = Array.isArray or (obj) -> toString.call(obj) is'[object Array]' _.defaults = (object, values) -> for key in Object.keys(values) do (key) -> object[key] ?= values[key] _.each = (object, fn) -> return if not object if _.isArray(object) object.forEach(fn) arr = [] for key in Object.keys(object) do (key) -> fn(object[key]) _.pairs = (object) -> arr = [] for key in Object.keys(object) do (key) -> arr.push([key, object[key]]) return arr _.map = (object, fn) -> if _.isArray(object) return object.map(fn) arr = [] for key in Object.keys(object) do (key) -> arr.push(fn(object[key])) arr _.last = (object, n) -> len = object.length object.slice(len - n, len) _.select = (object, fn) -> object.filter(fn) _.extend = (object, template) -> for key in Object.keys(template) do (key) -> object[key] = template[key] object _.toArray = (object) -> return Array.prototype.slice.call(object) # Generate a Github class # ========= # # Depending on how this is loaded (nodejs, requirejs, globals) # the actual underscore, jQuery.ajax/Deferred, and base64 encode functions may differ. makeOctokit = (newPromise, allPromises, XMLHttpRequest, base64encode, userAgent) => # Simple jQuery.ajax() shim that returns a promise for a xhr object ajax = (options) -> return newPromise (resolve, reject) -> xhr = new XMLHttpRequest() xhr.dataType = options.dataType xhr.overrideMimeType?(options.mimeType) xhr.open(options.type, options.url) if options.data and 'GET' != options.type xhr.setRequestHeader('Content-Type', options.contentType) for name, value of options.headers xhr.setRequestHeader(name, value) xhr.onreadystatechange = () -> if 4 == xhr.readyState options.statusCode?[xhr.status]?() if xhr.status >= 200 and xhr.status < 300 or xhr.status == 304 resolve(xhr) else reject(xhr) xhr.send(options.data) # Returns an always-resolved promise (like `Promise.resolve(val)` ) resolvedPromise = (val) -> return newPromise (resolve, reject) -> resolve(val) # Returns an always-rejected promise (like `Promise.reject(err)` ) rejectedPromise = (err) -> return newPromise (resolve, reject) -> reject(err) class Octokit constructor: (clientOptions={}) -> # Provide an option to override the default URL _.defaults clientOptions, rootURL: 'https://api.github.com' useETags: true usePostInsteadOfPatch: false _client = @ # Useful for other classes (like Repo) to get the current Client object # These are updated whenever a request is made _listeners = [] # To support ETag caching cache the responses. class ETagResponse constructor: (@eTag, @data, @status) -> # Cached responses are stored in this object keyed by `path` _cachedETags = {} # Send simple progress notifications notifyStart = (promise, path) -> promise.notify? {type:'start', path:path} notifyEnd = (promise, path) -> promise.notify? {type:'end', path:path} # HTTP Request Abstraction # ======= # _request = (method, path, data, options={raw:false, isBase64:false, isBoolean:false}) -> if 'PATCH' == method and clientOptions.usePostInsteadOfPatch method = 'POST' # Only prefix the path when it does not begin with http. # This is so pagination works (which provides absolute URLs). path = "#{clientOptions.rootURL}#{path}" if not /^http/.test(path) # Support binary data by overriding the response mimeType mimeType = undefined mimeType = 'text/plain; charset=x-user-defined' if options.isBase64 headers = { 'Accept': 'application/vnd.github.raw' } # Set the `User-Agent` because it is required and NodeJS # does not send one by default. # See http://developer.github.com/v3/#user-agent-required headers['User-Agent'] = userAgent if userAgent # Send the ETag if re-requesting a URL if path of _cachedETags headers['If-None-Match'] = _cachedETags[path].eTag else # The browser will sneak in a 'If-Modified-Since' header if the GET has been requested before # but for some reason the cached response does not seem to be available # in the jqXHR object. # So, the first time a URL is requested set this date to 0 so we always get a response the 1st time # a URL is requested. headers['If-Modified-Since'] = 'Thu, 01 Jan 1970 00:00:00 GMT' if (clientOptions.token) or (clientOptions.username and clientOptions.password) if clientOptions.token auth = "token #{clientOptions.token}" else auth = 'Basic ' + base64encode("#{clientOptions.username}:#{clientOptions.password}") headers['Authorization'] = auth promise = newPromise (resolve, reject) -> ajaxConfig = # Be sure to **not** blow the cache with a random number # (GitHub will respond with 5xx or CORS errors) url: path type: method contentType: 'application/json' mimeType: mimeType headers: headers processData: false # Don't convert to QueryString data: !options.raw and data and JSON.stringify(data) or data dataType: 'json' unless options.raw # If the request is a boolean yes/no question GitHub will indicate # via the HTTP Status of 204 (No Content) or 404 instead of a 200. if options.isBoolean ajaxConfig.statusCode = # a Boolean 'yes' 204: () => resolve(true) # a Boolean 'no' 404: () => resolve(false) xhrPromise = ajax(ajaxConfig) always = (jqXHR) => notifyEnd(@, path) # Fire listeners when the request completes or fails rateLimit = parseFloat(jqXHR.getResponseHeader 'X-RateLimit-Limit') rateLimitRemaining = parseFloat(jqXHR.getResponseHeader 'X-RateLimit-Remaining') for listener in _listeners listener(rateLimitRemaining, rateLimit, method, path, data, options) # Return the result and Base64 encode it if `options.isBase64` flag is set. xhrPromise.then (jqXHR) -> always(jqXHR) # If the response was a 304 then return the cached version if 304 == jqXHR.status if clientOptions.useETags and _cachedETags[path] eTagResponse = _cachedETags[path] resolve(eTagResponse.data, eTagResponse.status, jqXHR) else resolve(jqXHR.responseText, status, jqXHR) # If it was a boolean question and the server responded with 204 # return true. else if 204 == jqXHR.status and options.isBoolean resolve(true, status, jqXHR) else if jqXHR.responseText and 'json' == ajaxConfig.dataType data = JSON.parse(jqXHR.responseText) # Only JSON responses have next/prev/first/last link headers # Add them to data so the resolved value is iterable valOptions = {} # Parse the Link headers # of the form `<http://a.com>; rel="next", <https://b.com?a=b&c=d>; rel="previous"` links = jqXHR.getResponseHeader('Link') _.each links?.split(','), (part) -> [discard, href, rel] = part.match(/<([^>]+)>;\ rel="([^"]+)"/) # Name the functions `nextPage`, `previousPage`, `firstPage`, `lastPage` valOptions["#{rel}Page"] = () -> _request('GET', href, null, options) # Add the pagination functions on the JSON since Promises resolve one value _.extend(data, valOptions) else data = jqXHR.responseText # Convert the response to a Base64 encoded string if 'GET' == method and options.isBase64 # Convert raw data to binary chopping off the higher-order bytes in each char. # Useful for Base64 encoding. converted = '' for i in [0..data.length] converted += String.fromCharCode(data.charCodeAt(i) & 0xff) data = converted # Cache the response to reuse later if 'GET' == method and jqXHR.getResponseHeader('ETag') and clientOptions.useETags eTag = jqXHR.getResponseHeader('ETag') _cachedETags[path] = new ETagResponse(eTag, data, jqXHR.status) resolve(data, jqXHR.status, jqXHR) # Parse the error if one occurs onError = (jqXHR) -> always(jqXHR) # If the request was for a Boolean then a 404 should be treated as a "false" if options.isBoolean and 404 == jqXHR.status resolve(false) else if jqXHR.getResponseHeader('Content-Type') != 'application/json; charset=utf-8' err = new Error(jqXHR.responseText) err['status'] = jqXHR.status err['__jqXHR'] = jqXHR reject(err) else err = new Error("Github error: #{jqXHR.responseText}") if jqXHR.responseText json = JSON.parse(jqXHR.responseText) else # In the case of 404 errors, `responseText` is an empty string json = '' # XXX: should be body or something else probably err['error'] = json err['status'] = jqXHR.status err['__jqXHR'] = jqXHR reject(err) # Depending on the Promise implementation, the `catch` method may be `.catch` or `.fail` xhrPromise.catch?(onError) or xhrPromise.fail(onError) notifyStart(promise, path) # Return the promise return promise # Converts a dictionary to a query string. # Internal helper method toQueryString = (options) -> # Returns '' if `options` is empty so this string can always be appended to a URL return '' if _.isEmpty(options) params = [] _.each _.pairs(options), ([key, value]) -> params.push "#{key}=#{encodeURIComponent(value)}" return "?#{params.join('&')}" # Clear the local cache # ------- @clearCache = clearCache = () -> _cachedETags = {} ## Get the local cache # ------- @getCache = getCache = () -> _cachedETags ## Set the local cache # ------- @setCache = setCache = (cachedETags) -> # check if argument is valid. unless cachedETags != null and typeof cachedETags == 'object' throw new Error 'BUG: argument of method "setCache" should be an object' else _cachedETags = cachedETags # Add a listener that fires when the `rateLimitRemaining` changes as a result of # communicating with github. @onRateLimitChanged = (listener) -> _listeners.push listener # Random zen quote (test the API) # ------- @getZen = () -> # Send `data` to `null` and the `raw` flag to `true` _request 'GET', '/zen', null, {raw:true} # Get all users # ------- @getAllUsers = (since=null) -> options = {} options.since = since if since _request 'GET', '/users', options # List public repositories for an Organization # ------- @getOrgRepos = (orgName, type='all') -> _request 'GET', "/orgs/#{orgName}/repos?type=#{type}&per_page=1000&sort=updated&direction=desc", null # Get public Gists on all of GitHub # ------- @getPublicGists = (since=null) -> options = null # Converts a Date object to a string getDate = (time) -> return time.toISOString() if Date == time.constructor return time options = {since: getDate(since)} if since _request 'GET', '/gists/public', options # List Public Events on all of GitHub # ------- @getPublicEvents = () -> _request 'GET', '/events', null # List unread notifications for authenticated user # ------- # Optional arguments: # # - `all`: `true` to show notifications marked as read. # - `participating`: `true` to show only notifications in which the user is directly participating or mentioned. # - `since`: Optional time. @getNotifications = (options={}) -> # Converts a Date object to a string getDate = (time) -> return time.toISOString() if Date == time.constructor return time options.since = getDate(options.since) if options.since queryString = toQueryString(options) _request 'GET', "/notifications#{queryString}", null # Github Users API # ======= class User # Store the username constructor: (_username=null) -> # Private var that stores the root path. # Use a different URL if this user is the authenticated user if _username _rootPath = "/users/#{_username}" else _rootPath = "/user" # Retrieve user information # ------- _cachedInfo = null @getInfo = (force=false) -> _cachedInfo = null if force if _cachedInfo return resolvedPromise(_cachedInfo) _request('GET', "#{_rootPath}", null) # Squirrel away the user info .then (info) -> _cachedInfo = info # List user repositories # ------- @getRepos = (type='all', sort='pushed', direction='desc') -> _request 'GET', "#{_rootPath}/repos?type=#{type}&per_page=1000&sort=#{sort}&direction=#{direction}", null # List user organizations # ------- @getOrgs = () -> _request 'GET', "#{_rootPath}/orgs", null # List a user's gists # ------- @getGists = () -> _request 'GET', "#{_rootPath}/gists", null # List followers of a user # ------- @getFollowers = () -> _request 'GET', "#{_rootPath}/followers", null # List who this user is following # ------- @getFollowing = () -> _request 'GET', "#{_rootPath}/following", null # Check if this user is following another user # ------- @isFollowing = (user) -> _request 'GET', "#{_rootPath}/following/#{user}", null, {isBoolean:true} # List public keys for a user # ------- @getPublicKeys = () -> _request 'GET', "#{_rootPath}/keys", null # Get Received events for this user # ------- @getReceivedEvents = (onlyPublic) -> throw new Error 'BUG: This does not work for authenticated users yet!' if not _username isPublic = '' isPublic = '/public' if onlyPublic _request 'GET', "/users/#{_username}/received_events#{isPublic}", null # Get all events for this user # ------- @getEvents = (onlyPublic) -> throw new Error 'BUG: This does not work for authenticated users yet!' if not _username isPublic = '' isPublic = '/public' if onlyPublic _request 'GET', "/users/#{_username}/events#{isPublic}", null # Authenticated User API # ======= class AuthenticatedUser extends User constructor: () -> super() # Update the authenticated user # ------- # # Valid options: # - `name`: String # - `email` : Publicly visible email address # - `blog`: String # - `company`: String # - `location`: String # - `hireable`: Boolean # - `bio`: String @updateInfo = (options) -> _request 'PATCH', '/user', options # List authenticated user's gists # ------- @getGists = () -> _request 'GET', '/gists', null # Follow a user # ------- @follow = (username) -> _request 'PUT', "/user/following/#{username}", null # Unfollow user # ------- @unfollow = (username) -> _request 'DELETE', "/user/following/#{username}", null # Get Emails associated with this user # ------- @getEmails = () -> _request 'GET', '/user/emails', null # Add Emails associated with this user # ------- @addEmail = (emails) -> emails = [emails] if !_.isArray(emails) _request 'POST', '/user/emails', emails # Remove Emails associated with this user # ------- @addEmail = (emails) -> emails = [emails] if !_.isArray(emails) _request 'DELETE', '/user/emails', emails # Get a single public key # ------- @getPublicKey = (id) -> _request 'GET', "/user/keys/#{id}", null # Add a public key # ------- @addPublicKey = (title, key) -> _request 'POST', "/user/keys", {title: title, key: key} # Update a public key # ------- @updatePublicKey = (id, options) -> _request 'PATCH', "/user/keys/#{id}", options # Create a repository # ------- # # Optional parameters: # - `description`: String # - `homepage`: String # - `private`: boolean (Default `false`) # - `has_issues`: boolean (Default `true`) # - `has_wiki`: boolean (Default `true`) # - `has_downloads`: boolean (Default `true`) # - `auto_init`: boolean (Default `false`) @createRepo = (name, options={}) -> options.name = name _request 'POST', "/user/repos", options # Get Received events for this authenticated user # ------- @getReceivedEvents = (username, page = 1) -> currentPage = '?page=' + page _request 'GET', '/users/' + username + '/received_events' + currentPage, null @getStars = () -> _request 'GET', "/user/starred" @putStar = (owner, repo) -> _request 'PUT', "/user/starred/#{owner}/#{repo}" @deleteStar = (owner, repo) -> _request 'DELETE', "/user/starred/#{owner}/#{repo}" # Organization API # ======= class Team constructor: (@id) -> @getInfo = () -> _request 'GET', "/teams/#{@id}", null # - `name` # - `permission` @updateTeam = (options) -> _request 'PATCH', "/teams/#{@id}", options @remove = () -> _request 'DELETE', "/teams/#{@id}" @getMembers = () -> _request 'GET', "/teams/#{@id}/members" @isMember = (user) -> _request 'GET', "/teams/#{@id}/members/#{user}", null, {isBoolean:true} @addMember = (user) -> _request 'PUT', "/teams/#{@id}/members/#{user}" @removeMember = (user) -> _request 'DELETE', "/teams/#{@id}/members/#{user}" @getRepos = () -> _request 'GET', "/teams/#{@id}/repos" @addRepo = (orgName, repoName) -> _request 'PUT', "/teams/#{@id}/repos/#{orgName}/#{repoName}" @removeRepo = (orgName, repoName) -> _request 'DELETE', "/teams/#{@id}/repos/#{orgName}/#{repoName}" class Organization constructor: (@name) -> @getInfo = () -> _request 'GET', "/orgs/#{@name}", null # - `billing_email`: Billing email address. This address is not publicized. # - `company` # - `email` # - `location` # - `name` @updateInfo = (options) -> _request 'PATCH', "/orgs/#{@name}", options @getTeams = () -> _request 'GET', "/orgs/#{@name}/teams", null # `permission` can be one of `pull`, `push`, or `admin` @createTeam = (name, repoNames=null, permission='pull') -> options = {name: name, permission: permission} options.repo_names = repoNames if repoNames _request 'POST', "/orgs/#{@name}/teams", options @getMembers = () -> _request 'GET', "/orgs/#{@name}/members", null @isMember = (user) -> _request 'GET', "/orgs/#{@name}/members/#{user}", null, {isBoolean:true} @removeMember = (user) -> _request 'DELETE', "/orgs/#{@name}/members/#{user}", null # Create a repository # ------- # # Optional parameters are the same as `.getUser().createRepo()` with one addition: # - `team_id`: number @createRepo = (name, options={}) -> options.name = name _request 'POST', "/orgs/#{@name}/repos", options # List repos for an organisation # ------- @getRepos = () -> _request 'GET', "/orgs/#{@name}/repos?type=all", null # Repository API # ======= # Low-level class for manipulating a Git Repository # ------- class GitRepo constructor: (@repoUser, @repoName) -> _repoPath = "/repos/#{@repoUser}/#{@repoName}" # Delete this Repository # ------- # **Note:** This is here instead of on the `Repository` object # so it is less likely to accidentally be used. @deleteRepo = () -> _request 'DELETE', "#{_repoPath}" # Uses the cache if branch has not been changed # ------- @_updateTree = (branch) -> @getRef("heads/#{branch}") # Get a particular reference # ------- @getRef = (ref) -> _request('GET', "#{_repoPath}/git/refs/#{ref}", null) .then (res) => return res.object.sha # Create a new reference # -------- # # { # "ref": "refs/heads/my-new-branch-name", # "sha": "827efc6d56897b048c772eb4087f854f46256132" # } @createRef = (options) -> _request 'POST', "#{_repoPath}/git/refs", options # Delete a reference # -------- # # repo.deleteRef('heads/gh-pages') # repo.deleteRef('tags/v1.0') @deleteRef = (ref) -> _request 'DELETE', "#{_repoPath}/git/refs/#{ref}", @options # List all branches of a repository # ------- @getBranches = () -> _request('GET', "#{_repoPath}/git/refs/heads", null) .then (heads) => return _.map(heads, (head) -> _.last head.ref.split("/") ) # Retrieve the contents of a blob # ------- @getBlob = (sha, isBase64) -> _request 'GET', "#{_repoPath}/git/blobs/#{sha}", null, {raw:true, isBase64:isBase64} # For a given file path, get the corresponding sha (blob for files, tree for dirs) # ------- @getSha = (branch, path) -> # Just use head if path is empty return @getRef("heads/#{branch}") if path is '' @getTree(branch, {recursive:true}) .then (tree) => file = _.select(tree, (file) -> file.path is path )[0] return file?.sha if file?.sha # Return a promise that has failed if no sha was found return rejectedPromise {message: 'SHA_NOT_FOUND'} # Get contents (file/dir) # ------- @getContents = (path, sha=null) -> queryString = '' if sha != null queryString = toQueryString({ref:sha}) _request('GET', "#{_repoPath}/contents/#{path}#{queryString}", null, {raw:true}) .then (contents) => return contents # Remove a file from the tree # ------- @removeFile = (path, message, sha, branch) -> params = message: message sha: sha branch: branch _request 'DELETE', "#{_repoPath}/contents/#{path}", params, null # Retrieve the tree a commit points to # ------- # Optionally set recursive to true @getTree = (tree, options=null) -> queryString = toQueryString(options) _request('GET', "#{_repoPath}/git/trees/#{tree}#{queryString}", null) .then (res) => return res.tree # Post a new blob object, getting a blob SHA back # ------- @postBlob = (content, isBase64) -> if typeof (content) is 'string' # Base64 encode the content if it is binary (isBase64) content = base64encode(content) if isBase64 content = content: content encoding: 'utf-8' content.encoding = 'base64' if isBase64 _request('POST', "#{_repoPath}/git/blobs", content) .then (res) => return res.sha # Update an existing tree adding a new blob object getting a tree SHA back # ------- # `newTree` is of the form: # # [ { # path: path # mode: '100644' # type: 'blob' # sha: blob # } ] @updateTreeMany = (baseTree, newTree) -> data = base_tree: baseTree tree: newTree _request('POST', "#{_repoPath}/git/trees", data) .then (res) => return res.sha # Post a new tree object having a file path pointer replaced # with a new blob SHA getting a tree SHA back # ------- @postTree = (tree) -> _request('POST', "#{_repoPath}/git/trees", {tree: tree}) .then (res) => return res.sha # Create a new commit object with the current commit SHA as the parent # and the new tree SHA, getting a commit SHA back # ------- @commit = (parents, tree, message) -> parents = [parents] if not _.isArray(parents) data = message: message parents: parents tree: tree _request('POST', "#{_repoPath}/git/commits", data) .then((commit) -> return commit.sha) # Update the reference of your head to point to the new commit SHA # ------- @updateHead = (head, commit, force=false) -> options = {sha:commit} options.force = true if force _request 'PATCH', "#{_repoPath}/git/refs/heads/#{head}", options # Get a single commit # -------------------- @getCommit = (sha) -> _request('GET', "#{_repoPath}/commits/#{sha}", null) # List commits on a repository. # ------- # Takes an object of optional paramaters: # # - `sha`: SHA or branch to start listing commits from # - `path`: Only commits containing this file path will be returned # - `author`: GitHub login, name, or email by which to filter by commit author # - `since`: ISO 8601 date - only commits after this date will be returned # - `until`: ISO 8601 date - only commits before this date will be returned @getCommits = (options={}) -> options = _.extend {}, options # Converts a Date object to a string getDate = (time) -> return time.toISOString() if Date == time.constructor return time options.since = getDate(options.since) if options.since options.until = getDate(options.until) if options.until queryString = toQueryString(options) _request('GET', "#{_repoPath}/commits#{queryString}", null) # Branch Class # ------- # Provides common methods that may require several git operations. class Branch constructor: (git, getRef) -> # Private variables _git = git _getRef = getRef or -> throw new Error 'BUG: No way to fetch branch ref!' # Get a single commit # -------------------- @getCommit = (sha) -> _git.getCommit(sha) # List commits on a branch. # ------- # Takes an object of optional paramaters: # # - `path`: Only commits containing this file path will be returned # - `author`: GitHub login, name, or email by which to filter by commit author # - `since`: ISO 8601 date - only commits after this date will be returned # - `until`: ISO 8601 date - only commits before this date will be returned @getCommits = (options={}) -> options = _.extend {}, options # Limit to the current branch _getRef() .then (branch) -> options.sha = branch _git.getCommits(options) # Creates a new branch based on the current reference of this branch # ------- @createBranch = (newBranchName) -> _getRef() .then (branch) => _git.getSha(branch, '') .then (sha) => _git.createRef({sha:sha, ref:"refs/heads/#{newBranchName}"}) # Read file at given path # ------- # Set `isBase64=true` to get back a base64 encoded binary file @read = (path, isBase64) -> _getRef() .then (branch) => _git.getSha(branch, path) .then (sha) => _git.getBlob(sha, isBase64) # Return both the commit hash and the content .then (bytes) => return {sha:sha, content:bytes} # Get contents at given path # ------- @contents = (path) -> _getRef() .then (branch) => _git.getSha(branch, '') .then (sha) => _git.getContents(path, sha) .then (contents) => return contents # Remove a file from the tree # ------- # Optionally provide the sha of the file so it is not accidentally # deleted if the repo has changed in the meantime. @remove = (path, message="Removed #{path}", sha=null) -> _getRef() .then (branch) => if sha _git.removeFile(path, message, sha, branch) else _git.getSha(branch, path) .then (sha) => _git.removeFile(path, message, sha, branch) # Move a file to a new location # ------- @move = (path, newPath, message="Moved #{path}") -> _getRef() .then (branch) => _git._updateTree(branch) .then (latestCommit) => _git.getTree(latestCommit, {recursive:true}) .then (tree) => # Update Tree _.each tree, (ref) -> ref.path = newPath if ref.path is path delete ref.sha if ref.type is 'tree' _git.postTree(tree) .then (rootTree) => _git.commit(latestCommit, rootTree, message) .then (commit) => _git.updateHead(branch, commit) .then (res) => return res # Finally, return the result # Write file contents to a given branch and path # ------- # To write base64 encoded data set `isBase64==true` # # Optionally takes a `parentCommitSha` which will be used as the # parent of this commit @write = (path, content, message="Changed #{path}", isBase64, parentCommitSha=null) -> contents = {} contents[path] = content: content isBase64: isBase64 @writeMany(contents, message, parentCommitSha) # Write the contents of multiple files to a given branch # ------- # Each file can also be binary. # # In general `contents` is a map where the key is the path and the value is `{content:'Hello World!', isBase64:false}`. # In the case of non-base64 encoded files the value may be a string instead. # # Example: # # contents = { # 'hello.txt': 'Hello World!', # 'path/to/hello2.txt': { content: 'Ahoy!', isBase64: false} # } # # Optionally takes an array of `parentCommitShas` which will be used as the # parents of this commit. @writeMany = (contents, message="Changed Multiple", parentCommitShas=null) -> # This method: # # 0. Finds the latest commit if one is not provided # 1. Asynchronously send new blobs for each file # 2. Use the return of the new Blob Post to return an entry in the new Commit Tree # 3. Wait on all the new blobs to finish # 4. Commit and update the branch _getRef() .then (branch) => # See below for Step 0. afterParentCommitShas = (parentCommitShas) => # 1. Asynchronously send all the files as new blobs. promises = _.map _.pairs(contents), ([path, data]) -> # `data` can be an object or a string. # If it is a string assume isBase64 is false and the string is the content content = data.content or data isBase64 = data.isBase64 or false _git.postBlob(content, isBase64) .then (blob) => # 2. return an entry in the new Commit Tree return { path: path mode: '100644' type: 'blob' sha: blob } # 3. Wait on all the new blobs to finish # Different Promise APIs implement this differently. For example: # - Promise uses `Promise.all([...])` # - jQuery uses `jQuery.when(p1, p2, p3, ...)` allPromises(promises) .then (newTrees) => _git.updateTreeMany(parentCommitShas, newTrees) .then (tree) => # 4. Commit and update the branch _git.commit(parentCommitShas, tree, message) .then (commitSha) => _git.updateHead(branch, commitSha) .then (res) => # Finally, return the result return res.object # Return something that has a `.sha` to match the signature for read # 0. Finds the latest commit if one is not provided if parentCommitShas return afterParentCommitShas(parentCommitShas) else return _git._updateTree(branch).then(afterParentCommitShas) # Repository Class # ------- # Provides methods for operating on the entire repository # and ways to operate on a `Branch`. class Repository constructor: (@options) -> # Private fields _user = @options.user _repo = @options.name # Set the `git` instance variable @git = new GitRepo(_user, _repo) @repoPath = "/repos/#{_user}/#{_repo}" @currentTree = branch: null sha: null @updateInfo = (options) -> _request 'PATCH', @repoPath, options # List all branches of a repository # ------- @getBranches = () -> @git.getBranches() # Get a branch of a repository # ------- @getBranch = (branchName=null) -> if branchName getRef = () => return resolvedPromise(branchName) return new Branch(@git, getRef) else return @getDefaultBranch() # Get the default branch of a repository # ------- @getDefaultBranch = () -> # Calls getInfo() to get the default branch name getRef = => @getInfo() .then (info) => return info.default_branch new Branch(@git, getRef) @setDefaultBranch = (branchName) -> @updateInfo {name: _repo, default_branch: branchName} # Get repository information # ------- @getInfo = () -> _request 'GET', @repoPath, null # Get contents # -------- @getContents = (branch, path) -> _request 'GET', "#{@repoPath}/contents?ref=#{branch}", {path: path} # Fork repository # ------- @fork = (organization) -> if organization _request 'POST', "#{@repoPath}/forks", organization: organization else _request 'POST', "#{@repoPath}/forks", null # Create pull request # -------- @createPullRequest = (options) -> _request 'POST', "#{@repoPath}/pulls", options # Get recent commits to the repository # -------- # Takes an object of optional paramaters: # # - `path`: Only commits containing this file path will be returned # - `author`: GitHub login, name, or email by which to filter by commit author # - `since`: ISO 8601 date - only commits after this date will be returned # - `until`: ISO 8601 date - only commits before this date will be returned @getCommits = (options) -> @git.getCommits(options) # List repository events # ------- @getEvents = () -> _request 'GET', "#{@repoPath}/events", null # List Issue events for a Repository # ------- @getIssueEvents = () -> _request 'GET', "#{@repoPath}/issues/events", null # List events for a network of Repositories # ------- @getNetworkEvents = () -> _request 'GET', "/networks/#{_user}/#{_repo}/events", null # List unread notifications for authenticated user # ------- # Optional arguments: # # - `all`: `true` to show notifications marked as read. # - `participating`: `true` to show only notifications in which # the user is directly participating or mentioned. # - `since`: Optional time. @getNotifications = (options={}) -> # Converts a Date object to a string getDate = (time) -> return time.toISOString() if Date == time.constructor return time options.since = getDate(options.since) if options.since queryString = toQueryString(options) _request 'GET', "#{@repoPath}/notifications#{queryString}", null # List Collaborators # ------- # When authenticating as an organization owner of an # organization-owned repository, all organization owners # are included in the list of collaborators. # Otherwise, only users with access to the repository are # returned in the collaborators list. @getCollaborators = () -> _request 'GET', "#{@repoPath}/collaborators", null @addCollaborator = (username) -> throw new Error 'BUG: username is required' if not username _request 'PUT', "#{@repoPath}/collaborators/#{username}", null, {isBoolean:true} @removeCollaborator = (username) -> throw new Error 'BUG: username is required' if not username _request 'DELETE', "#{@repoPath}/collaborators/#{username}", null, {isBoolean:true} @isCollaborator = (username=null) -> throw new Error 'BUG: username is required' if not username _request 'GET', "#{@repoPath}/collaborators/#{username}", null, {isBoolean:true} # Can Collaborate # ------- # True if the authenticated user has permission # to commit to this repository. @canCollaborate = () -> # Short-circuit if no credentials provided if not (clientOptions.password or clientOptions.token) return resolvedPromise(false) _client.getLogin() .then (login) => if not login return false else return @isCollaborator(login) .then null, (err) => # Problem logging in (maybe bad username/password) return false # List all hooks # ------- @getHooks = () -> _request 'GET', "#{@repoPath}/hooks", null # Get single hook # ------- @getHook = (id) -> _request 'GET', "#{@repoPath}/hooks/#{id}", null # Create a new hook # ------- # # - `name` (Required string) : The name of the service that is being called. # (See /hooks for the list of valid hook names.) # - `config` (Required hash) : A Hash containing key/value pairs to provide settings for this hook. # These settings vary between the services and are defined in the github-services repo. # - `events` (Optional array) : Determines what events the hook is triggered for. Default: ["push"]. # - `active` (Optional boolean) : Determines whether the hook is actually triggered on pushes. @createHook = (name, config, events=['push'], active=true) -> data = name: name config: config events: events active: active _request 'POST', "#{@repoPath}/hooks", data # Edit a hook # ------- # # - `config` (Optional hash) : A Hash containing key/value pairs to provide settings for this hook. # Modifying this will replace the entire config object. # These settings vary between the services and are defined in the github-services repo. # - `events` (Optional array) : Determines what events the hook is triggered for. # This replaces the entire array of events. Default: ["push"]. # - `addEvents` (Optional array) : Determines a list of events to be added to the list of events that the Hook triggers for. # - `removeEvents` (Optional array) : Determines a list of events to be removed from the list of events that the Hook triggers for. # - `active` (Optional boolean) : Determines whether the hook is actually triggered on pushes. @editHook = (id, config=null, events=null, addEvents=null, removeEvents=null, active=null) -> data = {} data.config = config if config != null data.events = events if events != null data.add_events = addEvents if addEvents != null data.remove_events = removeEvents if removeEvents != null data.active = active if active != null _request 'PATCH', "#{@repoPath}/hooks/#{id}", data # Test a `push` hook # ------- # This will trigger the hook with the latest push to the current # repository if the hook is subscribed to push events. # If the hook is not subscribed to push events, the server will # respond with 204 but no test POST will be generated. @testHook = (id) -> _request 'POST', "#{@repoPath}/hooks/#{id}/tests", null # Delete a hook # ------- @deleteHook = (id) -> _request 'DELETE', "#{@repoPath}/hooks/#{id}", null # List all Languages # ------- @getLanguages = -> _request 'GET', "#{@repoPath}/languages", null # List all releases # ------- @getReleases = () -> _request 'GET', "#{@repoPath}/releases", null # Gist API # ------- class Gist constructor: (@options) -> id = @options.id _gistPath = "/gists/#{id}" # Read the gist # -------- @read = () -> _request 'GET', _gistPath, null # Create the gist # -------- # # Files contains a hash with the filename as the key and # `{content: 'File Contents Here'}` as the value. # # Example: # # { "file1.txt": { # "content": "String file contents" # } # } @create = (files, isPublic=false, description=null) -> options = isPublic: isPublic files: files options.description = description if description? _request 'POST', "/gists", options # Delete the gist # -------- @delete = () -> _request 'DELETE', _gistPath, null # Fork a gist # -------- @fork = () -> _request 'POST', "#{_gistPath}/forks", null # Update a gist with the new stuff # -------- # `files` are files that make up this gist. # The key of which should be an optional string filename # and the value another optional hash with parameters: # # - `content`: Optional string - Updated file contents # - `filename`: Optional string - New name for this file. # # **NOTE:** All files from the previous version of the gist are carried # over by default if not included in the hash. Deletes can be performed # by including the filename with a null hash. @update = (files, description=null) -> options = {files: files} options.description = description if description? _request 'PATCH', _gistPath, options # Star a gist # ------- @star = () -> _request 'PUT', "#{_gistPath}/star" # Unstar a gist # ------- @unstar = () -> _request 'DELETE', "#{_gistPath}/star" # Check if a gist is starred # ------- @isStarred = () -> _request 'GET', "#{_gistPath}", null, {isBoolean:true} # Top Level API # ------- @getRepo = (user, repo) -> throw new Error('BUG! user argument is required') if not user throw new Error('BUG! repo argument is required') if not repo new Repository( user: user name: repo ) @getOrg = (name) -> new Organization(name) # API for viewing info for arbitrary users or the current user # if no arguments are provided. @getUser = (login=null) -> if login return new User(login) else if clientOptions.password or clientOptions.token return new AuthenticatedUser() else return null @getGist = (id) -> new Gist(id: id) # Returns the login of the current user. # When using OAuth this is unknown but is necessary to # determine if the current user has commit access to a # repository @getLogin = () -> # 3 cases: # 1. No authentication provided # 2. Username (and password) provided # 3. OAuth token provided if clientOptions.password or clientOptions.token return new User().getInfo() .then (info) -> return info.login else return resolvedPromise(null) # Return the class for assignment return Octokit # Register with nodejs, requirejs, or as a global # ------- # Depending on the context this file is called, register it appropriately if exports? # Use native promises if Harmony is on Promise = @Promise or require('es6-promise').Promise XMLHttpRequest = @XMLHttpRequest or require('xmlhttprequest').XMLHttpRequest newPromise = (fn) -> return new Promise(fn) allPromises = (promises) -> return Promise.all.call(Promise, promises) # Encode using native Base64 encode = @btoa or (str) -> buffer = new Buffer(str, 'binary') return buffer.toString('base64') Octokit = makeOctokit(newPromise, allPromises, XMLHttpRequest, encode, 'octokit') # `User-Agent` (for nodejs) exports.new = (options) -> new Octokit(options) else # Octokit is being used in the browser. # Find a Promise API and register with `define` (if available) # Register Octokit once a Promise API is loaded. # In the case of angular, this may be async. createGlobalAndAMD = (newPromise, allPromises) => if @define? @define 'octokit', [], () => return makeOctokit(newPromise, allPromises, @XMLHttpRequest, @btoa) else Octokit = makeOctokit(newPromise, allPromises, @XMLHttpRequest, @btoa) # Assign to a global `Octokit` @Octokit = Octokit @Github = Octokit # Determine the correct Promise factory. # Try to use libraries before native Promises since most Promise users # are already using a library. # # Try in the following order: # - Q Promise # - angularjs Promise # - jQuery Promise # - native Promise or a polyfill if @Q newPromise = (fn) => deferred = @Q.defer() resolve = (val) -> deferred.resolve(val) reject = (err) -> deferred.reject(err) fn(resolve, reject) return deferred.promise allPromises = (promises) -> @Q.all(promises) createGlobalAndAMD(newPromise, allPromises) else if @angular # Details on Angular Promises: http://docs.angularjs.org/api/ng/service/$q injector = angular.injector(['ng']) injector.invoke ($q) -> newPromise = (fn) -> deferred = $q.defer() resolve = (val) -> deferred.resolve(val) reject = (err) -> deferred.reject(err) fn(resolve, reject) return deferred.promise allPromises = (promises) -> $q.all(promises) createGlobalAndAMD(newPromise, allPromises) else if @jQuery?.Deferred newPromise = (fn) => promise = @jQuery.Deferred() resolve = (val) -> promise.resolve(val) reject = (val) -> promise.reject(val) fn(resolve, reject) return promise.promise() allPromises = (promises) => # `jQuery.when` is a little odd. # - It accepts each promise as an argument (instead of an array of promises) # - Each resolved value is an argument (instead of an array of values) # # So, convert the array of promises to args and then the resolved args to an array return @jQuery.when(promises...).then((promises...) -> return promises) createGlobalAndAMD(newPromise, allPromises) else if @Promise newPromise = (fn) => return new @Promise (resolve, reject) -> # Some browsers (like node-webkit 0.8.6) contain an older implementation # of Promises that provide 1 argument (a `PromiseResolver`). if resolve.fulfill fn(resolve.resolve.bind(resolve), resolve.reject.bind(resolve)) else fn(arguments...) allPromises = (promises) => @Promise.all.call(@Promise, promises) createGlobalAndAMD(newPromise, allPromises) else # Otherwise, throw an error err = (msg) -> console?.error?(msg) throw new Error(msg) err('A Promise API was not found. Supported libraries that have Promises are jQuery, angularjs, and https://github.com/jakearchibald/es6-promise')
true
# Github Promise API # ====== # # This class provides a Promise API for accessing GitHub. # Most methods return a Promise object whose value is resolved when `.then(doneFn, failFn)` # is called. # # Based on Github.js 0.7.0 # # (c) 2012 PI:NAME:<NAME>END_PI, Development Seed # Github.js is freely distributable under the MIT license. # For all details and documentation: # http://substance.io/michael/github # Underscore shim # ========= # # The following code is a shim for the underscore.js functions this code relise on _ = {} _.isEmpty = (object) -> Object.keys(object).length == 0 _.isArray = Array.isArray or (obj) -> toString.call(obj) is'[object Array]' _.defaults = (object, values) -> for key in Object.keys(values) do (key) -> object[key] ?= values[key] _.each = (object, fn) -> return if not object if _.isArray(object) object.forEach(fn) arr = [] for key in Object.keys(object) do (key) -> fn(object[key]) _.pairs = (object) -> arr = [] for key in Object.keys(object) do (key) -> arr.push([key, object[key]]) return arr _.map = (object, fn) -> if _.isArray(object) return object.map(fn) arr = [] for key in Object.keys(object) do (key) -> arr.push(fn(object[key])) arr _.last = (object, n) -> len = object.length object.slice(len - n, len) _.select = (object, fn) -> object.filter(fn) _.extend = (object, template) -> for key in Object.keys(template) do (key) -> object[key] = template[key] object _.toArray = (object) -> return Array.prototype.slice.call(object) # Generate a Github class # ========= # # Depending on how this is loaded (nodejs, requirejs, globals) # the actual underscore, jQuery.ajax/Deferred, and base64 encode functions may differ. makeOctokit = (newPromise, allPromises, XMLHttpRequest, base64encode, userAgent) => # Simple jQuery.ajax() shim that returns a promise for a xhr object ajax = (options) -> return newPromise (resolve, reject) -> xhr = new XMLHttpRequest() xhr.dataType = options.dataType xhr.overrideMimeType?(options.mimeType) xhr.open(options.type, options.url) if options.data and 'GET' != options.type xhr.setRequestHeader('Content-Type', options.contentType) for name, value of options.headers xhr.setRequestHeader(name, value) xhr.onreadystatechange = () -> if 4 == xhr.readyState options.statusCode?[xhr.status]?() if xhr.status >= 200 and xhr.status < 300 or xhr.status == 304 resolve(xhr) else reject(xhr) xhr.send(options.data) # Returns an always-resolved promise (like `Promise.resolve(val)` ) resolvedPromise = (val) -> return newPromise (resolve, reject) -> resolve(val) # Returns an always-rejected promise (like `Promise.reject(err)` ) rejectedPromise = (err) -> return newPromise (resolve, reject) -> reject(err) class Octokit constructor: (clientOptions={}) -> # Provide an option to override the default URL _.defaults clientOptions, rootURL: 'https://api.github.com' useETags: true usePostInsteadOfPatch: false _client = @ # Useful for other classes (like Repo) to get the current Client object # These are updated whenever a request is made _listeners = [] # To support ETag caching cache the responses. class ETagResponse constructor: (@eTag, @data, @status) -> # Cached responses are stored in this object keyed by `path` _cachedETags = {} # Send simple progress notifications notifyStart = (promise, path) -> promise.notify? {type:'start', path:path} notifyEnd = (promise, path) -> promise.notify? {type:'end', path:path} # HTTP Request Abstraction # ======= # _request = (method, path, data, options={raw:false, isBase64:false, isBoolean:false}) -> if 'PATCH' == method and clientOptions.usePostInsteadOfPatch method = 'POST' # Only prefix the path when it does not begin with http. # This is so pagination works (which provides absolute URLs). path = "#{clientOptions.rootURL}#{path}" if not /^http/.test(path) # Support binary data by overriding the response mimeType mimeType = undefined mimeType = 'text/plain; charset=x-user-defined' if options.isBase64 headers = { 'Accept': 'application/vnd.github.raw' } # Set the `User-Agent` because it is required and NodeJS # does not send one by default. # See http://developer.github.com/v3/#user-agent-required headers['User-Agent'] = userAgent if userAgent # Send the ETag if re-requesting a URL if path of _cachedETags headers['If-None-Match'] = _cachedETags[path].eTag else # The browser will sneak in a 'If-Modified-Since' header if the GET has been requested before # but for some reason the cached response does not seem to be available # in the jqXHR object. # So, the first time a URL is requested set this date to 0 so we always get a response the 1st time # a URL is requested. headers['If-Modified-Since'] = 'Thu, 01 Jan 1970 00:00:00 GMT' if (clientOptions.token) or (clientOptions.username and clientOptions.password) if clientOptions.token auth = "token #{clientOptions.token}" else auth = 'Basic ' + base64encode("#{clientOptions.username}:#{clientOptions.password}") headers['Authorization'] = auth promise = newPromise (resolve, reject) -> ajaxConfig = # Be sure to **not** blow the cache with a random number # (GitHub will respond with 5xx or CORS errors) url: path type: method contentType: 'application/json' mimeType: mimeType headers: headers processData: false # Don't convert to QueryString data: !options.raw and data and JSON.stringify(data) or data dataType: 'json' unless options.raw # If the request is a boolean yes/no question GitHub will indicate # via the HTTP Status of 204 (No Content) or 404 instead of a 200. if options.isBoolean ajaxConfig.statusCode = # a Boolean 'yes' 204: () => resolve(true) # a Boolean 'no' 404: () => resolve(false) xhrPromise = ajax(ajaxConfig) always = (jqXHR) => notifyEnd(@, path) # Fire listeners when the request completes or fails rateLimit = parseFloat(jqXHR.getResponseHeader 'X-RateLimit-Limit') rateLimitRemaining = parseFloat(jqXHR.getResponseHeader 'X-RateLimit-Remaining') for listener in _listeners listener(rateLimitRemaining, rateLimit, method, path, data, options) # Return the result and Base64 encode it if `options.isBase64` flag is set. xhrPromise.then (jqXHR) -> always(jqXHR) # If the response was a 304 then return the cached version if 304 == jqXHR.status if clientOptions.useETags and _cachedETags[path] eTagResponse = _cachedETags[path] resolve(eTagResponse.data, eTagResponse.status, jqXHR) else resolve(jqXHR.responseText, status, jqXHR) # If it was a boolean question and the server responded with 204 # return true. else if 204 == jqXHR.status and options.isBoolean resolve(true, status, jqXHR) else if jqXHR.responseText and 'json' == ajaxConfig.dataType data = JSON.parse(jqXHR.responseText) # Only JSON responses have next/prev/first/last link headers # Add them to data so the resolved value is iterable valOptions = {} # Parse the Link headers # of the form `<http://a.com>; rel="next", <https://b.com?a=b&c=d>; rel="previous"` links = jqXHR.getResponseHeader('Link') _.each links?.split(','), (part) -> [discard, href, rel] = part.match(/<([^>]+)>;\ rel="([^"]+)"/) # Name the functions `nextPage`, `previousPage`, `firstPage`, `lastPage` valOptions["#{rel}Page"] = () -> _request('GET', href, null, options) # Add the pagination functions on the JSON since Promises resolve one value _.extend(data, valOptions) else data = jqXHR.responseText # Convert the response to a Base64 encoded string if 'GET' == method and options.isBase64 # Convert raw data to binary chopping off the higher-order bytes in each char. # Useful for Base64 encoding. converted = '' for i in [0..data.length] converted += String.fromCharCode(data.charCodeAt(i) & 0xff) data = converted # Cache the response to reuse later if 'GET' == method and jqXHR.getResponseHeader('ETag') and clientOptions.useETags eTag = jqXHR.getResponseHeader('ETag') _cachedETags[path] = new ETagResponse(eTag, data, jqXHR.status) resolve(data, jqXHR.status, jqXHR) # Parse the error if one occurs onError = (jqXHR) -> always(jqXHR) # If the request was for a Boolean then a 404 should be treated as a "false" if options.isBoolean and 404 == jqXHR.status resolve(false) else if jqXHR.getResponseHeader('Content-Type') != 'application/json; charset=utf-8' err = new Error(jqXHR.responseText) err['status'] = jqXHR.status err['__jqXHR'] = jqXHR reject(err) else err = new Error("Github error: #{jqXHR.responseText}") if jqXHR.responseText json = JSON.parse(jqXHR.responseText) else # In the case of 404 errors, `responseText` is an empty string json = '' # XXX: should be body or something else probably err['error'] = json err['status'] = jqXHR.status err['__jqXHR'] = jqXHR reject(err) # Depending on the Promise implementation, the `catch` method may be `.catch` or `.fail` xhrPromise.catch?(onError) or xhrPromise.fail(onError) notifyStart(promise, path) # Return the promise return promise # Converts a dictionary to a query string. # Internal helper method toQueryString = (options) -> # Returns '' if `options` is empty so this string can always be appended to a URL return '' if _.isEmpty(options) params = [] _.each _.pairs(options), ([key, value]) -> params.push "#{key}=#{encodeURIComponent(value)}" return "?#{params.join('&')}" # Clear the local cache # ------- @clearCache = clearCache = () -> _cachedETags = {} ## Get the local cache # ------- @getCache = getCache = () -> _cachedETags ## Set the local cache # ------- @setCache = setCache = (cachedETags) -> # check if argument is valid. unless cachedETags != null and typeof cachedETags == 'object' throw new Error 'BUG: argument of method "setCache" should be an object' else _cachedETags = cachedETags # Add a listener that fires when the `rateLimitRemaining` changes as a result of # communicating with github. @onRateLimitChanged = (listener) -> _listeners.push listener # Random zen quote (test the API) # ------- @getZen = () -> # Send `data` to `null` and the `raw` flag to `true` _request 'GET', '/zen', null, {raw:true} # Get all users # ------- @getAllUsers = (since=null) -> options = {} options.since = since if since _request 'GET', '/users', options # List public repositories for an Organization # ------- @getOrgRepos = (orgName, type='all') -> _request 'GET', "/orgs/#{orgName}/repos?type=#{type}&per_page=1000&sort=updated&direction=desc", null # Get public Gists on all of GitHub # ------- @getPublicGists = (since=null) -> options = null # Converts a Date object to a string getDate = (time) -> return time.toISOString() if Date == time.constructor return time options = {since: getDate(since)} if since _request 'GET', '/gists/public', options # List Public Events on all of GitHub # ------- @getPublicEvents = () -> _request 'GET', '/events', null # List unread notifications for authenticated user # ------- # Optional arguments: # # - `all`: `true` to show notifications marked as read. # - `participating`: `true` to show only notifications in which the user is directly participating or mentioned. # - `since`: Optional time. @getNotifications = (options={}) -> # Converts a Date object to a string getDate = (time) -> return time.toISOString() if Date == time.constructor return time options.since = getDate(options.since) if options.since queryString = toQueryString(options) _request 'GET', "/notifications#{queryString}", null # Github Users API # ======= class User # Store the username constructor: (_username=null) -> # Private var that stores the root path. # Use a different URL if this user is the authenticated user if _username _rootPath = "/users/#{_username}" else _rootPath = "/user" # Retrieve user information # ------- _cachedInfo = null @getInfo = (force=false) -> _cachedInfo = null if force if _cachedInfo return resolvedPromise(_cachedInfo) _request('GET', "#{_rootPath}", null) # Squirrel away the user info .then (info) -> _cachedInfo = info # List user repositories # ------- @getRepos = (type='all', sort='pushed', direction='desc') -> _request 'GET', "#{_rootPath}/repos?type=#{type}&per_page=1000&sort=#{sort}&direction=#{direction}", null # List user organizations # ------- @getOrgs = () -> _request 'GET', "#{_rootPath}/orgs", null # List a user's gists # ------- @getGists = () -> _request 'GET', "#{_rootPath}/gists", null # List followers of a user # ------- @getFollowers = () -> _request 'GET', "#{_rootPath}/followers", null # List who this user is following # ------- @getFollowing = () -> _request 'GET', "#{_rootPath}/following", null # Check if this user is following another user # ------- @isFollowing = (user) -> _request 'GET', "#{_rootPath}/following/#{user}", null, {isBoolean:true} # List public keys for a user # ------- @getPublicKeys = () -> _request 'GET', "#{_rootPath}/keys", null # Get Received events for this user # ------- @getReceivedEvents = (onlyPublic) -> throw new Error 'BUG: This does not work for authenticated users yet!' if not _username isPublic = '' isPublic = '/public' if onlyPublic _request 'GET', "/users/#{_username}/received_events#{isPublic}", null # Get all events for this user # ------- @getEvents = (onlyPublic) -> throw new Error 'BUG: This does not work for authenticated users yet!' if not _username isPublic = '' isPublic = '/public' if onlyPublic _request 'GET', "/users/#{_username}/events#{isPublic}", null # Authenticated User API # ======= class AuthenticatedUser extends User constructor: () -> super() # Update the authenticated user # ------- # # Valid options: # - `name`: String # - `email` : Publicly visible email address # - `blog`: String # - `company`: String # - `location`: String # - `hireable`: Boolean # - `bio`: String @updateInfo = (options) -> _request 'PATCH', '/user', options # List authenticated user's gists # ------- @getGists = () -> _request 'GET', '/gists', null # Follow a user # ------- @follow = (username) -> _request 'PUT', "/user/following/#{username}", null # Unfollow user # ------- @unfollow = (username) -> _request 'DELETE', "/user/following/#{username}", null # Get Emails associated with this user # ------- @getEmails = () -> _request 'GET', '/user/emails', null # Add Emails associated with this user # ------- @addEmail = (emails) -> emails = [emails] if !_.isArray(emails) _request 'POST', '/user/emails', emails # Remove Emails associated with this user # ------- @addEmail = (emails) -> emails = [emails] if !_.isArray(emails) _request 'DELETE', '/user/emails', emails # Get a single public key # ------- @getPublicKey = (id) -> _request 'GET', "/user/keys/#{id}", null # Add a public key # ------- @addPublicKey = (title, key) -> _request 'POST', "/user/keys", {title: title, key: key} # Update a public key # ------- @updatePublicKey = (id, options) -> _request 'PATCH', "/user/keys/#{id}", options # Create a repository # ------- # # Optional parameters: # - `description`: String # - `homepage`: String # - `private`: boolean (Default `false`) # - `has_issues`: boolean (Default `true`) # - `has_wiki`: boolean (Default `true`) # - `has_downloads`: boolean (Default `true`) # - `auto_init`: boolean (Default `false`) @createRepo = (name, options={}) -> options.name = name _request 'POST', "/user/repos", options # Get Received events for this authenticated user # ------- @getReceivedEvents = (username, page = 1) -> currentPage = '?page=' + page _request 'GET', '/users/' + username + '/received_events' + currentPage, null @getStars = () -> _request 'GET', "/user/starred" @putStar = (owner, repo) -> _request 'PUT', "/user/starred/#{owner}/#{repo}" @deleteStar = (owner, repo) -> _request 'DELETE', "/user/starred/#{owner}/#{repo}" # Organization API # ======= class Team constructor: (@id) -> @getInfo = () -> _request 'GET', "/teams/#{@id}", null # - `name` # - `permission` @updateTeam = (options) -> _request 'PATCH', "/teams/#{@id}", options @remove = () -> _request 'DELETE', "/teams/#{@id}" @getMembers = () -> _request 'GET', "/teams/#{@id}/members" @isMember = (user) -> _request 'GET', "/teams/#{@id}/members/#{user}", null, {isBoolean:true} @addMember = (user) -> _request 'PUT', "/teams/#{@id}/members/#{user}" @removeMember = (user) -> _request 'DELETE', "/teams/#{@id}/members/#{user}" @getRepos = () -> _request 'GET', "/teams/#{@id}/repos" @addRepo = (orgName, repoName) -> _request 'PUT', "/teams/#{@id}/repos/#{orgName}/#{repoName}" @removeRepo = (orgName, repoName) -> _request 'DELETE', "/teams/#{@id}/repos/#{orgName}/#{repoName}" class Organization constructor: (@name) -> @getInfo = () -> _request 'GET', "/orgs/#{@name}", null # - `billing_email`: Billing email address. This address is not publicized. # - `company` # - `email` # - `location` # - `name` @updateInfo = (options) -> _request 'PATCH', "/orgs/#{@name}", options @getTeams = () -> _request 'GET', "/orgs/#{@name}/teams", null # `permission` can be one of `pull`, `push`, or `admin` @createTeam = (name, repoNames=null, permission='pull') -> options = {name: name, permission: permission} options.repo_names = repoNames if repoNames _request 'POST', "/orgs/#{@name}/teams", options @getMembers = () -> _request 'GET', "/orgs/#{@name}/members", null @isMember = (user) -> _request 'GET', "/orgs/#{@name}/members/#{user}", null, {isBoolean:true} @removeMember = (user) -> _request 'DELETE', "/orgs/#{@name}/members/#{user}", null # Create a repository # ------- # # Optional parameters are the same as `.getUser().createRepo()` with one addition: # - `team_id`: number @createRepo = (name, options={}) -> options.name = name _request 'POST', "/orgs/#{@name}/repos", options # List repos for an organisation # ------- @getRepos = () -> _request 'GET', "/orgs/#{@name}/repos?type=all", null # Repository API # ======= # Low-level class for manipulating a Git Repository # ------- class GitRepo constructor: (@repoUser, @repoName) -> _repoPath = "/repos/#{@repoUser}/#{@repoName}" # Delete this Repository # ------- # **Note:** This is here instead of on the `Repository` object # so it is less likely to accidentally be used. @deleteRepo = () -> _request 'DELETE', "#{_repoPath}" # Uses the cache if branch has not been changed # ------- @_updateTree = (branch) -> @getRef("heads/#{branch}") # Get a particular reference # ------- @getRef = (ref) -> _request('GET', "#{_repoPath}/git/refs/#{ref}", null) .then (res) => return res.object.sha # Create a new reference # -------- # # { # "ref": "refs/heads/my-new-branch-name", # "sha": "827efc6d56897b048c772eb4087f854f46256132" # } @createRef = (options) -> _request 'POST', "#{_repoPath}/git/refs", options # Delete a reference # -------- # # repo.deleteRef('heads/gh-pages') # repo.deleteRef('tags/v1.0') @deleteRef = (ref) -> _request 'DELETE', "#{_repoPath}/git/refs/#{ref}", @options # List all branches of a repository # ------- @getBranches = () -> _request('GET', "#{_repoPath}/git/refs/heads", null) .then (heads) => return _.map(heads, (head) -> _.last head.ref.split("/") ) # Retrieve the contents of a blob # ------- @getBlob = (sha, isBase64) -> _request 'GET', "#{_repoPath}/git/blobs/#{sha}", null, {raw:true, isBase64:isBase64} # For a given file path, get the corresponding sha (blob for files, tree for dirs) # ------- @getSha = (branch, path) -> # Just use head if path is empty return @getRef("heads/#{branch}") if path is '' @getTree(branch, {recursive:true}) .then (tree) => file = _.select(tree, (file) -> file.path is path )[0] return file?.sha if file?.sha # Return a promise that has failed if no sha was found return rejectedPromise {message: 'SHA_NOT_FOUND'} # Get contents (file/dir) # ------- @getContents = (path, sha=null) -> queryString = '' if sha != null queryString = toQueryString({ref:sha}) _request('GET', "#{_repoPath}/contents/#{path}#{queryString}", null, {raw:true}) .then (contents) => return contents # Remove a file from the tree # ------- @removeFile = (path, message, sha, branch) -> params = message: message sha: sha branch: branch _request 'DELETE', "#{_repoPath}/contents/#{path}", params, null # Retrieve the tree a commit points to # ------- # Optionally set recursive to true @getTree = (tree, options=null) -> queryString = toQueryString(options) _request('GET', "#{_repoPath}/git/trees/#{tree}#{queryString}", null) .then (res) => return res.tree # Post a new blob object, getting a blob SHA back # ------- @postBlob = (content, isBase64) -> if typeof (content) is 'string' # Base64 encode the content if it is binary (isBase64) content = base64encode(content) if isBase64 content = content: content encoding: 'utf-8' content.encoding = 'base64' if isBase64 _request('POST', "#{_repoPath}/git/blobs", content) .then (res) => return res.sha # Update an existing tree adding a new blob object getting a tree SHA back # ------- # `newTree` is of the form: # # [ { # path: path # mode: '100644' # type: 'blob' # sha: blob # } ] @updateTreeMany = (baseTree, newTree) -> data = base_tree: baseTree tree: newTree _request('POST', "#{_repoPath}/git/trees", data) .then (res) => return res.sha # Post a new tree object having a file path pointer replaced # with a new blob SHA getting a tree SHA back # ------- @postTree = (tree) -> _request('POST', "#{_repoPath}/git/trees", {tree: tree}) .then (res) => return res.sha # Create a new commit object with the current commit SHA as the parent # and the new tree SHA, getting a commit SHA back # ------- @commit = (parents, tree, message) -> parents = [parents] if not _.isArray(parents) data = message: message parents: parents tree: tree _request('POST', "#{_repoPath}/git/commits", data) .then((commit) -> return commit.sha) # Update the reference of your head to point to the new commit SHA # ------- @updateHead = (head, commit, force=false) -> options = {sha:commit} options.force = true if force _request 'PATCH', "#{_repoPath}/git/refs/heads/#{head}", options # Get a single commit # -------------------- @getCommit = (sha) -> _request('GET', "#{_repoPath}/commits/#{sha}", null) # List commits on a repository. # ------- # Takes an object of optional paramaters: # # - `sha`: SHA or branch to start listing commits from # - `path`: Only commits containing this file path will be returned # - `author`: GitHub login, name, or email by which to filter by commit author # - `since`: ISO 8601 date - only commits after this date will be returned # - `until`: ISO 8601 date - only commits before this date will be returned @getCommits = (options={}) -> options = _.extend {}, options # Converts a Date object to a string getDate = (time) -> return time.toISOString() if Date == time.constructor return time options.since = getDate(options.since) if options.since options.until = getDate(options.until) if options.until queryString = toQueryString(options) _request('GET', "#{_repoPath}/commits#{queryString}", null) # Branch Class # ------- # Provides common methods that may require several git operations. class Branch constructor: (git, getRef) -> # Private variables _git = git _getRef = getRef or -> throw new Error 'BUG: No way to fetch branch ref!' # Get a single commit # -------------------- @getCommit = (sha) -> _git.getCommit(sha) # List commits on a branch. # ------- # Takes an object of optional paramaters: # # - `path`: Only commits containing this file path will be returned # - `author`: GitHub login, name, or email by which to filter by commit author # - `since`: ISO 8601 date - only commits after this date will be returned # - `until`: ISO 8601 date - only commits before this date will be returned @getCommits = (options={}) -> options = _.extend {}, options # Limit to the current branch _getRef() .then (branch) -> options.sha = branch _git.getCommits(options) # Creates a new branch based on the current reference of this branch # ------- @createBranch = (newBranchName) -> _getRef() .then (branch) => _git.getSha(branch, '') .then (sha) => _git.createRef({sha:sha, ref:"refs/heads/#{newBranchName}"}) # Read file at given path # ------- # Set `isBase64=true` to get back a base64 encoded binary file @read = (path, isBase64) -> _getRef() .then (branch) => _git.getSha(branch, path) .then (sha) => _git.getBlob(sha, isBase64) # Return both the commit hash and the content .then (bytes) => return {sha:sha, content:bytes} # Get contents at given path # ------- @contents = (path) -> _getRef() .then (branch) => _git.getSha(branch, '') .then (sha) => _git.getContents(path, sha) .then (contents) => return contents # Remove a file from the tree # ------- # Optionally provide the sha of the file so it is not accidentally # deleted if the repo has changed in the meantime. @remove = (path, message="Removed #{path}", sha=null) -> _getRef() .then (branch) => if sha _git.removeFile(path, message, sha, branch) else _git.getSha(branch, path) .then (sha) => _git.removeFile(path, message, sha, branch) # Move a file to a new location # ------- @move = (path, newPath, message="Moved #{path}") -> _getRef() .then (branch) => _git._updateTree(branch) .then (latestCommit) => _git.getTree(latestCommit, {recursive:true}) .then (tree) => # Update Tree _.each tree, (ref) -> ref.path = newPath if ref.path is path delete ref.sha if ref.type is 'tree' _git.postTree(tree) .then (rootTree) => _git.commit(latestCommit, rootTree, message) .then (commit) => _git.updateHead(branch, commit) .then (res) => return res # Finally, return the result # Write file contents to a given branch and path # ------- # To write base64 encoded data set `isBase64==true` # # Optionally takes a `parentCommitSha` which will be used as the # parent of this commit @write = (path, content, message="Changed #{path}", isBase64, parentCommitSha=null) -> contents = {} contents[path] = content: content isBase64: isBase64 @writeMany(contents, message, parentCommitSha) # Write the contents of multiple files to a given branch # ------- # Each file can also be binary. # # In general `contents` is a map where the key is the path and the value is `{content:'Hello World!', isBase64:false}`. # In the case of non-base64 encoded files the value may be a string instead. # # Example: # # contents = { # 'hello.txt': 'Hello World!', # 'path/to/hello2.txt': { content: 'Ahoy!', isBase64: false} # } # # Optionally takes an array of `parentCommitShas` which will be used as the # parents of this commit. @writeMany = (contents, message="Changed Multiple", parentCommitShas=null) -> # This method: # # 0. Finds the latest commit if one is not provided # 1. Asynchronously send new blobs for each file # 2. Use the return of the new Blob Post to return an entry in the new Commit Tree # 3. Wait on all the new blobs to finish # 4. Commit and update the branch _getRef() .then (branch) => # See below for Step 0. afterParentCommitShas = (parentCommitShas) => # 1. Asynchronously send all the files as new blobs. promises = _.map _.pairs(contents), ([path, data]) -> # `data` can be an object or a string. # If it is a string assume isBase64 is false and the string is the content content = data.content or data isBase64 = data.isBase64 or false _git.postBlob(content, isBase64) .then (blob) => # 2. return an entry in the new Commit Tree return { path: path mode: '100644' type: 'blob' sha: blob } # 3. Wait on all the new blobs to finish # Different Promise APIs implement this differently. For example: # - Promise uses `Promise.all([...])` # - jQuery uses `jQuery.when(p1, p2, p3, ...)` allPromises(promises) .then (newTrees) => _git.updateTreeMany(parentCommitShas, newTrees) .then (tree) => # 4. Commit and update the branch _git.commit(parentCommitShas, tree, message) .then (commitSha) => _git.updateHead(branch, commitSha) .then (res) => # Finally, return the result return res.object # Return something that has a `.sha` to match the signature for read # 0. Finds the latest commit if one is not provided if parentCommitShas return afterParentCommitShas(parentCommitShas) else return _git._updateTree(branch).then(afterParentCommitShas) # Repository Class # ------- # Provides methods for operating on the entire repository # and ways to operate on a `Branch`. class Repository constructor: (@options) -> # Private fields _user = @options.user _repo = @options.name # Set the `git` instance variable @git = new GitRepo(_user, _repo) @repoPath = "/repos/#{_user}/#{_repo}" @currentTree = branch: null sha: null @updateInfo = (options) -> _request 'PATCH', @repoPath, options # List all branches of a repository # ------- @getBranches = () -> @git.getBranches() # Get a branch of a repository # ------- @getBranch = (branchName=null) -> if branchName getRef = () => return resolvedPromise(branchName) return new Branch(@git, getRef) else return @getDefaultBranch() # Get the default branch of a repository # ------- @getDefaultBranch = () -> # Calls getInfo() to get the default branch name getRef = => @getInfo() .then (info) => return info.default_branch new Branch(@git, getRef) @setDefaultBranch = (branchName) -> @updateInfo {name: _repo, default_branch: branchName} # Get repository information # ------- @getInfo = () -> _request 'GET', @repoPath, null # Get contents # -------- @getContents = (branch, path) -> _request 'GET', "#{@repoPath}/contents?ref=#{branch}", {path: path} # Fork repository # ------- @fork = (organization) -> if organization _request 'POST', "#{@repoPath}/forks", organization: organization else _request 'POST', "#{@repoPath}/forks", null # Create pull request # -------- @createPullRequest = (options) -> _request 'POST', "#{@repoPath}/pulls", options # Get recent commits to the repository # -------- # Takes an object of optional paramaters: # # - `path`: Only commits containing this file path will be returned # - `author`: GitHub login, name, or email by which to filter by commit author # - `since`: ISO 8601 date - only commits after this date will be returned # - `until`: ISO 8601 date - only commits before this date will be returned @getCommits = (options) -> @git.getCommits(options) # List repository events # ------- @getEvents = () -> _request 'GET', "#{@repoPath}/events", null # List Issue events for a Repository # ------- @getIssueEvents = () -> _request 'GET', "#{@repoPath}/issues/events", null # List events for a network of Repositories # ------- @getNetworkEvents = () -> _request 'GET', "/networks/#{_user}/#{_repo}/events", null # List unread notifications for authenticated user # ------- # Optional arguments: # # - `all`: `true` to show notifications marked as read. # - `participating`: `true` to show only notifications in which # the user is directly participating or mentioned. # - `since`: Optional time. @getNotifications = (options={}) -> # Converts a Date object to a string getDate = (time) -> return time.toISOString() if Date == time.constructor return time options.since = getDate(options.since) if options.since queryString = toQueryString(options) _request 'GET', "#{@repoPath}/notifications#{queryString}", null # List Collaborators # ------- # When authenticating as an organization owner of an # organization-owned repository, all organization owners # are included in the list of collaborators. # Otherwise, only users with access to the repository are # returned in the collaborators list. @getCollaborators = () -> _request 'GET', "#{@repoPath}/collaborators", null @addCollaborator = (username) -> throw new Error 'BUG: username is required' if not username _request 'PUT', "#{@repoPath}/collaborators/#{username}", null, {isBoolean:true} @removeCollaborator = (username) -> throw new Error 'BUG: username is required' if not username _request 'DELETE', "#{@repoPath}/collaborators/#{username}", null, {isBoolean:true} @isCollaborator = (username=null) -> throw new Error 'BUG: username is required' if not username _request 'GET', "#{@repoPath}/collaborators/#{username}", null, {isBoolean:true} # Can Collaborate # ------- # True if the authenticated user has permission # to commit to this repository. @canCollaborate = () -> # Short-circuit if no credentials provided if not (clientOptions.password or clientOptions.token) return resolvedPromise(false) _client.getLogin() .then (login) => if not login return false else return @isCollaborator(login) .then null, (err) => # Problem logging in (maybe bad username/password) return false # List all hooks # ------- @getHooks = () -> _request 'GET', "#{@repoPath}/hooks", null # Get single hook # ------- @getHook = (id) -> _request 'GET', "#{@repoPath}/hooks/#{id}", null # Create a new hook # ------- # # - `name` (Required string) : The name of the service that is being called. # (See /hooks for the list of valid hook names.) # - `config` (Required hash) : A Hash containing key/value pairs to provide settings for this hook. # These settings vary between the services and are defined in the github-services repo. # - `events` (Optional array) : Determines what events the hook is triggered for. Default: ["push"]. # - `active` (Optional boolean) : Determines whether the hook is actually triggered on pushes. @createHook = (name, config, events=['push'], active=true) -> data = name: name config: config events: events active: active _request 'POST', "#{@repoPath}/hooks", data # Edit a hook # ------- # # - `config` (Optional hash) : A Hash containing key/value pairs to provide settings for this hook. # Modifying this will replace the entire config object. # These settings vary between the services and are defined in the github-services repo. # - `events` (Optional array) : Determines what events the hook is triggered for. # This replaces the entire array of events. Default: ["push"]. # - `addEvents` (Optional array) : Determines a list of events to be added to the list of events that the Hook triggers for. # - `removeEvents` (Optional array) : Determines a list of events to be removed from the list of events that the Hook triggers for. # - `active` (Optional boolean) : Determines whether the hook is actually triggered on pushes. @editHook = (id, config=null, events=null, addEvents=null, removeEvents=null, active=null) -> data = {} data.config = config if config != null data.events = events if events != null data.add_events = addEvents if addEvents != null data.remove_events = removeEvents if removeEvents != null data.active = active if active != null _request 'PATCH', "#{@repoPath}/hooks/#{id}", data # Test a `push` hook # ------- # This will trigger the hook with the latest push to the current # repository if the hook is subscribed to push events. # If the hook is not subscribed to push events, the server will # respond with 204 but no test POST will be generated. @testHook = (id) -> _request 'POST', "#{@repoPath}/hooks/#{id}/tests", null # Delete a hook # ------- @deleteHook = (id) -> _request 'DELETE', "#{@repoPath}/hooks/#{id}", null # List all Languages # ------- @getLanguages = -> _request 'GET', "#{@repoPath}/languages", null # List all releases # ------- @getReleases = () -> _request 'GET', "#{@repoPath}/releases", null # Gist API # ------- class Gist constructor: (@options) -> id = @options.id _gistPath = "/gists/#{id}" # Read the gist # -------- @read = () -> _request 'GET', _gistPath, null # Create the gist # -------- # # Files contains a hash with the filename as the key and # `{content: 'File Contents Here'}` as the value. # # Example: # # { "file1.txt": { # "content": "String file contents" # } # } @create = (files, isPublic=false, description=null) -> options = isPublic: isPublic files: files options.description = description if description? _request 'POST', "/gists", options # Delete the gist # -------- @delete = () -> _request 'DELETE', _gistPath, null # Fork a gist # -------- @fork = () -> _request 'POST', "#{_gistPath}/forks", null # Update a gist with the new stuff # -------- # `files` are files that make up this gist. # The key of which should be an optional string filename # and the value another optional hash with parameters: # # - `content`: Optional string - Updated file contents # - `filename`: Optional string - New name for this file. # # **NOTE:** All files from the previous version of the gist are carried # over by default if not included in the hash. Deletes can be performed # by including the filename with a null hash. @update = (files, description=null) -> options = {files: files} options.description = description if description? _request 'PATCH', _gistPath, options # Star a gist # ------- @star = () -> _request 'PUT', "#{_gistPath}/star" # Unstar a gist # ------- @unstar = () -> _request 'DELETE', "#{_gistPath}/star" # Check if a gist is starred # ------- @isStarred = () -> _request 'GET', "#{_gistPath}", null, {isBoolean:true} # Top Level API # ------- @getRepo = (user, repo) -> throw new Error('BUG! user argument is required') if not user throw new Error('BUG! repo argument is required') if not repo new Repository( user: user name: repo ) @getOrg = (name) -> new Organization(name) # API for viewing info for arbitrary users or the current user # if no arguments are provided. @getUser = (login=null) -> if login return new User(login) else if clientOptions.password or clientOptions.token return new AuthenticatedUser() else return null @getGist = (id) -> new Gist(id: id) # Returns the login of the current user. # When using OAuth this is unknown but is necessary to # determine if the current user has commit access to a # repository @getLogin = () -> # 3 cases: # 1. No authentication provided # 2. Username (and password) provided # 3. OAuth token provided if clientOptions.password or clientOptions.token return new User().getInfo() .then (info) -> return info.login else return resolvedPromise(null) # Return the class for assignment return Octokit # Register with nodejs, requirejs, or as a global # ------- # Depending on the context this file is called, register it appropriately if exports? # Use native promises if Harmony is on Promise = @Promise or require('es6-promise').Promise XMLHttpRequest = @XMLHttpRequest or require('xmlhttprequest').XMLHttpRequest newPromise = (fn) -> return new Promise(fn) allPromises = (promises) -> return Promise.all.call(Promise, promises) # Encode using native Base64 encode = @btoa or (str) -> buffer = new Buffer(str, 'binary') return buffer.toString('base64') Octokit = makeOctokit(newPromise, allPromises, XMLHttpRequest, encode, 'octokit') # `User-Agent` (for nodejs) exports.new = (options) -> new Octokit(options) else # Octokit is being used in the browser. # Find a Promise API and register with `define` (if available) # Register Octokit once a Promise API is loaded. # In the case of angular, this may be async. createGlobalAndAMD = (newPromise, allPromises) => if @define? @define 'octokit', [], () => return makeOctokit(newPromise, allPromises, @XMLHttpRequest, @btoa) else Octokit = makeOctokit(newPromise, allPromises, @XMLHttpRequest, @btoa) # Assign to a global `Octokit` @Octokit = Octokit @Github = Octokit # Determine the correct Promise factory. # Try to use libraries before native Promises since most Promise users # are already using a library. # # Try in the following order: # - Q Promise # - angularjs Promise # - jQuery Promise # - native Promise or a polyfill if @Q newPromise = (fn) => deferred = @Q.defer() resolve = (val) -> deferred.resolve(val) reject = (err) -> deferred.reject(err) fn(resolve, reject) return deferred.promise allPromises = (promises) -> @Q.all(promises) createGlobalAndAMD(newPromise, allPromises) else if @angular # Details on Angular Promises: http://docs.angularjs.org/api/ng/service/$q injector = angular.injector(['ng']) injector.invoke ($q) -> newPromise = (fn) -> deferred = $q.defer() resolve = (val) -> deferred.resolve(val) reject = (err) -> deferred.reject(err) fn(resolve, reject) return deferred.promise allPromises = (promises) -> $q.all(promises) createGlobalAndAMD(newPromise, allPromises) else if @jQuery?.Deferred newPromise = (fn) => promise = @jQuery.Deferred() resolve = (val) -> promise.resolve(val) reject = (val) -> promise.reject(val) fn(resolve, reject) return promise.promise() allPromises = (promises) => # `jQuery.when` is a little odd. # - It accepts each promise as an argument (instead of an array of promises) # - Each resolved value is an argument (instead of an array of values) # # So, convert the array of promises to args and then the resolved args to an array return @jQuery.when(promises...).then((promises...) -> return promises) createGlobalAndAMD(newPromise, allPromises) else if @Promise newPromise = (fn) => return new @Promise (resolve, reject) -> # Some browsers (like node-webkit 0.8.6) contain an older implementation # of Promises that provide 1 argument (a `PromiseResolver`). if resolve.fulfill fn(resolve.resolve.bind(resolve), resolve.reject.bind(resolve)) else fn(arguments...) allPromises = (promises) => @Promise.all.call(@Promise, promises) createGlobalAndAMD(newPromise, allPromises) else # Otherwise, throw an error err = (msg) -> console?.error?(msg) throw new Error(msg) err('A Promise API was not found. Supported libraries that have Promises are jQuery, angularjs, and https://github.com/jakearchibald/es6-promise')
[ { "context": "jector](http://neocotic.com/injector)\n#\n# (c) 2014 Alasdair Mercer\n#\n# Freely distributable under the MIT license\n\n#", "end": 71, "score": 0.9998696446418762, "start": 56, "tag": "NAME", "value": "Alasdair Mercer" } ]
src/coffee/models.coffee
SlinkySalmon633/injector-chrome
33
# [Injector](http://neocotic.com/injector) # # (c) 2014 Alasdair Mercer # # Freely distributable under the MIT license # Models # ------ # Expose all models (and collections) that are used throughout the extension. # # These are intentionally not added to the global object (i.e. `window`) to avoid cluttering that # *namespace*. models = window.models = { # Convenience short-hand method for retrieving all common models and collections. # # The `callback` function will be passed a map of the fetched instances. fetch: (callback) -> Settings.fetch (settings) -> EditorSettings.fetch (editorSettings) -> Snippets.fetch (snippets) -> callback({ settings, editorSettings, snippets }) } # Editor # ------ # The settings associated with the Ace editor. EditorSettings = models.EditorSettings = Injector.SingletonModel.extend { # Store the editor settings remotely. storage: name: 'EditorSettings' type: 'sync' # Default attributes for the editor settings. defaults: indentSize: 2 lineWrap: no softTabs: yes theme: 'chrome' } # Settings # -------- # The general settings that can be configured (or are related to) the options page. Settings = models.Settings = Injector.SingletonModel.extend { # Store the general settings remotely. storage: name: 'Settings' type: 'sync' # Default attributes for the general settings. defaults: analytics: yes tab: 'snippets_nav' } # Snippets # -------- # Default Ace editor mode/language. DEFAULT_MODE = 'javascript' # A snippet to be injected into a specific host. # # The snippet's code can be written in a number of supported languages and can be either be a # script to be executed on the page or contain styles to be applied to it. Snippet = models.Snippet = Injector.Model.extend { # Default attributes for a snippet. defaults: code: '' mode: DEFAULT_MODE selected: no # Deselect this snippet, but only if it is currently selected. deselect: -> if @get('selected') @save({ selected: no }) .done => @trigger('deselected', @) else $.Deferred().resolve() # Indicate whether or not the mode of this snippet falls under a group with the given `name`. inGroup: (group, name) -> name = group if _.isString(group) _.contains(Snippet.modeGroups[name], @get('mode')) # Select this snippet, but only if it is *not* already selected. select: -> if @get('selected') $.Deferred().resolve() else @save({ selected: yes }) .done => @collection?.chain() .without(@) .invoke('save', { selected: no }) @trigger('selected', @) # Validate that the attributes of this snippet are valid. validate: (attributes) -> {host, mode} = attributes unless host 'host is required' else unless mode 'mode is required' }, { # Expose the default Ace editor mode/language publically. defaultMode: DEFAULT_MODE # Map of mode groups. modeGroups: {} # Add all of the mode `groups` that are provided in their object form. # # If a group already exists, it's original value will be overridden. mapModeGroups: (groups) -> @modeGroups[group.name] = group.modes for group in groups # Populates the map of mode groups with the values from the configuration file. # # Nothing happens if `Snippet.modeGroups` has already been populated. populateModeGroups: (callback) -> if _.isEmpty(@modeGroups) $.getJSON chrome.extension.getURL('configuration.json'), (config) => @mapModeGroups(config.editor.modeGroups) callback() else callback() } # Collection of snippets created by the user. Snippets = models.Snippets = Injector.Collection.extend { # Store the snippets locally. storage: name: 'Snippets' type: 'local' # Model class contained by this collection. model: Snippet # Sort snippets based on the `host` attribute. comparator: 'host' # List the snippets that are associated with a mode under the group witht the given `name`. group: (name) -> Snippets.group(@, name) }, { # Retrieve **all** `Snippet` models. fetch: (callback) -> Snippet.populateModeGroups -> collection = new Snippets() collection.fetch().then -> callback(collection) # Map the specified `snippets` based on their mode groups. # # Optionally, when a group `name` is provided, only a list of the snippets that are associated # with a mode under that group will be returned. group: (snippets, name) -> if name snippets.filter (snippet) -> snippet.inGroup(name) else groups = {} for name, modes of Snippet.modeGroups groups[name] = snippets.filter (snippet) -> snippet.inGroup(name) groups }
213024
# [Injector](http://neocotic.com/injector) # # (c) 2014 <NAME> # # Freely distributable under the MIT license # Models # ------ # Expose all models (and collections) that are used throughout the extension. # # These are intentionally not added to the global object (i.e. `window`) to avoid cluttering that # *namespace*. models = window.models = { # Convenience short-hand method for retrieving all common models and collections. # # The `callback` function will be passed a map of the fetched instances. fetch: (callback) -> Settings.fetch (settings) -> EditorSettings.fetch (editorSettings) -> Snippets.fetch (snippets) -> callback({ settings, editorSettings, snippets }) } # Editor # ------ # The settings associated with the Ace editor. EditorSettings = models.EditorSettings = Injector.SingletonModel.extend { # Store the editor settings remotely. storage: name: 'EditorSettings' type: 'sync' # Default attributes for the editor settings. defaults: indentSize: 2 lineWrap: no softTabs: yes theme: 'chrome' } # Settings # -------- # The general settings that can be configured (or are related to) the options page. Settings = models.Settings = Injector.SingletonModel.extend { # Store the general settings remotely. storage: name: 'Settings' type: 'sync' # Default attributes for the general settings. defaults: analytics: yes tab: 'snippets_nav' } # Snippets # -------- # Default Ace editor mode/language. DEFAULT_MODE = 'javascript' # A snippet to be injected into a specific host. # # The snippet's code can be written in a number of supported languages and can be either be a # script to be executed on the page or contain styles to be applied to it. Snippet = models.Snippet = Injector.Model.extend { # Default attributes for a snippet. defaults: code: '' mode: DEFAULT_MODE selected: no # Deselect this snippet, but only if it is currently selected. deselect: -> if @get('selected') @save({ selected: no }) .done => @trigger('deselected', @) else $.Deferred().resolve() # Indicate whether or not the mode of this snippet falls under a group with the given `name`. inGroup: (group, name) -> name = group if _.isString(group) _.contains(Snippet.modeGroups[name], @get('mode')) # Select this snippet, but only if it is *not* already selected. select: -> if @get('selected') $.Deferred().resolve() else @save({ selected: yes }) .done => @collection?.chain() .without(@) .invoke('save', { selected: no }) @trigger('selected', @) # Validate that the attributes of this snippet are valid. validate: (attributes) -> {host, mode} = attributes unless host 'host is required' else unless mode 'mode is required' }, { # Expose the default Ace editor mode/language publically. defaultMode: DEFAULT_MODE # Map of mode groups. modeGroups: {} # Add all of the mode `groups` that are provided in their object form. # # If a group already exists, it's original value will be overridden. mapModeGroups: (groups) -> @modeGroups[group.name] = group.modes for group in groups # Populates the map of mode groups with the values from the configuration file. # # Nothing happens if `Snippet.modeGroups` has already been populated. populateModeGroups: (callback) -> if _.isEmpty(@modeGroups) $.getJSON chrome.extension.getURL('configuration.json'), (config) => @mapModeGroups(config.editor.modeGroups) callback() else callback() } # Collection of snippets created by the user. Snippets = models.Snippets = Injector.Collection.extend { # Store the snippets locally. storage: name: 'Snippets' type: 'local' # Model class contained by this collection. model: Snippet # Sort snippets based on the `host` attribute. comparator: 'host' # List the snippets that are associated with a mode under the group witht the given `name`. group: (name) -> Snippets.group(@, name) }, { # Retrieve **all** `Snippet` models. fetch: (callback) -> Snippet.populateModeGroups -> collection = new Snippets() collection.fetch().then -> callback(collection) # Map the specified `snippets` based on their mode groups. # # Optionally, when a group `name` is provided, only a list of the snippets that are associated # with a mode under that group will be returned. group: (snippets, name) -> if name snippets.filter (snippet) -> snippet.inGroup(name) else groups = {} for name, modes of Snippet.modeGroups groups[name] = snippets.filter (snippet) -> snippet.inGroup(name) groups }
true
# [Injector](http://neocotic.com/injector) # # (c) 2014 PI:NAME:<NAME>END_PI # # Freely distributable under the MIT license # Models # ------ # Expose all models (and collections) that are used throughout the extension. # # These are intentionally not added to the global object (i.e. `window`) to avoid cluttering that # *namespace*. models = window.models = { # Convenience short-hand method for retrieving all common models and collections. # # The `callback` function will be passed a map of the fetched instances. fetch: (callback) -> Settings.fetch (settings) -> EditorSettings.fetch (editorSettings) -> Snippets.fetch (snippets) -> callback({ settings, editorSettings, snippets }) } # Editor # ------ # The settings associated with the Ace editor. EditorSettings = models.EditorSettings = Injector.SingletonModel.extend { # Store the editor settings remotely. storage: name: 'EditorSettings' type: 'sync' # Default attributes for the editor settings. defaults: indentSize: 2 lineWrap: no softTabs: yes theme: 'chrome' } # Settings # -------- # The general settings that can be configured (or are related to) the options page. Settings = models.Settings = Injector.SingletonModel.extend { # Store the general settings remotely. storage: name: 'Settings' type: 'sync' # Default attributes for the general settings. defaults: analytics: yes tab: 'snippets_nav' } # Snippets # -------- # Default Ace editor mode/language. DEFAULT_MODE = 'javascript' # A snippet to be injected into a specific host. # # The snippet's code can be written in a number of supported languages and can be either be a # script to be executed on the page or contain styles to be applied to it. Snippet = models.Snippet = Injector.Model.extend { # Default attributes for a snippet. defaults: code: '' mode: DEFAULT_MODE selected: no # Deselect this snippet, but only if it is currently selected. deselect: -> if @get('selected') @save({ selected: no }) .done => @trigger('deselected', @) else $.Deferred().resolve() # Indicate whether or not the mode of this snippet falls under a group with the given `name`. inGroup: (group, name) -> name = group if _.isString(group) _.contains(Snippet.modeGroups[name], @get('mode')) # Select this snippet, but only if it is *not* already selected. select: -> if @get('selected') $.Deferred().resolve() else @save({ selected: yes }) .done => @collection?.chain() .without(@) .invoke('save', { selected: no }) @trigger('selected', @) # Validate that the attributes of this snippet are valid. validate: (attributes) -> {host, mode} = attributes unless host 'host is required' else unless mode 'mode is required' }, { # Expose the default Ace editor mode/language publically. defaultMode: DEFAULT_MODE # Map of mode groups. modeGroups: {} # Add all of the mode `groups` that are provided in their object form. # # If a group already exists, it's original value will be overridden. mapModeGroups: (groups) -> @modeGroups[group.name] = group.modes for group in groups # Populates the map of mode groups with the values from the configuration file. # # Nothing happens if `Snippet.modeGroups` has already been populated. populateModeGroups: (callback) -> if _.isEmpty(@modeGroups) $.getJSON chrome.extension.getURL('configuration.json'), (config) => @mapModeGroups(config.editor.modeGroups) callback() else callback() } # Collection of snippets created by the user. Snippets = models.Snippets = Injector.Collection.extend { # Store the snippets locally. storage: name: 'Snippets' type: 'local' # Model class contained by this collection. model: Snippet # Sort snippets based on the `host` attribute. comparator: 'host' # List the snippets that are associated with a mode under the group witht the given `name`. group: (name) -> Snippets.group(@, name) }, { # Retrieve **all** `Snippet` models. fetch: (callback) -> Snippet.populateModeGroups -> collection = new Snippets() collection.fetch().then -> callback(collection) # Map the specified `snippets` based on their mode groups. # # Optionally, when a group `name` is provided, only a list of the snippets that are associated # with a mode under that group will be returned. group: (snippets, name) -> if name snippets.filter (snippet) -> snippet.inGroup(name) else groups = {} for name, modes of Snippet.modeGroups groups[name] = snippets.filter (snippet) -> snippet.inGroup(name) groups }
[ { "context": "# @author Gianluigi Mango\n# Post API\nPostHandler = require './handler/postH", "end": 25, "score": 0.9998695850372314, "start": 10, "tag": "NAME", "value": "Gianluigi Mango" } ]
dev/server/api/postApi.coffee
knickatheart/mean-api
0
# @author Gianluigi Mango # Post API PostHandler = require './handler/postHandler' module.exports = class UserApi constructor: (@action, @path, @req, @res) -> @postHandler = new PostHandler @req console.info '[Query]', action switch @action when 'getAll' then @postHandler.getAll @path, @res when 'savePost' then @postHandler.savePost @path, @res else res.send Error: 'No method found'
199067
# @author <NAME> # Post API PostHandler = require './handler/postHandler' module.exports = class UserApi constructor: (@action, @path, @req, @res) -> @postHandler = new PostHandler @req console.info '[Query]', action switch @action when 'getAll' then @postHandler.getAll @path, @res when 'savePost' then @postHandler.savePost @path, @res else res.send Error: 'No method found'
true
# @author PI:NAME:<NAME>END_PI # Post API PostHandler = require './handler/postHandler' module.exports = class UserApi constructor: (@action, @path, @req, @res) -> @postHandler = new PostHandler @req console.info '[Query]', action switch @action when 'getAll' then @postHandler.getAll @path, @res when 'savePost' then @postHandler.savePost @path, @res else res.send Error: 'No method found'
[ { "context": "ileoverview Tests for no-div-regex rule.\n# @author Matt DuVall <http://www.mattduvall.com>\n###\n\n'use strict'\n\n#-", "end": 71, "score": 0.9998252987861633, "start": 60, "tag": "NAME", "value": "Matt DuVall" } ]
src/tests/rules/no-div-regex.coffee
danielbayley/eslint-plugin-coffee
21
###* # @fileoverview Tests for no-div-regex rule. # @author Matt DuVall <http://www.mattduvall.com> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/no-div-regex' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-div-regex', rule, valid: ["f = -> /foo/ig.test('bar')", 'f = -> /\\=foo/', 'f = -> ///=foo///'] invalid: [ code: 'f = -> /=foo/' output: 'f = -> /[=]foo/' errors: [messageId: 'unexpected', type: 'Literal'] ]
12656
###* # @fileoverview Tests for no-div-regex rule. # @author <NAME> <http://www.mattduvall.com> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/no-div-regex' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-div-regex', rule, valid: ["f = -> /foo/ig.test('bar')", 'f = -> /\\=foo/', 'f = -> ///=foo///'] invalid: [ code: 'f = -> /=foo/' output: 'f = -> /[=]foo/' errors: [messageId: 'unexpected', type: 'Literal'] ]
true
###* # @fileoverview Tests for no-div-regex rule. # @author PI:NAME:<NAME>END_PI <http://www.mattduvall.com> ### 'use strict' #------------------------------------------------------------------------------ # Requirements #------------------------------------------------------------------------------ rule = require '../../rules/no-div-regex' {RuleTester} = require 'eslint' path = require 'path' #------------------------------------------------------------------------------ # Tests #------------------------------------------------------------------------------ ruleTester = new RuleTester parser: path.join __dirname, '../../..' ruleTester.run 'no-div-regex', rule, valid: ["f = -> /foo/ig.test('bar')", 'f = -> /\\=foo/', 'f = -> ///=foo///'] invalid: [ code: 'f = -> /=foo/' output: 'f = -> /[=]foo/' errors: [messageId: 'unexpected', type: 'Literal'] ]
[ { "context": "n.meta.should.eql {}\n\n collection.jsonKey = 'base_collection'\n collection.parse(jsonKeyResp)\n collec", "end": 2465, "score": 0.8898191452026367, "start": 2450, "tag": "KEY", "value": "base_collection" } ]
test/shared/base/collection.test.coffee
redbadger/rendr
0
require('../../../shared/globals') should = require('should') BaseCollection = require('../../../shared/base/collection') BaseModel = require('../../../shared/base/model') fetcher = require('../../../shared/fetcher') modelUtils = require('../../../shared/modelUtils') describe 'BaseCollection', -> describe 'parse', -> beforeEach -> class @MyCollection extends BaseCollection jsonKey: 'my_collection' model: class MyModel extends BaseModel jsonKey: 'my_model' @collection = new @MyCollection models = [ {id: 1, name: 'one'} {id: 2, name: 'two'} ] modelsNested = [ {my_model: {id: 1, name: 'one'}} {my_model: {id: 2, name: 'two'}} ] @denested = models @nested = my_collection: models @denestedModelsNested = modelsNested @nestedModelsNested = my_collection: modelsNested it "should not de-nest collection if not nested collection", -> @collection.parse(@denested).should.eql @denested it "should de-nest collection if nested collection", -> @collection.parse(@nested).should.eql @denested it "should de-nest models if nested models", -> @collection.parse(@denestedModelsNested).should.eql @denested it "should de-nest collection and models if nested collection and models", -> @collection.parse(@nestedModelsNested).should.eql @denested describe 'fetch', -> it "sould store params used", -> params = items_per_page: 10 offset: 30 collection = new BaseCollection # Make 'sync' a noop. collection.sync = -> collection.params.should.eql {} collection.fetch url: 'foo' data: params should.deepEqual params, collection.params describe 'meta', -> it "should store 'meta' on initialization", -> collection = new BaseCollection collection.meta.should.eql {} meta = foo: 'bar' collection = new BaseCollection([], {meta: meta}) collection.meta.should.eql meta it "should store 'meta' when parsing, and there is a jsonKey", -> meta = foo: 'bar' resp = [{id: 1, foo: 'bar'}, {id: 2, foo: 'bot'}] jsonKeyResp = _.extend {}, meta, base_collection: resp collection = new BaseCollection collection.parse(resp) collection.meta.should.eql {} collection.jsonKey = 'base_collection' collection.parse(jsonKeyResp) collection.meta.should.eql meta describe "store", -> beforeEach -> fetcher.modelStore.clear() fetcher.collectionStore.clear() class @MyCollection extends BaseCollection modelUtils.addClassMapping @MyCollection.name, @MyCollection it "should store its models in the modelStore and params in collectionStore", -> models = [{id: 1, foo: 'bar'}, {id: 2, foo: 'bot'}] meta = item1: 'value1' item2: 'value2' collection = new @MyCollection(models, {meta: meta}) collection.store() models.forEach (modelAttrs) => storedModel = fetcher.modelStore.get collection.model.name, modelAttrs.id storedModel.should.eql modelAttrs storedCollection = fetcher.collectionStore.get @MyCollection.name, collection.params storedCollection.ids.should.eql _.pluck(models, 'id') storedCollection.meta.should.eql meta
73746
require('../../../shared/globals') should = require('should') BaseCollection = require('../../../shared/base/collection') BaseModel = require('../../../shared/base/model') fetcher = require('../../../shared/fetcher') modelUtils = require('../../../shared/modelUtils') describe 'BaseCollection', -> describe 'parse', -> beforeEach -> class @MyCollection extends BaseCollection jsonKey: 'my_collection' model: class MyModel extends BaseModel jsonKey: 'my_model' @collection = new @MyCollection models = [ {id: 1, name: 'one'} {id: 2, name: 'two'} ] modelsNested = [ {my_model: {id: 1, name: 'one'}} {my_model: {id: 2, name: 'two'}} ] @denested = models @nested = my_collection: models @denestedModelsNested = modelsNested @nestedModelsNested = my_collection: modelsNested it "should not de-nest collection if not nested collection", -> @collection.parse(@denested).should.eql @denested it "should de-nest collection if nested collection", -> @collection.parse(@nested).should.eql @denested it "should de-nest models if nested models", -> @collection.parse(@denestedModelsNested).should.eql @denested it "should de-nest collection and models if nested collection and models", -> @collection.parse(@nestedModelsNested).should.eql @denested describe 'fetch', -> it "sould store params used", -> params = items_per_page: 10 offset: 30 collection = new BaseCollection # Make 'sync' a noop. collection.sync = -> collection.params.should.eql {} collection.fetch url: 'foo' data: params should.deepEqual params, collection.params describe 'meta', -> it "should store 'meta' on initialization", -> collection = new BaseCollection collection.meta.should.eql {} meta = foo: 'bar' collection = new BaseCollection([], {meta: meta}) collection.meta.should.eql meta it "should store 'meta' when parsing, and there is a jsonKey", -> meta = foo: 'bar' resp = [{id: 1, foo: 'bar'}, {id: 2, foo: 'bot'}] jsonKeyResp = _.extend {}, meta, base_collection: resp collection = new BaseCollection collection.parse(resp) collection.meta.should.eql {} collection.jsonKey = '<KEY>' collection.parse(jsonKeyResp) collection.meta.should.eql meta describe "store", -> beforeEach -> fetcher.modelStore.clear() fetcher.collectionStore.clear() class @MyCollection extends BaseCollection modelUtils.addClassMapping @MyCollection.name, @MyCollection it "should store its models in the modelStore and params in collectionStore", -> models = [{id: 1, foo: 'bar'}, {id: 2, foo: 'bot'}] meta = item1: 'value1' item2: 'value2' collection = new @MyCollection(models, {meta: meta}) collection.store() models.forEach (modelAttrs) => storedModel = fetcher.modelStore.get collection.model.name, modelAttrs.id storedModel.should.eql modelAttrs storedCollection = fetcher.collectionStore.get @MyCollection.name, collection.params storedCollection.ids.should.eql _.pluck(models, 'id') storedCollection.meta.should.eql meta
true
require('../../../shared/globals') should = require('should') BaseCollection = require('../../../shared/base/collection') BaseModel = require('../../../shared/base/model') fetcher = require('../../../shared/fetcher') modelUtils = require('../../../shared/modelUtils') describe 'BaseCollection', -> describe 'parse', -> beforeEach -> class @MyCollection extends BaseCollection jsonKey: 'my_collection' model: class MyModel extends BaseModel jsonKey: 'my_model' @collection = new @MyCollection models = [ {id: 1, name: 'one'} {id: 2, name: 'two'} ] modelsNested = [ {my_model: {id: 1, name: 'one'}} {my_model: {id: 2, name: 'two'}} ] @denested = models @nested = my_collection: models @denestedModelsNested = modelsNested @nestedModelsNested = my_collection: modelsNested it "should not de-nest collection if not nested collection", -> @collection.parse(@denested).should.eql @denested it "should de-nest collection if nested collection", -> @collection.parse(@nested).should.eql @denested it "should de-nest models if nested models", -> @collection.parse(@denestedModelsNested).should.eql @denested it "should de-nest collection and models if nested collection and models", -> @collection.parse(@nestedModelsNested).should.eql @denested describe 'fetch', -> it "sould store params used", -> params = items_per_page: 10 offset: 30 collection = new BaseCollection # Make 'sync' a noop. collection.sync = -> collection.params.should.eql {} collection.fetch url: 'foo' data: params should.deepEqual params, collection.params describe 'meta', -> it "should store 'meta' on initialization", -> collection = new BaseCollection collection.meta.should.eql {} meta = foo: 'bar' collection = new BaseCollection([], {meta: meta}) collection.meta.should.eql meta it "should store 'meta' when parsing, and there is a jsonKey", -> meta = foo: 'bar' resp = [{id: 1, foo: 'bar'}, {id: 2, foo: 'bot'}] jsonKeyResp = _.extend {}, meta, base_collection: resp collection = new BaseCollection collection.parse(resp) collection.meta.should.eql {} collection.jsonKey = 'PI:KEY:<KEY>END_PI' collection.parse(jsonKeyResp) collection.meta.should.eql meta describe "store", -> beforeEach -> fetcher.modelStore.clear() fetcher.collectionStore.clear() class @MyCollection extends BaseCollection modelUtils.addClassMapping @MyCollection.name, @MyCollection it "should store its models in the modelStore and params in collectionStore", -> models = [{id: 1, foo: 'bar'}, {id: 2, foo: 'bot'}] meta = item1: 'value1' item2: 'value2' collection = new @MyCollection(models, {meta: meta}) collection.store() models.forEach (modelAttrs) => storedModel = fetcher.modelStore.get collection.model.name, modelAttrs.id storedModel.should.eql modelAttrs storedCollection = fetcher.collectionStore.get @MyCollection.name, collection.params storedCollection.ids.should.eql _.pluck(models, 'id') storedCollection.meta.should.eql meta
[ { "context": " = singularize underscore name\n fkey ?= \"#{name}_id\"\n\n association = (record) ->\n model = loa", "end": 1505, "score": 0.7915302515029907, "start": 1503, "tag": "KEY", "value": "id" } ]
src/async.coffee
nextorigin/spine-relations
0
Spine = require "spine" errify = require "errify" Relations = require "./relations" helpers = require "./helpers" {singularize, underscore, loadModel} = helpers arraysMatch = (arrays...) -> match = String arrays.pop() return false for array in arrays when (String array) isnt match true isEmpty = (obj) -> return false for own key of obj true class Collection extends Relations.Classes.BaseCollection select: (cb) -> @model.select (rec) => @associated(rec) and cb(rec) class Instance extends Relations.Classes.Instance find: (cb = ->) -> unless @record[@fkey] cb "no foreign key" false else @model.find @record[@fkey], cb update: (value, cb = ->) -> ideally = errify cb unless value instanceof @model value = new @model value await value.save ideally defer() if value.isNew() @record[@fkey] = value and value.id @record.save cb class Singleton extends Relations.Classes.Singleton find: (cb = ->) -> @record.id and @model.findByAttribute @fkey, @record.id, cb update: (value, cb = ->) -> unless value instanceof @model value = @model.fromJSON(value) value[@fkey] = @record.id value.save cb Async = findCached: -> Spine.Model.find.apply this, arguments belongsTo: (model, name, fkey) -> parent = @ unless name? model = loadModel model, parent name = model.className.toLowerCase() name = singularize underscore name fkey ?= "#{name}_id" association = (record) -> model = loadModel model, parent new Instance {name, model, record, fkey} @::[name] = (value, cb = ->) -> if typeof value is "function" cb = value value = null if value? association(@).update value, cb else association(@).find cb @attributes.push fkey hasOne: (model, name, fkey) -> parent = @ unless name? model = loadModel model, parent name = model.className.toLowerCase() name = singularize underscore name fkey ?= "#{underscore(@className)}_id" association = (record) -> model = loadModel model, parent new Singleton {name, model, record, fkey} @::[name] = (value, cb) -> if value? association(@).update value, cb else association(@).find cb AsyncHelpers = diff: -> return this if @isNew() attrs = @attributes() orig = @constructor.findCached @id diff = {} for key, value of attrs origkey = orig[key] origkey = orig[key]() if typeof origkey is "function" if Array.isArray value diff[key] = value unless arraysMatch origkey, value else diff[key] = value unless origkey is value return null if isEmpty diff diff Spine.Model.extend.call Relations, Async Spine.Model.extend Relations Spine.Model.include AsyncHelpers Relations.Classes.Collection = Collection Relations.Classes.Instance = Instance Spine.Model.Relations = Relations module?.exports = Relations
185269
Spine = require "spine" errify = require "errify" Relations = require "./relations" helpers = require "./helpers" {singularize, underscore, loadModel} = helpers arraysMatch = (arrays...) -> match = String arrays.pop() return false for array in arrays when (String array) isnt match true isEmpty = (obj) -> return false for own key of obj true class Collection extends Relations.Classes.BaseCollection select: (cb) -> @model.select (rec) => @associated(rec) and cb(rec) class Instance extends Relations.Classes.Instance find: (cb = ->) -> unless @record[@fkey] cb "no foreign key" false else @model.find @record[@fkey], cb update: (value, cb = ->) -> ideally = errify cb unless value instanceof @model value = new @model value await value.save ideally defer() if value.isNew() @record[@fkey] = value and value.id @record.save cb class Singleton extends Relations.Classes.Singleton find: (cb = ->) -> @record.id and @model.findByAttribute @fkey, @record.id, cb update: (value, cb = ->) -> unless value instanceof @model value = @model.fromJSON(value) value[@fkey] = @record.id value.save cb Async = findCached: -> Spine.Model.find.apply this, arguments belongsTo: (model, name, fkey) -> parent = @ unless name? model = loadModel model, parent name = model.className.toLowerCase() name = singularize underscore name fkey ?= "#{name}_<KEY>" association = (record) -> model = loadModel model, parent new Instance {name, model, record, fkey} @::[name] = (value, cb = ->) -> if typeof value is "function" cb = value value = null if value? association(@).update value, cb else association(@).find cb @attributes.push fkey hasOne: (model, name, fkey) -> parent = @ unless name? model = loadModel model, parent name = model.className.toLowerCase() name = singularize underscore name fkey ?= "#{underscore(@className)}_id" association = (record) -> model = loadModel model, parent new Singleton {name, model, record, fkey} @::[name] = (value, cb) -> if value? association(@).update value, cb else association(@).find cb AsyncHelpers = diff: -> return this if @isNew() attrs = @attributes() orig = @constructor.findCached @id diff = {} for key, value of attrs origkey = orig[key] origkey = orig[key]() if typeof origkey is "function" if Array.isArray value diff[key] = value unless arraysMatch origkey, value else diff[key] = value unless origkey is value return null if isEmpty diff diff Spine.Model.extend.call Relations, Async Spine.Model.extend Relations Spine.Model.include AsyncHelpers Relations.Classes.Collection = Collection Relations.Classes.Instance = Instance Spine.Model.Relations = Relations module?.exports = Relations
true
Spine = require "spine" errify = require "errify" Relations = require "./relations" helpers = require "./helpers" {singularize, underscore, loadModel} = helpers arraysMatch = (arrays...) -> match = String arrays.pop() return false for array in arrays when (String array) isnt match true isEmpty = (obj) -> return false for own key of obj true class Collection extends Relations.Classes.BaseCollection select: (cb) -> @model.select (rec) => @associated(rec) and cb(rec) class Instance extends Relations.Classes.Instance find: (cb = ->) -> unless @record[@fkey] cb "no foreign key" false else @model.find @record[@fkey], cb update: (value, cb = ->) -> ideally = errify cb unless value instanceof @model value = new @model value await value.save ideally defer() if value.isNew() @record[@fkey] = value and value.id @record.save cb class Singleton extends Relations.Classes.Singleton find: (cb = ->) -> @record.id and @model.findByAttribute @fkey, @record.id, cb update: (value, cb = ->) -> unless value instanceof @model value = @model.fromJSON(value) value[@fkey] = @record.id value.save cb Async = findCached: -> Spine.Model.find.apply this, arguments belongsTo: (model, name, fkey) -> parent = @ unless name? model = loadModel model, parent name = model.className.toLowerCase() name = singularize underscore name fkey ?= "#{name}_PI:KEY:<KEY>END_PI" association = (record) -> model = loadModel model, parent new Instance {name, model, record, fkey} @::[name] = (value, cb = ->) -> if typeof value is "function" cb = value value = null if value? association(@).update value, cb else association(@).find cb @attributes.push fkey hasOne: (model, name, fkey) -> parent = @ unless name? model = loadModel model, parent name = model.className.toLowerCase() name = singularize underscore name fkey ?= "#{underscore(@className)}_id" association = (record) -> model = loadModel model, parent new Singleton {name, model, record, fkey} @::[name] = (value, cb) -> if value? association(@).update value, cb else association(@).find cb AsyncHelpers = diff: -> return this if @isNew() attrs = @attributes() orig = @constructor.findCached @id diff = {} for key, value of attrs origkey = orig[key] origkey = orig[key]() if typeof origkey is "function" if Array.isArray value diff[key] = value unless arraysMatch origkey, value else diff[key] = value unless origkey is value return null if isEmpty diff diff Spine.Model.extend.call Relations, Async Spine.Model.extend Relations Spine.Model.include AsyncHelpers Relations.Classes.Collection = Collection Relations.Classes.Instance = Instance Spine.Model.Relations = Relations module?.exports = Relations
[ { "context": "tabase\nrequire(\"./db\") \"mongodb://heroku_lvm2p4zk:27me0oje7us7b97s3pg9s7ooak@ds035703.mongolab.com:35703/heroku_lvm2p4zk\", ->\n Recipe = require \"./", "end": 160, "score": 0.999545693397522, "start": 112, "tag": "EMAIL", "value": "27me0oje7us7b97s3pg9s7ooak@ds035703.mong...
algo/index.coffee
1egoman/bag-node
0
#!/usr/bin/env coffee async = require "async" # connect to database require("./db") "mongodb://heroku_lvm2p4zk:27me0oje7us7b97s3pg9s7ooak@ds035703.mongolab.com:35703/heroku_lvm2p4zk", -> Recipe = require "./models/list_model" User = require "./models/user_model" Pick = require "./models/pick_model" query user_id: "55d3b333e2bf182b637341dc" , Recipe, User, Pick query = (opts, Recipe, User, Pick) -> Recipe.find {}, (err, recipes) -> if err # error else # get our user User.findOne _id: opts.user_id, (err, user) -> # make sure we've got user.clicks user.clicks or= [] all = [ require("./one_oldfavs").exec.bind null, user require("./two_similaring").exec.bind null, user, Recipe, recipes require("./three_views").exec.bind null, user ] # using all of these items, lets compile a total score. totals = {} async.map all, (i, cb) -> i cb , (err, all) -> for i in all for k,v of i if k of totals totals[k] += v else totals[k] = v console.log totals # add choices to picks on server Pick.findOne user: user._id, (err, pick) -> if err return console.log err else all = _.compact _.map totals, (v, k) -> if k not in pick.blacklist key: k value: v else null picks.pick = _.object _.pluck(all, 'key'), _.pluck(all, 'value') pick.save (err) -> if err return console.log err else console.log "Wrote picks!" console.log all
83583
#!/usr/bin/env coffee async = require "async" # connect to database require("./db") "mongodb://heroku_lvm2p4zk:<EMAIL>:35703/heroku_lvm2p4zk", -> Recipe = require "./models/list_model" User = require "./models/user_model" Pick = require "./models/pick_model" query user_id: "55d3b333e2bf182b637341dc" , Recipe, User, Pick query = (opts, Recipe, User, Pick) -> Recipe.find {}, (err, recipes) -> if err # error else # get our user User.findOne _id: opts.user_id, (err, user) -> # make sure we've got user.clicks user.clicks or= [] all = [ require("./one_oldfavs").exec.bind null, user require("./two_similaring").exec.bind null, user, Recipe, recipes require("./three_views").exec.bind null, user ] # using all of these items, lets compile a total score. totals = {} async.map all, (i, cb) -> i cb , (err, all) -> for i in all for k,v of i if k of totals totals[k] += v else totals[k] = v console.log totals # add choices to picks on server Pick.findOne user: user._id, (err, pick) -> if err return console.log err else all = _.compact _.map totals, (v, k) -> if k not in pick.blacklist key: k value: v else null picks.pick = _.object _.pluck(all, 'key'), _.pluck(all, 'value') pick.save (err) -> if err return console.log err else console.log "Wrote picks!" console.log all
true
#!/usr/bin/env coffee async = require "async" # connect to database require("./db") "mongodb://heroku_lvm2p4zk:PI:EMAIL:<EMAIL>END_PI:35703/heroku_lvm2p4zk", -> Recipe = require "./models/list_model" User = require "./models/user_model" Pick = require "./models/pick_model" query user_id: "55d3b333e2bf182b637341dc" , Recipe, User, Pick query = (opts, Recipe, User, Pick) -> Recipe.find {}, (err, recipes) -> if err # error else # get our user User.findOne _id: opts.user_id, (err, user) -> # make sure we've got user.clicks user.clicks or= [] all = [ require("./one_oldfavs").exec.bind null, user require("./two_similaring").exec.bind null, user, Recipe, recipes require("./three_views").exec.bind null, user ] # using all of these items, lets compile a total score. totals = {} async.map all, (i, cb) -> i cb , (err, all) -> for i in all for k,v of i if k of totals totals[k] += v else totals[k] = v console.log totals # add choices to picks on server Pick.findOne user: user._id, (err, pick) -> if err return console.log err else all = _.compact _.map totals, (v, k) -> if k not in pick.blacklist key: k value: v else null picks.pick = _.object _.pluck(all, 'key'), _.pluck(all, 'value') pick.save (err) -> if err return console.log err else console.log "Wrote picks!" console.log all
[ { "context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com>\nAll rights reserved.\n\nRedistri", "end": 42, "score": 0.9998394846916199, "start": 24, "tag": "NAME", "value": "Alexander Cherniuk" }, { "context": "###\nCopyright (c) 2013, Alexander Cherniuk <ts33kr@gmai...
library/semantic/formular.coffee
ts33kr/granite
6
### Copyright (c) 2013, Alexander Cherniuk <ts33kr@gmail.com> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### _ = require "lodash" teacup = require "teacup" assert = require "assert" {Widget} = require "./abstract" {Archetype} = require "../nucleus/arche" {remote, cc} = require "../membrane/remote" {GoogleFonts} = require "../shipped/fonting" # This is a user interface widget abstraction that provides protocol # that is used to work with the forms and input controls in general. # Exposes most common functionality of manipulating the input form, # such as downloading and uploading of data and the data validation. # Some of the provided methods can also be used on the server site. # Also, refer to the final implementations of abstraction for info. module.exports.Formular = cc -> class Formular extends Widget # This is a marker that indicates to some internal subsystems # that this class has to be considered abstract and therefore # can not be treated as a complete class implementation. This # mainly is used to exclude or account for abstract classes. # Once inherited from, the inheritee is not abstract anymore. @abstract yes # Bring the tags definitions of the `Teacup` template engine # to the current class scope on the client and server sites. # Remember, that the `teacup` symbol is constantly available # on both sites, respecitvely. Also, take into consideration # that when you need a client-site template in the service, # this is all done automatically and there if no need for it. # Please see the `TemplateToolkit` class for more information. {div} = teacup # This prototype definition is a template-function driven by # the `Teacup` templating engine. When widget instantiated, # this defintion is used to render the root DOM element of # the widget and store it in the widget instance under the # instance variable with the same name of `element`. Please # refer to the `TemplateToolkit` class for an information. # Also, please refer to the `Teacup` manual for reference. element: -> div ".ui.form.segment.formular-widget" # This is a polymorphic, simple yet powerfull validation tool # that is intended to be used primarily on the server site for # the purpose of validating data that came in from a formular. # It is adapted to the formular protocol, attuned to specific # data protocol that is used inside of it. Reference a coding. # It is ambivalent and can be used on client and server sites. @validator: (data) -> (id, check, message) -> assert _.isArray(data), "got invalid data object" assert _.isString(id), "got invalid identification" assert _.isString(message), "got no fail message" object = try _.find data, identity: id.toString() assert _.isPlainObject(object), "no #{id} object" conditions = -> (try object.checked or no) is yes functional = -> try check.call object, object.value expression = -> check.test object.value or String() sequential = -> (object.value or null) in check select = _.isBoolean(check) and not conditions() method = _.isFunction(check) and not functional() regexp = _.isRegExp(check) and not expression() vector = _.isArray(check) and not sequential() failed = method or regexp or select or vector return object.warning = message if failed # This method is part of the formular core protocol. It should # be invoked once a formular is required to reset its state and # all the values, that is making a formular prestine. The method # is implemented within the terms of the upload and the download # pieces of the protocol, as well as within the internal chnages. # Please refer to the implementation for important mechanics. prestine: (cleaners = new Array()) -> cleaners.push (handle) -> handle.error = null cleaners.push (handle) -> handle.value = null cleaners.push (handle) -> handle.warning = null cleaners.push (handle) -> handle.checked = null @errors.empty() if _.isObject @errors or null @warnings.empty() if _.isObject @warnings or 0 @element.removeClass "warning error" # clean up transform = (x) -> _.each cleaners, (f) -> f(x) assert _.isArray downloaded = try this.download() assert fields = @element.find(".field") or Array() _.each downloaded, transform; @upload downloaded sieve = (seq) -> _.filter seq, (value) -> value sieve _.map fields, (value, index, iteratee) => assert _.isObject value = $(value) or null assert not (i = value.find("input")).val() i.after(i.clone(yes).val("")).remove() try value.removeClass "warning error" # This method is intended for rendering error messages attached # to the fields. It traverses all of the fields and see if any # of the fields have warning metadata attached to it. If so, a # warning is added to the list of messages and the field marked # with an error tag, which makes its validity visually distinct. # Please refer to the implementation for important mechanics. messages: (heading, force) -> assert this.element.removeClass "warning error" @warnings.remove() if _.isObject @warnings or null @warnings = $ "<div>", class: "ui warning message" @warnings.prependTo @element # add warn platings @warnings.empty(); list = $ "<ul>", class: "list" h = $("<div>", class: "header").appendTo @warnings h.text heading.toString(); list.appendTo @warnings return this.element.addClass "warning" if force assert fields = @element.find(".field") or [] sieve = (seq) -> _.filter seq, (value) -> value sieve _.map fields, (value, index, iteratee) => assert _.isObject value = $(value) or null warning = value.data("warning") or undefined value.removeClass "error" if value.is ".error" return if not warning? or _.isEmpty warning value.addClass "error"; notice = $ "<li>" notice.appendTo(list).text "#{warning}" @element.addClass "warning"; value # This is a part of the formular protocol. This method allows # you to upload all the fields from a vector of objects, each # of whom describes each field in the formular; its value and # errors or warnings that it may have attached to it. This is # like deserializing the outputed form data from transferable. # Please refer to the implementation for important mechanics. upload: (sequence) -> identify = @constructor.identify().underline assert fields = @element.find(".field") or [] message = "Upload formular %s sequence at %s" logger.debug message, @reference.bold, identify compare = (id) -> (hand) -> hand.identity is id sieve = (seq) -> _.filter seq, (value) -> value sieve _.map fields, (value, index, iteratee) -> assert _.isObject value = $(value) or null input = value?.find("input") or undefined identity = $(value).data("identity") or 0 handle = _.find sequence, compare identity return unless input and input.length is 1 return unless _.isPlainObject handle or 0 return unless _.isString identity or null $(input).attr checked: handle.checked or no $(input).val try handle.value or new String value.data "warning", handle.warning or 0 value.data "error", handle.error; handle # This is a part of the formular protocol. This methods allows # you to download all the fields into a vector of object, each # of whom describes each field in the formular; its value and # errors or warnings that it may have attached to it. This is # like serializing the inputted form data into a transferable. # Please refer to the implementation for important mechanics. download: (reset) -> identify = @constructor.identify().underline assert fields = @element.find(".field") or [] message = "Download formular %s sequence at %s" logger.debug message, @reference.bold, identify sieve = (seq) -> _.filter seq, (value) -> value sieve _.map fields, (value, index, iteratee) -> assert _.isObject value = $(value) or null input = value?.find("input") or undefined identity = $(value).data("identity") or 0 return unless input and input.length is 1 return unless _.isString identity or null assert _.isPlainObject handle = new Object handle.identity = try identity.toString() handle.value = $(input).val() or undefined handle.checked = try $(input).is ":checked" value.data warning: 0, error: null if reset do -> handle.warning = value.data "warning" handle.error = value.data "error"; handle
115688
### Copyright (c) 2013, <NAME> <<EMAIL>> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### _ = require "lodash" teacup = require "teacup" assert = require "assert" {Widget} = require "./abstract" {Archetype} = require "../nucleus/arche" {remote, cc} = require "../membrane/remote" {GoogleFonts} = require "../shipped/fonting" # This is a user interface widget abstraction that provides protocol # that is used to work with the forms and input controls in general. # Exposes most common functionality of manipulating the input form, # such as downloading and uploading of data and the data validation. # Some of the provided methods can also be used on the server site. # Also, refer to the final implementations of abstraction for info. module.exports.Formular = cc -> class Formular extends Widget # This is a marker that indicates to some internal subsystems # that this class has to be considered abstract and therefore # can not be treated as a complete class implementation. This # mainly is used to exclude or account for abstract classes. # Once inherited from, the inheritee is not abstract anymore. @abstract yes # Bring the tags definitions of the `Teacup` template engine # to the current class scope on the client and server sites. # Remember, that the `teacup` symbol is constantly available # on both sites, respecitvely. Also, take into consideration # that when you need a client-site template in the service, # this is all done automatically and there if no need for it. # Please see the `TemplateToolkit` class for more information. {div} = teacup # This prototype definition is a template-function driven by # the `Teacup` templating engine. When widget instantiated, # this defintion is used to render the root DOM element of # the widget and store it in the widget instance under the # instance variable with the same name of `element`. Please # refer to the `TemplateToolkit` class for an information. # Also, please refer to the `Teacup` manual for reference. element: -> div ".ui.form.segment.formular-widget" # This is a polymorphic, simple yet powerfull validation tool # that is intended to be used primarily on the server site for # the purpose of validating data that came in from a formular. # It is adapted to the formular protocol, attuned to specific # data protocol that is used inside of it. Reference a coding. # It is ambivalent and can be used on client and server sites. @validator: (data) -> (id, check, message) -> assert _.isArray(data), "got invalid data object" assert _.isString(id), "got invalid identification" assert _.isString(message), "got no fail message" object = try _.find data, identity: id.toString() assert _.isPlainObject(object), "no #{id} object" conditions = -> (try object.checked or no) is yes functional = -> try check.call object, object.value expression = -> check.test object.value or String() sequential = -> (object.value or null) in check select = _.isBoolean(check) and not conditions() method = _.isFunction(check) and not functional() regexp = _.isRegExp(check) and not expression() vector = _.isArray(check) and not sequential() failed = method or regexp or select or vector return object.warning = message if failed # This method is part of the formular core protocol. It should # be invoked once a formular is required to reset its state and # all the values, that is making a formular prestine. The method # is implemented within the terms of the upload and the download # pieces of the protocol, as well as within the internal chnages. # Please refer to the implementation for important mechanics. prestine: (cleaners = new Array()) -> cleaners.push (handle) -> handle.error = null cleaners.push (handle) -> handle.value = null cleaners.push (handle) -> handle.warning = null cleaners.push (handle) -> handle.checked = null @errors.empty() if _.isObject @errors or null @warnings.empty() if _.isObject @warnings or 0 @element.removeClass "warning error" # clean up transform = (x) -> _.each cleaners, (f) -> f(x) assert _.isArray downloaded = try this.download() assert fields = @element.find(".field") or Array() _.each downloaded, transform; @upload downloaded sieve = (seq) -> _.filter seq, (value) -> value sieve _.map fields, (value, index, iteratee) => assert _.isObject value = $(value) or null assert not (i = value.find("input")).val() i.after(i.clone(yes).val("")).remove() try value.removeClass "warning error" # This method is intended for rendering error messages attached # to the fields. It traverses all of the fields and see if any # of the fields have warning metadata attached to it. If so, a # warning is added to the list of messages and the field marked # with an error tag, which makes its validity visually distinct. # Please refer to the implementation for important mechanics. messages: (heading, force) -> assert this.element.removeClass "warning error" @warnings.remove() if _.isObject @warnings or null @warnings = $ "<div>", class: "ui warning message" @warnings.prependTo @element # add warn platings @warnings.empty(); list = $ "<ul>", class: "list" h = $("<div>", class: "header").appendTo @warnings h.text heading.toString(); list.appendTo @warnings return this.element.addClass "warning" if force assert fields = @element.find(".field") or [] sieve = (seq) -> _.filter seq, (value) -> value sieve _.map fields, (value, index, iteratee) => assert _.isObject value = $(value) or null warning = value.data("warning") or undefined value.removeClass "error" if value.is ".error" return if not warning? or _.isEmpty warning value.addClass "error"; notice = $ "<li>" notice.appendTo(list).text "#{warning}" @element.addClass "warning"; value # This is a part of the formular protocol. This method allows # you to upload all the fields from a vector of objects, each # of whom describes each field in the formular; its value and # errors or warnings that it may have attached to it. This is # like deserializing the outputed form data from transferable. # Please refer to the implementation for important mechanics. upload: (sequence) -> identify = @constructor.identify().underline assert fields = @element.find(".field") or [] message = "Upload formular %s sequence at %s" logger.debug message, @reference.bold, identify compare = (id) -> (hand) -> hand.identity is id sieve = (seq) -> _.filter seq, (value) -> value sieve _.map fields, (value, index, iteratee) -> assert _.isObject value = $(value) or null input = value?.find("input") or undefined identity = $(value).data("identity") or 0 handle = _.find sequence, compare identity return unless input and input.length is 1 return unless _.isPlainObject handle or 0 return unless _.isString identity or null $(input).attr checked: handle.checked or no $(input).val try handle.value or new String value.data "warning", handle.warning or 0 value.data "error", handle.error; handle # This is a part of the formular protocol. This methods allows # you to download all the fields into a vector of object, each # of whom describes each field in the formular; its value and # errors or warnings that it may have attached to it. This is # like serializing the inputted form data into a transferable. # Please refer to the implementation for important mechanics. download: (reset) -> identify = @constructor.identify().underline assert fields = @element.find(".field") or [] message = "Download formular %s sequence at %s" logger.debug message, @reference.bold, identify sieve = (seq) -> _.filter seq, (value) -> value sieve _.map fields, (value, index, iteratee) -> assert _.isObject value = $(value) or null input = value?.find("input") or undefined identity = $(value).data("identity") or 0 return unless input and input.length is 1 return unless _.isString identity or null assert _.isPlainObject handle = new Object handle.identity = try identity.toString() handle.value = $(input).val() or undefined handle.checked = try $(input).is ":checked" value.data warning: 0, error: null if reset do -> handle.warning = value.data "warning" handle.error = value.data "error"; handle
true
### Copyright (c) 2013, PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ### _ = require "lodash" teacup = require "teacup" assert = require "assert" {Widget} = require "./abstract" {Archetype} = require "../nucleus/arche" {remote, cc} = require "../membrane/remote" {GoogleFonts} = require "../shipped/fonting" # This is a user interface widget abstraction that provides protocol # that is used to work with the forms and input controls in general. # Exposes most common functionality of manipulating the input form, # such as downloading and uploading of data and the data validation. # Some of the provided methods can also be used on the server site. # Also, refer to the final implementations of abstraction for info. module.exports.Formular = cc -> class Formular extends Widget # This is a marker that indicates to some internal subsystems # that this class has to be considered abstract and therefore # can not be treated as a complete class implementation. This # mainly is used to exclude or account for abstract classes. # Once inherited from, the inheritee is not abstract anymore. @abstract yes # Bring the tags definitions of the `Teacup` template engine # to the current class scope on the client and server sites. # Remember, that the `teacup` symbol is constantly available # on both sites, respecitvely. Also, take into consideration # that when you need a client-site template in the service, # this is all done automatically and there if no need for it. # Please see the `TemplateToolkit` class for more information. {div} = teacup # This prototype definition is a template-function driven by # the `Teacup` templating engine. When widget instantiated, # this defintion is used to render the root DOM element of # the widget and store it in the widget instance under the # instance variable with the same name of `element`. Please # refer to the `TemplateToolkit` class for an information. # Also, please refer to the `Teacup` manual for reference. element: -> div ".ui.form.segment.formular-widget" # This is a polymorphic, simple yet powerfull validation tool # that is intended to be used primarily on the server site for # the purpose of validating data that came in from a formular. # It is adapted to the formular protocol, attuned to specific # data protocol that is used inside of it. Reference a coding. # It is ambivalent and can be used on client and server sites. @validator: (data) -> (id, check, message) -> assert _.isArray(data), "got invalid data object" assert _.isString(id), "got invalid identification" assert _.isString(message), "got no fail message" object = try _.find data, identity: id.toString() assert _.isPlainObject(object), "no #{id} object" conditions = -> (try object.checked or no) is yes functional = -> try check.call object, object.value expression = -> check.test object.value or String() sequential = -> (object.value or null) in check select = _.isBoolean(check) and not conditions() method = _.isFunction(check) and not functional() regexp = _.isRegExp(check) and not expression() vector = _.isArray(check) and not sequential() failed = method or regexp or select or vector return object.warning = message if failed # This method is part of the formular core protocol. It should # be invoked once a formular is required to reset its state and # all the values, that is making a formular prestine. The method # is implemented within the terms of the upload and the download # pieces of the protocol, as well as within the internal chnages. # Please refer to the implementation for important mechanics. prestine: (cleaners = new Array()) -> cleaners.push (handle) -> handle.error = null cleaners.push (handle) -> handle.value = null cleaners.push (handle) -> handle.warning = null cleaners.push (handle) -> handle.checked = null @errors.empty() if _.isObject @errors or null @warnings.empty() if _.isObject @warnings or 0 @element.removeClass "warning error" # clean up transform = (x) -> _.each cleaners, (f) -> f(x) assert _.isArray downloaded = try this.download() assert fields = @element.find(".field") or Array() _.each downloaded, transform; @upload downloaded sieve = (seq) -> _.filter seq, (value) -> value sieve _.map fields, (value, index, iteratee) => assert _.isObject value = $(value) or null assert not (i = value.find("input")).val() i.after(i.clone(yes).val("")).remove() try value.removeClass "warning error" # This method is intended for rendering error messages attached # to the fields. It traverses all of the fields and see if any # of the fields have warning metadata attached to it. If so, a # warning is added to the list of messages and the field marked # with an error tag, which makes its validity visually distinct. # Please refer to the implementation for important mechanics. messages: (heading, force) -> assert this.element.removeClass "warning error" @warnings.remove() if _.isObject @warnings or null @warnings = $ "<div>", class: "ui warning message" @warnings.prependTo @element # add warn platings @warnings.empty(); list = $ "<ul>", class: "list" h = $("<div>", class: "header").appendTo @warnings h.text heading.toString(); list.appendTo @warnings return this.element.addClass "warning" if force assert fields = @element.find(".field") or [] sieve = (seq) -> _.filter seq, (value) -> value sieve _.map fields, (value, index, iteratee) => assert _.isObject value = $(value) or null warning = value.data("warning") or undefined value.removeClass "error" if value.is ".error" return if not warning? or _.isEmpty warning value.addClass "error"; notice = $ "<li>" notice.appendTo(list).text "#{warning}" @element.addClass "warning"; value # This is a part of the formular protocol. This method allows # you to upload all the fields from a vector of objects, each # of whom describes each field in the formular; its value and # errors or warnings that it may have attached to it. This is # like deserializing the outputed form data from transferable. # Please refer to the implementation for important mechanics. upload: (sequence) -> identify = @constructor.identify().underline assert fields = @element.find(".field") or [] message = "Upload formular %s sequence at %s" logger.debug message, @reference.bold, identify compare = (id) -> (hand) -> hand.identity is id sieve = (seq) -> _.filter seq, (value) -> value sieve _.map fields, (value, index, iteratee) -> assert _.isObject value = $(value) or null input = value?.find("input") or undefined identity = $(value).data("identity") or 0 handle = _.find sequence, compare identity return unless input and input.length is 1 return unless _.isPlainObject handle or 0 return unless _.isString identity or null $(input).attr checked: handle.checked or no $(input).val try handle.value or new String value.data "warning", handle.warning or 0 value.data "error", handle.error; handle # This is a part of the formular protocol. This methods allows # you to download all the fields into a vector of object, each # of whom describes each field in the formular; its value and # errors or warnings that it may have attached to it. This is # like serializing the inputted form data into a transferable. # Please refer to the implementation for important mechanics. download: (reset) -> identify = @constructor.identify().underline assert fields = @element.find(".field") or [] message = "Download formular %s sequence at %s" logger.debug message, @reference.bold, identify sieve = (seq) -> _.filter seq, (value) -> value sieve _.map fields, (value, index, iteratee) -> assert _.isObject value = $(value) or null input = value?.find("input") or undefined identity = $(value).data("identity") or 0 return unless input and input.length is 1 return unless _.isString identity or null assert _.isPlainObject handle = new Object handle.identity = try identity.toString() handle.value = $(input).val() or undefined handle.checked = try $(input).is ":checked" value.data warning: 0, error: null if reset do -> handle.warning = value.data "warning" handle.error = value.data "error"; handle
[ { "context": "e Now API Username\n# HUBOT_SERVICE_NOW_PASSWORD: Service Now API Password\n\n\nmodule.exports = (robot) ->\n sn_domain = proce", "end": 592, "score": 0.9785292744636536, "start": 568, "tag": "PASSWORD", "value": "Service Now API Password" } ]
src/hubot-service-now.coffee
colorstheforce/hubot-service-now
5
# Description: # Service Now Record lookup # # Commands: # hubot <sn|snapi|service now> <record number> - Look up record number in Service Now # hubot <sn|snapi|service now> listen - Toggle Implicit/Explicit listening for Service Now records # # Configuration: # HUBOT_SERVICE_NOW_INSTANCE: Service Now instance (e.g. 'devtest' of devtest.service-now.com) # HUBOT_SERVICE_NOW_DOMAIN: Override FQDN for service now instance # useful if you need to use an internal proxy # HUBOT_SERVICE_NOW_USER: Service Now API Username # HUBOT_SERVICE_NOW_PASSWORD: Service Now API Password module.exports = (robot) -> sn_domain = process.env.HUBOT_SERVICE_NOW_DOMAIN sn_instance = process.env.HUBOT_SERVICE_NOW_INSTANCE if sn_domain? and sn_instance? robot.logger.error "HUBOT_SERVICE_NOW_DOMAIN and " + "HUBOT_SERVICE_NOW_INSTANCE can't be set at the same time. Use one or the other" else if sn_domain? sn_fqdn = "https://#{sn_domain}" else if sn_instance? sn_fqdn = "https://#{sn_instance}.service-now.com" robot.logger.debug("sn_fqdn: #{sn_fqdn}") ### The bit that does the work to ask Service Now for stuff is registered as an event so that you can consume this in other scripts if you'd like. The expected format of the 'request' object is as follows: request = table, rec_number, fields, user table and rec_number should be strings fields should be an object of keys/values, where the key is the record field and the value is the human-readable description The user object should be a room or user that the script should return the results to ### robot.on "sn_record_get", (request) -> query_fields = Object.keys(request.fields) # inject sys_id to query_fields for use later query_fields.push 'sys_id' api_url = "#{sn_fqdn}/api/now/v2/table/#{request.table}" req_args = "sysparm_query=number=#{request.rec_number}&" + "sysparm_display_value=true&sysparm_limit=1&sysparm_fields=#{query_fields}" sn_url = "#{api_url}?#{req_args}" robot.logger.debug "SN URL: #{sn_url}" sn_user = process.env.HUBOT_SERVICE_NOW_USER sn_pass = process.env.HUBOT_SERVICE_NOW_PASSWORD unless sn_user? and sn_pass? robot.logger.error "HUBOT_SERVICE_NOW_USER and HUBOT_SERVICE_NOW_PASSWORD " + "Must be defined!" robot.send request.user, "Integration user name and password are not " + "defined. I can't look up Service Now Requests without them" robot.http(sn_url) .header('Accept', 'application/json') .auth(process.env.HUBOT_SERVICE_NOW_USER, process.env.HUBOT_SERVICE_NOW_PASSWORD) .get() (err, res, body) -> if (err?) robot.send request.user, err robot.send request.user, "Error was encountered while looking for " + "`#{request.rec_number}`" robot.logger.error "Received error #{err} when looking for " + "`#{request.rec_number}`" return robot.logger.debug("Received body from Service Now: #{body}") data = JSON.parse body result = data['result'] unless result? robot.send request.user, "Error was encountered while looking for " + "`#{request.rec_number}`" robot.logger.error "Received error '#{data.error.message}' while " + "looking for '#{request.rec_number}'" return if (result.length < 1) robot.send request.user, "Service Now returned 0 records for " + "'#{request.rec_number}'" else rec_count = res.headers['X-Total-Count'] if (rec_count > 1) robot.send request.user, "Service Now returned #{rec_count} " + "records. Showing the first" sn_single_result_fmt(request.user, request.fields, request.rec_number, result[0]) sn_single_result_fmt = (user, fields, rec_number, result) -> # if we have a sys_id field in the results, use it to generate a URL to the record if 'sys_id' in Object.keys(result) # get record type from rec_number and look up service now table rec_type = rec_number.match(/([A-z]{3,6})([0-9]{7,})/)[1] sn_table = table_lookup[rec_type]['table'] # construct URL to record sn_url = "#{sn_fqdn}/nav_to.do?uri=/#{sn_table}.do?sys_id=#{result['sys_id']}" # create hyperlink output = "Found *<#{sn_url}|#{rec_number}>:*" else output = "Found *#{rec_number}:*" for k, v of fields robot.logger.debug "Getting #{k} from result" output += "\n*#{v}:* #{result[k]}" robot.send user, output return robot.respond /(?:sn(?:ow)?|service now) ([A-z]{3,6})([0-9]{7,})/i, (res) -> rec_type = res.match[1] rec_num = res.match[2] if table_lookup[rec_type]? robot.logger.debug "Record: #{rec_type}#{rec_num}" robot.logger.debug "user: #{res.message.user.name}" robot.logger.debug "table: #{table_lookup[rec_type]['table']}" robot.emit "sn_record_get", { user: res.message.user, table: table_lookup[rec_type]['table'], fields: table_lookup[rec_type]['fields'] rec_number: "#{rec_type}#{rec_num}" } else robot.logger.debug "No table_lookup entry for #{rec_type} records" res.send "I don't know how to look up #{rec_type} records" robot.respond /(?:sn(?:ow)?|service now) listen/i, (res) -> channel_id = res.message.room listen_brain = robot.brain.get("sn_api.#{channel_id}.listen") # handle scenario when variable is null if listen_brain? listen_toggle = !listen_brain else listen_toggle = true # persist the toggle state in the "brain" robot.brain.set "sn_api.#{channel_id}.listen", listen_toggle # generate a human-friendly string to describe the current state if listen_toggle listen_friendly = "will" else listen_friendly = "won't" res.send "I #{listen_friendly} listen for Service Now" # the record types we know about, and their table names table_lookup = { PRB: { table: 'problem', fields: { 'short_description': 'Short Description', 'assigned_to.name': 'Assigned to', 'opened_by.name': 'Opened by', 'opened_at': 'Opened at', 'priority': 'Priority' 'state': 'State' } } INC: { table: 'incident', fields: { 'short_description': 'Short Description', 'assigned_to.name': 'Assigned to', 'opened_by.name': 'Opened by', 'opened_at': 'Opened at', 'priority': 'Priority' 'state': 'State' } } CHG: { table: 'change_request' fields: { 'short_description': 'Short Description', 'cmdb_ci.name': 'CMDB CI', 'assignment_group.name': 'Assignment group', 'requested_by.name': 'Requested by', 'start_date': 'Start Date', 'end_date': 'End Date', 'state': 'State' } } CTASK: { table: 'change_task' fields: { 'short_description': 'Short Description', 'change_request.number': 'Change Request', 'cmdb_ci.name': 'CMDB CI', 'assignment_group.name': 'Assignment group', 'opened_by.name': 'Opened by', 'opened_at': 'Opened at' 'state': 'State' } } RITM: { table: 'sc_req_item' fields: { 'short_description': 'Short Description', 'assignment_group.name': 'Assignment group', 'opened_by.name': 'Opened by', 'opened_at': 'Opened At' 'state': 'State' } } SCTASK: { table: 'sc_task' fields: { 'short_description': 'Short Description', 'request.number': 'Request', 'request_item.number': 'Request Item', 'request.requested_for.name': 'Requested For', 'assignment_group.name': 'Assignment Group', 'state': 'State' } } STRY: { table: 'rm_story' fields: { 'short_description': 'Short Description', 'epic.short_description': 'Epic', 'opened_by.name': 'Opened by', 'product.name': 'Product', 'state': 'State' } } STSK: { table: 'rm_scrum_task' fields: { 'short_description': 'Short Description' 'opened_by.name': 'Opened by', 'state': 'State', 'story.number': 'Story Number', 'story.short_description': 'Story Description' } } } # this works similar to the robot.respond message above, # but it looks only for the record types we know about # also, we need to be careful to avoid interaction with the normal # robot.respond messages, and we also don't want to create a feedback loop # between bots robot.hear ///(#{Object.keys(table_lookup).join('|')})([0-9]{7,})///i, (res) -> name_mention = "@#{robot.name}" start_with_mention = res.message.text.startsWith name_mention start_with_name = res.message.text.startsWith robot.name # don't do anything if bot was @ mentioned if start_with_mention or start_with_name robot.logger.debug "robot.hear ignoring explicit Service Now request " + "and allowing robot.respond to handle it" return # don't do anything if listen is false unless robot.brain.get("sn_api.#{res.message.room}.listen") robot.logger.debug "Ignoring Service Now request; sn listen is off" return # ignore messages from bots if res.message.user.is_bot or res.message.user.slack?.is_bot robot.logger.debug "Ignoring Service Now mention by bot" return rec_type = res.match[1] rec_num = res.match[2] robot.logger.debug "Record: #{rec_type}#{rec_num}" robot.logger.debug "user: #{res.message.user.name}" robot.logger.debug "table: #{table_lookup[rec_type]['table']}" robot.emit "sn_record_get", { user: res.message.user, table: table_lookup[rec_type]['table'], fields: table_lookup[rec_type]['fields'] rec_number: "#{rec_type}#{rec_num}" }
83775
# Description: # Service Now Record lookup # # Commands: # hubot <sn|snapi|service now> <record number> - Look up record number in Service Now # hubot <sn|snapi|service now> listen - Toggle Implicit/Explicit listening for Service Now records # # Configuration: # HUBOT_SERVICE_NOW_INSTANCE: Service Now instance (e.g. 'devtest' of devtest.service-now.com) # HUBOT_SERVICE_NOW_DOMAIN: Override FQDN for service now instance # useful if you need to use an internal proxy # HUBOT_SERVICE_NOW_USER: Service Now API Username # HUBOT_SERVICE_NOW_PASSWORD: <PASSWORD> module.exports = (robot) -> sn_domain = process.env.HUBOT_SERVICE_NOW_DOMAIN sn_instance = process.env.HUBOT_SERVICE_NOW_INSTANCE if sn_domain? and sn_instance? robot.logger.error "HUBOT_SERVICE_NOW_DOMAIN and " + "HUBOT_SERVICE_NOW_INSTANCE can't be set at the same time. Use one or the other" else if sn_domain? sn_fqdn = "https://#{sn_domain}" else if sn_instance? sn_fqdn = "https://#{sn_instance}.service-now.com" robot.logger.debug("sn_fqdn: #{sn_fqdn}") ### The bit that does the work to ask Service Now for stuff is registered as an event so that you can consume this in other scripts if you'd like. The expected format of the 'request' object is as follows: request = table, rec_number, fields, user table and rec_number should be strings fields should be an object of keys/values, where the key is the record field and the value is the human-readable description The user object should be a room or user that the script should return the results to ### robot.on "sn_record_get", (request) -> query_fields = Object.keys(request.fields) # inject sys_id to query_fields for use later query_fields.push 'sys_id' api_url = "#{sn_fqdn}/api/now/v2/table/#{request.table}" req_args = "sysparm_query=number=#{request.rec_number}&" + "sysparm_display_value=true&sysparm_limit=1&sysparm_fields=#{query_fields}" sn_url = "#{api_url}?#{req_args}" robot.logger.debug "SN URL: #{sn_url}" sn_user = process.env.HUBOT_SERVICE_NOW_USER sn_pass = process.env.HUBOT_SERVICE_NOW_PASSWORD unless sn_user? and sn_pass? robot.logger.error "HUBOT_SERVICE_NOW_USER and HUBOT_SERVICE_NOW_PASSWORD " + "Must be defined!" robot.send request.user, "Integration user name and password are not " + "defined. I can't look up Service Now Requests without them" robot.http(sn_url) .header('Accept', 'application/json') .auth(process.env.HUBOT_SERVICE_NOW_USER, process.env.HUBOT_SERVICE_NOW_PASSWORD) .get() (err, res, body) -> if (err?) robot.send request.user, err robot.send request.user, "Error was encountered while looking for " + "`#{request.rec_number}`" robot.logger.error "Received error #{err} when looking for " + "`#{request.rec_number}`" return robot.logger.debug("Received body from Service Now: #{body}") data = JSON.parse body result = data['result'] unless result? robot.send request.user, "Error was encountered while looking for " + "`#{request.rec_number}`" robot.logger.error "Received error '#{data.error.message}' while " + "looking for '#{request.rec_number}'" return if (result.length < 1) robot.send request.user, "Service Now returned 0 records for " + "'#{request.rec_number}'" else rec_count = res.headers['X-Total-Count'] if (rec_count > 1) robot.send request.user, "Service Now returned #{rec_count} " + "records. Showing the first" sn_single_result_fmt(request.user, request.fields, request.rec_number, result[0]) sn_single_result_fmt = (user, fields, rec_number, result) -> # if we have a sys_id field in the results, use it to generate a URL to the record if 'sys_id' in Object.keys(result) # get record type from rec_number and look up service now table rec_type = rec_number.match(/([A-z]{3,6})([0-9]{7,})/)[1] sn_table = table_lookup[rec_type]['table'] # construct URL to record sn_url = "#{sn_fqdn}/nav_to.do?uri=/#{sn_table}.do?sys_id=#{result['sys_id']}" # create hyperlink output = "Found *<#{sn_url}|#{rec_number}>:*" else output = "Found *#{rec_number}:*" for k, v of fields robot.logger.debug "Getting #{k} from result" output += "\n*#{v}:* #{result[k]}" robot.send user, output return robot.respond /(?:sn(?:ow)?|service now) ([A-z]{3,6})([0-9]{7,})/i, (res) -> rec_type = res.match[1] rec_num = res.match[2] if table_lookup[rec_type]? robot.logger.debug "Record: #{rec_type}#{rec_num}" robot.logger.debug "user: #{res.message.user.name}" robot.logger.debug "table: #{table_lookup[rec_type]['table']}" robot.emit "sn_record_get", { user: res.message.user, table: table_lookup[rec_type]['table'], fields: table_lookup[rec_type]['fields'] rec_number: "#{rec_type}#{rec_num}" } else robot.logger.debug "No table_lookup entry for #{rec_type} records" res.send "I don't know how to look up #{rec_type} records" robot.respond /(?:sn(?:ow)?|service now) listen/i, (res) -> channel_id = res.message.room listen_brain = robot.brain.get("sn_api.#{channel_id}.listen") # handle scenario when variable is null if listen_brain? listen_toggle = !listen_brain else listen_toggle = true # persist the toggle state in the "brain" robot.brain.set "sn_api.#{channel_id}.listen", listen_toggle # generate a human-friendly string to describe the current state if listen_toggle listen_friendly = "will" else listen_friendly = "won't" res.send "I #{listen_friendly} listen for Service Now" # the record types we know about, and their table names table_lookup = { PRB: { table: 'problem', fields: { 'short_description': 'Short Description', 'assigned_to.name': 'Assigned to', 'opened_by.name': 'Opened by', 'opened_at': 'Opened at', 'priority': 'Priority' 'state': 'State' } } INC: { table: 'incident', fields: { 'short_description': 'Short Description', 'assigned_to.name': 'Assigned to', 'opened_by.name': 'Opened by', 'opened_at': 'Opened at', 'priority': 'Priority' 'state': 'State' } } CHG: { table: 'change_request' fields: { 'short_description': 'Short Description', 'cmdb_ci.name': 'CMDB CI', 'assignment_group.name': 'Assignment group', 'requested_by.name': 'Requested by', 'start_date': 'Start Date', 'end_date': 'End Date', 'state': 'State' } } CTASK: { table: 'change_task' fields: { 'short_description': 'Short Description', 'change_request.number': 'Change Request', 'cmdb_ci.name': 'CMDB CI', 'assignment_group.name': 'Assignment group', 'opened_by.name': 'Opened by', 'opened_at': 'Opened at' 'state': 'State' } } RITM: { table: 'sc_req_item' fields: { 'short_description': 'Short Description', 'assignment_group.name': 'Assignment group', 'opened_by.name': 'Opened by', 'opened_at': 'Opened At' 'state': 'State' } } SCTASK: { table: 'sc_task' fields: { 'short_description': 'Short Description', 'request.number': 'Request', 'request_item.number': 'Request Item', 'request.requested_for.name': 'Requested For', 'assignment_group.name': 'Assignment Group', 'state': 'State' } } STRY: { table: 'rm_story' fields: { 'short_description': 'Short Description', 'epic.short_description': 'Epic', 'opened_by.name': 'Opened by', 'product.name': 'Product', 'state': 'State' } } STSK: { table: 'rm_scrum_task' fields: { 'short_description': 'Short Description' 'opened_by.name': 'Opened by', 'state': 'State', 'story.number': 'Story Number', 'story.short_description': 'Story Description' } } } # this works similar to the robot.respond message above, # but it looks only for the record types we know about # also, we need to be careful to avoid interaction with the normal # robot.respond messages, and we also don't want to create a feedback loop # between bots robot.hear ///(#{Object.keys(table_lookup).join('|')})([0-9]{7,})///i, (res) -> name_mention = "@#{robot.name}" start_with_mention = res.message.text.startsWith name_mention start_with_name = res.message.text.startsWith robot.name # don't do anything if bot was @ mentioned if start_with_mention or start_with_name robot.logger.debug "robot.hear ignoring explicit Service Now request " + "and allowing robot.respond to handle it" return # don't do anything if listen is false unless robot.brain.get("sn_api.#{res.message.room}.listen") robot.logger.debug "Ignoring Service Now request; sn listen is off" return # ignore messages from bots if res.message.user.is_bot or res.message.user.slack?.is_bot robot.logger.debug "Ignoring Service Now mention by bot" return rec_type = res.match[1] rec_num = res.match[2] robot.logger.debug "Record: #{rec_type}#{rec_num}" robot.logger.debug "user: #{res.message.user.name}" robot.logger.debug "table: #{table_lookup[rec_type]['table']}" robot.emit "sn_record_get", { user: res.message.user, table: table_lookup[rec_type]['table'], fields: table_lookup[rec_type]['fields'] rec_number: "#{rec_type}#{rec_num}" }
true
# Description: # Service Now Record lookup # # Commands: # hubot <sn|snapi|service now> <record number> - Look up record number in Service Now # hubot <sn|snapi|service now> listen - Toggle Implicit/Explicit listening for Service Now records # # Configuration: # HUBOT_SERVICE_NOW_INSTANCE: Service Now instance (e.g. 'devtest' of devtest.service-now.com) # HUBOT_SERVICE_NOW_DOMAIN: Override FQDN for service now instance # useful if you need to use an internal proxy # HUBOT_SERVICE_NOW_USER: Service Now API Username # HUBOT_SERVICE_NOW_PASSWORD: PI:PASSWORD:<PASSWORD>END_PI module.exports = (robot) -> sn_domain = process.env.HUBOT_SERVICE_NOW_DOMAIN sn_instance = process.env.HUBOT_SERVICE_NOW_INSTANCE if sn_domain? and sn_instance? robot.logger.error "HUBOT_SERVICE_NOW_DOMAIN and " + "HUBOT_SERVICE_NOW_INSTANCE can't be set at the same time. Use one or the other" else if sn_domain? sn_fqdn = "https://#{sn_domain}" else if sn_instance? sn_fqdn = "https://#{sn_instance}.service-now.com" robot.logger.debug("sn_fqdn: #{sn_fqdn}") ### The bit that does the work to ask Service Now for stuff is registered as an event so that you can consume this in other scripts if you'd like. The expected format of the 'request' object is as follows: request = table, rec_number, fields, user table and rec_number should be strings fields should be an object of keys/values, where the key is the record field and the value is the human-readable description The user object should be a room or user that the script should return the results to ### robot.on "sn_record_get", (request) -> query_fields = Object.keys(request.fields) # inject sys_id to query_fields for use later query_fields.push 'sys_id' api_url = "#{sn_fqdn}/api/now/v2/table/#{request.table}" req_args = "sysparm_query=number=#{request.rec_number}&" + "sysparm_display_value=true&sysparm_limit=1&sysparm_fields=#{query_fields}" sn_url = "#{api_url}?#{req_args}" robot.logger.debug "SN URL: #{sn_url}" sn_user = process.env.HUBOT_SERVICE_NOW_USER sn_pass = process.env.HUBOT_SERVICE_NOW_PASSWORD unless sn_user? and sn_pass? robot.logger.error "HUBOT_SERVICE_NOW_USER and HUBOT_SERVICE_NOW_PASSWORD " + "Must be defined!" robot.send request.user, "Integration user name and password are not " + "defined. I can't look up Service Now Requests without them" robot.http(sn_url) .header('Accept', 'application/json') .auth(process.env.HUBOT_SERVICE_NOW_USER, process.env.HUBOT_SERVICE_NOW_PASSWORD) .get() (err, res, body) -> if (err?) robot.send request.user, err robot.send request.user, "Error was encountered while looking for " + "`#{request.rec_number}`" robot.logger.error "Received error #{err} when looking for " + "`#{request.rec_number}`" return robot.logger.debug("Received body from Service Now: #{body}") data = JSON.parse body result = data['result'] unless result? robot.send request.user, "Error was encountered while looking for " + "`#{request.rec_number}`" robot.logger.error "Received error '#{data.error.message}' while " + "looking for '#{request.rec_number}'" return if (result.length < 1) robot.send request.user, "Service Now returned 0 records for " + "'#{request.rec_number}'" else rec_count = res.headers['X-Total-Count'] if (rec_count > 1) robot.send request.user, "Service Now returned #{rec_count} " + "records. Showing the first" sn_single_result_fmt(request.user, request.fields, request.rec_number, result[0]) sn_single_result_fmt = (user, fields, rec_number, result) -> # if we have a sys_id field in the results, use it to generate a URL to the record if 'sys_id' in Object.keys(result) # get record type from rec_number and look up service now table rec_type = rec_number.match(/([A-z]{3,6})([0-9]{7,})/)[1] sn_table = table_lookup[rec_type]['table'] # construct URL to record sn_url = "#{sn_fqdn}/nav_to.do?uri=/#{sn_table}.do?sys_id=#{result['sys_id']}" # create hyperlink output = "Found *<#{sn_url}|#{rec_number}>:*" else output = "Found *#{rec_number}:*" for k, v of fields robot.logger.debug "Getting #{k} from result" output += "\n*#{v}:* #{result[k]}" robot.send user, output return robot.respond /(?:sn(?:ow)?|service now) ([A-z]{3,6})([0-9]{7,})/i, (res) -> rec_type = res.match[1] rec_num = res.match[2] if table_lookup[rec_type]? robot.logger.debug "Record: #{rec_type}#{rec_num}" robot.logger.debug "user: #{res.message.user.name}" robot.logger.debug "table: #{table_lookup[rec_type]['table']}" robot.emit "sn_record_get", { user: res.message.user, table: table_lookup[rec_type]['table'], fields: table_lookup[rec_type]['fields'] rec_number: "#{rec_type}#{rec_num}" } else robot.logger.debug "No table_lookup entry for #{rec_type} records" res.send "I don't know how to look up #{rec_type} records" robot.respond /(?:sn(?:ow)?|service now) listen/i, (res) -> channel_id = res.message.room listen_brain = robot.brain.get("sn_api.#{channel_id}.listen") # handle scenario when variable is null if listen_brain? listen_toggle = !listen_brain else listen_toggle = true # persist the toggle state in the "brain" robot.brain.set "sn_api.#{channel_id}.listen", listen_toggle # generate a human-friendly string to describe the current state if listen_toggle listen_friendly = "will" else listen_friendly = "won't" res.send "I #{listen_friendly} listen for Service Now" # the record types we know about, and their table names table_lookup = { PRB: { table: 'problem', fields: { 'short_description': 'Short Description', 'assigned_to.name': 'Assigned to', 'opened_by.name': 'Opened by', 'opened_at': 'Opened at', 'priority': 'Priority' 'state': 'State' } } INC: { table: 'incident', fields: { 'short_description': 'Short Description', 'assigned_to.name': 'Assigned to', 'opened_by.name': 'Opened by', 'opened_at': 'Opened at', 'priority': 'Priority' 'state': 'State' } } CHG: { table: 'change_request' fields: { 'short_description': 'Short Description', 'cmdb_ci.name': 'CMDB CI', 'assignment_group.name': 'Assignment group', 'requested_by.name': 'Requested by', 'start_date': 'Start Date', 'end_date': 'End Date', 'state': 'State' } } CTASK: { table: 'change_task' fields: { 'short_description': 'Short Description', 'change_request.number': 'Change Request', 'cmdb_ci.name': 'CMDB CI', 'assignment_group.name': 'Assignment group', 'opened_by.name': 'Opened by', 'opened_at': 'Opened at' 'state': 'State' } } RITM: { table: 'sc_req_item' fields: { 'short_description': 'Short Description', 'assignment_group.name': 'Assignment group', 'opened_by.name': 'Opened by', 'opened_at': 'Opened At' 'state': 'State' } } SCTASK: { table: 'sc_task' fields: { 'short_description': 'Short Description', 'request.number': 'Request', 'request_item.number': 'Request Item', 'request.requested_for.name': 'Requested For', 'assignment_group.name': 'Assignment Group', 'state': 'State' } } STRY: { table: 'rm_story' fields: { 'short_description': 'Short Description', 'epic.short_description': 'Epic', 'opened_by.name': 'Opened by', 'product.name': 'Product', 'state': 'State' } } STSK: { table: 'rm_scrum_task' fields: { 'short_description': 'Short Description' 'opened_by.name': 'Opened by', 'state': 'State', 'story.number': 'Story Number', 'story.short_description': 'Story Description' } } } # this works similar to the robot.respond message above, # but it looks only for the record types we know about # also, we need to be careful to avoid interaction with the normal # robot.respond messages, and we also don't want to create a feedback loop # between bots robot.hear ///(#{Object.keys(table_lookup).join('|')})([0-9]{7,})///i, (res) -> name_mention = "@#{robot.name}" start_with_mention = res.message.text.startsWith name_mention start_with_name = res.message.text.startsWith robot.name # don't do anything if bot was @ mentioned if start_with_mention or start_with_name robot.logger.debug "robot.hear ignoring explicit Service Now request " + "and allowing robot.respond to handle it" return # don't do anything if listen is false unless robot.brain.get("sn_api.#{res.message.room}.listen") robot.logger.debug "Ignoring Service Now request; sn listen is off" return # ignore messages from bots if res.message.user.is_bot or res.message.user.slack?.is_bot robot.logger.debug "Ignoring Service Now mention by bot" return rec_type = res.match[1] rec_num = res.match[2] robot.logger.debug "Record: #{rec_type}#{rec_num}" robot.logger.debug "user: #{res.message.user.name}" robot.logger.debug "table: #{table_lookup[rec_type]['table']}" robot.emit "sn_record_get", { user: res.message.user, table: table_lookup[rec_type]['table'], fields: table_lookup[rec_type]['fields'] rec_number: "#{rec_type}#{rec_num}" }
[ { "context": "ent.IndexService\n local_storage_key = 'sort-' + IndexService.controller\n\n syncIndexS", "end": 318, "score": 0.7387930750846863, "start": 312, "tag": "KEY", "value": "sort-'" } ]
resources/assets/coffee/directives/order-by.coffee
maxflex/tcms
0
angular.module 'Egecms' .directive 'orderBy', -> restrict: 'E' replace: true scope: options: '=' templateUrl: 'directives/order-by' link: ($scope, $element, $attrs) -> IndexService = $scope.$parent.IndexService local_storage_key = 'sort-' + IndexService.controller syncIndexService = (sort) -> IndexService.sort = sort IndexService.current_page = 1 IndexService.loadPage() $scope.setSort = (sort) -> $scope.sort = sort localStorage.setItem(local_storage_key, sort) syncIndexService(sort) $scope.sort = localStorage.getItem(local_storage_key) if $scope.sort is null $scope.setSort(0) else syncIndexService($scope.sort)
89282
angular.module 'Egecms' .directive 'orderBy', -> restrict: 'E' replace: true scope: options: '=' templateUrl: 'directives/order-by' link: ($scope, $element, $attrs) -> IndexService = $scope.$parent.IndexService local_storage_key = '<KEY> + IndexService.controller syncIndexService = (sort) -> IndexService.sort = sort IndexService.current_page = 1 IndexService.loadPage() $scope.setSort = (sort) -> $scope.sort = sort localStorage.setItem(local_storage_key, sort) syncIndexService(sort) $scope.sort = localStorage.getItem(local_storage_key) if $scope.sort is null $scope.setSort(0) else syncIndexService($scope.sort)
true
angular.module 'Egecms' .directive 'orderBy', -> restrict: 'E' replace: true scope: options: '=' templateUrl: 'directives/order-by' link: ($scope, $element, $attrs) -> IndexService = $scope.$parent.IndexService local_storage_key = 'PI:KEY:<KEY>END_PI + IndexService.controller syncIndexService = (sort) -> IndexService.sort = sort IndexService.current_page = 1 IndexService.loadPage() $scope.setSort = (sort) -> $scope.sort = sort localStorage.setItem(local_storage_key, sort) syncIndexService(sort) $scope.sort = localStorage.getItem(local_storage_key) if $scope.sort is null $scope.setSort(0) else syncIndexService($scope.sort)
[ { "context": "eturn\n\n query =\n email: creds[0]\n password: creds[1]\n Users.findOne(query).then (results) ->\n if ", "end": 589, "score": 0.9948930144309998, "start": 582, "tag": "PASSWORD", "value": "creds[1" } ]
server/src/helpers/auth.coffee
codyseibert/typr.io
1
Base64 = require('js-base64').Base64 Users = require('../models/models').Users module.exports = (req, res, next) -> auth = req.headers.authorization if not auth? res.status 400 res.send 'invalid authorization header' return auth = auth.split(" ") if auth.length isnt 2 res.status 400 res.send 'invalid authorization header' return creds = auth[1] creds = Base64.decode creds creds = creds.split ':' if creds.length isnt 2 res.status 400 res.send 'invalid creditials passed' return query = email: creds[0] password: creds[1] Users.findOne(query).then (results) -> if not results? res.status 403 res.send 'invalid login' else req.user = results next()
219821
Base64 = require('js-base64').Base64 Users = require('../models/models').Users module.exports = (req, res, next) -> auth = req.headers.authorization if not auth? res.status 400 res.send 'invalid authorization header' return auth = auth.split(" ") if auth.length isnt 2 res.status 400 res.send 'invalid authorization header' return creds = auth[1] creds = Base64.decode creds creds = creds.split ':' if creds.length isnt 2 res.status 400 res.send 'invalid creditials passed' return query = email: creds[0] password: <PASSWORD>] Users.findOne(query).then (results) -> if not results? res.status 403 res.send 'invalid login' else req.user = results next()
true
Base64 = require('js-base64').Base64 Users = require('../models/models').Users module.exports = (req, res, next) -> auth = req.headers.authorization if not auth? res.status 400 res.send 'invalid authorization header' return auth = auth.split(" ") if auth.length isnt 2 res.status 400 res.send 'invalid authorization header' return creds = auth[1] creds = Base64.decode creds creds = creds.split ':' if creds.length isnt 2 res.status 400 res.send 'invalid creditials passed' return query = email: creds[0] password: PI:PASSWORD:<PASSWORD>END_PI] Users.findOne(query).then (results) -> if not results? res.status 403 res.send 'invalid login' else req.user = results next()
[ { "context": " 321: 2\n 456: 3\n 654: 4\n password = '0123456789'\n matches = matching.reverse_dictionary_match pa", "end": 6899, "score": 0.9994208216667175, "start": 6889, "tag": "PASSWORD", "value": "0123456789" }, { "context": " dicts =\n words:\n aac: 1\n ...
test/test-matching.coffee
lpavlicek/zxcvbn-czech
3
test = require 'tape' matching = require '../src/matching' adjacency_graphs = require '../src/adjacency_graphs' # takes a pattern and list of prefixes/suffixes # returns a bunch of variants of that pattern embedded # with each possible prefix/suffix combination, including no prefix/suffix # returns a list of triplets [variant, i, j] where [i,j] is the start/end of the pattern, inclusive genpws = (pattern, prefixes, suffixes) -> prefixes = prefixes.slice() suffixes = suffixes.slice() for lst in [prefixes, suffixes] lst.unshift '' if '' not in lst result = [] for prefix in prefixes for suffix in suffixes [i, j] = [prefix.length, prefix.length + pattern.length - 1] result.push [prefix + pattern + suffix, i, j] result check_matches = (prefix, t, matches, pattern_names, patterns, ijs, props) -> if typeof pattern_names is "string" # shortcut: if checking for a list of the same type of patterns, # allow passing a string 'pat' instead of array ['pat', 'pat', ...] pattern_names = (pattern_names for i in [0...patterns.length]) is_equal_len_args = pattern_names.length == patterns.length == ijs.length for prop, lst of props # props is structured as: keys that points to list of values is_equal_len_args = is_equal_len_args and (lst.length == patterns.length) throw 'unequal argument lists to check_matches' unless is_equal_len_args msg = "#{prefix}: matches.length == #{patterns.length}" t.equal matches.length, patterns.length, msg for k in [0...patterns.length] match = matches[k] pattern_name = pattern_names[k] pattern = patterns[k] [i, j] = ijs[k] msg = "#{prefix}: matches[#{k}].pattern == '#{pattern_name}'" t.equal match.pattern, pattern_name, msg msg = "#{prefix}: matches[#{k}] should have [i, j] of [#{i}, #{j}]" t.deepEqual [match.i, match.j], [i, j], msg msg = "#{prefix}: matches[#{k}].token == '#{pattern}'" t.equal match.token, pattern, msg for prop_name, prop_list of props prop_msg = prop_list[k] prop_msg = "'#{prop_msg}'" if typeof(prop_msg) == 'string' msg = "#{prefix}: matches[#{k}].#{prop_name} == #{prop_msg}" t.deepEqual match[prop_name], prop_list[k], msg test 'matching utils', (t) -> t.ok matching.empty([]), ".empty returns true for an empty array" t.ok matching.empty({}), ".empty returns true for an empty object" for obj in [ [1] [1, 2] [[]] {a: 1} {0: {}} ] t.notOk matching.empty(obj), ".empty returns false for non-empty objects and arrays" lst = [] matching.extend lst, [] t.deepEqual lst, [], "extending an empty list with an empty list leaves it empty" matching.extend lst, [1] t.deepEqual lst, [1], "extending an empty list with another makes it equal to the other" matching.extend lst, [2, 3] t.deepEqual lst, [1, 2, 3], "extending a list with another adds each of the other's elements" [lst1, lst2] = [[1], [2]] matching.extend lst1, lst2 t.deepEqual lst2, [2], "extending a list by another doesn't affect the other" chr_map = {a: 'A', b: 'B'} for [string, map, result] in [ ['a', chr_map, 'A'] ['c', chr_map, 'c'] ['ab', chr_map, 'AB'] ['abc', chr_map, 'ABc'] ['aa', chr_map, 'AA'] ['abab', chr_map, 'ABAB'] ['', chr_map, ''] ['', {}, ''] ['abc', {}, 'abc'] ] msg = "translates '#{string}' to '#{result}' with provided charmap" t.equal matching.translate(string, map), result, msg for [[dividend, divisor], remainder] in [ [[ 0, 1], 0] [[ 1, 1], 0] [[-1, 1], 0] [[ 5, 5], 0] [[ 3, 5], 3] [[-1, 5], 4] [[-5, 5], 0] [[ 6, 5], 1] ] msg = "mod(#{dividend}, #{divisor}) == #{remainder}" t.equal matching.mod(dividend, divisor), remainder, msg t.deepEqual matching.sorted([]), [], "sorting an empty list leaves it empty" [m1, m2, m3, m4, m5, m6] = [ {i: 5, j: 5} {i: 6, j: 7} {i: 2, j: 5} {i: 0, j: 0} {i: 2, j: 3} {i: 0, j: 3} ] msg = "matches are sorted on i index primary, j secondary" t.deepEqual matching.sorted([m1, m2, m3, m4, m5, m6]), [m4, m6, m5, m3, m1, m2], msg t.end() test 'dictionary matching', (t) -> dm = (pw) -> matching.dictionary_match pw, test_dicts test_dicts = d1: motherboard: 1 mother: 2 board: 3 abcd: 4 cdef: 5 d2: # min token length is 3 'zzz': 1 '888': 2 '9999': 3 '$%^': 4 'asdf1234&*': 5 matches = dm 'motherboard' patterns = ['mother', 'motherboard', 'board'] msg = "matches words that contain other words" check_matches msg, t, matches, 'dictionary', patterns, [[0,5], [0,10], [6,10]], matched_word: ['mother', 'motherboard', 'board'] rank: [2, 1, 3] dictionary_name: ['d1', 'd1', 'd1'] matches = dm 'abcdef' patterns = ['abcd', 'cdef'] msg = "matches multiple words when they overlap" check_matches msg, t, matches, 'dictionary', patterns, [[0,3], [2,5]], matched_word: ['abcd', 'cdef'] rank: [4, 5] dictionary_name: ['d1', 'd1'] matches = dm 'BoaRdZzz' patterns = ['BoaRd', 'Zzz'] msg = "ignores uppercasing" check_matches msg, t, matches, 'dictionary', patterns, [[0,4], [5,7]], matched_word: ['board', 'zzz'] rank: [3, 1] dictionary_name: ['d1', 'd2'] prefixes = ['q', '%%'] suffixes = ['%', 'qq'] word = 'asdf1234&*' for [password, i, j] in genpws word, prefixes, suffixes matches = dm password msg = "identifies words surrounded by non-words" check_matches msg, t, matches, 'dictionary', [word], [[i,j]], matched_word: [word] rank: [5] dictionary_name: ['d2'] for name, dict of test_dicts for word, rank of dict continue if word is 'motherboard' # skip words that contain others matches = dm word msg = "matches against all words in provided dictionaries" check_matches msg, t, matches, 'dictionary', [word], [[0, word.length - 1]], matched_word: [word] rank: [rank] dictionary_name: [name] # test the default dictionaries matches = matching.dictionary_match 'wow' patterns = ['wow'] ijs = [[0,2]] msg = "default dictionaries" check_matches msg, t, matches, 'dictionary', patterns, ijs, matched_word: patterns rank: [317] dictionary_name: ['us_tv_and_film'] matching.set_user_input_dictionary ['foo', 'bar'] matches = matching.dictionary_match 'foobar' matches = matches.filter (match) -> match.dictionary_name == 'user_inputs' msg = "matches with provided user input dictionary" check_matches msg, t, matches, 'dictionary', ['foo', 'bar'], [[0, 2], [3, 5]], matched_word: ['foo', 'bar'] rank: [1, 2] t.end() test 'reverse dictionary matching', (t) -> test_dicts = d1: 123: 1 321: 2 456: 3 654: 4 password = '0123456789' matches = matching.reverse_dictionary_match password, test_dicts msg = 'matches against reversed words' check_matches msg, t, matches, 'dictionary', ['123', '456'], [[1, 3], [4, 6]], matched_word: ['321', '654'] reversed: [true, true] dictionary_name: ['d1', 'd1'] rank: [2, 4] t.end() test 'l33t matching', (t) -> test_table = a: ['4', '@'] c: ['(', '{', '[', '<'] g: ['6', '9'] o: ['0'] for [pw, expected] in [ [ '', {} ] [ 'abcdefgo123578!#$&*)]}>', {} ] [ 'a', {} ] [ '4', {'a': ['4']} ] [ '4@', {'a': ['4','@']} ] [ '4({60', {'a': ['4'], 'c': ['(','{'], 'g': ['6'], 'o': ['0']} ] ] msg = "reduces l33t table to only the substitutions that a password might be employing" t.deepEquals matching.relevant_l33t_subtable(pw, test_table), expected, msg for [table, subs] in [ [ {}, [{}] ] [ {a: ['@']}, [{'@': 'a'}] ] [ {a: ['@','4']}, [{'@': 'a'}, {'4': 'a'}] ] [ {a: ['@','4'], c: ['(']}, [{'@': 'a', '(': 'c' }, {'4': 'a', '(': 'c'}] ] ] msg = "enumerates the different sets of l33t substitutions a password might be using" t.deepEquals matching.enumerate_l33t_subs(table), subs, msg lm = (pw) -> matching.l33t_match pw, dicts, test_table dicts = words: aac: 1 password: 3 paassword: 4 asdf0: 5 words2: cgo: 1 t.deepEquals lm(''), [], "doesn't match ''" t.deepEquals lm('password'), [], "doesn't match pure dictionary words" for [password, pattern, word, dictionary_name, rank, ij, sub] in [ [ 'p4ssword', 'p4ssword', 'password', 'words', 3, [0,7], {'4': 'a'} ] [ 'p@ssw0rd', 'p@ssw0rd', 'password', 'words', 3, [0,7], {'@': 'a', '0': 'o'} ] [ 'aSdfO{G0asDfO', '{G0', 'cgo', 'words2', 1, [5, 7], {'{': 'c', '0': 'o'} ] ] msg = "matches against common l33t substitutions" check_matches msg, t, lm(password), 'dictionary', [pattern], [ij], l33t: [true] sub: [sub] matched_word: [word] rank: [rank] dictionary_name: [dictionary_name] matches = lm '@a(go{G0' msg = "matches against overlapping l33t patterns" check_matches msg, t, matches, 'dictionary', ['@a(', '(go', '{G0'], [[0,2], [2,4], [5,7]], l33t: [true, true, true] sub: [{'@': 'a', '(': 'c'}, {'(': 'c'}, {'{': 'c', '0': 'o'}] matched_word: ['aac', 'cgo', 'cgo'] rank: [1, 1, 1] dictionary_name: ['words', 'words2', 'words2'] msg = "doesn't match when multiple l33t substitutions are needed for the same letter" t.deepEqual lm('p4@ssword'), [], msg msg = "doesn't match single-character l33ted words" matches = matching.l33t_match '4 1 @' t.deepEqual matches, [], msg # known issue: subsets of substitutions aren't tried. # for long inputs, trying every subset of every possible substitution could quickly get large, # but there might be a performant way to fix. # (so in this example: {'4': a, '0': 'o'} is detected as a possible sub, # but the subset {'4': 'a'} isn't tried, missing the match for asdf0.) # TODO: consider partially fixing by trying all subsets of size 1 and maybe 2 msg = "doesn't match with subsets of possible l33t substitutions" t.deepEqual lm('4sdf0'), [], msg t.end() test 'spatial matching', (t) -> for password in ['', '/', 'qw', '*/'] msg = "doesn't match 1- and 2-character spatial patterns" t.deepEqual matching.spatial_match(password), [], msg # for testing, make a subgraph that contains a single keyboard _graphs = qwerty: adjacency_graphs.qwerty pattern = '6tfGHJ' matches = matching.spatial_match "rz!#{pattern}%z", _graphs msg = "matches against spatial patterns surrounded by non-spatial patterns" check_matches msg, t, matches, 'spatial', [pattern], [[3, 3 + pattern.length - 1]], graph: ['qwerty'] turns: [2] shifted_count: [3] for [pattern, keyboard, turns, shifts] in [ [ '12345', 'qwerty', 1, 0 ] [ '@WSX', 'qwerty', 1, 4 ] [ '6tfGHJ', 'qwerty', 2, 3 ] [ 'hGFd', 'qwerty', 1, 2 ] [ '/;p09876yhn', 'qwerty', 3, 0 ] [ 'Xdr%', 'qwerty', 1, 2 ] [ '159-', 'keypad', 1, 0 ] [ '*84', 'keypad', 1, 0 ] [ '/8520', 'keypad', 1, 0 ] [ '369', 'keypad', 1, 0 ] [ '/963.', 'mac_keypad', 1, 0 ] [ '*-632.0214', 'mac_keypad', 9, 0 ] [ 'aoEP%yIxkjq:', 'dvorak', 4, 5 ] [ ';qoaOQ:Aoq;a', 'dvorak', 11, 4 ] ] _graphs = {} _graphs[keyboard] = adjacency_graphs[keyboard] matches = matching.spatial_match pattern, _graphs msg = "matches '#{pattern}' as a #{keyboard} pattern" check_matches msg, t, matches, 'spatial', [pattern], [[0, pattern.length - 1]], graph: [keyboard] turns: [turns] shifted_count: [shifts] t.end() test 'sequence matching', (t) -> for password in ['', 'a', '1'] msg = "doesn't match length-#{password.length} sequences" t.deepEqual matching.sequence_match(password), [], msg matches = matching.sequence_match 'abcbabc' msg = "matches overlapping patterns" check_matches msg, t, matches, 'sequence', ['abc', 'cba', 'abc'], [[0, 2], [2, 4], [4, 6]], ascending: [true, false, true] prefixes = ['!', '22'] suffixes = ['!', '22'] pattern = 'jihg' for [password, i, j] in genpws pattern, prefixes, suffixes matches = matching.sequence_match password msg = "matches embedded sequence patterns #{password}" check_matches msg, t, matches, 'sequence', [pattern], [[i, j]], sequence_name: ['lower'] ascending: [false] for [pattern, name, is_ascending] in [ ['ABC', 'upper', true] ['CBA', 'upper', false] ['PQR', 'upper', true] ['RQP', 'upper', false] ['XYZ', 'upper', true] ['ZYX', 'upper', false] ['abcd', 'lower', true] ['dcba', 'lower', false] ['jihg', 'lower', false] ['wxyz', 'lower', true] ['zxvt', 'lower', false] ['0369', 'digits', true] ['97531', 'digits', false] ] matches = matching.sequence_match pattern msg = "matches '#{pattern}' as a '#{name}' sequence" check_matches msg, t, matches, 'sequence', [pattern], [[0, pattern.length - 1]], sequence_name: [name] ascending: [is_ascending] t.end() test 'repeat matching', (t) -> for password in ['', '#'] msg = "doesn't match length-#{password.length} repeat patterns" t.deepEqual matching.repeat_match(password), [], msg # test single-character repeats prefixes = ['@', 'y4@'] suffixes = ['u', 'u%7'] pattern = '&&&&&' for [password, i, j] in genpws pattern, prefixes, suffixes matches = matching.repeat_match password msg = "matches embedded repeat patterns" check_matches msg, t, matches, 'repeat', [pattern], [[i, j]], base_token: ['&'] for length in [3, 12] for chr in ['a', 'Z', '4', '&'] pattern = Array(length + 1).join(chr) matches = matching.repeat_match pattern msg = "matches repeats with base character '#{chr}'" check_matches msg, t, matches, 'repeat', [pattern], [[0, pattern.length - 1]], base_token: [chr] matches = matching.repeat_match 'BBB1111aaaaa@@@@@@' patterns = ['BBB','1111','aaaaa','@@@@@@'] msg = 'matches multiple adjacent repeats' check_matches msg, t, matches, 'repeat', patterns, [[0, 2],[3, 6],[7, 11],[12, 17]], base_token: ['B', '1', 'a', '@'] matches = matching.repeat_match '2818BBBbzsdf1111@*&@!aaaaaEUDA@@@@@@1729' msg = 'matches multiple repeats with non-repeats in-between' check_matches msg, t, matches, 'repeat', patterns, [[4, 6],[12, 15],[21, 25],[30, 35]], base_token: ['B', '1', 'a', '@'] # test multi-character repeats pattern = 'abab' matches = matching.repeat_match pattern msg = 'matches multi-character repeat pattern' check_matches msg, t, matches, 'repeat', [pattern], [[0, pattern.length - 1]], base_token: ['ab'] pattern = 'aabaab' matches = matching.repeat_match pattern msg = 'matches aabaab as a repeat instead of the aa prefix' check_matches msg, t, matches, 'repeat', [pattern], [[0, pattern.length - 1]], base_token: ['aab'] pattern = 'abababab' matches = matching.repeat_match pattern msg = 'identifies ab as repeat string, even though abab is also repeated' check_matches msg, t, matches, 'repeat', [pattern], [[0, pattern.length - 1]], base_token: ['ab'] t.end() test 'regex matching', (t) -> for [pattern, name] in [ ['1922', 'recent_year'] ['2017', 'recent_year'] ] matches = matching.regex_match pattern msg = "matches #{pattern} as a #{name} pattern" check_matches msg, t, matches, 'regex', [pattern], [[0, pattern.length - 1]], regex_name: [name] t.end() test 'date matching', (t) -> for sep in ['', ' ', '-', '/', '\\', '_', '.'] password = "13#{sep}2#{sep}1921" matches = matching.date_match password msg = "matches dates that use '#{sep}' as a separator" check_matches msg, t, matches, 'date', [password], [[0, password.length - 1]], separator: [sep] year: [1921] month: [2] day: [13] for order in ['mdy', 'dmy', 'ymd', 'ydm'] [d,m,y] = [8,8,88] password = order .replace 'y', y .replace 'm', m .replace 'd', d matches = matching.date_match password msg = "matches dates with '#{order}' format" check_matches msg, t, matches, 'date', [password], [[0, password.length - 1]], separator: [''] year: [1988] month: [8] day: [8] password = '111504' matches = matching.date_match password msg = "matches the date with year closest to REFERENCE_YEAR when ambiguous" check_matches msg, t, matches, 'date', [password], [[0, password.length - 1]], separator: [''] year: [2004] # picks '04' -> 2004 as year, not '1504' month: [11] day: [15] for [day, month, year] in [ [1, 1, 1999] [11, 8, 2000] [9, 12, 2005] [22, 11, 1551] ] password = "#{year}#{month}#{day}" matches = matching.date_match password msg = "matches #{password}" check_matches msg, t, matches, 'date', [password], [[0, password.length - 1]], separator: [''] year: [year] password = "#{year}.#{month}.#{day}" matches = matching.date_match password msg = "matches #{password}" check_matches msg, t, matches, 'date', [password], [[0, password.length - 1]], separator: ['.'] year: [year] password = "02/02/02" matches = matching.date_match password msg = "matches zero-padded dates" check_matches msg, t, matches, 'date', [password], [[0, password.length - 1]], separator: ['/'] year: [2002] month: [2] day: [2] prefixes = ['a', 'ab'] suffixes = ['!'] pattern = '1/1/91' for [password, i, j] in genpws pattern, prefixes, suffixes matches = matching.date_match password msg = "matches embedded dates" check_matches msg, t, matches, 'date', [pattern], [[i, j]], year: [1991] month: [1] day: [1] matches = matching.date_match '12/20/1991.12.20' msg = "matches overlapping dates" check_matches msg, t, matches, 'date', ['12/20/1991', '1991.12.20'], [[0, 9], [6,15]], separator: ['/', '.'] year: [1991, 1991] month: [12, 12] day: [20, 20] matches = matching.date_match '912/20/919' msg = "matches dates padded by non-ambiguous digits" check_matches msg, t, matches, 'date', ['12/20/91'], [[1, 8]], separator: ['/'] year: [1991] month: [12] day: [20] t.end() test 'omnimatch', (t) -> t.deepEquals matching.omnimatch(''), [], "doesn't match ''" password = 'r0sebudmaelstrom11/20/91aaaa' matches = matching.omnimatch password for [pattern_name, [i, j]] in [ [ 'dictionary', [0, 6] ] [ 'dictionary', [7, 15] ] [ 'date', [16, 23] ] [ 'repeat', [24, 27] ] ] included = false for match in matches included = true if match.i == i and match.j == j and match.pattern == pattern_name msg = "for #{password}, matches a #{pattern_name} pattern at [#{i}, #{j}]" t.ok included, msg t.end()
72170
test = require 'tape' matching = require '../src/matching' adjacency_graphs = require '../src/adjacency_graphs' # takes a pattern and list of prefixes/suffixes # returns a bunch of variants of that pattern embedded # with each possible prefix/suffix combination, including no prefix/suffix # returns a list of triplets [variant, i, j] where [i,j] is the start/end of the pattern, inclusive genpws = (pattern, prefixes, suffixes) -> prefixes = prefixes.slice() suffixes = suffixes.slice() for lst in [prefixes, suffixes] lst.unshift '' if '' not in lst result = [] for prefix in prefixes for suffix in suffixes [i, j] = [prefix.length, prefix.length + pattern.length - 1] result.push [prefix + pattern + suffix, i, j] result check_matches = (prefix, t, matches, pattern_names, patterns, ijs, props) -> if typeof pattern_names is "string" # shortcut: if checking for a list of the same type of patterns, # allow passing a string 'pat' instead of array ['pat', 'pat', ...] pattern_names = (pattern_names for i in [0...patterns.length]) is_equal_len_args = pattern_names.length == patterns.length == ijs.length for prop, lst of props # props is structured as: keys that points to list of values is_equal_len_args = is_equal_len_args and (lst.length == patterns.length) throw 'unequal argument lists to check_matches' unless is_equal_len_args msg = "#{prefix}: matches.length == #{patterns.length}" t.equal matches.length, patterns.length, msg for k in [0...patterns.length] match = matches[k] pattern_name = pattern_names[k] pattern = patterns[k] [i, j] = ijs[k] msg = "#{prefix}: matches[#{k}].pattern == '#{pattern_name}'" t.equal match.pattern, pattern_name, msg msg = "#{prefix}: matches[#{k}] should have [i, j] of [#{i}, #{j}]" t.deepEqual [match.i, match.j], [i, j], msg msg = "#{prefix}: matches[#{k}].token == '#{pattern}'" t.equal match.token, pattern, msg for prop_name, prop_list of props prop_msg = prop_list[k] prop_msg = "'#{prop_msg}'" if typeof(prop_msg) == 'string' msg = "#{prefix}: matches[#{k}].#{prop_name} == #{prop_msg}" t.deepEqual match[prop_name], prop_list[k], msg test 'matching utils', (t) -> t.ok matching.empty([]), ".empty returns true for an empty array" t.ok matching.empty({}), ".empty returns true for an empty object" for obj in [ [1] [1, 2] [[]] {a: 1} {0: {}} ] t.notOk matching.empty(obj), ".empty returns false for non-empty objects and arrays" lst = [] matching.extend lst, [] t.deepEqual lst, [], "extending an empty list with an empty list leaves it empty" matching.extend lst, [1] t.deepEqual lst, [1], "extending an empty list with another makes it equal to the other" matching.extend lst, [2, 3] t.deepEqual lst, [1, 2, 3], "extending a list with another adds each of the other's elements" [lst1, lst2] = [[1], [2]] matching.extend lst1, lst2 t.deepEqual lst2, [2], "extending a list by another doesn't affect the other" chr_map = {a: 'A', b: 'B'} for [string, map, result] in [ ['a', chr_map, 'A'] ['c', chr_map, 'c'] ['ab', chr_map, 'AB'] ['abc', chr_map, 'ABc'] ['aa', chr_map, 'AA'] ['abab', chr_map, 'ABAB'] ['', chr_map, ''] ['', {}, ''] ['abc', {}, 'abc'] ] msg = "translates '#{string}' to '#{result}' with provided charmap" t.equal matching.translate(string, map), result, msg for [[dividend, divisor], remainder] in [ [[ 0, 1], 0] [[ 1, 1], 0] [[-1, 1], 0] [[ 5, 5], 0] [[ 3, 5], 3] [[-1, 5], 4] [[-5, 5], 0] [[ 6, 5], 1] ] msg = "mod(#{dividend}, #{divisor}) == #{remainder}" t.equal matching.mod(dividend, divisor), remainder, msg t.deepEqual matching.sorted([]), [], "sorting an empty list leaves it empty" [m1, m2, m3, m4, m5, m6] = [ {i: 5, j: 5} {i: 6, j: 7} {i: 2, j: 5} {i: 0, j: 0} {i: 2, j: 3} {i: 0, j: 3} ] msg = "matches are sorted on i index primary, j secondary" t.deepEqual matching.sorted([m1, m2, m3, m4, m5, m6]), [m4, m6, m5, m3, m1, m2], msg t.end() test 'dictionary matching', (t) -> dm = (pw) -> matching.dictionary_match pw, test_dicts test_dicts = d1: motherboard: 1 mother: 2 board: 3 abcd: 4 cdef: 5 d2: # min token length is 3 'zzz': 1 '888': 2 '9999': 3 '$%^': 4 'asdf1234&*': 5 matches = dm 'motherboard' patterns = ['mother', 'motherboard', 'board'] msg = "matches words that contain other words" check_matches msg, t, matches, 'dictionary', patterns, [[0,5], [0,10], [6,10]], matched_word: ['mother', 'motherboard', 'board'] rank: [2, 1, 3] dictionary_name: ['d1', 'd1', 'd1'] matches = dm 'abcdef' patterns = ['abcd', 'cdef'] msg = "matches multiple words when they overlap" check_matches msg, t, matches, 'dictionary', patterns, [[0,3], [2,5]], matched_word: ['abcd', 'cdef'] rank: [4, 5] dictionary_name: ['d1', 'd1'] matches = dm 'BoaRdZzz' patterns = ['BoaRd', 'Zzz'] msg = "ignores uppercasing" check_matches msg, t, matches, 'dictionary', patterns, [[0,4], [5,7]], matched_word: ['board', 'zzz'] rank: [3, 1] dictionary_name: ['d1', 'd2'] prefixes = ['q', '%%'] suffixes = ['%', 'qq'] word = 'asdf1234&*' for [password, i, j] in genpws word, prefixes, suffixes matches = dm password msg = "identifies words surrounded by non-words" check_matches msg, t, matches, 'dictionary', [word], [[i,j]], matched_word: [word] rank: [5] dictionary_name: ['d2'] for name, dict of test_dicts for word, rank of dict continue if word is 'motherboard' # skip words that contain others matches = dm word msg = "matches against all words in provided dictionaries" check_matches msg, t, matches, 'dictionary', [word], [[0, word.length - 1]], matched_word: [word] rank: [rank] dictionary_name: [name] # test the default dictionaries matches = matching.dictionary_match 'wow' patterns = ['wow'] ijs = [[0,2]] msg = "default dictionaries" check_matches msg, t, matches, 'dictionary', patterns, ijs, matched_word: patterns rank: [317] dictionary_name: ['us_tv_and_film'] matching.set_user_input_dictionary ['foo', 'bar'] matches = matching.dictionary_match 'foobar' matches = matches.filter (match) -> match.dictionary_name == 'user_inputs' msg = "matches with provided user input dictionary" check_matches msg, t, matches, 'dictionary', ['foo', 'bar'], [[0, 2], [3, 5]], matched_word: ['foo', 'bar'] rank: [1, 2] t.end() test 'reverse dictionary matching', (t) -> test_dicts = d1: 123: 1 321: 2 456: 3 654: 4 password = '<PASSWORD>' matches = matching.reverse_dictionary_match password, test_dicts msg = 'matches against reversed words' check_matches msg, t, matches, 'dictionary', ['123', '456'], [[1, 3], [4, 6]], matched_word: ['321', '654'] reversed: [true, true] dictionary_name: ['d1', 'd1'] rank: [2, 4] t.end() test 'l33t matching', (t) -> test_table = a: ['4', '@'] c: ['(', '{', '[', '<'] g: ['6', '9'] o: ['0'] for [pw, expected] in [ [ '', {} ] [ 'abcdefgo123578!#$&*)]}>', {} ] [ 'a', {} ] [ '4', {'a': ['4']} ] [ '4@', {'a': ['4','@']} ] [ '4({60', {'a': ['4'], 'c': ['(','{'], 'g': ['6'], 'o': ['0']} ] ] msg = "reduces l33t table to only the substitutions that a password might be employing" t.deepEquals matching.relevant_l33t_subtable(pw, test_table), expected, msg for [table, subs] in [ [ {}, [{}] ] [ {a: ['@']}, [{'@': 'a'}] ] [ {a: ['@','4']}, [{'@': 'a'}, {'4': 'a'}] ] [ {a: ['@','4'], c: ['(']}, [{'@': 'a', '(': 'c' }, {'4': 'a', '(': 'c'}] ] ] msg = "enumerates the different sets of l33t substitutions a password might be using" t.deepEquals matching.enumerate_l33t_subs(table), subs, msg lm = (pw) -> matching.l33t_match pw, dicts, test_table dicts = words: aac: 1 password: <PASSWORD> paassword: <PASSWORD> asdf0: 5 words2: cgo: 1 t.deepEquals lm(''), [], "doesn't match ''" t.deepEquals lm('password'), [], "doesn't match pure dictionary words" for [password, pattern, word, dictionary_name, rank, ij, sub] in [ [ 'p4ssword', 'p4ssword', 'password', 'words', 3, [0,7], {'4': 'a'} ] [ 'p@ssw0rd', 'p@ssw0rd', 'password', 'words', 3, [0,7], {'@': 'a', '0': 'o'} ] [ 'aSdfO{G0asDfO', '{G0', 'cgo', 'words2', 1, [5, 7], {'{': 'c', '0': 'o'} ] ] msg = "matches against common l33t substitutions" check_matches msg, t, lm(password), 'dictionary', [pattern], [ij], l33t: [true] sub: [sub] matched_word: [word] rank: [rank] dictionary_name: [dictionary_name] matches = lm '@a(go{G0' msg = "matches against overlapping l33t patterns" check_matches msg, t, matches, 'dictionary', ['@a(', '(go', '{G0'], [[0,2], [2,4], [5,7]], l33t: [true, true, true] sub: [{'@': 'a', '(': 'c'}, {'(': 'c'}, {'{': 'c', '0': 'o'}] matched_word: ['aac', 'cgo', 'cgo'] rank: [1, 1, 1] dictionary_name: ['words', 'words2', 'words2'] msg = "doesn't match when multiple l33t substitutions are needed for the same letter" t.deepEqual lm('p4@ssword'), [], msg msg = "doesn't match single-character l33ted words" matches = matching.l33t_match '4 1 @' t.deepEqual matches, [], msg # known issue: subsets of substitutions aren't tried. # for long inputs, trying every subset of every possible substitution could quickly get large, # but there might be a performant way to fix. # (so in this example: {'4': a, '0': 'o'} is detected as a possible sub, # but the subset {'4': 'a'} isn't tried, missing the match for asdf0.) # TODO: consider partially fixing by trying all subsets of size 1 and maybe 2 msg = "doesn't match with subsets of possible l33t substitutions" t.deepEqual lm('4sdf0'), [], msg t.end() test 'spatial matching', (t) -> for password in ['', '/', 'qw', '*/'] msg = "doesn't match 1- and 2-character spatial patterns" t.deepEqual matching.spatial_match(password), [], msg # for testing, make a subgraph that contains a single keyboard _graphs = qwerty: adjacency_graphs.qwerty pattern = '6tfGHJ' matches = matching.spatial_match "rz!#{pattern}%z", _graphs msg = "matches against spatial patterns surrounded by non-spatial patterns" check_matches msg, t, matches, 'spatial', [pattern], [[3, 3 + pattern.length - 1]], graph: ['qwerty'] turns: [2] shifted_count: [3] for [pattern, keyboard, turns, shifts] in [ [ '12345', 'qwerty', 1, 0 ] [ '@WSX', 'qwerty', 1, 4 ] [ '6tfGHJ', 'qwerty', 2, 3 ] [ 'hGFd', 'qwerty', 1, 2 ] [ '/;p09876yhn', 'qwerty', 3, 0 ] [ 'Xdr%', 'qwerty', 1, 2 ] [ '159-', 'keypad', 1, 0 ] [ '*84', 'keypad', 1, 0 ] [ '/8520', 'keypad', 1, 0 ] [ '369', 'keypad', 1, 0 ] [ '/963.', 'mac_keypad', 1, 0 ] [ '*-632.0214', 'mac_keypad', 9, 0 ] [ 'aoEP%yIxkjq:', 'dvorak', 4, 5 ] [ ';qoaOQ:Aoq;a', 'dvorak', 11, 4 ] ] _graphs = {} _graphs[keyboard] = adjacency_graphs[keyboard] matches = matching.spatial_match pattern, _graphs msg = "matches '#{pattern}' as a #{keyboard} pattern" check_matches msg, t, matches, 'spatial', [pattern], [[0, pattern.length - 1]], graph: [keyboard] turns: [turns] shifted_count: [shifts] t.end() test 'sequence matching', (t) -> for password in ['', '<PASSWORD>', '<PASSWORD>'] msg = "doesn't match length-#{password.length} sequences" t.deepEqual matching.sequence_match(password), [], msg matches = matching.sequence_match 'abcbabc' msg = "matches overlapping patterns" check_matches msg, t, matches, 'sequence', ['abc', 'cba', 'abc'], [[0, 2], [2, 4], [4, 6]], ascending: [true, false, true] prefixes = ['!', '22'] suffixes = ['!', '22'] pattern = 'jihg' for [password, i, j] in genpws pattern, prefixes, suffixes matches = matching.sequence_match password msg = "matches embedded sequence patterns #{password}" check_matches msg, t, matches, 'sequence', [pattern], [[i, j]], sequence_name: ['lower'] ascending: [false] for [pattern, name, is_ascending] in [ ['ABC', 'upper', true] ['CBA', 'upper', false] ['PQR', 'upper', true] ['RQP', 'upper', false] ['XYZ', 'upper', true] ['ZYX', 'upper', false] ['abcd', 'lower', true] ['dcba', 'lower', false] ['jihg', 'lower', false] ['wxyz', 'lower', true] ['zxvt', 'lower', false] ['0369', 'digits', true] ['97531', 'digits', false] ] matches = matching.sequence_match pattern msg = "matches '#{pattern}' as a '#{name}' sequence" check_matches msg, t, matches, 'sequence', [pattern], [[0, pattern.length - 1]], sequence_name: [name] ascending: [is_ascending] t.end() test 'repeat matching', (t) -> for password in ['', '#'] msg = "doesn't match length-#{password.length} repeat patterns" t.deepEqual matching.repeat_match(password), [], msg # test single-character repeats prefixes = ['@', 'y4@'] suffixes = ['u', 'u%7'] pattern = '&&&&&' for [password, i, j] in genpws pattern, prefixes, suffixes matches = matching.repeat_match password msg = "matches embedded repeat patterns" check_matches msg, t, matches, 'repeat', [pattern], [[i, j]], base_token: ['&'] for length in [3, 12] for chr in ['a', 'Z', '4', '&'] pattern = Array(length + 1).join(chr) matches = matching.repeat_match pattern msg = "matches repeats with base character '#{chr}'" check_matches msg, t, matches, 'repeat', [pattern], [[0, pattern.length - 1]], base_token: [chr] matches = matching.repeat_match 'BBB1111aaaaa@@@@@@' patterns = ['BBB','1111','aaaaa','@@@@@@'] msg = 'matches multiple adjacent repeats' check_matches msg, t, matches, 'repeat', patterns, [[0, 2],[3, 6],[7, 11],[12, 17]], base_token: ['B', '1', 'a', '@'] matches = matching.repeat_match '2818BBBbzsdf1111@*&@!aaaaaEUDA@@@@@@1729' msg = 'matches multiple repeats with non-repeats in-between' check_matches msg, t, matches, 'repeat', patterns, [[4, 6],[12, 15],[21, 25],[30, 35]], base_token: ['B', '1', 'a', '@'] # test multi-character repeats pattern = 'abab' matches = matching.repeat_match pattern msg = 'matches multi-character repeat pattern' check_matches msg, t, matches, 'repeat', [pattern], [[0, pattern.length - 1]], base_token: ['ab'] pattern = 'aabaab' matches = matching.repeat_match pattern msg = 'matches aabaab as a repeat instead of the aa prefix' check_matches msg, t, matches, 'repeat', [pattern], [[0, pattern.length - 1]], base_token: ['aab'] pattern = 'abababab' matches = matching.repeat_match pattern msg = 'identifies ab as repeat string, even though abab is also repeated' check_matches msg, t, matches, 'repeat', [pattern], [[0, pattern.length - 1]], base_token: ['ab'] t.end() test 'regex matching', (t) -> for [pattern, name] in [ ['1922', 'recent_year'] ['2017', 'recent_year'] ] matches = matching.regex_match pattern msg = "matches #{pattern} as a #{name} pattern" check_matches msg, t, matches, 'regex', [pattern], [[0, pattern.length - 1]], regex_name: [name] t.end() test 'date matching', (t) -> for sep in ['', ' ', '-', '/', '\\', '_', '.'] password = "<PASSWORD>" matches = matching.date_match password msg = "matches dates that use '#{sep}' as a separator" check_matches msg, t, matches, 'date', [password], [[0, password.length - 1]], separator: [sep] year: [1921] month: [2] day: [13] for order in ['mdy', 'dmy', 'ymd', 'ydm'] [d,m,y] = [8,8,88] password = order .replace 'y', y .replace 'm', m .replace 'd', d matches = matching.date_match password msg = "matches dates with '#{order}' format" check_matches msg, t, matches, 'date', [password], [[0, password.length - 1]], separator: [''] year: [1988] month: [8] day: [8] password = '<PASSWORD>' matches = matching.date_match password msg = "matches the date with year closest to REFERENCE_YEAR when ambiguous" check_matches msg, t, matches, 'date', [password], [[0, password.length - 1]], separator: [''] year: [2004] # picks '04' -> 2004 as year, not '1504' month: [11] day: [15] for [day, month, year] in [ [1, 1, 1999] [11, 8, 2000] [9, 12, 2005] [22, 11, 1551] ] password = <PASSWORD>}" matches = matching.date_match password msg = "matches #{password}" check_matches msg, t, matches, 'date', [password], [[0, password.length - 1]], separator: [''] year: [year] password = <PASSWORD>}" matches = matching.date_match password msg = "matches #{password}" check_matches msg, t, matches, 'date', [password], [[0, password.length - 1]], separator: ['.'] year: [year] password = "<PASSWORD>" matches = matching.date_match password msg = "matches zero-padded dates" check_matches msg, t, matches, 'date', [password], [[0, password.length - 1]], separator: ['/'] year: [2002] month: [2] day: [2] prefixes = ['a', 'ab'] suffixes = ['!'] pattern = '1/1/91' for [password, i, j] in genpws pattern, prefixes, suffixes matches = matching.date_match password msg = "matches embedded dates" check_matches msg, t, matches, 'date', [pattern], [[i, j]], year: [1991] month: [1] day: [1] matches = matching.date_match '12/20/1991.12.20' msg = "matches overlapping dates" check_matches msg, t, matches, 'date', ['12/20/1991', '1991.12.20'], [[0, 9], [6,15]], separator: ['/', '.'] year: [1991, 1991] month: [12, 12] day: [20, 20] matches = matching.date_match '912/20/919' msg = "matches dates padded by non-ambiguous digits" check_matches msg, t, matches, 'date', ['12/20/91'], [[1, 8]], separator: ['/'] year: [1991] month: [12] day: [20] t.end() test 'omnimatch', (t) -> t.deepEquals matching.omnimatch(''), [], "doesn't match ''" password = '<PASSWORD>' matches = matching.omnimatch password for [pattern_name, [i, j]] in [ [ 'dictionary', [0, 6] ] [ 'dictionary', [7, 15] ] [ 'date', [16, 23] ] [ 'repeat', [24, 27] ] ] included = false for match in matches included = true if match.i == i and match.j == j and match.pattern == pattern_name msg = "for #{password}, matches a #{pattern_name} pattern at [#{i}, #{j}]" t.ok included, msg t.end()
true
test = require 'tape' matching = require '../src/matching' adjacency_graphs = require '../src/adjacency_graphs' # takes a pattern and list of prefixes/suffixes # returns a bunch of variants of that pattern embedded # with each possible prefix/suffix combination, including no prefix/suffix # returns a list of triplets [variant, i, j] where [i,j] is the start/end of the pattern, inclusive genpws = (pattern, prefixes, suffixes) -> prefixes = prefixes.slice() suffixes = suffixes.slice() for lst in [prefixes, suffixes] lst.unshift '' if '' not in lst result = [] for prefix in prefixes for suffix in suffixes [i, j] = [prefix.length, prefix.length + pattern.length - 1] result.push [prefix + pattern + suffix, i, j] result check_matches = (prefix, t, matches, pattern_names, patterns, ijs, props) -> if typeof pattern_names is "string" # shortcut: if checking for a list of the same type of patterns, # allow passing a string 'pat' instead of array ['pat', 'pat', ...] pattern_names = (pattern_names for i in [0...patterns.length]) is_equal_len_args = pattern_names.length == patterns.length == ijs.length for prop, lst of props # props is structured as: keys that points to list of values is_equal_len_args = is_equal_len_args and (lst.length == patterns.length) throw 'unequal argument lists to check_matches' unless is_equal_len_args msg = "#{prefix}: matches.length == #{patterns.length}" t.equal matches.length, patterns.length, msg for k in [0...patterns.length] match = matches[k] pattern_name = pattern_names[k] pattern = patterns[k] [i, j] = ijs[k] msg = "#{prefix}: matches[#{k}].pattern == '#{pattern_name}'" t.equal match.pattern, pattern_name, msg msg = "#{prefix}: matches[#{k}] should have [i, j] of [#{i}, #{j}]" t.deepEqual [match.i, match.j], [i, j], msg msg = "#{prefix}: matches[#{k}].token == '#{pattern}'" t.equal match.token, pattern, msg for prop_name, prop_list of props prop_msg = prop_list[k] prop_msg = "'#{prop_msg}'" if typeof(prop_msg) == 'string' msg = "#{prefix}: matches[#{k}].#{prop_name} == #{prop_msg}" t.deepEqual match[prop_name], prop_list[k], msg test 'matching utils', (t) -> t.ok matching.empty([]), ".empty returns true for an empty array" t.ok matching.empty({}), ".empty returns true for an empty object" for obj in [ [1] [1, 2] [[]] {a: 1} {0: {}} ] t.notOk matching.empty(obj), ".empty returns false for non-empty objects and arrays" lst = [] matching.extend lst, [] t.deepEqual lst, [], "extending an empty list with an empty list leaves it empty" matching.extend lst, [1] t.deepEqual lst, [1], "extending an empty list with another makes it equal to the other" matching.extend lst, [2, 3] t.deepEqual lst, [1, 2, 3], "extending a list with another adds each of the other's elements" [lst1, lst2] = [[1], [2]] matching.extend lst1, lst2 t.deepEqual lst2, [2], "extending a list by another doesn't affect the other" chr_map = {a: 'A', b: 'B'} for [string, map, result] in [ ['a', chr_map, 'A'] ['c', chr_map, 'c'] ['ab', chr_map, 'AB'] ['abc', chr_map, 'ABc'] ['aa', chr_map, 'AA'] ['abab', chr_map, 'ABAB'] ['', chr_map, ''] ['', {}, ''] ['abc', {}, 'abc'] ] msg = "translates '#{string}' to '#{result}' with provided charmap" t.equal matching.translate(string, map), result, msg for [[dividend, divisor], remainder] in [ [[ 0, 1], 0] [[ 1, 1], 0] [[-1, 1], 0] [[ 5, 5], 0] [[ 3, 5], 3] [[-1, 5], 4] [[-5, 5], 0] [[ 6, 5], 1] ] msg = "mod(#{dividend}, #{divisor}) == #{remainder}" t.equal matching.mod(dividend, divisor), remainder, msg t.deepEqual matching.sorted([]), [], "sorting an empty list leaves it empty" [m1, m2, m3, m4, m5, m6] = [ {i: 5, j: 5} {i: 6, j: 7} {i: 2, j: 5} {i: 0, j: 0} {i: 2, j: 3} {i: 0, j: 3} ] msg = "matches are sorted on i index primary, j secondary" t.deepEqual matching.sorted([m1, m2, m3, m4, m5, m6]), [m4, m6, m5, m3, m1, m2], msg t.end() test 'dictionary matching', (t) -> dm = (pw) -> matching.dictionary_match pw, test_dicts test_dicts = d1: motherboard: 1 mother: 2 board: 3 abcd: 4 cdef: 5 d2: # min token length is 3 'zzz': 1 '888': 2 '9999': 3 '$%^': 4 'asdf1234&*': 5 matches = dm 'motherboard' patterns = ['mother', 'motherboard', 'board'] msg = "matches words that contain other words" check_matches msg, t, matches, 'dictionary', patterns, [[0,5], [0,10], [6,10]], matched_word: ['mother', 'motherboard', 'board'] rank: [2, 1, 3] dictionary_name: ['d1', 'd1', 'd1'] matches = dm 'abcdef' patterns = ['abcd', 'cdef'] msg = "matches multiple words when they overlap" check_matches msg, t, matches, 'dictionary', patterns, [[0,3], [2,5]], matched_word: ['abcd', 'cdef'] rank: [4, 5] dictionary_name: ['d1', 'd1'] matches = dm 'BoaRdZzz' patterns = ['BoaRd', 'Zzz'] msg = "ignores uppercasing" check_matches msg, t, matches, 'dictionary', patterns, [[0,4], [5,7]], matched_word: ['board', 'zzz'] rank: [3, 1] dictionary_name: ['d1', 'd2'] prefixes = ['q', '%%'] suffixes = ['%', 'qq'] word = 'asdf1234&*' for [password, i, j] in genpws word, prefixes, suffixes matches = dm password msg = "identifies words surrounded by non-words" check_matches msg, t, matches, 'dictionary', [word], [[i,j]], matched_word: [word] rank: [5] dictionary_name: ['d2'] for name, dict of test_dicts for word, rank of dict continue if word is 'motherboard' # skip words that contain others matches = dm word msg = "matches against all words in provided dictionaries" check_matches msg, t, matches, 'dictionary', [word], [[0, word.length - 1]], matched_word: [word] rank: [rank] dictionary_name: [name] # test the default dictionaries matches = matching.dictionary_match 'wow' patterns = ['wow'] ijs = [[0,2]] msg = "default dictionaries" check_matches msg, t, matches, 'dictionary', patterns, ijs, matched_word: patterns rank: [317] dictionary_name: ['us_tv_and_film'] matching.set_user_input_dictionary ['foo', 'bar'] matches = matching.dictionary_match 'foobar' matches = matches.filter (match) -> match.dictionary_name == 'user_inputs' msg = "matches with provided user input dictionary" check_matches msg, t, matches, 'dictionary', ['foo', 'bar'], [[0, 2], [3, 5]], matched_word: ['foo', 'bar'] rank: [1, 2] t.end() test 'reverse dictionary matching', (t) -> test_dicts = d1: 123: 1 321: 2 456: 3 654: 4 password = 'PI:PASSWORD:<PASSWORD>END_PI' matches = matching.reverse_dictionary_match password, test_dicts msg = 'matches against reversed words' check_matches msg, t, matches, 'dictionary', ['123', '456'], [[1, 3], [4, 6]], matched_word: ['321', '654'] reversed: [true, true] dictionary_name: ['d1', 'd1'] rank: [2, 4] t.end() test 'l33t matching', (t) -> test_table = a: ['4', '@'] c: ['(', '{', '[', '<'] g: ['6', '9'] o: ['0'] for [pw, expected] in [ [ '', {} ] [ 'abcdefgo123578!#$&*)]}>', {} ] [ 'a', {} ] [ '4', {'a': ['4']} ] [ '4@', {'a': ['4','@']} ] [ '4({60', {'a': ['4'], 'c': ['(','{'], 'g': ['6'], 'o': ['0']} ] ] msg = "reduces l33t table to only the substitutions that a password might be employing" t.deepEquals matching.relevant_l33t_subtable(pw, test_table), expected, msg for [table, subs] in [ [ {}, [{}] ] [ {a: ['@']}, [{'@': 'a'}] ] [ {a: ['@','4']}, [{'@': 'a'}, {'4': 'a'}] ] [ {a: ['@','4'], c: ['(']}, [{'@': 'a', '(': 'c' }, {'4': 'a', '(': 'c'}] ] ] msg = "enumerates the different sets of l33t substitutions a password might be using" t.deepEquals matching.enumerate_l33t_subs(table), subs, msg lm = (pw) -> matching.l33t_match pw, dicts, test_table dicts = words: aac: 1 password: PI:PASSWORD:<PASSWORD>END_PI paassword: PI:PASSWORD:<PASSWORD>END_PI asdf0: 5 words2: cgo: 1 t.deepEquals lm(''), [], "doesn't match ''" t.deepEquals lm('password'), [], "doesn't match pure dictionary words" for [password, pattern, word, dictionary_name, rank, ij, sub] in [ [ 'p4ssword', 'p4ssword', 'password', 'words', 3, [0,7], {'4': 'a'} ] [ 'p@ssw0rd', 'p@ssw0rd', 'password', 'words', 3, [0,7], {'@': 'a', '0': 'o'} ] [ 'aSdfO{G0asDfO', '{G0', 'cgo', 'words2', 1, [5, 7], {'{': 'c', '0': 'o'} ] ] msg = "matches against common l33t substitutions" check_matches msg, t, lm(password), 'dictionary', [pattern], [ij], l33t: [true] sub: [sub] matched_word: [word] rank: [rank] dictionary_name: [dictionary_name] matches = lm '@a(go{G0' msg = "matches against overlapping l33t patterns" check_matches msg, t, matches, 'dictionary', ['@a(', '(go', '{G0'], [[0,2], [2,4], [5,7]], l33t: [true, true, true] sub: [{'@': 'a', '(': 'c'}, {'(': 'c'}, {'{': 'c', '0': 'o'}] matched_word: ['aac', 'cgo', 'cgo'] rank: [1, 1, 1] dictionary_name: ['words', 'words2', 'words2'] msg = "doesn't match when multiple l33t substitutions are needed for the same letter" t.deepEqual lm('p4@ssword'), [], msg msg = "doesn't match single-character l33ted words" matches = matching.l33t_match '4 1 @' t.deepEqual matches, [], msg # known issue: subsets of substitutions aren't tried. # for long inputs, trying every subset of every possible substitution could quickly get large, # but there might be a performant way to fix. # (so in this example: {'4': a, '0': 'o'} is detected as a possible sub, # but the subset {'4': 'a'} isn't tried, missing the match for asdf0.) # TODO: consider partially fixing by trying all subsets of size 1 and maybe 2 msg = "doesn't match with subsets of possible l33t substitutions" t.deepEqual lm('4sdf0'), [], msg t.end() test 'spatial matching', (t) -> for password in ['', '/', 'qw', '*/'] msg = "doesn't match 1- and 2-character spatial patterns" t.deepEqual matching.spatial_match(password), [], msg # for testing, make a subgraph that contains a single keyboard _graphs = qwerty: adjacency_graphs.qwerty pattern = '6tfGHJ' matches = matching.spatial_match "rz!#{pattern}%z", _graphs msg = "matches against spatial patterns surrounded by non-spatial patterns" check_matches msg, t, matches, 'spatial', [pattern], [[3, 3 + pattern.length - 1]], graph: ['qwerty'] turns: [2] shifted_count: [3] for [pattern, keyboard, turns, shifts] in [ [ '12345', 'qwerty', 1, 0 ] [ '@WSX', 'qwerty', 1, 4 ] [ '6tfGHJ', 'qwerty', 2, 3 ] [ 'hGFd', 'qwerty', 1, 2 ] [ '/;p09876yhn', 'qwerty', 3, 0 ] [ 'Xdr%', 'qwerty', 1, 2 ] [ '159-', 'keypad', 1, 0 ] [ '*84', 'keypad', 1, 0 ] [ '/8520', 'keypad', 1, 0 ] [ '369', 'keypad', 1, 0 ] [ '/963.', 'mac_keypad', 1, 0 ] [ '*-632.0214', 'mac_keypad', 9, 0 ] [ 'aoEP%yIxkjq:', 'dvorak', 4, 5 ] [ ';qoaOQ:Aoq;a', 'dvorak', 11, 4 ] ] _graphs = {} _graphs[keyboard] = adjacency_graphs[keyboard] matches = matching.spatial_match pattern, _graphs msg = "matches '#{pattern}' as a #{keyboard} pattern" check_matches msg, t, matches, 'spatial', [pattern], [[0, pattern.length - 1]], graph: [keyboard] turns: [turns] shifted_count: [shifts] t.end() test 'sequence matching', (t) -> for password in ['', 'PI:PASSWORD:<PASSWORD>END_PI', 'PI:PASSWORD:<PASSWORD>END_PI'] msg = "doesn't match length-#{password.length} sequences" t.deepEqual matching.sequence_match(password), [], msg matches = matching.sequence_match 'abcbabc' msg = "matches overlapping patterns" check_matches msg, t, matches, 'sequence', ['abc', 'cba', 'abc'], [[0, 2], [2, 4], [4, 6]], ascending: [true, false, true] prefixes = ['!', '22'] suffixes = ['!', '22'] pattern = 'jihg' for [password, i, j] in genpws pattern, prefixes, suffixes matches = matching.sequence_match password msg = "matches embedded sequence patterns #{password}" check_matches msg, t, matches, 'sequence', [pattern], [[i, j]], sequence_name: ['lower'] ascending: [false] for [pattern, name, is_ascending] in [ ['ABC', 'upper', true] ['CBA', 'upper', false] ['PQR', 'upper', true] ['RQP', 'upper', false] ['XYZ', 'upper', true] ['ZYX', 'upper', false] ['abcd', 'lower', true] ['dcba', 'lower', false] ['jihg', 'lower', false] ['wxyz', 'lower', true] ['zxvt', 'lower', false] ['0369', 'digits', true] ['97531', 'digits', false] ] matches = matching.sequence_match pattern msg = "matches '#{pattern}' as a '#{name}' sequence" check_matches msg, t, matches, 'sequence', [pattern], [[0, pattern.length - 1]], sequence_name: [name] ascending: [is_ascending] t.end() test 'repeat matching', (t) -> for password in ['', '#'] msg = "doesn't match length-#{password.length} repeat patterns" t.deepEqual matching.repeat_match(password), [], msg # test single-character repeats prefixes = ['@', 'y4@'] suffixes = ['u', 'u%7'] pattern = '&&&&&' for [password, i, j] in genpws pattern, prefixes, suffixes matches = matching.repeat_match password msg = "matches embedded repeat patterns" check_matches msg, t, matches, 'repeat', [pattern], [[i, j]], base_token: ['&'] for length in [3, 12] for chr in ['a', 'Z', '4', '&'] pattern = Array(length + 1).join(chr) matches = matching.repeat_match pattern msg = "matches repeats with base character '#{chr}'" check_matches msg, t, matches, 'repeat', [pattern], [[0, pattern.length - 1]], base_token: [chr] matches = matching.repeat_match 'BBB1111aaaaa@@@@@@' patterns = ['BBB','1111','aaaaa','@@@@@@'] msg = 'matches multiple adjacent repeats' check_matches msg, t, matches, 'repeat', patterns, [[0, 2],[3, 6],[7, 11],[12, 17]], base_token: ['B', '1', 'a', '@'] matches = matching.repeat_match '2818BBBbzsdf1111@*&@!aaaaaEUDA@@@@@@1729' msg = 'matches multiple repeats with non-repeats in-between' check_matches msg, t, matches, 'repeat', patterns, [[4, 6],[12, 15],[21, 25],[30, 35]], base_token: ['B', '1', 'a', '@'] # test multi-character repeats pattern = 'abab' matches = matching.repeat_match pattern msg = 'matches multi-character repeat pattern' check_matches msg, t, matches, 'repeat', [pattern], [[0, pattern.length - 1]], base_token: ['ab'] pattern = 'aabaab' matches = matching.repeat_match pattern msg = 'matches aabaab as a repeat instead of the aa prefix' check_matches msg, t, matches, 'repeat', [pattern], [[0, pattern.length - 1]], base_token: ['aab'] pattern = 'abababab' matches = matching.repeat_match pattern msg = 'identifies ab as repeat string, even though abab is also repeated' check_matches msg, t, matches, 'repeat', [pattern], [[0, pattern.length - 1]], base_token: ['ab'] t.end() test 'regex matching', (t) -> for [pattern, name] in [ ['1922', 'recent_year'] ['2017', 'recent_year'] ] matches = matching.regex_match pattern msg = "matches #{pattern} as a #{name} pattern" check_matches msg, t, matches, 'regex', [pattern], [[0, pattern.length - 1]], regex_name: [name] t.end() test 'date matching', (t) -> for sep in ['', ' ', '-', '/', '\\', '_', '.'] password = "PI:PASSWORD:<PASSWORD>END_PI" matches = matching.date_match password msg = "matches dates that use '#{sep}' as a separator" check_matches msg, t, matches, 'date', [password], [[0, password.length - 1]], separator: [sep] year: [1921] month: [2] day: [13] for order in ['mdy', 'dmy', 'ymd', 'ydm'] [d,m,y] = [8,8,88] password = order .replace 'y', y .replace 'm', m .replace 'd', d matches = matching.date_match password msg = "matches dates with '#{order}' format" check_matches msg, t, matches, 'date', [password], [[0, password.length - 1]], separator: [''] year: [1988] month: [8] day: [8] password = 'PI:PASSWORD:<PASSWORD>END_PI' matches = matching.date_match password msg = "matches the date with year closest to REFERENCE_YEAR when ambiguous" check_matches msg, t, matches, 'date', [password], [[0, password.length - 1]], separator: [''] year: [2004] # picks '04' -> 2004 as year, not '1504' month: [11] day: [15] for [day, month, year] in [ [1, 1, 1999] [11, 8, 2000] [9, 12, 2005] [22, 11, 1551] ] password = PI:PASSWORD:<PASSWORD>END_PI}" matches = matching.date_match password msg = "matches #{password}" check_matches msg, t, matches, 'date', [password], [[0, password.length - 1]], separator: [''] year: [year] password = PI:PASSWORD:<PASSWORD>END_PI}" matches = matching.date_match password msg = "matches #{password}" check_matches msg, t, matches, 'date', [password], [[0, password.length - 1]], separator: ['.'] year: [year] password = "PI:PASSWORD:<PASSWORD>END_PI" matches = matching.date_match password msg = "matches zero-padded dates" check_matches msg, t, matches, 'date', [password], [[0, password.length - 1]], separator: ['/'] year: [2002] month: [2] day: [2] prefixes = ['a', 'ab'] suffixes = ['!'] pattern = '1/1/91' for [password, i, j] in genpws pattern, prefixes, suffixes matches = matching.date_match password msg = "matches embedded dates" check_matches msg, t, matches, 'date', [pattern], [[i, j]], year: [1991] month: [1] day: [1] matches = matching.date_match '12/20/1991.12.20' msg = "matches overlapping dates" check_matches msg, t, matches, 'date', ['12/20/1991', '1991.12.20'], [[0, 9], [6,15]], separator: ['/', '.'] year: [1991, 1991] month: [12, 12] day: [20, 20] matches = matching.date_match '912/20/919' msg = "matches dates padded by non-ambiguous digits" check_matches msg, t, matches, 'date', ['12/20/91'], [[1, 8]], separator: ['/'] year: [1991] month: [12] day: [20] t.end() test 'omnimatch', (t) -> t.deepEquals matching.omnimatch(''), [], "doesn't match ''" password = 'PI:PASSWORD:<PASSWORD>END_PI' matches = matching.omnimatch password for [pattern_name, [i, j]] in [ [ 'dictionary', [0, 6] ] [ 'dictionary', [7, 15] ] [ 'date', [16, 23] ] [ 'repeat', [24, 27] ] ] included = false for match in matches included = true if match.i == i and match.j == j and match.pattern == pattern_name msg = "for #{password}, matches a #{pattern_name} pattern at [#{i}, #{j}]" t.ok included, msg t.end()
[ { "context": "': (event) => @archiveToClipboard(event) }))\n #@subscriptions.add(atom.commands.add('atom-text-edi", "end": 7446, "score": 0.5765600800514221, "start": 7446, "tag": "EMAIL", "value": "" }, { "context": "@archiveToClipboard(event) }))\n #@subscriptions.add(atom.co...
lib/organized.coffee
brvier/organized
137
{CompositeDisposable, Directory, Point} = require 'atom' fs = require 'fs' {dialog} = require('electron') moment = require 'moment' CodeBlock = require './codeblock' #GoogleCalendar = require './google-calendar' OrganizedToolbar = require './toolbar' OrganizedView = require './organized-view' SidebarView = require './sidebar-view' Star = require './star' Table = require './table' Todo = require './sidebar-items' module.exports = organizedView: null modalPanel: null subscriptions: null levelStyle: 'spaces' indentSpaces: 2 createStarsOnEnter: true autoSizeTables: true organizedToolbar: null useBracketsAroundTodoTags: true trackCloseTimeOfTodos: true defaultVisibilityCycle: 'hide-none' config: levelStyle: title: 'Level Style' description: 'If you indent a star/bullet point, how should it be indented by default?' type: 'string' default: 'whitespace' enum: [ {value: 'whitespace', description: 'Sublevels are created by putting spaces or tabs (based on your editor tabType setting) in front of the stars'} {value: 'stacked', description: 'Sublevels are created using multiple stars. For example, level three of the outline would start with ***'} ] autoCreateStarsOnEnter: type: 'boolean' default: true useBracketsAroundTodoTags: type: 'boolean' default: true description: "When created TODO or DONE tags, prefer [TODO] over TODO and [DONE] over DONE" trackCloseTimeOfTodos: type: 'boolean' default: true description: "When transitioning from TODO to DONE record a CLOSED time" defaultVisibilityCycle: title: 'Default Org-File Visibility' description: 'Which part of the file will be visible on load' type: 'string' default: 'hide-none' enum: [ {value: 'hide-all', description: 'Only show the top-level bullets in a file'} {value: 'hide-bottom', description: 'Show first and second leve bullets in a file'} {value: 'hide-none', description: 'Show all information in the file'} ] autoSizeTables: type: 'boolean' default: false description: "(Not Ready for Prime Time) If you are typing in a table, automatically resize the columns so your text fits." enableToolbarSupport: type: 'boolean' default: true description: "Show a toolbar using the tool-bar package if that package is installed" searchDirectories: type: 'array' title: 'Predefined search directories / files' description: 'Directories and/or files where we will look for organized files when building todo lists, agendas, or searching. Separate multiple files or directories with a comma' default: ['','','','',''] items: type: 'string' includeProjectPathsInSearchDirectories: type: 'boolean' default: true description: 'Indicates whether we should include the paths for the current project in the search directories' searchSkipFiles: type: 'array' title: 'Organized Partial File Names to Skip' description: 'A list of partial file names to skip' default: ['', '', '', '', ''] items: type: 'string' sidebarVisible: type: 'boolean' title: "Show Sidebar" description: "Sidebar is currently being shown" default: false activate: (state) -> atom.themes.requireStylesheet(require.resolve('../styles/organized.less')); @organizedView = new OrganizedView(state.organizedViewState) @modalPanel = atom.workspace.addModalPanel({ item: @organizedView.getElement(), visible: false }) @subscriptions = new CompositeDisposable() # Set up text editors @subscriptions.add atom.workspace.observeTextEditors (editor) => @handleEvents(editor) @subscriptions.add editor.onDidSave => if @sidebar and @sidebar.sidebarVisible and editor.getGrammar().name is 'Organized' @sidebar.refreshAll() # Register command that toggles this view @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:indent': (event) => @indent(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:unindent': (event) => @unindent(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:setTodo': (event) => @setTodo(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:setTodoCompleted': (event) => @setTodoCompleted(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:toggleTodo': (event) => @toggleTodo(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:newLine': (event) => @newLine(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:newStarLine': (event) => @newStarLine(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:createTable': (event) => @createTable(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:newTableRow': (event) => @newTableRow(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:closeTable': (event) => @closeTable(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:openTable': (event) => @openTable(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:insertDate': (event) => @insert8601Date(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:insertDateTime': (event) => @insert8601DateTime(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:executeCodeBlock': (event) => @executeCodeBlock(event) })) #@subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:encryptBuffer': (event) => @encryptBuffer(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:toggleBold': (event) => @toggleBold(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:toggleUnderline': (event) => @toggleUnderline(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:toggleHeading': (event) => @toggleHeading(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:makeCodeBlock': (event) => @makeCodeBlock(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:makeResultBlock': (event) => @makeResultBlock(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:makeLink': (event) => @makeLink(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:refreshTodos': (event) => @sidebar.refreshTodos() })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:refreshAgenda': (event) => @sidebar.refreshAgendaItems() })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:scheduleItem': (event) => @scheduleItem(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:deadlineItem': (event) => @deadlineItem(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:archiveSubtree': (event) => @archiveSubtree(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:archiveToClipboard': (event) => @archiveToClipboard(event) })) #@subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:importTodaysEvents': (event) => GoogleCalendar.importTodaysEvents() })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:increasePriority': (event) => @increasePriority(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:decreasePriority': (event) => @decreasePriority(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:cycleVisibility': (event) => @cycleVisibility(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:cycleGlobalVisibility': (event) => @cycleGlobalVisibility(event) })) @subscriptions.add atom.config.observe 'organized.autoCreateStarsOnEnter', (newValue) => @createStarsOnEnter = newValue @subscriptions.add atom.config.observe 'organized.levelStyle', (newValue) => @levelStyle = newValue @subscriptions.add atom.config.observe 'organized.autoSizeTables', (newValue) => @autoSizeTables = newValue @subscriptions.add atom.config.observe 'editor.tabLength', (newValue) => @indentSpaces = newValue @subscriptions.add atom.config.observe 'organized.useBracketsAroundTodoTags', (newValue) => @useBracketsAroundTodoTags = newValue @subscriptions.add atom.config.observe 'organized.trackCloseTimeOfTodos', (newValue) => @trackCloseTimeOfTodos = newValue @subscriptions.add atom.config.observe 'organized.defaultVisibilityCycle', (newValue) => @defaultVisibilityCycle = newValue @sidebar = new SidebarView() @sidebar.activate(@subscriptions) if not @organizedToolbar @organizedToolbar = new OrganizedToolbar() @organizedToolbar.activate(@subscriptions) @organizedToolbar.setSidebar(@sidebar) editor = atom.workspace.getActiveTextEditor() if editor and editor.getGrammar().name is 'Organized' if @defaultVisibilityCycle is 'hide-all' @cycleGlobalVisibility(null) else if @defaultVisibilityCycle is 'hide-bottom' # Doing this twice is messy. We should fix this later @cycleGlobalVisibility(null) @cycleGlobalVisibility(null) archiveSubtree: (event) -> @_archiveSubtree(false) archiveToClipboard: (event) -> archiveText = @_archiveSubtree(true) atom.clipboard.write(archiveText) closeTable: (event) -> if editor = atom.workspace.getActiveTextEditor() position = editor.getCursorBufferPosition() editor.transact 1000, () -> # See if we are on an editor line. If so, the close will be on the next line line = editor.lineTextForBufferRow(position.row) if 'border.table.organized' in editor.scopeDescriptorForBufferPosition(position).getScopesArray() editor.insertNewline() else line = editor.lineTextForBufferRow(position.row-1) editor.setTextInBufferRange([[position.row, 0], [position.row, position.column]], "") startMatch = /^(\s*)[\|\+]/.exec(line) endMatch = /[\|\+](\s*$)/.exec(line) if startMatch and endMatch # console.log("startMatch: #{startMatch}, endMatch: #{endMatch}") dashCount = endMatch.index-startMatch.index-startMatch[0].length editor.insertText("+#{'-'.repeat(dashCount)}+") # Callback from tool-bar to create a toolbar consumeToolBar: (toolBar) -> if not @organizedToolbar @organizedToolbar = new OrganizedToolbar() @organizedToolbar.activate(@subscriptions) @organizedToolbar.setSidebar(@sidebar) @organizedToolbar.consumeToolBar(toolBar) # Create a skeleton of a table ready for a user to start typing in it. createTable: (event) -> if editor = atom.workspace.getActiveTextEditor() position = editor.getCursorBufferPosition() editor.transact 1000, () => if not editor.lineTextForBufferRow(position.row).match(/\s*/) editor.insertNewline() editor.insertText("+----+") editor.insertNewline() editor.insertText("| ") position = editor.getCursorBufferPosition() editor.insertNewline() editor.insertText("+----+") editor.setCursorBufferPosition(position) cycleGlobalVisibility: (event) -> if editor = atom.workspace.getActiveTextEditor() @_cycleVisibility(editor, 0, editor.getLastBufferRow()) cycleVisibility: (event) -> if editor = atom.workspace.getActiveTextEditor() position = editor.getCursorBufferPosition() startRow = position.row if startStar = @_starInfo(editor, position) lastRow = startStar.getEndOfSubtree() @_cycleVisibility(editor, startRow, lastRow) deactivate: () -> @organizedToolbar.deactivate() @modalPanel.destroy() @subscriptions.dispose() @organizedView.destroy() deadlineItem: (event) -> @_addMarkerDate("DEADLINE") decreasePriority: () -> @_changePriority(false) executeCodeBlock: () -> if editor = atom.workspace.getActiveTextEditor() if position = editor.getCursorBufferPosition() codeblock = new CodeBlock(position.row) codeblock.execute() else atom.notifications.error("Unable to find code block") handleEvents: (editor) -> tableChangeSubscription = editor.onDidChange (event) => @tableChange(event) tableStoppedChangingSub = editor.onDidStopChanging (event) => @tableStoppedChanging(event) editorDestroySubscription = editor.onDidDestroy => tableStoppedChangingSub.dispose() # @subscriptions.add(tableChangeSubscription) @subscriptions.add(tableStoppedChangingSub) @subscriptions.add(editorDestroySubscription) increasePriority: () -> @_changePriority(true) indent: (event) -> if editor = atom.workspace.getActiveTextEditor() visited = {} editor.transact 2000, () => @_withAllSelectedLines editor, (position, selection) => if visited[position.row] return if star = @_starInfo(editor, position) for i in [star.startRow..star.endRow] visited[i] = true indent = if star.indentType is "stacked" then star.starType else @_indentChars() for row in [star.startRow..star.endRow] editor.setTextInBufferRange([[row, 0], [row, 0]], indent) else editor.indentSelectedRows() insert8601Date: (event) -> d = new Date() editor = atom.workspace.getActiveTextEditor() editor.insertText(@_getISO8601Date(d)) insert8601DateTime: (event) -> d = new Date() editor = atom.workspace.getActiveTextEditor() editor.insertText(@_getISO8601Date(d) + "T" + @_getISO8601Time(d)) makeCodeBlock: (event) -> if editor = atom.workspace.getActiveTextEditor() position = editor.getCursorBufferPosition() editor.transact 1000, () => if not editor.lineTextForBufferRow(position.row).match(/\s*/) editor.insertNewline() editor.insertText('```') endPosition = editor.getCursorBufferPosition() editor.insertNewline() editor.insertText('```') editor.setCursorBufferPosition(endPosition) makeResultBlock: (event) -> if editor = atom.workspace.getActiveTextEditor() position = editor.getCursorBufferPosition() editor.transact 1000, () => if not editor.lineTextForBufferRow(position.row).match(/\s*/) editor.insertNewline() editor.insertText('```result') editor.insertNewline() editor.insertText('```') makeLink: (event) -> if editor = atom.workspace.getActiveTextEditor() editor.transact 1000, () => @_withAllSelectedLines editor, (position, selection) => if selection.isEmpty() editor.insertText("[]()") selection.cursor.moveLeft(3) else range = selection.getBufferRange() if selection.getText().match(/^https?:\/\//) editor.setTextInBufferRange([range.end, range.end], ")") editor.setTextInBufferRange([range.start, range.start], "[](") else editor.setTextInBufferRange([range.end, range.end], "]()") editor.setTextInBufferRange([range.start, range.start], "[") # Respond to someone pressing enter. # There's some special handling here. The auto-intent that's built into atom does a good job, but I want the # new text to be even with the start of the text, not the start of the star. newLine: (event) -> if editor = atom.workspace.getActiveTextEditor() if star = @_starInfo() editor.transact 1000, () => editor.insertNewline() spaceCount = star.startTodoCol - star.starCol indent = @_levelWhitespace(star, editor).repeat(star.indentLevel) + " ".repeat(spaceCount) # console.log("spaceCount: #{spaceCount}, indentLevel: #{star.indentLevel}, levelWhiteSpace='#{@_levelWhitespace(star, editor)}'") newPosition = editor.getCursorBufferPosition() editor.transact 1000, () => editor.setTextInBufferRange([[newPosition.row, 0],[newPosition.row, newPosition.column]], indent) editor.setCursorBufferPosition([newPosition.row, indent.length]) else editor.insertNewline() newStarLine: (event) -> if editor = atom.workspace.getActiveTextEditor() # Bail out if the user didn't want any special behavior if !@createStarsOnEnter editor.insertNewline() return # If a user hits return and they haven't really done anything on this line, # treat it like an unindent. It seems awkward to add another empty one. oldPosition = editor.getCursorBufferPosition() line = editor.lineTextForBufferRow(oldPosition.row) if line.match(/([\*\-\+]|\d+\.|[A-z]\.) $/) @unindent() return # If the previous line was entirely empty, it seems like the outline is kind # of "done". Don't try to restart it yet. if line.match(/^\s*$/) editor.insertNewline() return # Make sure we aren't in the middle of a codeblock row = oldPosition.row line = editor.lineTextForBufferRow(row) star = @_starInfo() minRow = if star then star.startRow else 0 while row > minRow and not line.match(/^\s*```/) row -= 1 line = editor.lineTextForBufferRow(row) if line.match(/^\s*```/) # Just add a newline, we're in the middle of a code block editor.insertNewline() return # Figure out where we were so we can use it to figure out where to put the star # and what kind of star to use # Really hit return now editor.transact 1000, () => # If there is a star on the next line, we'll use it's insert level and bullet type # We'll keep a reference to the old star because we need it sometimes oldStar = star if oldPosition.row+1 <= editor.getLastBufferRow() if nextStar = @_starInfo(editor, new Point(oldPosition.row+1, oldPosition.col)) if not star or nextStar.indentLevel > star.indentLevel star = nextStar if star and star.indentLevel >= 0 editor.insertNewline() if oldPosition.column <= star.starCol # If the cursor on a column before the star on the line, just insert a newline return #Create our new text to insert newPosition = editor.getCursorBufferPosition() if star.starType is 'numbers' # Make sure we use a reference to the old star here so we get the editor.setTextInBufferRange([[newPosition.row, 0], [newPosition.row, Infinity]], oldStar.newStarLine()) position = new Point(newPosition.row+1, 0) #console.log("newPosition+1: #{position}, last buffer row: #{editor.getLastBufferRow()}") while position.row <= editor.getLastBufferRow() and nextStar = @_starInfo(editor, position) if nextStar.starType isnt 'numbers' or nextStar.indentLevel isnt star.indentLevel break #console.log("Position: #{position}, nextStar.startRow: #{nextStar.startRow}, nextStar.endRow: #{nextStar.endRow}") #console.log("Replacing #{nextStar.currentNumber} with #{nextStar.nextNumber}") editor.setTextInBufferRange([[nextStar.startRow, nextStar.starCol], [nextStar.startRow, nextStar.starCol+(""+nextStar.currentNumber).length]], "" + nextStar.nextNumber) position = new Point(nextStar.endRow+1, 0) else if star.starType is 'letters' # Make sure we use a reference to the old star here so we get the editor.setTextInBufferRange([[newPosition.row, 0], [newPosition.row, Infinity]], oldStar.newStarLine()) position = new Point(newPosition.row+1, 0) #console.log("newPosition+1: #{position}, last buffer row: #{editor.getLastBufferRow()}") while position.row <= editor.getLastBufferRow() and nextStar = @_starInfo(editor, position) if nextStar.starType isnt 'letters' or nextStar.indentLevel isnt star.indentLevel break #console.log("Position: #{position}, nextStar.startRow: #{nextStar.startRow}, nextStar.endRow: #{nextStar.endRow}") #console.log("Replacing #{nextStar.currentNumber} with #{nextStar.nextNumber}") editor.setTextInBufferRange([[nextStar.startRow, nextStar.starCol], [nextStar.startRow, nextStar.starCol+(""+nextStar.currentLetter).length]], "" + nextStar.nextLetter) position = new Point(nextStar.endRow+1, 0) else indent = star.newStarLine() editor.transact 1000, () => editor.setTextInBufferRange([[newPosition.row, 0],[newPosition.row, newPosition.column]], indent) editor.setCursorBufferPosition([newPosition.row, indent.length]) else editor.insertNewline() newTableRow: () -> if editor = atom.workspace.getActiveTextEditor() oldPosition = editor.getCursorBufferPosition() line = editor.lineTextForBufferRow(oldPosition.row) if match = line.match(/^\s*(\|[ ]?)/) editor.transact 1000, () -> editor.insertNewline() editor.insertText(match[0]) else editor.insertNewline() openTable: (event) -> if editor = atom.workspace.getActiveTextEditor() currentPosition = editor.getCursorBufferPosition() line = editor.lineTextForBufferRow(currentPosition.row) if match = line.match(/^(\s*)/) editor.insertText("+----+\n#{match[0]}| ") serialize: () -> return { organizedViewState: @organizedView.serialize() } scheduleItem: (event) -> @_addMarkerDate("SCHEDULED") setTodo: (event) -> if editor = atom.workspace.getActiveTextEditor() visited = {} startPosition = editor.getCursorBufferPosition() startRow = startPosition.row @_withAllSelectedLines editor, (position, selection) => if visited[position.row] return if star = @_starInfo(editor, position) for i in [star.startRow..star.endRow] visited[i] = true line = editor.lineTextForBufferRow(star.startRow) editor.setTextInBufferRange([[star.startRow, star.startTodoCol], [star.startRow, star.startTextCol]], " [TODO] ") setTodoCompleted: (event) -> if editor = atom.workspace.getActiveTextEditor() visited = {} startPosition = editor.getCursorBufferPosition() startRow = startPosition.row @_withAllSelectedLines editor, (position, selection) => if visited[position.row] return if star = @_starInfo(editor, position) for i in [star.startRow..star.endRow] visited[i] = true line = editor.lineTextForBufferRow(star.startRow) editor.setTextInBufferRange([[star.startRow, star.whitespaceCol], [star.startRow, star.startTextCol]], " [DONE] ") tableChange: (event) -> if not @autoSizeTables return if editor = atom.workspace.getActiveTextEditor() scopes = editor.getLastCursor().getScopeDescriptor().getScopesArray() if 'row.table.organized' in scopes or 'border.table.organized' in scopes table = new Table(editor) return unless table.found? # Getting closer, but not there yet. #table.normalizeRowSizes() tableStoppedChanging: (event) -> return unless @autoSizeTables # if editor = atom.workspace.getActiveTextEditor() # scopes = editor.getLastCursor().getScopeDescriptor().getScopesArray() # if 'row.table.organized' in scopes or 'border.table.organized' in scopes # console.log("Stopped changing") toggleBold: (event) -> if editor = atom.workspace.getActiveTextEditor() editor.transact 1000, () => @_withAllSelectedLines editor, (position, selection) => if selection.isEmpty() editor.insertText("____") selection.cursor.moveLeft(2) else range = selection.getBufferRange() startMarked = editor.getTextInBufferRange([range.start, [range.start.row, range.start.column+2]]) is "__" endMarked = editor.getTextInBufferRange([[range.end.row, range.end.column-2], range.end]) is "__" if startMarked and endMarked editor.setTextInBufferRange([[range.end.row, range.end.column-2], range.end], "") editor.setTextInBufferRange([range.start, [range.start.row, range.start.column+2]], "") else editor.setTextInBufferRange([range.end, range.end], '__') editor.setTextInBufferRange([range.start, range.start], "__") toggleHeading: (event) -> if editor = atom.workspace.getActiveTextEditor() editor.transact 1000, () => @_withAllSelectedLines editor, (position, selection) => startChars = editor.getTextInBufferRange([[position.row, 0], [position.row, 4]]) hashCount = 0 hashCount +=1 until startChars[hashCount] isnt '#' if hashCount is 0 editor.setTextInBufferRange([[position.row, 0], [position.row, 0]], '# ') else if hashCount < 3 editor.setTextInBufferRange([[position.row, 0], [position.row, 0]], '#') else charsToDelete = if startChars[3] is ' ' then 4 else 3 editor.setTextInBufferRange([[position.row, 0], [position.row, charsToDelete]], '') toggleTodo: (event) -> if editor = atom.workspace.getActiveTextEditor() visited = {} startPosition = editor.getCursorBufferPosition() startRow = startPosition.row @_withAllSelectedLines editor, (position, selection) => if visited[position.row] return if star = @_starInfo(editor, position) for i in [star.startRow..star.endRow] visited[i] = true line = editor.lineTextForBufferRow(star.startRow) if match = line.match(/\s*([\-\+\*]+|\d+\.|[A-z]\.) (\[(TODO)\]|TODO) /) replacement = if match[2].includes('[') then " [DONE] " else " DONE " editor.transact 1000, () => editor.setTextInBufferRange([[star.startRow, star.whitespaceCol], [star.startRow, star.startTextCol]], replacement) if @trackCloseTimeOfTodos d = new Date() closeText = "CLOSED: [#{@_getISO8601DateTime(d)}]" line = editor.lineTextForBufferRow(star.startRow+1) if line and line.indexOf("SCHEDULED: <") > -1 editor.setTextInBufferRange([[star.startRow+1, star.startTodoCol], [star.startRow+1, star.startTodoCol]], closeText + " ") else spaceCount = star.startTodoCol - star.starCol indent = @_levelWhitespace(star, editor).repeat(star.indentLevel) + " ".repeat(spaceCount) closeText = "\n" + indent + closeText + "\n" editor.setTextInBufferRange([[star.startRow, Infinity],[star.startRow+1, 0]], closeText) else if (line.match(/\s*([\-\+\*]+|\d+.|[A-z]\.) ((\[(COMPLETED|DONE)\])|(COMPLETED|DONE)) /)) editor.transact 1000, () => editor.setTextInBufferRange([[star.startRow, star.whitespaceCol], [star.startRow, star.startTextCol]], " ") line = editor.lineTextForBufferRow(star.startRow+1) if line if match = line.match(/^\s*CLOSED: \[[^\]]+\]\s*$/) editor.setTextInBufferRange([[star.startRow, Infinity], [star.startRow+1, Infinity]], "") else line = line.replace(/CLOSED: \[[^\]]+\]\s*/, "") editor.setTextInBufferRange([[star.startRow+1, 0], [star.startRow+1, Infinity]], line) else replacement = if @useBracketsAroundTodoTags then " [TODO] " else " TODO " editor.setTextInBufferRange([[star.startRow, star.whitespaceCol], [star.startRow, star.startTextCol]], replacement) toggleUnderline: (event) -> if editor = atom.workspace.getActiveTextEditor() editor.transact 1000, () => @_withAllSelectedLines editor, (position, selection) => if selection.isEmpty() editor.insertText('__') selection.cursor.moveLeft(1) else range = selection.getBufferRange() startThree = editor.getTextInBufferRange([range.start, [range.start.row, range.start.column+3]]) endThree = editor.getTextInBufferRange([[range.end.row, range.end.column-3], range.end]) # Need to consider situations where there is a bold and an underline startMatch = startThree.match(/(_[^_][^_]|___)/) endMatch = endThree.match(/([^_][^_]_|___)/) if startMatch and endMatch editor.setTextInBufferRange([[range.end.row, range.end.column-1], range.end], "") editor.setTextInBufferRange([range.start, [range.start.row, range.start.column+1]], "") else editor.setTextInBufferRange([range.end, range.end], '_') editor.setTextInBufferRange([range.start, range.start], "_") unindent: (event) -> if editor = atom.workspace.getActiveTextEditor() visited = {} editor.transact 2000, () => @_withAllSelectedLines editor, (position, selection) => if visited[position.row] return if star = @_starInfo(editor, position) for i in [star.startRow..star.endRow] visited[i] = true firstRow = star.startRow lastRow = star.endRow #Unindent editor.transact 1000, () -> for row in [firstRow..lastRow] line = editor.lineTextForBufferRow(row) if not line continue else if line.match("^ ") editor.setTextInBufferRange([[row, 0], [row, 2]], "") else if line.match("^\\t") editor.setTextInBufferRange([[row, 0], [row, 1]], "") else if match = line.match(/^([\*\-\+]|\d+\.|[A-z]\.) /) editor.setTextInBufferRange([[row, 0], [row, match[0].length]], "") else if line.match(/^[\*\-\+]/) #Stacked editor.setTextInBufferRange([[row, 0], [row, 1]], "") else #cannot unindent - not sure how to do so else editor.outdentSelectedRows() _addMarkerDate: (dateType) -> if editor = atom.workspace.getActiveTextEditor() visited = {} d = new Date() df = new Intl.DateTimeFormat('en-US', {weekday: 'short'}) dow = df.format(d) @_withAllSelectedLines editor, (position, selection) => if visited[position.row] return if star = @_starInfo(editor, position) for i in [star.startRow..star.endRow] visited[i] = true editor.transact 1000, () => originalPosition = editor.getCursorBufferPosition() # Now add the marker newText = "\n" + " ".repeat(star.startTodoCol) + "#{dateType}: <#{@_getISO8601Date(d)} #{dow}>" col = editor.lineTextForBufferRow(star.startRow).length editor.setTextInBufferRange([[star.startRow, col+1], [star.startRow, col+1]], newText) _archiveFinishedInSubtree: (outputToString) -> if editor = atom.workspace.getActiveTextEditor() visited = {} linesToArchive = [] if not star = @_starInfo(editor, position) return startIndentLevel = star.indentLevel currentLine = star.lineTextForBufferRow() _archiveSubtree: (outputToString) -> if editor = atom.workspace.getActiveTextEditor() visited = {} baseArchiveLevel = null stars = [] # If there are multiple selections, this could span multiple subtrees. Calculate # the total size of the tree first. One possible problem is that we aren't going # to have properties for each of the subtrees when we archive. @_withAllSelectedLines editor, (position, selection) => if visited[position.row] return # Mark all lines in subtree as visited visited[position.row] = true if not star = @_starInfo(editor, position) return # Capture the first star, so we know how deeply to indent the properties if not baseArchiveLevel baseArchiveLevel = star.indentLevel if star.indentLevel == baseArchiveLevel # We need to put properties on this level too, otherwise we won't be able to unarchive it. stars.push(star) endOfSubtree = star.getEndOfSubtree() for line in [star.startRow..endOfSubtree] visited[line] = true # Now act on those lines editor.transact 2000, () => textToInsertIntoArchiveFile = "" rangeToDelete = null # Iterate backwards so we don't change the line number of stars. # Collect the text to delete and the ranges that we are deleting. for star in stars by -1 startOfSubtree = star.startRow endOfSubtree = star.getEndOfSubtree() startTodoCol = star.startTodoCol # Be careful to support selecting out of the end of a file if endOfSubtree == editor.getLastBufferRow() lastCol = editor.lineTextForBufferRow(endOfSubtree).length else endOfSubtree += 1 lastCol = 0 archiveText = editor.lineTextForBufferRow(startOfSubtree) + '\n' archiveText += ' '.repeat(startTodoCol) + ':PROPERTIES:' + '\n' archiveText += ' '.repeat(startTodoCol) + ':ARCHIVE_TIME: ' + moment().format('YYYY-MM-DD ddd HH:mm') + '\n' if path = editor.getPath() archiveText += ' '.repeat(startTodoCol) + ':ARCHIVE_FILE: ' + path + "\n" archiveText += ' '.repeat(startTodoCol) + ':END:' + "\n" # If end is the same as the beginning, we've already gotten all of the text if endOfSubtree > startOfSubtree archiveText += editor.getTextInBufferRange([[startOfSubtree+1, 0], [endOfSubtree, lastCol]]) if textToInsertIntoArchiveFile isnt '' textToInsertIntoArchiveFile = archiveText + textToInsertIntoArchiveFile else textToInsertIntoArchiveFile = archiveText starRangeToDelete = [[startOfSubtree, 0], [endOfSubtree, lastCol]] # Increase the total range we are deleting to encompass this star too if not rangeToDelete rangeToDelete = starRangeToDelete # Is this later than our selection to delete? if starRangeToDelete[1][0] > rangeToDelete[1][0] rangeToDelete[1] = starRangeToDelete[1] # Is this earlier than our earliest selection to delete? if starRangeToDelete[0][0] < rangeToDelete[0][0] rangeToDelete[0] = starRangeToDelete[0] # If there is actually something to archive, do that now if rangeToDelete if outputToString editor.setTextInBufferRange(rangeToDelete, '') return textToInsertIntoArchiveFile.trimLeft() else if not archiveFilename = editor.getPath() + '_archive' archiveFilename = dialog.showSaveDialog({title: 'Archive filename', message: 'Choose the file where this content will be moved to'}) if not archiveFilename return fs.stat archiveFilename, (err, stat) -> if err == fs.ENOENT or (not err and stat.size == 0) textToInsertIntoArchiveFile = textToInsertIntoArchiveFile.trimLeft() else if err atom.notifications.addError("Unable to archive content due to error: " + err, options) fs.appendFile archiveFilename, textToInsertIntoArchiveFile, (err) -> if err atom.notifications.addError("Unable to archive content due to error: " + err) else editor.setTextInBufferRange(rangeToDelete, '') _changePriority: (up) -> if editor = atom.workspace.getActiveTextEditor() visited = {} editor.transact 1000, () => @_withAllSelectedLines editor, (position, selection) => if visited[position.row] return if star = @_starInfo(editor, position) for i in [star.startRow..star.endRow] visited[i] = true if up star.increasePriority(editor) else star.decreasePriority(editor) _cycleVisibility: (editor, globalStartRow, globalEndRow) -> currentRow = globalStartRow while currentRow < globalEndRow startStar = @_starInfo(editor, new Point(currentRow, 3)) if not startStar currentRow += 1 continue startRow = currentRow lastRow = startStar.getEndOfSubtree() if editor.isFoldedAtBufferRow(startRow) # We are folded at the global level, unfold this level and fold all the children for i in [startStar.startRow..lastRow] editor.unfoldBufferRow(i) # Now fold all the rows at indentLevel+1 currentStar = @_starInfo(editor, new Point(startStar.endRow+1, startStar.starCol)) while currentStar != null and currentStar.endRow < editor.getLastBufferRow() and currentStar.endRow <= lastRow if currentStar.indentLevel == startStar.indentLevel+1 currentStarLastRow = currentStar.getEndOfSubtree() if currentStarLastRow > currentStar.startRow editor.foldBufferRange([[currentStar.startRow, Infinity],[currentStarLastRow, Infinity]]) currentStar = @_starInfo(editor, new Point(currentStar.endRow+1, currentStar.starCol)) else # Check to see if there is any Folding anyFolded = false for i in [startStar.startRow..lastRow] if editor.isFoldedAtBufferRow(i) anyFolded = true break if anyFolded # Unfold all for i in [startStar.startRow..lastRow] editor.unfoldBufferRow(i) else firstEnd = editor.lineTextForBufferRow(startStar.startRow).length editor.foldBufferRange([[startStar.startRow, firstEnd], [lastRow, Infinity]]) currentRow = lastRow + 1 _getISO8601Date: (date) -> year = ("0000" + date.getFullYear()).substr(-4, 4) month = ("00" + (date.getMonth() + 1)).substr(-2, 2) date = ("00" + date.getDate()).substr(-2, 2) "" + year + "-" + month + "-" + date _getISO8601DateTime: (date) -> return @_getISO8601Date(date) + "T" + @_getISO8601Time(date) _getISO8601Time: (date) -> offset = date.getTimezoneOffset() if offset is 0 offsetString = "Z" else negative = offset < 0; offsetHours = ("00" + Math.floor(offset/60)).substr(-2, 2) offsetMinutes = ("00" + (offset % 60)).substr(-2, 2) offsetString = if negative then "-" else "+" offsetString += offsetHours + ":" + offsetMinutes hours = ("00" + date.getHours()).substr(-2, 2) minutes = ("00" + date.getMinutes()).substr(-2, 2) seconds = ("00" + date.getSeconds()).substr(-2, 2) "" + hours + ":" + minutes + ":" + seconds + offsetString _indentChars: (star=null, editor=atom.workspace.getActiveTextEditor(), position=editor.getCursorBufferPosition()) -> if star and star.indentType isnt "mixed" and star.indentType isnt "none" indentStyle = star.indentType else if @levelStyle is "whitespace" indentStyle = if editor.getSoftTabs() then "spaces" else "tabs" else indentStyle = @levelStyle if indentStyle is "spaces" indent = " ".repeat(@indentSpaces) else if indentStyle is "tabs" indent = "\t" else if indentStyle is "stacked" if not star star = @_starInfo() indent = star.starType return indent _levelWhitespace: (star=null, editor=atom.workspace.getActiveTextEditor()) -> if not star star = @_starInfo(editor) # console.log("star: #{star}, indentType: #{star.indentType}, softTabs: #{editor.getSoftTabs()}") if star and star.indentType is "stacked" indent = "" else if editor.getSoftTabs() indent = " ".repeat(@indentSpaces) else indent = "\t" return indent _starInfo: (editor=atom.workspace.getActiveTextEditor(), position=editor.getCursorBufferPosition()) -> # Returns the following info # * Start Position of last star # * Last line of star # * Type of star (*, -, +, number) # * Type of whitespace (tabs, spaces, stacked, mixed) if not editor console.error("Editor is required") return if not position console.error("Position is required") return # Find the line with the last star. If you find blank lines or a header, there probably isn't a # star for this position currentLine = position.row star = new Star(currentLine, @indentSpaces, @levelStyle) if star.startRow >= 0 return star else return null _withAllSelectedLines: (editor, callback) -> editor = atom.workspace.getActiveTextEditor() unless editor if editor selections = editor.getSelections() for selection in selections range = selection.getBufferRange() #Adjust for selections that span the whole line if range.end.column is 0 and (range.start.column isnt range.end.column or range.start.row isnt range.end.row) if line = editor.lineTextForBufferRow(range.end.row-1) range.end = new Point(range.end.row-1, line.length-1) for i in [range.start.row..range.end.row] # Create a virtual position object from the range object if i is range.end.row position = new Point(i, range.end.col) else if i is range.start.row position = new Point(i, range.start.col) else position = new Point(i, 0) callback(position, selection)
4204
{CompositeDisposable, Directory, Point} = require 'atom' fs = require 'fs' {dialog} = require('electron') moment = require 'moment' CodeBlock = require './codeblock' #GoogleCalendar = require './google-calendar' OrganizedToolbar = require './toolbar' OrganizedView = require './organized-view' SidebarView = require './sidebar-view' Star = require './star' Table = require './table' Todo = require './sidebar-items' module.exports = organizedView: null modalPanel: null subscriptions: null levelStyle: 'spaces' indentSpaces: 2 createStarsOnEnter: true autoSizeTables: true organizedToolbar: null useBracketsAroundTodoTags: true trackCloseTimeOfTodos: true defaultVisibilityCycle: 'hide-none' config: levelStyle: title: 'Level Style' description: 'If you indent a star/bullet point, how should it be indented by default?' type: 'string' default: 'whitespace' enum: [ {value: 'whitespace', description: 'Sublevels are created by putting spaces or tabs (based on your editor tabType setting) in front of the stars'} {value: 'stacked', description: 'Sublevels are created using multiple stars. For example, level three of the outline would start with ***'} ] autoCreateStarsOnEnter: type: 'boolean' default: true useBracketsAroundTodoTags: type: 'boolean' default: true description: "When created TODO or DONE tags, prefer [TODO] over TODO and [DONE] over DONE" trackCloseTimeOfTodos: type: 'boolean' default: true description: "When transitioning from TODO to DONE record a CLOSED time" defaultVisibilityCycle: title: 'Default Org-File Visibility' description: 'Which part of the file will be visible on load' type: 'string' default: 'hide-none' enum: [ {value: 'hide-all', description: 'Only show the top-level bullets in a file'} {value: 'hide-bottom', description: 'Show first and second leve bullets in a file'} {value: 'hide-none', description: 'Show all information in the file'} ] autoSizeTables: type: 'boolean' default: false description: "(Not Ready for Prime Time) If you are typing in a table, automatically resize the columns so your text fits." enableToolbarSupport: type: 'boolean' default: true description: "Show a toolbar using the tool-bar package if that package is installed" searchDirectories: type: 'array' title: 'Predefined search directories / files' description: 'Directories and/or files where we will look for organized files when building todo lists, agendas, or searching. Separate multiple files or directories with a comma' default: ['','','','',''] items: type: 'string' includeProjectPathsInSearchDirectories: type: 'boolean' default: true description: 'Indicates whether we should include the paths for the current project in the search directories' searchSkipFiles: type: 'array' title: 'Organized Partial File Names to Skip' description: 'A list of partial file names to skip' default: ['', '', '', '', ''] items: type: 'string' sidebarVisible: type: 'boolean' title: "Show Sidebar" description: "Sidebar is currently being shown" default: false activate: (state) -> atom.themes.requireStylesheet(require.resolve('../styles/organized.less')); @organizedView = new OrganizedView(state.organizedViewState) @modalPanel = atom.workspace.addModalPanel({ item: @organizedView.getElement(), visible: false }) @subscriptions = new CompositeDisposable() # Set up text editors @subscriptions.add atom.workspace.observeTextEditors (editor) => @handleEvents(editor) @subscriptions.add editor.onDidSave => if @sidebar and @sidebar.sidebarVisible and editor.getGrammar().name is 'Organized' @sidebar.refreshAll() # Register command that toggles this view @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:indent': (event) => @indent(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:unindent': (event) => @unindent(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:setTodo': (event) => @setTodo(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:setTodoCompleted': (event) => @setTodoCompleted(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:toggleTodo': (event) => @toggleTodo(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:newLine': (event) => @newLine(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:newStarLine': (event) => @newStarLine(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:createTable': (event) => @createTable(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:newTableRow': (event) => @newTableRow(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:closeTable': (event) => @closeTable(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:openTable': (event) => @openTable(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:insertDate': (event) => @insert8601Date(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:insertDateTime': (event) => @insert8601DateTime(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:executeCodeBlock': (event) => @executeCodeBlock(event) })) #@subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:encryptBuffer': (event) => @encryptBuffer(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:toggleBold': (event) => @toggleBold(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:toggleUnderline': (event) => @toggleUnderline(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:toggleHeading': (event) => @toggleHeading(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:makeCodeBlock': (event) => @makeCodeBlock(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:makeResultBlock': (event) => @makeResultBlock(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:makeLink': (event) => @makeLink(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:refreshTodos': (event) => @sidebar.refreshTodos() })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:refreshAgenda': (event) => @sidebar.refreshAgendaItems() })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:scheduleItem': (event) => @scheduleItem(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:deadlineItem': (event) => @deadlineItem(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:archiveSubtree': (event) => @archiveSubtree(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:archiveToClipboard': (event) => @archiveToClipboard(event) })) #<EMAIL>@subscriptions<EMAIL>.add(atom.commands.add('atom-text-editor', { 'organized:importTodaysEvents': (event) => GoogleCalendar.importTodaysEvents() })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:increasePriority': (event) => @increasePriority(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:decreasePriority': (event) => @decreasePriority(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:cycleVisibility': (event) => @cycleVisibility(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:cycleGlobalVisibility': (event) => @cycleGlobalVisibility(event) })) @subscriptions.add atom.config.observe 'organized.autoCreateStarsOnEnter', (newValue) => @createStarsOnEnter = newValue @subscriptions.add atom.config.observe 'organized.levelStyle', (newValue) => @levelStyle = newValue @subscriptions.add atom.config.observe 'organized.autoSizeTables', (newValue) => @autoSizeTables = newValue @subscriptions.add atom.config.observe 'editor.tabLength', (newValue) => @indentSpaces = newValue @subscriptions.add atom.config.observe 'organized.useBracketsAroundTodoTags', (newValue) => @useBracketsAroundTodoTags = newValue @subscriptions.add atom.config.observe 'organized.trackCloseTimeOfTodos', (newValue) => @trackCloseTimeOfTodos = newValue @subscriptions.add atom.config.observe 'organized.defaultVisibilityCycle', (newValue) => @defaultVisibilityCycle = newValue @sidebar = new SidebarView() @sidebar.activate(@subscriptions) if not @organizedToolbar @organizedToolbar = new OrganizedToolbar() @organizedToolbar.activate(@subscriptions) @organizedToolbar.setSidebar(@sidebar) editor = atom.workspace.getActiveTextEditor() if editor and editor.getGrammar().name is 'Organized' if @defaultVisibilityCycle is 'hide-all' @cycleGlobalVisibility(null) else if @defaultVisibilityCycle is 'hide-bottom' # Doing this twice is messy. We should fix this later @cycleGlobalVisibility(null) @cycleGlobalVisibility(null) archiveSubtree: (event) -> @_archiveSubtree(false) archiveToClipboard: (event) -> archiveText = @_archiveSubtree(true) atom.clipboard.write(archiveText) closeTable: (event) -> if editor = atom.workspace.getActiveTextEditor() position = editor.getCursorBufferPosition() editor.transact 1000, () -> # See if we are on an editor line. If so, the close will be on the next line line = editor.lineTextForBufferRow(position.row) if 'border.table.organized' in editor.scopeDescriptorForBufferPosition(position).getScopesArray() editor.insertNewline() else line = editor.lineTextForBufferRow(position.row-1) editor.setTextInBufferRange([[position.row, 0], [position.row, position.column]], "") startMatch = /^(\s*)[\|\+]/.exec(line) endMatch = /[\|\+](\s*$)/.exec(line) if startMatch and endMatch # console.log("startMatch: #{startMatch}, endMatch: #{endMatch}") dashCount = endMatch.index-startMatch.index-startMatch[0].length editor.insertText("+#{'-'.repeat(dashCount)}+") # Callback from tool-bar to create a toolbar consumeToolBar: (toolBar) -> if not @organizedToolbar @organizedToolbar = new OrganizedToolbar() @organizedToolbar.activate(@subscriptions) @organizedToolbar.setSidebar(@sidebar) @organizedToolbar.consumeToolBar(toolBar) # Create a skeleton of a table ready for a user to start typing in it. createTable: (event) -> if editor = atom.workspace.getActiveTextEditor() position = editor.getCursorBufferPosition() editor.transact 1000, () => if not editor.lineTextForBufferRow(position.row).match(/\s*/) editor.insertNewline() editor.insertText("+----+") editor.insertNewline() editor.insertText("| ") position = editor.getCursorBufferPosition() editor.insertNewline() editor.insertText("+----+") editor.setCursorBufferPosition(position) cycleGlobalVisibility: (event) -> if editor = atom.workspace.getActiveTextEditor() @_cycleVisibility(editor, 0, editor.getLastBufferRow()) cycleVisibility: (event) -> if editor = atom.workspace.getActiveTextEditor() position = editor.getCursorBufferPosition() startRow = position.row if startStar = @_starInfo(editor, position) lastRow = startStar.getEndOfSubtree() @_cycleVisibility(editor, startRow, lastRow) deactivate: () -> @organizedToolbar.deactivate() @modalPanel.destroy() @subscriptions.dispose() @organizedView.destroy() deadlineItem: (event) -> @_addMarkerDate("DEADLINE") decreasePriority: () -> @_changePriority(false) executeCodeBlock: () -> if editor = atom.workspace.getActiveTextEditor() if position = editor.getCursorBufferPosition() codeblock = new CodeBlock(position.row) codeblock.execute() else atom.notifications.error("Unable to find code block") handleEvents: (editor) -> tableChangeSubscription = editor.onDidChange (event) => @tableChange(event) tableStoppedChangingSub = editor.onDidStopChanging (event) => @tableStoppedChanging(event) editorDestroySubscription = editor.onDidDestroy => tableStoppedChangingSub.dispose() # @subscriptions.add(tableChangeSubscription) @subscriptions.add(tableStoppedChangingSub) @subscriptions.add(editorDestroySubscription) increasePriority: () -> @_changePriority(true) indent: (event) -> if editor = atom.workspace.getActiveTextEditor() visited = {} editor.transact 2000, () => @_withAllSelectedLines editor, (position, selection) => if visited[position.row] return if star = @_starInfo(editor, position) for i in [star.startRow..star.endRow] visited[i] = true indent = if star.indentType is "stacked" then star.starType else @_indentChars() for row in [star.startRow..star.endRow] editor.setTextInBufferRange([[row, 0], [row, 0]], indent) else editor.indentSelectedRows() insert8601Date: (event) -> d = new Date() editor = atom.workspace.getActiveTextEditor() editor.insertText(@_getISO8601Date(d)) insert8601DateTime: (event) -> d = new Date() editor = atom.workspace.getActiveTextEditor() editor.insertText(@_getISO8601Date(d) + "T" + @_getISO8601Time(d)) makeCodeBlock: (event) -> if editor = atom.workspace.getActiveTextEditor() position = editor.getCursorBufferPosition() editor.transact 1000, () => if not editor.lineTextForBufferRow(position.row).match(/\s*/) editor.insertNewline() editor.insertText('```') endPosition = editor.getCursorBufferPosition() editor.insertNewline() editor.insertText('```') editor.setCursorBufferPosition(endPosition) makeResultBlock: (event) -> if editor = atom.workspace.getActiveTextEditor() position = editor.getCursorBufferPosition() editor.transact 1000, () => if not editor.lineTextForBufferRow(position.row).match(/\s*/) editor.insertNewline() editor.insertText('```result') editor.insertNewline() editor.insertText('```') makeLink: (event) -> if editor = atom.workspace.getActiveTextEditor() editor.transact 1000, () => @_withAllSelectedLines editor, (position, selection) => if selection.isEmpty() editor.insertText("[]()") selection.cursor.moveLeft(3) else range = selection.getBufferRange() if selection.getText().match(/^https?:\/\//) editor.setTextInBufferRange([range.end, range.end], ")") editor.setTextInBufferRange([range.start, range.start], "[](") else editor.setTextInBufferRange([range.end, range.end], "]()") editor.setTextInBufferRange([range.start, range.start], "[") # Respond to someone pressing enter. # There's some special handling here. The auto-intent that's built into atom does a good job, but I want the # new text to be even with the start of the text, not the start of the star. newLine: (event) -> if editor = atom.workspace.getActiveTextEditor() if star = @_starInfo() editor.transact 1000, () => editor.insertNewline() spaceCount = star.startTodoCol - star.starCol indent = @_levelWhitespace(star, editor).repeat(star.indentLevel) + " ".repeat(spaceCount) # console.log("spaceCount: #{spaceCount}, indentLevel: #{star.indentLevel}, levelWhiteSpace='#{@_levelWhitespace(star, editor)}'") newPosition = editor.getCursorBufferPosition() editor.transact 1000, () => editor.setTextInBufferRange([[newPosition.row, 0],[newPosition.row, newPosition.column]], indent) editor.setCursorBufferPosition([newPosition.row, indent.length]) else editor.insertNewline() newStarLine: (event) -> if editor = atom.workspace.getActiveTextEditor() # Bail out if the user didn't want any special behavior if !@createStarsOnEnter editor.insertNewline() return # If a user hits return and they haven't really done anything on this line, # treat it like an unindent. It seems awkward to add another empty one. oldPosition = editor.getCursorBufferPosition() line = editor.lineTextForBufferRow(oldPosition.row) if line.match(/([\*\-\+]|\d+\.|[A-z]\.) $/) @unindent() return # If the previous line was entirely empty, it seems like the outline is kind # of "done". Don't try to restart it yet. if line.match(/^\s*$/) editor.insertNewline() return # Make sure we aren't in the middle of a codeblock row = oldPosition.row line = editor.lineTextForBufferRow(row) star = @_starInfo() minRow = if star then star.startRow else 0 while row > minRow and not line.match(/^\s*```/) row -= 1 line = editor.lineTextForBufferRow(row) if line.match(/^\s*```/) # Just add a newline, we're in the middle of a code block editor.insertNewline() return # Figure out where we were so we can use it to figure out where to put the star # and what kind of star to use # Really hit return now editor.transact 1000, () => # If there is a star on the next line, we'll use it's insert level and bullet type # We'll keep a reference to the old star because we need it sometimes oldStar = star if oldPosition.row+1 <= editor.getLastBufferRow() if nextStar = @_starInfo(editor, new Point(oldPosition.row+1, oldPosition.col)) if not star or nextStar.indentLevel > star.indentLevel star = nextStar if star and star.indentLevel >= 0 editor.insertNewline() if oldPosition.column <= star.starCol # If the cursor on a column before the star on the line, just insert a newline return #Create our new text to insert newPosition = editor.getCursorBufferPosition() if star.starType is 'numbers' # Make sure we use a reference to the old star here so we get the editor.setTextInBufferRange([[newPosition.row, 0], [newPosition.row, Infinity]], oldStar.newStarLine()) position = new Point(newPosition.row+1, 0) #console.log("newPosition+1: #{position}, last buffer row: #{editor.getLastBufferRow()}") while position.row <= editor.getLastBufferRow() and nextStar = @_starInfo(editor, position) if nextStar.starType isnt 'numbers' or nextStar.indentLevel isnt star.indentLevel break #console.log("Position: #{position}, nextStar.startRow: #{nextStar.startRow}, nextStar.endRow: #{nextStar.endRow}") #console.log("Replacing #{nextStar.currentNumber} with #{nextStar.nextNumber}") editor.setTextInBufferRange([[nextStar.startRow, nextStar.starCol], [nextStar.startRow, nextStar.starCol+(""+nextStar.currentNumber).length]], "" + nextStar.nextNumber) position = new Point(nextStar.endRow+1, 0) else if star.starType is 'letters' # Make sure we use a reference to the old star here so we get the editor.setTextInBufferRange([[newPosition.row, 0], [newPosition.row, Infinity]], oldStar.newStarLine()) position = new Point(newPosition.row+1, 0) #console.log("newPosition+1: #{position}, last buffer row: #{editor.getLastBufferRow()}") while position.row <= editor.getLastBufferRow() and nextStar = @_starInfo(editor, position) if nextStar.starType isnt 'letters' or nextStar.indentLevel isnt star.indentLevel break #console.log("Position: #{position}, nextStar.startRow: #{nextStar.startRow}, nextStar.endRow: #{nextStar.endRow}") #console.log("Replacing #{nextStar.currentNumber} with #{nextStar.nextNumber}") editor.setTextInBufferRange([[nextStar.startRow, nextStar.starCol], [nextStar.startRow, nextStar.starCol+(""+nextStar.currentLetter).length]], "" + nextStar.nextLetter) position = new Point(nextStar.endRow+1, 0) else indent = star.newStarLine() editor.transact 1000, () => editor.setTextInBufferRange([[newPosition.row, 0],[newPosition.row, newPosition.column]], indent) editor.setCursorBufferPosition([newPosition.row, indent.length]) else editor.insertNewline() newTableRow: () -> if editor = atom.workspace.getActiveTextEditor() oldPosition = editor.getCursorBufferPosition() line = editor.lineTextForBufferRow(oldPosition.row) if match = line.match(/^\s*(\|[ ]?)/) editor.transact 1000, () -> editor.insertNewline() editor.insertText(match[0]) else editor.insertNewline() openTable: (event) -> if editor = atom.workspace.getActiveTextEditor() currentPosition = editor.getCursorBufferPosition() line = editor.lineTextForBufferRow(currentPosition.row) if match = line.match(/^(\s*)/) editor.insertText("+----+\n#{match[0]}| ") serialize: () -> return { organizedViewState: @organizedView.serialize() } scheduleItem: (event) -> @_addMarkerDate("SCHEDULED") setTodo: (event) -> if editor = atom.workspace.getActiveTextEditor() visited = {} startPosition = editor.getCursorBufferPosition() startRow = startPosition.row @_withAllSelectedLines editor, (position, selection) => if visited[position.row] return if star = @_starInfo(editor, position) for i in [star.startRow..star.endRow] visited[i] = true line = editor.lineTextForBufferRow(star.startRow) editor.setTextInBufferRange([[star.startRow, star.startTodoCol], [star.startRow, star.startTextCol]], " [TODO] ") setTodoCompleted: (event) -> if editor = atom.workspace.getActiveTextEditor() visited = {} startPosition = editor.getCursorBufferPosition() startRow = startPosition.row @_withAllSelectedLines editor, (position, selection) => if visited[position.row] return if star = @_starInfo(editor, position) for i in [star.startRow..star.endRow] visited[i] = true line = editor.lineTextForBufferRow(star.startRow) editor.setTextInBufferRange([[star.startRow, star.whitespaceCol], [star.startRow, star.startTextCol]], " [DONE] ") tableChange: (event) -> if not @autoSizeTables return if editor = atom.workspace.getActiveTextEditor() scopes = editor.getLastCursor().getScopeDescriptor().getScopesArray() if 'row.table.organized' in scopes or 'border.table.organized' in scopes table = new Table(editor) return unless table.found? # Getting closer, but not there yet. #table.normalizeRowSizes() tableStoppedChanging: (event) -> return unless @autoSizeTables # if editor = atom.workspace.getActiveTextEditor() # scopes = editor.getLastCursor().getScopeDescriptor().getScopesArray() # if 'row.table.organized' in scopes or 'border.table.organized' in scopes # console.log("Stopped changing") toggleBold: (event) -> if editor = atom.workspace.getActiveTextEditor() editor.transact 1000, () => @_withAllSelectedLines editor, (position, selection) => if selection.isEmpty() editor.insertText("____") selection.cursor.moveLeft(2) else range = selection.getBufferRange() startMarked = editor.getTextInBufferRange([range.start, [range.start.row, range.start.column+2]]) is "__" endMarked = editor.getTextInBufferRange([[range.end.row, range.end.column-2], range.end]) is "__" if startMarked and endMarked editor.setTextInBufferRange([[range.end.row, range.end.column-2], range.end], "") editor.setTextInBufferRange([range.start, [range.start.row, range.start.column+2]], "") else editor.setTextInBufferRange([range.end, range.end], '__') editor.setTextInBufferRange([range.start, range.start], "__") toggleHeading: (event) -> if editor = atom.workspace.getActiveTextEditor() editor.transact 1000, () => @_withAllSelectedLines editor, (position, selection) => startChars = editor.getTextInBufferRange([[position.row, 0], [position.row, 4]]) hashCount = 0 hashCount +=1 until startChars[hashCount] isnt '#' if hashCount is 0 editor.setTextInBufferRange([[position.row, 0], [position.row, 0]], '# ') else if hashCount < 3 editor.setTextInBufferRange([[position.row, 0], [position.row, 0]], '#') else charsToDelete = if startChars[3] is ' ' then 4 else 3 editor.setTextInBufferRange([[position.row, 0], [position.row, charsToDelete]], '') toggleTodo: (event) -> if editor = atom.workspace.getActiveTextEditor() visited = {} startPosition = editor.getCursorBufferPosition() startRow = startPosition.row @_withAllSelectedLines editor, (position, selection) => if visited[position.row] return if star = @_starInfo(editor, position) for i in [star.startRow..star.endRow] visited[i] = true line = editor.lineTextForBufferRow(star.startRow) if match = line.match(/\s*([\-\+\*]+|\d+\.|[A-z]\.) (\[(TODO)\]|TODO) /) replacement = if match[2].includes('[') then " [DONE] " else " DONE " editor.transact 1000, () => editor.setTextInBufferRange([[star.startRow, star.whitespaceCol], [star.startRow, star.startTextCol]], replacement) if @trackCloseTimeOfTodos d = new Date() closeText = "CLOSED: [#{@_getISO8601DateTime(d)}]" line = editor.lineTextForBufferRow(star.startRow+1) if line and line.indexOf("SCHEDULED: <") > -1 editor.setTextInBufferRange([[star.startRow+1, star.startTodoCol], [star.startRow+1, star.startTodoCol]], closeText + " ") else spaceCount = star.startTodoCol - star.starCol indent = @_levelWhitespace(star, editor).repeat(star.indentLevel) + " ".repeat(spaceCount) closeText = "\n" + indent + closeText + "\n" editor.setTextInBufferRange([[star.startRow, Infinity],[star.startRow+1, 0]], closeText) else if (line.match(/\s*([\-\+\*]+|\d+.|[A-z]\.) ((\[(COMPLETED|DONE)\])|(COMPLETED|DONE)) /)) editor.transact 1000, () => editor.setTextInBufferRange([[star.startRow, star.whitespaceCol], [star.startRow, star.startTextCol]], " ") line = editor.lineTextForBufferRow(star.startRow+1) if line if match = line.match(/^\s*CLOSED: \[[^\]]+\]\s*$/) editor.setTextInBufferRange([[star.startRow, Infinity], [star.startRow+1, Infinity]], "") else line = line.replace(/CLOSED: \[[^\]]+\]\s*/, "") editor.setTextInBufferRange([[star.startRow+1, 0], [star.startRow+1, Infinity]], line) else replacement = if @useBracketsAroundTodoTags then " [TODO] " else " TODO " editor.setTextInBufferRange([[star.startRow, star.whitespaceCol], [star.startRow, star.startTextCol]], replacement) toggleUnderline: (event) -> if editor = atom.workspace.getActiveTextEditor() editor.transact 1000, () => @_withAllSelectedLines editor, (position, selection) => if selection.isEmpty() editor.insertText('__') selection.cursor.moveLeft(1) else range = selection.getBufferRange() startThree = editor.getTextInBufferRange([range.start, [range.start.row, range.start.column+3]]) endThree = editor.getTextInBufferRange([[range.end.row, range.end.column-3], range.end]) # Need to consider situations where there is a bold and an underline startMatch = startThree.match(/(_[^_][^_]|___)/) endMatch = endThree.match(/([^_][^_]_|___)/) if startMatch and endMatch editor.setTextInBufferRange([[range.end.row, range.end.column-1], range.end], "") editor.setTextInBufferRange([range.start, [range.start.row, range.start.column+1]], "") else editor.setTextInBufferRange([range.end, range.end], '_') editor.setTextInBufferRange([range.start, range.start], "_") unindent: (event) -> if editor = atom.workspace.getActiveTextEditor() visited = {} editor.transact 2000, () => @_withAllSelectedLines editor, (position, selection) => if visited[position.row] return if star = @_starInfo(editor, position) for i in [star.startRow..star.endRow] visited[i] = true firstRow = star.startRow lastRow = star.endRow #Unindent editor.transact 1000, () -> for row in [firstRow..lastRow] line = editor.lineTextForBufferRow(row) if not line continue else if line.match("^ ") editor.setTextInBufferRange([[row, 0], [row, 2]], "") else if line.match("^\\t") editor.setTextInBufferRange([[row, 0], [row, 1]], "") else if match = line.match(/^([\*\-\+]|\d+\.|[A-z]\.) /) editor.setTextInBufferRange([[row, 0], [row, match[0].length]], "") else if line.match(/^[\*\-\+]/) #Stacked editor.setTextInBufferRange([[row, 0], [row, 1]], "") else #cannot unindent - not sure how to do so else editor.outdentSelectedRows() _addMarkerDate: (dateType) -> if editor = atom.workspace.getActiveTextEditor() visited = {} d = new Date() df = new Intl.DateTimeFormat('en-US', {weekday: 'short'}) dow = df.format(d) @_withAllSelectedLines editor, (position, selection) => if visited[position.row] return if star = @_starInfo(editor, position) for i in [star.startRow..star.endRow] visited[i] = true editor.transact 1000, () => originalPosition = editor.getCursorBufferPosition() # Now add the marker newText = "\n" + " ".repeat(star.startTodoCol) + "#{dateType}: <#{@_getISO8601Date(d)} #{dow}>" col = editor.lineTextForBufferRow(star.startRow).length editor.setTextInBufferRange([[star.startRow, col+1], [star.startRow, col+1]], newText) _archiveFinishedInSubtree: (outputToString) -> if editor = atom.workspace.getActiveTextEditor() visited = {} linesToArchive = [] if not star = @_starInfo(editor, position) return startIndentLevel = star.indentLevel currentLine = star.lineTextForBufferRow() _archiveSubtree: (outputToString) -> if editor = atom.workspace.getActiveTextEditor() visited = {} baseArchiveLevel = null stars = [] # If there are multiple selections, this could span multiple subtrees. Calculate # the total size of the tree first. One possible problem is that we aren't going # to have properties for each of the subtrees when we archive. @_withAllSelectedLines editor, (position, selection) => if visited[position.row] return # Mark all lines in subtree as visited visited[position.row] = true if not star = @_starInfo(editor, position) return # Capture the first star, so we know how deeply to indent the properties if not baseArchiveLevel baseArchiveLevel = star.indentLevel if star.indentLevel == baseArchiveLevel # We need to put properties on this level too, otherwise we won't be able to unarchive it. stars.push(star) endOfSubtree = star.getEndOfSubtree() for line in [star.startRow..endOfSubtree] visited[line] = true # Now act on those lines editor.transact 2000, () => textToInsertIntoArchiveFile = "" rangeToDelete = null # Iterate backwards so we don't change the line number of stars. # Collect the text to delete and the ranges that we are deleting. for star in stars by -1 startOfSubtree = star.startRow endOfSubtree = star.getEndOfSubtree() startTodoCol = star.startTodoCol # Be careful to support selecting out of the end of a file if endOfSubtree == editor.getLastBufferRow() lastCol = editor.lineTextForBufferRow(endOfSubtree).length else endOfSubtree += 1 lastCol = 0 archiveText = editor.lineTextForBufferRow(startOfSubtree) + '\n' archiveText += ' '.repeat(startTodoCol) + ':PROPERTIES:' + '\n' archiveText += ' '.repeat(startTodoCol) + ':ARCHIVE_TIME: ' + moment().format('YYYY-MM-DD ddd HH:mm') + '\n' if path = editor.getPath() archiveText += ' '.repeat(startTodoCol) + ':ARCHIVE_FILE: ' + path + "\n" archiveText += ' '.repeat(startTodoCol) + ':END:' + "\n" # If end is the same as the beginning, we've already gotten all of the text if endOfSubtree > startOfSubtree archiveText += editor.getTextInBufferRange([[startOfSubtree+1, 0], [endOfSubtree, lastCol]]) if textToInsertIntoArchiveFile isnt '' textToInsertIntoArchiveFile = archiveText + textToInsertIntoArchiveFile else textToInsertIntoArchiveFile = archiveText starRangeToDelete = [[startOfSubtree, 0], [endOfSubtree, lastCol]] # Increase the total range we are deleting to encompass this star too if not rangeToDelete rangeToDelete = starRangeToDelete # Is this later than our selection to delete? if starRangeToDelete[1][0] > rangeToDelete[1][0] rangeToDelete[1] = starRangeToDelete[1] # Is this earlier than our earliest selection to delete? if starRangeToDelete[0][0] < rangeToDelete[0][0] rangeToDelete[0] = starRangeToDelete[0] # If there is actually something to archive, do that now if rangeToDelete if outputToString editor.setTextInBufferRange(rangeToDelete, '') return textToInsertIntoArchiveFile.trimLeft() else if not archiveFilename = editor.getPath() + '_archive' archiveFilename = dialog.showSaveDialog({title: 'Archive filename', message: 'Choose the file where this content will be moved to'}) if not archiveFilename return fs.stat archiveFilename, (err, stat) -> if err == fs.ENOENT or (not err and stat.size == 0) textToInsertIntoArchiveFile = textToInsertIntoArchiveFile.trimLeft() else if err atom.notifications.addError("Unable to archive content due to error: " + err, options) fs.appendFile archiveFilename, textToInsertIntoArchiveFile, (err) -> if err atom.notifications.addError("Unable to archive content due to error: " + err) else editor.setTextInBufferRange(rangeToDelete, '') _changePriority: (up) -> if editor = atom.workspace.getActiveTextEditor() visited = {} editor.transact 1000, () => @_withAllSelectedLines editor, (position, selection) => if visited[position.row] return if star = @_starInfo(editor, position) for i in [star.startRow..star.endRow] visited[i] = true if up star.increasePriority(editor) else star.decreasePriority(editor) _cycleVisibility: (editor, globalStartRow, globalEndRow) -> currentRow = globalStartRow while currentRow < globalEndRow startStar = @_starInfo(editor, new Point(currentRow, 3)) if not startStar currentRow += 1 continue startRow = currentRow lastRow = startStar.getEndOfSubtree() if editor.isFoldedAtBufferRow(startRow) # We are folded at the global level, unfold this level and fold all the children for i in [startStar.startRow..lastRow] editor.unfoldBufferRow(i) # Now fold all the rows at indentLevel+1 currentStar = @_starInfo(editor, new Point(startStar.endRow+1, startStar.starCol)) while currentStar != null and currentStar.endRow < editor.getLastBufferRow() and currentStar.endRow <= lastRow if currentStar.indentLevel == startStar.indentLevel+1 currentStarLastRow = currentStar.getEndOfSubtree() if currentStarLastRow > currentStar.startRow editor.foldBufferRange([[currentStar.startRow, Infinity],[currentStarLastRow, Infinity]]) currentStar = @_starInfo(editor, new Point(currentStar.endRow+1, currentStar.starCol)) else # Check to see if there is any Folding anyFolded = false for i in [startStar.startRow..lastRow] if editor.isFoldedAtBufferRow(i) anyFolded = true break if anyFolded # Unfold all for i in [startStar.startRow..lastRow] editor.unfoldBufferRow(i) else firstEnd = editor.lineTextForBufferRow(startStar.startRow).length editor.foldBufferRange([[startStar.startRow, firstEnd], [lastRow, Infinity]]) currentRow = lastRow + 1 _getISO8601Date: (date) -> year = ("0000" + date.getFullYear()).substr(-4, 4) month = ("00" + (date.getMonth() + 1)).substr(-2, 2) date = ("00" + date.getDate()).substr(-2, 2) "" + year + "-" + month + "-" + date _getISO8601DateTime: (date) -> return @_getISO8601Date(date) + "T" + @_getISO8601Time(date) _getISO8601Time: (date) -> offset = date.getTimezoneOffset() if offset is 0 offsetString = "Z" else negative = offset < 0; offsetHours = ("00" + Math.floor(offset/60)).substr(-2, 2) offsetMinutes = ("00" + (offset % 60)).substr(-2, 2) offsetString = if negative then "-" else "+" offsetString += offsetHours + ":" + offsetMinutes hours = ("00" + date.getHours()).substr(-2, 2) minutes = ("00" + date.getMinutes()).substr(-2, 2) seconds = ("00" + date.getSeconds()).substr(-2, 2) "" + hours + ":" + minutes + ":" + seconds + offsetString _indentChars: (star=null, editor=atom.workspace.getActiveTextEditor(), position=editor.getCursorBufferPosition()) -> if star and star.indentType isnt "mixed" and star.indentType isnt "none" indentStyle = star.indentType else if @levelStyle is "whitespace" indentStyle = if editor.getSoftTabs() then "spaces" else "tabs" else indentStyle = @levelStyle if indentStyle is "spaces" indent = " ".repeat(@indentSpaces) else if indentStyle is "tabs" indent = "\t" else if indentStyle is "stacked" if not star star = @_starInfo() indent = star.starType return indent _levelWhitespace: (star=null, editor=atom.workspace.getActiveTextEditor()) -> if not star star = @_starInfo(editor) # console.log("star: #{star}, indentType: #{star.indentType}, softTabs: #{editor.getSoftTabs()}") if star and star.indentType is "stacked" indent = "" else if editor.getSoftTabs() indent = " ".repeat(@indentSpaces) else indent = "\t" return indent _starInfo: (editor=atom.workspace.getActiveTextEditor(), position=editor.getCursorBufferPosition()) -> # Returns the following info # * Start Position of last star # * Last line of star # * Type of star (*, -, +, number) # * Type of whitespace (tabs, spaces, stacked, mixed) if not editor console.error("Editor is required") return if not position console.error("Position is required") return # Find the line with the last star. If you find blank lines or a header, there probably isn't a # star for this position currentLine = position.row star = new Star(currentLine, @indentSpaces, @levelStyle) if star.startRow >= 0 return star else return null _withAllSelectedLines: (editor, callback) -> editor = atom.workspace.getActiveTextEditor() unless editor if editor selections = editor.getSelections() for selection in selections range = selection.getBufferRange() #Adjust for selections that span the whole line if range.end.column is 0 and (range.start.column isnt range.end.column or range.start.row isnt range.end.row) if line = editor.lineTextForBufferRow(range.end.row-1) range.end = new Point(range.end.row-1, line.length-1) for i in [range.start.row..range.end.row] # Create a virtual position object from the range object if i is range.end.row position = new Point(i, range.end.col) else if i is range.start.row position = new Point(i, range.start.col) else position = new Point(i, 0) callback(position, selection)
true
{CompositeDisposable, Directory, Point} = require 'atom' fs = require 'fs' {dialog} = require('electron') moment = require 'moment' CodeBlock = require './codeblock' #GoogleCalendar = require './google-calendar' OrganizedToolbar = require './toolbar' OrganizedView = require './organized-view' SidebarView = require './sidebar-view' Star = require './star' Table = require './table' Todo = require './sidebar-items' module.exports = organizedView: null modalPanel: null subscriptions: null levelStyle: 'spaces' indentSpaces: 2 createStarsOnEnter: true autoSizeTables: true organizedToolbar: null useBracketsAroundTodoTags: true trackCloseTimeOfTodos: true defaultVisibilityCycle: 'hide-none' config: levelStyle: title: 'Level Style' description: 'If you indent a star/bullet point, how should it be indented by default?' type: 'string' default: 'whitespace' enum: [ {value: 'whitespace', description: 'Sublevels are created by putting spaces or tabs (based on your editor tabType setting) in front of the stars'} {value: 'stacked', description: 'Sublevels are created using multiple stars. For example, level three of the outline would start with ***'} ] autoCreateStarsOnEnter: type: 'boolean' default: true useBracketsAroundTodoTags: type: 'boolean' default: true description: "When created TODO or DONE tags, prefer [TODO] over TODO and [DONE] over DONE" trackCloseTimeOfTodos: type: 'boolean' default: true description: "When transitioning from TODO to DONE record a CLOSED time" defaultVisibilityCycle: title: 'Default Org-File Visibility' description: 'Which part of the file will be visible on load' type: 'string' default: 'hide-none' enum: [ {value: 'hide-all', description: 'Only show the top-level bullets in a file'} {value: 'hide-bottom', description: 'Show first and second leve bullets in a file'} {value: 'hide-none', description: 'Show all information in the file'} ] autoSizeTables: type: 'boolean' default: false description: "(Not Ready for Prime Time) If you are typing in a table, automatically resize the columns so your text fits." enableToolbarSupport: type: 'boolean' default: true description: "Show a toolbar using the tool-bar package if that package is installed" searchDirectories: type: 'array' title: 'Predefined search directories / files' description: 'Directories and/or files where we will look for organized files when building todo lists, agendas, or searching. Separate multiple files or directories with a comma' default: ['','','','',''] items: type: 'string' includeProjectPathsInSearchDirectories: type: 'boolean' default: true description: 'Indicates whether we should include the paths for the current project in the search directories' searchSkipFiles: type: 'array' title: 'Organized Partial File Names to Skip' description: 'A list of partial file names to skip' default: ['', '', '', '', ''] items: type: 'string' sidebarVisible: type: 'boolean' title: "Show Sidebar" description: "Sidebar is currently being shown" default: false activate: (state) -> atom.themes.requireStylesheet(require.resolve('../styles/organized.less')); @organizedView = new OrganizedView(state.organizedViewState) @modalPanel = atom.workspace.addModalPanel({ item: @organizedView.getElement(), visible: false }) @subscriptions = new CompositeDisposable() # Set up text editors @subscriptions.add atom.workspace.observeTextEditors (editor) => @handleEvents(editor) @subscriptions.add editor.onDidSave => if @sidebar and @sidebar.sidebarVisible and editor.getGrammar().name is 'Organized' @sidebar.refreshAll() # Register command that toggles this view @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:indent': (event) => @indent(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:unindent': (event) => @unindent(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:setTodo': (event) => @setTodo(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:setTodoCompleted': (event) => @setTodoCompleted(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:toggleTodo': (event) => @toggleTodo(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:newLine': (event) => @newLine(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:newStarLine': (event) => @newStarLine(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:createTable': (event) => @createTable(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:newTableRow': (event) => @newTableRow(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:closeTable': (event) => @closeTable(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:openTable': (event) => @openTable(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:insertDate': (event) => @insert8601Date(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:insertDateTime': (event) => @insert8601DateTime(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:executeCodeBlock': (event) => @executeCodeBlock(event) })) #@subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:encryptBuffer': (event) => @encryptBuffer(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:toggleBold': (event) => @toggleBold(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:toggleUnderline': (event) => @toggleUnderline(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:toggleHeading': (event) => @toggleHeading(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:makeCodeBlock': (event) => @makeCodeBlock(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:makeResultBlock': (event) => @makeResultBlock(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:makeLink': (event) => @makeLink(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:refreshTodos': (event) => @sidebar.refreshTodos() })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:refreshAgenda': (event) => @sidebar.refreshAgendaItems() })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:scheduleItem': (event) => @scheduleItem(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:deadlineItem': (event) => @deadlineItem(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:archiveSubtree': (event) => @archiveSubtree(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:archiveToClipboard': (event) => @archiveToClipboard(event) })) #PI:EMAIL:<EMAIL>END_PI@subscriptionsPI:EMAIL:<EMAIL>END_PI.add(atom.commands.add('atom-text-editor', { 'organized:importTodaysEvents': (event) => GoogleCalendar.importTodaysEvents() })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:increasePriority': (event) => @increasePriority(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:decreasePriority': (event) => @decreasePriority(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:cycleVisibility': (event) => @cycleVisibility(event) })) @subscriptions.add(atom.commands.add('atom-text-editor', { 'organized:cycleGlobalVisibility': (event) => @cycleGlobalVisibility(event) })) @subscriptions.add atom.config.observe 'organized.autoCreateStarsOnEnter', (newValue) => @createStarsOnEnter = newValue @subscriptions.add atom.config.observe 'organized.levelStyle', (newValue) => @levelStyle = newValue @subscriptions.add atom.config.observe 'organized.autoSizeTables', (newValue) => @autoSizeTables = newValue @subscriptions.add atom.config.observe 'editor.tabLength', (newValue) => @indentSpaces = newValue @subscriptions.add atom.config.observe 'organized.useBracketsAroundTodoTags', (newValue) => @useBracketsAroundTodoTags = newValue @subscriptions.add atom.config.observe 'organized.trackCloseTimeOfTodos', (newValue) => @trackCloseTimeOfTodos = newValue @subscriptions.add atom.config.observe 'organized.defaultVisibilityCycle', (newValue) => @defaultVisibilityCycle = newValue @sidebar = new SidebarView() @sidebar.activate(@subscriptions) if not @organizedToolbar @organizedToolbar = new OrganizedToolbar() @organizedToolbar.activate(@subscriptions) @organizedToolbar.setSidebar(@sidebar) editor = atom.workspace.getActiveTextEditor() if editor and editor.getGrammar().name is 'Organized' if @defaultVisibilityCycle is 'hide-all' @cycleGlobalVisibility(null) else if @defaultVisibilityCycle is 'hide-bottom' # Doing this twice is messy. We should fix this later @cycleGlobalVisibility(null) @cycleGlobalVisibility(null) archiveSubtree: (event) -> @_archiveSubtree(false) archiveToClipboard: (event) -> archiveText = @_archiveSubtree(true) atom.clipboard.write(archiveText) closeTable: (event) -> if editor = atom.workspace.getActiveTextEditor() position = editor.getCursorBufferPosition() editor.transact 1000, () -> # See if we are on an editor line. If so, the close will be on the next line line = editor.lineTextForBufferRow(position.row) if 'border.table.organized' in editor.scopeDescriptorForBufferPosition(position).getScopesArray() editor.insertNewline() else line = editor.lineTextForBufferRow(position.row-1) editor.setTextInBufferRange([[position.row, 0], [position.row, position.column]], "") startMatch = /^(\s*)[\|\+]/.exec(line) endMatch = /[\|\+](\s*$)/.exec(line) if startMatch and endMatch # console.log("startMatch: #{startMatch}, endMatch: #{endMatch}") dashCount = endMatch.index-startMatch.index-startMatch[0].length editor.insertText("+#{'-'.repeat(dashCount)}+") # Callback from tool-bar to create a toolbar consumeToolBar: (toolBar) -> if not @organizedToolbar @organizedToolbar = new OrganizedToolbar() @organizedToolbar.activate(@subscriptions) @organizedToolbar.setSidebar(@sidebar) @organizedToolbar.consumeToolBar(toolBar) # Create a skeleton of a table ready for a user to start typing in it. createTable: (event) -> if editor = atom.workspace.getActiveTextEditor() position = editor.getCursorBufferPosition() editor.transact 1000, () => if not editor.lineTextForBufferRow(position.row).match(/\s*/) editor.insertNewline() editor.insertText("+----+") editor.insertNewline() editor.insertText("| ") position = editor.getCursorBufferPosition() editor.insertNewline() editor.insertText("+----+") editor.setCursorBufferPosition(position) cycleGlobalVisibility: (event) -> if editor = atom.workspace.getActiveTextEditor() @_cycleVisibility(editor, 0, editor.getLastBufferRow()) cycleVisibility: (event) -> if editor = atom.workspace.getActiveTextEditor() position = editor.getCursorBufferPosition() startRow = position.row if startStar = @_starInfo(editor, position) lastRow = startStar.getEndOfSubtree() @_cycleVisibility(editor, startRow, lastRow) deactivate: () -> @organizedToolbar.deactivate() @modalPanel.destroy() @subscriptions.dispose() @organizedView.destroy() deadlineItem: (event) -> @_addMarkerDate("DEADLINE") decreasePriority: () -> @_changePriority(false) executeCodeBlock: () -> if editor = atom.workspace.getActiveTextEditor() if position = editor.getCursorBufferPosition() codeblock = new CodeBlock(position.row) codeblock.execute() else atom.notifications.error("Unable to find code block") handleEvents: (editor) -> tableChangeSubscription = editor.onDidChange (event) => @tableChange(event) tableStoppedChangingSub = editor.onDidStopChanging (event) => @tableStoppedChanging(event) editorDestroySubscription = editor.onDidDestroy => tableStoppedChangingSub.dispose() # @subscriptions.add(tableChangeSubscription) @subscriptions.add(tableStoppedChangingSub) @subscriptions.add(editorDestroySubscription) increasePriority: () -> @_changePriority(true) indent: (event) -> if editor = atom.workspace.getActiveTextEditor() visited = {} editor.transact 2000, () => @_withAllSelectedLines editor, (position, selection) => if visited[position.row] return if star = @_starInfo(editor, position) for i in [star.startRow..star.endRow] visited[i] = true indent = if star.indentType is "stacked" then star.starType else @_indentChars() for row in [star.startRow..star.endRow] editor.setTextInBufferRange([[row, 0], [row, 0]], indent) else editor.indentSelectedRows() insert8601Date: (event) -> d = new Date() editor = atom.workspace.getActiveTextEditor() editor.insertText(@_getISO8601Date(d)) insert8601DateTime: (event) -> d = new Date() editor = atom.workspace.getActiveTextEditor() editor.insertText(@_getISO8601Date(d) + "T" + @_getISO8601Time(d)) makeCodeBlock: (event) -> if editor = atom.workspace.getActiveTextEditor() position = editor.getCursorBufferPosition() editor.transact 1000, () => if not editor.lineTextForBufferRow(position.row).match(/\s*/) editor.insertNewline() editor.insertText('```') endPosition = editor.getCursorBufferPosition() editor.insertNewline() editor.insertText('```') editor.setCursorBufferPosition(endPosition) makeResultBlock: (event) -> if editor = atom.workspace.getActiveTextEditor() position = editor.getCursorBufferPosition() editor.transact 1000, () => if not editor.lineTextForBufferRow(position.row).match(/\s*/) editor.insertNewline() editor.insertText('```result') editor.insertNewline() editor.insertText('```') makeLink: (event) -> if editor = atom.workspace.getActiveTextEditor() editor.transact 1000, () => @_withAllSelectedLines editor, (position, selection) => if selection.isEmpty() editor.insertText("[]()") selection.cursor.moveLeft(3) else range = selection.getBufferRange() if selection.getText().match(/^https?:\/\//) editor.setTextInBufferRange([range.end, range.end], ")") editor.setTextInBufferRange([range.start, range.start], "[](") else editor.setTextInBufferRange([range.end, range.end], "]()") editor.setTextInBufferRange([range.start, range.start], "[") # Respond to someone pressing enter. # There's some special handling here. The auto-intent that's built into atom does a good job, but I want the # new text to be even with the start of the text, not the start of the star. newLine: (event) -> if editor = atom.workspace.getActiveTextEditor() if star = @_starInfo() editor.transact 1000, () => editor.insertNewline() spaceCount = star.startTodoCol - star.starCol indent = @_levelWhitespace(star, editor).repeat(star.indentLevel) + " ".repeat(spaceCount) # console.log("spaceCount: #{spaceCount}, indentLevel: #{star.indentLevel}, levelWhiteSpace='#{@_levelWhitespace(star, editor)}'") newPosition = editor.getCursorBufferPosition() editor.transact 1000, () => editor.setTextInBufferRange([[newPosition.row, 0],[newPosition.row, newPosition.column]], indent) editor.setCursorBufferPosition([newPosition.row, indent.length]) else editor.insertNewline() newStarLine: (event) -> if editor = atom.workspace.getActiveTextEditor() # Bail out if the user didn't want any special behavior if !@createStarsOnEnter editor.insertNewline() return # If a user hits return and they haven't really done anything on this line, # treat it like an unindent. It seems awkward to add another empty one. oldPosition = editor.getCursorBufferPosition() line = editor.lineTextForBufferRow(oldPosition.row) if line.match(/([\*\-\+]|\d+\.|[A-z]\.) $/) @unindent() return # If the previous line was entirely empty, it seems like the outline is kind # of "done". Don't try to restart it yet. if line.match(/^\s*$/) editor.insertNewline() return # Make sure we aren't in the middle of a codeblock row = oldPosition.row line = editor.lineTextForBufferRow(row) star = @_starInfo() minRow = if star then star.startRow else 0 while row > minRow and not line.match(/^\s*```/) row -= 1 line = editor.lineTextForBufferRow(row) if line.match(/^\s*```/) # Just add a newline, we're in the middle of a code block editor.insertNewline() return # Figure out where we were so we can use it to figure out where to put the star # and what kind of star to use # Really hit return now editor.transact 1000, () => # If there is a star on the next line, we'll use it's insert level and bullet type # We'll keep a reference to the old star because we need it sometimes oldStar = star if oldPosition.row+1 <= editor.getLastBufferRow() if nextStar = @_starInfo(editor, new Point(oldPosition.row+1, oldPosition.col)) if not star or nextStar.indentLevel > star.indentLevel star = nextStar if star and star.indentLevel >= 0 editor.insertNewline() if oldPosition.column <= star.starCol # If the cursor on a column before the star on the line, just insert a newline return #Create our new text to insert newPosition = editor.getCursorBufferPosition() if star.starType is 'numbers' # Make sure we use a reference to the old star here so we get the editor.setTextInBufferRange([[newPosition.row, 0], [newPosition.row, Infinity]], oldStar.newStarLine()) position = new Point(newPosition.row+1, 0) #console.log("newPosition+1: #{position}, last buffer row: #{editor.getLastBufferRow()}") while position.row <= editor.getLastBufferRow() and nextStar = @_starInfo(editor, position) if nextStar.starType isnt 'numbers' or nextStar.indentLevel isnt star.indentLevel break #console.log("Position: #{position}, nextStar.startRow: #{nextStar.startRow}, nextStar.endRow: #{nextStar.endRow}") #console.log("Replacing #{nextStar.currentNumber} with #{nextStar.nextNumber}") editor.setTextInBufferRange([[nextStar.startRow, nextStar.starCol], [nextStar.startRow, nextStar.starCol+(""+nextStar.currentNumber).length]], "" + nextStar.nextNumber) position = new Point(nextStar.endRow+1, 0) else if star.starType is 'letters' # Make sure we use a reference to the old star here so we get the editor.setTextInBufferRange([[newPosition.row, 0], [newPosition.row, Infinity]], oldStar.newStarLine()) position = new Point(newPosition.row+1, 0) #console.log("newPosition+1: #{position}, last buffer row: #{editor.getLastBufferRow()}") while position.row <= editor.getLastBufferRow() and nextStar = @_starInfo(editor, position) if nextStar.starType isnt 'letters' or nextStar.indentLevel isnt star.indentLevel break #console.log("Position: #{position}, nextStar.startRow: #{nextStar.startRow}, nextStar.endRow: #{nextStar.endRow}") #console.log("Replacing #{nextStar.currentNumber} with #{nextStar.nextNumber}") editor.setTextInBufferRange([[nextStar.startRow, nextStar.starCol], [nextStar.startRow, nextStar.starCol+(""+nextStar.currentLetter).length]], "" + nextStar.nextLetter) position = new Point(nextStar.endRow+1, 0) else indent = star.newStarLine() editor.transact 1000, () => editor.setTextInBufferRange([[newPosition.row, 0],[newPosition.row, newPosition.column]], indent) editor.setCursorBufferPosition([newPosition.row, indent.length]) else editor.insertNewline() newTableRow: () -> if editor = atom.workspace.getActiveTextEditor() oldPosition = editor.getCursorBufferPosition() line = editor.lineTextForBufferRow(oldPosition.row) if match = line.match(/^\s*(\|[ ]?)/) editor.transact 1000, () -> editor.insertNewline() editor.insertText(match[0]) else editor.insertNewline() openTable: (event) -> if editor = atom.workspace.getActiveTextEditor() currentPosition = editor.getCursorBufferPosition() line = editor.lineTextForBufferRow(currentPosition.row) if match = line.match(/^(\s*)/) editor.insertText("+----+\n#{match[0]}| ") serialize: () -> return { organizedViewState: @organizedView.serialize() } scheduleItem: (event) -> @_addMarkerDate("SCHEDULED") setTodo: (event) -> if editor = atom.workspace.getActiveTextEditor() visited = {} startPosition = editor.getCursorBufferPosition() startRow = startPosition.row @_withAllSelectedLines editor, (position, selection) => if visited[position.row] return if star = @_starInfo(editor, position) for i in [star.startRow..star.endRow] visited[i] = true line = editor.lineTextForBufferRow(star.startRow) editor.setTextInBufferRange([[star.startRow, star.startTodoCol], [star.startRow, star.startTextCol]], " [TODO] ") setTodoCompleted: (event) -> if editor = atom.workspace.getActiveTextEditor() visited = {} startPosition = editor.getCursorBufferPosition() startRow = startPosition.row @_withAllSelectedLines editor, (position, selection) => if visited[position.row] return if star = @_starInfo(editor, position) for i in [star.startRow..star.endRow] visited[i] = true line = editor.lineTextForBufferRow(star.startRow) editor.setTextInBufferRange([[star.startRow, star.whitespaceCol], [star.startRow, star.startTextCol]], " [DONE] ") tableChange: (event) -> if not @autoSizeTables return if editor = atom.workspace.getActiveTextEditor() scopes = editor.getLastCursor().getScopeDescriptor().getScopesArray() if 'row.table.organized' in scopes or 'border.table.organized' in scopes table = new Table(editor) return unless table.found? # Getting closer, but not there yet. #table.normalizeRowSizes() tableStoppedChanging: (event) -> return unless @autoSizeTables # if editor = atom.workspace.getActiveTextEditor() # scopes = editor.getLastCursor().getScopeDescriptor().getScopesArray() # if 'row.table.organized' in scopes or 'border.table.organized' in scopes # console.log("Stopped changing") toggleBold: (event) -> if editor = atom.workspace.getActiveTextEditor() editor.transact 1000, () => @_withAllSelectedLines editor, (position, selection) => if selection.isEmpty() editor.insertText("____") selection.cursor.moveLeft(2) else range = selection.getBufferRange() startMarked = editor.getTextInBufferRange([range.start, [range.start.row, range.start.column+2]]) is "__" endMarked = editor.getTextInBufferRange([[range.end.row, range.end.column-2], range.end]) is "__" if startMarked and endMarked editor.setTextInBufferRange([[range.end.row, range.end.column-2], range.end], "") editor.setTextInBufferRange([range.start, [range.start.row, range.start.column+2]], "") else editor.setTextInBufferRange([range.end, range.end], '__') editor.setTextInBufferRange([range.start, range.start], "__") toggleHeading: (event) -> if editor = atom.workspace.getActiveTextEditor() editor.transact 1000, () => @_withAllSelectedLines editor, (position, selection) => startChars = editor.getTextInBufferRange([[position.row, 0], [position.row, 4]]) hashCount = 0 hashCount +=1 until startChars[hashCount] isnt '#' if hashCount is 0 editor.setTextInBufferRange([[position.row, 0], [position.row, 0]], '# ') else if hashCount < 3 editor.setTextInBufferRange([[position.row, 0], [position.row, 0]], '#') else charsToDelete = if startChars[3] is ' ' then 4 else 3 editor.setTextInBufferRange([[position.row, 0], [position.row, charsToDelete]], '') toggleTodo: (event) -> if editor = atom.workspace.getActiveTextEditor() visited = {} startPosition = editor.getCursorBufferPosition() startRow = startPosition.row @_withAllSelectedLines editor, (position, selection) => if visited[position.row] return if star = @_starInfo(editor, position) for i in [star.startRow..star.endRow] visited[i] = true line = editor.lineTextForBufferRow(star.startRow) if match = line.match(/\s*([\-\+\*]+|\d+\.|[A-z]\.) (\[(TODO)\]|TODO) /) replacement = if match[2].includes('[') then " [DONE] " else " DONE " editor.transact 1000, () => editor.setTextInBufferRange([[star.startRow, star.whitespaceCol], [star.startRow, star.startTextCol]], replacement) if @trackCloseTimeOfTodos d = new Date() closeText = "CLOSED: [#{@_getISO8601DateTime(d)}]" line = editor.lineTextForBufferRow(star.startRow+1) if line and line.indexOf("SCHEDULED: <") > -1 editor.setTextInBufferRange([[star.startRow+1, star.startTodoCol], [star.startRow+1, star.startTodoCol]], closeText + " ") else spaceCount = star.startTodoCol - star.starCol indent = @_levelWhitespace(star, editor).repeat(star.indentLevel) + " ".repeat(spaceCount) closeText = "\n" + indent + closeText + "\n" editor.setTextInBufferRange([[star.startRow, Infinity],[star.startRow+1, 0]], closeText) else if (line.match(/\s*([\-\+\*]+|\d+.|[A-z]\.) ((\[(COMPLETED|DONE)\])|(COMPLETED|DONE)) /)) editor.transact 1000, () => editor.setTextInBufferRange([[star.startRow, star.whitespaceCol], [star.startRow, star.startTextCol]], " ") line = editor.lineTextForBufferRow(star.startRow+1) if line if match = line.match(/^\s*CLOSED: \[[^\]]+\]\s*$/) editor.setTextInBufferRange([[star.startRow, Infinity], [star.startRow+1, Infinity]], "") else line = line.replace(/CLOSED: \[[^\]]+\]\s*/, "") editor.setTextInBufferRange([[star.startRow+1, 0], [star.startRow+1, Infinity]], line) else replacement = if @useBracketsAroundTodoTags then " [TODO] " else " TODO " editor.setTextInBufferRange([[star.startRow, star.whitespaceCol], [star.startRow, star.startTextCol]], replacement) toggleUnderline: (event) -> if editor = atom.workspace.getActiveTextEditor() editor.transact 1000, () => @_withAllSelectedLines editor, (position, selection) => if selection.isEmpty() editor.insertText('__') selection.cursor.moveLeft(1) else range = selection.getBufferRange() startThree = editor.getTextInBufferRange([range.start, [range.start.row, range.start.column+3]]) endThree = editor.getTextInBufferRange([[range.end.row, range.end.column-3], range.end]) # Need to consider situations where there is a bold and an underline startMatch = startThree.match(/(_[^_][^_]|___)/) endMatch = endThree.match(/([^_][^_]_|___)/) if startMatch and endMatch editor.setTextInBufferRange([[range.end.row, range.end.column-1], range.end], "") editor.setTextInBufferRange([range.start, [range.start.row, range.start.column+1]], "") else editor.setTextInBufferRange([range.end, range.end], '_') editor.setTextInBufferRange([range.start, range.start], "_") unindent: (event) -> if editor = atom.workspace.getActiveTextEditor() visited = {} editor.transact 2000, () => @_withAllSelectedLines editor, (position, selection) => if visited[position.row] return if star = @_starInfo(editor, position) for i in [star.startRow..star.endRow] visited[i] = true firstRow = star.startRow lastRow = star.endRow #Unindent editor.transact 1000, () -> for row in [firstRow..lastRow] line = editor.lineTextForBufferRow(row) if not line continue else if line.match("^ ") editor.setTextInBufferRange([[row, 0], [row, 2]], "") else if line.match("^\\t") editor.setTextInBufferRange([[row, 0], [row, 1]], "") else if match = line.match(/^([\*\-\+]|\d+\.|[A-z]\.) /) editor.setTextInBufferRange([[row, 0], [row, match[0].length]], "") else if line.match(/^[\*\-\+]/) #Stacked editor.setTextInBufferRange([[row, 0], [row, 1]], "") else #cannot unindent - not sure how to do so else editor.outdentSelectedRows() _addMarkerDate: (dateType) -> if editor = atom.workspace.getActiveTextEditor() visited = {} d = new Date() df = new Intl.DateTimeFormat('en-US', {weekday: 'short'}) dow = df.format(d) @_withAllSelectedLines editor, (position, selection) => if visited[position.row] return if star = @_starInfo(editor, position) for i in [star.startRow..star.endRow] visited[i] = true editor.transact 1000, () => originalPosition = editor.getCursorBufferPosition() # Now add the marker newText = "\n" + " ".repeat(star.startTodoCol) + "#{dateType}: <#{@_getISO8601Date(d)} #{dow}>" col = editor.lineTextForBufferRow(star.startRow).length editor.setTextInBufferRange([[star.startRow, col+1], [star.startRow, col+1]], newText) _archiveFinishedInSubtree: (outputToString) -> if editor = atom.workspace.getActiveTextEditor() visited = {} linesToArchive = [] if not star = @_starInfo(editor, position) return startIndentLevel = star.indentLevel currentLine = star.lineTextForBufferRow() _archiveSubtree: (outputToString) -> if editor = atom.workspace.getActiveTextEditor() visited = {} baseArchiveLevel = null stars = [] # If there are multiple selections, this could span multiple subtrees. Calculate # the total size of the tree first. One possible problem is that we aren't going # to have properties for each of the subtrees when we archive. @_withAllSelectedLines editor, (position, selection) => if visited[position.row] return # Mark all lines in subtree as visited visited[position.row] = true if not star = @_starInfo(editor, position) return # Capture the first star, so we know how deeply to indent the properties if not baseArchiveLevel baseArchiveLevel = star.indentLevel if star.indentLevel == baseArchiveLevel # We need to put properties on this level too, otherwise we won't be able to unarchive it. stars.push(star) endOfSubtree = star.getEndOfSubtree() for line in [star.startRow..endOfSubtree] visited[line] = true # Now act on those lines editor.transact 2000, () => textToInsertIntoArchiveFile = "" rangeToDelete = null # Iterate backwards so we don't change the line number of stars. # Collect the text to delete and the ranges that we are deleting. for star in stars by -1 startOfSubtree = star.startRow endOfSubtree = star.getEndOfSubtree() startTodoCol = star.startTodoCol # Be careful to support selecting out of the end of a file if endOfSubtree == editor.getLastBufferRow() lastCol = editor.lineTextForBufferRow(endOfSubtree).length else endOfSubtree += 1 lastCol = 0 archiveText = editor.lineTextForBufferRow(startOfSubtree) + '\n' archiveText += ' '.repeat(startTodoCol) + ':PROPERTIES:' + '\n' archiveText += ' '.repeat(startTodoCol) + ':ARCHIVE_TIME: ' + moment().format('YYYY-MM-DD ddd HH:mm') + '\n' if path = editor.getPath() archiveText += ' '.repeat(startTodoCol) + ':ARCHIVE_FILE: ' + path + "\n" archiveText += ' '.repeat(startTodoCol) + ':END:' + "\n" # If end is the same as the beginning, we've already gotten all of the text if endOfSubtree > startOfSubtree archiveText += editor.getTextInBufferRange([[startOfSubtree+1, 0], [endOfSubtree, lastCol]]) if textToInsertIntoArchiveFile isnt '' textToInsertIntoArchiveFile = archiveText + textToInsertIntoArchiveFile else textToInsertIntoArchiveFile = archiveText starRangeToDelete = [[startOfSubtree, 0], [endOfSubtree, lastCol]] # Increase the total range we are deleting to encompass this star too if not rangeToDelete rangeToDelete = starRangeToDelete # Is this later than our selection to delete? if starRangeToDelete[1][0] > rangeToDelete[1][0] rangeToDelete[1] = starRangeToDelete[1] # Is this earlier than our earliest selection to delete? if starRangeToDelete[0][0] < rangeToDelete[0][0] rangeToDelete[0] = starRangeToDelete[0] # If there is actually something to archive, do that now if rangeToDelete if outputToString editor.setTextInBufferRange(rangeToDelete, '') return textToInsertIntoArchiveFile.trimLeft() else if not archiveFilename = editor.getPath() + '_archive' archiveFilename = dialog.showSaveDialog({title: 'Archive filename', message: 'Choose the file where this content will be moved to'}) if not archiveFilename return fs.stat archiveFilename, (err, stat) -> if err == fs.ENOENT or (not err and stat.size == 0) textToInsertIntoArchiveFile = textToInsertIntoArchiveFile.trimLeft() else if err atom.notifications.addError("Unable to archive content due to error: " + err, options) fs.appendFile archiveFilename, textToInsertIntoArchiveFile, (err) -> if err atom.notifications.addError("Unable to archive content due to error: " + err) else editor.setTextInBufferRange(rangeToDelete, '') _changePriority: (up) -> if editor = atom.workspace.getActiveTextEditor() visited = {} editor.transact 1000, () => @_withAllSelectedLines editor, (position, selection) => if visited[position.row] return if star = @_starInfo(editor, position) for i in [star.startRow..star.endRow] visited[i] = true if up star.increasePriority(editor) else star.decreasePriority(editor) _cycleVisibility: (editor, globalStartRow, globalEndRow) -> currentRow = globalStartRow while currentRow < globalEndRow startStar = @_starInfo(editor, new Point(currentRow, 3)) if not startStar currentRow += 1 continue startRow = currentRow lastRow = startStar.getEndOfSubtree() if editor.isFoldedAtBufferRow(startRow) # We are folded at the global level, unfold this level and fold all the children for i in [startStar.startRow..lastRow] editor.unfoldBufferRow(i) # Now fold all the rows at indentLevel+1 currentStar = @_starInfo(editor, new Point(startStar.endRow+1, startStar.starCol)) while currentStar != null and currentStar.endRow < editor.getLastBufferRow() and currentStar.endRow <= lastRow if currentStar.indentLevel == startStar.indentLevel+1 currentStarLastRow = currentStar.getEndOfSubtree() if currentStarLastRow > currentStar.startRow editor.foldBufferRange([[currentStar.startRow, Infinity],[currentStarLastRow, Infinity]]) currentStar = @_starInfo(editor, new Point(currentStar.endRow+1, currentStar.starCol)) else # Check to see if there is any Folding anyFolded = false for i in [startStar.startRow..lastRow] if editor.isFoldedAtBufferRow(i) anyFolded = true break if anyFolded # Unfold all for i in [startStar.startRow..lastRow] editor.unfoldBufferRow(i) else firstEnd = editor.lineTextForBufferRow(startStar.startRow).length editor.foldBufferRange([[startStar.startRow, firstEnd], [lastRow, Infinity]]) currentRow = lastRow + 1 _getISO8601Date: (date) -> year = ("0000" + date.getFullYear()).substr(-4, 4) month = ("00" + (date.getMonth() + 1)).substr(-2, 2) date = ("00" + date.getDate()).substr(-2, 2) "" + year + "-" + month + "-" + date _getISO8601DateTime: (date) -> return @_getISO8601Date(date) + "T" + @_getISO8601Time(date) _getISO8601Time: (date) -> offset = date.getTimezoneOffset() if offset is 0 offsetString = "Z" else negative = offset < 0; offsetHours = ("00" + Math.floor(offset/60)).substr(-2, 2) offsetMinutes = ("00" + (offset % 60)).substr(-2, 2) offsetString = if negative then "-" else "+" offsetString += offsetHours + ":" + offsetMinutes hours = ("00" + date.getHours()).substr(-2, 2) minutes = ("00" + date.getMinutes()).substr(-2, 2) seconds = ("00" + date.getSeconds()).substr(-2, 2) "" + hours + ":" + minutes + ":" + seconds + offsetString _indentChars: (star=null, editor=atom.workspace.getActiveTextEditor(), position=editor.getCursorBufferPosition()) -> if star and star.indentType isnt "mixed" and star.indentType isnt "none" indentStyle = star.indentType else if @levelStyle is "whitespace" indentStyle = if editor.getSoftTabs() then "spaces" else "tabs" else indentStyle = @levelStyle if indentStyle is "spaces" indent = " ".repeat(@indentSpaces) else if indentStyle is "tabs" indent = "\t" else if indentStyle is "stacked" if not star star = @_starInfo() indent = star.starType return indent _levelWhitespace: (star=null, editor=atom.workspace.getActiveTextEditor()) -> if not star star = @_starInfo(editor) # console.log("star: #{star}, indentType: #{star.indentType}, softTabs: #{editor.getSoftTabs()}") if star and star.indentType is "stacked" indent = "" else if editor.getSoftTabs() indent = " ".repeat(@indentSpaces) else indent = "\t" return indent _starInfo: (editor=atom.workspace.getActiveTextEditor(), position=editor.getCursorBufferPosition()) -> # Returns the following info # * Start Position of last star # * Last line of star # * Type of star (*, -, +, number) # * Type of whitespace (tabs, spaces, stacked, mixed) if not editor console.error("Editor is required") return if not position console.error("Position is required") return # Find the line with the last star. If you find blank lines or a header, there probably isn't a # star for this position currentLine = position.row star = new Star(currentLine, @indentSpaces, @levelStyle) if star.startRow >= 0 return star else return null _withAllSelectedLines: (editor, callback) -> editor = atom.workspace.getActiveTextEditor() unless editor if editor selections = editor.getSelections() for selection in selections range = selection.getBufferRange() #Adjust for selections that span the whole line if range.end.column is 0 and (range.start.column isnt range.end.column or range.start.row isnt range.end.row) if line = editor.lineTextForBufferRow(range.end.row-1) range.end = new Point(range.end.row-1, line.length-1) for i in [range.start.row..range.end.row] # Create a virtual position object from the range object if i is range.end.row position = new Point(i, range.end.col) else if i is range.start.row position = new Point(i, range.start.col) else position = new Point(i, 0) callback(position, selection)
[ { "context": "\n###\n Partially extracted from https://github.com/padolsey/mini/blob/master/mini.js\n \"mini\" Selector Engine\n", "end": 90, "score": 0.9977962374687195, "start": 82, "tag": "USERNAME", "value": "padolsey" }, { "context": "ini.js\n \"mini\" Selector Engine\n Copyrigh...
src/tb/lib/ti/helpers/mini.coffee
vcu/titanium-backbone
1
matchers = require './matchers' ### Partially extracted from https://github.com/padolsey/mini/blob/master/mini.js "mini" Selector Engine Copyright (c) 2009 James Padolsey ------------------------------------------------------- Dual licensed under the MIT and GPL licenses. - http://www.opensource.org/licenses/mit-license.php - http://www.gnu.org/copyleft/gpl.html ------------------------------------------------------- Version: 0.01 (BETA) ### snack = /(?:[\w\-\\.#]+)+(?:\[\w+?=([\'"])?(?:\\\1|.)+?\1\])?|\*|>/ig findOne = (context, test) -> return unless context if _.isArray context if result = _.find(context, (el) -> findOne el, test) result else if test context context else findOne context.children, test # This is likely not very efficient findAll = (context, test, collector = [], include = true) -> return [] unless context if _.isArray context $(context).each -> findAll @, test, collector else context = $(context).get 0 collector.push context if include and test(context) findAll $(context).children(), test, collector collector findById = (id, context) -> findOne context, (el) -> el.id is id findByNodeAndClassName = (nodeName, className, context, include = true) -> findAll context, ((el) -> matchers.hasNameClassAttrs el, nodeName, className), [], include filterParents = (selectorParts, collection, direct) -> parentSelector = selectorParts.pop() if parentSelector is '>' return filterParents selectorParts, collection, true ret = [] { id, className, nodeName } = matchers.parseSelector parentSelector for node in collection parent = node.parent while parent matches = matchers.isIdNameClass parent, id, nodeName, className break if direct or matches parent = parent.parent if matches ret.push node if selectorParts[0] and ret[0] then filterParents(selectorParts, ret) else ret _is = (selector, context) -> parts = selector.match snack part = parts.pop() if matchers.matches context, part if parts[0] filterParents(parts, [context]).length > 0 else true find = (selector = '*', context, includeSelf = false) -> parts = selector.match snack part = parts.pop() if selector.indexOf(',') > -1 ret = [] for selector in selector.split(/,/g) ret = _.uniq ret.concat find selector.trim(), context return ret { id, className, nodeName } = matchers.parseSelector part if id return if child = findById(id, context) then [child] else [] else collection = findByNodeAndClassName nodeName, className, context, includeSelf if parts[0] and collection[0] then filterParents(parts, collection) else collection module.exports = find: find is: _is
133312
matchers = require './matchers' ### Partially extracted from https://github.com/padolsey/mini/blob/master/mini.js "mini" Selector Engine Copyright (c) 2009 <NAME> ------------------------------------------------------- Dual licensed under the MIT and GPL licenses. - http://www.opensource.org/licenses/mit-license.php - http://www.gnu.org/copyleft/gpl.html ------------------------------------------------------- Version: 0.01 (BETA) ### snack = /(?:[\w\-\\.#]+)+(?:\[\w+?=([\'"])?(?:\\\1|.)+?\1\])?|\*|>/ig findOne = (context, test) -> return unless context if _.isArray context if result = _.find(context, (el) -> findOne el, test) result else if test context context else findOne context.children, test # This is likely not very efficient findAll = (context, test, collector = [], include = true) -> return [] unless context if _.isArray context $(context).each -> findAll @, test, collector else context = $(context).get 0 collector.push context if include and test(context) findAll $(context).children(), test, collector collector findById = (id, context) -> findOne context, (el) -> el.id is id findByNodeAndClassName = (nodeName, className, context, include = true) -> findAll context, ((el) -> matchers.hasNameClassAttrs el, nodeName, className), [], include filterParents = (selectorParts, collection, direct) -> parentSelector = selectorParts.pop() if parentSelector is '>' return filterParents selectorParts, collection, true ret = [] { id, className, nodeName } = matchers.parseSelector parentSelector for node in collection parent = node.parent while parent matches = matchers.isIdNameClass parent, id, nodeName, className break if direct or matches parent = parent.parent if matches ret.push node if selectorParts[0] and ret[0] then filterParents(selectorParts, ret) else ret _is = (selector, context) -> parts = selector.match snack part = parts.pop() if matchers.matches context, part if parts[0] filterParents(parts, [context]).length > 0 else true find = (selector = '*', context, includeSelf = false) -> parts = selector.match snack part = parts.pop() if selector.indexOf(',') > -1 ret = [] for selector in selector.split(/,/g) ret = _.uniq ret.concat find selector.trim(), context return ret { id, className, nodeName } = matchers.parseSelector part if id return if child = findById(id, context) then [child] else [] else collection = findByNodeAndClassName nodeName, className, context, includeSelf if parts[0] and collection[0] then filterParents(parts, collection) else collection module.exports = find: find is: _is
true
matchers = require './matchers' ### Partially extracted from https://github.com/padolsey/mini/blob/master/mini.js "mini" Selector Engine Copyright (c) 2009 PI:NAME:<NAME>END_PI ------------------------------------------------------- Dual licensed under the MIT and GPL licenses. - http://www.opensource.org/licenses/mit-license.php - http://www.gnu.org/copyleft/gpl.html ------------------------------------------------------- Version: 0.01 (BETA) ### snack = /(?:[\w\-\\.#]+)+(?:\[\w+?=([\'"])?(?:\\\1|.)+?\1\])?|\*|>/ig findOne = (context, test) -> return unless context if _.isArray context if result = _.find(context, (el) -> findOne el, test) result else if test context context else findOne context.children, test # This is likely not very efficient findAll = (context, test, collector = [], include = true) -> return [] unless context if _.isArray context $(context).each -> findAll @, test, collector else context = $(context).get 0 collector.push context if include and test(context) findAll $(context).children(), test, collector collector findById = (id, context) -> findOne context, (el) -> el.id is id findByNodeAndClassName = (nodeName, className, context, include = true) -> findAll context, ((el) -> matchers.hasNameClassAttrs el, nodeName, className), [], include filterParents = (selectorParts, collection, direct) -> parentSelector = selectorParts.pop() if parentSelector is '>' return filterParents selectorParts, collection, true ret = [] { id, className, nodeName } = matchers.parseSelector parentSelector for node in collection parent = node.parent while parent matches = matchers.isIdNameClass parent, id, nodeName, className break if direct or matches parent = parent.parent if matches ret.push node if selectorParts[0] and ret[0] then filterParents(selectorParts, ret) else ret _is = (selector, context) -> parts = selector.match snack part = parts.pop() if matchers.matches context, part if parts[0] filterParents(parts, [context]).length > 0 else true find = (selector = '*', context, includeSelf = false) -> parts = selector.match snack part = parts.pop() if selector.indexOf(',') > -1 ret = [] for selector in selector.split(/,/g) ret = _.uniq ret.concat find selector.trim(), context return ret { id, className, nodeName } = matchers.parseSelector part if id return if child = findById(id, context) then [child] else [] else collection = findByNodeAndClassName nodeName, className, context, includeSelf if parts[0] and collection[0] then filterParents(parts, collection) else collection module.exports = find: find is: _is
[ { "context": ".log Songs.get_count()\n# => 0\n\n\nsong = new Songs(\"Rick Astley\", \"Never Gonna Give You Up\")\nconsole.log Songs.ge", "end": 414, "score": 0.9998939633369446, "start": 403, "tag": "NAME", "value": "Rick Astley" } ]
test/coffee_scoping_test.coffee
orospakr/diatropikon
5
class Songs @_titles: 0 # Although it's directly accessible, the leading _ defines it by convention as private property. @get_count: -> # console.log "GET COUNT THIS IS " + this @_titles constructor: (@artist, @title) -> Songs._titles++ class Poop extends Songs @poop_method: -> console.log @get_count() console.log Songs.get_count() # => 0 song = new Songs("Rick Astley", "Never Gonna Give You Up") console.log Songs.get_count() # => 1 console.log Poop.get_count() mypoop = Poop("fsadfasdf") console.log Songs.get_count() # => 2 # song.get_count() # => TypeError: Object <Songs> has no method 'get_count'
10224
class Songs @_titles: 0 # Although it's directly accessible, the leading _ defines it by convention as private property. @get_count: -> # console.log "GET COUNT THIS IS " + this @_titles constructor: (@artist, @title) -> Songs._titles++ class Poop extends Songs @poop_method: -> console.log @get_count() console.log Songs.get_count() # => 0 song = new Songs("<NAME>", "Never Gonna Give You Up") console.log Songs.get_count() # => 1 console.log Poop.get_count() mypoop = Poop("fsadfasdf") console.log Songs.get_count() # => 2 # song.get_count() # => TypeError: Object <Songs> has no method 'get_count'
true
class Songs @_titles: 0 # Although it's directly accessible, the leading _ defines it by convention as private property. @get_count: -> # console.log "GET COUNT THIS IS " + this @_titles constructor: (@artist, @title) -> Songs._titles++ class Poop extends Songs @poop_method: -> console.log @get_count() console.log Songs.get_count() # => 0 song = new Songs("PI:NAME:<NAME>END_PI", "Never Gonna Give You Up") console.log Songs.get_count() # => 1 console.log Poop.get_count() mypoop = Poop("fsadfasdf") console.log Songs.get_count() # => 2 # song.get_count() # => TypeError: Object <Songs> has no method 'get_count'
[ { "context": "egistry keys used for context menu\nfileKeyPath = 'HKCU\\\\Software\\\\Classes\\\\*\\\\shell\\\\Atom'\ndirectoryKeyPath = 'HKCU\\\\Software\\\\Classes\\\\dir", "end": 309, "score": 0.9994993209838867, "start": 270, "tag": "KEY", "value": "HKCU\\\\Software\\\\Classes\\\\*\\\\she...
src/main-process/win-registry.coffee
noscripter/atom
2
path = require 'path' Spawner = require './spawner' if process.env.SystemRoot system32Path = path.join(process.env.SystemRoot, 'System32') regPath = path.join(system32Path, 'reg.exe') else regPath = 'reg.exe' # Registry keys used for context menu fileKeyPath = 'HKCU\\Software\\Classes\\*\\shell\\Atom' directoryKeyPath = 'HKCU\\Software\\Classes\\directory\\shell\\Atom' backgroundKeyPath = 'HKCU\\Software\\Classes\\directory\\background\\shell\\Atom' applicationsKeyPath = 'HKCU\\Software\\Classes\\Applications\\atom.exe' # Spawn reg.exe and callback when it completes spawnReg = (args, callback) -> Spawner.spawn(regPath, args, callback) # Install the Open with Atom explorer context menu items via the registry. # # * `callback` The {Function} to call after registry operation is done. # It will be invoked with the same arguments provided by {Spawner.spawn}. # # Returns `undefined`. exports.installContextMenu = (callback) -> addToRegistry = (args, callback) -> args.unshift('add') args.push('/f') spawnReg(args, callback) installFileHandler = (callback) -> args = ["#{applicationsKeyPath}\\shell\\open\\command", '/ve', '/d', "\"#{process.execPath}\" \"%1\""] addToRegistry(args, callback) installMenu = (keyPath, arg, callback) -> args = [keyPath, '/ve', '/d', 'Open with Atom'] addToRegistry args, -> args = [keyPath, '/v', 'Icon', '/d', "\"#{process.execPath}\""] addToRegistry args, -> args = ["#{keyPath}\\command", '/ve', '/d', "\"#{process.execPath}\" \"#{arg}\""] addToRegistry(args, callback) installMenu fileKeyPath, '%1', -> installMenu directoryKeyPath, '%1', -> installMenu backgroundKeyPath, '%V', -> installFileHandler(callback) # Uninstall the Open with Atom explorer context menu items via the registry. # # * `callback` The {Function} to call after registry operation is done. # It will be invoked with the same arguments provided by {Spawner.spawn}. # # Returns `undefined`. exports.uninstallContextMenu = (callback) -> deleteFromRegistry = (keyPath, callback) -> spawnReg(['delete', keyPath, '/f'], callback) deleteFromRegistry fileKeyPath, -> deleteFromRegistry directoryKeyPath, -> deleteFromRegistry backgroundKeyPath, -> deleteFromRegistry(applicationsKeyPath, callback)
219226
path = require 'path' Spawner = require './spawner' if process.env.SystemRoot system32Path = path.join(process.env.SystemRoot, 'System32') regPath = path.join(system32Path, 'reg.exe') else regPath = 'reg.exe' # Registry keys used for context menu fileKeyPath = '<KEY>' directoryKeyPath = '<KEY>' backgroundKeyPath = '<KEY>' applicationsKeyPath = '<KEY>' # Spawn reg.exe and callback when it completes spawnReg = (args, callback) -> Spawner.spawn(regPath, args, callback) # Install the Open with Atom explorer context menu items via the registry. # # * `callback` The {Function} to call after registry operation is done. # It will be invoked with the same arguments provided by {Spawner.spawn}. # # Returns `undefined`. exports.installContextMenu = (callback) -> addToRegistry = (args, callback) -> args.unshift('add') args.push('/f') spawnReg(args, callback) installFileHandler = (callback) -> args = ["#{applicationsKeyPath}\\shell\\open\\command", '/ve', '/d', "\"#{process.execPath}\" \"%1\""] addToRegistry(args, callback) installMenu = (keyPath, arg, callback) -> args = [keyPath, '/ve', '/d', 'Open with Atom'] addToRegistry args, -> args = [keyPath, '/v', 'Icon', '/d', "\"#{process.execPath}\""] addToRegistry args, -> args = ["#{keyPath}\\command", '/ve', '/d', "\"#{process.execPath}\" \"#{arg}\""] addToRegistry(args, callback) installMenu fileKeyPath, '%1', -> installMenu directoryKeyPath, '%1', -> installMenu backgroundKeyPath, '%V', -> installFileHandler(callback) # Uninstall the Open with Atom explorer context menu items via the registry. # # * `callback` The {Function} to call after registry operation is done. # It will be invoked with the same arguments provided by {Spawner.spawn}. # # Returns `undefined`. exports.uninstallContextMenu = (callback) -> deleteFromRegistry = (keyPath, callback) -> spawnReg(['delete', keyPath, '/f'], callback) deleteFromRegistry fileKeyPath, -> deleteFromRegistry directoryKeyPath, -> deleteFromRegistry backgroundKeyPath, -> deleteFromRegistry(applicationsKeyPath, callback)
true
path = require 'path' Spawner = require './spawner' if process.env.SystemRoot system32Path = path.join(process.env.SystemRoot, 'System32') regPath = path.join(system32Path, 'reg.exe') else regPath = 'reg.exe' # Registry keys used for context menu fileKeyPath = 'PI:KEY:<KEY>END_PI' directoryKeyPath = 'PI:KEY:<KEY>END_PI' backgroundKeyPath = 'PI:KEY:<KEY>END_PI' applicationsKeyPath = 'PI:KEY:<KEY>END_PI' # Spawn reg.exe and callback when it completes spawnReg = (args, callback) -> Spawner.spawn(regPath, args, callback) # Install the Open with Atom explorer context menu items via the registry. # # * `callback` The {Function} to call after registry operation is done. # It will be invoked with the same arguments provided by {Spawner.spawn}. # # Returns `undefined`. exports.installContextMenu = (callback) -> addToRegistry = (args, callback) -> args.unshift('add') args.push('/f') spawnReg(args, callback) installFileHandler = (callback) -> args = ["#{applicationsKeyPath}\\shell\\open\\command", '/ve', '/d', "\"#{process.execPath}\" \"%1\""] addToRegistry(args, callback) installMenu = (keyPath, arg, callback) -> args = [keyPath, '/ve', '/d', 'Open with Atom'] addToRegistry args, -> args = [keyPath, '/v', 'Icon', '/d', "\"#{process.execPath}\""] addToRegistry args, -> args = ["#{keyPath}\\command", '/ve', '/d', "\"#{process.execPath}\" \"#{arg}\""] addToRegistry(args, callback) installMenu fileKeyPath, '%1', -> installMenu directoryKeyPath, '%1', -> installMenu backgroundKeyPath, '%V', -> installFileHandler(callback) # Uninstall the Open with Atom explorer context menu items via the registry. # # * `callback` The {Function} to call after registry operation is done. # It will be invoked with the same arguments provided by {Spawner.spawn}. # # Returns `undefined`. exports.uninstallContextMenu = (callback) -> deleteFromRegistry = (keyPath, callback) -> spawnReg(['delete', keyPath, '/f'], callback) deleteFromRegistry fileKeyPath, -> deleteFromRegistry directoryKeyPath, -> deleteFromRegistry backgroundKeyPath, -> deleteFromRegistry(applicationsKeyPath, callback)
[ { "context": "\n width = 400\n height = 400\n me = 'Konstantin Denerz'\n window.color = d3.scale.category20()\n\n ", "end": 436, "score": 0.9998458027839661, "start": 419, "tag": "NAME", "value": "Konstantin Denerz" } ]
coffee/skills.coffee
konstantindenerz/cv.konstantin.denerz.com
1
$ ()-> $skills = $ '.skills' window.lab = window.lab or {} window.lab.ui = window.lab.ui or {} window.lab.ui.graph = window.lab.ui.graph or {} # Define helper functions if typeof String.prototype.endsWith isnt 'function' String.prototype.endsWith = (suffix)-> this.indexOf(suffix, this.length - suffix.length) isnt -1 class SkillsGraph init: ()-> width = 400 height = 400 me = 'Konstantin Denerz' window.color = d3.scale.category20() window.force = d3.layout.force() .charge(-150) .linkDistance(25) .size [width, height] svg = d3 .select(".skills .graph") .append("svg") .attr("width", '100%') .attr("height", '100%') .attr('viewBox',"0 0 #{Math.min width, height} #{Math.min width, height}") .attr('preserveAspectRatio','xMinYMin') skills = window.data.skillsData force .nodes(skills.nodes) .links(skills.links) .start() link = svg.selectAll '.link' .data skills.links .enter() .append 'line' .attr 'class', 'link' .style 'stroke-width', (d)-> return Math.sqrt d.value node = svg.selectAll('.node') .data(skills.nodes) .enter() .append 'g' .attr 'data-tooltip', '' .attr 'data-width', (d)-> duration = d.duration || 1 10 + duration * 2 .attr 'class', 'node' .call force.drag node.append 'circle' .attr 'class', 'ic' .attr 'r', (d)-> duration = d.duration || 1 10 + duration * 2 .attr "data-foo", (d)-> d.name .style 'fill', (d)-> if d.name is me return 'transparent' else return color d.group imageWidth = 20 imageHeight = 20 node.append 'image' .attr 'xlink:href', (d)-> if d.name is me return 'style/assets/css/me.png' else if d.duration return 'style/assets/css/p4.png' else switch d.type when 'language' then return 'style/assets/css/language.png' when 'technology' then return 'style/assets/css/technology.png' when 'tool' then return 'style/assets/css/tool.png' .attr 'x', -imageWidth / 2 .attr 'y', -imageHeight / 2 .attr 'width', imageWidth .attr 'height', imageHeight node.append 'div' .attr 'class', 'tooltip-content' .text (d)-> return d.source or d.name force.on 'tick', ()-> link .attr 'x1', (d)-> return d.source.x .attr 'y1', (d)-> return d.source.y .attr 'x2', (d)-> return d.target.x .attr 'y2', (d)-> return d.target.y .style 'stroke-width', (d)-> return Math.sqrt d.value node.attr 'transform', (d)-> return "translate(#{d.x},#{d.y})" node.select '.ic' .attr 'data-selected', (d)-> return window.currentSelection and d.source in window.currentSelection.split(';') .attr 'r', (d)-> duration = d.duration || 1 if window.currentSelection && d.source in window.currentSelection.split(';') return 20 else return 6 + duration node.select 'image' .attr 'x', (d)-> if window.currentSelection && d.source in window.currentSelection.split(';') return -imageWidth else return -imageWidth / 2 .attr 'y', (d)-> if window.currentSelection && d.source in window.currentSelection.split(';') return -imageHeight else return -imageHeight / 2 .attr 'width', (d)-> if window.currentSelection && d.source in window.currentSelection.split(';') return imageWidth * 2 else return imageWidth .attr 'height', (d)-> if window.currentSelection && d.source in window.currentSelection.split(';') return imageHeight * 2 else return imageHeight window.lab.ui.graph.skills = new SkillsGraph lab.ui.graph.skills.init() class SkillsList init: ()-> data = window.data.skillsData sortedNodes = data.nodes.sort (sourceA, sourceB)-> a = $.extend true, {}, sourceA b = $.extend true, {}, sourceB prop = 'source' result = 0 for object in [a, b] object[prop] = if object[prop] then object[prop] else '1' if a[prop].toUpperCase() > b[prop].toUpperCase() result = 1 else if a[prop].toUpperCase() < b[prop].toUpperCase() result = -1 return result types = ['language', 'technology', 'tool'] $skills.find('.type > ul').children().remove() add = (node)-> setCurrentSelection = ()-> window.currentSelection = $(this).attr('data-source') force.start() removeCurrentSelection = ()-> window.currentSelection = undefined # default view $list = $skills.find(".type.#{node.type} > ul") if $list.find("li[data-source=\"#{node.source}\"]").length is 0 bg = color node.group isFav = if node.isFavorite then '<img src="style/assets/css/fav.png">' else "<div class='placeholder'></div>" $item = $("<li data-source='#{node.source}'><div class=color-mapping style='background:#{bg}'></div>#{isFav}<span>#{node.source}</span></li>") $item.appendTo $list $item.hover setCurrentSelection, removeCurrentSelection # view for small devices $list = $skills.find(".type.#{node.type} select") if $list.find("option[data-source=\"#{node.source}\"]").length is 0 $item = $("<option data-source='#{node.source}'>#{node.source}</option>") $item.appendTo $list add node for node in sortedNodes when node.type in types $lists = $skills.find('.type select') $lists.change ()-> window.currentSelection = '' $lists.each ()-> window.currentSelection += if window.currentSelection is '' then '' else ';' window.currentSelection += $(this).val() force.start() lab.ui.graph.skills.list = new SkillsList lab.ui.graph.skills.list.init() lab.ui.tooltip.init '[data-tooltip]', ($object)-> rect = object = $object[0].getBoundingClientRect() result = width: rect.width height: rect.height # Common $lists = $skills.find '.lists' updateTab = ()-> $activeTab = $lists.find 'li.active' for type in ['language', 'technology', 'tool'] $list = $lists.find ".type.#{type}" if $activeTab.hasClass type $list.show() else $list.hide() updateTab() $tabs = $lists.find '.nav li' $tabs.click ()-> $otherTabs = $lists.find('li').not this $otherTabs.removeClass 'active' $activeTab = $ this $activeTab.addClass 'active' updateTab() # Help $helpButton = $skills.find '.help.icon' # Animation for help button helpButtonAnimation = ()-> animation = 'animated wobble' $helpButton.addClass animation window.setTimeout (()-> $helpButton.removeClass animation), 2000 interval = window.setInterval helpButtonAnimation, 5000 $helpButton.hover ()-> window.clearInterval interval, ()-> $helpButton.click ()-> if lab.ui.sidebar.isVisible 'skills-explanation' lab.ui.sidebar.hide() else lab.ui.sidebar.show 'skills-explanation'
80691
$ ()-> $skills = $ '.skills' window.lab = window.lab or {} window.lab.ui = window.lab.ui or {} window.lab.ui.graph = window.lab.ui.graph or {} # Define helper functions if typeof String.prototype.endsWith isnt 'function' String.prototype.endsWith = (suffix)-> this.indexOf(suffix, this.length - suffix.length) isnt -1 class SkillsGraph init: ()-> width = 400 height = 400 me = '<NAME>' window.color = d3.scale.category20() window.force = d3.layout.force() .charge(-150) .linkDistance(25) .size [width, height] svg = d3 .select(".skills .graph") .append("svg") .attr("width", '100%') .attr("height", '100%') .attr('viewBox',"0 0 #{Math.min width, height} #{Math.min width, height}") .attr('preserveAspectRatio','xMinYMin') skills = window.data.skillsData force .nodes(skills.nodes) .links(skills.links) .start() link = svg.selectAll '.link' .data skills.links .enter() .append 'line' .attr 'class', 'link' .style 'stroke-width', (d)-> return Math.sqrt d.value node = svg.selectAll('.node') .data(skills.nodes) .enter() .append 'g' .attr 'data-tooltip', '' .attr 'data-width', (d)-> duration = d.duration || 1 10 + duration * 2 .attr 'class', 'node' .call force.drag node.append 'circle' .attr 'class', 'ic' .attr 'r', (d)-> duration = d.duration || 1 10 + duration * 2 .attr "data-foo", (d)-> d.name .style 'fill', (d)-> if d.name is me return 'transparent' else return color d.group imageWidth = 20 imageHeight = 20 node.append 'image' .attr 'xlink:href', (d)-> if d.name is me return 'style/assets/css/me.png' else if d.duration return 'style/assets/css/p4.png' else switch d.type when 'language' then return 'style/assets/css/language.png' when 'technology' then return 'style/assets/css/technology.png' when 'tool' then return 'style/assets/css/tool.png' .attr 'x', -imageWidth / 2 .attr 'y', -imageHeight / 2 .attr 'width', imageWidth .attr 'height', imageHeight node.append 'div' .attr 'class', 'tooltip-content' .text (d)-> return d.source or d.name force.on 'tick', ()-> link .attr 'x1', (d)-> return d.source.x .attr 'y1', (d)-> return d.source.y .attr 'x2', (d)-> return d.target.x .attr 'y2', (d)-> return d.target.y .style 'stroke-width', (d)-> return Math.sqrt d.value node.attr 'transform', (d)-> return "translate(#{d.x},#{d.y})" node.select '.ic' .attr 'data-selected', (d)-> return window.currentSelection and d.source in window.currentSelection.split(';') .attr 'r', (d)-> duration = d.duration || 1 if window.currentSelection && d.source in window.currentSelection.split(';') return 20 else return 6 + duration node.select 'image' .attr 'x', (d)-> if window.currentSelection && d.source in window.currentSelection.split(';') return -imageWidth else return -imageWidth / 2 .attr 'y', (d)-> if window.currentSelection && d.source in window.currentSelection.split(';') return -imageHeight else return -imageHeight / 2 .attr 'width', (d)-> if window.currentSelection && d.source in window.currentSelection.split(';') return imageWidth * 2 else return imageWidth .attr 'height', (d)-> if window.currentSelection && d.source in window.currentSelection.split(';') return imageHeight * 2 else return imageHeight window.lab.ui.graph.skills = new SkillsGraph lab.ui.graph.skills.init() class SkillsList init: ()-> data = window.data.skillsData sortedNodes = data.nodes.sort (sourceA, sourceB)-> a = $.extend true, {}, sourceA b = $.extend true, {}, sourceB prop = 'source' result = 0 for object in [a, b] object[prop] = if object[prop] then object[prop] else '1' if a[prop].toUpperCase() > b[prop].toUpperCase() result = 1 else if a[prop].toUpperCase() < b[prop].toUpperCase() result = -1 return result types = ['language', 'technology', 'tool'] $skills.find('.type > ul').children().remove() add = (node)-> setCurrentSelection = ()-> window.currentSelection = $(this).attr('data-source') force.start() removeCurrentSelection = ()-> window.currentSelection = undefined # default view $list = $skills.find(".type.#{node.type} > ul") if $list.find("li[data-source=\"#{node.source}\"]").length is 0 bg = color node.group isFav = if node.isFavorite then '<img src="style/assets/css/fav.png">' else "<div class='placeholder'></div>" $item = $("<li data-source='#{node.source}'><div class=color-mapping style='background:#{bg}'></div>#{isFav}<span>#{node.source}</span></li>") $item.appendTo $list $item.hover setCurrentSelection, removeCurrentSelection # view for small devices $list = $skills.find(".type.#{node.type} select") if $list.find("option[data-source=\"#{node.source}\"]").length is 0 $item = $("<option data-source='#{node.source}'>#{node.source}</option>") $item.appendTo $list add node for node in sortedNodes when node.type in types $lists = $skills.find('.type select') $lists.change ()-> window.currentSelection = '' $lists.each ()-> window.currentSelection += if window.currentSelection is '' then '' else ';' window.currentSelection += $(this).val() force.start() lab.ui.graph.skills.list = new SkillsList lab.ui.graph.skills.list.init() lab.ui.tooltip.init '[data-tooltip]', ($object)-> rect = object = $object[0].getBoundingClientRect() result = width: rect.width height: rect.height # Common $lists = $skills.find '.lists' updateTab = ()-> $activeTab = $lists.find 'li.active' for type in ['language', 'technology', 'tool'] $list = $lists.find ".type.#{type}" if $activeTab.hasClass type $list.show() else $list.hide() updateTab() $tabs = $lists.find '.nav li' $tabs.click ()-> $otherTabs = $lists.find('li').not this $otherTabs.removeClass 'active' $activeTab = $ this $activeTab.addClass 'active' updateTab() # Help $helpButton = $skills.find '.help.icon' # Animation for help button helpButtonAnimation = ()-> animation = 'animated wobble' $helpButton.addClass animation window.setTimeout (()-> $helpButton.removeClass animation), 2000 interval = window.setInterval helpButtonAnimation, 5000 $helpButton.hover ()-> window.clearInterval interval, ()-> $helpButton.click ()-> if lab.ui.sidebar.isVisible 'skills-explanation' lab.ui.sidebar.hide() else lab.ui.sidebar.show 'skills-explanation'
true
$ ()-> $skills = $ '.skills' window.lab = window.lab or {} window.lab.ui = window.lab.ui or {} window.lab.ui.graph = window.lab.ui.graph or {} # Define helper functions if typeof String.prototype.endsWith isnt 'function' String.prototype.endsWith = (suffix)-> this.indexOf(suffix, this.length - suffix.length) isnt -1 class SkillsGraph init: ()-> width = 400 height = 400 me = 'PI:NAME:<NAME>END_PI' window.color = d3.scale.category20() window.force = d3.layout.force() .charge(-150) .linkDistance(25) .size [width, height] svg = d3 .select(".skills .graph") .append("svg") .attr("width", '100%') .attr("height", '100%') .attr('viewBox',"0 0 #{Math.min width, height} #{Math.min width, height}") .attr('preserveAspectRatio','xMinYMin') skills = window.data.skillsData force .nodes(skills.nodes) .links(skills.links) .start() link = svg.selectAll '.link' .data skills.links .enter() .append 'line' .attr 'class', 'link' .style 'stroke-width', (d)-> return Math.sqrt d.value node = svg.selectAll('.node') .data(skills.nodes) .enter() .append 'g' .attr 'data-tooltip', '' .attr 'data-width', (d)-> duration = d.duration || 1 10 + duration * 2 .attr 'class', 'node' .call force.drag node.append 'circle' .attr 'class', 'ic' .attr 'r', (d)-> duration = d.duration || 1 10 + duration * 2 .attr "data-foo", (d)-> d.name .style 'fill', (d)-> if d.name is me return 'transparent' else return color d.group imageWidth = 20 imageHeight = 20 node.append 'image' .attr 'xlink:href', (d)-> if d.name is me return 'style/assets/css/me.png' else if d.duration return 'style/assets/css/p4.png' else switch d.type when 'language' then return 'style/assets/css/language.png' when 'technology' then return 'style/assets/css/technology.png' when 'tool' then return 'style/assets/css/tool.png' .attr 'x', -imageWidth / 2 .attr 'y', -imageHeight / 2 .attr 'width', imageWidth .attr 'height', imageHeight node.append 'div' .attr 'class', 'tooltip-content' .text (d)-> return d.source or d.name force.on 'tick', ()-> link .attr 'x1', (d)-> return d.source.x .attr 'y1', (d)-> return d.source.y .attr 'x2', (d)-> return d.target.x .attr 'y2', (d)-> return d.target.y .style 'stroke-width', (d)-> return Math.sqrt d.value node.attr 'transform', (d)-> return "translate(#{d.x},#{d.y})" node.select '.ic' .attr 'data-selected', (d)-> return window.currentSelection and d.source in window.currentSelection.split(';') .attr 'r', (d)-> duration = d.duration || 1 if window.currentSelection && d.source in window.currentSelection.split(';') return 20 else return 6 + duration node.select 'image' .attr 'x', (d)-> if window.currentSelection && d.source in window.currentSelection.split(';') return -imageWidth else return -imageWidth / 2 .attr 'y', (d)-> if window.currentSelection && d.source in window.currentSelection.split(';') return -imageHeight else return -imageHeight / 2 .attr 'width', (d)-> if window.currentSelection && d.source in window.currentSelection.split(';') return imageWidth * 2 else return imageWidth .attr 'height', (d)-> if window.currentSelection && d.source in window.currentSelection.split(';') return imageHeight * 2 else return imageHeight window.lab.ui.graph.skills = new SkillsGraph lab.ui.graph.skills.init() class SkillsList init: ()-> data = window.data.skillsData sortedNodes = data.nodes.sort (sourceA, sourceB)-> a = $.extend true, {}, sourceA b = $.extend true, {}, sourceB prop = 'source' result = 0 for object in [a, b] object[prop] = if object[prop] then object[prop] else '1' if a[prop].toUpperCase() > b[prop].toUpperCase() result = 1 else if a[prop].toUpperCase() < b[prop].toUpperCase() result = -1 return result types = ['language', 'technology', 'tool'] $skills.find('.type > ul').children().remove() add = (node)-> setCurrentSelection = ()-> window.currentSelection = $(this).attr('data-source') force.start() removeCurrentSelection = ()-> window.currentSelection = undefined # default view $list = $skills.find(".type.#{node.type} > ul") if $list.find("li[data-source=\"#{node.source}\"]").length is 0 bg = color node.group isFav = if node.isFavorite then '<img src="style/assets/css/fav.png">' else "<div class='placeholder'></div>" $item = $("<li data-source='#{node.source}'><div class=color-mapping style='background:#{bg}'></div>#{isFav}<span>#{node.source}</span></li>") $item.appendTo $list $item.hover setCurrentSelection, removeCurrentSelection # view for small devices $list = $skills.find(".type.#{node.type} select") if $list.find("option[data-source=\"#{node.source}\"]").length is 0 $item = $("<option data-source='#{node.source}'>#{node.source}</option>") $item.appendTo $list add node for node in sortedNodes when node.type in types $lists = $skills.find('.type select') $lists.change ()-> window.currentSelection = '' $lists.each ()-> window.currentSelection += if window.currentSelection is '' then '' else ';' window.currentSelection += $(this).val() force.start() lab.ui.graph.skills.list = new SkillsList lab.ui.graph.skills.list.init() lab.ui.tooltip.init '[data-tooltip]', ($object)-> rect = object = $object[0].getBoundingClientRect() result = width: rect.width height: rect.height # Common $lists = $skills.find '.lists' updateTab = ()-> $activeTab = $lists.find 'li.active' for type in ['language', 'technology', 'tool'] $list = $lists.find ".type.#{type}" if $activeTab.hasClass type $list.show() else $list.hide() updateTab() $tabs = $lists.find '.nav li' $tabs.click ()-> $otherTabs = $lists.find('li').not this $otherTabs.removeClass 'active' $activeTab = $ this $activeTab.addClass 'active' updateTab() # Help $helpButton = $skills.find '.help.icon' # Animation for help button helpButtonAnimation = ()-> animation = 'animated wobble' $helpButton.addClass animation window.setTimeout (()-> $helpButton.removeClass animation), 2000 interval = window.setInterval helpButtonAnimation, 5000 $helpButton.hover ()-> window.clearInterval interval, ()-> $helpButton.click ()-> if lab.ui.sidebar.isVisible 'skills-explanation' lab.ui.sidebar.hide() else lab.ui.sidebar.show 'skills-explanation'
[ { "context": "# Copyright (c) Konode. All rights reserved.\n# This source code is subje", "end": 22, "score": 0.992316484451294, "start": 16, "tag": "NAME", "value": "Konode" }, { "context": "s 'colorKeyHex'\n\t\t\t\t\tColorKeyBubble {\n\t\t\t\t\t\tkey: 'bubble'\n\t\t\t\t\t\tcolorKey...
src/clientFilePage/filterBar.coffee
LogicalOutcomes/KoNote
1
# Copyright (c) Konode. All rights reserved. # This source code is subject to the terms of the Mozilla Public License, v. 2.0 # that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0 # Toolbar for handling search query (via props and internal copy), # and a dropdown menu handling selection for options within each filter type _ = require 'underscore' Imm = require 'immutable' Term = require '../term' load = (win) -> React = win.React {PropTypes} = React {findDOMNode} = win.ReactDOM R = React.DOM ColorKeyBubble = require('../colorKeyBubble').load(win) {FaIcon, showWhen} = require('../utils').load(win) FilterBar = React.createFactory React.createClass displayName: 'FilterBar' mixins: [React.addons.PureRenderMixin] propTypes: { # TODO: isRequired? programIdFilter: PropTypes.string dataTypeFilter: PropTypes.oneOf ['progNotes', 'targets', 'events'] programsById: PropTypes.instanceOf Imm.List() dataTypeOptions: PropTypes.instanceOf Imm.List() onClose: PropTypes.func onUpdateSearchQuery: PropTypes.func onSelectProgramId: PropTypes.func onSelectDataType: PropTypes.func } getInitialState: -> { searchText: '' # Stays internal for perf reasons } componentWillMount: -> # Sparingly update the parent progNotesTab UI @_updateSearchQuery = _.debounce(@props.onUpdateSearchQuery, 350) componentDidMount: -> @_focusInput() clear: -> @_updateSearchText {target: {value: ''}} @props.onSelectProgramId null @props.onSelectDataType null @_focusInput() _focusInput: -> @refs.searchText.focus() if @refs.searchText? _updateSearchText: (event) -> searchText = event.target.value @setState {searchText} @_updateSearchQuery(searchText) render: -> R.div({ className: 'filterBar' onClick: @_focusInput }, R.section({}, R.input({ ref: 'searchText' className: 'form-control' value: @state.searchText onChange: @_updateSearchText placeholder: "Search by keywords . . ." }) ) R.section({className: 'filters'}, FilterDropdownMenu({ title: 'Data' selectedValue: @props.dataTypeFilter dataOptions: @props.dataTypeOptions onSelect: @props.onSelectDataType }) (unless @props.programsById.isEmpty() FilterDropdownMenu({ title: Term 'Programs' selectedValue: @props.programIdFilter dataOptions: @props.programsById onSelect: @props.onSelectProgramId }) ) ) R.section({ className: 'closeButton' onClick: @props.onClose }, FaIcon('times-circle') ) ) FilterDropdownMenu = React.createFactory React.createClass displayName: 'FilterDropdownMenu' mixins: [React.addons.PureRenderMixin] getInitialState: -> {isOpen: false} componentDidMount: -> win.document.addEventListener 'click', @_onDocumentClick componentWillUnmount: -> win.document.removeEventListener 'click', @_onDocumentClick _onDocumentClick: (event) -> button = findDOMNode @refs.menuButton optionsList = findDOMNode @refs.optionsList # Check for inside/outside click if button.contains event.target @_toggleIsOpen() else if not optionsList.contains event.target @setState {isOpen: false} _toggleIsOpen: -> @setState {isOpen: not @state.isOpen} _onSelect: (value) -> @props.onSelect(value) _renderOption: (option) -> selectedOption = option or @props.dataOptions.find (o) => o.get('id') is @props.selectedValue name = selectedOption.get('name') # Specific logic for userProgram icon to appear isUserProgram = selectedOption.get('id') is global.ActiveSession.programId [ (if selectedOption.has 'colorKeyHex' ColorKeyBubble { key: 'bubble' colorKeyHex: selectedOption.get('colorKeyHex') icon: 'check' if isUserProgram } ) R.span({ key: 'value' className: 'value' }, name ) ] render: -> {title, dataOptions, selectedValue} = @props hasSelection = !!selectedValue if hasSelection # Filter out selected type dataOptions = dataOptions.filterNot (o) -> o.get('id') is selectedValue R.div({ className: [ 'filterDropdownMenu' 'isOpen' if @state.isOpen ].join ' ' }, R.ul({ ref: 'optionsList' className: 'filterOptions' }, (if hasSelection R.li({ className: 'selectAllOption' onClick: @_onSelect.bind null, null }, R.span({className: 'value'}, "All #{title}" ) ) ) (dataOptions.toSeq().map (option) => R.li({ key: option.get('id') className: 'option' onClick: @_onSelect.bind null, option.get('id') }, @_renderOption(option) ) ) ) R.div({ ref: 'menuButton' className: 'option selectedValue' }, (if hasSelection @_renderOption() else R.span({className: 'value'}, "All #{title}" ) ) ' ' FaIcon('caret-down') ) ) return FilterBar module.exports = {load}
26219
# Copyright (c) <NAME>. All rights reserved. # This source code is subject to the terms of the Mozilla Public License, v. 2.0 # that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0 # Toolbar for handling search query (via props and internal copy), # and a dropdown menu handling selection for options within each filter type _ = require 'underscore' Imm = require 'immutable' Term = require '../term' load = (win) -> React = win.React {PropTypes} = React {findDOMNode} = win.ReactDOM R = React.DOM ColorKeyBubble = require('../colorKeyBubble').load(win) {FaIcon, showWhen} = require('../utils').load(win) FilterBar = React.createFactory React.createClass displayName: 'FilterBar' mixins: [React.addons.PureRenderMixin] propTypes: { # TODO: isRequired? programIdFilter: PropTypes.string dataTypeFilter: PropTypes.oneOf ['progNotes', 'targets', 'events'] programsById: PropTypes.instanceOf Imm.List() dataTypeOptions: PropTypes.instanceOf Imm.List() onClose: PropTypes.func onUpdateSearchQuery: PropTypes.func onSelectProgramId: PropTypes.func onSelectDataType: PropTypes.func } getInitialState: -> { searchText: '' # Stays internal for perf reasons } componentWillMount: -> # Sparingly update the parent progNotesTab UI @_updateSearchQuery = _.debounce(@props.onUpdateSearchQuery, 350) componentDidMount: -> @_focusInput() clear: -> @_updateSearchText {target: {value: ''}} @props.onSelectProgramId null @props.onSelectDataType null @_focusInput() _focusInput: -> @refs.searchText.focus() if @refs.searchText? _updateSearchText: (event) -> searchText = event.target.value @setState {searchText} @_updateSearchQuery(searchText) render: -> R.div({ className: 'filterBar' onClick: @_focusInput }, R.section({}, R.input({ ref: 'searchText' className: 'form-control' value: @state.searchText onChange: @_updateSearchText placeholder: "Search by keywords . . ." }) ) R.section({className: 'filters'}, FilterDropdownMenu({ title: 'Data' selectedValue: @props.dataTypeFilter dataOptions: @props.dataTypeOptions onSelect: @props.onSelectDataType }) (unless @props.programsById.isEmpty() FilterDropdownMenu({ title: Term 'Programs' selectedValue: @props.programIdFilter dataOptions: @props.programsById onSelect: @props.onSelectProgramId }) ) ) R.section({ className: 'closeButton' onClick: @props.onClose }, FaIcon('times-circle') ) ) FilterDropdownMenu = React.createFactory React.createClass displayName: 'FilterDropdownMenu' mixins: [React.addons.PureRenderMixin] getInitialState: -> {isOpen: false} componentDidMount: -> win.document.addEventListener 'click', @_onDocumentClick componentWillUnmount: -> win.document.removeEventListener 'click', @_onDocumentClick _onDocumentClick: (event) -> button = findDOMNode @refs.menuButton optionsList = findDOMNode @refs.optionsList # Check for inside/outside click if button.contains event.target @_toggleIsOpen() else if not optionsList.contains event.target @setState {isOpen: false} _toggleIsOpen: -> @setState {isOpen: not @state.isOpen} _onSelect: (value) -> @props.onSelect(value) _renderOption: (option) -> selectedOption = option or @props.dataOptions.find (o) => o.get('id') is @props.selectedValue name = selectedOption.get('name') # Specific logic for userProgram icon to appear isUserProgram = selectedOption.get('id') is global.ActiveSession.programId [ (if selectedOption.has 'colorKeyHex' ColorKeyBubble { key: '<KEY>' colorKeyHex: selectedOption.get('colorKeyHex') icon: 'check' if isUserProgram } ) R.span({ key: 'value' className: 'value' }, name ) ] render: -> {title, dataOptions, selectedValue} = @props hasSelection = !!selectedValue if hasSelection # Filter out selected type dataOptions = dataOptions.filterNot (o) -> o.get('id') is selectedValue R.div({ className: [ 'filterDropdownMenu' 'isOpen' if @state.isOpen ].join ' ' }, R.ul({ ref: 'optionsList' className: 'filterOptions' }, (if hasSelection R.li({ className: 'selectAllOption' onClick: @_onSelect.bind null, null }, R.span({className: 'value'}, "All #{title}" ) ) ) (dataOptions.toSeq().map (option) => R.li({ key: option.get('id') className: 'option' onClick: @_onSelect.bind null, option.get('id') }, @_renderOption(option) ) ) ) R.div({ ref: 'menuButton' className: 'option selectedValue' }, (if hasSelection @_renderOption() else R.span({className: 'value'}, "All #{title}" ) ) ' ' FaIcon('caret-down') ) ) return FilterBar module.exports = {load}
true
# Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved. # This source code is subject to the terms of the Mozilla Public License, v. 2.0 # that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0 # Toolbar for handling search query (via props and internal copy), # and a dropdown menu handling selection for options within each filter type _ = require 'underscore' Imm = require 'immutable' Term = require '../term' load = (win) -> React = win.React {PropTypes} = React {findDOMNode} = win.ReactDOM R = React.DOM ColorKeyBubble = require('../colorKeyBubble').load(win) {FaIcon, showWhen} = require('../utils').load(win) FilterBar = React.createFactory React.createClass displayName: 'FilterBar' mixins: [React.addons.PureRenderMixin] propTypes: { # TODO: isRequired? programIdFilter: PropTypes.string dataTypeFilter: PropTypes.oneOf ['progNotes', 'targets', 'events'] programsById: PropTypes.instanceOf Imm.List() dataTypeOptions: PropTypes.instanceOf Imm.List() onClose: PropTypes.func onUpdateSearchQuery: PropTypes.func onSelectProgramId: PropTypes.func onSelectDataType: PropTypes.func } getInitialState: -> { searchText: '' # Stays internal for perf reasons } componentWillMount: -> # Sparingly update the parent progNotesTab UI @_updateSearchQuery = _.debounce(@props.onUpdateSearchQuery, 350) componentDidMount: -> @_focusInput() clear: -> @_updateSearchText {target: {value: ''}} @props.onSelectProgramId null @props.onSelectDataType null @_focusInput() _focusInput: -> @refs.searchText.focus() if @refs.searchText? _updateSearchText: (event) -> searchText = event.target.value @setState {searchText} @_updateSearchQuery(searchText) render: -> R.div({ className: 'filterBar' onClick: @_focusInput }, R.section({}, R.input({ ref: 'searchText' className: 'form-control' value: @state.searchText onChange: @_updateSearchText placeholder: "Search by keywords . . ." }) ) R.section({className: 'filters'}, FilterDropdownMenu({ title: 'Data' selectedValue: @props.dataTypeFilter dataOptions: @props.dataTypeOptions onSelect: @props.onSelectDataType }) (unless @props.programsById.isEmpty() FilterDropdownMenu({ title: Term 'Programs' selectedValue: @props.programIdFilter dataOptions: @props.programsById onSelect: @props.onSelectProgramId }) ) ) R.section({ className: 'closeButton' onClick: @props.onClose }, FaIcon('times-circle') ) ) FilterDropdownMenu = React.createFactory React.createClass displayName: 'FilterDropdownMenu' mixins: [React.addons.PureRenderMixin] getInitialState: -> {isOpen: false} componentDidMount: -> win.document.addEventListener 'click', @_onDocumentClick componentWillUnmount: -> win.document.removeEventListener 'click', @_onDocumentClick _onDocumentClick: (event) -> button = findDOMNode @refs.menuButton optionsList = findDOMNode @refs.optionsList # Check for inside/outside click if button.contains event.target @_toggleIsOpen() else if not optionsList.contains event.target @setState {isOpen: false} _toggleIsOpen: -> @setState {isOpen: not @state.isOpen} _onSelect: (value) -> @props.onSelect(value) _renderOption: (option) -> selectedOption = option or @props.dataOptions.find (o) => o.get('id') is @props.selectedValue name = selectedOption.get('name') # Specific logic for userProgram icon to appear isUserProgram = selectedOption.get('id') is global.ActiveSession.programId [ (if selectedOption.has 'colorKeyHex' ColorKeyBubble { key: 'PI:KEY:<KEY>END_PI' colorKeyHex: selectedOption.get('colorKeyHex') icon: 'check' if isUserProgram } ) R.span({ key: 'value' className: 'value' }, name ) ] render: -> {title, dataOptions, selectedValue} = @props hasSelection = !!selectedValue if hasSelection # Filter out selected type dataOptions = dataOptions.filterNot (o) -> o.get('id') is selectedValue R.div({ className: [ 'filterDropdownMenu' 'isOpen' if @state.isOpen ].join ' ' }, R.ul({ ref: 'optionsList' className: 'filterOptions' }, (if hasSelection R.li({ className: 'selectAllOption' onClick: @_onSelect.bind null, null }, R.span({className: 'value'}, "All #{title}" ) ) ) (dataOptions.toSeq().map (option) => R.li({ key: option.get('id') className: 'option' onClick: @_onSelect.bind null, option.get('id') }, @_renderOption(option) ) ) ) R.div({ ref: 'menuButton' className: 'option selectedValue' }, (if hasSelection @_renderOption() else R.span({className: 'value'}, "All #{title}" ) ) ' ' FaIcon('caret-down') ) ) return FilterBar module.exports = {load}
[ { "context": "li className=\"user\"\n key={\"username-#{i}\"}\n onClick={@choose.bind @, \"@", "end": 5167, "score": 0.6899269819259644, "start": 5167, "tag": "KEY", "value": "" } ]
app/talk/suggester.cjsx
tlalka/Panoptes-Front-End
72
React = require 'react' PropTypes = require 'prop-types' createReactClass = require 'create-react-class' ReactDOM = require 'react-dom' talkClient = require 'panoptes-client/lib/talk-client' Loading = require('../components/loading-indicator').default getCaretPosition = require './lib/get-caret-position' module.exports = createReactClass displayName: 'Suggester' propTypes: input: PropTypes.string.isRequired onSelect: PropTypes.func getDefaultProps: -> onSelect: -> getInitialState: -> data: [] loading: false open: false kind: null pendingSearch: null lastSearch: null id: null componentDidMount: -> textArea = ReactDOM.findDOMNode(@).querySelector 'textarea' @setState textArea: textArea, id: Date.now().toString(16) textArea.addEventListener 'click', @handleInput componentWillUnmount: -> @state.textArea.removeEventListener 'click', @handleInput mimic.remove() for mimic in document.querySelectorAll('[id^="mimic-textarea-"]') componentWillReceiveProps: (nextProps) -> @handleInput() if @state.textArea show: (kind) -> return if @state.open @reposition() @refs.suggestions.style.display = 'block' @setState open: true, kind: kind, data: [] reposition: -> position = getCaretPosition @state.id, @state.textArea, @refs.suggestions, @state.textArea.selectionEnd @refs.suggestions.style.top = "#{position.top}px" @refs.suggestions.style.left = "#{position.left}px" hide: -> return unless @state.open @refs.suggestions.style.display = 'none' @setState @getInitialState() defer: (search) -> if @state.loading or @debounce() @setState pendingSearch: search true debounce: -> timeSince = Date.now() - @state.lastSearch tooSoon = timeSince < 300 if tooSoon setTimeout => if pendingSearch = @state.pendingSearch @setState pendingSearch: null @searchFor pendingSearch , 300 - timeSince tooSoon getTags: (search) -> section = if @props.project then "project-#{@props.project.id}" else 'zooniverse' @get 'tags/autocomplete', {search, section} getUsers: (search) -> @get 'users/autocomplete', {search} get: (resource, params) -> return if @defer params.search @setState loading: true, lastSearch: new Date() talkClient.type(resource).get(params).then @handleResults handleResults: (results) -> if pendingSearch = @state.pendingSearch @setState data: results, loading: false, pendingSearch: null @searchFor pendingSearch else @setState data: results, loading: false searchFor: (search = '', kind) -> search = search.toLowerCase().replace /[@#]+/g, '' kind or= @state.kind @show kind if kind is 'usernames' @getUsers search else if kind is 'tags' @getTags search lastWord: -> words = @state.textArea.value.substr(0, @state.textArea.selectionEnd).split /\s/m words[words.length - 1] currentTrigger: -> if @state.kind is 'usernames' '@' else if @state.kind is 'tags' '#' title: -> if @state.kind is 'usernames' 'Mention a user' else if @state.kind is 'tags' 'Use a tag' handleInput: -> lastWord = @lastWord() @reposition() if @state.open @hide() if lastWord.match(/^(\@|\#)/)?[1] isnt @currentTrigger() if lastWord.match(/^\@/) @searchFor lastWord, 'usernames' else if lastWord.match(/^\#/) @searchFor lastWord, 'tags' moveCaretTo: (position) -> @state.textArea.focus() if @state.textArea.setSelectionRange @state.textArea.setSelectionRange position, position else if @state.textArea.createTextRange range = @state.textArea.createTextRange() range.collapse true range.moveEnd 'character', position range.moveStart 'character', position range.select() choose: (value) -> lastWord = @lastWord() endingPosition = @state.textArea.selectionEnd startingPosition = endingPosition - lastWord.length beginning = @state.textArea.value.substr 0, startingPosition ending = @state.textArea.value.substr endingPosition, @state.textArea.value.length @state.textArea.value = "#{beginning}#{value} #{ending.replace(/^ /, '')}" @moveCaretTo startingPosition + value.length + 1 @hide() # Pass a fake input change event @props.onSelect target: @state.textArea render: -> <div className="suggester"> {@props.children} <div ref="suggestions" className={"suggestions suggest-#{@state.kind}"}> <p className="title"> {@title()} <span className={"loading #{if @state.loading or @state.pendingSearch then 'shown' else ''}"}> <Loading /> </span> </p> <ul> {for datum, i in @state.data if @state.kind is 'tags' <li className="tag" key={"tag-#{i}"} onClick={@choose.bind @, "##{datum.name}"}> {datum.name} </li> else if @state.kind is 'usernames' <li className="user" key={"username-#{i}"} onClick={@choose.bind @, "@#{datum.login}"}> @{datum.login} <small>{datum.display_name}</small> </li>} </ul> </div> </div>
48272
React = require 'react' PropTypes = require 'prop-types' createReactClass = require 'create-react-class' ReactDOM = require 'react-dom' talkClient = require 'panoptes-client/lib/talk-client' Loading = require('../components/loading-indicator').default getCaretPosition = require './lib/get-caret-position' module.exports = createReactClass displayName: 'Suggester' propTypes: input: PropTypes.string.isRequired onSelect: PropTypes.func getDefaultProps: -> onSelect: -> getInitialState: -> data: [] loading: false open: false kind: null pendingSearch: null lastSearch: null id: null componentDidMount: -> textArea = ReactDOM.findDOMNode(@).querySelector 'textarea' @setState textArea: textArea, id: Date.now().toString(16) textArea.addEventListener 'click', @handleInput componentWillUnmount: -> @state.textArea.removeEventListener 'click', @handleInput mimic.remove() for mimic in document.querySelectorAll('[id^="mimic-textarea-"]') componentWillReceiveProps: (nextProps) -> @handleInput() if @state.textArea show: (kind) -> return if @state.open @reposition() @refs.suggestions.style.display = 'block' @setState open: true, kind: kind, data: [] reposition: -> position = getCaretPosition @state.id, @state.textArea, @refs.suggestions, @state.textArea.selectionEnd @refs.suggestions.style.top = "#{position.top}px" @refs.suggestions.style.left = "#{position.left}px" hide: -> return unless @state.open @refs.suggestions.style.display = 'none' @setState @getInitialState() defer: (search) -> if @state.loading or @debounce() @setState pendingSearch: search true debounce: -> timeSince = Date.now() - @state.lastSearch tooSoon = timeSince < 300 if tooSoon setTimeout => if pendingSearch = @state.pendingSearch @setState pendingSearch: null @searchFor pendingSearch , 300 - timeSince tooSoon getTags: (search) -> section = if @props.project then "project-#{@props.project.id}" else 'zooniverse' @get 'tags/autocomplete', {search, section} getUsers: (search) -> @get 'users/autocomplete', {search} get: (resource, params) -> return if @defer params.search @setState loading: true, lastSearch: new Date() talkClient.type(resource).get(params).then @handleResults handleResults: (results) -> if pendingSearch = @state.pendingSearch @setState data: results, loading: false, pendingSearch: null @searchFor pendingSearch else @setState data: results, loading: false searchFor: (search = '', kind) -> search = search.toLowerCase().replace /[@#]+/g, '' kind or= @state.kind @show kind if kind is 'usernames' @getUsers search else if kind is 'tags' @getTags search lastWord: -> words = @state.textArea.value.substr(0, @state.textArea.selectionEnd).split /\s/m words[words.length - 1] currentTrigger: -> if @state.kind is 'usernames' '@' else if @state.kind is 'tags' '#' title: -> if @state.kind is 'usernames' 'Mention a user' else if @state.kind is 'tags' 'Use a tag' handleInput: -> lastWord = @lastWord() @reposition() if @state.open @hide() if lastWord.match(/^(\@|\#)/)?[1] isnt @currentTrigger() if lastWord.match(/^\@/) @searchFor lastWord, 'usernames' else if lastWord.match(/^\#/) @searchFor lastWord, 'tags' moveCaretTo: (position) -> @state.textArea.focus() if @state.textArea.setSelectionRange @state.textArea.setSelectionRange position, position else if @state.textArea.createTextRange range = @state.textArea.createTextRange() range.collapse true range.moveEnd 'character', position range.moveStart 'character', position range.select() choose: (value) -> lastWord = @lastWord() endingPosition = @state.textArea.selectionEnd startingPosition = endingPosition - lastWord.length beginning = @state.textArea.value.substr 0, startingPosition ending = @state.textArea.value.substr endingPosition, @state.textArea.value.length @state.textArea.value = "#{beginning}#{value} #{ending.replace(/^ /, '')}" @moveCaretTo startingPosition + value.length + 1 @hide() # Pass a fake input change event @props.onSelect target: @state.textArea render: -> <div className="suggester"> {@props.children} <div ref="suggestions" className={"suggestions suggest-#{@state.kind}"}> <p className="title"> {@title()} <span className={"loading #{if @state.loading or @state.pendingSearch then 'shown' else ''}"}> <Loading /> </span> </p> <ul> {for datum, i in @state.data if @state.kind is 'tags' <li className="tag" key={"tag-#{i}"} onClick={@choose.bind @, "##{datum.name}"}> {datum.name} </li> else if @state.kind is 'usernames' <li className="user" key={"username<KEY>-#{i}"} onClick={@choose.bind @, "@#{datum.login}"}> @{datum.login} <small>{datum.display_name}</small> </li>} </ul> </div> </div>
true
React = require 'react' PropTypes = require 'prop-types' createReactClass = require 'create-react-class' ReactDOM = require 'react-dom' talkClient = require 'panoptes-client/lib/talk-client' Loading = require('../components/loading-indicator').default getCaretPosition = require './lib/get-caret-position' module.exports = createReactClass displayName: 'Suggester' propTypes: input: PropTypes.string.isRequired onSelect: PropTypes.func getDefaultProps: -> onSelect: -> getInitialState: -> data: [] loading: false open: false kind: null pendingSearch: null lastSearch: null id: null componentDidMount: -> textArea = ReactDOM.findDOMNode(@).querySelector 'textarea' @setState textArea: textArea, id: Date.now().toString(16) textArea.addEventListener 'click', @handleInput componentWillUnmount: -> @state.textArea.removeEventListener 'click', @handleInput mimic.remove() for mimic in document.querySelectorAll('[id^="mimic-textarea-"]') componentWillReceiveProps: (nextProps) -> @handleInput() if @state.textArea show: (kind) -> return if @state.open @reposition() @refs.suggestions.style.display = 'block' @setState open: true, kind: kind, data: [] reposition: -> position = getCaretPosition @state.id, @state.textArea, @refs.suggestions, @state.textArea.selectionEnd @refs.suggestions.style.top = "#{position.top}px" @refs.suggestions.style.left = "#{position.left}px" hide: -> return unless @state.open @refs.suggestions.style.display = 'none' @setState @getInitialState() defer: (search) -> if @state.loading or @debounce() @setState pendingSearch: search true debounce: -> timeSince = Date.now() - @state.lastSearch tooSoon = timeSince < 300 if tooSoon setTimeout => if pendingSearch = @state.pendingSearch @setState pendingSearch: null @searchFor pendingSearch , 300 - timeSince tooSoon getTags: (search) -> section = if @props.project then "project-#{@props.project.id}" else 'zooniverse' @get 'tags/autocomplete', {search, section} getUsers: (search) -> @get 'users/autocomplete', {search} get: (resource, params) -> return if @defer params.search @setState loading: true, lastSearch: new Date() talkClient.type(resource).get(params).then @handleResults handleResults: (results) -> if pendingSearch = @state.pendingSearch @setState data: results, loading: false, pendingSearch: null @searchFor pendingSearch else @setState data: results, loading: false searchFor: (search = '', kind) -> search = search.toLowerCase().replace /[@#]+/g, '' kind or= @state.kind @show kind if kind is 'usernames' @getUsers search else if kind is 'tags' @getTags search lastWord: -> words = @state.textArea.value.substr(0, @state.textArea.selectionEnd).split /\s/m words[words.length - 1] currentTrigger: -> if @state.kind is 'usernames' '@' else if @state.kind is 'tags' '#' title: -> if @state.kind is 'usernames' 'Mention a user' else if @state.kind is 'tags' 'Use a tag' handleInput: -> lastWord = @lastWord() @reposition() if @state.open @hide() if lastWord.match(/^(\@|\#)/)?[1] isnt @currentTrigger() if lastWord.match(/^\@/) @searchFor lastWord, 'usernames' else if lastWord.match(/^\#/) @searchFor lastWord, 'tags' moveCaretTo: (position) -> @state.textArea.focus() if @state.textArea.setSelectionRange @state.textArea.setSelectionRange position, position else if @state.textArea.createTextRange range = @state.textArea.createTextRange() range.collapse true range.moveEnd 'character', position range.moveStart 'character', position range.select() choose: (value) -> lastWord = @lastWord() endingPosition = @state.textArea.selectionEnd startingPosition = endingPosition - lastWord.length beginning = @state.textArea.value.substr 0, startingPosition ending = @state.textArea.value.substr endingPosition, @state.textArea.value.length @state.textArea.value = "#{beginning}#{value} #{ending.replace(/^ /, '')}" @moveCaretTo startingPosition + value.length + 1 @hide() # Pass a fake input change event @props.onSelect target: @state.textArea render: -> <div className="suggester"> {@props.children} <div ref="suggestions" className={"suggestions suggest-#{@state.kind}"}> <p className="title"> {@title()} <span className={"loading #{if @state.loading or @state.pendingSearch then 'shown' else ''}"}> <Loading /> </span> </p> <ul> {for datum, i in @state.data if @state.kind is 'tags' <li className="tag" key={"tag-#{i}"} onClick={@choose.bind @, "##{datum.name}"}> {datum.name} </li> else if @state.kind is 'usernames' <li className="user" key={"usernamePI:KEY:<KEY>END_PI-#{i}"} onClick={@choose.bind @, "@#{datum.login}"}> @{datum.login} <small>{datum.display_name}</small> </li>} </ul> </div> </div>
[ { "context": "t value', ->\n post = buildPost author_name: 'John Doe'\n expect(post.authorName()).to.equal 'John D", "end": 690, "score": 0.9996042847633362, "start": 682, "tag": "NAME", "value": "John Doe" }, { "context": "hn Doe'\n expect(post.authorName()).to.equal ...
spec/javascripts/models/post_spec.coffee
njade/boot2docker-docker-fig-rails
24
#= require spec_helper # describe "App.Models.Post", -> buildPost = (options) -> new App.Models.Post(options) describe '#title', -> it 'returns the correct value', -> post = buildPost title: 'Great title' expect(post.title()).to.equal 'Great title' describe '#body', -> it 'returns the correct value', -> post = buildPost body: 'Great body' expect(post.body()).to.equal 'Great body' describe '#domId', -> it 'returns the correct value', -> post = buildPost dom_id: 'post_1' expect(post.domId()).to.equal 'post_1' describe '#authorName', -> it 'returns the correct value', -> post = buildPost author_name: 'John Doe' expect(post.authorName()).to.equal 'John Doe'
187261
#= require spec_helper # describe "App.Models.Post", -> buildPost = (options) -> new App.Models.Post(options) describe '#title', -> it 'returns the correct value', -> post = buildPost title: 'Great title' expect(post.title()).to.equal 'Great title' describe '#body', -> it 'returns the correct value', -> post = buildPost body: 'Great body' expect(post.body()).to.equal 'Great body' describe '#domId', -> it 'returns the correct value', -> post = buildPost dom_id: 'post_1' expect(post.domId()).to.equal 'post_1' describe '#authorName', -> it 'returns the correct value', -> post = buildPost author_name: '<NAME>' expect(post.authorName()).to.equal '<NAME>'
true
#= require spec_helper # describe "App.Models.Post", -> buildPost = (options) -> new App.Models.Post(options) describe '#title', -> it 'returns the correct value', -> post = buildPost title: 'Great title' expect(post.title()).to.equal 'Great title' describe '#body', -> it 'returns the correct value', -> post = buildPost body: 'Great body' expect(post.body()).to.equal 'Great body' describe '#domId', -> it 'returns the correct value', -> post = buildPost dom_id: 'post_1' expect(post.domId()).to.equal 'post_1' describe '#authorName', -> it 'returns the correct value', -> post = buildPost author_name: 'PI:NAME:<NAME>END_PI' expect(post.authorName()).to.equal 'PI:NAME:<NAME>END_PI'
[ { "context": " ws.on 'close', callback\n ws.write\n key:\"userid:#{username}:#{id}\"\n value:\n username: us", "end": 914, "score": 0.8088796138763428, "start": 905, "tag": "KEY", "value": "userid:#{" }, { "context": "callback\n ws.write\n key:\"userid:#{...
src/usermetrics.coffee
MegPau/testnode
0
level = require 'level' levelws = require 'level-ws' metrics = require './metrics' user = require './user' db = levelws level "#{__dirname}/../db/usermetrics" module.exports = get: (username, id, callback) -> userid = [] if callback == undefined callback = id id = null if id == null then opts = gte: "userid:#{username}:0" lte: "userid:#{username}:9999" else opts = gte: "userid:#{username}:#{id}" lte: "userid:#{username}:#{id}" rs = db.createReadStream(opts) rs.on 'data', (data) -> value = JSON.parse data.value console.log value userid.push value rs.on 'error', callback rs.on 'close', -> console.log 'closing' callback null, userid save: (username, id, callback) -> ws = db.createWriteStream() ws.on 'error', callback ws.on 'close', callback ws.write key:"userid:#{username}:#{id}" value: username: username id: id valueEncoding: 'json' ws.end() remove: (username, id, callback) -> console.log "deleting usermetric #{username}:#{id}" db.del "userid:#{username}:#{id}", callback # We won't do update
11025
level = require 'level' levelws = require 'level-ws' metrics = require './metrics' user = require './user' db = levelws level "#{__dirname}/../db/usermetrics" module.exports = get: (username, id, callback) -> userid = [] if callback == undefined callback = id id = null if id == null then opts = gte: "userid:#{username}:0" lte: "userid:#{username}:9999" else opts = gte: "userid:#{username}:#{id}" lte: "userid:#{username}:#{id}" rs = db.createReadStream(opts) rs.on 'data', (data) -> value = JSON.parse data.value console.log value userid.push value rs.on 'error', callback rs.on 'close', -> console.log 'closing' callback null, userid save: (username, id, callback) -> ws = db.createWriteStream() ws.on 'error', callback ws.on 'close', callback ws.write key:"<KEY>username}:<KEY>}" value: username: username id: id valueEncoding: 'json' ws.end() remove: (username, id, callback) -> console.log "deleting usermetric #{username}:#{id}" db.del "userid:#{username}:#{id}", callback # We won't do update
true
level = require 'level' levelws = require 'level-ws' metrics = require './metrics' user = require './user' db = levelws level "#{__dirname}/../db/usermetrics" module.exports = get: (username, id, callback) -> userid = [] if callback == undefined callback = id id = null if id == null then opts = gte: "userid:#{username}:0" lte: "userid:#{username}:9999" else opts = gte: "userid:#{username}:#{id}" lte: "userid:#{username}:#{id}" rs = db.createReadStream(opts) rs.on 'data', (data) -> value = JSON.parse data.value console.log value userid.push value rs.on 'error', callback rs.on 'close', -> console.log 'closing' callback null, userid save: (username, id, callback) -> ws = db.createWriteStream() ws.on 'error', callback ws.on 'close', callback ws.write key:"PI:KEY:<KEY>END_PIusername}:PI:KEY:<KEY>END_PI}" value: username: username id: id valueEncoding: 'json' ws.end() remove: (username, id, callback) -> console.log "deleting usermetric #{username}:#{id}" db.del "userid:#{username}:#{id}", callback # We won't do update
[ { "context": " data:\n username: uname,\n password: pass\n ", "end": 877, "score": 0.997836709022522, "start": 872, "tag": "USERNAME", "value": "uname" }, { "context": " username: uname,\n password:...
zero_privacy_hacker_news/app/assets/javascripts/backbone/apps/header/show/show_view.js.coffee
davidrusu/zero_privacy_hacker_news
0
App.module "HeaderApp.Show", (Show, App, Backbone, Marionette, $, _) -> LOGIN_URL="/user" Show.Controller = showHeader: (failedAuth = false) -> headerView = @getHeaderView(failedAuth) App.headerRegion.show headerView getHeaderView: (failedAuth) -> model = new Backbone.Model failedAuth: failedAuth new Show.Header model: model logout: -> window.localStorage.removeItem('session') @showHeader() login: (uname, pass) -> # Attempt to login with the given username and password # If the attempt fails, we try to create a new account # with this password. # If that fails, it means that username is taken $.ajax url: LOGIN_URL, data: username: uname, password: pass method: 'GET' success: ((data) -> console.log data if data.session window.localStorage.setItem('session', data.session) console.log "testing" @showHeader() else $.ajax url: LOGIN_URL, data: username: uname, password: pass method: 'POST' success: ((data) -> console.log 'created user', data if data.session window.localStorage.setItem('session',data.session) @showHeader() else console.log 'failed to create user' @showHeader(true) ).bind @ ).bind @ class Show.Header extends Marionette.ItemView template: (data) -> console.log data session = window.localStorage.getItem('session') console.log session popup = $('<div id="login_popup">') logout = $('<button id="logout_btn">logout</button>') logout.click -> Show.Controller.logout() if not session logout.hide() username = $('<input id="uname_input" type="text" placeholder="username">') password = $('<input id="pass_input" type="password" placeholder="password">') button = $('<button>Login or Register</button>') button.click -> Show.Controller.login( $('#uname_input').val(), $('#pass_input').val() ) popup = popup .append($("<h3>You aren't logged in!</h3>")) .append($('<p>login or create an account.</p>')) .append(username) .append($('<br>')) .append(password) .append($('<br>')) .append($('<br>')) .append(button) if data.failedAuth username.addClass('failed_auth') password.addClass('failed_auth') popup.append($('<p id="bad_auth_msg">').text("User with that name already exists and that's the wrong password. Feel free to try again!")) else popup.hide() header = $('<span>') .append($('<div id="hn_logo">Y</div>')) .append($('<a id="hn_name" href="/">Hacker News</div>')) .append(logout) .append(popup) return header
13266
App.module "HeaderApp.Show", (Show, App, Backbone, Marionette, $, _) -> LOGIN_URL="/user" Show.Controller = showHeader: (failedAuth = false) -> headerView = @getHeaderView(failedAuth) App.headerRegion.show headerView getHeaderView: (failedAuth) -> model = new Backbone.Model failedAuth: failedAuth new Show.Header model: model logout: -> window.localStorage.removeItem('session') @showHeader() login: (uname, pass) -> # Attempt to login with the given username and password # If the attempt fails, we try to create a new account # with this password. # If that fails, it means that username is taken $.ajax url: LOGIN_URL, data: username: uname, password: <PASSWORD> method: 'GET' success: ((data) -> console.log data if data.session window.localStorage.setItem('session', data.session) console.log "testing" @showHeader() else $.ajax url: LOGIN_URL, data: username: uname, password: <PASSWORD> method: 'POST' success: ((data) -> console.log 'created user', data if data.session window.localStorage.setItem('session',data.session) @showHeader() else console.log 'failed to create user' @showHeader(true) ).bind @ ).bind @ class Show.Header extends Marionette.ItemView template: (data) -> console.log data session = window.localStorage.getItem('session') console.log session popup = $('<div id="login_popup">') logout = $('<button id="logout_btn">logout</button>') logout.click -> Show.Controller.logout() if not session logout.hide() username = $('<input id="uname_input" type="text" placeholder="username">') password = $('<input id="pass_input" type="password" placeholder="<PASSWORD>">') button = $('<button>Login or Register</button>') button.click -> Show.Controller.login( $('#uname_input').val(), $('#pass_input').val() ) popup = popup .append($("<h3>You aren't logged in!</h3>")) .append($('<p>login or create an account.</p>')) .append(username) .append($('<br>')) .append(password) .append($('<br>')) .append($('<br>')) .append(button) if data.failedAuth username.addClass('failed_auth') password.addClass('failed_auth') popup.append($('<p id="bad_auth_msg">').text("User with that name already exists and that's the wrong password. Feel free to try again!")) else popup.hide() header = $('<span>') .append($('<div id="hn_logo">Y</div>')) .append($('<a id="hn_name" href="/">Hacker News</div>')) .append(logout) .append(popup) return header
true
App.module "HeaderApp.Show", (Show, App, Backbone, Marionette, $, _) -> LOGIN_URL="/user" Show.Controller = showHeader: (failedAuth = false) -> headerView = @getHeaderView(failedAuth) App.headerRegion.show headerView getHeaderView: (failedAuth) -> model = new Backbone.Model failedAuth: failedAuth new Show.Header model: model logout: -> window.localStorage.removeItem('session') @showHeader() login: (uname, pass) -> # Attempt to login with the given username and password # If the attempt fails, we try to create a new account # with this password. # If that fails, it means that username is taken $.ajax url: LOGIN_URL, data: username: uname, password: PI:PASSWORD:<PASSWORD>END_PI method: 'GET' success: ((data) -> console.log data if data.session window.localStorage.setItem('session', data.session) console.log "testing" @showHeader() else $.ajax url: LOGIN_URL, data: username: uname, password: PI:PASSWORD:<PASSWORD>END_PI method: 'POST' success: ((data) -> console.log 'created user', data if data.session window.localStorage.setItem('session',data.session) @showHeader() else console.log 'failed to create user' @showHeader(true) ).bind @ ).bind @ class Show.Header extends Marionette.ItemView template: (data) -> console.log data session = window.localStorage.getItem('session') console.log session popup = $('<div id="login_popup">') logout = $('<button id="logout_btn">logout</button>') logout.click -> Show.Controller.logout() if not session logout.hide() username = $('<input id="uname_input" type="text" placeholder="username">') password = $('<input id="pass_input" type="password" placeholder="PI:PASSWORD:<PASSWORD>END_PI">') button = $('<button>Login or Register</button>') button.click -> Show.Controller.login( $('#uname_input').val(), $('#pass_input').val() ) popup = popup .append($("<h3>You aren't logged in!</h3>")) .append($('<p>login or create an account.</p>')) .append(username) .append($('<br>')) .append(password) .append($('<br>')) .append($('<br>')) .append(button) if data.failedAuth username.addClass('failed_auth') password.addClass('failed_auth') popup.append($('<p id="bad_auth_msg">').text("User with that name already exists and that's the wrong password. Feel free to try again!")) else popup.hide() header = $('<span>') .append($('<div id="hn_logo">Y</div>')) .append($('<a id="hn_name" href="/">Hacker News</div>')) .append(logout) .append(popup) return header
[ { "context": "Length: 4\n \"exception-reporting\":\n userId: \"ed76c550-bec0-47a7-9681-03451d887cf5\"\n fonts: {}\n l", "end": 535, "score": 0.5033734440803528, "start": 534, "tag": "PASSWORD", "value": "7" }, { "context": "\"exception-reporting\":\n userId: \"ed76c550-bec0-...
.atom/config.cson
fullpipe/dotfiles
0
"*": "activate-power-mode": plugins: playAudio: true screenShake: true "atom-ide-ui": use: "atom-ide-code-format": false "atom-ide-code-highlight": false "atom-ide-datatip": false "atom-ide-outline-view": false "atom-ide-signature-help": false core: disabledPackages: [ "cucumber" "atom-autocomplete-php" "linter" ] telemetryConsent: "no" editor: fontSize: 17 showInvisibles: true tabLength: 4 "exception-reporting": userId: "ed76c550-bec0-47a7-9681-03451d887cf5" fonts: {} linter: lintOnChange: false "linter-ui-default": showPanel: true minimap: plugins: bookmarks: true bookmarksDecorationsZIndex: 0 cursorline: true cursorlineDecorationsZIndex: 0 "highlight-selected": true "highlight-selectedDecorationsZIndex": 0 "php-cs-fixer": executablePath: "/usr/local/bin/php-cs-fixer" pathMode: "intersection" showInfoNotifications: true "php-debug": ServerPort: 9090 currentPanelMode: "bottom" "remote-sync": autoHideLogPanel: true foldLogPanel: true "tree-view": {} welcome: showOnStartup: false
74481
"*": "activate-power-mode": plugins: playAudio: true screenShake: true "atom-ide-ui": use: "atom-ide-code-format": false "atom-ide-code-highlight": false "atom-ide-datatip": false "atom-ide-outline-view": false "atom-ide-signature-help": false core: disabledPackages: [ "cucumber" "atom-autocomplete-php" "linter" ] telemetryConsent: "no" editor: fontSize: 17 showInvisibles: true tabLength: 4 "exception-reporting": userId: "ed<PASSWORD>6c550-bec0-<PASSWORD>7a7-9681-03451<PASSWORD>cf<PASSWORD>" fonts: {} linter: lintOnChange: false "linter-ui-default": showPanel: true minimap: plugins: bookmarks: true bookmarksDecorationsZIndex: 0 cursorline: true cursorlineDecorationsZIndex: 0 "highlight-selected": true "highlight-selectedDecorationsZIndex": 0 "php-cs-fixer": executablePath: "/usr/local/bin/php-cs-fixer" pathMode: "intersection" showInfoNotifications: true "php-debug": ServerPort: 9090 currentPanelMode: "bottom" "remote-sync": autoHideLogPanel: true foldLogPanel: true "tree-view": {} welcome: showOnStartup: false
true
"*": "activate-power-mode": plugins: playAudio: true screenShake: true "atom-ide-ui": use: "atom-ide-code-format": false "atom-ide-code-highlight": false "atom-ide-datatip": false "atom-ide-outline-view": false "atom-ide-signature-help": false core: disabledPackages: [ "cucumber" "atom-autocomplete-php" "linter" ] telemetryConsent: "no" editor: fontSize: 17 showInvisibles: true tabLength: 4 "exception-reporting": userId: "edPI:PASSWORD:<PASSWORD>END_PI6c550-bec0-PI:PASSWORD:<PASSWORD>END_PI7a7-9681-03451PI:PASSWORD:<PASSWORD>END_PIcfPI:PASSWORD:<PASSWORD>END_PI" fonts: {} linter: lintOnChange: false "linter-ui-default": showPanel: true minimap: plugins: bookmarks: true bookmarksDecorationsZIndex: 0 cursorline: true cursorlineDecorationsZIndex: 0 "highlight-selected": true "highlight-selectedDecorationsZIndex": 0 "php-cs-fixer": executablePath: "/usr/local/bin/php-cs-fixer" pathMode: "intersection" showInfoNotifications: true "php-debug": ServerPort: 9090 currentPanelMode: "bottom" "remote-sync": autoHideLogPanel: true foldLogPanel: true "tree-view": {} welcome: showOnStartup: false
[ { "context": "return\n\nItemManager::create = () ->\n this.items['dagon'] = new Item {\n name: 'dagon',\n clickNeeded", "end": 95, "score": 0.9387613534927368, "start": 90, "tag": "NAME", "value": "dagon" }, { "context": " ->\n this.items['dagon'] = new Item {\n name: 'dag...
assets/js/src/itemManager.coffee
juancjara/dota-game
0
ItemManager = () -> this.items = {} return ItemManager::create = () -> this.items['dagon'] = new Item { name: 'dagon', clickNeeded: true, secondsCd: 2, srcImg: 'dagon', endDurationDmg: 800 } this.items['ethereal'] = new Item { name: 'ethereal', clickNeeded: true, secondsCd: 2, srcImg: 'ethereal', endDurationDmg: 75 } this.items['eul'] = new Item { name: 'eul', clickNeeded: true, secondsCd: 2, srcImg: 'eul', duration: 2.5, endDurationDmg: 50, effect: 'invulnerable' } this.items['scythe'] = new Item { name: 'scythe', clickNeeded: true, secondsCd: 2, srcImg: 'scythe', duration: 3.5, effect: 'hex' } this.items['shiva'] = new Item { name: 'shiva', clickNeeded: false, secondsCd: 2, srcImg: 'shivas', endDurationDmg: 200, effect: 'slow' } this.items['no-item'] = new Item { name: '', clickNeeded: false, srcImg: 'no-item' } return this
146103
ItemManager = () -> this.items = {} return ItemManager::create = () -> this.items['<NAME>'] = new Item { name: '<NAME>', clickNeeded: true, secondsCd: 2, srcImg: 'dagon', endDurationDmg: 800 } this.items['ethereal'] = new Item { name: '<NAME>', clickNeeded: true, secondsCd: 2, srcImg: 'ethereal', endDurationDmg: 75 } this.items['eul'] = new Item { name: '<NAME>', clickNeeded: true, secondsCd: 2, srcImg: 'eul', duration: 2.5, endDurationDmg: 50, effect: 'invulnerable' } this.items['scythe'] = new Item { name: '<NAME>', clickNeeded: true, secondsCd: 2, srcImg: 'scythe', duration: 3.5, effect: 'hex' } this.items['shiva'] = new Item { name: '<NAME>', clickNeeded: false, secondsCd: 2, srcImg: 'shivas', endDurationDmg: 200, effect: 'slow' } this.items['no-item'] = new Item { name: '', clickNeeded: false, srcImg: 'no-item' } return this
true
ItemManager = () -> this.items = {} return ItemManager::create = () -> this.items['PI:NAME:<NAME>END_PI'] = new Item { name: 'PI:NAME:<NAME>END_PI', clickNeeded: true, secondsCd: 2, srcImg: 'dagon', endDurationDmg: 800 } this.items['ethereal'] = new Item { name: 'PI:NAME:<NAME>END_PI', clickNeeded: true, secondsCd: 2, srcImg: 'ethereal', endDurationDmg: 75 } this.items['eul'] = new Item { name: 'PI:NAME:<NAME>END_PI', clickNeeded: true, secondsCd: 2, srcImg: 'eul', duration: 2.5, endDurationDmg: 50, effect: 'invulnerable' } this.items['scythe'] = new Item { name: 'PI:NAME:<NAME>END_PI', clickNeeded: true, secondsCd: 2, srcImg: 'scythe', duration: 3.5, effect: 'hex' } this.items['shiva'] = new Item { name: 'PI:NAME:<NAME>END_PI', clickNeeded: false, secondsCd: 2, srcImg: 'shivas', endDurationDmg: 200, effect: 'slow' } this.items['no-item'] = new Item { name: '', clickNeeded: false, srcImg: 'no-item' } return this
[ { "context": "--------\n# A number of collection classes based on Rich Hickey's persistent\n# hash trie implementation from Cloj", "end": 124, "score": 0.9991720914840698, "start": 113, "tag": "NAME", "value": "Rich Hickey" }, { "context": "oduced as a mutable data structure in a pap...
lib/indexed.coffee
odf/pazy.js
0
# -------------------------------------------------------------------- # A number of collection classes based on Rich Hickey's persistent # hash trie implementation from Clojure (http://clojure.org), which # was originally introduced as a mutable data structure in a paper by # Phil Bagwell. # # To simplify the logic downstream, all node classes assume that # plus() or minus() are only ever called if they would result in a # changed node. This has therefore to be assured by the caller, and # ultimately by the collection classes themselves. # # This version: Copyright (c) 2010 Olaf Delgado-Friedrichs (odf@github.com) # # Original copyright and licensing: # -------------------------------------------------------------------- # Copyright (c) Rich Hickey. All rights reserved. # The use and distribution terms for this software are covered by the # Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) # which can be found in the file epl-v10.html at the root of this distribution. # By using this software in any fashion, you are agreeing to be bound by # the terms of this license. # You must not remove this notice, or any other, from this software. # -------------------------------------------------------------------- if typeof(require) != 'undefined' { equal, hashCode } = require 'core_extensions' { seq } = require('sequence') else { equal, hashCode, seq } = this.pazy # -------------------------------------------------------------------- # Nodes and support functions used by several collections. # -------------------------------------------------------------------- # A collection of utility functions used by interior nodes. util = { arrayWith: (a, i, x) -> (if j == i then x else a[j]) for j in [0...a.length] arrayWithInsertion: (a, i, x) -> (if j < i then a[j] else if j > i then a[j-1] else x) for j in [0..a.length] arrayWithout: (a, i) -> a[j] for j in [0...a.length] when j != i isKey: (n) -> typeof(n) == "number" and (0x100000000 > n >= 0) and (n % 1 == 0) mask: (key, shift) -> (key >> (27 - shift)) & 0x1f bitCount: (n) -> n -= (n >> 1) & 0x55555555 n = (n & 0x33333333) + ((n >> 2) & 0x33333333) n = (n & 0x0f0f0f0f) + ((n >> 4) & 0x0f0f0f0f) n += n >> 8 (n + (n >> 16)) & 0x3f indexForBit: (bitmap, bit) -> util.bitCount(bitmap & (bit - 1)) bitPosAndIndex: (bitmap, key, shift) -> bit = 1 << util.mask(key, shift) [bit, util.indexForBit(bitmap, bit)] } # A node with no entries. We need only one of those. EmptyNode = { size: 0 get: (shift, key, data) -> undefined elements: null plus: (shift, key, leaf) -> leaf minus: (shift, key, data) -> this toString: -> "EmptyNode" } # A sparse interior node using a bitmap to indicate which of the # indices 0..31 are in use. class BitmapIndexedNode constructor: (bitmap, progeny, size) -> [@bitmap, @progeny, @size] = if arguments.length == 0 [0, [], 0] else [bitmap, progeny, size] @elements = seq.flatMap @progeny, (n) -> n?.elements get: (shift, key, data) -> [bit, i] = util.bitPosAndIndex(@bitmap, key, shift) @progeny[i].get(shift + 5, key, data) if (@bitmap & bit) != 0 plus: (shift, key, leaf) -> [bit, i] = util.bitPosAndIndex(@bitmap, key, shift) if (@bitmap & bit) == 0 n = util.bitCount(@bitmap) if n < 8 newArray = util.arrayWithInsertion(@progeny, i, leaf) new BitmapIndexedNode(@bitmap | bit, newArray, @size + 1) else progeny = for m in [0..31] b = 1 << m @progeny[util.indexForBit(@bitmap, b)] if (@bitmap & b) != 0 new ArrayNode(progeny, util.mask(key, shift), leaf, @size + 1) else v = @progeny[i] node = v.plus(shift + 5, key, leaf) if @bitmap == (1 << i) new ProxyNode(i, node) else array = util.arrayWith(@progeny, i, node) new BitmapIndexedNode(@bitmap, array, @size + node.size - v.size) minus: (shift, key, data) -> [bit, i] = util.bitPosAndIndex(@bitmap, key, shift) v = @progeny[i] node = v.minus(shift + 5, key, data) if node? newBitmap = @bitmap newSize = @size + node.size - v.size newArray = util.arrayWith(@progeny, i, node) else newBitmap = @bitmap ^ bit newSize = @size - 1 newArray = util.arrayWithout(@progeny, i) bits = util.bitCount(newBitmap) if bits == 0 null else if bits == 1 node = newArray[0] if node.progeny? new ProxyNode(util.bitCount(newBitmap - 1), node) else node else new BitmapIndexedNode(newBitmap, newArray, newSize) toString: (prefix = '') -> pre = prefix + ' ' buf = [] for m in [0..31] b = 1 << m if (@bitmap & b) != 0 buf.push @progeny[util.indexForBit(@bitmap, b)].toString(pre) if buf.length == 1 '{' + buf[0] + '}' else buf.unshift '' '{' + buf.join('\n' + pre) + '}' # Special case of a sparse interior node which has exactly one descendant. class ProxyNode constructor: (@child_index, @progeny) -> @size = @progeny.size @elements = @progeny.elements get: (shift, key, data) -> @progeny.get(shift + 5, key, data) if @child_index == util.mask(key, shift) plus: (shift, key, leaf) -> i = util.mask(key, shift) if @child_index == i new ProxyNode(i, @progeny.plus(shift + 5, key, leaf)) else bitmap = (1 << @child_index) | (1 << i) array = if i < @child_index then [leaf, @progeny] else [@progeny, leaf] new BitmapIndexedNode(bitmap, array, @size + leaf.size) minus: (shift, key, data) -> node = @progeny.minus(shift + 5, key, data) if node?.progeny? new ProxyNode(@child_index, node) else node toString: (prefix = '') -> '.' + @progeny.toString(prefix + ' ') # A dense interior node with room for 32 entries. class ArrayNode constructor: (progeny, i, node, @size) -> @progeny = util.arrayWith(progeny, i, node) @elements = seq.flatMap @progeny, (n) -> n?.elements get: (shift, key, data) -> i = util.mask(key, shift) @progeny[i].get(shift + 5, key, data) if @progeny[i]? plus: (shift, key, leaf) -> i = util.mask(key, shift) if @progeny[i]? node = @progeny[i].plus(shift + 5, key, leaf) newSize = @size + node.size - @progeny[i].size new ArrayNode(@progeny, i, node, newSize) else new ArrayNode(@progeny, i, leaf, @size + 1) minus: (shift, key, data) -> i = util.mask(key, shift) node = @progeny[i].minus(shift + 5, key, data) if node? new ArrayNode(@progeny, i, node, @size - 1) else remaining = (j for j in [0...@progeny.length] when j != i and @progeny[j]) if remaining.length <= 4 bitmap = seq.reduce(remaining, 0, (b, j) -> b | (1 << j)) array = (@progeny[j] for j in remaining) new BitmapIndexedNode(bitmap, array, @size - 1) else new ArrayNode(@progeny, i, null, @size - 1) toString: (prefix = '') -> pre = prefix + ' ' buf = (x.toString(pre) for x in @progeny when x?) if buf.length == 1 '[' + buf[0] + ']' else buf.unshift '' '[' + buf.join('\n' + pre) + ']' # -------------------------------------------------------------------- # A common base class for all collection wrappers. # -------------------------------------------------------------------- class Collection # The constructor takes a root node, defaulting to empty. constructor: (@root) -> @root ?= EmptyNode @entries = @root?.elements size: -> @root.size # If called with a block, iterates over the elements in this set; # otherwise, returns this set (this mimics Ruby enumerables). each: (func) -> if func? then @entries?.each(func) else this # Generic update method update_: (root) -> if root != @root then new @constructor(root) else this # Returns a new set with the given keys inserted as elements, or # this set if it already contains all those elements. plus: -> @plusAll arguments # Like plus, but takes a sequence of keys plusAll: (s) -> @update_ seq.reduce s, @root, @constructor.plusOne # Returns a new set with the given keys removed, or this set if it # does not contain any of them. minus: -> @minusAll arguments # Like plus, but takes a sequence of keys minusAll: (s) -> @update_ seq.reduce s, @root, @constructor.minusOne # Creates a mapped collection of the same type map: (fun) -> new @constructor().plusAll seq.map @entries, fun # The sequence of entries. toSeq: -> @entries # Returns the elements in this set as an array. toArray: -> seq.into @entries, [] # Returns a string representation of this collection. toString: -> "#{@constructor.name}(#{@root})" # -------------------------------------------------------------------- # Collections with integer keys. # -------------------------------------------------------------------- # A leaf node containing a single integer. class IntLeaf constructor: (@key) -> @elements = seq.conj @key size: 1 get: (shift, key, data) -> key == @key plus: (shift, key, leaf) -> new BitmapIndexedNode().plus(shift, @key, this).plus(shift, key, leaf) minus: (shift, key, data) -> null toString: -> "#{@key}" # The IntSet class. class IntSet extends Collection @name = "IntSet" # Returns true or false depending on whether the given key is an # element of this set. contains: (key) -> @root.get(0, key) == true @plusOne: (root, key) -> if util.isKey(key) and not root.get(0, key) root.plus(0, key, new IntLeaf(key)) else root @minusOne: (root, key) -> if util.isKey(key) and root?.get(0, key) root.minus(0, key) else root # A leaf node with an integer key and arbitrary value. class IntLeafWithValue constructor: (@key, @value) -> @elements = seq.conj [@key, @value] size: 1 get: (shift, key, data) -> @value if key == @key plus: (shift, key, leaf) -> if @key == key leaf else new BitmapIndexedNode().plus(shift, @key, this).plus(shift, key, leaf) minus: (shift, key, data) -> null toString: -> "#{@key} ~> #{@value}" # The IntMap class is essentially a huge sparse array. class IntMap extends Collection @name = "IntMap" # Returns true or false depending on whether the given key is an # element of this set. get: (key) -> @root.get(0, key) @plusOne: (root, [key, value]) -> if util.isKey(key) and root.get(0, key) != value root.plus(0, key, new IntLeafWithValue(key, value)) else root @minusOne: (root, key) -> if util.isKey(key) and typeof(root?.get(0, key)) != 'undefined' root.minus(0, key) else root # -------------------------------------------------------------------- # Support for collections that use hashing. # -------------------------------------------------------------------- # A collision node contains several leaf nodes, stored in an array # @bucket, in which all keys share a common hash value. class CollisionNode constructor: (@hash, @bucket) -> @bucket = [] unless @bucket? @size = @bucket.length @elements = seq.flatMap @bucket, (n) -> n?.elements get: (shift, hash, key) -> leaf = seq.find @bucket, (v) -> equal(v.key, key) leaf.get(shift, hash, key) if leaf? plus: (shift, hash, leaf) -> if hash != @hash new BitmapIndexedNode().plus(shift, @hash, this).plus(shift, hash, leaf) else newBucket = this.bucketWithout(leaf.key) newBucket.push leaf new CollisionNode(hash, newBucket) minus: (shift, hash, key) -> switch @bucket.length when 0, 1 then null when 2 then seq.find @bucket, (v) -> not equal(v.key, key) else new CollisionNode(hash, this.bucketWithout(key)) toString: -> "#{@bucket.join("|")}" bucketWithout: (key) -> item for item in @bucket when not equal(item.key, key) # -------------------------------------------------------------------- # The hash set collection class and its leaf nodes. # -------------------------------------------------------------------- # A leaf node contains a single key and also caches its hash value. class HashLeaf constructor: (@hash, @key) -> @elements = seq.conj @key size: 1 get: (shift, hash, key) -> true if equal(key, @key) plus: (shift, hash, leaf) -> if hash == @hash base = new CollisionNode(hash) else base = new BitmapIndexedNode() base.plus(shift, @hash, this).plus(shift, hash, leaf) minus: (shift, hash, key) -> null toString: -> "#{@key}" # The HashSet class provides the public API and serves as a wrapper # for the various node classes that hold the actual information. class HashSet extends Collection @name = "HashSet" # Returns true or false depending on whether the given key is an # element of this set. contains: (key) -> @root.get(0, hashCode(key), key) == true @plusOne: (root, key) -> hash = hashCode(key) if root.get(0, hash, key) root else root.plus(0, hash, new HashLeaf(hash, key)) @minusOne: (root, key) -> hash = hashCode(key) if root?.get(0, hash, key) root.minus(0, hash, key) else root # -------------------------------------------------------------------- # The hash map collection class and its leaf nodes. # -------------------------------------------------------------------- # A leaf node contains a single key-value pair and also caches the # hash value for the key. class HashLeafWithValue constructor: (@hash, @key, @value) -> @elements = seq.conj [@key, @value] size: 1 get: (shift, hash, key) -> @value if equal(key, @key) plus: (shift, hash, leaf) -> if equal(@key, leaf.key) leaf else if hash == @hash base = new CollisionNode(hash) else base = new BitmapIndexedNode() base.plus(shift, @hash, this).plus(shift, hash, leaf) minus: (shift, hash, key) -> null toString: -> "#{@key} ~> #{@value}" # The HashMap class provides the public API and serves as a wrapper # for the various node classes that hold the actual information. class HashMap extends Collection @name = "HashMap" # Retrieves the value associated with the given key, or nil if the # key is not present. get: (key) -> @root.get(0, hashCode(key), key) @plusOne: (root, [key, value]) -> hash = hashCode(key) if root.get(0, hash, key) == value root else root.plus(0, hash, new HashLeafWithValue(hash, key, value)) @minusOne: (root, key) -> hash = hashCode(key) if typeof(root?.get(0, hash, key)) != 'undefined' root.minus(0, hash, key) else root # -------------------------------------------------------------------- # Exporting. # -------------------------------------------------------------------- exports = module?.exports or this.pazy ?= {} exports.IntSet = IntSet exports.IntMap = IntMap exports.HashMap = HashMap exports.HashSet = HashSet
98286
# -------------------------------------------------------------------- # A number of collection classes based on <NAME>'s persistent # hash trie implementation from Clojure (http://clojure.org), which # was originally introduced as a mutable data structure in a paper by # <NAME>. # # To simplify the logic downstream, all node classes assume that # plus() or minus() are only ever called if they would result in a # changed node. This has therefore to be assured by the caller, and # ultimately by the collection classes themselves. # # This version: Copyright (c) 2010 <NAME> (<EMAIL>) # # Original copyright and licensing: # -------------------------------------------------------------------- # Copyright (c) <NAME>. All rights reserved. # The use and distribution terms for this software are covered by the # Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) # which can be found in the file epl-v10.html at the root of this distribution. # By using this software in any fashion, you are agreeing to be bound by # the terms of this license. # You must not remove this notice, or any other, from this software. # -------------------------------------------------------------------- if typeof(require) != 'undefined' { equal, hashCode } = require 'core_extensions' { seq } = require('sequence') else { equal, hashCode, seq } = this.pazy # -------------------------------------------------------------------- # Nodes and support functions used by several collections. # -------------------------------------------------------------------- # A collection of utility functions used by interior nodes. util = { arrayWith: (a, i, x) -> (if j == i then x else a[j]) for j in [0...a.length] arrayWithInsertion: (a, i, x) -> (if j < i then a[j] else if j > i then a[j-1] else x) for j in [0..a.length] arrayWithout: (a, i) -> a[j] for j in [0...a.length] when j != i isKey: (n) -> typeof(n) == "number" and (0x100000000 > n >= 0) and (n % 1 == 0) mask: (key, shift) -> (key >> (27 - shift)) & 0x1f bitCount: (n) -> n -= (n >> 1) & 0x55555555 n = (n & 0x33333333) + ((n >> 2) & 0x33333333) n = (n & 0x0f0f0f0f) + ((n >> 4) & 0x0f0f0f0f) n += n >> 8 (n + (n >> 16)) & 0x3f indexForBit: (bitmap, bit) -> util.bitCount(bitmap & (bit - 1)) bitPosAndIndex: (bitmap, key, shift) -> bit = 1 << util.mask(key, shift) [bit, util.indexForBit(bitmap, bit)] } # A node with no entries. We need only one of those. EmptyNode = { size: 0 get: (shift, key, data) -> undefined elements: null plus: (shift, key, leaf) -> leaf minus: (shift, key, data) -> this toString: -> "EmptyNode" } # A sparse interior node using a bitmap to indicate which of the # indices 0..31 are in use. class BitmapIndexedNode constructor: (bitmap, progeny, size) -> [@bitmap, @progeny, @size] = if arguments.length == 0 [0, [], 0] else [bitmap, progeny, size] @elements = seq.flatMap @progeny, (n) -> n?.elements get: (shift, key, data) -> [bit, i] = util.bitPosAndIndex(@bitmap, key, shift) @progeny[i].get(shift + 5, key, data) if (@bitmap & bit) != 0 plus: (shift, key, leaf) -> [bit, i] = util.bitPosAndIndex(@bitmap, key, shift) if (@bitmap & bit) == 0 n = util.bitCount(@bitmap) if n < 8 newArray = util.arrayWithInsertion(@progeny, i, leaf) new BitmapIndexedNode(@bitmap | bit, newArray, @size + 1) else progeny = for m in [0..31] b = 1 << m @progeny[util.indexForBit(@bitmap, b)] if (@bitmap & b) != 0 new ArrayNode(progeny, util.mask(key, shift), leaf, @size + 1) else v = @progeny[i] node = v.plus(shift + 5, key, leaf) if @bitmap == (1 << i) new ProxyNode(i, node) else array = util.arrayWith(@progeny, i, node) new BitmapIndexedNode(@bitmap, array, @size + node.size - v.size) minus: (shift, key, data) -> [bit, i] = util.bitPosAndIndex(@bitmap, key, shift) v = @progeny[i] node = v.minus(shift + 5, key, data) if node? newBitmap = @bitmap newSize = @size + node.size - v.size newArray = util.arrayWith(@progeny, i, node) else newBitmap = @bitmap ^ bit newSize = @size - 1 newArray = util.arrayWithout(@progeny, i) bits = util.bitCount(newBitmap) if bits == 0 null else if bits == 1 node = newArray[0] if node.progeny? new ProxyNode(util.bitCount(newBitmap - 1), node) else node else new BitmapIndexedNode(newBitmap, newArray, newSize) toString: (prefix = '') -> pre = prefix + ' ' buf = [] for m in [0..31] b = 1 << m if (@bitmap & b) != 0 buf.push @progeny[util.indexForBit(@bitmap, b)].toString(pre) if buf.length == 1 '{' + buf[0] + '}' else buf.unshift '' '{' + buf.join('\n' + pre) + '}' # Special case of a sparse interior node which has exactly one descendant. class ProxyNode constructor: (@child_index, @progeny) -> @size = @progeny.size @elements = @progeny.elements get: (shift, key, data) -> @progeny.get(shift + 5, key, data) if @child_index == util.mask(key, shift) plus: (shift, key, leaf) -> i = util.mask(key, shift) if @child_index == i new ProxyNode(i, @progeny.plus(shift + 5, key, leaf)) else bitmap = (1 << @child_index) | (1 << i) array = if i < @child_index then [leaf, @progeny] else [@progeny, leaf] new BitmapIndexedNode(bitmap, array, @size + leaf.size) minus: (shift, key, data) -> node = @progeny.minus(shift + 5, key, data) if node?.progeny? new ProxyNode(@child_index, node) else node toString: (prefix = '') -> '.' + @progeny.toString(prefix + ' ') # A dense interior node with room for 32 entries. class ArrayNode constructor: (progeny, i, node, @size) -> @progeny = util.arrayWith(progeny, i, node) @elements = seq.flatMap @progeny, (n) -> n?.elements get: (shift, key, data) -> i = util.mask(key, shift) @progeny[i].get(shift + 5, key, data) if @progeny[i]? plus: (shift, key, leaf) -> i = util.mask(key, shift) if @progeny[i]? node = @progeny[i].plus(shift + 5, key, leaf) newSize = @size + node.size - @progeny[i].size new ArrayNode(@progeny, i, node, newSize) else new ArrayNode(@progeny, i, leaf, @size + 1) minus: (shift, key, data) -> i = util.mask(key, shift) node = @progeny[i].minus(shift + 5, key, data) if node? new ArrayNode(@progeny, i, node, @size - 1) else remaining = (j for j in [0...@progeny.length] when j != i and @progeny[j]) if remaining.length <= 4 bitmap = seq.reduce(remaining, 0, (b, j) -> b | (1 << j)) array = (@progeny[j] for j in remaining) new BitmapIndexedNode(bitmap, array, @size - 1) else new ArrayNode(@progeny, i, null, @size - 1) toString: (prefix = '') -> pre = prefix + ' ' buf = (x.toString(pre) for x in @progeny when x?) if buf.length == 1 '[' + buf[0] + ']' else buf.unshift '' '[' + buf.join('\n' + pre) + ']' # -------------------------------------------------------------------- # A common base class for all collection wrappers. # -------------------------------------------------------------------- class Collection # The constructor takes a root node, defaulting to empty. constructor: (@root) -> @root ?= EmptyNode @entries = @root?.elements size: -> @root.size # If called with a block, iterates over the elements in this set; # otherwise, returns this set (this mimics Ruby enumerables). each: (func) -> if func? then @entries?.each(func) else this # Generic update method update_: (root) -> if root != @root then new @constructor(root) else this # Returns a new set with the given keys inserted as elements, or # this set if it already contains all those elements. plus: -> @plusAll arguments # Like plus, but takes a sequence of keys plusAll: (s) -> @update_ seq.reduce s, @root, @constructor.plusOne # Returns a new set with the given keys removed, or this set if it # does not contain any of them. minus: -> @minusAll arguments # Like plus, but takes a sequence of keys minusAll: (s) -> @update_ seq.reduce s, @root, @constructor.minusOne # Creates a mapped collection of the same type map: (fun) -> new @constructor().plusAll seq.map @entries, fun # The sequence of entries. toSeq: -> @entries # Returns the elements in this set as an array. toArray: -> seq.into @entries, [] # Returns a string representation of this collection. toString: -> "#{@constructor.name}(#{@root})" # -------------------------------------------------------------------- # Collections with integer keys. # -------------------------------------------------------------------- # A leaf node containing a single integer. class IntLeaf constructor: (@key) -> @elements = seq.conj @key size: 1 get: (shift, key, data) -> key == @key plus: (shift, key, leaf) -> new BitmapIndexedNode().plus(shift, @key, this).plus(shift, key, leaf) minus: (shift, key, data) -> null toString: -> "#{@key}" # The IntSet class. class IntSet extends Collection @name = "IntSet" # Returns true or false depending on whether the given key is an # element of this set. contains: (key) -> @root.get(0, key) == true @plusOne: (root, key) -> if util.isKey(key) and not root.get(0, key) root.plus(0, key, new IntLeaf(key)) else root @minusOne: (root, key) -> if util.isKey(key) and root?.get(0, key) root.minus(0, key) else root # A leaf node with an integer key and arbitrary value. class IntLeafWithValue constructor: (@key, @value) -> @elements = seq.conj [@key, @value] size: 1 get: (shift, key, data) -> @value if key == @key plus: (shift, key, leaf) -> if @key == key leaf else new BitmapIndexedNode().plus(shift, @key, this).plus(shift, key, leaf) minus: (shift, key, data) -> null toString: -> "#{@key} ~> #{@value}" # The IntMap class is essentially a huge sparse array. class IntMap extends Collection @name = "IntMap" # Returns true or false depending on whether the given key is an # element of this set. get: (key) -> @root.get(0, key) @plusOne: (root, [key, value]) -> if util.isKey(key) and root.get(0, key) != value root.plus(0, key, new IntLeafWithValue(key, value)) else root @minusOne: (root, key) -> if util.isKey(key) and typeof(root?.get(0, key)) != 'undefined' root.minus(0, key) else root # -------------------------------------------------------------------- # Support for collections that use hashing. # -------------------------------------------------------------------- # A collision node contains several leaf nodes, stored in an array # @bucket, in which all keys share a common hash value. class CollisionNode constructor: (@hash, @bucket) -> @bucket = [] unless @bucket? @size = @bucket.length @elements = seq.flatMap @bucket, (n) -> n?.elements get: (shift, hash, key) -> leaf = seq.find @bucket, (v) -> equal(v.key, key) leaf.get(shift, hash, key) if leaf? plus: (shift, hash, leaf) -> if hash != @hash new BitmapIndexedNode().plus(shift, @hash, this).plus(shift, hash, leaf) else newBucket = this.bucketWithout(leaf.key) newBucket.push leaf new CollisionNode(hash, newBucket) minus: (shift, hash, key) -> switch @bucket.length when 0, 1 then null when 2 then seq.find @bucket, (v) -> not equal(v.key, key) else new CollisionNode(hash, this.bucketWithout(key)) toString: -> "#{@bucket.join("|")}" bucketWithout: (key) -> item for item in @bucket when not equal(item.key, key) # -------------------------------------------------------------------- # The hash set collection class and its leaf nodes. # -------------------------------------------------------------------- # A leaf node contains a single key and also caches its hash value. class HashLeaf constructor: (@hash, @key) -> @elements = seq.conj @key size: 1 get: (shift, hash, key) -> true if equal(key, @key) plus: (shift, hash, leaf) -> if hash == @hash base = new CollisionNode(hash) else base = new BitmapIndexedNode() base.plus(shift, @hash, this).plus(shift, hash, leaf) minus: (shift, hash, key) -> null toString: -> "#{@key}" # The HashSet class provides the public API and serves as a wrapper # for the various node classes that hold the actual information. class HashSet extends Collection @name = "HashSet" # Returns true or false depending on whether the given key is an # element of this set. contains: (key) -> @root.get(0, hashCode(key), key) == true @plusOne: (root, key) -> hash = hashCode(key) if root.get(0, hash, key) root else root.plus(0, hash, new HashLeaf(hash, key)) @minusOne: (root, key) -> hash = hashCode(key) if root?.get(0, hash, key) root.minus(0, hash, key) else root # -------------------------------------------------------------------- # The hash map collection class and its leaf nodes. # -------------------------------------------------------------------- # A leaf node contains a single key-value pair and also caches the # hash value for the key. class HashLeafWithValue constructor: (@hash, @key, @value) -> @elements = seq.conj [@key, @value] size: 1 get: (shift, hash, key) -> @value if equal(key, @key) plus: (shift, hash, leaf) -> if equal(@key, leaf.key) leaf else if hash == @hash base = new CollisionNode(hash) else base = new BitmapIndexedNode() base.plus(shift, @hash, this).plus(shift, hash, leaf) minus: (shift, hash, key) -> null toString: -> "#{@key} ~> #{@value}" # The HashMap class provides the public API and serves as a wrapper # for the various node classes that hold the actual information. class HashMap extends Collection @name = "HashMap" # Retrieves the value associated with the given key, or nil if the # key is not present. get: (key) -> @root.get(0, hashCode(key), key) @plusOne: (root, [key, value]) -> hash = hashCode(key) if root.get(0, hash, key) == value root else root.plus(0, hash, new HashLeafWithValue(hash, key, value)) @minusOne: (root, key) -> hash = hashCode(key) if typeof(root?.get(0, hash, key)) != 'undefined' root.minus(0, hash, key) else root # -------------------------------------------------------------------- # Exporting. # -------------------------------------------------------------------- exports = module?.exports or this.pazy ?= {} exports.IntSet = IntSet exports.IntMap = IntMap exports.HashMap = HashMap exports.HashSet = HashSet
true
# -------------------------------------------------------------------- # A number of collection classes based on PI:NAME:<NAME>END_PI's persistent # hash trie implementation from Clojure (http://clojure.org), which # was originally introduced as a mutable data structure in a paper by # PI:NAME:<NAME>END_PI. # # To simplify the logic downstream, all node classes assume that # plus() or minus() are only ever called if they would result in a # changed node. This has therefore to be assured by the caller, and # ultimately by the collection classes themselves. # # This version: Copyright (c) 2010 PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI) # # Original copyright and licensing: # -------------------------------------------------------------------- # Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved. # The use and distribution terms for this software are covered by the # Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) # which can be found in the file epl-v10.html at the root of this distribution. # By using this software in any fashion, you are agreeing to be bound by # the terms of this license. # You must not remove this notice, or any other, from this software. # -------------------------------------------------------------------- if typeof(require) != 'undefined' { equal, hashCode } = require 'core_extensions' { seq } = require('sequence') else { equal, hashCode, seq } = this.pazy # -------------------------------------------------------------------- # Nodes and support functions used by several collections. # -------------------------------------------------------------------- # A collection of utility functions used by interior nodes. util = { arrayWith: (a, i, x) -> (if j == i then x else a[j]) for j in [0...a.length] arrayWithInsertion: (a, i, x) -> (if j < i then a[j] else if j > i then a[j-1] else x) for j in [0..a.length] arrayWithout: (a, i) -> a[j] for j in [0...a.length] when j != i isKey: (n) -> typeof(n) == "number" and (0x100000000 > n >= 0) and (n % 1 == 0) mask: (key, shift) -> (key >> (27 - shift)) & 0x1f bitCount: (n) -> n -= (n >> 1) & 0x55555555 n = (n & 0x33333333) + ((n >> 2) & 0x33333333) n = (n & 0x0f0f0f0f) + ((n >> 4) & 0x0f0f0f0f) n += n >> 8 (n + (n >> 16)) & 0x3f indexForBit: (bitmap, bit) -> util.bitCount(bitmap & (bit - 1)) bitPosAndIndex: (bitmap, key, shift) -> bit = 1 << util.mask(key, shift) [bit, util.indexForBit(bitmap, bit)] } # A node with no entries. We need only one of those. EmptyNode = { size: 0 get: (shift, key, data) -> undefined elements: null plus: (shift, key, leaf) -> leaf minus: (shift, key, data) -> this toString: -> "EmptyNode" } # A sparse interior node using a bitmap to indicate which of the # indices 0..31 are in use. class BitmapIndexedNode constructor: (bitmap, progeny, size) -> [@bitmap, @progeny, @size] = if arguments.length == 0 [0, [], 0] else [bitmap, progeny, size] @elements = seq.flatMap @progeny, (n) -> n?.elements get: (shift, key, data) -> [bit, i] = util.bitPosAndIndex(@bitmap, key, shift) @progeny[i].get(shift + 5, key, data) if (@bitmap & bit) != 0 plus: (shift, key, leaf) -> [bit, i] = util.bitPosAndIndex(@bitmap, key, shift) if (@bitmap & bit) == 0 n = util.bitCount(@bitmap) if n < 8 newArray = util.arrayWithInsertion(@progeny, i, leaf) new BitmapIndexedNode(@bitmap | bit, newArray, @size + 1) else progeny = for m in [0..31] b = 1 << m @progeny[util.indexForBit(@bitmap, b)] if (@bitmap & b) != 0 new ArrayNode(progeny, util.mask(key, shift), leaf, @size + 1) else v = @progeny[i] node = v.plus(shift + 5, key, leaf) if @bitmap == (1 << i) new ProxyNode(i, node) else array = util.arrayWith(@progeny, i, node) new BitmapIndexedNode(@bitmap, array, @size + node.size - v.size) minus: (shift, key, data) -> [bit, i] = util.bitPosAndIndex(@bitmap, key, shift) v = @progeny[i] node = v.minus(shift + 5, key, data) if node? newBitmap = @bitmap newSize = @size + node.size - v.size newArray = util.arrayWith(@progeny, i, node) else newBitmap = @bitmap ^ bit newSize = @size - 1 newArray = util.arrayWithout(@progeny, i) bits = util.bitCount(newBitmap) if bits == 0 null else if bits == 1 node = newArray[0] if node.progeny? new ProxyNode(util.bitCount(newBitmap - 1), node) else node else new BitmapIndexedNode(newBitmap, newArray, newSize) toString: (prefix = '') -> pre = prefix + ' ' buf = [] for m in [0..31] b = 1 << m if (@bitmap & b) != 0 buf.push @progeny[util.indexForBit(@bitmap, b)].toString(pre) if buf.length == 1 '{' + buf[0] + '}' else buf.unshift '' '{' + buf.join('\n' + pre) + '}' # Special case of a sparse interior node which has exactly one descendant. class ProxyNode constructor: (@child_index, @progeny) -> @size = @progeny.size @elements = @progeny.elements get: (shift, key, data) -> @progeny.get(shift + 5, key, data) if @child_index == util.mask(key, shift) plus: (shift, key, leaf) -> i = util.mask(key, shift) if @child_index == i new ProxyNode(i, @progeny.plus(shift + 5, key, leaf)) else bitmap = (1 << @child_index) | (1 << i) array = if i < @child_index then [leaf, @progeny] else [@progeny, leaf] new BitmapIndexedNode(bitmap, array, @size + leaf.size) minus: (shift, key, data) -> node = @progeny.minus(shift + 5, key, data) if node?.progeny? new ProxyNode(@child_index, node) else node toString: (prefix = '') -> '.' + @progeny.toString(prefix + ' ') # A dense interior node with room for 32 entries. class ArrayNode constructor: (progeny, i, node, @size) -> @progeny = util.arrayWith(progeny, i, node) @elements = seq.flatMap @progeny, (n) -> n?.elements get: (shift, key, data) -> i = util.mask(key, shift) @progeny[i].get(shift + 5, key, data) if @progeny[i]? plus: (shift, key, leaf) -> i = util.mask(key, shift) if @progeny[i]? node = @progeny[i].plus(shift + 5, key, leaf) newSize = @size + node.size - @progeny[i].size new ArrayNode(@progeny, i, node, newSize) else new ArrayNode(@progeny, i, leaf, @size + 1) minus: (shift, key, data) -> i = util.mask(key, shift) node = @progeny[i].minus(shift + 5, key, data) if node? new ArrayNode(@progeny, i, node, @size - 1) else remaining = (j for j in [0...@progeny.length] when j != i and @progeny[j]) if remaining.length <= 4 bitmap = seq.reduce(remaining, 0, (b, j) -> b | (1 << j)) array = (@progeny[j] for j in remaining) new BitmapIndexedNode(bitmap, array, @size - 1) else new ArrayNode(@progeny, i, null, @size - 1) toString: (prefix = '') -> pre = prefix + ' ' buf = (x.toString(pre) for x in @progeny when x?) if buf.length == 1 '[' + buf[0] + ']' else buf.unshift '' '[' + buf.join('\n' + pre) + ']' # -------------------------------------------------------------------- # A common base class for all collection wrappers. # -------------------------------------------------------------------- class Collection # The constructor takes a root node, defaulting to empty. constructor: (@root) -> @root ?= EmptyNode @entries = @root?.elements size: -> @root.size # If called with a block, iterates over the elements in this set; # otherwise, returns this set (this mimics Ruby enumerables). each: (func) -> if func? then @entries?.each(func) else this # Generic update method update_: (root) -> if root != @root then new @constructor(root) else this # Returns a new set with the given keys inserted as elements, or # this set if it already contains all those elements. plus: -> @plusAll arguments # Like plus, but takes a sequence of keys plusAll: (s) -> @update_ seq.reduce s, @root, @constructor.plusOne # Returns a new set with the given keys removed, or this set if it # does not contain any of them. minus: -> @minusAll arguments # Like plus, but takes a sequence of keys minusAll: (s) -> @update_ seq.reduce s, @root, @constructor.minusOne # Creates a mapped collection of the same type map: (fun) -> new @constructor().plusAll seq.map @entries, fun # The sequence of entries. toSeq: -> @entries # Returns the elements in this set as an array. toArray: -> seq.into @entries, [] # Returns a string representation of this collection. toString: -> "#{@constructor.name}(#{@root})" # -------------------------------------------------------------------- # Collections with integer keys. # -------------------------------------------------------------------- # A leaf node containing a single integer. class IntLeaf constructor: (@key) -> @elements = seq.conj @key size: 1 get: (shift, key, data) -> key == @key plus: (shift, key, leaf) -> new BitmapIndexedNode().plus(shift, @key, this).plus(shift, key, leaf) minus: (shift, key, data) -> null toString: -> "#{@key}" # The IntSet class. class IntSet extends Collection @name = "IntSet" # Returns true or false depending on whether the given key is an # element of this set. contains: (key) -> @root.get(0, key) == true @plusOne: (root, key) -> if util.isKey(key) and not root.get(0, key) root.plus(0, key, new IntLeaf(key)) else root @minusOne: (root, key) -> if util.isKey(key) and root?.get(0, key) root.minus(0, key) else root # A leaf node with an integer key and arbitrary value. class IntLeafWithValue constructor: (@key, @value) -> @elements = seq.conj [@key, @value] size: 1 get: (shift, key, data) -> @value if key == @key plus: (shift, key, leaf) -> if @key == key leaf else new BitmapIndexedNode().plus(shift, @key, this).plus(shift, key, leaf) minus: (shift, key, data) -> null toString: -> "#{@key} ~> #{@value}" # The IntMap class is essentially a huge sparse array. class IntMap extends Collection @name = "IntMap" # Returns true or false depending on whether the given key is an # element of this set. get: (key) -> @root.get(0, key) @plusOne: (root, [key, value]) -> if util.isKey(key) and root.get(0, key) != value root.plus(0, key, new IntLeafWithValue(key, value)) else root @minusOne: (root, key) -> if util.isKey(key) and typeof(root?.get(0, key)) != 'undefined' root.minus(0, key) else root # -------------------------------------------------------------------- # Support for collections that use hashing. # -------------------------------------------------------------------- # A collision node contains several leaf nodes, stored in an array # @bucket, in which all keys share a common hash value. class CollisionNode constructor: (@hash, @bucket) -> @bucket = [] unless @bucket? @size = @bucket.length @elements = seq.flatMap @bucket, (n) -> n?.elements get: (shift, hash, key) -> leaf = seq.find @bucket, (v) -> equal(v.key, key) leaf.get(shift, hash, key) if leaf? plus: (shift, hash, leaf) -> if hash != @hash new BitmapIndexedNode().plus(shift, @hash, this).plus(shift, hash, leaf) else newBucket = this.bucketWithout(leaf.key) newBucket.push leaf new CollisionNode(hash, newBucket) minus: (shift, hash, key) -> switch @bucket.length when 0, 1 then null when 2 then seq.find @bucket, (v) -> not equal(v.key, key) else new CollisionNode(hash, this.bucketWithout(key)) toString: -> "#{@bucket.join("|")}" bucketWithout: (key) -> item for item in @bucket when not equal(item.key, key) # -------------------------------------------------------------------- # The hash set collection class and its leaf nodes. # -------------------------------------------------------------------- # A leaf node contains a single key and also caches its hash value. class HashLeaf constructor: (@hash, @key) -> @elements = seq.conj @key size: 1 get: (shift, hash, key) -> true if equal(key, @key) plus: (shift, hash, leaf) -> if hash == @hash base = new CollisionNode(hash) else base = new BitmapIndexedNode() base.plus(shift, @hash, this).plus(shift, hash, leaf) minus: (shift, hash, key) -> null toString: -> "#{@key}" # The HashSet class provides the public API and serves as a wrapper # for the various node classes that hold the actual information. class HashSet extends Collection @name = "HashSet" # Returns true or false depending on whether the given key is an # element of this set. contains: (key) -> @root.get(0, hashCode(key), key) == true @plusOne: (root, key) -> hash = hashCode(key) if root.get(0, hash, key) root else root.plus(0, hash, new HashLeaf(hash, key)) @minusOne: (root, key) -> hash = hashCode(key) if root?.get(0, hash, key) root.minus(0, hash, key) else root # -------------------------------------------------------------------- # The hash map collection class and its leaf nodes. # -------------------------------------------------------------------- # A leaf node contains a single key-value pair and also caches the # hash value for the key. class HashLeafWithValue constructor: (@hash, @key, @value) -> @elements = seq.conj [@key, @value] size: 1 get: (shift, hash, key) -> @value if equal(key, @key) plus: (shift, hash, leaf) -> if equal(@key, leaf.key) leaf else if hash == @hash base = new CollisionNode(hash) else base = new BitmapIndexedNode() base.plus(shift, @hash, this).plus(shift, hash, leaf) minus: (shift, hash, key) -> null toString: -> "#{@key} ~> #{@value}" # The HashMap class provides the public API and serves as a wrapper # for the various node classes that hold the actual information. class HashMap extends Collection @name = "HashMap" # Retrieves the value associated with the given key, or nil if the # key is not present. get: (key) -> @root.get(0, hashCode(key), key) @plusOne: (root, [key, value]) -> hash = hashCode(key) if root.get(0, hash, key) == value root else root.plus(0, hash, new HashLeafWithValue(hash, key, value)) @minusOne: (root, key) -> hash = hashCode(key) if typeof(root?.get(0, hash, key)) != 'undefined' root.minus(0, hash, key) else root # -------------------------------------------------------------------- # Exporting. # -------------------------------------------------------------------- exports = module?.exports or this.pazy ?= {} exports.IntSet = IntSet exports.IntMap = IntMap exports.HashMap = HashMap exports.HashSet = HashSet
[ { "context": "use: sinon.spy(), resume: sinon.spy(), username: \"anonymous\", authorization: {} }\n @res = { header: sinon.", "end": 2907, "score": 0.9973425269126892, "start": 2898, "tag": "USERNAME", "value": "anonymous" }, { "context": "eEach ->\n @us...
test/ropc-unit.coffee
awdrius/restify-oauth2
0
"use strict" require("chai").use(require("sinon-chai")) sinon = require("sinon") should = require("chai").should() Assertion = require("chai").Assertion restify = require("restify") restifyOAuth2 = require("..") tokenEndpoint = "/token-uri" wwwAuthenticateRealm = "Realm string" tokenExpirationTime = 12345 Assertion.addMethod("unauthorized", (message, options) -> expectedLink = '<' + tokenEndpoint + '>; rel="oauth2-token"; grant-types="password"; token-types="bearer"' expectedWwwAuthenticate = 'Bearer realm="' + wwwAuthenticateRealm + '"' if not options?.noWwwAuthenticateErrors expectedWwwAuthenticate += ', error="invalid_token", error_description="' + message + '"' spyToTest = if options?.send then @_obj.send else @_obj.nextSpy @_obj.header.should.have.been.calledWith("WWW-Authenticate", expectedWwwAuthenticate) @_obj.header.should.have.been.calledWith("Link", expectedLink) spyToTest.should.have.been.calledOnce spyToTest.should.have.been.calledWith(sinon.match.instanceOf(restify.UnauthorizedError)) spyToTest.should.have.been.calledWith(sinon.match.has("message", sinon.match(message))) ) Assertion.addMethod("unauthenticated", (message) -> expectedLink = '<' + tokenEndpoint + '>; rel="oauth2-token"; grant-types="password"; token-types="bearer"' @_obj.header.should.have.been.calledWith("Link", expectedLink) @_obj.send.should.have.been.calledOnce @_obj.send.should.have.been.calledWith(sinon.match.instanceOf(restify.ForbiddenError)) @_obj.send.should.have.been.calledWith(sinon.match.has("message", sinon.match(message))) ) Assertion.addMethod("bad", (message) -> expectedLink = '<' + tokenEndpoint + '>; rel="oauth2-token"; grant-types="password"; token-types="bearer"' expectedWwwAuthenticate = 'Bearer realm="' + wwwAuthenticateRealm + '", error="invalid_request", ' + 'error_description="' + message + '"' @_obj.header.should.have.been.calledWith("WWW-Authenticate", expectedWwwAuthenticate) @_obj.header.should.have.been.calledWith("Link", expectedLink) @_obj.nextSpy.should.have.been.calledOnce @_obj.nextSpy.should.have.been.calledWith(sinon.match.instanceOf(restify.BadRequestError)) @_obj.nextSpy.should.have.been.calledWith(sinon.match.has("message", sinon.match(message))) ) Assertion.addMethod("oauthError", (errorClass, errorType, errorDescription) -> desiredBody = { error: errorType, error_description: errorDescription } @_obj.nextSpy.should.have.been.calledOnce @_obj.nextSpy.should.have.been.calledWith(sinon.match.instanceOf(restify[errorClass + "Error"])) @_obj.nextSpy.should.have.been.calledWith(sinon.match.has("message", errorDescription)) @_obj.nextSpy.should.have.been.calledWith(sinon.match.has("body", desiredBody)) ) beforeEach -> @req = { pause: sinon.spy(), resume: sinon.spy(), username: "anonymous", authorization: {} } @res = { header: sinon.spy(), send: sinon.spy() } @tokenNext = sinon.spy() @pluginNext = sinon.spy() @server = post: sinon.spy((path, handler) => @postToTokenEndpoint = => handler(@req, @res, @tokenNext)) use: (plugin) => plugin(@req, @res, @pluginNext) @authenticateToken = sinon.stub() @validateClient = sinon.stub() @grantUserToken = sinon.stub() @grantScopes = sinon.stub() options = { tokenEndpoint wwwAuthenticateRealm tokenExpirationTime hooks: { @authenticateToken @validateClient @grantUserToken } } optionsWithScope = { tokenEndpoint wwwAuthenticateRealm tokenExpirationTime hooks: { @authenticateToken @validateClient @grantUserToken @grantScopes } } @doIt = => restifyOAuth2.ropc(@server, options) @doItWithScopes = => restifyOAuth2.ropc(@server, optionsWithScope) describe "Resource Owner Password Credentials flow", -> it "should set up the token endpoint", -> @doIt() @server.post.should.have.been.calledWith(tokenEndpoint) describe "For POST requests to the token endpoint", -> beforeEach -> @req.method = "POST" @req.path = => tokenEndpoint @res.nextSpy = @tokenNext baseDoIt = @doIt @doIt = => baseDoIt() @postToTokenEndpoint() describe "with a body", -> beforeEach -> @req.body = {} describe "that has grant_type=password", -> beforeEach -> @req.body.grant_type = "password" describe "with a basic access authentication header", -> beforeEach -> [@clientId, @clientSecret] = ["clientId123", "clientSecret456"] @req.authorization = scheme: "Basic" basic: { username: @clientId, password: @clientSecret } describe "and has a username field", -> beforeEach -> @username = "username123" @req.body.username = @username describe "and a password field", -> beforeEach -> @password = "password456" @req.body.password = @password it "should validate the client, with client ID/secret from the basic authentication", -> @doIt() @validateClient.should.have.been.calledWith({ @clientId, @clientSecret }, @req) describe "when `validateClient` calls back with `true`", -> beforeEach -> @validateClient.yields(null, true) it "should use the username and password body fields to grant a token", -> @doIt() @grantUserToken.should.have.been.calledWith( { @clientId, @clientSecret, @username, @password }, @req ) describe "when `grantUserToken` calls back with a token", -> beforeEach -> @token = "token123" @grantUserToken.yields(null, @token) describe "and a `grantScopes` hook is defined", -> beforeEach -> baseDoIt = @doItWithScopes @doIt = => baseDoIt() @postToTokenEndpoint() @requestedScopes = ["one", "two"] @req.body.scope = @requestedScopes.join(" ") it "should use credentials and requested scopes to grant scopes", -> @doIt() @grantScopes.should.have.been.calledWith( { @clientId, @clientSecret, @username, @password, @token }, @requestedScopes ) describe "when `grantScopes` calls back with an array of granted scopes", -> beforeEach -> @grantedScopes = ["three"] @grantScopes.yields(null, @grantedScopes) it "should send a response with access_token, token_type, scope, and " + "expires_in set, where scope is limited to the granted scopes", -> @doIt() @res.send.should.have.been.calledWith( access_token: @token, token_type: "Bearer" expires_in: tokenExpirationTime, scope: @grantedScopes.join(" ") ) it "should call `next`", -> @doIt() @tokenNext.should.have.been.calledWithExactly() describe "when `grantScopes` calls back with `true`", -> beforeEach -> @grantScopes.yields(null, true) it "should send a response with access_token, token_type, scope, and " + "expires_in set, where scope is the same as the requested scopes", -> @doIt() @res.send.should.have.been.calledWith( access_token: @token, token_type: "Bearer" expires_in: tokenExpirationTime, scope: @requestedScopes.join(" ") ) it "should call `next`", -> @doIt() @tokenNext.should.have.been.calledWithExactly() describe "when `grantScopes` calls back with `false`", -> beforeEach -> @grantScopes.yields(null, false) it "should send a 400 response with error_type=invalid_scope", -> @doIt() message = "The requested scopes are invalid, unknown, or exceed the " + "set of scopes appropriate for these credentials." @res.should.be.an.oauthError("BadRequest", "invalid_scope", message) describe "when `grantScopes` calls back with an error", -> beforeEach -> @error = new Error("Bad things happened, internally.") @grantScopes.yields(@error) it "should call `next` with that error", -> @doIt() @tokenNext.should.have.been.calledWithExactly(@error) describe "and a `grantScopes` hook is not defined", -> beforeEach -> @grantScopes = undefined it "should send a response with access_token, token_type, and expires_in " + "set", -> @doIt() @res.send.should.have.been.calledWith( access_token: @token, token_type: "Bearer" expires_in: tokenExpirationTime ) it "should call `next`", -> @doIt() @tokenNext.should.have.been.calledWithExactly() describe "when `grantUserToken` calls back with `false`", -> beforeEach -> @grantUserToken.yields(null, false) it "should send a 401 response with error_type=invalid_grant", -> @doIt() @res.should.be.an.oauthError("Unauthorized", "invalid_grant", "Username and password did not authenticate.") describe "when `grantUserToken` calls back with `null`", -> beforeEach -> @grantUserToken.yields(null, null) it "should send a 401 response with error_type=invalid_grant", -> @doIt() @res.should.be.an.oauthError("Unauthorized", "invalid_grant", "Username and password did not authenticate.") describe "when `grantUserToken` calls back with an error", -> beforeEach -> @error = new Error("Bad things happened, internally.") @grantUserToken.yields(@error) it "should call `next` with that error", -> @doIt() @tokenNext.should.have.been.calledWithExactly(@error) describe "when `validateClient` calls back with `false`", -> beforeEach -> @validateClient.yields(null, false) it "should send a 401 response with error_type=invalid_client and a WWW-Authenticate " + "header", -> @doIt() @res.header.should.have.been.calledWith( "WWW-Authenticate", 'Basic realm="Client ID and secret did not validate."' ) @res.should.be.an.oauthError("Unauthorized", "invalid_client", "Client ID and secret did not validate.") it "should not call the `grantUserToken` hook", -> @doIt() @grantUserToken.should.not.have.been.called describe "when `validateClient` calls back with an error", -> beforeEach -> @error = new Error("Bad things happened, internally.") @validateClient.yields(@error) it "should call `next` with that error", -> @doIt() @tokenNext.should.have.been.calledWithExactly(@error) it "should not call the `grantUserToken` hook", -> @doIt() @grantUserToken.should.not.have.been.called describe "that has no password field", -> beforeEach -> @req.body.password = null it "should send a 400 response with error_type=invalid_request", -> @doIt() @res.should.be.an.oauthError("BadRequest", "invalid_request", "Must specify password field.") it "should not call the `validateClient` or `grantUserToken` hooks", -> @doIt() @validateClient.should.not.have.been.called @grantUserToken.should.not.have.been.called describe "that has no username field", -> beforeEach -> @req.body.username = null it "should send a 400 response with error_type=invalid_request", -> @doIt() @res.should.be.an.oauthError("BadRequest", "invalid_request", "Must specify username field.") it "should not call the `validateClient` or `grantUserToken` hooks", -> @doIt() @validateClient.should.not.have.been.called @grantUserToken.should.not.have.been.called describe "without an authorization header", -> it "should send a 400 response with error_type=invalid_request", -> @doIt() @res.should.be.an.oauthError("BadRequest", "invalid_request", "Must include a basic access authentication header.") it "should not call the `validateClient` or `grantUserToken` hooks", -> @doIt() @validateClient.should.not.have.been.called @grantUserToken.should.not.have.been.called describe "with an authorization header that does not contain basic access credentials", -> beforeEach -> @req.authorization = scheme: "Bearer" credentials: "asdf" it "should send a 400 response with error_type=invalid_request", -> @doIt() @res.should.be.an.oauthError("BadRequest", "invalid_request", "Must include a basic access authentication header.") it "should not call the `validateClient` or `grantUserToken` hooks", -> @doIt() @validateClient.should.not.have.been.called @grantUserToken.should.not.have.been.called describe "that has grant_type=authorization_code", -> beforeEach -> @req.body.grant_type = "authorization_code" it "should send a 400 response with error_type=unsupported_grant_type", -> @doIt() @res.should.be.an.oauthError("BadRequest", "unsupported_grant_type", "Only grant_type=password is supported.") it "should not call the `validateClient` or `grantUserToken` hooks", -> @doIt() @validateClient.should.not.have.been.called @grantUserToken.should.not.have.been.called describe "that has no grant_type value", -> it "should send a 400 response with error_type=invalid_request", -> @doIt() @res.should.be.an.oauthError("BadRequest", "invalid_request", "Must specify grant_type field.") it "should not call the `validateClient` or `grantUserToken` hooks", -> @doIt() @validateClient.should.not.have.been.called @grantUserToken.should.not.have.been.called describe "without a body", -> beforeEach -> @req.body = null it "should send a 400 response with error_type=invalid_request", -> @doIt() @res.should.be.an.oauthError("BadRequest", "invalid_request", "Must supply a body.") it "should not call the `validateClient` or `grantUserToken` hooks", -> @doIt() @validateClient.should.not.have.been.called @grantUserToken.should.not.have.been.called describe "without a body that has been parsed into an object", -> beforeEach -> @req.body = "Left as a string or buffer or something" it "should send a 400 response with error_type=invalid_request", -> @doIt() @res.should.be.an.oauthError("BadRequest", "invalid_request", "Must supply a body.") it "should not call the `validateClient` or `grantUserToken` hooks", -> @doIt() @validateClient.should.not.have.been.called @grantUserToken.should.not.have.been.called describe "For other requests", -> beforeEach -> @req.path = => "/other-resource" @res.nextSpy = @pluginNext describe "with an authorization header that contains a valid bearer token", -> beforeEach -> @token = "TOKEN123" @req.authorization = { scheme: "Bearer", credentials: @token } it "should pause the request and authenticate the token", -> @doIt() @req.pause.should.have.been.called @authenticateToken.should.have.been.calledWith(@token, @req) describe "when the `authenticateToken` calls back with `true`", -> beforeEach -> @authenticateToken.yields(null, true) it "should resume the request and call `next`", -> @doIt() @req.resume.should.have.been.called @pluginNext.should.have.been.calledWithExactly() describe "when the `authenticateToken` calls back with `false`", -> beforeEach -> @authenticateToken.yields(null, false) it "should resume the request and send a 401 response, along with WWW-Authenticate and Link headers", -> @doIt() @req.resume.should.have.been.called @res.should.be.unauthorized( "Bearer token invalid. Follow the oauth2-token link to get a valid one!" ) describe "when the `authenticateToken` calls back with a 401 error", -> beforeEach -> @errorMessage = "The authentication failed for some reason." @authenticateToken.yields(new restify.UnauthorizedError(@errorMessage)) it "should resume the request and send the error, along with WWW-Authenticate and Link headers", -> @doIt() @req.resume.should.have.been.called @res.should.be.unauthorized(@errorMessage) describe "when the `authenticateToken` calls back with a non-401 error", -> beforeEach -> @error = new restify.ForbiddenError("The authentication succeeded but this resource is forbidden.") @authenticateToken.yields(@error) it "should resume the request and send the error, but no headers", -> @doIt() @req.resume.should.have.been.called @pluginNext.should.have.been.calledWith(@error) @res.header.should.not.have.been.called describe "without an authorization header", -> beforeEach -> @req.authorization = {} it "should remove `req.username`, and simply call `next`", -> @doIt() should.not.exist(@req.username) @pluginNext.should.have.been.calledWithExactly() describe "with an authorization header that does not contain a bearer token", -> beforeEach -> @req.authorization = scheme: "basic" credentials: "asdf" basic: { username: "aaa", password: "bbb" } it "should send a 400 response with WWW-Authenticate and Link headers", -> @doIt() @res.should.be.bad("Bearer token required. Follow the oauth2-token link to get one!") describe "with an authorization header that contains an empty bearer token", -> beforeEach -> @req.authorization = scheme: "Bearer" credentials: "" it "should send a 400 response with WWW-Authenticate and Link headers", -> @doIt() @res.should.be.bad("Bearer token required. Follow the oauth2-token link to get one!") describe "`res.sendUnauthenticated`", -> beforeEach -> @req.path = => "/other-resource" @res.nextSpy = @pluginNext @doIt() describe "with no arguments", -> beforeEach -> @res.sendUnauthenticated() it "should send a 401 response with WWW-Authenticate (but with no error code) and Link headers, plus the " + "default message", -> @res.should.be.unauthorized( "Authentication via bearer token required. Follow the oauth2-token link to get one!" { noWwwAuthenticateErrors: true, send: true } ) describe "with a message passed", -> message = "You really should go get a bearer token" beforeEach -> @res.sendUnauthenticated(message) it "should send a 401 response with WWW-Authenticate (but with no error code) and Link headers, plus the " + "specified message", -> @res.should.be.unauthorized(message, { noWwwAuthenticateErrors: true, send: true }) describe "`res.sendUnauthorized`", -> beforeEach -> @req.path = => "/other-resource" @res.nextSpy = @pluginNext @doIt() describe "with no arguments", -> beforeEach -> @res.sendUnauthorized() it "should send a 403 response with Link headers, plus the default message", -> @res.should.be.unauthenticated( "Insufficient authorization. Follow the oauth2-token link to get a token with more authorization!" ) describe "with a message passed", -> message = "You really should go get a bearer token with more scopes" beforeEach -> @res.sendUnauthorized(message) it "should send a 403 response with WWW-Authenticate (but with no error code) and Link headers, plus the " + "specified message", -> @res.should.be.unauthenticated(message)
212625
"use strict" require("chai").use(require("sinon-chai")) sinon = require("sinon") should = require("chai").should() Assertion = require("chai").Assertion restify = require("restify") restifyOAuth2 = require("..") tokenEndpoint = "/token-uri" wwwAuthenticateRealm = "Realm string" tokenExpirationTime = 12345 Assertion.addMethod("unauthorized", (message, options) -> expectedLink = '<' + tokenEndpoint + '>; rel="oauth2-token"; grant-types="password"; token-types="bearer"' expectedWwwAuthenticate = 'Bearer realm="' + wwwAuthenticateRealm + '"' if not options?.noWwwAuthenticateErrors expectedWwwAuthenticate += ', error="invalid_token", error_description="' + message + '"' spyToTest = if options?.send then @_obj.send else @_obj.nextSpy @_obj.header.should.have.been.calledWith("WWW-Authenticate", expectedWwwAuthenticate) @_obj.header.should.have.been.calledWith("Link", expectedLink) spyToTest.should.have.been.calledOnce spyToTest.should.have.been.calledWith(sinon.match.instanceOf(restify.UnauthorizedError)) spyToTest.should.have.been.calledWith(sinon.match.has("message", sinon.match(message))) ) Assertion.addMethod("unauthenticated", (message) -> expectedLink = '<' + tokenEndpoint + '>; rel="oauth2-token"; grant-types="password"; token-types="bearer"' @_obj.header.should.have.been.calledWith("Link", expectedLink) @_obj.send.should.have.been.calledOnce @_obj.send.should.have.been.calledWith(sinon.match.instanceOf(restify.ForbiddenError)) @_obj.send.should.have.been.calledWith(sinon.match.has("message", sinon.match(message))) ) Assertion.addMethod("bad", (message) -> expectedLink = '<' + tokenEndpoint + '>; rel="oauth2-token"; grant-types="password"; token-types="bearer"' expectedWwwAuthenticate = 'Bearer realm="' + wwwAuthenticateRealm + '", error="invalid_request", ' + 'error_description="' + message + '"' @_obj.header.should.have.been.calledWith("WWW-Authenticate", expectedWwwAuthenticate) @_obj.header.should.have.been.calledWith("Link", expectedLink) @_obj.nextSpy.should.have.been.calledOnce @_obj.nextSpy.should.have.been.calledWith(sinon.match.instanceOf(restify.BadRequestError)) @_obj.nextSpy.should.have.been.calledWith(sinon.match.has("message", sinon.match(message))) ) Assertion.addMethod("oauthError", (errorClass, errorType, errorDescription) -> desiredBody = { error: errorType, error_description: errorDescription } @_obj.nextSpy.should.have.been.calledOnce @_obj.nextSpy.should.have.been.calledWith(sinon.match.instanceOf(restify[errorClass + "Error"])) @_obj.nextSpy.should.have.been.calledWith(sinon.match.has("message", errorDescription)) @_obj.nextSpy.should.have.been.calledWith(sinon.match.has("body", desiredBody)) ) beforeEach -> @req = { pause: sinon.spy(), resume: sinon.spy(), username: "anonymous", authorization: {} } @res = { header: sinon.spy(), send: sinon.spy() } @tokenNext = sinon.spy() @pluginNext = sinon.spy() @server = post: sinon.spy((path, handler) => @postToTokenEndpoint = => handler(@req, @res, @tokenNext)) use: (plugin) => plugin(@req, @res, @pluginNext) @authenticateToken = sinon.stub() @validateClient = sinon.stub() @grantUserToken = sinon.stub() @grantScopes = sinon.stub() options = { tokenEndpoint wwwAuthenticateRealm tokenExpirationTime hooks: { @authenticateToken @validateClient @grantUserToken } } optionsWithScope = { tokenEndpoint wwwAuthenticateRealm tokenExpirationTime hooks: { @authenticateToken @validateClient @grantUserToken @grantScopes } } @doIt = => restifyOAuth2.ropc(@server, options) @doItWithScopes = => restifyOAuth2.ropc(@server, optionsWithScope) describe "Resource Owner Password Credentials flow", -> it "should set up the token endpoint", -> @doIt() @server.post.should.have.been.calledWith(tokenEndpoint) describe "For POST requests to the token endpoint", -> beforeEach -> @req.method = "POST" @req.path = => tokenEndpoint @res.nextSpy = @tokenNext baseDoIt = @doIt @doIt = => baseDoIt() @postToTokenEndpoint() describe "with a body", -> beforeEach -> @req.body = {} describe "that has grant_type=password", -> beforeEach -> @req.body.grant_type = "password" describe "with a basic access authentication header", -> beforeEach -> [@clientId, @clientSecret] = ["clientId123", "clientSecret456"] @req.authorization = scheme: "Basic" basic: { username: @clientId, password: @clientSecret } describe "and has a username field", -> beforeEach -> @username = "username123" @req.body.username = @username describe "and a password field", -> beforeEach -> @password = "<PASSWORD>" @req.body.password = @<PASSWORD> it "should validate the client, with client ID/secret from the basic authentication", -> @doIt() @validateClient.should.have.been.calledWith({ @clientId, @clientSecret }, @req) describe "when `validateClient` calls back with `true`", -> beforeEach -> @validateClient.yields(null, true) it "should use the username and password body fields to grant a token", -> @doIt() @grantUserToken.should.have.been.calledWith( { @clientId, @clientSecret, @username, @password }, @req ) describe "when `grantUserToken` calls back with a token", -> beforeEach -> @token = "<KEY> <PASSWORD>" @grantUserToken.yields(null, @token) describe "and a `grantScopes` hook is defined", -> beforeEach -> baseDoIt = @doItWithScopes @doIt = => baseDoIt() @postToTokenEndpoint() @requestedScopes = ["one", "two"] @req.body.scope = @requestedScopes.join(" ") it "should use credentials and requested scopes to grant scopes", -> @doIt() @grantScopes.should.have.been.calledWith( { @clientId, @clientSecret, @username, @password, @token }, @requestedScopes ) describe "when `grantScopes` calls back with an array of granted scopes", -> beforeEach -> @grantedScopes = ["three"] @grantScopes.yields(null, @grantedScopes) it "should send a response with access_token, token_type, scope, and " + "expires_in set, where scope is limited to the granted scopes", -> @doIt() @res.send.should.have.been.calledWith( access_token: @token, token_type: "Bearer" expires_in: tokenExpirationTime, scope: @grantedScopes.join(" ") ) it "should call `next`", -> @doIt() @tokenNext.should.have.been.calledWithExactly() describe "when `grantScopes` calls back with `true`", -> beforeEach -> @grantScopes.yields(null, true) it "should send a response with access_token, token_type, scope, and " + "expires_in set, where scope is the same as the requested scopes", -> @doIt() @res.send.should.have.been.calledWith( access_token: @token, token_type: "Bearer" expires_in: tokenExpirationTime, scope: @requestedScopes.join(" ") ) it "should call `next`", -> @doIt() @tokenNext.should.have.been.calledWithExactly() describe "when `grantScopes` calls back with `false`", -> beforeEach -> @grantScopes.yields(null, false) it "should send a 400 response with error_type=invalid_scope", -> @doIt() message = "The requested scopes are invalid, unknown, or exceed the " + "set of scopes appropriate for these credentials." @res.should.be.an.oauthError("BadRequest", "invalid_scope", message) describe "when `grantScopes` calls back with an error", -> beforeEach -> @error = new Error("Bad things happened, internally.") @grantScopes.yields(@error) it "should call `next` with that error", -> @doIt() @tokenNext.should.have.been.calledWithExactly(@error) describe "and a `grantScopes` hook is not defined", -> beforeEach -> @grantScopes = undefined it "should send a response with access_token, token_type, and expires_in " + "set", -> @doIt() @res.send.should.have.been.calledWith( access_token: @token, token_type: "Bearer" expires_in: tokenExpirationTime ) it "should call `next`", -> @doIt() @tokenNext.should.have.been.calledWithExactly() describe "when `grantUserToken` calls back with `false`", -> beforeEach -> @grantUserToken.yields(null, false) it "should send a 401 response with error_type=invalid_grant", -> @doIt() @res.should.be.an.oauthError("Unauthorized", "invalid_grant", "Username and password did not authenticate.") describe "when `grantUserToken` calls back with `null`", -> beforeEach -> @grantUserToken.yields(null, null) it "should send a 401 response with error_type=invalid_grant", -> @doIt() @res.should.be.an.oauthError("Unauthorized", "invalid_grant", "Username and password did not authenticate.") describe "when `grantUserToken` calls back with an error", -> beforeEach -> @error = new Error("Bad things happened, internally.") @grantUserToken.yields(@error) it "should call `next` with that error", -> @doIt() @tokenNext.should.have.been.calledWithExactly(@error) describe "when `validateClient` calls back with `false`", -> beforeEach -> @validateClient.yields(null, false) it "should send a 401 response with error_type=invalid_client and a WWW-Authenticate " + "header", -> @doIt() @res.header.should.have.been.calledWith( "WWW-Authenticate", 'Basic realm="Client ID and secret did not validate."' ) @res.should.be.an.oauthError("Unauthorized", "invalid_client", "Client ID and secret did not validate.") it "should not call the `grantUserToken` hook", -> @doIt() @grantUserToken.should.not.have.been.called describe "when `validateClient` calls back with an error", -> beforeEach -> @error = new Error("Bad things happened, internally.") @validateClient.yields(@error) it "should call `next` with that error", -> @doIt() @tokenNext.should.have.been.calledWithExactly(@error) it "should not call the `grantUserToken` hook", -> @doIt() @grantUserToken.should.not.have.been.called describe "that has no password field", -> beforeEach -> @req.body.password = <PASSWORD> it "should send a 400 response with error_type=invalid_request", -> @doIt() @res.should.be.an.oauthError("BadRequest", "invalid_request", "Must specify password field.") it "should not call the `validateClient` or `grantUserToken` hooks", -> @doIt() @validateClient.should.not.have.been.called @grantUserToken.should.not.have.been.called describe "that has no username field", -> beforeEach -> @req.body.username = null it "should send a 400 response with error_type=invalid_request", -> @doIt() @res.should.be.an.oauthError("BadRequest", "invalid_request", "Must specify username field.") it "should not call the `validateClient` or `grantUserToken` hooks", -> @doIt() @validateClient.should.not.have.been.called @grantUserToken.should.not.have.been.called describe "without an authorization header", -> it "should send a 400 response with error_type=invalid_request", -> @doIt() @res.should.be.an.oauthError("BadRequest", "invalid_request", "Must include a basic access authentication header.") it "should not call the `validateClient` or `grantUserToken` hooks", -> @doIt() @validateClient.should.not.have.been.called @grantUserToken.should.not.have.been.called describe "with an authorization header that does not contain basic access credentials", -> beforeEach -> @req.authorization = scheme: "Bearer" credentials: "asdf" it "should send a 400 response with error_type=invalid_request", -> @doIt() @res.should.be.an.oauthError("BadRequest", "invalid_request", "Must include a basic access authentication header.") it "should not call the `validateClient` or `grantUserToken` hooks", -> @doIt() @validateClient.should.not.have.been.called @grantUserToken.should.not.have.been.called describe "that has grant_type=authorization_code", -> beforeEach -> @req.body.grant_type = "authorization_code" it "should send a 400 response with error_type=unsupported_grant_type", -> @doIt() @res.should.be.an.oauthError("BadRequest", "unsupported_grant_type", "Only grant_type=password is supported.") it "should not call the `validateClient` or `grantUserToken` hooks", -> @doIt() @validateClient.should.not.have.been.called @grantUserToken.should.not.have.been.called describe "that has no grant_type value", -> it "should send a 400 response with error_type=invalid_request", -> @doIt() @res.should.be.an.oauthError("BadRequest", "invalid_request", "Must specify grant_type field.") it "should not call the `validateClient` or `grantUserToken` hooks", -> @doIt() @validateClient.should.not.have.been.called @grantUserToken.should.not.have.been.called describe "without a body", -> beforeEach -> @req.body = null it "should send a 400 response with error_type=invalid_request", -> @doIt() @res.should.be.an.oauthError("BadRequest", "invalid_request", "Must supply a body.") it "should not call the `validateClient` or `grantUserToken` hooks", -> @doIt() @validateClient.should.not.have.been.called @grantUserToken.should.not.have.been.called describe "without a body that has been parsed into an object", -> beforeEach -> @req.body = "Left as a string or buffer or something" it "should send a 400 response with error_type=invalid_request", -> @doIt() @res.should.be.an.oauthError("BadRequest", "invalid_request", "Must supply a body.") it "should not call the `validateClient` or `grantUserToken` hooks", -> @doIt() @validateClient.should.not.have.been.called @grantUserToken.should.not.have.been.called describe "For other requests", -> beforeEach -> @req.path = => "/other-resource" @res.nextSpy = @pluginNext describe "with an authorization header that contains a valid bearer token", -> beforeEach -> @token = "<KEY> <PASSWORD>" @req.authorization = { scheme: "Bearer", credentials: @token } it "should pause the request and authenticate the token", -> @doIt() @req.pause.should.have.been.called @authenticateToken.should.have.been.calledWith(@token, @req) describe "when the `authenticateToken` calls back with `true`", -> beforeEach -> @authenticateToken.yields(null, true) it "should resume the request and call `next`", -> @doIt() @req.resume.should.have.been.called @pluginNext.should.have.been.calledWithExactly() describe "when the `authenticateToken` calls back with `false`", -> beforeEach -> @authenticateToken.yields(null, false) it "should resume the request and send a 401 response, along with WWW-Authenticate and Link headers", -> @doIt() @req.resume.should.have.been.called @res.should.be.unauthorized( "Bearer token invalid. Follow the oauth2-token link to get a valid one!" ) describe "when the `authenticateToken` calls back with a 401 error", -> beforeEach -> @errorMessage = "The authentication failed for some reason." @authenticateToken.yields(new restify.UnauthorizedError(@errorMessage)) it "should resume the request and send the error, along with WWW-Authenticate and Link headers", -> @doIt() @req.resume.should.have.been.called @res.should.be.unauthorized(@errorMessage) describe "when the `authenticateToken` calls back with a non-401 error", -> beforeEach -> @error = new restify.ForbiddenError("The authentication succeeded but this resource is forbidden.") @authenticateToken.yields(@error) it "should resume the request and send the error, but no headers", -> @doIt() @req.resume.should.have.been.called @pluginNext.should.have.been.calledWith(@error) @res.header.should.not.have.been.called describe "without an authorization header", -> beforeEach -> @req.authorization = {} it "should remove `req.username`, and simply call `next`", -> @doIt() should.not.exist(@req.username) @pluginNext.should.have.been.calledWithExactly() describe "with an authorization header that does not contain a bearer token", -> beforeEach -> @req.authorization = scheme: "basic" credentials: "asdf" basic: { username: "aaa", password: "<PASSWORD>" } it "should send a 400 response with WWW-Authenticate and Link headers", -> @doIt() @res.should.be.bad("Bearer token required. Follow the oauth2-token link to get one!") describe "with an authorization header that contains an empty bearer token", -> beforeEach -> @req.authorization = scheme: "Bearer" credentials: "" it "should send a 400 response with WWW-Authenticate and Link headers", -> @doIt() @res.should.be.bad("Bearer token required. Follow the oauth2-token link to get one!") describe "`res.sendUnauthenticated`", -> beforeEach -> @req.path = => "/other-resource" @res.nextSpy = @pluginNext @doIt() describe "with no arguments", -> beforeEach -> @res.sendUnauthenticated() it "should send a 401 response with WWW-Authenticate (but with no error code) and Link headers, plus the " + "default message", -> @res.should.be.unauthorized( "Authentication via bearer token required. Follow the oauth2-token link to get one!" { noWwwAuthenticateErrors: true, send: true } ) describe "with a message passed", -> message = "You really should go get a bearer token" beforeEach -> @res.sendUnauthenticated(message) it "should send a 401 response with WWW-Authenticate (but with no error code) and Link headers, plus the " + "specified message", -> @res.should.be.unauthorized(message, { noWwwAuthenticateErrors: true, send: true }) describe "`res.sendUnauthorized`", -> beforeEach -> @req.path = => "/other-resource" @res.nextSpy = @pluginNext @doIt() describe "with no arguments", -> beforeEach -> @res.sendUnauthorized() it "should send a 403 response with Link headers, plus the default message", -> @res.should.be.unauthenticated( "Insufficient authorization. Follow the oauth2-token link to get a token with more authorization!" ) describe "with a message passed", -> message = "You really should go get a bearer token with more scopes" beforeEach -> @res.sendUnauthorized(message) it "should send a 403 response with WWW-Authenticate (but with no error code) and Link headers, plus the " + "specified message", -> @res.should.be.unauthenticated(message)
true
"use strict" require("chai").use(require("sinon-chai")) sinon = require("sinon") should = require("chai").should() Assertion = require("chai").Assertion restify = require("restify") restifyOAuth2 = require("..") tokenEndpoint = "/token-uri" wwwAuthenticateRealm = "Realm string" tokenExpirationTime = 12345 Assertion.addMethod("unauthorized", (message, options) -> expectedLink = '<' + tokenEndpoint + '>; rel="oauth2-token"; grant-types="password"; token-types="bearer"' expectedWwwAuthenticate = 'Bearer realm="' + wwwAuthenticateRealm + '"' if not options?.noWwwAuthenticateErrors expectedWwwAuthenticate += ', error="invalid_token", error_description="' + message + '"' spyToTest = if options?.send then @_obj.send else @_obj.nextSpy @_obj.header.should.have.been.calledWith("WWW-Authenticate", expectedWwwAuthenticate) @_obj.header.should.have.been.calledWith("Link", expectedLink) spyToTest.should.have.been.calledOnce spyToTest.should.have.been.calledWith(sinon.match.instanceOf(restify.UnauthorizedError)) spyToTest.should.have.been.calledWith(sinon.match.has("message", sinon.match(message))) ) Assertion.addMethod("unauthenticated", (message) -> expectedLink = '<' + tokenEndpoint + '>; rel="oauth2-token"; grant-types="password"; token-types="bearer"' @_obj.header.should.have.been.calledWith("Link", expectedLink) @_obj.send.should.have.been.calledOnce @_obj.send.should.have.been.calledWith(sinon.match.instanceOf(restify.ForbiddenError)) @_obj.send.should.have.been.calledWith(sinon.match.has("message", sinon.match(message))) ) Assertion.addMethod("bad", (message) -> expectedLink = '<' + tokenEndpoint + '>; rel="oauth2-token"; grant-types="password"; token-types="bearer"' expectedWwwAuthenticate = 'Bearer realm="' + wwwAuthenticateRealm + '", error="invalid_request", ' + 'error_description="' + message + '"' @_obj.header.should.have.been.calledWith("WWW-Authenticate", expectedWwwAuthenticate) @_obj.header.should.have.been.calledWith("Link", expectedLink) @_obj.nextSpy.should.have.been.calledOnce @_obj.nextSpy.should.have.been.calledWith(sinon.match.instanceOf(restify.BadRequestError)) @_obj.nextSpy.should.have.been.calledWith(sinon.match.has("message", sinon.match(message))) ) Assertion.addMethod("oauthError", (errorClass, errorType, errorDescription) -> desiredBody = { error: errorType, error_description: errorDescription } @_obj.nextSpy.should.have.been.calledOnce @_obj.nextSpy.should.have.been.calledWith(sinon.match.instanceOf(restify[errorClass + "Error"])) @_obj.nextSpy.should.have.been.calledWith(sinon.match.has("message", errorDescription)) @_obj.nextSpy.should.have.been.calledWith(sinon.match.has("body", desiredBody)) ) beforeEach -> @req = { pause: sinon.spy(), resume: sinon.spy(), username: "anonymous", authorization: {} } @res = { header: sinon.spy(), send: sinon.spy() } @tokenNext = sinon.spy() @pluginNext = sinon.spy() @server = post: sinon.spy((path, handler) => @postToTokenEndpoint = => handler(@req, @res, @tokenNext)) use: (plugin) => plugin(@req, @res, @pluginNext) @authenticateToken = sinon.stub() @validateClient = sinon.stub() @grantUserToken = sinon.stub() @grantScopes = sinon.stub() options = { tokenEndpoint wwwAuthenticateRealm tokenExpirationTime hooks: { @authenticateToken @validateClient @grantUserToken } } optionsWithScope = { tokenEndpoint wwwAuthenticateRealm tokenExpirationTime hooks: { @authenticateToken @validateClient @grantUserToken @grantScopes } } @doIt = => restifyOAuth2.ropc(@server, options) @doItWithScopes = => restifyOAuth2.ropc(@server, optionsWithScope) describe "Resource Owner Password Credentials flow", -> it "should set up the token endpoint", -> @doIt() @server.post.should.have.been.calledWith(tokenEndpoint) describe "For POST requests to the token endpoint", -> beforeEach -> @req.method = "POST" @req.path = => tokenEndpoint @res.nextSpy = @tokenNext baseDoIt = @doIt @doIt = => baseDoIt() @postToTokenEndpoint() describe "with a body", -> beforeEach -> @req.body = {} describe "that has grant_type=password", -> beforeEach -> @req.body.grant_type = "password" describe "with a basic access authentication header", -> beforeEach -> [@clientId, @clientSecret] = ["clientId123", "clientSecret456"] @req.authorization = scheme: "Basic" basic: { username: @clientId, password: @clientSecret } describe "and has a username field", -> beforeEach -> @username = "username123" @req.body.username = @username describe "and a password field", -> beforeEach -> @password = "PI:PASSWORD:<PASSWORD>END_PI" @req.body.password = @PI:PASSWORD:<PASSWORD>END_PI it "should validate the client, with client ID/secret from the basic authentication", -> @doIt() @validateClient.should.have.been.calledWith({ @clientId, @clientSecret }, @req) describe "when `validateClient` calls back with `true`", -> beforeEach -> @validateClient.yields(null, true) it "should use the username and password body fields to grant a token", -> @doIt() @grantUserToken.should.have.been.calledWith( { @clientId, @clientSecret, @username, @password }, @req ) describe "when `grantUserToken` calls back with a token", -> beforeEach -> @token = "PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI" @grantUserToken.yields(null, @token) describe "and a `grantScopes` hook is defined", -> beforeEach -> baseDoIt = @doItWithScopes @doIt = => baseDoIt() @postToTokenEndpoint() @requestedScopes = ["one", "two"] @req.body.scope = @requestedScopes.join(" ") it "should use credentials and requested scopes to grant scopes", -> @doIt() @grantScopes.should.have.been.calledWith( { @clientId, @clientSecret, @username, @password, @token }, @requestedScopes ) describe "when `grantScopes` calls back with an array of granted scopes", -> beforeEach -> @grantedScopes = ["three"] @grantScopes.yields(null, @grantedScopes) it "should send a response with access_token, token_type, scope, and " + "expires_in set, where scope is limited to the granted scopes", -> @doIt() @res.send.should.have.been.calledWith( access_token: @token, token_type: "Bearer" expires_in: tokenExpirationTime, scope: @grantedScopes.join(" ") ) it "should call `next`", -> @doIt() @tokenNext.should.have.been.calledWithExactly() describe "when `grantScopes` calls back with `true`", -> beforeEach -> @grantScopes.yields(null, true) it "should send a response with access_token, token_type, scope, and " + "expires_in set, where scope is the same as the requested scopes", -> @doIt() @res.send.should.have.been.calledWith( access_token: @token, token_type: "Bearer" expires_in: tokenExpirationTime, scope: @requestedScopes.join(" ") ) it "should call `next`", -> @doIt() @tokenNext.should.have.been.calledWithExactly() describe "when `grantScopes` calls back with `false`", -> beforeEach -> @grantScopes.yields(null, false) it "should send a 400 response with error_type=invalid_scope", -> @doIt() message = "The requested scopes are invalid, unknown, or exceed the " + "set of scopes appropriate for these credentials." @res.should.be.an.oauthError("BadRequest", "invalid_scope", message) describe "when `grantScopes` calls back with an error", -> beforeEach -> @error = new Error("Bad things happened, internally.") @grantScopes.yields(@error) it "should call `next` with that error", -> @doIt() @tokenNext.should.have.been.calledWithExactly(@error) describe "and a `grantScopes` hook is not defined", -> beforeEach -> @grantScopes = undefined it "should send a response with access_token, token_type, and expires_in " + "set", -> @doIt() @res.send.should.have.been.calledWith( access_token: @token, token_type: "Bearer" expires_in: tokenExpirationTime ) it "should call `next`", -> @doIt() @tokenNext.should.have.been.calledWithExactly() describe "when `grantUserToken` calls back with `false`", -> beforeEach -> @grantUserToken.yields(null, false) it "should send a 401 response with error_type=invalid_grant", -> @doIt() @res.should.be.an.oauthError("Unauthorized", "invalid_grant", "Username and password did not authenticate.") describe "when `grantUserToken` calls back with `null`", -> beforeEach -> @grantUserToken.yields(null, null) it "should send a 401 response with error_type=invalid_grant", -> @doIt() @res.should.be.an.oauthError("Unauthorized", "invalid_grant", "Username and password did not authenticate.") describe "when `grantUserToken` calls back with an error", -> beforeEach -> @error = new Error("Bad things happened, internally.") @grantUserToken.yields(@error) it "should call `next` with that error", -> @doIt() @tokenNext.should.have.been.calledWithExactly(@error) describe "when `validateClient` calls back with `false`", -> beforeEach -> @validateClient.yields(null, false) it "should send a 401 response with error_type=invalid_client and a WWW-Authenticate " + "header", -> @doIt() @res.header.should.have.been.calledWith( "WWW-Authenticate", 'Basic realm="Client ID and secret did not validate."' ) @res.should.be.an.oauthError("Unauthorized", "invalid_client", "Client ID and secret did not validate.") it "should not call the `grantUserToken` hook", -> @doIt() @grantUserToken.should.not.have.been.called describe "when `validateClient` calls back with an error", -> beforeEach -> @error = new Error("Bad things happened, internally.") @validateClient.yields(@error) it "should call `next` with that error", -> @doIt() @tokenNext.should.have.been.calledWithExactly(@error) it "should not call the `grantUserToken` hook", -> @doIt() @grantUserToken.should.not.have.been.called describe "that has no password field", -> beforeEach -> @req.body.password = PI:PASSWORD:<PASSWORD>END_PI it "should send a 400 response with error_type=invalid_request", -> @doIt() @res.should.be.an.oauthError("BadRequest", "invalid_request", "Must specify password field.") it "should not call the `validateClient` or `grantUserToken` hooks", -> @doIt() @validateClient.should.not.have.been.called @grantUserToken.should.not.have.been.called describe "that has no username field", -> beforeEach -> @req.body.username = null it "should send a 400 response with error_type=invalid_request", -> @doIt() @res.should.be.an.oauthError("BadRequest", "invalid_request", "Must specify username field.") it "should not call the `validateClient` or `grantUserToken` hooks", -> @doIt() @validateClient.should.not.have.been.called @grantUserToken.should.not.have.been.called describe "without an authorization header", -> it "should send a 400 response with error_type=invalid_request", -> @doIt() @res.should.be.an.oauthError("BadRequest", "invalid_request", "Must include a basic access authentication header.") it "should not call the `validateClient` or `grantUserToken` hooks", -> @doIt() @validateClient.should.not.have.been.called @grantUserToken.should.not.have.been.called describe "with an authorization header that does not contain basic access credentials", -> beforeEach -> @req.authorization = scheme: "Bearer" credentials: "asdf" it "should send a 400 response with error_type=invalid_request", -> @doIt() @res.should.be.an.oauthError("BadRequest", "invalid_request", "Must include a basic access authentication header.") it "should not call the `validateClient` or `grantUserToken` hooks", -> @doIt() @validateClient.should.not.have.been.called @grantUserToken.should.not.have.been.called describe "that has grant_type=authorization_code", -> beforeEach -> @req.body.grant_type = "authorization_code" it "should send a 400 response with error_type=unsupported_grant_type", -> @doIt() @res.should.be.an.oauthError("BadRequest", "unsupported_grant_type", "Only grant_type=password is supported.") it "should not call the `validateClient` or `grantUserToken` hooks", -> @doIt() @validateClient.should.not.have.been.called @grantUserToken.should.not.have.been.called describe "that has no grant_type value", -> it "should send a 400 response with error_type=invalid_request", -> @doIt() @res.should.be.an.oauthError("BadRequest", "invalid_request", "Must specify grant_type field.") it "should not call the `validateClient` or `grantUserToken` hooks", -> @doIt() @validateClient.should.not.have.been.called @grantUserToken.should.not.have.been.called describe "without a body", -> beforeEach -> @req.body = null it "should send a 400 response with error_type=invalid_request", -> @doIt() @res.should.be.an.oauthError("BadRequest", "invalid_request", "Must supply a body.") it "should not call the `validateClient` or `grantUserToken` hooks", -> @doIt() @validateClient.should.not.have.been.called @grantUserToken.should.not.have.been.called describe "without a body that has been parsed into an object", -> beforeEach -> @req.body = "Left as a string or buffer or something" it "should send a 400 response with error_type=invalid_request", -> @doIt() @res.should.be.an.oauthError("BadRequest", "invalid_request", "Must supply a body.") it "should not call the `validateClient` or `grantUserToken` hooks", -> @doIt() @validateClient.should.not.have.been.called @grantUserToken.should.not.have.been.called describe "For other requests", -> beforeEach -> @req.path = => "/other-resource" @res.nextSpy = @pluginNext describe "with an authorization header that contains a valid bearer token", -> beforeEach -> @token = "PI:KEY:<KEY>END_PI PI:PASSWORD:<PASSWORD>END_PI" @req.authorization = { scheme: "Bearer", credentials: @token } it "should pause the request and authenticate the token", -> @doIt() @req.pause.should.have.been.called @authenticateToken.should.have.been.calledWith(@token, @req) describe "when the `authenticateToken` calls back with `true`", -> beforeEach -> @authenticateToken.yields(null, true) it "should resume the request and call `next`", -> @doIt() @req.resume.should.have.been.called @pluginNext.should.have.been.calledWithExactly() describe "when the `authenticateToken` calls back with `false`", -> beforeEach -> @authenticateToken.yields(null, false) it "should resume the request and send a 401 response, along with WWW-Authenticate and Link headers", -> @doIt() @req.resume.should.have.been.called @res.should.be.unauthorized( "Bearer token invalid. Follow the oauth2-token link to get a valid one!" ) describe "when the `authenticateToken` calls back with a 401 error", -> beforeEach -> @errorMessage = "The authentication failed for some reason." @authenticateToken.yields(new restify.UnauthorizedError(@errorMessage)) it "should resume the request and send the error, along with WWW-Authenticate and Link headers", -> @doIt() @req.resume.should.have.been.called @res.should.be.unauthorized(@errorMessage) describe "when the `authenticateToken` calls back with a non-401 error", -> beforeEach -> @error = new restify.ForbiddenError("The authentication succeeded but this resource is forbidden.") @authenticateToken.yields(@error) it "should resume the request and send the error, but no headers", -> @doIt() @req.resume.should.have.been.called @pluginNext.should.have.been.calledWith(@error) @res.header.should.not.have.been.called describe "without an authorization header", -> beforeEach -> @req.authorization = {} it "should remove `req.username`, and simply call `next`", -> @doIt() should.not.exist(@req.username) @pluginNext.should.have.been.calledWithExactly() describe "with an authorization header that does not contain a bearer token", -> beforeEach -> @req.authorization = scheme: "basic" credentials: "asdf" basic: { username: "aaa", password: "PI:PASSWORD:<PASSWORD>END_PI" } it "should send a 400 response with WWW-Authenticate and Link headers", -> @doIt() @res.should.be.bad("Bearer token required. Follow the oauth2-token link to get one!") describe "with an authorization header that contains an empty bearer token", -> beforeEach -> @req.authorization = scheme: "Bearer" credentials: "" it "should send a 400 response with WWW-Authenticate and Link headers", -> @doIt() @res.should.be.bad("Bearer token required. Follow the oauth2-token link to get one!") describe "`res.sendUnauthenticated`", -> beforeEach -> @req.path = => "/other-resource" @res.nextSpy = @pluginNext @doIt() describe "with no arguments", -> beforeEach -> @res.sendUnauthenticated() it "should send a 401 response with WWW-Authenticate (but with no error code) and Link headers, plus the " + "default message", -> @res.should.be.unauthorized( "Authentication via bearer token required. Follow the oauth2-token link to get one!" { noWwwAuthenticateErrors: true, send: true } ) describe "with a message passed", -> message = "You really should go get a bearer token" beforeEach -> @res.sendUnauthenticated(message) it "should send a 401 response with WWW-Authenticate (but with no error code) and Link headers, plus the " + "specified message", -> @res.should.be.unauthorized(message, { noWwwAuthenticateErrors: true, send: true }) describe "`res.sendUnauthorized`", -> beforeEach -> @req.path = => "/other-resource" @res.nextSpy = @pluginNext @doIt() describe "with no arguments", -> beforeEach -> @res.sendUnauthorized() it "should send a 403 response with Link headers, plus the default message", -> @res.should.be.unauthenticated( "Insufficient authorization. Follow the oauth2-token link to get a token with more authorization!" ) describe "with a message passed", -> message = "You really should go get a bearer token with more scopes" beforeEach -> @res.sendUnauthorized(message) it "should send a 403 response with WWW-Authenticate (but with no error code) and Link headers, plus the " + "specified message", -> @res.should.be.unauthenticated(message)
[ { "context": "ed\n catch\n key = if globals.os is 'mac' then '⌘ + C' else 'Ctrl + C'\n msg = \"Hit #{key} to copy!\"\n", "end": 373, "score": 0.7489832639694214, "start": 368, "tag": "KEY", "value": "⌘ + C" }, { "context": " key = if globals.os is 'mac' then '⌘ + C' else 'Ctr...
client/app/lib/util/copyToClipboard.coffee
ezgikaysi/koding
1
kd = require 'kd' notification = null module.exports = copyToClipboard = (el, showNotification = yes) -> notification?.destroy() kd.utils.selectText el msg = 'Copied to clipboard!' try copied = document.execCommand 'copy' couldntCopy = 'couldn\'t copy' throw couldntCopy unless copied catch key = if globals.os is 'mac' then '⌘ + C' else 'Ctrl + C' msg = "Hit #{key} to copy!" return unless showNotification notification = new kd.NotificationView { title: msg }
224399
kd = require 'kd' notification = null module.exports = copyToClipboard = (el, showNotification = yes) -> notification?.destroy() kd.utils.selectText el msg = 'Copied to clipboard!' try copied = document.execCommand 'copy' couldntCopy = 'couldn\'t copy' throw couldntCopy unless copied catch key = if globals.os is 'mac' then '<KEY>' else '<KEY>' msg = "Hit #{key} to copy!" return unless showNotification notification = new kd.NotificationView { title: msg }
true
kd = require 'kd' notification = null module.exports = copyToClipboard = (el, showNotification = yes) -> notification?.destroy() kd.utils.selectText el msg = 'Copied to clipboard!' try copied = document.execCommand 'copy' couldntCopy = 'couldn\'t copy' throw couldntCopy unless copied catch key = if globals.os is 'mac' then 'PI:KEY:<KEY>END_PI' else 'PI:KEY:<KEY>END_PI' msg = "Hit #{key} to copy!" return unless showNotification notification = new kd.NotificationView { title: msg }