<commit_before>"use strict";

load('jsecma5.js');
load('narcissus/lib/jsdefs.js');
load('narcissus/lib/jslex.js');
load('narcissus/lib/jsparse.js');

var tkn = Narcissus.definitions.tokenIds;

Array.isArray = Array.isArray || function(o) {
    return Object.prototype.toString.call(o) === '[object Array]';
};

function createTraverseData() {
    var o = [];

    o[tkn.FUNCTION] = ["body"];
    o[tkn.IF] = ["condition", "thenPart", "elsePart"];
    o[tkn.SWITCH] = ["discriminant", "cases"];
    o[tkn.CASE] = ["caseLabel", "statements"];
    o[tkn.DEFAULT] = ["statements"];
    o[tkn.FOR] = ["setup", "condition", "body", "update"];
    o[tkn.WHILE] = ["condition", "body"];
    o[tkn.FOR_IN] = ["varDecl", "iterator", "object", "body"];
    o[tkn.DO] = ["body", "condition"];
    o[tkn.TRY] = ["tryBlock", "catchClauses", "finallyBlock"];
    o[tkn.CATCH] = ["guard", "block"];
    o[tkn.THROW] = ["exception"];
    o[tkn.RETURN] = ["value"];
    o[tkn.WITH] = ["object", "body"];
    o[tkn.SEMICOLON] = ["expression"];
    o[tkn.LABEL] = ["statement"];
    o[tkn.IDENTIFIER] = ["initializer"];
    o[tkn.GETTER] = ["body"];
    o[tkn.SETTER] = ["body"];

    var c = [tkn.SCRIPT,
             tkn.BLOCK, tkn.VAR, tkn.CONST, tkn.COMMA, tkn.ASSIGN,
             tkn.HOOK, tkn.OR, tkn.AND, tkn.BITWISE_OR, tkn.BITWISE_XOR,
             tkn.BITWISE_AND, tkn.EQ, tkn.NE, tkn.STRICT_EQ, tkn.STRICT_NE,
             tkn.LT, tkn.LE, tkn.GE, tkn.GT, tkn.IN, tkn.INSTANCEOF,
             tkn.LSH, tkn.RSH, tkn.URSH, tkn.PLUS, tkn.MINUS, tkn.MUL,
             tkn.DIV, tkn.MOD, tkn.DELETE, tkn.VOID, tkn.TYPEOF,
             tkn.NOT, tkn.BITWISE_NOT, tkn.UNARY_PLUS, tkn.UNARY_MINUS,
             tkn.INCREMENT, tkn.DECREMENT, tkn.DOT, tkn.INDEX,
             tkn.LIST, tkn.CALL, tkn.NEW, tkn.NEW_WITH_ARGS, tkn.ARRAY_INIT,
             tkn.OBJECT_INIT, tkn.PROPERTY_INIT, tkn.GROUP];

    // add "children" to all tokens enumerated in c
    for (var i = 0; i < c.length; i++) {
        if (o[c[i]]) {
            o[c[i]].push("children");
        }
        else {
            o[c[i]] = ["children"];
        }
    }

    return o;
}

var traverseData = createTraverseData();

// visitfns: {pre: function, post: function}
// visit function signature: function(node, level, parent, parentProp)
function traverseAstDFS(node, visitfns, level, parent, parentProp) {
    if (!node) {
        return;
    }
    if (node instanceof Narcissus.parser.Node !== true) {
        throw new Error("traverseAstDFS expected Node, got "+ typeof node +
                       ". parentProp: "+ parentProp);
    }

    level = level || 0;
    var n;
    visitfns.pre && (n = visitfns.pre(node, level, parent, parentProp));
    if (n !== undefined) {
        node = n;
    }

    for (var prop in node) {
        if (!node.hasOwnProperty(prop)) {
            continue;
        }
        if (prop === "funDecls" || prop === "params" || prop === "varDecls" ||
            prop === "target") {
            continue;
        }
        if (node[prop] instanceof Narcissus.parser.Node) {
            traverseAstDFS(node[prop], visitfns, level + 1, node, prop);
        }
        else if (Array.isArray(node[prop])) {
            for (var j = 0, k = node[prop].length; j < k; j++) {
                traverseAstDFS(node[prop][j], visitfns, level + 1, node, prop + "[" + String(j) + "]");
            }
        }
    }

    visitfns.post && visitfns.post(node, level, parent, parentProp);
}

function traverseAstDFS_traverseData(node, visitfns, level, parent, parentProp) {
    if (!node) {
        return;
    }
    level = level || 0;
    var n;
    visitfns.pre && (n = visitfns.pre(node, level, parent, parentProp));
    if (n !== undefined) {
        node = n;
    }

    var subprops = traverseData[node.type];
    // temporary sanity-check
    if (Array.isArray(node.children) && node.children.length > 0 &&
        (!Array.isArray(subprops) || subprops[subprops.length - 1] !== "children")) {
        throw new Error("traverse error "+ tokenString(node.type) +
                        " has children property but not in subprops");
    }

    if (subprops) {
        for (var i = 0; i < subprops.length; i++) {
            var prop = subprops[i];
            if (Array.isArray(node[prop])) {
                for (var j = 0, k = node[prop].length; j < k; j++) {
                    traverseAstDFS(node[prop][j], visitfns, level + 1, node, prop + "[" + String(j) + "]");
                }
            }
            else {
                traverseAstDFS(node[prop], visitfns, level + 1, node, prop);
            }
        }
    }

    visitfns.post && visitfns.post(node, level, parent, parentProp);
}

function spaces(n, s) {
    var str = "";
    s = s || " ";
    for (var i = 0; i < n; i++) {
        str += s;
    }
    return str;
}
function tokenString(tt) {
    var defs = Narcissus.definitions;
    var t = defs.tokens[tt];
    return /^\W/.test(t) ? defs.opTypeNames[t] : t.toUpperCase();
}

function abbrev(str, max) {
    max = Math.max(Number(max) || 3, 3);
    if (str.length <= max) {
        return str;
    }
    var l = Math.ceil((max - 3) / 2);
    var r = Math.floor((max - 3) / 2);
    return str.slice(0, l) +"..."+ str.slice(str.length - r, str.length);
}

function nodeString(node) {
    function strPos(pos) {
        return pos === undefined ? "?" : String(pos);
    }
    var src = node.tokenizer.source;
    return tokenString(node.type) +
        ("start" in node && "end" in node ?
         " '"+ abbrev(src.slice(node.start, node.end), 30) +"'" :
         (node.value !== undefined ? " ("+ node.value +")" : "")) +
        ("start" in node || "end" in node ?
         " ("+ strPos(node.start) +".."+ strPos(node.end) +")" : "") +
        ("parenthesized" in node ? " parenthesized": "");
}

function printTree(root) {
    traverseAstDFS(root, {pre: function(node, level, parent, parentProp) {
        print(spaces(level * 2) + (parentProp || "root") +": "+
              nodeString(node));
    }});
}

function setParent(parent, parentProp, node) {
    if (parentProp[parentProp.length - 1] === "]") {
        var leftBracket = parentProp.indexOf("[");
        var index = parentProp.slice(leftBracket + 1,
                                     parentProp.length - 1);
        var base = parentProp.slice(0, leftBracket);
        parent[base][index] = node;
    }
    else {
        parent[parentProp] = node;
    }
}

function newNode(type, tokenizer, props) {
    var node = Object.create(Narcissus.parser.Node.prototype);
    node.tokenizer = tokenizer;
    node.type = type;
    node.children = [];

    if (props !== undefined) {
        for (var prop in props) {
            node[prop] = props[prop];
        }
    }
    //value, lineno, start, end
    return node;
}

function alterTree(root) {
    var tokenizer = root.tokenizer;
    function IDENTIFIER(name) {
        return newNode(tkn.IDENTIFIER, tokenizer, {value: name});
    }
    function LIST(children) {
        return newNode(tkn.LIST, tokenizer, {children: children});
    }
    function CALL(f, args) {
        return newNode(tkn.CALL, tokenizer, {
            children: [IDENTIFIER(f), LIST(args)]
        });
    }
    function replace(node, var_args) {
        var placeholders = [];
        //collect all # nodes into placeholders array
        traverseAstDFS(node, {pre: function(node, level, parent, parentProp) {
            if (node.type === tkn.PLACEHOLDER) {
                placeholders.push({node: node, parent: parent, parentProp: parentProp});
            }
        }});
        if (arguments.length - 1 !== placeholders.length) {
            throw new Error("replace: placeholders.length mismatch");
        }
        //sort placeholders on textual position
        placeholders.sort(function(a, b) {
            return a.node.start - b.node.start;
        });

        // offsets is an array of pairs (pos, offs)
        // where offs is the offset to be added to characters on
        // position pos upto the offs in next pair
        //
        // perform textual replacement of node.tokenizer.source
        var offsets = [[0, 0]]; // include [0, 0] for easier iteration
        var fragments = [];
        var origSource = node.tokenizer.source;
        for (var i = 0, offs = 0, pos = 0; i < placeholders.length; i++) {
            var orig = placeholders[i].node;
            var repl = arguments[i + 1];
            offs += (repl.end - repl.start) - (orig.end - orig.start);
            offsets.push([orig.end, offs]);

            fragments.push(origSource.slice(pos, orig.start));
            fragments.push(repl.getSource());
            pos = orig.end;
        }
        fragments.push(origSource.slice(pos, node.end));
        node.tokenizer.source = fragments.join(''); // this won't work (destroys parent)

        // add offsets to node-tree based on offsets
        traverseAstDFS(node, {pre: function(node, level, parent, parentProp) {
            // TODO replace linear with binary search
            var i;
            for (i = 0; i < offsets.length && offsets[i][0] <= node.start; i++) {
            }
            node.start += offsets[i - 1][1];

            for (i = 0; i < offsets.length && offsets[i][0] < node.end; i++) {
            }
            node.end += offsets[i - 1][1];
        }});

        // add offsets to new nodes and change their tokenizer
        for (i = 0; i < placeholders.length; i++) {
            var orig = placeholders[i].node;
            var repl = arguments[i + 1];
            //TODO
        }

        // replace placeholders with new nodes
        for (i = 0; i < placeholders.length; i++) {
            var o = placeholders[i];
            setParent(o.parent, o.parentProp, arguments[i + 1]);
        }
    }
    traverseAstDFS(root, {pre: function(node, level, parent, parentProp) {
        if (node.type === tkn.PLUS) {
            // prs("__add(@)", node.children);
            // n: new node (CALL, IDENTIFIER, LIST, node.children)
            // s: nodestring
            // setParent(parent, parentProp, n);
            // replace text
            //var replaceNode = parseExpression("__add(#, #)");
            var replaceNode = parseExpression(" # + !#");
            print(":");
            printTree(replaceNode);
            replace(replaceNode, node.children[0], node.children[1]);
            printTree(replaceNode);

            var call = CALL("__add", node.children);
            setParent(parent, parentProp, call);
            print(nodeString(node));
            print(nodeString(node.children[0]));
            print(nodeString(node.children[1]));
            var src = "__add("+ node.children[0].getSource() +", "+ node.children[1].getSource() +")";
            print(src);
            return call;
        }
    }});
}
function adjustStartEnd(root) {
    traverseAstDFS(root, {post: function(node, level, parent, parentProp) {
        if (parent) {
            if (parent.start === undefined || parent.end === undefined ||
                node.start === undefined || node.end === undefined) {
                throw new Error("adjustStartEnd: undefined start/end");
            }
            parent.start = Math.min(parent.start, node.start);
            parent.end = Math.max(parent.end, node.end);
        }
    }});
    return root;
}

print("checker.js done");
<commit_msg>createTraverseData children ordering<commit_after>"use strict";

load('jsecma5.js');
load('narcissus/lib/jsdefs.js');
load('narcissus/lib/jslex.js');
load('narcissus/lib/jsparse.js');

var tkn = Narcissus.definitions.tokenIds;

Array.isArray = Array.isArray || function(o) {
    return Object.prototype.toString.call(o) === '[object Array]';
};

function createTraverseData() {
    var o = [];

    o[tkn.FUNCTION] = ["body"];
    o[tkn.IF] = ["condition", "thenPart", "elsePart"];
    o[tkn.SWITCH] = ["discriminant", "cases"];
    o[tkn.CASE] = ["caseLabel", "statements"];
    o[tkn.DEFAULT] = ["statements"];
    o[tkn.FOR] = ["setup", "condition", "update", "body"];
    o[tkn.WHILE] = ["condition", "body"];
    o[tkn.FOR_IN] = ["varDecl", "iterator", "object", "body"];
    o[tkn.DO] = ["body", "condition"];
    o[tkn.TRY] = ["tryBlock", "catchClauses", "finallyBlock"];
    o[tkn.CATCH] = ["guard", "block"];
    o[tkn.THROW] = ["exception"];
    o[tkn.RETURN] = ["value"];
    o[tkn.WITH] = ["object", "body"];
    o[tkn.SEMICOLON] = ["expression"];
    o[tkn.LABEL] = ["statement"];
    o[tkn.IDENTIFIER] = ["initializer"];
    o[tkn.GETTER] = ["body"];
    o[tkn.SETTER] = ["body"];

    var c = [tkn.SCRIPT,
             tkn.BLOCK, tkn.VAR, tkn.CONST, tkn.COMMA, tkn.ASSIGN,
             tkn.HOOK, tkn.OR, tkn.AND, tkn.BITWISE_OR, tkn.BITWISE_XOR,
             tkn.BITWISE_AND, tkn.EQ, tkn.NE, tkn.STRICT_EQ, tkn.STRICT_NE,
             tkn.LT, tkn.LE, tkn.GE, tkn.GT, tkn.IN, tkn.INSTANCEOF,
             tkn.LSH, tkn.RSH, tkn.URSH, tkn.PLUS, tkn.MINUS, tkn.MUL,
             tkn.DIV, tkn.MOD, tkn.DELETE, tkn.VOID, tkn.TYPEOF,
             tkn.NOT, tkn.BITWISE_NOT, tkn.UNARY_PLUS, tkn.UNARY_MINUS,
             tkn.INCREMENT, tkn.DECREMENT, tkn.DOT, tkn.INDEX,
             tkn.LIST, tkn.CALL, tkn.NEW, tkn.NEW_WITH_ARGS, tkn.ARRAY_INIT,
             tkn.OBJECT_INIT, tkn.PROPERTY_INIT, tkn.GROUP];

    // add "children" to all tokens enumerated in c
    for (var i = 0; i < c.length; i++) {
        if (o[c[i]]) {
            throw new Error("createTraverseData: don't know ordering so "+
                            "can't add 'children' to existing traverseData");
        }
        o[c[i]] = ["children"];
    }

    return o;
}

var traverseData = createTraverseData();

// visitfns: {pre: function, post: function}
// visit function signature: function(node, level, parent, parentProp)
function traverseAstDFS(node, visitfns, level, parent, parentProp) {
    if (!node) {
        return;
    }
    if (node instanceof Narcissus.parser.Node !== true) {
        throw new Error("traverseAstDFS expected Node, got "+ typeof node +
                       ". parentProp: "+ parentProp);
    }

    level = level || 0;
    var n;
    visitfns.pre && (n = visitfns.pre(node, level, parent, parentProp));
    if (n !== undefined) {
        node = n;
    }

    for (var prop in node) {
        if (!node.hasOwnProperty(prop)) {
            continue;
        }
        if (prop === "funDecls" || prop === "params" || prop === "varDecls" ||
            prop === "target") {
            continue;
        }
        if (node[prop] instanceof Narcissus.parser.Node) {
            traverseAstDFS(node[prop], visitfns, level + 1, node, prop);
        }
        else if (Array.isArray(node[prop])) {
            for (var j = 0, k = node[prop].length; j < k; j++) {
                traverseAstDFS(node[prop][j], visitfns, level + 1, node, prop + "[" + String(j) + "]");
            }
        }
    }

    visitfns.post && visitfns.post(node, level, parent, parentProp);
}

function traverseAstDFS_traverseData(node, visitfns, level, parent, parentProp) {
    if (!node) {
        return;
    }
    level = level || 0;
    var n;
    visitfns.pre && (n = visitfns.pre(node, level, parent, parentProp));
    if (n !== undefined) {
        node = n;
    }

    var subprops = traverseData[node.type];
    // temporary sanity-check
    if (Array.isArray(node.children) && node.children.length > 0 &&
        (!Array.isArray(subprops) || subprops[subprops.length - 1] !== "children")) {
        throw new Error("traverse error "+ tokenString(node.type) +
                        " has children property but not in subprops");
    }

    if (subprops) {
        for (var i = 0; i < subprops.length; i++) {
            var prop = subprops[i];
            if (Array.isArray(node[prop])) {
                for (var j = 0, k = node[prop].length; j < k; j++) {
                    traverseAstDFS(node[prop][j], visitfns, level + 1, node, prop + "[" + String(j) + "]");
                }
            }
            else {
                traverseAstDFS(node[prop], visitfns, level + 1, node, prop);
            }
        }
    }

    visitfns.post && visitfns.post(node, level, parent, parentProp);
}

function spaces(n, s) {
    var str = "";
    s = s || " ";
    for (var i = 0; i < n; i++) {
        str += s;
    }
    return str;
}
function tokenString(tt) {
    var defs = Narcissus.definitions;
    var t = defs.tokens[tt];
    return /^\W/.test(t) ? defs.opTypeNames[t] : t.toUpperCase();
}

function abbrev(str, max) {
    max = Math.max(Number(max) || 3, 3);
    if (str.length <= max) {
        return str;
    }
    var l = Math.ceil((max - 3) / 2);
    var r = Math.floor((max - 3) / 2);
    return str.slice(0, l) +"..."+ str.slice(str.length - r, str.length);
}

function nodeString(node) {
    function strPos(pos) {
        return pos === undefined ? "?" : String(pos);
    }
    var src = node.tokenizer.source;
    return tokenString(node.type) +
        ("start" in node && "end" in node ?
         " '"+ abbrev(src.slice(node.start, node.end), 30) +"'" :
         (node.value !== undefined ? " ("+ node.value +")" : "")) +
        ("start" in node || "end" in node ?
         " ("+ strPos(node.start) +".."+ strPos(node.end) +")" : "") +
        ("parenthesized" in node ? " parenthesized": "");
}

function printTree(root) {
    traverseAstDFS(root, {pre: function(node, level, parent, parentProp) {
        print(spaces(level * 2) + (parentProp || "root") +": "+
              nodeString(node));
    }});
}

function setParent(parent, parentProp, node) {
    if (parentProp[parentProp.length - 1] === "]") {
        var leftBracket = parentProp.indexOf("[");
        var index = parentProp.slice(leftBracket + 1,
                                     parentProp.length - 1);
        var base = parentProp.slice(0, leftBracket);
        parent[base][index] = node;
    }
    else {
        parent[parentProp] = node;
    }
}

function newNode(type, tokenizer, props) {
    var node = Object.create(Narcissus.parser.Node.prototype);
    node.tokenizer = tokenizer;
    node.type = type;
    node.children = [];

    if (props !== undefined) {
        for (var prop in props) {
            node[prop] = props[prop];
        }
    }
    //value, lineno, start, end
    return node;
}

function alterTree(root) {
    var tokenizer = root.tokenizer;
    function IDENTIFIER(name) {
        return newNode(tkn.IDENTIFIER, tokenizer, {value: name});
    }
    function LIST(children) {
        return newNode(tkn.LIST, tokenizer, {children: children});
    }
    function CALL(f, args) {
        return newNode(tkn.CALL, tokenizer, {
            children: [IDENTIFIER(f), LIST(args)]
        });
    }
    function replace(node, var_args) {
        var placeholders = [];
        //collect all # nodes into placeholders array
        traverseAstDFS(node, {pre: function(node, level, parent, parentProp) {
            if (node.type === tkn.PLACEHOLDER) {
                placeholders.push({node: node, parent: parent, parentProp: parentProp});
            }
        }});
        if (arguments.length - 1 !== placeholders.length) {
            throw new Error("replace: placeholders.length mismatch");
        }
        //sort placeholders on textual position
        placeholders.sort(function(a, b) {
            return a.node.start - b.node.start;
        });

        // offsets is an array of pairs (pos, offs)
        // where offs is the offset to be added to characters on
        // position pos upto the offs in next pair
        //
        // perform textual replacement of node.tokenizer.source
        var offsets = [[0, 0]]; // include [0, 0] for easier iteration
        var fragments = [];
        var origSource = node.tokenizer.source;
        for (var i = 0, offs = 0, pos = 0; i < placeholders.length; i++) {
            var orig = placeholders[i].node;
            var repl = arguments[i + 1];
            offs += (repl.end - repl.start) - (orig.end - orig.start);
            offsets.push([orig.end, offs]);

            fragments.push(origSource.slice(pos, orig.start));
            fragments.push(repl.getSource());
            pos = orig.end;
        }
        fragments.push(origSource.slice(pos, node.end));
        node.tokenizer.source = fragments.join(''); // this won't work (destroys parent)

        // add offsets to node-tree based on offsets
        traverseAstDFS(node, {pre: function(node, level, parent, parentProp) {
            // TODO replace linear with binary search
            var i;
            for (i = 0; i < offsets.length && offsets[i][0] <= node.start; i++) {
            }
            node.start += offsets[i - 1][1];

            for (i = 0; i < offsets.length && offsets[i][0] < node.end; i++) {
            }
            node.end += offsets[i - 1][1];
        }});

        // add offsets to new nodes and change their tokenizer
        for (i = 0; i < placeholders.length; i++) {
            var orig = placeholders[i].node;
            var repl = arguments[i + 1];
            //TODO
        }

        // replace placeholders with new nodes
        for (i = 0; i < placeholders.length; i++) {
            var o = placeholders[i];
            setParent(o.parent, o.parentProp, arguments[i + 1]);
        }
    }
    traverseAstDFS(root, {pre: function(node, level, parent, parentProp) {
        if (node.type === tkn.PLUS) {
            // prs("__add(@)", node.children);
            // n: new node (CALL, IDENTIFIER, LIST, node.children)
            // s: nodestring
            // setParent(parent, parentProp, n);
            // replace text
            //var replaceNode = parseExpression("__add(#, #)");
            var replaceNode = parseExpression(" # + !#");
            print(":");
            printTree(replaceNode);
            replace(replaceNode, node.children[0], node.children[1]);
            printTree(replaceNode);

            var call = CALL("__add", node.children);
            setParent(parent, parentProp, call);
            print(nodeString(node));
            print(nodeString(node.children[0]));
            print(nodeString(node.children[1]));
            var src = "__add("+ node.children[0].getSource() +", "+ node.children[1].getSource() +")";
            print(src);
            return call;
        }
    }});
}
function adjustStartEnd(root) {
    traverseAstDFS(root, {post: function(node, level, parent, parentProp) {
        if (parent) {
            if (parent.start === undefined || parent.end === undefined ||
                node.start === undefined || node.end === undefined) {
                throw new Error("adjustStartEnd: undefined start/end");
            }
            parent.start = Math.min(parent.start, node.start);
            parent.end = Math.max(parent.end, node.end);
        }
    }});
    return root;
}

print("checker.js done");
<|endoftext|>


<commit_before>// https://github.com/angular-ui/angular-google-maps/blob/master/example/assets/scripts/controllers/issue-624-drawing-manager.js
'use strict';

angular.module('venueApp')
  .controller('AssignEventFormCtrl', function($scope, Auth, EventInfo, User, SectionEvent, Upload){

    $scope.event = {};
    $scope.eventInfo = $scope.eventContainer.info;

    User.get({withSections:true, withSectionCourse:true}, (user) => {
      var coursesObj = {};
      user.sections.forEach((section) => {
        var course = coursesObj[section.course._id] || section.course;
        course.sections = course.sections || [];
        course.sections.push(section);
        coursesObj[section.course._id] = course;
      });
      $scope.courses = _.values(coursesObj);
    });

    $scope.isActiveCourse = function(course){
      return course.sections.every((section) => section.active);
    };

    $scope.selectCourse = function(course){
      if ($scope.isActiveCourse(course)){
        course.sections.forEach((section) => {
          section.active = false;
        });
      }else{
        course.sections.forEach((section) => {
          section.active = true;
        });
      }
    };

    $scope.onSectionClick = function(section){
      section.active = !section.active;
    };

    function getSectionIds(){
      window.courses = $scope.courses;
      var sections = $scope.courses
        .reduce((prev,course) => prev.concat(course.sections), [])
        .filter((section)=>section.active)
        .map((section) => section._id);
      return sections;
    }

    $scope.submitEventAssignment = function(form){
        $scope.submitted = true;
        if(getSectionIds().length == 0){
          $scope.eventAssignmentSectionsError = true;
          return;
        }
        if (form.$valid){
          var sections = getSectionIds();
          var createdSuccess = 0;
          sections.forEach((sectionId)=>{
            var sectionEvent = {
              section: sectionId,
              info: $scope.eventInfo._id,
              author: Auth.getCurrentUser()._id,
              submissionInstructions: $scope.event.submissionInstructions
            };
            SectionEvent.create(sectionEvent).$promise
              .then((course) => {
                createdSuccess += 1;
                $scope.event.assignmentId = course._id;
                if (createdSuccess === sections.length){
                  $scope.success = true;
                  if ($scope.onSubmit){
                    $scope.onSubmit();
                  }
                }
              })
              .catch(err => {
                err = err.data;
                $scope.errors = {};

                // Update validity of form fields that match the mongoose errors
                angular.forEach(err.errors, (error, field) => {
                  form[field].$setValidity('mongoose', false);
                  $scope.errors[field] = error.message;
                });
              })
          });

        }
      };
  });
<commit_msg>Change to promises<commit_after>// https://github.com/angular-ui/angular-google-maps/blob/master/example/assets/scripts/controllers/issue-624-drawing-manager.js
'use strict';

angular.module('venueApp')
  .controller('AssignEventFormCtrl', function($scope, Auth, EventInfo, User, SectionEvent, Upload){

    $scope.event = {};
    $scope.eventInfo = $scope.eventContainer.info;

    User.get({withSections:true, withSectionCourse:true}, (user) => {
      var coursesObj = {};
      user.sections.forEach((section) => {
        var course = coursesObj[section.course._id] || section.course;
        course.sections = course.sections || [];
        course.sections.push(section);
        coursesObj[section.course._id] = course;
      });
      $scope.courses = _.values(coursesObj);
    });

    $scope.isActiveCourse = function(course){
      return course.sections.every((section) => section.active);
    };

    $scope.selectCourse = function(course){
      if ($scope.isActiveCourse(course)){
        course.sections.forEach((section) => {
          section.active = false;
        });
      }else{
        course.sections.forEach((section) => {
          section.active = true;
        });
      }
    };

    $scope.onSectionClick = function(section){
      section.active = !section.active;
    };

    function getSectionIds(){
      window.courses = $scope.courses;
      var sections = $scope.courses
        .reduce((prev,course) => prev.concat(course.sections), [])
        .filter((section)=>section.active)
        .map((section) => section._id);
      return sections;
    }

    $scope.submitEventAssignment = function(form){
        $scope.submitted = true;
        if(getSectionIds().length == 0){
          $scope.eventAssignmentSectionsError = true;
          return;
        }
        if (form.$valid){
          var sections = getSectionIds();
          var createdSuccess = 0;
          var createSectionEventsPromises = [];
          sections.forEach((sectionId)=>{
            var sectionEvent = {
              section: sectionId,
              info: $scope.eventInfo._id,
              author: Auth.getCurrentUser()._id,
              submissionInstructions: $scope.event.submissionInstructions
            };
            createSectionEventsPromises.push(SectionEvent.create(sectionEvent))
            Promise.all(createSectionEventsPromises)
              .then((course) => {
                $scope.event.assignmentId = course._id;
                $scope.success = true;
                if ($scope.onSubmit){
                  $scope.onSubmit();
                }
              })
              .catch(err => {
                err = err.data;
                $scope.errors = {};

                // Update validity of form fields that match the mongoose errors
                angular.forEach(err.errors, (error, field) => {
                  form[field].$setValidity('mongoose', false);
                  $scope.errors[field] = error.message;
                });
              })
          });

        }
      };
  });
<|endoftext|>


<commit_before>#!/usr/bin/env node
/*
	Copyright (c) 2014 Guilherme Prá Vieira

	This file is part of Wysia.

	Wysia 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.

	Wysia 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 Wysia. If not, see <http://www.gnu.org/licenses/>.
*/
var vm = require('vm');
var fs = require('fs');
var glob = require('glob');
var path = require('path');
var http = require('http');
var express = require('express');
var hbs = require('handlebars');
var marked = require('marked');
var args = require('../src/arguments');
var merge = require('../src/merge');
hbs.registerHelper (
	'markdown', function(text) {
		if(!text) {
			return '';
		}
		return new hbs.SafeString (
			marked (
				text
				, {
					gfm: true
					, sanitize: true
					, breaks: true
					, tables: true
				}
			)
		);
	}
);
var app = express();
if(app.get('env') === 'development') {
	app.use(express.logger());
}
app.use(express.static(__dirname + '/../public'));
app.use (
	express.static (
		path.resolve(process.cwd(), args['templates-dir'])
	)
);
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use (
	function(req, res, next) {
		res.send_error = function(err) {
			if(err.bad_request) {
				res.status(400);
			}
			else
			if(err.not_found) {
				res.status(404);
			}
			else {
				res.status(500);
			}
			if(!err.stack) {
				res.send(err);
				console.error("Non-standard error thrown:", err);
			}
			else {
				res.set('Content-Type', 'text/plain');
				res.send(err.stack);
				console.error(err.stack);
			}
		};
		next();
	}
);
var shared_state = (function() {
	try {
		var path = args['templates-dir']
				+ '/' + args['wysia-subdir']
				+ '/initial-shared-state.json';
		return JSON.parse(fs.readFileSync(path, 'utf8'));
	}
	catch(err) {
		if(err.code !== 'ENOENT') {
			console.error("Error loading initial shared state:", err);
			console.log("Starting with empty shared_state.");
		}
	}
	return {};
})();
function render(shell, page, models, cookies, cb) {
	var shell_template;
	var page_template;
	var model_data = {};
	var partials = {};
	(function load_shell() {
		if(!shell) {
			load_page();
		}
		else {
			var file_name = shell + '.hbs';
			var path = args['templates-dir'] + '/' + file_name;
			fs.readFile (
				path, 'utf8', function(err, template) {
					if(err) {
						cb(err);
						return;
					}
					shell_template = template;
					load_page();
				}
			);
		}
	})();
	function load_page() {
		var file_name = page + '.hbs';
		var path = args['templates-dir'] + '/' + file_name;
		fs.readFile (
			path, 'utf8', function(err, template) {
				if(err) {
					cb(err);
					return;
				}
				page_template = template;
				load_models();
			}
		);
	}
	function load_models() {
		var load_count = 0;
		(function load_model(err, model) {
			if(err) {
				cb(err);
				return;
			}
			if(model) {
				try {
					var loaded_model = JSON.parse(model);
					model_data = merge(model_data, loaded_model);
				}
				catch(err) {
					cb(err);
					return;
				}
			}
			if(load_count < models.length) {
				var file_name = models[load_count++] + '.json';
				var path = args['templates-dir']
						+ '/' + args['wysia-subdir']
						+ '/' + file_name;
				fs.readFile(path, 'utf8', load_model);
			}
			else {
				merge_shared_state();
			}
		})();
	}
	function merge_shared_state() {
		try {
			model_data = merge(model_data, shared_state);
		}
		catch(err) {
			cb(err);
			return;
		}
		merge_cookies();
	}
	function merge_cookies() {
		if(!cookies) {
			load_partials();
			return;
		}
		try {
			for(var key in cookies) {
				cookies[key] = (function execute_copies(node) {
					if(typeof(node) !== 'object') {
						return node;
					}
					var keys = Object.keys(node);
					if(keys[0] !== '$copy') {
						for(var key in node) {
							node[key] = execute_copies(node[key]);
						}
						return node;
					}
					var path = node[keys[0]].split('.');
					return path.reduce (
						function(current_path_node, next_path_node_name) {
							if(typeof(current_path_node) !== 'object') {
								return undefined;
							}
							return current_path_node[next_path_node_name];
						}
						, model_data
					);
				})(cookies[key]);
			}
			model_data = merge(model_data, cookies);
		}
		catch(err) {
			cb(err);
			return;
		}
		load_partials();
	}
	function load_partials() {
		var glob_ = args['templates-dir'] + '/*.partial.hbs';
		var partial_files;
		glob (
			glob_, function(err, files) {
				if(err) {
					cb(err);
					return;
				}
				partial_files = files;
				load_partial();
			}
		);
		var load_count = 0;
		function load_partial(err, name, partial) {
			if(err) {
				cb(err);
				return;
			}
			if(partial) {
				partials[name] = partial;
			}
			if(load_count < partial_files.length) {
				var path_ = partial_files[load_count++];
				var name = path.basename(path_, '.partial.hbs');
				fs.readFile (
					path_, 'utf8', function(err, partial) {
						load_partial(err, name, partial);
					}
				);
			}
			else {
				partials['wysia-shared-state'] =
						'<script>'
						+ '\nwindow.wysia = window.wysia || {};'
						+ '\nwindow.wysia.shared_state = '
							+ JSON.stringify(shared_state) + ';'
						+ '\n</script>';
				render_();
			}
		}
	}
	function render_() {
		try {
			model_data.is_wysia = true;
			for(var name in partials) {
				hbs.registerPartial(name, partials[name]);
			}
			var html = hbs.compile(page_template)(model_data);
			if(shell_template) {
				model_data.page_html = html;
				html = hbs.compile(shell_template)(model_data);
			}
			for(var name in partials) {
				hbs.unregisterPartial(name);
			}
			cb(null, html);
		}
		catch(err) {
			cb(err);
		}
	}
}
function get_handler(req, res) {
	var shell = req.params.shell || null;
	var page = req.params.page;
	var models = [];
	if(req.params.models) {
		models = req.params.models.split(',');
	}
	var cookies = {};
	if(req.headers.cookie) {
		try {
			cookies = JSON.parse(unescape(req.headers.cookie));
		}
		catch(err) {
			console.error("Failed to parse cookies:", req.headers.cookie + ".");
		}
	}
	render (
		shell, page, models, cookies, function(err, html) {
			if(err) {
				res.send_error(err);
				return;
			}
			res.send(html);
		}
	);
}
function post_handler(req, res) {
	if(req.body['$state-update-logic']) {
		var cookies = (function() {
			if(req.headers.cookie) {
				try {
					return JSON.parse(unescape(req.headers.cookie));
				}
				catch(err) {
					console.error("Failed to parse cookies:", req.headers.cookie + ".");
					return undefined;
				}
			}
			return {};
		})();
		var set_cookies_if_any = function() {
			if(cookies !== undefined) {
				res.set('Set-Cookie', escape(JSON.stringify(cookies)));
			}
		};
		try {
			vm.runInNewContext (
				req.body['$state-update-logic']
				, {
					state: shared_state
					, cookies: cookies
					, form_data: req.body
				}
			);
		}
		catch(err) {
			set_cookies_if_any();
			res.send_error(err);
			return;
		}
		set_cookies_if_any();
	}
	res.redirect(req.url);
}
app.get('/:shell,:page', get_handler);
app.post('/:shell,:page', post_handler);
app.get('/:shell,:page/:models', get_handler);
app.post('/:shell,:page/:models', post_handler);
app.get('/:page', get_handler);
app.post('/:page', post_handler);
app.get('/:page/:models', get_handler);
app.post('/:page/:models', post_handler);
app.listen(args.port);
console.log("Wysia started on port", args.port + ".");
<commit_msg>Add Handlebars helpers support.<commit_after>#!/usr/bin/env node
/*
	Copyright (c) 2014 Guilherme Prá Vieira

	This file is part of Wysia.

	Wysia 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.

	Wysia 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 Wysia. If not, see <http://www.gnu.org/licenses/>.
*/
var vm = require('vm');
var fs = require('fs');
var glob = require('glob');
var path = require('path');
var http = require('http');
var express = require('express');
var hbs = require('handlebars');
var marked = require('marked');
var args = require('../src/arguments');
var merge = require('../src/merge');
hbs.registerHelper (
	'markdown', function(text) {
		if(!text) {
			return '';
		}
		return new hbs.SafeString (
			marked (
				text
				, {
					gfm: true
					, sanitize: true
					, breaks: true
					, tables: true
				}
			)
		);
	}
);
(function load_user_helpers() {
	var path_ = path.resolve(args['templates-dir'], args['wysia-subdir']);
	var files = glob.sync(path_ + '/*.helper.js');
	files.forEach (
		function(file) {
			var name = path.basename(file, '.helper.js');
			var helper = require(file);
			hbs.registerHelper(name, helper);
		}
	);
})();
var app = express();
if(app.get('env') === 'development') {
	app.use(express.logger());
}
app.use(express.static(__dirname + '/../public'));
app.use (
	express.static (
		path.resolve(process.cwd(), args['templates-dir'])
	)
);
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use (
	function(req, res, next) {
		res.send_error = function(err) {
			if(err.bad_request) {
				res.status(400);
			}
			else
			if(err.not_found) {
				res.status(404);
			}
			else {
				res.status(500);
			}
			if(!err.stack) {
				res.send(err);
				console.error("Non-standard error thrown:", err);
			}
			else {
				res.set('Content-Type', 'text/plain');
				res.send(err.stack);
				console.error(err.stack);
			}
		};
		next();
	}
);
var shared_state = (function() {
	try {
		var path = args['templates-dir']
				+ '/' + args['wysia-subdir']
				+ '/initial-shared-state.json';
		return JSON.parse(fs.readFileSync(path, 'utf8'));
	}
	catch(err) {
		if(err.code !== 'ENOENT') {
			console.error("Error loading initial shared state:", err);
			console.log("Starting with empty shared_state.");
		}
	}
	return {};
})();
function render(shell, page, models, cookies, cb) {
	var shell_template;
	var page_template;
	var model_data = {};
	var partials = {};
	(function load_shell() {
		if(!shell) {
			load_page();
		}
		else {
			var file_name = shell + '.hbs';
			var path = args['templates-dir'] + '/' + file_name;
			fs.readFile (
				path, 'utf8', function(err, template) {
					if(err) {
						cb(err);
						return;
					}
					shell_template = template;
					load_page();
				}
			);
		}
	})();
	function load_page() {
		var file_name = page + '.hbs';
		var path = args['templates-dir'] + '/' + file_name;
		fs.readFile (
			path, 'utf8', function(err, template) {
				if(err) {
					cb(err);
					return;
				}
				page_template = template;
				load_models();
			}
		);
	}
	function load_models() {
		var load_count = 0;
		(function load_model(err, model) {
			if(err) {
				cb(err);
				return;
			}
			if(model) {
				try {
					var loaded_model = JSON.parse(model);
					model_data = merge(model_data, loaded_model);
				}
				catch(err) {
					cb(err);
					return;
				}
			}
			if(load_count < models.length) {
				var file_name = models[load_count++] + '.json';
				var path = args['templates-dir']
						+ '/' + args['wysia-subdir']
						+ '/' + file_name;
				fs.readFile(path, 'utf8', load_model);
			}
			else {
				merge_shared_state();
			}
		})();
	}
	function merge_shared_state() {
		try {
			model_data = merge(model_data, shared_state);
		}
		catch(err) {
			cb(err);
			return;
		}
		merge_cookies();
	}
	function merge_cookies() {
		if(!cookies) {
			load_partials();
			return;
		}
		try {
			for(var key in cookies) {
				cookies[key] = (function execute_copies(node) {
					if(typeof(node) !== 'object') {
						return node;
					}
					var keys = Object.keys(node);
					if(keys[0] !== '$copy') {
						for(var key in node) {
							node[key] = execute_copies(node[key]);
						}
						return node;
					}
					var path = node[keys[0]].split('.');
					return path.reduce (
						function(current_path_node, next_path_node_name) {
							if(typeof(current_path_node) !== 'object') {
								return undefined;
							}
							return current_path_node[next_path_node_name];
						}
						, model_data
					);
				})(cookies[key]);
			}
			model_data = merge(model_data, cookies);
		}
		catch(err) {
			cb(err);
			return;
		}
		load_partials();
	}
	function load_partials() {
		var glob_ = args['templates-dir'] + '/*.partial.hbs';
		var partial_files;
		glob (
			glob_, function(err, files) {
				if(err) {
					cb(err);
					return;
				}
				partial_files = files;
				load_partial();
			}
		);
		var load_count = 0;
		function load_partial(err, name, partial) {
			if(err) {
				cb(err);
				return;
			}
			if(partial) {
				partials[name] = partial;
			}
			if(load_count < partial_files.length) {
				var path_ = partial_files[load_count++];
				var name = path.basename(path_, '.partial.hbs');
				fs.readFile (
					path_, 'utf8', function(err, partial) {
						load_partial(err, name, partial);
					}
				);
			}
			else {
				partials['wysia-shared-state'] =
						'<script>'
						+ '\nwindow.wysia = window.wysia || {};'
						+ '\nwindow.wysia.shared_state = '
							+ JSON.stringify(shared_state) + ';'
						+ '\n</script>';
				render_();
			}
		}
	}
	function render_() {
		try {
			model_data.is_wysia = true;
			for(var name in partials) {
				hbs.registerPartial(name, partials[name]);
			}
			var html = hbs.compile(page_template)(model_data);
			if(shell_template) {
				model_data.page_html = html;
				html = hbs.compile(shell_template)(model_data);
			}
			for(var name in partials) {
				hbs.unregisterPartial(name);
			}
			cb(null, html);
		}
		catch(err) {
			cb(err);
		}
	}
}
function get_handler(req, res) {
	var shell = req.params.shell || null;
	var page = req.params.page;
	var models = [];
	if(req.params.models) {
		models = req.params.models.split(',');
	}
	var cookies = {};
	if(req.headers.cookie) {
		try {
			cookies = JSON.parse(unescape(req.headers.cookie));
		}
		catch(err) {
			console.error("Failed to parse cookies:", req.headers.cookie + ".");
		}
	}
	render (
		shell, page, models, cookies, function(err, html) {
			if(err) {
				res.send_error(err);
				return;
			}
			res.send(html);
		}
	);
}
function post_handler(req, res) {
	if(req.body['$state-update-logic']) {
		var cookies = (function() {
			if(req.headers.cookie) {
				try {
					return JSON.parse(unescape(req.headers.cookie));
				}
				catch(err) {
					console.error("Failed to parse cookies:", req.headers.cookie + ".");
					return undefined;
				}
			}
			return {};
		})();
		var set_cookies_if_any = function() {
			if(cookies !== undefined) {
				res.set('Set-Cookie', escape(JSON.stringify(cookies)));
			}
		};
		try {
			vm.runInNewContext (
				req.body['$state-update-logic']
				, {
					state: shared_state
					, cookies: cookies
					, form_data: req.body
				}
			);
		}
		catch(err) {
			set_cookies_if_any();
			res.send_error(err);
			return;
		}
		set_cookies_if_any();
	}
	res.redirect(req.url);
}
app.get('/:shell,:page', get_handler);
app.post('/:shell,:page', post_handler);
app.get('/:shell,:page/:models', get_handler);
app.post('/:shell,:page/:models', post_handler);
app.get('/:page', get_handler);
app.post('/:page', post_handler);
app.get('/:page/:models', get_handler);
app.post('/:page/:models', post_handler);
app.listen(args.port);
console.log("Wysia started on port", args.port + ".");
<|endoftext|>


<commit_before>"use strict";

define(['clientUtil',
        'text!html/Widgets/MetaEditor/MetaEditorPointerNamesDialog.html',
        'css!/css/Widgets/MetaEditor/MetaEditorPointerNamesDialog'], function ( util,
                                                               metaEditorPointerNamesDialogTemplate) {

    var MetaEditorPointerNamesDialog,
        POPULAR_POINTER_NAMES = ['src', 'dst', 'ref'];

    MetaEditorPointerNamesDialog = function () {

    };

    MetaEditorPointerNamesDialog.prototype.show = function (pointerNames, callBack) {
        var self = this;

        this._initDialog(pointerNames, callBack);

        this._dialog.modal('show');

        this._dialog.on('shown', function () {
            if (pointerNames.length === 0) {
	        	self._txtNewPointerName.focus();
	        }
        });

        this._dialog.on('hidden', function () {
            self._dialog.remove();
            self._dialog.empty();
            self._dialog = undefined;
        });
    };

    MetaEditorPointerNamesDialog.prototype._initDialog = function (pointerNames, callBack) {
        var self = this,
            i,
            len = pointerNames.length,
            closeAndCallback,
            popularsAdded,
            isValidPointerName;

        closeAndCallback = function (selectedName) {
        	self._dialog.modal('hide');

        	if (callBack) {
        		callBack.call(self, selectedName);
        	}
        };

        isValidPointerName = function (name) {
            return !(name === "" || pointerNames.indexOf(name) !== -1);
        };

        this._dialog = $(metaEditorPointerNamesDialogTemplate);

        //get controls
        this._el = this._dialog.find('.modal-body').first();
        this._btnGroup = this._el.find('.btn-group-existing').first();
        this._btnGroupPopular = this._dialog.find('.btn-group-popular').first();

		//fill pointer names
        pointerNames.sort();
        for (i = 0; i < len ; i += 1) {
            this._btnGroup.append($('<button class="btn">' + util.toSafeString(pointerNames[i]) + '</button>'));
        }

        //add most popular ones
        len = POPULAR_POINTER_NAMES.length;
        popularsAdded = false;
        for (i = 0; i < len ; i += 1) {
            if (pointerNames.indexOf(POPULAR_POINTER_NAMES[i]) === -1) {
                this._btnGroupPopular.append($('<button class="btn">' + POPULAR_POINTER_NAMES[i] + '</button>'));
                popularsAdded = true;
            }
        }

        //if all the popular ones were there already, remove popular panel completely
        if (!popularsAdded) {
            this._dialog.find('.panel-popular').remove();
        }

        //create UI for new pointer name
        this._txtNewPointerName =  this._dialog.find('.txt-pointer-name').first();
        this._btnCreateNew = this._dialog.find('.btn-create').first();
        this._panelCreateNew = this._dialog.find('.panel-create-new').first();

        //hook up event handlers
        this._btnGroup.on('click', '.btn', function (event) {
        	var selectedPointerName = $(this).text();

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

            closeAndCallback(selectedPointerName);
        });

        //hook up event handlers
        this._btnGroupPopular.on('click', '.btn', function (event) {
            var selectedPointerName = $(this).text();

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

            closeAndCallback(selectedPointerName);
        });

        this._txtNewPointerName.on('keyup', function () {
            var val = self._txtNewPointerName.val();

            self._btnCreateNew.text('Create \'' + val +'\'');

            if (!isValidPointerName(val)) {
                self._panelCreateNew.addClass("error");
                self._btnCreateNew.addClass("disabled");
            } else {
                self._panelCreateNew.removeClass("error");
                self._btnCreateNew.removeClass("disabled");
            }
        });

        this._txtNewPointerName.on('keydown', function (event) {
            var enterPressed = event.which === 13,
                selectedPointerName = self._txtNewPointerName.val();

            if (enterPressed && isValidPointerName(selectedPointerName)) {
                closeAndCallback(selectedPointerName);

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

        this._btnCreateNew.on('click', function (event) {
        	var selectedPointerName = self._txtNewPointerName.val();

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

            if (!($(this).hasClass('disabled'))) {
            	closeAndCallback(selectedPointerName);
            }
        });
    };

    return MetaEditorPointerNamesDialog;
});<commit_msg>using CONSTANTS.POINTER_* for popular GME related pointer names and do not allow pointername CONSTANTS.POINTER_BASE<commit_after>"use strict";

define(['clientUtil',
        'js/Constants',
        'text!html/Widgets/MetaEditor/MetaEditorPointerNamesDialog.html',
        'css!/css/Widgets/MetaEditor/MetaEditorPointerNamesDialog'], function ( util,
                                                                                CONSTANTS,
                                                               metaEditorPointerNamesDialogTemplate) {

    var MetaEditorPointerNamesDialog,
        POPULAR_POINTER_NAMES = [CONSTANTS.POINTER_SOURCE, CONSTANTS.POINTER_TARGET, CONSTANTS.POINTER_REF],
        RESERVED_POINTER_NAMES = [CONSTANTS.POINTER_BASE];

    MetaEditorPointerNamesDialog = function () {

    };

    MetaEditorPointerNamesDialog.prototype.show = function (pointerNames, callBack) {
        var self = this;

        this._initDialog(pointerNames, callBack);

        this._dialog.modal('show');

        this._dialog.on('shown', function () {
            if (pointerNames.length === 0) {
	        	self._txtNewPointerName.focus();
	        }
        });

        this._dialog.on('hidden', function () {
            self._dialog.remove();
            self._dialog.empty();
            self._dialog = undefined;
        });
    };

    MetaEditorPointerNamesDialog.prototype._initDialog = function (pointerNames, callBack) {
        var self = this,
            i,
            len = pointerNames.length,
            closeAndCallback,
            popularsAdded,
            isValidPointerName;

        closeAndCallback = function (selectedName) {
        	self._dialog.modal('hide');

        	if (callBack) {
        		callBack.call(self, selectedName);
        	}
        };

        isValidPointerName = function (name) {
            return !(name === "" || pointerNames.indexOf(name) !== -1 || RESERVED_POINTER_NAMES.indexOf(name) !== -1);
        };

        this._dialog = $(metaEditorPointerNamesDialogTemplate);

        //get controls
        this._el = this._dialog.find('.modal-body').first();
        this._btnGroup = this._el.find('.btn-group-existing').first();
        this._btnGroupPopular = this._dialog.find('.btn-group-popular').first();

		//fill pointer names
        pointerNames.sort();
        for (i = 0; i < len ; i += 1) {
            this._btnGroup.append($('<button class="btn">' + util.toSafeString(pointerNames[i]) + '</button>'));
        }

        //add most popular ones
        len = POPULAR_POINTER_NAMES.length;
        popularsAdded = false;
        for (i = 0; i < len ; i += 1) {
            if (pointerNames.indexOf(POPULAR_POINTER_NAMES[i]) === -1) {
                this._btnGroupPopular.append($('<button class="btn">' + POPULAR_POINTER_NAMES[i] + '</button>'));
                popularsAdded = true;
            }
        }

        //if all the popular ones were there already, remove popular panel completely
        if (!popularsAdded) {
            this._dialog.find('.panel-popular').remove();
        }

        //create UI for new pointer name
        this._txtNewPointerName =  this._dialog.find('.txt-pointer-name').first();
        this._btnCreateNew = this._dialog.find('.btn-create').first();
        this._panelCreateNew = this._dialog.find('.panel-create-new').first();

        //hook up event handlers
        this._btnGroup.on('click', '.btn', function (event) {
        	var selectedPointerName = $(this).text();

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

            closeAndCallback(selectedPointerName);
        });

        //hook up event handlers
        this._btnGroupPopular.on('click', '.btn', function (event) {
            var selectedPointerName = $(this).text();

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

            closeAndCallback(selectedPointerName);
        });

        this._txtNewPointerName.on('keyup', function () {
            var val = self._txtNewPointerName.val();

            self._btnCreateNew.text('Create \'' + val +'\'');

            if (!isValidPointerName(val)) {
                self._panelCreateNew.addClass("error");
                self._btnCreateNew.addClass("disabled");
            } else {
                self._panelCreateNew.removeClass("error");
                self._btnCreateNew.removeClass("disabled");
            }
        });

        this._txtNewPointerName.on('keydown', function (event) {
            var enterPressed = event.which === 13,
                selectedPointerName = self._txtNewPointerName.val();

            if (enterPressed && isValidPointerName(selectedPointerName)) {
                closeAndCallback(selectedPointerName);

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

        this._btnCreateNew.on('click', function (event) {
        	var selectedPointerName = self._txtNewPointerName.val();

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

            if (!($(this).hasClass('disabled'))) {
            	closeAndCallback(selectedPointerName);
            }
        });
    };

    return MetaEditorPointerNamesDialog;
});<|endoftext|>


<commit_before>const path = require('path');
const merge = require('webpack-merge');
const validateOptions = require('./options-validator');

// Constants
const DEFAULT_PATTERN = '**/*.svg';

module.exports = (pattern, options) => {
    // Make the first argument optional, just passing a configuration
    // object should result in the default pattern being used
    if ( typeof options === 'undefined' && (typeof pattern === 'object' && pattern !== null) ) {
        options = pattern;
        pattern = DEFAULT_PATTERN;
    } else if ( typeof pattern === 'undefined' && typeof options === 'undefined' ) {
        pattern = DEFAULT_PATTERN;
    }

    // Validate input
    validateOptions(pattern, options);

    // Format output (`null` values will be overwritten below the object initialization)
    const output = merge({
        input: {
            options: {}
        },
        output: {
            filename: 'spritemap.svg',
            svg: {
                sizes: null
            },
            chunk: {
                name: 'spritemap',
                delete: true
            },
            svg4everybody: false,
            svgo: true
        },
        sprite: {
            prefix: 'sprite-',
            idify: require('html4-id'), // TODO [MAJOR]: Replace this with a function that returns a valid HTML5 id (https://html.spec.whatwg.org/multipage/dom.html#the-id-attribute)
            gutter: 0,
            generate: {
                title: true,
                symbol: true,
                use: false,
                view: false
            }
        },
        styles: false
    }, options, {
        input: {
            patterns: typeof pattern === 'string' ? [pattern] : pattern
        }
    });

    // [input.patterns] Normalize the patterns to make sure the correct slashes are used
    output.input.patterns = output.input.patterns.map((pattern) => path.normalize(pattern));

    // [output.svg.sizes] If no option is specified base this on the `sprite.generate.use` option
    if ( output.output.svg.sizes === null ) {
        output.output.svg.sizes = output.sprite.generate.use;
    }

    // [output.svgo] If enabled by by passing `true`, set it to an empty object
    if ( output.output.svgo === true ) {
        output.output.svgo = {};
    }

    // [output.svg4everybody] If enabled by by passing `true`, set it to an empty object
    if ( output.output.svg4everybody === true ) {
        output.output.svg4everybody = {};
    }

    // [sprite.prefix] If disabled by passing `false`, set it to an empty string
    if ( output.sprite.prefix === false ) {
        output.sprite.prefix = '';
    }

    // [sprite.idify] If disabled by passing `false`, set it to a function that returns the input
    if ( output.sprite.idify === false ) {
        output.sprite.idify = (value) => value;
    }

    // [sprite.gutter] Reformat `false` to 0
    if ( output.sprite.gutter === false ) {
        output.sprite.gutter = 0;
    }

    if ( output.styles ) {
        if ( typeof output.styles === 'string' ) {
            output.styles = {
                filename: output.styles
            };
        } else if ( output.styles === true ) {
            output.styles = {};
        }

        output.styles = merge({
            filename: '~sprites.css',
            format: 'data',
            variables: {
                sprites: 'sprites',
                sizes: 'sizes',
                variables: 'variables',
                mixin: 'sprite'
            }
        }, output.styles);
    }

    return output;
};
<commit_msg>Fix leftover chunk.delete option default in options-formatter<commit_after>const path = require('path');
const merge = require('webpack-merge');
const validateOptions = require('./options-validator');

// Constants
const DEFAULT_PATTERN = '**/*.svg';

module.exports = (pattern, options) => {
    // Make the first argument optional, just passing a configuration
    // object should result in the default pattern being used
    if ( typeof options === 'undefined' && (typeof pattern === 'object' && pattern !== null) ) {
        options = pattern;
        pattern = DEFAULT_PATTERN;
    } else if ( typeof pattern === 'undefined' && typeof options === 'undefined' ) {
        pattern = DEFAULT_PATTERN;
    }

    // Validate input
    validateOptions(pattern, options);

    // Format output (`null` values will be overwritten below the object initialization)
    const output = merge({
        input: {
            options: {}
        },
        output: {
            filename: 'spritemap.svg',
            svg: {
                sizes: null
            },
            chunk: {
                name: 'spritemap',
                keep: false
            },
            svg4everybody: false,
            svgo: true
        },
        sprite: {
            prefix: 'sprite-',
            idify: require('html4-id'), // TODO [MAJOR]: Replace this with a function that returns a valid HTML5 id (https://html.spec.whatwg.org/multipage/dom.html#the-id-attribute)
            gutter: 0,
            generate: {
                title: true,
                symbol: true,
                use: false,
                view: false
            }
        },
        styles: false
    }, options, {
        input: {
            patterns: typeof pattern === 'string' ? [pattern] : pattern
        }
    });

    // [input.patterns] Normalize the patterns to make sure the correct slashes are used
    output.input.patterns = output.input.patterns.map((pattern) => path.normalize(pattern));

    // [output.svg.sizes] If no option is specified base this on the `sprite.generate.use` option
    if ( output.output.svg.sizes === null ) {
        output.output.svg.sizes = output.sprite.generate.use;
    }

    // [output.svgo] If enabled by by passing `true`, set it to an empty object
    if ( output.output.svgo === true ) {
        output.output.svgo = {};
    }

    // [output.svg4everybody] If enabled by by passing `true`, set it to an empty object
    if ( output.output.svg4everybody === true ) {
        output.output.svg4everybody = {};
    }

    // [sprite.prefix] If disabled by passing `false`, set it to an empty string
    if ( output.sprite.prefix === false ) {
        output.sprite.prefix = '';
    }

    // [sprite.idify] If disabled by passing `false`, set it to a function that returns the input
    if ( output.sprite.idify === false ) {
        output.sprite.idify = (value) => value;
    }

    // [sprite.gutter] Reformat `false` to 0
    if ( output.sprite.gutter === false ) {
        output.sprite.gutter = 0;
    }

    if ( output.styles ) {
        if ( typeof output.styles === 'string' ) {
            output.styles = {
                filename: output.styles
            };
        } else if ( output.styles === true ) {
            output.styles = {};
        }

        output.styles = merge({
            filename: '~sprites.css',
            format: 'data',
            variables: {
                sprites: 'sprites',
                sizes: 'sizes',
                variables: 'variables',
                mixin: 'sprite'
            }
        }, output.styles);
    }

    return output;
};
<|endoftext|>


<commit_before>'use strict';

const gulp = global.gulp;
const replace = require('gulp-replace');
const utils = require('fepper-utils');

const conf = global.conf;
const pref = global.pref;

const backendStylesDirChild = utils.backendDirCheck(`${pref.backend.synced_dirs.styles_dir}/bld`);

let backendStylesDirParent = pref.backend.synced_dirs.styles_dir.replace('-child', '');
backendStylesDirParent = utils.backendDirCheck(`${backendStylesDirParent}/bld`);

gulp.task('tab-indent-compiled-stylus:parent', function (cb) {
  if (backendStylesDirParent) {
    return gulp.src(conf.ui.paths.public.cssBld + '/style.css')
      .pipe(replace(/ {2}/g, '\t'))
      .pipe(gulp.dest(backendStylesDirParent));
  }
  else {
    cb();
  }
});

gulp.task('tab-indent-compiled-stylus:child', function (cb) {
  if (backendStylesDirChild) {
    return gulp.src(conf.ui.paths.public.cssBld + '/style-child.css')
      .pipe(replace(/ {2}/g, '\t'))
      .pipe(gulp.dest(backendStylesDirChild));
  }
  else {
    cb();
  }
});

gulp.task('tab-indent-compiled-stylus', [
  'tab-indent-compiled-stylus:parent',
  'tab-indent-compiled-stylus:child'
]);
<commit_msg>custom wp-stylus extension copies from source instead of public<commit_after>'use strict';

const gulp = global.gulp;
const replace = require('gulp-replace');
const utils = require('fepper-utils');

const conf = global.conf;
const pref = global.pref;

const backendStylesDirChild = utils.backendDirCheck(`${pref.backend.synced_dirs.styles_dir}/bld`);

let backendStylesDirParent = pref.backend.synced_dirs.styles_dir.replace('-child', '');
backendStylesDirParent = utils.backendDirCheck(`${backendStylesDirParent}/bld`);

gulp.task('tab-indent-compiled-stylus:parent', function (cb) {
  if (backendStylesDirParent) {
    return gulp.src(conf.ui.paths.source.cssBld + '/style.css')
      .pipe(replace(/ {2}/g, '\t'))
      .pipe(gulp.dest(backendStylesDirParent));
  }
  else {
    cb();
  }
});

gulp.task('tab-indent-compiled-stylus:child', function (cb) {
  if (backendStylesDirChild) {
    return gulp.src(conf.ui.paths.source.cssBld + '/style-child.css')
      .pipe(replace(/ {2}/g, '\t'))
      .pipe(gulp.dest(backendStylesDirChild));
  }
  else {
    cb();
  }
});

gulp.task('tab-indent-compiled-stylus', [
  'tab-indent-compiled-stylus:parent',
  'tab-indent-compiled-stylus:child'
]);
<|endoftext|>


<commit_before>/*
* scripts page implementation
*/
var Scripts = new function(){

	/*
	* initialize scripts page; load documents
	*/
	this.initialize = function(){

		var gui = this;

		this.selectionContainer = $("#scriptsSelection");
		$('
'+Util.getString('scriptSelection')+'
').appendTo(this.selectionContainer);
		$('
'+Util.getString('directSelection')+'
').appendTo(this.selectionContainer);
		$('
'+Util.getString('pleaseSelect')+'
').appendTo(this.selectionContainer);

		var form = $('<form/>').appendTo(this.selectionContainer);
		var fieldset = $('<fieldset/>').appendTo(form);
		this.selectionDropdown = $('<select class="selectHandschriften"/>').appendTo(fieldset);
		$(this.selectionDropdown).change(function(){
			$("select option:selected",this.selectionDropdown).each(function(){
				gui.showDocument($(this).attr('id'));
			});
		});

		$('<option>'+Util.getString('selectHandwriting')+'</option>').appendTo(gui.selectionDropdown);

		var loadDocs = function(){
			if( Util.docsLoaded ){
				for( var i=0; i<Util.documents.length; i++ ){
					$('<option id="'+Util.documents[i].title+'">'+Util.documents[i].name+'</option>').appendTo(gui.selectionDropdown);
				}
			}
			else {
				setTimeout(function(){
					loadDocs();
				}, 1000 );
			}
		}
		loadDocs();

		this.scriptContainer = $("#scriptContainer");

	};

	/*
	* show document with given <title>
	*/
	this.showDocument = function(title){
		if( title == Util.getString('selectHandwriting') ){
			return;
		}
		var doc = Util.getDoc(title);
		var gui = this;
		$(this.scriptContainer).empty();
		$.ajax({
			url: EditionProperties.metadataQuery.replace('DOC_ID',title),
			dataType: 'html',
			success: function(xhtml){
				$('
'+Util.getString('handwriting')+': '+title+'
').appendTo(gui.scriptContainer);
				var width = ScriptsProps.hwImageWidth;
				var height = ScriptsProps.hwImageHeight;
				var imageDiv = $('
').appendTo(gui.scriptContainer);
				var image = $('').appendTo(imageDiv);
				var contentDiv = $('
').appendTo(gui.scriptContainer);
				$(xhtml).appendTo(contentDiv);
				$('span',contentDiv).each(function(){
					var lang = Util.getAttribute(this,'xml:lang');
					if( Util.language != lang ){
						$(this).css('display','none');
					}
				});
			}
		});
	};

};

ScriptsProps = {
	// default size if manuscripts page image
	hwImageHeight: 328,
	hwImageWidth: 359
};

Scripts.initialize();
<commit_msg>repaired Scripts (really)<commit_after>/*
* scripts page implementation
*/
var Scripts = new function(){

	/*
	* initialize scripts page; load documents
	*/
	this.initialize = function(){

		var gui = this;

		this.selectionContainer = $("#scriptsSelection");
		$('
'+Util.getString('scriptSelection')+'
').appendTo(this.selectionContainer);
		$('
'+Util.getString('directSelection')+'
').appendTo(this.selectionContainer);
		$('
'+Util.getString('pleaseSelect')+'
').appendTo(this.selectionContainer);

		var form = $('<form/>').appendTo(this.selectionContainer);
		var fieldset = $('<fieldset/>').appendTo(form);
		this.selectionDropdown = $('<select class="selectHandschriften"/>').appendTo(fieldset);

		$('<option>'+Util.getString('selectHandwriting')+'</option>').appendTo(gui.selectionDropdown);
		$(this.selectionDropdown).change(function(){
			$("select option:selected",this.selectionDropdown).each(function(){
				if( $(this).attr('id') != '' ){
					gui.showDocument($(this).attr('id'));
				}
			});
		});

		var loadDocs = function(){
			if( Util.docsLoaded ){
				for( var i=0; i<Util.documents.length; i++ ){
					$('<option id="'+Util.documents[i].title+'">'+Util.documents[i].name+'</option>').appendTo(gui.selectionDropdown);
				}
			}
			else {
				setTimeout(function(){
					loadDocs();
				}, 1000 );
			}
		}
		loadDocs();

		this.scriptContainer = $("#scriptContainer");

	};

	/*
	* show document with given <title>
	*/
	this.showDocument = function(title){
		if( title == Util.getString('selectHandwriting') ){
			return;
		}
		var doc = Util.getDoc(title);
		var gui = this;
		$(this.scriptContainer).empty();
		$.ajax({
			url: EditionProperties.metadataQuery.replace('DOC_ID',title),
			dataType: 'html',
			success: function(xhtml){
				$('
'+Util.getString('handwriting')+': '+title+'
').appendTo(gui.scriptContainer);
				var width = ScriptsProps.hwImageWidth;
				var height = ScriptsProps.hwImageHeight;
				var imageDiv = $('
').appendTo(gui.scriptContainer);
				var image = $('').appendTo(imageDiv);
				var contentDiv = $('
').appendTo(gui.scriptContainer);
				$(xhtml).appendTo(contentDiv);
				$('span',contentDiv).each(function(){
					var lang = Util.getAttribute(this,'xml:lang');
					if( Util.language != lang ){
						$(this).css('display','none');
					}
				});
			}
		});
	};

};

ScriptsProps = {
	// default size if manuscripts page image
	hwImageHeight: 328,
	hwImageWidth: 359
};

Scripts.initialize();
<|endoftext|>


<commit_before>
const EventEmitter = require('events');
const Packet = require('./Packet');
const net = require('./protocol');

class User extends EventEmitter {

	/**
	 * Create a new instance of User
	 * @param {WebSocket} socket the web socket that connects to the client
	 */
	constructor(socket = null) {
		super();

		this.id = 0;
		this.server = null;
		this.setSocket(socket);
	}

	/**
	 * @return {boolean} whether the user is connected
	 */
	get connected() {
		return this.socket && this.socket.readyState == WebSocket.OPEN;
	}

	/**
	 * @return {{id:number,name:string}} brief infomation
	 */
	get briefInfo() {
		return {
			id: this.id,
			nickname: this.nickname
		};
	}

	/**
	 * Send a command to the client
	 * @param {number} command
	 * @param {object} arguments
	 * @return {boolean} true iff. the command was sent
	 */
	send(command, args = null) {
		if (!this.socket) {
			return false;
		}

		let packet = new Packet;
		packet.command = command;
		if (args) {
			packet.arguments = args;
		}

		this.socket.send(packet.toJSON());
		return true;
	}

	/**
	 * Send a notification to the client
	 * @param {number} command
	 * @param {object} args
	 */
	notify(command, args) {
		this.send(net.Notify, {
			cmd: command,
			arg: args,
		});
	}

	/**
	 * Disconnect the client
	 */
	disconnect() {
		if (this.socket) {
			this.socket.close();
			this.socket = null;
		}
	}

	/**
	 * Disconnect current socket and set a new one
	 * @param {WebSocket} socket
	 */
	setSocket(socket) {
		if (this.socket) {
			this.disconnect();
		}

		this.socket = socket;
		if (socket) {
			this.socket.on('message', json => {
				let packet = new Packet;
				if (packet.parse(json)) {
					this.emit('action', packet);
				}
			});

			this.socket.on('close', (code, reason) => {
				this.emit('close', code, reason);
			});
		}
	}
}

module.exports = User;
<commit_msg>Handle unexpected socket error<commit_after>
const EventEmitter = require('events');
const Packet = require('./Packet');
const net = require('./protocol');

class User extends EventEmitter {

	/**
	 * Create a new instance of User
	 * @param {WebSocket} socket the web socket that connects to the client
	 */
	constructor(socket = null) {
		super();

		this.id = 0;
		this.server = null;
		this.setSocket(socket);
	}

	/**
	 * @return {boolean} whether the user is connected
	 */
	get connected() {
		return this.socket && this.socket.readyState == WebSocket.OPEN;
	}

	/**
	 * @return {{id:number,name:string}} brief infomation
	 */
	get briefInfo() {
		return {
			id: this.id,
			nickname: this.nickname
		};
	}

	/**
	 * Send a command to the client
	 * @param {number} command
	 * @param {object} arguments
	 * @return {boolean} true iff. the command was sent
	 */
	send(command, args = null) {
		if (!this.socket) {
			return false;
		}

		let packet = new Packet;
		packet.command = command;
		if (args) {
			packet.arguments = args;
		}

		this.socket.send(packet.toJSON());
		return true;
	}

	/**
	 * Send a notification to the client
	 * @param {number} command
	 * @param {object} args
	 */
	notify(command, args) {
		this.send(net.Notify, {
			cmd: command,
			arg: args,
		});
	}

	/**
	 * Disconnect the client
	 */
	disconnect() {
		if (this.socket) {
			this.socket.close();
			this.socket = null;
		}
	}

	/**
	 * Disconnect current socket and set a new one
	 * @param {WebSocket} socket
	 */
	setSocket(socket) {
		if (this.socket) {
			this.disconnect();
		}

		this.socket = socket;
		if (socket) {
			this.socket.on('message', json => {
				let packet = new Packet;
				if (packet.parse(json)) {
					this.emit('action', packet);
				}
			});

			this.socket.on('close', (code, reason) => {
				this.emit('close', code, reason);
			});

			this.socket.on('error', error => {
				this.emit('close', error.code, error.message);
			});
		}
	}
}

module.exports = User;
<|endoftext|>