<commit_before>/**
 * Created by Hendrik Strobelt (hendrik.strobelt.com) on 1/28/15.
 */

//TODO: DO IT ! :) Look at agevis.js for a useful structure

/**
 * Created by Hendrik Strobelt (hendrik.strobelt.com) on 1/28/15.
 */

/*
 *
 * ======================================================
 * We follow the vis template of init - wrangle - update
 * ======================================================
 *
 * */

/**
 * AgeVis object for HW3 of CS171
 * @param _parentElement -- the HTML or SVG element (D3 node) to which to attach the vis
 * @param _data -- the data array
 * @param _metaData -- the meta-data / data description object
 * @constructor
 */
PrioVis = function(_parentElement, _data, _metaData){
    this.parentElement = _parentElement;
    this.data = _data;
    this.metaData = _metaData;
    this.displayData = [];

    // TODO: define all constants here
    this.margin = {top: 20, right: 0, bottom: 30, left: 70},
    this.width = getInnerWidth(this.parentElement) - this.margin.left - this.margin.right,
    this.height = 400 - this.margin.top - this.margin.bottom;

    this.initVis();

}

/**
 * Method that sets up the SVG and the variables
 */
PrioVis.prototype.initVis = function(){

    var that = this; // read about the this

    //TODO: construct or select SVG
    //TODO: create axis and scales

    // constructs SVG layout
    this.svg = this.parentElement.append("svg")
        .attr("width", this.width + this.margin.left + this.margin.right)
        .attr("height", this.height + this.margin.top + this.margin.bottom)
        .attr("class", "lightcoral")
      .append("g")
        .attr("transform", "translate(" + this.margin.left + "," + "450)");

    this.y = d3.scale.linear()
      .range([0, this.height]);

    this.x = d3.scale.ordinal()
      .rangeRoundBands([0, this.width], .1);

    this.color = d3.scale.category20();

    this.yAxis = d3.svg.axis()
      .scale(this.y)
      .ticks(6)
      .orient("bottom");

    this.xAxis = d3.svg.axis()
      .scale(this.x)
      .orient("left");

    // Add axes visual elements
    this.svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + /*this.height*/50 + ")");

    // filter, aggregate, modify data
    this.wrangleData(null);

    // call the update method
    this.updateVis();
}

/**
 * Method to wrangle the data. In this case it takes an options object
 * @param _filterFunction - a function that filters data or "null" if none
 */
PrioVis.prototype.wrangleData = function(_filterFunction){

    // displayData should hold the data which is visualized
    this.displayData = this.filterAndAggregate(_filterFunction);

    //// you might be able to pass some options,
    //// if you don't pass options -- set the default options
    //// the default is: var options = {filter: function(){return true;} }
    //var options = _options || {filter: function(){return true;}};

}

/**
 * the drawing function - should use the D3 selection, enter, exit
 */
PrioVis.prototype.doesLabelFit = function(datum, label) {
      var pixel_per_character = 6;  // obviously a (rough) approximation

      return true;//return datum.type.length * pixel_per_character < this.x(datum.count);
    }

PrioVis.prototype.updateVis = function(){
    var that = this;

    // updates scales
    this.y.domain(d3.extent(this.displayData, function(d) { console.log(d);return d.count; }));
    this.x.domain(this.displayData.map(function(d) { console.log(d);return d.type; }));
    this.color.domain(this.displayData.map(function(d) { return d.type }));
    console.log('updating');
    // updates axis
    this.svg.select(".x.axis")
        .call(this.xAxis);

    // updates graph

    // Data join
    var bar = this.svg.selectAll(".bar")
      .data(this.displayData, function(d) { console.log(d);return d.type; });

    // Append new bar groups, if required
    var bar_enter = bar.enter().append("g");

    // Append a rect and a text only for the Enter set (new g)
    bar_enter.append("rect");
    bar_enter.append("text");

    // Add click interactivity
    bar_enter.on("click", function(d) {
       $(that.eventHandler).trigger("selectionChanged", d.type);
    })
    console.log('hi');
    // Add attributes (position) to all bars
    bar
      .attr("class", "bar")
      .transition()
      .attr("transform", function(d, i) { console.log(d);return "translate(0," + i/*that.y(d.type)*/ + ")"; })

    // Remove the extra bars
    bar.exit()
      .remove();

    // Update all inner rects and texts (both update and enter sets)

    bar.selectAll("rect")
      .attr("x", 0)
      .attr("y", 0)
      // .attr("height", this.y.rangeBand())
      .style("fill", function(d,i) {
        return that.color(d.type);
      })
      .transition()
      .attr("width", function(d, i) {
          return that.x(d.count);
      });

    bar.selectAll("text")
      .transition()
      .attr("x", function(d) { return that.x(d.count) + (that.doesLabelFit(d) ? -3 : 5); })
      // .attr("y", function(d,i) { return that.y.rangeBand() / 2; })
      .text(function(d) { return d.type; })
      .attr("class", "type-label")
      .attr("dy", ".35em")
      .attr("text-anchor", function(d) { return that.doesLabelFit(d) ? "end" : "start"; })
      .attr("fill", function(d) { return that.doesLabelFit(d) ? "white" : "black"; });
}

/**
 * Gets called by event handler and should create new aggregated data
 * aggregation is done by the function "aggregate(filter)". Filter has to
 * be defined here.
 * @param selection
 */
PrioVis.prototype.onSelectionChange= function (selectionStart, selectionEnd){

    // TODO: call wrangle function
    console.log(selectionStart);
    prioSelectionStart = selectionStart;
    prioSelectionEnd = selectionEnd;
    this.wrangleData(null);
    this.updateVis();

}

/*
*
* ==================================
* From here on only HELPER functions
* ==================================
*
* */

/**
 * The aggregate function that creates the counts for each age for a given filter.
 * @param _filter - A filter can be, e.g.,  a function that is only true for data of a given time range
 * @returns {Array|*}
 */
var dateFormat = d3.time.format("%Y-%m-%d");
PrioVis.prototype.filterAndAggregate = function(_filter){

    // Set filter to a function that accepts all items
    // ONLY if the parameter _filter is NOT null use this parameter
    var filter = function(){return true;}
    if (_filter != null){
        filter = _filter;
    }
    //Dear JS hipster, a more hip variant of this construct would be:
    // var filter = _filter || function(){return true;}

    var that = this;

    // create an array of values for age 0-100
    bins = d3.range(16);

    // accumulate all values that fulfill the filter criterion

    // TODO: implement the function that filters the data and sums the values

    compareDates = function(limit, current) {
        limitYear = limit.getFullYear();
        limitMonth = limit.getMonth();
        limitDate = limit.getDate();
        currentYear = parseInt(current.charAt(0)+current.charAt(1)+current.charAt(2)+current.charAt(3))
        currentMonth = parseInt(current.charAt(5)+current.charAt(6)) - 1;
        currentDate = parseInt(current.charAt(8)+current.charAt(9));
        if (limitYear > currentYear) {return false}
        else if (limitMonth > currentMonth) {return false}
        else if (limitDate > currentDate) {return false}
        else {return true}
    }

    // for each age on y-axis
    bins.forEach(function(c, h) {
    // we look at each day of votes
    console.log(mainData);
    mainData.forEach(function(d, i) {

    if (typeof prioSelectionStart == 'undefined') {
        prioSelectionStart = new Date(Date.parse("December 1, 2012"));
        prioSelectionEnd = new Date(Date.parse("December 31, 2013"));
    }

        // see that the day is in range
        if (compareDates(prioSelectionStart,d.day) && !compareDates(prioSelectionEnd,d.day)) {

                 console.log(d)   //bins[h] += d[i]["sum(p0)"]

                }
            })
        }

    );

    newBins = bins;
    console.log(newBins);
    return bins;
}
<commit_msg>obtained value array for prios<commit_after>/**
 * Created by Hendrik Strobelt (hendrik.strobelt.com) on 1/28/15.
 */

//TODO: DO IT ! :) Look at agevis.js for a useful structure

/**
 * Created by Hendrik Strobelt (hendrik.strobelt.com) on 1/28/15.
 */

/*
 *
 * ======================================================
 * We follow the vis template of init - wrangle - update
 * ======================================================
 *
 * */

/**
 * AgeVis object for HW3 of CS171
 * @param _parentElement -- the HTML or SVG element (D3 node) to which to attach the vis
 * @param _data -- the data array
 * @param _metaData -- the meta-data / data description object
 * @constructor
 */
PrioVis = function(_parentElement, _data, _metaData){
    this.parentElement = _parentElement;
    this.data = _data;
    this.metaData = _metaData;
    this.displayData = [];

    // TODO: define all constants here
    this.margin = {top: 20, right: 0, bottom: 30, left: 70},
    this.width = getInnerWidth(this.parentElement) - this.margin.left - this.margin.right,
    this.height = 400 - this.margin.top - this.margin.bottom;

    this.initVis();

}

/**
 * Method that sets up the SVG and the variables
 */
PrioVis.prototype.initVis = function(){

    var that = this; // read about the this

    //TODO: construct or select SVG
    //TODO: create axis and scales

    // constructs SVG layout
    this.svg = this.parentElement.append("svg")
        .attr("width", this.width + this.margin.left + this.margin.right)
        .attr("height", this.height + this.margin.top + this.margin.bottom)
        .attr("class", "lightcoral")
      .append("g")
        .attr("transform", "translate(" + this.margin.left + "," + "450)");

    this.y = d3.scale.linear()
      .range([0, this.height]);

    this.x = d3.scale.ordinal()
      .rangeRoundBands([0, this.width], .1);

    this.color = d3.scale.category20();

    this.yAxis = d3.svg.axis()
      .scale(this.y)
      .ticks(6)
      .orient("bottom");

    this.xAxis = d3.svg.axis()
      .scale(this.x)
      .orient("left");

    // Add axes visual elements
    this.svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + /*this.height*/50 + ")");

    // filter, aggregate, modify data
    this.wrangleData(null);

    // call the update method
    this.updateVis();
}

/**
 * Method to wrangle the data. In this case it takes an options object
 * @param _filterFunction - a function that filters data or "null" if none
 */
PrioVis.prototype.wrangleData = function(_filterFunction){

    // displayData should hold the data which is visualized
    this.displayData = this.filterAndAggregate(_filterFunction);

    //// you might be able to pass some options,
    //// if you don't pass options -- set the default options
    //// the default is: var options = {filter: function(){return true;} }
    //var options = _options || {filter: function(){return true;}};

}

/**
 * the drawing function - should use the D3 selection, enter, exit
 */
PrioVis.prototype.doesLabelFit = function(datum, label) {
      var pixel_per_character = 6;  // obviously a (rough) approximation

      return true;//return datum.type.length * pixel_per_character < this.x(datum.count);
    }

PrioVis.prototype.updateVis = function(){
    var that = this;

    // updates scales
    this.y.domain(d3.extent(this.displayData, function(d) { return d.count; }));
    this.x.domain(this.displayData.map(function(d) { return d.type; }));
    this.color.domain(this.displayData.map(function(d) { return d.type }));

    // updates axis
    this.svg.select(".x.axis")
        .call(this.xAxis);

    // updates graph

    // Data join
    var bar = this.svg.selectAll(".bar")
      .data(this.displayData, function(d) { return d.type; });

    // Append new bar groups, if required
    var bar_enter = bar.enter().append("g");

    // Append a rect and a text only for the Enter set (new g)
    bar_enter.append("rect");
    bar_enter.append("text");

    // Add click interactivity
    bar_enter.on("click", function(d) {
       $(that.eventHandler).trigger("selectionChanged", d.type);
    })

    // Add attributes (position) to all bars
    bar
      .attr("class", "bar")
      .transition()
      .attr("transform", function(d, i) { return "translate(0," + i/*that.y(d.type)*/ + ")"; })

    // Remove the extra bars
    bar.exit()
      .remove();

    // Update all inner rects and texts (both update and enter sets)

    bar.selectAll("rect")
      .attr("x", 0)
      .attr("y", 0)
      // .attr("height", this.y.rangeBand())
      .style("fill", function(d,i) {
        return that.color(d.type);
      })
      .transition()
      .attr("width", function(d, i) {
          return that.x(d.count);
      });

    bar.selectAll("text")
      .transition()
      .attr("x", function(d) { return that.x(d.count) + (that.doesLabelFit(d) ? -3 : 5); })
      // .attr("y", function(d,i) { return that.y.rangeBand() / 2; })
      .text(function(d) { return d.type; })
      .attr("class", "type-label")
      .attr("dy", ".35em")
      .attr("text-anchor", function(d) { return that.doesLabelFit(d) ? "end" : "start"; })
      .attr("fill", function(d) { return that.doesLabelFit(d) ? "white" : "black"; });
}

/**
 * Gets called by event handler and should create new aggregated data
 * aggregation is done by the function "aggregate(filter)". Filter has to
 * be defined here.
 * @param selection
 */
PrioVis.prototype.onSelectionChange= function (selectionStart, selectionEnd){

    // TODO: call wrangle function
    prioSelectionStart = selectionStart;
    prioSelectionEnd = selectionEnd;
    this.wrangleData(null);
    this.updateVis();

}

/*
*
* ==================================
* From here on only HELPER functions
* ==================================
*
* */

/**
 * The aggregate function that creates the counts for each age for a given filter.
 * @param _filter - A filter can be, e.g.,  a function that is only true for data of a given time range
 * @returns {Array|*}
 */
var dateFormat = d3.time.format("%Y-%m-%d");
PrioVis.prototype.filterAndAggregate = function(_filter){

    // Set filter to a function that accepts all items
    // ONLY if the parameter _filter is NOT null use this parameter
    var filter = function(){return true;}
    if (_filter != null){
        filter = _filter;
    }
    //Dear JS hipster, a more hip variant of this construct would be:
    // var filter = _filter || function(){return true;}

    var that = this;

    // create an array of values for age 0-100
    bins = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];

    // accumulate all values that fulfill the filter criterion

    // TODO: implement the function that filters the data and sums the values

    compareDates = function(limit, current) {
        limitYear = limit.getFullYear();
        limitMonth = limit.getMonth();
        limitDate = limit.getDate();
        currentYear = parseInt(current.charAt(0)+current.charAt(1)+current.charAt(2)+current.charAt(3))
        currentMonth = parseInt(current.charAt(5)+current.charAt(6)) - 1;
        currentDate = parseInt(current.charAt(8)+current.charAt(9));
        if (limitYear > currentYear) {return false}
        else if (limitMonth > currentMonth) {return false}
        else if (limitDate > currentDate) {return false}
        else {return true}
    }

    // for each age on y-axis
    if (typeof prioSelectionStart == 'undefined') {
        prioSelectionStart = new Date(Date.parse("December 1, 2012"));
        prioSelectionEnd = new Date(Date.parse("December 31, 2013"));
    }
    //for each day of votes
    mainData.forEach(function(d, i) {
      // for each bin (priority)
      bins.forEach(function(c, h) {

        // if date is in range
        if (compareDates(prioSelectionStart,d.day) && !compareDates(prioSelectionEnd,d.day)) {

               if(typeof(d["sum(p" + i + ")"]) !== 'undefined') { console.log(d);bins[h] += d["sum(p" + h + ")"];}

                }
            })
        }

    );

    newBins = bins;
    console.log(newBins);
    return bins;
}<|endoftext|>


<commit_before>/** This is a folderFunction, which is basically a function
 * that is expanded into data objects. */
hax.FolderFunction = function(name,owner,initialData,createEmptyInternalFolder) {
    //base init
    hax.Child.init.call(this,name,hax.FolderFunction.generator);
    hax.DataHolder.init.call(this);
    hax.Dependent.init.call(this);
    hax.ContextHolder.init.call(this);
    hax.Owner.init.call(this);
    hax.RootHolder.init.call(this);

    this.initOwner(owner);

    //set initial data
    this.argList = initialData.argList !== undefined ? initialData.argList : "";
    this.returnValueString = initialData.returnValue !== undefined ? initialData.returnValue : [];
    //set to an empty function
    this.setData(function(){});

    //recreate the root folder if info is specified
    if(createEmptyInternalFolder) {
        var internalFolder = new hax.Folder(name,this);
        this.setRoot(internalFolder);
    }
}

//add components to this class
hax.base.mixin(hax.FolderFunction,hax.Child);
hax.base.mixin(hax.FolderFunction,hax.DataHolder);
hax.base.mixin(hax.FolderFunction,hax.Dependent);
hax.base.mixin(hax.FolderFunction,hax.ContextHolder);
hax.base.mixin(hax.FolderFunction,hax.Owner);
hax.base.mixin(hax.FolderFunction,hax.RootHolder);

/** This gets the internal forlder for the folderFunction. */
hax.FolderFunction.prototype.getInternalFolder = function() {
    return this.internalFolder;
}

/** Implemnetation of get root for folder function. */
hax.FolderFunction.prototype.getRoot = function() {
    return this.getInternalFolder();
}

/** This method sets the root object - implemented from RootHolder.  */
hax.FolderFunction.prototype.setRoot = function(child) {
    this.internalFolder = child;
    var newDependsOn = [child];
    this.updateDependencies(newDependsOn);
}

/** This gets the name of the return object for the folderFunction function. */
hax.FolderFunction.prototype.getReturnValueString = function() {
    return this.returnValueString;
}

/** This gets the arg list of the folderFunction function. */
hax.FolderFunction.prototype.getArgList = function() {
    return this.argList;
}

//------------------------------
// Child Methods
//------------------------------

/** This overrides the get displaymethod of child to return the function declaration. */
hax.FolderFunction.prototype.getDisplayName = function() {
    var name = this.getName();
    var argList = this.getArgList();
    var argListString = argList.join(",");

    var displayName = name + "(" + argListString + ")";
    if((this.returnValueString != null)&&(this.returnValueString.length > 0)) {
        displayName += " = " + this.returnValueString;
    }

    return displayName;
}

/** This method is called when the child is deleted. If necessary the implementation
 * can extend this function, but it should call this base version of the function
 * if it does.  */
hax.FolderFunction.prototype.onDelete = function() {

    var returnValue;

    if(this.internalFolder) {
        var actionResponse = hax.deletemember.deleteMember(this.internalFolder);
        if(!actionResponse.getSuccess()) {
            //show an error message
            var msg = actionResponse.getErrorMsg();
            alert(msg);
        }
    }

//I don't know what to do if this fails. Figure that out.

    //call the base delete
    returnValue = hax.Child.onDelete.call(this);
	return returnValue;
}

/** This method creates a child from a json. It should be implemented as a static
 * method in a non-abstract class. */
hax.FolderFunction.fromJson = function(owner,json,childrenJsonOutputList) {
    var initialData = {};
    initialData.argList = json.argList;
    initialData.returnValue = json.returnValue;

    var createEmptyInternalFolder;
    if(json.internalFolder) {
        childrenJsonOutputList.push(json.internalFolder);
        createEmptyInternalFolder = false;
    }
    else {
        createEmptyInternalFolder = true;
    }

    return new hax.FolderFunction(json.name,owner,initialData,createEmptyInternalFolder);
}

/** This method adds any additional data to the json saved for this child.
 * @protected */
hax.FolderFunction.prototype.addToJson = function(json) {
    json.argList = this.argList;
    json.returnValue = this.returnValueString;
    json.internalFolder = this.internalFolder.toJson();
}

//-------------------------------
// Dependent Methods
//-------------------------------

/** If this is true the member must be executed. */
hax.FolderFunction.prototype.needsCalculating = function() {
	return true;
}

/** This updates the member data based on the function. It returns
 * true for success and false if there is an error.  */
hax.FolderFunction.prototype.calculate = function() {
    //make sure the data is set in each impactor
    this.initializeImpactors();

    var folderFunctionErrors = [];

	//check for code errors, if so set a data error
    var folderFunctionFunction = this.getFolderFunctionFunction(folderFunctionErrors);

    if(folderFunctionErrors.length == 0) {
        this.setData(folderFunctionFunction);
    }
    else {
        //for now I can only set a single error. I will set the first.
        //I should get way to set multiple
        this.addErrors(folderFunctionErrors);
    }

    this.clearCalcPending();
}

/** This method updates the dependencies of any children
 * based on an object being added. */
hax.FolderFunction.prototype.updateDependeciesForModelChange = function(recalculateList) {
    if(this.internalFolder) {
        this.internalFolder.updateDependeciesForModelChange(recalculateList);
    }
}

//------------------------------
//ContextHolder methods
//------------------------------

/** This method retrieve creates the loaded context manager. */
hax.FolderFunction.prototype.createContextManager = function() {
    return new hax.ContextManager(this);
}

//------------------------------
//Owner methods
//------------------------------

/** this method gets the hame the children inherit for the full name. */
hax.FolderFunction.prototype.getPossesionNameBase = function() {
    return this.getFullName() + ":";
}

//==============================
// Private Methods
//==============================

/** This is called from the update action. It should not be called externally. */
hax.FolderFunction.prototype.setReturnValueString = function(returnValueString) {
    this.returnValueString = returnValueString;
}

/** This is called from the update action. It should not be called externally. */
hax.FolderFunction.prototype.setArgList = function(argList) {
    this.argList = argList;
}

/** This method creates the folderFunction function. It is called from the update action
 * and should not be called externally.
 * @private */
hax.FolderFunction.prototype.getFolderFunctionFunction = function(folderFunctionErrors) {

    //create a copy of the workspace to do the function calculation - we don't update the UI display version
    var virtualWorkspace;
    var rootFolder;
    var inputElementArray;
    var returnValueTable;

    var initialized = false;
    var instance = this;

    var folderFunctionFunction = function(args) {

        if(!initialized) {
            //create a copy of the workspace to do the function calculation - we don't update the UI display version
            virtualWorkspace = instance.createVirtualWorkspace(folderFunctionErrors);

    //HANDLE THIS ERROR CASE DIFFERENTLY!!!
            if(!virtualWorkspace) {
                return null;
            }

            //lookup elements from virtual workspace
            rootFolder = virtualWorkspace.getRoot();
            inputElementArray = instance.loadInputElements(rootFolder,folderFunctionErrors);
            returnValueTable = instance.loadOutputElement(rootFolder,folderFunctionErrors);
        }

        //create an update array to set the table values to the elements
        var updateDataList = [];
        for(var i = 0; i < inputElementArray.length; i++) {
            var entry = {};
            entry.member = inputElementArray[i];
            entry.data = arguments[i];
            updateDataList.push(entry);
        }

        //apply the update
        var actionResponse = hax.updatemember.updateObjects(updateDataList);
        if(actionResponse.getSuccess()) {
            //retrieve the result
            if(returnValueTable) {
                return returnValueTable.getData();
            }
            else {
                //no return value found
                return undefined;
            }
        }
        else {
            //error exectuing folderFunction function - thro wan exception
            throw hax.base.createError(actionResponse.getErrorMsg());
        }
    }

    return folderFunctionFunction;
}

/** This method creates a copy of the workspace to be used for the function evvaluation.
 * @private */
hax.FolderFunction.prototype.createVirtualWorkspace = function(folderFunctionErrors) {
    try {
		return hax.Workspace.createVirtualWorkpaceFromFolder("temp",this.internalFolder,this.getOwner());
	}
	catch(error) {
        var actionError = hax.ActionError.processException(exception,"FolderFunction - Code",false);
		folderFunctionErrors.push(actionError);
		return null;
	}
}

/** This method loads the input argument members from the virtual workspace.
 * @private */
hax.FolderFunction.prototype.loadInputElements = function(rootFolder,folderFunctionErrors) {
    var argMembers = [];
    for(var i = 0; i < this.argList.length; i++) {
        var argName = this.argList[i];
        var argMember = rootFolder.lookupChild(argName);
        if(argMember) {
			argMembers.push(argMember);
		}
//		else {
//            //missing input element
//            var msg = "Input element not found in folderFunction: " + argName;
//            var actionError = new hax.ActionError(msg,"FolderFunction - Code",this);
//            folderFunctionErrors.push(actionError);
//        }
    }
    return argMembers;
}

/** This method loads the output member from the virtual workspace.
 * @private  */
hax.FolderFunction.prototype.loadOutputElement = function(rootFolder,folderFunctionErrors) {
    var returnValueMember = rootFolder.lookupChild(this.returnValueString);
//    if(!returnValueMember) {
//        //missing input element
//        var msg = "Return element not found in folderFunction: " + this.returnValueString;
//        var actionError = new hax.ActionError(msg,"FolderFunction - Code",this);
//        folderFunctionErrors.push(actionError);
//    }
    return returnValueMember;
}

//============================
// Static methods
//============================

hax.FolderFunction.generator = {};
hax.FolderFunction.generator.displayName = "Folder Function";
hax.FolderFunction.generator.type = "hax.FolderFunction";
hax.FolderFunction.generator.createMember = hax.FolderFunction.fromJson;

//register this member
hax.Workspace.addMemberGenerator(hax.FolderFunction.generator);<commit_msg>fixed a bug from in folder function delete<commit_after>/** This is a folderFunction, which is basically a function
 * that is expanded into data objects. */
hax.FolderFunction = function(name,owner,initialData,createEmptyInternalFolder) {
    //base init
    hax.Child.init.call(this,name,hax.FolderFunction.generator);
    hax.DataHolder.init.call(this);
    hax.Dependent.init.call(this);
    hax.ContextHolder.init.call(this);
    hax.Owner.init.call(this);
    hax.RootHolder.init.call(this);

    this.initOwner(owner);

    //set initial data
    this.argList = initialData.argList !== undefined ? initialData.argList : "";
    this.returnValueString = initialData.returnValue !== undefined ? initialData.returnValue : [];
    //set to an empty function
    this.setData(function(){});

    //recreate the root folder if info is specified
    if(createEmptyInternalFolder) {
        var internalFolder = new hax.Folder(name,this);
        this.setRoot(internalFolder);
    }
}

//add components to this class
hax.base.mixin(hax.FolderFunction,hax.Child);
hax.base.mixin(hax.FolderFunction,hax.DataHolder);
hax.base.mixin(hax.FolderFunction,hax.Dependent);
hax.base.mixin(hax.FolderFunction,hax.ContextHolder);
hax.base.mixin(hax.FolderFunction,hax.Owner);
hax.base.mixin(hax.FolderFunction,hax.RootHolder);

/** This gets the internal forlder for the folderFunction. */
hax.FolderFunction.prototype.getInternalFolder = function() {
    return this.internalFolder;
}

/** Implemnetation of get root for folder function. */
hax.FolderFunction.prototype.getRoot = function() {
    return this.getInternalFolder();
}

/** This method sets the root object - implemented from RootHolder.  */
hax.FolderFunction.prototype.setRoot = function(child) {
    this.internalFolder = child;
    var newDependsOn = [];
    if(child) newDependsOn.push(child);
    this.updateDependencies(newDependsOn);
}

/** This gets the name of the return object for the folderFunction function. */
hax.FolderFunction.prototype.getReturnValueString = function() {
    return this.returnValueString;
}

/** This gets the arg list of the folderFunction function. */
hax.FolderFunction.prototype.getArgList = function() {
    return this.argList;
}

//------------------------------
// Child Methods
//------------------------------

/** This overrides the get displaymethod of child to return the function declaration. */
hax.FolderFunction.prototype.getDisplayName = function() {
    var name = this.getName();
    var argList = this.getArgList();
    var argListString = argList.join(",");

    var displayName = name + "(" + argListString + ")";
    if((this.returnValueString != null)&&(this.returnValueString.length > 0)) {
        displayName += " = " + this.returnValueString;
    }

    return displayName;
}

/** This method is called when the child is deleted. If necessary the implementation
 * can extend this function, but it should call this base version of the function
 * if it does.  */
hax.FolderFunction.prototype.onDelete = function() {

    var returnValue;

    if(this.internalFolder) {
        var actionResponse = hax.deletemember.deleteMember(this.internalFolder);
        if(!actionResponse.getSuccess()) {
            //show an error message
            var msg = actionResponse.getErrorMsg();
            alert(msg);
        }
    }

//I don't know what to do if this fails. Figure that out.

    //call the base delete
    returnValue = hax.Child.onDelete.call(this);
	return returnValue;
}

/** This method creates a child from a json. It should be implemented as a static
 * method in a non-abstract class. */
hax.FolderFunction.fromJson = function(owner,json,childrenJsonOutputList) {
    var initialData = {};
    initialData.argList = json.argList;
    initialData.returnValue = json.returnValue;

    var createEmptyInternalFolder;
    if(json.internalFolder) {
        childrenJsonOutputList.push(json.internalFolder);
        createEmptyInternalFolder = false;
    }
    else {
        createEmptyInternalFolder = true;
    }

    return new hax.FolderFunction(json.name,owner,initialData,createEmptyInternalFolder);
}

/** This method adds any additional data to the json saved for this child.
 * @protected */
hax.FolderFunction.prototype.addToJson = function(json) {
    json.argList = this.argList;
    json.returnValue = this.returnValueString;
    json.internalFolder = this.internalFolder.toJson();
}

//-------------------------------
// Dependent Methods
//-------------------------------

/** If this is true the member must be executed. */
hax.FolderFunction.prototype.needsCalculating = function() {
	return true;
}

/** This updates the member data based on the function. It returns
 * true for success and false if there is an error.  */
hax.FolderFunction.prototype.calculate = function() {
    //make sure the data is set in each impactor
    this.initializeImpactors();

    var folderFunctionErrors = [];

	//check for code errors, if so set a data error
    var folderFunctionFunction = this.getFolderFunctionFunction(folderFunctionErrors);

    if(folderFunctionErrors.length == 0) {
        this.setData(folderFunctionFunction);
    }
    else {
        //for now I can only set a single error. I will set the first.
        //I should get way to set multiple
        this.addErrors(folderFunctionErrors);
    }

    this.clearCalcPending();
}

/** This method updates the dependencies of any children
 * based on an object being added. */
hax.FolderFunction.prototype.updateDependeciesForModelChange = function(recalculateList) {
    if(this.internalFolder) {
        this.internalFolder.updateDependeciesForModelChange(recalculateList);
    }
}

//------------------------------
//ContextHolder methods
//------------------------------

/** This method retrieve creates the loaded context manager. */
hax.FolderFunction.prototype.createContextManager = function() {
    return new hax.ContextManager(this);
}

//------------------------------
//Owner methods
//------------------------------

/** this method gets the hame the children inherit for the full name. */
hax.FolderFunction.prototype.getPossesionNameBase = function() {
    return this.getFullName() + ":";
}

//==============================
// Private Methods
//==============================

/** This is called from the update action. It should not be called externally. */
hax.FolderFunction.prototype.setReturnValueString = function(returnValueString) {
    this.returnValueString = returnValueString;
}

/** This is called from the update action. It should not be called externally. */
hax.FolderFunction.prototype.setArgList = function(argList) {
    this.argList = argList;
}

/** This method creates the folderFunction function. It is called from the update action
 * and should not be called externally.
 * @private */
hax.FolderFunction.prototype.getFolderFunctionFunction = function(folderFunctionErrors) {

    //create a copy of the workspace to do the function calculation - we don't update the UI display version
    var virtualWorkspace;
    var rootFolder;
    var inputElementArray;
    var returnValueTable;

    var initialized = false;
    var instance = this;

    var folderFunctionFunction = function(args) {

        if(!initialized) {
            //create a copy of the workspace to do the function calculation - we don't update the UI display version
            virtualWorkspace = instance.createVirtualWorkspace(folderFunctionErrors);

    //HANDLE THIS ERROR CASE DIFFERENTLY!!!
            if(!virtualWorkspace) {
                return null;
            }

            //lookup elements from virtual workspace
            rootFolder = virtualWorkspace.getRoot();
            inputElementArray = instance.loadInputElements(rootFolder,folderFunctionErrors);
            returnValueTable = instance.loadOutputElement(rootFolder,folderFunctionErrors);
        }

        //create an update array to set the table values to the elements
        var updateDataList = [];
        for(var i = 0; i < inputElementArray.length; i++) {
            var entry = {};
            entry.member = inputElementArray[i];
            entry.data = arguments[i];
            updateDataList.push(entry);
        }

        //apply the update
        var actionResponse = hax.updatemember.updateObjects(updateDataList);
        if(actionResponse.getSuccess()) {
            //retrieve the result
            if(returnValueTable) {
                return returnValueTable.getData();
            }
            else {
                //no return value found
                return undefined;
            }
        }
        else {
            //error exectuing folderFunction function - thro wan exception
            throw hax.base.createError(actionResponse.getErrorMsg());
        }
    }

    return folderFunctionFunction;
}

/** This method creates a copy of the workspace to be used for the function evvaluation.
 * @private */
hax.FolderFunction.prototype.createVirtualWorkspace = function(folderFunctionErrors) {
    try {
		return hax.Workspace.createVirtualWorkpaceFromFolder("temp",this.internalFolder,this.getOwner());
	}
	catch(error) {
        var actionError = hax.ActionError.processException(exception,"FolderFunction - Code",false);
		folderFunctionErrors.push(actionError);
		return null;
	}
}

/** This method loads the input argument members from the virtual workspace.
 * @private */
hax.FolderFunction.prototype.loadInputElements = function(rootFolder,folderFunctionErrors) {
    var argMembers = [];
    for(var i = 0; i < this.argList.length; i++) {
        var argName = this.argList[i];
        var argMember = rootFolder.lookupChild(argName);
        if(argMember) {
			argMembers.push(argMember);
		}
//		else {
//            //missing input element
//            var msg = "Input element not found in folderFunction: " + argName;
//            var actionError = new hax.ActionError(msg,"FolderFunction - Code",this);
//            folderFunctionErrors.push(actionError);
//        }
    }
    return argMembers;
}

/** This method loads the output member from the virtual workspace.
 * @private  */
hax.FolderFunction.prototype.loadOutputElement = function(rootFolder,folderFunctionErrors) {
    var returnValueMember = rootFolder.lookupChild(this.returnValueString);
//    if(!returnValueMember) {
//        //missing input element
//        var msg = "Return element not found in folderFunction: " + this.returnValueString;
//        var actionError = new hax.ActionError(msg,"FolderFunction - Code",this);
//        folderFunctionErrors.push(actionError);
//    }
    return returnValueMember;
}

//============================
// Static methods
//============================

hax.FolderFunction.generator = {};
hax.FolderFunction.generator.displayName = "Folder Function";
hax.FolderFunction.generator.type = "hax.FolderFunction";
hax.FolderFunction.generator.createMember = hax.FolderFunction.fromJson;

//register this member
hax.Workspace.addMemberGenerator(hax.FolderFunction.generator);<|endoftext|>


<commit_before>// NOCOMPILE
// This example uses the GMapx v3 API, which we do not have an exports file for.
goog.require('ol.Map');
goog.require('ol.RendererHint');
goog.require('ol.View2D');
goog.require('ol.interaction');
goog.require('ol.interaction.DragPan');
goog.require('ol.layer.Vector');
goog.require('ol.proj');
goog.require('ol.source.GeoJSON');
goog.require('ol.style.Fill');
goog.require('ol.style.Stroke');
goog.require('ol.style.Style');

var gmap = new google.maps.Map(document.getElementById('map'), {
  center: new google.maps.LatLng(0, 0),
  zoom: 1,
  disableDefaultUI: true,
  keyboardShortcuts: false,
  draggable: false,
  disableDoubleClickZoom: true,
  scrollwheel: false,
  streetViewControl: false
});

var olmap = document.createElement('div');
olmap.style['width'] = '100%';
olmap.style['height'] = '100%';
gmap.controls[google.maps.ControlPosition.TOP_LEFT].push(olmap);

google.maps.event.addListenerOnce(gmap, 'tilesloaded', function() {
  var vector = new ol.layer.Vector({
    source: new ol.source.GeoJSON({
      url: 'data/geojson/countries.geojson',
      projection: 'EPSG:3857'
    }),
    styleFunction: function(feature, resolution) {
      return [new ol.style.Style({
        fill: new ol.style.Fill({
          color: 'rgba(255, 255, 255, 0.6)'
        }),
        stroke: new ol.style.Stroke({
          color: '#319FD3',
          width: 1
        })
      })];
    }
  });

  var center = gmap.getCenter();
  var map = new ol.Map({
    layers: [vector],
    interactions: ol.interaction.defaults({dragPan: false})
        .extend([new ol.interaction.DragPan({kinetic: false})]),
    renderer: ol.RendererHint.CANVAS,
    target: olmap,
    view: new ol.View2D({
      center: ol.proj.transform([center.lng(), center.lat()],
          'EPSG:4326', 'EPSG:3857'),
      zoom: gmap.getZoom()
    })
  });

  var view = map.getView().getView2D();
  view.on('change:center', function() {
    var center = ol.proj.transform(view.getCenter(),
        'EPSG:3857', 'EPSG:4326');
    gmap.setCenter(new google.maps.LatLng(center[1], center[0]));
  });
  view.on('change:resolution', function() {
    gmap.setZoom(view.getZoom());
  });
});
<commit_msg>Create styles only once<commit_after>// NOCOMPILE
// This example uses the GMapx v3 API, which we do not have an exports file for.
goog.require('ol.Map');
goog.require('ol.RendererHint');
goog.require('ol.View2D');
goog.require('ol.interaction');
goog.require('ol.interaction.DragPan');
goog.require('ol.layer.Vector');
goog.require('ol.proj');
goog.require('ol.source.GeoJSON');
goog.require('ol.style.Fill');
goog.require('ol.style.Stroke');
goog.require('ol.style.Style');

var gmap = new google.maps.Map(document.getElementById('map'), {
  center: new google.maps.LatLng(0, 0),
  zoom: 1,
  disableDefaultUI: true,
  keyboardShortcuts: false,
  draggable: false,
  disableDoubleClickZoom: true,
  scrollwheel: false,
  streetViewControl: false
});

var olmap = document.createElement('div');
olmap.style['width'] = '100%';
olmap.style['height'] = '100%';
gmap.controls[google.maps.ControlPosition.TOP_LEFT].push(olmap);

google.maps.event.addListenerOnce(gmap, 'tilesloaded', function() {
  var vector = new ol.layer.Vector({
    source: new ol.source.GeoJSON({
      url: 'data/geojson/countries.geojson',
      projection: 'EPSG:3857'
    }),
    styleFunction: (function() {
      var styleArray = [new ol.style.Style({
        fill: new ol.style.Fill({
          color: 'rgba(255, 255, 255, 0.6)'
        }),
        stroke: new ol.style.Stroke({
          color: '#319FD3',
          width: 1
        })
      })];
      return function(feature, resolution) {
        return styleArray;
      };
    }())
  });

  var center = gmap.getCenter();
  var map = new ol.Map({
    layers: [vector],
    interactions: ol.interaction.defaults({dragPan: false})
        .extend([new ol.interaction.DragPan({kinetic: false})]),
    renderer: ol.RendererHint.CANVAS,
    target: olmap,
    view: new ol.View2D({
      center: ol.proj.transform([center.lng(), center.lat()],
          'EPSG:4326', 'EPSG:3857'),
      zoom: gmap.getZoom()
    })
  });

  var view = map.getView().getView2D();
  view.on('change:center', function() {
    var center = ol.proj.transform(view.getCenter(),
        'EPSG:3857', 'EPSG:4326');
    gmap.setCenter(new google.maps.LatLng(center[1], center[0]));
  });
  view.on('change:resolution', function() {
    gmap.setZoom(view.getZoom());
  });
});
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2010 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * @constructor
 * @extends {WebInspector.SidebarPane}
 */
WebInspector.WorkersSidebarPane = function()
{
    WebInspector.SidebarPane.call(this, WebInspector.UIString("Workers"));

    this._enableWorkersCheckbox = new WebInspector.Checkbox(
        WebInspector.UIString("Pause on start"),
        "sidebar-label",
        WebInspector.UIString("Automatically attach to new workers and pause them. Enabling this option will force opening inspector for all new workers."));
    this._enableWorkersCheckbox.element.id = "pause-workers-checkbox";
    this.bodyElement.appendChild(this._enableWorkersCheckbox.element);
    this._enableWorkersCheckbox.addEventListener(this._autoattachToWorkersClicked.bind(this));
    this._enableWorkersCheckbox.checked = false;

    var note = this.bodyElement.createChild("div");
    note.id = "shared-workers-list";
    note.classList.add("sidebar-label")
    note.textContent = WebInspector.UIString("Shared workers can be inspected in the Task Manager");

    var separator = this.bodyElement.createChild("div", "sidebar-separator");
    separator.textContent = WebInspector.UIString("Dedicated worker inspectors");

    this._workerListElement = document.createElement("ol");
    this._workerListElement.tabIndex = 0;
    this._workerListElement.classList.add("properties-tree");
    this._workerListElement.classList.add("sidebar-label");
    this.bodyElement.appendChild(this._workerListElement);

    this._idToWorkerItem = {};

    var threadList = WebInspector.workerManager.threadsList();
    for (var i = 0; i < threadList.length; ++i) {
        var threadId = threadList[i];
        if (threadId === WebInspector.WorkerManager.MainThreadId)
            continue;

        this._addWorker(threadId, WebInspector.workerManager.threadUrl(threadId));
    }

    WebInspector.workerManager.addEventListener(WebInspector.WorkerManager.Events.WorkerAdded, this._workerAdded, this);
    WebInspector.workerManager.addEventListener(WebInspector.WorkerManager.Events.WorkerRemoved, this._workerRemoved, this);
    WebInspector.workerManager.addEventListener(WebInspector.WorkerManager.Events.WorkersCleared, this._workersCleared, this);
}

WebInspector.WorkersSidebarPane.prototype = {
    _workerAdded: function(event)
    {
        this._addWorker(event.data.workerId, event.data.url);
    },

    _workerRemoved: function(event)
    {
        this._idToWorkerItem[event.data].remove();
        delete this._idToWorkerItem[event.data];
    },

    _workersCleared: function(event)
    {
        this._idToWorkerItem = {};
        this._workerListElement.removeChildren();
    },

    _addWorker: function(workerId, url)
    {
        var item = this._workerListElement.createChild("div", "dedicated-worker-item");
        var link = item.createChild("a");
        link.textContent = url;
        link.href = "#";
        link.target = "_blank";
        link.addEventListener("click", this._workerItemClicked.bind(this, workerId), true);
        this._idToWorkerItem[workerId] = item;
    },

    _workerItemClicked: function(workerId, event)
    {
        event.preventDefault();
        WebInspector.workerFrontendManager.openWorkerInspector(workerId);
    },

    _autoattachToWorkersClicked: function(event)
    {
        WorkerAgent.setAutoconnectToWorkers(this._enableWorkersCheckbox.checked);
    },

    __proto__: WebInspector.SidebarPane.prototype
}
<commit_msg>DevTools: prevent opening third devtools window while opening worker frontend<commit_after>/*
 * Copyright (C) 2010 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * @constructor
 * @extends {WebInspector.SidebarPane}
 */
WebInspector.WorkersSidebarPane = function()
{
    WebInspector.SidebarPane.call(this, WebInspector.UIString("Workers"));

    this._enableWorkersCheckbox = new WebInspector.Checkbox(
        WebInspector.UIString("Pause on start"),
        "sidebar-label",
        WebInspector.UIString("Automatically attach to new workers and pause them. Enabling this option will force opening inspector for all new workers."));
    this._enableWorkersCheckbox.element.id = "pause-workers-checkbox";
    this.bodyElement.appendChild(this._enableWorkersCheckbox.element);
    this._enableWorkersCheckbox.addEventListener(this._autoattachToWorkersClicked.bind(this));
    this._enableWorkersCheckbox.checked = false;

    var note = this.bodyElement.createChild("div");
    note.id = "shared-workers-list";
    note.classList.add("sidebar-label")
    note.textContent = WebInspector.UIString("Shared workers can be inspected in the Task Manager");

    var separator = this.bodyElement.createChild("div", "sidebar-separator");
    separator.textContent = WebInspector.UIString("Dedicated worker inspectors");

    this._workerListElement = document.createElement("ol");
    this._workerListElement.tabIndex = 0;
    this._workerListElement.classList.add("properties-tree");
    this._workerListElement.classList.add("sidebar-label");
    this.bodyElement.appendChild(this._workerListElement);

    this._idToWorkerItem = {};

    var threadList = WebInspector.workerManager.threadsList();
    for (var i = 0; i < threadList.length; ++i) {
        var threadId = threadList[i];
        if (threadId === WebInspector.WorkerManager.MainThreadId)
            continue;

        this._addWorker(threadId, WebInspector.workerManager.threadUrl(threadId));
    }

    WebInspector.workerManager.addEventListener(WebInspector.WorkerManager.Events.WorkerAdded, this._workerAdded, this);
    WebInspector.workerManager.addEventListener(WebInspector.WorkerManager.Events.WorkerRemoved, this._workerRemoved, this);
    WebInspector.workerManager.addEventListener(WebInspector.WorkerManager.Events.WorkersCleared, this._workersCleared, this);
}

WebInspector.WorkersSidebarPane.prototype = {
    _workerAdded: function(event)
    {
        this._addWorker(event.data.workerId, event.data.url);
    },

    _workerRemoved: function(event)
    {
        this._idToWorkerItem[event.data].remove();
        delete this._idToWorkerItem[event.data];
    },

    _workersCleared: function(event)
    {
        this._idToWorkerItem = {};
        this._workerListElement.removeChildren();
    },

    _addWorker: function(workerId, url)
    {
        var item = this._workerListElement.createChild("div", "dedicated-worker-item");
        var link = item.createChild("a");
        link.textContent = url;
        link.href = "#";
        link.target = "_blank";
        link.addEventListener("click", this._workerItemClicked.bind(this, workerId), true);
        this._idToWorkerItem[workerId] = item;
    },

    _workerItemClicked: function(workerId, event)
    {
        event.consume(true);
        WebInspector.workerFrontendManager.openWorkerInspector(workerId);
    },

    _autoattachToWorkersClicked: function(event)
    {
        WorkerAgent.setAutoconnectToWorkers(this._enableWorkersCheckbox.checked);
    },

    __proto__: WebInspector.SidebarPane.prototype
}
<|endoftext|>


<commit_before>/**
 * @file a Chatbot using tensorflow. idk what else to say
 * @todo meme satania
 * @author Capuccino
 */
 const tf = require('tensorflow2');
 const bucket = require('./Bucket');

 /**
  * A class the handles text-based neural intelligence
  */
 class Chatbot {
     /**
      * @param {String} dataPath path of where the data is
      * @param {String} convoFile the corpus file for convos
      * @param {String} lineFile the corpus file for lines
      * @param {String} outputFile  the output corpus file
      * @param {String} processedPath the path on where to dump processed files for caching
      * @param {String} checkpoints path of where to place the checkpoints
      * @param {Number} treshold the treshold for collision
      * @param {Number} padID *
      * @param {Number} unkID *
      * @param {Number} startID *
      * @param {Number} eosID *
      * @param {Number} testSetSize the size of the test sets
      */
     constructor(dataPath, convoFile, lineFile, outputFile, processedPath, checkpoints, treshold, padID, unkID, startID, eosID, testSetSize) {
         this.dataPath = dataPath,
         this.convoFile = convoFile,
         this.outputFile = outputFile,
         this.processedPath = processedPath,
         this.checkpoints = checkpoints,
         this.treshold = treshold,
         this.padID = padID,
         this.unkID = unkID,
         this.startID = startID,
         this.eosID = eosID,
         this.testSetSize = testSetSize || 25000;
     }
 }

 module.exports = Chatbot;<commit_msg>add typechecker<commit_after>/**
 * @file a Chatbot using tensorflow. idk what else to say
 * @todo meme satania
 * @author Capuccino
 */
 const tf = require('tensorflow2');
 const bucket = require('./Bucket');

 /**
  * A class the handles text-based neural intelligence
  */
 class Chatbot {
     /**
      * @param {String} dataPath path of where the data is
      * @param {String} convoFile the corpus file for convos
      * @param {String} lineFile the corpus file for lines
      * @param {String} outputFile  the output corpus file
      * @param {String} processedPath the path on where to dump processed files for caching
      * @param {String} checkpoints path of where to place the checkpoints
      * @param {Number} treshold the treshold for collision
      * @param {Number} padID *
      * @param {Number} unkID *
      * @param {Number} startID *
      * @param {Number} eosID *
      * @param {Number} testSetSize the size of the test sets
      */
     constructor(dataPath, convoFile, lineFile, outputFile, processedPath, checkpoints, treshold, padID, unkID, startID, eosID, testSetSize) {
         this.dataPath = dataPath,
         this.convoFile = convoFile,
         this.outputFile = outputFile,
         this.processedPath = processedPath,
         this.checkpoints = checkpoints,
         this.treshold = treshold,
         this.padID = padID,
         this.unkID = unkID,
         this.startID = startID,
         this.eosID = eosID,
         this.testSetSize = testSetSize || 25000;

         //typechecker for number-only properties
         if (!isNaN(this.eodID, this.padID, this.treshold, this.unkID, this.startID, this.testSetSize) === false) return new TypeError('you have set a property that only allows number. Please amend.');
     }
 }

 module.exports = Chatbot;<|endoftext|>


<commit_before>//  Copyright 2015 Fabian Dietenberger

"use strict";

var q = require('q'),
    request = require('request'),
    _ = require('lodash');

var hypemResolver = {},
    hypemTrackUrl = "http://hypem.com/track/",
    hypemGoUrl = "http://hypem.com/go/sc/";

hypemResolver.getById = function (hypemId, callback) {
    var url = hypemGoUrl + hypemId;
    var options = {method: "HEAD", followRedirect: false, url: url};
    var testResultUrl = "https://soundcloud.com/griz/summer-97-ft-muzzy-bearr";

    request(options, function (err, response, body) {
        if (err || response.statusCode != 302) {
            callback(err, null);
        } else {
            callback(null, testResultUrl);
        }
    });
};

hypemResolver.getByUrl = function (hypemUrl, callback) {
    var trimmedUrl = _.trim(hypemUrl);
    if (_.startsWith(trimmedUrl, hypemTrackUrl)) { // maybe use url
        var hypemPath = hypemUrl.slice(hypemTrackUrl.length);
        var hypemId = hypemPath.split("/")[0];
        this.getById(hypemId, callback);
    } else {
        callback(new Error("Hypem url is not correct. It should start with 'http://hypem.com/track/'", null));
    }
};

module.exports = hypemResolver;<commit_msg>Simplify request function<commit_after>//  Copyright 2015 Fabian Dietenberger

"use strict";

var q = require('q'),
    request = require('request'),
    _ = require('lodash');

var hypemResolver = {},
    hypemTrackUrl = "http://hypem.com/track/",
    hypemGoUrl = "http://hypem.com/go/sc/";

hypemResolver.getById = function (hypemId, callback) {
    var url = hypemGoUrl + hypemId;
    var options = {method: "HEAD", followRedirect: false, url: url};
    var testResultUrl = "https://soundcloud.com/griz/summer-97-ft-muzzy-bearr";

    request(options, function (err, response) {
        if (err || response.statusCode !== 302) {
            callback(err, null);
        } else {
            callback(null, testResultUrl);
        }
    });
};

hypemResolver.getByUrl = function (hypemUrl, callback) {
    var trimmedUrl = _.trim(hypemUrl);
    if (_.startsWith(trimmedUrl, hypemTrackUrl)) { // maybe use url
        var hypemPath = hypemUrl.slice(hypemTrackUrl.length);
        var hypemId = hypemPath.split("/")[0];
        this.getById(hypemId, callback);
    } else {
        callback(new Error("Hypem url is not correct. It should start with 'http://hypem.com/track/'", null));
    }
};

module.exports = hypemResolver;<|endoftext|>


<commit_before>const Command = require('../Command')
const DiscordServer = require('../../DiscordServer')

async function recursiveUpdate(memberArray, server, msg) {
  let nextMember = memberArray.pop()
  if (!nextMember) {
    return msg.reply(`:white_check_mark: Finished bulk update! ${server.bulkUpdateCount} members affected.`).then(() => {
      server.bulkUpdateCount = 0
      server.ongoingBulkUpdate = false
    })
  }

  if (!nextMember.user.bot) {
    let member = await server.getMember(nextMember.id)
    if (member) {
      let res = await member.verify({ skipWelcomeMessage: true })
      server.bulkUpdateCount++
    }
  }
  return recursiveUpdate(memberArray, server, msg);
}

module.exports =
class UpdateCommand extends Command {
  constructor (client) {
    super(client, {
      name: 'update',
      properName: 'Update',
      aliases: ['roverupdate'],
      description: '`<Discord User>` Forcibly update verification status of a user, same as them running !verify. Make sure you @mention the user.',

      args: [
        {
          key: 'user',
          prompt: 'User to update',
          type: 'user|role'
        }
      ]
    })
  }

  hasPermission (msg) {
    return this.client.isOwner(msg.author) || msg.member.hasPermission(this.userPermissions) || msg.member.roles.find(role => role.name === 'RoVer Admin') || msg.member.roles.find(role => role.name === 'RoVer Updater')
  }

  async fn (msg, args) {
    let user = args.user
    DiscordServer.clearMemberCache(user.id)

    let server = await this.discordBot.getServer(msg.guild.id)
    if (user.hoist === undefined) { // They want to update a specific user (roles have .hoist, users do not)
      let member = await server.getMember(user.id)
      if (!member) {
        return msg.reply('User not in guild.')
      }

      member.verify({ message: msg, skipWelcomeMessage: true })
    } else { // They want to update a whole role (premium feature)
      let roleMembers = user.members.array()
      let affectedCount = roleMembers.length // # of affected users
      let server = await this.discordBot.getServer(msg.guild.id)

      if (server.ongoingBulkUpdate) {
        return msg.reply("There is already an ongoing bulk update in this server.")
      }

      if (affectedCount > 250) {
        return msg.reply(`Sorry, but RoVer only supports updating up to 250 members at once. Updating this role would affect ${affectedCount} members.`)
      }

      server.ongoingBulkUpdate = true
      msg.channel.send(`:hourglass_flowing_sand: Please wait - bulk update for ${affectedCount} members in progress. We'll let you know when it's done.`)

      recursiveUpdate(roleMembers, server, msg)
    }
  }
}
<commit_msg>Fix style<commit_after>const Command = require('../Command')
const DiscordServer = require('../../DiscordServer')

async function recursiveUpdate (memberArray, server, msg) {
  let nextMember = memberArray.pop()
  if (!nextMember) {
    return msg.reply(`:white_check_mark: Finished bulk update! ${server.bulkUpdateCount} members affected.`).then(() => {
      server.bulkUpdateCount = 0
      server.ongoingBulkUpdate = false
    })
  }

  if (!nextMember.user.bot) {
    let member = await server.getMember(nextMember.id)
    if (member) {
      await member.verify({ skipWelcomeMessage: true })
      server.bulkUpdateCount++
    }
  }
  return recursiveUpdate(memberArray, server, msg)
}

module.exports =
class UpdateCommand extends Command {
  constructor (client) {
    super(client, {
      name: 'update',
      properName: 'Update',
      aliases: ['roverupdate'],
      description: '`<Discord User>` Forcibly update verification status of a user, same as them running !verify. Make sure you @mention the user.',

      args: [
        {
          key: 'user',
          prompt: 'User to update',
          type: 'user|role'
        }
      ]
    })
  }

  hasPermission (msg) {
    return this.client.isOwner(msg.author) || msg.member.hasPermission(this.userPermissions) || msg.member.roles.find(role => role.name === 'RoVer Admin') || msg.member.roles.find(role => role.name === 'RoVer Updater')
  }

  async fn (msg, args) {
    let user = args.user
    DiscordServer.clearMemberCache(user.id)

    let server = await this.discordBot.getServer(msg.guild.id)
    if (user.hoist === undefined) { // They want to update a specific user (roles have .hoist, users do not)
      let member = await server.getMember(user.id)
      if (!member) {
        return msg.reply('User not in guild.')
      }

      member.verify({ message: msg, skipWelcomeMessage: true })
    } else { // They want to update a whole role (premium feature)
      let roleMembers = user.members.array()
      let affectedCount = roleMembers.length // # of affected users
      let server = await this.discordBot.getServer(msg.guild.id)

      if (server.ongoingBulkUpdate) {
        return msg.reply('There is already an ongoing bulk update in this server.')
      }

      if (affectedCount > 250) {
        return msg.reply(`Sorry, but RoVer only supports updating up to 250 members at once. Updating this role would affect ${affectedCount} members.`)
      }

      server.ongoingBulkUpdate = true
      msg.channel.send(`:hourglass_flowing_sand: Please wait - bulk update for ${affectedCount} members in progress. We'll let you know when it's done.`)

      recursiveUpdate(roleMembers, server, msg)
    }
  }
}
<|endoftext|>


<commit_before>/* https://github.com/DiemenDesign/summernote-cleaner */
(function(factory) {
  if(typeof define === 'function' && define.amd) {
    define(['jquery'], factory);
  } else if (typeof module === 'object' && module.exports) {
    module.exports = factory(require('jquery'));
  } else {
    factory(window.jQuery);
  }
}
(function($) {
  $.extend(true,$.summernote.lang, {
    'en-US': {
      cleaner: {
        tooltip: 'Cleaner',
        not: 'Text has been Cleaned!!!'
      }
    }
  });
  $.extend($.summernote.options, {
    cleaner: {
      notTime: 2400, // Time to display Notifications.
      action: 'both', // both|button|paste 'button' only cleans via toolbar button, 'paste' only clean when pasting content, both does both options.
      newline: '
', // Summernote's default is to use '

'
      notStyle: 'position:absolute;top:0;left:0;right:0',
      icon: '<svg xmlns="http://www.w3.org/2000/svg" id="libre-paintbrush" viewBox="0 0 14 14" width="14" height="14"><path d="m 11.821425,1 q 0.46875,0 0.82031,0.311384 0.35157,0.311384 0.35157,0.780134 0,0.421875 -0.30134,1.01116 -2.22322,4.212054 -3.11384,5.035715 -0.64956,0.609375 -1.45982,0.609375 -0.84375,0 -1.44978,-0.61942 -0.60603,-0.61942 -0.60603,-1.469866 0,-0.857143 0.61608,-1.419643 l 4.27232,-3.877232 Q 11.345985,1 11.821425,1 z m -6.08705,6.924107 q 0.26116,0.508928 0.71317,0.870536 0.45201,0.361607 1.00781,0.508928 l 0.007,0.475447 q 0.0268,1.426339 -0.86719,2.32366 Q 5.700895,13 4.261155,13 q -0.82366,0 -1.45982,-0.311384 -0.63616,-0.311384 -1.0212,-0.853795 -0.38505,-0.54241 -0.57924,-1.225446 -0.1942,-0.683036 -0.1942,-1.473214 0.0469,0.03348 0.27455,0.200893 0.22768,0.16741 0.41518,0.29799 0.1875,0.130581 0.39509,0.24442 0.20759,0.113839 0.30804,0.113839 0.27455,0 0.3683,-0.247767 0.16741,-0.441965 0.38505,-0.753349 0.21763,-0.311383 0.4654,-0.508928 0.24776,-0.197545 0.58928,-0.31808 0.34152,-0.120536 0.68974,-0.170759 0.34821,-0.05022 0.83705,-0.07031 z"/></svg>',
      keepHtml: true, //Remove all Html formats
      keepOnlyTags: [], // If keepHtml is true, remove all tags except these
      keepClasses: false, //Remove Classes
      badTags: ['style', 'script', 'applet', 'embed', 'noframes', 'noscript', 'html'], //Remove full tags with contents
      badAttributes: ['style', 'start'] //Remove attributes from remaining tags
    }
  });
  $.extend($.summernote.plugins, {
    'cleaner':function(context) {
      var self = this;
      var ui = $.summernote.ui;
      var $note = context.layoutInfo.note;
      var $editor = context.layoutInfo.editor;
      var options = context.options;
      var lang = options.langInfo;
      var cleanText = function(txt, nlO) {
        var out = txt;
        if (!options.cleaner.keepClasses) {
          var sS = /(\n|\r| class=(")?Mso[a-zA-Z]+(")?)/g;
          out = txt.replace(sS, ' ');
        }
        var nL = /(\n)+/g;
        out = out.replace(nL, nlO);
        if (options.cleaner.keepHtml) {
          var cS = new RegExp('', 'gi');
          out = out.replace(cS, '');
          var tS = new RegExp('<(/)*(meta|link|\\?xml:|st1:|o:|font)(.*?)>', 'gi');
          out = out.replace(tS, '');
          var bT = options.cleaner.badTags;
          for (var i = 0; i < bT.length; i++) {
            // suggestion by @LoloDf at #40
            tS=new RegExp('<'+bT[i]+'\\b.*>.*</'+bT[i]+'>','gi');
            out = out.replace(tS, '');
          }
          var allowedTags = options.cleaner.keepOnlyTags;
          if (typeof(allowedTags) == "undefined")
            allowedTags = [];
          if (allowedTags.length > 0) {
            allowedTags = (((allowedTags||'') + '').toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join('');
            var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi;
            out = out.replace(tags,function($0, $1) {
              return allowedTags.indexOf('<' + $1.toLowerCase()+'>') > -1 ? $0 : ''
            });
          }
          var bA = options.cleaner.badAttributes;
          for (var ii = 0; ii < bA.length; ii++ ) {
            //var aS=new RegExp(' ('+bA[ii]+'="(.*?)")|('+bA[ii]+'=\'(.*?)\')','gi');
            var aS = new RegExp(' ' + bA[ii] + '=[\'|"](.*?)[\'|"]', 'gi');
            out = out.replace(aS, '');
          }
        }
        return out;
      };
      if (options.cleaner.action == 'both' || options.cleaner.action == 'button') {
        context.memo('button.cleaner',function() {
          var button = ui.button({
            contents: options.cleaner.icon,
            tooltip: lang.cleaner.tooltip,
            click:function() {
              if ($note.summernote('createRange').toString()) {
                var text = $note.summernote('createRange').toString();
                $note.summernote('pasteHTML', text);
              } else {
                var text = cleanText($note.summernote('code'));
                $note.summernote('code', text);
              }
              if (options.cleaner.notTime > 0) {
                $editor.find('.note-editing-area').append('
' + lang.cleaner.not + '
');
                setTimeout(function(){$editor.find('.summernote-cleanerAlert').remove();},options.cleaner.notTime);
              }
            }
          });
          return button.render();
        });
      }
      this.events = {
        'summernote.paste':function(we,e) {
          if (options.cleaner.action=='both' || options.cleaner.action=='paste') {
            var ua = window.navigator.userAgent;
            var msie = ua.indexOf("MSIE ");
            msie = msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./);
            if (msie) {
              var text = window.clipboardData.getData("Text");
            } else {
              var text = e.originalEvent.clipboardData.getData((options.cleaner.keepHtml ? 'text/html' : 'text/plain'));
            }
            if (text && text!='') {
              e.preventDefault();
              var text=cleanText(text, options.cleaner.newline);
              var pasteFn = function() {
                $note.summernote('pasteHTML', text);
              }
              if (msie) {
                setTimeout(pasteFn, 1);
              } else {
                pasteFn();
              }
              if (options.cleaner.notTime > 0) {
                $editor.find('.note-resizebar').append('
' + lang.cleaner.not + '
');
                setTimeout(function(){$editor.find('.summernote-cleanerAlert').remove();}, options.cleaner.notTime);
              }
            }
          }
        }
      }
    }
  });
}));
<commit_msg>Fixing paste at cursor on Firefox<commit_after>/* https://github.com/DiemenDesign/summernote-cleaner */
(function(factory) {
  if(typeof define === 'function' && define.amd) {
    define(['jquery'], factory);
  } else if (typeof module === 'object' && module.exports) {
    module.exports = factory(require('jquery'));
  } else {
    factory(window.jQuery);
  }
}
(function($) {
  $.extend(true,$.summernote.lang, {
    'en-US': {
      cleaner: {
        tooltip: 'Cleaner',
        not: 'Text has been Cleaned!!!'
      }
    }
  });
  $.extend($.summernote.options, {
    cleaner: {
      notTime: 2400, // Time to display Notifications.
      action: 'both', // both|button|paste 'button' only cleans via toolbar button, 'paste' only clean when pasting content, both does both options.
      newline: '
', // Summernote's default is to use '

'
      notStyle: 'position:absolute;top:0;left:0;right:0',
      icon: '<svg xmlns="http://www.w3.org/2000/svg" id="libre-paintbrush" viewBox="0 0 14 14" width="14" height="14"><path d="m 11.821425,1 q 0.46875,0 0.82031,0.311384 0.35157,0.311384 0.35157,0.780134 0,0.421875 -0.30134,1.01116 -2.22322,4.212054 -3.11384,5.035715 -0.64956,0.609375 -1.45982,0.609375 -0.84375,0 -1.44978,-0.61942 -0.60603,-0.61942 -0.60603,-1.469866 0,-0.857143 0.61608,-1.419643 l 4.27232,-3.877232 Q 11.345985,1 11.821425,1 z m -6.08705,6.924107 q 0.26116,0.508928 0.71317,0.870536 0.45201,0.361607 1.00781,0.508928 l 0.007,0.475447 q 0.0268,1.426339 -0.86719,2.32366 Q 5.700895,13 4.261155,13 q -0.82366,0 -1.45982,-0.311384 -0.63616,-0.311384 -1.0212,-0.853795 -0.38505,-0.54241 -0.57924,-1.225446 -0.1942,-0.683036 -0.1942,-1.473214 0.0469,0.03348 0.27455,0.200893 0.22768,0.16741 0.41518,0.29799 0.1875,0.130581 0.39509,0.24442 0.20759,0.113839 0.30804,0.113839 0.27455,0 0.3683,-0.247767 0.16741,-0.441965 0.38505,-0.753349 0.21763,-0.311383 0.4654,-0.508928 0.24776,-0.197545 0.58928,-0.31808 0.34152,-0.120536 0.68974,-0.170759 0.34821,-0.05022 0.83705,-0.07031 z"/></svg>',
      keepHtml: true, //Remove all Html formats
      keepOnlyTags: [], // If keepHtml is true, remove all tags except these
      keepClasses: false, //Remove Classes
      badTags: ['style', 'script', 'applet', 'embed', 'noframes', 'noscript', 'html'], //Remove full tags with contents
      badAttributes: ['style', 'start'] //Remove attributes from remaining tags
    }
  });
  $.extend($.summernote.plugins, {
    'cleaner':function(context) {
      var self = this;
      var ui = $.summernote.ui;
      var $note = context.layoutInfo.note;
      var $editor = context.layoutInfo.editor;
      var options = context.options;
      var lang = options.langInfo;
      var cleanText = function(txt, nlO) {
        var out = txt;
        if (!options.cleaner.keepClasses) {
          var sS = /(\n|\r| class=(")?Mso[a-zA-Z]+(")?)/g;
          out = txt.replace(sS, ' ');
        }
        var nL = /(\n)+/g;
        out = out.replace(nL, nlO);
        if (options.cleaner.keepHtml) {
          var cS = new RegExp('', 'gi');
          out = out.replace(cS, '');
          var tS = new RegExp('<(/)*(meta|link|\\?xml:|st1:|o:|font)(.*?)>', 'gi');
          out = out.replace(tS, '');
          var bT = options.cleaner.badTags;
          for (var i = 0; i < bT.length; i++) {
            // suggestion by @LoloDf at #40
            tS=new RegExp('<'+bT[i]+'\\b.*>.*</'+bT[i]+'>','gi');
            out = out.replace(tS, '');
          }
          var allowedTags = options.cleaner.keepOnlyTags;
          if (typeof(allowedTags) == "undefined")
            allowedTags = [];
          if (allowedTags.length > 0) {
            allowedTags = (((allowedTags||'') + '').toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join('');
            var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi;
            out = out.replace(tags,function($0, $1) {
              return allowedTags.indexOf('<' + $1.toLowerCase()+'>') > -1 ? $0 : ''
            });
          }
          var bA = options.cleaner.badAttributes;
          for (var ii = 0; ii < bA.length; ii++ ) {
            //var aS=new RegExp(' ('+bA[ii]+'="(.*?)")|('+bA[ii]+'=\'(.*?)\')','gi');
            var aS = new RegExp(' ' + bA[ii] + '=[\'|"](.*?)[\'|"]', 'gi');
            out = out.replace(aS, '');
          }
        }
        return out;
      };
      if (options.cleaner.action == 'both' || options.cleaner.action == 'button') {
        context.memo('button.cleaner',function() {
          var button = ui.button({
            contents: options.cleaner.icon,
            tooltip: lang.cleaner.tooltip,
            click:function() {
              if ($note.summernote('createRange').toString()) {
                var text = $note.summernote('createRange').toString();
                $note.summernote('pasteHTML', text);
              } else {
                var text = cleanText($note.summernote('code'));
                $note.summernote('code', text);
              }
              if (options.cleaner.notTime > 0) {
                $editor.find('.note-editing-area').append('
' + lang.cleaner.not + '
');
                setTimeout(function(){$editor.find('.summernote-cleanerAlert').remove();},options.cleaner.notTime);
              }
            }
          });
          return button.render();
        });
      }
      this.events = {
        'summernote.paste':function(we,e) {
          if (options.cleaner.action=='both' || options.cleaner.action=='paste') {
            var ua = window.navigator.userAgent;
            var msie = ua.indexOf("MSIE ");
            msie = msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./);
            var ffox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
            if (msie) {
              var text = window.clipboardData.getData("Text");
            } else {
              var text = e.originalEvent.clipboardData.getData((options.cleaner.keepHtml ? 'text/html' : 'text/plain'));
            }
            if (text && text!='') {
              e.preventDefault();
              var text=cleanText(text, options.cleaner.newline);
              var pasteFn = function() {
                $note.summernote('pasteHTML', text);
              }
              if (msie || ffox) {
                setTimeout(pasteFn, 1);
              } else {
                pasteFn();
              }
              if (options.cleaner.notTime > 0) {
                $editor.find('.note-resizebar').append('
' + lang.cleaner.not + '
');
                setTimeout(function(){$editor.find('.summernote-cleanerAlert').remove();}, options.cleaner.notTime);
              }
            }
          }
        }
      }
    }
  });
}));
<|endoftext|>


<commit_before>// curry/auto is from wu.js
(function() {
  var toArray = function(x) {
    return Array.prototype.slice.call(x);
  }

  var curry = function (fn /* variadic number of args */) {
         var args = Array.prototype.slice.call(arguments, 1);
         var f = function () {
             return fn.apply(this, args.concat(toArray(arguments)));
         };
         return f;
      };

  var autoCurry = function (fn, numArgs) {
         numArgs = numArgs || fn.length;
         var f = function () {
             if (arguments.length < numArgs) {
                 return numArgs - arguments.length > 0 ?
                     autoCurry(curry.apply(this, [fn].concat(toArray(arguments))),
                                  numArgs - arguments.length) :
                     curry.apply(this, [fn].concat(toArray(arguments)));
             }
             else {
                 return fn.apply(this, arguments);
             }
         };
         f.toString = function(){ return fn.toString(); };
         f.curried = true;
         f.arity = fn.length;
         return f;
     };

     Function.prototype.autoCurry = function(n) {
       return autoCurry(this, n);
     }
})();

// set timeout works for titanium env, which i'm typically in.  Switch with different strategies if needed.
parallel = function(){
	var fns = map(Function.toFunction,arguments)
	, arglen = fns.length;

	return function(x){
		for(var i=arglen;--i>=0;) {
			setTimeout(fns[i].p(x), 100);
		}

		return arguments[0];
	}
}

memoize = function( fn ) {
    return function () {
        var args = Array.prototype.slice.call(arguments),
            hash = "",
            i = args.length;
        currentArg = null;
        while (i--) {
            currentArg = args[i];
            hash += (currentArg === Object(currentArg)) ?
            JSON.stringify(currentArg) : currentArg;
            fn.memoize || (fn.memoize = {});
        }
        return (hash in fn.memoize) ? fn.memoize[hash] :
        fn.memoize[hash] = fn.apply(this, args);
    };
}

compose = function() {
  var fns = map(Function.toFunction,arguments),
      arglen = fns.length;

  return function(){
    for(var i=arglen;--i>=0;) {
      var fn = fns[i]
        , args = fn.length ? Array.prototype.slice.call(arguments, 0, fn.length) : arguments
        , next_args = Array.prototype.slice.call(arguments, (fn.length || 1)); //not right with *args
      next_args.unshift(fn.apply(this,args));
      arguments = next_args;
    }
    return arguments[0];
  }
}

typeof window=='undefined'&&(window={});var Functional=window.Functional||{};Functional.install=function(except){var source=Functional,target=window;for(var name in source)
name=='install'||name.charAt(0)=='_'||except&&name in except||{}[name]||(target[name]=source[name]);}
// compose=function(){var fns=map(Function.toFunction,arguments),arglen=fns.length;return function(){for(var i=arglen;--i>=0;)
// arguments=[fns[i].apply(this,arguments)];return arguments[0];}}
composel=function(){ var args=Array.slice(arguments,1).reverse(); compose.apply(args); }
sequence=function(){var fns=map(Function.toFunction,arguments),arglen=fns.length;return function(){for(var i=0;i<arglen;i++)
arguments=[fns[i].apply(this,arguments)];return arguments[0];}}
map=function(fn,sequence){fn=Function.toFunction(fn);var len=sequence.length,result=new Array(len);for(var i=0;i<len;i++)
result[i]=fn.apply(null,[sequence[i],i]);return result;}.autoCurry();
reduce=function(fn,init,sequence){fn=Function.toFunction(fn);var len=sequence.length,result=init;for(var i=0;i<len;i++)
result=fn.apply(null,[result,sequence[i]]);return result;}.autoCurry();
select=function(fn,sequence){fn=Function.toFunction(fn);var len=sequence.length,result=[];for(var i=0;i<len;i++){var x=sequence[i];fn.apply(null,[x,i])&&result.push(x);}
return result;}.autoCurry();
guard=function(guard,otherwise,fn){fn=Function.toFunction(fn);guard=Function.toFunction(guard||I);otherwise=Function.toFunction(otherwise||I);return function(){return(guard.apply(this,arguments)?fn:otherwise).apply(this,arguments);}}
flip = function(f){return f.flip(); }
filter=select;foldl=reduce;foldr=function(fn,init,sequence){fn=Function.toFunction(fn);var len=sequence.length,result=init;for(var i=len;--i>=0;)
result=fn.apply(null,[sequence[i],result]);return result;}
annd=function(){var args=map(Function.toFunction,arguments),arglen=args.length;return function(){var value=true;for(var i=0;i<arglen;i++)
if(!(value=args[i].apply(this,arguments)))
break;return value;}}
or=function(){var args=map(Function.toFunction,arguments),arglen=args.length;return function(){var value=false;for(var i=0;i<arglen;i++)
if((value=args[i].apply(this,arguments)))
break;return value;}}
some=function(fn,sequence){fn=Function.toFunction(fn);var len=sequence.length,value=false;for(var i=0;i<len;i++)
if((value=fn.call(null,sequence[i])))
break;return value;}.autoCurry();
every=function(fn,sequence){fn=Function.toFunction(fn);var len=sequence.length,value=true;for(var i=0;i<len;i++)
if(!(value=fn.call(null,sequence[i])))
break;return value;}.autoCurry();
not=function(fn){fn=Function.toFunction(fn);return function(){return!fn.apply(null,arguments);}}
equal=function(){var arglen=arguments.length,args=map(Function.toFunction,arguments);if(!arglen)return K(true);return function(){var value=args[0].apply(this,arguments);for(var i=1;i<arglen;i++)
if(value!=args[i].apply(this,args))
return false;return true;}}
lambda=function(object){return object.toFunction();}
invoke=function(methodName){var args=Array.slice(arguments,1);return function(object){return object[methodName].apply(object,Array.slice(arguments,1).concat(args));}}
pluck=function(name){return function(object){return object[name];}}
until=function(pred,fn){fn=Function.toFunction(fn);pred=Function.toFunction(pred);return function(value){while(!pred.call(null,value))
value=fn.call(null,value);return value;}}.autoCurry();
zip=function(){var n=Math.min.apply(null,map('.length',arguments));var results=new Array(n);for(var i=0;i<n;i++){var key=String(i);results[key]=map(pluck(key),arguments);};return results;}
_startRecordingMethodChanges=function(object){var initialMethods={};for(var name in object)
initialMethods[name]=object[name];return{getChangedMethods:function(){var changedMethods={};for(var name in object)
if(object[name]!=initialMethods[name])
changedMethods[name]=object[name];return changedMethods;}};}
_attachMethodDelegates=function(methods){for(var name in methods)
Functional[name]=Functional[name]||(function(name){var fn=methods[name];return function(object){return fn.apply(Function.toFunction(object),Array.slice(arguments,1));}})(name);}
__initalFunctionState=_startRecordingMethodChanges(Function.prototype);Function.prototype.bind=function(object){var fn=this;var args=Array.slice(arguments,1);return function(){return fn.apply(object,args.concat(Array.slice(arguments,0)));}}
Function.prototype.saturate=function(){var fn=this;var args=Array.slice(arguments,0);return function(){return fn.apply(this,args);}}
Function.prototype.aritize=function(n){var fn=this;return function(){return fn.apply(this,Array.slice(arguments,0,n));}}
Function.prototype.curry=function(){var fn=this;var args=Array.slice(arguments,0);return function(){return fn.apply(this,args.concat(Array.slice(arguments,0)));};}
Function.prototype.rcurry=function(){var fn=this;var args=Array.slice(arguments,0);return function(){return fn.apply(this,Array.slice(arguments,0).concat(args));};}
Function.prototype.ncurry=function(n){var fn=this;var largs=Array.slice(arguments,1);return function(){var args=largs.concat(Array.slice(arguments,0));if(args.length<n){args.unshift(n);return fn.ncurry.apply(fn,args);}
return fn.apply(this,args);};}
Function.prototype.rncurry=function(n){var fn=this;var rargs=Array.slice(arguments,1);return function(){var args=Array.slice(arguments,0).concat(rargs);if(args.length<n){args.unshift(n);return fn.rncurry.apply(fn,args);}
return fn.apply(this,args);};}
_=Function._={};Function.prototype.partial=function(){var fn=this;var _=Function._;var args=Array.slice(arguments,0);var subpos=[],value;for(var i=0;i<arguments.length;i++)
arguments[i]==_&&subpos.push(i);return function(){var specialized=args.concat(Array.slice(arguments,subpos.length));for(var i=0;i<Math.min(subpos.length,arguments.length);i++)
specialized[subpos[i]]=arguments[i];for(var i=0;i<specialized.length;i++)
if(specialized[i]==_)
return fn.partial.apply(fn,specialized);return fn.apply(this,specialized);}}
Function.prototype.p = Function.prototype.partial; // alias for ease of use.
I=function(x){return x};K=function(x){return function(){return x}};id=I;constfn=K;S=function(f,g){f=Function.toFunction(f);g=Function.toFunction(g);return function(){return f.apply(this,[g.apply(this,arguments)].concat(Array.slice(arguments,0)));}}
Function.prototype.flip=function(){var fn=this;return function(){var args=Array.slice(arguments,0);args=args.slice(1,2).concat(args.slice(0,1)).concat(args.slice(2));return fn.apply(this,args);}}
Function.prototype.uncurry=function(){var fn=this;return function(){var f1=fn.apply(this,Array.slice(arguments,0,1));return f1.apply(this,Array.slice(arguments,1));}}
Function.prototype.prefilterObject=function(filter){filter=Function.toFunction(filter);var fn=this;return function(){return fn.apply(filter(this),arguments);}}
Function.prototype.prefilterAt=function(index,filter){filter=Function.toFunction(filter);var fn=this;return function(){var args=Array.slice(arguments,0);args[index]=filter.call(this,args[index]);return fn.apply(this,args);}}
Function.prototype.prefilterSlice=function(filter,start,end){filter=Function.toFunction(filter);start=start||0;var fn=this;return function(){var args=Array.slice(arguments,0);var e=end<0?args.length+end:end||args.length;args.splice.apply(args,[start,(e||args.length)-start].concat(filter.apply(this,args.slice(start,e))));return fn.apply(this,args);}}
Function.prototype.compose=function(fn){var self=this;fn=Function.toFunction(fn);return function(){return self.apply(this,[fn.apply(this,arguments)]);}}
Function.prototype.sequence=function(fn){var self=this;fn=Function.toFunction(fn);return function(){return fn.apply(this,[self.apply(this,arguments)]);}}
Function.prototype.guard=function(guard,otherwise){var fn=this;guard=Function.toFunction(guard||I);otherwise=Function.toFunction(otherwise||I);return function(){return(guard.apply(this,arguments)?fn:otherwise).apply(this,arguments);}}
Function.prototype.traced=function(name){var self=this;name=name||self;return function(){window.console&&console.info('[',name,'apply(',this!=window&&this,',',arguments,')');var result=self.apply(this,arguments);window.console&&console.info(']',name,' -> ',result);return result;}}
_attachMethodDelegates(__initalFunctionState.getChangedMethods());delete __initalFunctionState;Function.toFunction=Function.toFunction||K;if(!Array.slice){Array.slice=(function(slice){return function(object){return slice.apply(object,slice.call(arguments,1));};})(Array.prototype.slice);}
String.prototype.lambda=function(){var params=[],expr=this,sections=expr.ECMAsplit(/\s*->\s*/m);if(sections.length>1){while(sections.length){expr=sections.pop();params=sections.pop().split(/\s*,\s*|\s+/m);sections.length&&sections.push('(function('+params+'){return ('+expr+')})');}}else if(expr.match(/\b_\b/)){params='_';}else{var leftSection=expr.match(/^\s*(?:[+*\/%&|\^\.=<>]|!=)/m),rightSection=expr.match(/[+\-*\/%&|\^\.=<>!]\s*$/m);if(leftSection||rightSection){if(leftSection){params.push('$1');expr='$1'+expr;}
if(rightSection){params.push('$2');expr=expr+'$2';}}else{var vars=this.replace(/(?:\b[A-Z]|\.[a-zA-Z_$])[a-zA-Z_$\d]*|[a-zA-Z_$][a-zA-Z_$\d]*\s*:|this|arguments|'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"/g,'').match(/([a-z_$][a-z_$\d]*)/gi)||[];for(var i=0,v;v=vars[i++];)
params.indexOf(v)>=0||params.push(v);}}
return new Function(params,'return ('+expr+')');}
String.prototype.lambda.cache=function(){var proto=String.prototype,cache={},uncached=proto.lambda,cached=function(){var key='#'+this;return cache[key]||(cache[key]=uncached.call(this));};cached.cached=function(){};cached.uncache=function(){proto.lambda=uncached};proto.lambda=cached;}
String.prototype.apply=function(thisArg,args){return this.toFunction().apply(thisArg,args);}
String.prototype.call=function(){return this.toFunction().apply(arguments[0],Array.prototype.slice.call(arguments,1));}
String.prototype.toFunction=function(){var body=this;if(body.match(/\breturn\b/))
return new Function(this);return this.lambda();}
Function.prototype.toFunction=function(){return this;}
Function.toFunction=function(value){return value.toFunction();}
String.prototype.ECMAsplit=('ab'.split(/a*/).length>1?String.prototype.split:function(separator,limit){if(typeof limit!='undefined')
throw"ECMAsplit: limit is unimplemented";var result=this.split.apply(this,arguments),re=RegExp(separator),savedIndex=re.lastIndex,match=re.exec(this);if(match&&match.index==0)
result.unshift('');re.lastIndex=savedIndex;return result;});<commit_msg>kill most of support/functional<commit_after>var toArray = function(x) {
  return Array.prototype.slice.call(x);
}

// curry/auto is from wu.js
(function() {

  var curry = function (fn /* variadic number of args */) {
    var args = Array.prototype.slice.call(arguments, 1);
    var f = function () {
      return fn.apply(this, args.concat(toArray(arguments)));
    };
    return f;
  };

  var autoCurry = function (fn, numArgs) {
    numArgs = numArgs || fn.length;
    var f = function () {
      if (arguments.length < numArgs) {
        return numArgs - arguments.length > 0 ?
          autoCurry(curry.apply(this, [fn].concat(toArray(arguments))), numArgs - arguments.length) :
          curry.apply(this, [fn].concat(toArray(arguments)));
      }
      else {
        return fn.apply(this, arguments);
      }
    };
    f.toString = function(){ return fn.toString(); };
    f.curried = true;
    f.arity = fn.length;
    return f;
  };

  Function.prototype.autoCurry = function(n) {
    return autoCurry(this, n);
  }
})();

compose = function() {
  var fns = toArray(arguments),
      arglen = fns.length;

  return function(){
    for(var i=arglen;--i>=0;) {
      var fn = fns[i]
        , args = fn.length ? Array.prototype.slice.call(arguments, 0, fn.length) : arguments
        , next_args = Array.prototype.slice.call(arguments, (fn.length || 1)); //not right with *args
      next_args.unshift(fn.apply(this,args));
      arguments = next_args;
    }
    return arguments[0];
  }
}
<|endoftext|>