<commit_before>// Copyright 2014 Cognitect. All Rights Reserved.
//
// 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.

goog.provide("com.cognitect.transit.impl.decoder");
goog.require("com.cognitect.transit.util");
goog.require("com.cognitect.transit.delimiters");
goog.require("com.cognitect.transit.caching");
goog.require("com.cognitect.transit.types");

goog.scope(function() {

var decoder = com.cognitect.transit.impl.decoder,
    util    = com.cognitect.transit.util,
    d       = com.cognitect.transit.delimiters,
    caching = com.cognitect.transit.caching,
    types   = com.cognitect.transit.types;

// =============================================================================
// Decoder

/**
 * @constructor
 */
decoder.Tag = function(s) {
    this.str = s;
};

decoder.tag = function(s) {
    return new decoder.Tag(s);
};

decoder.isTag = function(x) {
    return x && (x instanceof decoder.Tag);
};

decoder.isGroundHandler = function(handler) {
    switch(handler) {
        case "_":
        case "s":
        case "?":
        case "i":
        case "d":
        case "b":
        case "'":
        case "array":
        case "map":
        return true;
    }
    return false;
};

/**
 * A transit decoder
 * @constructor
 */
decoder.Decoder = function(options) {
    this.options = options || {};
    this.handlers = {};
    for(var h in this.defaults.handlers) {
        this.handlers[h] = this.defaults.handlers[h];
    }
    for(var h in this.options["handlers"]) {
        if(decoder.isGroundHandler(h)) {
            throw new Error("Cannot override handler for ground type \""+h+"\"");
        }
        this.handlers[h] = this.options["handlers"][h];
    }
    this.preferStrings = this.options["preferStrings"] != null ? this.options["preferStrings"] : this.defaults.preferStrings;
    this.preferBuffers = this.options["preferBuffers"] != null ? this.options["preferBuffers"] : this.defaults.preferBuffers;
    this.defaultHandler = this.options["defaultHandler"] || this.defaults.defaultHandler;
    /* NOT PUBLIC */
    this.mapBuilder = this.options["mapBuilder"];
    this.arrayBuilder = this.options["arrayBuilder"];
};

decoder.Decoder.prototype.defaults = {
    handlers: {
        "_": function(v, d) { return types.nullValue(); },
        "?": function(v, d) { return types.boolValue(v); },
        "b": function(v, d) { return types.binary(v, d); },
        "i": function(v, d) { return types.intValue(v); },
        "n": function(v, d) { return types.bigInteger(v); },
        "d": function(v, d) { return types.floatValue(v); },
        "f": function(v, d) { return types.bigDecimalValue(v); },
        "c": function(v, d) { return types.charValue(v); },
        ":": function(v, d) { return types.keyword(v); },
        "$": function(v, d) { return types.symbol(v); },
        "r": function(v, d) { return types.uri(v); },
        "z": function(v, d) { return types.specialDouble(v); },

        // tagged
        "'": function(v, d) { return v; },
        "m": function(v, d) { return types.date(v); },
        "t": function(v, d) { return types.verboseDate(v); },
        "u": function(v, d) { return types.uuid(v); },
        "set": function(v, d) { return types.set(v); },
        "list": function(v, d) { return types.list(v); },
        "link": function(v, d) { return types.link(v); },
        "cmap": function(v, d) { return types.map(v, false); }
    },
    defaultHandler: function(c, val) {
        return types.taggedValue(c, val);
    },
    preferStrings: true,
    preferBuffers: true
};

decoder.Decoder.prototype.decode = function(node, cache, asMapKey, tagValue) {
    if(node == null) return null;

    var t = typeof node;

    switch(t) {
    case "string":
        return this.decodeString(node, cache, asMapKey, tagValue);
        break;
    case "object":
        if(util.isArray(node)) {
            if(node[0] === "^ ") {
                return this.decodeArrayHash(node, cache, asMapKey, tagValue);
            } else {
                return this.decodeArray(node, cache, asMapKey, tagValue);
            }
        } else {
            return this.decodeHash(node, cache, asMapKey, tagValue);
        }
        break;
    }

    return node;
};
decoder.Decoder.prototype["decode"] = decoder.Decoder.prototype.decode;

decoder.Decoder.prototype.decodeString = function(string, cache, asMapKey, tagValue) {
    if(caching.isCacheable(string, asMapKey)) {
        var val = this.parseString(string, cache, false);
        if(cache) {
            cache.write(val, asMapKey);
        }
        return val;
    } else if(caching.isCacheCode(string)) {
        return cache.read(string, asMapKey);
    } else {
        return this.parseString(string, cache, asMapKey);
    }
};

decoder.Decoder.prototype.decodeHash = function(hash, cache, asMapKey, tagValue) {
    var ks  = util.objectKeys(hash),
        key = ks[0],
        tag = ks.length == 1 ? this.decode(key, cache, false, false) : null;

    if(decoder.isTag(tag)) {
        var val     = hash[key],
            handler = this.handlers[tag.str];
        if(handler != null) {
            return handler(this.decode(val, cache, false, true), this);
        } else {
            return types.taggedValue(tag.str, this.decode(val, cache, false, false));
        }
    } else if(this.mapBuilder) {
        if((ks.length < (types.SMALL_ARRAY_MAP_THRESHOLD*2)) && this.mapBuilder.fromArray) {
            var nodep = [];
            for(var i = 0; i < ks.length; i++) {
                var strKey = ks[i];
                nodep.push(this.decode(strKey, cache, true, false));
                nodep.push(this.decode(hash[strKey], cache, false, false));
            }
            return this.mapBuilder.fromArray(nodep, hash);
        } else {
            var ret = this.mapBuilder.init(hash);
            for(var i = 0; i < ks.length; i++) {
                var strKey = ks[i];
                ret = this.mapBuilder.add(ret,
                                          this.decode(strKey, cache, true, false),
                                          this.decode(hash[strKey], cache, false, false),
                                          hash);
            }
            return this.mapBuilder.finalize(ret, hash);
        }
    } else {
        var nodep = [];

        for(var i = 0; i < ks.length; i++) {
            var strKey = ks[i];
            nodep.push(this.decode(strKey, cache, true, false));
            nodep.push(this.decode(hash[strKey], cache, false, false));
        }

        return types.map(nodep, false);
    }
};

decoder.Decoder.prototype.decodeArrayHash = function(node, cache, asMapKey, tagValue) {
    if(this.mapBuilder) {
        if((node.length < ((types.SMALL_ARRAY_MAP_THRESHOLD*2)+1)) && this.mapBuilder.fromArray) {
            var nodep = [];
            for(var i = 1; i < node.length; i+=2) {
                nodep.push(this.decode(node[i], cache, true, false));
                nodep.push(this.decode(node[i+1], cache, false, false));
            }
            return this.mapBuilder.fromArray(nodep, node);
        } else {
            var ret = this.mapBuilder.init(node);
            for(var i = 1; i < node.length; i+=2) {
                ret = this.mapBuilder.add(ret,
                                          this.decode(node[i], cache, true, false),
                                          this.decode(node[i+1], cache, false, false),
                                          node)
            }
            return this.mapBuilder.finalize(ret, node);
        }
    } else {
        var nodep = [];

        // collect keys
        for(var i = 1; i < node.length; i +=2) {
            nodep.push(this.decode(node[i], cache, true, false));
            nodep.push(this.decode(node[i+1], cache, false, false));
        }

        return types.map(nodep, false);
    }
};

decoder.Decoder.prototype.decodeArray = function(node, cache, asMapKey, tagValue) {
    if(tagValue) {
        var ret = [];
        for(var i = 0; i < node.length; i++) {
            ret.push(this.decode(node[i], cache, asMapKey, false));
        }
        return ret;
    } else {
        var cacheIdx = cache && cache.idx;
        // tagged value as 2-array case
        if((node.length === 2) &&
           (typeof node[0] === "string")) {
            var tag = this.decode(node[0], cache, false, false);
            if(decoder.isTag(tag)) {
                var val     = node[1],
                    handler = this.handlers[tag.str];
                if(handler != null) {
                    var ret = handler(this.decode(val, cache, asMapKey, true), this);
                    return ret;
                } else {
                    return types.taggedValue(tag.str, this.decode(val, cache, asMapKey, false))
                }
            }
        }

        // rewind cache
        if(cache && (cacheIdx != cache.idx)) {
            cache.idx = cacheIdx;
        }

        if(this.arrayBuilder) {
            // NOTE: hard coded for ClojureScript for now - David
            if(node.length <= 32 && this.arrayBuilder.fromArray) {
                var arr = [];
                for(var i = 0; i < node.length; i++) {
                    arr.push(this.decode(node[i], cache, asMapKey, false));
                }
                return this.arrayBuilder.fromArray(arr, node);
            } else {
                var ret = this.arrayBuilder.init(node);
                for(var i = 0; i < node.length; i++) {
                    ret = this.arrayBuilder.add(ret, this.decode(node[i], cache, asMapKey, false), node);
                }
                return this.arrayBuilder.finalize(ret, node);
            }
        } else {
            var ret = [];
            for(var i = 0; i < node.length; i++) {
                ret.push(this.decode(node[i], cache, asMapKey, false));
            }
            return ret;
        }
    }
};

decoder.Decoder.prototype.parseString = function(string, cache, asMapKey) {
    if(string.charAt(0) === d.ESC) {
        var c = string.charAt(1);
        if(c === d.ESC || c === d.SUB || c === d.RES) {
            return string.substring(1);
        } else if (c === d.TAG) {
            return decoder.tag(string.substring(2));
        } else {
            var handler = this.handlers[c];
            if(handler == null) {
                return this.defaultHandler(c, string.substring(2));
            } else {
                return handler(string.substring(2), this);
            }
        }
    } else {
        return string;
    }
};

decoder.decoder = function(options) {
    return new decoder.Decoder(options);
};

});
<commit_msg>reformat decoder<commit_after>// Copyright 2014 Cognitect. All Rights Reserved.
//
// 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.

goog.provide("com.cognitect.transit.impl.decoder");
goog.require("com.cognitect.transit.util");
goog.require("com.cognitect.transit.delimiters");
goog.require("com.cognitect.transit.caching");
goog.require("com.cognitect.transit.types");

goog.scope(function () {

    var decoder = com.cognitect.transit.impl.decoder,
        util    = com.cognitect.transit.util,
        d       = com.cognitect.transit.delimiters,
        caching = com.cognitect.transit.caching,
        types   = com.cognitect.transit.types;

    // =========================================================================
    // Decoder

    /**
     * @constructor
     */
    decoder.Tag = function (s) {
        this.str = s;
    };

    decoder.tag = function (s) {
        return new decoder.Tag(s);
    };

    decoder.isTag = function (x) {
        return x && (x instanceof decoder.Tag);
    };

    decoder.isGroundHandler = function (handler) {
        switch (handler) {
            case "_":
            case "s":
            case "?":
            case "i":
            case "d":
            case "b":
            case "'":
            case "array":
            case "map":
                return true;
        }
        return false;
    };

    /**
     * A transit decoder
     * @constructor
     */
    decoder.Decoder = function (options) {
        this.options = options || {};
        this.handlers = {};
        for (var h in this.defaults.handlers) {
            this.handlers[h] = this.defaults.handlers[h];
        }
        for (var h in this.options["handlers"]) {
            if (decoder.isGroundHandler(h)) {
                throw new Error("Cannot override handler for ground type \"" + h + "\"");
            }
            this.handlers[h] = this.options["handlers"][h];
        }
        this.preferStrings = this.options["preferStrings"] != null ? this.options["preferStrings"] : this.defaults.preferStrings;
        this.preferBuffers = this.options["preferBuffers"] != null ? this.options["preferBuffers"] : this.defaults.preferBuffers;
        this.defaultHandler = this.options["defaultHandler"] || this.defaults.defaultHandler;
        /* NOT PUBLIC */
        this.mapBuilder = this.options["mapBuilder"];
        this.arrayBuilder = this.options["arrayBuilder"];
    };

    decoder.Decoder.prototype.defaults = {
        handlers: {
            "_": function (v, d) {
                return types.nullValue();
            },
            "?": function (v, d) {
                return types.boolValue(v);
            },
            "b": function (v, d) {
                return types.binary(v, d);
            },
            "i": function (v, d) {
                return types.intValue(v);
            },
            "n": function (v, d) {
                return types.bigInteger(v);
            },
            "d": function (v, d) {
                return types.floatValue(v);
            },
            "f": function (v, d) {
                return types.bigDecimalValue(v);
            },
            "c": function (v, d) {
                return types.charValue(v);
            },
            ":": function (v, d) {
                return types.keyword(v);
            },
            "$": function (v, d) {
                return types.symbol(v);
            },
            "r": function (v, d) {
                return types.uri(v);
            },
            "z": function (v, d) {
                return types.specialDouble(v);
            },

            // tagged
            "'": function (v, d) {
                return v;
            },
            "m": function (v, d) {
                return types.date(v);
            },
            "t": function (v, d) {
                return types.verboseDate(v);
            },
            "u": function (v, d) {
                return types.uuid(v);
            },
            "set": function (v, d) {
                return types.set(v);
            },
            "list": function (v, d) {
                return types.list(v);
            },
            "link": function (v, d) {
                return types.link(v);
            },
            "cmap": function (v, d) {
                return types.map(v, false);
            }
        },
        defaultHandler: function (c, val) {
            return types.taggedValue(c, val);
        },
        preferStrings: true,
        preferBuffers: true
    };

    decoder.Decoder.prototype.decode = function (node, cache, asMapKey, tagValue) {
        if (node == null) return null;

        var t = typeof node;

        switch (t) {
            case "string":
                return this.decodeString(node, cache, asMapKey, tagValue);
                break;
            case "object":
                if (util.isArray(node)) {
                    if (node[0] === "^ ") {
                        return this.decodeArrayHash(node, cache, asMapKey, tagValue);
                    } else {
                        return this.decodeArray(node, cache, asMapKey, tagValue);
                    }
                } else {
                    return this.decodeHash(node, cache, asMapKey, tagValue);
                }
                break;
        }

        return node;
    };
    decoder.Decoder.prototype["decode"] = decoder.Decoder.prototype.decode;

    decoder.Decoder.prototype.decodeString = function (string, cache, asMapKey, tagValue) {
        if (caching.isCacheable(string, asMapKey)) {
            var val = this.parseString(string, cache, false);
            if (cache) {
                cache.write(val, asMapKey);
            }
            return val;
        } else if (caching.isCacheCode(string)) {
            return cache.read(string, asMapKey);
        } else {
            return this.parseString(string, cache, asMapKey);
        }
    };

    decoder.Decoder.prototype.decodeHash = function (hash, cache, asMapKey, tagValue) {
        var ks = util.objectKeys(hash),
            key = ks[0],
            tag = ks.length == 1 ? this.decode(key, cache, false, false) : null;

        if (decoder.isTag(tag)) {
            var val = hash[key],
                handler = this.handlers[tag.str];
            if (handler != null) {
                return handler(this.decode(val, cache, false, true), this);
            } else {
                return types.taggedValue(tag.str, this.decode(val, cache, false, false));
            }
        } else if (this.mapBuilder) {
            if ((ks.length < (types.SMALL_ARRAY_MAP_THRESHOLD * 2)) && this.mapBuilder.fromArray) {
                var nodep = [];
                for (var i = 0; i < ks.length; i++) {
                    var strKey = ks[i];
                    nodep.push(this.decode(strKey, cache, true, false));
                    nodep.push(this.decode(hash[strKey], cache, false, false));
                }
                return this.mapBuilder.fromArray(nodep, hash);
            } else {
                var ret = this.mapBuilder.init(hash);
                for (var i = 0; i < ks.length; i++) {
                    var strKey = ks[i];
                    ret = this.mapBuilder.add(ret,
                        this.decode(strKey, cache, true, false),
                        this.decode(hash[strKey], cache, false, false),
                        hash);
                }
                return this.mapBuilder.finalize(ret, hash);
            }
        } else {
            var nodep = [];

            for (var i = 0; i < ks.length; i++) {
                var strKey = ks[i];
                nodep.push(this.decode(strKey, cache, true, false));
                nodep.push(this.decode(hash[strKey], cache, false, false));
            }

            return types.map(nodep, false);
        }
    };

    decoder.Decoder.prototype.decodeArrayHash = function (node, cache, asMapKey, tagValue) {
        if (this.mapBuilder) {
            if ((node.length < ((types.SMALL_ARRAY_MAP_THRESHOLD * 2) + 1)) && this.mapBuilder.fromArray) {
                var nodep = [];
                for (var i = 1; i < node.length; i += 2) {
                    nodep.push(this.decode(node[i], cache, true, false));
                    nodep.push(this.decode(node[i + 1], cache, false, false));
                }
                return this.mapBuilder.fromArray(nodep, node);
            } else {
                var ret = this.mapBuilder.init(node);
                for (var i = 1; i < node.length; i += 2) {
                    ret = this.mapBuilder.add(ret,
                        this.decode(node[i], cache, true, false),
                        this.decode(node[i + 1], cache, false, false),
                        node)
                }
                return this.mapBuilder.finalize(ret, node);
            }
        } else {
            var nodep = [];

            // collect keys
            for (var i = 1; i < node.length; i += 2) {
                nodep.push(this.decode(node[i], cache, true, false));
                nodep.push(this.decode(node[i + 1], cache, false, false));
            }

            return types.map(nodep, false);
        }
    };

    decoder.Decoder.prototype.decodeArray = function (node, cache, asMapKey, tagValue) {
        if (tagValue) {
            var ret = [];
            for (var i = 0; i < node.length; i++) {
                ret.push(this.decode(node[i], cache, asMapKey, false));
            }
            return ret;
        } else {
            var cacheIdx = cache && cache.idx;
            // tagged value as 2-array case
            if ((node.length === 2) &&
                (typeof node[0] === "string")) {
                var tag = this.decode(node[0], cache, false, false);
                if (decoder.isTag(tag)) {
                    var val = node[1],
                        handler = this.handlers[tag.str];
                    if (handler != null) {
                        var ret = handler(this.decode(val, cache, asMapKey, true), this);
                        return ret;
                    } else {
                        return types.taggedValue(tag.str, this.decode(val, cache, asMapKey, false))
                    }
                }
            }

            // rewind cache
            if (cache && (cacheIdx != cache.idx)) {
                cache.idx = cacheIdx;
            }

            if (this.arrayBuilder) {
                // NOTE: hard coded for ClojureScript for now - David
                if (node.length <= 32 && this.arrayBuilder.fromArray) {
                    var arr = [];
                    for (var i = 0; i < node.length; i++) {
                        arr.push(this.decode(node[i], cache, asMapKey, false));
                    }
                    return this.arrayBuilder.fromArray(arr, node);
                } else {
                    var ret = this.arrayBuilder.init(node);
                    for (var i = 0; i < node.length; i++) {
                        ret = this.arrayBuilder.add(ret, this.decode(node[i], cache, asMapKey, false), node);
                    }
                    return this.arrayBuilder.finalize(ret, node);
                }
            } else {
                var ret = [];
                for (var i = 0; i < node.length; i++) {
                    ret.push(this.decode(node[i], cache, asMapKey, false));
                }
                return ret;
            }
        }
    };

    decoder.Decoder.prototype.parseString = function (string, cache, asMapKey) {
        if (string.charAt(0) === d.ESC) {
            var c = string.charAt(1);
            if (c === d.ESC || c === d.SUB || c === d.RES) {
                return string.substring(1);
            } else if (c === d.TAG) {
                return decoder.tag(string.substring(2));
            } else {
                var handler = this.handlers[c];
                if (handler == null) {
                    return this.defaultHandler(c, string.substring(2));
                } else {
                    return handler(string.substring(2), this);
                }
            }
        } else {
            return string;
        }
    };

    decoder.decoder = function (options) {
        return new decoder.Decoder(options);
    };

});
<|endoftext|>


<commit_before><commit_msg>Add jasmine tests for finding and opening anchors within sections<commit_after><|endoftext|>


<commit_before>module.exports = {
    className: 'phone',
    template: require('./index.html'),
    data: {
        name: 'Phone',
        icon: 'images/blocks_phone.png',
        attributes: {
            number: {
                label: 'Phone #',
                type: 'string',
                value: '+18005555555'
            },
            innerHTML: {
                label: 'Label',
                type: 'string',
                value: 'Place call'
            },
            color: {
                label: 'Button Color',
                type: 'color',
                value: '#64A8EE',
                skipAutoRender: true
            }
        }
    },
    created: function () {
        var self = this;

        // Disable if editing mode
        self.$data.onClick = function (e) {
            e.preventDefault();
            window.location = 'tel:' + self.$data.attributes.number.value;
        };
    }
};
<commit_msg>moves the onClick handler to the Vue object prototype, so that it doesn't get lost across clone() operations<commit_after>module.exports = {
    className: 'phone',
    template: require('./index.html'),
    data: {
        name: 'Phone',
        icon: 'images/blocks_phone.png',
        attributes: {
            number: {
                label: 'Phone #',
                type: 'string',
                value: '+18005555555'
            },
            innerHTML: {
                label: 'Label',
                type: 'string',
                value: 'Place call'
            },
            color: {
                label: 'Button Color',
                type: 'color',
                value: '#64A8EE',
                skipAutoRender: true
            }
        }
    },
    methods: {
        onClick: function (e) {
            e.preventDefault();
            window.location = 'tel:' + this.$data.attributes.number.value;
        }
    }
};
<|endoftext|>


<commit_before>/* global define */
(function() {
    'use strict';
    define(['lodash', 'helpers/modal-helpers'], function(_) {

        var clusterPollIntervalMs = 1000;
        var FirstTimeController = function($q, $log, $timeout, $location, $scope, KeyService, ClusterService, $modal) {
            var promises = [KeyService.getList()];
            $scope.addDisabled = true;
            $scope.debug = false;
            $q.all(promises).then(function(results) {

                $scope.up = true;
                if (ClusterService.clusterId !== null) {
                    $location.path('/');
                    return;
                }

                (function(keys) {
                    $scope.hosts = _.reduce(keys, function(result, key) {
                        if (key.status === 'pre') {
                            result.pre.push(key);
                        } else if (key.status === 'accepted') {
                            result.accepted.push(key);
                        } else {
                            result.blocked.push(key);
                        }
                        return result;
                    }, {
                        accepted: [],
                        pre: [],
                        blocked: []
                    });
                    $scope.addDisabled = false;
                    $scope.acceptAll = function() {
                        var ids = _.map($scope.hosts.pre, function(key) {
                            return key.id;
                        });
                        $log.debug(ids);
                        $scope.addDisabled = true;
                        var modal = $modal({
                            'title': ' Accept Request Sent',
                            'template': 'views/new-install-modal.html',
                            'content': '
 Waiting for First Cluster to Join
',
                            'backdrop': 'static',
                            'html': true
                        });
                        modal.$scope.closeDisabled = true;
                        modal.$scope.$hide = _.wrap(modal.$scope.$hide, function($hide) {
                            $hide();
                            ClusterService.initialize().then(function() {
                                $location.path('/');
                            });
                        });

                        function checkClusterUp() {
                            ClusterService.getList().then(function(clusters) {
                                if (clusters.length) {
                                    modal.$scope.closeDisabled = false;
                                    modal.$scope.content = 'Cluster Initialized.';
                                    return;
                                }
                                $timeout(checkClusterUp, clusterPollIntervalMs);
                            });
                        }
                        KeyService.accept(ids).then(function(resp) {
                            $log.debug(resp);
                            if (resp.status === 204) {
                                $timeout(checkClusterUp, clusterPollIntervalMs);
                            }
                            $scope.addDisabled = false;

                        }, function(resp) {
                            modal.$scope.content = ' Error ' + resp.status + '. Please try reloading the page and logging in again.

Raw Response

' + resp.data + '

';
                            $scope.addDisabled = false;
                        });
                        return;
                    };
                })(results[0]);

            });
        };
        return ['$q', '$log', '$timeout', '$location', '$scope', 'KeyService', 'ClusterService', '$modal', FirstTimeController];
    });
})();
<commit_msg>Docco first.js<commit_after>/* global define */
(function() {
    'use strict';
    define(['lodash', 'helpers/modal-helpers'], function(_) {

        var clusterPollIntervalMs = 1000;
        // **FirstTimeController** should only be invoked on a fresh Calamari install where there are
        // no currently accepted cluster hosts. Calamari root.js detects this condition by requesting a list of
        // the current clusters and if there are none, redirects to this controller.
        //
        // We handle the initial bootstrapping of Calamari by offering a visual way for the end-user
        // to accept all the registered hosts. This makes the assumption that they are all members of
        // the same cluster. Something which may not necessarily be true if this is a multi-cluster
        // installation.
        //
        var FirstTimeController = function($q, $log, $timeout, $location, $scope, KeyService, ClusterService, $modal) {
            var promises = [KeyService.getList()];
            // Start the view out with adds disabled via ng-disabled
            $scope.addDisabled = true;
            $scope.debug = false;
            $q.all(promises).then(function(results) {

                // **up** is used to control whether the view is rendered yet via ng-show.
                $scope.up = true;
                if (ClusterService.clusterId !== null) {
                    // The user has navigated to this URL erroneously, send them back to
                    // the default cluster page.
                    $location.path('/');
                    return;
                }

                // Process the returned list of server minion key states.
                (function(keys) {
                    // Bucket the keys in **pre**, **accepted** and **blocked** sets.
                    // We really only care about accepted ones.
                    $scope.hosts = _.reduce(keys, function(result, key) {
                        if (key.status === 'pre') {
                            result.pre.push(key);
                        } else if (key.status === 'accepted') {
                            result.accepted.push(key);
                        } else {
                            result.blocked.push(key);
                        }
                        return result;
                    }, {
                        accepted: [],
                        pre: [],
                        blocked: []
                    });
                    // Re-enable add button via ng-disabled
                    $scope.addDisabled = false;

                    // Install the click event handler.
                    $scope.acceptAll = function() {
                        // get the ids of all pre-accepted hosts
                        var ids = _.map($scope.hosts.pre, function(key) {
                            return key.id;
                        });
                        $log.debug(ids);
                        // Disable add button via ng-disabled because we are now done
                        // unless there is an error.
                        $scope.addDisabled = true;

                        // Create a modal we will show while we are waiting for Calamari to accept
                        // the servers.
                        var modal = $modal({
                            'title': ' Accept Request Sent',
                            'template': 'views/new-install-modal.html',
                            'content': '
 Waiting for First Cluster to Join
',
                            'backdrop': 'static',
                            'html': true
                        });
                        // Disable closing of the modal while we are in this state.
                        modal.$scope.closeDisabled = true;

                        // Decorate the $hide method from angular-strap so we can
                        // add some behavior to it.
                        modal.$scope.$hide = _.wrap(modal.$scope.$hide, function($hide) {
                            $hide();
                            ClusterService.initialize().then(function() {
                                $location.path('/');
                            });
                        });

                        // Helper to poll Calamari until the cluster API responds
                        // with an actual cluster data structure.
                        function checkClusterUp() {
                            ClusterService.getList().then(function(clusters) {
                                if (clusters.length) {
                                    // A Cluster is now available. Release the modal
                                    // lockdown and tell the user.
                                    modal.$scope.closeDisabled = false;
                                    modal.$scope.content = 'Cluster Initialized.';
                                    return;
                                }
                                // Schedule poll again - Calamari is still working.
                                $timeout(checkClusterUp, clusterPollIntervalMs);
                            });
                        }

                        // Send the Accept command to Calamari and start polling.
                        KeyService.accept(ids).then(function(resp) {
                            $log.debug(resp);
                            if (resp.status === 204) {
                                // Start polling loop
                                $timeout(checkClusterUp, clusterPollIntervalMs);
                            }
                            $scope.addDisabled = false;

                        }, function(resp) {
                            // Uh-oh, an error occurred. Tell the user.
                            modal.$scope.content = ' Error ' + resp.status + '. Please try reloading the page and logging in again.

Raw Response

' + resp.data + '

';
                            $scope.addDisabled = false;
                        });
                        return;
                    };
                })(results[0]);

            });
        };
        return ['$q', '$log', '$timeout', '$location', '$scope', 'KeyService', 'ClusterService', '$modal', FirstTimeController];
    });
})();
<|endoftext|>


<commit_before>import BaseLfo from '../core/base-lfo';

export default class Framer extends BaseLfo {
  constructor(options) {
    const defaults = {
      frameSize: 512,
      centeredTimeTag: false
    };

    super(options, defaults);

    this.frameIndex = 0;
  }

  configureStream() {
    // defaults to `hopSize` === `frameSize`
    if (!this.params.hopSize) {
      this.params.hopSize = this.params.frameSize;
    }

    this.streamParams.frameSize = this.params.frameSize;
    this.streamParams.frameRate = this.streamParams.sourceSampleRate / this.params.hopSize;
  }

  // @NOTE must be tested
  reset() {
    this.frameIndex = 0;
    super.reset();
  }

  finalize() {
    // @NOTE what about time ?
    // fill the ongoing buffer with 0
    for (let i = this.frameIndex, l = this.outFrame.length; i < l; i++) {
      this.outFrame[i] = 0;
    }
    // output it
    this.output();

    super.finalize();
  }

  process(time, block, metaData) {
    const sampleRate = this.streamParams.sourceSampleRate;
    const samplePeriod = 1 / sampleRate;

    const frameIndex = this.frameIndex;
    const frameSize = this.streamParams.frameSize;
    const blockSize = block.length;
    const blockIndex = 0;
    const hopSize = this.params.hopSize;

    const outFrame = this.outFrame;

    while (blockIndex < blockSize) {
      const numSkip = 0;

      // skip block samples for negative frameIndex
      if (frameIndex < 0) {
        numSkip = -frameIndex;
      }

      if (numSkip < blockSize) {
        blockIndex += numSkip; // skip block segment
        // can copy all the rest of the incoming block
        const numCopy = blockSize - blockIndex;
        // connot copy more than what fits into the frame
        const maxCopy = frameSize - frameIndex;

        if (numCopy >= maxCopy) {
          numCopy = maxCopy;
        }

        // copy block segment into frame
        const copy = block.subarray(blockIndex, blockIndex + numCopy);
        // console.log(blockIndex, frameIndex, numCopy);
        outFrame.set(copy, frameIndex);

        // advance block and frame index
        blockIndex += numCopy;
        frameIndex += numCopy;

        // send frame when completed
        if (frameIndex === frameSize) {
          // define time tag for the outFrame according to configuration
          if (this.params.centeredTimeTag) {
            this.time = time + (blockIndex - frameSize / 2) * samplePeriod;
          } else {
            this.time = time + (blockIndex - frameSize) * samplePeriod;
          }

          // forward metaData ?
          this.metaData = metaData;

          // forward to next nodes
          this.output();

          // shift frame left
          if (hopSize < frameSize) {
            outFrame.set(outFrame.subarray(hopSize, frameSize), 0);
          }

          frameIndex -= hopSize; // hop forward
        }
      } else {
        // skip entire block
        const blockRest = blockSize - blockIndex;
        frameIndex += blockRest;
        blockIndex += blockRest;
      }
    }

    this.frameIndex = frameIndex;
  }
}
<commit_msg>minor fixes<commit_after>import BaseLfo from '../core/base-lfo';

export default class Framer extends BaseLfo {
  constructor(options) {
    super(options, {
      frameSize: 512,
      centeredTimeTag: false
    });

    this.frameIndex = 0;
  }

  configureStream() {
    // defaults to `hopSize` === `frameSize`
    if (!this.params.hopSize) {
      this.params.hopSize = this.params.frameSize;
    }

    this.streamParams.frameSize = this.params.frameSize;
    this.streamParams.frameRate = this.streamParams.sourceSampleRate / this.params.hopSize;
  }

  // @NOTE must be tested
  reset() {
    this.frameIndex = 0;
    super.reset();
  }

  finalize() {
    // @NOTE what about time ?
    // fill the ongoing buffer with 0
    for (let i = this.frameIndex, l = this.outFrame.length; i < l; i++) {
      this.outFrame[i] = 0;
    }
    // output it
    this.output();

    super.finalize();
  }

  process(time, block, metaData) {
    const outFrame = this.outFrame;
    const sampleRate = this.streamParams.sourceSampleRate;
    const samplePeriod = 1 / sampleRate;
    const frameSize = this.streamParams.frameSize;
    const blockSize = block.length;
    const hopSize = this.params.hopSize;
    let frameIndex = this.frameIndex;
    let blockIndex = 0;

    while (blockIndex < blockSize) {
      let numSkip = 0;

      // skip block samples for negative frameIndex
      if (frameIndex < 0) {
        numSkip = -frameIndex;
      }

      if (numSkip < blockSize) {
        blockIndex += numSkip; // skip block segment

        // can copy all the rest of the incoming block
        let numCopy = blockSize - blockIndex;

        // connot copy more than what fits into the frame
        const maxCopy = frameSize - frameIndex;

        if (numCopy >= maxCopy) {
          numCopy = maxCopy;
        }

        // copy block segment into frame
        const copy = block.subarray(blockIndex, blockIndex + numCopy);

        // console.log(blockIndex, frameIndex, numCopy);
        outFrame.set(copy, frameIndex);

        // advance block and frame index
        blockIndex += numCopy;
        frameIndex += numCopy;

        // send frame when completed
        if (frameIndex === frameSize) {
          // define time tag for the outFrame according to configuration
          if (this.params.centeredTimeTag) {
            this.time = time + (blockIndex - frameSize / 2) * samplePeriod;
          } else {
            this.time = time + (blockIndex - frameSize) * samplePeriod;
          }

          // forward metaData ?
          this.metaData = metaData;

          // forward to next nodes
          this.output();

          // shift frame left
          if (hopSize < frameSize) {
            outFrame.set(outFrame.subarray(hopSize, frameSize), 0);
          }

          frameIndex -= hopSize; // hop forward
        }
      } else {
        // skip entire block
        const blockRest = blockSize - blockIndex;
        frameIndex += blockRest;
        blockIndex += blockRest;
      }
    }

    this.frameIndex = frameIndex;
  }
}
<|endoftext|>


<commit_before>L.Control.MiniMap = L.Control.extend({
	options: {
		position: 'bottomright',
		toggleDisplay: false,
		zoomLevelOffset: -5,
		zoomLevelFixed: false,
		zoomAnimation: false,
		autoToggleDisplay: false,
		width: 150,
		height: 150
	},

	hideText: 'Hide MiniMap',

	showText: 'Show MiniMap',

	//layer is the map layer to be shown in the minimap
	initialize: function (layer, options) {
		L.Util.setOptions(this, options);
		this._layer = layer;
	},

	onAdd: function (map) {

		this._mainMap = map;

		//Creating the container and stopping events from spilling through to the main map.
		this._container = L.DomUtil.create('div', 'leaflet-control-minimap');
		this._container.style.width = this.options.width + 'px';
		this._container.style.height = this.options.height + 'px';
		L.DomEvent.disableClickPropagation(this._container);
		L.DomEvent.on(this._container, 'mousewheel', L.DomEvent.stopPropagation);

		this._miniMap = new L.Map(this._container,
		{
			attributionControl: false,
			zoomControl: false,
			zoomAnimation: this.options.zoomAnimation,
			autoToggleDisplay: this.options.autoToggleDisplay,
			touchZoom: !this.options.zoomLevelFixed,
			scrollWheelZoom: !this.options.zoomLevelFixed,
			doubleClickZoom: !this.options.zoomLevelFixed,
			boxZoom: !this.options.zoomLevelFixed
		});

		this._miniMap.addLayer(this._layer);

		//These bools are used to prevent infinite loops of the two maps notifying each other that they've moved.
		this._mainMapMoving = false;
		this._miniMapMoving = false;

		//Keep a record of this to prevent auto toggling when the user explicitly doesn't want it.
		this._userToggledDisplay = false;
		this._minimized = false;

		if (this.options.toggleDisplay) {
			this._addToggleButton();
		}

		this._miniMap.whenReady(L.Util.bind(function () {
			this._aimingRect = L.rectangle(this._mainMap.getBounds(), {color: "#ff7800", weight: 1, clickable: false}).addTo(this._miniMap);
			this._shadowRect = L.rectangle(this._mainMap.getBounds(), {color: "#000000", weight: 1, clickable: false,opacity:0,fillOpacity:0}).addTo(this._miniMap);
			this._mainMap.on('moveend', this._onMainMapMoved, this);
			this._mainMap.on('move', this._onMainMapMoving, this);
			this._miniMap.on('movestart', this._onMiniMapMoveStarted, this);
			this._miniMap.on('move', this._onMiniMapMoving, this);
			this._miniMap.on('moveend', this._onMiniMapMoved, this);
		}, this));

		return this._container;
	},

	addTo: function (map) {
		L.Control.prototype.addTo.call(this, map);
		this._miniMap.setView(this._mainMap.getCenter(), this._decideZoom(true));
		this._setDisplay(this._decideMinimized());
		return this;
	},

	onRemove: function (map) {
		this._mainMap.off('moveend', this._onMainMapMoved, this);
		this._mainMap.off('move', this._onMainMapMoving, this);
		this._miniMap.off('moveend', this._onMiniMapMoved, this);

		this._miniMap.removeLayer(this._layer);
	},

	_addToggleButton: function () {
		this._toggleDisplayButton = this.options.toggleDisplay ? this._createButton(
				'', this.hideText, 'leaflet-control-minimap-toggle-display', this._container, this._toggleDisplayButtonClicked, this) : undefined;
	},

	_createButton: function (html, title, className, container, fn, context) {
		var link = L.DomUtil.create('a', className, container);
		link.innerHTML = html;
		link.href = '#';
		link.title = title;

		var stop = L.DomEvent.stopPropagation;

		L.DomEvent
			.on(link, 'click', stop)
			.on(link, 'mousedown', stop)
			.on(link, 'dblclick', stop)
			.on(link, 'click', L.DomEvent.preventDefault)
			.on(link, 'click', fn, context);

		return link;
	},

	_toggleDisplayButtonClicked: function () {
		this._userToggledDisplay = true;
		if (!this._minimized) {
			this._minimize();
			this._toggleDisplayButton.title = this.showText;
		}
		else {
			this._restore();
			this._toggleDisplayButton.title = this.hideText;
		}
	},

	_setDisplay: function (minimize) {
		if (minimize != this._minimized) {
			if (!this._minimized) {
				this._minimize();
			}
			else {
				this._restore();
			}
		}
	},

	_minimize: function () {
		// hide the minimap
		if (this.options.toggleDisplay) {
			this._container.style.width = '19px';
			this._container.style.height = '19px';
			this._toggleDisplayButton.className += ' minimized';
		}
		else {
			this._container.style.display = 'none';
		}
		this._minimized = true;
	},

	_restore: function () {
		if (this.options.toggleDisplay) {
			this._container.style.width = this.options.width + 'px';
			this._container.style.height = this.options.height + 'px';
			this._toggleDisplayButton.className = this._toggleDisplayButton.className
					.replace(/(?:^|\s)minimized(?!\S)/g, '');
		}
		else {
			this._container.style.display = 'block';
		}
		this._minimized = false;
	},

	_onMainMapMoved: function (e) {
		if (!this._miniMapMoving) {
			this._mainMapMoving = true;
			this._miniMap.setView(this._mainMap.getCenter(), this._decideZoom(true));
			this._setDisplay(this._decideMinimized());
		} else {
			this._miniMapMoving = false;
		}
		this._aimingRect.setBounds(this._mainMap.getBounds());
	},

	_onMainMapMoving: function (e) {
		this._aimingRect.setBounds(this._mainMap.getBounds());
	},

	_onMiniMapMoveStarted:function (e) {
		var lastAimingRect = this._aimingRect.getBounds();
		var sw = this._miniMap.latLngToContainerPoint(lastAimingRect.getSouthWest());
		var ne = this._miniMap.latLngToContainerPoint(lastAimingRect.getNorthEast());
		this._lastAimingRectPosition = {sw:sw,ne:ne};
	},

	_onMiniMapMoving: function (e) {
		if (!this._mainMapMoving && this._lastAimingRectPosition) {
			this._shadowRect.setBounds(new L.LatLngBounds(this._miniMap.containerPointToLatLng(this._lastAimingRectPosition.sw),this._miniMap.containerPointToLatLng(this._lastAimingRectPosition.ne)));
			this._shadowRect.setStyle({opacity:1,fillOpacity:0.3});
		}
	},

	_onMiniMapMoved: function (e) {
		if (!this._mainMapMoving) {
			this._miniMapMoving = true;
			this._mainMap.setView(this._miniMap.getCenter(), this._decideZoom(false));
			this._shadowRect.setStyle({opacity:0,fillOpacity:0});
		} else {
			this._mainMapMoving = false;
		}
	},

	_decideZoom: function (fromMaintoMini) {
		if (!this.options.zoomLevelFixed) {
			if (fromMaintoMini)
				return this._mainMap.getZoom() + this.options.zoomLevelOffset;
			else
				return this._miniMap.getZoom() - this.options.zoomLevelOffset;
		} else {
			if (fromMaintoMini)
				return this.options.zoomLevelFixed;
			else
				return this._mainMap.getZoom();
		}
	},

	_decideMinimized: function () {
		if (this._userToggledDisplay) {
			return this._minimized;
		}

		if (this.options.autoToggleDisplay) {
			if (this._mainMap.getBounds().contains(this._miniMap.getBounds())) {
				return true;
			}
			return false;
		}

		return this._minimized;
	}
});

L.Map.mergeOptions({
	miniMapControl: false
});

L.Map.addInitHook(function () {
	if (this.options.miniMapControl) {
		this.miniMapControl = (new L.Control.MiniMap()).addTo(this);
	}
});

L.control.minimap = function (options) {
	return new L.Control.MiniMap(options);
};
<commit_msg>copy CRS over from main map.<commit_after>L.Control.MiniMap = L.Control.extend({
	options: {
		position: 'bottomright',
		toggleDisplay: false,
		zoomLevelOffset: -5,
		zoomLevelFixed: false,
		zoomAnimation: false,
		autoToggleDisplay: false,
		width: 150,
		height: 150
	},

	hideText: 'Hide MiniMap',

	showText: 'Show MiniMap',

	//layer is the map layer to be shown in the minimap
	initialize: function (layer, options) {
		L.Util.setOptions(this, options);
		this._layer = layer;
	},

	onAdd: function (map) {

		this._mainMap = map;

		//Creating the container and stopping events from spilling through to the main map.
		this._container = L.DomUtil.create('div', 'leaflet-control-minimap');
		this._container.style.width = this.options.width + 'px';
		this._container.style.height = this.options.height + 'px';
		L.DomEvent.disableClickPropagation(this._container);
		L.DomEvent.on(this._container, 'mousewheel', L.DomEvent.stopPropagation);

		this._miniMap = new L.Map(this._container,
		{
			attributionControl: false,
			zoomControl: false,
			zoomAnimation: this.options.zoomAnimation,
			autoToggleDisplay: this.options.autoToggleDisplay,
			touchZoom: !this.options.zoomLevelFixed,
			scrollWheelZoom: !this.options.zoomLevelFixed,
			doubleClickZoom: !this.options.zoomLevelFixed,
			boxZoom: !this.options.zoomLevelFixed,
			crs: map.options.crs
		});

		this._miniMap.addLayer(this._layer);

		//These bools are used to prevent infinite loops of the two maps notifying each other that they've moved.
		this._mainMapMoving = false;
		this._miniMapMoving = false;

		//Keep a record of this to prevent auto toggling when the user explicitly doesn't want it.
		this._userToggledDisplay = false;
		this._minimized = false;

		if (this.options.toggleDisplay) {
			this._addToggleButton();
		}

		this._miniMap.whenReady(L.Util.bind(function () {
			this._aimingRect = L.rectangle(this._mainMap.getBounds(), {color: "#ff7800", weight: 1, clickable: false}).addTo(this._miniMap);
			this._shadowRect = L.rectangle(this._mainMap.getBounds(), {color: "#000000", weight: 1, clickable: false,opacity:0,fillOpacity:0}).addTo(this._miniMap);
			this._mainMap.on('moveend', this._onMainMapMoved, this);
			this._mainMap.on('move', this._onMainMapMoving, this);
			this._miniMap.on('movestart', this._onMiniMapMoveStarted, this);
			this._miniMap.on('move', this._onMiniMapMoving, this);
			this._miniMap.on('moveend', this._onMiniMapMoved, this);
		}, this));

		return this._container;
	},

	addTo: function (map) {
		L.Control.prototype.addTo.call(this, map);
		this._miniMap.setView(this._mainMap.getCenter(), this._decideZoom(true));
		this._setDisplay(this._decideMinimized());
		return this;
	},

	onRemove: function (map) {
		this._mainMap.off('moveend', this._onMainMapMoved, this);
		this._mainMap.off('move', this._onMainMapMoving, this);
		this._miniMap.off('moveend', this._onMiniMapMoved, this);

		this._miniMap.removeLayer(this._layer);
	},

	_addToggleButton: function () {
		this._toggleDisplayButton = this.options.toggleDisplay ? this._createButton(
				'', this.hideText, 'leaflet-control-minimap-toggle-display', this._container, this._toggleDisplayButtonClicked, this) : undefined;
	},

	_createButton: function (html, title, className, container, fn, context) {
		var link = L.DomUtil.create('a', className, container);
		link.innerHTML = html;
		link.href = '#';
		link.title = title;

		var stop = L.DomEvent.stopPropagation;

		L.DomEvent
			.on(link, 'click', stop)
			.on(link, 'mousedown', stop)
			.on(link, 'dblclick', stop)
			.on(link, 'click', L.DomEvent.preventDefault)
			.on(link, 'click', fn, context);

		return link;
	},

	_toggleDisplayButtonClicked: function () {
		this._userToggledDisplay = true;
		if (!this._minimized) {
			this._minimize();
			this._toggleDisplayButton.title = this.showText;
		}
		else {
			this._restore();
			this._toggleDisplayButton.title = this.hideText;
		}
	},

	_setDisplay: function (minimize) {
		if (minimize != this._minimized) {
			if (!this._minimized) {
				this._minimize();
			}
			else {
				this._restore();
			}
		}
	},

	_minimize: function () {
		// hide the minimap
		if (this.options.toggleDisplay) {
			this._container.style.width = '19px';
			this._container.style.height = '19px';
			this._toggleDisplayButton.className += ' minimized';
		}
		else {
			this._container.style.display = 'none';
		}
		this._minimized = true;
	},

	_restore: function () {
		if (this.options.toggleDisplay) {
			this._container.style.width = this.options.width + 'px';
			this._container.style.height = this.options.height + 'px';
			this._toggleDisplayButton.className = this._toggleDisplayButton.className
					.replace(/(?:^|\s)minimized(?!\S)/g, '');
		}
		else {
			this._container.style.display = 'block';
		}
		this._minimized = false;
	},

	_onMainMapMoved: function (e) {
		if (!this._miniMapMoving) {
			this._mainMapMoving = true;
			this._miniMap.setView(this._mainMap.getCenter(), this._decideZoom(true));
			this._setDisplay(this._decideMinimized());
		} else {
			this._miniMapMoving = false;
		}
		this._aimingRect.setBounds(this._mainMap.getBounds());
	},

	_onMainMapMoving: function (e) {
		this._aimingRect.setBounds(this._mainMap.getBounds());
	},

	_onMiniMapMoveStarted:function (e) {
		var lastAimingRect = this._aimingRect.getBounds();
		var sw = this._miniMap.latLngToContainerPoint(lastAimingRect.getSouthWest());
		var ne = this._miniMap.latLngToContainerPoint(lastAimingRect.getNorthEast());
		this._lastAimingRectPosition = {sw:sw,ne:ne};
	},

	_onMiniMapMoving: function (e) {
		if (!this._mainMapMoving && this._lastAimingRectPosition) {
			this._shadowRect.setBounds(new L.LatLngBounds(this._miniMap.containerPointToLatLng(this._lastAimingRectPosition.sw),this._miniMap.containerPointToLatLng(this._lastAimingRectPosition.ne)));
			this._shadowRect.setStyle({opacity:1,fillOpacity:0.3});
		}
	},

	_onMiniMapMoved: function (e) {
		if (!this._mainMapMoving) {
			this._miniMapMoving = true;
			this._mainMap.setView(this._miniMap.getCenter(), this._decideZoom(false));
			this._shadowRect.setStyle({opacity:0,fillOpacity:0});
		} else {
			this._mainMapMoving = false;
		}
	},

	_decideZoom: function (fromMaintoMini) {
		if (!this.options.zoomLevelFixed) {
			if (fromMaintoMini)
				return this._mainMap.getZoom() + this.options.zoomLevelOffset;
			else
				return this._miniMap.getZoom() - this.options.zoomLevelOffset;
		} else {
			if (fromMaintoMini)
				return this.options.zoomLevelFixed;
			else
				return this._mainMap.getZoom();
		}
	},

	_decideMinimized: function () {
		if (this._userToggledDisplay) {
			return this._minimized;
		}

		if (this.options.autoToggleDisplay) {
			if (this._mainMap.getBounds().contains(this._miniMap.getBounds())) {
				return true;
			}
			return false;
		}

		return this._minimized;
	}
});

L.Map.mergeOptions({
	miniMapControl: false
});

L.Map.addInitHook(function () {
	if (this.options.miniMapControl) {
		this.miniMapControl = (new L.Control.MiniMap()).addTo(this);
	}
});

L.control.minimap = function (options) {
	return new L.Control.MiniMap(options);
};
<|endoftext|>


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

  function SoundCloudService($http) {
    var service = {};
    var intv = null,
        audio = document.querySelector('audio'),
        audiosource = new SoundCloudAudioSource(audio);
    service.scResponse = null;

    service.init = function() {
      SC.initialize({
        client_id: SOUNDCLOUD_APT_KEY
      });
    }

    service.searchSoundCloud = function(query) {
      return $http.get('https://api.soundcloud.com/tracks.json?client_id=' + SOUNDCLOUD_APT_KEY + '&q=' + query + '&limit=1').
      then(function(response) {
        service.scResponse = response.data;
        console.debug("SoundCloud link: ", service.scResponse[0].permalink_url);
        var streamUrl = service.scResponse[0].stream_url + '?client_id=' + SOUNDCLOUD_APT_KEY;
        audio.setAttribute('src', streamUrl);

        return service.scResponse;
      });
    };

    service.play = function(){
      audio.play();
      intv = setInterval(function(){ audiosource.draw() }, 1000 / 30);
    };

    service.pause = function(){
      audio.pause();
      clearInterval(intv);
      audiosource.audioCtx.close();
    };

    service.replay = function(){
      audio.currentTime = 0;
      audio.pause();
      intv = setInterval(function(){ audiosource.draw() }, 1000 / 30);
    };

    return service;
  }

  var SoundCloudAudioSource = function(audio){
    var self = this;
    this.audioCtx = new (window.AudioContext || window.webkitAudioContext);
    var source = this.audioCtx.createMediaElementSource(audio);

    var analyser = this.audioCtx.createAnalyser();
    analyser.fftSize = 256;
    audio.crossOrigin = "anonymous";
    source.connect(analyser);
    analyser.connect(this.audioCtx.destination);

    this.bufferLength = analyser.frequencyBinCount;

    this.dataArray = new Uint8Array(this.bufferLength);

    this.draw = function() {
      analyser.getByteTimeDomainData(this.dataArray);
      drawCanvas(this.dataArray,this.bufferLength);
    };
    // intv = setInterval(function(){ draw() }, 1000 / 30);

  }

  function drawCanvas(dataArray,bufferLength){
    var canvas = document.getElementById('visualizer');
    var canvasCtx = canvas.getContext("2d");

    var WIDTH = 150;
    var HEIGHT = 150;

    canvasCtx.fillStyle = 'rgb(0, 0, 0)';
    canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
    canvasCtx.strokeStyle = 'rgb(255,255,255)';

    canvasCtx.lineWidth = 2;
    canvasCtx.beginPath();

    var sliceWidth = WIDTH * 1.0 / bufferLength;
    var x = 0;

    for(var i = 0; i < bufferLength; i++) {
      var data = dataArray[i];
      var v = data / 128.0;
      var y = v * HEIGHT/2;

      if(i === 0) {
        canvasCtx.moveTo(x, y);
      } else {
        canvasCtx.lineTo(x, y);
      }

      x += sliceWidth;
    }
    canvasCtx.lineTo(canvas.width, canvas.height/2);
    canvasCtx.stroke();
  }

  angular.module('SmartMirror')
  .factory('SoundCloudService', SoundCloudService);

}());
<commit_msg>modify "sound cloud replay" and "sound cloud resume"<commit_after>(function() {
  'use strict';

  function SoundCloudService($http) {
    var service = {};
    var intv = null,
        audio = document.querySelector('audio'),
        audiosource = new SoundCloudAudioSource(audio);
    service.scResponse = null;

    service.init = function() {
      SC.initialize({
        client_id: SOUNDCLOUD_APT_KEY
      });
    }

    service.searchSoundCloud = function(query) {
      return $http.get('https://api.soundcloud.com/tracks.json?client_id=' + SOUNDCLOUD_APT_KEY + '&q=' + query + '&limit=1').
      then(function(response) {
        service.scResponse = response.data;
        console.debug("SoundCloud link: ", service.scResponse[0].permalink_url);
        var streamUrl = service.scResponse[0].stream_url + '?client_id=' + SOUNDCLOUD_APT_KEY;
        audio.setAttribute('src', streamUrl);

        return service.scResponse;
      });
    };

    service.play = function(){
      audio.play();
      intv = setInterval(function(){ audiosource.draw() }, 1000 / 30);
    };

    service.pause = function(){
      audio.pause();
      clearInterval(intv);
      // audiosource.audioCtx.close();
    };

    service.replay = function(){
      audio.currentTime = 0;
      audio.pause();
      audio.play();
      intv = setInterval(function(){ audiosource.draw() }, 1000 / 30);
    };

    return service;
  }

  var SoundCloudAudioSource = function(audio){
    var self = this;
    this.audioCtx = new (window.AudioContext || window.webkitAudioContext);
    var source = this.audioCtx.createMediaElementSource(audio);

    var analyser = this.audioCtx.createAnalyser();
    analyser.fftSize = 256;
    audio.crossOrigin = "anonymous";
    source.connect(analyser);
    analyser.connect(this.audioCtx.destination);

    this.bufferLength = analyser.frequencyBinCount;

    this.dataArray = new Uint8Array(this.bufferLength);

    this.draw = function() {
      analyser.getByteTimeDomainData(this.dataArray);
      drawCanvas(this.dataArray,this.bufferLength);
    };
    // intv = setInterval(function(){ draw() }, 1000 / 30);

  }

  function drawCanvas(dataArray,bufferLength){
    var canvas = document.getElementById('visualizer');
    var canvasCtx = canvas.getContext("2d");

    var WIDTH = 150;
    var HEIGHT = 150;

    canvasCtx.fillStyle = 'rgb(0, 0, 0)';
    canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
    canvasCtx.strokeStyle = 'rgb(255,255,255)';

    canvasCtx.lineWidth = 2;
    canvasCtx.beginPath();

    var sliceWidth = WIDTH * 1.0 / bufferLength;
    var x = 0;

    for(var i = 0; i < bufferLength; i++) {
      var data = dataArray[i];
      var v = data / 128.0;
      var y = v * HEIGHT/2;

      if(i === 0) {
        canvasCtx.moveTo(x, y);
      } else {
        canvasCtx.lineTo(x, y);
      }

      x += sliceWidth;
    }
    canvasCtx.lineTo(canvas.width, canvas.height/2);
    canvasCtx.stroke();
  }

  angular.module('SmartMirror')
  .factory('SoundCloudService', SoundCloudService);

}());
<|endoftext|>


<commit_before>var babel = require('systemjs-babel-build').babel;

// the SystemJS babel build includes standard presets
var es2015 = require('systemjs-babel-build').presetES2015;
var es2015Register = require('systemjs-babel-build').presetES2015Register;
var modulesRegister = require('systemjs-babel-build').modulesRegister;
var stage3 = require('systemjs-babel-build').presetStage3;

var externalHelpers = require('systemjs-babel-build').externalHelpers;
var runtimeTransform = require('systemjs-babel-build').runtimeTransform;

var babelRuntimePath = System.decanonicalize('babel-runtime/', module.id);
var modularHelpersPath = System.decanonicalize('./babel-helpers/', module.id);
var externalHelpersPath = System.decanonicalize('./babel-helpers.js', module.id);
var regeneratorRuntimePath = System.decanonicalize('./regenerator-runtime.js', module.id);

// in builds we want to embed canonical names to helpers
if (System.getCanonicalName) {
  babelRuntimePath = System.getCanonicalName(babelRuntimePath);
  modularHelpersPath = System.getCanonicalName(modularHelpersPath);
  externalHelpersPath = System.getCanonicalName(externalHelpersPath);
  regeneratorRuntimePath = System.getCanonicalName(regeneratorRuntimePath);
}

// disable SystemJS runtime detection
SystemJS._loader.loadedTranspilerRuntime = true;

function prepend(a, b) {
  for (var p in b)
    if (!(p in a))
      a[p] = b[p];
  return a;
}

/*
 * babelOptions:
 *   modularRuntime: true / false (whether to use babel-runtime or babel/external-helpers respectively)
 *   sourceMaps: true / false (defaults to true) Not working pending https://phabricator.babeljs.io/T6903
 *   es2015: true / false (defaults to true)
 *   stage3: true / false (defaults to true)
 *   plugins: array of custom plugins (objects or module name strings)
 *   presets: array of custom presets (objects or module name strings)
 *   moduleName: true / false (whether to set __moduleName, defaults to false) needed pending https://phabricator.babeljs.io/T6899
 *
 * babelOptions can be set at SystemJS.babelOptions OR on the metadata object for a given module
 */
var defaultBabelOptions = {
  modularRuntime: true,
  sourceMaps: true,
  es2015: true,
  stage3: true,
  moduleName: false
};

exports.translate = function(load) {
  // we don't transpile anything other than CommonJS or ESM
  if (load.metadata.format == 'global' || load.metadata.format == 'amd' || load.metadata.format == 'json')
    throw new TypeError('plugin-babel cannot transpile ' + load.metadata.format + ' modules. Ensure "' + load.name + '" is configured not to use this loader.');

  var loader = this;
  var pluginLoader = loader.pluginLoader || loader;

  var babelOptions = {};

  if (load.metadata.babelOptions)
    prepend(babelOptions, load.metadata.babelOptions);

  if (loader.babelOptions)
    prepend(babelOptions, loader.babelOptions);

  prepend(babelOptions, defaultBabelOptions);

  // determine any plugins or preset strings which need to be imported as modules
  var pluginAndPresetModuleLoads = [];

  if (babelOptions.presets)
    babelOptions.presets.forEach(function(preset) {
      if (typeof preset == 'string')
        pluginAndPresetModuleLoads.push(pluginLoader['import'](preset, module.id));
    });

  if (babelOptions.plugins)
    babelOptions.plugins.forEach(function(plugin) {
      if (typeof plugin == 'string')
        pluginAndPresetModuleLoads.push(pluginLoader['import'](plugin, module.id));
      else if (plugin instanceof Array && typeof plugin[0] == 'string')
        pluginAndPresetModuleLoads.push(pluginLoader['import'](plugin[0], module.id));
    });

  return Promise.all(pluginAndPresetModuleLoads)
  .then(function(pluginAndPresetModules) {
    var curPluginOrPresetModule = 0;

    var presets = [];
    var plugins = [];

    if (babelOptions.stage3)
      presets.push(stage3);

    if (babelOptions.modularRuntime) {
      if (load.metadata.format == 'cjs')
        throw new TypeError('plugin-babel does not support modular runtime for CJS module transpilations. Set babelOptions.modularRuntime: false if needed.');
      presets.push(runtimeTransform);
    }
    else {
      if (load.metadata.format == 'cjs')
        load.source = 'var babelHelpers = require("' + externalHelpersPath + '");' + load.source;
      else
        load.source = 'import babelHelpers from "' + externalHelpersPath + '";' + load.source;
      presets.push(externalHelpers);
    }

    if (babelOptions.es2015)
      presets.push((loader.builder || load.metadata.format == 'cjs') ? es2015 : es2015Register);
    else
      presets.push(modulesRegister);

    if (babelOptions.presets)
      babelOptions.presets.forEach(function(preset) {
        if (typeof preset == 'string')
          presets.push(pluginAndPresetModules[curPluginOrPresetModule++]);
        else
          presets.push(preset);
      });

    if (babelOptions.plugins)
      babelOptions.plugins.forEach(function(plugin) {
        if (typeof plugin == 'string')
          plugins.push(pluginAndPresetModules[curPluginOrPresetModule++]);
        else if (plugin instanceof Array && typeof plugin[0] == 'string')
          plugins.push([pluginAndPresetModules[curPluginOrPresetModule++], plugin[1]]);
        else
          plugins.push(plugin);
      });

    var output = babel.transform(load.source, {
      plugins: plugins,
      presets: presets,
      filename: load.address,
      sourceMap: babelOptions.sourceMap,
      inputSourceMap: load.metadata.sourceMap,
      code: true,
      ast: false,
      resolveModuleSource: function(m) {
        if (m.substr(0, 22) == 'babel-runtime/helpers/') {
          m = modularHelpersPath + m.substr(22) + '.js';
        }
        else if (m == 'babel-runtime/regenerator') {
          m = regeneratorRuntimePath;
        }
        else if (m.substr(0, 14) == 'babel-runtime/') {
          if (babelRuntimePath == 'babel-runtime/')
            throw new Error('The babel-runtime module must be mapped to support modular helpers and builtins. If using jspm run jspm install npm:babel-runtime.');
          m = babelRuntimePath + m.substr(14) + '.js';
        }
        return m;
      }
    });

    // add babelHelpers as a dependency for non-modular runtime
    if (!babelOptions.modularRuntime)
      load.metadata.deps.push(externalHelpersPath);

    // set output module format
    // (in builder we output modules as esm)
    if (!load.metadata.format || load.metadata.format == 'detect')
      load.metadata.format = loader.builder ? 'esm' : 'register';

    load.metadata.sourceMap = output.map;

    if (loader.builder || !babelOptions.moduleName)
      return output.code;
    else
      return '(function(__moduleName){' + output.code + '\n})("' + load.name + '");';
  });
};

<commit_msg>dont read from babelrc<commit_after>var babel = require('systemjs-babel-build').babel;

// the SystemJS babel build includes standard presets
var es2015 = require('systemjs-babel-build').presetES2015;
var es2015Register = require('systemjs-babel-build').presetES2015Register;
var modulesRegister = require('systemjs-babel-build').modulesRegister;
var stage3 = require('systemjs-babel-build').presetStage3;

var externalHelpers = require('systemjs-babel-build').externalHelpers;
var runtimeTransform = require('systemjs-babel-build').runtimeTransform;

var babelRuntimePath = System.decanonicalize('babel-runtime/', module.id);
var modularHelpersPath = System.decanonicalize('./babel-helpers/', module.id);
var externalHelpersPath = System.decanonicalize('./babel-helpers.js', module.id);
var regeneratorRuntimePath = System.decanonicalize('./regenerator-runtime.js', module.id);

// in builds we want to embed canonical names to helpers
if (System.getCanonicalName) {
  babelRuntimePath = System.getCanonicalName(babelRuntimePath);
  modularHelpersPath = System.getCanonicalName(modularHelpersPath);
  externalHelpersPath = System.getCanonicalName(externalHelpersPath);
  regeneratorRuntimePath = System.getCanonicalName(regeneratorRuntimePath);
}

// disable SystemJS runtime detection
SystemJS._loader.loadedTranspilerRuntime = true;

function prepend(a, b) {
  for (var p in b)
    if (!(p in a))
      a[p] = b[p];
  return a;
}

/*
 * babelOptions:
 *   modularRuntime: true / false (whether to use babel-runtime or babel/external-helpers respectively)
 *   sourceMaps: true / false (defaults to true) Not working pending https://phabricator.babeljs.io/T6903
 *   es2015: true / false (defaults to true)
 *   stage3: true / false (defaults to true)
 *   plugins: array of custom plugins (objects or module name strings)
 *   presets: array of custom presets (objects or module name strings)
 *   moduleName: true / false (whether to set __moduleName, defaults to false) needed pending https://phabricator.babeljs.io/T6899
 *
 * babelOptions can be set at SystemJS.babelOptions OR on the metadata object for a given module
 */
var defaultBabelOptions = {
  modularRuntime: true,
  sourceMaps: true,
  es2015: true,
  stage3: true,
  moduleName: false
};

exports.translate = function(load) {
  // we don't transpile anything other than CommonJS or ESM
  if (load.metadata.format == 'global' || load.metadata.format == 'amd' || load.metadata.format == 'json')
    throw new TypeError('plugin-babel cannot transpile ' + load.metadata.format + ' modules. Ensure "' + load.name + '" is configured not to use this loader.');

  var loader = this;
  var pluginLoader = loader.pluginLoader || loader;

  var babelOptions = {};

  if (load.metadata.babelOptions)
    prepend(babelOptions, load.metadata.babelOptions);

  if (loader.babelOptions)
    prepend(babelOptions, loader.babelOptions);

  prepend(babelOptions, defaultBabelOptions);

  // determine any plugins or preset strings which need to be imported as modules
  var pluginAndPresetModuleLoads = [];

  if (babelOptions.presets)
    babelOptions.presets.forEach(function(preset) {
      if (typeof preset == 'string')
        pluginAndPresetModuleLoads.push(pluginLoader['import'](preset, module.id));
    });

  if (babelOptions.plugins)
    babelOptions.plugins.forEach(function(plugin) {
      if (typeof plugin == 'string')
        pluginAndPresetModuleLoads.push(pluginLoader['import'](plugin, module.id));
      else if (plugin instanceof Array && typeof plugin[0] == 'string')
        pluginAndPresetModuleLoads.push(pluginLoader['import'](plugin[0], module.id));
    });

  return Promise.all(pluginAndPresetModuleLoads)
  .then(function(pluginAndPresetModules) {
    var curPluginOrPresetModule = 0;

    var presets = [];
    var plugins = [];

    if (babelOptions.stage3)
      presets.push(stage3);

    if (babelOptions.modularRuntime) {
      if (load.metadata.format == 'cjs')
        throw new TypeError('plugin-babel does not support modular runtime for CJS module transpilations. Set babelOptions.modularRuntime: false if needed.');
      presets.push(runtimeTransform);
    }
    else {
      if (load.metadata.format == 'cjs')
        load.source = 'var babelHelpers = require("' + externalHelpersPath + '");' + load.source;
      else
        load.source = 'import babelHelpers from "' + externalHelpersPath + '";' + load.source;
      presets.push(externalHelpers);
    }

    if (babelOptions.es2015)
      presets.push((loader.builder || load.metadata.format == 'cjs') ? es2015 : es2015Register);
    else
      presets.push(modulesRegister);

    if (babelOptions.presets)
      babelOptions.presets.forEach(function(preset) {
        if (typeof preset == 'string')
          presets.push(pluginAndPresetModules[curPluginOrPresetModule++]);
        else
          presets.push(preset);
      });

    if (babelOptions.plugins)
      babelOptions.plugins.forEach(function(plugin) {
        if (typeof plugin == 'string')
          plugins.push(pluginAndPresetModules[curPluginOrPresetModule++]);
        else if (plugin instanceof Array && typeof plugin[0] == 'string')
          plugins.push([pluginAndPresetModules[curPluginOrPresetModule++], plugin[1]]);
        else
          plugins.push(plugin);
      });

    var output = babel.transform(load.source, {
      babelrc: false,
      plugins: plugins,
      presets: presets,
      filename: load.address,
      sourceMap: babelOptions.sourceMap,
      inputSourceMap: load.metadata.sourceMap,
      code: true,
      ast: false,
      resolveModuleSource: function(m) {
        if (m.substr(0, 22) == 'babel-runtime/helpers/') {
          m = modularHelpersPath + m.substr(22) + '.js';
        }
        else if (m == 'babel-runtime/regenerator') {
          m = regeneratorRuntimePath;
        }
        else if (m.substr(0, 14) == 'babel-runtime/') {
          if (babelRuntimePath == 'babel-runtime/')
            throw new Error('The babel-runtime module must be mapped to support modular helpers and builtins. If using jspm run jspm install npm:babel-runtime.');
          m = babelRuntimePath + m.substr(14) + '.js';
        }
        return m;
      }
    });

    // add babelHelpers as a dependency for non-modular runtime
    if (!babelOptions.modularRuntime)
      load.metadata.deps.push(externalHelpersPath);

    // set output module format
    // (in builder we output modules as esm)
    if (!load.metadata.format || load.metadata.format == 'detect')
      load.metadata.format = loader.builder ? 'esm' : 'register';

    load.metadata.sourceMap = output.map;

    if (loader.builder || !babelOptions.moduleName)
      return output.code;
    else
      return '(function(__moduleName){' + output.code + '\n})("' + load.name + '");';
  });
};

<|endoftext|>


<commit_before>$(document).ready(function(){
    var changeColor = function() {
        console.log('change');
        this.setAttribute('color', 'green');
    };

    $('a-box').hover(changeColor());
});<commit_msg>Revert to pure JS code<commit_after>$(document).ready(function(){
    var box = document.getElementsByTagName('a-box');

    var changeColor = function() {
        console.log('change');
        this.setAttribute('color', 'green');
    };
    var returnColor = function() {
        console.log('return');
        this.setAttribute('color', '#4CC3D9');
    };

    for (var i = 0; i < box.length; i++) {
        box[i].addEventListener('mouseenter', changeColor, false);
        box[i].addEventListener('mouseleave', returnColor, false);
    }
});<|endoftext|>


<commit_before>// Copyright (c) Cognitect, Inc.
// All rights reserved.

goog.provide("com.cognitect.transit.impl.decoder");
goog.require("com.cognitect.transit.util");
goog.require("com.cognitect.transit.delimiters");
goog.require("com.cognitect.transit.caching");
goog.require("com.cognitect.transit.types");

goog.scope(function() {

var decoder = com.cognitect.transit.impl.decoder,
    util    = com.cognitect.transit.util,
    d       = com.cognitect.transit.delimiters,
    caching = com.cognitect.transit.caching,
    types   = com.cognitect.transit.types;

// =============================================================================
// Decoder

decoder.isGroundDecoder = function(decoder) {
    switch(decoder) {
        case "_":
        case "s":
        case "?":
        case "i":
        case "d":
        case "b":
        case "'":
        case "array":
        case "map":
        return true;
    }
    return false;
};

/**
 * A transit decoder
 * @constructor
 */
decoder.Decoder = function(options) {
    this.options = options || {};
    this.decoders = {};
    for(var d in this.defaults.decoders) {
        this.decoders[d] = this.defaults.decoders[d];
    }
    for(var d in this.options["decoders"]) {
        if(decoder.isGroundDecoder(d)) {
            throw new Error("Cannot override decoder for ground types");
        }
        this.decoders[d] = this.options["decoders"][d];
    }
    this.prefersStrings = this.options["prefersStrings"] != null ? this.options["prefersStrings"] : this.defaults.prefersStrings;
    this.defaultStringDecoder = this.options["defaultStringDecoder"] || this.defaults.defaultStringDecoder;
    /* NOT PUBLIC */
    this.mapBuilder = this.options["mapBuilder"];
    this.arrayBuilder = this.options["arrayBuilder"];
};

decoder.Decoder.prototype.defaults = {
    decoders: {
        "_": function(v) { return types.nullValue(); },
        "?": function(v) { return types.boolValue(v); },
        "b": function(v) { return types.binary(v); },
        "i": function(v) { return types.intValue(v); },
        "n": function(v) { return types.bigInteger(v); },
        "d": function(v) { return types.floatValue(v); },
        "f": function(v) { return types.bigDecimalValue(v); },
        "c": function(v) { return types.charValue(v); },
        ":": function(v) { return types.keyword(v); },
        "$": function(v) { return types.symbol(v); },
        "r": function(v) { return types.uri(v); },

        // tagged
        "'": function(v) { return v; },
        "m": function(v) { return types.date(v); },
        "t": function(v) { return types.verboseDate(v); },
        "u": function(v) { return types.uuid(v); },
        "set": function(v) { return types.set(v); },
        "list": function(v) { return types.list(v); },
        "ints": function(v) { return types.ints(v); },
        "longs": function(v) { return types.longs(v); },
        "floats": function(v) { return types.floats(v); },
        "doubles": function(v) { return types.doubles(v); },
        "bools": function(v) { return types.bools(v); },
        "cmap": function(v) { return types.map(v); }
    },
    prefersStrings: true
};

decoder.Decoder.prototype.decode = function(node, cache, asMapKey, tagValue) {
    if(node == null) return null;

    var t = typeof node;

    switch(t) {
    case "string":
        return this.decodeString(node, cache, asMapKey, tagValue);
        break;
    case "object":
        if(util.isArray(node)) {
            if(node[0] === "^ ") {
                return this.decodeArrayHash(node, cache, asMapKey, tagValue);
            } else {
                return this.decodeArray(node, cache, false, tagValue);
            }
        } else {
            return this.decodeHash(node, cache, asMapKey, tagValue);
        }
        break;
    }

    return node;
};
decoder.Decoder.prototype["decode"] = decoder.Decoder.prototype.decode;

decoder.Decoder.prototype.decodeString = function(string, cache, asMapKey, tagValue) {
    if(caching.isCacheable(string, asMapKey)) {
        var val = this.parseString(string, cache, false);
        if(cache) {
            cache.write(val, asMapKey);
        }
        return val;
    } else if(caching.isCacheCode(string)) {
        return cache.read(string, asMapKey);
    } else {
        return this.parseString(string, cache, asMapKey);
    }
};

decoder.Decoder.prototype.isStringKey = function(node, cache) {
    if(typeof node !== "string") {
        return false;
    } else {
        var c0 = node[0],
            c1 = node[1];
        if(c0 === d.ESC) {
            if(this.decoders[c1] != null) {
                return false;
            } else {
                return (c1 === d.ESC || c1 === d.SUB || c1 === d.RES);
            }
        } else if(c0 === d.SUB && ((typeof cache.read(node)) !== "string"))  {
            return false;
        } else {
            return true;
        }
    }
};

decoder.Decoder.prototype.decodeHash = function(hash, cache, asMapKey, tagValue) {
    var ks     = util.objectKeys(hash),
        key    = ks[0],
        tagKey = ks.length == 1 ? this.decode(key, cache, false, false) : null;

    if((tagKey != null) &&
       (tagKey[0] === d.ESC) &&
       (tagKey[1] === d.TAG)) {
        var val     = hash[key],
            decoder = this.decoders[tagKey.substring(2)];
        if(decoder != null) {
            return decoder(this.decode(val, cache, false, true));
        } else {
            return types.taggedValue(tagKey.substring(2), this.decode(val, cache, false, false));
        }
    } else if(this.mapBuilder) {
        var ret = this.mapBuilder.init();

        for(var i = 0; i < ks.length; i++) {
            var strKey = ks[i];
            ret = this.mapBuilder.add(ret, this.decode(strKey, cache, true, false),
                                           this.decode(hash[strKey], cache, false, false));
        }

        return this.mapBuilder.finalize(ret);
    } else {
        var stringKeys = true;

        for(var i = 0; i < ks.length; i++) {
            if(!this.isStringKey(ks[i], cache)) {
                stringKeys = false;
                break;
            }
        }

        if(stringKeys) {
            var ret = {};
            for(var i = 0; i < ks.length; i++) {
                var strKey = ks[i];
                ret[this.decode(strKey, cache, true, false)] = this.decode(hash[strKey], cache, false, false);
            }
            return ret;
        } else {
            var ret = types.map();
            for(var i = 0; i < ks.length; i++) {
                var strKey = ks[i];
                ret.set(this.decode(strKey, cache, true, false), this.decode(hash[strKey], cache, false, false));
            }
            return ret;
        }
    }
};

decoder.Decoder.prototype.decodeArrayHash = function(node, cache, asMapKey, tagValue) {
    if(this.mapBuilder) {
        var ret = this.mapBuilder.init();
        for(var i = 1; i < node.length; i+=2) {
            ret = this.mapBuilder.add(ret, this.decode(node[i], cache, true, false),
                                           this.decode(node[i+1], cache, false, false))
        }
        return this.mapBuilder.finalize(ret);
    } else {
        var stringKeys = true;

        // collect keys
        for(var i = 1; i < node.length; i +=2) {
            if(!this.isStringKey(node[i], cache)) {
                stringKeys = false;
                break;
            }
        }

        if(stringKeys) {
            var ret = {};
            for(var i = 1; i < node.length; i+=2) {
                ret[this.decode(node[i], cache, true, false)] = this.decode(node[i+1], cache, false, false);
            }
            return ret;
        } else {
            var ret = types.map();
            for(var i = 1; i < node.length; i+=2) {
                ret.set(this.decode(node[i], cache, true, false), this.decode(node[i+1], cache, false, false));
            }
            return ret;
        }
    }
};

decoder.Decoder.prototype.decodeArray = function(node, cache, asMapKey, tagValue) {
    if(tagValue) {
        var ret = [];
        for(var i = 0; i < node.length; i++) {
            ret.push(this.decode(node[i], cache, asMapKey, false));
        }
        return ret;
    } else if(this.arrayBuilder) {
        var ret = this.arrayBuilder.init();
        for(var i = 0; i < node.length; i++) {
            ret = this.arrayBuilder.add(ret, this.decode(node[i], cache, asMapKey, false));
        }
        return this.arrayBuilder.finalize(ret);
    } else {
        var ret = [];
        for(var i = 0; i < node.length; i++) {
            ret.push(this.decode(node[i], cache, asMapKey, false));
        }
        return ret;
    }
};

decoder.Decoder.prototype.parseString = function(string, cache, asMapKey) {
    if(string[0] === d.ESC) {
        var c = string[1];
        if(c === d.ESC || c === d.SUB || c === d.RES) {
            return string.substring(1);
        } else if (c === d.TAG) {
            return string;
        } else {
            var decoder = this.decoders[c];
            if(decoder == null) {
                return types.taggedValue(c, string.substring(2));
            } else {
                return decoder(string.substring(2));
            }
        }
    } else {
        return string;
    }
};

decoder.decoder = function(options) {
    return new decoder.Decoder(options);
};

});
<commit_msg>fix subtle caching bug, need to build 2nd array<commit_after>// Copyright (c) Cognitect, Inc.
// All rights reserved.

goog.provide("com.cognitect.transit.impl.decoder");
goog.require("com.cognitect.transit.util");
goog.require("com.cognitect.transit.delimiters");
goog.require("com.cognitect.transit.caching");
goog.require("com.cognitect.transit.types");

goog.scope(function() {

var decoder = com.cognitect.transit.impl.decoder,
    util    = com.cognitect.transit.util,
    d       = com.cognitect.transit.delimiters,
    caching = com.cognitect.transit.caching,
    types   = com.cognitect.transit.types;

// =============================================================================
// Decoder

decoder.isGroundDecoder = function(decoder) {
    switch(decoder) {
        case "_":
        case "s":
        case "?":
        case "i":
        case "d":
        case "b":
        case "'":
        case "array":
        case "map":
        return true;
    }
    return false;
};

/**
 * A transit decoder
 * @constructor
 */
decoder.Decoder = function(options) {
    this.options = options || {};
    this.decoders = {};
    for(var d in this.defaults.decoders) {
        this.decoders[d] = this.defaults.decoders[d];
    }
    for(var d in this.options["decoders"]) {
        if(decoder.isGroundDecoder(d)) {
            throw new Error("Cannot override decoder for ground types");
        }
        this.decoders[d] = this.options["decoders"][d];
    }
    this.prefersStrings = this.options["prefersStrings"] != null ? this.options["prefersStrings"] : this.defaults.prefersStrings;
    this.defaultStringDecoder = this.options["defaultStringDecoder"] || this.defaults.defaultStringDecoder;
    /* NOT PUBLIC */
    this.mapBuilder = this.options["mapBuilder"];
    this.arrayBuilder = this.options["arrayBuilder"];
};

decoder.Decoder.prototype.defaults = {
    decoders: {
        "_": function(v) { return types.nullValue(); },
        "?": function(v) { return types.boolValue(v); },
        "b": function(v) { return types.binary(v); },
        "i": function(v) { return types.intValue(v); },
        "n": function(v) { return types.bigInteger(v); },
        "d": function(v) { return types.floatValue(v); },
        "f": function(v) { return types.bigDecimalValue(v); },
        "c": function(v) { return types.charValue(v); },
        ":": function(v) { return types.keyword(v); },
        "$": function(v) { return types.symbol(v); },
        "r": function(v) { return types.uri(v); },

        // tagged
        "'": function(v) { return v; },
        "m": function(v) { return types.date(v); },
        "t": function(v) { return types.verboseDate(v); },
        "u": function(v) { return types.uuid(v); },
        "set": function(v) { return types.set(v); },
        "list": function(v) { return types.list(v); },
        "ints": function(v) { return types.ints(v); },
        "longs": function(v) { return types.longs(v); },
        "floats": function(v) { return types.floats(v); },
        "doubles": function(v) { return types.doubles(v); },
        "bools": function(v) { return types.bools(v); },
        "cmap": function(v) { return types.map(v); }
    },
    prefersStrings: true
};

decoder.Decoder.prototype.decode = function(node, cache, asMapKey, tagValue) {
    if(node == null) return null;

    var t = typeof node;

    switch(t) {
    case "string":
        return this.decodeString(node, cache, asMapKey, tagValue);
        break;
    case "object":
        if(util.isArray(node)) {
            if(node[0] === "^ ") {
                return this.decodeArrayHash(node, cache, asMapKey, tagValue);
            } else {
                return this.decodeArray(node, cache, false, tagValue);
            }
        } else {
            return this.decodeHash(node, cache, asMapKey, tagValue);
        }
        break;
    }

    return node;
};
decoder.Decoder.prototype["decode"] = decoder.Decoder.prototype.decode;

decoder.Decoder.prototype.decodeString = function(string, cache, asMapKey, tagValue) {
    if(caching.isCacheable(string, asMapKey)) {
        var val = this.parseString(string, cache, false);
        if(cache) {
            cache.write(val, asMapKey);
        }
        return val;
    } else if(caching.isCacheCode(string)) {
        return cache.read(string, asMapKey);
    } else {
        return this.parseString(string, cache, asMapKey);
    }
};

decoder.Decoder.prototype.isStringKey = function(node, cache) {
    if(typeof node !== "string") {
        return false;
    } else {
        var c0 = node[0],
            c1 = node[1];
        if(c0 === d.ESC) {
            if(this.decoders[c1] != null) {
                return false;
            } else {
                return (c1 === d.ESC || c1 === d.SUB || c1 === d.RES);
            }
        } else if(c0 === d.SUB && ((typeof cache.read(node)) !== "string"))  {
            return false;
        } else {
            return true;
        }
    }
};

decoder.Decoder.prototype.decodeHash = function(hash, cache, asMapKey, tagValue) {
    var ks     = util.objectKeys(hash),
        key    = ks[0],
        tagKey = ks.length == 1 ? this.decode(key, cache, false, false) : null;

    if((tagKey != null) &&
       (tagKey[0] === d.ESC) &&
       (tagKey[1] === d.TAG)) {
        var val     = hash[key],
            decoder = this.decoders[tagKey.substring(2)];
        if(decoder != null) {
            return decoder(this.decode(val, cache, false, true));
        } else {
            return types.taggedValue(tagKey.substring(2), this.decode(val, cache, false, false));
        }
    } else if(this.mapBuilder) {
        var ret = this.mapBuilder.init();

        for(var i = 0; i < ks.length; i++) {
            var strKey = ks[i];
            ret = this.mapBuilder.add(ret, this.decode(strKey, cache, true, false),
                                           this.decode(hash[strKey], cache, false, false));
        }

        return this.mapBuilder.finalize(ret);
    } else {
        var stringKeys = true,
            nodep      = [];

        for(var i = 0; i < ks.length; i++) {
            var strKey = ks[i];
            stringKeys = stringKeys && this.isStringKey(strKey, cache);
            nodep.push(this.decode(strKey, cache, true, false));
            nodep.push(this.decode(hash[strKey], cache, false, false));
        }

        if(stringKeys) {
            var ret = {};
            for(var j = 0; j < nodep.length; j+=2) {
                ret[nodep[j]] = nodep[j+1];
            }
            return ret;
        } else {
            var ret = types.map();
            for(var j = 0; j < nodep.length; j+=2) {
                ret.set(nodep[j], nodep[j+1]);
            }
            return ret;
        }
    }
};

decoder.Decoder.prototype.decodeArrayHash = function(node, cache, asMapKey, tagValue) {
    if(this.mapBuilder) {
        var ret = this.mapBuilder.init();
        for(var i = 1; i < node.length; i+=2) {
            ret = this.mapBuilder.add(ret, this.decode(node[i], cache, true, false),
                                           this.decode(node[i+1], cache, false, false))
        }
        return this.mapBuilder.finalize(ret);
    } else {
        var stringKeys = true,
            nodep      = [];

        // collect keys
        for(var i = 1; i < node.length; i +=2) {
            stringKeys = stringKeys && this.isStringKey(node[i], cache);
            nodep.push(this.decode(node[i], cache, true, false));
            nodep.push(this.decode(node[i+1], cache, false, false));
        }

        if(stringKeys) {
            var ret = {};
            for(var j = 0; j < nodep.length; j+=2) {
                ret[nodep[j]] = nodep[j+1];
            }
            return ret;
        } else {
            var ret = types.map();
            for(var j = 0; j < nodep.length; j+=2) {
                ret.set(nodep[j], nodep[j+1]);
            }
            return ret;
        }
    }
};

decoder.Decoder.prototype.decodeArray = function(node, cache, asMapKey, tagValue) {
    if(tagValue) {
        var ret = [];
        for(var i = 0; i < node.length; i++) {
            ret.push(this.decode(node[i], cache, asMapKey, false));
        }
        return ret;
    } else if(this.arrayBuilder) {
        var ret = this.arrayBuilder.init();
        for(var i = 0; i < node.length; i++) {
            ret = this.arrayBuilder.add(ret, this.decode(node[i], cache, asMapKey, false));
        }
        return this.arrayBuilder.finalize(ret);
    } else {
        var ret = [];
        for(var i = 0; i < node.length; i++) {
            ret.push(this.decode(node[i], cache, asMapKey, false));
        }
        return ret;
    }
};

decoder.Decoder.prototype.parseString = function(string, cache, asMapKey) {
    if(string[0] === d.ESC) {
        var c = string[1];
        if(c === d.ESC || c === d.SUB || c === d.RES) {
            return string.substring(1);
        } else if (c === d.TAG) {
            return string;
        } else {
            var decoder = this.decoders[c];
            if(decoder == null) {
                return types.taggedValue(c, string.substring(2));
            } else {
                return decoder(string.substring(2));
            }
        }
    } else {
        return string;
    }
};

decoder.decoder = function(options) {
    return new decoder.Decoder(options);
};

});
<|endoftext|>