<commit_before>define(["lodash", "backbone", "jquery", "js/models/LevelsPool", "js/enum", "js/models/UserModel"],
    function (_, Backbone, $, LevelsPool, Enum, UserModel) {

        /*
         * General rules:
         * 1. methods started with fetch* are used to fetch data and, probably, save it to inetrnals
         */

        return Backbone.Model.extend({

            defaults: {
                DB_NAME: "LinkItDB",
                DB_VERSION: 8,
                DB_LEVELS_STORAGE: "levels",
                DB_USERS_STORAGE: "users",
                DB_USER_ID_KEY: "userId",
                url: "./js/levels.json",
                levelsCount: null,
                db: null
            },

            initDB: function () {
                var dfd = new $.Deferred(),
                    request = window.indexedDB.open(this.get("DB_NAME"), this.get("DB_VERSION")),
                    model = this;

                function safeFallback(db) {
                    db.onversionchange = function (e) {
                        db.close();
                    };
                }

                request.onsuccess = function () {
                    //DB exists and was opened successfully
                    model.set("db", this.result);
                    safeFallback(this.result);

                    model.fetchLevelsCount().then(function (levelsCount) {
                        if (levelsCount < 1) {
                            model.fetchLevels().always(dfd.resolve);
                        } else {
                            dfd.resolve();
                        }
                    }, function () {
                        //fail to get levels amount
                        dfd.reject();
                    });
                };

                request.onerror = function () {
                    //error durin DB opening/creation
                    dfd.reject();
                };

                request.onupgradeneeded = function (e) {
                    var db = this.result,
                        store, userStore;

                    model.set("db", db);

                    model.clearDB([model.get("DB_LEVELS_STORAGE")]);
                    store = db.createObjectStore(model.get("DB_LEVELS_STORAGE"), { keyPath: 'id', autoIncrement: true });

                    if (!_.contains(db.objectStoreNames, model.get("DB_USERS_STORAGE"))) {
                        userStore = db.createObjectStore(model.get("DB_USERS_STORAGE"), { keyPath: 'name' });
                    }

                    store.createIndex("by_index", "index", { unique: true });

                    store.transaction.onerror = function (e) {
                        dfd.reject();
                    };
                };

                return dfd;
            },

            initUser: function (name) {
                var model = this,
                    dfd = new $.Deferred(),
                    db = this.get("db"),
                    userStore;

                userStore = db.transaction(this.get("DB_USERS_STORAGE"), "readonly")
                    .objectStore(this.get("DB_USERS_STORAGE"));

                //TODO: review!!! not working!!!
                userStore.get(name || "");

                userStore.transaction.oncomplete = function (e) {
                    var user = e.target.result,
                        userStore;

                    if (user) {
                        //new UserModel
                        dfd.resolve();
                    } else {
                        userStore = db.transaction(model.get("DB_USERS_STORAGE"), "readwrite")
                            .objectStore(model.get("DB_USERS_STORAGE"));

                        user = model.getDefaultUser();
                        userStore.add(user);

                        userStore.transaction.oncomplete = function (e) {
                            dfd.resolve(new UserModel(user));
                        };
                        userStore.transaction.onerror = function () {
                            dfd.reject();
                        };
                    }
                };
                userStore.transaction.onerror = function () {
                    dfd.reject();
                };

                return dfd;
            },

            getDefaultUser: function () {
                return { name: "user" + _.random(Number.MAX_SAFE_INTEGER), activeLevel: 1 };
            },

            getCurrentUserName: function () {
                return window.localStorage.getItem(this.get("DB_USER_ID_KEY"));
            },

            saveCurrentUserName: function (userId) {
                if (userId && _.isString(userId)) {
                    window.localStorage.setItem(this.get("DB_USER_ID_KEY"), userId);
                }
            },

            getLevel: function (index) {
                var dfd = new $.Deferred(),
                    db = this.get("db"),
                    objectStore, storeIndex;

                if (!_.isNumber(index)) {
                    return dfd.reject();
                }

                objectStore = db.transaction(this.get("DB_LEVELS_STORAGE"), "readonly")
                        .objectStore(this.get("DB_LEVELS_STORAGE"));
                storeIndex = objectStore.index("by_index").get(index);

                storeIndex.onsuccess = function () {
                    dfd.resolve(LevelsPool.get().init(this.result));
                };
                storeIndex.onerror = function () {
                    dfd.reject();
                };

                return dfd;
            },

            fetchLevels: function () {
                var dfd = new $.Deferred(),
                    model = this;

                $.getJSON(this.get("url"))
                    .then(function (data) {
                        if (!data || !_.isArray(data.levels)) {
                            return dfd.reject();
                        }

                        var db = model.get("db"),
                            levelsCount = data.levels.length,
                            levelIdx = 0;

                        function addItem() {
                            if (levelIdx < levelsCount) {
                                $.when(model.loadImages(data.levels[levelIdx])).always(function (level) {
                                    var store = db.transaction(model.get("DB_LEVELS_STORAGE"), "readwrite")
                                        .objectStore(model.get("DB_LEVELS_STORAGE"));

                                    store.transaction.oncomplete = addItem;
                                    store.transaction.onerror = dfd.reject;

                                    store.add(level);
                                    levelIdx++;
                                });
                            } else {
                                model.set("levelsCount", levelsCount);
                                dfd.resolve();
                            }
                        }

                        addItem();
                    }, function (e) {
                        dfd.reject();
                    });

                return dfd;
            },

            loadImages: function (level) {
                var model = this,
                    dfd = new $.Deferred(),
                    imgRequests = [];

                _.forEach(level.basis, function (base) {
                    if (base.dataType === Enum.ItemDataType.IMAGE) {
                        imgRequests.push(model.loadImage(base));
                    }
                });
                _.forEach(level.targets, function (target) {
                    if (target.dataType === Enum.ItemDataType.IMAGE) {
                        imgRequests.push(model.loadImage(target));
                    }
                });

                $.when.apply($, imgRequests).always(_.bind(dfd.resolve, dfd, level));

                return dfd;
            },

            loadImage: function (item) {
                var dfd = new $.Deferred(),
                    xhr = new XMLHttpRequest();

                xhr.open("GET", item.data, true);
                xhr.responseType = "blob";

                xhr.addEventListener("load", function () {
                    if (xhr.readyState === 4) {
                        if (xhr.status === 200) {
                            item.data = xhr.response;
                        }
                        dfd.resolve();
                    }
                }, false);
                xhr.send();

                return dfd;
            },

            getLevelsCount: function () {
                return this.get("levelsCount") || 0;
            },

            getAllLevels: function () {
                var dfd = new $.Deferred(),
                    db = this.get("db"),
                    levels = [],
                    objectStore, objectCursor;

                objectStore = db.transaction(this.get("DB_LEVELS_STORAGE"), "readonly")
                        .objectStore(this.get("DB_LEVELS_STORAGE"));

                objectCursor = objectStore.openCursor();

                objectCursor.onsuccess = function (e) {
                    var cursor = e.target.result,
                        level;

                    if (cursor) {
                        level = cursor.value;
                        levels.push(LevelsPool.get().init(level));
                        cursor.continue();
                    } else {
                        dfd.resolve(levels);
                    }
                };

                objectCursor.onerror = function () {
                    dfd.reject();
                };

                return dfd;
            },

            fetchLevelsCount: function () {
                var dfd = new $.Deferred(),
                    db = this.get("db"),
                    store = db.transaction(this.get("DB_LEVELS_STORAGE"), "readonly")
                        .objectStore(this.get("DB_LEVELS_STORAGE")),
                    count = store.count(),
                    model = this;

                count.onsuccess = function (e) {
                    model.set("levelsCount", this.result || 0);
                    dfd.resolve(this.result);
                };

                count.onerror = function (e) {
                    model.set("levelsCount", null);
                    dfd.reject(null);
                };

                return dfd;
            },

            clearDB: function (stores) {
                var db = this.get("db");

                if (!db) {
                    return;
                }

                _.forEach(stores || db.objectStoreNames, function (storeName) {
                    if (_.contains(db.objectStoreNames, storeName)) {
                        db.deleteObjectStore(storeName);
                    }
                });
            },

            deleteDB: function () {
                var dfd = new $.Deferred(),
                    db = this.get("db"),
                    request;

                if (db) {
                    db.close();
                }

                request = window.indexedDB.deleteDatabase(this.get("DB_NAME"));

                request.onsuccess = dfd.resolve;
                request.onerror = dfd.reject;

                return dfd;
            }

        });
});<commit_msg>Fix user saving;<commit_after>define(["lodash", "backbone", "jquery", "js/models/LevelsPool", "js/enum", "js/models/UserModel"],
    function (_, Backbone, $, LevelsPool, Enum, UserModel) {

        /*
         * General rules:
         * 1. methods started with fetch* are used to fetch data and, probably, save it to inetrnals
         */

        return Backbone.Model.extend({

            defaults: {
                DB_NAME: "LinkItDB",
                DB_VERSION: 8,
                DB_LEVELS_STORAGE: "levels",
                DB_USERS_STORAGE: "users",
                DB_USER_ID_KEY: "userId",
                url: "./js/levels.json",
                levelsCount: null,
                db: null
            },

            initDB: function () {
                var dfd = new $.Deferred(),
                    request = window.indexedDB.open(this.get("DB_NAME"), this.get("DB_VERSION")),
                    model = this;

                function safeFallback(db) {
                    db.onversionchange = function (e) {
                        db.close();
                    };
                }

                request.onsuccess = function () {
                    //DB exists and was opened successfully
                    model.set("db", this.result);
                    safeFallback(this.result);

                    model.fetchLevelsCount().then(function (levelsCount) {
                        if (levelsCount < 1) {
                            model.fetchLevels().always(dfd.resolve);
                        } else {
                            dfd.resolve();
                        }
                    }, function () {
                        //fail to get levels amount
                        dfd.reject();
                    });
                };

                request.onerror = function () {
                    //error durin DB opening/creation
                    dfd.reject();
                };

                request.onupgradeneeded = function (e) {
                    var db = this.result,
                        store, userStore;

                    model.set("db", db);

                    model.clearDB([model.get("DB_LEVELS_STORAGE")]);
                    store = db.createObjectStore(model.get("DB_LEVELS_STORAGE"), { keyPath: 'id', autoIncrement: true });

                    if (!_.contains(db.objectStoreNames, model.get("DB_USERS_STORAGE"))) {
                        userStore = db.createObjectStore(model.get("DB_USERS_STORAGE"), { keyPath: 'name', autoIncrement: true });
                    }

                    store.createIndex("by_index", "index", { unique: true });

                    store.transaction.onerror = function (e) {
                        dfd.reject();
                    };
                };

                return dfd;
            },

            initUser: function (name) {
                var model = this,
                    dfd = new $.Deferred(),
                    db = this.get("db"),
                    userStore, request;

                userStore = db.transaction(this.get("DB_USERS_STORAGE"), "readonly")
                    .objectStore(this.get("DB_USERS_STORAGE"));

                request = userStore.get(name || "");

                request.onerror = function (e) {
                    dfd.reject();
                };

                request.onsuccess = function (e) {
                    var user = e.target.result,
                        userStore;

                    if (user) {
                        dfd.resolve(new UserModel(user));
                    } else {
                        userStore = db.transaction(model.get("DB_USERS_STORAGE"), "readwrite")
                            .objectStore(model.get("DB_USERS_STORAGE"));

                        user = model.getDefaultUser();
                        userStore.add(user);

                        userStore.transaction.oncomplete = function (e) {
                            dfd.resolve(new UserModel(user));
                        };
                        userStore.transaction.onerror = function () {
                            dfd.reject();
                        };
                    }
                };

                return dfd;
            },

            getDefaultUser: function () {
                return { name: "user" + _.random(Number.MAX_SAFE_INTEGER), activeLevel: 1 };
            },

            getCurrentUserName: function () {
                return window.localStorage.getItem(this.get("DB_USER_ID_KEY"));
            },

            saveCurrentUserName: function (userId) {
                if (userId && _.isString(userId)) {
                    window.localStorage.setItem(this.get("DB_USER_ID_KEY"), userId);
                }
            },

            getLevel: function (index) {
                var dfd = new $.Deferred(),
                    db = this.get("db"),
                    objectStore, storeIndex;

                if (!_.isNumber(index)) {
                    return dfd.reject();
                }

                objectStore = db.transaction(this.get("DB_LEVELS_STORAGE"), "readonly")
                        .objectStore(this.get("DB_LEVELS_STORAGE"));
                storeIndex = objectStore.index("by_index").get(index);

                storeIndex.onsuccess = function () {
                    dfd.resolve(LevelsPool.get().init(this.result));
                };
                storeIndex.onerror = function () {
                    dfd.reject();
                };

                return dfd;
            },

            fetchLevels: function () {
                var dfd = new $.Deferred(),
                    model = this;

                $.getJSON(this.get("url"))
                    .then(function (data) {
                        if (!data || !_.isArray(data.levels)) {
                            return dfd.reject();
                        }

                        var db = model.get("db"),
                            levelsCount = data.levels.length,
                            levelIdx = 0;

                        function addItem() {
                            if (levelIdx < levelsCount) {
                                $.when(model.loadImages(data.levels[levelIdx])).always(function (level) {
                                    var store = db.transaction(model.get("DB_LEVELS_STORAGE"), "readwrite")
                                        .objectStore(model.get("DB_LEVELS_STORAGE"));

                                    store.transaction.oncomplete = addItem;
                                    store.transaction.onerror = dfd.reject;

                                    store.add(level);
                                    levelIdx++;
                                });
                            } else {
                                model.set("levelsCount", levelsCount);
                                dfd.resolve();
                            }
                        }

                        addItem();
                    }, function (e) {
                        dfd.reject();
                    });

                return dfd;
            },

            loadImages: function (level) {
                var model = this,
                    dfd = new $.Deferred(),
                    imgRequests = [];

                _.forEach(level.basis, function (base) {
                    if (base.dataType === Enum.ItemDataType.IMAGE) {
                        imgRequests.push(model.loadImage(base));
                    }
                });
                _.forEach(level.targets, function (target) {
                    if (target.dataType === Enum.ItemDataType.IMAGE) {
                        imgRequests.push(model.loadImage(target));
                    }
                });

                $.when.apply($, imgRequests).always(_.bind(dfd.resolve, dfd, level));

                return dfd;
            },

            loadImage: function (item) {
                var dfd = new $.Deferred(),
                    xhr = new XMLHttpRequest();

                xhr.open("GET", item.data, true);
                xhr.responseType = "blob";

                xhr.addEventListener("load", function () {
                    if (xhr.readyState === 4) {
                        if (xhr.status === 200) {
                            item.data = xhr.response;
                        }
                        dfd.resolve();
                    }
                }, false);
                xhr.send();

                return dfd;
            },

            getLevelsCount: function () {
                return this.get("levelsCount") || 0;
            },

            getAllLevels: function () {
                var dfd = new $.Deferred(),
                    db = this.get("db"),
                    levels = [],
                    objectStore, objectCursor;

                objectStore = db.transaction(this.get("DB_LEVELS_STORAGE"), "readonly")
                        .objectStore(this.get("DB_LEVELS_STORAGE"));

                objectCursor = objectStore.openCursor();

                objectCursor.onsuccess = function (e) {
                    var cursor = e.target.result,
                        level;

                    if (cursor) {
                        level = cursor.value;
                        levels.push(LevelsPool.get().init(level));
                        cursor.continue();
                    } else {
                        dfd.resolve(levels);
                    }
                };

                objectCursor.onerror = function () {
                    dfd.reject();
                };

                return dfd;
            },

            fetchLevelsCount: function () {
                var dfd = new $.Deferred(),
                    db = this.get("db"),
                    store = db.transaction(this.get("DB_LEVELS_STORAGE"), "readonly")
                        .objectStore(this.get("DB_LEVELS_STORAGE")),
                    count = store.count(),
                    model = this;

                count.onsuccess = function (e) {
                    model.set("levelsCount", this.result || 0);
                    dfd.resolve(this.result);
                };

                count.onerror = function (e) {
                    model.set("levelsCount", null);
                    dfd.reject(null);
                };

                return dfd;
            },

            clearDB: function (stores) {
                var db = this.get("db");

                if (!db) {
                    return;
                }

                _.forEach(stores || db.objectStoreNames, function (storeName) {
                    if (_.contains(db.objectStoreNames, storeName)) {
                        db.deleteObjectStore(storeName);
                    }
                });
            },

            deleteDB: function () {
                var dfd = new $.Deferred(),
                    db = this.get("db"),
                    request;

                if (db) {
                    db.close();
                }

                request = window.indexedDB.deleteDatabase(this.get("DB_NAME"));

                request.onsuccess = dfd.resolve;
                request.onerror = dfd.reject;

                return dfd;
            }

        });
});<|endoftext|>


<commit_before>/*
 *   Copyright 2012 OSBI Ltd
 *
 *   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.
 */

/**
 * Holds the resultset for a query, and notifies plugins when resultset updated
 */
var Result = Backbone.Model.extend({

    result: null,
    firstRun: false,

    initialize: function(args, options) {
        // Keep reference to query
        this.query = options.query;
    },

    parse: function(response) {
        // Show the UI if hidden
        this.query.workspace.unblock();
        this.query.workspace.processing.hide();
        this.result = response;
        this.query.model = _.extend({}, response.query, this.query.model);
        this.firstRun = true;

        this.query.workspace.trigger('query:result', {
            workspace: this.query.workspace,
            data: response
        });

    },

    hasRun: function() {
        return this.firstRun;
    },

    lastresult: function() {
            return this.result;
    },

    url: function() {
        //return encodeURI(this.query.url() + "/result/" + this.query.getProperty('formatter'));
        return encodeURI(this.query.url() + "/../execute" );
    }
});
<commit_msg>syncing query after result execution<commit_after>/*
 *   Copyright 2012 OSBI Ltd
 *
 *   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.
 */

/**
 * Holds the resultset for a query, and notifies plugins when resultset updated
 */
var Result = Backbone.Model.extend({

    result: null,
    firstRun: false,

    initialize: function(args, options) {
        // Keep reference to query
        this.query = options.query;
    },

    parse: function(response) {
        // Show the UI if hidden
        this.query.workspace.unblock();
        this.query.workspace.processing.hide();
        this.result = response;
        this.query.model = _.extend({}, response.query);
        this.firstRun = true;

        this.query.workspace.trigger('query:result', {
            workspace: this.query.workspace,
            data: response
        });

    },

    hasRun: function() {
        return this.firstRun;
    },

    lastresult: function() {
            return this.result;
    },

    url: function() {
        //return encodeURI(this.query.url() + "/result/" + this.query.getProperty('formatter'));
        return encodeURI(this.query.url() + "/../execute" );
    }
});
<|endoftext|>


<commit_before>/*
 *   Copyright 2012 OSBI Ltd
 *
 *   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.
 */

/**
 * The global toolbar
 */
var Upgrade = Backbone.View.extend({
	tagName: "div",

	events: {
	},

	initialize: function(a, b) {

		this.workspace = a.workspace;

	},

	daydiff: function(first, second) {
		return Math.round((second-first)/(1000*60*60*24));
	},

	render: function() {

		var self = this;
		var license = new License();

		if(Settings.BIPLUGIN5){
			license.fetch_license('api/api/license', function (opt) {
				if(Saiku.session.get("notice") != undefined && Saiku.session.get("notice")!=null && Saiku.session.get("notice")!=""){
					$(self.workspace.el).find('.upgrade').append("

Notice:"+Saiku.session.get("notice")+"
");

				}
				if (opt.status !== 'error' && opt.data.get("licenseType") != "trial") {
					return this;
				}
				else if(opt.status !== 'error' && opt.data.get("licenseType") === "trial"){
					var yourEpoch = parseFloat(opt.data.get("expiration"));
					var yourDate = new Date(yourEpoch);
					self.remainingdays = self.daydiff(new Date(), yourDate);

					$(self.workspace.el).find('.upgrade').append("

You are using a Saiku Enterprise Trial license, you have "+ self.remainingdays+" days remaining. Buy licenses online.
");
					return self;
				}
				else {
					$(self.workspace.el).find('.upgrade').append("

You are using Saiku Community Edition, please consider upgrading to Saiku Enterprise, or entering a sponsorship agreement with us to support development. " +
						"Or contribute by joining our community and helping other users!

");
					return self;
				}
			});
		}
		else {
			license.fetch_license('api/license/', function (opt) {
				if(Saiku.session.get("notice") != undefined && Saiku.session.get("notice")!=null && Saiku.session.get("notice")!=""){
					$(self.workspace.el).find('.upgrade').append("

Notice:"+Saiku.session.get("notice")+"
");

				}
				if (opt.status !== 'error' && opt.data.get("licenseType") != "trial") {
					return this;
				}
				else if(opt.status !== 'error' && opt.data.get("licenseType") === "trial"){
					var yourEpoch = parseFloat(opt.data.get("expiration"));
					var yourDate = new Date(yourEpoch);

					self.remainingdays = self.daydiff(new Date(), yourDate);

					$(self.workspace.el).find('.upgrade').append("

You are using a Saiku Enterprise Trial license, you have "+ self.remainingdays+" days remaining. Buy licenses online.
");
					return self;
				}
				else {
					$(self.workspace.el).find('.upgrade').append("

You are using Saiku Community Edition, please consider upgrading to Saiku Enterprise, or entering a sponsorship agreement with us to support development. " +
						"Or contribute by joining our community and helping other users!

");
					return self;
				}
			});
		}

	},

	call: function(e) {
	}

});
<commit_msg>fix upgrade bar<commit_after>/*
 *   Copyright 2012 OSBI Ltd
 *
 *   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.
 */

/**
 * The global toolbar
 */
var Upgrade = Backbone.View.extend({
	tagName: "div",

	events: {
	},

	initialize: function(a, b) {

		this.workspace = a.workspace;

	},

	daydiff: function(first, second) {
		return Math.round((second-first)/(1000*60*60*24));
	},

	render: function() {

		var self = this;
		var license = new License();

		if(Settings.BIPLUGIN5){
				if(Saiku.session.get("notice") != undefined && Saiku.session.get("notice")!=null && Saiku.session.get("notice")!=""){
					$(self.workspace.el).find('.upgrade').append("

Notice:"+Saiku.session.get("notice")+"
");

				}
				if (Settings.LICENSE.licenseType != "trial" && Settings.LICENSE.licenceType != "Open Source License") {
					return this;
				}
				if (Settings.LICENSE.licenseType === "trial" && Settings.LICENSE.licenceType === "Open Source" +
					" License") {
					var yourEpoch = parseFloat(opt.data.get("expiration"));
					var yourDate = new Date(yourEpoch);
					self.remainingdays = self.daydiff(new Date(), yourDate);

					$(self.workspace.el).find('.upgrade').append("

You are using a Saiku Enterprise Trial license, you have "+ self.remainingdays+" days remaining. Buy licenses online.
");
					return self;
				}
				else {
					$(self.workspace.el).find('.upgrade').append("

You are using Saiku Community Edition, please consider upgrading to Saiku Enterprise, or entering a sponsorship agreement with us to support development. " +
						"Or contribute by joining our community and helping other users!

");
					return self;
				}
		}
		else {
				if(Saiku.session.get("notice") != undefined && Saiku.session.get("notice")!=null && Saiku.session.get("notice")!=""){
					$(self.workspace.el).find('.upgrade').append("

Notice:"+Saiku.session.get("notice")+"
");

				}
				if (Settings.LICENSE.licenseType != "trial" && Settings.LICENSE.licenceType != "Open Source License") {
					return this;
				}
			if (Settings.LICENSE.licenseType === "trial" && Settings.LICENSE.licenceType === "Open Source" +
				" License") {
					var yourEpoch = parseFloat(opt.data.get("expiration"));
					var yourDate = new Date(yourEpoch);

					self.remainingdays = self.daydiff(new Date(), yourDate);

					$(self.workspace.el).find('.upgrade').append("

You are using a Saiku Enterprise Trial license, you have "+ self.remainingdays+" days remaining. Buy licenses online.
");
					return self;
				}
				else {
					$(self.workspace.el).find('.upgrade').append("

You are using Saiku Community Edition, please consider upgrading to Saiku Enterprise, or entering a sponsorship agreement with us to support development. " +
						"Or contribute by joining our community and helping other users!

");
					return self;
				}
		}

	},

	call: function(e) {
	}

});
<|endoftext|>


<commit_before>/*global pulse, app, jQuery, require, document, esri, esriuk, Handlebars, console, $, mynearest, window, alert, unescape, define */

/*
 | Copyright 2015 ESRI (UK) Limited
 |
 | 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.
 */
/**
 * Execute the Query Task to a Layer
 */
define(["dojo/Deferred", "esri/layers/FeatureLayer", "esri/renderers/jsonUtils", "esri/tasks/query", "esri/tasks/QueryTask", "esri/geometry/Circle", "esri/units"],
    function (Deferred, FeatureLayer, jsonUtils, Query, QueryTask, Circle, Units) {
    var taskOutput = function LayerInfoTask(props) {
        this.properties = props;

        this.getLayerInfo = function () {
            var _this = this, result = new Deferred(), featureLayer;

            // Need to also get the symbology for each layer
            featureLayer = new FeatureLayer(_this.properties.serviceUrl);

            featureLayer.on("error", function (err) {
                result.resolve({ id: _this.properties.layerId, layerInfo: null, results:null, error: err, itemId: _this.properties.itemId });
            });
            featureLayer.on("load", function (data) {
                var layerInf = { renderer: null, id: _this.properties.layerId, itemId: _this.properties.itemId, opacity: _this.properties.layerOpacity };

                if (props.layerRenderer !== undefined && props.layerRenderer !== null) {
                    layerInf.renderer = jsonUtils.fromJson(props.layerRenderer);
                }
                else {
                    layerInf.renderer = data.layer.renderer;
                }

                _this.queryLayer(data.layer.maxRecordCount).then(function (res) {
                    result.resolve({ id: _this.properties.layerId, layerInfo: layerInf, results: res.results, error: null, itemId: _this.properties.itemId, url: _this.properties.serviceUrl });
                });
            });

            return result.promise;
        };

        this.getUnits = function (distanceUnits) {
            switch (distanceUnits) {
                case "m":
                    return Units.MILES;

                case "km":
                    return Units.KILOMETERS

                case "me":
                    return Units.METERS

                default:
                    return Units.MILES;
            }
        };

        this.queryLayer = function (maxRecords) {
            var _this = this, result = new Deferred(), query, queryTask;

            // Use the current location and buffer the point to create a search radius
            query = new Query();
            queryTask = new QueryTask(_this.properties.serviceUrl);

            query.where = "1=1"; // Get everything
            query.geometry = new Circle({
                center: [_this.properties.currentPoint.x, _this.properties.currentPoint.y],
                geodesic: true,
                radius: _this.properties.searchRadius,
                radiusUnit: _this.getUnits(_this.properties.distanceUnits)
            });
            query.outFields = ["*"];
            query.returnGeometry = true;
            query.outSpatialReference = _this.properties.currentPoint.spatialReference;
            query.num = maxRecords || 1000;

            queryTask.execute(query, function (features) {
                result.resolve({ error: null, id: _this.properties.layerId, results: features, itemId: _this.properties.itemId});
            },
            function (error) {
                result.resolve({ error: error, id: _this.properties.layerId, results: null, itemId: _this.properties.itemId });
            });

            return result.promise;
        };

        this.execute = function () {
            return this.getLayerInfo();
        };
    };

    return taskOutput;
});<commit_msg>Fix for Zero Search Radius<commit_after>/*global pulse, app, jQuery, require, document, esri, esriuk, Handlebars, console, $, mynearest, window, alert, unescape, define */

/*
 | Copyright 2015 ESRI (UK) Limited
 |
 | 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.
 */
/**
 * Execute the Query Task to a Layer
 */
define(["dojo/Deferred", "esri/layers/FeatureLayer", "esri/renderers/jsonUtils", "esri/tasks/query", "esri/tasks/QueryTask", "esri/geometry/Circle", "esri/units"],
    function (Deferred, FeatureLayer, jsonUtils, Query, QueryTask, Circle, Units) {
    var taskOutput = function LayerInfoTask(props) {
        this.properties = props;

        this.getLayerInfo = function () {
            var _this = this, result = new Deferred(), featureLayer;

            // Need to also get the symbology for each layer
            featureLayer = new FeatureLayer(_this.properties.serviceUrl);

            featureLayer.on("error", function (err) {
                result.resolve({ id: _this.properties.layerId, layerInfo: null, results:null, error: err, itemId: _this.properties.itemId });
            });
            featureLayer.on("load", function (data) {
                var layerInf = { renderer: null, id: _this.properties.layerId, itemId: _this.properties.itemId, opacity: _this.properties.layerOpacity };

                if (props.layerRenderer !== undefined && props.layerRenderer !== null) {
                    layerInf.renderer = jsonUtils.fromJson(props.layerRenderer);
                }
                else {
                    layerInf.renderer = data.layer.renderer;
                }

                _this.queryLayer(data.layer.maxRecordCount).then(function (res) {
                    result.resolve({ id: _this.properties.layerId, layerInfo: layerInf, results: res.results, error: null, itemId: _this.properties.itemId, url: _this.properties.serviceUrl });
                });
            });

            return result.promise;
        };

        this.getUnits = function (distanceUnits) {
            switch (distanceUnits) {
                case "m":
                    return Units.MILES;

                case "km":
                    return Units.KILOMETERS;

                case "me":
                    return Units.METERS;

                default:
                    return Units.MILES;
            }
        };

        this.queryLayer = function (maxRecords) {
            var _this = this, result = new Deferred(), query, queryTask, geom;

            if (_this.properties.searchRadius > 0) {
                geom = new Circle({
                    center: [_this.properties.currentPoint.x, _this.properties.currentPoint.y],
                    geodesic: true,
                    radius: _this.properties.searchRadius,
                    radiusUnit: _this.getUnits(_this.properties.distanceUnits)
                });
            }
            else {
                geom = _this.properties.currentPoint;
            }

            // Use the current location and buffer the point to create a search radius
            query = new Query();
            queryTask = new QueryTask(_this.properties.serviceUrl);

            query.where = "1=1"; // Get everything
            query.geometry = geom;
            query.outFields = ["*"];
            query.returnGeometry = true;
            query.outSpatialReference = _this.properties.currentPoint.spatialReference;
            query.num = maxRecords || 1000;

            queryTask.execute(query, function (features) {
                result.resolve({ error: null, id: _this.properties.layerId, results: features, itemId: _this.properties.itemId});
            },
            function (error) {
                result.resolve({ error: error, id: _this.properties.layerId, results: null, itemId: _this.properties.itemId });
            });

            return result.promise;
        };

        this.execute = function () {
            return this.getLayerInfo();
        };
    };

    return taskOutput;
});<|endoftext|>


<commit_before>#!/usr/bin/env node
/*eslint no-console:0*/

var readcommand = require('readcommand');
var ora = require('ora');
var logSymbols = require('log-symbols');
var typeOf = require('type-of');
var valUrl    = require('valid-url');
var prettyjson = require('prettyjson');
var Promise = require('rsvp').Promise;
var colors = require('colors/safe');
var client = require('../index');

var argv = require('yargs')
.usage('Usage: chhc <url> [options]')
.demand(1)
.options({
  p: {
    alias: 'proxy',
    demand: false,
    describe: 'Proxy server address:port',
    type: 'string'
  }
})
.example('chhc http://foo/bar')
.example('chhc http://foo/bar --proxy http://proxy.server:2694/')
.version(function () {
  return require('../package.json').version;
})
.alias('v', 'version')
.help('h')
.alias('h', 'help')
.locale('en')
.argv;

var showData = function (data) {
  console.info(prettyjson.render(data));
};

var showSuccess = function () {
  var args = Array.prototype.slice.call(arguments);
  args.unshift(logSymbols.success);
  console.info.apply(console, args);
};

var showError = function (err) {
  console.error(logSymbols.error, String(err));
};

var commands = {
  help: {
    description: 'Show help',
    exec: function (args, location) {
      console.info(Object.keys(commands).map(function (com) {
        var c = commands[com];
        var p = colors.yellow((c.params || []).join(' '));
        return com + ' ' + p + '\n  ' + colors.gray(c.description);
      }).join('\n'));
    }
  },
  exit: {
    description: 'Exit chhc',
    exec: function (args, location) {
      console.info('bye\n');
      process.exit();
    }
  },
  setting: {
    description: 'Show current settings',
    exec: function (args, location) {
      var settings = {};
      Object.keys(client)
      .filter(function (prop) { return (commands[prop]); })
      .forEach(function (prop) { settings[prop] = client[prop]; });
      showData(settings);
    }
  },
  response: {
    description: 'Show response info',
    exec: function (args, location) {
      var res = location.response;
      showData({
        headers: res.headers,
        cookies: res.cookies
      });
    }
  }
};

Object.keys(client).forEach(function (prop) {
  var type = typeOf(client[prop]);
  if (type === 'number' || prop === 'maxDataSize') {
    commands[prop] = {
      description: 'Set ' + prop + ' property',
      params: [ '<number>' ],
      exec: function (args, $, res, body) {
        client.set(prop, parseInt(args[0], 10));
        showSuccess(
          'changed', colors.magenta(prop),
          'property to', colors.red(client[prop])
        );
      }
    };
  }
  if (type === 'boolean') {
    commands[prop] = {
      description: 'Toggle ' + prop + ' property',
      exec: function (args, $, res, body) {
        client.set(prop, ! client[prop]);
        showSuccess(
          'changed', colors.magenta(prop),
          'property to', colors.red(client[prop])
        );
      }
    };
  }
});

/*
<URL>
  fetch URL [params]
  ex)
    http://hoge.fuga/
    http://foo.bar/ a=hoge b="あいうえお かきくけこ"

$(...)
  show element info
  ex)
    $('title')

$(...).<method>([option])
  exec cheerio method
  ex)
    $('#menu').children()
    $('form').eq(0).fields()

<method>
  exec cheerio method(current element)
  ex)
    click()
    submit({ q: 'what is it' })
    val('hello world!')

open
  open current page in browser

log
  show command log

> <filename>
  output previous command result to file(JSON fromat)
  ex)
    > links.json
*/

var fetch = function (url, params) {
  var spinner = ora('fetch ' + url);
  spinner.start();
  return client.fetch(url)
  .then(function (result) {
    spinner.succeed('ready');
    return result;
  })
  .catch(function (err) {
    spinner.fail(err.message);
    throw new Error(err);
  });
};

var repl = function (init) {
  var location = init;

  readcommand.loop({
    ps1: function () {
      return [
        '',
        colors.cyan(location.$.documentInfo().url),
        colors.green('》')
      ].join('\n');
    }
  }, function (err, args, str, next) {
    if (err && err.code !== 'SIGINT') {
      console.error(colors.red(err.message));
      return next();
    }

    // eslint-disable-next-line eqeqeq, no-eq-null
    if (str == null) {
      return commands.exit.exec();
    }

    var matches = Object.keys(commands).filter(function (com) {
      return (com.indexOf(args[0]) === 0);
    });
    if (matches.length === 1) {
      args.shift();
      var ret = commands[matches[0]].exec(args, location);
      if (ret instanceof Promise) {
        return ret.catch(showError).finally(next);
      }
      return next();
    }

    if (valUrl.isUri(args[0])) {
      fetch(args[0]).then(function (result) {
        location = result;
      }).finally(next);
      return null;
    }

    console.info(logSymbols.warning, 'no such command');
    return next();
  });
};

if (argv.proxy) process.env.HTTP_PROXY = argv.proxy;
var startUrl = argv._[0];
if (! /:\/\//.test(startUrl)) {
  startUrl = 'http://' + startUrl;
}

fetch(startUrl).then(repl).catch(process.exit);
<commit_msg>chhc特殊コマンド実装(WIP)<commit_after>#!/usr/bin/env node
/*eslint no-console:0, no-underscore-dangle:0*/

var readcommand = require('readcommand');
var ora = require('ora');
var logSymbols = require('log-symbols');
var typeOf = require('type-of');
var valUrl    = require('valid-url');
var prettyjson = require('prettyjson');
var Promise = require('rsvp').Promise;
var colors = require('colors/safe');
var client = require('../index');

var argv = require('yargs')
.usage('Usage: chhc <url> [options]')
.demand(1)
.options({
  p: {
    alias: 'proxy',
    demand: false,
    describe: 'Proxy server address:port',
    type: 'string'
  }
})
.example('chhc http://foo/bar')
.example('chhc http://foo/bar --proxy http://proxy.server:2694/')
.version(function () {
  return require('../package.json').version;
})
.alias('v', 'version')
.help('h')
.alias('h', 'help')
.locale('en')
.argv;

var showData = function (data) {
  console.info(prettyjson.render(data));
};

var showSuccess = function () {
  var args = Array.prototype.slice.call(arguments);
  args.unshift(logSymbols.success);
  console.info.apply(console, args);
};

var showError = function (err) {
  console.error(logSymbols.error, String(err));
};

var showElementInfo = function ($, $el) {
  showData($el.map(function (i, el) {
    var dom = $(el).get(0);
    return {
      tagName: dom.name,
      attributes: dom.attribs,
      outerHTML: $.html($(el))
    };
  }).get());
};

var commands = {
  help: {
    description: 'Show help',
    exec: function (args, location) {
      console.info(Object.keys(commands).map(function (com) {
        var c = commands[com];
        var p = colors.yellow((c.params || []).join(' '));
        var lines = [
          com + ' ' + p,
          '  ' + colors.gray(c.description)
        ];
        if (c.examples) {
          lines = lines.concat([
            '  ' + colors.cyan('ex)'),
            '    ' + colors.cyan(c.examples.join('    '))
          ]);
        }
        return lines.join('\n');
      }).join('\n\n'));
    }
  },
  exit: {
    description: 'Exit chhc',
    exec: function (args, location) {
      console.info('bye\n');
      process.exit();
    }
  },
  setting: {
    description: 'Show current settings',
    exec: function (args, location) {
      var settings = {};
      Object.keys(client)
      .filter(function (prop) { return (commands[prop]); })
      .forEach(function (prop) { settings[prop] = client[prop]; });
      showData(settings);
    }
  },
  response: {
    description: 'Show response info',
    exec: function (args, location) {
      var res = location.response;
      showData({
        headers: res.headers,
        cookies: res.cookies
      });
    }
  },
  $: {
    description: 'Show element info',
    examples: [
      '$ #contents > .entry a[href*=hoge]'
    ],
    exec: function (args, location) {
      var $ = location.$;
      location._selector = args.join(' ');
      var $result = $(location._selector);
      location._$target = $result;
      showElementInfo($, $result);
    }
  },
  '.': {
    description: 'Execute cheerio method of current element',
    examples: [
      '. text',
      '. attr src',
      '. click'
    ],
    exec: function (args, location) {
      var $el = location._$target;
      if (! $el) return;
      var method = args.shift();
      var result = $el[method].apply($el, args);
      if (result.cheerio === '[cheerio object]') {
        showElementInfo(location.$, result);
      } else {
        console.info(result);
      }
    }
  }
};

Object.keys(client).forEach(function (prop) {
  var type = typeOf(client[prop]);
  if (type === 'number' || prop === 'maxDataSize') {
    commands[prop] = {
      description: 'Set ' + prop + ' property',
      params: [ '<number>' ],
      exec: function (args, $, res, body) {
        client.set(prop, parseInt(args[0], 10));
        showSuccess(
          'changed', colors.magenta(prop),
          'property to', colors.red(client[prop])
        );
      }
    };
  }
  if (type === 'boolean') {
    commands[prop] = {
      description: 'Toggle ' + prop + ' property',
      exec: function (args, $, res, body) {
        client.set(prop, ! client[prop]);
        showSuccess(
          'changed', colors.magenta(prop),
          'property to', colors.red(client[prop])
        );
      }
    };
  }
});

/*
<URL>
  fetch URL [params]
  ex)
    http://hoge.fuga/
    http://foo.bar/ a=hoge b="あいうえお かきくけこ"

$(...).<method>([option])
  exec cheerio method
  ex)
    $('#menu').children()
    $('form').eq(0).fields()

<method>
  exec cheerio method(current element)
  ex)
    click()
    submit({ q: 'what is it' })
    val('hello world!')

open
  open current page in browser

log
  show command log

> <filename>
  output previous command result to file(JSON fromat)
  ex)
    > links.json
*/
var normalizeUrl = function (url) {
  if (/:\/\//.test(url)) {
    return url;
  }
  if (/.+\.\w{2,}$/.test(url)) {
    url = 'http://' + url;
  }
  return url;
};

var fetch = function (url, params) {
  var spinner = ora('fetch ' + url);
  spinner.start();
  return client.fetch(url)
  .then(function (result) {
    spinner.succeed('ready');
    return result;
  })
  .catch(function (err) {
    spinner.fail(err.message);
    throw new Error(err);
  });
};

var repl = function (init) {
  var location = init;
  var prompt = function (next) {
    console.info('\n' + colors.blue(location.$.documentInfo().url));
    // eslint-disable-next-line callback-return
    if (next) next();
  };
  prompt();

  readcommand.loop({
    ps1: function () {
      var target = '';
      if (location._selector) {
        target = "$('" + location._selector + "')[" + location._$target.length + '] ';
      }
      return colors.yellow(target) + colors.green('》');
    }
  }, function (err, args, str, next) {
    if (err && err.code !== 'SIGINT') {
      console.error(colors.red(err.message));
      return prompt(next);
    }

    // eslint-disable-next-line eqeqeq, no-eq-null
    if (str == null) {
      return commands.exit.exec();
    }

    var matches = Object.keys(commands).filter(function (com) {
      return (com.indexOf(args[0]) === 0);
    });
    if (matches.length === 1) {
      // 基本コマンドに該当
      args.shift();
      var ret = commands[matches[0]].exec(args, location);
      if (ret instanceof Promise) {
        return ret.catch(showError).finally(function () {
          prompt(next);
        });
      }
      return prompt(next);
    }

    // 特殊コマンド: URL => fetch
    var checkUrl = normalizeUrl(args[0]);
    if (valUrl.isUri(checkUrl)) {
      fetch(checkUrl).then(function (result) {
        location = result;
      }).finally(function () { prompt(next); });
      return null;
    }

    console.info(logSymbols.warning, 'no such command');
    return prompt(next);
  });
};

if (argv.proxy) process.env.HTTP_PROXY = argv.proxy;
fetch(normalizeUrl(argv._[0])).then(repl).catch(process.exit);
<|endoftext|>


<commit_before>/*
Copyright (C) 2015 Sam Parkinson

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

window.platform = {
    android: /Android/i.test(navigator.userAgent),
    FF:      /Firefox/i.test(navigator.userAgent),
    mobile:  /Mobi/i   .test(navigator.userAgent),
    tablet:  /Tablet/i .test(navigator.userAgent)
};

platform.androidWebkit = platform.android && !platform.FF;
platform.FFOS = platform.FF
            && (platform.mobile || platform.tablet)
            && !platform.android;
console.log('On platform: ', platform);

window.platformColor = {
    blockText: '#282828',
    paletteColors: {
        'widgets': ['#7CD622', '#57AD02', '#77C428', '#B4EB7D'],
        'pitch': ['#7CD622', '#57AD02', '#77C428', '#B4EB7D'],
        'rhythm': ['#FE994F', '#E86B0E', '#FF8B2D', '#FEC092'],
        'meter': ['#FE994F', '#E86B0E', '#FF8B2D', '#FEC092'],
        'tone': ['#3EDCDD', '#1DBCBD', '#25C3C0', '#A1EEEF'],
        'ornament': ['#3EDCDD', '#1DBCBD', '#25C3C0', '#A1EEEF'],
        'intervals': ['#7CD622', '#57AD02', '#77C428', '#B4EB7D'],
        'volume': ['#3EDCDD', '#1DBCBD', '#25C3C0', '#A1EEEF'],
        'drum': ['#3EDCDD', '#1DBCBD', '#25C3C0', '#A1EEEF'],
        'graphics': ['#92A9FF', '#5370DC', '#728FF9', '#CDD8FF'],
        'pen': ['#92A9FF', '#5370DC', '#728FF9', '#CDD8FF'],
        'boxes': ['#FFBF00', '#DAAF30', '#DAA926', '#FFE391'],
        'action': ['#FFBF00', '#DAAF30', '#DAA926', '#FFE391'],
        'media': ['#FF664B', '#EA4326', '#FF5942', '#FFB9E2'],
        'number': ['#FF6EA1', '#FF2C76', '#FF5293', '#FFCDDF'],
        'boolean': ['#D97DF5', '#B653D3', '#C96DF3', '#EDC6A3'],
        'flow': ['#D98A43', '#B7651A', '#D68136', '#ECC6A4'],
        'sensors': ['#FF664B', '#EA4326', '#FF5942', '#FFB9E2'],
        'extras': ['#C4C4C4', '#A0A0A0', '#B0B0B0', '#D0D0D0'],
        'myblocks': ['#C4C4C4', '#A0A0A0', '#B0B0B0', '#D0D0D0'],
        'heap': ['#D98A43', '#B7651A', '#D68136', '#ECC6A4'],
        'ensemble': ['#92A9FF', '#5370DC', '#728FF9', '#CDD8FF'],
    },

    disconnected: '#C4C4C4',  // disconnected block color
    header: platform.FF? '#4DA6FF' : '#4DA6FF',
    aux: '#1A8CFF',
    sub: '#8CC6FF',
    doHeaderShadow: !platform.FF,
    rule: '#E2E2E2',
    ruleColor: '#E2E2E2',
    trashColor: '#C0C0C0',
    trashBorder: '#808080',
    trashActive: '#FF0000',
    background: '#F9F9F9',
    paletteSelected: '#F3F3F3',
    paletteBackground: '#FFFFFF',
    paletteText: '#666666',
    selectorBackground: '#8CC6FF',
    selectorSelected: '#1A8CFF',
    labelColor: '#90c100',
    tupletBackground: '#57e751',
    rhythmcellcolor: '#c8c8c8'
};

document.querySelector('meta[name=theme-color]')
        .content = platformColor.header;

function showButtonHighlight(x, y, r, event, scale, stage) {
    if (platform.FFOS) return {};
    return showMaterialHighlight(x, y, r, event, scale, stage);
};
<commit_msg>Update platformstyle.js<commit_after>/*
Copyright (C) 2015 Sam Parkinson

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

window.platform = {
    android: /Android/i.test(navigator.userAgent),
    FF:      /Firefox/i.test(navigator.userAgent),
    mobile:  /Mobi/i   .test(navigator.userAgent),
    tablet:  /Tablet/i .test(navigator.userAgent)
};

platform.androidWebkit = platform.android && !platform.FF;
platform.FFOS = platform.FF
            && (platform.mobile || platform.tablet)
            && !platform.android;
console.log('On platform: ', platform);

window.platformColor = {
    blockText: '#282828',
    paletteColors: {
        'widgets': ['#7CD622', '#57AD02', '#77C428', '#B4EB7D'],
        'pitch': ['#7CD622', '#57AD02', '#77C428', '#B4EB7D'],
        'rhythm': ['#FE994F', '#E86B0E', '#FF8B2D', '#FEC092'],
        'meter': ['#FE994F', '#E86B0E', '#FF8B2D', '#FEC092'],
        'tone': ['#3EDCDD', '#1DBCBD', '#25C3C0', '#A1EEEF'],
        'ornament': ['#3EDCDD', '#1DBCBD', '#25C3C0', '#A1EEEF'],
        'intervals': ['#7CD622', '#57AD02', '#77C428', '#B4EB7D'],
        'volume': ['#3EDCDD', '#1DBCBD', '#25C3C0', '#A1EEEF'],
        'drum': ['#3EDCDD', '#1DBCBD', '#25C3C0', '#A1EEEF'],
        'graphics': ['#92A9FF', '#5370DC', '#728FF9', '#CDD8FF'],
        'pen': ['#92A9FF', '#5370DC', '#728FF9', '#CDD8FF'],
        'boxes': ['#FFBF00', '#DAAF30', '#DAA926', '#FFE391'],
        'action': ['#FFBF00', '#DAAF30', '#DAA926', '#FFE391'],
        'media': ['#FF664B', '#EA4326', '#FF5942', '#FFB9E2'],
        'number': ['#FF6EA1', '#FF2C76', '#FF5293', '#FFCDDF'],
        'boolean': ['#D97DF5', '#B653D3', '#C96DF3', '#EDC6A3'],
        'flow': ['#D98A43', '#B7651A', '#D68136', '#ECC6A4'],
        'sensors': ['#FF664B', '#EA4326', '#FF5942', '#FFB9E2'],
        'extras': ['#C4C4C4', '#A0A0A0', '#B0B0B0', '#D0D0D0'],
        'myblocks': ['#C4C4C4', '#A0A0A0', '#B0B0B0', '#D0D0D0'],
        'heap': ['#D98A43', '#B7651A', '#D68136', '#ECC6A4'],
        'ensemble': ['#92A9FF', '#5370DC', '#728FF9', '#CDD8FF'],
    },

    disconnected: '#C4C4C4',  // disconnected block color
    header: platform.FF? '#4DA6FF' : '#4DA6FF',
    aux: '#1A8CFF',
    sub: '#8CC6FF',
    doHeaderShadow: !platform.FF,
    rule: '#E2E2E2',
    ruleColor: '#E2E2E2',
    trashColor: '#C0C0C0',
    trashBorder: '#808080',
    trashActive: '#FF0000',
    background: '#F9F9F9',
    paletteSelected: '#F3F3F3',
    paletteBackground: '#FFFFFF',
    paletteText: '#666666',
    selectorBackground: '#8CC6FF',
    selectorSelected: '#1A8CFF',
    labelColor: '#90c100',
    tupletBackground: '#57e751',
    rhythmcellcolor: '#c8c8c8',
	hitAreaGraphicsBeginFill: '#FFF',
	piemenuBasic: ['#3ea4a3', '#60bfbc', '#1d8989', '#60bfbc', '#1d8989'],
	pitchWheelcolors: ['#77c428', '#93e042', '#77c428', '#5ba900', '#77c428', '#93e042', '#adfd55'],
	exitWheelcolors: ['#808080', '#c0c0c0'],
	accidentalsWheelcolors: ['#77c428', '#93e042', '#77c428', '#5ba900', '#77c428'],
	accidentalsWheelcolorspush: '#c0c0c0',
	octavesWheelcolors: ['#ffb2bc', '#ffccd6', '#ffb2bc', '#ffccd6', '#ffb2bc', '#ffccd6', '#ffb2bc', '#ffccd6', '#c0c0c0', '#c0c0c0', '#c0c0c0', '#c0c0c0', '#c0c0c0', '#c0c0c0'],
	noteValueWheelcolors: ['#ffb2bc', '#ffccd6'],
	tabsWheelcolors: ['#ffb2bc', '#ffccd6'],
	numberWheelcolors: ['#ffb2bc', '#ffccd6'],
	piemenuBasicundefined: ['#77c428', '#93e042', '#5ba900'],
	booleanWheelcolors: ['#d3cf76', '#b8b45f'],
	piemenuVoicesColors: ['#3ea4a3', '#60bfbc', '#1d8989', '#60bfbc', '#1d8989'],
	intervalNameWheelcolors: ['#77c428', '#93e042', '#77c428', '#5ba900', '#93e042'],
	intervalWheelcolors: ['#77c428', '#93e042', '#77c428', '#5ba900', '#93e042'],
	modeWheelcolors: ['#77c428', '#93e042'],
	modeGroupWheelcolors: ['#ffb2bc', '#ffccd6', '#ffb2bc', '#ffccd6', '#ffb2bc', '#ffccd6', '#ffb2bc', '#ffccd6', '#c0c0c0', '#c0c0c0', '#c0c0c0', '#c0c0c0', '#c0c0c0', '#c0c0c0'],
	modePieMenusIfColorPush: '#4b8b0e',
	modePieMenusElseColorPush: '#66a62d',
	wheelcolors: ['#808080', '#909090', '#808080', '#909090', '#707070'],
};

document.querySelector('meta[name=theme-color]')
        .content = platformColor.header;

function showButtonHighlight(x, y, r, event, scale, stage) {
    if (platform.FFOS) return {};
    return showMaterialHighlight(x, y, r, event, scale, stage);
};
<|endoftext|>


<commit_before>
const copyAssets = require("./copy-assets")
const copyModules = require("./copy-modules")
const minimist = require("minimist");
const fs = require("fs");
const chalk = require("chalk");

const args = minimist(process.argv.slice(1), {
  string: ["mc"],
  boolean: ["watch", "symlink", "assets"]
});

const mc = args.mc || "./firefox";
const watch = args.watch;
const symlink = args.symlink;
const assets = args.assets

console.log(`Copying Files to ${mc} with params: `, {watch, assets, symlink})

async function start() {
  if (fs.existsSync(mc)) {
    try {
      await copyAssets({ assets, mc, watch, symlink})
      await copyModules.run({ mc, watch })
    } catch (e) {
      console.error(e);
      if (e.code === "ENOENT") {
        missingFilesErrorMessage();
      }
    }
  } else {
    missingFilesErrorMessage();
  }
}

function missingFilesErrorMessage() {
  let errorMessage = [
    'It looks like you are missing some files. The mozilla-central ',
    'codebase may be missing at ${mc}. You can clone mozilla-central by ',
    'running \`./bin/prepare-mochitests-dev\` from the root of the ',
    'debugger.html repository. You can find more information on bundling ',
    'or mochitests at ',
    'https://github.com/devtools-html/debugger.html/blob/master/docs/bundling.md or ',
    'https://github.com/devtools-html/debugger.html/blob/master/docs/mochitests.md'
  ].join('');

  console.warn(chalk.yellow(errorMessage));
}

start();
<commit_msg>Copy commits individually (#7486)<commit_after>
/*
 * copy files to mc
 * node ./bin/copy --mc ../gecko-dev
 *
 * copy files per commit
 * node ./bin/copy --mc ../gecko-dev --sha 123
 *
 * copy files per commit with a message
 * node ./bin/copy --mc ../gecko-dev --sha 123 --message "bug 123 (release 106) __message__.r=dwalsh"
 */

const copyAssets = require("./copy-assets")
const copyModules = require("./copy-modules")
const minimist = require("minimist");
const fs = require("fs");
const chalk = require("chalk");
const shell = require("shelljs");
const path = require("path")

const args = minimist(process.argv.slice(1), {
  string: ["mc", "sha", "message"],
  boolean: ["watch", "symlink", "assets"]
});

const mc = args.mc || "./firefox";
const watch = args.watch;
const symlink = args.symlink;
const assets = args.assets
const sha = args.sha
const message = args.message || ""

const mcPath = path.join(__dirname, mc)

async function copy({assets, mc, watch, symlink}) {
  if (fs.existsSync(mc)) {
    try {
      await copyAssets({ assets, mc, watch, symlink})
      await copyModules.run({ mc, watch })
    } catch (e) {
      console.error(e);
      if (e.code === "ENOENT") {
        missingFilesErrorMessage();
      }
    }
  } else {
    missingFilesErrorMessage();
  }
}

async function start() {
  console.log(`Copying Files to ${mc} with params: `, {watch, assets, symlink})
  return copy()
}

function missingFilesErrorMessage() {
  let errorMessage = [
    'It looks like you are missing some files. The mozilla-central ',
    'codebase may be missing at ${mc}. You can clone mozilla-central by ',
    'running \`./bin/prepare-mochitests-dev\` from the root of the ',
    'debugger.html repository. You can find more information on bundling ',
    'or mochitests at ',
    'https://github.com/devtools-html/debugger.html/blob/master/docs/bundling.md or ',
    'https://github.com/devtools-html/debugger.html/blob/master/docs/mochitests.md'
  ].join('');

  console.warn(chalk.yellow(errorMessage));
}

async function copyCommits() {
  function exec(cmd) {
    return shell.exec(cmd, { silent: true }).stdout;
  }

  function getMessage(sha) {
    return exec(`git log --format=%B -n 1 ${sha}`).split("\n")[0]
  }

  function getCommitsAfter(sha) {
    return exec(`git rev-list --reverse ${sha}^..HEAD`).trim().split("\n");
  }

  function commitChanges({msg}) {
    console.log(`git commit -m "${prefix} ${msg}"`)
    const commitMessage = message.replace('__message__', msg)
    exec(`git add devtools; git commit -m "${prefix} ${commitMessage}"`)
  }

  const commits = getCommitsAfter(sha)
  for (const commit of commits) {
    const message = getMessage(commit);
    console.log(`Copying ${message}`)
    exec(`git checkout ${commit}`);

    await copy({mc});
    shell.cd(mc);
    commitChanges({message});
    shell.cd(`-`);
  }
}

if (sha) {
  copyCommits();
} else {
  start();
}
<|endoftext|>


<commit_before>(function(){var root=this;var VERSION="0.2.7";var doc=root.document||require("jsdom").jsdom();var ident=function(x){return x};var makeElement=function(tag,classNames){var el=doc.createElement(tag);el.className=(classNames||[]).map(function(cn){return nb.prefix+cn}).join(" ");return el};var escapeHTML=function(raw){var replaced=raw.replace(/</g,"<").replace(/>/g,">");return replaced};var joinText=function(text){if(text.join){return text.map(joinText).join("")}else{return text}};var condRequire=function(module_name){return typeof require==="function"&&require(module_name)};var getMarkdown=function(){return root.marked||condRequire("marked")};var getAnsi=function(){var req=condRequire("ansi_up");var lib=root.ansi_up||req;return lib&&lib.ansi_to_html};var nb={prefix:"nb-",markdown:getMarkdown()||ident,ansi:getAnsi()||ident,VERSION:VERSION};nb.Input=function(raw,cell){this.raw=raw;this.cell=cell};nb.Input.prototype.render=function(){if(!this.raw.length){return makeElement("div")}var holder=makeElement("div",["input"]);var cell=this.cell;if(typeof cell.number==="number"){holder.setAttribute("data-prompt-number",this.cell.number)}var pre_el=makeElement("pre");var code_el=makeElement("code");var notebook=cell.worksheet.notebook;var m=notebook.metadata;var lang=this.cell.raw.language||m.language||m.language_info.name;code_el.setAttribute("data-language",lang);code_el.className="lang-"+lang;code_el.innerHTML=escapeHTML(joinText(this.raw));pre_el.appendChild(code_el);holder.appendChild(pre_el);this.el=holder;return holder};var imageCreator=function(format){return function(data){var el=makeElement("img",["image-output"]);el.src="data:image/"+format+";base64,"+joinText(data).replace(/\n/g,"");return el}};nb.display={};nb.display.text=function(text){var el=makeElement("pre",["text-output"]);el.innerHTML=escapeHTML(joinText(text));return el};nb.display["text/plain"]=nb.display.text;nb.display.html=function(html){var el=makeElement("div",["html-output"]);el.innerHTML=joinText(html);return el};nb.display["text/html"]=nb.display.html;nb.display.marked=function(md){return nb.display.html(nb.markdown(joinText(md)))};nb.display["text/markdown"]=nb.display.marked;nb.display.svg=function(svg){var el=makeElement("div",["svg-output"]);el.innerHTML=joinText(svg);return el};nb.display["text/svg+xml"]=nb.display.svg;nb.display.latex=function(latex){var el=makeElement("div",["latex-output"]);el.innerHTML=joinText(latex);return el};nb.display["text/latex"]=nb.display.latex;nb.display.javascript=function(js){var el=makeElement("script");el.innerHTML=joinText(js);return el};nb.display["application/javascript"]=nb.display.javascript;nb.display.png=imageCreator("png");nb.display["image/png"]=nb.display.png;nb.display.jpeg=imageCreator("jpeg");nb.display["image/jpeg"]=nb.display.jpeg;nb.display_priority=["png","image/png","jpeg","image/jpeg","svg","text/svg+xml","html","text/html","text/markdown","latex","text/latex","javascript","application/javascript","text","text/plain"];var render_display_data=function(){var o=this;var formats=nb.display_priority.filter(function(d){return o.raw.data?o.raw.data[d]:o.raw[d]});var format=formats[0];if(format){if(nb.display[format]){return nb.display[format](o.raw[format]||o.raw.data[format])}}return makeElement("div",["empty-output"])};var render_error=function(){var el=makeElement("pre",["pyerr"]);var raw=this.raw.traceback.join("\n");el.innerHTML=nb.ansi(escapeHTML(raw));return el};nb.Output=function(raw,cell){this.raw=raw;this.cell=cell;this.type=raw.output_type};nb.Output.prototype.renderers={display_data:render_display_data,execute_result:render_display_data,pyout:render_display_data,pyerr:render_error,error:render_error,stream:function(){var el=makeElement("pre",[this.raw.stream||this.raw.name]);var raw=joinText(this.raw.text);el.innerHTML=nb.ansi(escapeHTML(raw));return el}};nb.Output.prototype.render=function(){var outer=makeElement("div",["output"]);if(typeof this.cell.number==="number"){outer.setAttribute("data-prompt-number",this.cell.number)}var inner=this.renderers[this.type].call(this);outer.appendChild(inner);this.el=outer;return outer};nb.coalesceStreams=function(outputs){if(!outputs.length){return outputs}var last=outputs[0];var new_outputs=[last];outputs.slice(1).forEach(function(o){if(o.raw.output_type==="stream"&&last.raw.output_type==="stream"&&o.raw.stream===last.raw.stream){last.raw.text=last.raw.text.concat(o.raw.text)}else{new_outputs.push(o);last=o}});return new_outputs};nb.Cell=function(raw,worksheet){var cell=this;cell.raw=raw;cell.worksheet=worksheet;cell.type=raw.cell_type;if(cell.type==="code"){cell.number=raw.prompt_number>-1?raw.prompt_number:raw.execution_count;var source=raw.input||[raw.source];cell.input=new nb.Input(source,cell);var raw_outputs=(cell.raw.outputs||[]).map(function(o){return new nb.Output(o,cell)});cell.outputs=nb.coalesceStreams(raw_outputs)}};nb.Cell.prototype.renderers={markdown:function(){var el=makeElement("div",["cell","markdown-cell"]);el.innerHTML=nb.markdown(joinText(this.raw.source));return el},heading:function(){var el=makeElement("h"+this.raw.level,["cell","heading-cell"]);el.innerHTML=joinText(this.raw.source);return el},raw:function(){var el=makeElement("div",["cell","raw-cell"]);el.innerHTML=joinText(this.raw.source);return el},code:function(){var cell_el=makeElement("div",["cell","code-cell"]);cell_el.appendChild(this.input.render());var output_els=this.outputs.forEach(function(o){cell_el.appendChild(o.render())});return cell_el}};nb.Cell.prototype.render=function(){var el=this.renderers[this.type].call(this);this.el=el;return el};nb.Worksheet=function(raw,notebook){var worksheet=this;this.raw=raw;this.notebook=notebook;this.cells=raw.cells.map(function(c){return new nb.Cell(c,worksheet)});this.render=function(){var worksheet_el=makeElement("div",["worksheet"]);worksheet.cells.forEach(function(c){worksheet_el.appendChild(c.render())});this.el=worksheet_el;return worksheet_el}};nb.Notebook=function(raw,config){var notebook=this;this.raw=raw;this.config=config;var meta=this.metadata=raw.metadata;this.title=meta.title||meta.name;var _worksheets=raw.worksheets||[{cells:raw.cells}];this.worksheets=_worksheets.map(function(ws){return new nb.Worksheet(ws,notebook)});this.sheet=this.worksheets[0]};nb.Notebook.prototype.render=function(){var notebook_el=makeElement("div",["notebook"]);this.worksheets.forEach(function(w){notebook_el.appendChild(w.render())});this.el=notebook_el;return notebook_el};nb.parse=function(nbjson,config){return new nb.Notebook(nbjson,config)};if(typeof define==="function"&&define.amd){define(function(){return nb})}if(typeof exports!=="undefined"){if(typeof module!=="undefined"&&module.exports){exports=module.exports=nb}exports.nb=nb}else{root.nb=nb}}).call(this);<commit_msg>Update notebook.min.js to v0.3.0<commit_after>(function(){var root=this;var VERSION="0.3.0";var doc=root.document;if(!doc){var jsdom=require("jsdom");doc=(new jsdom.JSDOM).window.document}var ident=function(x){return x};var makeElement=function(tag,classNames){var el=doc.createElement(tag);el.className=(classNames||[]).map(function(cn){return nb.prefix+cn}).join(" ");return el};var escapeHTML=function(raw){var replaced=raw.replace(/</g,"<").replace(/>/g,">");return replaced};var joinText=function(text){if(text.join){return text.map(joinText).join("")}else{return text}};var condRequire=function(module_name){return typeof require==="function"&&require(module_name)};var getMarkdown=function(){return root.marked||condRequire("marked")};var getAnsi=function(){var req=condRequire("ansi_up");var lib=root.ansi_up||req;return lib&&lib.ansi_to_html};var nb={prefix:"nb-",markdown:getMarkdown()||ident,ansi:getAnsi()||ident,VERSION:VERSION};nb.Input=function(raw,cell){this.raw=raw;this.cell=cell};nb.Input.prototype.render=function(){if(!this.raw.length){return makeElement("div")}var holder=makeElement("div",["input"]);var cell=this.cell;if(typeof cell.number==="number"){holder.setAttribute("data-prompt-number",this.cell.number)}var pre_el=makeElement("pre");var code_el=makeElement("code");var notebook=cell.worksheet.notebook;var m=notebook.metadata;var lang=this.cell.raw.language||m.language||m.language_info.name;code_el.setAttribute("data-language",lang);code_el.className="lang-"+lang;code_el.innerHTML=escapeHTML(joinText(this.raw));pre_el.appendChild(code_el);holder.appendChild(pre_el);this.el=holder;return holder};var imageCreator=function(format){return function(data){var el=makeElement("img",["image-output"]);el.src="data:image/"+format+";base64,"+joinText(data).replace(/\n/g,"");return el}};nb.display={};nb.display.text=function(text){var el=makeElement("pre",["text-output"]);el.innerHTML=escapeHTML(joinText(text));return el};nb.display["text/plain"]=nb.display.text;nb.display.html=function(html){var el=makeElement("div",["html-output"]);el.innerHTML=joinText(html);return el};nb.display["text/html"]=nb.display.html;nb.display.marked=function(md){return nb.display.html(nb.markdown(joinText(md)))};nb.display["text/markdown"]=nb.display.marked;nb.display.svg=function(svg){var el=makeElement("div",["svg-output"]);el.innerHTML=joinText(svg);return el};nb.display["text/svg+xml"]=nb.display.svg;nb.display["image/svg+xml"]=nb.display.svg;nb.display.latex=function(latex){var el=makeElement("div",["latex-output"]);el.innerHTML=joinText(latex);return el};nb.display["text/latex"]=nb.display.latex;nb.display.javascript=function(js){var el=makeElement("script");el.innerHTML=joinText(js);return el};nb.display["application/javascript"]=nb.display.javascript;nb.display.png=imageCreator("png");nb.display["image/png"]=nb.display.png;nb.display.jpeg=imageCreator("jpeg");nb.display["image/jpeg"]=nb.display.jpeg;nb.display_priority=["png","image/png","jpeg","image/jpeg","svg","image/svg+xml","text/svg+xml","html","text/html","text/markdown","latex","text/latex","javascript","application/javascript","text","text/plain"];var render_display_data=function(){var o=this;var formats=nb.display_priority.filter(function(d){return o.raw.data?o.raw.data[d]:o.raw[d]});var format=formats[0];if(format){if(nb.display[format]){return nb.display[format](o.raw[format]||o.raw.data[format])}}return makeElement("div",["empty-output"])};var render_error=function(){var el=makeElement("pre",["pyerr"]);var raw=this.raw.traceback.join("\n");el.innerHTML=nb.ansi(escapeHTML(raw));return el};nb.Output=function(raw,cell){this.raw=raw;this.cell=cell;this.type=raw.output_type};nb.Output.prototype.renderers={display_data:render_display_data,execute_result:render_display_data,pyout:render_display_data,pyerr:render_error,error:render_error,stream:function(){var el=makeElement("pre",[this.raw.stream||this.raw.name]);var raw=joinText(this.raw.text);el.innerHTML=nb.ansi(escapeHTML(raw));return el}};nb.Output.prototype.render=function(){var outer=makeElement("div",["output"]);if(typeof this.cell.number==="number"){outer.setAttribute("data-prompt-number",this.cell.number)}var inner=this.renderers[this.type].call(this);outer.appendChild(inner);this.el=outer;return outer};nb.coalesceStreams=function(outputs){if(!outputs.length){return outputs}var last=outputs[0];var new_outputs=[last];outputs.slice(1).forEach(function(o){if(o.raw.output_type==="stream"&&last.raw.output_type==="stream"&&o.raw.stream===last.raw.stream){last.raw.text=last.raw.text.concat(o.raw.text)}else{new_outputs.push(o);last=o}});return new_outputs};nb.Cell=function(raw,worksheet){var cell=this;cell.raw=raw;cell.worksheet=worksheet;cell.type=raw.cell_type;if(cell.type==="code"){cell.number=raw.prompt_number>-1?raw.prompt_number:raw.execution_count;var source=raw.input||[raw.source];cell.input=new nb.Input(source,cell);var raw_outputs=(cell.raw.outputs||[]).map(function(o){return new nb.Output(o,cell)});cell.outputs=nb.coalesceStreams(raw_outputs)}};nb.Cell.prototype.renderers={markdown:function(){var el=makeElement("div",["cell","markdown-cell"]);el.innerHTML=nb.markdown(joinText(this.raw.source));return el},heading:function(){var el=makeElement("h"+this.raw.level,["cell","heading-cell"]);el.innerHTML=joinText(this.raw.source);return el},raw:function(){var el=makeElement("div",["cell","raw-cell"]);el.innerHTML=joinText(this.raw.source);return el},code:function(){var cell_el=makeElement("div",["cell","code-cell"]);cell_el.appendChild(this.input.render());var output_els=this.outputs.forEach(function(o){cell_el.appendChild(o.render())});return cell_el}};nb.Cell.prototype.render=function(){var el=this.renderers[this.type].call(this);this.el=el;return el};nb.Worksheet=function(raw,notebook){var worksheet=this;this.raw=raw;this.notebook=notebook;this.cells=raw.cells.map(function(c){return new nb.Cell(c,worksheet)});this.render=function(){var worksheet_el=makeElement("div",["worksheet"]);worksheet.cells.forEach(function(c){worksheet_el.appendChild(c.render())});this.el=worksheet_el;return worksheet_el}};nb.Notebook=function(raw,config){var notebook=this;this.raw=raw;this.config=config;var meta=this.metadata=raw.metadata;this.title=meta.title||meta.name;var _worksheets=raw.worksheets||[{cells:raw.cells}];this.worksheets=_worksheets.map(function(ws){return new nb.Worksheet(ws,notebook)});this.sheet=this.worksheets[0]};nb.Notebook.prototype.render=function(){var notebook_el=makeElement("div",["notebook"]);this.worksheets.forEach(function(w){notebook_el.appendChild(w.render())});this.el=notebook_el;return notebook_el};nb.parse=function(nbjson,config){return new nb.Notebook(nbjson,config)};if(typeof define==="function"&&define.amd){define(function(){return nb})}if(typeof exports!=="undefined"){if(typeof module!=="undefined"&&module.exports){exports=module.exports=nb}exports.nb=nb}else{root.nb=nb}}).call(this);
<|endoftext|>


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

  ionic.views.HeaderBar = ionic.views.View.inherit({
    initialize: function(opts) {
      this.el = opts.el;

      ionic.extend(this, {
        alignTitle: 'center'
      }, opts);

      this.align();
    },

    align: function(align) {

      align || (align = this.alignTitle);

      // Find the titleEl element
      var titleEl = this.el.querySelector('.title');
      if(!titleEl) {
        return;
      }

      var self = this;
      //We have to rAF here so all of the elements have time to initialize
      ionic.requestAnimationFrame(function() {
        var i, c, childSize;
        var childNodes = self.el.childNodes;
        var leftWidth = 0;
        var rightWidth = 0;
        var isCountingRightWidth = false;

        // Compute how wide the left children are
        // Skip all titles (there may still be two titles, one leaving the dom)
        // Once we encounter a titleEl, realize we are now counting the right-buttons, not left
        for(i = 0; i < childNodes.length; i++) {
          c = childNodes[i];
          if (c.tagName && c.tagName.toLowerCase() == 'h1') {
            isCountingRightWidth = true;
            continue;
          }

          childSize = null;
          if(c.nodeType == 3) {
            childSize = ionic.DomUtil.getTextBounds(c).width;
          } else if(c.nodeType == 1) {
            childSize = c.offsetWidth;
          }
          if(childSize) {
            if (isCountingRightWidth) {
              rightWidth += childSize;
            } else {
              leftWidth += childSize;
            }
          }
        }

        var margin = Math.max(leftWidth, rightWidth) + 10;

        //Reset left and right before setting again
        titleEl.style.left = titleEl.style.right = '';

        // Size and align the header titleEl based on the sizes of the left and
        // right children, and the desired alignment mode
        if(align == 'center') {
          if(margin > 10) {
            titleEl.style.left = margin + 'px';
            titleEl.style.right = margin + 'px';
          }
          if(titleEl.offsetWidth < titleEl.scrollWidth) {
            if(rightWidth > 0) {
              titleEl.style.right = (rightWidth + 5) + 'px';
            }
          }
        } else if(align == 'left') {
          titleEl.classList.add('title-left');
          if(leftWidth > 0) {
            titleEl.style.left = (leftWidth + 15) + 'px';
          }
        } else if(align == 'right') {
          titleEl.classList.add('title-right');
          if(rightWidth > 0) {
            titleEl.style.right = (rightWidth + 15) + 'px';
          }
        }
      });
    }
  });

})(ionic);
<commit_msg>fix(headerBarView): check for null in getTextBounds<commit_after>(function(ionic) {
'use strict';

  ionic.views.HeaderBar = ionic.views.View.inherit({
    initialize: function(opts) {
      this.el = opts.el;

      ionic.extend(this, {
        alignTitle: 'center'
      }, opts);

      this.align();
    },

    align: function(align) {

      align || (align = this.alignTitle);

      // Find the titleEl element
      var titleEl = this.el.querySelector('.title');
      if(!titleEl) {
        return;
      }

      var self = this;
      //We have to rAF here so all of the elements have time to initialize
      ionic.requestAnimationFrame(function() {
        var i, c, childSize;
        var childNodes = self.el.childNodes;
        var leftWidth = 0;
        var rightWidth = 0;
        var isCountingRightWidth = false;

        // Compute how wide the left children are
        // Skip all titles (there may still be two titles, one leaving the dom)
        // Once we encounter a titleEl, realize we are now counting the right-buttons, not left
        for(i = 0; i < childNodes.length; i++) {
          c = childNodes[i];
          if (c.tagName && c.tagName.toLowerCase() == 'h1') {
            isCountingRightWidth = true;
            continue;
          }

          childSize = null;
          if(c.nodeType == 3) {
            var bounds = ionic.DomUtil.getTextBounds(c);
            if(bounds) {
              childSize = bounds.width;
            }
          } else if(c.nodeType == 1) {
            childSize = c.offsetWidth;
          }
          if(childSize) {
            if (isCountingRightWidth) {
              rightWidth += childSize;
            } else {
              leftWidth += childSize;
            }
          }
        }

        var margin = Math.max(leftWidth, rightWidth) + 10;

        //Reset left and right before setting again
        titleEl.style.left = titleEl.style.right = '';

        // Size and align the header titleEl based on the sizes of the left and
        // right children, and the desired alignment mode
        if(align == 'center') {
          if(margin > 10) {
            titleEl.style.left = margin + 'px';
            titleEl.style.right = margin + 'px';
          }
          if(titleEl.offsetWidth < titleEl.scrollWidth) {
            if(rightWidth > 0) {
              titleEl.style.right = (rightWidth + 5) + 'px';
            }
          }
        } else if(align == 'left') {
          titleEl.classList.add('title-left');
          if(leftWidth > 0) {
            titleEl.style.left = (leftWidth + 15) + 'px';
          }
        } else if(align == 'right') {
          titleEl.classList.add('title-right');
          if(rightWidth > 0) {
            titleEl.style.right = (rightWidth + 15) + 'px';
          }
        }
      });
    }
  });

})(ionic);
<|endoftext|>


<commit_before>//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
//>>description: Creates collapsible content blocks.
//>>label: Collapsible
//>>group: Widgets
//>>css.structure: ../css/structure/jquery.mobile.collapsible.css
//>>css.theme: ../css/themes/default/jquery.mobile.theme.css

define( [ "jquery", "../jquery.mobile.widget", "../jquery.mobile.buttonMarkup", "../jquery.mobile.registry" ], function( jQuery ) {
//>>excludeEnd("jqmBuildExclude");
(function( $, undefined ) {

var getAttr = $.mobile.getAttribute;

$.widget( "mobile.collapsible", $.mobile.widget, {
	options: {
		expandCueText: " click to expand contents",
		collapseCueText: " click to collapse contents",
		collapsed: true,
		heading: "h1,h2,h3,h4,h5,h6,legend",
		collapsedIcon: "plus",
		expandedIcon: "minus",
		iconpos: "left",
		theme: null,
		contentTheme: null,
		inset: true,
		corners: true,
		mini: false
	},

	_create: function() {
		var $el = this.element,
			o = this.options,
			collapsiblesetWidgetSelector = ( $.mobile.collapsibleset ? ", :mobile-collapsibleset" : "" ),
			collapsible = $el.addClass( "ui-collapsible" ),
			collapsibleHeading = $el.children( o.heading ).first(),
			collapsibleContent = collapsible.wrapInner( "

" ).children( ".ui-collapsible-content" ),
			collapsibleSet = $el.closest( ":jqmData(role='collapsible-set')" + collapsiblesetWidgetSelector ).addClass( "ui-collapsible-set" ),
			collapsibleClasses = "";

		// Replace collapsibleHeading if it's a legend
		if ( collapsibleHeading.is( "legend" ) ) {
			collapsibleHeading = $( "
"+ collapsibleHeading.html() +"
" ).insertBefore( collapsibleHeading );
			collapsibleHeading.next().remove();
		}

		// If we are in a collapsible set
		if ( collapsibleSet.length ) {
			// Inherit the theme from collapsible-set
			if ( !o.theme ) {
				o.theme = getAttr( collapsibleSet[ 0 ], "theme", true ) || $.mobile.getInheritedTheme( collapsibleSet, "c" );
			}
			// Inherit the content-theme from collapsible-set
			if ( !o.contentTheme ) {
				o.contentTheme = getAttr( collapsibleSet[ 0 ], "content-theme", true );
			}

			// Get the preference for collapsed icon in the set, but override with data- attribute on the individual collapsible
			o.collapsedIcon = getAttr( $el[ 0 ], "collapsed-icon", true ) || getAttr( collapsibleSet[ 0 ], "collapsed-icon", true ) || o.collapsedIcon;

			// Get the preference for expanded icon in the set, but override with data- attribute on the individual collapsible
			o.expandedIcon = getAttr( $el[ 0 ], "expanded-icon", true ) || getAttr( collapsibleSet[ 0 ], "expanded-icon", true ) || o.expandedIcon;

			// Gets the preference icon position in the set, but override with data- attribute on the individual collapsible
			o.iconpos = getAttr( $el[ 0 ], "iconpos", true ) || getAttr( collapsibleSet[ 0 ], "iconpos", true ) || o.iconpos;

			// Inherit the preference for inset from collapsible-set or set the default value to ensure equalty within a set
			if ( getAttr( collapsibleSet[ 0 ], "inset", true ) !== undefined ) {
				o.inset = getAttr( collapsibleSet[ 0 ], "inset", true );
			} else {
				o.inset = true;
			}
			// Set corners for individual collapsibles to false when in a collapsible-set
			o.corners = false;
			// Gets the preference for mini in the set
			if ( !o.mini ) {
				o.mini = getAttr( collapsibleSet[ 0 ], "mini", true );
			}
		} else {
			// get inherited theme if not a set and no theme has been set
			if ( !o.theme ) {
				o.theme = $.mobile.getInheritedTheme( $el, "c" );
			}
		}

		if ( !!o.inset ) {
			collapsibleClasses += " ui-collapsible-inset";
			if ( !!o.corners ) {
				collapsibleClasses += " ui-corner-all" ;
			}
		}
		if ( o.contentTheme ) {
			collapsibleClasses += " ui-collapsible-themed-content";
			collapsibleContent.addClass( "ui-body-" + o.contentTheme );
		}
		if ( collapsibleClasses !== "" ) {
			collapsible.addClass( collapsibleClasses );
		}

		collapsibleHeading
			//drop heading in before content
			.insertBefore( collapsibleContent )
			//modify markup & attributes
			.addClass( "ui-collapsible-heading" )
			.append( "" )
			.wrapInner( "" )
			.find( "a" )
				.first()
				.buttonMarkup({
					shadow: false,
					corners: false,
					iconpos: o.iconpos,
					icon: o.collapsedIcon,
					mini: o.mini,
					theme: o.theme
				});

		$.extend( this, {
			_collapsibleHeading: collapsibleHeading,
			_collapsibleContent: collapsibleContent
		});

		//events
		this._on({
			"expand": "_handleExpandCollapse",
			"collapse": "_handleExpandCollapse"
		});

		this._on( collapsibleHeading, {
			"tap": function(/* event */) {
				collapsibleHeading.find( "a" ).first().addClass( $.mobile.activeBtnClass );
			},

			"click": function( event ) {

				var type = collapsibleHeading.hasClass( "ui-collapsible-heading-collapsed" ) ? "expand" : "collapse";

				collapsible.trigger( type );

				event.preventDefault();
				event.stopPropagation();
			}
		});

		this._setOptions( this.options );
	},

	_handleExpandCollapse: function( event ) {
		var isCollapse,
			o = this.options;

		if ( !event.isDefaultPrevented() ) {
			isCollapse = ( event.type === "collapse" );

			event.preventDefault();

			this._collapsibleHeading
				.toggleClass( "ui-collapsible-heading-collapsed", isCollapse )
				.find( ".ui-collapsible-heading-status" )
				.text( isCollapse ? o.expandCueText : o.collapseCueText )
				.end()
				.find( ".ui-icon" )
				.toggleClass( "ui-icon-" + o.expandedIcon, !isCollapse )
				// logic or cause same icon for expanded/collapsed state would remove the ui-icon-class
				.toggleClass( "ui-icon-" + o.collapsedIcon, ( isCollapse || o.expandedIcon === o.collapsedIcon ) )
				.end()
				.find( "a" ).first().removeClass( $.mobile.activeBtnClass );

			this.element.toggleClass( "ui-collapsible-collapsed", isCollapse );
			this._collapsibleContent
				.toggleClass( "ui-collapsible-content-collapsed", isCollapse )
				.attr( "aria-hidden", isCollapse )
				.trigger( "updatelayout" );
		}
	},

	_setOptions: function( o ) {
		var $el = this.element;

		if ( o.collapsed !== undefined ) {
			$el.trigger( o.collapsed ? "collapse" : "expand" );
		}

		return this._super( o );
	}
});

$.mobile.collapsible.initSelector = ":jqmData(role='collapsible')";

//auto self-init widgets
$.mobile._enhancer.add( "mobile.collapsible", { dependencies: [ "mobile.page","mobile.toolbar" ] });

})( jQuery );
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
});
//>>excludeEnd("jqmBuildExclude");
<commit_msg>Collapsible: Needs to depend on core, because it uses $.mobile.getAttribute.<commit_after>//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
//>>description: Creates collapsible content blocks.
//>>label: Collapsible
//>>group: Widgets
//>>css.structure: ../css/structure/jquery.mobile.collapsible.css
//>>css.theme: ../css/themes/default/jquery.mobile.theme.css

define( [
	"jquery",
	"../jquery.mobile.core",
	"../jquery.mobile.widget",
	"../jquery.mobile.buttonMarkup",
	"../jquery.mobile.registry" ], function( jQuery ) {
//>>excludeEnd("jqmBuildExclude");
(function( $, undefined ) {

var getAttr = $.mobile.getAttribute;

$.widget( "mobile.collapsible", $.mobile.widget, {
	options: {
		expandCueText: " click to expand contents",
		collapseCueText: " click to collapse contents",
		collapsed: true,
		heading: "h1,h2,h3,h4,h5,h6,legend",
		collapsedIcon: "plus",
		expandedIcon: "minus",
		iconpos: "left",
		theme: null,
		contentTheme: null,
		inset: true,
		corners: true,
		mini: false
	},

	_create: function() {
		var $el = this.element,
			o = this.options,
			collapsiblesetWidgetSelector = ( $.mobile.collapsibleset ? ", :mobile-collapsibleset" : "" ),
			collapsible = $el.addClass( "ui-collapsible" ),
			collapsibleHeading = $el.children( o.heading ).first(),
			collapsibleContent = collapsible.wrapInner( "

" ).children( ".ui-collapsible-content" ),
			collapsibleSet = $el.closest( ":jqmData(role='collapsible-set')" + collapsiblesetWidgetSelector ).addClass( "ui-collapsible-set" ),
			collapsibleClasses = "";

		// Replace collapsibleHeading if it's a legend
		if ( collapsibleHeading.is( "legend" ) ) {
			collapsibleHeading = $( "
"+ collapsibleHeading.html() +"
" ).insertBefore( collapsibleHeading );
			collapsibleHeading.next().remove();
		}

		// If we are in a collapsible set
		if ( collapsibleSet.length ) {
			// Inherit the theme from collapsible-set
			if ( !o.theme ) {
				o.theme = getAttr( collapsibleSet[ 0 ], "theme", true ) || $.mobile.getInheritedTheme( collapsibleSet, "c" );
			}
			// Inherit the content-theme from collapsible-set
			if ( !o.contentTheme ) {
				o.contentTheme = getAttr( collapsibleSet[ 0 ], "content-theme", true );
			}

			// Get the preference for collapsed icon in the set, but override with data- attribute on the individual collapsible
			o.collapsedIcon = getAttr( $el[ 0 ], "collapsed-icon", true ) || getAttr( collapsibleSet[ 0 ], "collapsed-icon", true ) || o.collapsedIcon;

			// Get the preference for expanded icon in the set, but override with data- attribute on the individual collapsible
			o.expandedIcon = getAttr( $el[ 0 ], "expanded-icon", true ) || getAttr( collapsibleSet[ 0 ], "expanded-icon", true ) || o.expandedIcon;

			// Gets the preference icon position in the set, but override with data- attribute on the individual collapsible
			o.iconpos = getAttr( $el[ 0 ], "iconpos", true ) || getAttr( collapsibleSet[ 0 ], "iconpos", true ) || o.iconpos;

			// Inherit the preference for inset from collapsible-set or set the default value to ensure equalty within a set
			if ( getAttr( collapsibleSet[ 0 ], "inset", true ) !== undefined ) {
				o.inset = getAttr( collapsibleSet[ 0 ], "inset", true );
			} else {
				o.inset = true;
			}
			// Set corners for individual collapsibles to false when in a collapsible-set
			o.corners = false;
			// Gets the preference for mini in the set
			if ( !o.mini ) {
				o.mini = getAttr( collapsibleSet[ 0 ], "mini", true );
			}
		} else {
			// get inherited theme if not a set and no theme has been set
			if ( !o.theme ) {
				o.theme = $.mobile.getInheritedTheme( $el, "c" );
			}
		}

		if ( !!o.inset ) {
			collapsibleClasses += " ui-collapsible-inset";
			if ( !!o.corners ) {
				collapsibleClasses += " ui-corner-all" ;
			}
		}
		if ( o.contentTheme ) {
			collapsibleClasses += " ui-collapsible-themed-content";
			collapsibleContent.addClass( "ui-body-" + o.contentTheme );
		}
		if ( collapsibleClasses !== "" ) {
			collapsible.addClass( collapsibleClasses );
		}

		collapsibleHeading
			//drop heading in before content
			.insertBefore( collapsibleContent )
			//modify markup & attributes
			.addClass( "ui-collapsible-heading" )
			.append( "" )
			.wrapInner( "" )
			.find( "a" )
				.first()
				.buttonMarkup({
					shadow: false,
					corners: false,
					iconpos: o.iconpos,
					icon: o.collapsedIcon,
					mini: o.mini,
					theme: o.theme
				});

		$.extend( this, {
			_collapsibleHeading: collapsibleHeading,
			_collapsibleContent: collapsibleContent
		});

		//events
		this._on({
			"expand": "_handleExpandCollapse",
			"collapse": "_handleExpandCollapse"
		});

		this._on( collapsibleHeading, {
			"tap": function(/* event */) {
				collapsibleHeading.find( "a" ).first().addClass( $.mobile.activeBtnClass );
			},

			"click": function( event ) {

				var type = collapsibleHeading.hasClass( "ui-collapsible-heading-collapsed" ) ? "expand" : "collapse";

				collapsible.trigger( type );

				event.preventDefault();
				event.stopPropagation();
			}
		});

		this._setOptions( this.options );
	},

	_handleExpandCollapse: function( event ) {
		var isCollapse,
			o = this.options;

		if ( !event.isDefaultPrevented() ) {
			isCollapse = ( event.type === "collapse" );

			event.preventDefault();

			this._collapsibleHeading
				.toggleClass( "ui-collapsible-heading-collapsed", isCollapse )
				.find( ".ui-collapsible-heading-status" )
				.text( isCollapse ? o.expandCueText : o.collapseCueText )
				.end()
				.find( ".ui-icon" )
				.toggleClass( "ui-icon-" + o.expandedIcon, !isCollapse )
				// logic or cause same icon for expanded/collapsed state would remove the ui-icon-class
				.toggleClass( "ui-icon-" + o.collapsedIcon, ( isCollapse || o.expandedIcon === o.collapsedIcon ) )
				.end()
				.find( "a" ).first().removeClass( $.mobile.activeBtnClass );

			this.element.toggleClass( "ui-collapsible-collapsed", isCollapse );
			this._collapsibleContent
				.toggleClass( "ui-collapsible-content-collapsed", isCollapse )
				.attr( "aria-hidden", isCollapse )
				.trigger( "updatelayout" );
		}
	},

	_setOptions: function( o ) {
		var $el = this.element;

		if ( o.collapsed !== undefined ) {
			$el.trigger( o.collapsed ? "collapse" : "expand" );
		}

		return this._super( o );
	}
});

$.mobile.collapsible.initSelector = ":jqmData(role='collapsible')";

//auto self-init widgets
$.mobile._enhancer.add( "mobile.collapsible", { dependencies: [ "mobile.page","mobile.toolbar" ] });

})( jQuery );
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
});
//>>excludeEnd("jqmBuildExclude");
<|endoftext|>