<commit_before>/* Copyright 2013 William Summers, Metatribal Research
 * adapted from https://developer.mozilla.org/en-US/docs/JXON
 *
 * 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.
 */
/**
 * @author William Summers
 *
 * CSSAssist provides a minimal set of methods for working with CSS
 * Browser support is limited by the availability of
 *            querySelector (http://caniuse.com/queryselector)
 *            add/removeEventListener (ie9+, most others support)
 *
 * these are the chainable methods
 *      init, forEach, hasClass, addClass, removeClass, toggleClass
 *      setStyle, setAttr, addListener, removeListener
 *
 * additional methods supplied by plugin (chainable)
 *      unique, union, intersects, difference
 *
 * non-chainable methods
 *      makeArray, loadCSS, createCSS
 */
// create a self-invoking function
var CSSAssist = (function () {

        // this is the main object
        // internally assigned to CSSAssist to enhance compressor performance
        var CSSAssist = function (selector) {
                return new CSSAssist.prototype.init(selector);
        };

        CSSAssist.version = '2.0.0-alpha2';

        // define the CSSAssist prototype
        CSSAssist.fn = CSSAssist.prototype = {

                init: function (selector) {
                        var context = [];
                        if (!selector) context = [];
                        // got self
                        else if (selector instanceof CSSAssist) return selector;
                        else {
                                // if an array
                                if (selector instanceof Array) context = selector;
                                // wrap dom nodes.
                                else if (selector.nodeType) context = [selector];
                                // if its a string (CSS selector)
                                else if (typeof selector === 'string') {
                                        context = [].slice.call(document.querySelectorAll(selector),0);
                                } else {
                                        context = [];
                                }
                        }

                        // build this object
                        // copy over the context array
                        for (var i = 0; i < context.length; ++i) this[i] = context[i];
                        // set this length
                        this.length = context.length;
                        return this;

                },

                // simple forEach loop (faster than native forEach for most cases)
                forEach: function (func) {
                        for (var i = 0; i < this.length; ++i) {
                                func.call(this, this[i], i);
                        }
                        return this;
                },

                /**
                 * Returns true if each node in the context containes each class in values
                 * Returns false otherwise.
                 * values may be either a space delimited string or an array
                 * e.g. CSSAssist('div').hasClass('myAwesomeStyle');
                 */
                hasClass: function (values) {
                        if (!values) values = ' ';
                        var values = CSSAssist.makeArray(values);
                        for (var i = 0; i < this.length; ++i) {
                                var className = (' ' + this[i].className + ' ').replace(rSpace, ' ');
                                for (var j = 0; j < values.length; ++j) {
                                        if ((className.indexOf(' ' + values[j] + ' ') < 0)) return false;
                                }
                        }
                        return true;

                },

                /**
                 * Adds each class in values to each node in context
                 * values may be either a space delimited string or an array
                 * e.g. CSSAssist('div').addClass('myAwesomeStyle');
                 */
                addClass: function (values) {
                        if (values) {
                                var values = CSSAssist.makeArray(values);
                                this.forEach(
                                        function (item) {
                                                for (var j = 0; j < values.length; ++j) {
                                                        if (!CSSAssist(item).hasClass(values[j])) item.className += ' ' + values[j];
                                                }
                                        }
                                );
                        }
                        return this;
                },

                /**
                 * Removes each class in values from each node in context
                 * values may be either a space delimited string or an array
                 * e.g. CSSAssist('div').removeClass('myAwesomeStyle');
                 */
                removeClass: function (values) {
                        if (values) values = CSSAssist.makeArray(values);
                        this.forEach(
                                function (item) {
                                        if (values) {
                                                var className = (' ' + item.className + ' ').replace(rSpace, ' ');
                                                for (var j = 0; j < values.length; ++j) {
                                                        while (className.indexOf(' ' + values[j] + ' ') > -1) {
                                                                className = className.replace(' ' + values[j] + ' ', ' ');
                                                        }
                                                }
                                                item.className = className.trim();
                                        } else item.removeAttribute('class');
                                }
                        );

                        return this;
                },

                /**
                 * For each class in values for each node in context
                 *    if the class is present, remove it
                 *    if the class is not present, add it
                 * values may be either a space delimited string or an array
                 * e.g. CSSAssist('div').toggleClass('myAwesomeStyle');
                 */
                toggleClass: function (values) {
                        if (values) {
                                var values = CSSAssist.makeArray(values);
                                this.forEach(
                                        function (item) {
                                                for (var j = 0; j < values.length; ++j) {
                                                        var it = CSSAssist(item);
                                                        if (it.hasClass(values[j])) it.removeClass(values[j])
                                                        else it.addClass(values[j]);
                                                }
                                        }
                                );
                        }
                        return this;
                },

                /**
                 * for each node in context
                 *      sets or clears the specified style property
                 * e.g. CSSAssist('.red').setStyle('color', '#FF0000'); // sets the style
                 * e.g. CSSAssist('.red').setStyle('color', ); // clears the style
                 */
                setStyle: function (property, value) {
                        if (property) {
                                this.forEach(
                                        function (item) {
                                                if (value) item.style[property] = value;
                                                else item.style[property] = '';
                                        }
                                );
                        }
                        return this;
                },

                /**
                 * for each node in context
                 *      sets or clears the specified style property
                 * e.g. CSSAssist('span').setAttr('data-src', 'my data source'); // sets the style
                 * e.g. CSSAssist('span').setAttr('data-src', ); // clears the style
                 */
                setAttr: function (attr, value) {
                        if (attr) {
                                this.forEach(
                                        function (item) {
                                                if (value) item.setAttribute(attr, value);
                                                else item.removeAttribute(attr);
                                        }
                                );
                        }
                        return this;
                },

                /**
                 * Set operations (as plugins)
                 */

                // unique function (returns an array not a CSSAssist object)
                unique: function () {
                        var unique = [];
                        for (var i = 0; i < this.length; i += 1) {
                                if (unique.indexOf(this[i]) < 0) {
                                        unique.push(this[i]);
                                }
                        }
                        return CSSAssist(unique);
                },

                // union (brute force concat)
                union: function (arrayObj) {
                        if (arrayObj) {
                                var ret = [];
                                for (var i = 0; i < this.length; ++i) {
                                        ret.push(this[i]);
                                }
                                for (var i = 0; i < arrayObj.length; ++i) {
                                        ret.push(arrayObj[i]);
                                }
                                return CSSAssist(ret).unique();
                        }
                        return this;
                },

                // intersection (brute force)
                intersects: function (arrayObj) {
                        if (arrayObj) {
                                var ret = [];
                                this.forEach(
                                        function (item) {
                                                for (var i = 0; i < arrayObj.length; ++i) {
                                                        if (item == arrayObj[i]) {
                                                                ret.push(item);
                                                                break;
                                                        }
                                                }
                                        }
                                );
                                return CSSAssist(ret).unique();
                        }
                        return this;
                },

                // difference
                difference: function (arrayObj) {
                        if (arrayObj) {
                                var ret = [],
                                        all = this.union(arrayObj);
                                all.forEach(
                                        function (item) {
                                                if (([].indexOf.call(this, item) > -1) != ([].indexOf.call(arrayObj, item) > -1)) {
                                                        ret.push(item)
                                                }
                                        }
                                );
                                return CSSAssist(ret);
                        }
                        return this;
                },

                /**
                 * Add an event listener to each node in context
                 */
                addListener: function (type, listener, useCapture) {
                        if (type && listener) {
                                var capture = useCapture || false;
                                this.forEach(
                                        function (item) {
                                                if (item.addEventListener) item.addEventListener(type, listener, capture);
                                                else if (item.attachEvent) item.attachEvent( "on" + type, listener );
                                                else return false;
                                        }
                                );
                        }
                        return this;
                },

                /**
                 * Remove an event listener from each node in context
                 */
                removeListener: function (type, listener, useCapture) {
                        if (type && listener) {
                                var capture = useCapture || false;
                                this.forEach(
                                        function (item) {
                                                if (item.addEventListener) item.removeEventListener(type, listener, capture);
                                                else if (item.attachEvent) item.detachEvent( "on" + type, listener );
                                                else return false;
                                        }
                                );
                        }
                        return this;
                }

        }; // end prototype

        // regex for collapsing space, tabs, returns, and newlines to single space
        var rSpace = /[\s+\t\r\n\f]/g;

        /**
         * Utility methods outside of the prototype but in CSSAssist namespace
         * these methods do not require/accept a context
         */

        /**
         * Utility method to coerce a space delimited string into an array
         * if values is not passed, return an empty array
         * if values is already an array, simply return it
         * if values is a string clean and split it
         * oterwise, return this
         */
        CSSAssist.makeArray = function (values) {
                if (!values) return []
                if (values instanceof Array) return values
                else if (typeof values === 'string') return values.replace(/^\s+|\s+$/g, '').split(/\s+/);
                else return [];
        };

        /**
         * Load an external CSS file
         * e.g. CSSAssist.loadCSSLink('http://meyerweb.com/eric/tools/css/reset/reset.css');
         */
        CSSAssist.loadCSS = function (url) {
                if (url) {
                        var head = document.getElementsByTagName('head')[0],
                                link = document.createElement('link');
                        link.type = 'text/css';
                        link.rel = 'stylesheet';
                        link.href = url;
                        head.appendChild(link);
                        return this;
                }
                return this;
        }

        /**
         * Inject a programmatically created stylesheet
         * styles is a string containing css rules to be injected
         * e.g CSSAssist.loadCSS( 'body { background-color: red;} div { background-color: yellow;}' );
         */
        CSSAssist.createCSS = function (styles) {
                if (styles) {
                        var head = document.getElementsByTagName('head')[0],
                                styleNode = document.createElement('style');
                        styleNode.type = 'text/css';
                        if (styleNode.styleSheet) styleNode.styleSheet.cssText = styles;
                        else styleNode.appendChild(document.createTextNode(styles));
                        head.appendChild(styleNode);
                }
                return this;
        }

        // Give the init method the CSSAssist prototype for later instantiation
        CSSAssist.fn.init.prototype = CSSAssist.fn;
        return CSSAssist;

})(); // end self-invoking function
<commit_msg>bumped version to 2.0.0-beta<commit_after>/* Copyright 2013 William Summers, Metatribal Research
 * adapted from https://developer.mozilla.org/en-US/docs/JXON
 *
 * 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.
 */
/**
 * @author William Summers
 *
 * CSSAssist provides a minimal set of methods for working with CSS
 * Browser support is limited by the availability of
 *            querySelector (http://caniuse.com/queryselector)
 *            add/removeEventListener (ie9+, most others support)
 *
 * these are the chainable methods
 *      init, forEach, hasClass, addClass, removeClass, toggleClass
 *      setStyle, setAttr, addListener, removeListener
 *
 * additional methods supplied by plugin (chainable)
 *      unique, union, intersects, difference
 *
 * non-chainable methods
 *      makeArray, loadCSS, createCSS
 */
// create a self-invoking function
var CSSAssist = (function () {

        // this is the main object
        // internally assigned to CSSAssist to enhance compressor performance
        var CSSAssist = function (selector) {
                return new CSSAssist.prototype.init(selector);
        };

        CSSAssist.version = '2.0.0-beta';

        // define the CSSAssist prototype
        CSSAssist.fn = CSSAssist.prototype = {

                init: function (selector) {
                        var context = [];
                        if (!selector) context = [];
                        // got self
                        else if (selector instanceof CSSAssist) return selector;
                        else {
                                // if an array
                                if (selector instanceof Array) context = selector;
                                // wrap dom nodes.
                                else if (selector.nodeType) context = [selector];
                                // if its a string (CSS selector)
                                else if (typeof selector === 'string') {
                                        context = [].slice.call(document.querySelectorAll(selector),0);
                                } else {
                                        context = [];
                                }
                        }

                        // build this object
                        // copy over the context array
                        for (var i = 0; i < context.length; ++i) this[i] = context[i];
                        // set this length
                        this.length = context.length;
                        return this;

                },

                // simple forEach loop (faster than native forEach for most cases)
                forEach: function (func) {
                        for (var i = 0; i < this.length; ++i) {
                                func.call(this, this[i], i);
                        }
                        return this;
                },

                /**
                 * Returns true if each node in the context containes each class in values
                 * Returns false otherwise.
                 * values may be either a space delimited string or an array
                 * e.g. CSSAssist('div').hasClass('myAwesomeStyle');
                 */
                hasClass: function (values) {
                        if (!values) values = ' ';
                        var values = CSSAssist.makeArray(values);
                        for (var i = 0; i < this.length; ++i) {
                                var className = (' ' + this[i].className + ' ').replace(rSpace, ' ');
                                for (var j = 0; j < values.length; ++j) {
                                        if ((className.indexOf(' ' + values[j] + ' ') < 0)) return false;
                                }
                        }
                        return true;

                },

                /**
                 * Adds each class in values to each node in context
                 * values may be either a space delimited string or an array
                 * e.g. CSSAssist('div').addClass('myAwesomeStyle');
                 */
                addClass: function (values) {
                        if (values) {
                                var values = CSSAssist.makeArray(values);
                                this.forEach(
                                        function (item) {
                                                for (var j = 0; j < values.length; ++j) {
                                                        if (!CSSAssist(item).hasClass(values[j])) item.className += ' ' + values[j];
                                                }
                                        }
                                );
                        }
                        return this;
                },

                /**
                 * Removes each class in values from each node in context
                 * values may be either a space delimited string or an array
                 * e.g. CSSAssist('div').removeClass('myAwesomeStyle');
                 */
                removeClass: function (values) {
                        if (values) values = CSSAssist.makeArray(values);
                        this.forEach(
                                function (item) {
                                        if (values) {
                                                var className = (' ' + item.className + ' ').replace(rSpace, ' ');
                                                for (var j = 0; j < values.length; ++j) {
                                                        while (className.indexOf(' ' + values[j] + ' ') > -1) {
                                                                className = className.replace(' ' + values[j] + ' ', ' ');
                                                        }
                                                }
                                                item.className = className.trim();
                                        } else item.removeAttribute('class');
                                }
                        );

                        return this;
                },

                /**
                 * For each class in values for each node in context
                 *    if the class is present, remove it
                 *    if the class is not present, add it
                 * values may be either a space delimited string or an array
                 * e.g. CSSAssist('div').toggleClass('myAwesomeStyle');
                 */
                toggleClass: function (values) {
                        if (values) {
                                var values = CSSAssist.makeArray(values);
                                this.forEach(
                                        function (item) {
                                                for (var j = 0; j < values.length; ++j) {
                                                        var it = CSSAssist(item);
                                                        if (it.hasClass(values[j])) it.removeClass(values[j])
                                                        else it.addClass(values[j]);
                                                }
                                        }
                                );
                        }
                        return this;
                },

                /**
                 * for each node in context
                 *      sets or clears the specified style property
                 * e.g. CSSAssist('.red').setStyle('color', '#FF0000'); // sets the style
                 * e.g. CSSAssist('.red').setStyle('color', ); // clears the style
                 */
                setStyle: function (property, value) {
                        if (property) {
                                this.forEach(
                                        function (item) {
                                                if (value) item.style[property] = value;
                                                else item.style[property] = '';
                                        }
                                );
                        }
                        return this;
                },

                /**
                 * for each node in context
                 *      sets or clears the specified style property
                 * e.g. CSSAssist('span').setAttr('data-src', 'my data source'); // sets the style
                 * e.g. CSSAssist('span').setAttr('data-src', ); // clears the style
                 */
                setAttr: function (attr, value) {
                        if (attr) {
                                this.forEach(
                                        function (item) {
                                                if (value) item.setAttribute(attr, value);
                                                else item.removeAttribute(attr);
                                        }
                                );
                        }
                        return this;
                },

                /**
                 * Set operations (as plugins)
                 */

                // unique function (returns an array not a CSSAssist object)
                unique: function () {
                        var unique = [];
                        for (var i = 0; i < this.length; i += 1) {
                                if (unique.indexOf(this[i]) < 0) {
                                        unique.push(this[i]);
                                }
                        }
                        return CSSAssist(unique);
                },

                // union (brute force concat)
                union: function (arrayObj) {
                        if (arrayObj) {
                                var ret = [];
                                for (var i = 0; i < this.length; ++i) {
                                        ret.push(this[i]);
                                }
                                for (var i = 0; i < arrayObj.length; ++i) {
                                        ret.push(arrayObj[i]);
                                }
                                return CSSAssist(ret).unique();
                        }
                        return this;
                },

                // intersection (brute force)
                intersects: function (arrayObj) {
                        if (arrayObj) {
                                var ret = [];
                                this.forEach(
                                        function (item) {
                                                for (var i = 0; i < arrayObj.length; ++i) {
                                                        if (item == arrayObj[i]) {
                                                                ret.push(item);
                                                                break;
                                                        }
                                                }
                                        }
                                );
                                return CSSAssist(ret).unique();
                        }
                        return this;
                },

                // difference
                difference: function (arrayObj) {
                        if (arrayObj) {
                                var ret = [],
                                        all = this.union(arrayObj);
                                all.forEach(
                                        function (item) {
                                                if (([].indexOf.call(this, item) > -1) != ([].indexOf.call(arrayObj, item) > -1)) {
                                                        ret.push(item)
                                                }
                                        }
                                );
                                return CSSAssist(ret);
                        }
                        return this;
                },

                /**
                 * Add an event listener to each node in context
                 */
                addListener: function (type, listener, useCapture) {
                        if (type && listener) {
                                var capture = useCapture || false;
                                this.forEach(
                                        function (item) {
                                                if (item.addEventListener) item.addEventListener(type, listener, capture);
                                                else if (item.attachEvent) item.attachEvent( "on" + type, listener );
                                                else return false;
                                        }
                                );
                        }
                        return this;
                },

                /**
                 * Remove an event listener from each node in context
                 */
                removeListener: function (type, listener, useCapture) {
                        if (type && listener) {
                                var capture = useCapture || false;
                                this.forEach(
                                        function (item) {
                                                if (item.addEventListener) item.removeEventListener(type, listener, capture);
                                                else if (item.attachEvent) item.detachEvent( "on" + type, listener );
                                                else return false;
                                        }
                                );
                        }
                        return this;
                }

        }; // end prototype

        // regex for collapsing space, tabs, returns, and newlines to single space
        var rSpace = /[\s+\t\r\n\f]/g;

        /**
         * Utility methods outside of the prototype but in CSSAssist namespace
         * these methods do not require/accept a context
         */

        /**
         * Utility method to coerce a space delimited string into an array
         * if values is not passed, return an empty array
         * if values is already an array, simply return it
         * if values is a string clean and split it
         * oterwise, return this
         */
        CSSAssist.makeArray = function (values) {
                if (!values) return []
                if (values instanceof Array) return values
                else if (typeof values === 'string') return values.replace(/^\s+|\s+$/g, '').split(/\s+/);
                else return [];
        };

        /**
         * Load an external CSS file
         * e.g. CSSAssist.loadCSSLink('http://meyerweb.com/eric/tools/css/reset/reset.css');
         */
        CSSAssist.loadCSS = function (url) {
                if (url) {
                        var head = document.getElementsByTagName('head')[0],
                                link = document.createElement('link');
                        link.type = 'text/css';
                        link.rel = 'stylesheet';
                        link.href = url;
                        head.appendChild(link);
                        return this;
                }
                return this;
        }

        /**
         * Inject a programmatically created stylesheet
         * styles is a string containing css rules to be injected
         * e.g CSSAssist.loadCSS( 'body { background-color: red;} div { background-color: yellow;}' );
         */
        CSSAssist.createCSS = function (styles) {
                if (styles) {
                        var head = document.getElementsByTagName('head')[0],
                                styleNode = document.createElement('style');
                        styleNode.type = 'text/css';
                        if (styleNode.styleSheet) styleNode.styleSheet.cssText = styles;
                        else styleNode.appendChild(document.createTextNode(styles));
                        head.appendChild(styleNode);
                }
                return this;
        }

        // Give the init method the CSSAssist prototype for later instantiation
        CSSAssist.fn.init.prototype = CSSAssist.fn;
        return CSSAssist;

})(); // end self-invoking function
<|endoftext|>


<commit_before>"use strict";
module.exports = function(sequelize, DataTypes) {
  var User = sequelize.define("User", {
    firstName: { type: DataTypes.STRING, allowNull: false },
    lastName: DataTypes.STRING,
    email: { type: DataTypes.STRING, allowNull: false, unique: true,
             validate: { isEmail: { msg: 'Email must be valid.' } }
            },
    password: { type: DataTypes.STRING, allowNull: false,
        validate: { len: { args: 8, msg: 'Password must be at-least 8 characters.' } }
    },
    admin: DataTypes.BOOLEAN
  }, {
    classMethods: {
      associate: function(models) {
          User.hasMany(models.ProjectTeamMember)
          User.hasMany(models.Project, { through: 'ProjectTeamMember' })
          User.hasMany(models.Task)
      }
    }
  });
  return User;
};<commit_msg>validation fix<commit_after>"use strict";
module.exports = function(sequelize, DataTypes) {
  var User = sequelize.define("User", {
    firstName: { type: DataTypes.STRING, allowNull: false },
    lastName: DataTypes.STRING,
    email: { type: DataTypes.STRING, allowNull: false, unique: true,
             validate: { isEmail: { msg: 'Email must be valid.' } }
            },
    password: { type: DataTypes.STRING, allowNull: false,
        validate: { len: { args: [ 8, 24 ], msg: 'Password must be between 8 to 24 characters.' } }
    },
    admin: DataTypes.BOOLEAN
  }, {
    classMethods: {
      associate: function(models) {
          User.hasMany(models.ProjectTeamMember)
          User.hasMany(models.Project, { through: 'ProjectTeamMember' })
          User.hasMany(models.Task)
      }
    }
  });
  return User;
};<|endoftext|>


<commit_before>/* global LD2h, rdf */

$(function () {
    //by default of the html the config-sections are visible
    //the enableMainSection function switches to the main section
    var prefix = "http://example.org/";
    var graphname = "http://zazuko.com/projects";

    if (localStorage.getItem("sparqlQuery")) {
        $("#sparqlQuery").val(localStorage.getItem("sparqlQuery"));
    }
    if (localStorage.getItem("sparqlUpdate")) {
        $("#sparqlUpdate").val(localStorage.getItem("sparqlUpdate"));
    }
    if (localStorage.getItem("sparqlUsername")) {
        $("#sparqlUsername").val(localStorage.getItem("sparqlUsername"));
    }
    if (localStorage.getItem("sparqlPassword")) {
        $("#sparqlPassword").val(localStorage.getItem("sparqlPassword"));
    }
    var showMain = function() {
        $("#endpointsForm").hide();
        $("#endpointsLink").show();
        $("#main").show();
        var basicAuthHeaderValue = "Basic " + btoa($("#sparqlUsername").val() + ":" + $("#sparqlPassword").val());
        var store = new rdf.SparqlStore({
                endpointUrl: $("#sparqlQuery").val(),
                updateUrl: $("#sparqlUpdate").val(), //shouldn't be needed
                request: function(method, requestUrl, headers, content, callback) {
                    var newHeaders = headers || {};
                    newHeaders["Authorization"] = basicAuthHeaderValue;
                    rdf.defaultRequest(method, requestUrl, headers, content, callback);
                }
            });
        LD2h.getDataGraph = function (callback) {
            store.graph(graphname, callback); //Caveat: with newer rdf-ext version the callback takes (uri,g)
        };
        $("#showEndpointsConfig").click(function (e) {
            localStorage.setItem("endPointsSet", false);
            window.location.reload();
            return false;
        });
        var sparqlUpdate = function(update) {
            jQuery.ajax(
                    { type: "POST",
                      url: $("#sparqlUpdate").val(),
                      async: false,
                      headers: {
                          "Authorization": basicAuthHeaderValue
                      },
                      data: {update: update}
                  }).done(function () {
                        console.log("successfully updated");
                        window.location.reload();
                    })
                    .fail(function (e) {
                        if (e.status === 401) {
                            alert("Authentication failed, check you username and password in the SPARQL Endpoint Config");
                        } else {
                            alert("error (see console for details)");
                        }
                        console.log("error with query " + update, e);
                    });
        };
        $("#createProject").on("click", function () {
            var projectTitle = $("#projectTitle").val();
            if (projectTitle.length < 4) {
                alert("Project title too short.");
                return;
            }
            var shortName = $("#projectName").val();
            if (shortName.length < 3) {
                alert("Project short name must not be shorter than 3 characters.");
                return;
            }
            if (shortName.indexOf(' ') > -1) {
                alert("Project short name must not contain spaces.");
                return;
            }
            var projectHours = $("#projectHours").val();
            if (!projectHours) {
                projectHours = 0;
            }
            var projectIRI = prefix + "project/"+shortName;
            var update = "PREFIX dct: <http://purl.org/dc/terms/>\n" +
                    "PREFIX pro: <http://schema.zazukoians.org/projects/>\n" +
                    "PREFIX rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n" +
                    "INSERT DATA\n" +
                    "{ GRAPH <" + graphname + ">\n" +
                    "{ <" + projectIRI + ">  rdf:type  pro:Project." +
                    "<" + projectIRI + ">  pro:plannedTime  " + projectHours + "." +
                    "<" + projectIRI + "> dct:title  \"" + projectTitle + "\" } \n" +
                    "}";
            sparqlUpdate(update);
        });
        $("#reportHours").on("click", function () {
            function makeid() {
                var text = "";
                var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

                for( var i=0; i < 7; i++ )
                    text += possible.charAt(Math.floor(Math.random() * possible.length));

                return text;
            };
            var entryHours = $("#entryHours").val();
            if (!entryHours) {
                alert("Must set entry hours");
                return;
            }
            var entryIri = prefix+"entry/"+makeid();
            var update = "PREFIX dct: <http://purl.org/dc/terms/>\n" +
                    "PREFIX pro: <http://schema.zazukoians.org/projects/>\n" +
                    "PREFIX rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n" +
                    "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>\n" +
                    "INSERT DATA\n" +
                    "{ GRAPH <" + graphname + ">\n" +
                    "{ <" + entryIri + ">  rdf:type  pro:Entry.\n" +
                    "<" + entryIri + ">  pro:spentTime  " + entryHours + ".\n" +
                    "<" + entryIri + ">  dct:description  \"" + $("#entryDescription").val() + "\" .\n" +
                    "<" + entryIri + ">  pro:project  <" + $("#entryProject").val() + "> .\n" +
                    "<" + entryIri + ">  pro:employee  <" + $("#entryPerson").val() + "> .\n" +
                    "<" + entryIri + ">  pro:entryDate  \"" + $("#entryDate").val() + "\"^^xsd:date } \n" +
                    "}";
            sparqlUpdate(update);
        });
        $("#createPerson").on("click", function () {
            var personIri = prefix+"employees/"+ $("#nick").val();
            var update = "PREFIX schema: <http://schema.org/>\n" +
                    "PREFIX foaf: <http://xmlns.com/foaf/0.1/>\n" +
                    "INSERT DATA\n" +
                    "{ GRAPH <" + graphname + ">\n" +
                        "{\n" +
                            "<"+personIri + "> a schema:Person, foaf:Person;\n" +
                            "  foaf:nick \""+ $("#nick").val() + "\" ;\n" +
                            "  schema:givenName \""+ $("#givenName").val() + "\" ;\n" +
                            "  schema:familyName \""+ $("#familyName").val() + "\" ;\n" +
                            "  schema:email \""+ $("#email").val() + "\" .\n" +
                        "}\n" +
                    "}";
            sparqlUpdate(update);
        });
        LD2h.expand();
    };
    //be compatibel also with old er browsers that convert everything in localStore to String
    if (localStorage.getItem("endPointsSet") && localStorage.getItem("endPointsSet").toString() === "true") {
        showMain();
    }
    $("#setEndpoints").click(function (e) {
        localStorage.setItem("sparqlQuery", $("#sparqlQuery").val());
        localStorage.setItem("sparqlUpdate", $("#sparqlUpdate").val());
        localStorage.setItem("sparqlUsername", $("#sparqlUsername").val());
        localStorage.setItem("sparqlPassword", $("#sparqlPassword").val());
        localStorage.setItem("endPointsSet", true);
        showMain();
    });
});<commit_msg>changed ontological tems/namespace<commit_after>/* global LD2h, rdf */

$(function () {
    //by default of the html the config-sections are visible
    //the enableMainSection function switches to the main section
    var prefix = "https://data.zazuko.com/";
    var graphname = "http://zazuko.com/projects";

    if (localStorage.getItem("sparqlQuery")) {
        $("#sparqlQuery").val(localStorage.getItem("sparqlQuery"));
    }
    if (localStorage.getItem("sparqlUpdate")) {
        $("#sparqlUpdate").val(localStorage.getItem("sparqlUpdate"));
    }
    if (localStorage.getItem("sparqlUsername")) {
        $("#sparqlUsername").val(localStorage.getItem("sparqlUsername"));
    }
    if (localStorage.getItem("sparqlPassword")) {
        $("#sparqlPassword").val(localStorage.getItem("sparqlPassword"));
    }
    var showMain = function() {
        $("#endpointsForm").hide();
        $("#endpointsLink").show();
        $("#main").show();
        var basicAuthHeaderValue = "Basic " + btoa($("#sparqlUsername").val() + ":" + $("#sparqlPassword").val());
        var store = new rdf.SparqlStore({
                endpointUrl: $("#sparqlQuery").val(),
                updateUrl: $("#sparqlUpdate").val(), //shouldn't be needed
                request: function(method, requestUrl, headers, content, callback) {
                    var newHeaders = headers || {};
                    newHeaders["Authorization"] = basicAuthHeaderValue;
                    rdf.defaultRequest(method, requestUrl, headers, content, callback);
                }
            });
        LD2h.getDataGraph = function (callback) {
            store.graph(graphname, callback); //Caveat: with newer rdf-ext version the callback takes (uri,g)
        };
        $("#showEndpointsConfig").click(function (e) {
            localStorage.setItem("endPointsSet", false);
            window.location.reload();
            return false;
        });
        var sparqlUpdate = function(update) {
            jQuery.ajax(
                    { type: "POST",
                      url: $("#sparqlUpdate").val(),
                      async: false,
                      headers: {
                          "Authorization": basicAuthHeaderValue
                      },
                      data: {update: update}
                  }).done(function () {
                        console.log("successfully updated");
                        window.location.reload();
                    })
                    .fail(function (e) {
                        if (e.status === 401) {
                            alert("Authentication failed, check you username and password in the SPARQL Endpoint Config");
                        } else {
                            alert("error (see console for details)");
                        }
                        console.log("error with query " + update, e);
                    });
        };
        $("#createProject").on("click", function () {
            var projectTitle = $("#projectTitle").val();
            if (projectTitle.length < 4) {
                alert("Project title too short.");
                return;
            }
            var shortName = $("#projectName").val();
            if (shortName.length < 3) {
                alert("Project short name must not be shorter than 3 characters.");
                return;
            }
            if (shortName.indexOf(' ') > -1) {
                alert("Project short name must not contain spaces.");
                return;
            }
            var projectHours = $("#projectHours").val();
            if (!projectHours) {
                projectHours = 0;
            }
            var projectIRI = prefix + "project/"+shortName;
            var update = "PREFIX dct: <http://purl.org/dc/terms/>\n" +
                    "PREFIX pro: <http://schema.zazuko.com/work/>\n" +
                    "PREFIX doap: <http://usefulinc.com/ns/doap#>\n" +
                    "PREFIX rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n" +
                    "INSERT DATA\n" +
                    "{ GRAPH <" + graphname + ">\n" +
                    "{ <" + projectIRI + ">  rdf:type  doap:Project." +
                    "<" + projectIRI + ">  pro:plannedTime  " + projectHours + "." +
                    "<" + projectIRI + "> dct:title  \"" + projectTitle + "\" } \n" +
                    "}";
            sparqlUpdate(update);
        });
        $("#reportHours").on("click", function () {
            function makeid() {
                var text = "";
                var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

                for( var i=0; i < 7; i++ )
                    text += possible.charAt(Math.floor(Math.random() * possible.length));

                return text;
            };
            var entryHours = $("#entryHours").val();
            if (!entryHours) {
                alert("Must set entry hours");
                return;
            }
            var entryIri = prefix+"entry/"+makeid();
            var update = "PREFIX dct: <http://purl.org/dc/terms/>\n" +
                    "PREFIX pro: <http://schema.zazuko.com/work/>\n" +
                    "PREFIX rdf:  <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n" +
                    "PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>\n" +
                    "INSERT DATA\n" +
                    "{ GRAPH <" + graphname + ">\n" +
                    "{ <" + entryIri + ">  rdf:type  pro:Entry.\n" +
                    "<" + entryIri + ">  pro:spentTime  " + entryHours + ".\n" +
                    "<" + entryIri + ">  dct:description  \"" + $("#entryDescription").val() + "\" .\n" +
                    "<" + entryIri + ">  pro:project  <" + $("#entryProject").val() + "> .\n" +
                    "<" + entryIri + ">  pro:employee  <" + $("#entryPerson").val() + "> .\n" +
                    "<" + entryIri + ">  pro:entryDate  \"" + $("#entryDate").val() + "\"^^xsd:date } \n" +
                    "}";
            sparqlUpdate(update);
        });
        $("#createPerson").on("click", function () {
            var personIri = prefix+"people/"+ $("#nick").val();
            var update = "PREFIX schema: <http://schema.org/>\n" +
                    "PREFIX foaf: <http://xmlns.com/foaf/0.1/>\n" +
                    "INSERT DATA\n" +
                    "{ GRAPH <" + graphname + ">\n" +
                        "{\n" +
                            "<"+personIri + "> a schema:Person, foaf:Person;\n" +
                            "  foaf:nick \""+ $("#nick").val() + "\" ;\n" +
                            "  schema:givenName \""+ $("#givenName").val() + "\" ;\n" +
                            "  schema:familyName \""+ $("#familyName").val() + "\" ;\n" +
                            "  schema:email \""+ $("#email").val() + "\" .\n" +
                        "}\n" +
                    "}";
            sparqlUpdate(update);
        });
        LD2h.expand();
    };
    //be compatibel also with old er browsers that convert everything in localStore to String
    if (localStorage.getItem("endPointsSet") && localStorage.getItem("endPointsSet").toString() === "true") {
        showMain();
    }
    $("#setEndpoints").click(function (e) {
        localStorage.setItem("sparqlQuery", $("#sparqlQuery").val());
        localStorage.setItem("sparqlUpdate", $("#sparqlUpdate").val());
        localStorage.setItem("sparqlUsername", $("#sparqlUsername").val());
        localStorage.setItem("sparqlPassword", $("#sparqlPassword").val());
        localStorage.setItem("endPointsSet", true);
        showMain();
    });
});<|endoftext|>


<commit_before>if (typeof (require) != 'undefined') {
	var loader = require('../../node_modules/Butterfly-js/dist/butterfly.min.js').loader;
}

/**
 * Entry point of the game, contains some part of the game engine and deals with
 * the different entities
 */
loader.executeModule('main',
'B', 'Canvas', 'Entities', 'Physics', 'Utils', 'data', 'Controls', 'Level', 'GUI',
function (B, canvas, Entities, Physics, Utils, data, Controls, Level, GUI) {
	var car,
		level,
		walls = [],
		// position of the mouse in the canvas, taking in account the scroll
		// and position of the canvas in the page
		mouseX,
		mouseY,
		fps = 30,
		urlParams = Utils.getUrlParams(window.location.search);

	const DEBUG = urlParams.debug || NO_DEBUG;

	B.on(window, 'load', function () {
		// Init the view
		canvas.init(document.getElementById('game-canvas'));
		Controls.init(true);

		loadResources(function () {
			setInterval(updateAll, 1000 / fps);

			level = Level.createLevel(data, 0);

			// Init the car

			var startCell = level.getCoordinatesCenterCell(data.maps[0].start[0], data.maps[0].start[1]);
			car = new Entities.Car(startCell[0], startCell[1], Math.PI / 2, CAR_SPEED);
			car.setGraphic(data.resources[data.resourcesMap.CAR].resource);
		});

		B.Events.on('keydown', car, function (code) {
			if (code == KEY_LEFT_ARROW) {
				car.steerLeft(true);
			}
			else if (code == KEY_UP_ARROW) {
				car.accelerate(true);
			}
			else if (code == KEY_RIGHT_ARROW) {
				car.steerRight(true);
			}
			else if (code == KEY_DOWN_ARROW) {
				car.reverse(true);
			}
		});

		B.Events.on('keyup', car, function (code) {
			if (code == KEY_LEFT_ARROW) {
				car.steerLeft(false);
			}
			else if (code == KEY_UP_ARROW) {
				car.accelerate(false);
			}
			else if (code == KEY_RIGHT_ARROW) {
				car.steerRight(false);
			}
			else if (code == KEY_DOWN_ARROW) {
				car.reverse(false);
			}
		});
	});

	/* Events */
	// Event to execute when the player wins
	B.Events.on('win', null, function () {
		car.reset();
	});

	// Event to execute when the player loses
	B.Events.on('lost', null, function () {
	});

	// Event to execute when the mouse move
	B.Events.on('mouse-moved', null, function (mX, mY) {
		mouseX = mX;
		mouseY = mY;

		if (DEBUG) {
			car.x = mouseX;
			car.y = mouseY;
			car.speed = CAR_SPEED;
		}
	});
	/* End of Events */

	function loadResources (loadedCallback) {
		var r, loaded = 0,
			loadingPadding = canvas.width() / 5,
			loadingWidth = 3 * loadingPadding;

		if (!data.resources) {
			loadedCallback();
			return;
		}

		canvas.clearScreen();
		GUI.progressBar(
			loadingPadding, canvas.height() / 2,
			loadingWidth, 30,
			0,
			'black', 'white', 'black'
		);
		for (r = 0; r < data.resources.length; r++) {
			data.resources[r].resource = new Image();
			data.resources[r].resource.onload = function () {
				if (++loaded == data.resources.length) {
					loadedCallback();
				}
				else {
					GUI.progressBar(
						loadingPadding, canvas.height() / 2,
						loadingWidth, 30,
						loaded / data.resources.length,
						'black', 'white', 'black'
					);
				}
			};
			data.resources[r].resource.src = data.resources[r].url;
		}
	}

	/**
	 * Method to update the game state and the objects's position
	 */
	function moveAll () {
		// Update the car position
		car.updatePosition();

		var carGridCellCol = Math.floor(car.x / level.gridCellWidth),
			carGridCellRow = Math.floor(car.y / level.gridCellHeight);

		/* Car and edges collision*/
		Physics.sphereBounceAgainstInnerRectangle(car, {x: 0, y: 0, w: canvas.width(), h: canvas.height()});
		/* End of Car and edges collision*/

		/* Car and wall collision */
		var wall = level.getCell(
			carGridCellCol,
			carGridCellRow
		);

		// if the car is on a wall
		if (0 <= carGridCellCol && carGridCellCol < level.width
			&& 0 <= carGridCellRow && carGridCellRow < level.height
			&& data.resources[wall.state].obstacle
		) {
			car.bumpBack();
		}
		/* End of Car and wall collision */
	}

	/**
	 * Method to execute on each frame to update the game state and the
	 * objects's position and then redraw the canvas
	 */
	function updateAll () {
		moveAll();
		canvas.drawAll([level.cells, car]);
	}
});
<commit_msg>useless debug removed<commit_after>if (typeof (require) != 'undefined') {
	var loader = require('../../node_modules/Butterfly-js/dist/butterfly.min.js').loader;
}

/**
 * Entry point of the game, contains some part of the game engine and deals with
 * the different entities
 */
loader.executeModule('main',
'B', 'Canvas', 'Entities', 'Physics', 'Utils', 'data', 'Controls', 'Level', 'GUI',
function (B, canvas, Entities, Physics, Utils, data, Controls, Level, GUI) {
	var car,
		level,
		walls = [],
		// position of the mouse in the canvas, taking in account the scroll
		// and position of the canvas in the page
		mouseX,
		mouseY,
		fps = 30,
		urlParams = Utils.getUrlParams(window.location.search);

	const DEBUG = urlParams.debug || NO_DEBUG;

	B.on(window, 'load', function () {
		// Init the view
		canvas.init(document.getElementById('game-canvas'));
		Controls.init(true);

		loadResources(function () {
			setInterval(updateAll, 1000 / fps);

			level = Level.createLevel(data, 0);

			// Init the car

			var startCell = level.getCoordinatesCenterCell(data.maps[0].start[0], data.maps[0].start[1]);
			car = new Entities.Car(startCell[0], startCell[1], Math.PI / 2, CAR_SPEED);
			car.setGraphic(data.resources[data.resourcesMap.CAR].resource);
		});

		B.Events.on('keydown', car, function (code) {
			if (code == KEY_LEFT_ARROW) {
				car.steerLeft(true);
			}
			else if (code == KEY_UP_ARROW) {
				car.accelerate(true);
			}
			else if (code == KEY_RIGHT_ARROW) {
				car.steerRight(true);
			}
			else if (code == KEY_DOWN_ARROW) {
				car.reverse(true);
			}
		});

		B.Events.on('keyup', car, function (code) {
			if (code == KEY_LEFT_ARROW) {
				car.steerLeft(false);
			}
			else if (code == KEY_UP_ARROW) {
				car.accelerate(false);
			}
			else if (code == KEY_RIGHT_ARROW) {
				car.steerRight(false);
			}
			else if (code == KEY_DOWN_ARROW) {
				car.reverse(false);
			}
		});
	});

	/* Events */
	// Event to execute when the player wins
	B.Events.on('win', null, function () {
		car.reset();
	});

	// Event to execute when the player loses
	B.Events.on('lost', null, function () {
	});

	// Event to execute when the mouse move
	B.Events.on('mouse-moved', null, function (mX, mY) {
		mouseX = mX;
		mouseY = mY;
	});
	/* End of Events */

	function loadResources (loadedCallback) {
		var r, loaded = 0,
			loadingPadding = canvas.width() / 5,
			loadingWidth = 3 * loadingPadding;

		if (!data.resources) {
			loadedCallback();
			return;
		}

		canvas.clearScreen();
		GUI.progressBar(
			loadingPadding, canvas.height() / 2,
			loadingWidth, 30,
			0,
			'black', 'white', 'black'
		);
		for (r = 0; r < data.resources.length; r++) {
			data.resources[r].resource = new Image();
			data.resources[r].resource.onload = function () {
				if (++loaded == data.resources.length) {
					loadedCallback();
				}
				else {
					GUI.progressBar(
						loadingPadding, canvas.height() / 2,
						loadingWidth, 30,
						loaded / data.resources.length,
						'black', 'white', 'black'
					);
				}
			};
			data.resources[r].resource.src = data.resources[r].url;
		}
	}

	/**
	 * Method to update the game state and the objects's position
	 */
	function moveAll () {
		// Update the car position
		car.updatePosition();

		var carGridCellCol = Math.floor(car.x / level.gridCellWidth),
			carGridCellRow = Math.floor(car.y / level.gridCellHeight);

		/* Car and edges collision*/
		Physics.sphereBounceAgainstInnerRectangle(car, {x: 0, y: 0, w: canvas.width(), h: canvas.height()});
		/* End of Car and edges collision*/

		/* Car and wall collision */
		var wall = level.getCell(
			carGridCellCol,
			carGridCellRow
		);

		// if the car is on a wall
		if (0 <= carGridCellCol && carGridCellCol < level.width
			&& 0 <= carGridCellRow && carGridCellRow < level.height
			&& data.resources[wall.state].obstacle
		) {
			car.bumpBack();
		}
		/* End of Car and wall collision */
	}

	/**
	 * Method to execute on each frame to update the game state and the
	 * objects's position and then redraw the canvas
	 */
	function updateAll () {
		moveAll();
		canvas.drawAll([level.cells, car]);
	}
});
<|endoftext|>


<commit_before>import CubicBezier from './CubicBezier';

export default class Animation {
	constructor(element, newPosition, duration, easing = 'linear', options = {}) {
		this.element = element;

		this.startingPosition = getElementTransformTranslateX(element);
		this.currentPosition = this.startingPosition;
		this.newPosition = newPosition;
		this.animationBezierCurve = getCubicBezierForEasing(easing);

		this.onStart = options.onStart;
		this.onEnd = options.onEnd;
		this.onStep = options.onStep;

		this.startTime;
		this.previousStepTime;
		this.duration = duration;
	}

	start() {
		this.requestId = window.requestAnimationFrame((time) => {
			this.startTime = time;
			this.step(time);
		});

		if (this.hasOwnProperty('onStart') && typeof this.onStart === 'function') {
			this.onStart();
		}
	}

	end() {
		if (this.requestId) {
			window.cancelAnimationFrame(this.requestId);
			delete this.requestId;

			if (this.hasOwnProperty('onEnd') && typeof this.onEnd === 'function') {
				this.onEnd();
			}
		}
	}

	step(currentTime) {
		let time = currentTime - this.startTime;
		let distance = this.newPosition - this.startingPosition;
		let positionChange = calculatePositionChange(time, distance, this.duration, this.animationBezierCurve);

		this.currentPosition = this.startingPosition + positionChange;

		renderElementAtHorizontalOffset(this.element, this.currentPosition);

		if (this.hasOwnProperty('onStep') && typeof this.onStep === 'function') {
			this.onStep();
		}

		if (this.currentPosition !== this.newPosition) {
			this.requestId = window.requestAnimationFrame(this.step.bind(this));
		} else {
			this.end();
		}
	}
}

function getCubicBezierForEasing(easing) {
	if (typeof easing === 'object' && easing.length === 4) {
		return CubicBezier.createCustomAnimation(
			easing[0],
			easing[1],
			easing[2],
			easing[3]
		);
	}

	switch (easing) {
		case 'ease':
			return CubicBezier.createEase();
		case 'easeIn':
			return CubicBezier.createEaseIn();
		case 'easeOut':
			return CubicBezier.createEaseOut();
		case 'easeInOut':
			return CubicBezier.createEaseInOut();
		case 'linear':
		default:
			return CubicBezier.createLinear();
	}
}

function renderElementAtHorizontalOffset(element, offset) {
	if (element instanceof Element) {
		element.style.transform = `translateX(${offset}px)`;
	}
}

function calculatePositionChange(time, distance, duration, animationBezierCurve) {
	let progress = time / duration;
	let positionChange = distance * animationBezierCurve.calculateVerticalForTime(progress);

	return positionChange;
}

function getElementTransformTranslateX(element) {
	if (window.getComputedStyle) {
		let style = window.getComputedStyle(element);
		let calculatedTransformation = style.transform || style.webkitTransform || style.mozTransform;

		let transformationMatrix3D = calculatedTransformation.match(/^matrix3d\((.+)\)$/);
		if (transformationMatrix3D) {
			return parseFloat(transformationMatrix3D[1].split(', ')[13]);
		}

		let transformationMatrix = calculatedTransformation.match(/^matrix\((.+)\)$/);
		if (transformationMatrix) {
			return parseFloat(transformationMatrix[1].split(', ')[4]);
		}
	}

	return 0;
}
<commit_msg>Destroy animation on end<commit_after>import CubicBezier from './CubicBezier';

export default class Animation {
	constructor(element, newPosition, duration, easing = 'linear', options = {}) {
		this.element = element;

		this.startingPosition = getElementTransformTranslateX(element);
		this.currentPosition = this.startingPosition;
		this.newPosition = newPosition;
		this.animationBezierCurve = getCubicBezierForEasing(easing);

		this.onStart = options.onStart;
		this.onEnd = options.onEnd;
		this.onStep = options.onStep;

		this.startTime;
		this.previousStepTime;
		this.duration = duration;
	}

	start() {
		this.requestId = window.requestAnimationFrame((time) => {
			this.startTime = time;
			this.step(time);
		});

		if (this.hasOwnProperty('onStart') && typeof this.onStart === 'function') {
			this.onStart();
		}
	}

	end() {
		if (this.requestId) {
			this.destroy();

			if (this.hasOwnProperty('onEnd') && typeof this.onEnd === 'function') {
				this.onEnd();
			}
		}
	}

	destroy() {
		if (this.requestId) {
			window.cancelAnimationFrame(this.requestId);
			delete this.requestId;
		}
	}

	step(currentTime) {
		let time = currentTime - this.startTime;
		let distance = this.newPosition - this.startingPosition;
		let positionChange = calculatePositionChange(time, distance, this.duration, this.animationBezierCurve);

		this.currentPosition = this.startingPosition + positionChange;

		renderElementAtHorizontalOffset(this.element, this.currentPosition);

		if (this.hasOwnProperty('onStep') && typeof this.onStep === 'function') {
			this.onStep();
		}

		if (this.currentPosition !== this.newPosition) {
			this.requestId = window.requestAnimationFrame(this.step.bind(this));
		} else {
			this.end();
		}
	}
}

function getCubicBezierForEasing(easing) {
	if (typeof easing === 'object' && easing.length === 4) {
		return CubicBezier.createCustomAnimation(
			easing[0],
			easing[1],
			easing[2],
			easing[3]
		);
	}

	switch (easing) {
		case 'ease':
			return CubicBezier.createEase();
		case 'easeIn':
			return CubicBezier.createEaseIn();
		case 'easeOut':
			return CubicBezier.createEaseOut();
		case 'easeInOut':
			return CubicBezier.createEaseInOut();
		case 'linear':
		default:
			return CubicBezier.createLinear();
	}
}

function renderElementAtHorizontalOffset(element, offset) {
	if (element instanceof Element) {
		element.style.transform = `translateX(${offset}px)`;
	}
}

function calculatePositionChange(time, distance, duration, animationBezierCurve) {
	let progress = time / duration;
	let positionChange = distance * animationBezierCurve.calculateVerticalForTime(progress);

	return positionChange;
}

function getElementTransformTranslateX(element) {
	if (window.getComputedStyle) {
		let style = window.getComputedStyle(element);
		let calculatedTransformation = style.transform || style.webkitTransform || style.mozTransform;

		let transformationMatrix3D = calculatedTransformation.match(/^matrix3d\((.+)\)$/);
		if (transformationMatrix3D) {
			return parseFloat(transformationMatrix3D[1].split(', ')[13]);
		}

		let transformationMatrix = calculatedTransformation.match(/^matrix\((.+)\)$/);
		if (transformationMatrix) {
			return parseFloat(transformationMatrix[1].split(', ')[4]);
		}
	}

	return 0;
}
<|endoftext|>


<commit_before>"use strict";

var util = require("util");
/**
 * @param {Errors[]} errorsCollection
 */
module.exports = function(errorsCollection) {
    var errorCount = 0;

    console.log("##teamcity[testSuiteStarted name='JSCS']");

    /**
     * Formatting every error set.
     */
    errorsCollection.forEach(function(errors) {
        var file = errors.getFilename();

        if (!errors.isEmpty()) {
            errors.getErrorList().forEach(function(error) {
                errorCount++;
                console.log(util.format("##teamcity[testStarted name='%s']", file));
                console.log(util.format("##teamcity[testFailed name='%s' message='line %d, col %d, %s']",
                    file, error.line, error.column, error.message));
            });
        }

    });

    if (errorCount === 0) {
       console.log("##teamcity[testStarted name='JSCS']");
       console.log("##teamcity[testFinished name='JSCS']");
    }

    console.log(util.format("##teamcity[testSuiteFinished name='JSCS']"));
};
<commit_msg>fix code style errors<commit_after>'use strict';

var util = require('util');
/**
 * @param {Errors[]} errorsCollection
 */
module.exports = function(errorsCollection) {
    var errorCount = 0;

    console.log('##teamcity[testSuiteStarted name=\'JSCS\']');

    /**
     * Formatting every error set.
     */
    errorsCollection.forEach(function(errors) {
        var file = errors.getFilename();

        if (!errors.isEmpty()) {
            errors.getErrorList().forEach(function(error) {
                errorCount++;
                console.log(util.format('##teamcity[testStarted name=\'%s\']', file));
                console.log(util.format('##teamcity[testFailed name=\'%s\' message=\'line %d, col %d, %s\']',
                    file, error.line, error.column, error.message));
            });
        }

    });

    if (errorCount === 0) {
       console.log('##teamcity[testStarted name=\'JSCS\']');
       console.log('##teamcity[testFinished name=\'JSCS\']');
    }

    console.log(util.format('##teamcity[testSuiteFinished name=\'JSCS\']'));
};
<|endoftext|>


<commit_before>/* Copyright (C) 2011  Lincoln de Sousa <lincoln@comum.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

var navapi = null;

$(function () {
   $("#question-writer").ghost_typer({
     text:'Como podemos melhorar o atendimento na saúde pública?',
     speed: 80
   });

    var wizard = $('.wizard').data('isLoaded', false);

    $("ol.tabs", wizard).tabs(
        "div.panes > div", {
            effect: 'fade',
            lazy: true,
            onBeforeClick: function () {
                if (wizard.data('isLoaded')) {
                    $('html,body').animate({ scrollTop: 320 }, 150);
                }
            }
        });
    wizard.data('isLoaded', true);

    navapi = $("ol.tabs", wizard).data("tabs");

    // "next tab" button
    $(".next", wizard).click(function () {
        $('html,body').animate({ scrollTop: 320 }, 100);
	navapi.next();
    });

    // "previous tab" button
    $(".prev", wizard).click(function () {
        $('html,body').animate({ scrollTop: 320 }, 100);
	navapi.prev();
    });

    /* -- Setting up the per-theme description overlays --*/
    (function () {
        $('a.theme').overlay({
            top: '10%',
            speed: 'fast',
            fixed: false,
            oneInstance: false,
            mask: {
                color: '#111',
                opacity: 0.7
            }
        }).click(function () {
            themeapi.change(
                $(this).parent().attr('class'),
                $(this).attr('title')
            );
        });

        var $t1 = $('#themed');
        $('ul.internal', $t1).tabs(
            "div.ptpanes > div", {
                effect: 'fade', onBeforeClick: function (evt, idx) {
                    themeapi.update(idx);
                }
            });

        var api = $('ul.internal', $t1).data('tabs');
        $('.next', $t1).click(function () { api.next(); });
        $('.prev', $t1).click(function () { api.prev(); });
    })();
});

var themeapi = (function () {

    function ThemeApi() {
        this.current = '';
    }

    ThemeApi.prototype = {
        change: function(name, label) {
            $('#themed')
                .attr('class', '')
                .addClass('overlay')
                .addClass(name);

            $('#themed h1').html(label);
            $('#themed ul.allThemes li.' + name).hide();
            $('#themed ul.allThemes li[class~=' +
              this.current + ']').fadeIn();
            this.current = name;
            $('#themed ul.internal').data('tabs').click(0);
            this.update(0);
        },

        update: function (idx) {
            if (this.current === '')
                return null;

            var $el = $('a', $('ul.internal li').get(idx));
            var name = $el.attr('target');
            var $target =
                    $('div.' + name + ' .cont', $('.ptpanes')).html('');
            var url =
                    BASE_URL + 'pages/govpergunta/' +
                    themeapi.current + '/' + name + '.json';

            /* The user asked to go to the contribute form */
            if (name === 'contribua') {
                navapi.click(3);
                $('a.theme').each(function () {
                    $(this).data('overlay').close();
                });
                return null;
            }

            $.getJSON(url, function (data) {
                /* Yes, if none is retrieved, we'll clean the
                 * element content. */
                var ct = (data !== null) ? data.content : '';
                $target.html(ct);
            });
            return $el;
        },

        goToContribForm: function () {
        }
    };

    /* -- Contribute page -- */

    $('.contribute label').click(function () {
        $('.contribute label').removeClass('selected');
        $(this).addClass('selected');
    });

    $('.contribute form').ajaxForm({
        beforeSubmit: function () {
            var form = $('.contribute form');
            form.find('input,textarea').removeClass('fielderror');
            form.find('.error').fadeOut();
            form.find('.errmsg').html('');

            if (!auth.isAuthenticated()) {
                auth.showLoginForm({
                    success: function () {
                        form.submit();
                    }
                });
                return false;
            }
            return true;
        },

        success: function (data) {
            var pData = $.parseJSON(data);
            if (pData.status === 'ok') {
                $('#form fieldset').fadeOut();
                return $('div.success').fadeIn();
            }

            /* Here we know that something is wrong */
            var form = $('.contribute form');
            var errors = pData.msg.data;
            var code = pData.code;
            var csrfToken = pData.msg.csrf;

            /* The first step now is to set the new csrf token to
             * our form. If we don't do it, we can't try to
             * register again. */
            form.find('[name=csrf]').val(csrfToken);

            /* The user made a mistake when filling the form */
            if (code === 'ValidationError') {
                for (var f in errors) {
                    form
                        .find('[name=' + f  + ']')
                        .addClass('fielderror');
                    form
                        .find('.'+ f + '-error')
                        .html(errors[f][0]);
                    form.find('div.error')
                        .html('Falta alguma informação para completar a sua proposta')
                        .fadeIn('fast');
                }
            } else {
                form.find('div.error').html(pData.msg.data).fadeIn('fast');
            }
            return null;
        }
    });

    return new ThemeApi();
})();

function show_form_again() {
    $("#form .title").attr("value", "")
    $("#form textarea").val("")
    $('.contribute label').removeClass('selected');
    $("#form input[type=radio]").attr("checked",false)

    $('#form fieldset').fadeIn();
    $('div.success').fadeOut();
}<commit_msg>(govp) Marreta da boa pra traduzir uma msg de erro do wtforms<commit_after>/* Copyright (C) 2011  Lincoln de Sousa <lincoln@comum.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

var navapi = null;

$(function () {
   $("#question-writer").ghost_typer({
     text:'Como podemos melhorar o atendimento na saúde pública?',
     speed: 80
   });

    var wizard = $('.wizard').data('isLoaded', false);

    $("ol.tabs", wizard).tabs(
        "div.panes > div", {
            effect: 'fade',
            lazy: true,
            onBeforeClick: function () {
                if (wizard.data('isLoaded')) {
                    $('html,body').animate({ scrollTop: 320 }, 150);
                }
            }
        });
    wizard.data('isLoaded', true);

    navapi = $("ol.tabs", wizard).data("tabs");

    // "next tab" button
    $(".next", wizard).click(function () {
        $('html,body').animate({ scrollTop: 320 }, 100);
	navapi.next();
    });

    // "previous tab" button
    $(".prev", wizard).click(function () {
        $('html,body').animate({ scrollTop: 320 }, 100);
	navapi.prev();
    });

    /* -- Setting up the per-theme description overlays --*/
    (function () {
        $('a.theme').overlay({
            top: '10%',
            speed: 'fast',
            fixed: false,
            oneInstance: false,
            mask: {
                color: '#111',
                opacity: 0.7
            }
        }).click(function () {
            themeapi.change(
                $(this).parent().attr('class'),
                $(this).attr('title')
            );
        });

        var $t1 = $('#themed');
        $('ul.internal', $t1).tabs(
            "div.ptpanes > div", {
                effect: 'fade', onBeforeClick: function (evt, idx) {
                    themeapi.update(idx);
                }
            });

        var api = $('ul.internal', $t1).data('tabs');
        $('.next', $t1).click(function () { api.next(); });
        $('.prev', $t1).click(function () { api.prev(); });
    })();
});

var themeapi = (function () {

    function ThemeApi() {
        this.current = '';
    }

    ThemeApi.prototype = {
        change: function(name, label) {
            $('#themed')
                .attr('class', '')
                .addClass('overlay')
                .addClass(name);

            $('#themed h1').html(label);
            $('#themed ul.allThemes li.' + name).hide();
            $('#themed ul.allThemes li[class~=' +
              this.current + ']').fadeIn();
            this.current = name;
            $('#themed ul.internal').data('tabs').click(0);
            this.update(0);
        },

        update: function (idx) {
            if (this.current === '')
                return null;

            var $el = $('a', $('ul.internal li').get(idx));
            var name = $el.attr('target');
            var $target =
                    $('div.' + name + ' .cont', $('.ptpanes')).html('');
            var url =
                    BASE_URL + 'pages/govpergunta/' +
                    themeapi.current + '/' + name + '.json';

            /* The user asked to go to the contribute form */
            if (name === 'contribua') {
                navapi.click(3);
                $('a.theme').each(function () {
                    $(this).data('overlay').close();
                });
                return null;
            }

            $.getJSON(url, function (data) {
                /* Yes, if none is retrieved, we'll clean the
                 * element content. */
                var ct = (data !== null) ? data.content : '';
                $target.html(ct);
            });
            return $el;
        },

        goToContribForm: function () {
        }
    };

    /* -- Contribute page -- */

    $('.contribute label').click(function () {
        $('.contribute label').removeClass('selected');
        $(this).addClass('selected');
    });

    $('.contribute form').ajaxForm({
        beforeSubmit: function () {
            var form = $('.contribute form');
            form.find('input,textarea').removeClass('fielderror');
            form.find('.error').fadeOut();
            form.find('.errmsg').html('');

            if (!auth.isAuthenticated()) {
                auth.showLoginForm({
                    success: function () {
                        form.submit();
                    }
                });
                return false;
            }
            return true;
        },

        success: function (data) {
            var pData = $.parseJSON(data);
            if (pData.status === 'ok') {
                $('#form fieldset').fadeOut();
                return $('div.success').fadeIn();
            }

            /* Here we know that something is wrong */
            var form = $('.contribute form');
            var errors = pData.msg.data;
            var code = pData.code;
            var csrfToken = pData.msg.csrf;

            /* The first step now is to set the new csrf token to
             * our form. If we don't do it, we can't try to
             * register again. */
            form.find('[name=csrf]').val(csrfToken);

            /* The user made a mistake when filling the form */
            if (code === 'ValidationError') {
                for (var f in errors) {
                    var msg = errors[f][0];
                    /* O lixo do wtforms não me deixou traduzir as strings
                     * que ele gera dinâmicamente. Logo, fiz marreta. */
                    if (f === 'theme')
                        msg = 'Escolha uma das opções acima';
                    form
                        .find('[name=' + f  + ']')
                        .addClass('fielderror');
                    form
                        .find('.'+ f + '-error')
                        .html(msg);
                    form.find('div.error')
                        .html('Falta alguma informação para completar a sua proposta')
                        .fadeIn('fast');
                }
            } else {
                form.find('div.error').html(pData.msg.data).fadeIn('fast');
            }
            return null;
        }
    });

    return new ThemeApi();
})();

function show_form_again() {
    $("#form .title").attr("value", "")
    $("#form textarea").val("")
    $('.contribute label').removeClass('selected');
    $("#form input[type=radio]").attr("checked",false)

    $('#form fieldset').fadeIn();
    $('div.success').fadeOut();
}<|endoftext|>


<commit_before>/**
 * dispatcher
 * type
 * filePath
 * tplPath
 * dataPath(sync才有)
 */
const { util, DispatherTypes } = require('@foxman/helpers');
const path = require('path');
const pathToRegexp = require('path-to-regexp');

/**
 * 全局中间件,会将具体的页面转换成需要的资源
 * 1.同步
 *  { commonTplPath,commonSync }
 * 2.异步
 *  { commonAsync }
 * @param  {[type]} config [description]
 * @return {[type]}        [description]
 */

const { values, removeSuffix, addDataExt, jsonPathResolve } = util;

/**
 * ① 拦截 router
 * 遍历路由表, 并给请求对象处理,生成 dispatcher
 */
function getRouterDispatcher(
    {
        runtimeRouters,
        reqQuery,
        reqMethod,
        reqPath,
        viewRoot,
        extension,
        divideMethod,
        syncDataMatch,
        asyncDataMatch
    }
) {
    if (Number(reqQuery.mode) === 1) {
        return;
    }

    let dispatcher;
    const routers = values(runtimeRouters).reduce(
        (prev, item) => prev.concat(item),
        []
    );
    routers.some(function(router) {
        const { filePath, sync, method, url, handler } = router;

        if (divideMethod && method.toUpperCase() !== reqMethod.toUpperCase()) {
            return false;
        }

        if (!pathToRegexp(url).test(reqPath)) {
            return false;
        }

        dispatcher = {
            router,
            filePath,
            handler
        };

        if (sync) {
            const tplName = removeSuffix(filePath, extension);
            return Object.assign(dispatcher, {
                type: 'sync',
                pagePath: path.join(viewRoot, `${tplName}.${extension}`),
                dataPath: syncDataMatch(addDataExt(tplName))
            });
        }

        return Object.assign(dispatcher, {
            type: 'async',
            dataPath: asyncDataMatch(addDataExt(filePath))
        });
    });

    return dispatcher;
}

/**
 * ② 未拦截到 router 入口时，拦截 router
 */
function getResourcesDispatcher(
    {
        reqQuery,
        reqPath,
        extension,
        viewRoot,
        syncDataMatch
    }
) {
    if (Number(reqQuery.mode) !== 1 && reqPath === '/') {
        reqPath = '/index.html';
    }

    const DIR = '/';
    const SYNC = `.${extension}`;
    const dispatcherMap = {
        [DIR]: {
            type: DispatherTypes.DIR,
            dataPath: null
        },
        [SYNC]: {
            type: DispatherTypes.SYNC,
            dataPath: jsonPathResolve(syncDataMatch(reqPath))
        }
    };

    let dispatcher;

    Object.keys(dispatcherMap).some(endFlag => {
        if (reqPath.endsWith(endFlag)) {
            const { type, dataPath } = dispatcherMap[endFlag];
            dispatcher = {
                type,
                filePath: reqPath,
                pagePath: path.join(viewRoot, reqPath),
                dataPath
            };
            return true;
        }
    });

    return dispatcher;
}

module.exports = (
    {
        runtimeRouters, // structor
        extension,
        divideMethod, // string
        viewRoot, //path
        syncDataMatch,
        asyncDataMatch // fns
    }
) => {
    return function*(next) {
        const { method, query, path } = this.request;
        const [reqPath, reqMethod, reqQuery] = [path, method, query];

        const routerDispatcher = getRouterDispatcher({
            runtimeRouters,
            reqQuery,
            reqMethod,
            reqPath,
            viewRoot,
            extension,
            divideMethod,
            syncDataMatch,
            asyncDataMatch
        });
        const resourcesDispatcher = getResourcesDispatcher({
            reqPath,
            reqQuery,
            extension,
            viewRoot,
            syncDataMatch
        });
        this.dispatcher = routerDispatcher || resourcesDispatcher;

        return yield next;
    };
};
<commit_msg>fix#126 (#127)<commit_after>/**
 * dispatcher
 * type
 * filePath
 * tplPath
 * dataPath(sync才有)
 */
const { util, DispatherTypes } = require('@foxman/helpers');
const path = require('path');
const pathToRegexp = require('path-to-regexp');

/**
 * 全局中间件,会将具体的页面转换成需要的资源
 * 1.同步
 *  { commonTplPath,commonSync }
 * 2.异步
 *  { commonAsync }
 * @param  {[type]} config [description]
 * @return {[type]}        [description]
 */

const { values, removeSuffix, addDataExt, jsonPathResolve } = util;

/**
 * ① 拦截 router
 * 遍历路由表, 并给请求对象处理,生成 dispatcher
 */
function getRouterDispatcher(
    {
        runtimeRouters,
        reqQuery,
        reqMethod,
        reqPath,
        viewRoot,
        extension,
        divideMethod,
        syncDataMatch,
        asyncDataMatch
    }
) {
    if (Number(reqQuery.mode) === 1) {
        return;
    }

    let dispatcher;
    const routers = values(runtimeRouters).reduce(
        (prev, item) => prev.concat(item),
        []
    );
    routers.some(function(router) {
        const { filePath, sync, method, url, handler } = router;

        if (divideMethod && method.toUpperCase() !== reqMethod.toUpperCase()) {
            return false;
        }

        if (!pathToRegexp(url).test(reqPath)) {
            return false;
        }

        dispatcher = {
            router,
            filePath,
            handler
        };

        if (sync) {
            const tplName = removeSuffix(filePath, extension);
            return Object.assign(dispatcher, {
                type: 'sync',
                pagePath: path.join(viewRoot, `${tplName}.${extension}`),
                dataPath: syncDataMatch(addDataExt(tplName))
            });
        }

        return Object.assign(dispatcher, {
            type: 'async',
            dataPath: asyncDataMatch(addDataExt(filePath))
        });
    });

    return dispatcher;
}

/**
 * ② 未拦截到 router 入口时，拦截 router
 */
function getResourcesDispatcher(
    {
        reqQuery,
        reqPath,
        extension,
        viewRoot,
        syncDataMatch
    }
) {
    if (Number(reqQuery.mode) !== 1 && reqPath === '/') {
        reqPath = '/index.html';
    }

    const DIR = '/';
    const SYNC = `.${extension}`;
    const dispatcherMap = {
        [DIR]: {
            type: DispatherTypes.DIR,
            dataPath: null
        },
        [SYNC]: {
            type: DispatherTypes.SYNC,
            dataPath: syncDataMatch(jsonPathResolve(reqPath))
        }
    };

    let dispatcher;

    Object.keys(dispatcherMap).some(endFlag => {
        if (reqPath.endsWith(endFlag)) {
            const { type, dataPath } = dispatcherMap[endFlag];
            dispatcher = {
                type,
                filePath: reqPath,
                pagePath: path.join(viewRoot, reqPath),
                dataPath
            };
            return true;
        }
    });

    return dispatcher;
}

module.exports = (
    {
        runtimeRouters, // structor
        extension,
        divideMethod, // string
        viewRoot, //path
        syncDataMatch,
        asyncDataMatch // fns
    }
) => {
    return function*(next) {
        const { method, query, path } = this.request;
        const [reqPath, reqMethod, reqQuery] = [path, method, query];

        const routerDispatcher = getRouterDispatcher({
            runtimeRouters,
            reqQuery,
            reqMethod,
            reqPath,
            viewRoot,
            extension,
            divideMethod,
            syncDataMatch,
            asyncDataMatch
        });
        const resourcesDispatcher = getResourcesDispatcher({
            reqPath,
            reqQuery,
            extension,
            viewRoot,
            syncDataMatch
        });
        this.dispatcher = routerDispatcher || resourcesDispatcher;

        return yield next;
    };
};
<|endoftext|>


<commit_before>(function(){"use strict";var n,r,t,e,u,i;n={parseIntBase:10};e={Boolean:false,String:"",Number:0,Object:{},Array:[],Function:function(){}};t=function(r){var t;t=function(t){switch(r){case"Number":if(n.notNaN(t=parseInt(t,n.parseIntBase))){return t}break;case"String":if(n.isStringOrNumber(t)){return t+""}break;default:if(n["typeof"](t)===r.toLowerCase()){return t}}return false};return function(u,i){if(i==null){i=u}if(n["is"+r](u)){return u}if(false!==(i=t(i))){return i}return e[r]}};u=function(n,r,t){var e,u,o;if(t==null){t=[]}if(t.length<1){if(n===i.Undefined){return true}return false}for(u=0,o=t.length;u<o;u++){e=t[u];if(n(e)===r){return r}}return!r};i={Undefined:function(n){return n===void 0},Null:function(n){return n===null},Boolean:function(n){return typeof n==="boolean"},String:function(n){return typeof n==="string"},Function:function(n){return typeof n==="function"},Number:function(n){return typeof n==="number"&&n===n},Array:function(n){return typeof n==="object"&&n instanceof Array},RegExp:function(n){return n instanceof RegExp},Date:function(n){return n instanceof Date},Object:function(n){return typeof n==="object"&&!(n instanceof Array)&&!(n instanceof RegExp)&&!(n instanceof Date)&&!(n===null)},NaN:function(n){return typeof n==="number"&&n!==n}};i.StringOrNumber=function(n){return i["String"](n)||i["Number"](n)};r=true;(function(){var o,f,a;a=[];for(o in i){f=i[o];a.push(function(i,o){n["is"+i]=o;n["not"+i]=function(n){return!o(n)};n["has"+i]=function(){return u(o,r,arguments)};n["all"+i]=function(){return u(o,!r,arguments)};if(i in e){return n["force"+i]=t(i)}}(o,f))}return a})();n["typeof"]=function(n){var r,t;for(t in i){r=i[t];if(r(n)===true){return t.toLowerCase()}}return"unknown"};if(typeof window!=="undefined"&&window!==null){window.Types=n}else if(module){module.exports=n}}).call(this);<commit_msg>smaller file<commit_after>(function(){"use strict";var n,t,r,e,u,o;n={parseIntBase:10},e={Boolean:!1,String:"",Number:0,Object:{},Array:[],Function:function(){}},r=function(t){var r;return r=function(r){switch(t){case"Number":if(n.notNaN(r=parseInt(r,n.parseIntBase)))return r;break;case"String":if(n.isStringOrNumber(r))return r+"";break;default:if(n["typeof"](r)===t.toLowerCase())return r}return!1},function(u,o){return null==o&&(o=u),n["is"+t](u)?u:!1!==(o=r(o))?o:e[t]}},u=function(n,t,r){var e,u,i;if(null==r&&(r=[]),r.length<1)return n===o.Undefined?!0:!1;for(u=0,i=r.length;i>u;u++)if(e=r[u],n(e)===t)return t;return!t},o={Undefined:function(n){return void 0===n},Null:function(n){return null===n},Boolean:function(n){return"boolean"==typeof n},String:function(n){return"string"==typeof n},Function:function(n){return"function"==typeof n},Number:function(n){return"number"==typeof n&&n===n},Array:function(n){return"object"==typeof n&&n instanceof Array},RegExp:function(n){return"object"==typeof n&&n instanceof RegExp},Date:function(n){return"object"==typeof n&&n instanceof Date},Object:function(n){return!("object"!=typeof n||n instanceof Array||n instanceof RegExp||n instanceof Date||null===n)},NaN:function(n){return"number"==typeof n&&n!==n}},o.StringOrNumber=function(n){return o.String(n)||o.Number(n)},t=!0,function(){var i,f,c;c=[];for(i in o)f=o[i],c.push(function(o,i){return n["is"+o]=i,n["not"+o]=function(n){return!i(n)},n["has"+o]=function(){return u(i,t,arguments)},n["all"+o]=function(){return u(i,!t,arguments)},o in e?n["force"+o]=r(o):void 0}(i,f));return c}(),n["typeof"]=function(n){var t,r;for(r in o)if(t=o[r],t(n)===!0)return r.toLowerCase();return"unknown"},"undefined"!=typeof window&&null!==window?window.Types=n:module&&(module.exports=n)}).call(this);<|endoftext|>


<commit_before>// Load the Visualization API
google.load('visualization', '1.0', {'packages':['corechart']});

$(
    /**
     * Simple Google Charts wrapper for drawing activity graphs. Will make callbacks to server for data.
     *
     * Requires "https://www.google.com/jsapi"
     *
     * Template modified from Google charts Column Chart example.
     */
    function(){

        function drawVisualization(arrays, title, target_id, width, height, vTitle, hTitle) {
            // Create and populate the data table.
            var data =
                google.visualization.arrayToDataTable(
                    arrays
                );

            // Create and draw the visualization.
            new google.visualization.ColumnChart(document.getElementById(target_id)).
                draw(data,
                     {title: title,
                      width:width, height:height,
                      isStacked: true,
                      vAxis: {title: vTitle},
                      hAxis: {title: hTitle}}
                    );
        }
        function drawUserGraph(){
            function draw(model, response){
                data = { title: model.get('title'), width: 600, height:400, vTitle: model.get("vTitle"), hTitle: model.get("hTitle"),
                         table: model.get('table')
                       };
                drawVisualization(data.table, data.title, 'usergraph', data.width, data.height, data.vTitle, data.hTitle);
            };
            new UserGraph({id: getUser()}).
                fetch({success: draw, error: draw});
        }

        function getUser(){
            return $('#user_pk').val();
        }

        // Set a callback to run when the Google Visualization API is loaded.
        google.setOnLoadCallback(drawUserGraph);
    }
);
<commit_msg>*** empty log message ***<commit_after>// Load the Visualization API
google.load('visualization', '1.0', {'packages':['corechart']});
/**
 * Simple Google Charts wrapper for drawing activity graphs. Will make callbacks to server for data.
 *
 * Requires "https://www.google.com/jsapi"
 *
 * Template modified from Google charts Column Chart example.
 */
ActivityGraphing = function(){
    function drawVisualization(arrays, title, target, width, height, vTitle, hTitle) {
        google.setOnLoadCallback(function(){
                                     // Create and populate the data table.
                                     var data =
                                         google.visualization.arrayToDataTable(
                                             arrays
                                         );

                                     // Create and draw the visualization.
                                     new google.visualization.ColumnChart(document.getElementById(target)).
                                         draw(data,
                                              {title: title,
                                               width:width, height:height,
                                               isStacked: true,
                                               vAxis: {title: vTitle},
                                               hAxis: {title: hTitle}}
                                             );
                                 }
                                );
    }
    function delayedDraw(height, width, target){
        function draw(model, response){
            var data = { title: model.get('title'), width: width, height:height, vTitle: model.get("vTitle"), hTitle: model.get("hTitle"),
                         table: model.get('table')
                       };
            drawVisualization(data.table, data.title, target, data.width, data.height, data.vTitle, data.hTitle);
        };
        return draw;
    }

    function drawUserGraph(user, height, width, target){
        var draw = delayedDraw(height, width, target);
        new UserGraph({id:user}).
            fetch({success: draw});
    }
    function drawProjectGraph(project, height, width, target){
        var draw = delayedDraw(height, width, target);
        new ProjectGraph({id:project}).fetch({success: draw});
    }

    return {
        drawUserGraph: drawUserGraph,
        drawProjectGraph: drawProjectGraph
    };
};
<|endoftext|>