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

define(
        "joynr/capabilities/CapabilitiesStore",
        [ "joynr/util/Typing"
        ],
        function(Typing) {

            /**
             * Private function. This function returns the hashCode of the given discovery entry, this should uniquely identify a
             * discovery entry within the capability directory.
             *
             * @name CapabilitiesStore#hashCode
             * @function
             * @private
             *
             * @param {DiscoveryEntry}
             *            discoveryEntry - discovery entry
             */
            function hashCode(discoveryEntry) {
                return discoveryEntry.domain
                    + discoveryEntry.interfaceName
                    + discoveryEntry.participantId;
            }

            /**
             * Private function. Returns a key for indexing by the domain, interfaceName and providerQos.
             *
             * @name CapabilitiesStore#getDomainInterfaceNameKey
             * @function
             * @private
             *
             * @param {String}
             *            domain - the domain
             * @param {String}
             *            interfaceName - the interface name
             * @returns {String} the unique key for the domain and interface name
             */
            function getDomainInterfaceNameKey(domain, interfaceName) {
                return domain + interfaceName;
            }

            /**
             * The Local Capabilities Storage
             *
             * @name CapabilitiesStore
             * @constructor
             *
             * @classdesc
             * The CapabilitiesStore is a joynr internal interface. When a provider that is registered with joynr, the framework creates an
             * entry for that provider in the capabilities directory. These {@link DiscoveryEntry} entries contain access
             * information as well as supported Qos. The information is later used in the arbitration process to pick a provider for a proxy.
             *
             * @param {Array}
             *            initialCapabilities
             * @param {CapabilityInformation}
             *            initialCapabilities.array
             */
            function CapabilitiesStore(initialCapabilities) {
                // participantId -> Array of Capability Information
                var discoveryEntryStoreByParticipantId = {};

                // domain + interface -> Array of Capability Information
                var discoveryEntryStoreByDomainInterfaceName = {};

                // discovery entry hashCode -> Array of Capability Information
                var discoveryEntryStore = {};

                var registeredCapabilitiesTime = {};

                /**
                 * Unregisters a discovery entry from the store.
                 *
                 * @name CapabilitiesStore#removeDiscoveryEntryFromStore
                 * @function
                 *
                 * @param {String}
                 *            participantId - the participant ID uniquely identifying the discovery entry to be removed
                 */
                function removeDiscoveryEntryFromStore(participantId) {
                    var domainInterfaceKey, key, capabilities, capId, cap, capFound = false, discoveryEntry;

                    discoveryEntry = discoveryEntryStoreByParticipantId[participantId];

                    // unregister by participant id
                    discoveryEntryStoreByParticipantId[participantId] = undefined;

                    if (discoveryEntry !== undefined) {
                        // unregister by domain and interface
                        domainInterfaceKey =
                                getDomainInterfaceNameKey(
                                        discoveryEntry.domain,
                                        discoveryEntry.interfaceName);
                        capabilities = discoveryEntryStoreByDomainInterfaceName[domainInterfaceKey];

                        capFound = false;
                        for (capId in capabilities) {
                            if (capabilities.hasOwnProperty(capId) && !capFound) {
                                cap = capabilities[capId];
                                if (cap.interfaceName === discoveryEntry.interfaceName
                                    && cap.domain === discoveryEntry.domain) {
                                    capFound = true;
                                    discoveryEntryStoreByDomainInterfaceName[domainInterfaceKey]
                                            .splice(capId, 1);
                                }
                            }
                        }

                        // unregister master store
                        key = hashCode(discoveryEntry);
                        delete discoveryEntryStore[key];
                    }
                }

                /**
                 * Registers discovery entry to the store.
                 *
                 * @name CapabilitiesStore#addDiscoveryEntryToStore
                 * @function
                 *
                 * @param {DiscoveryEntry}
                 *            discoveryEntry - the capability to register
                 *
                 */
                function addDiscoveryEntryToStore(discoveryEntry) {
                    var entryFound = false, isAlreadyThere, discoveryEntries, entryId, entry, domainInterfaceKey, discoveryEntryKey =
                            hashCode(discoveryEntry);

                    // master store, storing key to actual discovery entry object
                    isAlreadyThere = discoveryEntryStore[discoveryEntryKey];
                    if (isAlreadyThere !== undefined) {
                        removeDiscoveryEntryFromStore(isAlreadyThere);
                    }
                    discoveryEntryStore[discoveryEntryKey] = discoveryEntry;
                    registeredCapabilitiesTime[discoveryEntryKey] = Date.now();

                    // by participant id
                    discoveryEntryStoreByParticipantId[discoveryEntry.participantId] =
                            discoveryEntry;

                    // by domain interface and provider qos
                    domainInterfaceKey =
                            getDomainInterfaceNameKey(
                                    discoveryEntry.domain,
                                    discoveryEntry.interfaceName);
                    if (discoveryEntryStoreByDomainInterfaceName[domainInterfaceKey] === undefined) {
                        discoveryEntryStoreByDomainInterfaceName[domainInterfaceKey] = [];
                    }

                    discoveryEntries = discoveryEntryStoreByDomainInterfaceName[domainInterfaceKey];

                    for (entryId in discoveryEntries) {
                        if (discoveryEntries.hasOwnProperty(entryId) && !entryFound) {
                            entry = discoveryEntries[entryId];
                            if (entry.participantId === discoveryEntry.participantId) {
                                entryFound = true;
                            }
                        }
                    }

                    if (!entryFound) {
                        discoveryEntryStoreByDomainInterfaceName[domainInterfaceKey]
                                .push(discoveryEntry);
                    }
                }

                /**
                 * Registers either a single discovery entry or a list of discovery entry to the store.
                 *
                 * @name CapabilitiesStore#add
                 * @function
                 *
                 * @param {Object}
                 *            settings - an object containing the required parameters
                 * @param {Array.<DiscoveryEntry>}
                 *            settings.discoveryEntries - an array of discovery entries to register
                 * @param {DiscoveryEntry}
                 *            settings.discoveryEntry a single discovery entry to register (only if settings.discoveryEntries is not supplied)
                 * @param {Boolean}
                 *            settings.remote true if the provided entry/entries are gathered from remote
                 *
                 * @returns {CapabilitiesStore} returns this for a fluent interface
                 *
                 */
                this.add =
                        function add(settings) {
                            var i;
                            if (settings.discoveryEntries !== undefined
                                && Typing.getObjectType(settings.discoveryEntries) === "Array") {
                                for (i = 0; i < settings.discoveryEntries.length; i++) {
                                    addDiscoveryEntryToStore(settings.discoveryEntries[i]);
                                }
                            } else if (settings.discoveryEntry !== undefined) {
                                addDiscoveryEntryToStore(settings.discoveryEntry);
                            } else {
                                throw new Error(
                                        "missing arguments for function CapabilitiesStore.add: neither settings.discoveryEntries nor settings.discoveryEntry are provided");
                            }
                            return this;
                        };

                /**
                 * checks if the provided discoveryEntry is not older than the second argument maxAge
                 *
                 * @name CapabilitiesStore#checkAge
                 * @function
                 *
                 * @param {DiscoveryEntry} discoveryEntry - the discovery entry to check
                 * @param {Number} maxAge - the maximum age of the discovery entry
                 */
                var checkAge = function checkAge(discoveryEntry, maxAge) {
                    var registrationTime = registeredCapabilitiesTime[hashCode(discoveryEntry)];
                    if (registrationTime === undefined || maxAge === undefined) {
                        return true;
                    }
                    return (Date.now() - registrationTime <= maxAge);
                };

                /**
                 * checks if the discoveryQos matches with the discoveryEntry
                 *
                 * @name CapabilitiesStore#qosMatches
                 * @function
                 *
                 * @param {DiscoveryEntry} discoveryEntry - the discovery entry to check
                 * @param {Number} cacheMaxAge - the maximum age of the discovery entry
                 */
                var qosMatches = function qosMatches(discoveryEntry, cacheMaxAge) {
                    return discoveryEntry !== undefined && checkAge(discoveryEntry, cacheMaxAge);
                };

                /**
                 * filters provided entries and returns only local entries
                 *
                 * @name CapabilitiesStore#filterEntries
                 * @function
                 *
                 * @param {Array.<DiscoveryEntry>} entries - the discovery entries to be filtered
                 * @param {Number} cacheMaxAge - the maximum age of the discovery entries
                 */
                var filterEntries = function filterEntries(entries, cacheMaxAge) {
                    var i, returnValue, discoveryEntry;
                    returnValue = [];
                    for (i = entries.length - 1; i >= 0; i--) {
                        discoveryEntry = entries[i];
                        if (qosMatches(discoveryEntry, cacheMaxAge)) {
                            returnValue.push(discoveryEntry);
                        }
                    }
                    return returnValue;
                };

                /**
                 * Looks up a list of capabilities either for a given participant ID or for a given domain / interfaceName combination
                 *
                 * @name CapabilitiesStore#lookup
                 * @function
                 *
                 * @param {Object}
                 *            settings - an object containing the required parameters
                 * @param {String}
                 *            settings.domain - the name of the domain
                 * @param {String}
                 *            settings.interfaceName - the interface name of the capability
                 * @param {String}
                 *            settings.participantId - the participantId of the capability
                 * @param {DiscoveryQos}
                 *            settings.cacheMaxAge - max age used for filtering the store entries
                 *
                 * @returns {Array} a list of matching discovery entries.
                 */
                this.lookup =
                        function lookup(settings) {
                            var key, returnValue, storedEntries;
                            if (settings.domain !== undefined
                                && settings.interfaceName !== undefined) {
                                key =
                                        getDomainInterfaceNameKey(
                                                settings.domain,
                                                settings.interfaceName);
                                storedEntries = discoveryEntryStoreByDomainInterfaceName[key] || [];
                                returnValue = filterEntries(storedEntries, settings.cacheMaxAge);
                            } else if (settings.participantId !== undefined) {
                                storedEntries =
                                        discoveryEntryStoreByParticipantId[settings.participantId];
                                if (qosMatches(storedEntries, settings.cacheMaxAge)) {
                                    returnValue = storedEntries;
                                } else {
                                    returnValue = undefined;
                                }
                            } else {
                                throw new Error(
                                        "missing arguments for function CapabilitiesStore.lookup: neither settings.domain + settings.interfaceName nor settings.participantId are provided");
                            }
                            return returnValue;
                        };

                /**
                 * Unregisters either a list of discovery entries or a single discovery entry from the store.
                 *
                 * @name CapabilitiesStore#remove
                 * @function
                 *
                 * @param {Object}
                 *            settings - an object containing the required parameters
                 * @param {Array.<String>}
                 *            settings.participantIds - an array of participant IDs uniquely identifying the discovery entry to be removed
                 * @param {String}
                 *            settings.participantId -  a participant ID uniquely identifying the discovery entry to be removed
                 *
                 * @returns {CapabilitiesStore} returns this for a fluent interface
                 */
                this.remove =
                        function remove(settings) {
                            var i;
                            if (settings.participantIds !== undefined
                                && Typing.getObjectType(settings.participantIds) === "Array") {
                                for (i = 0; i < settings.participantIds.length; i++) {
                                    removeDiscoveryEntryFromStore(settings.participantIds[i]);
                                }
                            } else if (settings.participantId !== undefined) {
                                removeDiscoveryEntryFromStore(settings.participantId);
                            } else {
                                throw new Error(
                                        "missing arguments for function CapabilitiesStore.remove: neither settings.participantIds nor settings.participantId are provided");
                            }

                            return this;
                        };

                if (initialCapabilities && initialCapabilities.length > 0) {
                    this.add({
                        discoveryEntries : initialCapabilities
                    });
                }
            }

            return CapabilitiesStore;

        });<commit_msg>[JS] CapabilitiesStore.checkAge ignores negative max ages<commit_after>/*
 * #%L
 * %%
 * Copyright (C) 2011 - 2015 BMW Car IT GmbH
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

define(
        "joynr/capabilities/CapabilitiesStore",
        [ "joynr/util/Typing"
        ],
        function(Typing) {

            /**
             * Private function. This function returns the hashCode of the given discovery entry, this should uniquely identify a
             * discovery entry within the capability directory.
             *
             * @name CapabilitiesStore#hashCode
             * @function
             * @private
             *
             * @param {DiscoveryEntry}
             *            discoveryEntry - discovery entry
             */
            function hashCode(discoveryEntry) {
                return discoveryEntry.domain
                    + discoveryEntry.interfaceName
                    + discoveryEntry.participantId;
            }

            /**
             * Private function. Returns a key for indexing by the domain, interfaceName and providerQos.
             *
             * @name CapabilitiesStore#getDomainInterfaceNameKey
             * @function
             * @private
             *
             * @param {String}
             *            domain - the domain
             * @param {String}
             *            interfaceName - the interface name
             * @returns {String} the unique key for the domain and interface name
             */
            function getDomainInterfaceNameKey(domain, interfaceName) {
                return domain + interfaceName;
            }

            /**
             * The Local Capabilities Storage
             *
             * @name CapabilitiesStore
             * @constructor
             *
             * @classdesc
             * The CapabilitiesStore is a joynr internal interface. When a provider that is registered with joynr, the framework creates an
             * entry for that provider in the capabilities directory. These {@link DiscoveryEntry} entries contain access
             * information as well as supported Qos. The information is later used in the arbitration process to pick a provider for a proxy.
             *
             * @param {Array}
             *            initialCapabilities
             * @param {CapabilityInformation}
             *            initialCapabilities.array
             */
            function CapabilitiesStore(initialCapabilities) {
                // participantId -> Array of Capability Information
                var discoveryEntryStoreByParticipantId = {};

                // domain + interface -> Array of Capability Information
                var discoveryEntryStoreByDomainInterfaceName = {};

                // discovery entry hashCode -> Array of Capability Information
                var discoveryEntryStore = {};

                var registeredCapabilitiesTime = {};

                /**
                 * Unregisters a discovery entry from the store.
                 *
                 * @name CapabilitiesStore#removeDiscoveryEntryFromStore
                 * @function
                 *
                 * @param {String}
                 *            participantId - the participant ID uniquely identifying the discovery entry to be removed
                 */
                function removeDiscoveryEntryFromStore(participantId) {
                    var domainInterfaceKey, key, capabilities, capId, cap, capFound = false, discoveryEntry;

                    discoveryEntry = discoveryEntryStoreByParticipantId[participantId];

                    // unregister by participant id
                    discoveryEntryStoreByParticipantId[participantId] = undefined;

                    if (discoveryEntry !== undefined) {
                        // unregister by domain and interface
                        domainInterfaceKey =
                                getDomainInterfaceNameKey(
                                        discoveryEntry.domain,
                                        discoveryEntry.interfaceName);
                        capabilities = discoveryEntryStoreByDomainInterfaceName[domainInterfaceKey];

                        capFound = false;
                        for (capId in capabilities) {
                            if (capabilities.hasOwnProperty(capId) && !capFound) {
                                cap = capabilities[capId];
                                if (cap.interfaceName === discoveryEntry.interfaceName
                                    && cap.domain === discoveryEntry.domain) {
                                    capFound = true;
                                    discoveryEntryStoreByDomainInterfaceName[domainInterfaceKey]
                                            .splice(capId, 1);
                                }
                            }
                        }

                        // unregister master store
                        key = hashCode(discoveryEntry);
                        delete discoveryEntryStore[key];
                    }
                }

                /**
                 * Registers discovery entry to the store.
                 *
                 * @name CapabilitiesStore#addDiscoveryEntryToStore
                 * @function
                 *
                 * @param {DiscoveryEntry}
                 *            discoveryEntry - the capability to register
                 *
                 */
                function addDiscoveryEntryToStore(discoveryEntry) {
                    var entryFound = false, isAlreadyThere, discoveryEntries, entryId, entry, domainInterfaceKey, discoveryEntryKey =
                            hashCode(discoveryEntry);

                    // master store, storing key to actual discovery entry object
                    isAlreadyThere = discoveryEntryStore[discoveryEntryKey];
                    if (isAlreadyThere !== undefined) {
                        removeDiscoveryEntryFromStore(isAlreadyThere);
                    }
                    discoveryEntryStore[discoveryEntryKey] = discoveryEntry;
                    registeredCapabilitiesTime[discoveryEntryKey] = Date.now();

                    // by participant id
                    discoveryEntryStoreByParticipantId[discoveryEntry.participantId] =
                            discoveryEntry;

                    // by domain interface and provider qos
                    domainInterfaceKey =
                            getDomainInterfaceNameKey(
                                    discoveryEntry.domain,
                                    discoveryEntry.interfaceName);
                    if (discoveryEntryStoreByDomainInterfaceName[domainInterfaceKey] === undefined) {
                        discoveryEntryStoreByDomainInterfaceName[domainInterfaceKey] = [];
                    }

                    discoveryEntries = discoveryEntryStoreByDomainInterfaceName[domainInterfaceKey];

                    for (entryId in discoveryEntries) {
                        if (discoveryEntries.hasOwnProperty(entryId) && !entryFound) {
                            entry = discoveryEntries[entryId];
                            if (entry.participantId === discoveryEntry.participantId) {
                                entryFound = true;
                            }
                        }
                    }

                    if (!entryFound) {
                        discoveryEntryStoreByDomainInterfaceName[domainInterfaceKey]
                                .push(discoveryEntry);
                    }
                }

                /**
                 * Registers either a single discovery entry or a list of discovery entry to the store.
                 *
                 * @name CapabilitiesStore#add
                 * @function
                 *
                 * @param {Object}
                 *            settings - an object containing the required parameters
                 * @param {Array.<DiscoveryEntry>}
                 *            settings.discoveryEntries - an array of discovery entries to register
                 * @param {DiscoveryEntry}
                 *            settings.discoveryEntry a single discovery entry to register (only if settings.discoveryEntries is not supplied)
                 * @param {Boolean}
                 *            settings.remote true if the provided entry/entries are gathered from remote
                 *
                 * @returns {CapabilitiesStore} returns this for a fluent interface
                 *
                 */
                this.add =
                        function add(settings) {
                            var i;
                            if (settings.discoveryEntries !== undefined
                                && Typing.getObjectType(settings.discoveryEntries) === "Array") {
                                for (i = 0; i < settings.discoveryEntries.length; i++) {
                                    addDiscoveryEntryToStore(settings.discoveryEntries[i]);
                                }
                            } else if (settings.discoveryEntry !== undefined) {
                                addDiscoveryEntryToStore(settings.discoveryEntry);
                            } else {
                                throw new Error(
                                        "missing arguments for function CapabilitiesStore.add: neither settings.discoveryEntries nor settings.discoveryEntry are provided");
                            }
                            return this;
                        };

                /**
                 * checks if the provided discoveryEntry is not older than the second argument maxAge
                 *
                 * @name CapabilitiesStore#checkAge
                 * @function
                 *
                 * @param {DiscoveryEntry} discoveryEntry - the discovery entry to check
                 * @param {Number} maxAge - the maximum age of the discovery entry
                 */
                var checkAge = function checkAge(discoveryEntry, maxAge) {
                    var registrationTime = registeredCapabilitiesTime[hashCode(discoveryEntry)];
                    if (registrationTime === undefined || maxAge === undefined || maxAge < 0) {
                        return true;
                    }
                    return (Date.now() - registrationTime <= maxAge);
                };

                /**
                 * checks if the discoveryQos matches with the discoveryEntry
                 *
                 * @name CapabilitiesStore#qosMatches
                 * @function
                 *
                 * @param {DiscoveryEntry} discoveryEntry - the discovery entry to check
                 * @param {Number} cacheMaxAge - the maximum age of the discovery entry
                 */
                var qosMatches = function qosMatches(discoveryEntry, cacheMaxAge) {
                    return discoveryEntry !== undefined && checkAge(discoveryEntry, cacheMaxAge);
                };

                /**
                 * filters provided entries and returns only local entries
                 *
                 * @name CapabilitiesStore#filterEntries
                 * @function
                 *
                 * @param {Array.<DiscoveryEntry>} entries - the discovery entries to be filtered
                 * @param {Number} cacheMaxAge - the maximum age of the discovery entries
                 */
                var filterEntries = function filterEntries(entries, cacheMaxAge) {
                    var i, returnValue, discoveryEntry;
                    returnValue = [];
                    for (i = entries.length - 1; i >= 0; i--) {
                        discoveryEntry = entries[i];
                        if (qosMatches(discoveryEntry, cacheMaxAge)) {
                            returnValue.push(discoveryEntry);
                        }
                    }
                    return returnValue;
                };

                /**
                 * Looks up a list of capabilities either for a given participant ID or for a given domain / interfaceName combination
                 *
                 * @name CapabilitiesStore#lookup
                 * @function
                 *
                 * @param {Object}
                 *            settings - an object containing the required parameters
                 * @param {String}
                 *            settings.domain - the name of the domain
                 * @param {String}
                 *            settings.interfaceName - the interface name of the capability
                 * @param {String}
                 *            settings.participantId - the participantId of the capability
                 * @param {DiscoveryQos}
                 *            settings.cacheMaxAge - max age used for filtering the store entries
                 *
                 * @returns {Array} a list of matching discovery entries.
                 */
                this.lookup =
                        function lookup(settings) {
                            var key, returnValue, storedEntries;
                            if (settings.domain !== undefined
                                && settings.interfaceName !== undefined) {
                                key =
                                        getDomainInterfaceNameKey(
                                                settings.domain,
                                                settings.interfaceName);
                                storedEntries = discoveryEntryStoreByDomainInterfaceName[key] || [];
                                returnValue = filterEntries(storedEntries, settings.cacheMaxAge);
                            } else if (settings.participantId !== undefined) {
                                storedEntries =
                                        discoveryEntryStoreByParticipantId[settings.participantId];
                                if (qosMatches(storedEntries, settings.cacheMaxAge)) {
                                    returnValue = storedEntries;
                                } else {
                                    returnValue = undefined;
                                }
                            } else {
                                throw new Error(
                                        "missing arguments for function CapabilitiesStore.lookup: neither settings.domain + settings.interfaceName nor settings.participantId are provided");
                            }
                            return returnValue;
                        };

                /**
                 * Unregisters either a list of discovery entries or a single discovery entry from the store.
                 *
                 * @name CapabilitiesStore#remove
                 * @function
                 *
                 * @param {Object}
                 *            settings - an object containing the required parameters
                 * @param {Array.<String>}
                 *            settings.participantIds - an array of participant IDs uniquely identifying the discovery entry to be removed
                 * @param {String}
                 *            settings.participantId -  a participant ID uniquely identifying the discovery entry to be removed
                 *
                 * @returns {CapabilitiesStore} returns this for a fluent interface
                 */
                this.remove =
                        function remove(settings) {
                            var i;
                            if (settings.participantIds !== undefined
                                && Typing.getObjectType(settings.participantIds) === "Array") {
                                for (i = 0; i < settings.participantIds.length; i++) {
                                    removeDiscoveryEntryFromStore(settings.participantIds[i]);
                                }
                            } else if (settings.participantId !== undefined) {
                                removeDiscoveryEntryFromStore(settings.participantId);
                            } else {
                                throw new Error(
                                        "missing arguments for function CapabilitiesStore.remove: neither settings.participantIds nor settings.participantId are provided");
                            }

                            return this;
                        };

                if (initialCapabilities && initialCapabilities.length > 0) {
                    this.add({
                        discoveryEntries : initialCapabilities
                    });
                }
            }

            return CapabilitiesStore;

        });<|endoftext|>


<commit_before>/*******************************************************************************
 * Name: QuizziPedia::Front-End::Controllers::EditorQMLController;
 * Description: questa classe permette di gestire l'inserimento delle domande QML
 *
 * Relations with other classes:
 * +
 *
 * Creation data: 03-05-2016;
 * Author: Alberto Ferrara;
 * License: MIT.
 ********************************************************************************
 * Updates history
 *-------------------------------------------------------------------------------
 * ID: EditorQMLController_20160503
 * Update data: 03-05-2016
 * Description: Creato il controller;
 * Author: Alberto Ferrara.
 *-------------------------------------------------------------------------------
 *******************************************************************************/
app.controller('EditorQMLController', EditorQMLController);

EditorQMLController.$inject = ['$scope', '$rootScope', '$routeParams', 'QuestionsService', '$location', '$mdDialog', 'QuestionItemModel', 'ErrorInfoModel'];

function EditorQMLController($scope, $rootScope, $routeParams, QuestionsService, $location, $mdDialog, QuestionItemModel, ErrorInfoModel){

    $scope.submitQuestion = function(question){
        //Parser della domanda
        if(question == undefined){
            alert = $mdDialog.alert()
                .title("Errore con la domanda")
                .content("Domanda Vuota!")
                .ok('Ok');
            $mdDialog
                .show(alert)
                .finally(function () {
                    alert = undefined;
                });
        }
        else{
        var result = jsonlint.parse(question);
        if (result) {
            var q = JSON.stringify(question, null, "  ");
            console.log('q: ' + q);
            QuestionsService.sendQuestion(q, $routeParams.lang)
                .then(function (result) {
                    if (result) {
                        $rootScope.question = new QuestionItemModel();
                        $scope.error = new ErrorInfoModel();
                        alert = $mdDialog.alert()
                            .title("Inserimento avvenuto con successo")
                            .content("La domanda è stata inserita!")
                            .ok('Ok');
                        $mdDialog
                            .show(alert)
                            .finally(function () {
                                alert = undefined;
                            });
                        $location.path('/' + $routeParams.lang + '/home');
                    }
                }, function (err) {
                    $scope.error = new ErrorInfoModel();
                    alert = $mdDialog.alert()
                        .title("Errore")
                        .content("La richiesta di inserimento domanda non è andata a buon fine")
                        .ok('Ok');
                    $mdDialog
                        .show(alert)
                        .finally(function () {
                            alert = undefined;
                        });
                });
        }
        }
    }

    $scope.goToWizard = function () {
        $location.path('/'+$routeParams.lang+'/wizard');
    };

}
<commit_msg>Aggiunto controllo errore sintassi (da perfezionare)<commit_after>/*******************************************************************************
 * Name: QuizziPedia::Front-End::Controllers::EditorQMLController;
 * Description: questa classe permette di gestire l'inserimento delle domande QML
 *
 * Relations with other classes:
 * +
 *
 * Creation data: 03-05-2016;
 * Author: Alberto Ferrara;
 * License: MIT.
 ********************************************************************************
 * Updates history
 *-------------------------------------------------------------------------------
 * ID: EditorQMLController_20160503
 * Update data: 03-05-2016
 * Description: Creato il controller;
 * Author: Alberto Ferrara.
 *-------------------------------------------------------------------------------
 *******************************************************************************/
app.controller('EditorQMLController', EditorQMLController);

EditorQMLController.$inject = ['$scope', '$rootScope', '$routeParams', 'QuestionsService', '$location', '$mdDialog', 'QuestionItemModel', 'ErrorInfoModel'];

function EditorQMLController($scope, $rootScope, $routeParams, QuestionsService, $location, $mdDialog, QuestionItemModel, ErrorInfoModel){

    $scope.submitQuestion = function(question){
        //Parser della domanda
        if(question == undefined){
            alert = $mdDialog.alert()
                .title("Errore con la domanda")
                .content("Domanda Vuota!")
                .ok('Ok');
            $mdDialog
                .show(alert)
                .finally(function () {
                    alert = undefined;
                });
        }
        else{
            var result = '';
            try{
            result = jsonlint.parse(question);}
            catch(e){
                alert = $mdDialog.alert()
                    .title("Errore con la domanda")
                    .content("Ci sono degli errori nella sintassi!")
                    .ok('Ok');
                $mdDialog
                    .show(alert)
                    .finally(function () {
                        alert = undefined;
                    });
                return;
            }

            if (result) {
            var q = JSON.stringify(question, null, "  ");
            console.log('q: ' + q);

            QuestionsService.sendQuestion(q, $routeParams.lang)
                .then(function (result) {
                    if (result) {
                        $rootScope.question = new QuestionItemModel();
                        $scope.error = new ErrorInfoModel();
                        alert = $mdDialog.alert()
                            .title("Inserimento avvenuto con successo")
                            .content("La domanda è stata inserita!")
                            .ok('Ok');
                        $mdDialog
                            .show(alert)
                            .finally(function () {
                                alert = undefined;
                            });
                        $location.path('/' + $routeParams.lang + '/home');
                    }
                }, function (err) {
                    $scope.error = new ErrorInfoModel();
                    alert = $mdDialog.alert()
                        .title("Errore")
                        .content("La richiesta di inserimento domanda non è andata a buon fine")
                        .ok('Ok');
                    $mdDialog
                        .show(alert)
                        .finally(function () {
                            alert = undefined;
                        });
                });
        }
        }
    }

    $scope.goToWizard = function () {
        $location.path('/'+$routeParams.lang+'/wizard');
    };

}
<|endoftext|>


<commit_before>'use strict';

// MODULES //

var resolve = require( 'path' ).resolve;
var exec = require( 'child_process' ).exec;
var tape = require( 'tape' );
var IS_BROWSER = require( '@stdlib/assert/is-browser' );
var IS_WINDOWS = require( '@stdlib/assert/is-windows' );
var readFileSync = require( '@stdlib/fs/read-file' ).sync;

// VARIABLES //

var fpath = resolve( __dirname, '..', 'bin', 'cli' );
var opts = {
	'skip': IS_BROWSER || IS_WINDOWS
};

// FIXTURES //

var PKG_VERSION = require('./../package.json' ).version;

// TESTS //

tape( 'command-line interface', function test( t ) {
	t.ok( true, __filename );
	t.end();
});

tape( 'when invoked with a `--help` flag, the command-line interface prints the help text to `stderr`', opts, function test( t ) {
	var expected;
	var cmd;

	expected = readFileSync( resolve( __dirname, '..', 'bin', 'usage.txt' ), {
		'encoding': 'utf8'
	});
	cmd = [
		process.execPath,
		fpath,
		'--help'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' );
			t.strictEqual( stderr.toString(), expected+'\n', 'expected value' );
		}
		t.end();
	}
});

tape( 'when invoked with a `-h` flag, the command-line interface prints the help text to `stderr`', opts, function test( t ) {
	var expected;
	var cmd;

	expected = readFileSync( resolve( __dirname, '..', 'bin', 'usage.txt' ), {
		'encoding': 'utf8'
	});
	cmd = [
		process.execPath,
		fpath,
		'-h'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' );
			t.strictEqual( stderr.toString(), expected+'\n', 'expected value' );
		}
		t.end();
	}
});

tape( 'when invoked with a `--version` flag, the command-line interface prints the version to `stderr`', opts, function test( t ) {
	var cmd = [
		process.execPath,
		fpath,
		'--version'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' );
			t.strictEqual( stderr.toString(), PKG_VERSION+'\n', 'expected value' );
		}
		t.end();
	}
});

tape( 'when invoked with a `-V` flag, the command-line interface prints the version to `stderr`', opts, function test( t ) {
	var cmd = [
		process.execPath,
		fpath,
		'-V'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' );
			t.strictEqual( stderr.toString(), PKG_VERSION+'\n', 'expected value' );
		}
		t.end();
	}
});

tape( 'the function converts a TeX or LaTeX string to an SVG (no options)', opts, function test( t ) {
	var expected;
	var cmd;

	cmd = [
		process.execPath,
		fpath,
		'\'\\operatorname{erf}(x) = \\frac{2}{\\sqrt\\pi}\\int_0^x e^{-t^2}\\,\\mathrm dt.\''
	];
	expected = readFileSync( resolve( __dirname, 'fixtures', '1.svg' ), {
		'encoding': 'utf8'
	});

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		var svg;
		if ( error ) {
			t.fail( error.message );
		} else {
			svg = stdout.toString();
			t.strictEqual( typeof svg, 'string', 'returns a string' );
			t.strictEqual( svg.substring( 0, 4 ), '<svg', 'svg tag' );
			t.strictEqual( svg.substring( svg.length-7, svg.length-1 ), '</svg>', 'closing svg tag' );
			t.strictEqual( svg.substring( svg.length-1 ), '\n', 'new line' );
			t.strictEqual( svg, expected, 'expected value' );
			t.strictEqual( stderr.toString(), '', 'does not print to `stderr`' );
		}
		t.end();
	}
});

tape( 'the function converts a TeX or LaTeX string to an SVG (options)', opts, function test( t ) {
	var expected;
	var cmd;

	cmd = [
		process.execPath,
		fpath,
		'\'\\operatorname{erf}(x) = \\frac{2}{\\sqrt\\pi}\\int_0^x e^{-t^2}\\,\\mathrm dt.\'',
		'--inline',
		'--no-linebreaks'
	];
	expected = readFileSync( resolve( __dirname, 'fixtures', '2.svg' ), {
		'encoding': 'utf8'
	});

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		var svg;
		if ( error ) {
			t.fail( error.message );
		} else {
			svg = stdout.toString();
			t.strictEqual( typeof svg, 'string', 'returns a string' );
			t.strictEqual( svg.substring( 0, 4 ), '<svg', 'svg tag' );
			t.strictEqual( svg.substring( svg.length-7, svg.length-1 ), '</svg>', 'closing svg tag' );
			t.strictEqual( svg.substring( svg.length-1 ), '\n', 'new line' );
			t.strictEqual( svg, expected, 'expected value' );
			t.strictEqual( stderr.toString(), '', 'does not print to `stderr`' );
		}
		t.end();
	}
});

<commit_msg>Fix descriptions<commit_after>'use strict';

// MODULES //

var resolve = require( 'path' ).resolve;
var exec = require( 'child_process' ).exec;
var tape = require( 'tape' );
var IS_BROWSER = require( '@stdlib/assert/is-browser' );
var IS_WINDOWS = require( '@stdlib/assert/is-windows' );
var readFileSync = require( '@stdlib/fs/read-file' ).sync;

// VARIABLES //

var fpath = resolve( __dirname, '..', 'bin', 'cli' );
var opts = {
	'skip': IS_BROWSER || IS_WINDOWS
};

// FIXTURES //

var PKG_VERSION = require('./../package.json' ).version;

// TESTS //

tape( 'command-line interface', function test( t ) {
	t.ok( true, __filename );
	t.end();
});

tape( 'when invoked with a `--help` flag, the command-line interface prints the help text to `stderr`', opts, function test( t ) {
	var expected;
	var cmd;

	expected = readFileSync( resolve( __dirname, '..', 'bin', 'usage.txt' ), {
		'encoding': 'utf8'
	});
	cmd = [
		process.execPath,
		fpath,
		'--help'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' );
			t.strictEqual( stderr.toString(), expected+'\n', 'expected value' );
		}
		t.end();
	}
});

tape( 'when invoked with a `-h` flag, the command-line interface prints the help text to `stderr`', opts, function test( t ) {
	var expected;
	var cmd;

	expected = readFileSync( resolve( __dirname, '..', 'bin', 'usage.txt' ), {
		'encoding': 'utf8'
	});
	cmd = [
		process.execPath,
		fpath,
		'-h'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' );
			t.strictEqual( stderr.toString(), expected+'\n', 'expected value' );
		}
		t.end();
	}
});

tape( 'when invoked with a `--version` flag, the command-line interface prints the version to `stderr`', opts, function test( t ) {
	var cmd = [
		process.execPath,
		fpath,
		'--version'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' );
			t.strictEqual( stderr.toString(), PKG_VERSION+'\n', 'expected value' );
		}
		t.end();
	}
});

tape( 'when invoked with a `-V` flag, the command-line interface prints the version to `stderr`', opts, function test( t ) {
	var cmd = [
		process.execPath,
		fpath,
		'-V'
	];

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		if ( error ) {
			t.fail( error.message );
		} else {
			t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' );
			t.strictEqual( stderr.toString(), PKG_VERSION+'\n', 'expected value' );
		}
		t.end();
	}
});

tape( 'the command-line interface converts a TeX or LaTeX string to an SVG (no options)', opts, function test( t ) {
	var expected;
	var cmd;

	cmd = [
		process.execPath,
		fpath,
		'\'\\operatorname{erf}(x) = \\frac{2}{\\sqrt\\pi}\\int_0^x e^{-t^2}\\,\\mathrm dt.\''
	];
	expected = readFileSync( resolve( __dirname, 'fixtures', '1.svg' ), {
		'encoding': 'utf8'
	});

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		var svg;
		if ( error ) {
			t.fail( error.message );
		} else {
			svg = stdout.toString();
			t.strictEqual( typeof svg, 'string', 'returns a string' );
			t.strictEqual( svg.substring( 0, 4 ), '<svg', 'svg tag' );
			t.strictEqual( svg.substring( svg.length-7, svg.length-1 ), '</svg>', 'closing svg tag' );
			t.strictEqual( svg.substring( svg.length-1 ), '\n', 'new line' );
			t.strictEqual( svg, expected, 'expected value' );
			t.strictEqual( stderr.toString(), '', 'does not print to `stderr`' );
		}
		t.end();
	}
});

tape( 'the command-line interface converts a TeX or LaTeX string to an SVG (options)', opts, function test( t ) {
	var expected;
	var cmd;

	cmd = [
		process.execPath,
		fpath,
		'\'\\operatorname{erf}(x) = \\frac{2}{\\sqrt\\pi}\\int_0^x e^{-t^2}\\,\\mathrm dt.\'',
		'--inline',
		'--no-linebreaks'
	];
	expected = readFileSync( resolve( __dirname, 'fixtures', '2.svg' ), {
		'encoding': 'utf8'
	});

	exec( cmd.join( ' ' ), done );

	function done( error, stdout, stderr ) {
		var svg;
		if ( error ) {
			t.fail( error.message );
		} else {
			svg = stdout.toString();
			t.strictEqual( typeof svg, 'string', 'returns a string' );
			t.strictEqual( svg.substring( 0, 4 ), '<svg', 'svg tag' );
			t.strictEqual( svg.substring( svg.length-7, svg.length-1 ), '</svg>', 'closing svg tag' );
			t.strictEqual( svg.substring( svg.length-1 ), '\n', 'new line' );
			t.strictEqual( svg, expected, 'expected value' );
			t.strictEqual( stderr.toString(), '', 'does not print to `stderr`' );
		}
		t.end();
	}
});

<|endoftext|>


<commit_before>define(["require","exports","module","jquery","underscore","knockout","classify"],function(require,exports,module,$,_,ko,Classify){

    var SuperSQLStore = {};
    SuperSQLStore.ObservableRow = Classify.newClass({
        constructor: function(config) {
            var self = this;

            config = config || {};
            var row = config.row;
            self._originalData = row;
            self._columns = {};

            // Loop through the properties on the row to make observable versions of each column.
            jQuery.each(_.keys(row), function(index, propertyName) {
                var value = row[propertyName];

                // Filter out non-primative properties, as well as properties that start with an underscore
                if ((!_.isArray(value) && (_.keys(value)).length === 0) && (!propertyName.toString().match(/^_/))) {
                    //TODO: Eventually, handle the loading of urn link values.
                    if ( (value === null) || !value.toString().match(/^urn:/)) {
                        self[propertyName] = ko.observable(value);
                        self._columns[propertyName] = true;
                    }
                }
            });
        },
        methods: {
            getColumn: function(key) {
                if ( (key in this._columns) && (ko.isObservable(this[key])) ) {
                    return this[key]();
                }
                else {
                    return undefined;
                }
            },
            setColumn: function(key, newVal) {
                if ( (key in this._columns) && (ko.isObservable(this[key])) ) {
                    var oldVal = this[key]();
                    this[key](newVal);
                    return oldVal;
                }
                else {
                    return undefined;
                }
            },
            hasBeenModified: function() {
                //TODO: consider using objects and flags to make this more efficient.
                var self = this;
                var hasBeenModified = false;
                jQuery.each(this._columns, function(key) {
                    if (self._originalData[key] !== self.getColumn(key)) {
                        hasBeenModified = true;
                    }
                });
                return hasBeenModified;
            },
            columnHasBeenModified: function(column) {
                if (self._originalData[column] !== self.getColumn(column)) {
                    return true;
                }
                else {
                    return false;
                }
            }
        },
        computeds: {
            getRawRowData: function() {
                var self = this;
                var rowData = _.clone(this._originalData);

                jQuery.each(this._columns, function(key) {
                    rowData[key] = self.getColumn(key);
                });

                return rowData;
            }
        }
    });

    SuperSQLStore.ObservableTable = Classify.newClass({
        constructor: function(config) {
            config = config || {};
            var rows = config.rows;
            var rowsArray = [];
            config = config || {};

            var rowConstructor = SuperSQLStore.ObservableRow;
            if ('rowConstructor' in config) {
                rowConstructor = config.rowConstructor;
            }

            jQuery.each(rows, function (index, value) {
                rowsArray.push(new rowConstructor({
                    row: value
                }));
            });

            this.rows = ko.observableArray(rowsArray);
        },
        methods: {
            each: function(callback) {
                ko.utils.arrayForEach(this.rows(), function(row) {
                    callback.call(row,row);
                });
            }
        },
        computeds: {
            getRawRows: function() {
                var rows = [];

                ko.utils.arrayForEach(this.rows(), function(row) {
                    rows.push(row.getRawRowData());
                });

                return rows;
            },
            // Give us a computed that tracks modifications.
            changedRowsRaw: function() {

                var changedRows = _.filter(this.rows(), function(row) {
                    if ( row.hasBeenModified() ) {
                        return true;
                    }
                    else {
                        return false;
                    }
                });

                changedRows = _.map(changedRows, function(row) {
                    return row.getRawRowData();
                });

                return changedRows;
            }
        }
    });

    SuperSQLStore.IndexedObservableTable = Classify.newClass({
        parent: SuperSQLStore.ObservableTable,
        constructor: function(config) {
            var self = this;
            if (!('key' in config)) {
                throw "You need to supply a key to index on in an IndexedObservableTable";
            }
            this.keyForIndex = config.key;

            // Build the index
            this.keyIndex = {};
            _.each(this.rows(), function(row, index) {
                self.keyIndex[ko.unwrap(row[self.keyForIndex])] = index;
            });

            // Ensure that the index is up to date.
            this.rows.subscribe(function(changes) {
                _.each(changes, function(change) {
                    //  Note: change is of the following form:
                    //     change = {
                    //         index:  3,        // index of the change.
                    //         status: 'added',  // 'added', 'deleted'
                    //         moved:  1,        // optional: the index to which this element has moved
                    //         value:  {}        // Value of the array element
                    var keyValue = ko.unwrap(change.value[self.keyForIndex]);
                    var index    = self.keyIndex;

                    if ( 'moved' in change ) {
                        index[keyValue] = change.moved;
                    }
                    else if ( status === 'added' ) {
                        index[keyValue] = change.index;
                    }
                    else if ( status === 'deleted' ) {
                        delete index[keyValue];
                    }
                });
            }, null, "arrayChange");
        },
        methods: {
            getRowByKey: function(key) {
                return this.rows()[this.keyIndex[key]];
            }
        }
    });

    SuperSQLStore.Version = '0.0.10';

    return SuperSQLStore;

});
<commit_msg>Update supersqlstore to new version.<commit_after>define(["require","exports","module","jquery","underscore","knockout","classify"],function(require,exports,module,$,_,ko,Classify){

    var SuperSQLStore = {};
    SuperSQLStore.ObservableRow = Classify.newClass({
        constructor: function(config) {
            var self = this;

            config = config || {};
            var row = config.row;
            self._originalData = row;
            self._columns = {};

            // Loop through the properties on the row to make observable versions of each column.
            jQuery.each(_.keys(row), function(index, propertyName) {
                var value = row[propertyName];

                // Filter out non-primative properties, as well as properties that start with an underscore
                if ((!_.isArray(value) && (_.keys(value)).length === 0) && (!propertyName.toString().match(/^_/))) {
                    //TODO: Eventually, handle the loading of urn link values.
                    if ( (value === null) || !value.toString().match(/^urn:/)) {
                        self[propertyName] = ko.observable(value);
                        self._columns[propertyName] = true;
                    }
                }
            });
        },
        methods: {
            getColumn: function(key) {
                if ( (key in this._columns) && (ko.isObservable(this[key])) ) {
                    return this[key]();
                }
                else {
                    return undefined;
                }
            },
            setColumn: function(key, newVal) {
                if ( (key in this._columns) && (ko.isObservable(this[key])) ) {
                    var oldVal = this[key]();
                    this[key](newVal);
                    return oldVal;
                }
                else {
                    return undefined;
                }
            },
            hasBeenModified: function() {
                //TODO: consider using objects and flags to make this more efficient.
                var self = this;
                var hasBeenModified = false;
                jQuery.each(this._columns, function(key) {
                    if (self._originalData[key] !== self.getColumn(key)) {
                        hasBeenModified = true;
                    }
                });
                return hasBeenModified;
            },
            columnHasBeenModified: function(column) {
                if (self._originalData[column] !== self.getColumn(column)) {
                    return true;
                }
                else {
                    return false;
                }
            }
        },
        computeds: {
            getRawRowData: function() {
                var self = this;
                var rowData = _.clone(this._originalData);

                jQuery.each(this._columns, function(key) {
                    rowData[key] = self.getColumn(key);
                });

                return rowData;
            }
        }
    });

    SuperSQLStore.ObservableTable = Classify.newClass({
        constructor: function(config) {
            config = config || {};

            var rowConstructor = SuperSQLStore.ObservableRow;
            if ('rowConstructor' in config) {
                rowConstructor = config.rowConstructor;
            }

            var rows = [];
            if (!_.isArray(config.rows)) {
                rows = _.map(config.rows, function(row) {
                    return new rowConstructor({
                        row: value
                    })
                });
            }
            this.rows = ko.observableArray(rows);
        },
        methods: {
            each: function(callback) {
                ko.utils.arrayForEach(this.rows(), function(row) {
                    callback.call(row,row);
                });
            }
        },
        computeds: {
            getRawRows: function() {
                var rows = [];

                ko.utils.arrayForEach(this.rows(), function(row) {
                    rows.push(row.getRawRowData());
                });

                return rows;
            },
            // Give us a computed that tracks modifications.
            changedRowsRaw: function() {

                var changedRows = _.filter(this.rows(), function(row) {
                    if ( row.hasBeenModified() ) {
                        return true;
                    }
                    else {
                        return false;
                    }
                });

                changedRows = _.map(changedRows, function(row) {
                    return row.getRawRowData();
                });

                return changedRows;
            }
        }
    });

    SuperSQLStore.IndexedObservableTable = Classify.newClass({
        parent: SuperSQLStore.ObservableTable,
        constructor: function(config) {
            var self = this;
            if (!('key' in config)) {
                throw "You need to supply a key to index on in an IndexedObservableTable";
            }
            this.keyForIndex = config.key;

            // Build the index
            this.keyIndex = {};
            _.each(this.rows(), function(row, index) {
                self.keyIndex[ko.unwrap(row[self.keyForIndex])] = index;
            });

            // Ensure that the index is up to date.
            this.rows.subscribe(function(changes) {
                _.each(changes, function(change) {
                    //  Note: change is of the following form:
                    //     change = {
                    //         index:  3,        // index of the change.
                    //         status: 'added',  // 'added', 'deleted'
                    //         moved:  1,        // optional: the index to which this element has moved
                    //         value:  {}        // Value of the array element
                    var keyValue = ko.unwrap(change.value[self.keyForIndex]);
                    var index    = self.keyIndex;

                    if ( 'moved' in change ) {
                        index[keyValue] = change.moved;
                    }
                    else if ( change.status === 'added' ) {
                        index[keyValue] = change.index;
                    }
                    else if ( change.status === 'deleted' ) {
                        delete index[keyValue];
                    }
                });
            }, null, "arrayChange");
        },
        methods: {
            getRowByKey: function(key) {
                return this.rows()[this.keyIndex[key]];
            }
        }
    });

    SuperSQLStore.Version = '0.0.11';

    return SuperSQLStore;

});
<|endoftext|>


<commit_before>(function($, d3, window, _) {
    var titles = {
        'User': 15,
        'Pirate': 5,
        'Kitten': 5,
        'Unicorn': 5,
        'Ninja': 5,
        'Whimsy': 4,
        'Matt': 1,
        'Tyler': 1,
        'Portland': 1,
        'fa-beer': 1,
        'fa-star': 1,
        'fa-trophy': 1,
        'fa-comments': 1,
        '☠': 1,
        '用户': 1,
        'Supercalifragilisticexpialidocious': 1,
        'CrazyPants': 1,
        'Canada': 1,
        'Persona' : 1,
        'Go': 1,
        'KeyboardCat': 1,
        'Odin': 1,
        'Congrats': 100,
        'Heartbeat': 10,
        'Rock': 1
    };

    var exceptions = {
        'Pirate'    :   ['Arrrvocacy','Arrrvocacy',
                        'Arrrrvocacy','Arrrrrvocacy','Arrrrrrrrrrrvocacy',
                        'Arrrrrrrrrrrrrrrrrrrrrvocacy'],
        'Canada'    :   ['Eh?vocacy'],
        'Go'        :   ['SFGiants', 'Niners', 'Warriors'],
        'Congrats'  :   ['Tyler&Emily'],
        'Heartbeat' :   [   '★★★★&#x2605',
                            '★★★★&#x2606',
                            '★★★☆&#x2606',
                            '★★☆☆&#x2606',
                            '★☆☆☆&#x2606'],
        'Rock'      :   ['Climbing', 'AndRoll']
    };

    var sum = _.reduce(titles, function (a,w) { return a+w }, 0);
    function randomNavTitle (whimsy) {
        var nav_grey = $('.navbar-brand .large-grey-text');
        var nav_red = $('.navbar-brand .large-red-text');
        if (whimsy) {
            var rand = _.random(0, sum, true);
            var rolling = 0;
            var item;
            _.forIn(titles, function (w,t) {
                rolling += w;
                if (rolling > rand) {
                    item = t;
                    return false;
                }
            });

            if(item.match('^fa\-')) {
                nav_grey.html(' ');
                nav_red.text('Advocacy');
            } else if (exceptions[item]) {
                nav_grey.text(item);
                nav_red.html(_.sample(exceptions[item]));
            } else if (item.match('^\&\#')) {
                nav_grey.html(''+item+' ');
                nav_red.text('Advocacy');
            } else {
                nav_grey.text(item);
                nav_red.text('Advocacy');
            }

            // Here is the code for Matt's wedding! Don't delete until Matt gets
            // back from his wedding.

            var today = new Date();
            var wedding_start = new Date("2015-06-25");
            var wedding_end = new Date("2015-07-13");

            if(today < wedding_end && today > wedding_start) {
                item = _.sample(['Pirate','☠', 'Congrats']);
                if (item == 'Congrats') {
                    nav_grey.text(item);
                    nav_red.text('Matt&Jess');
                }
                else if (exceptions[item]) {
                    nav_grey.text(item);
                    nav_red.html(_.sample(exceptions[item]));
                } else if (item.match('^\&\#')) {
                    nav_grey.html(''+item+' ');
                    nav_red.text('Advocacy');
                }
            }

            // end code for Matt's wedding

        } else {
            nav_grey.text('User');
            nav_red.text('Advocacy');
        }
    }

    function whimsify(whimsy) {
        if (whimsy) {
            $('.container').addClass('whimsy');
        } else {
            $('.container').removeClass('whimsy');
        }
        randomNavTitle(whimsy);
    }

    window.addEventListener("message", function (event) {
        if (event.data === 'whimsy:enabled') {
            whimsify(true);
        }
    }, false);

    window.whimsify = whimsify

}(jQuery, d3, window, _));
<commit_msg>Even better whimsy!<commit_after>(function($, d3, window, _) {
    var titles = {
        'User': 15,
        'Pirate': 5,
        'Kitten': 5,
        'Unicorn': 5,
        'Ninja': 5,
        'Whimsy': 4,
        'Matt': 1,
        'Tyler': 1,
        'Portland': 1,
        'fa-beer': 1,
        'fa-star': 1,
        'fa-trophy': 1,
        'fa-comments': 1,
        '☠': 1,
        '用户': 1,
        'Supercalifragilisticexpialidocious': 1,
        'CrazyPants': 1,
        'Canada': 1,
        'Persona' : 1,
        'Go': 1,
        'KeyboardCat': 1,
        'Odin': 1,
        'Heartbeat': 10,
        'Rock': 1
    };

    var exceptions = {
        'Pirate'    :   ['Arrrvocacy','Arrrvocacy',
                        'Arrrrvocacy','Arrrrrvocacy','Arrrrrrrrrrrvocacy',
                        'Arrrrrrrrrrrrrrrrrrrrrvocacy'],
        'Canada'    :   ['Eh?vocacy'],
        'Go'        :   ['SFGiants', 'Niners', 'Warriors'],
        'Congrats'  :   ['Tyler&Emily'],
        'Heartbeat' :   [   '★★★★&#x2605',
                            '★★★★&#x2606',
                            '★★★☆&#x2606',
                            '★★☆☆&#x2606',
                            '★☆☆☆&#x2606'],
        'Rock'      :   ['Climbing', 'AndRoll']
    };

    var sum = _.reduce(titles, function (a,w) { return a+w }, 0);
    function randomNavTitle (whimsy) {
        var nav_grey = $('.navbar-brand .large-grey-text');
        var nav_red = $('.navbar-brand .large-red-text');
        if (whimsy) {
            var rand = _.random(0, sum, true);
            var rolling = 0;
            var item;
            _.forIn(titles, function (w,t) {
                rolling += w;
                if (rolling > rand) {
                    item = t;
                    return false;
                }
            });

            if(item.match('^fa\-')) {
                nav_grey.html(' ');
                nav_red.text('Advocacy');
            } else if (exceptions[item]) {
                nav_grey.text(item);
                nav_red.html(_.sample(exceptions[item]));
            } else if (item.match('^\&\#')) {
                nav_grey.html(''+item+' ');
                nav_red.text('Advocacy');
            } else {
                nav_grey.text(item);
                nav_red.text('Advocacy');
            }

            // Here is the code for Matt's wedding! Don't delete until Matt gets
            // back from his wedding.

            var today = new Date();
            var wedding_start = new Date("2015-06-25");
            var wedding_end = new Date("2015-07-25");

            if(today < wedding_end && today > wedding_start) {
                item = _.sample(['Pirate','Congrats', 'Unicorn', 'Welcome']);
                if (item == 'Congrats') {
                    nav_grey.text(item);
                    nav_red.text('Matt&Jess');
                }
                else if (item == 'Welcome') {
                    nav_grey.text(item);
                    nav_red.text('Sawyer');
                }
                else if (exceptions[item]) {
                    nav_grey.text(item);
                    nav_red.html(_.sample(exceptions[item]));
                } else if (item.match('^\&\#')) {
                    nav_grey.html(''+item+' ');
                    nav_red.text('Advocacy');
                }
            }

            // end code for Matt's wedding

        } else {
            nav_grey.text('User');
            nav_red.text('Advocacy');
        }
    }

    function whimsify(whimsy) {
        if (whimsy) {
            $('.container').addClass('whimsy');
        } else {
            $('.container').removeClass('whimsy');
        }
        randomNavTitle(whimsy);
    }

    window.addEventListener("message", function (event) {
        if (event.data === 'whimsy:enabled') {
            whimsify(true);
        }
    }, false);

    window.whimsify = whimsify

}(jQuery, d3, window, _));
<|endoftext|>


<commit_before>angular.module('streama')
  .run(function ($window, $rootScope, $state, localStorageService, apiService, modalService,
                 userService, profileService, $translate) {

  apiService.currentUser().then(function (data) {
		userService.setCurrentUser(data);
	});

  loadAndInitProfiles();

	$rootScope.baseData = {};
	$rootScope.isCurrentState = function (stateName) {
		return ($state.current.name == stateName);
	};

	$rootScope.searchMedia = function (query) {
		return apiService.dash.searchMedia(query).then(function (data) {
			return data.data.movies.concat(data.data.shows);
		});
	};

	apiService.settings.list().then(function (data) {
		$rootScope.settings = data;
	});

	$rootScope.getSetting = function (name) {
		return _.find($rootScope.settings, {name: name}) || _.find($rootScope.settings, {settingsKey: name});
	};

	$rootScope.selectFromSearch = function (item) {
    modalService.mediaDetailModal({mediaId: item.id, mediaType: item.mediaType});
	};

	$rootScope.toggleGenreMenu = function (close) {
		if(close){
			$rootScope.genreMenuOpen = false;
		}else{
			$rootScope.genreMenuOpen = !$rootScope.genreMenuOpen;
		}
	};

  $rootScope.$on('streama.profiles.onChange', loadAndInitProfiles);

	$rootScope.changeGenre = function (genre) {
		$rootScope.toggleGenreMenu(true);
		$state.go('dash', {genreId: (genre ? genre.id : null)});
		$rootScope.$broadcast('changedGenre', genre);
	};

	$rootScope.loginUser = function () {
	  $window.location.assign('/login/login');
  };

	$rootScope.$on('$stateChangeSuccess', function (e, toState) {
		$rootScope.toggleGenreMenu(true);
		if(toState.name == "player"){
			localStorageService.set('originUrl', location.href);
		}
	});

	function loadAndInitProfiles() {
    profileService.getUserProfiles().then(
      function(data) {
        var savedProfile = profileService.getCurrentProfile();
        if(!savedProfile){
          $state.go('sub-profiles');
        }
        $rootScope.usersProfiles = data.data;
        $rootScope.currentProfile = savedProfile || $rootScope.usersProfiles[0];
        $translate.use(_.get($rootScope, 'currentProfile.profileLanguage') || _.get($rootScope, 'currentUser.language') || 'en')
      });
    $rootScope.setCurrentSubProfile = profileService.setCurrentProfile;
  }
});
<commit_msg>fix wrong usage of data-binding for $rootScope.settings<commit_after>angular.module('streama')
  .run(function ($window, $rootScope, $state, localStorageService, apiService, modalService,
                 userService, profileService, $translate) {

  apiService.currentUser().then(function (data) {
		userService.setCurrentUser(data);
	});

  loadAndInitProfiles();

	$rootScope.baseData = {};
	$rootScope.isCurrentState = function (stateName) {
		return ($state.current.name == stateName);
	};

	$rootScope.searchMedia = function (query) {
		return apiService.dash.searchMedia(query).then(function (data) {
			return data.data.movies.concat(data.data.shows);
		});
	};

	apiService.settings.list().then(function (response) {
		$rootScope.settings = response.data;
	});

	$rootScope.getSetting = function (name) {
		return _.find($rootScope.settings, {name: name}) || _.find($rootScope.settings, {settingsKey: name});
	};

	$rootScope.selectFromSearch = function (item) {
    modalService.mediaDetailModal({mediaId: item.id, mediaType: item.mediaType});
	};

	$rootScope.toggleGenreMenu = function (close) {
		if(close){
			$rootScope.genreMenuOpen = false;
		}else{
			$rootScope.genreMenuOpen = !$rootScope.genreMenuOpen;
		}
	};

  $rootScope.$on('streama.profiles.onChange', loadAndInitProfiles);

	$rootScope.changeGenre = function (genre) {
		$rootScope.toggleGenreMenu(true);
		$state.go('dash', {genreId: (genre ? genre.id : null)});
		$rootScope.$broadcast('changedGenre', genre);
	};

	$rootScope.loginUser = function () {
	  $window.location.assign('/login/login');
  };

	$rootScope.$on('$stateChangeSuccess', function (e, toState) {
		$rootScope.toggleGenreMenu(true);
		if(toState.name == "player"){
			localStorageService.set('originUrl', location.href);
		}
	});

	function loadAndInitProfiles() {
    profileService.getUserProfiles().then(
      function(data) {
        var savedProfile = profileService.getCurrentProfile();
        if(!savedProfile){
          $state.go('sub-profiles');
        }
        $rootScope.usersProfiles = data.data;
        $rootScope.currentProfile = savedProfile || $rootScope.usersProfiles[0];
        $translate.use(_.get($rootScope, 'currentProfile.profileLanguage') || _.get($rootScope, 'currentUser.language') || 'en')
      });
    $rootScope.setCurrentSubProfile = profileService.setCurrentProfile;
  }
});
<|endoftext|>


<commit_before>import React from 'react';

// utils
import debounce from 'lodash/debounce';

// constants
import { INITIAL_PAGINATION } from 'components/datasets/table/constants';

// services
import { fetchWidgets } from 'services/widget';

// Components
import Spinner from 'components/ui/Spinner';
import CustomTable from 'components/ui/customtable/CustomTable';
import SearchInput from 'components/ui/SearchInput';

// Table components
import EditAction from './actions/EditAction';
import DeleteAction from './actions/DeleteAction';

// TDs
import TitleTD from './td/TitleTD';
import PublishedTD from './td/PublishedTD';
import OwnerTD from './td/OwnerTD';

class WidgetsTable extends React.Component {
  state = {
    pagination: INITIAL_PAGINATION,
    loading: true,
    widgets: [],
    filters: { name: null }
  }

  componentDidMount() {
    const { pagination } = this.state;

    fetchWidgets({
      includes: 'widget,layer,metadata,vocabulary,user',
      'page[number]': pagination.page,
      'page[size]': pagination.limit
    }, true)
      .then(({ widgets, meta }) => {
        const {
          'total-pages': pages,
          'total-items': size
        } = meta;
        const nextPagination = {
          ...pagination,
          size,
          pages
        };

        this.setState({
          loading: false,
          pagination: nextPagination,
          widgets
        });
      })
      .catch((error) => { this.setState({ error }); });
  }

  /**
   * Event handler executed when the user search for a widget
   * @param {string} { value } Search keywords
   */
  onSearch = debounce((value) => {
    const { pagination, filters } = this.state;

    if (value.length > 0 && value.length < 3) return;

    this.setState({
      loading: true,
      filters: {
        ...filters,
        name: value
      }
    }, () => {
      const params = {
        includes: 'widget,layer,metadata,vocabulary,user',
        ...!value.length && {
          'page[number]': INITIAL_PAGINATION.page,
          'page[size]': INITIAL_PAGINATION.limit
        },
        ...value.length > 2 && {
          'page[number]': INITIAL_PAGINATION.page,
          'page[size]': INITIAL_PAGINATION.limit,
          sort: 'name',
          name: value
        }
      };
      fetchWidgets(params, true)
        .then(({ widgets, meta }) => {
          const {
            'total-pages': pages,
            'total-items': size
          } = meta;
          const nextPagination = {
            ...pagination,
            size,
            pages,
            page: INITIAL_PAGINATION.page
          };

          this.setState({
            loading: false,
            pagination: nextPagination,
            widgets
          });
        })
        .catch((error) => { this.setState({ error }); });
    });
  }, 250)

  onChangePage = (nextPage) => {
    const { pagination, filters } = this.state;

    this.setState({
      loading: true,
      pagination: {
        ...pagination,
        page: nextPage
      }
    }, () => {
      const { pagination: { page } } = this.state;

      fetchWidgets({
        includes: 'widget,layer,metadata,vocabulary,user',
        'page[number]': page,
        'page[size]': pagination.limit,
        ...filters
      })
        .then((widgets) => {
          this.setState({
            loading: false,
            widgets
          });
        })
        .catch((error) => { this.setState({ error }); });
    });
  }

  onRemoveWidget = () => {
    const { pagination } = this.state;

    this.setState({ loading: true });
    fetchWidgets({
      includes: 'widget,layer,metadata,vocabulary,user',
      'page[number]': pagination.page,
      'page[size]': pagination.limit
    }, true)
      .then(({ widgets, meta }) => {
        const {
          'total-pages': pages,
          'total-items': size
        } = meta;
        const nextPagination = {
          ...pagination,
          size,
          pages
        };

        this.setState({
          loading: false,
          pagination: nextPagination,
          widgets
        });
      })
      .catch((error) => { this.setState({ error }); });
  }

  render() {
    const {
      loading,
      pagination,
      widgets,
      error
    } = this.state;

    return (

        <Spinner className="-light" isLoading={loading} />

        {error && (

Error: {error}

        )}

        <SearchInput
          input={{ placeholder: 'Search widget' }}
          link={{
            label: 'New widget',
            route: 'admin_data_detail',
            params: {
              tab: 'widgets',
              id: 'new'
            }
          }}
          onSearch={this.onSearch}
        />

        {!error && (
          <CustomTable
            columns={[
              { label: 'Title', value: 'name', td: TitleTD },
              { label: 'Published', value: 'published', td: PublishedTD },
              { label: 'Owner', value: 'owner', td: OwnerTD }
            ]}
            actions={{
              show: true,
              list: [
                { name: 'Edit', route: 'admin_data_detail', params: { tab: 'widgets', subtab: 'edit', id: '{{id}}' }, show: true, component: EditAction },
                { name: 'Remove', route: 'admin_data_detail', params: { tab: 'widgets', subtab: 'remove', id: '{{id}}' }, component: DeleteAction, componentProps: { authorization: this.props.authorization } }
              ]
            }}
            sort={{
              field: 'name',
              value: 1
            }}
            filters={false}
            data={widgets}
            onChangePage={this.onChangePage}
            pagination={pagination}
            onRowDelete={this.onRemoveWidget}
          />
        )}

    );
  }
}

export default WidgetsTable;
<commit_msg>PR - changes<commit_after>import React from 'react';

// utils
import debounce from 'lodash/debounce';

// constants
import { INITIAL_PAGINATION } from 'components/datasets/table/constants';

// services
import { fetchWidgets } from 'services/widget';

// Components
import Spinner from 'components/ui/Spinner';
import CustomTable from 'components/ui/customtable/CustomTable';
import SearchInput from 'components/ui/SearchInput';

// Table components
import EditAction from './actions/EditAction';
import DeleteAction from './actions/DeleteAction';

// TDs
import TitleTD from './td/TitleTD';
import PublishedTD from './td/PublishedTD';
import OwnerTD from './td/OwnerTD';

class WidgetsTable extends React.Component {
  state = {
    pagination: INITIAL_PAGINATION,
    loading: true,
    widgets: [],
    filters: { name: null }
  }

  componentDidMount() {
    const { pagination } = this.state;

    fetchWidgets({
      includes: 'dataset,layer,metadata,vocabulary,user',
      'page[number]': pagination.page,
      'page[size]': pagination.limit
    }, true)
      .then(({ widgets, meta }) => {
        const {
          'total-pages': pages,
          'total-items': size
        } = meta;
        const nextPagination = {
          ...pagination,
          size,
          pages
        };

        this.setState({
          loading: false,
          pagination: nextPagination,
          widgets
        });
      })
      .catch((error) => { this.setState({ error }); });
  }

  /**
   * Event handler executed when the user search for a widget
   * @param {string} { value } Search keywords
   */
  onSearch = debounce((value) => {
    const { pagination, filters } = this.state;

    if (value.length > 0 && value.length < 3) return;

    this.setState({
      loading: true,
      filters: {
        ...filters,
        name: value
      }
    }, () => {
      const params = {
        includes: 'dataset,layer,metadata,vocabulary,user',
        ...!value.length && {
          'page[number]': INITIAL_PAGINATION.page,
          'page[size]': INITIAL_PAGINATION.limit
        },
        ...value.length > 2 && {
          'page[number]': INITIAL_PAGINATION.page,
          'page[size]': INITIAL_PAGINATION.limit,
          sort: 'name',
          name: value
        }
      };
      fetchWidgets(params, true)
        .then(({ widgets, meta }) => {
          const {
            'total-pages': pages,
            'total-items': size
          } = meta;
          const nextPagination = {
            ...pagination,
            size,
            pages,
            page: INITIAL_PAGINATION.page
          };

          this.setState({
            loading: false,
            pagination: nextPagination,
            widgets
          });
        })
        .catch((error) => { this.setState({ error }); });
    });
  }, 250)

  onChangePage = (nextPage) => {
    const { pagination, filters } = this.state;

    this.setState({
      loading: true,
      pagination: {
        ...pagination,
        page: nextPage
      }
    }, () => {
      const { pagination: { page } } = this.state;

      fetchWidgets({
        includes: 'dataset,layer,metadata,vocabulary,user',
        'page[number]': page,
        'page[size]': pagination.limit,
        ...filters
      })
        .then((widgets) => {
          this.setState({
            loading: false,
            widgets
          });
        })
        .catch((error) => { this.setState({ error }); });
    });
  }

  onRemoveWidget = () => {
    const { pagination } = this.state;

    this.setState({ loading: true });
    fetchWidgets({
      includes: 'dataset,layer,metadata,vocabulary,user',
      'page[number]': pagination.page,
      'page[size]': pagination.limit
    }, true)
      .then(({ widgets, meta }) => {
        const {
          'total-pages': pages,
          'total-items': size
        } = meta;
        const nextPagination = {
          ...pagination,
          size,
          pages
        };

        this.setState({
          loading: false,
          pagination: nextPagination,
          widgets
        });
      })
      .catch((error) => { this.setState({ error }); });
  }

  render() {
    const {
      loading,
      pagination,
      widgets,
      error
    } = this.state;

    return (

        <Spinner className="-light" isLoading={loading} />

        {error && (

Error: {error}

        )}

        <SearchInput
          input={{ placeholder: 'Search widget' }}
          link={{
            label: 'New widget',
            route: 'admin_data_detail',
            params: {
              tab: 'widgets',
              id: 'new'
            }
          }}
          onSearch={this.onSearch}
        />

        {!error && (
          <CustomTable
            columns={[
              { label: 'Title', value: 'name', td: TitleTD },
              { label: 'Published', value: 'published', td: PublishedTD },
              { label: 'Owner', value: 'owner', td: OwnerTD }
            ]}
            actions={{
              show: true,
              list: [
                { name: 'Edit', route: 'admin_data_detail', params: { tab: 'widgets', subtab: 'edit', id: '{{id}}' }, show: true, component: EditAction },
                { name: 'Remove', route: 'admin_data_detail', params: { tab: 'widgets', subtab: 'remove', id: '{{id}}' }, component: DeleteAction, componentProps: { authorization: this.props.authorization } }
              ]
            }}
            sort={{
              field: 'name',
              value: 1
            }}
            filters={false}
            data={widgets}
            onChangePage={this.onChangePage}
            pagination={pagination}
            onRowDelete={this.onRemoveWidget}
          />
        )}

    );
  }
}

export default WidgetsTable;
<|endoftext|>


<commit_before>import {BehaviorSubject, ReplaySubject, Subject} from 'rxjs'
import {finalize, first, tap} from 'rxjs/operators'
import {getLogger} from 'log'
import {getTileManagerGroup} from './tileManagerGroup'
import {requestTag, tileProviderTag} from 'tag'
import {v4 as uuid} from 'uuid'

const log = getLogger('tileManager')

// const requests = {}

export const getTileManager = tileProvider => {
    const {getTileProviderInfo, addTileProvider, removeTileProvider, submit, cancelByRequestId, setHidden, getCount} = getTileManagerGroup(tileProvider)

    const tileProviderId = uuid()
    const pending$ = new BehaviorSubject(0)

    addTileProvider(tileProviderId, tileProvider)

    const getType = () => {
        return getTileProviderInfo(tileProviderId).tileProvider.getType()
    }

    const getConcurrency = () => {
        return getTileProviderInfo(tileProviderId).tileProvider.getConcurrency()
    }

    const reportPending = () => {
        const tileProviderCount = getCount(tileProviderId)
        const overallCount = getCount()
        const pending = tileProviderCount.enqueued + tileProviderCount.executing
        pending$.next(pending)
        log.trace(`${tileProviderTag(tileProviderId)}: enqueued: ${tileProviderCount.enqueued}/${overallCount.enqueued}, executing: ${tileProviderCount.executing}/${overallCount.executing}`)
    }

    const loadTile$ = request => {
        const response$ = new ReplaySubject()
        const cancel$ = new Subject()
        const requestId = request.id
        log.debug(`Load tile ${requestTag({tileProviderId, requestId})}`)
        submit({tileProviderId, requestId, request, response$, cancel$})
        reportPending()
        return response$.pipe(
            first(),
            tap(() => reportPending()),
            finalize(() => {
                cancel$.next()
                reportPending()
            })
        )
    }

    const releaseTile = requestId => {
        log.debug(`Release tile ${requestTag({tileProviderId, requestId})}`)
        reportPending()
        cancelByRequestId(requestId)
    }

    const hide = hidden => {
        log.debug(`Set ${tileProviderTag(tileProviderId)} ${hidden ? 'hidden' : 'visible'}`)
        setHidden(tileProviderId, hidden)
    }

    const close = () => {
        log.debug('Close')
        removeTileProvider(tileProviderId)
    }

    return {
        getType,
        getConcurrency,
        loadTile$,
        releaseTile,
        hide,
        pending$,
        close
    }
}
<commit_msg>Cleanup.<commit_after>import {BehaviorSubject, ReplaySubject, Subject} from 'rxjs'
import {finalize, first} from 'rxjs/operators'
import {getLogger} from 'log'
import {getTileManagerGroup} from './tileManagerGroup'
import {requestTag, tileProviderTag} from 'tag'
import {v4 as uuid} from 'uuid'

const log = getLogger('tileManager')

export const getTileManager = tileProvider => {
    const {getTileProviderInfo, addTileProvider, removeTileProvider, submit, cancelByRequestId, setHidden, getCount} = getTileManagerGroup(tileProvider)

    const tileProviderId = uuid()
    const pending$ = new BehaviorSubject(0)

    addTileProvider(tileProviderId, tileProvider)

    const getType = () => {
        return getTileProviderInfo(tileProviderId).tileProvider.getType()
    }

    const getConcurrency = () => {
        return getTileProviderInfo(tileProviderId).tileProvider.getConcurrency()
    }

    const reportPending = () => {
        const tileProviderCount = getCount(tileProviderId)
        const overallCount = getCount()
        const pending = tileProviderCount.enqueued + tileProviderCount.executing
        pending$.next(pending)
        log.trace(`${tileProviderTag(tileProviderId)}: enqueued: ${tileProviderCount.enqueued}/${overallCount.enqueued}, executing: ${tileProviderCount.executing}/${overallCount.executing}`)
    }

    const loadTile$ = request => {
        const response$ = new ReplaySubject()
        const cancel$ = new Subject()
        const requestId = request.id
        log.debug(`Load tile ${requestTag({tileProviderId, requestId})}`)
        submit({tileProviderId, requestId, request, response$, cancel$})
        reportPending()
        return response$.pipe(
            first(),
            finalize(() => {
                cancel$.next()
                reportPending()
            })
        )
    }

    const releaseTile = requestId => {
        log.debug(`Release tile ${requestTag({tileProviderId, requestId})}`)
        reportPending()
        cancelByRequestId(requestId)
    }

    const hide = hidden => {
        log.debug(`Set ${tileProviderTag(tileProviderId)} ${hidden ? 'hidden' : 'visible'}`)
        setHidden(tileProviderId, hidden)
    }

    const close = () => {
        log.debug('Close')
        removeTileProvider(tileProviderId)
    }

    return {
        getType,
        getConcurrency,
        loadTile$,
        releaseTile,
        hide,
        pending$,
        close
    }
}
<|endoftext|>


<commit_before>(() => {
    'use strict';

    angular
        .module('dpHeader')
        .component('dpEmbedHeader', {
            controller: DpEmbedHeader,
            templateUrl: 'modules/header/components/embed-header/embed-header.html',
            controllerAs: 'vm'
        });

    DpEmbedHeader.$inject = ['store', 'embed'];

    function DpEmbedHeader (store, embed) {
        const vm = this;

        store.subscribe(update);
        update();

        function update () {
            const ghostState = angular.copy(store.getState());

            // create link without embed AND embed preview in href
            ghostState.atlas.isEmbedPreview = false;
            ghostState.atlas.isEmbed = false;
            vm.link = embed.getLink(ghostState);

            // create iframe with embed but not embed preview in the html
            ghostState.atlas.isEmbedPreview = false;
            ghostState.atlas.isEmbed = true;
            vm.html = embed.getHtml(ghostState);
        }
    }
})();
<commit_msg>fixed incorrect link in embed form tg-4019<commit_after>(() => {
    'use strict';

    angular
        .module('dpHeader')
        .component('dpEmbedHeader', {
            controller: DpEmbedHeader,
            templateUrl: 'modules/header/components/embed-header/embed-header.html',
            controllerAs: 'vm'
        });

    DpEmbedHeader.$inject = ['store', 'embed'];

    function DpEmbedHeader (store, embed) {
        const vm = this;

        store.subscribe(update);
        update();

        function update () {
            const ghostState = angular.copy(store.getState());

            // create link and iframe without embed AND embed preview in href
            ghostState.atlas.isEmbedPreview = false;
            ghostState.atlas.isEmbed = true;
            vm.link = embed.getLink(ghostState);
            vm.html = embed.getHtml(ghostState);
        }
    }
})();
<|endoftext|>