<commit_before>import Future from 'fibers/future'
import Fiber from 'fibers'
import assign from 'object.assign'

const SYNC_COMMANDS = ['domain', '_events', '_maxListeners', 'setMaxListeners', 'emit',
    'addListener', 'on', 'once', 'removeListener', 'removeAllListeners', 'listeners',
    'getMaxListeners', 'listenerCount']

let commandIsRunning = false
let forcePromises = false

let isAsync = function () {
    if (!global.browser || !global.browser.options) {
        return false
    }

    return global.browser.options.sync === false
}

/**
 * helper method to execute a row of hooks with certain parameters
 * @param  {Function|Function[]} hooks  list of hooks
 * @param  {Object[]} args  list of parameter for hook functions
 * @return {Promise}  promise that gets resolved once all hooks finished running
 */
let executeHooksWithArgs = (hooks = [], args) => {
    /**
     * make sure hooks are an array of functions
     */
    if (typeof hooks === 'function') {
        hooks = [hooks]
    }

    /**
     * make sure args is an array since we are calling apply
     */
    if (!Array.isArray(args)) {
        args = [args]
    }

    hooks = hooks.map((hook) => new Promise((resolve) => {
        let _commandIsRunning = commandIsRunning

        /**
         * no need for fiber wrap in async mode
         */
        if (isAsync()) {
            commandIsRunning = true
            let result = resolve(hook.apply(null, args))
            commandIsRunning = _commandIsRunning
            return result
        }

        try {
            /**
             * after command hooks require additional Fiber environment
             */
            return Fiber(() => {
                commandIsRunning = true
                resolve(hook.apply(null, args))
                commandIsRunning = _commandIsRunning
            }).run()
        } catch (e) {
            console.error(e.stack)
        }

        resolve()
    }))

    return Promise.all(hooks)
}

/**
 * global function to wrap callbacks into Fiber context
 * @param  {Function} fn  function to wrap around
 * @return {Function}     wrapped around function
 */
global.wdioSync = function (fn, done) {
    return function (...args) {
        return Fiber(() => {
            const result = fn.apply(this, args)

            if (typeof done === 'function') {
                done(result)
            }
        }).run()
    }
}

/**
 * wraps a function into a Fiber ready context to enable sync execution and hooks
 * @param  {Function}   fn             function to be executed
 * @param  {String}     commandName    name of that function
 * @param  {Function[]} beforeCommand  method to be executed before calling the actual function
 * @param  {Function[]} afterCommand   method to be executed after calling the actual function
 * @return {Function}   actual wrapped function
 */
let wrapCommand = function (fn, commandName, beforeCommand, afterCommand) {
    if (isAsync()) {
        /**
         * async command wrap
         */
        return function (...commandArgs) {
            return fn.apply(this, commandArgs)
        }
    }

    /**
     * sync command wrap
     */
    return function (...commandArgs) {
        let future = new Future()
        let futureFailed = false

        if (forcePromises) {
            return fn.apply(this, commandArgs)
        }

        /**
         * don't execute [before/after]Command hook if a command was executed
         * in these hooks (otherwise we will get into an endless loop)
         */
        if (commandIsRunning) {
            let commandPromise = fn.apply(this, commandArgs)

            /**
             * try to execute with Fibers and fall back if can't
             */
            try {
                commandPromise.then(future.return.bind(future), future.throw.bind(future))
                return future.wait()
            } catch (e) {
                if (e.message === "Can't wait without a fiber") {
                    return commandPromise
                }
                throw e
            }
        }

        commandIsRunning = true
        let newInstance = this
        let commandResult, commandError
        new Promise((r) => r(executeHooksWithArgs(beforeCommand, [commandName, commandArgs])))
            .then(() => {
                /**
                 * actual function was already executed in desired catch block
                 */
                if (futureFailed) {
                    return
                }

                newInstance = fn.apply(this, commandArgs)
                return newInstance
            })
            .then(
                (result) => {
                    commandResult = result
                    return executeHooksWithArgs(afterCommand, [commandName, commandArgs, result])
                },
                (e) => {
                    commandError = e
                    return executeHooksWithArgs(afterCommand, [commandName, commandArgs, null, e])
                }
            )
            .then(() => {
                commandIsRunning = false

                if (commandError) {
                    return future.throw(commandError)
                }
                wrapCommands(newInstance, beforeCommand, afterCommand)
                return future.return(applyPrototype.call(newInstance, commandResult))
            })

        /**
         * try to execute with Fibers and fall back if can't
         */
        try {
            return future.wait()
        } catch (e) {
            if (e.message === "Can't wait without a fiber") {
                futureFailed = true
                return fn.apply(this, commandArgs)
            }
            throw e
        }
    }
}

/**
 * enhance result with instance prototype to enable command chaining
 * @param  {Object} result   command result
 * @return {Object}          command result with enhanced prototype
 */
let applyPrototype = function (result) {
    if (!result || typeof result !== 'object' || Array.isArray(result)) {
        return result
    }

    let prototype = {}
    let hasExtendedPrototype = false
    for (let commandName of Object.keys(Object.getPrototypeOf(this))) {
        if (result[commandName] || SYNC_COMMANDS.indexOf(commandName) > -1) {
            continue
        }

        this.lastResult = result
        prototype[commandName] = { value: this[commandName].bind(this) }
        hasExtendedPrototype = true
    }

    if (hasExtendedPrototype) {
        let newResult = Object.create(result, prototype)

        /**
         * since status is a command we need to rename the property
         */
        if (typeof result.status !== 'undefined') {
            result._status = result.status
            delete result.status
        }

        result = assign(newResult, result)
    }

    return result
}

/**
 * wraps all WebdriverIO commands
 * @param  {Object}     instance       WebdriverIO client instance (browser)
 * @param  {Function[]} beforeCommand  before command hook
 * @param  {Function[]} afterCommand   after command hook
 */
let wrapCommands = function (instance, beforeCommand, afterCommand) {
    Object.keys(Object.getPrototypeOf(instance)).forEach((commandName) => {
        if (SYNC_COMMANDS.indexOf(commandName) > -1) {
            return
        }

        let origFn = instance[commandName]
        instance[commandName] = wrapCommand.call(instance, origFn, commandName, beforeCommand, afterCommand)
    })

    /**
     * no need to overwrite addCommand in async mode
     */
    if (isAsync()) {
        return
    }

    /**
     * Adding a command within fiber context doesn't require a special routine
     * since everything runs sync. There is no need to promisify the command.
     */
    instance.addCommand = function (fnName, fn, forceOverwrite) {
        let commandGroup = instance
        let commandName = fnName
        let namespace

        if (typeof fn === 'string') {
            namespace = arguments[0]
            fnName = arguments[1]
            fn = arguments[2]
            forceOverwrite = arguments[3]

            switch (typeof commandGroup[namespace]) {
            case 'function':
                throw new Error(`Command namespace "${namespace}" is used internally, and can't be overwritten!`)
            case 'undefined':
                commandGroup[namespace] = {}
                break
            }

            commandName = `${namespace}.${fnName}`
            commandGroup = commandGroup[namespace]
        }

        if (commandGroup[fnName] && !forceOverwrite) {
            throw new Error(`Command ${fnName} is already defined!`)
        }

        /**
         * if method name is async the user specifies that he wants to
         * use bare promises to handle asynchronicity
         */
        if (fn.name === 'async') {
            commandGroup[fnName] = wrapCommand((...args) => {
                forcePromises = true
                let res = fn.apply(instance, args)
                forcePromises = false
                return res
            }, commandName, beforeCommand, afterCommand)
            return
        }

        /**
         * for all other cases we internally return a promise that is
         * finished once the Fiber wrapped custom function has finished
         * #functionalProgrammingWTF!
         */
        commandGroup[fnName] = wrapCommand((...args) => new Promise((r) => {
            wdioSync(fn, r).apply(instance, args)
        }), commandName, beforeCommand, afterCommand)
    }
}

/**
 * [runInFiberContext description]
 * @param  {[type]} testInterfaceFnNames  global command that runs specs
 * @param  {[type]} before               before hook hook
 * @param  {[type]} after                after hook hook
 * @param  {[type]} fnName               test interface command to wrap
 */
let runInFiberContext = function (testInterfaceFnNames, before, after, fnName) {
    let origFn = global[fnName]

    let runSpec = function (specTitle, specFn) {
        /**
         * user wants handle async command using promises, no need to wrap in fiber context
         */
        if (isAsync()) {
            return origFn.call(this, specTitle, specFn)
        }

        return origFn(specTitle, function (done) {
            Fiber(() => {
                specFn.call(this)
                done()
            }).run()
        })
    }

    let runHook = function (hookFn) {
        /**
         * user wants handle async command using promises, no need to wrap in fiber context
         */
        if (isAsync()) {
            return origFn(function (done) {
                executeHooksWithArgs(before).catch((e) => {
                    console.error(`Error in beforeHook: [${e}]`)
                }).then(() => {
                    return hookFn.call(this)
                }).then(() => {
                    return executeHooksWithArgs(after)
                    .catch((e) => {
                        console.error(`Error in afterHook: [${e}]`)
                    })
                }).then(() => done(), done)
            })
        }

        return origFn(function (done) {
            // Print errors encountered in beforeHook and afterHook to console, but
            // don't propagate them to avoid failing the test. However, errors in
            // framework hook functions should fail the test, so propagate those.
            executeHooksWithArgs(before)
                .catch((e) => {
                    console.error(`Error in beforeHook: [${e}]`)
                })
                .then(() => new Promise((resolve, reject) => {
                    return Fiber(() => {
                        try {
                            hookFn.call(this)
                        } catch (e) {
                            reject(e)
                        }
                        resolve()
                    }).run()
                }))
                .then(() => {
                    return executeHooksWithArgs(after)
                    .catch((e) => {
                        console.error(`Error in afterHook: [${e}]`)
                    })
                })
                .then(() => done(), done)
        })
    }

    global[fnName] = function (...specArguments) {
        /**
         * Variadic arguments: [title, fn], [title], [fn]
         */
        let specFn = typeof specArguments[0] === 'function' ? specArguments.shift()
            : (typeof specArguments[1] === 'function' ? specArguments.pop() : undefined)
        let specTitle = specArguments[0]

        if (testInterfaceFnNames.indexOf(fnName) > -1) {
            if (specFn) return runSpec(specTitle, specFn)

            /**
             * if specFn is undefined we are dealing with a pending function
             */
            return origFn(specTitle)
        }

        return runHook(specFn)
    }

    if (testInterfaceFnNames.indexOf(fnName) > -1) {
        global[fnName].skip = origFn.skip
        global[fnName].only = origFn.only
    }
}

export { wrapCommand, wrapCommands, runInFiberContext, executeHooksWithArgs }
<commit_msg>make sure instances of multibrowser variable get hooked up with fibers too<commit_after>import Future from 'fibers/future'
import Fiber from 'fibers'
import assign from 'object.assign'

const SYNC_COMMANDS = ['domain', '_events', '_maxListeners', 'setMaxListeners', 'emit',
    'addListener', 'on', 'once', 'removeListener', 'removeAllListeners', 'listeners',
    'getMaxListeners', 'listenerCount']

let commandIsRunning = false
let forcePromises = false

let isAsync = function () {
    if (!global.browser || !global.browser.options) {
        return false
    }

    return global.browser.options.sync === false
}

/**
 * helper method to execute a row of hooks with certain parameters
 * @param  {Function|Function[]} hooks  list of hooks
 * @param  {Object[]} args  list of parameter for hook functions
 * @return {Promise}  promise that gets resolved once all hooks finished running
 */
let executeHooksWithArgs = (hooks = [], args) => {
    /**
     * make sure hooks are an array of functions
     */
    if (typeof hooks === 'function') {
        hooks = [hooks]
    }

    /**
     * make sure args is an array since we are calling apply
     */
    if (!Array.isArray(args)) {
        args = [args]
    }

    hooks = hooks.map((hook) => new Promise((resolve) => {
        let _commandIsRunning = commandIsRunning

        /**
         * no need for fiber wrap in async mode
         */
        if (isAsync()) {
            commandIsRunning = true
            let result = resolve(hook.apply(null, args))
            commandIsRunning = _commandIsRunning
            return result
        }

        try {
            /**
             * after command hooks require additional Fiber environment
             */
            return Fiber(() => {
                commandIsRunning = true
                resolve(hook.apply(null, args))
                commandIsRunning = _commandIsRunning
            }).run()
        } catch (e) {
            console.error(e.stack)
        }

        resolve()
    }))

    return Promise.all(hooks)
}

/**
 * global function to wrap callbacks into Fiber context
 * @param  {Function} fn  function to wrap around
 * @return {Function}     wrapped around function
 */
global.wdioSync = function (fn, done) {
    return function (...args) {
        return Fiber(() => {
            const result = fn.apply(this, args)

            if (typeof done === 'function') {
                done(result)
            }
        }).run()
    }
}

/**
 * wraps a function into a Fiber ready context to enable sync execution and hooks
 * @param  {Function}   fn             function to be executed
 * @param  {String}     commandName    name of that function
 * @param  {Function[]} beforeCommand  method to be executed before calling the actual function
 * @param  {Function[]} afterCommand   method to be executed after calling the actual function
 * @return {Function}   actual wrapped function
 */
let wrapCommand = function (fn, commandName, beforeCommand, afterCommand) {
    if (isAsync()) {
        /**
         * async command wrap
         */
        return function (...commandArgs) {
            return fn.apply(this, commandArgs)
        }
    }

    /**
     * sync command wrap
     */
    return function (...commandArgs) {
        let future = new Future()
        let futureFailed = false

        if (forcePromises) {
            return fn.apply(this, commandArgs)
        }

        /**
         * don't execute [before/after]Command hook if a command was executed
         * in these hooks (otherwise we will get into an endless loop)
         */
        if (commandIsRunning) {
            let commandPromise = fn.apply(this, commandArgs)

            /**
             * try to execute with Fibers and fall back if can't
             */
            try {
                commandPromise.then(future.return.bind(future), future.throw.bind(future))
                return future.wait()
            } catch (e) {
                if (e.message === "Can't wait without a fiber") {
                    return commandPromise
                }
                throw e
            }
        }

        commandIsRunning = true
        let newInstance = this
        let commandResult, commandError
        new Promise((r) => r(executeHooksWithArgs(beforeCommand, [commandName, commandArgs])))
            .then(() => {
                /**
                 * actual function was already executed in desired catch block
                 */
                if (futureFailed) {
                    return
                }

                newInstance = fn.apply(this, commandArgs)
                return newInstance
            })
            .then(
                (result) => {
                    commandResult = result
                    return executeHooksWithArgs(afterCommand, [commandName, commandArgs, result])
                },
                (e) => {
                    commandError = e
                    return executeHooksWithArgs(afterCommand, [commandName, commandArgs, null, e])
                }
            )
            .then(() => {
                commandIsRunning = false

                if (commandError) {
                    return future.throw(commandError)
                }
                wrapCommands(newInstance, beforeCommand, afterCommand)
                return future.return(applyPrototype.call(newInstance, commandResult))
            })

        /**
         * try to execute with Fibers and fall back if can't
         */
        try {
            return future.wait()
        } catch (e) {
            if (e.message === "Can't wait without a fiber") {
                futureFailed = true
                return fn.apply(this, commandArgs)
            }
            throw e
        }
    }
}

/**
 * enhance result with instance prototype to enable command chaining
 * @param  {Object} result   command result
 * @return {Object}          command result with enhanced prototype
 */
let applyPrototype = function (result) {
    if (!result || typeof result !== 'object' || Array.isArray(result)) {
        return result
    }

    let prototype = {}
    let hasExtendedPrototype = false
    for (let commandName of Object.keys(Object.getPrototypeOf(this))) {
        if (result[commandName] || SYNC_COMMANDS.indexOf(commandName) > -1) {
            continue
        }

        this.lastResult = result
        prototype[commandName] = { value: this[commandName].bind(this) }
        hasExtendedPrototype = true
    }

    if (hasExtendedPrototype) {
        let newResult = Object.create(result, prototype)

        /**
         * since status is a command we need to rename the property
         */
        if (typeof result.status !== 'undefined') {
            result._status = result.status
            delete result.status
        }

        result = assign(newResult, result)
    }

    return result
}

/**
 * wraps all WebdriverIO commands
 * @param  {Object}     instance       WebdriverIO client instance (browser)
 * @param  {Function[]} beforeCommand  before command hook
 * @param  {Function[]} afterCommand   after command hook
 */
let wrapCommands = function (instance, beforeCommand, afterCommand) {
    /**
     * if instance is a multibrowser instance make sure to wrap commands
     * of its instances too
     */
    if (instance.isMultiremote) {
        instance.getInstances().forEach((browserName) => {
            wrapCommands(global[browserName], beforeCommand, afterCommand)
        })
    }

    Object.keys(Object.getPrototypeOf(instance)).forEach((commandName) => {
        if (SYNC_COMMANDS.indexOf(commandName) > -1) {
            return
        }

        let origFn = instance[commandName]
        instance[commandName] = wrapCommand.call(instance, origFn, commandName, beforeCommand, afterCommand)
    })

    /**
     * no need to overwrite addCommand in async mode
     */
    if (isAsync()) {
        return
    }

    /**
     * Adding a command within fiber context doesn't require a special routine
     * since everything runs sync. There is no need to promisify the command.
     */
    instance.addCommand = function (fnName, fn, forceOverwrite) {
        let commandGroup = instance
        let commandName = fnName
        let namespace

        if (typeof fn === 'string') {
            namespace = arguments[0]
            fnName = arguments[1]
            fn = arguments[2]
            forceOverwrite = arguments[3]

            switch (typeof commandGroup[namespace]) {
            case 'function':
                throw new Error(`Command namespace "${namespace}" is used internally, and can't be overwritten!`)
            case 'undefined':
                commandGroup[namespace] = {}
                break
            }

            commandName = `${namespace}.${fnName}`
            commandGroup = commandGroup[namespace]
        }

        if (commandGroup[fnName] && !forceOverwrite) {
            throw new Error(`Command ${fnName} is already defined!`)
        }

        /**
         * if method name is async the user specifies that he wants to
         * use bare promises to handle asynchronicity
         */
        if (fn.name === 'async') {
            commandGroup[fnName] = wrapCommand((...args) => {
                forcePromises = true
                let res = fn.apply(instance, args)
                forcePromises = false
                return res
            }, commandName, beforeCommand, afterCommand)
            return
        }

        /**
         * for all other cases we internally return a promise that is
         * finished once the Fiber wrapped custom function has finished
         * #functionalProgrammingWTF!
         */
        commandGroup[fnName] = wrapCommand((...args) => new Promise((r) => {
            wdioSync(fn, r).apply(instance, args)
        }), commandName, beforeCommand, afterCommand)
    }
}

/**
 * [runInFiberContext description]
 * @param  {[type]} testInterfaceFnNames  global command that runs specs
 * @param  {[type]} before               before hook hook
 * @param  {[type]} after                after hook hook
 * @param  {[type]} fnName               test interface command to wrap
 */
let runInFiberContext = function (testInterfaceFnNames, before, after, fnName) {
    let origFn = global[fnName]

    let runSpec = function (specTitle, specFn) {
        /**
         * user wants handle async command using promises, no need to wrap in fiber context
         */
        if (isAsync()) {
            return origFn.call(this, specTitle, specFn)
        }

        return origFn(specTitle, function (done) {
            Fiber(() => {
                specFn.call(this)
                done()
            }).run()
        })
    }

    let runHook = function (hookFn) {
        /**
         * user wants handle async command using promises, no need to wrap in fiber context
         */
        if (isAsync()) {
            return origFn(function (done) {
                executeHooksWithArgs(before).catch((e) => {
                    console.error(`Error in beforeHook: [${e}]`)
                }).then(() => {
                    return hookFn.call(this)
                }).then(() => {
                    return executeHooksWithArgs(after)
                    .catch((e) => {
                        console.error(`Error in afterHook: [${e}]`)
                    })
                }).then(() => done(), done)
            })
        }

        return origFn(function (done) {
            // Print errors encountered in beforeHook and afterHook to console, but
            // don't propagate them to avoid failing the test. However, errors in
            // framework hook functions should fail the test, so propagate those.
            executeHooksWithArgs(before)
                .catch((e) => {
                    console.error(`Error in beforeHook: [${e}]`)
                })
                .then(() => new Promise((resolve, reject) => {
                    return Fiber(() => {
                        try {
                            hookFn.call(this)
                        } catch (e) {
                            reject(e)
                        }
                        resolve()
                    }).run()
                }))
                .then(() => {
                    return executeHooksWithArgs(after)
                    .catch((e) => {
                        console.error(`Error in afterHook: [${e}]`)
                    })
                })
                .then(() => done(), done)
        })
    }

    global[fnName] = function (...specArguments) {
        /**
         * Variadic arguments: [title, fn], [title], [fn]
         */
        let specFn = typeof specArguments[0] === 'function' ? specArguments.shift()
            : (typeof specArguments[1] === 'function' ? specArguments.pop() : undefined)
        let specTitle = specArguments[0]

        if (testInterfaceFnNames.indexOf(fnName) > -1) {
            if (specFn) return runSpec(specTitle, specFn)

            /**
             * if specFn is undefined we are dealing with a pending function
             */
            return origFn(specTitle)
        }

        return runHook(specFn)
    }

    if (testInterfaceFnNames.indexOf(fnName) > -1) {
        global[fnName].skip = origFn.skip
        global[fnName].only = origFn.only
    }
}

export { wrapCommand, wrapCommands, runInFiberContext, executeHooksWithArgs }
<|endoftext|>


<commit_before>
// Global
pref("extensions.firebug.defaultPanelName", "html");
pref("extensions.firebug.throttleMessages", true);
pref("extensions.firebug.textSize", 0);
pref("extensions.firebug.showInfoTips", true);
pref("extensions.firebug.largeCommandLine", false);
pref("extensions.firebug.textWrapWidth", 100);
pref("extensions.firebug.openInWindow", false);
pref("extensions.firebug.showErrorCount", true);
pref("extensions.firebug.viewPanelOrient", "vertical");

pref("extensions.firebug.preferEnabled.Console", false);
pref("extensions.firebug.preferEnabled.Script", false);
pref("extensions.firebug.preferEnabled.Net", false);

pref("extensions.firebug.allowDoublePost", false);

// Console
pref("extensions.firebug.showJSErrors", true);
pref("extensions.firebug.showJSWarnings", false);
pref("extensions.firebug.showCSSErrors", false);
pref("extensions.firebug.showXMLErrors", false);
pref("extensions.firebug.showChromeErrors", false);
pref("extensions.firebug.showChromeMessages", false);
pref("extensions.firebug.showExternalErrors", false);
pref("extensions.firebug.showXMLHttpRequests", true);
pref("extensions.firebug-service.showStackTrace", true);
pref("extensions.firebug.console.logLimit", 500);
pref("extensions.firebug.console.enableLocalFiles", "");
pref("extensions.firebug.console.enableSystemPages", "");
pref("extensions.firebug.console.enableSites", false);

// HTML
pref("extensions.firebug.showCommentNodes", false);
pref("extensions.firebug.showWhitespaceNodes", false);
pref("extensions.firebug.showFullTextNodes", true);
pref("extensions.firebug.highlightMutations", true);
pref("extensions.firebug.expandMutations", false);
pref("extensions.firebug.scrollToMutations", false);
pref("extensions.firebug.shadeBoxModel", true);

// CSS
pref("extensions.firebug.showComputedStyle", false);
pref("extensions.firebug.showUserAgentCSS", false);

// Script
pref("extensions.firebug-service.breakOnErrors", false);
pref("extensions.firebug-service.filterSystemURLs", true);
pref("extensions.firebug-service.showAllSourceFiles", false);
pref("extensions.firebug-service.trackThrowCatch", false);
pref("extensions.firebug.script.enableLocalFiles", "");
pref("extensions.firebug.script.enableSystemPages", "");
pref("extensions.firebug.script.enableSites", false);
pref("extensions.firebug-service.scriptsFilter", "all");

// Stack
pref("extensions.firebug.omitObjectPathStack", false);

// DOM
pref("extensions.firebug.showUserProps", true);
pref("extensions.firebug.showUserFuncs", true);
pref("extensions.firebug.showDOMProps", true);
pref("extensions.firebug.showDOMFuncs", false);
pref("extensions.firebug.showDOMConstants", false);

// Layout
pref("extensions.firebug.showAdjacentLayout", false);
pref("extensions.firebug.showRulers", true);

// Net
pref("extensions.firebug.netFilterCategory", "all");
pref("extensions.firebug.collectHttpHeaders", true);
pref("extensions.firebug.net.logLimit", 500);
pref("extensions.firebug.net.enableLocalFiles", "");
pref("extensions.firebug.net.enableSystemPages", "");
pref("extensions.firebug.net.enableSites", false);

// External Editors
pref("extensions.firebug.externalEditors", "");

// Trace  /*@explore*/
pref("extensions.firebug.enableTraceConsole", true);     /*@explore*/
pref("extensions.firebug.alwaysOpenTraceConsole", false);     /*@explore*/
pref("extensions.firebug.trace.maxMessageLength", 400);     /*@explore*/
pref("extensions.firebug.trace.enableScope", false);     /*@explore*/
pref("extensions.firebug-service.DBG_FBS_JSDCONTEXT", false);// firebug-service trace scriptinfo(huge) /*@explore*/
pref("extensions.firebug-service.DBG_FBS_FF_START", false); // firebug-service trace from FF start(huge) /*@explore*/
pref("extensions.firebug-service.DBG_FBS_CREATION", false); // firebug-service script creation           /*@explore*/
pref("extensions.firebug-service.DBG_FBS_BP", false);       // firebug-service breakpoints               /*@explore*/
pref("extensions.firebug-service.DBG_FBS_SRCUNITS", false); // firebug-service script creation           /*@explore*/
pref("extensions.firebug-service.DBG_FBS_ERRORS", false);   // firebug-service errors                    /*@explore*/
pref("extensions.firebug-service.DBG_FBS_FINDDEBUGGER", false);   // firebug-service findDebugger        /*@explore*/
pref("extensions.firebug-service.DBG_FBS_STEP", false);     // firebug-service stepping                  /*@explore*/
pref("extensions.firebug-service.DBG_FBS_FUNCTION", false); // firebug-service new Function              /*@explore*/
pref("extensions.firebug.DBG_BP", false); 			// debugger.js and firebug-services.js; lots of output   /*@explore*/
pref("extensions.firebug.DBG_TOPLEVEL", false); 	// top level jsd scripts                     /*@explore*/
pref("extensions.firebug.DBG_STACK", false);  		// call stack, mostly debugger.js            /*@explore*/
pref("extensions.firebug.DBG_UI_LOOP", false); 		// debugger.js                               /*@explore*/
pref("extensions.firebug.DBG_ERRORS", false);  		// error.js                                  /*@explore*/
pref("extensions.firebug.DBG_EVENTS", false);  		// debugger.js for event handlers, need more /*@explore*/
pref("extensions.firebug.DBG_FUNCTION_NAMES", false);  // heuristics for anon functions          /*@explore*/
pref("extensions.firebug.DBG_EVAL", false);    		// debugger.js and firebug-service.js        /*@explore*/
pref("extensions.firebug.DBG_PANELS", false);  		// panel selection                           /*@explore*/
pref("extensions.firebug.DBG_CACHE", false);   		// sourceCache                               /*@explore*/
pref("extensions.firebug.DBG_CONSOLE", false);        // console                                   /*@explore*/
pref("extensions.firebug.DBG_CSS", false);          //                                             /*@explore*/
pref("extensions.firebug.DBG_DBG2FIREBUG", false);  //                                             /*@explore*/
pref("extensions.firebug.DBG_DOM", false);  //                                             /*@explore*/
pref("extensions.firebug.DBG_DISPATCH", false);     //                                          /*@explore*/
pref("extensions.firebug.DBG_HTML", false);         //                                          /*@explore*/
pref("extensions.firebug.DBG_LINETABLE", false);    // /*@explore*/
pref("extensions.firebug.DBG_SOURCEFILES", false); 	// debugger and sourceCache                  /*@explore*/
pref("extensions.firebug.DBG_WINDOWS", false);    	// tabWatcher, dispatch events; very useful for understand modules/panels  /*@explore*/
pref("extensions.firebug.DBG_NET", false);        	// net.js                                    /*@explore*/
pref("extensions.firebug.DBG_INITIALIZE", false);   // registry (modules panels); initialize FB  /*@explore*/
pref("extensions.firebug.DBG_INSPECT", false);   // inspector  /*@explore*/
pref("extensions.firebug.DBG_OPTIONS", false);      // /*@explore*/
pref("extensions.firebug-service.DBG_FBS_FLUSH", false); // /*@explore*/
pref("extensions.firebug.DBG_HTTPOBSERVER", false); // Centralized HTTP Observer /*@explore*/
pref("extensions.firebug.DBG_SPY", false);          // spy.js
<commit_msg>remove extensions.firebug-service.DBG_*<commit_after>
// Global
pref("extensions.firebug.defaultPanelName", "html");
pref("extensions.firebug.throttleMessages", true);
pref("extensions.firebug.textSize", 0);
pref("extensions.firebug.showInfoTips", true);
pref("extensions.firebug.largeCommandLine", false);
pref("extensions.firebug.textWrapWidth", 100);
pref("extensions.firebug.openInWindow", false);
pref("extensions.firebug.showErrorCount", true);
pref("extensions.firebug.viewPanelOrient", "vertical");

pref("extensions.firebug.preferEnabled.Console", false);
pref("extensions.firebug.preferEnabled.Script", false);
pref("extensions.firebug.preferEnabled.Net", false);

pref("extensions.firebug.allowDoublePost", false);

// Console
pref("extensions.firebug.showJSErrors", true);
pref("extensions.firebug.showJSWarnings", false);
pref("extensions.firebug.showCSSErrors", false);
pref("extensions.firebug.showXMLErrors", false);
pref("extensions.firebug.showChromeErrors", false);
pref("extensions.firebug.showChromeMessages", false);
pref("extensions.firebug.showExternalErrors", false);
pref("extensions.firebug.showXMLHttpRequests", true);
pref("extensions.firebug-service.showStackTrace", true);
pref("extensions.firebug.console.logLimit", 500);
pref("extensions.firebug.console.enableLocalFiles", "");
pref("extensions.firebug.console.enableSystemPages", "");
pref("extensions.firebug.console.enableSites", false);

// HTML
pref("extensions.firebug.showCommentNodes", false);
pref("extensions.firebug.showWhitespaceNodes", false);
pref("extensions.firebug.showFullTextNodes", true);
pref("extensions.firebug.highlightMutations", true);
pref("extensions.firebug.expandMutations", false);
pref("extensions.firebug.scrollToMutations", false);
pref("extensions.firebug.shadeBoxModel", true);

// CSS
pref("extensions.firebug.showComputedStyle", false);
pref("extensions.firebug.showUserAgentCSS", false);

// Script
pref("extensions.firebug-service.breakOnErrors", false);
pref("extensions.firebug-service.filterSystemURLs", true);
pref("extensions.firebug-service.showAllSourceFiles", false);
pref("extensions.firebug-service.trackThrowCatch", false);
pref("extensions.firebug.script.enableLocalFiles", "");
pref("extensions.firebug.script.enableSystemPages", "");
pref("extensions.firebug.script.enableSites", false);
pref("extensions.firebug-service.scriptsFilter", "all");

// Stack
pref("extensions.firebug.omitObjectPathStack", false);

// DOM
pref("extensions.firebug.showUserProps", true);
pref("extensions.firebug.showUserFuncs", true);
pref("extensions.firebug.showDOMProps", true);
pref("extensions.firebug.showDOMFuncs", false);
pref("extensions.firebug.showDOMConstants", false);

// Layout
pref("extensions.firebug.showAdjacentLayout", false);
pref("extensions.firebug.showRulers", true);

// Net
pref("extensions.firebug.netFilterCategory", "all");
pref("extensions.firebug.collectHttpHeaders", true);
pref("extensions.firebug.net.logLimit", 500);
pref("extensions.firebug.net.enableLocalFiles", "");
pref("extensions.firebug.net.enableSystemPages", "");
pref("extensions.firebug.net.enableSites", false);

// External Editors
pref("extensions.firebug.externalEditors", "");

// Trace  /*@explore*/
pref("extensions.firebug.enableTraceConsole", true);     /*@explore*/
pref("extensions.firebug.alwaysOpenTraceConsole", false);     /*@explore*/
pref("extensions.firebug.trace.maxMessageLength", 400);     /*@explore*/
pref("extensions.firebug.trace.enableScope", false);     /*@explore*/
pref("extensions.firebug.DBG_FBS_JSDCONTEXT", false);// firebug trace scriptinfo(huge) /*@explore*/
pref("extensions.firebug.DBG_FBS_FF_START", false); // firebug trace from FF start(huge) /*@explore*/
pref("extensions.firebug.DBG_FBS_CREATION", false); // firebug script creation           /*@explore*/
pref("extensions.firebug.DBG_FBS_BP", false);       // firebug breakpoints               /*@explore*/
pref("extensions.firebug.DBG_FBS_SRCUNITS", false); // firebug script creation           /*@explore*/
pref("extensions.firebug.DBG_FBS_ERRORS", false);   // firebug errors                    /*@explore*/
pref("extensions.firebug.DBG_FBS_FINDDEBUGGER", false);   // firebug findDebugger        /*@explore*/
pref("extensions.firebug.DBG_FBS_STEP", false);     // firebug stepping                  /*@explore*/
pref("extensions.firebug.DBG_FBS_FUNCTION", false); // firebug new Function              /*@explore*/
pref("extensions.firebug.DBG_BP", false); 			// debugger.js and firebug-services.js; lots of output   /*@explore*/
pref("extensions.firebug.DBG_TOPLEVEL", false); 	// top level jsd scripts                     /*@explore*/
pref("extensions.firebug.DBG_STACK", false);  		// call stack, mostly debugger.js            /*@explore*/
pref("extensions.firebug.DBG_UI_LOOP", false); 		// debugger.js                               /*@explore*/
pref("extensions.firebug.DBG_ERRORS", false);  		// error.js                                  /*@explore*/
pref("extensions.firebug.DBG_EVENTS", false);  		// debugger.js for event handlers, need more /*@explore*/
pref("extensions.firebug.DBG_FUNCTION_NAMES", false);  // heuristics for anon functions          /*@explore*/
pref("extensions.firebug.DBG_EVAL", false);    		// debugger.js and firebug-service.js        /*@explore*/
pref("extensions.firebug.DBG_PANELS", false);  		// panel selection                           /*@explore*/
pref("extensions.firebug.DBG_CACHE", false);   		// sourceCache                               /*@explore*/
pref("extensions.firebug.DBG_CONSOLE", false);        // console                                   /*@explore*/
pref("extensions.firebug.DBG_CSS", false);          //                                             /*@explore*/
pref("extensions.firebug.DBG_DBG2FIREBUG", false);  //                                             /*@explore*/
pref("extensions.firebug.DBG_DOM", false);  //                                             /*@explore*/
pref("extensions.firebug.DBG_DISPATCH", false);     //                                          /*@explore*/
pref("extensions.firebug.DBG_HTML", false);         //                                          /*@explore*/
pref("extensions.firebug.DBG_LINETABLE", false);    // /*@explore*/
pref("extensions.firebug.DBG_SOURCEFILES", false); 	// debugger and sourceCache                  /*@explore*/
pref("extensions.firebug.DBG_WINDOWS", false);    	// tabWatcher, dispatch events; very useful for understand modules/panels  /*@explore*/
pref("extensions.firebug.DBG_NET", false);        	// net.js                                    /*@explore*/
pref("extensions.firebug.DBG_INITIALIZE", false);   // registry (modules panels); initialize FB  /*@explore*/
pref("extensions.firebug.DBG_INSPECT", false);   // inspector  /*@explore*/
pref("extensions.firebug.DBG_OPTIONS", false);      // /*@explore*/
pref("extensions.firebug.DBG_FBS_FLUSH", false); // /*@explore*/
pref("extensions.firebug.DBG_HTTPOBSERVER", false); // Centralized HTTP Observer /*@explore*/
pref("extensions.firebug.DBG_SPY", false);          // spy.js
<|endoftext|>


<commit_before>// Copyright 2010 WebDriver committers
// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Atoms-based implementation of the webelement interface.
 */

goog.provide('webdriver.atoms.element');

goog.require('bot.Keyboard.Keys');
goog.require('bot.action');
goog.require('bot.dom');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.math');
goog.require('goog.string');
goog.require('goog.style');
goog.require('webdriver.Key');

/**
 * @param {!Element} element The element to use.
 * @return {boolean} Whether the element is checked or selected.
 */
webdriver.atoms.element.isSelected = function(element) {
  // Although this method looks unloved, its compiled form is used by
  // the Chrome and OperaDrivers.
  if (!bot.dom.isSelectable(element)) {
    return false;
  }

  return bot.dom.isSelected(element);
};

/**
 * Get the value of the given property or attribute. If the "attribute" is for
 * a boolean property, we return null in the case where the value is false. If
 * the attribute name is "style" an attempt to convert that style into a string
 * is done.
 *
 * @param {!Element} element The element to use.
 * @param {string} attribute The name of the attribute to look up.
 * @return {?string} The string value of the attribute or property, or null.
 */
webdriver.atoms.element.getAttribute = function(element, attribute) {
  var value = null;
  var name = attribute.toLowerCase();

  if ('style' == attribute.toLowerCase()) {
    value = element.style;

    if (value && !goog.isString(value)) {
      value = value.cssText;
    }

    return (/** @type {?string} */value);
  }

  if ('selected' == name || 'checked' == name &&
      bot.dom.isSelectable(element)) {
    return bot.dom.isSelected(element) ? 'true' : null;
  }

  // Our tests suggest that returning the attribute is desirable for
  // the href attribute of <a> tags and the src attribute of <img> tags,
  // but we normally attempt to get the property value before the attribute.
  var isLink = bot.dom.isElement(element, goog.dom.TagName.A);
  var isImg = bot.dom.isElement(element, goog.dom.TagName.IMG);

  // Although the attribute matters, the property is consistent. Return that in
  // preference to the attribute for links and images.
  if ((isImg && name == 'src') || (isLink && name == 'href')) {
    value = bot.dom.getAttribute(element, name);
    if (value) {
      // We want the full URL if present
      value = bot.dom.getProperty(element, name);
    }
    return (/** @type {?string} */value);
  }

  var property;
  try {
    property = bot.dom.getProperty(element, attribute);
  } catch (e) {
    // Leaves property undefined or null
  }

  // 1- Call getAttribute if getProperty fails,
  // i.e. property is null or undefined.
  // This happens for event handlers in Firefox.
  // For example, calling getProperty for 'onclick' would
  // fail while getAttribute for 'onclick' will succeed and
  // return the JS code of the handler.
  //
  // 2- When property is an object we fall back to the
  // actual attribute instead.
  // See issue http://code.google.com/p/selenium/issues/detail?id=966
  if (!goog.isDefAndNotNull(property) || goog.isObject(property)) {
    value = bot.dom.getAttribute(element, attribute);
  } else {
    value = property;
  }

  // The empty string is a valid return value.
  return goog.isDefAndNotNull(value) ? value.toString() : null;
};

/**
 * Get the location of the element in page space, if it's displayed.
 *
 * @param {!Element} element The element to get the location for.
 * @return {goog.math.Rect} The bounding rectangle of the element.
 */
webdriver.atoms.element.getLocation = function(element) {
  if (!bot.dom.isShown(element)) {
    return null;
  }
  return goog.style.getBounds(element);
};

/**
 * @param {Node} element The element to use.
 * @return {boolean} Whether the element is in the HEAD tag.
 * @private
 */
webdriver.atoms.element.isInHead_ = function(element) {
  while (element) {
    if (element.tagName && element.tagName.toLowerCase() == 'head') {
      return true;
    }
    try {
      element = element.parentNode;
    } catch (e) {
      // Fine. the DOM has dispeared from underneath us
      return false;
    }
  }

  return false;
};

/**
 * @param {!Element} element The element to get the text from.
 * @return {string} The visible text or an empty string.
 */
webdriver.atoms.element.getText = function(element) {
  if (webdriver.atoms.element.isInHead_(element)) {
    var doc = goog.dom.getOwnerDocument(element);
    if (element.tagName.toUpperCase() == goog.dom.TagName.TITLE &&
        goog.dom.getWindow(doc) == bot.window_.top) {
      return goog.string.trim((/** @type {string} */doc.title));
    }
    return '';
  }

  return bot.dom.getVisibleText(element);
};

/**
 * Types keys on the given {@code element} with a virtual keyboard. Converts
 * special characters from the WebDriver JSON wire protocol to the appropriate
 * {@link bot.Keyboard.Key} value.
 *
 * @param {!Element} element The element to type upon.
 * @param {!Array.<string>} keys The keys to type on the element.
 * @see bot.action.type
 * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol
 */
webdriver.atoms.element.type = function(element, keys) {
  // Convert to bot.Keyboard.Key values.
  var convertedSequences = [], current;
  convertedSequences.push(current = []);

  goog.array.forEach(keys, function(sequence) {
    goog.array.forEach(sequence.split(''), function(key) {
      if (isWebDriverKey(key)) {
        var webdriverKey = webdriver.atoms.element.type.JSON_TO_KEY_MAP_[key];
        // goog.isNull uses ==, which accepts undefined.
        if (webdriverKey === null) {
          // bot.action.type does not support a "null" key, so we have to
          // terminate the entire sequence to release modifier keys.
          convertedSequences.push(current = []);
        } else if (goog.isDef(webdriverKey)) {
          current.push(webdriverKey);
        } else {
          throw Error('Unsupported WebDriver key: \\u' +
              key.charCodeAt(0).toString(16));
        }
      }

      // Handle common aliases.
      switch (key) {
        case '\n':
          current.push(bot.Keyboard.Keys.ENTER);
          break;
        case '\t':
          current.push(bot.Keyboard.Keys.TAB);
          break;
        case '\b':
          current.push(bot.Keyboard.Keys.BACKSPACE);
          break;
      }
      current.push(key);
    });
  });

  goog.array.forEach(convertedSequences, function(sequence) {
    var args = goog.array.concat(element, sequence);
    bot.action.type.apply(null, args);
  });

  function isWebDriverKey(c) {
    return '\uE000' <= c && c <= '\uE03D';
  }
};

/**
 * Maps JSON wire protocol values to their {@link bot.Keyboard.Key} counterpart.
 * @type {!Object.<bot.Keyboard.Key>}
 * @const
 * @private
 */
webdriver.atoms.element.type.JSON_TO_KEY_MAP_ = {};
goog.scope(function() {
  var map = webdriver.atoms.element.type.JSON_TO_KEY_MAP_;
  var key = webdriver.Key;
  var botKey = bot.Keyboard.Keys;

  map[key.NULL] = null;
  map[key.BACK_SPACE] = botKey.BACKSPACE;
  map[key.TAB] = botKey.TAB;
  map[key.RETURN] = botKey.ENTER;
  // This not correct, but most browsers will do the right thing.
  map[key.ENTER] = botKey.ENTER;
  map[key.SHIFT] = botKey.SHIFT;
  map[key.CONTROL] = botKey.CONTROL;
  map[key.ALT] = botKey.ALT;
  map[key.PAUSE] = botKey.PAUSE;
  map[key.ESCAPE] = botKey.ESC;
  map[key.SPACE] = botKey.SPACE;
  map[key.PAGE_UP] = botKey.PAGE_UP;
  map[key.PAGE_DOWN] = botKey.PAGE_DOWN;
  map[key.END] = botKey.END;
  map[key.HOME] = botKey.HOME;
  map[key.LEFT] = botKey.LEFT;
  map[key.UP] = botKey.UP;
  map[key.RIGHT] = botKey.RIGHT;
  map[key.DOWN] = botKey.DOWN;
  map[key.INSERT] = botKey.INSERT;
  map[key.DELETE] = botKey.DELETE;
  map[key.SEMICOLON] = botKey.SEMICOLON;
  map[key.EQUALS] = botKey.EQUALS;
  map[key.NUMPAD0] = botKey.NUM_ZERO;
  map[key.NUMPAD1] = botKey.NUM_ONE;
  map[key.NUMPAD2] = botKey.NUM_TWO;
  map[key.NUMPAD3] = botKey.NUM_THREE;
  map[key.NUMPAD4] = botKey.NUM_FOUR;
  map[key.NUMPAD5] = botKey.NUM_FIVE;
  map[key.NUMPAD6] = botKey.NUM_SIX;
  map[key.NUMPAD7] = botKey.NUM_SEVEN;
  map[key.NUMPAD8] = botKey.NUM_EIGHT;
  map[key.NUMPAD9] = botKey.NUM_NINE;
  map[key.MULTIPLY] = botKey.NUM_MULTIPLY;
  map[key.ADD] = botKey.NUM_PLUS;
  map[key.SUBTRACT] = botKey.NUM_MINUS;
  map[key.DECIMAL] = botKey.NUM_PERIOD;
  map[key.DIVIDE] = botKey.NUM_DIVISION;
  map[key.F1] = botKey.F1;
  map[key.F2] = botKey.F2;
  map[key.F3] = botKey.F3;
  map[key.F4] = botKey.F4;
  map[key.F5] = botKey.F5;
  map[key.F6] = botKey.F6;
  map[key.F7] = botKey.F7;
  map[key.F8] = botKey.F8;
  map[key.F9] = botKey.F9;
  map[key.F10] = botKey.F10;
  map[key.F11] = botKey.F11;
  map[key.F12] = botKey.F12;
  map[key.META] = botKey.META;
});
<commit_msg>JasonLeyba: The signature of bot.action.type has changed.<commit_after>// Copyright 2010 WebDriver committers
// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Atoms-based implementation of the webelement interface.
 */

goog.provide('webdriver.atoms.element');

goog.require('bot.Keyboard.Keys');
goog.require('bot.action');
goog.require('bot.dom');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.math');
goog.require('goog.string');
goog.require('goog.style');
goog.require('webdriver.Key');

/**
 * @param {!Element} element The element to use.
 * @return {boolean} Whether the element is checked or selected.
 */
webdriver.atoms.element.isSelected = function(element) {
  // Although this method looks unloved, its compiled form is used by
  // the Chrome and OperaDrivers.
  if (!bot.dom.isSelectable(element)) {
    return false;
  }

  return bot.dom.isSelected(element);
};

/**
 * Get the value of the given property or attribute. If the "attribute" is for
 * a boolean property, we return null in the case where the value is false. If
 * the attribute name is "style" an attempt to convert that style into a string
 * is done.
 *
 * @param {!Element} element The element to use.
 * @param {string} attribute The name of the attribute to look up.
 * @return {?string} The string value of the attribute or property, or null.
 */
webdriver.atoms.element.getAttribute = function(element, attribute) {
  var value = null;
  var name = attribute.toLowerCase();

  if ('style' == attribute.toLowerCase()) {
    value = element.style;

    if (value && !goog.isString(value)) {
      value = value.cssText;
    }

    return (/** @type {?string} */value);
  }

  if ('selected' == name || 'checked' == name &&
      bot.dom.isSelectable(element)) {
    return bot.dom.isSelected(element) ? 'true' : null;
  }

  // Our tests suggest that returning the attribute is desirable for
  // the href attribute of <a> tags and the src attribute of <img> tags,
  // but we normally attempt to get the property value before the attribute.
  var isLink = bot.dom.isElement(element, goog.dom.TagName.A);
  var isImg = bot.dom.isElement(element, goog.dom.TagName.IMG);

  // Although the attribute matters, the property is consistent. Return that in
  // preference to the attribute for links and images.
  if ((isImg && name == 'src') || (isLink && name == 'href')) {
    value = bot.dom.getAttribute(element, name);
    if (value) {
      // We want the full URL if present
      value = bot.dom.getProperty(element, name);
    }
    return (/** @type {?string} */value);
  }

  var property;
  try {
    property = bot.dom.getProperty(element, attribute);
  } catch (e) {
    // Leaves property undefined or null
  }

  // 1- Call getAttribute if getProperty fails,
  // i.e. property is null or undefined.
  // This happens for event handlers in Firefox.
  // For example, calling getProperty for 'onclick' would
  // fail while getAttribute for 'onclick' will succeed and
  // return the JS code of the handler.
  //
  // 2- When property is an object we fall back to the
  // actual attribute instead.
  // See issue http://code.google.com/p/selenium/issues/detail?id=966
  if (!goog.isDefAndNotNull(property) || goog.isObject(property)) {
    value = bot.dom.getAttribute(element, attribute);
  } else {
    value = property;
  }

  // The empty string is a valid return value.
  return goog.isDefAndNotNull(value) ? value.toString() : null;
};

/**
 * Get the location of the element in page space, if it's displayed.
 *
 * @param {!Element} element The element to get the location for.
 * @return {goog.math.Rect} The bounding rectangle of the element.
 */
webdriver.atoms.element.getLocation = function(element) {
  if (!bot.dom.isShown(element)) {
    return null;
  }
  return goog.style.getBounds(element);
};

/**
 * @param {Node} element The element to use.
 * @return {boolean} Whether the element is in the HEAD tag.
 * @private
 */
webdriver.atoms.element.isInHead_ = function(element) {
  while (element) {
    if (element.tagName && element.tagName.toLowerCase() == 'head') {
      return true;
    }
    try {
      element = element.parentNode;
    } catch (e) {
      // Fine. the DOM has dispeared from underneath us
      return false;
    }
  }

  return false;
};

/**
 * @param {!Element} element The element to get the text from.
 * @return {string} The visible text or an empty string.
 */
webdriver.atoms.element.getText = function(element) {
  if (webdriver.atoms.element.isInHead_(element)) {
    var doc = goog.dom.getOwnerDocument(element);
    if (element.tagName.toUpperCase() == goog.dom.TagName.TITLE &&
        goog.dom.getWindow(doc) == bot.window_.top) {
      return goog.string.trim((/** @type {string} */doc.title));
    }
    return '';
  }

  return bot.dom.getVisibleText(element);
};

/**
 * Types keys on the given {@code element} with a virtual keyboard. Converts
 * special characters from the WebDriver JSON wire protocol to the appropriate
 * {@link bot.Keyboard.Key} value.
 *
 * @param {!Element} element The element to type upon.
 * @param {!Array.<string>} keys The keys to type on the element.
 * @see bot.action.type
 * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol
 */
webdriver.atoms.element.type = function(element, keys) {
  // Convert to bot.Keyboard.Key values.
  /** @type {!Array.<!Array.<(string|!bot.Keyboard.Key)>>} */
  var convertedSequences = [];
  /** @type {!Array.<(string|!bot.Keyboard.Key)>} */
  var current = [];
  convertedSequences.push(current);

  goog.array.forEach(keys, function(sequence) {
    goog.array.forEach(sequence.split(''), function(key) {
      if (isWebDriverKey(key)) {
        var webdriverKey = webdriver.atoms.element.type.JSON_TO_KEY_MAP_[key];
        // goog.isNull uses ==, which accepts undefined.
        if (webdriverKey === null) {
          // bot.action.type does not support a "null" key, so we have to
          // terminate the entire sequence to release modifier keys.
          convertedSequences.push(current = []);
        } else if (goog.isDef(webdriverKey)) {
          current.push(webdriverKey);
        } else {
          throw Error('Unsupported WebDriver key: \\u' +
              key.charCodeAt(0).toString(16));
        }
      }

      // Handle common aliases.
      switch (key) {
        case '\n':
          current.push(bot.Keyboard.Keys.ENTER);
          break;
        case '\t':
          current.push(bot.Keyboard.Keys.TAB);
          break;
        case '\b':
          current.push(bot.Keyboard.Keys.BACKSPACE);
          break;
      }
      current.push(key);
    });
  });

  goog.array.forEach(convertedSequences, function(sequence) {
    bot.action.type(element, sequence);
  });

  function isWebDriverKey(c) {
    return '\uE000' <= c && c <= '\uE03D';
  }
};

/**
 * Maps JSON wire protocol values to their {@link bot.Keyboard.Key} counterpart.
 * @type {!Object.<bot.Keyboard.Key>}
 * @const
 * @private
 */
webdriver.atoms.element.type.JSON_TO_KEY_MAP_ = {};
goog.scope(function() {
  var map = webdriver.atoms.element.type.JSON_TO_KEY_MAP_;
  var key = webdriver.Key;
  var botKey = bot.Keyboard.Keys;

  map[key.NULL] = null;
  map[key.BACK_SPACE] = botKey.BACKSPACE;
  map[key.TAB] = botKey.TAB;
  map[key.RETURN] = botKey.ENTER;
  // This not correct, but most browsers will do the right thing.
  map[key.ENTER] = botKey.ENTER;
  map[key.SHIFT] = botKey.SHIFT;
  map[key.CONTROL] = botKey.CONTROL;
  map[key.ALT] = botKey.ALT;
  map[key.PAUSE] = botKey.PAUSE;
  map[key.ESCAPE] = botKey.ESC;
  map[key.SPACE] = botKey.SPACE;
  map[key.PAGE_UP] = botKey.PAGE_UP;
  map[key.PAGE_DOWN] = botKey.PAGE_DOWN;
  map[key.END] = botKey.END;
  map[key.HOME] = botKey.HOME;
  map[key.LEFT] = botKey.LEFT;
  map[key.UP] = botKey.UP;
  map[key.RIGHT] = botKey.RIGHT;
  map[key.DOWN] = botKey.DOWN;
  map[key.INSERT] = botKey.INSERT;
  map[key.DELETE] = botKey.DELETE;
  map[key.SEMICOLON] = botKey.SEMICOLON;
  map[key.EQUALS] = botKey.EQUALS;
  map[key.NUMPAD0] = botKey.NUM_ZERO;
  map[key.NUMPAD1] = botKey.NUM_ONE;
  map[key.NUMPAD2] = botKey.NUM_TWO;
  map[key.NUMPAD3] = botKey.NUM_THREE;
  map[key.NUMPAD4] = botKey.NUM_FOUR;
  map[key.NUMPAD5] = botKey.NUM_FIVE;
  map[key.NUMPAD6] = botKey.NUM_SIX;
  map[key.NUMPAD7] = botKey.NUM_SEVEN;
  map[key.NUMPAD8] = botKey.NUM_EIGHT;
  map[key.NUMPAD9] = botKey.NUM_NINE;
  map[key.MULTIPLY] = botKey.NUM_MULTIPLY;
  map[key.ADD] = botKey.NUM_PLUS;
  map[key.SUBTRACT] = botKey.NUM_MINUS;
  map[key.DECIMAL] = botKey.NUM_PERIOD;
  map[key.DIVIDE] = botKey.NUM_DIVISION;
  map[key.F1] = botKey.F1;
  map[key.F2] = botKey.F2;
  map[key.F3] = botKey.F3;
  map[key.F4] = botKey.F4;
  map[key.F5] = botKey.F5;
  map[key.F6] = botKey.F6;
  map[key.F7] = botKey.F7;
  map[key.F8] = botKey.F8;
  map[key.F9] = botKey.F9;
  map[key.F10] = botKey.F10;
  map[key.F11] = botKey.F11;
  map[key.F12] = botKey.F12;
  map[key.META] = botKey.META;
});
<|endoftext|>


<commit_before>import React from 'react';

const edit = ({
  getEditId = () => {},
  getEditProperty = () => {},
  onActivate = () => {},
  onValue = () => {}
}) => editor => {
  const Edit = (value, extraParameters) => {
    const idx = getEditId(extraParameters);
    const editedCell = getEditProperty();

    if (editedCell === idx) {
      return {
        children: React.createElement(
          editor,
          {
            value,
            onValue: v => onValue(
              { value: v, ...extraParameters }
            )
          }
        )
      };
    }

    return {
      onClick: () => onActivate(idx)
    };
  };
  Edit.propTypes = {
    value: React.PropTypes.any,
    extraParameters: React.PropTypes.shape({
      cellData: React.PropTypes.object.isRequired,
      property: React.PropTypes.string.isRequired
    })
  };

  return Edit;
};

const sort = ({
  getSortingColumns = () => [],
  onSort = () => {}
} = {}) => property => {
  const Sort = () => {
    const columns = getSortingColumns();
    const index = columns.map(c => c.property).indexOf(property);
    let headerClass = 'sort sort-none';

    if (index >= 0) {
      headerClass = `sort sort-${columns[index].sort}`;
    }

    return {
      className: headerClass,
      onClick: () => onSort(property)
    };
  };
  Sort.propTypes = {
    property: React.PropTypes.string.isRequired
  };

  return Sort;
};

export default {
  edit,
  sort
};
<commit_msg>transforms - Simplify implementation<commit_after>import React from 'react';

const edit = ({
  getEditId = () => {},
  getEditProperty = () => {},
  onActivate = () => {},
  onValue = () => {}
}) => editor => (value, extraParameters) => {
  const idx = getEditId(extraParameters);
  const editedCell = getEditProperty();

  if (editedCell === idx) {
    return {
      children: React.createElement(
        editor,
        {
          value,
          onValue: v => onValue(
            { value: v, ...extraParameters }
          )
        }
      )
    };
  }

  return {
    onClick: () => onActivate(idx)
  };
};

const sort = ({
  getSortingColumns = () => [],
  onSort = () => {}
} = {}) => property => () => {
  const columns = getSortingColumns();
  const index = columns.map(c => c.property).indexOf(property);
  let headerClass = 'sort sort-none';

  if (index >= 0) {
    headerClass = `sort sort-${columns[index].sort}`;
  }

  return {
    className: headerClass,
    onClick: () => onSort(property)
  };
};

export default {
  edit,
  sort
};
<|endoftext|>


<commit_before>/**
 * Declares instance variables.
 *
 * @constructor
 *
 * @class A class for massaging a table.
 */
UI.Table_Masseuse = function TableMasseuse()
{
	Util.OOP.inherits(this, UI.Masseuse);

	var empty_header_text = 'Column title';

	/*
	 * Ensures that the given table follows the thead/tbody/tfoot structure.
	 */
	function normalize_table_structure(table, first_row_is_head)
	{
		function get_bodies() {
			var bodies;
			var c;

			// the tBodies property might be broken under IE8
			if (table.tBodies)
				return table.tBodies;

			bodies = [];
			for (var i = 0; i < table.childNodes.length; i++) {
				c = table.childNodes[i];

				if (Util.Node.is_tag(c, 'TBODY'))
					bodies.push(c);
			}

			return bodies;
		}

		function get_first_row()
		{
			var source = get_bodies()[0] || table;

			for (var c = source.firstChild; c; c = c.nextSibling) {
				if (Util.Node.is_tag(c, 'TR'))
					return c;
			}

			return null;
		}

		function promote_row(row, where)
		{
			var method = 'createT' + where[0].toUpperCase() + where.substr(1);
			var dest = table[method]();

			if (!row)
				return false;

			dest.insertBefore(row, dest.firstChild);
			return true;
		}

		function is_header_row(row) {
			var maybe = false;

			for (var c = row.firstChild; c; c = c.nextSibling) {
				if (Util.Node.is_tag(c, 'TD'))
					return false;
				if (!maybe && Util.Node.is_tag(c, 'TH'))
					maybe = true;
			}

			return maybe;
		}

		function count_columns(row) {
			var count = 0;

			for (var c = row.firstChild; c; c = c.nextSibling) {
				if (Util.Node.is_tag(c, 'TD') || Util.Node.is_tag(c, 'TH'))
					count++;
			}

			return count;
		}

		function create_header_row(cells) {
			var row = table.ownerDocument.createElement('TR');

			for (var i = 0; i < cells; i++) {
				row.appendChild(row.ownerDocument.createElement('TH'));
			}

			return row;
		}

		function fill_in_empty_cells(row)
		{
			var empty_pat = /^(\s| |
]*>)+$/i;

			for (var c = row.firstChild; c; c = c.nextSibling) {
				if (!Util.Node.is_tag(c, 'TD') && !Util.Node.is_tag(c, 'TH'))
					continue;

				if (!c.hasChildNodes() || empty_pat.test(c.innerHTML))
					c.innerHTML = empty_header_text;
			}
		}

		if (!Util.Node.is_tag(table, 'TABLE')) {
			throw new TypeError("Cannot normalize the table structure of a " +
				"non-table.");
		}

		console.debug(table);

		if (first_row_is_head) {
			promote_row(get_first_row(), 'head');
		}

		var head = table.createTHead();
		var head_valid = true;
		if (head.getElementsByTagName("TR").length == 0) {
			// See if the first row of the table is actually a header row.
			var candidate = get_first_row();
			console.debug(candidate);
			if (is_header_row(candidate)) {
				promote_row(candidate, 'head');
			} else {
				head_valid = false; // don't worry about the lack of header
				/*
				// Create an empty header row.
				var hr = create_header_row(count_columns(candidate));
				head.appendChild(hr);
				*/
			}
		}

		var bodies = get_bodies();
		if (bodies.length == 0) {
			var body = table.ownerDocument.createElement('TBODY');
			head.parentNode.insertBefore(body, head.nextSibling);

			for (var c = table.firstChild; c; c = c.nextSibling) {
				if (Util.Node.is_tag(c, 'TR'))
					body.appendChild(c);
			}
		}

		if (!head_valid) {
			table.deleteTHead();
		} else {
			for (var c = head.firstChild; c; c = c.nextSibling) {
				if (Util.Node.is_tag(c, 'TR'))
					fill_in_empty_cells(c);
			}
		}

		return table;
	}

	this.massage_node_descendants =
		function massage_table_node_descendants(node)
	{
		var tables = node.getElementsByTagName('TABLE');
		if (!tables.length)
			return;

		for (var i = tables.length - 1; i >= 0; i--) {
			massage_table(tables[i]);
		}
	}

	this.unmassage_node_descendants =
		function unmassage_table_node_descendants(node)
	{
		var tables = node.getElementsByTagName('TABLE');
		if (!tables.length)
			return;

		for (var i = tables.length - 1; i >= 0; i--) {
			unmassage_table(tables[i]);
		}
	}

	function massage_table(table)
	{
		if (!table.getAttribute('border'))
			Util.Element.add_class(table, 'loki__borderless_table');

		// Add trailing
 in Gecko, for better display and editing
		if (Util.Browser.Gecko) {
			// First, try innerHTML
			var h;
			if (table.innerHTML != null && table.innerHTML != '')
			{
				h = table.innerHTML;
				h.replace( new RegExp('(]*>)[ ]*(	)', 'gi'), '$1
$2' );
				h.replace( new RegExp('(]*>)[ ]*(	)', 'gi'), '$1
$2' );
				table.innerHTML = h;
			}
			// But sometimes (namely, when the table is first created in Gecko),
			// innerHTML is mysteriously not available. In that case, we use the
			// slower DOM method, which on large tables can cause Gecko to display
			// the "Something is causing this script to run slowly; do you want to
			// kill it?" alert:
			for ( var i = 0; i < table.rows.length; i++ )
			{
				var row = table.rows[i];
				for ( var j = 0; j < row.cells.length; j++ )
				{
					var cell = row.cells[j];
					if ( !( cell.lastChild != null &&
						    cell.lastChild.nodeType == Util.Node.ELEMENT_NODE &&
						    cell.lastChild.tagName == 'BR' ) )
					{
						cell.appendChild( cell.ownerDocument.createElement('BR') );
					}
				}
			}
		}

		normalize_table_structure(table, false);
	}

	function unmassage_table(table)
	{
		Util.Element.remove_class(table, 'loki__borderless_table');

		// Remove trailing
 in Gecko
		if (Util.Browser.Gecko) {
			var h = table.innerHTML;
			h.replace(/
(<\/t[dh]>)/gi, '$1');
			table.innerHTML = h;

			/*
			for ( var i = 0; i < table.rows.length; i++ )
			{
				var row = table.rows[i];
				for ( var j = 0; j < row.cells.length; j++ )
				{
					var cell = row.cells[j];
					if ( cell.lastChild != null &&
						 cell.lastChild.nodeType == Util.Node.ELEMENT_NODE &&
						 cell.lastChild.tagName == 'BR' )
					{
						cell.removeChild(cell.lastChild);
					}
				}
			}
			*/
		}
	}

	this.massage_elem = massage_table;
	this.unmassage_elem = unmassage_table;
};
<commit_msg>Removed dangerous logging statements.<commit_after>/**
 * Declares instance variables.
 *
 * @constructor
 *
 * @class A class for massaging a table.
 */
UI.Table_Masseuse = function TableMasseuse()
{
	Util.OOP.inherits(this, UI.Masseuse);

	var empty_header_text = 'Column title';

	/*
	 * Ensures that the given table follows the thead/tbody/tfoot structure.
	 */
	function normalize_table_structure(table, first_row_is_head)
	{
		function get_bodies() {
			var bodies;
			var c;

			// the tBodies property might be broken under IE8
			if (table.tBodies)
				return table.tBodies;

			bodies = [];
			for (var i = 0; i < table.childNodes.length; i++) {
				c = table.childNodes[i];

				if (Util.Node.is_tag(c, 'TBODY'))
					bodies.push(c);
			}

			return bodies;
		}

		function get_first_row()
		{
			var source = get_bodies()[0] || table;

			for (var c = source.firstChild; c; c = c.nextSibling) {
				if (Util.Node.is_tag(c, 'TR'))
					return c;
			}

			return null;
		}

		function promote_row(row, where)
		{
			var method = 'createT' + where[0].toUpperCase() + where.substr(1);
			var dest = table[method]();

			if (!row)
				return false;

			dest.insertBefore(row, dest.firstChild);
			return true;
		}

		function is_header_row(row) {
			var maybe = false;

			for (var c = row.firstChild; c; c = c.nextSibling) {
				if (Util.Node.is_tag(c, 'TD'))
					return false;
				if (!maybe && Util.Node.is_tag(c, 'TH'))
					maybe = true;
			}

			return maybe;
		}

		function count_columns(row) {
			var count = 0;

			for (var c = row.firstChild; c; c = c.nextSibling) {
				if (Util.Node.is_tag(c, 'TD') || Util.Node.is_tag(c, 'TH'))
					count++;
			}

			return count;
		}

		function create_header_row(cells) {
			var row = table.ownerDocument.createElement('TR');

			for (var i = 0; i < cells; i++) {
				row.appendChild(row.ownerDocument.createElement('TH'));
			}

			return row;
		}

		function fill_in_empty_cells(row)
		{
			var empty_pat = /^(\s| |
]*>)+$/i;

			for (var c = row.firstChild; c; c = c.nextSibling) {
				if (!Util.Node.is_tag(c, 'TD') && !Util.Node.is_tag(c, 'TH'))
					continue;

				if (!c.hasChildNodes() || empty_pat.test(c.innerHTML))
					c.innerHTML = empty_header_text;
			}
		}

		if (!Util.Node.is_tag(table, 'TABLE')) {
			throw new TypeError("Cannot normalize the table structure of a " +
				"non-table.");
		}

		if (first_row_is_head) {
			promote_row(get_first_row(), 'head');
		}

		var head = table.createTHead();
		var head_valid = true;
		if (head.getElementsByTagName("TR").length == 0) {
			// See if the first row of the table is actually a header row.
			var candidate = get_first_row();
			if (is_header_row(candidate)) {
				promote_row(candidate, 'head');
			} else {
				head_valid = false; // don't worry about the lack of header
				/*
				// Create an empty header row.
				var hr = create_header_row(count_columns(candidate));
				head.appendChild(hr);
				*/
			}
		}

		var bodies = get_bodies();
		if (bodies.length == 0) {
			var body = table.ownerDocument.createElement('TBODY');
			head.parentNode.insertBefore(body, head.nextSibling);

			for (var c = table.firstChild; c; c = c.nextSibling) {
				if (Util.Node.is_tag(c, 'TR'))
					body.appendChild(c);
			}
		}

		if (!head_valid) {
			table.deleteTHead();
		} else {
			for (var c = head.firstChild; c; c = c.nextSibling) {
				if (Util.Node.is_tag(c, 'TR'))
					fill_in_empty_cells(c);
			}
		}

		return table;
	}

	this.massage_node_descendants =
		function massage_table_node_descendants(node)
	{
		var tables = node.getElementsByTagName('TABLE');
		if (!tables.length)
			return;

		for (var i = tables.length - 1; i >= 0; i--) {
			massage_table(tables[i]);
		}
	}

	this.unmassage_node_descendants =
		function unmassage_table_node_descendants(node)
	{
		var tables = node.getElementsByTagName('TABLE');
		if (!tables.length)
			return;

		for (var i = tables.length - 1; i >= 0; i--) {
			unmassage_table(tables[i]);
		}
	}

	function massage_table(table)
	{
		if (!table.getAttribute('border'))
			Util.Element.add_class(table, 'loki__borderless_table');

		// Add trailing
 in Gecko, for better display and editing
		if (Util.Browser.Gecko) {
			// First, try innerHTML
			var h;
			if (table.innerHTML != null && table.innerHTML != '')
			{
				h = table.innerHTML;
				h.replace( new RegExp('(]*>)[ ]*(	)', 'gi'), '$1
$2' );
				h.replace( new RegExp('(]*>)[ ]*(	)', 'gi'), '$1
$2' );
				table.innerHTML = h;
			}
			// But sometimes (namely, when the table is first created in Gecko),
			// innerHTML is mysteriously not available. In that case, we use the
			// slower DOM method, which on large tables can cause Gecko to display
			// the "Something is causing this script to run slowly; do you want to
			// kill it?" alert:
			for ( var i = 0; i < table.rows.length; i++ )
			{
				var row = table.rows[i];
				for ( var j = 0; j < row.cells.length; j++ )
				{
					var cell = row.cells[j];
					if ( !( cell.lastChild != null &&
						    cell.lastChild.nodeType == Util.Node.ELEMENT_NODE &&
						    cell.lastChild.tagName == 'BR' ) )
					{
						cell.appendChild( cell.ownerDocument.createElement('BR') );
					}
				}
			}
		}

		normalize_table_structure(table, false);
	}

	function unmassage_table(table)
	{
		Util.Element.remove_class(table, 'loki__borderless_table');

		// Remove trailing
 in Gecko
		if (Util.Browser.Gecko) {
			var h = table.innerHTML;
			h.replace(/
(<\/t[dh]>)/gi, '$1');
			table.innerHTML = h;

			/*
			for ( var i = 0; i < table.rows.length; i++ )
			{
				var row = table.rows[i];
				for ( var j = 0; j < row.cells.length; j++ )
				{
					var cell = row.cells[j];
					if ( cell.lastChild != null &&
						 cell.lastChild.nodeType == Util.Node.ELEMENT_NODE &&
						 cell.lastChild.tagName == 'BR' )
					{
						cell.removeChild(cell.lastChild);
					}
				}
			}
			*/
		}
	}

	this.massage_elem = massage_table;
	this.unmassage_elem = unmassage_table;
};
<|endoftext|>


<commit_before>var Hal=function(g,d){var k="iyelik",a="i",h="e",b="de",l="den",i="ııiiuuüü",f=g[g.length-1],c=~~/[ei][^ıüoö]*[au]l$|alp$/.test(g)*2,j=g.match(/[aıeiouöü]/g).pop(),e=(d==k||d==a)?i["aıeiouöü".indexOf(j)+c]:(/[aıou]/.test(j))?c?"e":"a":"e";if(f==j){e=(d==k)?"n"+e:(d==a||d==h)?"y"+e:e}if(d==b||d==l){e=(/[fstkçşhp]/.test(f)?"t":"d")+e}if(d==k||d==l){e+="n"}return g+"'"+e};
<commit_msg>Lisans eklendi<commit_after>/*
* Copyright 2012 Sercan Eraslan
*
* 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.
*/

/*
*
* Haller.js v2.1
* http://sercaneraslan.github.io/Selider/
*
* Github : @sercaneraslan
* Twitter : @sercan_eraslan
* Web : sercaneraslan.com
*/
var Hal=function(g,d){var k="iyelik",a="i",h="e",b="de",l="den",i="ııiiuuüü",f=g[g.length-1],c=~~/[ei][^ıüoö]*[au]l$|alp$/.test(g)*2,j=g.match(/[aıeiouöü]/g).pop(),e=(d==k||d==a)?i["aıeiouöü".indexOf(j)+c]:(/[aıou]/.test(j))?c?"e":"a":"e";if(f==j){e=(d==k)?"n"+e:(d==a||d==h)?"y"+e:e}if(d==b||d==l){e=(/[fstkçşhp]/.test(f)?"t":"d")+e}if(d==k||d==l){e+="n"}return g+"'"+e};
<|endoftext|>


<commit_before>const fs = require('fs')
const path = require('path')
const glob = require('glob')
const electron = require('electron')
const BrowserWindow = electron.BrowserWindow
var app = electron.app
var mainWindow = null

electron.hideInternalModules()
process.throwDeprecation = true

// Require and setup each JS file in the main-process dir
glob(__dirname + '/main-process/**/*.js', function (error, files) {
  if (error) return console.log(error)
  files.forEach(function (file) {
    eval(fs.readFileSync(file, 'utf8'))
  })
})

function createWindow () {
  var iconPath = path.join(__dirname, '/assets/app-icon/png/512.png')
  mainWindow = new BrowserWindow({ width: 970, 'min-width': 680, height: 900, icon: iconPath })
  mainWindow.loadURL('file://' + __dirname + '/index.html')
  mainWindow.on('closed', function () {
    mainWindow = null
  })
}

app.on('ready', createWindow)

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', function () {
  if (mainWindow === null) {
    createWindow()
  }
})
<commit_msg>use require instead of eval<commit_after>const path = require('path')
const glob = require('glob')
const electron = require('electron')
const BrowserWindow = electron.BrowserWindow
var app = electron.app
var mainWindow = null

electron.hideInternalModules()
process.throwDeprecation = true

// Require and setup each JS file in the main-process dir
glob(__dirname + '/main-process/**/*.js', function (error, files) {
  if (error) return console.log(error)
  files.forEach(function (file) {
    require(file)
  })
})

function createWindow () {
  var iconPath = path.join(__dirname, '/assets/app-icon/png/512.png')
  mainWindow = new BrowserWindow({ width: 970, 'min-width': 680, height: 900, icon: iconPath })
  mainWindow.loadURL('file://' + __dirname + '/index.html')
  mainWindow.on('closed', function () {
    mainWindow = null
  })
}

app.on('ready', createWindow)

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', function () {
  if (mainWindow === null) {
    createWindow()
  }
})
<|endoftext|>


<commit_before>'use strict';

angular.module('core').service('RetentionCalculatorService', [
    function () {

        return {

            getPredictedCardRetention: function(card) {
                if (!card.history || card.history.length === 0) {
                    return 0.0;
                }
                var hist = card.history[card.history.length-1];
                return this.getPredictedRetention(hist.when, hist.hrt, Date.now());

            },

            getPredictedRetention: function(lastRep, hrt, time) {

                //console.log(lastRep);
                //console.log(hrt);
                //console.log(time);
                return Math.exp((time - lastRep) / hrt * Math.log(0.5));
            },

            randomize: function (val) {
                return val * (Math.random() / 10.0 + 1.0);
            },
            initialAssessment: function(assessment) {
                if (assessment === 0) {
                    // 30 s
                    return this.randomize(30 * 1000);
                } else if (assessment === 1) {
                    // 5 min
                    return this.randomize(1000 * 60 * 5);
                } else if (assessment === 2) {
                    // 1 day
                    return this.randomize(1000 * 60 * 60 * 24);
                } else if (assessment === 3) {
                    // 3 days

                    return this.randomize(1000 * 60 * 60 * 24 * 3);

                    // 10 s for debugging
                    //return this.randomize(1000 * 10);
                }
            },
            calculateWeight: function(pr) {
                if (pr >=0.4) {
                    return 5/3 - 1/0.6*pr;
                } else {
                    return 2 - (5/3-1/0.6*pr);
                }
            },

            calculateFor: function (card, time, assessment) {
                console.log(card.question);

                var hrt;

                // setting init values for first iteration
                if (!card.history) {
                    card.history = [];
                }

                if (card.history.length === 0 ) {
                    return this.initialAssessment(assessment);
                }

                var endTime = time;
                var counter = 1;
                var totalWeight = 0;

                //console.log(card.question);

                for (var i = card.history.length-1; i >=0; i--) {
                    console.log('  ',i);
                    var entry = card.history[i];

                    var timeDiff = endTime - entry.when;
                    var pr = this.getPredictedRetention(entry.when, entry.hrt, endTime);
                    console.log('  pr:',pr);
                    var weight = this.calculateWeight(pr);
                    console.log('  w: ',weight);
                    totalWeight += (entry.assessment+1)*weight / (counter*counter);
                    console.log('  tw:',totalWeight);
                    endTime = entry.when;

                    counter++;
                }

                var maximalMultiplicator = 3;

                if (assessment === 3) {

                    // loss than an hour
                    if(card.hrt <= 1000*60*60) {
                        maximalMultiplicator = 50;
                    }

                    // less than a day
                    if(card.hrt > 1000*60*60 && card.hrt <= 1000*60*60*24) {
                        maximalMultiplicator = 25;
                    }

                    // less than a month
                    if(card.hrt > 1000*60*60*24 && card.hrt <= 1000*60*60*24*30) {
                        maximalMultiplicator = 5;
                    }

                    //console.log(totalWeight);
                    return card.hrt*(1+maximalMultiplicator*totalWeight);
                }

                if (assessment === 2) {

                    maximalMultiplicator = 2;

                    return card.hrt*(1+maximalMultiplicator*totalWeight);

                }

                if (assessment === 1) {

                    return card.hrt;

                }

                return this.initialAssessment(assessment);

            }
        };
    }
]);
<commit_msg>bugfix<commit_after>'use strict';

angular.module('core').service('RetentionCalculatorService', [
    function () {

        return {

            getPredictedCardRetention: function(card) {
                if (!card.history || card.history.length === 0) {
                    return 0.0;
                }
                var hist = card.history[card.history.length-1];
                return this.getPredictedRetention(hist.when, hist.hrt, Date.now());

            },

            getPredictedRetention: function(lastRep, hrt, time) {

                //console.log(lastRep);
                //console.log(hrt);
                //console.log(time);
                return Math.exp((time - lastRep) / hrt * Math.log(0.5));
            },

            randomize: function (val) {
                return val * (Math.random() / 10.0 + 1.0);
            },
            initialAssessment: function(assessment) {
                if (assessment === 0) {
                    // 30 s
                    return this.randomize(30 * 1000);
                } else if (assessment === 1) {
                    // 5 min
                    return this.randomize(1000 * 60 * 5);
                } else if (assessment === 2) {
                    // 1 day
                    return this.randomize(1000 * 60 * 60 * 24);
                } else if (assessment === 3) {
                    // 3 days

                    return this.randomize(1000 * 60 * 60 * 24 * 3);

                    // 10 s for debugging
                    //return this.randomize(1000 * 10);
                }
            },
            calculateWeight: function(pr) {
                if (pr >=0.4) {
                    return 5/3 - 1/0.6*pr;
                } else {
                    return 2 - (5/3-1/0.6*pr);
                }
            },

            calculateFor: function (card, time, assessment) {
                console.log(card.question);

                var hrt;

                // setting init values for first iteration
                if (!card.history) {
                    card.history = [];
                }

                if (card.history.length === 0 ) {
                    return this.initialAssessment(assessment);
                }

                var endTime = time;
                var counter = 1;
                var totalWeight = 0;

                //console.log(card.question);

                for (var i = card.history.length-1; i >=0; i--) {
                    console.log('  ',i);
                    var entry = card.history[i];

                    var timeDiff = endTime - entry.when;
                    var pr = this.getPredictedRetention(entry.when, entry.hrt, endTime);
                    console.log('  pr:',pr);
                    var weight = this.calculateWeight(pr);
                    console.log('  w: ',weight);
                    totalWeight += (entry.assessment+1)*weight / (counter*counter);
                    console.log('  tw:',totalWeight);
                    endTime = entry.when;

                    if (counter++ > 3) {
                        break;
                    }
                }

                var maximalMultiplicator = 3;

                if (assessment === 3) {

                    // loss than an hour
                    if(card.hrt <= 1000*60*60) {
                        maximalMultiplicator = 50;
                    }

                    // less than a day
                    if(card.hrt > 1000*60*60 && card.hrt <= 1000*60*60*24) {
                        maximalMultiplicator = 25;
                    }

                    // less than a month
                    if(card.hrt > 1000*60*60*24 && card.hrt <= 1000*60*60*24*30) {
                        maximalMultiplicator = 5;
                    }

                    //console.log(totalWeight);
                    return card.hrt*(1+maximalMultiplicator*totalWeight);
                }

                if (assessment === 2) {

                    maximalMultiplicator = 2;

                    return card.hrt*(1+maximalMultiplicator*totalWeight);

                }

                if (assessment === 1) {

                    return card.hrt;

                }

                return this.initialAssessment(assessment);

            }
        };
    }
]);
<|endoftext|>


<commit_before>var width = 500;
var height = 500;
var canvas = document.getElementById('asteroids');
canvas.width = width;
canvas.height = height;
var context = canvas.getContext('2d');

var rectWidth = width/5;
var rectHeight = height/5;

var x = 0;
var y = 0 - rectHeight;

var movementRate = 1;

function draw(){
	// call clearRect with the entire size of the canvas to clear the whole thing

	// Fill the whole canvas with a black rectangle
	context.fillStyle = "rgb(0, 0, 0)";
	context.fillRect(0, 0, width, height);

	// Draw a triangle with paths
	context.strokeStyle = 'red';

	// Start a new path
	context.beginPath();
	// Now define the path with .moveTo() and .lineTo() methods
	context.moveTo(x, y);
	context.lineTo(x + rectWidth, y);
	context.lineTo(x + rectWidth/2, y + rectHeight);
	context.closePath();

	// The path is only made visible when we call .stroke()
	context.stroke();

	// Update x and y for the next draw operation
	y = y + movementRate;

	window.requestAnimationFrame(draw);
}
window.requestAnimationFrame(draw);<commit_msg>refactoring triangle code to separate function<commit_after>var width = 500;
var height = 500;
var canvas = document.getElementById('asteroids');
canvas.width = width;
canvas.height = height;
var context = canvas.getContext('2d');

var rectWidth = width/5;
var rectHeight = height/5;

var x = 0;
var y = 0 - rectHeight;

var movementRate = 1;

function draw(){
	// call clearRect with the entire size of the canvas to clear the whole thing

	// Fill the whole canvas with a black rectangle
	context.fillStyle = "rgb(0, 0, 0)";
	context.fillRect(0, 0, width, height);

	drawTriangle(context, x, y, rectWidth, rectHeight);

	// Update x and y for the next draw operation
	y = y + movementRate;

	window.requestAnimationFrame(draw);
}
window.requestAnimationFrame(draw);

function drawTriangle(context, x, y, rectWidth, rectHeight){
	// Draw a triangle with paths
	context.strokeStyle = 'red';
	// Start a new path
	context.beginPath();
	// Now define the path with .moveTo() and .lineTo() methods
	context.moveTo(x, y);
	context.lineTo(x + rectWidth, y);
	context.lineTo(x + rectWidth/2, y + rectHeight);
	context.closePath();

	// The path is only made visible when we call .stroke()
	context.stroke();
}<|endoftext|>


<commit_before>import { PolymerElement } from '@polymer/polymer/polymer-element.js';
import { LocalizationMixin } from '../localization-mixin.js';
import { SirenEntityMixin } from '../siren-entity-mixin.js';
import { SirenActionMixin } from '../siren-action-mixin.js';
import { html } from '@polymer/polymer/lib/utils/html-tag.js';

import '../siren-entity.js';
import './note.js';

import '../courses/course-item.js';
import '../content/content-module-card.js';
import '../content/content-activity-item.js';
import '../discussions/discussions-topic-post-item.js';
import '../discussions/discussions-topic-post-list.js';
import '../discussions/discussions-topic.js';

/* @mixes LocalizationMixin
   @mixes SirenEntityMixin
   @mixes SirenActionMixin */
class ContextualNote extends LocalizationMixin(SirenActionMixin(SirenEntityMixin(PolymerElement))) {

	static get template() {
		return html`

		sourceLink: [[sourceLink]]
		<d2l-siren-entity href="[[sourceLink]]" token="[[token]]" entity="{{source}}"></d2l-siren-entity>

			<d2l-note href="[[href]]" token="[[token]]" ></d2l-note>

`;
	}

	static get is() { return 'd2l-contextual-note'; }

	static get properties() {
		return {
			sourceLink: {
				type: String,
				computed: '_getHrefByRel(entity, "https://notes.api.brightspace.com/rels/subject")'
			},
			source: Object,
			sourceType: {
				type: String,
				computed: '_getHandlerForSource(source)'
			}
		};
	}
	static get observers() {
		return [
			'_createInlineHandler(sourceType)'
		];
	}

	_getHrefByRel(entity, rel) {
		const link = (entity && entity.getLinkByRel && entity.getLinkByRel(rel)) || '';
		const href = (link && link.href) || '';
		return (href === 'undefined') ? '' : href;
	}
	_getHandlerForSource(source) {
		const classes_key = source.class && source.class.join('_');
		switch (classes_key) {
			case 'sequenced-activity': {
				return 'd2l-content-activity-item';
			}
			case 'sequence_sequence-description': {
				return 'd2l-content-module-card';
			}
			case 'active_organization':
			case 'active_cohort':
			case 'active_course-offering': {
				return 'd2l-course-item';
			}
			case 'thread_html': {
				return 'd2l-discussions-topic-post-item';
			}
			case 'topic_html': {
				return 'd2l-discussions-topic';
			}
			case 'threads_collection_paged': {
				return 'd2l-discussions-topic-post-list';
			}
			default: {
				return '';
			}
		}
	}
	_createInlineHandler(sourceType) {
		const hook = this.shadowRoot.querySelector('.source-hook');
		hook.innerHTML = '';
		if (!sourceType) {
			return;
		}
		const el = document.createElement(sourceType);
		el.href = this.sourceLink;
		el.token = this.token;

		hook.appendChild(el);
	}
}

window.customElements.define(ContextualNote.is, ContextualNote);
<commit_msg>remove source link<commit_after>import { PolymerElement } from '@polymer/polymer/polymer-element.js';
import { LocalizationMixin } from '../localization-mixin.js';
import { SirenEntityMixin } from '../siren-entity-mixin.js';
import { SirenActionMixin } from '../siren-action-mixin.js';
import { html } from '@polymer/polymer/lib/utils/html-tag.js';

import '../siren-entity.js';
import './note.js';

import '../courses/course-item.js';
import '../content/content-module-card.js';
import '../content/content-activity-item.js';
import '../discussions/discussions-topic-post-item.js';
import '../discussions/discussions-topic-post-list.js';
import '../discussions/discussions-topic.js';

/* @mixes LocalizationMixin
   @mixes SirenEntityMixin
   @mixes SirenActionMixin */
class ContextualNote extends LocalizationMixin(SirenActionMixin(SirenEntityMixin(PolymerElement))) {

	static get template() {
		return html`

		<d2l-siren-entity href="[[sourceLink]]" token="[[token]]" entity="{{source}}"></d2l-siren-entity>

			<d2l-note href="[[href]]" token="[[token]]" ></d2l-note>

`;
	}

	static get is() { return 'd2l-contextual-note'; }

	static get properties() {
		return {
			sourceLink: {
				type: String,
				computed: '_getHrefByRel(entity, "https://notes.api.brightspace.com/rels/subject")'
			},
			source: Object,
			sourceType: {
				type: String,
				computed: '_getHandlerForSource(source)'
			}
		};
	}
	static get observers() {
		return [
			'_createInlineHandler(sourceType)'
		];
	}

	_getHrefByRel(entity, rel) {
		const link = (entity && entity.getLinkByRel && entity.getLinkByRel(rel)) || '';
		const href = (link && link.href) || '';
		return (href === 'undefined') ? '' : href;
	}
	_getHandlerForSource(source) {
		const classes_key = source.class && source.class.join('_');
		switch (classes_key) {
			case 'sequenced-activity': {
				return 'd2l-content-activity-item';
			}
			case 'sequence_sequence-description': {
				return 'd2l-content-module-card';
			}
			case 'active_organization':
			case 'active_cohort':
			case 'active_course-offering': {
				return 'd2l-course-item';
			}
			case 'thread_html': {
				return 'd2l-discussions-topic-post-item';
			}
			case 'topic_html': {
				return 'd2l-discussions-topic';
			}
			case 'threads_collection_paged': {
				return 'd2l-discussions-topic-post-list';
			}
			default: {
				return '';
			}
		}
	}
	_createInlineHandler(sourceType) {
		const hook = this.shadowRoot.querySelector('.source-hook');
		hook.innerHTML = '';
		if (!sourceType) {
			return;
		}
		const el = document.createElement(sourceType);
		el.href = this.sourceLink;
		el.token = this.token;

		hook.appendChild(el);
	}
}

window.customElements.define(ContextualNote.is, ContextualNote);
<|endoftext|>