text:
/**
 * This class handles interactions, such as neumify, ungroup, head shape changes, deletions, etc.,
 * with the GUI to editing a page of cheironomic (staffless) neumes.
 *
 * @class Handles interactions with cheironomic (staffless) neumes
 * @param {Toe.View.RenderEngine} rendEng The rendering engine for glyphs on the page
 * @param {Toe.Model.Page} page The model of the page of music being edited
 * @param {String} apiprefix The prefix for each API function call
 * @param {Object} guiToggles Various presets and options for the starting state of the GUI
 */
Toe.View.CheironomicInteraction = function(rendEng, page, apiprefix, guiToggles) {
    Toe.View.Interaction.call(this, rendEng, page, apiprefix, guiToggles);
    var toggles = {
        initMode: "edit"
    };

    $.extend(toggles, guiToggles);

    // pointer to the the punctum drawing in insert mode
    this.punctDwg = null;

    /*
     * cache height and width of punctum glyph for use
     * in bounding box estimation in neumify and ungroup
     * and insert ornamentation spacing
     */
    var punctGlyph = rendEng.getGlyph("punctum").clone();
    this.punctWidth = punctGlyph.width*rendEng.getGlobalScale();
    this.punctHeight = punctGlyph.height*rendEng.getGlobalScale();

    this.objMoving = false;
    var parentDivId = "#gui-sidebar";

    // switch to edit mode
    $("#btn_edit").bind("click.edit", {gui: this, parentDivId: parentDivId}, this.handleEdit);

    // switch to insert mode
    $("#btn_insert").bind("click.insert", {gui: this, parentDivId: parentDivId}, this.handleInsert);

    // set active button on startup
    $("#btn_" + toggles.initMode).trigger('click');

    this.bindHotKeys();
};

Toe.View.CheironomicInteraction.prototype = new Toe.View.Interaction();
Toe.View.CheironomicInteraction.prototype.constructor = Toe.View.CheironomicInteraction;

/**************************************************
 *                  EDIT                          *
 **************************************************/
/**
 * Handler that sets up the GUI for editing the page of music by disabling the
 * handlers for insert mode and setting up handlers for edit mode.
 *
 * @methodOf Toe.View.CheironomicInteraction
 * @param {Event} e JavaScript event for the edit button push
 */
Toe.View.CheironomicInteraction.prototype.handleEdit = function(e) {
    var gui = e.data.gui;
    gui.activateCanvasObjects();
    gui.hideInfo();
    gui.removeInsertControls();
    gui.unbindEventHandlers();
    gui.insertEditControls(e.data.parentDivId);

    // remove drawings following the pointer from insert mode
    if (gui.punctDwg) {
        gui.rendEng.canvas.remove(gui.punctDwg);
    }
    gui.rendEng.repaint();

    // on mouse down get pointer coordinates
    gui.rendEng.canvas.observe('mouse:down', function(e) {
        // cache pointer coordinates for mouse up
        gui.downCoords = gui.rendEng.canvas.getPointer(e.e);
    });

    // set a flag when an object on the canvas is moving
    gui.rendEng.canvas.observe('object:moving', function(e) {
        gui.objMoving = true;
    });

    // when a selection is created, update the appearance of GUI widgets
    gui.rendEng.canvas.observe('selection:created', function(e) {
        var selection = e.target;
        selection.hasControls = false;
        selection.borderColor = 'rgba(102,153,255,1.0)';

        // disable/enable buttons
        var toNeumify = 0;
        var toUngroup = 0;
        var sModel = null;
        $.each(selection.getObjects(), function (oInd, o) {
            // don't draw a selection border around each object in the selection
            o.borderColor = 'rgba(0,0,0,0)';

            if (o.eleRef instanceof Toe.Model.Neume) {
                if (!sModel) {
                    sModel = o.eleRef.system;
                }

                toUngroup++;

                if (o.eleRef.system == sModel) {
                    toNeumify++;
                }
            }
        });

        $('#btn_delete').toggleClass('disabled', false);

        if (toNeumify < 2) {
            $('#btn_neumify').toggleClass('disabled', true);
            //$('#btn_neumify_liquescence').toggleClass('disabled', true);
        }
        else {
            $('#btn_neumify').toggleClass('disabled', false);
            $('#btn_neumify_liquescence_aug').toggleClass('disabled', false);
            $('#btn_neumify_liquescence_dim').toggleClass('disabled', false);
        }

        if (toUngroup > 0) {
            $('#btn_ungroup').toggleClass('disabled', false);
        }
        else {
            $('#btn_ungroup').toggleClass('disabled', true);
        }
    });

    // when a single object is selected, update GUI widgets
    gui.rendEng.canvas.observe('object:selected', function(e) {
        $('#btn_delete').toggleClass('disabled', false);

        var selection = gui.rendEng.canvas.getActiveObject();
        var ele = selection.eleRef;
        if (ele instanceof Toe.Model.Neume) {
            gui.showInfo("Selected: " + ele.name);

            $('#btn_ungroup').toggleClass('disabled', false);

            $("#menu_editclef").remove();

            if (ele.typeid == "punctum" || ele.typeid == "tractulus" ||
                ele.typeid == "cavum" || ele.typeid == "virga" ||
                ele.typeid == "gravis" || ele.typeid == "oriscus" || ele.typeid == "stropha") {

                if ($("#menu_editpunctum").length == 0) {
                    $("#sidebar-edit").append('

Ornamentation
\n' +
                                              '

\n' +
                                              '<button id="edit_chk_dot" class="btn">• Dot</button>\n' +
                                              '<button id="edit_chk_horizepisema" class="btn"> Episema</button>\n' +
                                              '<button id="edit_chk_vertepisema" class="btn"> Episema</button>\n

\n' +
                                              '

Attributes
\n' +
                                              '

\n' +
                                              'Head shape
\n' +
                                              '
punctum
\n' +
                                              '
tractulus
\n' +
                                              '
virga
\n' +
                                              '
gravis
\n' +
                                              '
oriscus
\n' +
                                              '
stropha
\n' +
                                              '
quilisma
\n' +
                                              '

');
                }

                // toggle ornamentation
                var nc = ele.components[0];
                var hasDot = nc.hasOrnament("dot");
                if (hasDot) {
                    $("#edit_chk_dot").toggleClass("active", true);
                }
                else {
                    $("#edit_chk_dot").toggleClass("active", false);
                }

                // Handle dot toggles
                // remove onclick listener for previous selection
                $("#edit_chk_dot").unbind("click");
                $("#edit_chk_dot").bind("click.edit", {gui: gui, punctum: ele}, gui.handleDotToggle);

                // Handle head shape change
                $("#head_punctum").unbind("click");
                $("#head_tractulus").unbind("click");
                $("#head_virga").unbind("click");
                $("#head_quilisma").unbind("click");
                $("#head_punctum").bind("click.edit", {gui: gui, punctum: ele, shape: "punctum"}, gui.handleHeadShapeChange);
                $("#head_tractulus").bind("click.edit", {gui: gui, punctum: ele, shape: "tractulus"}, gui.handleHeadShapeChange);
                $("#head_virga").bind("click.edit", {gui: gui, punctum: ele, shape: "virga"}, gui.handleHeadShapeChange);
                $("#head_gravis").bind("click.edit", {gui: gui, punctum: ele, shape: "gravis"}, gui.handleHeadShapeChange);
                $("#head_oriscus").bind("click.edit", {gui: gui, punctum: ele, shape: "oriscus"}, gui.handleHeadShapeChange);
                $("#head_stropha").bind("click.edit", {gui: gui, punctum: ele, shape: "stropha"}, gui.handleHeadShapeChange);
                $("#head_quilisma").bind("click.edit", {gui: gui, punctum: ele, shape: "quilisma"}, gui.handleHeadShapeChange);
            }
            else {
                $("#menu_editpunctum").remove();
            }
        }
        else {
            $("#menu_editpunctum").remove();
        }
    });

    // when a set of objects are deselected, update the GUI widgets
    gui.rendEng.canvas.observe('selection:cleared', function(e) {
        gui.hideInfo();

        // remove selection specific editing options
        $("#menu_editpunctum").remove();

        $('#btn_delete').toggleClass('disabled', true);
        $('#btn_neumify').toggleClass('disabled', true);
        $('#btn_neumify_liquescence_aug').toggleClass('disabled', true);
        $('#btn_neumify_liquescence_dim').toggleClass('disabled', true);
        $('#btn_ungroup').toggleClass('disabled', true);
    });

    gui.rendEng.canvas.observe('mouse:up', function(e) {
        var upCoords = gui.rendEng.canvas.getPointer(e.e);

        // get delta of the mouse movement
        var delta_x = gui.downCoords.x - upCoords.x;
        var delta_y = gui.downCoords.y - upCoords.y;
        // don't perform dragging action if the mouse doesn't move
        if (!gui.objMoving) {
            return;
        }

        // if something is selected we need to do some housekeeping
        // check for single selection
        var selection = gui.rendEng.canvas.getActiveObject();
        if (!selection) {
            // check for group selection
            selection = gui.rendEng.canvas.getActiveGroup();
        }

        if (selection) {
            var elements = new Array();
            if (selection.eleRef) {
                elements.push(selection);
            }
            else {
                $.each(selection.objects, function(ind, el) {
                    elements.push(el);
                });
            }

            $.each(elements, function(ind, element) {
                var ele = element.eleRef;

                // move neume
                if (ele instanceof Toe.Model.Neume) {
                    // snap to system
                    var finalCoords = {x: element.left, y: element.top};
                    var sModel = gui.page.getClosestSystem(finalCoords);
                    var snapCoords = sModel.getSystemSnapCoordinates(finalCoords, element.currentWidth, {ignoreEle: ele, y: false});

                    // set the bounding box hint for the neume
                    var ulx = snapCoords.x-(element.currentWidth/2);
                    var uly = snapCoords.y-(element.currentHeight/2);
                    var lrx = ulx + element.currentWidth;
                    var lry = uly + element.currentWidth;
                    ele.setBoundingBox([ulx, uly, lrx, lry]);

                    // remove the old neume
                    $(ele).trigger("vEraseDrawing");
                    ele.system.removeElementByRef(ele);

                    // mount the new neume on the most appropriate system
                    var nInd = sModel.addNeume(ele);
                    if (elements.length == 1) {
                        $(ele).trigger("vSelectDrawing");
                    }

                    // send pitch shift command to server to change underlying MEI
                    var outbb = gui.getOutputBoundingBox([ulx, uly, lrx, lry]);
                    var args = {id: ele.id, ulx: outbb[0], uly: outbb[1], lrx: outbb[2], lry: outbb[3], pitchInfo: null};

                    // get next element to insert before
                    if (nInd + 1 < sModel.elements.length) {
                        args["beforeid"] = sModel.elements[nInd+1].id;
                    }
                    else {
                        // insert before the next system break (system)
                        var sNextModel = gui.page.getNextSystem(sModel);
                        args["beforeid"] = sNextModel.id;
                    }

                    $.post(gui.apiprefix + "/move/neume", {data: JSON.stringify(args)})
                    .error(function() {
                        gui.showAlert("Server failed to move neume. Client and server are not synchronized.");
                    });
                }
            });
            if (elements.length > 1) {
                gui.rendEng.canvas.discardActiveGroup();
            }
            gui.rendEng.repaint();
        }
        // we're all done moving
        gui.objMoving = false;
    });

    // Bind click handlers for the side-bar buttons
    $("#btn_delete").unbind("click");
    $("#btn_neumify").unbind("click");
    $("#btn_ungroup").unbind("click");

    $("#btn_delete").bind("click.edit", {gui: gui}, gui.handleDelete);
    $("#btn_neumify").bind("click.edit", {gui: gui}, gui.handleNeumify);
    $("#btn_neumify_liquescence_aug").bind("click.edit", {gui: gui, modifier: "aug"}, gui.handleNeumify);
    $("#btn_neumify_liquescence_dim").bind("click.edit", {gui: gui, modifier: "dim"}, gui.handleNeumify);
    $("#btn_ungroup").bind("click.edit", {gui: gui}, gui.handleUngroup);
}

/**
 * Handler for toggling a dot on a single punctum neume.
 *
 * @methodOf Toe.View.CheironomicInteraction
 * @param {Event} e Event of the dot toggle button
 */
Toe.View.CheironomicInteraction.prototype.handleDotToggle = function(e) {
    var gui = e.data.gui;
    var punctum = e.data.punctum;

    var hasDot = punctum.components[0].hasOrnament("dot");
    if (!hasDot) {
        // add a dot
        var ornament = new Toe.Model.Ornament("dot", {form: "aug"});
        punctum.components[0].addOrnament(ornament);
    }
    else {
        // remove the dot
        punctum.components[0].removeOrnament("dot");
    }

    // update neume drawing
    punctum.syncDrawing();

    // get final bounding box information
    var outbb = gui.getOutputBoundingBox([punctum.zone.ulx, punctum.zone.uly, punctum.zone.lrx, punctum.zone.lry]);
    var args = {id: punctum.id, dotform: "aug", ulx: outbb[0], uly: outbb[1], lrx: outbb[2], lry: outbb[3]};
    if (!hasDot) {
        // send add dot command to server to change underlying MEI
        $.post(gui.apiprefix + "/insert/dot", args)
        .error(function() {
            gui.showAlert("Server failed to add a dot to the punctum. Client and server are not synchronized.");
        });
    }
    else {
        // send remove dot command to server to change underlying MEI
        $.post(gui.apiprefix + "/delete/dot", args)
        .error(function() {
            gui.showAlert("Server failed to remove dot from the punctum. Client and server are not synchronized.");
        });
    }

    $(this).toggleClass("active");
}

/**
 * Handler for changing the head shape of a single punctum neume.
 *
 * @methodOf Toe.View.CheironomicInteraction
 * @param {Event} e Event for the head shape change selection box
 */
Toe.View.CheironomicInteraction.prototype.handleHeadShapeChange = function(e) {
    var gui = e.data.gui;
    var shape = e.data.shape;
    var punctum = e.data.punctum;
    var nc = punctum.components[0];

    nc.setHeadShape(shape);

    // deal with head shapes that change the neume name
    switch (shape) {
        case "punctum":
            punctum.name = "Punctum";
            punctum.typeid = "punctum";
            break;
        case "tractulus":
            punctum.name = "Tractulus";
            punctum.typeid = "tractulus";
            break;
        case "virga":
            punctum.name = "Virga";
            punctum.typeid = "virga";
            break;
        case "gravis":
            punctum.name = "Gravis";
            punctum.typeid = "gravis";
            break;
        case "oriscus":
            punctum.name = "Oriscus";
            punctum.typeid = "oriscus";
            break;
        case "stropha":
            punctum.name = "Stropha";
            punctum.typeid = "stropha";
            break;
    }

    // update drawing
    punctum.syncDrawing();

    var outbb = gui.getOutputBoundingBox([punctum.zone.ulx, punctum.zone.uly, punctum.zone.lrx, punctum.zone.lry]);
    var args = {id: punctum.id, shape: shape, ulx: outbb[0], uly: outbb[1], lrx: outbb[2], lry: outbb[3]};

    // send change head command to server to change underlying MEI
    $.post(gui.apiprefix + "/update/neume/headshape", args)
    .error(function() {
        gui.showAlert("Server failed to change note head shape. Client and server are not synchronized.");
    });
}

/**
 * Handler for deleting a set of neumes from the page
 *
 * @methodOf Toe.View.CheironomicInteraction
 * @param {Event} e Event for pressing the delete button
 */
Toe.View.CheironomicInteraction.prototype.handleDelete = function(e) {
    var gui = e.data.gui;

    // get current canvas selection
    // check individual selection and group selections
    var nids = new Array();

    var deleteNeume = function(drawing) {
        var neume = drawing.eleRef;

        neume.system.removeElementByRef(neume);
        nids.push(neume.id);

        gui.rendEng.canvas.discardActiveObject();
    };

    var selection = gui.rendEng.canvas.getActiveObject();
    if (selection) {
        if (selection.eleRef instanceof Toe.Model.Neume) {
            deleteNeume(selection);
        }
        gui.rendEng.repaint();
    }
    else {
        selection = gui.rendEng.canvas.getActiveGroup();
        if (selection) {
            // group of elements selected
            $.each(selection.getObjects(), function(oInd, o) {
                if (o.eleRef instanceof Toe.Model.Neume) {
                    deleteNeume(o);
                }
            });

            gui.rendEng.canvas.discardActiveGroup();
            gui.rendEng.repaint();
        }
    }

    if (nids.length > 0) {
        // send delete command to server to change underlying MEI
        $.post(gui.apiprefix + "/delete/neume",  {ids: nids.join(",")})
        .error(function() {
            gui.showAlert("Server failed to delete neume. Client and server are not synchronized.");
        });
    }
}

/**
 * Handler for neumifying a group of selected neumes on the canvas
 *
 * @methodOf Toe.View.CheironomicInteraction
 * @param {Event} e Event for pressing the neumify button
 */
Toe.View.CheironomicInteraction.prototype.handleNeumify = function(e) {
    var gui = e.data.gui;
    var modifier = e.data.modifier;

    // only need to neumify if a group of objects are selected
    var selection = gui.rendEng.canvas.getActiveGroup();
    if (selection) {
        // there is something selected
        // make sure there are at least 2 neumes on the same system to work with
        var neumes = new Array();
        var sModel = null;
        $.each(selection.getObjects(), function (oInd, o) {
            if (o.eleRef instanceof Toe.Model.Neume) {
                if (!sModel) {
                    sModel = o.eleRef.system;
                }

                if (o.eleRef.system == sModel) {
                    neumes.push(o);
                }
            }
        });

        if (neumes.length < 2) {
            return;
        }

        // sort the group based on x position (why fabric doesn't do this, I don't know)
        neumes.sort(function(o1, o2) {
            return o1.eleRef.zone.ulx - o2.eleRef.zone.ulx;
        });

        // begin the NEUMIFICATION
        var newNeume = new Toe.Model.CheironomicNeume({modifier: modifier});

        numPunct = 0;
        var nids = new Array();
        var ulx = Number.MAX_VALUE;
        var uly = Number.MAX_VALUE;
        var lry = Number.MIN_VALUE;

        var prevTop = null;
        $.each(neumes, function (oInd, o) {
            var nModel = o.eleRef;

            // grab underlying notes
            $.merge(newNeume.components, o.eleRef.components);

            // update neume ids
            nids.push(o.eleRef.id);

            // calculate object's absolute positions from within selection group
            // use the centre position of each neume to calculate the melodic movement of neume components
            var left = selection.left + o.left;
            var top = selection.top + o.top;
            if (oInd > 0) {
                var relativePitch = 0;
                if (top < prevTop) {
                    relativePitch = 1
                }
                else if (top > prevTop) {
                    relativePitch = -1;
                }
                newNeume.components[numPunct].relativePitch = relativePitch;
            }
            prevTop = top;

            ulx = Math.min(ulx, left - o.currentHeight/2);
            uly = Math.min(uly, top - o.currentHeight/2);
            lry = Math.max(lry, top + o.currentHeight/2);

            numPunct += o.eleRef.components.length;

            // remove the neume, we don't need it anymore
            sModel.removeElementByRef(o.eleRef);
            gui.rendEng.canvas.remove(o);

        });
        var lrx = ulx + numPunct*gui.punctWidth;

        // set the bounding box hint of the new neume for drawing
        var bb = [ulx, uly, lrx, lry];
        newNeume.setBoundingBox(bb);

        // instantiate neume view and controller
        var nView = new Toe.View.NeumeView(gui.rendEng, gui.page.documentType);
        var nCtrl = new Toe.Ctrl.NeumeController(newNeume, nView);

        // render the new neume
        sModel.addNeume(newNeume);

        // get final bounding box information
        var outbb = gui.getOutputBoundingBox([newNeume.zone.ulx, newNeume.zone.uly, newNeume.zone.lrx, newNeume.zone.lry]);

        var typeid = newNeume.typeid;

        // get note head shapes to change in underlying mei
        var headShapes = $.map(newNeume.components, function(nc) {
            return nc.props.type;
        });

        var data = JSON.stringify({"nids": nids.join(","), "typeid": typeid, "liquescence": modifier, "headShapes": headShapes, "ulx": outbb[0], "uly": outbb[1], "lrx": outbb[2], "lry": outbb[3]});
        // call server neumify function to update MEI
        $.post(gui.apiprefix + "/neumify", {data: data}, function(data) {
            // set id of the new neume with generated ID from the server
            newNeume.id = JSON.parse(data).id;
        })
        .error(function() {
            gui.showAlert("Server failed to neumify selected neumes. Client and server are not synchronized.");
        });

        gui.rendEng.canvas.discardActiveGroup();

        // select the new neume
        // TODO: drawing for compound neumes with prefixes from the search tree
        if (newNeume.typeid != "compound") {
            $(newNeume).trigger("vSelectDrawing");
        }

        gui.rendEng.repaint();
    }
}

/**
 * Handler for ungrouping a set of neumes to punctums on the canvas.
 *
 * @methodOf Toe.View.CheironomicInteraction
 * @param {Event} e Event for pressing the ungroup button
 */
Toe.View.CheironomicInteraction.prototype.handleUngroup = function(e) {
    var gui = e.data.gui;

    var neumes = new Array();

    var selection = gui.rendEng.canvas.getActiveObject();
    if (selection) {
        if (selection.eleRef instanceof Toe.Model.Neume && selection.eleRef.components.length > 1) {
            neumes.push(selection);
        }
    }
    else {
        selection = gui.rendEng.canvas.getActiveGroup();
        if (selection) {
            // group of elements selected
            $.each(selection.getObjects(), function(oInd, o) {
                // only deal with neumes with that have more components than a punctum
                if (o.eleRef instanceof Toe.Model.Neume && o.eleRef.components.length > 1) {
                    neumes.push(o);
                }
            });
        }
    }

    var nids = new Array();
    var bbs = new Array();
    var punctums = new Array();

    // ungroup each selected neume
    $.each(neumes, function(oInd, o) {
        // add to list of neume ids
        nids.push(o.eleRef.id);

        var punctBoxes = new Array();
        var ulx = o.eleRef.zone.ulx;

        // remove the old neume
        o.eleRef.system.removeElementByRef(o.eleRef);
        gui.rendEng.canvas.remove(o);

        $.each(o.eleRef.components, function(ncInd, nc) {
            var newPunct = new Toe.Model.CheironomicNeume();
            newPunct.addComponent(nc);

            var uly = o.eleRef.zone.uly;
            if (o.eleRef.components[ncInd].relativePitch) {
                uly += (-o.eleRef.components[ncInd].relativePitch * gui.punctHeight);
            }

            // set the bounding box hint of the new neume for drawing
            var bb = [ulx+(ncInd*gui.punctWidth), uly, ulx+((ncInd+1)*gui.punctWidth), uly+gui.punctHeight];
            newPunct.setBoundingBox(bb);

            // instantiate neume view and controller
            var nView = new Toe.View.NeumeView(gui.rendEng, gui.page.documentType);
            var nCtrl = new Toe.Ctrl.NeumeController(newPunct, nView);

            // add the punctum to the system and draw it
            o.eleRef.system.addNeume(newPunct);

            // get final bounding box information
            var outbb = gui.getOutputBoundingBox([newPunct.zone.ulx, newPunct.zone.uly, newPunct.zone.lrx, newPunct.zone.lry]);
            punctBoxes.push({"ulx": outbb[0], "uly": outbb[1], "lrx": outbb[2], "lry": outbb[3]});

            punctums.push(newPunct);
        });

        // add to list of neume bounding boxes
        bbs.push(punctBoxes);
    });

    var data = JSON.stringify({"nids": nids.join(","), "bbs": bbs});

    // call server ungroup function to update MEI
    $.post(gui.apiprefix + "/ungroup", {data: data}, function(data) {
        // set ids of the new puncta from the IDs generated from the server
        var nids = JSON.parse(data).nids;
        // flatten array of nested nid arrays (if ungrouping more than one neume)
        nids = $.map(nids, function(n) {
            return n;
        });

        $.each(punctums, function(i, punct) {
            punct.id = nids[i];
        });
    })
    .error(function() {
        gui.showAlert("Server failed to ungroup selected neumes. Client and server are not synchronized.");
    });

    gui.rendEng.canvas.discardActiveObject();
    gui.rendEng.canvas.discardActiveGroup();
    gui.rendEng.repaint();
}

/**************************************************
 *                  INSERT                        *
 **************************************************/
/**
 * Handler for inserting a punctum neume on the canvas, which removes edit GUI widgets
 * and adds insert GUI widgets.
 *
 * @methodOf Toe.View.CheironomicInteraction
 * @param {Event} e Event from pressing the insert button
 */
Toe.View.CheironomicInteraction.prototype.handleInsert = function(e) {
    var gui = e.data.gui;
    var parentDivId = e.data.parentDivId;
    gui.deactivateCanvasObjects();
    gui.hideInfo();
    gui.removeInsertControls();
    gui.removeEditControls();
    gui.unbindEventHandlers();

    // unbind edit event handlers
    $("#btn_delete").unbind("click.edit");
    $("#btn_neumify").unbind("click.edit");
    $("#btn_ungroup").unbind("click.edit");

    // then add insert options
    if ($("#sidebar-insert").length == 0) {
        $(parentDivId).append('

Insert
\n' +
                              '

' +
                              '<button id="rad_punctum" class="btn"> Punctum</button>\n' +
                              '\n
\n
\n');
    }

    // update click handlers
    $("#rad_punctum").unbind("click");
    $("#rad_punctum").bind("click.insert", {gui: gui}, gui.handleInsertPunctum);

    // toggle punctum insert by default
    $("#rad_punctum").trigger('click');
}

/**
 * Handler for inserting a punctum neume on the canvas.
 *
 * @methodOf Toe.View.CheironomicInteraction
 * @param {Event} e Event for clicking on the canvas to insert a punctum
 */
Toe.View.CheironomicInteraction.prototype.handleInsertPunctum = function(e) {
    var gui = e.data.gui;
    gui.unbindEventHandlers();

    // add ornamentation toggles
    if ($("#menu_insertpunctum").length == 0) {
        $("#sidebar-insert").append('

Ornamentation
\n' +
                                    '

\n' +
                                    '<button id="chk_dot" class="btn">• Dot</button>\n' +
                                    '<button id="chk_horizepisema" class="btn"> Episema</button>\n' +
                                    '<button id="chk_vertepisema" class="btn"> Episema</button>\n

');
    }

    // ornamentation toggle flags
    var hasDot = false;
    var hasHorizEpisema = false;
    var hasVertEpisema = false;

    // keep the scope of the punctum drawing insert local
    // to not pollute the global namespace when inserting other
    // musical elements
    var updateFollowPunct = function(initial) {
        var elements = {modify: new Array(), fixed: new Array()};

        var punctPos = null;
        var punctGlyph = gui.rendEng.getGlyph("punctum");
        if (initial) {
            // draw the punctum off the screen, initially
            var punctPos = {left: -50, top: -50};
        }
        else {
            var punctPos = {left: gui.punctDwg.left, top: gui.punctDwg.top};

            if (hasDot) {
                var glyphDot = gui.rendEng.getGlyph("dot");
                var dot = glyphDot.clone().set({left: punctPos.left + gui.punctWidth, top: punctPos.top + (gui.punctHeight/2), opacity: 0.6});
                elements.modify.push(dot);
            }

            /* TODO: deal with episemata
            if (hasHorizEpisema) {
            }

            if (hasVertEpisema) {
            }
            */
        }

        // create clean punctum glyph with no ornamentation
        var punct = punctGlyph.clone().set({left: punctPos.left, top: punctPos.top, opacity: 0.6});
        elements.modify.push(punct);

        // remove old punctum drawing following the pointer
        if (gui.punctDwg) {
            gui.rendEng.canvas.remove(gui.punctDwg);
        }

        // replace with new punctum drawing
        gui.punctDwg = gui.rendEng.draw(elements, {group: true, selectable: false, repaint: true})[0];
    };

    // put the punctum off the screen for now
    updateFollowPunct(true);

    // render transparent punctum at pointer location
    gui.rendEng.canvas.observe('mouse:move', function(e) {
        var pnt = gui.rendEng.canvas.getPointer(e.e);
        gui.punctDwg.left = pnt.x - gui.punctDwg.currentWidth/4;
        gui.punctDwg.top = pnt.y - gui.punctDwg.currentHeight/4;

        gui.rendEng.repaint();
    });

    // deal with punctum insert
    gui.rendEng.canvas.observe('mouse:up', function(e) {
        var coords = {x: gui.punctDwg.left, y: gui.punctDwg.top};
        var sModel = gui.page.getClosestSystem(coords);

        // instantiate a punctum
        var nModel = new Toe.Model.CheironomicNeume();

        // calculate snapped coords
        var snapCoords = sModel.getSystemSnapCoordinates(coords, gui.punctDwg.currentWidth, {y: false});

        // update bounding box with physical position on the page
        var ulx = snapCoords.x - gui.punctDwg.currentWidth/2;
        var uly = snapCoords.y - gui.punctDwg.currentHeight/2;
        var bb = [ulx, uly, ulx + gui.punctDwg.currentWidth, uly + gui.punctDwg.currentHeight];
        nModel.setBoundingBox(bb);

        //  start forming arguments for the server function call
        var args = {};

        // check ornamentation toggles to add to component
        var ornaments = new Array();
        if (hasDot) {
            ornaments.push(new Toe.Model.Ornament("dot", {form: "aug"}));
            args["dotform"] = "aug";
        }

        /* TODO: deal with episemata
        if (hasHorizEpisema) {
        }
        if (hasVertEpisema) {
        }
        */

        var nc = new Toe.Model.CheironomicNeumeComponent({type: "punctum", ornaments: ornaments});
        nModel.addComponent(nc);

        // TODO: remove manually specifying neume type in lieu of trie search
        nModel.typeid = nModel.name = "punctum";

        // instantiate neume view and controller
        var nView = new Toe.View.NeumeView(gui.rendEng, gui.page.documentType);
        var nCtrl = new Toe.Ctrl.NeumeController(nModel, nView);

        // mount neume on the system
        var nInd = sModel.addNeume(nModel);

        // now that final bounding box is calculated from the drawing
        // add the bounding box information to the server function arguments
        var outbb = gui.getOutputBoundingBox([nModel.zone.ulx, nModel.zone.uly, nModel.zone.lrx, nModel.zone.lry]);
        args["ulx"] = outbb[0];
        args["uly"] = outbb[1];
        args["lrx"] = outbb[2];
        args["lry"] = outbb[3];

        // get next element to insert before
        if (nInd + 1 < sModel.elements.length) {
            args["beforeid"] = sModel.elements[nInd+1].id;
        }
        else {
            // insert before the next system break (system)
            var sNextModel = gui.page.getNextSystem(sModel);
            if (sNextModel) {
                args["beforeid"] = sNextModel.id;
            }
        }

        // send insert command to server to change underlying MEI
        $.post(gui.apiprefix + "/insert/neume", args, function(data) {
            nModel.id = JSON.parse(data).id;
        })
        .error(function() {
            gui.showAlert("Server failed to insert neume. Client and server are not synchronized.");
        });
    });

    $("#chk_dot").bind("click.insert", function() {
        // toggle dot
        if (!hasDot) {
            hasDot = true;
        }
        else {
            hasDot = false;
        }

        updateFollowPunct(false);
    });

    /* TODO: insert with episemata
    $("#chk_horizepisema").bind("click.insert", function() {
        if ($(this).hasClass("active")) {
            hasHorizEpisema = true;
        }
        else {
            hasHorizEpisema = false;
        }
    });

    $("#chk_vertepisema").bind("click.insert", function() {
    });
    */
}

/**
 * Helper function to translate the coordinates of the bounding box to incorporate
 * the scale of the page to fit on the fixed canvas size.
 *
 * @methodOf Toe.View.CheironomicInteraction
 * @param {Array} bb Array of bounding box coordinates [ulx, uly, lrx, lry]
 */
Toe.View.CheironomicInteraction.prototype.getOutputBoundingBox = function(bb) {
    gui = this;
    return $.map(bb, function(b) {
        return Math.round(b/gui.page.scale);
    });
}

/**
 * Helper function to set up hotkeys for interacting with the GUI widgets
 * as an alternative to clicking buttons with the mouse.
 *
 * @methodOf Toe.View.CheironomicInteraction
 */
Toe.View.CheironomicInteraction.prototype.bindHotKeys = function() {
    var gui = this;

    // delete hotkey
    Mousetrap.bind(['del', 'backspace'], function() {
        $("#btn_delete").trigger('click.edit', {gui:gui}, gui.handleDelete);
        return false;
    });

    // neumify hotkey
    Mousetrap.bind(['n', 'Ctrl+n', 'Command+n'], function() {
        $("#btn_neumify").trigger('click.edit', {gui:gui}, gui.handleNeumify);
        return false;
    });

    // ungroup hotkey
    Mousetrap.bind(['u', 'Ctrl+u', 'Command+u'], function() {
        $("#btn_ungroup").trigger('click.edit', {gui:gui}, gui.handleUngroup);
        return false;
    });
};

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// GUI Management Methods
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Toe.View.CheironomicInteraction.prototype.insertEditControls = function(aParentDivId) {
    if ($("#sidebar-edit").length == 0) {
        $(aParentDivId).append('

Edit
\n' +
                              '
\n<button id="btn_delete" class="btn"> Delete</button>\n
\n' +
                              '
\n
\n<button id="btn_neumify" class="btn"> Neumify</button>\n' +
                              '<button class="btn dropdown-toggle" data-toggle="dropdown"></button>\n' +
                              '

liquescence augmented
\n' +
                              '
liquescence diminished

\n' +
                              '
<button id="btn_ungroup" class="btn"> Ungroup</button>
\n
\n');
    }
    $('#btn_delete').toggleClass('disabled', true);
    $('#btn_neumify').toggleClass('disabled', true);
    $('#btn_ungroup').toggleClass('disabled', true);
};


text:
1. Attach the CSS file
  *Place JS' css file before website's css file. That way your own CSS file can overwrite the JS' css.
2. Attach jQuery file using scrpit tag
3. Attach the plugin JavaScript file after the jQuery file
4. Structure your HTML
5. Add your own JS using either external file or script tags on your page
6. Select the element on the page using jQuery ($)
7. Call the plugin function

redpajama_set_name: RedPajamaGithub


text:
<tool id="artbio_bam_cleaning" name="ARTbio bam cleaning" version="1.7+galaxy4">
    <description>
        on flags and PCR Duplicates and MD recalibration
    </description>
    <macros>
        <import>macro.xml</import>
    </macros>
    <requirements>
        <requirement type="package" version="1.6=hb116620_7">samtools</requirement>
        <requirement type="package" version="0.8.1=h41abebc_0">sambamba</requirement>
        <requirement type="package" version="1.3.5=py39hba5d119_3">freebayes</requirement>
    </requirements>
    <stdio>
        <exit_code range="1:" level="fatal" description="Error occured" />
    </stdio>
    <command detect_errors="exit_code"><![CDATA[
    @pipefail@
    @set_fasta_index@
    #set input_base = 'input'
    ln -f -s $input_bam.metadata.bam_index input.bam.bai &&
    ln -s $input_bam input.bam &&
    sambamba view -h -t \${GALAXY_SLOTS:-2} --filter="mapping_quality >= 1 and not(unmapped) and not(mate_is_unmapped) and not(duplicate)" -f "bam" ${input_base}".bam"
    | bamleftalign --fasta-reference reference.fa -c --max-iterations "5" -
    | samtools calmd  -C 50 -b -@ \${GALAXY_SLOTS:-2} - reference.fa
    #if $specify_outputs == 'just_calMD':
        > $calmd
    #else if $specify_outputs == 'both':
        | tee $calmd
        | sambamba view -h -t \${GALAXY_SLOTS:-2} --filter='mapping_quality <= 254 and proper_pair' -f 'bam' /dev/stdin > $fullfilter
    #else:
        | sambamba view -h -t \${GALAXY_SLOTS:-2} --filter='mapping_quality <= 254 and proper_pair' -f 'bam' /dev/stdin > $fullfilter
    #end if
    ]]></command>
    <inputs>
        <expand macro="reference_source_conditional" />
        <param name="input_bam" type="data" format="bam" label="BAM or SAM file to process"/>
        <param name="specify_outputs" type="select" label="specify cleaned output(s)"
               display="radio"
               help="The tool first generates MD-recalibrated alignements, then discards
                     aberrant Mapping Quality alignements generated by calMD recalibration.
                     One, the other, or both types of outputs can be retained by the tool">
            <option value="just_calMD">Alignments are only MD-recalibrated (for split or discordant read aware variant callers)</option>
            <option value="calMDandMQ" selected="true">Alignments are MD-recalibrated AND mapping quality > 254 are discarded AND only proper_pair flag is retained (for snv and small indel callers)</option>
            <option value="both">Both types of outputs are retained</option>
        </param>
    </inputs>
    <outputs>
        <data name="calmd" format="bam" label="CalMD filter (for lumpy-smoove)">
            <filter>specify_outputs == 'just_calMD' or specify_outputs == 'both'</filter>
        </data>
        <data name="fullfilter" format="bam" label="Full filtering (for somatic-varscan)">
            <filter>specify_outputs == 'calMDandMQ' or specify_outputs == 'both'</filter>
        </data>
    </outputs>
    <tests>
        <test>
            <param name="input_bam" value="chr22_sample.bam" ftype="bam" />
            <param name="reference_source_selector" value="history" />
            <param name="specify_outputs" value="calMDandMQ" />
            <param name="ref_file" value="chr22.fa" />
            <output name="fullfilter" file="full.bam" ftype="bam" />
        </test>
        <test>
            <param name="input_bam" value="chr22_sample.bam" ftype="bam" />
            <param name="reference_source_selector" value="history" />
            <param name="ref_file" value="chr22.fa" />
            <param name="specify_outputs" value="both" />
            <output name="calmd" file="calmd.bam" ftype="bam" />
            <output name="fullfilter" file="full.bam" ftype="bam" />
        </test>
        <test>
            <param name="input_bam" value="chr22_sample.bam" ftype="bam" />
            <param name="reference_source_selector" value="history" />
            <param name="specify_outputs" value="just_calMD" />
            <param name="ref_file" value="chr22.fa" />
            <output name="calmd" file="calmd.bam" ftype="bam" />
        </test>
    </tests>
    <help>
ARTbio bam cleaning overview
============================

.. class:: infomark

This tool is wrapping several cleaning steps to produce bam files suitable for subsequent
analyses with lumpy-smoove (or other large structural variation callers) or with
somatic-varscan (or other small structural variation callers)

Workflow
=============

.. class:: infomark

The tool is using the following command line for filtering:

::

    sambamba view -h -t 8 --filter='mapping_quality >= 1 and not(unmapped) and not(mate_is_unmapped) and not(duplicate)' -f 'bam' $input_base".bam"
    | bamleftalign --fasta-reference reference.fa -c --max-iterations "5" -
    | samtools calmd  -C 50 -b -@ 4 - reference.fa > $input_base".filt1.dedup.bamleft.calmd.bam" ;
    sambamba view -h -t 8 --filter='mapping_quality <= 254' -f 'bam' -o $input_base".filt1.dedup.bamleft.calmd.filt2.bam" $input_base".filt1.dedup.bamleft.calmd.bam"

.. class:: warningmark

From version **1.7+galaxy0**, this tool assumes that the input bam already has its
optical/PCR duplicate alignments marked appropriately in their flag value. If it is not the
case, it may be necessary to use tool that perform this job, for instance samtools markdup,
or sambamba markdup.

Purpose
--------

This "workflow" tool was generated in order to limit the number of ``python metadata/set.py`` jobs
which occur at each step of standard galaxy workflows. Indeed, these jobs are poorly optimized and may last considerable
amounts of time when datasets are large, at each step, lowering the overall performance of the workflow.

    </help>
    <citations>
        <citation type="doi">10.1371/journal.pone.0168397</citation>
    </citations>
</tool>


text:
[![Build Status](https://travis-ci.org/leoht/Apricot.png?branch=master)](https://travis-ci.org/leoht/Apricot)

Apricot is a micro PHP framework that stands in only one file.

Apricot makes PHP development easy and pleasant, without imposing you any structure or patterns for your application.
You're free to develop as you want, since you can use Apricot components anywhere in your code.

##Basic example

```php
<?php

use Apricot\Apricot as App;

App::when('/', function ()
{
    echo "Hello World!";
});

App::run();

```

##TODO:

- Write more tests
- Write some doc


text:
'use strict';
module.exports = function (str, opts) {
	if (typeof str !== 'string') {
		throw new TypeError('Expected a string');
	}

	return str.trim().replace(/\s{2,}/g, ' ');
};


text:
    <script src="http://connect.soundcloud.com/sdk.js"></script>
    <script src="http://w.soundcloud.com/player/api.js"></script>


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <predicate lemma="trawl">

        <roleset framnet="" id="trawl.01" name="trawl" vncls="35.2">
            <roles>
                <role descr="trawler, agent" f="" n="0">
                    <vnrole vncls="35.2" vntheta="agent"/>
                </role>
                <role descr="location trawled" f="" n="1">
                    <vnrole vncls="35.2" vntheta="location"/>
                </role>
                <note/>
                <role descr="thing trawled for" f="" n="">
                    <vnrole vncls="35.2" vntheta="theme"/>
                </role>
            </roles>
            <example name="from Google" src="web usage" type="">
                <text>Later, they trawled the bottom of the ocean and each passage of the machine brought up large quantities of sponges.</text>
                <note/>
                <arg f="tmp" n="m">Later</arg>
                <arg f="" n="0">they</arg>
                <rel f="">trawled</rel>
                <arg f="" n="1">the bottom of the ocean</arg>
            </example>
            <note>hand-checked by Kev</note>
        </roleset>
        <note>Automatically created based on framefiles: excavate (35.2)</note>
    </predicate>
    <note/>
</frameset>


text:
qc::smtp_send
=============

part of [Docs](../index.md)

Usage
-----
`qc::smtp_send sock string timeout`

Description
-----------
Write data to the smtp server via sock

----------------------------------
*[Qcode Software Limited] [qcode]*

[qcode]: http://www.qcode.co.uk "Qcode Software"


text:
list_of_integers = [11,22,27,34]
lower_bound = 10
upper_bound = 30

def count_between(list_of_integers, lower_bound, upper_bound)
  list_of_integers.count do |x| x.between?(lower_bound, upper_bound)
  end
end


text:
/**
 *
 */
package edu.gatech.mbse.plugins.mdmc.view;

import java.awt.event.ActionEvent;

import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;

import com.nomagic.magicdraw.openapi.uml.ModelElementsManager;
import com.nomagic.magicdraw.openapi.uml.ReadOnlyElementException;
import com.nomagic.magicdraw.ui.dialogs.MDDialogParentProvider;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Constraint;
import com.nomagic.uml2.ext.magicdraw.classes.mdkernel.Class;
import com.nomagic.uml2.ext.magicdraw.compositestructures.mdports.Port;

import edu.gatech.mbse.plugins.mdmc.controller.ModelCenterPlugin;
import edu.gatech.mbse.plugins.mdmc.exceptions.ModelCenterProfileNotLoaded;

/**
 * @author Sebastian
 *
 */
public class CreateScriptAction extends CreateElementAction {

	/**
	 * Constructor
	 *
	 * @param arg0
	 * @param arg1
	 * @param arg2
	 * @param arg3
	 */
	public CreateScriptAction() {
		super("", "Script", null, null);

		// Add an icon
		this.setSmallIcon(new ImageIcon(getClass().getResource("script.gif")));
	}

	/**
	 *
	 */
	public void actionPerformed(ActionEvent e) {
		// Ensure that session is locked
		ModelCenterPlugin.ensureMDSessionIsActive();

		// Try to create a new variable
		Constraint newScript;

		try {
			newScript = ModelCenterPlugin.getMDModelFactoryInstance().createScript("");
		}
		catch(ModelCenterProfileNotLoaded e2) {
			e2.printStackTrace();

			// Don't forget to close the session
			ModelCenterPlugin.closeMDSession();

			// Warn the user if the ModelCenter profile has not yet been loaded
			JOptionPane.showMessageDialog(MDDialogParentProvider.getProvider().getDialogParent(), "Please load ModelCenter profile first", "ModelCenter Plugin", JOptionPane.WARNING_MESSAGE);

			return;
		}

		try {
			// Set the constrained element
			newScript.getConstrainedElement().add(getSelectedElement());

			// Add the newly created data model element to the model
			ModelElementsManager.getInstance().addElement(newScript, getSelectedElement());
		}
		catch(ReadOnlyElementException e1) {
			// TODO: Handle if element is read only
			e1.printStackTrace();
		}

		// Done editing model, close session
		ModelCenterPlugin.closeMDSession();

		// Expand parent node
		expandSelectedNode();

		// Enable user to enter a name for the newly created element
		triggerRenameModeForElement(newScript);
	}

	/**
	 *
	 */
	public void updateState() {

	}

}


text:
{% include jaytch/sidebar/sidebar-init.liquid context="post" %}

    {% if leftCols > 0 %}

        {% include jaytch/sidebar/sidebar-ui.liquid context="left" %}

    {% endif %}

{{ page.title }}

<time datetime="{{ page.date | date_to_xmlschema }}" itemprop="datePublished">{{ page.date | date: "%b %-d, %Y" }}</time>{% if page.author %} • {{ page.author }}{% endif %}

                {{ content }}

    {% if rightCols > 0 %}

        {% include jaytch/sidebar/sidebar-ui.liquid context="right" %}

    {% endif %}


text:
import hashlib

from os import path, urandom
from unidecode import unidecode

from django.template.defaultfilters import slugify
from django.utils import timezone
from django.utils.encoding import force_bytes

from taiga.base.utils.iterators import split_by_n

def get_file_path(instance, filename, base_path):
    basename = path.basename(filename).lower()
    base, ext = path.splitext(basename)
    base = slugify(unidecode(base))[0:100]
    basename = "".join([base, ext])

    hs = hashlib.sha256()
    hs.update(force_bytes(timezone.now().isoformat()))
    hs.update(urandom(1024))

    p1, p2, p3, p4, *p5 = split_by_n(hs.hexdigest(), 1)
    hash_part = path.join(p1, p2, p3, p4, "".join(p5))

    return path.join(base_path, hash_part, basename)


text:
class Api::UsersController < Api::BaseController

  def index
    page = params[:page] || 1
    q = params[:q] || ''
    search = User.search do
      fulltext q
      paginate page: page, per_page: 20
    end.results
    render json: {
        users: search,
        pagination: {
            current_page: search.current_page,
            total_pages: search.total_pages,
            total_entries: search.total_entries
        }
    }
  end

  private

end


text:
package org.schedoscope

import akka.actor.ActorSystem
import org.schedoscope.scheduler.actors.{ SchemaManagerActor, TransformationManagerActor, ViewManagerActor }

/**
 * The Schedoscope object provides accessors for the various components of the schedoscope system.
 * It thus serves as an entry point to my system.
 */
object Schedoscope {

  /**
   * The Schedoscope actor system
   */
  lazy val actorSystem = ActorSystem("schedoscope")

  /**
   * The Schedoscope settings.
   */
  lazy val settings = Settings()

  /**
   * A reference to the Schedoscope transformation manager logger actor
   */
  lazy val transformationManagerActor = actorSystem.actorOf(TransformationManagerActor.props(settings), "transformations")

  /**
   * A reference to the Schedoscope schema manager actor
   */
  lazy val schemaManagerActor = actorSystem.actorOf(SchemaManagerActor.props(settings), "schema")

  /**
   * A reference to the Schedoscope view manager actor
   */
  lazy val viewManagerActor = actorSystem.actorOf(
    ViewManagerActor.props(settings,
      transformationManagerActor,
      schemaManagerActor,
      schemaManagerActor), "views")
}


text:
describe Facts::Macosx::Filesystems do
  describe '#call_the_resolver' do
    subject(:fact) { Facts::Macosx::Filesystems.new }

    let(:value) { 'apfs,autofs,devfs' }

    before do
      allow(Facter::Resolvers::Macosx::Filesystems).to receive(:resolve).with(:macosx_filesystems).and_return(value)
    end

    it 'calls Facter::Resolvers::Macosx::Filesystems' do
      fact.call_the_resolver
      expect(Facter::Resolvers::Macosx::Filesystems).to have_received(:resolve).with(:macosx_filesystems)
    end

    it 'returns filesystems fact' do
      expect(fact.call_the_resolver).to be_an_instance_of(Facter::ResolvedFact).and \
        have_attributes(name: 'filesystems', value: value)
    end
  end
end


text:
package org.wso2.developerstudio.eclipse.artifact.bpel.ui.wizard;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Link;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.wso2.developerstudio.eclipse.artifact.bpel.dialogs.RegistryResourseFileProviderDialog;
import org.wso2.developerstudio.eclipse.capp.core.artifacts.manager.CAppEnvironment;
import org.wso2.developerstudio.eclipse.capp.core.model.RegistryConnection;
import org.wso2.developerstudio.eclipse.general.project.dialogs.NewResourceTemplateDialog;
import org.wso2.developerstudio.eclipse.greg.core.interfaces.IRegistryConnection;
import org.wso2.developerstudio.eclipse.greg.core.interfaces.IRegistryData;
import org.wso2.developerstudio.eclipse.greg.core.interfaces.IRegistryFile;
import org.wso2.developerstudio.eclipse.greg.core.interfaces.IRegistryHandler;

/**
 * A SWT based editor dialog to be used for editing registry key properties.
 */
public class RegistryResourceBrowserDialog extends Dialog {

	/**
	 * Default registry url.
	 */
	private static final String DEFAULT_REGISTRY_URL = "https://localhost:9443/registry";

	/**
	 * Prefix for governance registry paths.
	 */
	private static final String G_REG_PATH_PREFIX = "/_system/governance/";

	/**
	 * Prefix for configuration registry paths.
	 */
	private static final String C_REG_PATH_PREFIX = "/_system/config/";

	private Text rkTextField;
	// private RegistryKeyProperty rkProperty;

	String title;
	String path;
	private java.util.List<NamedEntityDescriptor> localNamedEntities;
	private FormData rkTextFieldLayoutData;
	private Text txtPolicyFile;

	/**
	 * Creates a new {@link RegistryKeyPropertyEditorDialog} instance.
	 *
	 * @param parent
	 *            parent shell.
	 * @param style
	 *            style.
	 * @param property
	 *            {@link RegistryKeyProperty} to be edited.
	 * @param localNamedEntities
	 *            named entities currently defined on the local configuration.
	 * @param txtPolicyFile
	 */
	public RegistryResourceBrowserDialog(Shell parent, int style,
			java.util.List<NamedEntityDescriptor> localNamedEntities, Text txtPolicyFile) {
		super(parent);
		// this.rkProperty = property;
		this.txtPolicyFile = txtPolicyFile;
		this.localNamedEntities = localNamedEntities;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	@Override
	protected void configureShell(Shell newShell) {
		// TODO Auto-generated method stub
		super.configureShell(newShell);
		if (title != null) {
			newShell.setText(title);
		}
	}

	private void hide() {
		changeVisibility(false);
	}

	private void show() {
		changeVisibility(true);
	}

	private void changeVisibility(boolean visible) {
		try {
			this.getShell().setVisible(visible);
		} catch (Exception e) {
			// ignore this
		}
	}

	protected Control createDialogArea(Composite parent) {
		Composite container = (Composite) super.createDialogArea(parent);
		FillLayout fl_container = new FillLayout(SWT.HORIZONTAL);
		fl_container.marginHeight = 5;
		fl_container.marginWidth = 5;
		fl_container.spacing = 10;
		container.setLayout(fl_container);

		Group grpPropertyKey = new Group(container, SWT.None);
		grpPropertyKey.setText("Resource Key");

		FormLayout fl_grpPropertyKey = new FormLayout();
		fl_grpPropertyKey.marginHeight = 10;
		fl_grpPropertyKey.marginWidth = 10;
		grpPropertyKey.setLayout(fl_grpPropertyKey);

		// Registry key text field.
		rkTextField = new Text(grpPropertyKey, SWT.BORDER);
		rkTextField.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				saveConfiguration();
			}
		});
		{
			rkTextFieldLayoutData = new FormData();
			rkTextFieldLayoutData.right = new FormAttachment(100, -8);
			rkTextField.setLayoutData(rkTextFieldLayoutData);
		}

		Link link = new Link(grpPropertyKey, SWT.NONE);
		link.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				String selectedCommand = e.text;
				if (selectedCommand.equals("registry")) {
					openRegistryBrowser();
				} else if (selectedCommand.equals("workspace")) {
					openRegistryResourceProviderDialog();
				}
			}
		});
		rkTextFieldLayoutData.top = new FormAttachment(link, 7);
		rkTextFieldLayoutData.left = new FormAttachment(link, 0, SWT.LEFT);
		FormData fd_link = new FormData();
		fd_link.right = new FormAttachment(100, -4);
		fd_link.left = new FormAttachment(0);
		fd_link.top = new FormAttachment(0, -2);
		fd_link.bottom = new FormAttachment(0, 15);
		link.setLayoutData(fd_link);

		// Fixing TOOLS-2553
		// link.setText("Type the key or specify from registry, workspace or local entries");
		link.setText("Type the key or specify from registry or workspace");

		Link link_1 = new Link(grpPropertyKey, SWT.NONE);
		link_1.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				openNewResourceTemplateDialog();
			}
		});
		FormData fd_link_1 = new FormData();
		fd_link_1.top = new FormAttachment(rkTextField, 6);
		fd_link_1.right = new FormAttachment(rkTextField, 0, SWT.RIGHT);
		link_1.setLayoutData(fd_link_1);
		link_1.setText("Create && point to a new resource...");
		loadConfiguration();
		return container;
	}

	private void loadConfiguration() {
		if (!StringUtils.isBlank(txtPolicyFile.getText())) {
			rkTextField.setText(txtPolicyFile.getText());
		}
	}

	@Override
	protected void okPressed() {
		saveConfiguration();
		super.okPressed();
	}

	private void saveConfiguration() {
		txtPolicyFile.setText(rkTextField.getText());
		path = txtPolicyFile.getText();
		// rkProperty.setKey(rkTextField.getText());
	}

	protected void openNewResourceTemplateDialog() {
		// hide();
		try {
			NewResourceTemplateDialog newResourceTemplateDialog = new NewResourceTemplateDialog(getParentShell(),
					new HashMap<String, List<String>>());
			newResourceTemplateDialog.create();
			newResourceTemplateDialog.getShell().setText("New Resource");
			newResourceTemplateDialog.open();
			if (newResourceTemplateDialog.getReturnCode() == Window.OK) {
				setSelectedPath(newResourceTemplateDialog.getSelectedPath());
			}
		} finally {
			// show();
		}

	}

	private void openRegistryBrowser() {
		// Open registry browser.
		hide();
		try {
			IRegistryConnection[] registryConnections = CAppEnvironment.getRegistryHandler().getRegistryConnections();
			if (registryConnections.length == 0) {
				RegistryConnection registryConnection = new RegistryConnection();
				try {
					registryConnection.setURL(new URL(DEFAULT_REGISTRY_URL));
				} catch (MalformedURLException e) {
					// not gonna happen :D
				}
				registryConnection.setPath("/_system/config");
			}
			IRegistryData selectedPathData = CAppEnvironment.getRegistryHandler().selectRegistryPath(
					registryConnections, "Registry Browser", "Select Registry Resource:",
					IRegistryHandler.SELECTED_REGISTRY_RESOURCE);

			if (selectedPathData != null) {
				// Convert to prefixed format.
				setSelectedPath(selectedPathData.getPath());
			}
		} finally {
			show();
		}
	}

	private void setSelectedPath(String selectedPath) {
		if (selectedPath.startsWith(G_REG_PATH_PREFIX)) {
			selectedPath = String.format("gov:%s", selectedPath.substring(G_REG_PATH_PREFIX.length()));
		} else if (selectedPath.startsWith(C_REG_PATH_PREFIX)) {
			selectedPath = String.format("conf:%s", selectedPath.substring(C_REG_PATH_PREFIX.length()));
		}

		rkTextField.setText(selectedPath);
		if (selectedPath != null && !selectedPath.trim().equals("")) {
			okPressed();
		}
	}

	@SuppressWarnings("unchecked")
	private void openRegistryResourceProviderDialog() {
		hide();
		RegistryResourseFileProviderDialog registryResourceProviderSelector = new RegistryResourseFileProviderDialog(
				getParentShell(), new Class[] { IRegistryFile.class }, new HashMap<String, List<String>>());
		registryResourceProviderSelector.create();
		registryResourceProviderSelector.getShell().setText("Workspace Element Providers");
		registryResourceProviderSelector.open();
		if (registryResourceProviderSelector.getReturnCode() == Window.OK) {
			setSelectedPath(registryResourceProviderSelector.getSelectedPath());
		}
		show();
	}

	/**
	 * Gets the policy key
	 *
	 * @return policy key
	 */
	public String getPolicyKey() {
		return path;
	}
}


text:
var assert = require('assert'),
  val = require('../index');

describe('im.val', function() {

  it('Should set default value if undefined or null is given', function () {
    assert.equal('default', val(undefined, 'default'));
    assert.equal('default', val(null, 'default'));
  });

  it('Should set default value if checker truth test is failed', function () {
    var ok = { test: 'ok' },
      test = val({ test: false }, true, function(value) {
        if (value.test !== 'ok') return false;
        return true;
      });
    assert.equal(true, test);
  });

  it('Should NOT set default value if value is given and valid', function () {
    assert.equal(true, val(true, 'default'));
  });

  it('Should NOT set default value if checker truth test is passed', function () {
    var ok = { test: 'ok' },
      test = val(ok, 'Not Passed', function(value) {
        if (value.test !== 'ok') return false;
        return true;
      });
    assert.equal(ok, test);
  });

  it('Should return notDefined right', function() {
    assert.equal(val.notDefined, val());
    assert.equal(null, val(undefined, null));
    assert.equal(undefined, val(null, undefined));
  })

});


text:
layout: single
title:  "Contributing"
sidebar:
  nav: community
redirect_from: /docs/contributing-to-spinnaker
---

{% include toc %}

## Filing issues

Please file issues through the [Spinnaker GitHub issue tracker](https://github.com/spinnaker/spinnaker/issues).

## How to Become a Contributor

This is normally the place where we'd tell you about Contributor License Agreements and how you need to identify the right one and sign it before you are able to contribute code to Spinnaker.

We'll probably end up doing something like this, but at the moment we're exploring options that might make it easier for most of you to contribute. Please stay tuned...

In the meantime, if you're really excited about contributing and don't want to wait until we have all of this worked out, please reach out to us on [Slack](http://join.spinnaker.io). We love accepting community patches!

For more details about the patch submission process, look at [How to submit a patch](/community/contributing/submitting/).

## How to run Spinnaker locally for development

Running Spinnaker locally on your machine is a great option for testing changes before submitting a pull request.

Follow the [guide to setting up a dev environment](/guides/developer/getting-set-up/) to get up and running.


text:
<div *ngIf="merch" class="merch-display">
  <app-merch-card *ngFor="let item of merch" [merch]="item"></app-merch-card>
</div>


text:
import logging
import os

from django.db.models import Count
from django.core.management import BaseCommand
from django.conf import settings

from emgapi import models as emg_models
from emgena import models as ena_models

class Command(BaseCommand):
    help = "Sync the Studies status with ENA"

    def handle(self, *args, **kwargs):
        logging.info("Starting...")

        offset = 0
        batch_size = 1000
        studies_count = emg_models.Study.objects.count()

        logging.info(f"Total studies on EMG {studies_count}")

        while offset < studies_count:
            emg_studies_batch = list(
                emg_models.Study.objects.all()[offset : offset + batch_size]
            )
            ena_studies_batch = ena_models.Study.objects.using("era").filter(
                study_id__in=[study.secondary_accession for study in emg_studies_batch]
            )
            for emg_study in emg_studies_batch:
                ena_study = next(
                    (
                        el
                        for el in ena_studies_batch
                        if el.study_id == emg_study.secondary_accession
                    ),
                    None,
                )
                if ena_study is None:
                    logging.error(f"{emg_study} not found in ENA.")
                    continue
                if ena_study.study_status is None:
                    logging.error(f"{emg_study} on ENA has no value on the column status.")
                    continue

                emg_study.sync_with_ena_status(ena_study.study_status)
                emg_study.public_release_date = ena_study.hold_date

            emg_models.Study.objects.bulk_update(
                emg_studies_batch,
                [
                    "is_private",
                    "is_suppressed",
                    "suppression_reason",
                    "suppressed_at",
                    "public_release_date",
                ],
            )
            logging.info(f"Batch {round(studies_count / batch_size)} processed.")
            offset += batch_size

        logging.info("Completed")


text:
"""Tests for Windows Volume Shadow Copy flow."""

import stat

from absl import app

from grr_response_core import config
from grr_response_core.lib.rdfvalues import client_fs as rdf_client_fs
from grr_response_core.lib.rdfvalues import paths as rdf_paths
from grr_response_core.lib.rdfvalues import protodict as rdf_protodict
from grr_response_server import data_store
from grr_response_server.flows.general import windows_vsc
from grr.test_lib import action_mocks
from grr.test_lib import flow_test_lib
from grr.test_lib import test_lib

class TestClient(action_mocks.ActionMock):
  """A test client mock."""

  _RESPONSES = {
      "Caption": "None",
      "ClientAccessible": "True",
      "Count": "1",
      "Description": "None",
      "DeviceObject": r"\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy3",
      "Differential": "True",
      "ExposedLocally": "False",
      "ExposedName": "None",
      "ExposedPath": "None",
      "ExposedRemotely": "False",
      "HardwareAssisted": "False",
      "ID": "{4F1D1E03-C7C1-4023-8CE9-5FF4D16E133D}",
      "Imported": "False",
      "InstallDate": "20130430022911.144000-420",
      "Name": "None",
      "NoAutoRelease": "True",
      "NotSurfaced": "False",
      "NoWriters": "False",
      "OriginatingMachine": "mic-PC",
      "Persistent": "True",
      "Plex": "False",
      "ProviderID": "{B5946137-7B9F-4925-AF80-51ABD60B20D5}",
      "ServiceMachine": "mic-PC",
      "SetID": "{9419738B-113C-4ACC-BD64-DADDD3B88381}",
      "State": "12",
      "Status": "None",
      "Transportable": "False",
      "VolumeName": r"\\?\Volume{f2180d84-7eb0-11e1-bed0-806e6f6e6963}",
  }

  def WmiQuery(self, query):
    expected_query = "SELECT * FROM Win32_ShadowCopy"
    if query.query != expected_query:
      raise RuntimeError("Received unexpected query.")

    return [rdf_protodict.Dict(**self._RESPONSES)]

  def ListDirectory(self, list_directory_request):
    """A mock list directory."""
    pathspec = list_directory_request.pathspec
    if not pathspec:
      raise RuntimeError("Missing pathspec.")

    if (pathspec.path != r"\\.\HarddiskVolumeShadowCopy3" or
        pathspec.pathtype != rdf_paths.PathSpec.PathType.OS):
      raise RuntimeError("Invalid pathspec.")

    if not pathspec.nested_path:
      raise RuntimeError("Missing nested pathspec.")

    if (pathspec.nested_path.path != "/" or
        pathspec.nested_path.pathtype not in (
            rdf_paths.PathSpec.PathType.TSK, rdf_paths.PathSpec.PathType.NTFS)):
      raise RuntimeError("Invalid nested pathspec.")

    result = []
    for i in range(10):
      mock_pathspec = pathspec.Copy()
      mock_pathspec.last.path = "/file %s" % i
      result.append(
          rdf_client_fs.StatEntry(pathspec=mock_pathspec, st_mode=stat.S_IFDIR))

    return result

class TestListVolumeShadowCopies(flow_test_lib.FlowTestsBaseclass):
  """Test the list Volume Shadow Copies flow."""

  def testListVolumeShadowCopies(self):
    """Test the list Volume Shadow Copies flow."""
    client_id = self.SetupClient(0)
    flow_name = windows_vsc.ListVolumeShadowCopies.__name__

    # Run the flow in the simulated way
    flow_test_lib.TestFlowHelper(
        flow_name,
        TestClient(),
        creator=self.test_username,
        client_id=client_id)

    children = data_store.REL_DB.ListChildPathInfos(
        client_id, config.CONFIG["Server.raw_filesystem_access_pathtype"],
        ["\\\\.\\HarddiskVolumeShadowCopy3"])

    self.assertLen(children, 10)
    self.assertCountEqual([x.components[-1] for x in children],
                          ["file %s" % i for i in range(10)])

def main(argv):
  # Run the full test suite
  test_lib.main(argv)

if __name__ == "__main__":
  app.run(main)


text:
package com.woorea.openstack.nova.model;

import java.io.Serializable;
import java.util.Iterator;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonProperty;

public class SimpleTenantUsages implements Iterable<SimpleTenantUsage>, Serializable {

	@JsonProperty("tenant_usages")
	private List<SimpleTenantUsage> list;

	/**
	 * @return the list
	 */
	public List<SimpleTenantUsage> getList() {
		return list;
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "SimpleTenantUsage [list=" + list + "]";
	}

	@Override
	public Iterator<SimpleTenantUsage> iterator() {
		return list.iterator();
	}

}


text:
package com.github.rapid.security.admin.mapper;

import com.github.rapid.security.admin.entity.User;
import org.apache.ibatis.annotations.Param;
import tk.mybatis.mapper.common.Mapper;

import java.util.List;
/**
 *
 * @author sun-abel
 * @create 2017-10-23 下午6:38
 **/
public interface UserMapper extends Mapper<User> {
    public List<User> selectMemberByGroupId(@Param("groupId") int groupId);
    public List<User> selectLeaderByGroupId(@Param("groupId") int groupId);
}


text:
import mock
from django.contrib.auth.models import AnonymousUser
from ginger.forms import GingerForm
import json
from datetime import date, time, datetime
from django import test, forms
from django.core.paginator import Paginator

from ginger import serializer, exceptions, views, forms as jforms
from django.test.utils import override_settings
from django.core.exceptions import PermissionDenied
from ginger.exceptions import PermissionRequired, ValidationFailure

class DummyClass(object):
    name = "hello"

class TestSerializers(test.SimpleTestCase):

    def test_datetime(self):
        now = datetime.now()
        value = serializer.encode({'now': now})
        self.assertTrue(value)

    def test_date(self):
        now = date.today()
        value = serializer.encode({'now': now})
        self.assertTrue(value)

    def test_time(self):
        now = time()
        value = serializer.encode({'now': now})
        self.assertTrue(value)

    def test_dummy_class(self):
        obj = DummyClass()
        self.assertRaises(TypeError, lambda : serializer.encode(obj))
        value = serializer.encode(obj, serializers={DummyClass: lambda o: o.name})
        self.assertEqual(value, '"hello"', value)

    def test_page(self):
        total = 200
        object_list = list(range(total))
        num = 3
        pg = Paginator(object_list, per_page=10).page(num)
        result = json.loads(serializer.encode(pg))
        self.assertEqual(result['total'], total)
        self.assertEqual(result['per_page'], 10)
        self.assertEqual(result['start_index'], 21)
        self.assertEqual(result['end_index'], 30)
        self.assertEqual(result['index'], num)

class ValidationForm(GingerForm):
    name = forms.CharField(max_length=100)
    age = forms.IntegerField(min_value=0)

class TestExceptions(test.SimpleTestCase):

    def test_error(self):
        msg = "Some random message"
        status = 200
        error = exceptions.GingerHttpError(msg)
        error.status_code = status
        data = error.to_json()
        self.assertEqual(error.description, msg)
        self.assertEqual(data['message'], msg)
        self.assertEqual(data['type'], 'GingerHttpError')

    def test_notfound(self):
        errcls = exceptions.NotFound
        self.assertEqual(errcls.status_code, 404)
        self.assertEqual(errcls().to_json()['type'], 'NotFound')

    def test_methodnotfound(self):
        errcls = exceptions.MethodNotFound
        self.assertEqual(errcls.status_code, 405)
        self.assertEqual(errcls().to_json()['type'], 'MethodNotFound')

    def test_permissionrequired(self):
        errcls = exceptions.PermissionRequired
        self.assertEqual(errcls.status_code, 401)
        self.assertEqual(errcls().to_json()['type'], 'PermissionRequired')

    def test_loginrequired(self):
        errcls = exceptions.LoginRequired
        self.assertEqual(errcls.status_code, 401)
        self.assertEqual(errcls().to_json()['type'], 'LoginRequired')

    def test_validationfailure(self):
        self.assertEqual(exceptions.ValidationFailure.status_code, 422)
        name = "asd"*300
        age = -1
        msg = "Failed"
        form = ValidationForm(data={'name': name, 'age': age})
        form.failure_message = msg
        self.assertFalse(form.is_valid())
        data = exceptions.ValidationFailure(form).to_json()
        self.assertEqual(data['message'], msg, data)
        self.assertIn('name', data['data'])
        self.assertIn('age', data['data'])

class TestJSONView(test.SimpleTestCase):

    def create_view(self, **kwargs):
        cls = type("anything", (views.GingerJSONView,) , kwargs)
        return cls.as_view()

    def create_request(self, method, payload):
        factory = test.RequestFactory()
        kwargs = {}
        if payload is not None:
            content = json.dumps(payload)
            kwargs['content_type'] = 'application/json'
            kwargs['data'] = content
        request = getattr(factory, method)("/", **kwargs)
        request.user = AnonymousUser()
        return request

    def get_response(self, method, payload, **view_kwargs):
        view = self.create_view(**view_kwargs)
        req = self.create_request(method, payload)
        response = view(req)
        response.json = json.loads(response.content)
        return response

    def test_max_content_size(self):
        """
        Size of request cannot be larger than the specified MAX_CONTENT_SIZE attribute
        """
        payload = {'value': '****'*(20*1024)}
        resp = self.get_response('post', payload, post=lambda _, **kwargs: {'kwargs': kwargs})
        self.assertEqual(resp.status_code, 400)
        self.assertEqual(resp.json['type'], 'BadRequest')

    def test_bad_request(self):
        """
        Content of the body should be valid json
        """
        factory = test.RequestFactory()
        req = factory.post("/", content_type="application/json", data="asdasdasdasdasdasdasd")
        req.user = None
        view = self.create_view(post=lambda _, **kwargs: {'kwargs': kwargs})
        resp = view(req)
        result = json.loads(resp.content)
        self.assertEqual(resp.status_code, 400)
        self.assertEqual(result['type'], 'BadRequest')

    def test_missing_method(self):
        payload = {}
        resp = self.get_response('post', payload)
        self.assertEqual(resp.status_code, 405)
        self.assertEqual(resp.json['type'], 'MethodNotFound')

    def test_result(self):
        payload = {'name': 'Zail Singh'}
        resp = self.get_response('post', payload, post=lambda _, **kwargs: {'kwargs': kwargs})
        self.assertEqual(resp.json, {'kwargs': payload})

    def test_empty_request_body(self):
        payload = {'name': 'Zail Singh'}
        resp = self.get_response('post', {}, post=lambda _: payload)
        self.assertEqual(resp.json, payload)

    def test_get_request(self):
        payload = {'name': 'Zail Singh'}
        factory = test.RequestFactory()
        req = factory.get("/", data={}, content_type='application/json')
        req.user = AnonymousUser()
        view = self.create_view(get=lambda _: payload)
        resp = view(req)
        resp.json = json.loads(resp.content)
        self.assertEqual(resp.json, payload)

    def test_internal_error(self):
        payload = {'name': 'Zail Singh'}
        def func(_, **kwargs):
            raise ValueError("Something didn't go right !")
        resp = self.get_response('post', payload, post=func)
        self.assertEqual(resp.status_code, 500)
        self.assertIn('message', resp.json)

    @override_settings(DEBUG=True)
    def test_error_with_debug(self):
        payload = {'name': 'Zail Singh'}
        msg = "Something didn't go right !"
        def func(_, **kwargs):
            raise ValueError(msg)
        resp = self.get_response('post', payload, post=func)
        self.assertEqual(resp.status_code, 500)
        self.assertEqual(resp.json['type'], 'ValueError')
        self.assertEqual(resp.json['message'], msg)
        self.assertIsNotNone(resp.json['traceback'])

    def test_permission_denied(self):
        payload = {'name': 'Zail Singh'}
        def func(_, **kwargs):
            raise PermissionDenied
        resp = self.get_response('post', payload, post=func)
        self.assertEqual(resp.status_code, 403)
        self.assertEqual(resp.json['type'], 'PermissionDenied')

    def test_json_error(self):
        payload = {'name': 'Zail Singh'}
        def func(_, **kwargs):
            raise PermissionRequired
        resp = self.get_response('post', payload, post=func)
        self.assertEqual(resp.status_code, 401)
        self.assertEqual(resp.json['type'], 'PermissionRequired')

class DummyContextMixin(jforms.GingerFormMixin):

    called = False

    def process_context(self, context):
        self.called = True
        return context

class TestGingerForm(test.SimpleTestCase):

    def test_constructor(self):
        values = dict(name="Zail", age=81)
        form_obj = DummyContextMixin(**values)
        self.assertTrue(form_obj.called)
        context = form_obj.context
        self.assertEqual(context, values)

    def test_constructor_instance(self):
        values = dict(instance=100)
        form_obj = jforms.GingerFormMixin(**values)
        context = form_obj.context
        self.assertTrue(context)
        self.assertEqual(context['instance'], 100)

    def test_run_without_context(self):
        class MockForm(jforms.GingerForm):
            age = forms.IntegerField(max_value=38, min_value=18)

            def execute(self, name):
                age = self.cleaned_data['age']
                return {'age': age, 'name': name}

        form = MockForm(data={'age': 20})
        self.assertRaises(TypeError, form.run)

    def test_valid_run(self):
        template = "%(name)s has age = %(age)d"

        class MockForm(jforms.GingerForm):
            age = forms.IntegerField(max_value=38, min_value=18)

            def execute(self, name):
                age = self.cleaned_data['age']
                return template%{'age': age, 'name': name}

        form = MockForm(data={'age': 20}, name='Zail')
        result = form.run()
        self.assertEqual(result, template%dict(age=20, name="Zail"))

    def test_invalid_run(self):
        template = "%(name)s has age = %(age)d"

        class MockForm(jforms.GingerForm):
            age = forms.IntegerField(max_value=38, min_value=18)

            def execute(self, name):
                age = self.cleaned_data['age']
                return template%{'age': age, 'name': name}

        form = MockForm(data={'age': 200}, name='Zail')
        self.assertRaises(ValidationFailure, form.run)
        self.assertIn('age',form.errors)

    def test_add_error(self):
        msg = "I didn't like this name"
        name = "Zail"

        class MockForm(jforms.GingerForm):
            name = forms.CharField(max_length=20)

        form = MockForm(data={'name': name})
        form.is_valid()
        self.assertEqual(name, form.cleaned_data['name'])
        self.assertFalse(form.errors)
        form.add_error("name", msg)
        errors = ValidationFailure(form).to_json()
        self.assertEqual(msg, errors['data']['name'][0]['message'], errors)
        self.assertNotIn('name', form.cleaned_data)

    def test_invalid_with_add_error(self):
        template = "%(name)s has age = %(age)d"

        class MockForm(jforms.GingerForm):
            age = forms.IntegerField(max_value=38, min_value=18)

            def execute(self, name):
                age = self.cleaned_data['age']
                self.add_error('age', "I don't like 20years")
                return template%{'age': age, 'name': name}

        form = MockForm(data={'age': 20}, name='Zail')
        self.assertRaises(ValidationFailure, form.run)
        self.assertIn('age',form.errors)

class TestSearchForm(test.TestCase):
    pass


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Blank_Receipt
{
    public class Receipt
    {
        public static void Main()
        {
            ReceiptHeader();
            ReceiptBody();
            ReceiptFooter();
        }

        public static void ReceiptHeader()
        {
            Console.WriteLine("CASH RECEIPT");
            Console.WriteLine("------------------------------");
        }

        public static void ReceiptBody()
        {
            Console.WriteLine("Charged to____________________");
            Console.WriteLine("Received by___________________");
        }
        public static void ReceiptFooter()
        {
            Console.WriteLine("------------------------------");
            Console.WriteLine("© SoftUni");
        }
    }
}


text:
int TestEnvironmentMergeEnvironmentStrings(int argc, char* argv[])
{
#ifndef _WIN32
	TCHAR* p;
	size_t length;
	LPTCH lpszEnvironmentBlock;
	LPTCH lpsz2Merge = "SHELL=123\0test=1\0test1=2\0DISPLAY=:77\0\0";
	LPTCH lpszMergedEnvironmentBlock;

	WINPR_UNUSED(argc);
	WINPR_UNUSED(argv);

	lpszEnvironmentBlock = GetEnvironmentStrings();
	lpszMergedEnvironmentBlock = MergeEnvironmentStrings(lpszEnvironmentBlock, lpsz2Merge);
	p = (TCHAR*)lpszMergedEnvironmentBlock;

	while (p[0] && p[1])
	{
		printf("%s\n", p);
		length = strlen(p);
		p += (length + 1);
	}

	FreeEnvironmentStrings(lpszMergedEnvironmentBlock);
	FreeEnvironmentStrings(lpszEnvironmentBlock);
#endif
	return 0;
}


text:
define(function( require, exports, module ){

var backbone = require('backbone');

var Client = backbone.Model.extend({

    defaults: {
        id: null,
        label: null,
    },
});

exports.Client = Client;

});


text:
extern "C" {
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
#include <tolua++.h>
}

class Date { //tolua_export
    public:

        static int msectime(lua_State *L);//tolua_export

        static int gettimeofday(lua_State *L);//tolua_export

        static int issameday(lua_State *L);//tolua_export

        static int issamemonth(lua_State *L);//tolua_export

        static int issameweek(lua_State *L);//tolua_export

        static int strftime(lua_State *L);//tolua_export

        static int time(lua_State *L);//tolua_export
};//tolua_export

#endif


text:
<?php

namespace PhpSsrs\ReportingService2010;

class CredentialRetrievalEnum
{
  const __default = 'Prompt';
  const Prompt = 'Prompt';
  const Store = 'Store';
  const Integrated = 'Integrated';
  const None = 'None';

}


text:
"""Code to provide a hook for staging.

Some App Engine runtimes require an additional staging step before deployment
(e.g. when deploying compiled artifacts, or vendoring code that normally lives
outside of the app directory). This module contains (1) a registry mapping
runtime/environment combinations to staging commands, and (2) code to run said
commands.

The interface is defined as follows:

- A staging command is an executable (binary or script) that takes two
  positional parameters: the path of the `<service>.yaml` in the directory
  containing the unstaged application code, and the path of an empty directory
  in which to stage the application code.
- On success, the STDOUT and STDERR of the staging command are logged at the
  INFO level. On failure, a StagingCommandFailedError is raised containing the
  STDOUT and STDERR of the staging command (which are surfaced to the user as an
  ERROR message).
"""
import contextlib
import cStringIO
import os

from googlecloudsdk.api_lib.app import util
from googlecloudsdk.core import config
from googlecloudsdk.core import exceptions
from googlecloudsdk.core import execution_utils
from googlecloudsdk.core import log
from googlecloudsdk.core.updater import update_manager
from googlecloudsdk.core.util import files
from googlecloudsdk.core.util import platforms

class NoSdkRootError(exceptions.Error):

  def __init__(self):
    super(NoSdkRootError, self).__init__(
        'No SDK root could be found. Please check your installation.')

class StagingCommandFailedError(exceptions.Error):

  def __init__(self, args, return_code, output_message):
    super(StagingCommandFailedError, self).__init__(
        'Staging command [{0}] failed with return code [{1}].\n\n{2}'.format(
            ' '.join(args), return_code, output_message))

class _Command(object):
  """Represents a cross-platform command.

  Paths are relative to the Cloud SDK Root directory.

  Attributes:
    nix_path: str, the path to the executable on Linux and OS X
    windows_path: str, the path to the executable on Windows
    component: str or None, the name of the Cloud SDK component which contains
      the executable
  """

  def __init__(self, nix_path, windows_path, component=None):
    self.nix_path = nix_path
    self.windows_path = windows_path
    self.component = component

  @property
  def name(self):
    if platforms.OperatingSystem.Current() is platforms.OperatingSystem.WINDOWS:
      return self.windows_path
    else:
      return self.nix_path

  def GetPath(self):
    """Returns the path to the command.

    Returns:
      str, the path to the command

    Raises:
       NoSdkRootError: if no Cloud SDK root could be found (and therefore the
       command is not installed).
    """
    sdk_root = config.Paths().sdk_root
    if not sdk_root:
      raise NoSdkRootError()
    return os.path.join(sdk_root, self.name)

  def EnsureInstalled(self):
    if self.component is None:
      return
    msg = ('The component [{component}] is required for staging this '
           'application.').format(component=self.component)
    update_manager.UpdateManager.EnsureInstalledAndRestart([self.component],
                                                           msg=msg)

# Path to the go-app-stager binary
_GO_BIN_DIR = os.path.join('platform', 'google_appengine', 'goroot', 'bin')

# STAGING_REGISTRY is a map of (runtime, app-engine-environment) to executable
# path relative to Cloud SDK Root; it should look something like the following:
#
#     from googlecloudsdk.api_lib.app import util
#     STAGING_REGISTRY = {
#       ('intercal', util.Environment.FLEX):
#           _Command(
#               os.path.join('command_dir', 'stage-intercal-flex.sh'),
#               os.path.join('command_dir', 'stage-intercal-flex.exe'),
#               component='app-engine-intercal'),
#       ('x86-asm', util.Environment.STANDARD):
#           _Command(
#               os.path.join('command_dir', 'stage-x86-asm-standard'),
#               os.path.join('command_dir', 'stage-x86-asm-standard.exe'),
#               component='app-engine-intercal'),
#     }
_STAGING_REGISTRY = {}

# _STAGING_REGISTRY_BETA extends _STAGING_REGISTRY, overriding entries if the
# same key is used.
_STAGING_REGISTRY_BETA = {
    ('go', util.Environment.STANDARD):
        _Command(
            os.path.join(_GO_BIN_DIR, 'go-app-stager'),
            os.path.join(_GO_BIN_DIR, 'go-app-stager.exe'),
            component='app-engine-go'),
    ('go', util.Environment.MANAGED_VMS):
        _Command(
            os.path.join(_GO_BIN_DIR, 'go-app-stager'),
            os.path.join(_GO_BIN_DIR, 'go-app-stager.exe'),
            component='app-engine-go'),
    ('go', util.Environment.FLEX):
        _Command(
            os.path.join(_GO_BIN_DIR, 'go-app-stager'),
            os.path.join(_GO_BIN_DIR, 'go-app-stager.exe'),
            component='app-engine-go'),
}

_STAGING_COMMAND_OUTPUT_TEMPLATE = """\
------------------------------------ STDOUT ------------------------------------
{out}\
------------------------------------ STDERR ------------------------------------
{err}\
--------------------------------------------------------------------------------
"""

@contextlib.contextmanager
def _StageUsingGivenCommand(command_path, service_yaml):
  """Invokes a staging command with a given <service>.yaml and temp dir.

  This is a context manager because the temporary staging directory should
  always be deleted, independent of potential errors.

  Args:
    command_path: str, path to the staging command
    service_yaml: str, path to the unstaged <service>.yaml

  Yields:
    str, the path to the staged directory.

  Raises:
    StagingCommandFailedError: if the staging command process exited non-zero.
  """
  with files.TemporaryDirectory() as temp_directory:
    args = [command_path, service_yaml, temp_directory]
    log.info('Executing staging command: [{0}]\n\n'.format(' '.join(args)))
    out = cStringIO.StringIO()
    err = cStringIO.StringIO()
    return_code = execution_utils.Exec(args, no_exit=True, out_func=out.write,
                                       err_func=err.write)
    message = _STAGING_COMMAND_OUTPUT_TEMPLATE.format(out=out.getvalue(),
                                                      err=err.getvalue())
    log.info(message)
    if return_code:
      raise StagingCommandFailedError(args, return_code, message)
    yield temp_directory

class Stager(object):

  def __init__(self, registry):
    self.registry = registry

  @contextlib.contextmanager
  def Stage(self, service_yaml, runtime, environment):
    """Stage the given command.

    This method is a context manager that

    >>> with stager.Stage('python', util.Environment.STANDARD):
    ...   pass  # perform deployment steps

    Args:
      service_yaml: str, path to the unstaged <service>.yaml
      runtime: str, the name of the runtime for the application to stage
      environment: api_lib.app.util.Environment, the environment for the
          application to stage

    Yields:
      str, the path to the staged directory or None if no corresponding staging
          command was found.

    Raises:
      NoSdkRootError: if no Cloud SDK installation root could be found.
      StagingCommandFailedError: if the staging command process exited non-zero.
    """
    command = self.registry.get((runtime, environment))

    if not command:
      # Many runtimes do not require a staging step; this isn't a problem.
      log.debug(('No staging command found for runtime [%s] and environment '
                 '[%s].'), runtime, environment.name)
      yield None
      return

    command.EnsureInstalled()

    command_path = command.GetPath()
    with _StageUsingGivenCommand(command_path, service_yaml) as app_dir:
      yield app_dir

def GetStager():
  """Get the default stager."""
  return Stager(_STAGING_REGISTRY)

def GetBetaStager():
  """Get the beta stager, used for `gcloud beta *` commands."""
  registry = _STAGING_REGISTRY.copy()
  registry.update(_STAGING_REGISTRY_BETA)
  return Stager(registry)

def GetNoopStager():
  """Get a stager with an empty registry."""
  return Stager({})


text:
/******************************************************************************/
#ifdef JEMALLOC_H_TYPES

typedef enum {
	dss_prec_disabled  = 0,
	dss_prec_primary   = 1,
	dss_prec_secondary = 2,

	dss_prec_limit     = 3
} dss_prec_t;
#define	DSS_PREC_DEFAULT	dss_prec_secondary
#define	DSS_DEFAULT		"secondary"

#endif /* JEMALLOC_H_TYPES */
/******************************************************************************/
#ifdef JEMALLOC_H_STRUCTS

extern const char *dss_prec_names[];

#endif /* JEMALLOC_H_STRUCTS */
/******************************************************************************/
#ifdef JEMALLOC_H_EXTERNS

dss_prec_t	chunk_dss_prec_get(void);
bool	chunk_dss_prec_set(dss_prec_t dss_prec);
void	*chunk_alloc_dss(arena_t *arena, void *new_addr, size_t size,
    size_t alignment, bool *zero);
bool	chunk_in_dss(void *chunk);
bool	chunk_dss_boot(void);
void	chunk_dss_prefork(void);
void	chunk_dss_postfork_parent(void);
void	chunk_dss_postfork_child(void);

#endif /* JEMALLOC_H_EXTERNS */
/******************************************************************************/
#ifdef JEMALLOC_H_INLINES

#endif /* JEMALLOC_H_INLINES */
/******************************************************************************/


text:
package com.elmakers.mine.bukkit.utility.platform.v1_14.entity;

import java.util.Arrays;

import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Villager;

import com.elmakers.mine.bukkit.api.magic.MageController;
import com.elmakers.mine.bukkit.entity.EntityExtraData;
import com.elmakers.mine.bukkit.utility.ConfigUtils;
import com.elmakers.mine.bukkit.utility.random.RandomUtils;

public class EntityVillagerData extends EntityExtraData {
    protected Villager.Profession profession;
    protected Villager.Type type;
    protected Integer level;
    protected Integer experience;
    protected boolean randomProfession;

    public EntityVillagerData(ConfigurationSection parameters, MageController controller) {
        String professionKey = parameters.getString("villager_profession");
        if (professionKey != null && !professionKey.isEmpty()) {
            professionKey = professionKey.toUpperCase();
            if (professionKey.startsWith("RAND")) {
                randomProfession = true;
            } else {
                try {
                    profession = Villager.Profession.valueOf(professionKey);
                } catch (Exception ex) {
                    controller.getLogger().warning("Invalid villager_profession: " + professionKey);
                }
            }
        }
        String typeKey = parameters.getString("villager_type");
        if (typeKey != null && !typeKey.isEmpty()) {
            typeKey = typeKey.toUpperCase();
            try {
                type = Villager.Type.valueOf(typeKey);
            } catch (Exception ex) {
                controller.getLogger().warning("Invalid villager_type: " + typeKey);
            }
        }
        level = ConfigUtils.getOptionalInteger(parameters, "villager_level");
        experience = ConfigUtils.getOptionalInteger(parameters, "villager_experience");
    }

    public EntityVillagerData(Entity entity) {
        if (!(entity instanceof Villager)) return;
        Villager villager = (Villager)entity;
        profession = villager.getProfession();
        level = villager.getVillagerLevel();
        experience = villager.getVillagerExperience();
        type = villager.getVillagerType();
        randomProfession = false;
    }

    @Override
    public void apply(Entity entity) {
        if (!(entity instanceof Villager)) return;
        Villager villager = (Villager) entity;
        if (randomProfession) {
            Villager.Profession profession = RandomUtils.getRandom(Arrays.asList(Villager.Profession.values()), 1);
            villager.setProfession(profession);
        } else if (profession != null) {
            villager.setProfession(profession);
        }
        if (level != null) {
            villager.setVillagerLevel(level);
        }
        if (experience != null) {
            villager.setVillagerExperience(experience);
        }
        if (type != null) {
            villager.setVillagerType(type);
        }
    }

    @Override
    public boolean cycle(Entity entity) {
        if (!canCycle(entity)) {
            return false;
        }

        Villager villager = (Villager)entity;
        Villager.Profession profession = villager.getProfession();
        Villager.Profession[] professionValues = Villager.Profession.values();
        int villagerOrdinal = (profession.ordinal() + 1) % professionValues.length;
        profession = professionValues[villagerOrdinal];
        villager.setProfession(profession);
        return true;
    }

    @Override
    public boolean canCycle(Entity entity) {
        return entity instanceof Villager;
    }
}


text:
<?php

namespace OneMoreThing\CommonMark\Sanitize\Nodes;

use League\CommonMark\Inline\Element\HtmlInline;

class CdataSection extends HtmlInline
{
}


text:
package org.odlabs.wiquery.core.options;

import org.apache.wicket.Component;
import org.apache.wicket.model.IComponentAssignedModel;
import org.apache.wicket.model.IModel;

/**
 * $Id: $
 *

 * Wraps a {@link Boolean} to be generated as a JavaScript string.
 *

 * Example:
 *

 * The {@link Boolean} true should be rendered as true
 *

 *

 *
 * @author Lionel Armanet
 * @author Ernesto Reinaldo Barreiro
 * @since 0.5
 */
public class BooleanOption extends AbstractOption<Boolean>
{
	private static final long serialVersionUID = -5938430089917100476L;

	/**
	 * Builds a new instance of {@link BooleanOption}.
	 *
	 * @param value
	 *            the wrapped {@link Boolean}
	 */
	public BooleanOption(Boolean value)
	{
		super(value);
	}

	/**
	 * Builds a new instance of {@link BooleanOption}.
	 *
	 * @param value
	 *            the wrapped {@link String}
	 */
	public BooleanOption(IModel<Boolean> value)
	{
		super(value);
	}

	@Override
	public String toString()
	{
		Boolean value = getValue();
		return value != null ? Boolean.toString(value) : null;
	}

	public IModelOption<Boolean> wrapOnAssignment(Component component)
	{
		if (getModel() instanceof IComponentAssignedModel< ? >)
			return new BooleanOption(
				((IComponentAssignedModel<Boolean>) getModel()).wrapOnAssignment(component));
		return this;
	}
}