<commit_before>var w = 1600;
var h = 800;

var svg = d3.selectAll(".svg")
    //.selectAll("svg")
    .append("svg")
    .attr("width", w)
    .attr("height", h)
    .attr("class", "svg");

// http://codepen.io/anon/pen/azLvWR

var taskArray = [
    {
        task: "conceptualize",
        type: "development",
        startTime: "2013-1-28", //year/month/day
        endTime: "2013-2-1",
        details: "This actually didn't take any conceptualization"
    },

    {
        task: "sketch",
        type: "development",
        startTime: "2013-2-1",
        endTime: "2013-2-6",
        details: "No sketching either, really"
    },

    {
        task: "color profiles",
        type: "development",
        startTime: "2013-2-6",
        endTime: "2013-2-9"
    },

    {
        task: "HTML",
        type: "coding",
        startTime: "2013-2-2",
        endTime: "2013-2-6",
        details: "all three lines of it"
    },

    {
        task: "write the JS",
        type: "coding",
        startTime: "2013-2-6",
        endTime: "2013-2-9"
    },

    {
        task: "advertise",
        type: "promotion",
        startTime: "2013-2-9",
        endTime: "2013-2-12",
        details: "This counts, right?"
    },

    {
        task: "spam links",
        type: "promotion",
        startTime: "2013-2-12",
        endTime: "2013-2-14"
    },
    {
        task: "eat",
        type: "celebration",
        startTime: "2013-2-8",
        endTime: "2013-2-13",
        details: "All the things"
    },

    {
        task: "crying",
        type: "development",
        startTime: "2013-2-13",
        endTime: "2013-2-16"
    },

];

var dateFormat = d3.time.format("%Y-%m-%d");

var timeScale = d3.time.scale()
    .domain([d3.min(taskArray, function(d) {return dateFormat.parse(d.startTime);}),
        d3.max(taskArray, function(d) {return dateFormat.parse(d.endTime);})])
    .range([0,w-150]);

var categories = [];

for (var i = 0; i < taskArray.length; i++){
    categories.push(taskArray[i].type);
}

var catsUnfiltered = categories; //for vert labels

categories = checkUnique(categories);

makeGant(taskArray, w, h);

var title = svg.append("text")
    .text("Gantt Chart Process")
    .attr("x", w/2)
    .attr("y", 25)
    .attr("text-anchor", "middle")
    .attr("font-size", 18)
    .attr("fill", "#009FFC");

function makeGant(tasks, pageWidth, pageHeight){

    var barHeight = 20;
    var gap = barHeight + 4;
    var topPadding = 75;
    var sidePadding = 75;

    var colorScale = d3.scale.linear()
        .domain([0, categories.length])
        .range(["#00B9FA", "#F95002"])
        .interpolate(d3.interpolateHcl);

    makeGrid(sidePadding, topPadding, pageWidth, pageHeight);
    drawRects(tasks, gap, topPadding, sidePadding, barHeight, colorScale, pageWidth, pageHeight);
    vertLabels(gap, topPadding, sidePadding, barHeight, colorScale);

}

function drawRects(theArray, theGap, theTopPad, theSidePad, theBarHeight, theColorScale, w, h){

    var bigRects = svg.append("g")
        .selectAll("rect")
        .data(theArray)
        .enter()
        .append("rect")
        .attr("x", 0)
        .attr("y", function(d, i){
            return i*theGap + theTopPad - 2;
        })
        .attr("width", function(d){
            return w-theSidePad/2;
        })
        .attr("height", theGap)
        .attr("stroke", "none")
        .attr("fill", function(d){
            for (var i = 0; i < categories.length; i++){
                if (d.type == categories[i]){
                    return d3.rgb(theColorScale(i));
                }
            }
        })
        .attr("opacity", 0.2);

    var rectangles = svg.append('g')
        .selectAll("rect")
        .data(theArray)
        .enter();

    var innerRects = rectangles.append("rect")
        .attr("rx", 3)
        .attr("ry", 3)
        .attr("x", function(d){
            return timeScale(dateFormat.parse(d.startTime)) + theSidePad;
        })
        .attr("y", function(d, i){
            return i*theGap + theTopPad;
        })
        .attr("width", function(d){
            return (timeScale(dateFormat.parse(d.endTime))-timeScale(dateFormat.parse(d.startTime)));
        })
        .attr("height", theBarHeight)
        .attr("stroke", "none")
        .attr("fill", function(d){
            for (var i = 0; i < categories.length; i++){
                if (d.type == categories[i]){
                    return d3.rgb(theColorScale(i));
                }
            }
        });

    var rectText = rectangles.append("text")
        .text(function(d){
            return d.task;
        })
        .attr("x", function(d){
            return (timeScale(dateFormat.parse(d.endTime))-timeScale(dateFormat.parse(d.startTime)))/2 + timeScale(dateFormat.parse(d.startTime)) + theSidePad;
        })
        .attr("y", function(d, i){
            return i*theGap + 14+ theTopPad;
        })
        .attr("font-size", 11)
        .attr("text-anchor", "middle")
        .attr("text-height", theBarHeight)
        .attr("fill", "#fff");

    rectText.on('mouseover', function(e) {
        // console.log(this.x.animVal.getItem(this));
        var tag = "";

        if (typeof d3.select(this).data()[0].details !== 'undefined'){
            tag = "Task: " + d3.select(this).data()[0].task + "
" +
            "Type: " + d3.select(this).data()[0].type + "
" +
            "Starts: " + d3.select(this).data()[0].startTime + "
" +
            "Ends: " + d3.select(this).data()[0].endTime + "
" +
            "Details: " + d3.select(this).data()[0].details;
        } else {
            tag = "Task: " + d3.select(this).data()[0].task + "
" +
            "Type: " + d3.select(this).data()[0].type + "
" +
            "Starts: " + d3.select(this).data()[0].startTime + "
" +
            "Ends: " + d3.select(this).data()[0].endTime;
        }
        var output = document.getElementById("tag");

        var x = this.x.animVal.getItem(this) + "px";
        var y = this.y.animVal.getItem(this) + 25 + "px";

        output.innerHTML = tag;
        output.style.top = y;
        output.style.left = x;
        output.style.display = "block";
    }).on('mouseout', function() {
        var output = document.getElementById("tag");
        output.style.display = "none";
    });

    innerRects.on('mouseover', function(e) {
        //console.log(this);
        var tag = "";

        if (typeof d3.select(this).data()[0].details !== 'undefined'){
            tag = "Task: " + d3.select(this).data()[0].task + "
" +
            "Type: " + d3.select(this).data()[0].type + "
" +
            "Starts: " + d3.select(this).data()[0].startTime + "
" +
            "Ends: " + d3.select(this).data()[0].endTime + "
" +
            "Details: " + d3.select(this).data()[0].details;
        } else {
            tag = "Task: " + d3.select(this).data()[0].task + "
" +
            "Type: " + d3.select(this).data()[0].type + "
" +
            "Starts: " + d3.select(this).data()[0].startTime + "
" +
            "Ends: " + d3.select(this).data()[0].endTime;
        }
        var output = document.getElementById("tag");

        var x = (this.x.animVal.value + this.width.animVal.value/2) + "px";
        var y = this.y.animVal.value + 25 + "px";

        output.innerHTML = tag;
        output.style.top = y;
        output.style.left = x;
        output.style.display = "block";
    }).on('mouseout', function() {
        var output = document.getElementById("tag");
        output.style.display = "none";

    });

}

function makeGrid(theSidePad, theTopPad, w, h){

    var xAxis = d3.svg.axis()
        .scale(timeScale)
        .orient('bottom')
        .ticks(d3.time.weeks, 5)
        .tickSize(-h+theTopPad+20, 0, 0)
        .tickFormat(d3.time.format('%d %b'));

    var grid = svg.append('g')
        .attr('class', 'grid')
        .attr('transform', 'translate(' +theSidePad + ', ' + (h - 50) + ')')
        .call(xAxis)
        .selectAll("text")
        .style("text-anchor", "middle")
        .attr("fill", "#000")
        .attr("stroke", "none")
        .attr("font-size", 10)
        .attr("dy", "1em");
}

function vertLabels(theGap, theTopPad, theSidePad, theBarHeight, theColorScale){
    var numOccurances = [];
    var prevGap = 0;

    for (var i = 0; i < categories.length; i++){
        numOccurances[i] = [categories[i], getCount(categories[i], catsUnfiltered)];
    }

    var axisText = svg.append("g") //without doing this, impossible to put grid lines behind text
        .selectAll("text")
        .data(numOccurances)
        .enter()
        .append("text")
        .text(function(d){
            return d[0];
        })
        .attr("x", 10)
        .attr("y", function(d, i){
            if (i > 0){
                for (var j = 0; j < i; j++){
                    prevGap += numOccurances[i-1][1];
                    // console.log(prevGap);
                    return d[1]*theGap/2 + prevGap*theGap + theTopPad;
                }
            } else{
                return d[1]*theGap/2 + theTopPad;
            }
        })
        .attr("font-size", 11)
        .attr("text-anchor", "start")
        .attr("text-height", 14)
        .attr("fill", function(d){
            for (var i = 0; i < categories.length; i++){
                if (d[0] == categories[i]){
                    //  console.log("true!");
                    return d3.rgb(theColorScale(i)).darker();
                }
            }
        });

}

//from this stackexchange question: http://stackoverflow.com/questions/1890203/unique-for-arrays-in-javascript
function checkUnique(arr) {
    var hash = {}, result = [];
    for ( var i = 0, l = arr.length; i < l; ++i ) {
        if ( !hash.hasOwnProperty(arr[i]) ) { //it works with objects! in FF, at least
            hash[ arr[i] ] = true;
            result.push(arr[i]);
        }
    }
    return result;
}

//from this stackexchange question: http://stackoverflow.com/questions/14227981/count-how-many-strings-in-an-array-have-duplicates-in-the-same-array
function getCounts(arr) {
    var i = arr.length, // var to loop over
        obj = {}; // obj to store results
    while (i) obj[arr[--i]] = (obj[arr[i]] || 0) + 1; // count occurrences
    return obj;
}

// get specific from everything
function getCount(word, arr) {
    return getCounts(arr)[word] || 0;
}<commit_msg>First rendering draft<commit_after>var gantt = require('./parser/gantt').parser;
gantt.yy = require('./ganttDb');
var d3 = require('./d3');

module.exports.draw = function (text, id) {
    gantt.yy.clear();
    gantt.parse(text);
    console.log(gantt.yy.getTasks());
    var w = 1200;
    var h = 400;

    var svg = d3.select('#'+id)
        .attr("width", w)
        .attr("height", h);
    /*var svg = d3.selectAll(".svg")
        //.selectAll("svg")
        .append("svg")
        .attr("width", w)
        .attr("height", h)
        .attr("class", "svg");*/

// http://codepen.io/anon/pen/azLvWR

    var taskArray = gantt.yy.getTasks();

    var dateFormat = d3.time.format("%Y-%m-%d");

    // Set timescale
    var timeScale = d3.time.scale()
        .domain([d3.min(taskArray, function (d) {
            return dateFormat.parse(d.startTime);
        }),
            d3.max(taskArray, function (d) {
                return dateFormat.parse(d.endTime);
            })])
        .range([0, w - 150]);

    var categories = [];

    for (var i = 0; i < taskArray.length; i++) {
        categories.push(taskArray[i].type);
    }

    var catsUnfiltered = categories; //for vert labels

    categories = checkUnique(categories);

    makeGant(taskArray, w, h);

    var title = svg.append("text")
        .text(gantt.yy.getTitle())
        .attr("x", w / 2)
        .attr("y", 25)
        .attr("text-anchor", "middle")
        .attr("font-size", 18)
        .attr("fill", "#009FFC");

    function makeGant(tasks, pageWidth, pageHeight) {

        var barHeight = 20;
        var gap = barHeight + 4;
        var topPadding = 75;
        var sidePadding = 75;

        var colorScale = d3.scale.linear()
            .domain([0, categories.length])
            .range(["#00B9FA", "#F95002"])
            .interpolate(d3.interpolateHcl);

        makeGrid(sidePadding, topPadding, pageWidth, pageHeight);
        drawRects(tasks, gap, topPadding, sidePadding, barHeight, colorScale, pageWidth, pageHeight);
        vertLabels(gap, topPadding, sidePadding, barHeight, colorScale);

    }

    function drawRects(theArray, theGap, theTopPad, theSidePad, theBarHeight, theColorScale, w, h) {

        var bigRects = svg.append("g")
            .selectAll("rect")
            .data(theArray)
            .enter()
            .append("rect")
            .attr("x", 0)
            .attr("y", function (d, i) {
                return i * theGap + theTopPad - 2;
            })
            .attr("width", function (d) {
                return w - theSidePad / 2;
            })
            .attr("height", theGap)
            .attr("stroke", "none")
            .attr("fill", function (d) {
                for (var i = 0; i < categories.length; i++) {
                    if (d.type == categories[i]) {
                        return d3.rgb(theColorScale(i));
                    }
                }
            })
            .attr("opacity", 0.2);

        var rectangles = svg.append('g')
            .selectAll("rect")
            .data(theArray)
            .enter();

        var innerRects = rectangles.append("rect")
            .attr("rx", 3)
            .attr("ry", 3)
            .attr("x", function (d) {
                return timeScale(dateFormat.parse(d.startTime)) + theSidePad;
            })
            .attr("y", function (d, i) {
                return i * theGap + theTopPad;
            })
            .attr("width", function (d) {
                return (timeScale(dateFormat.parse(d.endTime)) - timeScale(dateFormat.parse(d.startTime)));
            })
            .attr("height", theBarHeight)
            .attr("stroke", "none")
            .attr("fill", function (d) {
                for (var i = 0; i < categories.length; i++) {
                    if (d.type == categories[i]) {
                        return d3.rgb(theColorScale(i));
                    }
                }
            });

        var rectText = rectangles.append("text")
            .text(function (d) {
                return d.task;
            })
            .attr("x", function (d) {
                return (timeScale(dateFormat.parse(d.endTime)) - timeScale(dateFormat.parse(d.startTime))) / 2 + timeScale(dateFormat.parse(d.startTime)) + theSidePad;
            })
            .attr("y", function (d, i) {
                return i * theGap + 14 + theTopPad;
            })
            .attr("font-size", 11)
            .attr("text-anchor", "middle")
            .attr("text-height", theBarHeight)
            .attr("fill", "#fff");

        rectText.on('mouseover', function (e) {
            // console.log(this.x.animVal.getItem(this));
            var tag = "";

            if (typeof d3.select(this).data()[0].details !== 'undefined') {
                tag = "Task: " + d3.select(this).data()[0].task + "
" +
                "Type: " + d3.select(this).data()[0].type + "
" +
                "Starts: " + d3.select(this).data()[0].startTime + "
" +
                "Ends: " + d3.select(this).data()[0].endTime + "
" +
                "Details: " + d3.select(this).data()[0].details;
            } else {
                tag = "Task: " + d3.select(this).data()[0].task + "
" +
                "Type: " + d3.select(this).data()[0].type + "
" +
                "Starts: " + d3.select(this).data()[0].startTime + "
" +
                "Ends: " + d3.select(this).data()[0].endTime;
            }
            var output = document.getElementById("tag");

            var x = this.x.animVal.getItem(this) + "px";
            var y = this.y.animVal.getItem(this) + 25 + "px";

            output.innerHTML = tag;
            output.style.top = y;
            output.style.left = x;
            output.style.display = "block";
        }).on('mouseout', function () {
            var output = document.getElementById("tag");
            output.style.display = "none";
        });

        innerRects.on('mouseover', function (e) {
            //console.log(this);
            var tag = "";

            if (typeof d3.select(this).data()[0].details !== 'undefined') {
                tag = "Task: " + d3.select(this).data()[0].task + "
" +
                "Type: " + d3.select(this).data()[0].type + "
" +
                "Starts: " + d3.select(this).data()[0].startTime + "
" +
                "Ends: " + d3.select(this).data()[0].endTime + "
" +
                "Details: " + d3.select(this).data()[0].details;
            } else {
                tag = "Task: " + d3.select(this).data()[0].task + "
" +
                "Type: " + d3.select(this).data()[0].type + "
" +
                "Starts: " + d3.select(this).data()[0].startTime + "
" +
                "Ends: " + d3.select(this).data()[0].endTime;
            }
            var output = document.getElementById("tag");

            var x = (this.x.animVal.value + this.width.animVal.value / 2) + "px";
            var y = this.y.animVal.value + 25 + "px";

            output.innerHTML = tag;
            output.style.top = y;
            output.style.left = x;
            output.style.display = "block";
        }).on('mouseout', function () {
            var output = document.getElementById("tag");
            output.style.display = "none";

        });

    }

    function makeGrid(theSidePad, theTopPad, w, h) {

        var xAxis = d3.svg.axis()
            .scale(timeScale)
            .orient('bottom')
            .ticks(d3.time.weeks, 5)
            .tickSize(-h + theTopPad + 20, 0, 0)
            .tickFormat(d3.time.format('%d %b'));

        var grid = svg.append('g')
            .attr('class', 'grid')
            .attr('transform', 'translate(' + theSidePad + ', ' + (h - 50) + ')')
            .call(xAxis)
            .selectAll("text")
            .style("text-anchor", "middle")
            .attr("fill", "#000")
            .attr("stroke", "none")
            .attr("font-size", 10)
            .attr("dy", "1em");
    }

    function vertLabels(theGap, theTopPad, theSidePad, theBarHeight, theColorScale) {
        var numOccurances = [];
        var prevGap = 0;

        for (var i = 0; i < categories.length; i++) {
            numOccurances[i] = [categories[i], getCount(categories[i], catsUnfiltered)];
        }

        var axisText = svg.append("g") //without doing this, impossible to put grid lines behind text
            .selectAll("text")
            .data(numOccurances)
            .enter()
            .append("text")
            .text(function (d) {
                return d[0];
            })
            .attr("x", 10)
            .attr("y", function (d, i) {
                if (i > 0) {
                    for (var j = 0; j < i; j++) {
                        prevGap += numOccurances[i - 1][1];
                        // console.log(prevGap);
                        return d[1] * theGap / 2 + prevGap * theGap + theTopPad;
                    }
                } else {
                    return d[1] * theGap / 2 + theTopPad;
                }
            })
            .attr("font-size", 11)
            .attr("text-anchor", "start")
            .attr("text-height", 14)
            .attr("fill", function (d) {
                for (var i = 0; i < categories.length; i++) {
                    if (d[0] == categories[i]) {
                        //  console.log("true!");
                        return d3.rgb(theColorScale(i)).darker();
                    }
                }
            });

    }

//from this stackexchange question: http://stackoverflow.com/questions/1890203/unique-for-arrays-in-javascript
    function checkUnique(arr) {
        var hash = {}, result = [];
        for (var i = 0, l = arr.length; i < l; ++i) {
            if (!hash.hasOwnProperty(arr[i])) { //it works with objects! in FF, at least
                hash[arr[i]] = true;
                result.push(arr[i]);
            }
        }
        return result;
    }

//from this stackexchange question: http://stackoverflow.com/questions/14227981/count-how-many-strings-in-an-array-have-duplicates-in-the-same-array
    function getCounts(arr) {
        var i = arr.length, // var to loop over
            obj = {}; // obj to store results
        while (i) obj[arr[--i]] = (obj[arr[i]] || 0) + 1; // count occurrences
        return obj;
    }

// get specific from everything
    function getCount(word, arr) {
        return getCounts(arr)[word] || 0;
    }
};<|endoftext|>


<commit_before>import _ from 'lodash';

class PostDetailsCtrl {
    constructor($scope, DateTime, PostNotifications, Hosts, Subreddits, $timeout, $state) {
        this.DateTime = DateTime;
        this.PostNotifications = PostNotifications;
        this.Subreddits = Subreddits;
        this.Hosts = Hosts;
        this.$timeout = $timeout;
        this.$scope = $scope;
        this.$state = $state;

        this.addressOverride = false;
    }

    goToPost() {
        this.$state.go('app.post', { id: this.post.id });
    }

    timePostedInAdvance() {
        return this.post.posted.from(this.post.opens, true) + ' in advance';
    }

    teamStyle() {
        return this.post.teams + (this.post.teamSize ? ' To' + this.post.teamSize : '');
    }

    showSubreddit() {
        return this.Subreddits.subreddits.length > 1;
    }

    openingTime() {
        return this.DateTime.format('POST_HEADER', this.post.opens);
    }

    openingTimeRelative() {
        return this.post.opens.from(this.DateTime.getTime()) || 'Unknown';
    }

    toggleFavourite(event) {
        event.preventDefault();
        event.stopPropagation();
        return this.Hosts.toggleFavouriteHost(this.post.author);
    }

    toggleNotification(event) {
        event.preventDefault();
        event.stopPropagation();
        this.PostNotifications.toggleNotifications(this.post.id);
    }

    isNotifying() {
        return this.PostNotifications.isNotifyingFor(this.post.id);
    }

    setAddressOverride(override) {
        this.addressOverride = override;
        this.$scope.$broadcast('regionCopyChange');
    }

    isFavouriteHost() {
        return this.Hosts.isFavouriteHost(this.post.author);
    }

    triggerCopiedMessage() {
        if (_.isEmpty(this.post.address)) {
            return;
        }

        // Toggle copied message on
        this.setAddressOverride('Copied!');

        // Toggle back after 2 seconds
        this.$timeout(() => this.setAddressOverride(false), 2000);
    }
}
PostDetailsCtrl.$inject = ['$scope', 'DateTime', 'PostNotifications', 'Hosts', 'Subreddits', '$timeout', '$state'];

function postDetails() {
    return {
        restrict: 'E',
        scope: {
            post: '='
        },
        template: require('./template.html'),
        controller: PostDetailsCtrl,
        controllerAs: 'details',
        bindToController: true
    };
}
postDetails.$inject = ['DateTime', 'PostNotifications', 'Hosts', 'Subreddits', '$timeout'];

export default postDetails;
<commit_msg>fix(postDetails): remove redundant inject<commit_after>import _ from 'lodash';

class PostDetailsCtrl {
    constructor($scope, DateTime, PostNotifications, Hosts, Subreddits, $timeout, $state) {
        this.DateTime = DateTime;
        this.PostNotifications = PostNotifications;
        this.Subreddits = Subreddits;
        this.Hosts = Hosts;
        this.$timeout = $timeout;
        this.$scope = $scope;
        this.$state = $state;

        this.addressOverride = false;
    }

    goToPost() {
        this.$state.go('app.post', { id: this.post.id });
    }

    timePostedInAdvance() {
        return this.post.posted.from(this.post.opens, true) + ' in advance';
    }

    teamStyle() {
        return this.post.teams + (this.post.teamSize ? ' To' + this.post.teamSize : '');
    }

    showSubreddit() {
        return this.Subreddits.subreddits.length > 1;
    }

    openingTime() {
        return this.DateTime.format('POST_HEADER', this.post.opens);
    }

    openingTimeRelative() {
        return this.post.opens.from(this.DateTime.getTime()) || 'Unknown';
    }

    toggleFavourite(event) {
        event.preventDefault();
        event.stopPropagation();
        return this.Hosts.toggleFavouriteHost(this.post.author);
    }

    toggleNotification(event) {
        event.preventDefault();
        event.stopPropagation();
        this.PostNotifications.toggleNotifications(this.post.id);
    }

    isNotifying() {
        return this.PostNotifications.isNotifyingFor(this.post.id);
    }

    setAddressOverride(override) {
        this.addressOverride = override;
        this.$scope.$broadcast('regionCopyChange');
    }

    isFavouriteHost() {
        return this.Hosts.isFavouriteHost(this.post.author);
    }

    triggerCopiedMessage() {
        if (_.isEmpty(this.post.address)) {
            return;
        }

        // Toggle copied message on
        this.setAddressOverride('Copied!');

        // Toggle back after 2 seconds
        this.$timeout(() => this.setAddressOverride(false), 2000);
    }
}
PostDetailsCtrl.$inject = ['$scope', 'DateTime', 'PostNotifications', 'Hosts', 'Subreddits', '$timeout', '$state'];

function postDetails() {
    return {
        restrict: 'E',
        scope: {
            post: '='
        },
        template: require('./template.html'),
        controller: PostDetailsCtrl,
        controllerAs: 'details',
        bindToController: true
    };
}

export default postDetails;
<|endoftext|>


<commit_before>const actions = {
  bold: {
    icon: 'B',
    title: 'Bold',
    result: () => exec('bold')
  },
  italic: {
    icon: 'I',
    title: 'Italic',
    result: () => exec('italic')
  },
  underline: {
    icon: 'U',
    title: 'Underline',
    result: () => exec('underline')
  },
  strikethrough: {
    icon: 'S',
    title: 'Strike-through',
    result: () => exec('strikeThrough')
  },
  heading1: {
    icon: 'H1',
    title: 'Heading 1',
    result: () => exec('formatBlock', '
')
  },
  heading2: {
    icon: 'H2',
    title: 'Heading 2',
    result: () => exec('formatBlock', '
')
  },
  paragraph: {
    icon: '¶',
    title: 'Paragraph',
    result: () => exec('formatBlock', '
')
  },
  quote: {
    icon: '“ ”',
    title: 'Quote',
    result: () => exec('formatBlock', '
')
  },
  olist: {
    icon: '#',
    title: 'Ordered List',
    result: () => exec('insertOrderedList')
  },
  ulist: {
    icon: '•',
    title: 'Unordered List',
    result: () => exec('insertUnorderedList')
  },
  code: {
    icon: '</>',
    title: 'Code',
    result: () => exec('formatBlock', '
')
  },
  line: {
    icon: '―',
    title: 'Horizontal Line',
    result: () => exec('insertHorizontalRule')
  },
  link: {
    icon: '🔗',
    title: 'Link',
    result: () => {
      const url = window.prompt('Enter the link URL')
      if (url) exec('createLink', url)
    }
  },
  image: {
    icon: '📷',
    title: 'Image',
    result: () => {
      const url = window.prompt('Enter the image URL')
      if (url) exec('insertImage', url)
    }
  }
}

const classes = {
  actionbar: 'pell-actionbar',
  button: 'pell-button',
  content: 'pell-content'
}

export const exec = (command, value = null) => {
  document.execCommand(command, false, value)
}

const preventTab = event => {
  if (event.which === 9) event.preventDefault()
}

export const init = settings => {
  settings.actions = settings.actions
    ? settings.actions.map(action => {
      if (typeof action === 'string') return actions[action]
      else if (actions[action.name]) return { ...actions[action.name], ...action }
      return action
    })
    : Object.keys(actions).map(action => actions[action])

  settings.classes = { ...classes, ...settings.classes }

  const actionbar = document.createElement('div')
  actionbar.className = settings.classes.actionbar
  settings.element.appendChild(actionbar)

  settings.element.content = document.createElement('div')
  settings.element.content.contentEditable = true
  settings.element.content.className = settings.classes.content
  settings.element.content.oninput = event => settings.onChange(event.target.innerHTML)
  settings.element.content.onkeydown = preventTab
  settings.element.appendChild(settings.element.content)

  settings.actions.forEach(action => {
    const button = document.createElement('button')
    button.className = settings.classes.button
    button.innerHTML = action.icon
    button.title = action.title
    button.setAttribute('type', 'button')
    button.onclick = action.result
    actionbar.appendChild(button)
  })

  if (settings.styleWithCSS) exec('styleWithCSS')

  return settings.element
}

export default { exec, init }
<commit_msg>Generate action items before attaching actionbar.<commit_after>const actions = {
  bold: {
    icon: 'B',
    title: 'Bold',
    result: () => exec('bold')
  },
  italic: {
    icon: 'I',
    title: 'Italic',
    result: () => exec('italic')
  },
  underline: {
    icon: 'U',
    title: 'Underline',
    result: () => exec('underline')
  },
  strikethrough: {
    icon: 'S',
    title: 'Strike-through',
    result: () => exec('strikeThrough')
  },
  heading1: {
    icon: 'H1',
    title: 'Heading 1',
    result: () => exec('formatBlock', '
')
  },
  heading2: {
    icon: 'H2',
    title: 'Heading 2',
    result: () => exec('formatBlock', '
')
  },
  paragraph: {
    icon: '¶',
    title: 'Paragraph',
    result: () => exec('formatBlock', '
')
  },
  quote: {
    icon: '“ ”',
    title: 'Quote',
    result: () => exec('formatBlock', '
')
  },
  olist: {
    icon: '#',
    title: 'Ordered List',
    result: () => exec('insertOrderedList')
  },
  ulist: {
    icon: '•',
    title: 'Unordered List',
    result: () => exec('insertUnorderedList')
  },
  code: {
    icon: '</>',
    title: 'Code',
    result: () => exec('formatBlock', '
')
  },
  line: {
    icon: '―',
    title: 'Horizontal Line',
    result: () => exec('insertHorizontalRule')
  },
  link: {
    icon: '🔗',
    title: 'Link',
    result: () => {
      const url = window.prompt('Enter the link URL')
      if (url) exec('createLink', url)
    }
  },
  image: {
    icon: '📷',
    title: 'Image',
    result: () => {
      const url = window.prompt('Enter the image URL')
      if (url) exec('insertImage', url)
    }
  }
}

const classes = {
  actionbar: 'pell-actionbar',
  button: 'pell-button',
  content: 'pell-content'
}

export const exec = (command, value = null) => {
  document.execCommand(command, false, value)
}

const preventTab = event => {
  if (event.which === 9) event.preventDefault()
}

export const init = settings => {
  settings.actions = settings.actions
    ? settings.actions.map(action => {
      if (typeof action === 'string') return actions[action]
      else if (actions[action.name]) return { ...actions[action.name], ...action }
      return action
    })
    : Object.keys(actions).map(action => actions[action])

  settings.classes = { ...classes, ...settings.classes }

  const actionbar = document.createElement('div')
  actionbar.className = settings.classes.actionbar
  settings.actions.forEach(action => {
    const button = document.createElement('button')
    button.className = settings.classes.button
    button.innerHTML = action.icon
    button.title = action.title
    button.setAttribute('type', 'button')
    button.onclick = action.result
    actionbar.appendChild(button)
  })
  settings.element.appendChild(actionbar)

  settings.element.content = document.createElement('div')
  settings.element.content.contentEditable = true
  settings.element.content.className = settings.classes.content
  settings.element.content.oninput = event => settings.onChange(event.target.innerHTML)
  settings.element.content.onkeydown = preventTab
  settings.element.appendChild(settings.element.content)

  if (settings.styleWithCSS) exec('styleWithCSS')

  return settings.element
}

export default { exec, init }
<|endoftext|>


<commit_before>/* Check LICENSE for details. Developed by Oratio.io */

//Node Standard Modules
var child_process = require('child_process');
var path = require('path');
var fs = require('fs');

//NPM Modules
var Promise = require('bluebird');

//safe-instances Modules
var util = require('./util');

//The Pool handles the
function Pool(size){
  this.processes = [];
  this.active = [];
  this.size = size;

  for(var i = 0; i < size; i++){
    this.processes[i] = child_process.spawn(Pool.command, [Pool.file], { stdio: ['pipe', 'pipe', 'pipe', 'ipc']});
    this.active[i] = false;
  }
}

Pool.prototype.getProcess = function(id){
  if(id != null)
    return this.processes[id];

  for(var i = 0; i < this.processes.length; i++){
    if(this.active[i] === false){

      return this.processes[i];
    }
  }

  return null;
}

Pool.prototype.killAll = function(signal){
  for(var i = 0; i < this.processes.length; i++){
    this.processes[i].kill(signal);
    this.processes[i] = null;
    this.active[i].active = false;
  }
}

Pool.prototype.restart = function(){
  for(var i = 0; i < this.size; i++){
    this.processes[i] = child_process.spawn(Pool.command, [Pool.file], { stdio: ['pipe', 'pipe', 'pipe', 'ipc']});
    this.active[i] = false;
  }
}

Pool.command = 'node';
Pool.file = './child.js';

module.exports = Pool;
<commit_msg>Fixes path error.<commit_after>/* Check LICENSE for details. Developed by Oratio.io */

//Node Standard Modules
var child_process = require('child_process');
var path = require('path');
var fs = require('fs');

//NPM Modules
var Promise = require('bluebird');

//safe-instances Modules
var util = require('./util');

//The Pool handles the
function Pool(size){
  this.processes = [];
  this.active = [];
  this.size = size;

  for(var i = 0; i < size; i++){
    this.processes[i] = child_process.spawn(Pool.command, [Pool.file], { stdio: ['pipe', 'pipe', 'pipe', 'ipc']});
    this.active[i] = false;
  }
}

Pool.prototype.getProcess = function(id){
  if(id != null)
    return this.processes[id];

  for(var i = 0; i < this.processes.length; i++){
    if(this.active[i] === false){

      return this.processes[i];
    }
  }

  return null;
}

Pool.prototype.killAll = function(signal){
  for(var i = 0; i < this.processes.length; i++){
    this.processes[i].kill(signal);
    this.processes[i] = null;
    this.active[i].active = false;
  }
}

Pool.prototype.restart = function(){
  for(var i = 0; i < this.size; i++){
    this.processes[i] = child_process.spawn(Pool.command, [Pool.file], { stdio: ['pipe', 'pipe', 'pipe', 'ipc']});
    this.active[i] = false;
  }
}

Pool.command = 'node';
Pool.file = 'src/child.js';

module.exports = Pool;
<|endoftext|>


<commit_before>/*-
 * #%L
 * thinkbig-ui-feed-manager
 * %%
 * Copyright (C) 2017 ThinkBig Analytics
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

define(['angular','feed-mgr/feeds/define-feed/module-name'], function (angular,moduleName) {

    var directive = function () {
        return {
            restrict: "EA",
            bindToController: {
                stepIndex: '@'
            },
            require:['thinkbigDefineFeedGeneralInfo','^thinkbigStepper'],
            scope: {},
            controllerAs: 'vm',
            templateUrl: 'js/feed-mgr/feeds/define-feed/feed-details/define-feed-general-info.html',
            controller: "DefineFeedGeneralInfoController",
            link: function ($scope, element, attrs, controllers) {
                var thisController = controllers[0];
                var stepperController = controllers[1];
                thisController.stepperController = stepperController;
                thisController.totalSteps = stepperController.totalSteps;
            }

        };
    }

    var controller =  function($scope,$log, $http,$mdToast,RestUrlService, FeedService, CategoriesService) {

        var self = this;

        /**
         * The angular form
         * @type {{}}
         */
        this.defineFeedGeneralForm = {};
        this.templates = [];
        this.model = FeedService.createFeedModel;
        this.isValid = false;
        this.stepNumber = parseInt(this.stepIndex)+1
        this.stepperController = null;

        // Contains existing system feed names for the current category
        this.existingFeedNames = {};

        this.categorySearchText = '';
        this.category;
        self.categorySelectedItemChange = selectedItemChange;
        self.categorySearchTextChanged = searchTextChange;
        self.categoriesService = CategoriesService;

        function searchTextChange(text) {
         //   $log.info('Text changed to ' + text);
        }
        function selectedItemChange(item) {
            //only allow it if the category is there and the 'createFeed' flag is true
            if(item != null && item != undefined && item.createFeed) {
                self.model.category.name = item.name;
                self.model.category.id = item.id;
                self.model.category.systemName = item.systemName;
                setSecurityGroups(item.name);
                validateUniqueFeedName();

                if (self.defineFeedGeneralForm && self.defineFeedGeneralForm['category']) {
                    self.defineFeedGeneralForm['category'].$setValidity('accessDenied', true);
                }
            }
            else {
                self.model.category.name = null;
                self.model.category.id = null;
                self.model.category.systemName = null;
                self.existingFeedNames = {};
                if (self.defineFeedGeneralForm && self.defineFeedGeneralForm['feedName']) {
                    self.defineFeedGeneralForm['feedName'].$setValidity('notUnique', true);
                }

                if(item && item.createFeed == false){
                    if (self.defineFeedGeneralForm && self.defineFeedGeneralForm['category']) {
                        self.defineFeedGeneralForm['category'].$setValidity('accessDenied', false);
                    }
                }
                else {
                    if (self.defineFeedGeneralForm && self.defineFeedGeneralForm['category']) {
                        self.defineFeedGeneralForm['category'].$setValidity('accessDenied', true);
                    }
                }
            }
        }

        function existingFeedNameKey(categoryId, feedName) {
            return categoryId + "-" + feedName;
        }

        populateExistingFeedNames();

        /**
         * updates the {@code existingFeedNames} object with the latest feed names from the server
         * @returns {promise}
         */
        function populateExistingFeedNames() {
            return $http.get(RestUrlService.GET_FEEDS_URL).then(function (response) {
                self.existingFeedNames = {};
                angular.forEach(response.data, function (feed) {
                    self.existingFeedNames[existingFeedNameKey(feed.categoryId, feed.systemFeedName)] = feed.systemFeedName;
                });
            });
        }

        function validateUniqueFeedName() {

            function _validate() {
                //validate to ensure the name is unique in this category
                if (self.model && self.model.category && self.existingFeedNames[existingFeedNameKey(self.model.category.id, self.model.systemFeedName)]) {
                    if (self.defineFeedGeneralForm && self.defineFeedGeneralForm['feedName']) {
                        self.defineFeedGeneralForm['feedName'].$setValidity('notUnique', false);
                    }
                }
                else {
                    if (self.defineFeedGeneralForm && self.defineFeedGeneralForm['feedName']) {
                        self.defineFeedGeneralForm['feedName'].$setValidity('notUnique', true);
                    }
                }
            }

            if (_.isEmpty(self.existingFeedNames)) {
                populateExistingFeedNames().then(function () {
                    _validate();
                });
            }
            else {
                _validate();
            }

        }

      //  getRegisteredTemplates();

        function validate(){
           var valid = isNotEmpty(self.model.category.name) && isNotEmpty(self.model.feedName) && isNotEmpty(self.model.templateId);
            self.isValid = valid;
        }

        function setSecurityGroups(newVal) {
            if(newVal) {
                var category = self.categoriesService.findCategoryByName(newVal)
                if(category != null) {
                    var securityGroups = category.securityGroups;
                    self.model.securityGroups = securityGroups;
                }
            }
        }

        function isNotEmpty(item){
            return item != null && item != undefined && item != '';
        }

        this.onTemplateChange = function() {

        }

        $scope.$watch(function(){
            return self.model.id;
        },function(newVal){
            if(newVal == null) {
                self.category = null;
            }
            else {
                self.category = self.model.category;
            }
        })

       var feedNameWatch = $scope.$watch(function(){
            return self.model.feedName;
        },function(newVal) {
           FeedService.getSystemName(newVal).then(function (response) {
               self.model.systemFeedName = response.data;
               validateUniqueFeedName();
               validate();
           });

        });

        $scope.$watch(function(){
            return self.model.category.name;
        },function(newVal) {

            validate();
        })

      var templateIdWatch =  $scope.$watch(function(){
            return self.model.templateId;
        },function(newVal) {
            validate();
        });

        /**
         * Return a list of the Registered Templates in the system
         * @returns {HttpPromise}
         */
        function getRegisteredTemplates() {
            var successFn = function (response) {
                self.templates = response.data;
            }
            var errorFn = function (err) {

            }
            var promise = $http.get(RestUrlService.GET_REGISTERED_TEMPLATES_URL);
            promise.then(successFn, errorFn);
            return promise;
        };

            $scope.$on('$destroy',function(){
                feedNameWatch();
                templateIdWatch();
                self.model = null;
            });

    };

    angular.module(moduleName).controller('DefineFeedGeneralInfoController', ["$scope","$log","$http","$mdToast","RestUrlService","FeedService","CategoriesService",controller]);

    angular.module(moduleName)
        .directive('thinkbigDefineFeedGeneralInfo', directive);

});
<commit_msg>KYLO-669 Allow existing feeds to have a non-unique name<commit_after>/*-
 * #%L
 * thinkbig-ui-feed-manager
 * %%
 * Copyright (C) 2017 ThinkBig Analytics
 * %%
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * #L%
 */

define(['angular','feed-mgr/feeds/define-feed/module-name'], function (angular,moduleName) {

    var directive = function () {
        return {
            restrict: "EA",
            bindToController: {
                stepIndex: '@'
            },
            require:['thinkbigDefineFeedGeneralInfo','^thinkbigStepper'],
            scope: {},
            controllerAs: 'vm',
            templateUrl: 'js/feed-mgr/feeds/define-feed/feed-details/define-feed-general-info.html',
            controller: "DefineFeedGeneralInfoController",
            link: function ($scope, element, attrs, controllers) {
                var thisController = controllers[0];
                var stepperController = controllers[1];
                thisController.stepperController = stepperController;
                thisController.totalSteps = stepperController.totalSteps;
            }

        };
    }

    var controller =  function($scope,$log, $http,$mdToast,RestUrlService, FeedService, CategoriesService) {

        var self = this;

        /**
         * The angular form
         * @type {{}}
         */
        this.defineFeedGeneralForm = {};
        this.templates = [];
        this.model = FeedService.createFeedModel;
        this.isValid = false;
        this.stepNumber = parseInt(this.stepIndex)+1
        this.stepperController = null;

        // Contains existing system feed names for the current category
        this.existingFeedNames = {};

        this.categorySearchText = '';
        this.category;
        self.categorySelectedItemChange = selectedItemChange;
        self.categorySearchTextChanged = searchTextChange;
        self.categoriesService = CategoriesService;

        function searchTextChange(text) {
         //   $log.info('Text changed to ' + text);
        }
        function selectedItemChange(item) {
            //only allow it if the category is there and the 'createFeed' flag is true
            if(item != null && item != undefined && item.createFeed) {
                self.model.category.name = item.name;
                self.model.category.id = item.id;
                self.model.category.systemName = item.systemName;
                setSecurityGroups(item.name);
                validateUniqueFeedName();

                if (self.defineFeedGeneralForm && self.defineFeedGeneralForm['category']) {
                    self.defineFeedGeneralForm['category'].$setValidity('accessDenied', true);
                }
            }
            else {
                self.model.category.name = null;
                self.model.category.id = null;
                self.model.category.systemName = null;
                self.existingFeedNames = {};
                if (self.defineFeedGeneralForm && self.defineFeedGeneralForm['feedName']) {
                    self.defineFeedGeneralForm['feedName'].$setValidity('notUnique', true);
                }

                if(item && item.createFeed == false){
                    if (self.defineFeedGeneralForm && self.defineFeedGeneralForm['category']) {
                        self.defineFeedGeneralForm['category'].$setValidity('accessDenied', false);
                    }
                }
                else {
                    if (self.defineFeedGeneralForm && self.defineFeedGeneralForm['category']) {
                        self.defineFeedGeneralForm['category'].$setValidity('accessDenied', true);
                    }
                }
            }
        }

        function existingFeedNameKey(categoryId, feedName) {
            return categoryId + "-" + feedName;
        }

        populateExistingFeedNames();

        /**
         * updates the {@code existingFeedNames} object with the latest feed names from the server
         * @returns {promise}
         */
        function populateExistingFeedNames() {
            return $http.get(RestUrlService.GET_FEEDS_URL).then(function (response) {
                self.existingFeedNames = {};
                angular.forEach(response.data, function (feed) {
                    self.existingFeedNames[existingFeedNameKey(feed.categoryId, feed.systemFeedName)] = feed.systemFeedName;
                });
            });
        }

        function validateUniqueFeedName() {

            function _validate() {
                //validate to ensure the name is unique in this category
                if (self.model && self.model.category && self.existingFeedNames[existingFeedNameKey(self.model.category.id, self.model.systemFeedName)]) {
                    if (self.defineFeedGeneralForm && self.defineFeedGeneralForm['feedName']) {
                        self.defineFeedGeneralForm['feedName'].$setValidity('notUnique', false);
                    }
                }
                else {
                    if (self.defineFeedGeneralForm && self.defineFeedGeneralForm['feedName']) {
                        self.defineFeedGeneralForm['feedName'].$setValidity('notUnique', true);
                    }
                }
            }

            if (self.model && self.model.id && self.model.id.length > 0) {
                self.defineFeedGeneralForm['feedName'].$setValidity('notUnique', true);
            } else if (_.isEmpty(self.existingFeedNames)) {
                populateExistingFeedNames().then(function () {
                    _validate();
                });
            } else {
                _validate();
            }

        }

      //  getRegisteredTemplates();

        function validate(){
           var valid = isNotEmpty(self.model.category.name) && isNotEmpty(self.model.feedName) && isNotEmpty(self.model.templateId);
            self.isValid = valid;
        }

        function setSecurityGroups(newVal) {
            if(newVal) {
                var category = self.categoriesService.findCategoryByName(newVal)
                if(category != null) {
                    var securityGroups = category.securityGroups;
                    self.model.securityGroups = securityGroups;
                }
            }
        }

        function isNotEmpty(item){
            return item != null && item != undefined && item != '';
        }

        this.onTemplateChange = function() {

        }

        $scope.$watch(function(){
            return self.model.id;
        },function(newVal){
            if(newVal == null) {
                self.category = null;
            }
            else {
                self.category = self.model.category;
            }
        })

       var feedNameWatch = $scope.$watch(function(){
            return self.model.feedName;
        },function(newVal) {
           FeedService.getSystemName(newVal).then(function (response) {
               self.model.systemFeedName = response.data;
               validateUniqueFeedName();
               validate();
           });

        });

        $scope.$watch(function(){
            return self.model.category.name;
        },function(newVal) {

            validate();
        })

      var templateIdWatch =  $scope.$watch(function(){
            return self.model.templateId;
        },function(newVal) {
            validate();
        });

        /**
         * Return a list of the Registered Templates in the system
         * @returns {HttpPromise}
         */
        function getRegisteredTemplates() {
            var successFn = function (response) {
                self.templates = response.data;
            }
            var errorFn = function (err) {

            }
            var promise = $http.get(RestUrlService.GET_REGISTERED_TEMPLATES_URL);
            promise.then(successFn, errorFn);
            return promise;
        };

            $scope.$on('$destroy',function(){
                feedNameWatch();
                templateIdWatch();
                self.model = null;
            });

    };

    angular.module(moduleName).controller('DefineFeedGeneralInfoController', ["$scope","$log","$http","$mdToast","RestUrlService","FeedService","CategoriesService",controller]);

    angular.module(moduleName)
        .directive('thinkbigDefineFeedGeneralInfo', directive);

});
<|endoftext|>


<commit_before>

var repl = module.exports = {};

var
	req = require('./req');

var
	path = require('path'),
	std  = require('repl');

var
	extend   = req.local('aux.js/object/extend'),
	colors   = req.local('cli-color'),
	minimist = req.local('minimist');

var
	evaler = require('./evaler'),
	utilrepl = require('./utilrepl');

repl.run = function (argv)
{
	var argopts = minimist(argv, {
		boolean:
		[
			'clean',
			'help',
			'version'
		],
		alias:
		{
			help: [ 'h', '?' ],
			version: [ 'v' ],
		}
	});

	if (argopts.help)
	{
		process.stdout.write(require('./help'));
		process.exit();
	}

	if (argopts.version)
	{
		process.stdout.write(require('../package.json').version + '\n');
		process.exit();
	}

	var mods = req.parse(argopts._);

	return repl.start({ argopts: argopts, mods: mods });
}

repl.start = function (options)
{
	options || (options = {});

	options = extend(
		{},
		defaults,
		options
	);

	var
		argopts = options.argopts,
		console = utilrepl.console.Console(options),
		mods    = req.process(options.mods, console);

	/* @todo override? */
	options.eval = evaler(options, console)

	var
		instance = std.start(options),
		context  = instance.context;

	reset(context);
	instance.on('reset', reset);

	return instance;

	/* @todo: check reset in other versions */
	function reset (context)
	{
		if (! argopts.clean)
		{
			utilrepl.console.inRepl(instance, console);

			utilrepl.log(instance, console);

			/* @todo: return value issue */
			/*instance.writer = */ context.dir = utilrepl.dir(instance, console);

			utilrepl.sg(instance, console);

			utilrepl.aux(instance);

			context.colors = colors;
		}

		req.inRepl(instance);
		req.extend(instance, mods);
	}
}

var defaults =
{
	prompt: 'js > ',
	ignoreUndefined: true,

	argopts: {},
	mods: []
}
<commit_msg>context: Promise.<commit_after>

var repl = module.exports = {};

var
	req = require('./req');

var
	path = require('path'),
	std  = require('repl');

var
	extend   = req.local('aux.js/object/extend'),
	colors   = req.local('cli-color'),
	minimist = req.local('minimist');

var
	evaler = require('./evaler'),
	utilrepl = require('./utilrepl');

repl.run = function (argv)
{
	var argopts = minimist(argv, {
		boolean:
		[
			'clean',
			'help',
			'version'
		],
		alias:
		{
			help: [ 'h', '?' ],
			version: [ 'v' ],
		}
	});

	if (argopts.help)
	{
		process.stdout.write(require('./help'));
		process.exit();
	}

	if (argopts.version)
	{
		process.stdout.write(require('../package.json').version + '\n');
		process.exit();
	}

	var mods = req.parse(argopts._);

	return repl.start({ argopts: argopts, mods: mods });
}

repl.start = function (options)
{
	options || (options = {});

	options = extend(
		{},
		defaults,
		options
	);

	var
		argopts = options.argopts,
		console = utilrepl.console.Console(options),
		mods    = req.process(options.mods, console);

	/* @todo override? */
	options.eval = evaler(options, console)

	var
		instance = std.start(options),
		context  = instance.context;

	reset(context);
	instance.on('reset', reset);

	return instance;

	/* @todo: check reset in other versions */
	function reset (context)
	{
		if (! argopts.clean)
		{
			utilrepl.console.inRepl(instance, console);

			utilrepl.log(instance, console);

			/* @todo: return value issue */
			/*instance.writer = */ context.dir = utilrepl.dir(instance, console);

			utilrepl.sg(instance, console);

			utilrepl.aux(instance);

			context.colors = colors;

			context.Promise = require('promise');
		}

		req.inRepl(instance);
		req.extend(instance, mods);
	}
}

var defaults =
{
	prompt: 'js > ',
	ignoreUndefined: true,

	argopts: {},
	mods: []
}
<|endoftext|>


<commit_before>const React = require('react');

class Repo extends React.Component {
    render() {
        const { name, url, description, language, language_color, stars, stars_in_period, forks, updated } = this.props.repo;

        return (

{name}

{description}

                            Language: {language}
                            Stars: {stars}
                            Forks: {forks}
                            {stars_in_period}
                            {updated}

        )
    }
}

Repo.propTypes = {
    repo: React.PropTypes.object.isRequired
};

module.exports = Repo;
<commit_msg>Updated repo component styling<commit_after>const React = require('react');

class Repo extends React.Component {
    render() {
        const { name, url, description, language, language_color, stars, stars_in_period, forks, updated } = this.props.repo;

        let repoLanguage;
        let repoStars;
        let repoForks;
        let repoStarsInPeriod;
        let repoUpdated;

        if (language) {
            repoLanguage =
                                {language}

        }

        if (stars) {
            repoStars =
                            {stars}

        }

        if (forks) {
            repoForks =
                            {forks}

        }

        if (stars_in_period) {
            repoStarsInPeriod =
                                    {stars_in_period}

        }

        if (updated) {
            repoUpdated =
                                {updated}

        }

        return (

{name}

                        {description}

                                {repoLanguage}
                                {repoStars}
                                {repoForks}

                                {repoStarsInPeriod}
                                {repoUpdated}

                    Open

        )
    }
}

Repo.propTypes = {
    repo: React.PropTypes.object.isRequired
};

module.exports = Repo;
<|endoftext|>


<commit_before>import {buildQueryString, join} from 'aurelia-path';
import {HttpClient} from 'aurelia-fetch-client';
import extend from 'extend';

/**
 * Rest class. A simple rest client to fetch resources
 */
export class Rest {
  /**
   * The defaults to apply to any request
   *
   * @param {{}} defaults The default fetch request options
   */
  defaults: {} = {
    headers: {
      'Accept'      : 'application/json',
      'Content-Type': 'application/json'
    }
  };

  /**
   * The client for the rest adapter
   *
   * @param {HttpClient} client The fetch client
   *
   */
  client: HttpClient;

  /**
   * The name of the endpoint it was registered under
   *
   * @param {string} endpoint The endpoint name
   */
  endpoint: string;

  /**
   * Inject the httpClient to use for requests.
   *
   * @param {HttpClient} httpClient The httpClient to use
   * @param {string}     endpoint   The endpoint name
   */
  constructor(httpClient: HttpClient, endpoint: string) {
    this.client   = httpClient;
    this.endpoint = endpoint;
  }

  /**
   * Make a request to the server.
   *
   * @param {string}          method     The fetch method
   * @param {string}          path       Path to the resource
   * @param {{}}              [body]     The body to send if applicable
   * @param {{}}              [options]  Fetch request options overwrites
   *
   * @return {Promise<*>|Promise<Error>} Server response as Object
   */
  request(method: string, path: string, body?: {}, options?: {}): Promise<any|Error> {
    let requestOptions = extend(true, {headers: {}}, this.defaults, options || {}, {method, body});
    let contentType    = requestOptions.headers['Content-Type'] || requestOptions.headers['content-type'];

    if (typeof body === 'object' && body !== null && contentType) {
      requestOptions.body = (/^application\/json/).test(contentType.toLowerCase())
                          ? JSON.stringify(body)
                          : buildQueryString(body);
    }

    return this.client.fetch(path, requestOptions).then((response: Response) => {
      if (response.status >= 200 && response.status < 400) {
        return response.json().catch(() => null);
      }

      throw response;
    });
  }

  /**
   * Find a resource.
   *
   * @param {string}                    resource  Resource to find in
   * @param {{}|string|number}          criteria  Object for where clause, string / number for id.
   * @param {{}}                        [options] Extra request options.
   *
   * @return {Promise<*>|Promise<Error>} Server response as Object
   */
  find(resource: string, criteria?: {}|string|number, options?: {}): Promise<any|Error> {
    return this.request('GET', getRequestPath(resource, criteria), undefined, options);
  }

  /**
   * Find a resource.
   *
   * @param {string}           resource    Resource to find in
   * @param {string|number}    id          String / number for id to be added to the path.
   * @param {{}}               [criteria]  Object for where clause
   * @param {{}}               [options]   Extra request options.
   *
   * @return {Promise<*>|Promise<Error>} Server response as Object
   */
  findOne(resource: string, id: string|number, criteria?: {}, options?: {}): Promise<any|Error> {
    return this.request('GET', getRequestPath(resource, id, criteria), undefined, options);
  }

  /**
   * Create a new instance for resource.
   *
   * @param {string}           resource  Resource to create
   * @param {{}}               [body]    The data to post (as Object)
   * @param {{}}               [options] Extra request options.
   *
   * @return {Promise<*>|Promise<Error>} Server response as Object
   */
  post(resource: string, body?: {}, options?: {}): Promise<any|Error> {
    return this.request('POST', resource, body, options);
  }

  /**
   * Update a resource.
   *
   * @param {string}           resource  Resource to update
   * @param {{}|string|number} criteria  Object for where clause, string / number for id.
   * @param {{}}               [body]    New data for provided criteria.
   * @param {{}}               [options] Extra request options.
   *
   * @return {Promise<*>|Promise<Error>} Server response as Object
   */
  update(resource: string, criteria?: {}|string|number, body?: {}, options?: {}): Promise<any|Error> {
    return this.request('PUT', getRequestPath(resource, criteria), body, options);
  }

  /**
   * Update a resource.
   *
   * @param {string}           resource   Resource to update
   * @param {string|number}    id         String / number for id to be added to the path.
   * @param {{}}               [criteria] Object for where clause
   * @param {{}}               [body]     New data for provided criteria.
   * @param {{}}               [options]  Extra request options.
   *
   * @return {Promise<*>|Promise<Error>} Server response as Object
   */
  updateOne(resource: string, id: string|number, criteria?: {}, body?: {}, options?: {}): Promise<any|Error> {
    return this.request('PUT', getRequestPath(resource, id, criteria), body, options);
  }

  /**
   * Patch a resource.
  *
   * @param {string}           resource   Resource to patch
   * @param {{}|string|number} [criteria] Object for where clause, string / number for id.
   * @param {{}}               [body]     Data to patch for provided criteria.
   * @param {{}}               [options]  Extra request options.
   *
   * @return {Promise<*>|Promise<Error>} Server response as Object
   */
  patch(resource: string, criteria?: {}|string|number, body?: {}, options?: {}): Promise<any|Error> {
    return this.request('PATCH', getRequestPath(resource, criteria), body, options);
  }

  /**
   * Patch a resource.
   *
   * @param {string}           resource   Resource to patch
   * @param {string|number}    id         String / number for id to be added to the path.
   * @param {{}}               [criteria] Object for where clause
   * @param {{}}               [body]     Data to patch for provided criteria.
   * @param {{}}               [options]  Extra request options.
   *
   * @return {Promise<*>|Promise<Error>} Server response as Object
   */
  patchOne(resource: string, id: string|number, criteria?: {}, body?: {}, options?: {}): Promise<any|Error> {
    return this.request('PATCH', getRequestPath(resource, id, criteria), body, options);
  }

  /**
   * Delete a resource.
   *
   * @param {string}           resource   The resource to delete
   * @param {{}|string|number} [criteria] Object for where clause, string / number for id.
   * @param {{}}               [options]  Extra request options.
   *
   * @return {Promise<*>|Promise<Error>} Server response as Object
   */
  destroy(resource: string, criteria?: {}|string|number, options?: {}): Promise<any|Error> {
    return this.request('DELETE', getRequestPath(resource, criteria), undefined, options);
  }

  /**
   * Delete a resource.
   *
   * @param {string}           resource   The resource to delete
   * @param {string|number}    id         String / number for id to be added to the path.
   * @param {{}}               [criteria] Object for where clause
   * @param {{}}               [options]  Extra request options.
   *
   * @return {Promise<*>|Promise<Error>} Server response as Object
   */
  destroyOne(resource: string, id: string|number, criteria?: {}, options?: {}): Promise<any|Error> {
    return this.request('DELETE', getRequestPath(resource, id, criteria), undefined, options);
  }

  /**
   * Create a new instance for resource.
   *
   * @param {string}           resource  The resource to create
   * @param {{}}               [body]    The data to post (as Object)
   * @param {{}}               [options] Extra request options.
   *
   * @return {Promise<*>} Server response as Object
   */
  create(resource: string, body?: {}, options?: {}): Promise<any|Error> {
    return this.post(resource, body, options);
  }
}

/**
 * getRequestPath
 *
 * @param {string} resource
 * @param {(string|number|{})} [idOrCriteria]
 * @param {{}} [criteria]
 * @returns {string}
 */
function getRequestPath(resource: string, idOrCriteria?: string|number|{}, criteria?: {}) {
  let hasSlash = resource.slice(-1) === '/';

  if (typeof idOrCriteria === 'string' || typeof idOrCriteria === 'number') {
    resource = `${join(resource, String(idOrCriteria))}${hasSlash ? '/' : ''}`;
  } else {
    criteria = idOrCriteria;
  }

  if (typeof criteria === 'object' && criteria !== null) {
    resource += `?${buildQueryString(criteria)}`;
  } else if (criteria) {
    resource += `${hasSlash ? '' : '/'}${criteria}${hasSlash ? '/' : ''}`;
  }

  return resource;
}
<commit_msg>feat(rest): add a flag to enable RFC6570 uri templates<commit_after>import {buildQueryString, join} from 'aurelia-path';
import {HttpClient} from 'aurelia-fetch-client';
import extend from 'extend';

/**
 * Rest class. A simple rest client to fetch resources
 */
export class Rest {
  /**
   * The defaults to apply to any request
   *
   * @param {{}} defaults The default fetch request options
   */
  defaults: {} = {
    headers: {
      'Accept'      : 'application/json',
      'Content-Type': 'application/json'
    }
  };

  /**
   * The client for the rest adapter
   *
   * @param {HttpClient} client The fetch client
   *
   */
  client: HttpClient;

  /**
   * The name of the endpoint it was registered under
   *
   * @param {string} endpoint The endpoint name
   */
  endpoint: string;

  /**
   * true to use the traditional URI template standard (RFC6570) when building
   * query strings from criteria objects, false otherwise. Default is false.
   *
   * @param {boolean} useTraditionalUriTemplates The flag that enables RFC6570 URI templates.
   */
  useTraditionalUriTemplates: boolean;

  /**
   * Inject the httpClient to use for requests.
   *
   * @param {HttpClient} httpClient                    The httpClient to use
   * @param {string}     endpoint                      The endpoint name
   * @param {boolean}    [useTraditionalUriTemplates]  true to use the traditional URI
   *                                                   template standard (RFC6570) when building
   *                                                   query strings from criteria objects, false
   *                                                   otherwise. Default is false.
   */
  constructor(httpClient: HttpClient, endpoint: string, useTraditionalUriTemplates?: boolean) {
    this.client   = httpClient;
    this.endpoint = endpoint;
    this.useTraditionalUriTemplates = !!useTraditionalUriTemplates;
  }

  /**
   * Make a request to the server.
   *
   * @param {string}          method     The fetch method
   * @param {string}          path       Path to the resource
   * @param {{}}              [body]     The body to send if applicable
   * @param {{}}              [options]  Fetch request options overwrites
   *
   * @return {Promise<*>|Promise<Error>} Server response as Object
   */
  request(method: string, path: string, body?: {}, options?: {}): Promise<any|Error> {
    let requestOptions = extend(true, {headers: {}}, this.defaults, options || {}, {method, body});
    let contentType    = requestOptions.headers['Content-Type'] || requestOptions.headers['content-type'];

    if (typeof body === 'object' && body !== null && contentType) {
      requestOptions.body = (/^application\/json/).test(contentType.toLowerCase())
                          ? JSON.stringify(body)
                          : buildQueryString(body);
    }

    return this.client.fetch(path, requestOptions).then((response: Response) => {
      if (response.status >= 200 && response.status < 400) {
        return response.json().catch(() => null);
      }

      throw response;
    });
  }

  /**
   * Find a resource.
   *
   * @param {string}                    resource  Resource to find in
   * @param {{}|string|number}          criteria  Object for where clause, string / number for id.
   * @param {{}}                        [options] Extra request options.
   *
   * @return {Promise<*>|Promise<Error>} Server response as Object
   */
  find(resource: string, criteria?: {}|string|number, options?: {}): Promise<any|Error> {
    return this.request('GET', getRequestPath(resource, this.useTraditionalUriTemplates, criteria), undefined, options);
  }

  /**
   * Find a resource.
   *
   * @param {string}           resource    Resource to find in
   * @param {string|number}    id          String / number for id to be added to the path.
   * @param {{}}               [criteria]  Object for where clause
   * @param {{}}               [options]   Extra request options.
   *
   * @return {Promise<*>|Promise<Error>} Server response as Object
   */
  findOne(resource: string, id: string|number, criteria?: {}, options?: {}): Promise<any|Error> {
    return this.request('GET', getRequestPath(resource, this.useTraditionalUriTemplates, id, criteria), undefined, options);
  }

  /**
   * Create a new instance for resource.
   *
   * @param {string}           resource  Resource to create
   * @param {{}}               [body]    The data to post (as Object)
   * @param {{}}               [options] Extra request options.
   *
   * @return {Promise<*>|Promise<Error>} Server response as Object
   */
  post(resource: string, body?: {}, options?: {}): Promise<any|Error> {
    return this.request('POST', resource, body, options);
  }

  /**
   * Update a resource.
   *
   * @param {string}           resource  Resource to update
   * @param {{}|string|number} criteria  Object for where clause, string / number for id.
   * @param {{}}               [body]    New data for provided criteria.
   * @param {{}}               [options] Extra request options.
   *
   * @return {Promise<*>|Promise<Error>} Server response as Object
   */
  update(resource: string, criteria?: {}|string|number, body?: {}, options?: {}): Promise<any|Error> {
    return this.request('PUT', getRequestPath(resource, this.useTraditionalUriTemplates, criteria), body, options);
  }

  /**
   * Update a resource.
   *
   * @param {string}           resource   Resource to update
   * @param {string|number}    id         String / number for id to be added to the path.
   * @param {{}}               [criteria] Object for where clause
   * @param {{}}               [body]     New data for provided criteria.
   * @param {{}}               [options]  Extra request options.
   *
   * @return {Promise<*>|Promise<Error>} Server response as Object
   */
  updateOne(resource: string, id: string|number, criteria?: {}, body?: {}, options?: {}): Promise<any|Error> {
    return this.request('PUT', getRequestPath(resource, this.useTraditionalUriTemplates, id, criteria), body, options);
  }

  /**
   * Patch a resource.
  *
   * @param {string}           resource   Resource to patch
   * @param {{}|string|number} [criteria] Object for where clause, string / number for id.
   * @param {{}}               [body]     Data to patch for provided criteria.
   * @param {{}}               [options]  Extra request options.
   *
   * @return {Promise<*>|Promise<Error>} Server response as Object
   */
  patch(resource: string, criteria?: {}|string|number, body?: {}, options?: {}): Promise<any|Error> {
    return this.request('PATCH', getRequestPath(resource, this.useTraditionalUriTemplates, criteria), body, options);
  }

  /**
   * Patch a resource.
   *
   * @param {string}           resource   Resource to patch
   * @param {string|number}    id         String / number for id to be added to the path.
   * @param {{}}               [criteria] Object for where clause
   * @param {{}}               [body]     Data to patch for provided criteria.
   * @param {{}}               [options]  Extra request options.
   *
   * @return {Promise<*>|Promise<Error>} Server response as Object
   */
  patchOne(resource: string, id: string|number, criteria?: {}, body?: {}, options?: {}): Promise<any|Error> {
    return this.request('PATCH', getRequestPath(resource, this.useTraditionalUriTemplates, id, criteria), body, options);
  }

  /**
   * Delete a resource.
   *
   * @param {string}           resource   The resource to delete
   * @param {{}|string|number} [criteria] Object for where clause, string / number for id.
   * @param {{}}               [options]  Extra request options.
   *
   * @return {Promise<*>|Promise<Error>} Server response as Object
   */
  destroy(resource: string, criteria?: {}|string|number, options?: {}): Promise<any|Error> {
    return this.request('DELETE', getRequestPath(resource, this.useTraditionalUriTemplates, criteria), undefined, options);
  }

  /**
   * Delete a resource.
   *
   * @param {string}           resource   The resource to delete
   * @param {string|number}    id         String / number for id to be added to the path.
   * @param {{}}               [criteria] Object for where clause
   * @param {{}}               [options]  Extra request options.
   *
   * @return {Promise<*>|Promise<Error>} Server response as Object
   */
  destroyOne(resource: string, id: string|number, criteria?: {}, options?: {}): Promise<any|Error> {
    return this.request('DELETE', getRequestPath(resource, this.useTraditionalUriTemplates, id, criteria), undefined, options);
  }

  /**
   * Create a new instance for resource.
   *
   * @param {string}           resource  The resource to create
   * @param {{}}               [body]    The data to post (as Object)
   * @param {{}}               [options] Extra request options.
   *
   * @return {Promise<*>} Server response as Object
   */
  create(resource: string, body?: {}, options?: {}): Promise<any|Error> {
    return this.post(resource, body, options);
  }
}

/**
 * getRequestPath
 *
 * @param {string} resource
 * @param {boolean} traditional
 * @param {(string|number|{})} [idOrCriteria]
 * @param {{}} [criteria]
 * @returns {string}
 */
function getRequestPath(resource: string, traditional: boolean, idOrCriteria?: string|number|{}, criteria?: {}) {
  let hasSlash = resource.slice(-1) === '/';

  if (typeof idOrCriteria === 'string' || typeof idOrCriteria === 'number') {
    resource = `${join(resource, String(idOrCriteria))}${hasSlash ? '/' : ''}`;
  } else {
    criteria = idOrCriteria;
  }

  if (typeof criteria === 'object' && criteria !== null) {
    resource += `?${buildQueryString(criteria, traditional)}`;
  } else if (criteria) {
    resource += `${hasSlash ? '' : '/'}${criteria}${hasSlash ? '/' : ''}`;
  }

  return resource;
}
<|endoftext|>


<commit_before>
export const baseURL = 'https://moecoop.arukascloud.io'

export function getCall(url, callback) {
  const xhr = new XMLHttpRequest()
  xhr.onreadystatechange = function() {
    callback(xhr)
  }
  xhr.respenseType = 'json'
  xhr.open('GET', url, true)
  xhr.send()
}

export function postCall(url, param, callback) {
  const xhr = new XMLHttpRequest()
  xhr.onreadystatechange = function() {
    callback(xhr)
  }
  xhr.open('POST', url, true)
  xhr.setRequestHeader('Content-Type', 'application/json')
  xhr.send(JSON.stringify(param))
}
<commit_msg>REST API の base URL を api.fukuro.coop.moe に修正<commit_after>
export const baseURL = 'https://api.fukuro.coop.moe'

export function getCall(url, callback) {
  const xhr = new XMLHttpRequest()
  xhr.onreadystatechange = function() {
    callback(xhr)
  }
  xhr.respenseType = 'json'
  xhr.open('GET', url, true)
  xhr.send()
}

export function postCall(url, param, callback) {
  const xhr = new XMLHttpRequest()
  xhr.onreadystatechange = function() {
    callback(xhr)
  }
  xhr.open('POST', url, true)
  xhr.setRequestHeader('Content-Type', 'application/json')
  xhr.send(JSON.stringify(param))
}
<|endoftext|>


<commit_before>/**
 * Perform the element default action.
 *
 * @param {JSEvent} event the event that triggered the action
 *
 * @properties={typeid:24,uuid:"570EDE4C-54AB-4279-A57B-74B45922F1E5"}
 */
function DATA_action_list(event) {
	// get block type
	var params = new Array(globals.WEB_page_id_area_selected, globals.WEB_page_id_block_selected)
	var sql =	"select id_block_type, form_name from web_block_type where " +
					"web_block_type.id_block_type = " +
					"(select id_block_type from web_block where " +
					"web_block.id_area = ? and " +
					"web_block.id_block = ?)"
	var dataset = databaseManager.getDataSetByQuery(
					controller.getServerName(), sql, params, -1)

	if ( dataset.getMaxRowIndex() ) {
		var typeID = dataset.getValue(1,1)
		var formName = dataset.getValue(1,2)
	}
	else {
		return "No mathing block type found"
	}

	// input method names for block type
	var params = [typeID]
	var sql =	"select input_name, method_name from web_block_action_client where " +
					"web_block_action_client.id_block_type = ?"
	var dataset = databaseManager.getDataSetByQuery(
					controller.getServerName(), sql, params, -1)

	if ( dataset.getMaxRowIndex() ) {

		//menu items
		var valuelist 	= dataset.getColumnAsArray(1)
		var methods		= dataset.getColumnAsArray(2)

		//set up menu with arguments
		var menu = new Array()
		for ( var i = 0 ; i < valuelist.length ; i++ ) {
			menu[i] = plugins.popupmenu.createMenuItem(valuelist[i],DATA_action_list_control)

			menu[i].setMethodArguments(formName, methods[i])

			if (menu[i].text == '----') {
				menu[i].setEnabled(false)
			}
		}

		//popup
		var elem = elements[application.getMethodTriggerElementName()]
		if (elem != null && valuelist.length) {
			plugins.popupmenu.showPopupMenu(elem, menu)
		}
	}
}

/**
 * Perform the element default action.
 *
 * @param {JSEvent} event the event that triggered the action
 *
 * @properties={typeid:24,uuid:"8861F626-796C-403D-AB5E-03E6593A9678"}
 */
function DATA_action_list_control(event) {
	forms[arguments[0]][arguments[1]]()
}
<commit_msg>fix block actions when called from page action wheel in data mode<commit_after>/**
 * Perform the element default action.
 *
 * @param {JSEvent} event the event that triggered the action
 *
 * @properties={typeid:24,uuid:"570EDE4C-54AB-4279-A57B-74B45922F1E5"}
 */
function DATA_action_list(event) {
	// get block type
	var params = new Array(globals.WEB_page_id_area_selected, globals.WEB_page_id_block_selected)
	var sql =	"select id_block_type, form_name from web_block_type where " +
					"web_block_type.id_block_type = " +
					"(select id_block_type from web_block where " +
					"web_block.id_area = ? and " +
					"web_block.id_block = ?)"
	var dataset = databaseManager.getDataSetByQuery(
					controller.getServerName(), sql, params, -1)

	if ( dataset.getMaxRowIndex() ) {
		var typeID = dataset.getValue(1,1)
		var formName = dataset.getValue(1,2)
	}
	else {
		return "No mathing block type found"
	}

	// input method names for block type
	var params = [typeID,"Block"]
	var sql =	"select input_name, method_name from web_block_action_client where " +
					"id_block_type = ? AND action_type = ?"
	var dataset = databaseManager.getDataSetByQuery(
					controller.getServerName(), sql, params, -1)

	if ( dataset.getMaxRowIndex() ) {
		//sort alphabetically
		dataset.sort(1,true)

		//menu items
		var valuelist 	= dataset.getColumnAsArray(1)
		var methods		= dataset.getColumnAsArray(2)

		//set up menu with arguments
		var menu = new Array()
		for ( var i = 0 ; i < valuelist.length ; i++ ) {
			menu[i] = plugins.popupmenu.createMenuItem(valuelist[i],DATA_action_list_control)

			menu[i].setMethodArguments(formName, methods[i])

			if (menu[i].text == '----') {
				menu[i].setEnabled(false)
			}
		}

		//popup
		var elem = elements[application.getMethodTriggerElementName()]
		if (elem != null && valuelist.length) {
			plugins.popupmenu.showPopupMenu(elem, menu)
		}
	}
}

/**
 * Perform the element default action.
 *
 * @param {JSEvent} event the event that triggered the action
 *
 * @properties={typeid:24,uuid:"8861F626-796C-403D-AB5E-03E6593A9678"}
 */
function DATA_action_list_control(event) {
	forms[arguments[0]][arguments[1]]()
}
<|endoftext|>


<commit_before>function WritableFilePointer(owner, writer, mapKey, baseKey) {
    this.owner = owner; //UserPublicKey
    this.writer = writer; //User
    this.mapKey = mapKey; //ByteArrayWrapper
    this.baseKey = baseKey; //SymmetricKey

    this.serialize = function() {
	var bout = new ByteBuffer();
	bout.writeArray(string2arraybuffer(username));
	bout.writeArray(owner.getSecretKeys());
	bout.writeArray(mapKey);
	bout.writeArray(rootDirKey.key);
	return bout.toArray();
    }
}

WritableFilePointer.deserialize = function(buf) {
    var bin = new ByteBuffer(buf);
    var name = "";
    var ua = bin.readArray();
    for (var i = 0; i < ua.length; i++)
        name += String.fromCharCode(ua.readUnsignedByte());
    var secKeys = bin.readArray();
    var mapKey = bin.readArray();
    var rootDirKeySecret = bin.readArray();
    return new SharedRootDir(name, User.fromSecretKeys(secKeys), mapKey, new SymmetricKey(rootDirKeySecret));
}

function SymmetricLink(link) {
    this.link = slice(link, SymmetricKey.NONCE_BYTES, link.length);
    this.nonce = slice(link, 0, SymmetricKey.NONCE_BYTES);

    this.serialize = function() {
	return concat(nonce, link);
    }

    this.target = function(from) {
	var encoded = from.decrypt(link, nonce);
	return new SymmetricKey(encoded);
    }
}
SymmetricLink.fromPair = function(from, to, nonce) {
    return new SymmetricLink(concat(nonce, from.encrypt(to.key, nonce)));
}

// UserPublicKey, UserPublicKey, Uint8Array
function Location(owner, subKey, mapKey) {
    this.owner = owner;
    this.subKey = subKey;
    this.mapKey = mapKey;

    this.serialize = function(bout) {
	var bout = new ByteBuffer(username.length + 64 + 32 + 12);
	bout.writeArray(string2arraybuffer(username));
	bout.writeArray(subKey.getPublicKeys());
	bout.writeArray(mapKey);
	return bout.toArray();
    }

    this.encrypt = function(key, nonce) {
	return key.encrypt(serialize(), nonce);
    }
}
Location.deserialize = function(buf) {
    var owner = buf.readArray();
    var writer = buf.readArray();
    var mapKey = buf.readArray();
    return new Location(new UserPublicKey(owner), new UserPublicKey(writer), mapKey);
}
Location.decrypt = function(from, nonce, loc) {
    var raw = from.decrypt(loc, nonce);
    return Location.deserialize(new ByteBuffer(raw));
}

function SymmetricLocationLink(buf) {
    this.link = buf.readArray();
    this.loc = buf.readArray();

    // SymmetricKey -> Location
    this.targetLocation = function(from) {
	var nonce = slice(link, 0, SymmetricKey.NONCE_BYTES);
	var rest = slice(link, SymmetricKey.NONCE_BYTES, link.length);
	return Location.decrypt(from, nonce, loc);
    }
}

function FileAccess(parent2meta, properties, retriever) {
    this.parent2meta = parent2meta;
    this.properties = properties;
    this.retriever = retriever;

    this.serialize = function(bout) {
	bout.writeArray(parent2meta.serialize());
	bout.writeArray(properties);
	bout.writeByte(retriever != null ? 1 : 0);
	if (retriever != null)
	    retriever.serialize(bout);
	bout.writeByte(this.getType());
    }

    // 0=FILE, 1=DIR
    this.getType = function() {
	return 0;
    }
}
FileAccess.deserialize = function(buf, ourKey /*SymmetricKey*/) {
    var p2m = buf.readArray();
    var properties = buf.readArray();
    var hasRetreiver = buf.readUnsignedByte();
    var retriever =  (hasRetreiver == 1) ? FileRetriever.deserialize(buf) : null;
    var type = buf.readUnsignedByte();
    switch(type) {
    case 0:
	return FileAccess.deserialize(buf, concat(metaNonce, encryptedMetadata));
    case 1:
	return DirAccess.deserialize(buf, ourKey, concat(metaNonce, encryptedMetadata));
    default: throw new Error("Unknown Metadata type: "+type);
    }
}

function DirAccess(subfolders2files, subfolders2parent, subfolders, files, parent2meta, properties, retriever) {
    FileAccess.call(this, parent2meta, properties, retriever);
    this.subfolders2files = subfolders2files;
    this.subfolders2parent = subfolders2parent;
    this.subfolders = subfolders;
    this.files = files;

    this.superSerialize = this.serialize;
    this.serialize = function(bout) {
	superSerialize(bout);
	bout.writeArray(subfolders2parent);
	bout.writeArray(subfolders2files);
	bout.writeUnsignedInt(0);
	bout.writeUnsignedInt(subfolders.length)
	for (var i=0; i < subfolders.length; i++)
	    bout.writeArray(subfolders[i].serialize());
	bout.writeUnsignedInt(files.length)
	for (var i=0; i < files.length; i++)
	    bout.writeArray(files[i].serialize());
    }

    // 0=FILE, 1=DIR
    this.getType = function() {
	return 1;
    }
}

DirAccess.deserialize = function(base, bin) {
    var s2p = bin.readArray();
    var s2f = bin.readArray();
    var nSharingKeys = bin.readUnsignedInt();
    var files = [], subfolders = [];
    var nsubfolders = bin.readUnsignedInt();
    for (var i=0; i < nsubfolders; i++)
	nsubfolders[i] = new SymmetricLocationLink(bin.readArray());
    var nfiles = bin.readUnsignedInt();
    for (var i=0; i < nfiles; i++)
	nfiles[i] = new SymmetricLocationLink(bin.readArray());
    return new DirAccess(s2f, s2p, subfolders, files, base.parent2meta, base.properties, base.retriever);
}

function FileRetriever() {
}
FileRetriever.deserialize = function(bin) {
    var type = bin.readUnsignedByte();
    switch (type) {
	case 0:
	throw new Exception("Simple FileRetriever not implemented!");
	case 1:
	return EncryptedChunkRetriever.deserialize(bin);
	default:
	throw new Exception("Unknown FileRetriever type: "+type);
    }
}

function EncryptedChunkRetriever(chunkNonce, chunkAuth, fragmentHashes, nextChunk) {
    this.chunkNonce = chunkNonce;
    this.chunkAuth = chunkAuth;
    this.fragmentHashes = fragmentHashes;
    this.nextChunk = nextChunk;

}
EncryptedChunkRetriever.deserialize = function(bin) {
    //TODO
}

function string2arraybuffer(str) {
  var buf = new ArrayBuffer(str.length);
  var bufView = new Uint8Array(buf);
  for (var i=0, strLen=str.length; i<strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return bufView;
}
<commit_msg>Up to LazyInputStreamCombiner and Erasure codes in JS<commit_after>function WritableFilePointer(owner, writer, mapKey, baseKey) {
    this.owner = owner; //UserPublicKey
    this.writer = writer; //User
    this.mapKey = mapKey; //ByteArrayWrapper
    this.baseKey = baseKey; //SymmetricKey

    this.serialize = function() {
	var bout = new ByteBuffer();
	bout.writeArray(string2arraybuffer(username));
	bout.writeArray(owner.getSecretKeys());
	bout.writeArray(mapKey);
	bout.writeArray(rootDirKey.key);
	return bout.toArray();
    }
}

WritableFilePointer.deserialize = function(buf) {
    var bin = new ByteBuffer(buf);
    var name = "";
    var ua = bin.readArray();
    for (var i = 0; i < ua.length; i++)
        name += String.fromCharCode(ua.readUnsignedByte());
    var secKeys = bin.readArray();
    var mapKey = bin.readArray();
    var rootDirKeySecret = bin.readArray();
    return new SharedRootDir(name, User.fromSecretKeys(secKeys), mapKey, new SymmetricKey(rootDirKeySecret));
}

function SymmetricLink(link) {
    this.link = slice(link, SymmetricKey.NONCE_BYTES, link.length);
    this.nonce = slice(link, 0, SymmetricKey.NONCE_BYTES);

    this.serialize = function() {
	return concat(nonce, link);
    }

    this.target = function(from) {
	var encoded = from.decrypt(link, nonce);
	return new SymmetricKey(encoded);
    }
}
SymmetricLink.fromPair = function(from, to, nonce) {
    return new SymmetricLink(concat(nonce, from.encrypt(to.key, nonce)));
}

// UserPublicKey, UserPublicKey, Uint8Array
function Location(owner, subKey, mapKey) {
    this.owner = owner;
    this.subKey = subKey;
    this.mapKey = mapKey;

    this.serialize = function(bout) {
	var bout = new ByteBuffer(username.length + 64 + 32 + 12);
	bout.writeArray(string2arraybuffer(username));
	bout.writeArray(subKey.getPublicKeys());
	bout.writeArray(mapKey);
	return bout.toArray();
    }

    this.encrypt = function(key, nonce) {
	return key.encrypt(serialize(), nonce);
    }
}
Location.deserialize = function(buf) {
    var owner = buf.readArray();
    var writer = buf.readArray();
    var mapKey = buf.readArray();
    return new Location(new UserPublicKey(owner), new UserPublicKey(writer), mapKey);
}
Location.decrypt = function(from, nonce, loc) {
    var raw = from.decrypt(loc, nonce);
    return Location.deserialize(new ByteBuffer(raw));
}

function SymmetricLocationLink(buf) {
    this.link = buf.readArray();
    this.loc = buf.readArray();

    // SymmetricKey -> Location
    this.targetLocation = function(from) {
	var nonce = slice(link, 0, SymmetricKey.NONCE_BYTES);
	var rest = slice(link, SymmetricKey.NONCE_BYTES, link.length);
	return Location.decrypt(from, nonce, loc);
    }
}

function FileAccess(parent2meta, properties, retriever) {
    this.parent2meta = parent2meta;
    this.properties = properties;
    this.retriever = retriever;

    this.serialize = function(bout) {
	bout.writeArray(parent2meta.serialize());
	bout.writeArray(properties);
	bout.writeByte(retriever != null ? 1 : 0);
	if (retriever != null)
	    retriever.serialize(bout);
	bout.writeByte(this.getType());
    }

    // 0=FILE, 1=DIR
    this.getType = function() {
	return 0;
    }
}
FileAccess.deserialize = function(buf, ourKey /*SymmetricKey*/) {
    var p2m = buf.readArray();
    var properties = buf.readArray();
    var hasRetreiver = buf.readUnsignedByte();
    var retriever =  (hasRetreiver == 1) ? FileRetriever.deserialize(buf) : null;
    var type = buf.readUnsignedByte();
    switch(type) {
    case 0:
	return FileAccess.deserialize(buf, concat(metaNonce, encryptedMetadata));
    case 1:
	return DirAccess.deserialize(buf, ourKey, concat(metaNonce, encryptedMetadata));
    default: throw new Error("Unknown Metadata type: "+type);
    }
}

function DirAccess(subfolders2files, subfolders2parent, subfolders, files, parent2meta, properties, retriever) {
    FileAccess.call(this, parent2meta, properties, retriever);
    this.subfolders2files = subfolders2files;
    this.subfolders2parent = subfolders2parent;
    this.subfolders = subfolders;
    this.files = files;

    this.superSerialize = this.serialize;
    this.serialize = function(bout) {
	superSerialize(bout);
	bout.writeArray(subfolders2parent);
	bout.writeArray(subfolders2files);
	bout.writeUnsignedInt(0);
	bout.writeUnsignedInt(subfolders.length)
	for (var i=0; i < subfolders.length; i++)
	    bout.writeArray(subfolders[i].serialize());
	bout.writeUnsignedInt(files.length)
	for (var i=0; i < files.length; i++)
	    bout.writeArray(files[i].serialize());
    }

    // 0=FILE, 1=DIR
    this.getType = function() {
	return 1;
    }
}

DirAccess.deserialize = function(base, bin) {
    var s2p = bin.readArray();
    var s2f = bin.readArray();
    var nSharingKeys = bin.readUnsignedInt();
    var files = [], subfolders = [];
    var nsubfolders = bin.readUnsignedInt();
    for (var i=0; i < nsubfolders; i++)
	nsubfolders[i] = new SymmetricLocationLink(bin.readArray());
    var nfiles = bin.readUnsignedInt();
    for (var i=0; i < nfiles; i++)
	nfiles[i] = new SymmetricLocationLink(bin.readArray());
    return new DirAccess(s2f, s2p, subfolders, files, base.parent2meta, base.properties, base.retriever);
}

function FileRetriever() {
}
FileRetriever.deserialize = function(bin) {
    var type = bin.readUnsignedByte();
    switch (type) {
	case 0:
	throw new Exception("Simple FileRetriever not implemented!");
	case 1:
	return EncryptedChunkRetriever.deserialize(bin);
	default:
	throw new Exception("Unknown FileRetriever type: "+type);
    }
}

function EncryptedChunkRetriever(chunkNonce, chunkAuth, fragmentHashes, nextChunk) {
    this.chunkNonce = chunkNonce;
    this.chunkAuth = chunkAuth;
    this.fragmentHashes = fragmentHashes;
    this.nextChunk = nextChunk;

    this.getFile = function(context, dataKey) {
	return new LazyInputStreamCombiner(this, context, dataKey);
    }

    this.getChunkInputStream = function(context, dataKey) {
	var fragments = context.downloadFragments(fragmentHashes);
	// reorder(fragments, fragmentHashes);
	var cipherText = Erasure.recombine(fragments, Chunk.MAX_SIZE, EncryptedChunk.ERASURE_ORIGINAL, EncryptedChunk.ERASURE_ALLOWED_FAILURES);
	var fullEncryptedChunk = new EncryptedChunk(concat(chunkAuth, cipherText));
        var original = fullEncryptedChunk.decrypt(dataKey, chunkNonce);
	return new ByteBuffer(original);
    }

    this.serialize = function(buf) {
	buf.writeUnsignedByte(1); // This class
	buf.writeArray(chunkNonce);
	buf.writeArray(chunkAuth);
	buf.writeArray(concat(fragmentHashes));
	buf.writeUnsignedByte(nextChunk != null ? 1 : 0);
	if (nextChunk != null)
	    nextChunk.serialize(buf);
    }
}
EncryptedChunkRetriever.deserialize = function(buf) {
    var chunkNonce = buf.readArray();
    var chunkAuth = buf.readArray();
    var concatFragmentHashes = buf.readArray();
    var fragmentHashes = split(concatFragmentHashes, UserPublicKey.HASH_BYTES);
    var hasNext = buf.readUnsignedByte();
    var nextChunk = null;
    if (hasNext == 1)
	nextChunk = Location.deserialize(buf);
    return new EncryptedChunkRetriever(chunkNonce, chunkAuth, fragmentHashes, nextChunk);
}

function LazyInputStreamCombiner() {

}

var Erasure = {};
Erasure.recombine = function(fragments, truncateTo, originalBlobs, allowedFailures) {

}

function string2arraybuffer(str) {
  var buf = new ArrayBuffer(str.length);
  var bufView = new Uint8Array(buf);
  for (var i=0, strLen=str.length; i<strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return bufView;
}
<|endoftext|>


<commit_before>import defineReactivePlugin from './utils/private/define-reactive-plugin.js'
import materialIcons from '../icon-set/material-icons.js'

const Plugin = defineReactivePlugin({
  iconMapFn: null,
  __icons: {}
}, {
  set (setObject, ssrContext) {
    const def = { ...setObject, rtl: setObject.rtl === true }

    if (__QUASAR_SSR_SERVER__) {
      if (ssrContext === void 0) {
        console.error('SSR ERROR: second param required: Quasar.iconSet.set(iconSet, ssrContext)')
        return
      }

      def.set = ssrContext.$q.iconSet.set
      Object.assign(ssrContext.$q.iconSet, def)
    }
    else {
      def.set = Plugin.set
      Object.assign(Plugin.__icons, def)
    }
  },

  install ({ $q, iconSet, ssrContext }) {
    if (__QUASAR_SSR_SERVER__) {
      const initialSet = iconSet || materialIcons

      $q.iconMapFn = ssrContext.$q.config.iconMapFn || Plugin.iconMapFn || null
      $q.iconSet = {}
      $q.iconSet.set = setObject => {
        this.set(setObject, ssrContext)
      }

      $q.iconSet.set(initialSet)
    }
    else {
      if ($q.config.iconMapFn !== void 0) {
        Plugin.iconMapFn = $q.config.iconMapFn
      }

      $q.iconSet = Plugin.__icons

      Object.defineProperty($q, 'iconMapFn', {
        get: () => Plugin.iconMapFn,
        set: val => { Plugin.iconMapFn = val }
      })

      if (this.__installed === true) {
        iconSet !== void 0 && this.set(iconSet)
      }
      else {
        this.set(iconSet || materialIcons)
      }
    }
  }
})

export default Plugin
<commit_msg>feat(ui): one more tweak to iconSet<commit_after>import defineReactivePlugin from './utils/private/define-reactive-plugin.js'
import materialIcons from '../icon-set/material-icons.js'

const Plugin = defineReactivePlugin({
  iconMapFn: null,
  __icons: {}
}, {
  set (setObject, ssrContext) {
    const def = { ...setObject, rtl: setObject.rtl === true }

    if (__QUASAR_SSR_SERVER__) {
      if (ssrContext === void 0) {
        console.error('SSR ERROR: second param required: Quasar.iconSet.set(iconSet, ssrContext)')
        return
      }

      def.set = ssrContext.$q.iconSet.set
      Object.assign(ssrContext.$q.iconSet, def)
    }
    else {
      def.set = Plugin.set
      Object.assign(Plugin.__icons, def)
    }
  },

  install ({ $q, iconSet, ssrContext }) {
    if (__QUASAR_SSR_SERVER__) {
      const initialSet = iconSet || materialIcons

      $q.iconMapFn = ssrContext.$q.config.iconMapFn || this.iconMapFn || null
      $q.iconSet = {}
      $q.iconSet.set = setObject => {
        this.set(setObject, ssrContext)
      }

      $q.iconSet.set(initialSet)
    }
    else {
      if ($q.config.iconMapFn !== void 0) {
        this.iconMapFn = $q.config.iconMapFn
      }

      $q.iconSet = this.__icons

      Object.defineProperty($q, 'iconMapFn', {
        get: () => this.iconMapFn,
        set: val => { this.iconMapFn = val }
      })

      if (this.__installed === true) {
        iconSet !== void 0 && this.set(iconSet)
      }
      else {
        this.set(iconSet || materialIcons)
      }
    }
  }
})

export default Plugin
<|endoftext|>