<commit_before>/*
 * Licensed to the Sakai Foundation (SF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The SF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */

// load the master sakai object to access all Sakai OAE API methods
require(["jquery", "sakai/sakai.api.core"], function($, sakai) {

    /**
     * @name sakai_global.mylibrary
     *
     * @class mylibrary
     *
     * @description
     * My Hello World is a dashboard widget that says hello to the current user
     * with text in the color of their choosing
     *
     * @version 0.0.1
     * @param {String} tuid Unique id of the widget
     * @param {Boolean} showSettings Show the settings of the widget or not
     */
    sakai_global.mylibrary = function (tuid, showSettings) {

        /////////////////////////////
        // Configuration variables //
        /////////////////////////////

        var mylibrary = {  // global data for mylibrary widget
            totalItems: 0,
            itemsPerPage: 8,
            currentPagenum: 1,
            sortBy: "_lastModified",
            sortOrder: "desc",
            isOwnerViewing: false,
            default_search_text: ""
        };

        // DOM jQuery Objects
        var $rootel = $("#" + tuid);  // unique container for each widget instance
        var $mylibrary_items = $("#mylibrary_items", $rootel);
        var $mylibrary_check = $(".mylibrary_check", $rootel);
        var $mylibrary_check_all = $("#mylibrary_check_all", $rootel);
        var $mylibrary_remove = $("#mylibrary_remove", $rootel);
        var $mylibrary_sortby = $("#mylibrary_sortby", $rootel);
        var $mylibrary_livefilter = $("#mylibrary_livefilter", $rootel);
        var $mylibrary_sortarea = $("#mylibrary_sortarea", $rootel);
        var $mylibrary_empty = $("#mylibrary_empty", $rootel);
        var $mylibrary_empty_note = $("#mylibrary_empty_note", $rootel);
        var $mylibrary_admin_actions = $("#mylibrary_admin_actions", $rootel);
        var $mylibrary_addcontent = $("#mylibrary_addcontent", $rootel);

        ///////////////////////
        // Utility Functions //
        ///////////////////////

        /**
         * Reset the current my library view
         *
         * @param {String} query  optional query string to limit search results
         */
        var reset = function (query) {
            $mylibrary_items.html("");
            $mylibrary_check_all.removeAttr("checked");
            $mylibrary_remove.attr("disabled", "disabled");
            var contextId = "";
            if(sakai_global.currentgroup){
                contextId = sakai_global.currentgroup.id;
            } else {
                contextId = sakai_global.profile.main.data.userid;
            }
            getLibraryItems(contextId,
                renderLibraryItems, query || false);
        };

        /**
         * Show the given page of library items.
         *
         * @param {int} pagenum The page number you want to display (not 0-indexed)
         */
        var showPage = function (pagenum) {
            showPager(pagenum);
            mylibrary.currentPagenum = pagenum;
            reset();
        };

        /**
         * Show the pager at the bottom of the page.
         *
         * @param {int} pagenum The number of the current page (not 0-indexed)
         */
        var showPager = function (pagenum) {
            mylibrary.currentPagenum = pagenum;
            if (Math.ceil(mylibrary.totalItems / mylibrary.itemsPerPage) > 1) {
                $("#mylibrary_pager", $rootel).pager({
                    pagenumber: pagenum,
                    pagecount: Math.ceil(mylibrary.totalItems / mylibrary.itemsPerPage),
                    buttonClickCallback: showPage
                });
            }
        };

        /**
         * Get personalized text for the given message bundle key based on
         * whether this library is owned by the viewer, or belongs to someone else.
         * The message should contain a '${firstname}' variable to replace with
         * and be located in this widget's properties files.
         *
         * @param {String} bundleKey The message bundle key
         */
        var getPersonalizedText = function (bundleKey) {
            if(sakai_global.currentgroup){
                return sakai.api.i18n.Widgets.getValueForKey(
                    "mylibrary","",bundleKey).replace(/\$\{firstname\}/gi,
                        sakai_global.currentgroup.data.authprofile["sakai:group-title"]);
            } else if (mylibrary.isOwnerViewing) {
                return sakai.api.i18n.Widgets.getValueForKey(
                    "mylibrary","",bundleKey).replace(/\$\{firstname\}/gi,
                        sakai.api.i18n.General.getValueForKey("YOUR").toLowerCase());
            } else {
                return sakai.api.i18n.Widgets.getValueForKey("mylibrary", "", bundleKey).replace(/\$\{firstname\}/gi, sakai_global.profile.main.data.basic.elements.firstName.value + "'s");
            }
        };

        ////////////////////
        // Event Handlers //
        ////////////////////

        $mylibrary_check.live("change", function (ev) {
            if ($(this).is(":checked")) {
                $mylibrary_remove.removeAttr("disabled");
            } else if (!$(".mylibrary_check:checked", $rootel).length) {
                $mylibrary_remove.attr("disabled", "disabled");
            }
        });

        $mylibrary_check_all.change(function (ev) {
            if ($(this).is(":checked")) {
                $(".mylibrary_check").attr("checked", "checked");
                $mylibrary_remove.removeAttr("disabled");
            } else {
                $(".mylibrary_check").removeAttr("checked");
                $mylibrary_remove.attr("disabled", "disabled");
            }
        });

        $mylibrary_remove.click(function (ev) {
            var $checked = $(".mylibrary_check:checked", $rootel);
            if ($checked.length) {
                var paths = [];
                $checked.each(function () {
                    paths.push("/p/" + this.id.split("mylibrary_check_")[1]);
                });
                $(window).trigger('init.deletecontent.sakai', [{
                    path: paths
                }, function (success) {
                    if (success) {
                        mylibrary.currentPagenum = 1;
                        reset();
                    }
                }]);
            }
        });

        $mylibrary_sortby.change(function (ev) {
            var sortSelection = this.options[this.selectedIndex].value;
            switch (sortSelection) {
                case "lastModified_asc":
                    mylibrary.sortBy = "_lastModified";
                    mylibrary.sortOrder = "asc";
                    break;
                default:
                    mylibrary.sortBy = "_lastModified";
                    mylibrary.sortOrder = "desc";
                    break;
            }
            reset();
        });

        $mylibrary_livefilter.keyup(function (ev) {
            var q = $.trim(this.value);
            if (q && ev.keyCode != 16) {
                $mylibrary_livefilter.addClass("mylibrary_livefilter_working");
                reset(q);
            }
            return false;
        });

        $mylibrary_livefilter.focus(function (ev) {
            $input = $(this);
            $input.removeClass("mylibrary_meta");
            if ($.trim($input.val()) === mylibrary.default_search_text) {
                $input.val("");
            }
        });

        $mylibrary_livefilter.blur(function (ev) {
            $input = $(this);
            if ($.trim($input.val()) === "") {
                $input.addClass("mylibrary_meta");
                $input.val(mylibrary.default_search_text);
            }
        });

        $mylibrary_addcontent.click(function (ev) {
            $(window).trigger("init.newaddcontent.sakai");
            return false;
        });

        ////////////////////////////////////////////
        // Data retrieval and rendering functions //
        ////////////////////////////////////////////

        /**
         * Gets the given user's library items and passes them to the callback
         * function
         *
         * @param {String} userid      the user id for the user whose library items we want
         * @param {Function} callback  function called with the following args:
         *     {Boolean} success - whether or not the fetch succeeded
         *     {Object} items - an array of library items or null if no success
         * @param {String} query       optional query string to limit search results
         */
        var getLibraryItems = function (userid, callback, query) {

            /**
             * Formats a tag list from the server for display in the UI
             *
             * @param {Array} tags  an array of tags from the server
             * @return {Array} an array of tags formatted for the UI
             */
            var formatTags = function (tags) {
                if (!tags) {
                    return null;
                }
                var formatted_tags = [];
                $.each(tags, function (i, name) {
                    formatted_tags.push({
                        name: name,
                        link: "/search#tag=/tags/" + name
                    });
                });
                return formatted_tags;
            };

            /**
             * Returns the number of people using the given item
             *
             * @param {Object} item  the item object returned from the server
             * @return {Number} the number of users using this item
             */
            var getNumPeopleUsing = function (item) {
                // Need KERN feed changes
                return 0;
            };

            /**
             * Returns the number of groups using the given item
             *
             * @param {Object} item  the item object returned from the server
             * @return {Number} the number of groups using this item
             */
            var getNumGroupsUsing = function (item) {
                // Need KERN feed changes
                return 0;
            };

            /**
             * Returns the number of comments for the given item
             *
             * @param {Object} item  the item object returned from the server
             * @return {Number} the number of comments for this item
             */
            var getNumComments = function (item) {
                if (!item) {
                    return 0;
                }
                var id = item["jcr:path"];
                var count = 0;
                if (item[id + "/comments"]) {
                    $.each(item[id + "/comments"], function (param, value) {
                        if (param.indexOf("/comments/") != -1) {
                            count++;
                        }
                    });
                }
                return count;
            };

            /**
             * Process library item results from the server
             */
            var handleLibraryItems = function (success, data) {
                if (success && data && data.results) {
                    mylibrary.totalItems = data.total;
                    var items = [];
                    if (mylibrary.totalItems === 0) {
                        callback(true, items);
                        return;
                    }
                    $.each(data.results, function (i, result) {
                        var mimetypeObj = sakai.api.Content.getMimeTypeData(result["_mimeType"] || result["sakai:custom-mimetype"]);
                        items.push({
                            id: result["jcr:path"],
                            filename: result["sakai:pooled-content-file-name"],
                            link: "/content#content_path=/p/" + result["jcr:path"],
                            last_updated: $.timeago(new Date(result["_lastModified"])),
                            type: sakai.api.i18n.General.getValueForKey(mimetypeObj.description),
                            type_src: mimetypeObj.URL,
                            ownerid: result["sakai:pool-content-created-for"],
                            ownername: sakai.data.me.user.userid === result["sakai:pool-content-created-for"] ?
                                sakai.api.i18n.General.getValueForKey("YOU") :
                                result["sakai:pool-content-created-for"],  // using id for now - need to get firstName lastName
                            tags: formatTags(result["sakai:tags"]),
                            numPeopleUsing: getNumPeopleUsing(),
                            numGroupsUsing: getNumGroupsUsing(),
                            numComments: getNumComments(result),
                            mimeType: result["_mimeType"] || result["sakai:custom-mimetype"],
                            fullResult: result
                        });
                    });
                    if (callback && typeof(callback) === "function") {
                        callback(true, items);
                    }
                } else {
                    debug.error("Fetching library items for userid: " + userid + " failed");
                    if (callback && typeof(callback) === "function") {
                        callback(false, null);
                    }
                }
            };

            // fetch the data
            sakai.api.Server.loadJSON("/var/search/pool/manager-viewer.json",
                handleLibraryItems, {
                    userid: userid,
                    page: mylibrary.currentPagenum - 1,
                    items: mylibrary.itemsPerPage,
                    sortOn: mylibrary.sortBy,
                    sortOrder: mylibrary.sortOrder,
                    q: query || "*"
                }
            );
        };

        /**
         * Renders the given library items
         *
         * @param {Boolean} success - whether or not we have library items
         * @param {Array} items - an array of library items or null if no success
         */
        var renderLibraryItems = function (success, items) {
            if (success && items.length) {
                var json = {
                    items: items,
                    user_is_owner: function (item) {
                        if (!item) return false;
                        return sakai.data.me.user.userid === item.ownerid && mylibrary.isOwnerViewing;
                    },
                    user_is_manager: function (item) {
                        if (!item) return false;
                        return sakai.data.me.user.userid === item.ownerid;
                    }
                };
                json.sakai = sakai;
                if (mylibrary.isOwnerViewing) {
                    $mylibrary_admin_actions.show();
                }
                $mylibrary_livefilter.show();
                $mylibrary_sortarea.show();
                $mylibrary_empty.hide();
                $("#mylibrary_title_bar").show();
                $("#mylibrary_items", $rootel).html(sakai.api.Util.TemplateRenderer($("#mylibrary_items_template", $rootel), json));
                showPager(mylibrary.currentPagenum);
                $mylibrary_livefilter.removeClass("mylibrary_livefilter_working");
            } else {
                $mylibrary_admin_actions.hide();
                $mylibrary_livefilter.hide();
                $mylibrary_sortarea.hide();
                $("#mylibrary_title_bar").hide();
                $mylibrary_empty_note.html(getPersonalizedText("NO_ITEMS_IN_YOUR_LIBRARY"));
                $mylibrary_empty.show();
                if (mylibrary.isOwnerViewing) {
                    $mylibrary_addcontent.show();
                }
            }
        };

        /////////////////////////////
        // Initialization function //
        /////////////////////////////

        /**
         * Initialization function that is run when the widget is loaded. Determines
         * which mode the widget is in (settings or main), loads the necessary data
         * and shows the correct view.
         */
        var doInit = function () {
            var contextId = "";
            var contextName = "";
            var isGroup = false;
            if (sakai_global.currentgroup) {
                contextId = sakai_global.currentgroup.id;
                contextName = sakai_global.currentgroup.data.authprofile["sakai:group-title"];
                isGroup = true;
                if (sakai_global.currentgroup.manager) {
                    mylibrary.isOwnerViewing = true;
                }
            } else {
                contextId = sakai_global.profile.main.data.userid;
                contextName = sakai_global.profile.main.data.basic.elements.firstName.value;
                if (contextId === sakai.data.me.user.userid) {
                    mylibrary.isOwnerViewing = true;
                }
            }
            if (contextId) {
                mylibrary.default_search_text = getPersonalizedText("SEARCH_YOUR_LIBRARY");
                $mylibrary_livefilter.val(mylibrary.default_search_text);
                mylibrary.currentPagenum = 1;
                getLibraryItems(contextId, renderLibraryItems);
                sakai.api.Util.TemplateRenderer("mylibrary_title_template", {
                    isMe: mylibrary.isOwnerViewing,
                    isGroup: isGroup,
                    firstName: contextName
                }, $("#mylibrary_title_container", $rootel));
            } else {
                debug.warn("No user found for My Library");
            }
        };

        // run the initialization function when the widget object loads
        doInit();

        // Listen for complete.fileupload.sakai event (from the fileupload widget)
        // to refresh this widget's file listing
        $(window).bind("complete.fileupload.sakai", function() {
            mylibrary.currentPagenum = 1;
            reset();
        });

    };

    // inform Sakai OAE that this widget has loaded and is ready to run
    sakai.api.Widgets.widgetLoader.informOnLoad("mylibrary");
});
<commit_msg>NOJIRA - Fixing issue with filtering in library<commit_after>/*
 * Licensed to the Sakai Foundation (SF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The SF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */

// load the master sakai object to access all Sakai OAE API methods
require(["jquery", "sakai/sakai.api.core"], function($, sakai) {

    /**
     * @name sakai_global.mylibrary
     *
     * @class mylibrary
     *
     * @description
     * My Hello World is a dashboard widget that says hello to the current user
     * with text in the color of their choosing
     *
     * @version 0.0.1
     * @param {String} tuid Unique id of the widget
     * @param {Boolean} showSettings Show the settings of the widget or not
     */
    sakai_global.mylibrary = function (tuid, showSettings) {

        /////////////////////////////
        // Configuration variables //
        /////////////////////////////

        var mylibrary = {  // global data for mylibrary widget
            totalItems: 0,
            itemsPerPage: 8,
            currentPagenum: 1,
            sortBy: "_lastModified",
            sortOrder: "desc",
            isOwnerViewing: false,
            default_search_text: ""
        };

        // DOM jQuery Objects
        var $rootel = $("#" + tuid);  // unique container for each widget instance
        var $mylibrary_items = $("#mylibrary_items", $rootel);
        var $mylibrary_check = $(".mylibrary_check", $rootel);
        var $mylibrary_check_all = $("#mylibrary_check_all", $rootel);
        var $mylibrary_remove = $("#mylibrary_remove", $rootel);
        var $mylibrary_sortby = $("#mylibrary_sortby", $rootel);
        var $mylibrary_livefilter = $("#mylibrary_livefilter", $rootel);
        var $mylibrary_sortarea = $("#mylibrary_sortarea", $rootel);
        var $mylibrary_empty = $("#mylibrary_empty", $rootel);
        var $mylibrary_empty_note = $("#mylibrary_empty_note", $rootel);
        var $mylibrary_admin_actions = $("#mylibrary_admin_actions", $rootel);
        var $mylibrary_addcontent = $("#mylibrary_addcontent", $rootel);

        ///////////////////////
        // Utility Functions //
        ///////////////////////

        /**
         * Reset the current my library view
         *
         * @param {String} query  optional query string to limit search results
         */
        var reset = function (query) {
            $mylibrary_items.html("");
            $mylibrary_check_all.removeAttr("checked");
            $mylibrary_remove.attr("disabled", "disabled");
            var contextId = "";
            if(sakai_global.currentgroup){
                contextId = sakai_global.currentgroup.id;
            } else {
                contextId = sakai_global.profile.main.data.userid;
            }
            getLibraryItems(contextId,
                renderLibraryItems, query || false);
        };

        /**
         * Show the given page of library items.
         *
         * @param {int} pagenum The page number you want to display (not 0-indexed)
         */
        var showPage = function (pagenum) {
            showPager(pagenum);
            mylibrary.currentPagenum = pagenum;
            reset();
        };

        /**
         * Show the pager at the bottom of the page.
         *
         * @param {int} pagenum The number of the current page (not 0-indexed)
         */
        var showPager = function (pagenum) {
            mylibrary.currentPagenum = pagenum;
            if (Math.ceil(mylibrary.totalItems / mylibrary.itemsPerPage) > 1) {
                $("#mylibrary_pager", $rootel).pager({
                    pagenumber: pagenum,
                    pagecount: Math.ceil(mylibrary.totalItems / mylibrary.itemsPerPage),
                    buttonClickCallback: showPage
                });
            }
        };

        /**
         * Get personalized text for the given message bundle key based on
         * whether this library is owned by the viewer, or belongs to someone else.
         * The message should contain a '${firstname}' variable to replace with
         * and be located in this widget's properties files.
         *
         * @param {String} bundleKey The message bundle key
         */
        var getPersonalizedText = function (bundleKey) {
            if(sakai_global.currentgroup){
                return sakai.api.i18n.Widgets.getValueForKey(
                    "mylibrary","",bundleKey).replace(/\$\{firstname\}/gi,
                        sakai_global.currentgroup.data.authprofile["sakai:group-title"]);
            } else if (mylibrary.isOwnerViewing) {
                return sakai.api.i18n.Widgets.getValueForKey(
                    "mylibrary","",bundleKey).replace(/\$\{firstname\}/gi,
                        sakai.api.i18n.General.getValueForKey("YOUR").toLowerCase());
            } else {
                return sakai.api.i18n.Widgets.getValueForKey("mylibrary", "", bundleKey).replace(/\$\{firstname\}/gi, sakai_global.profile.main.data.basic.elements.firstName.value + "'s");
            }
        };

        ////////////////////
        // Event Handlers //
        ////////////////////

        $mylibrary_check.live("change", function (ev) {
            if ($(this).is(":checked")) {
                $mylibrary_remove.removeAttr("disabled");
            } else if (!$(".mylibrary_check:checked", $rootel).length) {
                $mylibrary_remove.attr("disabled", "disabled");
            }
        });

        $mylibrary_check_all.change(function (ev) {
            if ($(this).is(":checked")) {
                $(".mylibrary_check").attr("checked", "checked");
                $mylibrary_remove.removeAttr("disabled");
            } else {
                $(".mylibrary_check").removeAttr("checked");
                $mylibrary_remove.attr("disabled", "disabled");
            }
        });

        $mylibrary_remove.click(function (ev) {
            var $checked = $(".mylibrary_check:checked", $rootel);
            if ($checked.length) {
                var paths = [];
                $checked.each(function () {
                    paths.push("/p/" + this.id.split("mylibrary_check_")[1]);
                });
                $(window).trigger('init.deletecontent.sakai', [{
                    path: paths
                }, function (success) {
                    if (success) {
                        mylibrary.currentPagenum = 1;
                        reset();
                    }
                }]);
            }
        });

        $mylibrary_sortby.change(function (ev) {
            var sortSelection = this.options[this.selectedIndex].value;
            switch (sortSelection) {
                case "lastModified_asc":
                    mylibrary.sortBy = "_lastModified";
                    mylibrary.sortOrder = "asc";
                    break;
                default:
                    mylibrary.sortBy = "_lastModified";
                    mylibrary.sortOrder = "desc";
                    break;
            }
            reset();
        });

        $mylibrary_livefilter.keyup(function (ev) {
            var q = $.trim(this.value);
            if (q && ev.keyCode != 16) {
                $mylibrary_livefilter.addClass("mylibrary_livefilter_working");
                reset(q);
            }
            return false;
        });

        $mylibrary_livefilter.focus(function (ev) {
            $input = $(this);
            $input.removeClass("mylibrary_meta");
            if ($.trim($input.val()) === mylibrary.default_search_text) {
                $input.val("");
            }
        });

        $mylibrary_livefilter.blur(function (ev) {
            $input = $(this);
            if ($.trim($input.val()) === "") {
                $input.addClass("mylibrary_meta");
                $input.val(mylibrary.default_search_text);
            }
        });

        $mylibrary_addcontent.click(function (ev) {
            $(window).trigger("init.newaddcontent.sakai");
            return false;
        });

        ////////////////////////////////////////////
        // Data retrieval and rendering functions //
        ////////////////////////////////////////////

        /**
         * Gets the given user's library items and passes them to the callback
         * function
         *
         * @param {String} userid      the user id for the user whose library items we want
         * @param {Function} callback  function called with the following args:
         *     {Boolean} success - whether or not the fetch succeeded
         *     {Object} items - an array of library items or null if no success
         * @param {String} query       optional query string to limit search results
         */
        var getLibraryItems = function (userid, callback, query) {

            /**
             * Formats a tag list from the server for display in the UI
             *
             * @param {Array} tags  an array of tags from the server
             * @return {Array} an array of tags formatted for the UI
             */
            var formatTags = function (tags) {
                if (!tags) {
                    return null;
                }
                var formatted_tags = [];
                $.each(tags, function (i, name) {
                    formatted_tags.push({
                        name: name,
                        link: "/search#tag=/tags/" + name
                    });
                });
                return formatted_tags;
            };

            /**
             * Returns the number of people using the given item
             *
             * @param {Object} item  the item object returned from the server
             * @return {Number} the number of users using this item
             */
            var getNumPeopleUsing = function (item) {
                // Need KERN feed changes
                return 0;
            };

            /**
             * Returns the number of groups using the given item
             *
             * @param {Object} item  the item object returned from the server
             * @return {Number} the number of groups using this item
             */
            var getNumGroupsUsing = function (item) {
                // Need KERN feed changes
                return 0;
            };

            /**
             * Returns the number of comments for the given item
             *
             * @param {Object} item  the item object returned from the server
             * @return {Number} the number of comments for this item
             */
            var getNumComments = function (item) {
                if (!item) {
                    return 0;
                }
                var id = item["jcr:path"];
                var count = 0;
                if (item[id + "/comments"]) {
                    $.each(item[id + "/comments"], function (param, value) {
                        if (param.indexOf("/comments/") != -1) {
                            count++;
                        }
                    });
                }
                return count;
            };

            /**
             * Process library item results from the server
             */
            var handleLibraryItems = function (success, data) {
                if (success && data && data.results) {
                    mylibrary.totalItems = data.total;
                    var items = [];
                    if (mylibrary.totalItems === 0) {
                        callback(true, items);
                        return;
                    }
                    $.each(data.results, function (i, result) {
                        var mimetypeObj = sakai.api.Content.getMimeTypeData(result["_mimeType"] || result["sakai:custom-mimetype"]);
                        items.push({
                            id: result["jcr:path"],
                            filename: result["sakai:pooled-content-file-name"],
                            link: "/content#content_path=/p/" + result["jcr:path"],
                            last_updated: $.timeago(new Date(result["_lastModified"])),
                            type: sakai.api.i18n.General.getValueForKey(mimetypeObj.description),
                            type_src: mimetypeObj.URL,
                            ownerid: result["sakai:pool-content-created-for"],
                            ownername: sakai.data.me.user.userid === result["sakai:pool-content-created-for"] ?
                                sakai.api.i18n.General.getValueForKey("YOU") :
                                result["sakai:pool-content-created-for"],  // using id for now - need to get firstName lastName
                            tags: formatTags(result["sakai:tags"]),
                            numPeopleUsing: getNumPeopleUsing(),
                            numGroupsUsing: getNumGroupsUsing(),
                            numComments: getNumComments(result),
                            mimeType: result["_mimeType"] || result["sakai:custom-mimetype"],
                            fullResult: result
                        });
                    });
                    if (callback && typeof(callback) === "function") {
                        callback(true, items);
                    }
                } else {
                    debug.error("Fetching library items for userid: " + userid + " failed");
                    if (callback && typeof(callback) === "function") {
                        callback(false, null);
                    }
                }
            };

            // fetch the data
            sakai.api.Server.loadJSON("/var/search/pool/manager-viewer.json",
                handleLibraryItems, {
                    userid: userid,
                    page: mylibrary.currentPagenum - 1,
                    items: mylibrary.itemsPerPage,
                    sortOn: mylibrary.sortBy,
                    sortOrder: mylibrary.sortOrder,
                    _q: query || "*"
                }
            );
        };

        /**
         * Renders the given library items
         *
         * @param {Boolean} success - whether or not we have library items
         * @param {Array} items - an array of library items or null if no success
         */
        var renderLibraryItems = function (success, items) {
            if (success && items.length) {
                var json = {
                    items: items,
                    user_is_owner: function (item) {
                        if (!item) return false;
                        return sakai.data.me.user.userid === item.ownerid && mylibrary.isOwnerViewing;
                    },
                    user_is_manager: function (item) {
                        if (!item) return false;
                        return sakai.data.me.user.userid === item.ownerid;
                    }
                };
                json.sakai = sakai;
                if (mylibrary.isOwnerViewing) {
                    $mylibrary_admin_actions.show();
                }
                $mylibrary_livefilter.show();
                $mylibrary_sortarea.show();
                $mylibrary_empty.hide();
                $("#mylibrary_title_bar").show();
                $("#mylibrary_items", $rootel).html(sakai.api.Util.TemplateRenderer($("#mylibrary_items_template", $rootel), json));
                showPager(mylibrary.currentPagenum);
                $mylibrary_livefilter.removeClass("mylibrary_livefilter_working");
            } else {
                $mylibrary_admin_actions.hide();
                $mylibrary_livefilter.hide();
                $mylibrary_sortarea.hide();
                $("#mylibrary_title_bar").hide();
                $mylibrary_empty_note.html(getPersonalizedText("NO_ITEMS_IN_YOUR_LIBRARY"));
                $mylibrary_empty.show();
                if (mylibrary.isOwnerViewing) {
                    $mylibrary_addcontent.show();
                }
            }
        };

        /////////////////////////////
        // Initialization function //
        /////////////////////////////

        /**
         * Initialization function that is run when the widget is loaded. Determines
         * which mode the widget is in (settings or main), loads the necessary data
         * and shows the correct view.
         */
        var doInit = function () {
            var contextId = "";
            var contextName = "";
            var isGroup = false;
            if (sakai_global.currentgroup) {
                contextId = sakai_global.currentgroup.id;
                contextName = sakai_global.currentgroup.data.authprofile["sakai:group-title"];
                isGroup = true;
                if (sakai_global.currentgroup.manager) {
                    mylibrary.isOwnerViewing = true;
                }
            } else {
                contextId = sakai_global.profile.main.data.userid;
                contextName = sakai_global.profile.main.data.basic.elements.firstName.value;
                if (contextId === sakai.data.me.user.userid) {
                    mylibrary.isOwnerViewing = true;
                }
            }
            if (contextId) {
                mylibrary.default_search_text = getPersonalizedText("SEARCH_YOUR_LIBRARY");
                $mylibrary_livefilter.val(mylibrary.default_search_text);
                mylibrary.currentPagenum = 1;
                getLibraryItems(contextId, renderLibraryItems);
                sakai.api.Util.TemplateRenderer("mylibrary_title_template", {
                    isMe: mylibrary.isOwnerViewing,
                    isGroup: isGroup,
                    firstName: contextName
                }, $("#mylibrary_title_container", $rootel));
            } else {
                debug.warn("No user found for My Library");
            }
        };

        // run the initialization function when the widget object loads
        doInit();

        // Listen for complete.fileupload.sakai event (from the fileupload widget)
        // to refresh this widget's file listing
        $(window).bind("complete.fileupload.sakai", function() {
            mylibrary.currentPagenum = 1;
            reset();
        });

    };

    // inform Sakai OAE that this widget has loaded and is ready to run
    sakai.api.Widgets.widgetLoader.informOnLoad("mylibrary");
});
<|endoftext|>


<commit_before>Dionysus.module('DionysusApp.AdminHeader', function(Header, Dionysus, Backbone, Marionette, $) {
  var LinkModel = Backbone.Model.extend({
    initialize: function() {
      Backbone.Select.Me.applyTo( this );
    }
  });

  var LinkCollection = Backbone.Collection.extend({
    model: LinkModel,
    initialize: function(models, options) {
      Backbone.Select.One.applyTo( this, models, options );
    }
  });

  var links = new LinkCollection([
    { name: "Home",       href: "/admin",             icon: "home"  },
    { name: "Articles",   href: "/admin/articles",    icon: "edit"  },
    { name: "Categories", href: "/admin/categories",  icon: "inbox" },
    { name: "Tests",      href: "/admin/tests",       icon: "lab"   }
  ]);

  var LinkView = Marionette.ItemView.extend({
    template: "#admin-header-tpl",
    className: "item",
    tagName: 'a',
    attributes: function() {
      return { href: this.model.get('href') };
    },
    modelEvents: {
      "selected": "onRender",
      "deselected": "onRender"
    },
    events: {
      "click" : "navigateMenu"
    },
    navigateMenu: function(e) {
      this.model.select();
    },
    onRender: function() {
      this.$el.toggleClass('active', !!this.model.selected);
    }
  });

  var HeaderView = Marionette.CollectionView.extend({
    childView: LinkView,
    className: 'ui menu',
    tagName: 'nav'
  });

  Dionysus.addInitializer(function() {
    Dionysus.headerRegion.show(new HeaderView({collection: links}));
  });
});

Dionysus.start();<commit_msg>fix jshint warnings<commit_after>Dionysus.module('DionysusApp.AdminHeader', function(Header, Dionysus, Backbone, Marionette) {
  'use strict';

  var LinkModel = Backbone.Model.extend({
    initialize: function() {
      Backbone.Select.Me.applyTo( this );
    }
  });

  var LinkCollection = Backbone.Collection.extend({
    model: LinkModel,
    initialize: function(models, options) {
      Backbone.Select.One.applyTo( this, models, options );
    }
  });

  var links = new LinkCollection([
    { name: 'Home',       href: '/admin',             icon: 'home'  },
    { name: 'Articles',   href: '/admin/articles',    icon: 'edit'  },
    { name: 'Categories', href: '/admin/categories',  icon: 'inbox' },
    { name: 'Tests',      href: '/admin/tests',       icon: 'lab'   }
  ]);

  var LinkView = Marionette.ItemView.extend({
    template: '#admin-header-tpl',
    className: 'item',
    tagName: 'a',
    attributes: function() {
      return { href: this.model.get('href') };
    },
    modelEvents: {
      'selected': 'onRender',
      'deselected': 'onRender'
    },
    events: {
      'click' : 'navigateMenu'
    },
    navigateMenu: function() {
      this.model.select();
    },
    onRender: function() {
      this.$el.toggleClass('active', !!this.model.selected);
    }
  });

  var HeaderView = Marionette.CollectionView.extend({
    childView: LinkView,
    className: 'ui menu',
    tagName: 'nav'
  });

  Dionysus.addInitializer(function() {
    Dionysus.headerRegion.show(new HeaderView({collection: links}));
  });
});

Dionysus.start();<|endoftext|>


<commit_before>ShapeTracer = function ()
{
	this.gpuTracer = null;
	this.fragmentShader = null;
	this.settings = null;
	this.model = null;
};

ShapeTracer.prototype.Init = function (canvasElem, controlsElem, fragmentShaderElem)
{
	if (!this.InitUserInterface (controlsElem)) {
		return false;
	}

	if (!this.InitRenderer (canvasElem, fragmentShaderElem)) {
		return false;
	}

	return true;
};

ShapeTracer.prototype.InitUserInterface = function (controlsElem)
{
	this.settings = {
		light : {
			rotation : 1.0,
			distance : 3.0,
			height : 5.0,
			radius : 0.5
		}
	};

	var myThis = this;

	UserInterface.AddTitle (controlsElem, 'light position');
	mainElem = UserInterface.AddMainElem (controlsElem);
	UserInterface.AddSliderControl (mainElem, 'rotation', UserInterface.ToSlider (this.settings.light.rotation, 0.0, 2.0 * Math.PI), function (ratio) {
		myThis.settings.light.rotation = UserInterface.FromSlider (ratio, 0.0, 2.0 * Math.PI);
		myThis.UpdateUniforms ();
		myThis.StartRender (true);
	});
	UserInterface.AddSliderControl (mainElem, 'distance', UserInterface.ToSlider (myThis.settings.light.distance, 1.0, 5.0), function (ratio) {
		myThis.settings.light.distance = UserInterface.FromSlider (ratio, 1.0, 5.0);
		myThis.UpdateUniforms ();
		myThis.StartRender (true);
	});
	UserInterface.AddSliderControl (mainElem, 'height', UserInterface.ToSlider (myThis.settings.light.height, 1.0, 8.0), function (ratio) {
		myThis.settings.light.height = UserInterface.FromSlider (ratio, 1.0, 8.0);
		myThis.UpdateUniforms ();
		myThis.StartRender (true);
	});
    UserInterface.AddSliderControl (mainElem, 'radius', UserInterface.ToSlider (myThis.settings.light.radius, 0.0, 1.0), function (ratio) {
		myThis.settings.light.radius = UserInterface.FromSlider (ratio, 0.0, 1.0);
		myThis.UpdateUniforms ();
		myThis.StartRender (true);
	});

	return true;
};

ShapeTracer.prototype.InitRenderer = function (canvasElem, fragmentShaderElem)
{
	this.fragmentShader = fragmentShaderElem.childNodes[0].nodeValue;

	var camera = new JSM.Camera (
		new JSM.Coord (5, 3, 4),
		new JSM.Coord (0, 0, 1),
		new JSM.Coord (0, 0, 1)
	);

	var maxIteration = 256;
	var myThis = this;

	this.gpuTracer = new GPUTracer ();
	var callbacks = {};

	if (!this.gpuTracer.Init (canvasElem, camera, maxIteration, callbacks)) {
		return false;
	}

	if (!this.Compile ()) {
		return false;
	}

	this.StartRender (false);
	return true;
};

ShapeTracer.prototype.Compile = function ()
{
	this.model = {
		room : {
			min : [-10, -10, 0],
			max : [10, 10, 20],
			material : {
				diffuse : [0.6, 0.6, 0.6],
				reflection : 0.0
			}
		},
		spheres : [
			{
				origin : [2.5, 0, 1],
				radius : 1.0,
				material : {
					diffuse : [0.0, 0.0, 0.7],
					reflection : 0.0
				}
			}
		],
		boxes : [
			{
				min : [-1, -1, 0],
				max : [1, 1, 2],
				material : {
					diffuse : [0.7, 0.0, 0.0],
					reflection : 0.0
				}
			}
		],
		cylinders : [
			{
				origin : [-2.5, 0, 0],
				radius : 1,
				height : 2,
				material : {
					diffuse : [0.0, 0.7, 0.0],
					reflection : 0.0
				}
			}
		]
	};

	var timer = new JSM.Timer ();
	timer.Start ();
	var defines = [
		'#define SPHERE_COUNT ' + this.model.spheres.length,
		'#define BOX_COUNT ' + this.model.boxes.length,
		'#define CYLINDER_COUNT ' + this.model.cylinders.length
	].join ('\n');
	var result = this.gpuTracer.Compile (defines + this.fragmentShader, function (error) {
		console.log (error);
	});
	if (!result) {
		return false;
	}
	if (!this.UpdateUniforms ()) {
		return false;
	}
	timer.Stop ();
	console.log ('Compile time: ' + timer.Result ());
	return true;
};

ShapeTracer.prototype.UpdateUniforms = function ()
{
	function GetLightPosition (lightData)
	{
		var origo = new JSM.Coord2D (0.0, 0.0);
		var lightPosition = JSM.CoordRotate2D (new JSM.Coord2D (1.0, 0.0), lightData.rotation, origo);
		lightPosition = JSM.VectorSetLength2D (lightPosition, lightData.distance);
		return new JSM.Coord (lightPosition.x, lightPosition.y, lightData.height);
	}

	this.gpuTracer.GetNavigation ().SetNearDistanceLimit (1.0);
	this.gpuTracer.GetNavigation ().SetFarDistanceLimit (20.0);
	var lightPosition = GetLightPosition (this.settings.light);
	this.gpuTracer.SetUniformVector ('uLightPosition', [lightPosition.x, lightPosition.y, lightPosition.z]);
	this.gpuTracer.SetUniformFloat ('uLightRadius', this.settings.light.radius);

	this.gpuTracer.SetUniformVector ('uRoomBox.min', this.model.room.min);
	this.gpuTracer.SetUniformVector ('uRoomBox.max', this.model.room.max);
	this.gpuTracer.SetUniformVector ('uRoomBox.material.diffuse', this.model.room.material.diffuse);
	this.gpuTracer.SetUniformFloat ('uRoomBox.material.reflection', this.model.room.material.reflection);

	var i;
	for (i = 0; i < this.model.spheres.length; i++) {
		this.gpuTracer.SetUniformVector ('uSpheres[' + i + '].origin', this.model.spheres[i].origin);
		this.gpuTracer.SetUniformFloat ('uSpheres[' + i + '].radius', this.model.spheres[i].radius);
		this.gpuTracer.SetUniformVector ('uSpheres[' + i + '].material.diffuse', this.model.spheres[i].material.diffuse);
		this.gpuTracer.SetUniformFloat ('uSpheres[' + i + '].material.reflection', this.model.spheres[i].material.reflection);
	}
	for (i = 0; i < this.model.boxes.length; i++) {
		this.gpuTracer.SetUniformVector ('uBoxes[' + i + '].min', this.model.boxes[i].min);
		this.gpuTracer.SetUniformVector ('uBoxes[' + i + '].max', this.model.boxes[i].max);
		this.gpuTracer.SetUniformVector ('uBoxes[' + i + '].material.diffuse', this.model.boxes[i].material.diffuse);
		this.gpuTracer.SetUniformFloat ('uBoxes[' + i + '].material.reflection', this.model.boxes[i].material.reflection);
	}
	for (i = 0; i < this.model.cylinders.length; i++) {
		this.gpuTracer.SetUniformVector ('uCylinders[' + i + '].origin', this.model.cylinders[i].origin);
		this.gpuTracer.SetUniformFloat ('uCylinders[' + i + '].radius', this.model.cylinders[i].radius);
		this.gpuTracer.SetUniformFloat ('uCylinders[' + i + '].height', this.model.cylinders[i].height);
		this.gpuTracer.SetUniformVector ('uCylinders[' + i + '].material.diffuse', this.model.cylinders[i].material.diffuse);
		this.gpuTracer.SetUniformFloat ('uCylinders[' + i + '].material.reflection', this.model.cylinders[i].material.reflection);
	}

	return true;
};

ShapeTracer.prototype.StartRender = function (isPreviewMode)
{
	if (isPreviewMode) {
		this.gpuTracer.StartInPreviewMode ();
	} else {
		this.gpuTracer.StartInNormalMode ();
	}
};
<commit_msg>Add some shapes.<commit_after>ShapeTracer = function ()
{
	this.gpuTracer = null;
	this.fragmentShader = null;
	this.settings = null;
	this.model = null;
};

ShapeTracer.prototype.Init = function (canvasElem, controlsElem, fragmentShaderElem)
{
	if (!this.InitUserInterface (controlsElem)) {
		return false;
	}

	if (!this.InitRenderer (canvasElem, fragmentShaderElem)) {
		return false;
	}

	return true;
};

ShapeTracer.prototype.InitUserInterface = function (controlsElem)
{
	this.settings = {
		light : {
			rotation : 1.0,
			distance : 3.0,
			height : 5.0,
			radius : 0.5
		}
	};

	var myThis = this;

	UserInterface.AddTitle (controlsElem, 'light position');
	mainElem = UserInterface.AddMainElem (controlsElem);
	UserInterface.AddSliderControl (mainElem, 'rotation', UserInterface.ToSlider (this.settings.light.rotation, 0.0, 2.0 * Math.PI), function (ratio) {
		myThis.settings.light.rotation = UserInterface.FromSlider (ratio, 0.0, 2.0 * Math.PI);
		myThis.UpdateUniforms ();
		myThis.StartRender (true);
	});
	UserInterface.AddSliderControl (mainElem, 'distance', UserInterface.ToSlider (myThis.settings.light.distance, 1.0, 5.0), function (ratio) {
		myThis.settings.light.distance = UserInterface.FromSlider (ratio, 1.0, 5.0);
		myThis.UpdateUniforms ();
		myThis.StartRender (true);
	});
	UserInterface.AddSliderControl (mainElem, 'height', UserInterface.ToSlider (myThis.settings.light.height, 1.0, 8.0), function (ratio) {
		myThis.settings.light.height = UserInterface.FromSlider (ratio, 1.0, 8.0);
		myThis.UpdateUniforms ();
		myThis.StartRender (true);
	});
    UserInterface.AddSliderControl (mainElem, 'radius', UserInterface.ToSlider (myThis.settings.light.radius, 0.0, 1.0), function (ratio) {
		myThis.settings.light.radius = UserInterface.FromSlider (ratio, 0.0, 1.0);
		myThis.UpdateUniforms ();
		myThis.StartRender (true);
	});

	return true;
};

ShapeTracer.prototype.InitRenderer = function (canvasElem, fragmentShaderElem)
{
	this.fragmentShader = fragmentShaderElem.childNodes[0].nodeValue;

	var camera = new JSM.Camera (
		new JSM.Coord (5, 3, 4),
		new JSM.Coord (0, 0, 1),
		new JSM.Coord (0, 0, 1)
	);

	var maxIteration = 256;
	var myThis = this;

	this.gpuTracer = new GPUTracer ();
	var callbacks = {};

	if (!this.gpuTracer.Init (canvasElem, camera, maxIteration, callbacks)) {
		return false;
	}

	if (!this.Compile ()) {
		return false;
	}

	this.StartRender (false);
	return true;
};

ShapeTracer.prototype.Compile = function ()
{
	this.model = {
		room : {
			min : [-10, -10, 0],
			max : [10, 10, 20],
			material : {
				diffuse : [0.6, 0.6, 0.6],
				reflection : 0.0
			}
		},
		spheres : [
			{
				origin : [2.5, 0, 1],
				radius : 1.0,
				material : {
					diffuse : [0.0, 0.0, 0.7],
					reflection : 0.0
				}
			},
			{
				origin : [0, 2.5, 1],
				radius : 1.0,
				material : {
					diffuse : [0.7, 0.0, 0.7],
					reflection : 0.0
				}
			}
		],
		boxes : [
			{
				min : [-1, -1, 0],
				max : [1, 1, 2.5],
				material : {
					diffuse : [0.7, 0.0, 0.0],
					reflection : 0.2
				}
			}
		],
		cylinders : [
			{
				origin : [-2.5, 0, 0],
				radius : 1,
				height : 4,
				material : {
					diffuse : [0.0, 0.7, 0.0],
					reflection : 0.0
				}
			},
			{
				origin : [0, -2.5, 0],
				radius : 1,
				height : 3,
				material : {
					diffuse : [0.7, 0.7, 0.0],
					reflection : 0.0
				}
			}
		]
	};

	var timer = new JSM.Timer ();
	timer.Start ();
	var defines = [
		'#define SPHERE_COUNT ' + this.model.spheres.length,
		'#define BOX_COUNT ' + this.model.boxes.length,
		'#define CYLINDER_COUNT ' + this.model.cylinders.length
	].join ('\n');
	var result = this.gpuTracer.Compile (defines + this.fragmentShader, function (error) {
		console.log (error);
	});
	if (!result) {
		return false;
	}
	if (!this.UpdateUniforms ()) {
		return false;
	}
	timer.Stop ();
	console.log ('Compile time: ' + timer.Result ());
	return true;
};

ShapeTracer.prototype.UpdateUniforms = function ()
{
	function GetLightPosition (lightData)
	{
		var origo = new JSM.Coord2D (0.0, 0.0);
		var lightPosition = JSM.CoordRotate2D (new JSM.Coord2D (1.0, 0.0), lightData.rotation, origo);
		lightPosition = JSM.VectorSetLength2D (lightPosition, lightData.distance);
		return new JSM.Coord (lightPosition.x, lightPosition.y, lightData.height);
	}

	this.gpuTracer.GetNavigation ().SetNearDistanceLimit (1.0);
	this.gpuTracer.GetNavigation ().SetFarDistanceLimit (20.0);
	var lightPosition = GetLightPosition (this.settings.light);
	this.gpuTracer.SetUniformVector ('uLightPosition', [lightPosition.x, lightPosition.y, lightPosition.z]);
	this.gpuTracer.SetUniformFloat ('uLightRadius', this.settings.light.radius);

	this.gpuTracer.SetUniformVector ('uRoomBox.min', this.model.room.min);
	this.gpuTracer.SetUniformVector ('uRoomBox.max', this.model.room.max);
	this.gpuTracer.SetUniformVector ('uRoomBox.material.diffuse', this.model.room.material.diffuse);
	this.gpuTracer.SetUniformFloat ('uRoomBox.material.reflection', this.model.room.material.reflection);

	var i;
	for (i = 0; i < this.model.spheres.length; i++) {
		this.gpuTracer.SetUniformVector ('uSpheres[' + i + '].origin', this.model.spheres[i].origin);
		this.gpuTracer.SetUniformFloat ('uSpheres[' + i + '].radius', this.model.spheres[i].radius);
		this.gpuTracer.SetUniformVector ('uSpheres[' + i + '].material.diffuse', this.model.spheres[i].material.diffuse);
		this.gpuTracer.SetUniformFloat ('uSpheres[' + i + '].material.reflection', this.model.spheres[i].material.reflection);
	}
	for (i = 0; i < this.model.boxes.length; i++) {
		this.gpuTracer.SetUniformVector ('uBoxes[' + i + '].min', this.model.boxes[i].min);
		this.gpuTracer.SetUniformVector ('uBoxes[' + i + '].max', this.model.boxes[i].max);
		this.gpuTracer.SetUniformVector ('uBoxes[' + i + '].material.diffuse', this.model.boxes[i].material.diffuse);
		this.gpuTracer.SetUniformFloat ('uBoxes[' + i + '].material.reflection', this.model.boxes[i].material.reflection);
	}
	for (i = 0; i < this.model.cylinders.length; i++) {
		this.gpuTracer.SetUniformVector ('uCylinders[' + i + '].origin', this.model.cylinders[i].origin);
		this.gpuTracer.SetUniformFloat ('uCylinders[' + i + '].radius', this.model.cylinders[i].radius);
		this.gpuTracer.SetUniformFloat ('uCylinders[' + i + '].height', this.model.cylinders[i].height);
		this.gpuTracer.SetUniformVector ('uCylinders[' + i + '].material.diffuse', this.model.cylinders[i].material.diffuse);
		this.gpuTracer.SetUniformFloat ('uCylinders[' + i + '].material.reflection', this.model.cylinders[i].material.reflection);
	}

	return true;
};

ShapeTracer.prototype.StartRender = function (isPreviewMode)
{
	if (isPreviewMode) {
		this.gpuTracer.StartInPreviewMode ();
	} else {
		this.gpuTracer.StartInNormalMode ();
	}
};
<|endoftext|>


<commit_before>// Future versions of Hyper may add additional config options,
// which will not automatically be merged into this file.
// See https://hyper.is#cfg for all currently supported options.

module.exports = {
  config: {
    // Choose either "stable" for receiving highly polished,
    // or "canary" for less polished but more frequent updates
    updateChannel: "stable",

    // The default size in pixels for the terminal
    fontSize: 12,

    // The font family to use with optional fallbacks
    fontFamily:
      '"Operator Mono Lig", "Operator Mono", Menlo, "DejaVu Sans Mono", Consolas, "Lucida Console", monospace',

    // The font family to use for the UI with optional fallbacks
    // uiFontFamily: "-apple-system, BlinkMacSystemFont, Segoe UI, Roboto",

    // The color of the caret in the terminal
    cursorColor: "#D4D4D4",

    // The shape of the caret in the terminal. Available options are: 'BEAM', 'UNDERLINE', 'BLOCK'
    cursorShape: "BEAM",

    // If true, cursor will blink
    cursorBlink: true,

    // The color of the main text of the terminal
    foregroundColor: "#D4D4D4",

    // The color and opacity of the window and main terminal background
    backgroundColor: "#242B2E",

    // The color of the main window border and tab bar
    borderColor: "#333",

    // Custom CSS to include in the main window
    css: ".terminal {font-weight: 500}",

    // Custom CSS to include in the terminal window
    termCSS:
      ".xterm {line-height: 17px} .xterm-rows > div {display: block; line-height: 15px}",

    // CSS padding values for the space around each term
    padding: "6px 8px",

    // A list of overrides for the color palette. The names of the keys represent the "ANSI 16", which can all be seen in the default config.
    colors: {
      black: "#7F7F7F",
      red: "#E15A60",
      green: "#99C794",
      yellow: "#FAC863",
      blue: "#6699CC",
      magenta: "#C594C5",
      cyan: "#5FB3B3",
      white: "#D4D4D4",
      lightBlack: "#7F7F7F",
      lightRed: "#E15A60",
      lightGreen: "#99C794",
      lightYellow: "#FAC863",
      lightBlue: "#6699CC",
      lightMagenta: "#C594C5",
      lightCyan: "#5FB3B3",
      lightWhite: "#FFFFFF"
    },

    // A path to a custom shell to run when Hyper starts a new session
    shell: "",

    // Override the npm registry URL to use when installing plugins
    // npmRegistry: "",

    // The default width/height in pixels of a new window e.g. [540, 380]
    // windowSize: null,

    // If true, selected text will automatically be copied to the clipboard
    // copyOnSelect: false,

    // System bell configuration. Available options are: "SOUND", false
    bell: false

    // The URL of the bell sound to use, used only if "bell" is set to "SOUND"
    // bellSoundURL: "lib-resource:hterm/audio/bell",

    // Change the behaviour of modifier keys to act as meta key
    // modifierKeys: { cmdIsMeta: false, altIsMeta: false },

    // Change the visibility of the hamburger menu. Available options are: true, false
    // showHamburgerMenu: "",

    // Change the position/visibility of the window controls. Available options are: true, false, "left"
    // showWindowControls: ""
  },

  // a list of plugins to fetch and install from npm
  // format: [@org/]project[#version]
  // examples:
  //   `hyperpower`
  //   `@company/project`
  //   `project#1.0.1`
  plugins: ["hyperterm-paste", "hyperlinks", "hypercwd"],

  // in development, you can create a directory under
  // `~/.hyper_plugins/local/` and include it here
  // to load it and avoid it being `npm install`ed
  localPlugins: ["hyperterm-mactabs"],

  keymaps: {
    // Example
    // 'window:devtools': 'cmd+alt+o',
  }
};
<commit_msg>Only change hyper font-weight on retina screens.<commit_after>// Future versions of Hyper may add additional config options,
// which will not automatically be merged into this file.
// See https://hyper.is#cfg for all currently supported options.

module.exports = {
  config: {
    // Choose either "stable" for receiving highly polished,
    // or "canary" for less polished but more frequent updates
    updateChannel: "stable",

    // The default size in pixels for the terminal
    fontSize: 12,

    // The font family to use with optional fallbacks
    fontFamily:
      '"Operator Mono Lig", "Operator Mono", Menlo, "DejaVu Sans Mono", Consolas, "Lucida Console", monospace',

    // The font family to use for the UI with optional fallbacks
    // uiFontFamily: "-apple-system, BlinkMacSystemFont, Segoe UI, Roboto",

    // The color of the caret in the terminal
    cursorColor: "#D4D4D4",

    // The shape of the caret in the terminal. Available options are: 'BEAM', 'UNDERLINE', 'BLOCK'
    cursorShape: "BEAM",

    // If true, cursor will blink
    cursorBlink: true,

    // The color of the main text of the terminal
    foregroundColor: "#D4D4D4",

    // The color and opacity of the window and main terminal background
    backgroundColor: "#242B2E",

    // The color of the main window border and tab bar
    borderColor: "#333",

    // Custom CSS to include in the main window
    css: "@media (min-resolution: 2dppx) { .terminal {font-weight: 500} }",

    // Custom CSS to include in the terminal window
    termCSS:
      ".xterm {line-height: 17px} .xterm-rows > div {display: block; line-height: 15px}",

    // CSS padding values for the space around each term
    padding: "6px 8px",

    // A list of overrides for the color palette. The names of the keys represent the "ANSI 16", which can all be seen in the default config.
    colors: {
      black: "#7F7F7F",
      red: "#E15A60",
      green: "#99C794",
      yellow: "#FAC863",
      blue: "#6699CC",
      magenta: "#C594C5",
      cyan: "#5FB3B3",
      white: "#D4D4D4",
      lightBlack: "#7F7F7F",
      lightRed: "#E15A60",
      lightGreen: "#99C794",
      lightYellow: "#FAC863",
      lightBlue: "#6699CC",
      lightMagenta: "#C594C5",
      lightCyan: "#5FB3B3",
      lightWhite: "#FFFFFF"
    },

    // A path to a custom shell to run when Hyper starts a new session
    shell: "",

    // Override the npm registry URL to use when installing plugins
    // npmRegistry: "",

    // The default width/height in pixels of a new window e.g. [540, 380]
    // windowSize: null,

    // If true, selected text will automatically be copied to the clipboard
    // copyOnSelect: false,

    // System bell configuration. Available options are: "SOUND", false
    bell: false

    // The URL of the bell sound to use, used only if "bell" is set to "SOUND"
    // bellSoundURL: "lib-resource:hterm/audio/bell",

    // Change the behaviour of modifier keys to act as meta key
    // modifierKeys: { cmdIsMeta: false, altIsMeta: false },

    // Change the visibility of the hamburger menu. Available options are: true, false
    // showHamburgerMenu: "",

    // Change the position/visibility of the window controls. Available options are: true, false, "left"
    // showWindowControls: ""
  },

  // a list of plugins to fetch and install from npm
  // format: [@org/]project[#version]
  // examples:
  //   `hyperpower`
  //   `@company/project`
  //   `project#1.0.1`
  plugins: ["hyperterm-paste", "hyperlinks", "hypercwd"],

  // in development, you can create a directory under
  // `~/.hyper_plugins/local/` and include it here
  // to load it and avoid it being `npm install`ed
  localPlugins: ["hyperterm-mactabs"],

  keymaps: {
    // Example
    // 'window:devtools': 'cmd+alt+o',
  }
};
<|endoftext|>


<commit_before>/*
Add this file to $(jupyter --data-dir)/nbextensions/gist.js
And load it with:

require(["nbextensions/gist"], function (gist_extension) {
    console.log('gist extension loaded');
    gist_extension.load_ipython_extension();
});

or add the following to your jupyter_notebook_config.py to
load for every notebook

from notebook.services.config import ConfigManager
cm = ConfigManager()
cm.update('notebook', {"load_extensions": {"gist": True}})
*/

function get_base_path() {
    var loc = window.location;
    var proto = loc.protocol;
    var host = loc.hostname;
    var port = loc.port;

    var base = proto + "//" + host;
    if (parseInt(port) != 80) {
        base += ":" + port;
    }
    return base;
}

function url_path_split(path) {
    var idx = path.lastIndexOf('/');
    if (idx === -1) {
        return ['', path];
    } else {
        return [ path.slice(0, idx), path.slice(idx + 1) ];
    }
}

function is_url_valid(url) {
    return /^(https?|s?ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(url);
}

define(function () {
    var github_redirect_uri = get_base_path() + "/create_gist";
    var gist_notebook = function () {
        // Save the notebook and create a checkpoint to ensure that we create
        // the gist using the most up-to-date content
        Jupyter.notebook.save_checkpoint();

        var github_client_id = Jupyter.notebook.config.data.oauth_client_id;
        // Get notebook path and encode it in base64
        // Characters like # get decoded by the github API and will mess up
        // getting the file path on the server if we use URI percent encoding,
        // so we use base64 instead
        var nb_path = window.btoa(Jupyter.notebook.base_url + Jupyter.notebook.notebook_path);

        // Start OAuth dialog
        window.open("https://github.com/login/oauth/authorize?client_id=" + github_client_id +
          "&scope=gist&redirect_uri=" + github_redirect_uri + "?nb_path=" + nb_path);
    };

    var load_from_url = function() {
        var url = prompt("Enter the URL to a Gist or a .ipynb.");
        if (url == "" || url == null) {
            // prompt() returns "" if empty value, or null
            // if user clicked cancel, want to abort in either case
            return;
        }
        if (!is_url_valid(url)) {
            alert('Invalid URL.');
            return;
        }
        var parser = document.createElement('a');
        parser.href = url;
        if (parser.hostname.indexOf('gist.github.com') > -1) {
            // this is a gist URL, extract the raw_url for the .ipynb file
            var gist_url_parts = url.split('/');
            var gist_id = gist_url_parts[gist_url_parts.length-1];

            var gist_api_url = "https://api.github.com/gists/" + gist_id;

            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function() {
                if (xhr.readyState == XMLHttpRequest.DONE) {
                    if (xhr.status == 200) {
                        var res = JSON.parse(xhr.responseText);
                        for (var filename in res.files) {
                            if (!res.files.hasOwnProperty(filename)) continue;
                            if (filename.endsWith('.ipynb')) {
                                download_nb_on_server(res.files[filename].raw_url, filename, false);
                            }
                        }
                        console.log(res);
                    } else if (xhr.status == 404) {
                        alert("Gist not found.")
                    } else {
                        alert("Couldn't load Gist.")
                    }
                }
            }
            xhr.open("GET", gist_api_url, true);
            xhr.send(null);
        } else if (url.indexOf('.ipynb', url.length - '.ipynb'.length) !== -1) {
            // URL is a raw .ipynb file
            var nb_pathname_parts = parser.pathname.split('/');
            var filename = decodeURIComponent(nb_pathname_parts[nb_pathname_parts.length - 1]);
            download_nb_on_server(url, filename, false);
        }
    }

    var download_nb_on_server = function(url, name, force_download) {
        var xhr = new XMLHttpRequest();
        var nb_info = {
            nb_url: url,
            nb_name: window.btoa(name),
            force_download: force_download
        }
        xhr.open("POST",  "/download_notebook", true);
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.onload = function () {
            if (xhr.status == 409) {
                // 409 Conflict
                // used if file already exists
                var newname = prompt("File already exists. Please enter a new name.\nNote: This may overwrite existing files.",
                                     name);
                if (newname == "" || newname == null) {
                    // prompt() returns "" if empty value, or null
                    // if user clicked cancel, want to abort in either case
                    return;
                }
                download_nb_on_server(url, newname, true);
            } else if (xhr.status == 200) {
                window.open(url_path_split(Jupyter.notebook.notebook_path)[0] + encodeURIComponent(this.responseText));
            }
        };
        xhr.send(JSON.stringify(nb_info));
    }

    var setup_info = function() {
        Jupyter.dialog.modal({
            title: "Error",
            body: "You haven't changed your GitHub client ID in your jupyter_notebook_config.py file. Please update your client ID and secret before using this plugin.",
            buttons: {
                "OK": {}
            }
        });
    }

    var gist_button = function () {
        if (!Jupyter.toolbar) {
            $([Jupyter.events]).on("app_initialized.NotebookApp", gist_button);
            return;
        }

        if (Jupyter.notebook.config.data.oauth_client_id == 'my_client_id') {
            Jupyter.toolbar.add_buttons_group([{
                'label':    'jupyter-notebook-gist setup',
                'icon':     'fa-github',
                'callback': setup_info,
                'id':       'setup_info'
            }]);

            return;
        }

        if ($("#gist_notebook").length === 0) {
            Jupyter.toolbar.add_buttons_group([
                {
                    'label'   : 'save notebook as gist',
                    'icon'    : 'fa-github',
                    'callback': gist_notebook,
                    'id'      : 'gist_notebook'
                }, {
                    'label'   : 'load notebook from URL',
                    'icon'    : 'fa-link',
                    'callback': load_from_url,
                    'id'      : 'load_notebook_from_url'
                }
            ]);
        }
    };

    var load_ipython_extension = function () {
        gist_button();
    };

    return {
        load_ipython_extension: load_ipython_extension
    };
});
<commit_msg>Add check for missing client ID<commit_after>/*
Add this file to $(jupyter --data-dir)/nbextensions/gist.js
And load it with:

require(["nbextensions/gist"], function (gist_extension) {
    console.log('gist extension loaded');
    gist_extension.load_ipython_extension();
});

or add the following to your jupyter_notebook_config.py to
load for every notebook

from notebook.services.config import ConfigManager
cm = ConfigManager()
cm.update('notebook', {"load_extensions": {"gist": True}})
*/

function get_base_path() {
    var loc = window.location;
    var proto = loc.protocol;
    var host = loc.hostname;
    var port = loc.port;

    var base = proto + "//" + host;
    if (parseInt(port) != 80) {
        base += ":" + port;
    }
    return base;
}

function url_path_split(path) {
    var idx = path.lastIndexOf('/');
    if (idx === -1) {
        return ['', path];
    } else {
        return [ path.slice(0, idx), path.slice(idx + 1) ];
    }
}

function is_url_valid(url) {
    return /^(https?|s?ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(url);
}

define(function () {
    var github_redirect_uri = get_base_path() + "/create_gist";
    var gist_notebook = function () {
        // Save the notebook and create a checkpoint to ensure that we create
        // the gist using the most up-to-date content
        Jupyter.notebook.save_checkpoint();

        var github_client_id = Jupyter.notebook.config.data.oauth_client_id;
        // Get notebook path and encode it in base64
        // Characters like # get decoded by the github API and will mess up
        // getting the file path on the server if we use URI percent encoding,
        // so we use base64 instead
        var nb_path = window.btoa(Jupyter.notebook.base_url + Jupyter.notebook.notebook_path);

        // Start OAuth dialog
        window.open("https://github.com/login/oauth/authorize?client_id=" + github_client_id +
          "&scope=gist&redirect_uri=" + github_redirect_uri + "?nb_path=" + nb_path);
    };

    var load_from_url = function() {
        var url = prompt("Enter the URL to a Gist or a .ipynb.");
        if (url == "" || url == null) {
            // prompt() returns "" if empty value, or null
            // if user clicked cancel, want to abort in either case
            return;
        }
        if (!is_url_valid(url)) {
            alert('Invalid URL.');
            return;
        }
        var parser = document.createElement('a');
        parser.href = url;
        if (parser.hostname.indexOf('gist.github.com') > -1) {
            // this is a gist URL, extract the raw_url for the .ipynb file
            var gist_url_parts = url.split('/');
            var gist_id = gist_url_parts[gist_url_parts.length-1];

            var gist_api_url = "https://api.github.com/gists/" + gist_id;

            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function() {
                if (xhr.readyState == XMLHttpRequest.DONE) {
                    if (xhr.status == 200) {
                        var res = JSON.parse(xhr.responseText);
                        for (var filename in res.files) {
                            if (!res.files.hasOwnProperty(filename)) continue;
                            if (filename.endsWith('.ipynb')) {
                                download_nb_on_server(res.files[filename].raw_url, filename, false);
                            }
                        }
                        console.log(res);
                    } else if (xhr.status == 404) {
                        alert("Gist not found.")
                    } else {
                        alert("Couldn't load Gist.")
                    }
                }
            }
            xhr.open("GET", gist_api_url, true);
            xhr.send(null);
        } else if (url.indexOf('.ipynb', url.length - '.ipynb'.length) !== -1) {
            // URL is a raw .ipynb file
            var nb_pathname_parts = parser.pathname.split('/');
            var filename = decodeURIComponent(nb_pathname_parts[nb_pathname_parts.length - 1]);
            download_nb_on_server(url, filename, false);
        }
    }

    var download_nb_on_server = function(url, name, force_download) {
        var xhr = new XMLHttpRequest();
        var nb_info = {
            nb_url: url,
            nb_name: window.btoa(name),
            force_download: force_download
        }
        xhr.open("POST",  "/download_notebook", true);
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.onload = function () {
            if (xhr.status == 409) {
                // 409 Conflict
                // used if file already exists
                var newname = prompt("File already exists. Please enter a new name.\nNote: This may overwrite existing files.",
                                     name);
                if (newname == "" || newname == null) {
                    // prompt() returns "" if empty value, or null
                    // if user clicked cancel, want to abort in either case
                    return;
                }
                download_nb_on_server(url, newname, true);
            } else if (xhr.status == 200) {
                window.open(url_path_split(Jupyter.notebook.notebook_path)[0] + encodeURIComponent(this.responseText));
            }
        };
        xhr.send(JSON.stringify(nb_info));
    }

    var setup_info = function() {
        Jupyter.dialog.modal({
            title: "Error",
            body: "You haven't changed your GitHub client ID in your jupyter_notebook_config.py file. Please update your client ID and secret before using this plugin.",
            buttons: {
                "OK": {}
            }
        });
    }

    var is_valid_client_id = function(client_id) {
        if (client_id === "my_client_id" || client_id === null || client_id === undefined) {
            return false;
        }
        return true;
    }

    var gist_button = function () {
        if (!Jupyter.toolbar) {
            $([Jupyter.events]).on("app_initialized.NotebookApp", gist_button);
            return;
        }

        if (!is_valid_client_id(Jupyter.notebook.config.data.oauth_client_id)) {
            Jupyter.toolbar.add_buttons_group([{
                'label':    'jupyter-notebook-gist setup',
                'icon':     'fa-github',
                'callback': setup_info,
                'id':       'setup_info'
            }]);

            return;
        }

        if ($("#gist_notebook").length === 0) {
            Jupyter.toolbar.add_buttons_group([
                {
                    'label'   : 'save notebook as gist',
                    'icon'    : 'fa-github',
                    'callback': gist_notebook,
                    'id'      : 'gist_notebook'
                }, {
                    'label'   : 'load notebook from URL',
                    'icon'    : 'fa-link',
                    'callback': load_from_url,
                    'id'      : 'load_notebook_from_url'
                }
            ]);
        }
    };

    var load_ipython_extension = function () {
        gist_button();
    };

    return {
        load_ipython_extension: load_ipython_extension
    };
});
<|endoftext|>


<commit_before>var http = require("http").createServer(handler); // handler will be the function with req, res as in previous example, just separated
var io = require("socket.io").listen(http); // socket.io for permanent connection between server and client
var fs = require("fs"); // variable fo "file system", i.e. fs
var firmata = require("firmata"); // make pins on Arduin oaccesible via serial-USB communication
var sendValueViaSocket = function() {}; // function to send message over socket
var sendStaticMsgViaSocket = function() {}; // function to send static message over socket
	 function handler(req, res) { // function with request and response, that is used in the first line of this example
     fs.readFile(__dirname + "/21diod.html",
      function (err, data){
          if (err) {
              res.writeHead(500, {"Content-Type": "text/plain"});
              return res.end("Error loading html page.");
	          }
      res.writeHead(200);
      res.end(data);
	      })
	  }

var desiredValue = 0; // variable for desired value (reference value or input)
var actualValue = 0; // variable for actual value (output value)

 // PID Algorithm variables
var Kp = 0.55; // proportional factor
var Ki = 0.008; // integral factor
var Kd = 0.15; // differential factor

var pwm = 0;
var pwmLimit = 254;

var err = 0; // variable for second pid implementation
var errSum = 0; // sum of errors
var dErr = 0; // difference of error
var lastErr = 0; // to keep the value of previous error
var KpE = 0; // multiplication of Kp x error
var KiIedt = 0; // multiplication of Ki x integral of error
var KdDe_dt = 0; // multiplication of Kd x differential of error i.e.e Derror/dt

var errSumAbs = 0; // sum of absolute errors as performance measure

var controlAlgorithmStartedFlag = 0; // flag in global scope to see weather ctrlAlg has been started
var intervalCtrl; // var for setInterval in global space

var readAnalogPin0Flag = 1; // for reading the pin if pot is driver

http.listen(8080); // determine on which port to listen (8080)
console.log("Starting the system"); // print the message to the console
var board = new firmata.Board("/dev/ttyACM0", function(){ // ACM Abstract Control Model for serial communication with Arduino (could be USB)
	      console.log("Connecting to Arduino");
	      board.pinMode(0, board.MODES.ANALOG); // analog pin 0
          board.pinMode(1, board.MODES.ANALOG); // analog pin 1
	      board.pinMode(2, board.MODES.OUTPUT); // direction of DC motor
	      board.pinMode(3, board.MODES.PWM); // PWM of motor i.e. speed of rotation
	      board.pinMode(4, board.MODES.OUTPUT); // direction DC motor
	  });

	  board.on("ready", function() {

	  board.analogRead(0, function(value) {
	      if (readAnalogPin0Flag == 1) desiredValue = value; // continuous read of pin A0
	  });

	  board.analogRead(1, function(value) {
	      actualValue = value; // continuous read of pin A1
	  });

	  io.sockets.on('connection', function(socket) {  // from bracket ( onward, we have an argument of the function on -> at 'connection' the argument is transfered i.e. function(socket)

	      socket.emit("messageToClient", "Server connected, board ready.");
	      socket.emit("staticMsgToClient", "Server connected, board ready.")

	      setInterval(sendValues, 40, socket); // na 40ms we send message to client

	      socket.on("startControlAlgorithm", function(numberOfControlAlgorithm){
	          startControlAlgorithm(numberOfControlAlgorithm);
	      });

          socket.on("sendPosition", function(position){
              readAnalogPin0Flag = 0; // to stop reading from pin 0
              desiredValue = position; // now the desired value from the GUI takes control
              socket.emit("messageToClient", "Position set to: position.")
	      });

	      socket.on("stopControlAlgorithm", function(){
	          stopControlAlgorithm();
	      });

	      sendValueViaSocket = function (value) {
	          io.sockets.emit("messageToClient", value);
      }

	      sendStaticMsgViaSocket = function (value) {
	          io.sockets.emit("staticMsgToClient", value);
	      }

	  });

  });

function controlAlgorithm (parameters) {
    if (parameters.ctrlAlgNo == 1) {
	   pwm = parameters.pCoeff*(desiredValue-actualValue);
	   errSumAbs += Math.abs(desiredValue-actualValue);
	   if(pwm > pwmLimit) {pwm = pwmLimit}; // to limit the value for pwm / positive
	   if(pwm < -pwmLimit) {pwm = -pwmLimit}; // to limit the value for pwm / negative
	   if (pwm > 0) {board.digitalWrite(2,1); board.digitalWrite(4,0);}; // določimo smer če je > 0
	   if (pwm < 0) {board.digitalWrite(2,0); board.digitalWrite(4,1);}; // določimo smer če je < 0
	   board.analogWrite(3, Math.round(Math.abs(pwm)));
	   console.log(Math.round(pwm));
	  }

	if (parameters.ctrlAlgNo == 2) {
	   err = desiredValue - actualValue; // error
	   errSum += err; // sum of errors, like integral
	   errSumAbs += Math.abs(err);
       dErr = err - lastErr; // difference of error
       // for sending to client we put the parts to global scope
       KpE=parameters.Kp1*err;
       KiIedt=parameters.Ki1*errSum;
       KdDe_dt=parameters.Kd1*dErr;
       pwm = KpE + KiIedt + KdDe_dt; // above parts are used
	   lastErr = err; // save the value for the next cycle
	   if(pwm > pwmLimit) {pwm = pwmLimit}; // to limit the value for pwm / positive
       if(pwm < -pwmLimit) {pwm = -pwmLimit}; // to limit the value for pwm / negative
	   if (pwm > 0) {board.digitalWrite(2,1); board.digitalWrite(4,0);}; // določimo smer če je > 0
	   if (pwm < 0) {board.digitalWrite(2,0); board.digitalWrite(4,1);}; // določimo smer če je < 0
	   board.analogWrite(3, Math.abs(pwm));
	  }
};

function sendValues (socket) {
    socket.emit("clientReadValues",
    { // json notation between curly braces
    "desiredValue": desiredValue,
    "actualValue": actualValue,
    "pwm": pwm,
    "err": err,
    "errSum": errSum,
    "dErr": dErr,
    "KpE": KpE,
    "KiIedt": KiIedt,
    "KdDe_dt": KdDe_dt,
    "errSumAbs": errSumAbs
  });
};

	  function startControlAlgorithm (parameters) {
	      if (controlAlgorithmStartedFlag == 0) {
	          controlAlgorithmStartedFlag = 1; // set flag that the algorithm has started
	          intervalCtrl = setInterval(function() {controlAlgorithm(parameters); }, 30); // na 30ms klic
	          console.log("Control algorithm " + parameters.ctrlAlgNo + " started");
	          sendStaticMsgViaSocket("Control algorithm " + parameters.ctrlAlgNo + " started | " + json2txt(parameters));
      }
	  };

	  function stopControlAlgorithm () {
	      clearInterval(intervalCtrl); // clear the interval of control algorihtm
	      board.analogWrite(3,0); // write 0 on pwm pin to stop the motor
	      controlAlgorithmStartedFlag = 0; // set flag that the algorithm has stopped
	      pwm = 0; // set pwm to 0

	      err = 0; // error
	      errSum = 0; // sum of errors, like integral
	      dErr = 0; // difference of error
	      KpE = 0;
	      KiIedt = 0;
	      KdDe_dt = 0;
          errSumAbs = 0;

	      console.log("ctrlAlg STOPPED");
	      sendStaticMsgViaSocket("Stop");
	  };

	  function json2txt(obj) // function to print out the json names and values
	  {
	    var txt = '';
    var recurse = function(_obj) {
	      if ('object' != typeof(_obj)) {
	        txt += ' = ' + _obj + '\n';
      }
      else {
	        for (var key in _obj) {
	          if (_obj.hasOwnProperty(key)) {
	            txt += '.' + key;
	            recurse(_obj[key]);
          }
	        }
	      }
	    };
	    recurse(obj);
	    return txt;
 }<commit_msg>Delete 21diod.js<commit_after><|endoftext|>


<commit_before>var exec = require('child_process').exec;

module.exports = {
    createNewServer: function(){
        var vmName = new Date().getTime();
        var createVm = exec('VBoxManage clonevm cd37efcb-9af4-4b90-a008-9ddc22e84006 --options link --snapshot 83c00d8e-36a4-433e-9cdd-f39787efef41 --register --name ' + vmName);
        createVm.on('exit', function(){
            var startvm = exec('VBoxManage startvm ' + vmName + " --type headless");
        });

    }

}
<commit_msg>Created controller for virtual machines<commit_after>var exec = require('child_process').exec;

module.exports = {
    createNewServer: function(){
        var vmName = new Date().getTime();
        var createVm = exec('VBoxManage clonevm cd37efcb-9af4-4b90-a008-9ddc22e84006 --options link --snapshot 70b1f605-f17b-4075-818e-bc7f9fd4f679 --register --name ' + vmName);
        createVm.on('exit', function(){
            var startvm = exec('VBoxManage startvm ' + vmName + " --type headless");
        });

    }

}
<|endoftext|>


<commit_before>const styles = require('../Style/style.js')

import React, { Component } from 'react'
import { View, AsyncStorage, StyleSheet } from 'react-native'
import HomeMap from './HomeMap'
import LoginPage from './LoginPage'

export default class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      userToken:'',
      userObj: ''
    }
  }

  setUser (userInfo) {
    this.setState({
      userToken: userInfo.accessToken,
      userObj: userInfo.user
      })
    AsyncStorage.setItem('pLotLoginKey',userInfo.accessToken)
    console.log('this is the state after Set User', this.state)
    }

  componentDidMount() {
    AsyncStorage.getItem('pLotLoginKey')
    .then( (userKey) => {
      console.log('DOT THEN', userKey)
      if(userKey) {
        this.setState({
        userToken: userKey
      })
      }
      console.log('user key ?', this.state.userToken)
    })
  }

  render () {
    if(this.state.userToken) {
      return (
        <View style={styles.container}>
          <HomeMap currentUser={this.state.userObj} userToken={this.state.userToken} />
        </View>
      )
    } else {
      return (
        <View>
         <LoginPage setUser={this.setUser.bind(this)}/>
        </View>
      )
    }
  }
}
<commit_msg>Renders login or map depending on user token. Needs work<commit_after>const styles = require('../Style/style.js')

import React, { Component } from 'react'
import { View, AsyncStorage, StyleSheet } from 'react-native'
import HomeMap from './HomeMap'
import LoginPage from './LoginPage'

export default class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      userToken:'',
      userObj: ''
    }
  }

  setUser (userInfo) {
    this.setState({
      userToken: userInfo.accessToken,
      userObj: userInfo.user
      })
    AsyncStorage.setItem('pLotLoginKey',userInfo.accessToken)
    console.log('this is the state after Set User', this.state)
    }

  componentDidMount() {
    AsyncStorage.getItem('pLotLoginKey')
    .then( (userKey) => {
      console.log('DOT THEN', userKey)
      if(userKey) {
        this.setState({
        userToken: userKey
      })
      }
      console.log('user key ?', this.state.userToken)
    })
  }

  render () {

    if(this.state.userToken) {
      return (
        <View style={styles.container}>
          <HomeMap currentUser={this.state.userObj} userToken={this.state.userToken} />
        </View>
      )
    } else {
      return (
        <View style={{flex: 1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center'}}>
          <LoginPage setUser={this.setUser.bind(this)}/>
        </View>
      )
    }
  }
}
<|endoftext|>