<commit_before>"use strict";

const assert = require("assert");
const shell = require("shelljs");
const fs = require("fs-extra");
const xml2js = require("xml2js");
const readline = require("readline");

describe("flags", () => {
  describe("--add-dependencies", () => {
    beforeEach(() => {
      shell.mkdir("-p", "tmp");
      shell.cd("tmp");
    });

    afterEach(() => {
      shell.cd("..");
      shell.rm("-Rf", "tmp");
    });

    it("should copy over missing dependencies to the destination", done => {
      shell.cp("-R", "../tests/add-dependency-test/*", ".");

      shell.exec("elm-test --add-dependencies test-elm-package.json", {
        silent: true
      });

      fs.readJson("test-elm-package.json", "utf8", (err, data) => {
        if (err) throw err;

        assert.equal(data.dependencies.foo, "1.0.0 <= v < 2.0.0");
        done();
      });
    });

    it("should fail if the destination file does not exist", () => {
      shell.cp("-R", "../tests/add-dependency-test/*", ".");
      shell.rm("-R", "test-elm-package.json");

      const runResult = shell.exec(
        "elm-test --add-dependencies test-elm-package.json",
        { silent: true }
      );

      assert.notEqual(runResult.code, 0);
    });

    it("should fail if the current directory does not contain an elm-package.json", () => {
      shell.cp("-R", "../tests/add-dependency-test/*", ".");
      shell.rm("-R", "elm-package.json");

      const runResult = shell.exec(
        "elm-test --add-dependencies test-elm-package.json",
        { silent: true }
      );

      assert.notEqual(runResult.code, 0);
    });
  });

  describe("--help", () => {
    it("Should print the usage", () => {
      const runResult = shell.exec("elm-test --help", { silent: true });
      // Checking against a fixture is brittle here
      // For now, check that the output is non-empty.
      assert.ok(runResult.stdout.length > 0);
    });

    it("Should exit indicating failure", () => {
      const runResult = shell.exec("elm-test --help", { silent: true });
      assert.notEqual(0, runResult.code);
    });
  });

  describe("--report", () => {
    it("Should be able to report json lines", () => {
      const runResult = shell.exec(
        "elm-test --report=json tests/OnePassing.elm",
        { silent: true }
      );

      let linesReceived = 0;

      runResult.stdout.split("\n").forEach(line => {
        if (line.length === 0) {
          return;
        }

        linesReceived += 1;
        assert.doesNotThrow(() => JSON.parse(line));
      });

      assert.ok(linesReceived > 0);
    }).timeout(60000);

    it("Should be able to report passing junit xml", done => {
      const runResult = shell.exec(
        "elm-test --report=junit tests/OnePassing.elm",
        { silent: true }
      );

      xml2js.parseString(runResult.stdout, (err, data) => {
        if (err) throw err;

        assert.ok(data);
        done();
      });
    }).timeout(60000);
    it("Should be able to report failing junit xml", done => {
      const runResult = shell.exec(
        "elm-test --report=junit tests/OneFailing.elm",
        { silent: true }
      );

      xml2js.parseString(runResult.stdout, (err, data) => {
        if (err) throw err;

        assert.ok(data);
        done();
      });
    }).timeout(60000);
  });

  describe("--seed", () => {
    it("Should use and, thus, show the proper seed in the JSON report", () => {
      const runResult = shell.exec(
        "elm-test --report=json --seed=12345 tests/OnePassing.elm",
        { silent: true }
      );

      const firstOutput = JSON.parse(runResult.stdout.split("\n")[0]);

      assert.equal("12345", firstOutput.initialSeed);
    }).timeout(60000);
  });

  describe("--fuzz", () => {
    it("Should default to 100", () => {
      const runResult = shell.exec(
        "elm-test --report=json tests/OnePassing.elm",
        { silent: true }
      );

      const firstOutput = JSON.parse(runResult.stdout.split("\n")[0]);

      assert.equal("100", firstOutput.fuzzRuns);
    }).timeout(60000);

    it("Should use the provided value", () => {
      const runResult = shell.exec(
        "elm-test --fuzz=5 --report=json tests/OnePassing.elm",
        { silent: true }
      );

      const firstOutput = JSON.parse(runResult.stdout.split("\n")[0]);

      assert.equal("5", firstOutput.fuzzRuns);
    }).timeout(60000);
  });

  describe("--compiler", () => {
    it("Should fail if the given compiler can't be executed", () => {
      const runResult = shell.exec(
        "elm-test --compiler=foobar tests/OnePassing.elm",
        { silent: true }
      );

      assert.notEqual(0, runResult.code);
    }).timeout(5000); // This sometimes needs more time to run on Travis.
  });

  describe("--watch", () => {
    it("Should re-run tests if a test file is touched", done => {
      const child = shell.exec(
        "elm-test --report=json --watch tests/OnePassing.elm",
        { silent: true, async: true }
      );

      let hasRetriggered = false;

      readline.createInterface(child.stdout).on("line", line => {
        const parsedLine = JSON.parse(line);
        if (parsedLine.event === "runComplete" && !hasRetriggered) {
          shell.touch("tests/OnePassing.elm");
          hasRetriggered = true;
        }

        if (parsedLine.event == "runComplete" && hasRetriggered) {
          child.kill();
          done();
        }
      });
    }).timeout(60000);
  });
});
<commit_msg>Use cross-spawn over shell.exec<commit_after>"use strict";

const assert = require("assert");
const shell = require("shelljs");
const spawn = require("cross-spawn");
const fs = require("fs-extra");
const xml2js = require("xml2js");
const readline = require("readline");

describe("flags", () => {
  describe("--add-dependencies", () => {
    beforeEach(() => {
      shell.mkdir("-p", "tmp");
      shell.cd("tmp");
    });

    afterEach(() => {
      shell.cd("..");
      shell.rm("-Rf", "tmp");
    });

    it("should copy over missing dependencies to the destination", done => {
      shell.cp("-R", "../tests/add-dependency-test/*", ".");

      shell.exec("elm-test --add-dependencies test-elm-package.json", {
        silent: true
      });

      fs.readJson("test-elm-package.json", "utf8", (err, data) => {
        if (err) throw err;

        assert.equal(data.dependencies.foo, "1.0.0 <= v < 2.0.0");
        done();
      });
    });

    it("should fail if the destination file does not exist", () => {
      shell.cp("-R", "../tests/add-dependency-test/*", ".");
      shell.rm("-R", "test-elm-package.json");

      const runResult = shell.exec(
        "elm-test --add-dependencies test-elm-package.json",
        { silent: true }
      );

      assert.notEqual(runResult.code, 0);
    });

    it("should fail if the current directory does not contain an elm-package.json", () => {
      shell.cp("-R", "../tests/add-dependency-test/*", ".");
      shell.rm("-R", "elm-package.json");

      const runResult = shell.exec(
        "elm-test --add-dependencies test-elm-package.json",
        { silent: true }
      );

      assert.notEqual(runResult.code, 0);
    });
  });

  describe("--help", () => {
    it("Should print the usage", () => {
      const runResult = shell.exec("elm-test --help", { silent: true });
      // Checking against a fixture is brittle here
      // For now, check that the output is non-empty.
      assert.ok(runResult.stdout.length > 0);
    });

    it("Should exit indicating failure", () => {
      const runResult = shell.exec("elm-test --help", { silent: true });
      assert.notEqual(0, runResult.code);
    });
  });

  describe("--report", () => {
    it("Should be able to report json lines", () => {
      const runResult = shell.exec(
        "elm-test --report=json tests/OnePassing.elm",
        { silent: true }
      );

      let linesReceived = 0;

      runResult.stdout.split("\n").forEach(line => {
        if (line.length === 0) {
          return;
        }

        linesReceived += 1;
        assert.doesNotThrow(() => JSON.parse(line));
      });

      assert.ok(linesReceived > 0);
    }).timeout(60000);

    it("Should be able to report passing junit xml", done => {
      const runResult = shell.exec(
        "elm-test --report=junit tests/OnePassing.elm",
        { silent: true }
      );

      xml2js.parseString(runResult.stdout, (err, data) => {
        if (err) throw err;

        assert.ok(data);
        done();
      });
    }).timeout(60000);
    it("Should be able to report failing junit xml", done => {
      const runResult = shell.exec(
        "elm-test --report=junit tests/OneFailing.elm",
        { silent: true }
      );

      xml2js.parseString(runResult.stdout, (err, data) => {
        if (err) throw err;

        assert.ok(data);
        done();
      });
    }).timeout(60000);
  });

  describe("--seed", () => {
    it("Should use and, thus, show the proper seed in the JSON report", () => {
      const runResult = shell.exec(
        "elm-test --report=json --seed=12345 tests/OnePassing.elm",
        { silent: true }
      );

      const firstOutput = JSON.parse(runResult.stdout.split("\n")[0]);

      assert.equal("12345", firstOutput.initialSeed);
    }).timeout(60000);
  });

  describe("--fuzz", () => {
    it("Should default to 100", () => {
      const runResult = shell.exec(
        "elm-test --report=json tests/OnePassing.elm",
        { silent: true }
      );

      const firstOutput = JSON.parse(runResult.stdout.split("\n")[0]);

      assert.equal("100", firstOutput.fuzzRuns);
    }).timeout(60000);

    it("Should use the provided value", () => {
      const runResult = shell.exec(
        "elm-test --fuzz=5 --report=json tests/OnePassing.elm",
        { silent: true }
      );

      const firstOutput = JSON.parse(runResult.stdout.split("\n")[0]);

      assert.equal("5", firstOutput.fuzzRuns);
    }).timeout(60000);
  });

  describe("--compiler", () => {
    it("Should fail if the given compiler can't be executed", () => {
      const runResult = shell.exec(
        "elm-test --compiler=foobar tests/OnePassing.elm",
        { silent: true }
      );

      assert.notEqual(0, runResult.code);
    }).timeout(5000); // This sometimes needs more time to run on Travis.
  });

  describe("--watch", () => {
    it("Should re-run tests if a test file is touched", done => {
      const child = spawn(
        "elm-test",
        ["--report=json", "--watch", "tests/OnePassing.elm"],
        { silent: true }
      );

      let hasRetriggered = false;

      readline.createInterface(child.stdout).on("line", line => {
        const parsedLine = JSON.parse(line);
        if (parsedLine.event === "runComplete" && !hasRetriggered) {
          shell.touch("tests/OnePassing.elm");
          hasRetriggered = true;
        }

        if (parsedLine.event == "runComplete" && hasRetriggered) {
          child.kill();
          done();
        }
      });
    }).timeout(60000);
  });
});
<|endoftext|>


<commit_before>/**
 * jquery-analogpad-plugin - jQuery plugin for emulate analog pad controller.
 *
 * https://github.com/hakobera/jquery-analogpad-plugin
 * version: 0.1
 *
 * Copyright 2011, Kazuyuki Honda (@hakobera)
 * Licensed under the MIT licenses (MIT-LICENSE.txt).
 */
jQuery.fn.extend({
    analogpad: function(args) {
        var clicked = false;
        var self = $(this);
        var x, y, sx, sy, cx, cy;

        self.addClass('analogpad')
        var base = $('<div>').addClass('analogpad-base').appendTo(self);
        var pad = $('<div>').addClass('analogpad-pad').appendTo(base);

        x =  cx = pad.css('left').replace("px", "") | 0;
        y =  cy = pad.css('top').replace("px", "") | 0;

        var onMoveStart = function() {
            clicked = true;
            var e = (event.touches ? event.touches[0] : event);
            sx = e.pageX | 0;
            sy = e.pageY | 0;
        };

        var onMoveEnd = function() {
            pad.css({ 'left': '', 'top': ''});
            clicked = false;
            x = cx;
            y = cy;
        };

        var onMove = function() {
            if (clicked) {
                event.preventDefault();
                var e = (event.touches ? event.touches[0] : event);
                var px = e.pageX | 0;
                var py =  e.pageY | 0;
                var left = pad.css('left').replace("px", "") | 0;
                var top = pad.css('top').replace("px", "") | 0;
                var dx = px - sx;
                var dy = py - sy;

                x = left + dx;
                y = top + dy;
                sx = px;
                sy = py;
                x = Math.max(0, Math.min(2*cx, x));
                y = Math.max(0, Math.min(2*cy, y));

                pad.css({ 'left': x + 'px', 'top': y + 'px'});
            }
        };

        pad.mousedown(onMoveStart);
        pad.bind('touchstart', onMoveStart);

        pad.mouseup(onMoveEnd);
        pad.mouseout(onMoveEnd);
        pad.bind('touchend', onMoveEnd);

        pad.mousemove(onMove);
        pad.bind('touchmove', onMove);

        var api = {
            /**
             * Return x axis value. Right direction is positive.
             * @return {float} value between -1.0 and 1.0.
             */
            getX: function() {
                return (x - cx) / cx;
            },

            /**
             * Return y axis value. Up direction is positive.
             * @return {float} Value between -1.0 and 1.0.
             */
            getY: function() {
                return (cy - y) / cy;
            },

            /**
             * Return x and y axis value.
             * @return {Object} key x: value between -1.0 and 1.0, key y: value between -1.0 and 1.0.
             */
            input: function() {
                return {
                    x: api.getX(),
                    y: api.getY()
                };
            }
        };

        return api;
    }
});<commit_msg>Set wait for onMove event prevent slow down cause event queue overflow.<commit_after>/**
 * jquery-analogpad-plugin - jQuery plugin for emulate analog pad controller.
 *
 * https://github.com/hakobera/jquery-analogpad-plugin
 * version: 0.1
 *
 * Copyright 2011, Kazuyuki Honda (@hakobera)
 * Licensed under the MIT licenses (MIT-LICENSE.txt).
 */
jQuery.fn.extend({
    analogpad: function(args) {
        var clicked = false;
        var self = $(this);
        var x, y, sx, sy, cx, cy;

        self.addClass('analogpad')
        var base = $('<div>').addClass('analogpad-base').appendTo(self);
        var pad = $('<div>').addClass('analogpad-pad').appendTo(base);

        x =  cx = pad.css('left').replace("px", "") | 0;
        y =  cy = pad.css('top').replace("px", "") | 0;

        var onMoveStart = function() {
            clicked = true;
            var e = (event.touches ? event.touches[0] : event);
            sx = e.pageX | 0;
            sy = e.pageY | 0;
        };

        var onMoveEnd = function() {
            pad.css({ 'left': '', 'top': ''});
            clicked = false;
            x = cx;
            y = cy;
        };

        var wait = false;
        var onMove = function() {
            if (clicked && !wait) {
                wait = true;

                event.preventDefault();
                var e = (event.touches ? event.touches[0] : event);
                var px = e.pageX | 0;
                var py =  e.pageY | 0;
                var left = pad.css('left').replace("px", "") | 0;
                var top = pad.css('top').replace("px", "") | 0;
                var dx = px - sx;
                var dy = py - sy;

                x = left + dx;
                y = top + dy;
                sx = px;
                sy = py;
                x = Math.max(0, Math.min(2*cx, x));
                y = Math.max(0, Math.min(2*cy, y));

                pad.css({ 'left': x + 'px', 'top': y + 'px'});

                setTimeout(function() { wait = false; }, 100);
            }
        };

        pad.mousedown(onMoveStart);
        pad.bind('touchstart', onMoveStart);

        pad.mouseup(onMoveEnd);
        pad.mouseout(onMoveEnd);
        pad.bind('touchend', onMoveEnd);

        pad.mousemove(onMove);
        pad.bind('touchmove', onMove);

        var api = {
            /**
             * Return x axis value. Right direction is positive.
             * @return {float} value between -1.0 and 1.0.
             */
            getX: function() {
                return (x - cx) / cx;
            },

            /**
             * Return y axis value. Up direction is positive.
             * @return {float} Value between -1.0 and 1.0.
             */
            getY: function() {
                return (cy - y) / cy;
            },

            /**
             * Return x and y axis value.
             * @return {Object} key x: value between -1.0 and 1.0, key y: value between -1.0 and 1.0.
             */
            input: function() {
                return {
                    x: api.getX(),
                    y: api.getY()
                };
            }
        };

        return api;
    }
});<|endoftext|>


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

    var _t = openerp._t;
    var hash = "#advanced-view-editor";

    var website = openerp.website;
    website.add_template_file('/website/static/src/xml/website.ace.xml');

    website.Ace = openerp.Widget.extend({
        launchAce: function (e) {
            if (e) {
                e.preventDefault();
            }
            if (this.globalEditor) {
                this.globalEditor.open();
            } else {
                this.globalEditor = new website.ace.ViewEditor(this);
                this.globalEditor.appendTo($(document.body));
            }
        },
    });

    website.ace = {};

    website.ace.XmlDocument = openerp.Class.extend({
        init: function (text) {
            this.xml = text;
        },
        isWellFormed: function () {
            var error;
            if (document.implementation.createDocument) {
                // use try catch for ie
                try {
                    var dom = new DOMParser().parseFromString(this.xml, "text/xml");
                    error = dom.getElementsByTagName("parsererror");
                    return error.length === 0 || $(error).text();
                } catch (e) {}
            }
            if (window.ActiveXObject) {
                // IE
                var msDom = new ActiveXObject("Microsoft.XMLDOM");
                msDom.async = false;
                msDom.loadXML(this.xml);
                return !msDom.parseError.errorCode || msDom.parseError.reason + "\nline " + msDom.parseError.line;
            }
            return true;
        },
        format: function () {
            return vkbeautify.xml(this.xml, 4);
        },
    });

    website.ace.ViewOption = openerp.Widget.extend({
        template: 'website.ace_view_option',
        init: function (parent, options) {
            this.view_id = options.id;
            this.view_name = options.name;

            var indent = _.str.repeat("- ", options.level);
            this.view_name = _.str.sprintf("%s%s", indent, options.name);
            this._super(parent);
        },
    });

    website.ace.ViewEditor = openerp.Widget.extend({
        resizing: false,
        refX: 0,
        minWidth: 40,
        template: 'website.ace_view_editor',
        events: {
            'change #ace-view-list': 'displaySelectedView',
            'click .js_include_bundles': 'loadTemplates',
            'click button[data-action=save]': 'saveViews',
            'click button[data-action=format]': 'formatXml',
            'click button[data-action=close]': 'close',
        },
        init: function (parent) {
            this.buffers = {};
            this.views = {};
            this._super(parent);
        },
        start: function () {
            var self = this;
            self.aceEditor = ace.edit(self.$('#ace-view-editor')[0]);
            self.aceEditor.setTheme("ace/theme/monokai");
            self.loadTemplates();

            var $editor = self.$('.ace_editor');
            function resizeEditor (target) {
                var width = Math.min(document.body.clientWidth, Math.max(parseInt(target, 10), self.minWidth));
                $editor.width(width);
                self.aceEditor.resize();
                self.$el.width(width);
            }
            function resizeEditorHeight(height) {
                self.$el.css('top', height);
                self.$('.ace_editor').css('bottom', height);
            }
            function storeEditorWidth() {
                window.localStorage.setItem('ace_editor_width', self.$el.width());
            }
            function readEditorWidth() {
                var width = window.localStorage.getItem('ace_editor_width');
                return parseInt(width || 720, 10);
            }
            function startResizing (e) {
                self.refX = e.pageX;
                self.resizing = true;
            }
            function stopResizing () {
                self.resizing = false;
            }
            function updateWidth (e) {
                if (self.resizing) {
                    var offset = e.pageX - self.refX;
                    var width = self.$el.width() - offset;
                    self.refX = e.pageX;
                    resizeEditor(width);
                    storeEditorWidth();
                }
            }
            document.body.addEventListener('mouseup', stopResizing, true);
            self.$('.ace_gutter').mouseup(stopResizing).mousedown(startResizing).click(stopResizing);
            $(document).mousemove(updateWidth);
            $('button[data-action=edit]').click(function () {
               self.close();
            });
            this.getParent().on('change:height', this, function (editor) {
                resizeEditorHeight(this.getParent().$el.outerHeight()+2);
            });
            resizeEditor(readEditorWidth());
            resizeEditorHeight(this.getParent().$el.outerHeight()+2);
        },
        loadTemplates: function () {
            var self = this;
            var args = {
                xml_id: $(document.documentElement).data('view-xmlid'),
                full: true,
                bundles: this.$('.js_include_bundles')[0].checked
            };
            return openerp
                .jsonRpc('/website/customize_template_get', 'call', args)
                .then(function (views) {
                    self.loadViews.call(self, views);
                    self.open.call(self);
                    var curentHash = window.location.hash;
                    var indexOfView = curentHash.indexOf("?view=");
                    if (indexOfView >= 0) {
                        var viewId = parseInt(curentHash.substring(indexOfView + 6, curentHash.length), 10);
                        self.$('#ace-view-list').val(viewId).change();
                    } else {
                        if (views.length >= 2) {
                            var mainTemplate = views[1];
                            self.$('#ace-view-list').val(mainTemplate.id).trigger('change');
                        }
                        window.location.hash = hash;
                    }
                });
        },
        loadViews: function (views) {
            var $viewList = this.$('#ace-view-list').empty();
            _(this.buildViewGraph(views)).each(function (view) {
                if (!view.id) { return; }

                this.views[view.id] = view;
                new website.ace.ViewOption(this, view).appendTo($viewList);
                this.loadView(view.id);
            }.bind(this));
        },
        buildViewGraph: function (views) {
            var activeViews = _.uniq(_.filter(views, function (view) {
               return view.active;
            }), false, function (view) {
                return view.id;
            });
            var index = {};
            var roots = [];
            _.each(activeViews, function (view) {
                index[view.id] = view;
                view.children = [];
            });
            _.each(index, function (view) {
                var parentId = view.inherit_id;
                if (parentId && index[parentId]) {
                    index[parentId].children.push(view);
                } else {
                    roots.push(view);
                }
            });
            var result = [];
            function visit (node, level) {
                node.level = level;
                result.push(node);
                _.each(node.children, function (child) {
                    visit(child, level + 1);
                });
            }
            _.each(roots, function (node) {
                visit(node, 0);
            });
            return result;
        },
        loadView: function (id) {
            var viewId = parseInt(id, 10);
            var self = this;
            openerp.jsonRpc('/web/dataset/call', 'call', {
                model: 'ir.ui.view',
                method: 'read',
                args: [[viewId], ['arch'], website.get_context()],
            }).then(function(result) {
                var editingSession = self.buffers[viewId] = new ace.EditSession(result[0].arch);
                editingSession.setMode("ace/mode/xml");
                editingSession.setUndoManager(new ace.UndoManager());
                editingSession.on("change", function () {
                    setTimeout(function () {
                        var $option = self.$('#ace-view-list').find('[value='+viewId+']');
                        var bufferName = $option.text();
                        var dirtyMarker = " (unsaved changes)";
                        var isDirty = editingSession.getUndoManager().hasUndo();
                        if (isDirty && bufferName.indexOf(dirtyMarker) < 0) {
                            $option.text(bufferName + dirtyMarker);
                        } else if (!isDirty && bufferName.indexOf(dirtyMarker) > 0) {
                            $option.text(bufferName.substring(0, bufferName.indexOf(dirtyMarker)));
                        }
                    }, 1);
                });
                if (viewId === self.selectedViewId()) {
                    self.displayView.call(self, viewId);
                }
            });
        },
        selectedViewId: function () {
            return parseInt(this.$('#ace-view-list').val(), 10);
        },
        displayView: function (id) {
            var viewId = parseInt(id, 10);
            var editingSession = this.buffers[viewId];
            if (editingSession) {
                this.aceEditor.setSession(editingSession);
                this.$('#ace-view-id').text(_.str.sprintf(
                    _t("Template ID: %s"),
                    this.views[viewId].xml_id));
            }
        },
        displaySelectedView: function () {
            this.displayView(this.selectedViewId());
            this.updateHash();
        },
        formatXml: function () {
            var xml = new website.ace.XmlDocument(this.aceEditor.getValue());
            this.aceEditor.setValue(xml.format());
        },
        saveViews: function () {
            var self = this;
            var toSave = _.filter(_.map(self.buffers, function (editingSession, viewId) {
                return {
                    id: parseInt(viewId, 10),
                    isDirty: editingSession.getUndoManager().hasUndo(),
                    text: editingSession.getValue(),
                };
            }), function (session) {
                return session.isDirty;
            });
            this.clearError();
            var requests = _.map(toSave, function (session) {
                return self.saveView(session);
            });
            $.when.apply($, requests).then(function () {
                self.reloadPage.call(self);
            }).fail(function (source, session, error) {
                self.displayError.call(self, source, session, error);
            });
        },
        saveView: function (session) {
            var self = this;
            var xml = new website.ace.XmlDocument(session.text);
            var isWellFormed = xml.isWellFormed();
            var def = $.Deferred();
            if (isWellFormed === true) {
                openerp.jsonRpc('/web/dataset/call', 'call', {
                    model: 'ir.ui.view',
                    method: 'write',
                    args: [[session.id], { 'arch':  xml.xml }, website.get_context()],
                }).then(function () {
                    def.resolve();
                }).fail(function (source, error) {
                    def.reject("server", session, error);
                });
            } else {
                def.reject(null, session, isWellFormed);
            }
            return def;
        },
        updateHash: function () {
            window.location.hash = hash + "?view=" + this.selectedViewId();
        },
        reloadPage: function () {
            this.updateHash();
            window.location.reload();
        },
        clearError: function () {
            this.$(".ace_layer.ace_text-layer .ace_line").css("background", "");
        },
        displayError: function (source, session, error) {
            var self = this;
            var line, test;
            // format error message
            var message = _.isString(error) ? error
                : (error && error.data && error.data.arguments && error.data.arguments[0] === "Access Denied") ? "Access denied: please sign in"
                : (error && error.data && error.data.message) ? error.data.message
                : (error && error.message) ? error.message
                : "Unexpected error";
            if (source == "server") {
                message = eval(message.replace(/^\(/g, '([')
                    .replace(/\)$/g, '])')
                    .replace(/u'/g, "'")
                    .replace(/<([^>]+)>/g, '<\$1>'))[1];
                line = -1;
            } else {
                line = message.match(/line ([0-9]+)/i);
                line = line ? parseInt(line[1],10) : -1;
                test = new RegExp("^\\s*"+line+"\\s*$");
            }

            function gotoline() {
                self.aceEditor.gotoLine(line);
                setTimeout(function () {
                    var $lines = self.$(".ace_editor .ace_gutter .ace_gutter-cell");
                    var index = $lines.filter(function () {
                        return test.test($(this).text());
                    }).index();
                    if (index>0) {
                        self.$(".ace_layer.ace_text-layer .ace_line:eq(" + index + ")").css("background", "#661100");
                    }
                },100);
            }
            function onchangeSession (e) {
                self.aceEditor.off('changeSession', onchangeSession);
                gotoline();
            }

            var $list = this.$("#ace-view-list");
            if (+$list.val() == session.id) {
                if (line>-1) gotoline();
            } else {
                if (line) self.aceEditor.on('changeSession', onchangeSession);
                this.$("#ace-view-list").val(session.id).change();
            }

            var $dialog = $(openerp.qweb.render('website.error_dialog', {
                title: session.text.match(/\s+name=['"]([^'"]+)['"]/i)[1],
                message:"Malformed XML document:
" + message
            }));
            $dialog.appendTo("body");
            $dialog.modal('show');
        },
        open: function () {
            this.$el.removeClass('oe_ace_closed').addClass('oe_ace_open');
        },
        close: function () {
            window.location.hash = "";
            this.$el.removeClass('oe_ace_open').addClass('oe_ace_closed');
        },
    });

    website.ready().done(function() {
        var ace = new website.Ace();
        $(document.body).on('click', 'a[data-action=ace]', function() {
            ace.launchAce();
        });
    });

})();
<commit_msg>[FIX] unmerged ace changes<commit_after>(function () {
    'use strict';

    var _t = openerp._t;
    var hash = "#advanced-view-editor";

    var website = openerp.website;
    website.add_template_file('/website/static/src/xml/website.ace.xml');

    website.Ace = openerp.Widget.extend({
        launchAce: function (e) {
            if (e) {
                e.preventDefault();
            }
            if (this.globalEditor) {
                this.globalEditor.open();
            } else {
                this.globalEditor = new website.ace.ViewEditor(this);
                this.globalEditor.appendTo($(document.body));
            }
        },
    });

    website.ace = {};

    website.ace.XmlDocument = openerp.Class.extend({
        init: function (text) {
            this.xml = text;
        },
        isWellFormed: function () {
            var error;
            if (document.implementation.createDocument) {
                // use try catch for ie
                try {
                    var dom = new DOMParser().parseFromString(this.xml, "text/xml");
                    error = dom.getElementsByTagName("parsererror");
                    return error.length === 0 || $(error).text();
                } catch (e) {}
            }
            if (window.ActiveXObject) {
                // IE
                var msDom = new ActiveXObject("Microsoft.XMLDOM");
                msDom.async = false;
                msDom.loadXML(this.xml);
                return !msDom.parseError.errorCode || msDom.parseError.reason + "\nline " + msDom.parseError.line;
            }
            return true;
        },
        format: function () {
            return vkbeautify.xml(this.xml, 4);
        },
    });

    website.ace.ViewOption = openerp.Widget.extend({
        template: 'website.ace_view_option',
        init: function (parent, options) {
            this.view_id = options.id;
            this.view_name = options.name;

            var indent = _.str.repeat("- ", options.level);
            this.view_name = _.str.sprintf("%s%s", indent, options.name);
            this._super(parent);
        },
    });

    website.ace.ViewEditor = openerp.Widget.extend({
        resizing: false,
        refX: 0,
        minWidth: 40,
        template: 'website.ace_view_editor',
        events: {
            'change #ace-view-list': 'displaySelectedView',
            'click button[data-action=save]': 'saveViews',
            'click button[data-action=format]': 'formatXml',
            'click button[data-action=close]': 'close',
        },
        init: function (parent) {
            this.buffers = {};
            this.views = {};
            this._super(parent);
        },
        start: function () {
            var self = this;
            self.aceEditor = ace.edit(self.$('#ace-view-editor')[0]);
            self.aceEditor.setTheme("ace/theme/monokai");
            var viewId = $(document.documentElement).data('view-xmlid');
            openerp.jsonRpc('/website/customize_template_get', 'call', {
                'xml_id': viewId,
                'full': true,
            }).then(function (views) {
                self.loadViews.call(self, views);
                self.open.call(self);
                var curentHash = window.location.hash;
                var indexOfView = curentHash.indexOf("?view=");
                if (indexOfView >= 0) {
                    var viewId = parseInt(curentHash.substring(indexOfView + 6, curentHash.length), 10);
                    self.$('#ace-view-list').val(viewId).change();
                } else {
                    if (views.length >= 2) {
                        var mainTemplate = views[1];
                        self.$('#ace-view-list').val(mainTemplate.id).trigger('change');
                    }
                    window.location.hash = hash;
                }
            });

            var $editor = self.$('.ace_editor');
            function resizeEditor (target) {
                var width = Math.min(document.body.clientWidth, Math.max(parseInt(target, 10), self.minWidth));
                $editor.width(width);
                self.aceEditor.resize();
                self.$el.width(width);
            }
            function resizeEditorHeight(height) {
                self.$el.css('top', height);
                self.$('.ace_editor').css('bottom', height);
            }
            function storeEditorWidth() {
                window.localStorage.setItem('ace_editor_width', self.$el.width());
            }
            function readEditorWidth() {
                var width = window.localStorage.getItem('ace_editor_width');
                return parseInt(width || 720, 10);
            }
            function startResizing (e) {
                self.refX = e.pageX;
                self.resizing = true;
            }
            function stopResizing () {
                self.resizing = false;
            }
            function updateWidth (e) {
                if (self.resizing) {
                    var offset = e.pageX - self.refX;
                    var width = self.$el.width() - offset;
                    self.refX = e.pageX;
                    resizeEditor(width);
                    storeEditorWidth();
                }
            }
            document.body.addEventListener('mouseup', stopResizing, true);
            self.$('.ace_gutter').mouseup(stopResizing).mousedown(startResizing).click(stopResizing);
            $(document).mousemove(updateWidth);
            $('button[data-action=edit]').click(function () {
               self.close();
            });
            this.getParent().on('change:height', this, function (editor) {
                resizeEditorHeight(this.getParent().$el.outerHeight()+2);
            });
            resizeEditor(readEditorWidth());
            resizeEditorHeight(this.getParent().$el.outerHeight()+2);
        },
        loadViews: function (views) {
            var $viewList = this.$('#ace-view-list');
            _(this.buildViewGraph(views)).each(function (view) {
                if (!view.id) { return; }

                this.views[view.id] = view;
                new website.ace.ViewOption(this, view).appendTo($viewList);
                this.loadView(view.id);
            }.bind(this));
        },
        buildViewGraph: function (views) {
            var activeViews = _.uniq(_.filter(views, function (view) {
               return view.active;
            }), false, function (view) {
                return view.id;
            });
            var index = {};
            var roots = [];
            _.each(activeViews, function (view) {
                index[view.id] = view;
                view.children = [];
            });
            _.each(index, function (view) {
                var parentId = view.inherit_id;
                if (parentId && index[parentId]) {
                    index[parentId].children.push(view);
                } else {
                    roots.push(view);
                }
            });
            var result = [];
            function visit (node, level) {
                node.level = level;
                result.push(node);
                _.each(node.children, function (child) {
                    visit(child, level + 1);
                });
            }
            _.each(roots, function (node) {
                visit(node, 0);
            });
            return result;
        },
        loadView: function (id) {
            var viewId = parseInt(id, 10);
            var self = this;
            openerp.jsonRpc('/web/dataset/call', 'call', {
                model: 'ir.ui.view',
                method: 'read',
                args: [[viewId], ['arch'], website.get_context()],
            }).then(function(result) {
                var editingSession = self.buffers[viewId] = new ace.EditSession(result[0].arch);
                editingSession.setMode("ace/mode/xml");
                editingSession.setUndoManager(new ace.UndoManager());
                editingSession.on("change", function () {
                    setTimeout(function () {
                        var $option = self.$('#ace-view-list').find('[value='+viewId+']');
                        var bufferName = $option.text();
                        var dirtyMarker = " (unsaved changes)";
                        var isDirty = editingSession.getUndoManager().hasUndo();
                        if (isDirty && bufferName.indexOf(dirtyMarker) < 0) {
                            $option.text(bufferName + dirtyMarker);
                        } else if (!isDirty && bufferName.indexOf(dirtyMarker) > 0) {
                            $option.text(bufferName.substring(0, bufferName.indexOf(dirtyMarker)));
                        }
                    }, 1);
                });
                if (viewId === self.selectedViewId()) {
                    self.displayView.call(self, viewId);
                }
            });
        },
        selectedViewId: function () {
            return parseInt(this.$('#ace-view-list').val(), 10);
        },
        displayView: function (id) {
            var viewId = parseInt(id, 10);
            var editingSession = this.buffers[viewId];
            if (editingSession) {
                this.aceEditor.setSession(editingSession);
                this.$('#ace-view-id').text(_.str.sprintf(
                    _t("Template ID: %s"),
                    this.views[viewId].xml_id));
            }
        },
        displaySelectedView: function () {
            this.displayView(this.selectedViewId());
            this.updateHash();
        },
        formatXml: function () {
            var xml = new website.ace.XmlDocument(this.aceEditor.getValue());
            this.aceEditor.setValue(xml.format());
        },
        saveViews: function () {
            var self = this;
            var toSave = _.filter(_.map(self.buffers, function (editingSession, viewId) {
                return {
                    id: parseInt(viewId, 10),
                    isDirty: editingSession.getUndoManager().hasUndo(),
                    text: editingSession.getValue(),
                };
            }), function (session) {
                return session.isDirty;
            });
            this.clearError();
            var requests = _.map(toSave, function (session) {
                return self.saveView(session);
            });
            $.when.apply($, requests).then(function () {
                self.reloadPage.call(self);
            }).fail(function (source, session, error) {
                self.displayError.call(self, source, session, error);
            });
        },
        saveView: function (session) {
            var self = this;
            var xml = new website.ace.XmlDocument(session.text);
            var isWellFormed = xml.isWellFormed();
            var def = $.Deferred();
            if (isWellFormed === true) {
                openerp.jsonRpc('/web/dataset/call', 'call', {
                    model: 'ir.ui.view',
                    method: 'write',
                    args: [[session.id], { 'arch':  xml.xml }, website.get_context()],
                }).then(function () {
                    def.resolve();
                }).fail(function (source, error) {
                    def.reject("server", session, error);
                });
            } else {
                def.reject(null, session, isWellFormed);
            }
            return def;
        },
        updateHash: function () {
            window.location.hash = hash + "?view=" + this.selectedViewId();
        },
        reloadPage: function () {
            this.updateHash();
            window.location.reload();
        },
        clearError: function () {
            this.$(".ace_layer.ace_text-layer .ace_line").css("background", "");
        },
        displayError: function (source, session, error) {
            var self = this;
            var line, test;
            // format error message
            var message = _.isString(error) ? error
                : (error && error.data && error.data.arguments && error.data.arguments[0] === "Access Denied") ? "Access denied: please sign in"
                : (error && error.data && error.data.message) ? error.data.message
                : (error && error.message) ? error.message
                : "Unexpected error";
            if (source == "server") {
                message = eval(message.replace(/^\(/g, '([')
                    .replace(/\)$/g, '])')
                    .replace(/u'/g, "'")
                    .replace(/<([^>]+)>/g, '<\$1>'))[1];
                line = -1;
            } else {
                line = message.match(/line ([0-9]+)/i);
                line = line ? parseInt(line[1],10) : -1;
                test = new RegExp("^\\s*"+line+"\\s*$");
            }

            function gotoline() {
                self.aceEditor.gotoLine(line);
                setTimeout(function () {
                    var $lines = self.$(".ace_editor .ace_gutter .ace_gutter-cell");
                    var index = $lines.filter(function () {
                        return test.test($(this).text());
                    }).index();
                    if (index>0) {
                        self.$(".ace_layer.ace_text-layer .ace_line:eq(" + index + ")").css("background", "#661100");
                    }
                },100);
            }
            function onchangeSession (e) {
                self.aceEditor.off('changeSession', onchangeSession);
                gotoline();
            }

            var $list = this.$("#ace-view-list");
            if (+$list.val() == session.id) {
                if (line>-1) gotoline();
            } else {
                if (line) self.aceEditor.on('changeSession', onchangeSession);
                this.$("#ace-view-list").val(session.id).change();
            }

            var $dialog = $(openerp.qweb.render('website.error_dialog', {
                title: session.text.match(/\s+name=['"]([^'"]+)['"]/i)[1],
                message:"Malformed XML document:
" + message
            }));
            $dialog.appendTo("body");
            $dialog.modal('show');
        },
        open: function () {
            this.$el.removeClass('oe_ace_closed').addClass('oe_ace_open');
        },
        close: function () {
            window.location.hash = "";
            this.$el.removeClass('oe_ace_open').addClass('oe_ace_closed');
        },
    });

    website.ready().done(function() {
        var ace = new website.Ace();
        $(document.body).on('click', 'a[data-action=ace]', function() {
            ace.launchAce();
        });
    });

})();
<|endoftext|>


<commit_before>var algorithmA = function(submittedSequence) {
    var correctSequence =
    [
        0,0,1,0,0,
        0,1,0,1,0,
        1,0,0,0,1,
        1,1,1,0,1,
        1,0,0,0,1,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {
        ('#successArea').attr('visible', 'true');
        ('#successTitle').attr('visible', 'true');
        ('#successText').attr('visible', 'true');
        ('#playAgainBtn').attr('visible', 'true');
        ('#playAgainTxt').attr('visible', 'true');
        ('#socialBtn').attr('visible', 'true');
        ('#socialBtnTxt').attr('visible', 'true');
        ('#exitBtn').attr('visible', 'true');
        ('#exitBtnText').attr('visible', 'true');
    }
};

var algorithmB = function(submittedSequence) {
    var correctSequence =
    [
        1,1,1,0,0,
        1,0,0,1,0,
        1,0,1,0,0,
        1,0,0,1,0,
        1,0,1,0,0,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmC = function(submittedSequence) {
    var correctSequence =
    [
        0,1,1,1,0,
        1,0,0,0,1,
        1,0,0,0,0,
        1,0,0,0,1,
        0,1,1,1,0,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmD = function(submittedSequence) {
    var correctSequence =
    [
        1,1,1,0,0,
        1,0,0,1,0,
        1,0,0,1,0,
        1,0,0,1,0,
        1,0,1,0,0,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmE = function(submittedSequence) {
    var correctSequence =
    [
        0,1,1,1,0,
        0,1,0,0,0,
        0,1,1,1,0,
        0,1,0,0,0,
        0,1,1,1,0,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmF = function(submittedSequence) {
    var correctSequence =
    [
        1,1,1,1,0,
        1,0,0,0,0,
        1,1,1,1,0,
        1,0,0,0,0,
        1,0,0,0,0,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmG = function(submittedSequence) {
    var correctSequence =
    [
        0,1,1,1,0,
        1,0,0,0,0,
        1,0,1,1,0,
        1,0,0,1,0,
        0,1,1,0,0,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmH = function(submittedSequence) {
    var correctSequence =
    [
        1,0,0,0,0,
        1,0,0,0,0,
        1,1,1,1,1,
        1,0,0,0,1,
        1,0,0,0,1,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmI = function(submittedSequence) {
    var correctSequence =
    [
        0,1,1,1,0,
        0,0,1,0,0,
        0,0,1,0,0,
        0,0,1,0,0,
        1,1,1,1,1,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmJ = function(submittedSequence) {
    var correctSequence =
    [
        1,1,1,1,1,
        0,0,0,1,0,
        0,0,0,1,0,
        1,0,0,1,0,
        0,1,1,0,0,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmK = function(submittedSequence) {
    var correctSequence =
    [
        1,0,0,0,1,
        1,0,0,1,0,
        1,1,1,0,0,
        1,0,0,1,0,
        1,0,0,0,1,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmL = function(submittedSequence) {
    var correctSequence =
    [
        1,1,1,0,0,
        0,1,0,0,0,
        0,1,0,0,0,
        0,1,0,0,0,
        0,1,1,1,1,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmM = function(submittedSequence) {
    var correctSequence =
    [
        0,0,0,0,0,
        1,1,0,1,1,
        1,0,1,0,1,
        1,0,0,0,1,
        1,0,0,0,1,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmN = function(submittedSequence) {
    var correctSequence =
    [
        0,1,1,1,0,
        1,0,0,0,1,
        1,0,0,0,1,
        1,0,0,0,1,
        1,0,0,0,1,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmO = function(submittedSequence) {
    var correctSequence =
    [
        0,1,1,0,0,
        1,0,0,0,1,
        1,0,0,0,1,
        1,0,0,0,1,
        0,1,1,1,0,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmP = function(submittedSequence) {
    var correctSequence =
    [
        1,1,1,1,0,
        1,0,0,1,0,
        1,0,1,1,0,
        1,0,0,0,0,
        1,0,0,0,0,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmQ = function(submittedSequence) {
    var correctSequence =
    [
        0,1,1,1,0,
        0,1,0,1,0,
        0,1,0,1,0,
        0,1,1,1,0,
        0,0,0,0,1,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmR = function(submittedSequence) {
    var correctSequence =
    [
        1,1,1,0,0,
        1,0,0,1,0,
        1,0,1,0,0,
        1,0,0,1,0,
        1,0,0,0,1,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmS = function(submittedSequence) {
    var correctSequence =
    [
        0,1,1,1,0,
        0,1,0,0,1,
        0,0,1,0,0,
        1,0,0,1,0,
        0,1,1,1,0,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmT = function(submittedSequence) {
    var correctSequence =
    [
        1,1,1,1,1,
        1,0,1,0,1,
        0,0,1,0,0,
        0,0,1,0,0,
        0,0,1,0,0,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmU = function(submittedSequence) {
    var correctSequence =
    [
        1,0,0,0,1,
        1,0,0,0,1,
        1,0,0,0,1,
        1,0,0,0,1,
        0,1,1,1,0,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmV = function(submittedSequence) {
    var correctSequence =
    [
        1,0,0,0,1,
        1,0,0,0,1,
        1,1,0,1,1,
        0,1,0,1,0,
        0,0,1,0,0,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmW = function(submittedSequence) {
    var correctSequence =
    [
        1,0,0,0,1,
        1,0,0,0,1,
        1,0,0,0,1,
        1,0,1,0,1,
        0,1,0,1,0,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmX = function(submittedSequence) {
    var correctSequence =
    [
        1,0,0,0,1,
        0,1,0,1,1,
        0,0,1,0,0,
        1,1,0,1,0,
        1,0,0,0,1,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmY = function(submittedSequence) {
    var correctSequence =
    [
        1,0,0,1,0,
        1,0,0,1,0,
        0,1,1,1,0,
        0,0,0,1,0,
        1,1,1,0,0,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmZ = function(submittedSequence) {
    var correctSequence =
    [
        1,1,1,1,0,
        0,0,0,1,0,
        0,0,1,0,0,
        0,1,0,0,0,
        1,1,1,1,0,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

<commit_msg>Fix lack of jquery<commit_after>var algorithmA = function(submittedSequence) {
    var correctSequence =
    [
        0,0,1,0,0,
        0,1,0,1,0,
        1,0,0,0,1,
        1,1,1,0,1,
        1,0,0,0,1,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {
        $('#successArea').attr('visible', 'true');
        $('#successTitle').attr('visible', 'true');
        $('#successText').attr('visible', 'true');
        $('#playAgainBtn').attr('visible', 'true');
        $('#playAgainTxt').attr('visible', 'true');
        $('#socialBtn').attr('visible', 'true');
        $('#socialBtnTxt').attr('visible', 'true');
        $('#exitBtn').attr('visible', 'true');
        $('#exitBtnText').attr('visible', 'true');
    }
};

var algorithmB = function(submittedSequence) {
    var correctSequence =
    [
        1,1,1,0,0,
        1,0,0,1,0,
        1,0,1,0,0,
        1,0,0,1,0,
        1,0,1,0,0,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmC = function(submittedSequence) {
    var correctSequence =
    [
        0,1,1,1,0,
        1,0,0,0,1,
        1,0,0,0,0,
        1,0,0,0,1,
        0,1,1,1,0,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmD = function(submittedSequence) {
    var correctSequence =
    [
        1,1,1,0,0,
        1,0,0,1,0,
        1,0,0,1,0,
        1,0,0,1,0,
        1,0,1,0,0,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmE = function(submittedSequence) {
    var correctSequence =
    [
        0,1,1,1,0,
        0,1,0,0,0,
        0,1,1,1,0,
        0,1,0,0,0,
        0,1,1,1,0,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmF = function(submittedSequence) {
    var correctSequence =
    [
        1,1,1,1,0,
        1,0,0,0,0,
        1,1,1,1,0,
        1,0,0,0,0,
        1,0,0,0,0,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmG = function(submittedSequence) {
    var correctSequence =
    [
        0,1,1,1,0,
        1,0,0,0,0,
        1,0,1,1,0,
        1,0,0,1,0,
        0,1,1,0,0,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmH = function(submittedSequence) {
    var correctSequence =
    [
        1,0,0,0,0,
        1,0,0,0,0,
        1,1,1,1,1,
        1,0,0,0,1,
        1,0,0,0,1,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmI = function(submittedSequence) {
    var correctSequence =
    [
        0,1,1,1,0,
        0,0,1,0,0,
        0,0,1,0,0,
        0,0,1,0,0,
        1,1,1,1,1,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmJ = function(submittedSequence) {
    var correctSequence =
    [
        1,1,1,1,1,
        0,0,0,1,0,
        0,0,0,1,0,
        1,0,0,1,0,
        0,1,1,0,0,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmK = function(submittedSequence) {
    var correctSequence =
    [
        1,0,0,0,1,
        1,0,0,1,0,
        1,1,1,0,0,
        1,0,0,1,0,
        1,0,0,0,1,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmL = function(submittedSequence) {
    var correctSequence =
    [
        1,1,1,0,0,
        0,1,0,0,0,
        0,1,0,0,0,
        0,1,0,0,0,
        0,1,1,1,1,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmM = function(submittedSequence) {
    var correctSequence =
    [
        0,0,0,0,0,
        1,1,0,1,1,
        1,0,1,0,1,
        1,0,0,0,1,
        1,0,0,0,1,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmN = function(submittedSequence) {
    var correctSequence =
    [
        0,1,1,1,0,
        1,0,0,0,1,
        1,0,0,0,1,
        1,0,0,0,1,
        1,0,0,0,1,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmO = function(submittedSequence) {
    var correctSequence =
    [
        0,1,1,0,0,
        1,0,0,0,1,
        1,0,0,0,1,
        1,0,0,0,1,
        0,1,1,1,0,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmP = function(submittedSequence) {
    var correctSequence =
    [
        1,1,1,1,0,
        1,0,0,1,0,
        1,0,1,1,0,
        1,0,0,0,0,
        1,0,0,0,0,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmQ = function(submittedSequence) {
    var correctSequence =
    [
        0,1,1,1,0,
        0,1,0,1,0,
        0,1,0,1,0,
        0,1,1,1,0,
        0,0,0,0,1,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmR = function(submittedSequence) {
    var correctSequence =
    [
        1,1,1,0,0,
        1,0,0,1,0,
        1,0,1,0,0,
        1,0,0,1,0,
        1,0,0,0,1,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmS = function(submittedSequence) {
    var correctSequence =
    [
        0,1,1,1,0,
        0,1,0,0,1,
        0,0,1,0,0,
        1,0,0,1,0,
        0,1,1,1,0,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmT = function(submittedSequence) {
    var correctSequence =
    [
        1,1,1,1,1,
        1,0,1,0,1,
        0,0,1,0,0,
        0,0,1,0,0,
        0,0,1,0,0,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmU = function(submittedSequence) {
    var correctSequence =
    [
        1,0,0,0,1,
        1,0,0,0,1,
        1,0,0,0,1,
        1,0,0,0,1,
        0,1,1,1,0,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmV = function(submittedSequence) {
    var correctSequence =
    [
        1,0,0,0,1,
        1,0,0,0,1,
        1,1,0,1,1,
        0,1,0,1,0,
        0,0,1,0,0,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmW = function(submittedSequence) {
    var correctSequence =
    [
        1,0,0,0,1,
        1,0,0,0,1,
        1,0,0,0,1,
        1,0,1,0,1,
        0,1,0,1,0,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmX = function(submittedSequence) {
    var correctSequence =
    [
        1,0,0,0,1,
        0,1,0,1,1,
        0,0,1,0,0,
        1,1,0,1,0,
        1,0,0,0,1,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmY = function(submittedSequence) {
    var correctSequence =
    [
        1,0,0,1,0,
        1,0,0,1,0,
        0,1,1,1,0,
        0,0,0,1,0,
        1,1,1,0,0,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

var algorithmZ = function(submittedSequence) {
    var correctSequence =
    [
        1,1,1,1,0,
        0,0,0,1,0,
        0,0,1,0,0,
        0,1,0,0,0,
        1,1,1,1,0,
    ];

    if ( submittedSequence.join() === correctSequence.join() )
    {

    }
};

<|endoftext|>


<commit_before>// Pattern which generates Table Of Contents.
//
// Author: Rok Garbas
// Contact: rok@garbas.si
// Version: 1.0
//
// License:
//
// Copyright (C) 2010 Plone Foundation
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 2 of the License.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License along with
// this program; if not, write to the Free Software Foundation, Inc., 51
// Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//

/*jshint bitwise:true, curly:true, eqeqeq:true, immed:true, latedef:true,
  newcap:true, noarg:true, noempty:true, nonew:true, plusplus:true,
  undef:true, strict:true, trailing:true, browser:true, evil:true */
/*global define:false */

define([
  'jquery',
  'js/patterns/base'
], function($, Base, Parser) {
  "use strict";

  var AutoTOC = Base.extend({
    name: "autotoc",
    defaults: {
      section: 'section',
      levels: 'h1,h2,h3',
      IDPrefix: 'autotoc-item-',
      klassTOC: 'autotoc-nav',
      klassSection: 'autotoc-section',
      klassLevelPrefix: 'autotoc-level-',
      klassActive: 'active',
      scrollDuration: 'slow',
      scrollEasing: 'swing'
    },
    init: function() {
      var self = this;
      self.$toc = $('<nav/>')
          .prependTo(self.$el)
          .addClass(self.options.klassTOC);

      if (self.options.klass) {
        self.$el.addClass(self.options.klass);
      }

      $(self.options.section, self.$el).addClass(self.options.klassSection);

      $(self.options.levels, self.$el).each(function(i) {
        var $level = $(this),
            id = $level.prop('id') ? '#' + $level.prop('id') :
                 $level.parents(self.options.section).prop('id');
        if (!id) {
          id = self.options.IDPrefix + self.name + '-' + i;
          $level.prop('id', id);
        }
        $('<a/>')
          .appendTo(self.$toc)
          .text($level.text())
          .prop('href', id)
          .addClass(self.options.klassLevelPrefix + self.getLevel($level))
          .on('click', function(e, doScroll) {
            e.stopPropagation();
            e.preventDefault();
            $('.' + self.options.klassActive, self.$el)
                .removeClass(self.options.klassActive);
            $(e.target).addClass(self.options.klassActive);
            $level.parents(self.options.section)
                .addClass(self.options.klassActive);
            if (doScroll !== false && self.options.scrollDuration && $level) {
              $('body,html').animate({
                scrollTop: $level.offset().top
              }, self.options.scrollDuration, self.options.scrollEasing);
            }
          });
      });

      self.$toc.find('a').first().trigger('click', false);

    },
    getLevel: function($el) {
      var elementLevel = 0;
      $.each(this.options.levels.split(','), function(level, levelSelector) {
        if ($el.filter(levelSelector).size() === 1) {
          elementLevel = level + 1;
          return false;
        }
      });
      return elementLevel;
    }
  });

  return AutoTOC;

});
<commit_msg>make autotoc pattern modal aware<commit_after>// Pattern which generates Table Of Contents.
//
// Author: Rok Garbas
// Contact: rok@garbas.si
// Version: 1.0
//
// License:
//
// Copyright (C) 2010 Plone Foundation
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 2 of the License.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License along with
// this program; if not, write to the Free Software Foundation, Inc., 51
// Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//

/*jshint bitwise:true, curly:true, eqeqeq:true, immed:true, latedef:true,
  newcap:true, noarg:true, noempty:true, nonew:true, plusplus:true,
  undef:true, strict:true, trailing:true, browser:true, evil:true */
/*global define:false */

define([
  'jquery',
  'js/patterns/base'
], function($, Base, Parser) {
  "use strict";

  var AutoTOC = Base.extend({
    name: "autotoc",
    defaults: {
      section: 'section',
      levels: 'h1,h2,h3',
      IDPrefix: 'autotoc-item-',
      klassTOC: 'autotoc-nav',
      klassSection: 'autotoc-section',
      klassLevelPrefix: 'autotoc-level-',
      klassActive: 'active',
      scrollDuration: 'slow',
      scrollEasing: 'swing'
    },
    init: function() {
      var self = this;
      self.$toc = $('<nav/>')
          .prependTo(self.$el)
          .addClass(self.options.klassTOC);

      if (self.options.klass) {
        self.$el.addClass(self.options.klass);
      }

      $(self.options.section, self.$el).addClass(self.options.klassSection);

      $(self.options.levels, self.$el).each(function(i) {
        var $level = $(this),
            id = $level.prop('id') ? '#' + $level.prop('id') :
                 $level.parents(self.options.section).prop('id');
        if (!id) {
          id = self.options.IDPrefix + self.name + '-' + i;
          $level.prop('id', id);
        }
        $('<a/>')
          .appendTo(self.$toc)
          .text($level.text())
          .prop('href', id)
          .addClass(self.options.klassLevelPrefix + self.getLevel($level))
          .on('click', function(e, doScroll) {
            e.stopPropagation();
            e.preventDefault();
            $('.' + self.options.klassActive, self.$el)
                .removeClass(self.options.klassActive);
            $(e.target).addClass(self.options.klassActive);
            $level.parents(self.options.section)
                .addClass(self.options.klassActive);
            if (doScroll !== false && self.options.scrollDuration && $level) {
              $('body,html').animate({
                scrollTop: $level.offset().top
              }, self.options.scrollDuration, self.options.scrollEasing);
            }
            if (self.$el.parents('.modal').size() !== 0) {
              self.$el.trigger('resize.modal.patterns');
            }
          });
      });

      self.$toc.find('a').first().trigger('click', false);

    },
    getLevel: function($el) {
      var elementLevel = 0;
      $.each(this.options.levels.split(','), function(level, levelSelector) {
        if ($el.filter(levelSelector).size() === 1) {
          elementLevel = level + 1;
          return false;
        }
      });
      return elementLevel;
    }
  });

  return AutoTOC;

});
<|endoftext|>


<commit_before>/**
 * Competence class
 */
function Competence(viewmodel, id, code, name, weight, locked, subcompetences) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        weight: ko.observable(weight),
        locked: ko.observable(locked),
        subcompetences: ko.observableArray(subcompetences),

        addSubCompetence: function() {
            this.subcompetences.push(new SubCompetence(this));

            /*var total = 100;
            alert(total);
            console.log(this.subcompetences);
            for(var sub in this.subcompetences){
                alert(sub);
                sub.calculateWeight(100);
                total -= sub.weight;
                alert(total);
            }*/
        },

        removeThis: function() {
            viewmodel.removeCompetence(this);
        },

        toggleLock: function(){
            if(this.locked == true)
            {

                this.locked = false;
            }
            else
            {
                this.locked = true;
            }
            console.log(this.locked);
            //alert(this.weight());
        },

        removeSubCompetence: function(subCompetence) {
            this.subcompetences.remove(subCompetence);
        }
    };

}

/**
 * SubCompetence class
 */
function SubCompetence(parent, id, code, name, weight, locked, indicators) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        weight: ko.observable(weight),
        locked: ko.observable(locked),
        indicators: ko.observableArray(indicators),

        addIndicator: function() {
            this.indicators.push(new Indicator(this));
        },

        /*calculateWeight: function(total){
            this.weight = total;
        },*/

        removeThis: function() {
            parent.removeSubCompetence(this);
        },

        toggleLock: function(){
            alert(this.weight());
        },

        removeIndicator: function(indicator) {
            this.indicators.remove(indicator);
        }

    };
}

/**
 * Indicator class
 */
function Indicator(parent, id, name, locked, description) {
    return {
        id: ko.observable(id),
        name: ko.observable(name),
        locked: ko.observable(locked),
        description : ko.observable(description),

        removeThis: function() {
            parent.removeIndicator(this);
        },

        toggleLock: function(){
            alert(this.weight());
        }

    };
}

// View model for the courses page
function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.competences = 0;
    gvm.subcomp = 0;

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.addCompetenceBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddCompetence");}, gvm);
    gvm.savePage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);

    gvm.lockedStatus = ko.computed(function()
    {
        return this.locked() ? "icon-lock" : "icon-unlock";
    });

    gvm.competences = ko.observableArray([]);

    gvm.addCompetence = function() {
        gvm.competences.push(new Competence(this));

        // Update automated weight calculation
        var size = gvm.competences.length;
        var percent = 100/size;
        gvm.competences[0] = 50;
        console.log(this.weight);

        ko.utils.arrayForEach(gvm.competences, function(competence){
            competence.weight(percent);
            alert(percent);
        });
    };

    gvm.removeCompetence = function(competence) {
        gvm.competences.remove(competence);
    }

    gvm.updateCompetence = function(id, code, description, max, weight) {
        var comp = new Competence(this, id, code, description, weight);
        gvm.competences.push(comp);
        return comp;
    }

    gvm.clearStructure = function() {
        gvm.competences.destroyAll();
    }
}

/**
 * Push the current project state to the database
 * @returns {undefined}
 */
function saveProjectStructure() {
    $.ajax({
       type: "POST",
       url: "/api/projectstructure/" + projectid,
       data: ko.toJSON(viewModel.competences),
       success: function(){
           // TODO make multilangual and with modals
           alert("Saved projectstructure to server");

           fetchProjectStructure();
       }
    });
}

function fetchProjectStructure() {
    viewModel.clearStructure();

    $.getJSON("/api/projectstructure/" + projectid, function(data){
        $.each(data, function(i, item){
            var competence = viewModel.updateCompetence(item.id, item.code, item.description, item.max, item.weight);

            $.each(item.subcompetences, function(i, subcomp){
               var subcompetence = new SubCompetence(competence, subcomp.id, subcomp.code, subcomp.description, subcomp.weight);
               competence.subcompetences.push(subcompetence);

               $.each(subcomp.indicators, function(i, indic){
                  subcompetence.indicators.push(new Indicator(subcompetence, indic.id, indic.name, indic.description));
               });
            });
        })
    });
}

function initPage() {
    fetchProjectStructure();

    $(".addCompetenceBtn").click(function() {
        viewModel.addCompetence();
    });

    $(".savePageBtn").click(function(){
        saveProjectStructure();
    });
}
<commit_msg>lock icons<commit_after>/**
 * Competence class
 */
function Competence(viewmodel, id, code, name, weight, locked, subcompetences) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        weight: ko.observable(weight),
        locked: ko.observable(locked),
        subcompetences: ko.observableArray(subcompetences),

        addSubCompetence: function() {
            this.subcompetences.push(new SubCompetence(this));

            /*var total = 100;
            alert(total);
            console.log(this.subcompetences);
            for(var sub in this.subcompetences){
                alert(sub);
                sub.calculateWeight(100);
                total -= sub.weight;
                alert(total);
            }*/
        },

        removeThis: function() {
            viewmodel.removeCompetence(this);
        },

        toggleLock: function(){
            if(this.locked == true)
            {

                this.locked = false;
            }
            else
            {
                this.locked = true;
            }
            console.log(this.locked);
            //alert(this.weight());
        },

        removeSubCompetence: function(subCompetence) {
            this.subcompetences.remove(subCompetence);
        }
    };

}

/**
 * SubCompetence class
 */
function SubCompetence(parent, id, code, name, weight, locked, indicators) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        weight: ko.observable(weight),
        locked: ko.observable(locked),
        indicators: ko.observableArray(indicators),

        addIndicator: function() {
            this.indicators.push(new Indicator(this));
        },

        /*calculateWeight: function(total){
            this.weight = total;
        },*/

        removeThis: function() {
            parent.removeSubCompetence(this);
        },

        toggleLock: function(){
            alert(this.weight());
        },

        removeIndicator: function(indicator) {
            this.indicators.remove(indicator);
        }

    };
}

/**
 * Indicator class
 */
function Indicator(parent, id, name, locked, description) {
    return {
        id: ko.observable(id),
        name: ko.observable(name),
        locked: ko.observable(locked),
        description : ko.observable(description),

        removeThis: function() {
            parent.removeIndicator(this);
        },

        toggleLock: function(){
            alert(this.weight());
        }

    };
}

// View model for the courses page
function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.competences = 0;
    gvm.subcomp = 0;

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.addCompetenceBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddCompetence");}, gvm);
    gvm.savePage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);

    gvm.lockedStatus = ko.computed(function()
    {
        return this.locked ? "icon-lock" : "icon-unlock";
    });

    gvm.competences = ko.observableArray([]);

    gvm.addCompetence = function() {
        gvm.competences.push(new Competence(this));

        // Update automated weight calculation
        var size = gvm.competences.length;
        var percent = 100/size;
        gvm.competences[0] = 50;
        console.log(this.weight);

        ko.utils.arrayForEach(gvm.competences, function(competence){
            competence.weight(percent);
            alert(percent);
        });
    };

    gvm.removeCompetence = function(competence) {
        gvm.competences.remove(competence);
    }

    gvm.updateCompetence = function(id, code, description, max, weight) {
        var comp = new Competence(this, id, code, description, weight);
        gvm.competences.push(comp);
        return comp;
    }

    gvm.clearStructure = function() {
        gvm.competences.destroyAll();
    }
}

/**
 * Push the current project state to the database
 * @returns {undefined}
 */
function saveProjectStructure() {
    $.ajax({
       type: "POST",
       url: "/api/projectstructure/" + projectid,
       data: ko.toJSON(viewModel.competences),
       success: function(){
           // TODO make multilangual and with modals
           alert("Saved projectstructure to server");

           fetchProjectStructure();
       }
    });
}

function fetchProjectStructure() {
    viewModel.clearStructure();

    $.getJSON("/api/projectstructure/" + projectid, function(data){
        $.each(data, function(i, item){
            var competence = viewModel.updateCompetence(item.id, item.code, item.description, item.max, item.weight);

            $.each(item.subcompetences, function(i, subcomp){
               var subcompetence = new SubCompetence(competence, subcomp.id, subcomp.code, subcomp.description, subcomp.weight);
               competence.subcompetences.push(subcompetence);

               $.each(subcomp.indicators, function(i, indic){
                  subcompetence.indicators.push(new Indicator(subcompetence, indic.id, indic.name, indic.description));
               });
            });
        })
    });
}

function initPage() {
    fetchProjectStructure();

    $(".addCompetenceBtn").click(function() {
        viewModel.addCompetence();
    });

    $(".savePageBtn").click(function(){
        saveProjectStructure();
    });
}
<|endoftext|>