<commit_before>/*
 * Copyright (c) 2012 Glenn Ruehle
 *
 * 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,  regexp: true, indent: 4, maxerr: 50 */
/*global define, brackets, $, window, _hideSettings */

define(function (require, exports, module) {
    "use strict";

    // Brackets modules
    var AppInit             = brackets.getModule("utils/AppInit"),
        NativeApp           = brackets.getModule("utils/NativeApp"),
        DocumentManager     = brackets.getModule("document/DocumentManager"),
        EditorManager       = brackets.getModule("editor/EditorManager"),
        ExtensionUtils      = brackets.getModule("utils/ExtensionUtils"),
        FileUtils           = brackets.getModule("file/FileUtils"),
        MainViewManager     = brackets.getModule("view/MainViewManager"),
        PopUpManager        = brackets.getModule("widgets/PopUpManager"),
        PreferencesManager  = brackets.getModule("preferences/PreferencesManager"),
        WorkspaceManager    = brackets.getModule("view/WorkspaceManager"),
        CommandManager      = brackets.getModule("command/CommandManager"),
        Menus               = brackets.getModule("command/Menus"),
        _                   = brackets.getModule("thirdparty/lodash");

    // Templates
    var panelHTML       = require("text!templates/panel.html"),
        previewHTML     = require("text!templates/preview.html"),
        settingsHTML    = require("text!templates/settings.html");

    // Local modules
    var marked          = require("lib/marked");

    // jQuery objects
    var $icon,
        $iframe,
        $panel,
        $settingsToggle,
        $settings;

    // Other vars
    var currentDoc,
        currentEditor,
        panel,
        viewMenu,
        toggleCmd,
        visible = false,
        realVisibility = false;

    // Prefs
    var _prefs = PreferencesManager.getExtensionPrefs("markdown-preview");
    _prefs.definePreference("useGFM", "boolean", false);
    _prefs.definePreference("theme", "string", "clean");
    _prefs.definePreference("syncScroll", "boolean", true);

    // (based on code in brackets.js)
    function _handleLinkClick(e) {
        // Check parents too, in case link has inline formatting tags
        var node = e.target, url;
        while (node) {
            if (node.tagName === "A") {
                url = node.getAttribute("href");
                if (url && !url.match(/^#/)) {
                    NativeApp.openURLInDefaultBrowser(url);
                }
                e.preventDefault();
                break;
            }
            node = node.parentElement;
        }

        // Close settings dropdown, if open
        _hideSettings();
    }

    function _calcScrollPos() {
        var scrollInfo = currentEditor._codeMirror.getScrollInfo();
        var scrollPercentage = scrollInfo.top / (scrollInfo.height - scrollInfo.clientHeight);
        var scrollTop = ($iframe[0].contentDocument.body.scrollHeight - $iframe[0].clientHeight) * scrollPercentage;

        return Math.round(scrollTop);
    }

    function _editorScroll() {
        if (_prefs.get("syncScroll") && $iframe) {
            var scrollTop = _calcScrollPos();

            $iframe[0].contentDocument.body.scrollTop = scrollTop;
        }
    }

    function _loadDoc(doc, isReload) {
        if (doc && visible && $iframe) {
            var docText     = doc.getText(),
                scrollPos   = 0,
                bodyText    = "",
                yamlRegEx   = /^-{3}([\w\W]+?)(-{3})/,
                yamlMatch   = yamlRegEx.exec(docText);

            // If there's yaml front matter, remove it.
            if (yamlMatch) {
                docText = docText.substr(yamlMatch[0].length);
            }

            if (isReload) {
                scrollPos = $iframe.contents()[0].body.scrollTop;
            } else if (_prefs.get("syncScroll")) {
                scrollPos = _calcScrollPos();
            }

            // Parse markdown into HTML
            bodyText = marked(docText);

            // Show URL in link tooltip
            bodyText = bodyText.replace(/(href=\"([^\"]*)\")/g, "$1 title=\"$2\"");

            // Convert protocol-relative URLS
            bodyText = bodyText.replace(/src="\/\//g, "src=\"http://");

            if (isReload) {
                $iframe[0].contentDocument.body.innerHTML = bodyText;
            } else {
                // Make <base> tag for relative URLS
                var baseUrl = window.location.protocol + "//" + FileUtils.getDirectoryPath(doc.file.fullPath);

                // Assemble the HTML source
                var htmlSource = _.template(previewHTML, {
                    baseUrl    : baseUrl,
                    themeUrl   : require.toUrl("./themes/" + _prefs.get("theme") + ".css"),
                    scrollTop  : scrollPos,
                    bodyText   : bodyText
                });
                $iframe.attr("srcdoc", htmlSource);

                // Remove any existing load handlers
                $iframe.off("load");
                $iframe.load(function () {
                    // Open external browser when links are clicked
                    // (similar to what brackets.js does - but attached to the iframe's document)
                    $iframe[0].contentDocument.body.addEventListener("click", _handleLinkClick, true);

                    // Sync scroll position (if needed)
                    if (!isReload) {
                        _editorScroll();
                    }

                    // Make sure iframe is showing
                    $iframe.show();
                });
            }
        }
    }

    function _documentChange(e) {
        _loadDoc(e.target, true);
    }

    function _resizeIframe() {
        if (visible && $iframe) {
            var iframeWidth = panel.$panel.innerWidth();
            $iframe.attr("width", iframeWidth + "px");
        }
    }

    function _updateSettings() {
        // Format
        var useGFM = _prefs.get("useGFM");
        marked.setOptions({
            breaks: useGFM,
            gfm: useGFM
        });

        // Re-render
        _loadDoc(currentDoc);
    }

    function _documentClicked(e) {
        if (!$settings.is(e.target) &&
                !$settingsToggle.is(e.target) &&
                $settings.has(e.target).length === 0) {
            _hideSettings();
        }
    }

    function _hideSettings() {
        if ($settings) {
            $settings.remove();
            $settings = null;
            $(window.document).off("mousedown", _documentClicked);
        }
    }

    function _showSettings(e) {
        _hideSettings();

        $settings = $(settingsHTML)
            .css({
                right: 12,
                top: $settingsToggle.position().top + $settingsToggle.outerHeight() + 12
            })
            .appendTo($panel);

        $settings.find("#markdown-preview-format")
            .prop("selectedIndex", _prefs.get("useGFM") ? 1 : 0)
            .change(function (e) {
                _prefs.set("useGFM", e.target.selectedIndex === 1);
                _updateSettings();
            });

        $settings.find("#markdown-preview-theme")
            .val(_prefs.get("theme"))
            .change(function (e) {
                _prefs.set("theme", e.target.value);
                _updateSettings();
            });

        var $syncScroll = $settings.find("#markdown-preview-sync-scroll");

        $syncScroll.change(function (e) {
            _prefs.set("syncScroll", e.target.checked);
            _editorScroll();
        });

        if (_prefs.get("syncScroll")) {
            $syncScroll.attr("checked", true);
        }

        PopUpManager.addPopUp($settings, _hideSettings, true);
        $(window.document).on("mousedown", _documentClicked);
    }

    function _setPanelVisibility(isVisible) {
        if (isVisible === realVisibility) {
            return;
        }

        realVisibility = isVisible;
        if (isVisible) {
            if (!panel) {
                $panel = $(panelHTML);
                $iframe = $panel.find("#panel-markdown-preview-frame");

                panel = WorkspaceManager.createBottomPanel("markdown-preview-panel", $panel);
                $panel.on("panelResizeUpdate", function (e, newSize) {
                    $iframe.attr("height", newSize);
                });
                $iframe.attr("height", $panel.height());

                window.setTimeout(_resizeIframe);

                $settingsToggle = $("#markdown-settings-toggle")
                    .click(function (e) {
                        if ($settings) {
                            _hideSettings();
                        } else {
                            _showSettings(e);
                        }
                    });

                $iframe.hide();
            }
            _loadDoc(DocumentManager.getCurrentDocument());
            $icon.toggleClass("active");
            panel.show();
        } else {
            $icon.toggleClass("active");
            panel.hide();
            $iframe.hide();
        }

        toggleCmd.setChecked(isVisible);
    }

    function _currentDocChangedHandler() {
        var doc = DocumentManager.getCurrentDocument(),
            ext = doc ? FileUtils.getFileExtension(doc.file.fullPath).toLowerCase() : "";

        if (currentDoc) {
            currentDoc.off("change", _documentChange);
            currentDoc = null;
        }

        if (currentEditor) {
            currentEditor.off("scroll", _editorScroll);
            currentEditor = null;
        }

        if (doc && /md|markdown|litcoffee|txt/.test(ext)) {
            currentDoc = doc;
            currentDoc.on("change", _documentChange);
            currentEditor = EditorManager.getCurrentFullEditor();
            currentEditor.on("scroll", _editorScroll);
            $icon.css({display: "block"});
            _setPanelVisibility(visible);
            toggleCmd.setEnabled(true);
            _loadDoc(doc);
        } else {
            $icon.css({display: "none"});
            toggleCmd.setEnabled(false);
            _setPanelVisibility(false);
        }
    }

    function _toggleVisibility() {
        visible = !visible;
        _setPanelVisibility(visible);
    }

    // Debounce event callback to avoid excess overhead
    // Update preview 300 ms ofter document change
    // Sync scroll 1ms after document scroll (just enough to ensure
    // the document scroll isn't blocked).
    _documentChange = _.debounce(_documentChange, 300);
    _editorScroll = _.debounce(_editorScroll, 1);

    // Insert CSS for this extension
    ExtensionUtils.loadStyleSheet(module, "styles/MarkdownPreview.css");

    // Add toolbar icon
    $icon = $("<a>")
        .attr({
            id: "markdown-preview-icon",
            href: "#"
        })
        .css({
            display: "none"
        })
        .click(_toggleVisibility)
        .appendTo($("#main-toolbar .buttons"));

    // Add a document change handler
    MainViewManager.on("currentFileChange", _currentDocChangedHandler);

    viewMenu = Menus.getMenu(Menus.AppMenuBar.VIEW_MENU);
    toggleCmd = CommandManager.register("Markdown Preview", "toggleMarkdownPreview", _toggleVisibility);

    viewMenu.addMenuItem(toggleCmd);

    toggleCmd.setChecked(realVisibility);
    toggleCmd.setEnabled(realVisibility);

    // currentDocumentChange is *not* called for the initial document. Use
    // appReady() to set initial state.
    AppInit.appReady(function () {
        _currentDocChangedHandler();
    });

    // Listen for resize events
    WorkspaceManager.on("workspaceUpdateLayout", _resizeIframe);
    $("#sidebar").on("panelCollapsed panelExpanded panelResizeUpdate", _resizeIframe);
});
<commit_msg>Updating checking menu item.<commit_after>/*
 * Copyright (c) 2012 Glenn Ruehle
 *
 * 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,  regexp: true, indent: 4, maxerr: 50 */
/*global define, brackets, $, window, _hideSettings */

define(function (require, exports, module) {
    "use strict";

    // Brackets modules
    var AppInit             = brackets.getModule("utils/AppInit"),
        NativeApp           = brackets.getModule("utils/NativeApp"),
        DocumentManager     = brackets.getModule("document/DocumentManager"),
        EditorManager       = brackets.getModule("editor/EditorManager"),
        ExtensionUtils      = brackets.getModule("utils/ExtensionUtils"),
        FileUtils           = brackets.getModule("file/FileUtils"),
        MainViewManager     = brackets.getModule("view/MainViewManager"),
        PopUpManager        = brackets.getModule("widgets/PopUpManager"),
        PreferencesManager  = brackets.getModule("preferences/PreferencesManager"),
        WorkspaceManager    = brackets.getModule("view/WorkspaceManager"),
        CommandManager      = brackets.getModule("command/CommandManager"),
        Menus               = brackets.getModule("command/Menus"),
        _                   = brackets.getModule("thirdparty/lodash");

    // Templates
    var panelHTML       = require("text!templates/panel.html"),
        previewHTML     = require("text!templates/preview.html"),
        settingsHTML    = require("text!templates/settings.html");

    // Local modules
    var marked          = require("lib/marked");

    // jQuery objects
    var $icon,
        $iframe,
        $panel,
        $settingsToggle,
        $settings;

    // Other vars
    var currentDoc,
        currentEditor,
        panel,
        viewMenu,
        toggleCmd,
        visible = false,
        realVisibility = false;

    // Prefs
    var _prefs = PreferencesManager.getExtensionPrefs("markdown-preview");
    _prefs.definePreference("useGFM", "boolean", false);
    _prefs.definePreference("theme", "string", "clean");
    _prefs.definePreference("syncScroll", "boolean", true);

    // (based on code in brackets.js)
    function _handleLinkClick(e) {
        // Check parents too, in case link has inline formatting tags
        var node = e.target, url;
        while (node) {
            if (node.tagName === "A") {
                url = node.getAttribute("href");
                if (url && !url.match(/^#/)) {
                    NativeApp.openURLInDefaultBrowser(url);
                }
                e.preventDefault();
                break;
            }
            node = node.parentElement;
        }

        // Close settings dropdown, if open
        _hideSettings();
    }

    function _calcScrollPos() {
        var scrollInfo = currentEditor._codeMirror.getScrollInfo();
        var scrollPercentage = scrollInfo.top / (scrollInfo.height - scrollInfo.clientHeight);
        var scrollTop = ($iframe[0].contentDocument.body.scrollHeight - $iframe[0].clientHeight) * scrollPercentage;

        return Math.round(scrollTop);
    }

    function _editorScroll() {
        if (_prefs.get("syncScroll") && $iframe) {
            var scrollTop = _calcScrollPos();

            $iframe[0].contentDocument.body.scrollTop = scrollTop;
        }
    }

    function _loadDoc(doc, isReload) {
        if (doc && visible && $iframe) {
            var docText     = doc.getText(),
                scrollPos   = 0,
                bodyText    = "",
                yamlRegEx   = /^-{3}([\w\W]+?)(-{3})/,
                yamlMatch   = yamlRegEx.exec(docText);

            // If there's yaml front matter, remove it.
            if (yamlMatch) {
                docText = docText.substr(yamlMatch[0].length);
            }

            if (isReload) {
                scrollPos = $iframe.contents()[0].body.scrollTop;
            } else if (_prefs.get("syncScroll")) {
                scrollPos = _calcScrollPos();
            }

            // Parse markdown into HTML
            bodyText = marked(docText);

            // Show URL in link tooltip
            bodyText = bodyText.replace(/(href=\"([^\"]*)\")/g, "$1 title=\"$2\"");

            // Convert protocol-relative URLS
            bodyText = bodyText.replace(/src="\/\//g, "src=\"http://");

            if (isReload) {
                $iframe[0].contentDocument.body.innerHTML = bodyText;
            } else {
                // Make <base> tag for relative URLS
                var baseUrl = window.location.protocol + "//" + FileUtils.getDirectoryPath(doc.file.fullPath);

                // Assemble the HTML source
                var htmlSource = _.template(previewHTML, {
                    baseUrl    : baseUrl,
                    themeUrl   : require.toUrl("./themes/" + _prefs.get("theme") + ".css"),
                    scrollTop  : scrollPos,
                    bodyText   : bodyText
                });
                $iframe.attr("srcdoc", htmlSource);

                // Remove any existing load handlers
                $iframe.off("load");
                $iframe.load(function () {
                    // Open external browser when links are clicked
                    // (similar to what brackets.js does - but attached to the iframe's document)
                    $iframe[0].contentDocument.body.addEventListener("click", _handleLinkClick, true);

                    // Sync scroll position (if needed)
                    if (!isReload) {
                        _editorScroll();
                    }

                    // Make sure iframe is showing
                    $iframe.show();
                });
            }
        }
    }

    function _documentChange(e) {
        _loadDoc(e.target, true);
    }

    function _resizeIframe() {
        if (visible && $iframe) {
            var iframeWidth = panel.$panel.innerWidth();
            $iframe.attr("width", iframeWidth + "px");
        }
    }

    function _updateSettings() {
        // Format
        var useGFM = _prefs.get("useGFM");
        marked.setOptions({
            breaks: useGFM,
            gfm: useGFM
        });

        // Re-render
        _loadDoc(currentDoc);
    }

    function _documentClicked(e) {
        if (!$settings.is(e.target) &&
                !$settingsToggle.is(e.target) &&
                $settings.has(e.target).length === 0) {
            _hideSettings();
        }
    }

    function _hideSettings() {
        if ($settings) {
            $settings.remove();
            $settings = null;
            $(window.document).off("mousedown", _documentClicked);
        }
    }

    function _showSettings(e) {
        _hideSettings();

        $settings = $(settingsHTML)
            .css({
                right: 12,
                top: $settingsToggle.position().top + $settingsToggle.outerHeight() + 12
            })
            .appendTo($panel);

        $settings.find("#markdown-preview-format")
            .prop("selectedIndex", _prefs.get("useGFM") ? 1 : 0)
            .change(function (e) {
                _prefs.set("useGFM", e.target.selectedIndex === 1);
                _updateSettings();
            });

        $settings.find("#markdown-preview-theme")
            .val(_prefs.get("theme"))
            .change(function (e) {
                _prefs.set("theme", e.target.value);
                _updateSettings();
            });

        var $syncScroll = $settings.find("#markdown-preview-sync-scroll");

        $syncScroll.change(function (e) {
            _prefs.set("syncScroll", e.target.checked);
            _editorScroll();
        });

        if (_prefs.get("syncScroll")) {
            $syncScroll.attr("checked", true);
        }

        PopUpManager.addPopUp($settings, _hideSettings, true);
        $(window.document).on("mousedown", _documentClicked);
    }

    function _setPanelVisibility(isVisible) {
        if (isVisible === realVisibility) {
            return;
        }

        realVisibility = isVisible;
        if (isVisible) {
            if (!panel) {
                $panel = $(panelHTML);
                $iframe = $panel.find("#panel-markdown-preview-frame");

                panel = WorkspaceManager.createBottomPanel("markdown-preview-panel", $panel);
                $panel.on("panelResizeUpdate", function (e, newSize) {
                    $iframe.attr("height", newSize);
                });
                $iframe.attr("height", $panel.height());

                window.setTimeout(_resizeIframe);

                $settingsToggle = $("#markdown-settings-toggle")
                    .click(function (e) {
                        if ($settings) {
                            _hideSettings();
                        } else {
                            _showSettings(e);
                        }
                    });

                $iframe.hide();
            }
            _loadDoc(DocumentManager.getCurrentDocument());
            $icon.toggleClass("active");
            panel.show();
        } else {
            $icon.toggleClass("active");
            panel.hide();
            $iframe.hide();
        }
    }

    function _currentDocChangedHandler() {
        var doc = DocumentManager.getCurrentDocument(),
            ext = doc ? FileUtils.getFileExtension(doc.file.fullPath).toLowerCase() : "";

        if (currentDoc) {
            currentDoc.off("change", _documentChange);
            currentDoc = null;
        }

        if (currentEditor) {
            currentEditor.off("scroll", _editorScroll);
            currentEditor = null;
        }

        if (doc && /md|markdown|litcoffee|txt/.test(ext)) {
            currentDoc = doc;
            currentDoc.on("change", _documentChange);
            currentEditor = EditorManager.getCurrentFullEditor();
            currentEditor.on("scroll", _editorScroll);
            $icon.css({display: "block"});
            _setPanelVisibility(visible);
            toggleCmd.setEnabled(true);
            _loadDoc(doc);
        } else {
            $icon.css({display: "none"});
            toggleCmd.setEnabled(false);
            _setPanelVisibility(false);
        }
    }

    function _toggleVisibility() {
        visible = !visible;
        _setPanelVisibility(visible);

        toggleCmd.setChecked(visible);
    }

    // Debounce event callback to avoid excess overhead
    // Update preview 300 ms ofter document change
    // Sync scroll 1ms after document scroll (just enough to ensure
    // the document scroll isn't blocked).
    _documentChange = _.debounce(_documentChange, 300);
    _editorScroll = _.debounce(_editorScroll, 1);

    // Insert CSS for this extension
    ExtensionUtils.loadStyleSheet(module, "styles/MarkdownPreview.css");

    // Add toolbar icon
    $icon = $("<a>")
        .attr({
            id: "markdown-preview-icon",
            href: "#"
        })
        .css({
            display: "none"
        })
        .click(_toggleVisibility)
        .appendTo($("#main-toolbar .buttons"));

    // Add a document change handler
    MainViewManager.on("currentFileChange", _currentDocChangedHandler);

    viewMenu = Menus.getMenu(Menus.AppMenuBar.VIEW_MENU);
    toggleCmd = CommandManager.register("Markdown Preview", "toggleMarkdownPreview", _toggleVisibility);

    viewMenu.addMenuItem(toggleCmd);

    toggleCmd.setChecked(realVisibility);
    toggleCmd.setEnabled(realVisibility);

    // currentDocumentChange is *not* called for the initial document. Use
    // appReady() to set initial state.
    AppInit.appReady(function () {
        _currentDocChangedHandler();
    });

    // Listen for resize events
    WorkspaceManager.on("workspaceUpdateLayout", _resizeIframe);
    $("#sidebar").on("panelCollapsed panelExpanded panelResizeUpdate", _resizeIframe);
});
<|endoftext|>


<commit_before>/*
config = {

    title: "Test Title",
    modules: {

        'idOfDomElement1': "miid",
        'idOfDomElement2': "miid"
    },
    source: {

        name: "operationName",
        path: "",
        data: {}
    },
    bind: [
        {
            val: "Logout",
            query: "#logout"
            events: {

                mouseup: {

                    method: "logout",
                    args: ["/route/to/public/page"]
                }
            }
        },
        {
            val: "DE",
            query: "#i18n_de"
            events: {

                mouseup: {

                    method: "i18n",
                    args: ["de"]
                }
            }
        },
        {
            val: "EN",
            query: "#i18n_en"
            events: {

                mouseup: {

                    method: "i18n",
                    args: ["en"]
                }
            }
        }
    ]
}
*/

define(["adioo/bind/bind"], function(Bind) {

    var Layout = {

        i18n: function(locale) {

            N.obs("i18n").f("change", locale);
            // TODO fetch own data
        },

        logout: function(route) {

            N.logout(function() {

                window.location(route || "/");
            });
        }
    };

    function init(config) {

        this.conf = config;

        var layout = N.ext(Layout, Bind(this));

        //load modules
        if (layout.conf.modules) {

            for (var selector in layout.conf.modules) {

                N.mod(this.dom.querySelector("#" + selector), layout.conf.modules[selector]);
            }
        }

        //set document title
        if (layout.conf.title) {

            document.title = layout.conf.title;
        }

        //bind data
        if (layout.conf.source || layout.conf.data) {

            if (layout.conf.data) {

                layout.bind(layout.conf.data);
            }

            if (layout.conf.source) {

                layout.link(layout.conf.source, function(err, result) {

                    if (!err && result) {

                        layout.bind(result);
                    }
                });
            }
        }
    }

    return init;
});<commit_msg>added version to url<commit_after>/*
config = {

    title: "Test Title",
    modules: {

        'idOfDomElement1': "miid",
        'idOfDomElement2': "miid"
    },
    source: {

        name: "operationName",
        path: "",
        data: {}
    },
    bind: [
        {
            val: "Logout",
            query: "#logout"
            events: {

                mouseup: {

                    method: "logout",
                    args: ["/route/to/public/page"]
                }
            }
        },
        {
            val: "DE",
            query: "#i18n_de"
            events: {

                mouseup: {

                    method: "i18n",
                    args: ["de"]
                }
            }
        },
        {
            val: "EN",
            query: "#i18n_en"
            events: {

                mouseup: {

                    method: "i18n",
                    args: ["en"]
                }
            }
        }
    ]
}
*/

define(["adioo/bind/bf98a5b73189be6c4670d97f97fc46f7d62d543a/bind"], function(Bind) {

    var Layout = {

        i18n: function(locale) {

            N.obs("i18n").f("change", locale);
            // TODO fetch own data
        },

        logout: function(route) {

            N.logout(function() {

                window.location(route || "/");
            });
        }
    };

    function init(config) {

        this.conf = config;

        var layout = N.ext(Layout, Bind(this));

        //load modules
        if (layout.conf.modules) {

            for (var selector in layout.conf.modules) {

                N.mod(this.dom.querySelector("#" + selector), layout.conf.modules[selector]);
            }
        }

        //set document title
        if (layout.conf.title) {

            document.title = layout.conf.title;
        }

        //bind data
        if (layout.conf.source || layout.conf.data) {

            if (layout.conf.data) {

                layout.bind(layout.conf.data);
            }

            if (layout.conf.source) {

                layout.link(layout.conf.source, function(err, result) {

                    if (!err && result) {

                        layout.bind(result);
                    }
                });
            }
        }
    }

    return init;
});<|endoftext|>


<commit_before>var async = require('async'),
	_ = require('underscore'),
	fs = require('fs');

eval(fs.readFileSync('latlon.js') + '');
eval(fs.readFileSync('gridref.js') + '');

var fetchNearbyPostcodes = function (homeLatLon, maxDistanceKm, callback) {
	maxDistanceKm = parseFloat(maxDistanceKm);
	var csv = require('csv');
	csv()
		.from.path('data/ONSPD_NOV_2014_csv/Data/ONSPD_NOV_2014_UK.csv', {
			'columns': true,
			'delimiter': ',',
		})
		.to.array(function (data) {
			callback(null, data);
		})
		.transform(function (row) {
			var latLon = OsGridRef.osGridToLatLong(new OsGridRef(row.oseast1m, row.osnrth1m)),
				// why the h*ll Chris Veness' distanceTo function returns a
				// string?
				distance = parseFloat(latLon.distanceTo(homeLatLon));
			if (distance <= maxDistanceKm) {
				row = {
					'pcds': row.pcds,
					'lat': latLon.lat(),
					'lon': latLon.lon(),
				};
			} else {
				row = undefined;
			}
			return row;
		});
}

// home is LatLon(51.759467, -0.577358);
fetchNearbyPostcodes(new LatLon(51.759467, -0.577358), .5, function (err, postcodes) {
	console.log(JSON.stringify(postcodes));
});<commit_msg>Now filters my proximity to many reference points<commit_after>var async = require('async'),
	_ = require('underscore'),
	fs = require('fs');

eval(fs.readFileSync('latlon.js') + '');
eval(fs.readFileSync('gridref.js') + '');

var fetchNearbyPostcodes = function (referenceLatLons, maxDistanceMiles, callback) {
	referenceLatLons = [ ].concat(referenceLatLons);
	maxDistanceKm = parseFloat(maxDistanceMiles) * 1.609344;
	var csv = require('csv');
	csv()
		.from.path('data/ONSPD_NOV_2014_csv/Data/ONSPD_NOV_2014_UK.csv', {
			'columns': true,
			'delimiter': ',',
		})
		.to.array(function (data) {
			callback(null, data);
		})
		.transform(function (row) {
			var latLon = OsGridRef.osGridToLatLong(new OsGridRef(row.oseast1m, row.osnrth1m));
			if (_.some(referenceLatLons, function (referenceLatLon) {
				return parseFloat(latLon.distanceTo(referenceLatLon)) <= maxDistanceKm;
			})) {
				row = {
					'pcds': row.pcds,
					'lat': latLon.lat(),
					'lon': latLon.lon()
				};
			} else {
				row = undefined;
			}
			return row;
		});
}

// home is LatLon(51.759467, -0.577358);
// Berkhamsted station is LatLon(51.764541, -0.562041);
fetchNearbyPostcodes([
			new LatLon(51.759467, -0.577358),
			// new LatLon(51.764541, -0.562041)
		], .1, function (err, postcodes) {
	console.log(JSON.stringify(postcodes));
});
<|endoftext|>


<commit_before>function substringify(lengths, string) {
  var i = 0;

  return lengths.map(function(len) {
    var substring = string.substr(i, len);
    i += len;
    return substring;
  });
}

function tryPossibleConfigurations(coefficients, patternLength, dataLength, func) {
  function weightedAdd(accum, cur, i) {
    return accum + cur * lengths[i];
  }
  var lengths = [];
  var totalDepth = coefficients.length;

  return (function level(depth) {
    var fullLength;
    var innermost = (depth === totalDepth - 1);
    var curCharCount = coefficients[depth];
    var _maxLen = (dataLength - patternLength + curCharCount) / curCharCount;
    for(var i = 1; i <= _maxLen; i++) {
      lengths[depth] = i;

      if (!innermost) {
        if (level(depth + 1)) {
          return true;
        }
      } else {
        fullLength = coefficients.reduce(weightedAdd, 0);

        if (fullLength < dataLength) continue;
        else if (fullLength === dataLength) {
          if (func(lengths)) {
            return true; // break out of all loops (bubbles up)
          }
        }
        else {
          return false; // breaks out of this loop (no bubbling)
        }
      }
    }
    return false;
  })(0);
}

function match(pattern, data) {
  var patternLength = pattern.length;
  var matches = {}, matchValues = {};
  var curPattern, curData;

  if (typeof pattern === 'string') {
    pattern = pattern.split('');
  }

  if (typeof data === 'string') {
    data = data.split(' ');
  }

  if (patternLength !== data.length) {
    return false;
  }

  for (var i = 0; i < patternLength; i++) {
    curPattern = pattern[i];
    curData = data[i];

    if (!matches[curPattern]) {
      if (!matchValues[curData]) {
        matches[curPattern] = curData;
        matchValues[curData] = true;
      } else return false;
    } else { // already recorded
      if (matches[curPattern] !== curData) {
        return false;
      }
    }
  }
  return true; // yay
}

function match2(pattern, data) {
  var splitPattern = pattern.split('');
  var patternLength = splitPattern.length;
  var dataLength = data.length;
  // coefficients stores the count of each character
  // charIdx maps a character to its index in coefficients
  var coefficients = [], charIdx = {};

  // populate coefficients and charIdx
  splitPattern.forEach(function(char) {
    if (charIdx[char] === undefined) {
      charIdx[char] = coefficients.push(1) - 1;
    } else ++coefficients[ charIdx[char] ];
  });

  // find possible substring length groups
  return tryPossibleConfigurations(coefficients, patternLength, dataLength, function(lengths) {
    var substrings = splitPattern.map(function(char) {
      return lengths[ charIdx[char] ];
    });
    var splitData = substringify(substrings, data);
    return match(splitPattern, splitData);
  });
}
<commit_msg>Refactor slightly, add comments<commit_after>var glorious = (function() {
  var exports = {};

  // takes a character pattern and a list of words
  // and returns true if they follow the same pattern
  exports.match = function(pattern, data) {
    var patternLength = pattern.length;
    var matches = {}, matchValues = {};
    var curPattern, curData;

    // handles arrays and strings
    if (typeof pattern === 'string') {
      pattern = pattern.split('');
    }

    // handles arrays and space-delimited strings
    if (typeof data === 'string') {
      data = data.split(' ');
    }

    if (patternLength !== data.length) {
      return false;
    }

    for (var i = 0; i < patternLength; i++) {
      curPattern = pattern[i];
      curData = data[i];

      if (!matches[curPattern]) {
        if (!matchValues[curData]) {
          matches[curPattern] = curData;
          matchValues[curData] = true;
        } else return false;
      } else { // already recorded
        if (matches[curPattern] !== curData) {
          return false;
        }
      }
    }
    return true;
  }

  // takes a string and returns an array of substrings.
  // splits are determined by the 'lengths' array
  function substringify(lengths, string) {
    var i = 0;

    return lengths.map(function(len) {
      var substring = string.substr(i, len);
      i += len;
      return substring;
    });
  }

  // finds likely substrings from non-delimited data
  // and runs them through the original match()
  function tryPossibleConfigurations(coefficients, patternLength, dataLength, func) {
    function weightedAdd(accum, cur, i) {
      return accum + cur * lengths[i];
    }
    // lengths holds the substring lengths represented by each character
    var lengths = [];
    var totalDepth = coefficients.length;

    // each level of the recursive call represents a unique
    // character in the pattern (in the order that they first appear)
    function loopThroughChars(depth) {
      var isInnermost = (depth === totalDepth - 1);
      var curCharCount = coefficients[depth];
      var derivedDataLength;
      // maxCharLength is the max substring length that this character can represent
      var maxCharLength = (dataLength - patternLength + curCharCount) / curCharCount;

      for(var i = 1; i <= maxCharLength; i++) {
        lengths[depth] = i;

        if (!isInnermost) {
          if (loopThroughChars(depth + 1)) {
            return true; // allows us to bubble up a true return
          }
        } else {
          derivedDataLength = coefficients.reduce(weightedAdd, 0);

          if (derivedDataLength < dataLength) continue;
          else if (derivedDataLength === dataLength) {
            if (func(lengths)) {
              return true; // break out of all loops (bubbles up)
            }
          }
          else {
            return false; // breaks out of this loop (no bubbling)
          }
        }
      }

      return false;
    };

    return loopThroughChars(0);
  }

  exports.megamatch = function(pattern, data) {
    var splitPattern = pattern.split('');
    var patternLength = splitPattern.length;
    var dataLength = data.length;
    // coefficients stores the count of each character
    // charIdx maps a character to its index in coefficients
    var coefficients = [], charIdx = {};

    // populate coefficients and charIdx
    splitPattern.forEach(function(char) {
      if (charIdx[char] === undefined) {
        charIdx[char] = coefficients.push(1) - 1;
      } else ++coefficients[ charIdx[char] ];
    });

    function splitAndMatch(lengths) {
      var substrings = splitPattern.map(function(char) {
        return lengths[ charIdx[char] ];
      });
      var splitData = substringify(substrings, data);
      return exports.match(splitPattern, splitData);
    }

    return tryPossibleConfigurations(coefficients, patternLength, dataLength, splitAndMatch);
  }

  return exports;
})();
<|endoftext|>


<commit_before>var bot = require('./bot');
start();
bot.on('message',message =>
	{
var guild = bot.guilds.find("name","Revive Network Dev");
if(message.guild != guild)
{return;}
if(message.content.toLowerCase()==='~restart')
{
	message.channel.sendMessage('~stop');
	start();
message.reply('restarted');
}
if(message.content.toLowerCase()==='~start')
{
	start();
	message.reply('started');
}

	});
function start(){
	var dt = process.env.DISCORD_TOKEN || process.argv[2];
	console.log('Starting?');
	const exec = require('child_process').exec;
	exec('node index.js '+process.argv[2], (error, stdout, stderr) => {
		  if (error) {
			  console.log("error");
			      start; return;
			    }
		  console.log(`stdout: ${stdout}`);
		  console.log(`stderr: ${stderr}`);
		});
};
<commit_msg>more verbose error handling<commit_after>var bot = require('./bot');
start();
bot.on('message',message =>
	{
var guild = bot.guilds.find("name","Revive Network Dev");
if(message.guild != guild)
{return;}
if(message.content.toLowerCase()==='~restart')
{
	message.channel.sendMessage('~stop');
	start();
message.reply('restarted');
}
if(message.content.toLowerCase()==='~start')
{
	start();
	message.reply('started');
}

	});
function start(){
	var dt = process.env.DISCORD_TOKEN || process.argv[2];
	console.log('Starting?');
	const exec = require('child_process').exec;
	exec('node index.js '+process.argv[2], (error, stdout, stderr) => {
		  if (error) {
			  console.log("error");
              console.log(error);
			      start; return;
			    }
		  console.log(`stdout: ${stdout}`);
		  console.log(`stderr: ${stderr}`);
		});
};
<|endoftext|>


<commit_before>// Night mode
var d = document.documentElement,
    t = document.querySelectorAll(".js-toggle-lights")[0],
    l = document.querySelectorAll(".site-description")[0],
    m = localStorage.getItem("nightmode");

if(m == "true") {
  d.classList.add("night-mode");
  l.textContent = "Ubuntu experience. Sleep mode.";
}

t.addEventListener("click", function(){
  if(d.classList.contains("night-mode")) {
    d.classList.remove("night-mode");
    localStorage.setItem("nightmode", "false");
    l.textContent = "Ubuntu experience.";
  } else {
    d.classList.add("night-mode");
    localStorage.setItem("nightmode", "true");
    l.textContent = "Ubuntu experience. Sleep mode.";
  }
});

function timeAgo(n){var i=[{name:"second",limit:60,in_seconds:1},{name:"minute",limit:3600,in_seconds:60},{name:"hour",limit:86400,in_seconds:3600},{name:"day",limit:604800,in_seconds:86400},{name:"week",limit:2629743,in_seconds:604800},{name:"month",limit:31556926,in_seconds:2629743},{name:"year",limit:null,in_seconds:31556926}],e=(new Date-new Date(1e3*n))/1e3;if(5>e)return"now";for(var m=0,o=null;null!==(o=i[m++]);)if(e<o.limit||!o.limit)return e=Math.floor(e/o.in_seconds),e+" "+o.name+(e>1?"s":"")+" ago"}

if (sessionStorage.irl) {
            document.getElementById('irl').innerHTML = sessionStorage.irl;
} else {
        var al = function(data) {
            var activity = parseInt(data.googlefit.steps);
            if(activity == 0) activity = "I've made " + activity.toLocaleString() + " steps today and"; else steps = "I'm either sleeping or working. Most likely sleeping.";
            var irl = activity + " I spent over " + data.health.age.days.toLocaleString() + " days on Earth, my heart beat rate is " + data.googlefit.heartRate.bpm + " bpm measured " + timeAgo(data.googlefit.heartRate.timestamp) + ".";
            document.getElementById('irl').innerHTML = irl;
            sessionStorage.irl = irl;
      };

        var alt = document.createElement('script'); alt.type = 'text/javascript'; alt.async = true;
        alt.src = "http://track.andreiluca.com/api/?callback=al";
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(alt, s);
}; // e.ss

// Jekyll search
!function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}for(var i="function"==typeof require&&require,o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){module.exports=function(){function receivedResponse(xhr){return 200==xhr.status&&4==xhr.readyState}function handleResponse(xhr,callback){xhr.onreadystatechange=function(){if(receivedResponse(xhr))try{callback(null,JSON.parse(xhr.responseText))}catch(err){callback(err,null)}}}var self=this;self.load=function(location,callback){var xhr=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP");xhr.open("GET",location,!0),handleResponse(xhr,callback),xhr.send()}}},{}],2:[function(require,module,exports){function FuzzySearchStrategy(){function createFuzzyRegExpFromString(string){return new RegExp(string.split("").join(".*?"),"gi")}var self=this;self.matches=function(string,crit){return"string"!=typeof string?!1:(string=string.trim(),!!string.match(createFuzzyRegExpFromString(crit)))}}module.exports=new FuzzySearchStrategy},{}],3:[function(require,module,exports){function LiteralSearchStrategy(){function doMatch(string,crit){return string.toLowerCase().indexOf(crit.toLowerCase())>=0}var self=this;self.matches=function(string,crit){return"string"!=typeof string?!1:(string=string.trim(),doMatch(string,crit))}}module.exports=new LiteralSearchStrategy},{}],4:[function(require,module,exports){module.exports=function(){function findMatches(store,crit,strategy){for(var data=store.get(),i=0;i<data.length&&matches.length<limit;i++)findMatchesInObject(data[i],crit,strategy);return matches}function findMatchesInObject(obj,crit,strategy){for(var key in obj)if(strategy.matches(obj[key],crit)){matches.push(obj);break}}function getSearchStrategy(){return fuzzy?fuzzySearchStrategy:literalSearchStrategy}var self=this,matches=[],fuzzy=!1,limit=10,fuzzySearchStrategy=require("./SearchStrategies/fuzzy"),literalSearchStrategy=require("./SearchStrategies/literal");self.setFuzzy=function(_fuzzy){fuzzy=!!_fuzzy},self.setLimit=function(_limit){limit=parseInt(_limit,10)||limit},self.search=function(data,crit){return crit?(matches.length=0,findMatches(data,crit,getSearchStrategy())):[]}}},{"./SearchStrategies/fuzzy":2,"./SearchStrategies/literal":3}],5:[function(require,module,exports){module.exports=function(_store){function isObject(obj){return!!obj&&"[object Object]"==Object.prototype.toString.call(obj)}function isArray(obj){return!!obj&&"[object Array]"==Object.prototype.toString.call(obj)}function addObject(data){return store.push(data),data}function addArray(data){for(var added=[],i=0;i<data.length;i++)isObject(data[i])&&added.push(addObject(data[i]));return added}var self=this,store=[];isArray(_store)&&addArray(_store),self.clear=function(){return store.length=0,store},self.get=function(){return store},self.put=function(data){return isObject(data)?addObject(data):isArray(data)?addArray(data):void 0}}},{}],6:[function(require,module,exports){module.exports=function(){var self=this,templatePattern=/\{(.*?)\}/g;self.setTemplatePattern=function(newTemplatePattern){templatePattern=newTemplatePattern},self.render=function(t,data){return t.replace(templatePattern,function(match,prop){return data[prop]||match})}}},{}],7:[function(require,module,exports){!function(window,document,undefined){"use strict";function initWithJSON(json){store.put(opt.json),registerInput()}function initWithURL(url){jsonLoader.load(url,function(err,json){err?throwError("failed to get JSON ("+url+")"):(store.put(json),registerInput())})}function throwError(message){throw new Error("SimpleJekyllSearch --- "+message)}function validateOptions(_opt){for(var i=0;i<requiredOptions.length;i++){var req=requiredOptions[i];_opt[req]||throwError("You must specify a "+req)}}function assignOptions(_opt){for(var option in opt)opt[option]=_opt[option]||opt[option]}function isJSON(json){try{return json instanceof Object&&JSON.parse(JSON.stringify(json))}catch(e){return!1}}function emptyResultsContainer(){opt.resultsContainer.innerHTML=""}function appendToResultsContainer(text){opt.resultsContainer.innerHTML+=text}function registerInput(){opt.searchInput.addEventListener("keyup",function(e){return 0==e.target.value.length?void emptyResultsContainer():void render(searcher.search(store,e.target.value))})}function render(results){if(emptyResultsContainer(),0==results.length)return appendToResultsContainer(opt.noResultsText);for(var i=0;i<results.length;i++)appendToResultsContainer(templater.render(opt.searchResultTemplate,results[i]))}var Searcher=require("./Searcher"),Templater=require("./Templater"),Store=require("./Store"),JSONLoader=require("./JSONLoader"),searcher=new Searcher,templater=new Templater,store=new Store,jsonLoader=new JSONLoader,requiredOptions=["searchInput","resultsContainer","json"],opt={searchInput:null,resultsContainer:null,json:[],searchResultTemplate:'
{title}
',noResultsText:"No results found",limit:10,fuzzy:!1};window.SimpleJekyllSearch=function(_opt){validateOptions(_opt),assignOptions(_opt),isJSON(opt.json)?initWithJSON(opt.json):initWithURL(opt.json)}}(window,document)},{"./JSONLoader":1,"./Searcher":4,"./Store":5,"./Templater":6}]},{},[7]);

SimpleJekyllSearch({
        searchInput: document.getElementById('search-input'),
        resultsContainer: document.getElementById('search-results'),
        json: '/search.json',
        searchResultTemplate: '
{title}
',
        noResultsText: '

',
        limit: 5,
        fuzzy: true,
});<commit_msg>Small adjustments<commit_after>// Night mode
var d = document.documentElement,
    t = document.querySelectorAll(".js-toggle-lights")[0],
    l = document.querySelectorAll(".site-description")[0],
    m = localStorage.getItem("nightmode");

if(m == "true") {
  d.classList.add("night-mode");
  l.textContent = "Ubuntu experience. Sleep mode.";
}

t.addEventListener("click", function(){
  if(d.classList.contains("night-mode")) {
    d.classList.remove("night-mode");
    localStorage.setItem("nightmode", "false");
    l.textContent = "Ubuntu experience.";
  } else {
    d.classList.add("night-mode");
    localStorage.setItem("nightmode", "true");
    l.textContent = "Ubuntu experience. Sleep mode.";
  }
});

function timeAgo(n){var i=[{name:"second",limit:60,in_seconds:1},{name:"minute",limit:3600,in_seconds:60},{name:"hour",limit:86400,in_seconds:3600},{name:"day",limit:604800,in_seconds:86400},{name:"week",limit:2629743,in_seconds:604800},{name:"month",limit:31556926,in_seconds:2629743},{name:"year",limit:null,in_seconds:31556926}],e=(new Date-new Date(1e3*n))/1e3;if(5>e)return"now";for(var m=0,o=null;null!==(o=i[m++]);)if(e<o.limit||!o.limit)return e=Math.floor(e/o.in_seconds),e+" "+o.name+(e>1?"s":"")+" ago"}

if (sessionStorage.irl) {
            document.getElementById('irl').innerHTML = sessionStorage.irl;
} else {
        var al = function(data) {
            var activity = parseInt(data.googlefit.steps);
            if(activity == 0) activity = "I've made " + activity.toLocaleString() + " steps today and"; else activity = "I'm either sleeping or working. Most likely sleeping.";
            var irl = activity + " I spent over " + data.health.age.days.toLocaleString() + " days on Earth, my heart beat rate is " + data.googlefit.heartRate.bpm + " bpm measured " + timeAgo(data.googlefit.heartRate.timestamp) + ".";
            document.getElementById('irl').innerHTML = irl;
            sessionStorage.irl = irl;
      };

        var alt = document.createElement('script'); alt.type = 'text/javascript'; alt.async = true;
        alt.src = "http://track.andreiluca.com/api/?callback=al";
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(alt, s);
}; // e.ss

// Jekyll search
!function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}for(var i="function"==typeof require&&require,o=0;o<r.length;o++)s(r[o]);return s}({1:[function(require,module,exports){module.exports=function(){function receivedResponse(xhr){return 200==xhr.status&&4==xhr.readyState}function handleResponse(xhr,callback){xhr.onreadystatechange=function(){if(receivedResponse(xhr))try{callback(null,JSON.parse(xhr.responseText))}catch(err){callback(err,null)}}}var self=this;self.load=function(location,callback){var xhr=window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP");xhr.open("GET",location,!0),handleResponse(xhr,callback),xhr.send()}}},{}],2:[function(require,module,exports){function FuzzySearchStrategy(){function createFuzzyRegExpFromString(string){return new RegExp(string.split("").join(".*?"),"gi")}var self=this;self.matches=function(string,crit){return"string"!=typeof string?!1:(string=string.trim(),!!string.match(createFuzzyRegExpFromString(crit)))}}module.exports=new FuzzySearchStrategy},{}],3:[function(require,module,exports){function LiteralSearchStrategy(){function doMatch(string,crit){return string.toLowerCase().indexOf(crit.toLowerCase())>=0}var self=this;self.matches=function(string,crit){return"string"!=typeof string?!1:(string=string.trim(),doMatch(string,crit))}}module.exports=new LiteralSearchStrategy},{}],4:[function(require,module,exports){module.exports=function(){function findMatches(store,crit,strategy){for(var data=store.get(),i=0;i<data.length&&matches.length<limit;i++)findMatchesInObject(data[i],crit,strategy);return matches}function findMatchesInObject(obj,crit,strategy){for(var key in obj)if(strategy.matches(obj[key],crit)){matches.push(obj);break}}function getSearchStrategy(){return fuzzy?fuzzySearchStrategy:literalSearchStrategy}var self=this,matches=[],fuzzy=!1,limit=10,fuzzySearchStrategy=require("./SearchStrategies/fuzzy"),literalSearchStrategy=require("./SearchStrategies/literal");self.setFuzzy=function(_fuzzy){fuzzy=!!_fuzzy},self.setLimit=function(_limit){limit=parseInt(_limit,10)||limit},self.search=function(data,crit){return crit?(matches.length=0,findMatches(data,crit,getSearchStrategy())):[]}}},{"./SearchStrategies/fuzzy":2,"./SearchStrategies/literal":3}],5:[function(require,module,exports){module.exports=function(_store){function isObject(obj){return!!obj&&"[object Object]"==Object.prototype.toString.call(obj)}function isArray(obj){return!!obj&&"[object Array]"==Object.prototype.toString.call(obj)}function addObject(data){return store.push(data),data}function addArray(data){for(var added=[],i=0;i<data.length;i++)isObject(data[i])&&added.push(addObject(data[i]));return added}var self=this,store=[];isArray(_store)&&addArray(_store),self.clear=function(){return store.length=0,store},self.get=function(){return store},self.put=function(data){return isObject(data)?addObject(data):isArray(data)?addArray(data):void 0}}},{}],6:[function(require,module,exports){module.exports=function(){var self=this,templatePattern=/\{(.*?)\}/g;self.setTemplatePattern=function(newTemplatePattern){templatePattern=newTemplatePattern},self.render=function(t,data){return t.replace(templatePattern,function(match,prop){return data[prop]||match})}}},{}],7:[function(require,module,exports){!function(window,document,undefined){"use strict";function initWithJSON(json){store.put(opt.json),registerInput()}function initWithURL(url){jsonLoader.load(url,function(err,json){err?throwError("failed to get JSON ("+url+")"):(store.put(json),registerInput())})}function throwError(message){throw new Error("SimpleJekyllSearch --- "+message)}function validateOptions(_opt){for(var i=0;i<requiredOptions.length;i++){var req=requiredOptions[i];_opt[req]||throwError("You must specify a "+req)}}function assignOptions(_opt){for(var option in opt)opt[option]=_opt[option]||opt[option]}function isJSON(json){try{return json instanceof Object&&JSON.parse(JSON.stringify(json))}catch(e){return!1}}function emptyResultsContainer(){opt.resultsContainer.innerHTML=""}function appendToResultsContainer(text){opt.resultsContainer.innerHTML+=text}function registerInput(){opt.searchInput.addEventListener("keyup",function(e){return 0==e.target.value.length?void emptyResultsContainer():void render(searcher.search(store,e.target.value))})}function render(results){if(emptyResultsContainer(),0==results.length)return appendToResultsContainer(opt.noResultsText);for(var i=0;i<results.length;i++)appendToResultsContainer(templater.render(opt.searchResultTemplate,results[i]))}var Searcher=require("./Searcher"),Templater=require("./Templater"),Store=require("./Store"),JSONLoader=require("./JSONLoader"),searcher=new Searcher,templater=new Templater,store=new Store,jsonLoader=new JSONLoader,requiredOptions=["searchInput","resultsContainer","json"],opt={searchInput:null,resultsContainer:null,json:[],searchResultTemplate:'
{title}
',noResultsText:"No results found",limit:10,fuzzy:!1};window.SimpleJekyllSearch=function(_opt){validateOptions(_opt),assignOptions(_opt),isJSON(opt.json)?initWithJSON(opt.json):initWithURL(opt.json)}}(window,document)},{"./JSONLoader":1,"./Searcher":4,"./Store":5,"./Templater":6}]},{},[7]);

SimpleJekyllSearch({
        searchInput: document.getElementById('search-input'),
        resultsContainer: document.getElementById('search-results'),
        json: '/search.json',
        searchResultTemplate: '
{title}
',
        noResultsText: '

',
        limit: 5,
        fuzzy: true,
});<|endoftext|>


<commit_before>var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
// Haltestellen in Y Achse
// Name der Haltestelle, Entfernung vom Startpunkt in m
var ratio = 1;
var stops = [

		{
				"name": "piazza domenicani - Domenikanerplatz",
				"arrivaltime": null,
				"departuretime": {
						"hour": 17,
						"min": 0
				},
				"diff": "0",
				"abs": "0"
		},
		{
				"name": "EURAC",
				"arrivaltime": {
						"hour": 17,
						"min": 2
				},
				"departuretime": {
						"hour": 17,
						"min": 2
				},
				"diff": "1000",
				"abs": "1000"
		},
		{
				"name": "TIS",
				"arrivaltime": {
						"hour": 17,
						"min": 9
				},
				"departuretime": {
						"hour": 17,
						"min": 9
				},
				"diff": "2500",
				"abs": "3500"
		},
		{
				"name": "SEL Ecotherm",
				"arrivaltime": {
						"hour": 17,
						"min": 13
				},
				"departuretime": {
						"hour": 17,
						"min": 13
				},
				"diff": "3000",
				"abs": "6500"
		},
		{
				"name": "SALEWA",
				"arrivaltime": {
						"hour": 17,
						"min": 20
				},
				"departuretime": {
						"hour": 17,
						"min": 20
				},
				"diff": "1000",
				"abs": "7500"
		},
		{
				"name": "IIT",
				"arrivaltime": {
						"hour": 17,
						"min": 23
				},
				"departuretime": {
						"hour": 23,
						"min": 23
				},
				"diff": "2200",
				"abs": "9700"
		},
		{
				"name": "TIS",
				"arrivaltime": {
						"hour": 17,
						"min": 27
				},
				"departuretime": {
						"hour": 17,
						"min": 27
				},
				"diff": "3000",
				"abs": "12700"
		},
		{
				"name": "EURAC",
				"arrivaltime": {
						"hour": 17,
						"min": 35
				},
				"departuretime": {
						"hour": 17,
						"min": 35
				},
				"diff": "2700",
				"abs": "15400"
		},
		{
				"name": "piazza Domenicani",
				"arrivaltime": {
						"hour": 17,
						"min": 38
				},
				"departuretime": null,
				"diff": "1200",
				"abs": "16600"
		}

];

// Liste von Punkten des Diagramms
// Timestamp, Entfernung vom Startpunkt in m
var points = [
	[[14,26,00],13],
	[[14,26,01],22],
	[[14,26,03],31],
	[[14,26,04],44],
	[[14,26,05],52]
]

/*
// Constants
var w;
var h;

var length_mult;
var time_mult;

var time_extra_factor;

var space;

// Visual stuff
var thin;
var thick;
var grid_grey;

// Data
var total_time;
var total_length;
var total_grid_w;
var total_grid_h;

var start_time;

var h = total_grid_h + 2 * space;
var time_mult = total_grid_w / total_time; // multiplier: px/min
*/

function init() {
	// Constants
	w =  canvas.width / ratio;
	length_mult = 0.03; // multiplier: px/m

	time_extra_factor = 0.9;

	space = 15; // horizontal space left/right of grid
	top_space = 40;
	text_width = 100;
	tick_length = 10;

	// Data
	total_time = 60;
	total_length = stops[stops.length-1].abs;

	total_grid_w = w - 2 * space - text_width;
	total_grid_h = length_mult * total_length;

	start_min = stops[0].departuretime.min - (stops[0].departuretime.min) % 10;
	start_hour = stops[0].departuretime.hour;

	time_offset_graph = (stops[0].departuretime.min) % 10;

	h = total_grid_h + 2 * top_space;
	time_mult = total_grid_w / total_time; // multiplier: px/min

	// Visual
	thin = 2;
	thick = 3;
	grid_grey = "#bbb";
	grid_dark = "#555";
}

// Clear the canvas and redraw it every 1000ms
window.setInterval(function(){
	draw();
}, 1000);

function draw() {
	init();
	context.clearRect(0, 0, canvas.width, canvas.height);
	drawTimeGrid();
	drawStopGrid();
	drawBus();
}

// Drawing Functions

function drawTimeGrid() {
	for (var i = 0; i < 8; i++) {
		// long grey lines
		context.beginPath();
		context.moveTo(space + i * time_mult * 10 + text_width, top_space);
		context.lineTo(space + i * time_mult * 10 + text_width, top_space + total_grid_h);
		context.lineWidth = thin;
		context.strokeStyle = (i == 0 || i == 6)?grid_dark:grid_grey;
		context.stroke();

		// small black ticks
		context.beginPath();
		context.moveTo(space + i * time_mult * 10 + text_width, top_space - tick_length);
		context.lineTo(space + i * time_mult * 10 + text_width, top_space);
		context.lineWidth = thin;
		context.strokeStyle = grid_dark;
		context.stroke();

		// time text
		var mins = (i < 6)?(start_min + i * 10):0;
		var hours = (i < 6)?start_hour:start_hour + 1;
		var time_format = ((hours < 10)? "0" + hours : hours) + ":" + ((mins < 10)? "0" + mins : mins);

		context.font = "500 8pt 'Fira Sans'";
		context.fillStyle = "#000";
		context.textAlign="right";
		context.fillText(time_format, space + text_width + i * time_mult * 10 + 13, top_space - 20);
	}
}

function drawStopGrid() {
	stops.forEach(function(stop, i) {

		// horizontal grid lines
		context.beginPath();
		context.moveTo(space + text_width - tick_length, top_space + stop.abs * length_mult);
		context.lineTo(space + total_grid_w + text_width, top_space + stop.abs * length_mult);
		context.lineWidth = thin;
		context.strokeStyle = grid_dark;
		context.stroke();

		// stop names
		context.font = "400 9pt 'Fira Sans'";
		context.fillStyle = "#000";
		context.textAlign="right";
		context.fillText(fittingString(context, stop.name, text_width - space), text_width - space/2, top_space + stop.abs * length_mult);
	});
}

function drawBus() {
	stops.forEach(function(stop, i) {
		lg(stop);

		var left_offset = space + text_width + time_offset_graph;
		var top_offset = top_space;

		if (i != 0) {
			var dep = stops[i-1];
			var arr = stop;

			var dep_left = (dep.departuretime.hour * 60 + dep.departuretime.min) * time_mult;
			var dep_top = dep.abs * length_mult;

			var arr_left = (arr.arrivaltime.hour * 60 + arr.arrivaltime.min) * time_mult;
			var arr_top = arr.abs * length_mult;

			// horizontal grid lines
			context.beginPath();
			context.moveTo(left_offset + dep_left, top_space + dep_top);
			context.lineTo(left_offset + arr_left, top_space + arr_top);
			context.lineWidth = thick;
			context.strokeStyle = "red";
			context.stroke();
		}
		if (i != stops.length-1) {
			var dep = stops[i-1];
			var arr = stop;
			lg(i-1);
			var dep_left = (dep.arrivaltime.hour * 60 + dep.arrivaltime.min) * time_mult;
			var dep_top = dep.abs * length_mult;

			var arr_left = (arr.departuretime.hour * 60 + arr.departuretime.min) * time_mult;
			var arr_top = dep.abs * length_mult;

			// horizontal grid lines
			context.beginPath();
			context.moveTo(left_offset + dep_left, top_space + dep_top);
			context.lineTo(left_offset + arr_left, top_space + arr_top);
			context.lineWidth = thick;
			context.strokeStyle = "red";
			context.stroke();
		}
	});
}

function maxCanvas() {
	console.log(window.innerWidth);
	canvas.width = window.innerWidth;
	canvas.height = h;
  scale();
	draw();
}

// EVENTS

window.onload = function(){
	init();
	maxCanvas();
};
window.onresize = function(){
	init();
	maxCanvas();
};

// UTILS
function lg(string) {
	console.log(string);
}

function fittingString(c, str, maxWidth) {
	var width = c.measureText(str).width;
	var ellipsis = '...';
	var ellipsisWidth = c.measureText(ellipsis).width;
	if (width<=maxWidth || width<=ellipsisWidth) {
		return str;
	} else {
		var len = str.length;
		while (width>=maxWidth-ellipsisWidth && len-->0) {
			str = str.substring(0, len);
			width = c.measureText(str).width;
		}
	return str+ellipsis;
	}
}
function scale() {
  var devicePixelRatio = window.devicePixelRatio || 1;
  var backingStoreRatio = context.webkitBackingStorePixelRatio ||
    context.mozBackingStorePixelRatio ||
    context.msBackingStorePixelRatio ||
    context.oBackingStorePixelRatio ||
    context.backingStorePixelRatio || 1;

  ratio = devicePixelRatio / backingStoreRatio;

  // upscale the canvas if the two ratios don't match
  if (devicePixelRatio !== backingStoreRatio) {
    var oldWidth = canvas.width;
    var oldHeight = canvas.height;

    canvas.width = oldWidth * ratio;
    canvas.height = oldHeight * ratio;

    canvas.style.width = oldWidth + 'px';
    canvas.style.height = oldHeight + 'px';

    // now scale the context to counter
    // the fact that we've manually scaled
    // our canvas element
    context.scale(ratio, ratio);
    return ratio;
  }
}
APIrequest("http://192.168.26.109/ajax/busstops.php");

function APIrequest(url) {
 function reqListener () {
     console.log(this.responseText);
 }

 var oReq = new XMLHttpRequest();
 oReq.onload = reqListener;
 oReq.open("get", url, true);
 oReq.send();
}
<commit_msg>[fix] fixed planeddata<commit_after>var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
// Haltestellen in Y Achse
// Name der Haltestelle, Entfernung vom Startpunkt in m
var ratio = 1;
var stops = [

		{
				"name": "piazza domenicani - Domenikanerplatz",
				"arrivaltime": null,
				"departuretime": {
						"hour": 17,
						"min": 0
				},
				"diff": "0",
				"abs": "0"
		},
		{
				"name": "EURAC",
				"arrivaltime": {
						"hour": 17,
						"min": 2
				},
				"departuretime": {
						"hour": 17,
						"min": 2
				},
				"diff": "1000",
				"abs": "1000"
		},
		{
				"name": "TIS",
				"arrivaltime": {
						"hour": 17,
						"min": 9
				},
				"departuretime": {
						"hour": 17,
						"min": 9
				},
				"diff": "2500",
				"abs": "3500"
		},
		{
				"name": "SEL Ecotherm",
				"arrivaltime": {
						"hour": 17,
						"min": 13
				},
				"departuretime": {
						"hour": 17,
						"min": 13
				},
				"diff": "3000",
				"abs": "6500"
		},
		{
				"name": "SALEWA",
				"arrivaltime": {
						"hour": 17,
						"min": 20
				},
				"departuretime": {
						"hour": 17,
						"min": 20
				},
				"diff": "1000",
				"abs": "7500"
		},
		{
				"name": "IIT",
				"arrivaltime": {
						"hour": 17,
						"min": 23
				},
				"departuretime": {
						"hour": 23,
						"min": 23
				},
				"diff": "2200",
				"abs": "9700"
		},
		{
				"name": "TIS",
				"arrivaltime": {
						"hour": 17,
						"min": 27
				},
				"departuretime": {
						"hour": 17,
						"min": 27
				},
				"diff": "3000",
				"abs": "12700"
		},
		{
				"name": "EURAC",
				"arrivaltime": {
						"hour": 17,
						"min": 35
				},
				"departuretime": {
						"hour": 17,
						"min": 35
				},
				"diff": "2700",
				"abs": "15400"
		},
		{
				"name": "piazza Domenicani",
				"arrivaltime": {
						"hour": 17,
						"min": 38
				},
				"departuretime": null,
				"diff": "1200",
				"abs": "16600"
		}

];

// Liste von Punkten des Diagramms
// Timestamp, Entfernung vom Startpunkt in m
var points = [
	[[14,26,00],13],
	[[14,26,01],22],
	[[14,26,03],31],
	[[14,26,04],44],
	[[14,26,05],52]
]

/*
// Constants
var w;
var h;

var length_mult;
var time_mult;

var time_extra_factor;

var space;

// Visual stuff
var thin;
var thick;
var grid_grey;

// Data
var total_time;
var total_length;
var total_grid_w;
var total_grid_h;

var start_time;

var h = total_grid_h + 2 * space;
var time_mult = total_grid_w / total_time; // multiplier: px/min
*/

function init() {
	// Constants
	w =  canvas.width / ratio;
	length_mult = 0.03; // multiplier: px/m

	time_extra_factor = 0.9;

	space = 15; // horizontal space left/right of grid
	top_space = 40;
	text_width = 100;
	tick_length = 10;

	// Data
	total_time = 60;
	total_length = stops[stops.length-1].abs;

	total_grid_w = w - 2 * space - text_width;
	total_grid_h = length_mult * total_length;

	start_min = stops[0].departuretime.min - (stops[0].departuretime.min) % 10;
	start_hour = stops[0].departuretime.hour;

	time_offset_graph = (stops[0].departuretime.min) % 10;

	h = total_grid_h + 2 * top_space;
	time_mult = total_grid_w / total_time; // multiplier: px/min

	// Visual
	thin = 2;
	thick = 3;
	grid_grey = "#bbb";
	grid_dark = "#555";
}

// Clear the canvas and redraw it every 1000ms
window.setInterval(function(){
	draw();
}, 1000);

function draw() {
	init();
	context.clearRect(0, 0, canvas.width, canvas.height);
	drawTimeGrid();
	drawStopGrid();
	drawBus();
}

// Drawing Functions

function drawTimeGrid() {
	for (var i = 0; i < 8; i++) {
		// long grey lines
		context.beginPath();
		context.moveTo(space + i * time_mult * 10 + text_width, top_space);
		context.lineTo(space + i * time_mult * 10 + text_width, top_space + total_grid_h);
		context.lineWidth = thin;
		context.strokeStyle = (i == 0 || i == 6)?grid_dark:grid_grey;
		context.stroke();

		// small black ticks
		context.beginPath();
		context.moveTo(space + i * time_mult * 10 + text_width, top_space - tick_length);
		context.lineTo(space + i * time_mult * 10 + text_width, top_space);
		context.lineWidth = thin;
		context.strokeStyle = grid_dark;
		context.stroke();

		// time text
		var mins = (i < 6)?(start_min + i * 10):0;
		var hours = (i < 6)?start_hour:start_hour + 1;
		var time_format = ((hours < 10)? "0" + hours : hours) + ":" + ((mins < 10)? "0" + mins : mins);

		context.font = "500 8pt 'Fira Sans'";
		context.fillStyle = "#000";
		context.textAlign="right";
		context.fillText(time_format, space + text_width + i * time_mult * 10 + 13, top_space - 20);
	}
}

function drawStopGrid() {
	stops.forEach(function(stop, i) {

		// horizontal grid lines
		context.beginPath();
		context.moveTo(space + text_width - tick_length, top_space + stop.abs * length_mult);
		context.lineTo(space + total_grid_w + text_width, top_space + stop.abs * length_mult);
		context.lineWidth = thin;
		context.strokeStyle = grid_dark;
		context.stroke();

		// stop names
		context.font = "400 9pt 'Fira Sans'";
		context.fillStyle = "#000";
		context.textAlign="right";
		context.fillText(fittingString(context, stop.name, text_width - space), text_width - space/2, top_space + stop.abs * length_mult);
	});
}

function drawBus() {
	var left_offset = space + text_width - (stops[0].departuretime.hour * 60 + stops[0].departuretime.min) * time_mult;
	var top_offset = top_space;
	stops.forEach(function(stop, i) {
		lg(stop);

		if (i < stops.length-1) {
			var dep = stop;
			var arr = stops[i+1];

      lg(i);
			var dep_left = (dep.departuretime.hour * 60 + dep.departuretime.min) * time_mult;
			var dep_top = dep.abs * length_mult;

			var arr_left = (arr.arrivaltime.hour * 60 + arr.arrivaltime.min) * time_mult;
			var arr_top = arr.abs * length_mult;

			// horizontal grid lines
			context.beginPath();
			context.moveTo(left_offset + dep_left, top_offset + dep_top);
			context.lineTo(left_offset + arr_left, top_offset + arr_top);
			context.lineWidth = thick;
			context.strokeStyle = "red";
			context.stroke();
		}
	/*	if (i != stops.length-1) {
			var dep = stops[i-1];
			var arr = stop;
			lg(i-1);
			var dep_left = (dep.arrivaltime.hour * 60 + dep.arrivaltime.min) * time_mult;
			var dep_top = dep.abs * length_mult;

			var arr_left = (arr.departuretime.hour * 60 + arr.departuretime.min) * time_mult;
			var arr_top = dep.abs * length_mult;

			// horizontal grid lines
			context.beginPath();
			context.moveTo(left_offset + dep_left, top_space + dep_top);
			context.lineTo(left_offset + arr_left, top_space + arr_top);
			context.lineWidth = thick;
			context.strokeStyle = "red";
			context.stroke();
		}*/
	});
}

function maxCanvas() {
	console.log(window.innerWidth);
	canvas.width = window.innerWidth;
	canvas.height = h;
  scale();
	draw();
}

// EVENTS

window.onload = function(){
	init();
	maxCanvas();
};
window.onresize = function(){
	init();
	maxCanvas();
};

// UTILS
function lg(string) {
	console.log(string);
}

function fittingString(c, str, maxWidth) {
	var width = c.measureText(str).width;
	var ellipsis = '...';
	var ellipsisWidth = c.measureText(ellipsis).width;
	if (width<=maxWidth || width<=ellipsisWidth) {
		return str;
	} else {
		var len = str.length;
		while (width>=maxWidth-ellipsisWidth && len-->0) {
			str = str.substring(0, len);
			width = c.measureText(str).width;
		}
	return str+ellipsis;
	}
}
function scale() {
  var devicePixelRatio = window.devicePixelRatio || 1;
  var backingStoreRatio = context.webkitBackingStorePixelRatio ||
    context.mozBackingStorePixelRatio ||
    context.msBackingStorePixelRatio ||
    context.oBackingStorePixelRatio ||
    context.backingStorePixelRatio || 1;

  ratio = devicePixelRatio / backingStoreRatio;

  // upscale the canvas if the two ratios don't match
  if (devicePixelRatio !== backingStoreRatio) {
    var oldWidth = canvas.width;
    var oldHeight = canvas.height;

    canvas.width = oldWidth * ratio;
    canvas.height = oldHeight * ratio;

    canvas.style.width = oldWidth + 'px';
    canvas.style.height = oldHeight + 'px';

    // now scale the context to counter
    // the fact that we've manually scaled
    // our canvas element
    context.scale(ratio, ratio);
    return ratio;
  }
}
APIrequest("http://192.168.26.109/ajax/busstops.php");

function APIrequest(url) {
 function reqListener () {
     console.log(this.responseText);
 }

 var oReq = new XMLHttpRequest();
 oReq.onload = reqListener;
 oReq.open("get", url, true);
 oReq.send();
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

var fs = require("fs"),
    rss = require("rss"),
    mustache = require("mustache"),
    chalk = require("chalk"),
    ncp = require("ncp"),
    prompt = require("prompt"),
    dateFormat = require("dateformat"),
    marked = require("marked"),
    optp = require("nomnom").script("shock"),
    wordcount = require('wordcount');

marked.setOptions({
    smartypants: true
});

var success = chalk.green,
    failure = chalk.red;

function isMarkdown(name) {
    return name.split(".")[name.split(".").length-1] === "md";
}
function ensureHTML(name) {
    return isMarkdown(name) ? name.replace(/\.md$/, ".html") : name;
}

prompt.message = "(shock)";

optp.command("init")
    .callback(function() {
        prompt.start();
        prompt.get(['title', 'author', 'description', 'url'], function(err, x) {
            if (err) {
                console.log(failure("Aborted."));
                process.exit();
            }
            ncp(__dirname+"/init", ".", function(err) {
                if (err) {
                    console.log(failure("Failed to create directory structure. Hmph."));
                    process.exit();
                }
                fs.readFile("index.json", function(err, data) {
                    var index = JSON.parse(data);
                    index.title = x.title;
                    index.author = x.author;
                    index.description = x.description;
                    index.url = x.url;
                    fs.writeFile("index.json", JSON.stringify(index, null, 4), function(err) {
                        console.log(success("Minimal shock site initialized."));
                    });
                });
            });
        });
    });

optp.command("compile")
    .callback(function() {
        fs.readFile("index.json", function(err, data) {
            if (err) {
                throw err;
            }
            var index;
            try {
                index = JSON.parse(data);
            } catch(e) {
                console.log(failure("index.json failed to parse (it has to be honest json, not a js object literal!)"));
                process.exit();
            }

            var header = fs.readFileSync("templates/" + index.templates.header).toString();
            var footer = fs.readFileSync("templates/" + index.templates.footer).toString();
            var postpage = fs.readFileSync("templates/" + index.templates.postpage).toString();
            var home = fs.readFileSync("templates/" + index.templates.home).toString();
            var notfound = fs.readFileSync("templates/" + index.templates["404"]).toString();

            // Create RSS feed
            var feed = new rss({
                title: index.title,
                description: index.description,
                site_url: index.url,
                feed_url: index.url+"/feed.xml",
                image_url: index.img,
                author: index.author,
                language: index.lang || "en",
            });

            var items = index.posts.sort(function(a, b) {
                return new Date(b.date).getTime() - new Date(a.date).getTime();
            }).filter(function(p) {
                return !p.draft;
            }).slice(0, 10);
            items.forEach(function(item) {
                var content = fs.readFileSync("content/" + item.file).toString();
                feed.item({
                    title: item.title,
                    description: marked(item.description) + "\n\n" + (item.markdown ? marked(content) : content),
                    url: index.url + "/" + ensureHTML(item.file),
                    date: item.date,
                    author: item.author || index.author
                });

                var view = {
                    title: item.title,
                    description: marked(item.description),
                    date: dateFormat(new Date(item.date), "fullDate"),
                    author: item.author,
                    header: header,
                    footer: footer,
                    content: item.markdown ? marked(content) : content,
                    file: item.file,
                    time: Math.ceil(wordcount(content) / 5.5 / 60)
                }
                fs.writeFile(ensureHTML(item.file), mustache.render(postpage, view), function() {
                    console.log(success("Created " + item.file));
                });

            });

            fs.writeFile("feed.xml", feed.xml("    "), function() {
                console.log(success("Created RSS feed."));
            });
            fs.writeFile("404.html", mustache.render(notfound, {
                header: header,
                footer: footer,
            }), function() {
                console.log(success("Created 404.html"));
            });

            fs.writeFile("index.html", mustache.render(home, {
                header: header,
                footer: footer,
                posts: items.map(function(i) {
                    i.file = ensureHTML(i.file);
                    i.date = dateFormat(new Date(i.date), "shortDate");
                    i.description = marked(i.description);
                    return i;
                })
            }), function() {
                console.log(success("Created homepage."));
            });
        });
    });

optp.command("newpost")
    .callback(function() {
        fs.readFile("index.json", function(err, data) {
            if (err) {
                console.log(failure("Couldn't read index.json."));
                process.exit();
            }
            var index = JSON.parse(data);
            prompt.start();
            prompt.get(
                ['title', 'author', 'description', 'file', 'date'],
                function(err, data) {
                    if (err) {
                        console.log(failure("Aborted."));
                        process.exit();
                    }
                    if (isMarkdown(data.file)) {
                        data.markdown = true;
                    }
                    data.author = data.author || index.author;
                    data.date = data.date || dateFormat(Date.now(), "shortDate");
                    index.posts.push(data);

                    fs.writeFile("index.json", JSON.stringify(index, null, 4), function(err) {
                        console.log(success("Post created."));
                    });
                });
        })
    });

optp.command("rm")
    .option("name", {
        position: 1,
        required: true
    })
    .callback(function() {
        fs.readFile("index.json", function(err, data) {
            if (err) {
                console.log(failure("Couldn't read index.json."));
                process.exit();
            }
            var index = JSON.parse(data);

            for (var i=0; i<index.posts.length; i++) {
                if (index.posts[i].file === opts.name) {
                    index.posts.splice(i, 1);
                    console.log(success("Deleted."));
                    break;
                }
            }
            if (i === index.posts.length) {
                console.log(failure("Nothing deleted."));
            }

            fs.writeFile("index.json", JSON.stringify(index, null, 4), function(err) {
                console.log(success("Updated index."));
            });

        })
    });

var opts = optp.parse();
<commit_msg>no really i have no idea how any of this works<commit_after>#!/usr/bin/env node

var fs = require("fs"),
    rss = require("rss"),
    mustache = require("mustache"),
    chalk = require("chalk"),
    ncp = require("ncp"),
    prompt = require("prompt"),
    dateFormat = require("dateformat"),
    marked = require("marked"),
    optp = require("nomnom").script("shock"),
    wordcount = require('wordcount');

marked.setOptions({
    smartypants: true
});

var success = chalk.green,
    failure = chalk.red;

function isMarkdown(name) {
    return name.split(".")[name.split(".").length-1] === "md";
}
function ensureHTML(name) {
    return isMarkdown(name) ? name.replace(/\.md$/, ".html") : name;
}

prompt.message = "(shock)";

optp.command("init")
    .callback(function() {
        prompt.start();
        prompt.get(['title', 'author', 'description', 'url'], function(err, x) {
            if (err) {
                console.log(failure("Aborted."));
                process.exit();
            }
            ncp(__dirname+"/init", ".", function(err) {
                if (err) {
                    console.log(failure("Failed to create directory structure. Hmph."));
                    process.exit();
                }
                fs.readFile("index.json", function(err, data) {
                    var index = JSON.parse(data);
                    index.title = x.title;
                    index.author = x.author;
                    index.description = x.description;
                    index.url = x.url;
                    fs.writeFile("index.json", JSON.stringify(index, null, 4), function(err) {
                        console.log(success("Minimal shock site initialized."));
                    });
                });
            });
        });
    });

optp.command("compile")
    .callback(function() {
        fs.readFile("index.json", function(err, data) {
            if (err) {
                throw err;
            }
            var index;
            try {
                index = JSON.parse(data);
            } catch(e) {
                console.log(failure("index.json failed to parse (it has to be honest json, not a js object literal!)"));
                process.exit();
            }

            var header = fs.readFileSync("templates/" + index.templates.header).toString();
            var footer = fs.readFileSync("templates/" + index.templates.footer).toString();
            var postpage = fs.readFileSync("templates/" + index.templates.postpage).toString();
            var home = fs.readFileSync("templates/" + index.templates.home).toString();
            var notfound = fs.readFileSync("templates/" + index.templates["404"]).toString();

            // Create RSS feed
            var feed = new rss({
                title: index.title,
                description: index.description,
                site_url: index.url,
                feed_url: index.url+"/feed.xml",
                image_url: index.img,
                author: index.author,
                language: index.lang || "en",
            });

            var items = index.posts.sort(function(a, b) {
                return new Date(b.date).getTime() - new Date(a.date).getTime();
            }).filter(function(p) {
                return !p.draft;
            });
            items.forEach(function(item, i) {
                var content = fs.readFileSync("content/" + item.file).toString();

                if (i < 10) {
                  feed.item({
                      title: item.title,
                      description: marked(item.description) + "\n\n" + (item.markdown ? marked(content) : content),
                      url: index.url + "/" + ensureHTML(item.file),
                      date: item.date,
                      author: item.author || index.author
                  });
                }

                var view = {
                    title: item.title,
                    description: marked(item.description),
                    date: dateFormat(new Date(item.date), "fullDate"),
                    author: item.author,
                    header: header,
                    footer: footer,
                    content: item.markdown ? marked(content) : content,
                    file: item.file,
                    time: Math.ceil(wordcount(content) / 5.5 / 60)
                }
                fs.writeFile(ensureHTML(item.file), mustache.render(postpage, view), function() {
                    console.log(success("Created " + item.file));
                });

            });

            fs.writeFile("feed.xml", feed.xml("    "), function() {
                console.log(success("Created RSS feed."));
            });
            fs.writeFile("404.html", mustache.render(notfound, {
                header: header,
                footer: footer,
            }), function() {
                console.log(success("Created 404.html"));
            });

            fs.writeFile("index.html", mustache.render(home, {
                header: header,
                footer: footer,
                posts: items.map(function(i) {
                    i.file = ensureHTML(i.file);
                    i.date = dateFormat(new Date(i.date), "shortDate");
                    i.description = marked(i.description);
                    return i;
                })
            }), function() {
                console.log(success("Created homepage."));
            });
        });
    });

optp.command("newpost")
    .callback(function() {
        fs.readFile("index.json", function(err, data) {
            if (err) {
                console.log(failure("Couldn't read index.json."));
                process.exit();
            }
            var index = JSON.parse(data);
            prompt.start();
            prompt.get(
                ['title', 'author', 'description', 'file', 'date'],
                function(err, data) {
                    if (err) {
                        console.log(failure("Aborted."));
                        process.exit();
                    }
                    if (isMarkdown(data.file)) {
                        data.markdown = true;
                    }
                    data.author = data.author || index.author;
                    data.date = data.date || dateFormat(Date.now(), "shortDate");
                    index.posts.push(data);

                    fs.writeFile("index.json", JSON.stringify(index, null, 4), function(err) {
                        console.log(success("Post created."));
                    });
                });
        })
    });

optp.command("rm")
    .option("name", {
        position: 1,
        required: true
    })
    .callback(function() {
        fs.readFile("index.json", function(err, data) {
            if (err) {
                console.log(failure("Couldn't read index.json."));
                process.exit();
            }
            var index = JSON.parse(data);

            for (var i=0; i<index.posts.length; i++) {
                if (index.posts[i].file === opts.name) {
                    index.posts.splice(i, 1);
                    console.log(success("Deleted."));
                    break;
                }
            }
            if (i === index.posts.length) {
                console.log(failure("Nothing deleted."));
            }

            fs.writeFile("index.json", JSON.stringify(index, null, 4), function(err) {
                console.log(success("Updated index."));
            });

        })
    });

var opts = optp.parse();
<|endoftext|>


<commit_before>define(function(require) {
var Backbone = require('backbone'),
    ContentView = require('streamhub-backbone/views/ContentView');

var TimelineView = Backbone.View.extend(
{
    initialize: function (opts) {
        this.$el.addClass(this.className);
        this.$el.hide();
        this.startDate = opts.startDate || new Date(0);
        this.endDate = opts.startDate || new Date(Math.pow(10,15));

        this.collection.on('add', this._insertItem, this);
        //this.collection.on('initialDataLoaded', this.render, this);
    },
    className: "hub-TimelineView",
    render: function () {
    	var listHolder = $(document.createElement('div'));
    	listHolder.addClass('events');

    	this.listEl = $(document.createElement('ul'));

    	listHolder.append(this.listEl);
    	this.$el.append($(document.createElement('div')).addClass('line-bg'));
    	this.$el.append(listHolder);

        this.$el.fadeIn();
    }
});

TimelineView.prototype._insertItem = function (item, col) {
    var itemEl = $(document.createElement('li'));
    itemEl.addClass('event-dot');
    itemEl.hide();

    var itemDescEl = $(document.createElement('div'));
    itemDescEl.addClass('event-desc');
    itemDescEl.html(item.get('bodyHtml') + '
' + item.get('createdAt'));
    itemDescEl.hide();

    itemEl.append(itemDescEl);
    itemEl.mouseenter(function() { itemDescEl.fadeIn(); });
    itemEl.mouseleave(function() { itemDescEl.fadeOut(); });

    this.listEl.append(itemEl);
    console.log(this.listEl);
    itemEl.fadeIn();

    return itemEl;
};

return TimelineView;
});
<commit_msg>render added<commit_after>define(function(require) {
var Backbone = require('backbone'),
    ContentView = require('streamhub-backbone/views/ContentView');

var TimelineView = Backbone.View.extend(
{
    initialize: function (opts) {
        this.$el.addClass(this.className);
        this.$el.hide();
        this.startDate = opts.startDate || new Date(0);
        this.endDate = opts.startDate || new Date(Math.pow(10,15));

        this.collection.on('add', this._insertItem, this);
        this.render();
    },
    className: "hub-TimelineView",
    render: function () {
    	var listHolder = $(document.createElement('div'));
    	listHolder.addClass('events');

    	this.listEl = $(document.createElement('ul'));

    	listHolder.append(this.listEl);
    	this.$el.append($(document.createElement('div')).addClass('line-bg'));
    	this.$el.append(listHolder);

        this.$el.fadeIn();
    }
});

TimelineView.prototype._insertItem = function (item, col) {
    var itemEl = $(document.createElement('li'));
    itemEl.addClass('event-dot');
    itemEl.hide();

    var itemDescEl = $(document.createElement('div'));
    itemDescEl.addClass('event-desc');
    itemDescEl.html(item.get('bodyHtml') + '
' + item.get('createdAt'));
    itemDescEl.hide();

    itemEl.append(itemDescEl);
    itemEl.mouseenter(function() { itemDescEl.fadeIn(); });
    itemEl.mouseleave(function() { itemDescEl.fadeOut(); });

    this.listEl.append(itemEl);
    console.log(this.listEl);
    itemEl.fadeIn();

    return itemEl;
};

return TimelineView;
});
<|endoftext|>