<commit_before>/*
 * Copyright (c) 2013 Jonathan Rowny. All rights reserved.
 * http://www.jonathanrowny.com
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, brackets, $, Mustache */

define(function (require, exports, module) {

    var _                       = brackets.getModule("thirdparty/lodash"),
        AppInit                 = brackets.getModule("utils/AppInit"),
        Commands                = brackets.getModule("command/Commands"),
        CommandManager          = brackets.getModule("command/CommandManager"),
        EditorManager           = brackets.getModule("editor/EditorManager"),
        DocumentManager         = brackets.getModule("document/DocumentManager"),
        ExtensionUtils          = brackets.getModule("utils/ExtensionUtils"),
        FileSystem              = brackets.getModule("filesystem/FileSystem"),
        KeyBindingManager       = brackets.getModule("command/KeyBindingManager"),
        FileUtils               = brackets.getModule("file/FileUtils"),
        Menus                   = brackets.getModule("command/Menus"),
        PanelManager            = brackets.getModule("view/PanelManager");

    // Local modules
    var InlineSnippetForm = require("src/InlineSnippetForm"),
        Preferences       = require("src/Preferences"),
        SettingsDialog    = require("src/SettingsDialog"),
        SnippetPresets    = require("src/SnippetPresets"),
        panelHtml         = require("text!templates/bottom-panel.html"),
        snippetsHTML      = require("text!templates/snippets-table.html");

        //Snippets array
    var snippets = [],
        //directory where snippets are
        snippetsDirectory = Preferences.get("snippetsDirectory").replace(/\\/g, "/"),
        $snippetsPanel,
        $snippetsContent,
        panel;

    //commands
    var SNIPPET_EXECUTE = "snippets.execute",
        VIEW_HIDE_SNIPPETS = "snippets.hideSnippets";

    function _handleHideSnippets() {
        if (panel.isVisible()) {
            panel.hide();
            CommandManager.get(VIEW_HIDE_SNIPPETS).setChecked(false);
        } else {
            panel.show();
            CommandManager.get(VIEW_HIDE_SNIPPETS).setChecked(true);
        }
        EditorManager.resizeEditor();
    }

    function inlineSnippetFormProvider(hostEditor, props, snippet) {
        var result = new $.Deferred();

        var snippetForm = new InlineSnippetForm(props, snippet);
        snippetForm.load(hostEditor);
        result.resolve(snippetForm);

        return result.promise();
    }

    function _parseArgs(str) {
        str = str.trim();

        var result = [],
            current = "",
            inQuotes = false,
            quotes = ['"', "'"];

        for (var i = 0, l = str.length; i < l; i++) {
            if (str[i] === " " && inQuotes === false) {
                if (current.length > 0) {
                    result.push(current);
                    current = "";
                }
                continue;
            }
            if (inQuotes && str[i] === inQuotes) {
                inQuotes = false;
            }
            if (current.length === 0 && quotes.indexOf(str[i]) !== -1) {
                inQuotes = str[i];
            }
            current += str[i];
        }
        result.push(current);

        return result;
    }

    function _handleSnippet(props) {
        var editor    = EditorManager.getCurrentFullEditor(),
            document  = DocumentManager.getCurrentDocument(),
            pos       = editor.getCursorPos(),
            line      = document.getLine(pos.line),
            preInline = [];

        if (!props) {
            props = _parseArgs(line);
        }

        function completeInsert(editor, pos, output) {
            var s,
                x,
                cursorPos,
                cursorOffset;

            // add back text that was found before inline snippet
            if (preInline.length > 0) {
                output = preInline.join(" ") + " " + output;
            }

            var lines = output.split("\n");

            //figure out cursor pos, remove cursor marker
            for (s = 0; s < lines.length; s++) {
                cursorOffset = lines[s].indexOf('!!{cursor}');
                if (cursorOffset >= 0) {
                    cursorPos = s;
                    output = output.replace('!!{cursor}', '');
                    break;
                }
            }

            //do insertion
            document.replaceRange(output + "\n", {line: pos.line, ch: 0}, {line: pos.line, ch: 0});

            //set cursor
            editor._codeMirror.setCursor(pos.line + cursorPos, cursorOffset);

            //indent lines
            for (x = 0; x < lines.length; x++) {
                editor._codeMirror.indentLine(pos.line + x);
            }

            //give focus back
            EditorManager.focusEditor();
        }
        function startInsert(output) {
            //we don't need to see the trigger text
            CommandManager.execute(Commands.EDIT_DELETE_LINES);

            //find variables
            var tmp = output.match(/\$\$\{[0-9A-Z_a-z]{1,32}\}/g);
             //remove duplicate variables
            var snippetVariables = [],
                j;

            if (tmp && tmp.length > 0) {
                for (j = 0; j < tmp.length; j++) {
                    if ($.inArray(tmp[j], snippetVariables) === -1) {
                        snippetVariables.push(tmp[j]);
                    }
                }
            }

            //if the same number of variables
            if (props.length - 1 >= snippetVariables.length) {
                var x;
                for (x = 0; x < snippetVariables.length; x++) {
                    //even my escapes have escapes
                    var re = new RegExp(snippetVariables[x].replace('$${', '\\$\\$\\{').replace('}', '\\}'), 'g');
                    output = output.replace(re, props[x + 1]);
                }
                completeInsert(editor, pos, output);
            } else {
                var snippetPromise,
                    result = new $.Deferred();
                snippetPromise = inlineSnippetFormProvider(editor, snippetVariables, output);

                snippetPromise.done(function (inlineWidget) {
                    var newPos = {line: pos.line - 1, ch: pos.ch};
                    editor.addInlineWidget(newPos, inlineWidget);
                    var inlineComplete = function () {
                        var z;
                        for (z = 0; z < snippetVariables.length; z++) {
                            //even my escapes have escapes
                            var re = new RegExp(snippetVariables[z].replace('$${', '\\$\\$\\{').replace('}', '\\}'), 'g');
                            output = output.replace(re, inlineWidget.$form.find('.snipvar-' + snippetVariables[z].replace('$${', '').replace('}', '')).val());
                        }

                        completeInsert(editor, pos, output);
                    };
                    inlineWidget.$form.on('complete', function () {
                        inlineComplete();
                        inlineWidget.close();
                    });
                }).fail(function () {
                    result.reject();
                    console.log("Can't create inline snippet form");
                });
            }
        }

        function readSnippetFromFile(fileName) {
            var snippetFilePath = snippetsDirectory + '/snippets/' + fileName;
            FileSystem.resolve(snippetFilePath, function (err, snippetFile) {
                if (err) {
                    FileUtils.showFileOpenError(err, snippetFilePath);
                    return;
                }

                snippetFile.read(function (err, text) {
                    if (err) {
                        FileUtils.showFileOpenError(err, snippetFile.fullPath);
                        return;
                    }

                    startInsert(SnippetPresets.execute(text));
                });
            });
        }

        if (props.length) {
            //try to find the snippet, given the trigger text
            var i,
                triggers = _.pluck(snippets, "trigger");
            //go in backwards order for a case there is an inline snippet along the way
            for (i = props.length - 1; i > 0; i--) {

                var io,
                    requireInline = true;

                // launch non-inline in inline mode snippets when %trigger is found
                if (props[i][0] === "%") {
                    requireInline = false;
                    io = triggers.indexOf(props[i].substring(1));
                } else {
                    io = triggers.indexOf(props[i]);
                }

                if (io !== -1 && (snippets[io].inline || !requireInline)) {
                    // found inline snippet
                    preInline = props.slice(0, i);
                    props = props.slice(i);
                    startInsert(SnippetPresets.execute(snippets[io].template));
                    return;
                }
            }
            //no inline snippet found so look for any snippet that matches props[0]
            //it can also have % as a prefix so remove
            if (props[0][0] === "%") {
                props[0] = props[0].substring(1);
            }
            var snippet = _.find(snippets, function (s) {
                return s.trigger === props[0];
            });
            if (snippet) {
                var output = snippet.template;
                if (output.indexOf('.snippet') === output.length - 8) {
                    readSnippetFromFile(output);
                } else {
                    startInsert(SnippetPresets.execute(output));
                }
            }
        }
    }

    //builds the snippets table
    function setupSnippets() {
        var s = Mustache.render(panelHtml);
        panel = PanelManager.createBottomPanel(VIEW_HIDE_SNIPPETS, $(s), 100);
        panel.hide();

        $snippetsPanel = $('#snippets');
        $snippetsContent = $snippetsPanel.find(".resizable-content");
        $snippetsPanel
            .on("click", ".snippets-settings", function () {
                SettingsDialog.show();
            })
            .on("click", ".snippets-close", function () {
                CommandManager.execute(VIEW_HIDE_SNIPPETS);
            });
    }

    function finalizeSnippetsTable() {
        var i,
            len,
            $snippetsTable;
        for (i = 0, len = arguments.length; i < len; i++) {
            if (arguments[i] && arguments[i].length) {
                snippets = snippets.concat(arguments[i]);
            }
        }
        $snippetsTable = Mustache.render(snippetsHTML, {"snippets" : snippets});
        $snippetsPanel.find('.resizable-content').append($snippetsTable);
        $snippetsPanel.find('.snippets-trigger').on('click', function () {
            CommandManager.execute(SNIPPET_EXECUTE, [$(this).attr('data-trigger')]);
        });
        $snippetsPanel.find('.snippets-source').on('click', function () {
            CommandManager.execute(Commands.FILE_OPEN, { fullPath: snippetsDirectory + "/" + $(this).attr('data-source') });
        });
    }

    //parse a JSON file with a snippet in it
    function loadSnippet(fileEntry) {
        var result = new $.Deferred();
        fileEntry.read(function (err, text) {
            if (err) {
                FileUtils.showFileOpenError(err, fileEntry.fullPath);
                result.reject(err);
                return;
            }

            try {
                //TODO: a better check for valid snippets
                var newSnippets = JSON.parse(text);
                newSnippets.forEach(function (item) {
                    item.source = fileEntry.name;
                });
                result.resolve(newSnippets);
            } catch (err) {
                console.error("Can't parse snippets from " + fileEntry.fullPath + " - " + err);
                result.reject(err);
            }
        });
        return result;
    }

    CommandManager.register("Run Snippet", SNIPPET_EXECUTE, _handleSnippet);
    CommandManager.register("Show Snippets", VIEW_HIDE_SNIPPETS, _handleHideSnippets);

    function loadSnippets() {
        if (!FileSystem.isAbsolutePath(snippetsDirectory)) {
            snippetsDirectory = FileUtils.getNativeModuleDirectoryPath(module) + "/" + snippetsDirectory;
        }
        //loop through the directory to load snippets
        FileSystem.resolve(snippetsDirectory, function (err, rootEntry) {
            if (err) {
                console.error("[Snippets] Error -- could not open snippets directory: " + snippetsDirectory);
                console.error(err);
                return;
            }

            rootEntry.getContents(function (err, entries) {
                if (err) {
                    console.error("[Snippets] Error -- could not read snippets directory: " + snippetsDirectory);
                    console.error(err);
                    return;
                }

                var loading = _.compact(entries.map(function (entry) {
                    if (entry.name.charAt(0) === ".") {
                        //ignore dotfiles
                        return;
                    }
                    if (entry.isDirectory) {
                        //ignore directories
                        return;
                    }
                    return loadSnippet(entry);
                }));

                $.when.apply(module, loading).done(finalizeSnippetsTable);
            });
        });
    }

    AppInit.appReady(function () {
        //add the HTML UI
        setupSnippets();

        //load css
        ExtensionUtils.loadStyleSheet(module, "styles/snippets.css");

        //add the menu and keybinding for view/hide
        var menu = Menus.getMenu(Menus.AppMenuBar.VIEW_MENU);
        menu.addMenuItem(VIEW_HIDE_SNIPPETS, Preferences.get("showSnippetsPanelShortcut"), Menus.AFTER, Commands.VIEW_HIDE_SIDEBAR);

        // Add toolbar icon
        $("<a>")
            .attr({
                id: "snippets-enable-icon",
                href: "#"
            })
            .click(_handleHideSnippets)
            .appendTo($("#main-toolbar .buttons"));

        //add the keybinding
        KeyBindingManager.addBinding(SNIPPET_EXECUTE, Preferences.get("triggerSnippetShortcut"));

        //load snippets
        loadSnippets();
    });

});
<commit_msg>Fix snippets deleting trailing text<commit_after>/*
 * Copyright (c) 2013 Jonathan Rowny. All rights reserved.
 * http://www.jonathanrowny.com
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define, brackets, $, Mustache */

define(function (require, exports, module) {

    var _                       = brackets.getModule("thirdparty/lodash"),
        AppInit                 = brackets.getModule("utils/AppInit"),
        Commands                = brackets.getModule("command/Commands"),
        CommandManager          = brackets.getModule("command/CommandManager"),
        EditorManager           = brackets.getModule("editor/EditorManager"),
        DocumentManager         = brackets.getModule("document/DocumentManager"),
        ExtensionUtils          = brackets.getModule("utils/ExtensionUtils"),
        FileSystem              = brackets.getModule("filesystem/FileSystem"),
        KeyBindingManager       = brackets.getModule("command/KeyBindingManager"),
        FileUtils               = brackets.getModule("file/FileUtils"),
        Menus                   = brackets.getModule("command/Menus"),
        PanelManager            = brackets.getModule("view/PanelManager");

    // Local modules
    var InlineSnippetForm = require("src/InlineSnippetForm"),
        Preferences       = require("src/Preferences"),
        SettingsDialog    = require("src/SettingsDialog"),
        SnippetPresets    = require("src/SnippetPresets"),
        panelHtml         = require("text!templates/bottom-panel.html"),
        snippetsHTML      = require("text!templates/snippets-table.html");

        //Snippets array
    var snippets = [],
        //directory where snippets are
        snippetsDirectory = Preferences.get("snippetsDirectory").replace(/\\/g, "/"),
        $snippetsPanel,
        $snippetsContent,
        panel;

    //commands
    var SNIPPET_EXECUTE = "snippets.execute",
        VIEW_HIDE_SNIPPETS = "snippets.hideSnippets";

    function _handleHideSnippets() {
        if (panel.isVisible()) {
            panel.hide();
            CommandManager.get(VIEW_HIDE_SNIPPETS).setChecked(false);
        } else {
            panel.show();
            CommandManager.get(VIEW_HIDE_SNIPPETS).setChecked(true);
        }
        EditorManager.resizeEditor();
    }

    function inlineSnippetFormProvider(hostEditor, props, snippet) {
        var result = new $.Deferred();

        var snippetForm = new InlineSnippetForm(props, snippet);
        snippetForm.load(hostEditor);
        result.resolve(snippetForm);

        return result.promise();
    }

    function _parseArgs(str) {
        str = str.trim();

        var result = [],
            current = "",
            inQuotes = false,
            quotes = ['"', "'"];

        for (var i = 0, l = str.length; i < l; i++) {
            if (str[i] === " " && inQuotes === false) {
                if (current.length > 0) {
                    result.push(current);
                    current = "";
                }
                continue;
            }
            if (inQuotes && str[i] === inQuotes) {
                inQuotes = false;
            }
            if (current.length === 0 && quotes.indexOf(str[i]) !== -1) {
                inQuotes = str[i];
            }
            current += str[i];
        }
        result.push(current);

        return result;
    }

    function _handleSnippet(props) {
        var editor     = EditorManager.getCurrentFullEditor(),
            document   = DocumentManager.getCurrentDocument(),
            pos        = editor.getCursorPos(),
            line       = document.getLine(pos.line),
            preInline  = null,
            postInline = null;

        if (!props) {
            props = _parseArgs(line);
        }

        function completeInsert(editor, pos, output) {
            var s,
                x,
                cursorPos,
                cursorOffset;

            // add back text that was found before inline snippet
            if (preInline) {
                output = preInline.join(" ") + " " + output;
            }
            if (postInline) {
                output = output + " " + postInline.join(" ");
            }

            var lines = output.split("\n");

            //figure out cursor pos, remove cursor marker
            for (s = 0; s < lines.length; s++) {
                cursorOffset = lines[s].indexOf('!!{cursor}');
                if (cursorOffset >= 0) {
                    cursorPos = s;
                    output = output.replace('!!{cursor}', '');
                    break;
                }
            }

            //do insertion
            document.replaceRange(output + "\n", {line: pos.line, ch: 0}, {line: pos.line, ch: 0});

            //set cursor
            editor._codeMirror.setCursor(pos.line + cursorPos, cursorOffset);

            //indent lines
            for (x = 0; x < lines.length; x++) {
                editor._codeMirror.indentLine(pos.line + x);
            }

            //give focus back
            EditorManager.focusEditor();
        }
        function startInsert(output) {
            //we don't need to see the trigger text
            CommandManager.execute(Commands.EDIT_DELETE_LINES);

            //find variables
            var tmp = output.match(/\$\$\{[0-9A-Z_a-z]{1,32}\}/g);
             //remove duplicate variables
            var snippetVariables = [],
                j;

            if (tmp && tmp.length > 0) {
                for (j = 0; j < tmp.length; j++) {
                    if ($.inArray(tmp[j], snippetVariables) === -1) {
                        snippetVariables.push(tmp[j]);
                    }
                }
            }

            var variablesDifference = props.length - 1 - snippetVariables.length;

            if (variablesDifference > 0) {
                // we have more variables than we require
                var mid = snippetVariables.length + 1;
                postInline = props.slice(mid);
                props = props.slice(0, mid);
                variablesDifference = 0;
            }

            if (variablesDifference === 0) {
                // we have exactly as many variables as we need
                for (var x = 0; x < snippetVariables.length; x++) {
                    //even my escapes have escapes
                    var re = new RegExp(snippetVariables[x].replace('$${', '\\$\\$\\{').replace('}', '\\}'), 'g');
                    output = output.replace(re, props[x + 1]);
                }
                completeInsert(editor, pos, output);
            } else {
                // we have less variables than we need
                var snippetPromise,
                    result = new $.Deferred();
                snippetPromise = inlineSnippetFormProvider(editor, snippetVariables, output);

                snippetPromise.done(function (inlineWidget) {
                    var newPos = {line: pos.line - 1, ch: pos.ch};
                    editor.addInlineWidget(newPos, inlineWidget);
                    var inlineComplete = function () {
                        var z;
                        for (z = 0; z < snippetVariables.length; z++) {
                            //even my escapes have escapes
                            var re = new RegExp(snippetVariables[z].replace('$${', '\\$\\$\\{').replace('}', '\\}'), 'g');
                            output = output.replace(re, inlineWidget.$form.find('.snipvar-' + snippetVariables[z].replace('$${', '').replace('}', '')).val());
                        }

                        completeInsert(editor, pos, output);
                    };
                    inlineWidget.$form.on('complete', function () {
                        inlineComplete();
                        inlineWidget.close();
                    });
                }).fail(function () {
                    result.reject();
                    console.log("Can't create inline snippet form");
                });
            }
        }

        function readSnippetFromFile(fileName) {
            var snippetFilePath = snippetsDirectory + '/snippets/' + fileName;
            FileSystem.resolve(snippetFilePath, function (err, snippetFile) {
                if (err) {
                    FileUtils.showFileOpenError(err, snippetFilePath);
                    return;
                }

                snippetFile.read(function (err, text) {
                    if (err) {
                        FileUtils.showFileOpenError(err, snippetFile.fullPath);
                        return;
                    }

                    startInsert(SnippetPresets.execute(text));
                });
            });
        }

        if (props.length) {
            //try to find the snippet, given the trigger text
            var i,
                triggers = _.pluck(snippets, "trigger");
            //go in backwards order for a case there is an inline snippet along the way
            for (i = props.length - 1; i > 0; i--) {

                var io,
                    requireInline = true;

                // launch non-inline in inline mode snippets when %trigger is found
                if (props[i][0] === "%") {
                    requireInline = false;
                    io = triggers.indexOf(props[i].substring(1));
                } else {
                    io = triggers.indexOf(props[i]);
                }

                if (io !== -1 && (snippets[io].inline || !requireInline)) {
                    // found inline snippet
                    preInline = props.slice(0, i);
                    props = props.slice(i);
                    startInsert(SnippetPresets.execute(snippets[io].template));
                    return;
                }
            }
            //no inline snippet found so look for any snippet that matches props[0]
            //it can also have % as a prefix so remove
            if (props[0][0] === "%") {
                props[0] = props[0].substring(1);
            }
            var snippet = _.find(snippets, function (s) {
                return s.trigger === props[0];
            });
            if (snippet) {
                var output = snippet.template;
                if (output.indexOf('.snippet') === output.length - 8) {
                    readSnippetFromFile(output);
                } else {
                    startInsert(SnippetPresets.execute(output));
                }
            }
        }
    }

    //builds the snippets table
    function setupSnippets() {
        var s = Mustache.render(panelHtml);
        panel = PanelManager.createBottomPanel(VIEW_HIDE_SNIPPETS, $(s), 100);
        panel.hide();

        $snippetsPanel = $('#snippets');
        $snippetsContent = $snippetsPanel.find(".resizable-content");
        $snippetsPanel
            .on("click", ".snippets-settings", function () {
                SettingsDialog.show();
            })
            .on("click", ".snippets-close", function () {
                CommandManager.execute(VIEW_HIDE_SNIPPETS);
            });
    }

    function finalizeSnippetsTable() {
        var i,
            len,
            $snippetsTable;
        for (i = 0, len = arguments.length; i < len; i++) {
            if (arguments[i] && arguments[i].length) {
                snippets = snippets.concat(arguments[i]);
            }
        }
        $snippetsTable = Mustache.render(snippetsHTML, {"snippets" : snippets});
        $snippetsPanel.find('.resizable-content').append($snippetsTable);
        $snippetsPanel.find('.snippets-trigger').on('click', function () {
            CommandManager.execute(SNIPPET_EXECUTE, [$(this).attr('data-trigger')]);
        });
        $snippetsPanel.find('.snippets-source').on('click', function () {
            CommandManager.execute(Commands.FILE_OPEN, { fullPath: snippetsDirectory + "/" + $(this).attr('data-source') });
        });
    }

    //parse a JSON file with a snippet in it
    function loadSnippet(fileEntry) {
        var result = new $.Deferred();
        fileEntry.read(function (err, text) {
            if (err) {
                FileUtils.showFileOpenError(err, fileEntry.fullPath);
                result.reject(err);
                return;
            }

            try {
                //TODO: a better check for valid snippets
                var newSnippets = JSON.parse(text);
                newSnippets.forEach(function (item) {
                    item.source = fileEntry.name;
                });
                result.resolve(newSnippets);
            } catch (err) {
                console.error("Can't parse snippets from " + fileEntry.fullPath + " - " + err);
                result.reject(err);
            }
        });
        return result;
    }

    CommandManager.register("Run Snippet", SNIPPET_EXECUTE, _handleSnippet);
    CommandManager.register("Show Snippets", VIEW_HIDE_SNIPPETS, _handleHideSnippets);

    function loadSnippets() {
        if (!FileSystem.isAbsolutePath(snippetsDirectory)) {
            snippetsDirectory = FileUtils.getNativeModuleDirectoryPath(module) + "/" + snippetsDirectory;
        }
        //loop through the directory to load snippets
        FileSystem.resolve(snippetsDirectory, function (err, rootEntry) {
            if (err) {
                console.error("[Snippets] Error -- could not open snippets directory: " + snippetsDirectory);
                console.error(err);
                return;
            }

            rootEntry.getContents(function (err, entries) {
                if (err) {
                    console.error("[Snippets] Error -- could not read snippets directory: " + snippetsDirectory);
                    console.error(err);
                    return;
                }

                var loading = _.compact(entries.map(function (entry) {
                    if (entry.name.charAt(0) === ".") {
                        //ignore dotfiles
                        return;
                    }
                    if (entry.isDirectory) {
                        //ignore directories
                        return;
                    }
                    return loadSnippet(entry);
                }));

                $.when.apply(module, loading).done(finalizeSnippetsTable);
            });
        });
    }

    AppInit.appReady(function () {
        //add the HTML UI
        setupSnippets();

        //load css
        ExtensionUtils.loadStyleSheet(module, "styles/snippets.css");

        //add the menu and keybinding for view/hide
        var menu = Menus.getMenu(Menus.AppMenuBar.VIEW_MENU);
        menu.addMenuItem(VIEW_HIDE_SNIPPETS, Preferences.get("showSnippetsPanelShortcut"), Menus.AFTER, Commands.VIEW_HIDE_SIDEBAR);

        // Add toolbar icon
        $("<a>")
            .attr({
                id: "snippets-enable-icon",
                href: "#"
            })
            .click(_handleHideSnippets)
            .appendTo($("#main-toolbar .buttons"));

        //add the keybinding
        KeyBindingManager.addBinding(SNIPPET_EXECUTE, Preferences.get("triggerSnippetShortcut"));

        //load snippets
        loadSnippets();
    });

});
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    for (var counter = 0; counter < length; counter++)
    {
      var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
      var args = ['commit', outFile, '-m', message]
      fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
      sleep(Math.random() * max_sleep)
      child_process.execFileSync('/usr/bin/git', args)
    }
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [time in seconds]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (<commit_msg>Fixing a typo added in the last readme update<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    for (var counter = 0; counter < length; counter++)
    {
      var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
      var args = ['commit', outFile, '-m', message]
      fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
      sleep(Math.random() * max_sleep)
      child_process.execFileSync('/usr/bin/git', args)
    }
  })
} else {
  console.info("Usage:")
  console.info("node commit.js infile outfile [time in seconds]")
}

function sleep(seconds) {
  var endTime = new Date().getTime() + (s<|endoftext|>


<commit_before>const electron = require('electron');
const {clipboard} = require('electron');
const {shell} = require('electron');
const SettingsFile = require('./application/SettingsFile');
const ChannelCheck = require('./application/ChannelCheck');
const ChannelPlay = require('./application/ChannelPlay');
const Notifications = require('./application/Notifications');

let settingsJson = new SettingsFile().readFile();

require('electron-handlebars')({
    channels: settingsJson.channels,
    settings: settingsJson.settings,
    version: require('./package.json').version
});

let ipcMain = electron.ipcMain;

ipcMain.on('add-channel', (event, channel) => {
    let channelObj = new SettingsFile().addChannel(channel.link);

    if (channelObj === false) {
        event.sender.send('add-channel-response', {status: false});
        return;
    }

    console.log('channel ' + channelObj.name + ' was added');

    event.sender.send('add-channel-response', {status: true, channel: channelObj});
});

ipcMain.on('channel-play', (event, channel) => {
    new ChannelPlay().launchPlayerLink(channel.link, channel.LQ);
});

ipcMain.on('open-page', (event, channel) => {
    if (channel.indexOf('klpq.men') >= 0) {
        shell.openExternal('http://stream.klpq.men/');
    }

    if (channel.startsWith('http')) {
        shell.openExternal(channel);
    }
});

ipcMain.on('open-chat', (event, channel) => {
    if (channel.indexOf('klpq.men') >= 0) {
        shell.openExternal('http://stream.klpq.men/chat/');
    }

    if (channel.startsWith('http')) {
        shell.openExternal(channel + '/chat');
    }
});

ipcMain.on('copy-clipboard', (event, channel) => {
    clipboard.writeText(channel);
});

ipcMain.on('remove-channel', (event, channel) => {
    let result = new SettingsFile().removeChannel(channel);

    console.log('channel ' + channel + ' was removed');

    event.sender.send('remove-channel-response', {status: result, channelLink: channel});
});

ipcMain.on('twitch-import', (event, channel) => {
    console.log('log - ' + channel);

    new ChannelCheck().twitchImport(channel);
});

ipcMain.on('change-setting', (event, setting) => {
    new SettingsFile().changeSetting(setting.name, setting.value);

    console.log('setting ' + setting.name + ' changed to ' + setting.value);
});

const app = electron.app;
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow;

const path = require('path');
const url = require('url');

let iconPath = process.platform === 'win32' ? 'icon.ico' : 'icon.png';

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;

function createWindow() {
    // Create the browser window.
    mainWindow = new BrowserWindow({
        title: 'Kolpaque Client',
        width: 400,
        height: 667,
        resizable: false,
        fullscreenable: false,
        icon: path.normalize(path.join(__dirname, iconPath))
    });

    mainWindow.setMenu(null);

    // and load the index.html of the app.
    mainWindow.loadURL(url.format({
        pathname: path.join(__dirname, 'index.hbs'),
        protocol: 'file:',
        slashes: true
    }));

    // Open the DevTools.
    //mainWindow.webContents.openDevTools();

    mainWindow.on('minimize', function () {
        mainWindow.hide();
    });

    mainWindow.on('close', function () {
        new SettingsFile().saveFile();
    });

    mainWindow.on('close', function (e) {
        if (process.platform === 'darwin') {
            e.preventDefault();
            mainWindow.hide();
        }
    });

    // Emitted when the window is closed.
    mainWindow.on('closed', function () {
        // Dereference the window object, usually you would store windows
        // in an array if your app supports multi windows, this is the time
        // when you should delete the corresponding element.

        mainWindow = null
    });

    new ChannelCheck().checkLoop(mainWindow);
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow);

// Quit when all windows are closed.
app.on('window-all-closed', function () {
    // On OS X it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q
    if (process.platform !== 'darwin') {
        app.quit()
    }
});

app.on('activate', function () {
    // On OS X it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (mainWindow === null) {
        createWindow()
    }
});

app.on('ready', function () {
    if (!settingsJson.settings.minimizeAtStart)
        return;

    mainWindow.hide();
});

const {Menu, Tray, nativeImage} = require('electron');

let appIcon = null;
app.on('ready', () => {
    appIcon = new Tray(nativeImage.createFromPath(path.normalize(path.join(__dirname, iconPath))));
    appIcon.setToolTip('Kolpaque Client');

    let contextMenuTemplate = [
        {
            label: 'Toggle Client', type: 'normal', click: () => {
            mainWindow.isVisible() ? mainWindow.hide() : mainWindow.show()
        }
        },
        {
            label: 'Online Channels', type: 'submenu', submenu: []
        },
        {
            label: 'Play from Clipboard', type: 'normal', click: () => {
            new ChannelPlay().launchPlayerLink(clipboard.readText());
        }
        },
        {
            label: 'Close Client', type: 'normal', click: () => {
            app.quit();
        }
        }
    ];

    let contextMenu = Menu.buildFromTemplate(contextMenuTemplate);

    appIcon.on('click', () => {
        mainWindow.isVisible() ? mainWindow.hide() : mainWindow.show()
    });

    appIcon.on('balloon-click', function () {
        new Notifications().onBalloonClick(ChannelPlay);
    });

    // Call this again for Linux because we modified the context menu
    appIcon.setContextMenu(contextMenu);

    new Notifications().takeIconReference(appIcon, contextMenuTemplate);
});

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
<commit_msg>Added force close for mac.<commit_after>const electron = require('electron');
const {clipboard} = require('electron');
const {shell} = require('electron');
const SettingsFile = require('./application/SettingsFile');
const ChannelCheck = require('./application/ChannelCheck');
const ChannelPlay = require('./application/ChannelPlay');
const Notifications = require('./application/Notifications');

let settingsJson = new SettingsFile().readFile();
let forceQuit = false;

require('electron-handlebars')({
    channels: settingsJson.channels,
    settings: settingsJson.settings,
    version: require('./package.json').version
});

let ipcMain = electron.ipcMain;

ipcMain.on('add-channel', (event, channel) => {
    let channelObj = new SettingsFile().addChannel(channel.link);

    if (channelObj === false) {
        event.sender.send('add-channel-response', {status: false});
        return;
    }

    console.log('channel ' + channelObj.name + ' was added');

    event.sender.send('add-channel-response', {status: true, channel: channelObj});
});

ipcMain.on('channel-play', (event, channel) => {
    new ChannelPlay().launchPlayerLink(channel.link, channel.LQ);
});

ipcMain.on('open-page', (event, channel) => {
    if (channel.indexOf('klpq.men') >= 0) {
        shell.openExternal('http://stream.klpq.men/');
    }

    if (channel.startsWith('http')) {
        shell.openExternal(channel);
    }
});

ipcMain.on('open-chat', (event, channel) => {
    if (channel.indexOf('klpq.men') >= 0) {
        shell.openExternal('http://stream.klpq.men/chat/');
    }

    if (channel.startsWith('http')) {
        shell.openExternal(channel + '/chat');
    }
});

ipcMain.on('copy-clipboard', (event, channel) => {
    clipboard.writeText(channel);
});

ipcMain.on('remove-channel', (event, channel) => {
    let result = new SettingsFile().removeChannel(channel);

    console.log('channel ' + channel + ' was removed');

    event.sender.send('remove-channel-response', {status: result, channelLink: channel});
});

ipcMain.on('twitch-import', (event, channel) => {
    console.log('log - ' + channel);

    new ChannelCheck().twitchImport(channel);
});

ipcMain.on('change-setting', (event, setting) => {
    new SettingsFile().changeSetting(setting.name, setting.value);

    console.log('setting ' + setting.name + ' changed to ' + setting.value);
});

const app = electron.app;
// Module to create native browser window.
const BrowserWindow = electron.BrowserWindow;

const path = require('path');
const url = require('url');

let iconPath = process.platform === 'win32' ? 'icon.ico' : 'icon.png';

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow;

function createWindow() {
    // Create the browser window.
    mainWindow = new BrowserWindow({
        title: 'Kolpaque Client',
        width: 400,
        height: 667,
        resizable: false,
        fullscreenable: false,
        icon: path.normalize(path.join(__dirname, iconPath))
    });

    mainWindow.setMenu(null);

    // and load the index.html of the app.
    mainWindow.loadURL(url.format({
        pathname: path.join(__dirname, 'index.hbs'),
        protocol: 'file:',
        slashes: true
    }));

    // Open the DevTools.
    //mainWindow.webContents.openDevTools();

    mainWindow.on('minimize', function () {
        mainWindow.hide();
    });

    mainWindow.on('close', function () {
        new SettingsFile().saveFile();
    });

    mainWindow.on('close', function (e) {
        console.log(forceQuit);

        if (forceQuit)
            return;

        if (process.platform === 'darwin') {
            e.preventDefault();
            mainWindow.hide();
        }
    });

    // Emitted when the window is closed.
    mainWindow.on('closed', function () {
        // Dereference the window object, usually you would store windows
        // in an array if your app supports multi windows, this is the time
        // when you should delete the corresponding element.

        mainWindow = null
    });

    new ChannelCheck().checkLoop(mainWindow);
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow);

// Quit when all windows are closed.
app.on('window-all-closed', function () {
    // On OS X it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q

    if (process.platform !== 'darwin') {
        app.quit()
    }
});

app.on('activate', function () {
    // On OS X it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (mainWindow === null) {
        createWindow()
    }
});

app.on('ready', function () {
    if (!settingsJson.settings.minimizeAtStart)
        return;

    mainWindow.hide();
});

const {Menu, Tray, nativeImage} = require('electron');

let appIcon = null;
app.on('ready', () => {
    appIcon = new Tray(nativeImage.createFromPath(path.normalize(path.join(__dirname, iconPath))));
    appIcon.setToolTip('Kolpaque Client');

    let contextMenuTemplate = [
        {
            label: 'Toggle Client', type: 'normal', click: () => {
            mainWindow.isVisible() ? mainWindow.hide() : mainWindow.show()
        }
        },
        {
            label: 'Online Channels', type: 'submenu', submenu: []
        },
        {
            label: 'Play from Clipboard', type: 'normal', click: () => {
            new ChannelPlay().launchPlayerLink(clipboard.readText());
        }
        },
        {
            label: 'Close Client', type: 'normal', click: () => {
            forceQuit = true;
            app.quit();
        }
        }
    ];

    let contextMenu = Menu.buildFromTemplate(contextMenuTemplate);

    appIcon.on('click', () => {
        mainWindow.isVisible() ? mainWindow.hide() : mainWindow.show()
    });

    appIcon.on('balloon-click', function () {
        new Notifications().onBalloonClick(ChannelPlay);
    });

    // Call this again for Linux because we modified the context menu
    appIcon.setContextMenu(contextMenu);

    new Notifications().takeIconReference(appIcon, contextMenuTemplate);
});

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",<commit_msg>Almost there<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ <commit_msg>Fixing a typo added in the last readme update<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the<commit_msg>Really commit all the required changes<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the <|endoftext|>


<commit_before>const {
  app,
  BrowserWindow,
  ipcMain
} = require('electron')
const { platform } = require('os')
const { join }     = require('path')

let win
app.on('ready', () => {
  win = new BrowserWindow({
    width:800,
    height: 600,
    show: false,
    frame: false,
    transparent: platform() == 'darwin' ? true : false,
    titleBarStyle : 'hidden-inset',
    icon: join(__dirname, 'parts', 'icon.png')
  })

  win.setMenu(null)
  win.loadURL(`file://${__dirname}/dist/index.html`)

  // Show devtools only if you're in development mode
  if(process.env.NODE_ENV == 'development') win.webContents.openDevTools()
})

ipcMain.on('ready', () => {
  win.show()
  win.focus()
})

ipcMain.on('bootstrap_error', () => {
  win.show()
  win.webContents.openDevTools()
})
<commit_msg>:art: Make the app always transparent<commit_after>const {
  app,
  BrowserWindow,
  ipcMain
} = require('electron')
const { join }     = require('path')

let win
app.on('ready', () => {
  win = new BrowserWindow({
    width:800,
    height: 600,
    show: false,
    frame: false,
    transparent: true,
    titleBarStyle : 'hidden-inset',
    icon: join(__dirname, 'parts', 'icon.png')
  })

  win.setMenu(null)
  win.loadURL(`file://${__dirname}/dist/index.html`)

  // Show devtools only if you're in development mode
  if(process.env.NODE_ENV == 'development') win.webContents.openDevTools()
})

ipcMain.on('ready', () => {
  win.show()
  win.focus()
})

ipcMain.on('bootstrap_error', () => {
  win.show()
  win.webContents.openDevTools()
})
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outF<commit_msg>Update character<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFi<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found<commit_msg>GET A HAIRCUT!<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found <|endoftext|>


<commit_before>'use strict'

const electron = require('electron')
const app = electron.app
const BrowserWindow = electron.BrowserWindow

// for auto reloading in dev env
//require('electron-reload')(__dirname)

const path = require('path')
const url = require('url')

// Main window
let mainWindow

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 1024,
    height: 800,
    webPreferences: {
      // nodeIntegration: false,
      preload: path.join(__dirname, 'preload.js')
    }
  })

  // use index.html as main page
  mainWindow.loadURL(url.format({
    pathname: path.join(__dirname, 'index.html'),
    protocol: 'file:',
    slashes: true
  }))

  // invoke dev tools
  console.log(process.env.NODE_ENV)
  if(process.env.NODE_ENV == 'develop') {
    mainWindow.webContents.openDevTools()
  }

  // window is closed
  mainWindow.on('closed', function () {
    mainWindow = null
  })
}

//  app is ready
app.on('ready', createWindow)

// all windows are closed
app.on('window-all-closed', function () {
  // macOSのとき以外はアプリケーションを終了させます
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// application is activated. [Mac] The dock icon is clicked.
app.on('activate', function () {
  /// when we dont have main window, create it.
  if (mainWindow === null) {
    createWindow()
  }
})
<commit_msg>Fix eslint<commit_after>'use strict'

const electron = require('electron')
const app = electron.app
const BrowserWindow = electron.BrowserWindow

// for auto reloading in dev env
// require('electron-reload')(__dirname)

const path = require('path')
const url = require('url')

// Main window
let mainWindow

function createWindow () {
  mainWindow = new BrowserWindow({
    width: 1024,
    height: 800,
    webPreferences: {
      // nodeIntegration: false,
      preload: path.join(__dirname, 'preload.js')
    }
  })

  // use index.html as main page
  mainWindow.loadURL(url.format({
    pathname: path.join(__dirname, 'index.html'),
    protocol: 'file:',
    slashes: true
  }))

  // invoke dev tools
  console.log(process.env.NODE_ENV)
  if (process.env.NODE_ENV === 'develop') {
    mainWindow.webContents.openDevTools()
  }

  // window is closed
  mainWindow.on('closed', function () {
    mainWindow = null
  })
}

//  app is ready
app.on('ready', createWindow)

// all windows are closed
app.on('window-all-closed', function () {
  // macOSのとき以外はアプリケーションを終了させます
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// application is activated. [Mac] The dock icon is clicked.
app.on('activate', function () {
  // when we dont have main window, create it.
  if (mainWindow === null) {
    createWindow()
  }
})
<|endoftext|>


<commit_before>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    for (var counter = 0; counter < length; counter++)
    {
      var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
      var args = ['commit', outFile, '-m', message]
      fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
      sleep(Math.random() * max_sleep)
      child_process.execFileSync('/usr/bin/git', args)
    }
  <commit_msg>AAAAAAAAAAARGH!<commit_after>var fs = require('fs');
var child_process = require('child_process')
var max_sleep = 300
//Added a comment that achieves no real goal.

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    console.info("Bytes: %s", length)
    try {
      child_process.execFileSync('/usr/bin/git', ['add', outFile])
    } catch (e) {
      console.error("Couldn't add %s to git: %s", outFile, e)
    }
    var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
    var args = ['commit', outFile, '-m', message]
    for (var counter = 0; counter < length; counter++)
    {
      var message = commit_messages[randomIntFromInterval(0, commit_messages.length - 1)]
      var args = ['commit', outFile, '-m', message]
      fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1)
      sleep(Math.random() * max_sleep)
      child_process.execFileSync('/usr/bin/git', args)
    }
  }<|endoftext|>


<commit_before>import Vue, { h as v3h } from 'vue'
import * as mdi from '@mdi/js'
import './icons.css'

const vueVersion = Vue === undefined ? 3 : 2;
const isV2 = vueVersion === 2

const versionDependentOpts = Vue
  ? { functional: true } // for v2.x
  : {} // for v3.x

const ucFirst = (str) => str.charAt(0).toUpperCase() + str.slice(1)

function render(v2h, v2ctx) {
  const data = isV2 ? v2ctx.data : this
  const props = isV2 ? v2ctx.props : this
  const attrs = isV2 ? v2ctx.attrs : this.$attrs
  const h = isV2 ? v2h : v3h
  const iconPath = mdi[`mdi${ucFirst(props.name)}`] || mdi.mdiAlert

  const spanAttrs = {
    role: props.role,
    'aria-label': props.ariaLabel,
    ...attrs
  }
  const svgAttrs = {
    fill: 'currentColor',
    width: props.width || props.size,
    height: props.height || props.size,
    viewBox: props.viewBox,
    xmlns: props.xmlns
  }
  const pathAttrs = {
    d: iconPath
  }

  return h('span', {
    ...(isV2 ? { attrs: spanAttrs } : spanAttrs),
    class: {
      ...(
        data.staticClass !== undefined
          ? { [data.staticClass]: true }
          : {}
      ),
      [`mdi mdi-${props.name}`]: true,
      'mdi-spin': props.spin === true
    }
  }, [
    h('svg', {
      ...(isV2 ? { attrs: svgAttrs } : svgAttrs)
    }, [
      ...[props.title ? h('title', [props.title]) : undefined],
      h('path', {
        ...(isV2 ? { attrs: pathAttrs } : pathAttrs)
      })
    ])
  ])
}

export default {
  install(app) {
    app.component('mdicon', {
      name: 'MDIcon',
      ...versionDependentOpts,
      props: {
        title: [String],
        spin: [Boolean],
        width: [Number, String],
        height: [Number, String],
        name: {
          type: String,
          required: true,
          default: 'alert'
        },
        size: {
          type: [Number, String],
          default: 24
        },
        viewBox: {
          type: String,
          default: '0 0 24 24'
        },
        xmlns: {
          type: String,
          default: 'http://www.w3.org/2000/svg'
        },
        role: {
          type: String,
          default: 'img'
        },
        spin: {
          type: Boolean,
          default: false
        }
      },
      render
    })
  }
}<commit_msg>fix: add missing props<commit_after>import Vue, { h as v3h } from 'vue'
import * as mdi from '@mdi/js'
import './icons.css'

const vueVersion = Vue === undefined ? 3 : 2;
const isV2 = vueVersion === 2

const versionDependentOpts = Vue
  ? { functional: true } // for v2.x
  : {} // for v3.x

const ucFirst = (str) => str.charAt(0).toUpperCase() + str.slice(1)

function render(v2h, v2ctx) {
  const data = isV2 ? v2ctx.data : this
  const props = isV2 ? v2ctx.props : this
  const attrs = isV2 ? v2ctx.attrs : this.$attrs
  const h = isV2 ? v2h : v3h
  const iconPath = mdi[`mdi${ucFirst(props.name)}`] || mdi.mdiAlert

  const spanAttrs = {
    role: props.role,
    'aria-label': props.ariaLabel,
    ...attrs
  }
  const svgAttrs = {
    fill: 'currentColor',
    width: props.width || props.size,
    height: props.height || props.size,
    viewBox: props.viewBox,
    xmlns: props.xmlns
  }
  const pathAttrs = {
    d: iconPath
  }

  return h('span', {
    ...(isV2 ? { attrs: spanAttrs } : spanAttrs),
    class: {
      ...(
        data.staticClass !== undefined
          ? { [data.staticClass]: true }
          : {}
      ),
      [`mdi mdi-${props.name}`]: true,
      'mdi-spin': props.spin === true
    }
  }, [
    h('svg', {
      ...(isV2 ? { attrs: svgAttrs } : svgAttrs)
    }, [
      ...[props.title ? h('title', [props.title]) : undefined],
      h('path', {
        ...(isV2 ? { attrs: pathAttrs } : pathAttrs)
      })
    ])
  ])
}

export default {
  install(app) {
    app.component('mdicon', {
      name: 'MDIcon',
      ...versionDependentOpts,
      props: {
        title: [String],
        spin: [Boolean],
        width: [Number, String],
        height: [Number, String],
        ariaLabel: [String],
        staticClass: [String], // hides: property access warning for ts with vue 3
        name: {
          type: String,
          required: true,
          default: 'alert'
        },
        size: {
          type: [Number, String],
          default: 24
        },
        viewBox: {
          type: String,
          default: '0 0 24 24'
        },
        xmlns: {
          type: String,
          default: 'http://www.w3.org/2000/svg'
        },
        role: {
          type: String,
          default: 'img'
        },
        spin: {
          type: Boolean,
          default: false
        }
      },
      render
    })
  }
}
<|endoftext|>


<commit_before>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var com<commit_msg>What do you mean you can't pack up the commit?<commit_after>var child_process = require('child_process')
var fs = require('fs');
var max_sleep = 300
var step = 10
//Added a comment that achieves no real goal.
//Non-blocking loop
//Adjustable step
//Status line
//Add a rough time indicator
//First cut at libfaketime support

var commit_messages = [
  "Fixing an important issue with the universe.",
  "Someone poisoned the waterhole!",
  "You feeling lucky punk?",
  "Five bullets or six?",
  "Fixed memory parsing error #1337",
  "Cleaned out the intertubes",
  "AAAAAAAAAAARGH!",
  "Fixed a typo",
  "Updated the readme",
  "Fixing a typo added in the last readme update",
  "GET A HAIRCUT!",
  "Updated the readme again",
  "Found an issue with the letter 'a', so I fixed it.",
  "Incompatible dimensions found, Cthuhlu Error 666",
  "Who you calling a fool?",
  "How many more of these can I make?",
  "Fixing an error introduced in the last commit",
  "Re-updating the readme.",
  "Work in Progress",
  "WIP",
  "Quick fix",
  "Grammar fix",
  "Fixing punctuation",
  "Correcting style",
  "Logic error",
  "Almost there",
  "Nearly got it",
  "Not quite working",
  "Ooops!",
  "Did I do that?",
  "Commit all the required changes",
  "Really commit all the required changes",
  "Should work now",
  "Back out the last commit",
  "Reverting changes",
  "One more time...",
  "Re-commiting last",
  "One more User Story done",
  "Can work my way through the Kanban",
  "Sprint complete",
  "Well that seemed pretty easy",
  "What do you mean you can't pack up the commit?",
  "Merge in master",
  "Fast-forwarding changes"
]

if ( process.argv[ 2 ] && process.argv[ 3 ] ) {
  var inFile = process.argv[ 2 ]
  var outFile = process.argv[ 3 ]
  if (inFile == outFile) {
    console.error("Aborted: infile and outfile must be different")
    return(-1);
  }
  if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ]
  if (process.argv [ 5 ]) step = parseInt(process.argv [ 5 ])
  console.info("Writing from %s to %s, with up to %s seconds between commits of %s bytes", inFile, outFile, max_sleep, step)
  var outFD = fs.openSync(outFile, 'w')
  fs.readFile(inFile, function(err,data) {
    var length = data.length
    var commit_count = Math.ceil(length / step)
    var commit_time = commit_count * max_sleep / 2
    var comm<|endoftext|>


<commit_before>
var brain =["hi",];

_mood = ['very good, thank you', 'not very good', 'fair', 'iffy', 'Awesome!', 'Good, thank you', 'Ready to Rock',];
mood = _mood[Math.floor(Math.random() * 7)];

//change this if we have longer commands.
annyang.start({continuous: true});

function listRemindersOutput() {
    speak("No reminders");
    document.getElementById('#resultplace').innerHTML = "No reminders"
};
function save_name(){
    console.log("hello");
    var input = document.getElementById("#namebox");
    localStorage.setItem("fname", input.value);
};
var firstname = localStorage.getItem("fname");

annyang.addCallback('resultNoMatch', function(){document.getElementById("#resultplace").innerHTML = "Say that again.";});
function speak (phrase) {
    var worte = new SpeechSynthesisUtterance(phrase);
    worte.lang = "en-GB";
    window.speechSynthesis.speak(worte);
};

// Just a list of functions that anyone can call
// you can call these in the console by typing actions.YourFunctioName()
var actions = {

    youtube: function (term) {
        if (mood == 'iffy' || mood == "not very good") {
            speak("no")
            document.getElementById('#resultplace').innerHTML = "no";
        }
        else {
            window.location.href = 'https://www.youtube.com/results?search_query='+term;
        }
    },
    //youtube: function (term) {
    //    speak(term)
    //},

    google: function (term) {
        if (mood == 'iffy' || mood == "not very good") {
            speak("no")
            document.getElementById('#resultplace').innerHTML = "no";
        }
        else {
            window.location.href = 'https://www.google.com/#q='+term;
        }
    },
    d20: function () {
        var d20 = Math.floor(Math.random() * 20);

        speak(d20);
        document.getElementById("#resultplace").innerHTML = d20;
    },
    testcode: function() {

        newcommand = prompt("Wanted code");
        if (newcommand.indexOf("document.getElementById") >= 0) {
            alert("Not allowed");

        }
        else if (newcommand.indexOf("document.getItem") >= 0) {
            alert("Not allowed");

        }

        else {
            eval(newcommand);
        }

    },

    removeReminders: function () {
        // set reminders to be an empty array, quickest way to clear it
        localStorage.setItem('reminders', JSON.stringify([]));
        speak("All reminders have been cleared")
        document.getElementById('#resultplace').innerHTML = "All reminders have been cleared";
    },
    addReminder: function(term) {
        var item = localStorage.getItem('reminders');
        if (item == null) {
            // if we've never stored any reminder, so use an empty array string
            item =  "[]";
        }

        // take our string item and parse it into a real array
        var reminders = JSON.parse(item);
        // push the new term onto the list
        reminders.push(term);
        // stringify the reminders and save them back in storage
        localStorage.setItem('reminders', JSON.stringify(reminders));

        speak('Saved to my memory')
        document.getElementById('#resultplace').innerHTML = "Saved to my memory";
    },

    listReminders: function() {
        var item = localStorage.getItem('reminders');
        if (item == null) {
            // nothing has ever been stored before
            // return so we don't do the rest of this function
            var listReminders = listRemindersOutput();
            return listReminders;

        }

        var reminders = JSON.parse(item);

        if(reminders.length == 0) {
            // theres an empty array, but still no reminders
            // return so we dont do the rest of this function
            return speak("no reminders");
        }

        speak('your reminders are as follows');
        for(var i=0; i < reminders.length; i++) {
            speak(reminders[i]);

            // array.join() sticks all the elements together seperated by a separator
            document.getElementById('#resultplace').innerHTML = reminders.join(", ");
        }
    },
    d6: function () {
        var d6 = Math.floor(Math.random() * 6);
        speak(d6);
        document.getElementById("#resultplace").innerHTML = d6;
    },

    diceroll1: function (term) {

        if (mood == 'iffy' || mood == "not very good") {
            speak("no")
            document.getElementById('#resultplace').innerHTML = "no";
        }
        else {
            var diceroll2 = Math.floor(Math.random() * term);
            speak(diceroll2);
            document.getElementById("#resultplace").innerHTML = diceroll2;
        }
    },

    wolfram: function(term) {
        $.get("https://api.wolframalpha.com/v2/query?input="+term+"&appid=THYQLJ-3K45Y2A7W5"), function(wolfram__) {
            speak(wolfram__);
        };
        //http://api.wolframalpha.com/v2/query?input=pi&appid=XXXX
        //var wolfram_ = "http://api.wolframalpha.com/v2/query?input="+term+"&appid=THYQLJ-3K45Y2A7W5";
        //speak(wolfram_);
    },
    weather: function (term) {
        $.get('https://api.openweathermap.org/data/2.5/weather?q='+term, function (theweather) {
            speak(theweather.temp);

        });

    },
    badAsk: function() {
        if (mood == 'not very good' || mood == 'iffy') {
            _askBad = ['its not about me', 'nothing of your concern'];
            askBad = _askBad[Math.floor(Math.random() * 2)];
            speak(askBad);
            document.getElementById("#resultplace").innerHTML = askBad;
        }
        else {}
    },

    mood: function() {
        _mood = ['very good, thank you', 'not very good', 'fair', 'iffy', 'Awesome!', 'Good, thank you', 'Ready to Rock',];
        mood = _mood[Math.floor(Math.random() * 7)];

    },

    howu: function () {

        speak(mood);
        document.getElementById("#resultplace").innerHTML = mood;

    },

};

function on() {
    speak("now listening")
}

// bind all of our spoken commands to the actions
if (annyang) {
    annyang.setLanguage('en-GB');

    // Define the triggers for the commands
    var commands = {
        '(hello)(hi)(hey)': function() {
            speak('hello ');
            document.getElementById("#resultplace").innerHTML = "hello ";
        },

        '(Who made you)(Who created you) (who is your creator) ': function() {
            speak('sam bolton');
            document.getElementById("#resultplace").innerHTML = "sam bolton";
        },
        '(hey aubrey)(aubrey) (ok aubrey)': function() {
            if (localStorage.getItem("fname") == null) {
                speak('Ready, sir');
                document.getElementById("#resultplace").innerHTML = "Ready, sir";
            }
            else {
                speak('Ready,' + firstname);
                document.getElementById("#resultplace").innerHTML = "Ready, " + firstname;

            }

        },
        '(thats good) (that is good)': function() {
            speak('good');
            document.getElementById("#resultplace").innerHTML = "good";
        },

        '(shutup) (shut up) (pause) (be quit) (go to sleep) (stop)': function() {
            if (mood == 'iffy' || mood == "not very good") {
                speak("no")
                document.getElementById('#resultplace').innerHTML = "no";
            }
            else {
                annyang.pause();
                annyang.removeCommands();
                annyang.addCommands(commands2);
                annyang.resume();
                document.getElementById("#resultplace").innerHTML = "Paused";
            }
        },

        '(hey aubrey can you) (can you) youtube *term': actions.youtube,
        '(hey aubrey can you) (can you) search *term': actions.google,
        '(hey aubrey can you) (can you) google *term': actions.google,
        'roll a d20': actions.d20,
        'roll a d6': actions.d6,
        //    'What is *term': actions.wolfram,
        'what is the weather in *term': actions.weather,
        '(how are you) (you good) (are you alright)': actions.howu,
        'roll a d *term': actions.diceroll1,
        'clear reminder(s)' : actions.removeReminders,
        'remember (for me) *term' : actions.addReminder,
        'list reminders' : actions.listReminders,
        '(whats wrong) (whats up)(what is up)' : actions.badAsk,
        'code test' : actions.testcode,

    };
    var commands2 = {
        //this is for the pause function only!
        '(wake up)(resume)(aubry wakeup)(start)': function() {
            annyang.pause();
            annyang.removeCommands();
            annyang.addCommands(commands);
            annyang.resume();
            document.getElementById("#resultplace").innerHTML = "Resumed";
        }

    }
    // take our list of commands and stick them all in
    annyang.addCommands(commands);
}

window.setInterval(function() {
    actions.mood()

}, 60000);
<commit_msg>Fixed some more output errors<commit_after>
var brain =["hi",];

_mood = ['very good, thank you', 'not very good', 'fair', 'iffy', 'Awesome!', 'Good, thank you', 'Ready to Rock',];
mood = _mood[Math.floor(Math.random() * 7)];

//change this if we have longer commands.
annyang.start({continuous: true});

function listRemindersOutput() {
    speak("No reminders");
    document.getElementById('#resultplace').innerHTML = "No reminders"
};
function save_name(){
    console.log("hello");
    var input = document.getElementById("#namebox");
    localStorage.setItem("fname", input.value);
};
var firstname = localStorage.getItem("fname");

annyang.addCallback('resultNoMatch', function(){document.getElementById("#resultplace").innerHTML = "Say that again.";});
function speak (phrase) {
    var worte = new SpeechSynthesisUtterance(phrase);
    worte.lang = "en-GB";
    window.speechSynthesis.speak(worte);
};

// Just a list of functions that anyone can call
// you can call these in the console by typing actions.YourFunctioName()
var actions = {

    youtube: function (term) {
        if (mood == 'iffy' || mood == "not very good") {
            speak("no")
            document.getElementById('#resultplace').innerHTML = "no";
        }
        else {
            window.location.href = 'https://www.youtube.com/results?search_query='+term;
        }
    },
    //youtube: function (term) {
    //    speak(term)
    //},

    google: function (term) {
        if (mood == 'iffy' || mood == "not very good") {
            speak("no")
            document.getElementById('#resultplace').innerHTML = "no";
        }
        else {
            window.location.href = 'https://www.google.com/#q='+term;
        }
    },
    d20: function () {
        var d20 = Math.floor(Math.random() * 20);

        speak(d20);
        document.getElementById("#resultplace").innerHTML = d20;
    },
    testcode: function() {

        newcommand = prompt("Wanted code");
        if (newcommand.indexOf("document.getElementById") >= 0) {
            alert("Not allowed");

        }
        else if (newcommand.indexOf("document.getItem") >= 0) {
            alert("Not allowed");

        }

        else {
            eval(newcommand);
        }

    },

    removeReminders: function () {
        // set reminders to be an empty array, quickest way to clear it
        localStorage.setItem('reminders', JSON.stringify([]));
        speak("All reminders have been cleared")
        document.getElementById('#resultplace').innerHTML = "All reminders have been cleared";
    },
    addReminder: function(term) {
        var item = localStorage.getItem('reminders');
        if (item == null) {
            // if we've never stored any reminder, so use an empty array string
            item =  "[]";
        }

        // take our string item and parse it into a real array
        var reminders = JSON.parse(item);
        // push the new term onto the list
        reminders.push(term);
        // stringify the reminders and save them back in storage
        localStorage.setItem('reminders', JSON.stringify(reminders));

        speak('Saved to my memory')
        document.getElementById('#resultplace').innerHTML = "Saved to my memory";
    },

    listReminders: function() {
        var item = localStorage.getItem('reminders');
        if (item == null) {
            // nothing has ever been stored before
            // return so we don't do the rest of this function
            var listReminders = listRemindersOutput();
            return listReminders;

        }

        var reminders = JSON.parse(item);

        if(reminders.length == 0) {
            // theres an empty array, but still no reminders
            // return so we dont do the rest of this function
            var listReminders = listRemindersOutput();
            return listReminders;
        }

        speak('your reminders are as follows');
        for(var i=0; i < reminders.length; i++) {
            speak(reminders[i]);

            // array.join() sticks all the elements together seperated by a separator
            document.getElementById('#resultplace').innerHTML = reminders.join(", ");
        }
    },
    d6: function () {
        var d6 = Math.floor(Math.random() * 6);
        speak(d6);
        document.getElementById("#resultplace").innerHTML = d6;
    },

    diceroll1: function (term) {

        if (mood == 'iffy' || mood == "not very good") {
            speak("no")
            document.getElementById('#resultplace').innerHTML = "no";
        }
        else {
            var diceroll2 = Math.floor(Math.random() * term);
            speak(diceroll2);
            document.getElementById("#resultplace").innerHTML = diceroll2;
        }
    },

    wolfram: function(term) {
        $.get("https://api.wolframalpha.com/v2/query?input="+term+"&appid=THYQLJ-3K45Y2A7W5"), function(wolfram__) {
            speak(wolfram__);
        };
        //http://api.wolframalpha.com/v2/query?input=pi&appid=XXXX
        //var wolfram_ = "http://api.wolframalpha.com/v2/query?input="+term+"&appid=THYQLJ-3K45Y2A7W5";
        //speak(wolfram_);
    },
    weather: function (term) {
        $.get('https://api.openweathermap.org/data/2.5/weather?q='+term, function (theweather) {
            speak(theweather.temp);

        });

    },
    badAsk: function() {
        if (mood == 'not very good' || mood == 'iffy') {
            _askBad = ['its not about me', 'nothing of your concerns'];
            askBad = _askBad[Math.floor(Math.random() * 2)];
            speak(askBad);
            document.getElementById("#resultplace").innerHTML = askBad;
        }
        else {}
    },

    mood: function() {
        _mood = ['very good, thank you', 'not very good', 'fair', 'iffy', 'Awesome!', 'Good, thank you', 'Ready to Rock',];
        mood = _mood[Math.floor(Math.random() * 7)];

    },

    howu: function () {

        speak(mood);
        document.getElementById("#resultplace").innerHTML = mood;

    },

};

function on() {
    speak("now listening")
}

// bind all of our spoken commands to the actions
if (annyang) {
    annyang.setLanguage('en-GB');

    // Define the triggers for the commands
    var commands = {
        '(hello)(hi)(hey)': function() {
            speak('hello ');
            document.getElementById("#resultplace").innerHTML = "hello ";
        },

        '(Who made you)(Who created you) (who is your creator) ': function() {
            speak('sam bolton');
            document.getElementById("#resultplace").innerHTML = "sam bolton";
        },
        '(hey aubrey)(aubrey) (ok aubrey)': function() {
            if (localStorage.getItem("fname") == null) {
                speak('Ready, sir');
                document.getElementById("#resultplace").innerHTML = "Ready, sir";
            }
            else {
                speak('Ready,' + firstname);
                document.getElementById("#resultplace").innerHTML = "Ready, " + firstname;

            }

        },
        '(thats good) (that is good)': function() {
            speak('good');
            document.getElementById("#resultplace").innerHTML = "good";
        },

        '(shutup) (shut up) (pause) (be quit) (go to sleep) (stop)': function() {
            if (mood == 'iffy' || mood == "not very good") {
                speak("no")
                document.getElementById('#resultplace').innerHTML = "no";
            }
            else {
                annyang.pause();
                annyang.removeCommands();
                annyang.addCommands(commands2);
                annyang.resume();
                document.getElementById("#resultplace").innerHTML = "Paused";
            }
        },

        '(hey aubrey can you) (can you) youtube *term': actions.youtube,
        '(hey aubrey can you) (can you) search *term': actions.google,
        '(hey aubrey can you) (can you) google *term': actions.google,
        'roll a d20': actions.d20,
        'roll a d6': actions.d6,
        //    'What is *term': actions.wolfram,
        'what is the weather in *term': actions.weather,
        '(how are you) (you good) (are you alright)': actions.howu,
        'roll a d *term': actions.diceroll1,
        'clear reminder(s)' : actions.removeReminders,
        'remember (for me) *term' : actions.addReminder,
        'list reminders' : actions.listReminders,
        '(whats wrong) (whats up)(what is up)' : actions.badAsk,
        'code test' : actions.testcode,

    };
    var commands2 = {
        //this is for the pause function only!
        '(wake up)(resume)(aubry wakeup)(start)': function() {
            annyang.pause();
            annyang.removeCommands();
            annyang.addCommands(commands);
            annyang.resume();
            document.getElementById("#resultplace").innerHTML = "Resumed";
        }

    }
    // take our list of commands and stick them all in
    annyang.addCommands(commands);
}

window.setInterval(function() {
    actions.mood()

}, 60000);
<|endoftext|>


<commit_before>var faye    = require('faye');

module.exports = function(options) {
  var url    = options.url;
  var client = new faye.Client(url);

  var start = function(id) {
    var messageCount    = 0;
    var claimedStudents = 0;

    var connect = function() {
      client.publish('/presence/teacher/connect', {
        userId: id,
        role:   'teacher'
      });
    };

    var claimStudent = function() {
      client.publish('/presence/claim_student', {
        teacherId: id
      });
    };

    var sendNextMessage = function(channel) {
      client.publish(channel, {
        message: 'Message from teacher: ' + ++messageCount
      });
    };

    client.subscribe('/presence/status', function(data) {
      if(data.students.waiting > 0 && claimedStudents < options.studentsPerTeacher) {
        claimStudent();
      }
    });

    client.subscribe('/presence/new_chat/teacher/' + id, function(data) {
      var sendChannel = data.sendChannel;

      claimedStudents++;
      console.log('Teacher now has ' + claimedStudents + ' students.');

      var chatSub = client.subscribe(data.receiveChannel, function(data) {
        console.log('teacher got chat message', data);

        if(messageCount < options.messageCount) {
          sendNextMessage(sendChannel);
        }
        else {
          chatSub.cancel();
          claimedStudents--;
          console.log('Done');
        }
      });

      // kick off the whole shebang
      sendNextMessage(sendChannel);
    });

    connect();
  };

  return {
    start: start
  }
};
<commit_msg>Callback refactoring.<commit_after>var faye    = require('faye');

module.exports = function(options) {
  var url    = options.url;
  var client = new faye.Client(url);

  var start = function(id) {
    var messageCount    = 0;
    var claimedStudents = 0;

    var connect = function() {
      client.publish('/presence/teacher/connect', {
        userId: id,
        role:   'teacher'
      });
    };

    var claimStudent = function() {
      client.publish('/presence/claim_student', {
        teacherId: id
      });
    };

    var sendNextMessage = function(channel) {
      client.publish(channel, {
        message: 'Message from teacher: ' + ++messageCount
      });
    };

    var handleNewChat = function(data) {
      var sendChannel    = data.sendChannel;
      var receiveChannel = data.receiveChannel;

      claimedStudents++;
      console.log('Teacher now has ' + claimedStudents + ' students.');

      var chatSub = client.subscribe(receiveChannel, function(data) {
        console.log('Teacher got chat message:', data);

        if(messageCount < options.messageCount) {
          sendNextMessage(sendChannel);
        }
        else {
          chatSub.cancel();
          claimedStudents--;
          console.log('Done');
        }
      });

      // kick off the whole shebang
      sendNextMessage(sendChannel);
    };

    client.subscribe('/presence/status', function(data) {
      if(data.students.waiting > 0 && claimedStudents < options.studentsPerTeacher) {
        claimStudent();
      }
    });

    client.subscribe('/presence/new_chat/teacher/' + id, handleNewChat);

    connect();
  };

  return {
    start: start
  }
};
<|endoftext|>