<commit_before>$(function() {
    if ($('body').hasClass('restaurant domain-com')) {
        // if page is a restaurant listing
        init();                     // render link and text box into page

        getResInfo(function (name, location) {

            getResID(name, location, function (id, rating, link, count) {

                getReviews(id, rating, link, function (result, avgResult, link) {
                        $yelp.text('');
                        renderOverall(avgResult, link, count);
                        var $reviewBox = $(document.createElement('div'));
                        $reviewBox.addClass('reviews-results');
                        $yelpBox.append($reviewBox);
                        $yelpBox.find('.reviews-results').css({
                            "padding": "20px"
                        });
                        $.each(result, renderReviews);
                    }
                    , function (string) {
                        $yelp.text(string);
                    });
            }, function (string) {
                $yelp.text(string);
            })

        })
    }

// callback is function(string, string)
// grabs restaurant information from page as queryString for ID search
function getResInfo(callback) {
    var $resName = $('div.profile-header-meta h1').text();
    var $resLoc = $('div.content-block-map-info div').text();

    callback($resName, $resLoc);
}

// callback is function(string, string, string, string)
// grabs restaurant id from api call and passes to review retriever
function getResID(name, location, callback, errorCallback) {
    $.ajax({
        url: "https://api.yelp.com/v3/businesses/search",
        type: "get",
        data: {
            term: name,
            location: location,
            limit: 1
        },
        headers: {"Authorization": "Bearer YT5DWSAAKlqAAer0-rapgayJp2Zk6XmKQ3i58uOnMJXCpWFo-Rf2-aAvJb0JbZ3Ypr3pC9bE-EiQtHiXLGDSCXxW_j62f7dCbIiKYKkylNVReTsFMkKHaYw-CTyiWHYx"},
        success: function(response){
            if(response.length < 1) {
                errorCallback('Restaurant not found');
                return;
            }

            var $resID = response.businesses[0].id;
            var $resRating = response.businesses[0].rating;
            var $resLink = response.businesses[0].url;
            var $resTotalCount = response.businesses[0].review_count;
            callback($resID, $resRating, $resLink, $resTotalCount);

        },
        error: function() {
            errorCallback('Error retrieving business information.');
        }

    });
}

// callback is function(array, double, string)
// grabs reviews from 2nd api call and passes result and avgRating to renderer
function getReviews(id, rating, link, callback, errorCallback) {

    $.ajax({
        url: "https://api.yelp.com/v3/businesses/" + id + "/reviews",
        type: "get",
        headers: {"Authorization": "Bearer YT5DWSAAKlqAAer0-rapgayJp2Zk6XmKQ3i58uOnMJXCpWFo-Rf2-aAvJb0JbZ3Ypr3pC9bE-EiQtHiXLGDSCXxW_j62f7dCbIiKYKkylNVReTsFMkKHaYw-CTyiWHYx"},
        success: function(response){
            if(response.length < 1) {
                errorCallback('No reviews found');
                return;
            }

            var result = [];               // store reviews in an array
            var avgRating = rating;
            for(var x = 0; x < 3; x++) {
                result.push({
                    text: response.reviews[x].text,
                    score: response.reviews[x].rating,
                    url: response.reviews[x].url,
                    name: response.reviews[x].user.name,
                    time: response.reviews[x].time_created
                });
            }

            callback(result, avgRating, link);

        },
        error: function() {
            errorCallback('Error grabbing reviews');
        }

    })
}

// Overall construction of review section before review insertion
function renderOverall(avgResult, link, count) {
    var $row = $(document.createElement('div'));
    $row.addClass('row');

    var $leftCol1 = $(document.createElement('div'));
    $leftCol1.addClass('column small-3 medium-2');
    var $leftCol2 = $(document.createElement('div'));
    $leftCol2.addClass('review-overall-score');
    var $msg1 = $(document.createElement('h1'));

    var $linkWrapper2 = $(document.createElement('a'));
    $linkWrapper2.attr('href', link);
    $linkWrapper2.append(avgResult);

    $msg1.append($linkWrapper2);
    $leftCol2.append($msg1);
    $leftCol1.append($leftCol2);
    $row.append($leftCol1);

    var $rightCol1 = $(document.createElement('div'));
    $rightCol1.addClass('column small-9 medium-10');
    var $rightCol2 = $(document.createElement('div'));
    $rightCol2.addClass('reviews-overall-info');

    var $rightCol3 = $(document.createElement('div'));
    $rightCol3.addClass('star-rating margin-bottom-small');

    var $newLink = $(document.createElement('a'));
    $newLink.text('Average Yelp Score');
    $newLink.prop('href', link);
    var $linkHolder = $(document.createElement('h4'));
    $linkHolder.append($newLink);

    var $span = $(document.createElement('span'));
    var $newMsg = "Based on " + count + " Yelp reviews";

    var $linkWrapper3 = $(document.createElement('a'));
    $linkWrapper3.attr('href', link);
    $linkWrapper3.append($newMsg);

    $span.append($linkWrapper3);
    $span.addClass('star-rating-text color-light hide-for-xsmall-only');

    var $starW = $(document.createElement('div'));
    $starW.addClass('star-wrapper small');

    var $yelpStars = $(document.createElement('img'));
    var $chooser = toStar(avgResult);
    $yelpStars.attr('src', $chooser);

    var $linkWrapper = $(document.createElement('a'));
    $linkWrapper.attr('href', this.url);
    $linkWrapper.append($yelpStars);

    $starW.append($linkWrapper);
    $rightCol3.append($starW);
    $rightCol3.append($span);

    $rightCol2.append($linkHolder);
    $rightCol2.append($rightCol3);
    $rightCol1.append($rightCol2);
    $row.append($rightCol1);
    $yelp.append($row);

    var $img = $(document.createElement('img'));
    var imgURL = chrome.extension.getURL("images/logo.png");
    $img.attr('src', imgURL);
    var $imgLink = $(document.createElement('a'));
    $imgLink.attr('href', "https://www.yelp.com/");
    $imgLink.append($img);
    $yelpBox.append($imgLink);

    $yelpBox.css({
        "position" : "relative"
    });
    $img.css({
        "position" : "absolute",
        "top" : "0px",
        "right" : "0px"
    });
    $leftCol1.css({
        "padding-left" : "70px"
    });
}

function renderReviews() {
    var msg = this.text;
    var $row = $(document.createElement('div'));
    $row.addClass('row');

    var $container = $(document.createElement('div'));
    $container.addClass('column medium-9');

    var $main = $(document.createElement('div'));
    $main.addClass('review-main');

    var $content = $(document.createElement('div'));
    $content.addClass('review-content');
    $content.prop('lang', 'en-US');

    var $review = $(document.createElement('p'));
    var $link = $(document.createElement('a'));
    $link.prop('href', this.url);
    $link.append("Click here to read more on Yelp...");
    $review.append(msg);
    $review.append($link);
    $content.append($review);

    var $meta = $(document.createElement('div'));
    $meta.addClass('review-meta');

    var $stars = $(document.createElement('div'));
    $stars.addClass('star-rating');

    var $starW = $(document.createElement('div'));
    $starW.addClass('star-wrapper');

    var $yelpStars = $(document.createElement('img'));
    var $chooser = toStar(this.score);
    $yelpStars.attr('src', $chooser);

    var $linkWrapper = $(document.createElement('a'));
    $linkWrapper.attr('href', this.url);
    $linkWrapper.append($yelpStars);

    $starW.append($linkWrapper);
    $stars.append($starW);
    $meta.append($stars);

    var $span1 = $(document.createElement('span'));
    $span1.addClass('color-light');

    var $spanSpan = $(document.createElement('span'));
    $spanSpan.addClass('review-meta-user');
    var $spanDiv = $(document.createElement('div'));
    $spanDiv.addClass('review-diner-info');

    var $spanWrap = $(document.createElement('span'));
    var $spanAuth = $(document.createElement('span'));
    $spanAuth.append(this.name);

    $spanWrap.append($spanAuth);
    $spanDiv.append($spanWrap);
    $span1.append($spanSpan);
    $span1.append($spanDiv);

    var $span2 = $(document.createElement('span'));
    $span2.addClass('color-light review-meta-separator');
    $span2.append('.');

    var $span3 = $(document.createElement('span'));
    $span3.addClass('color-light');
    var date = "Dined on " + this.time;
    $span3.append(date);

    $meta.append($span1);
    $meta.append($span2);
    $meta.append($span3);

    var $text = $(document.createElement('h4'));
    $text.addClass('review-title hide');
    $text.prop('lang','en-US');
    $text.text(this.text);
    $main.append($text);

    $main.append($meta);
    $main.append($content);
    $container.append($main);
    $row.append($container);
    $yelpBox.find('.reviews-results').append($row);
    $yelpBox.find('.reviews-results').append('<br>');
    $starW.css({
        "padding-top" : "3px"
    });
    $span3.css({
        "padding-top" : "11px"
    });
    $span2.css({
        "padding-top" : "6px"
    });
}

// returns extension rooted URL for appropriate stars image
function toStar(rating) {
    var star0 = chrome.extension.getURL("images/small_0.png");
    var star1 = chrome.extension.getURL("images/small_1.png");
    var star1half = chrome.extension.getURL("images/small_1_half.png");
    var star2 = chrome.extension.getURL("images/small_2.png");
    var star2half = chrome.extension.getURL("images/small_2_half.png");
    var star3 = chrome.extension.getURL("images/small_3.png");
    var star3half = chrome.extension.getURL("images/small_3_half.png");
    var star4 = chrome.extension.getURL("images/small_4.png");
    var star4half = chrome.extension.getURL("images/small_4_half.png");
    var star5 = chrome.extension.getURL("images/small_5.png");

    if (rating >= 5) {
        return star5;
    } else if (rating >= 4.5) {
        return star4half;
    } else if (rating >= 4) {
        return star4;
    } else if (rating >= 3.5) {
        return star3half;
    } else if (rating >= 3) {
        return star3;
    } else if (rating >=2.5) {
        return star2half;
    } else if (rating >=2) {
        return star2;
    } else if (rating >= 1.5) {
        return star1half;
    } else if (rating >= 1) {
        return star1;
    } else return star0;
}

// sets up page in preparation for api request
function init() {
    var $yelpLink = $(document.createElement('li'));
    $yelpLink.addClass('yelp-link');
    var $inside = $(document.createElement('a'));
    $inside.addClass('page-nav-link');
    $inside.text('Yelp Reviews');
    $inside.attr('href', '#yelp');
    $yelpLink.append($inside);
    $('nav.page-nav ul').append($yelpLink);  // finished inserting link

    var $yelpBox = $(document.createElement('div'));
    $yelpBox.addClass('content-block main-container');
    $yelpBox.attr('id', 'yelp');

    var $yelpSubBox = $(document.createElement('div'));
    $yelpSubBox.addClass('content-block-header');
    $yelpSubBox.html('<h3> Loading Yelp reviews.... </h3>');
    $yelpBox.append($yelpSubBox);
    var $appendSpot = $('div.column').not('.small-6, .medium-6, .medium-3, .medium-9, .medium-10, .small-3, .medium-2, .medium-12, .large-2, .small-9');
    $appendSpot.children().last().before($yelpBox);
}

var $yelp = $('#yelp div');
var $yelpBox = $('#yelp');
});

<commit_msg>Update main.js<commit_after>$(function() {
    if ($('body').hasClass('restaurant domain-com')) {
        // if page is a restaurant listing
        init();                     // render link and text box into page

        getResInfo(function (name, location) {

            getResID(name, location, function (id, rating, link, count) {

                getReviews(id, rating, link, function (result, avgResult, link) {
                        $yelp.text('');
                        renderOverall(avgResult, link, count);
                        var $reviewBox = $(document.createElement('div'));
                        $reviewBox.addClass('reviews-results');
                        $yelpBox.append($reviewBox);
                        $yelpBox.find('.reviews-results').css({
                            "padding": "20px"
                        });
                        $.each(result, renderReviews);
                    }
                    , function (string) {
                        $yelp.text(string);
                    });
            }, function (string) {
                $yelp.text(string);
            })

        })
    }

// callback is function(string, string)
// grabs restaurant information from page as queryString for ID search
function getResInfo(callback) {
    var $resName = $('div.profile-header-meta h1').text();
    var $resLoc = $('div.content-block-map-info div').text();

    callback($resName, $resLoc);
}

// callback is function(string, string, string, string)
// grabs restaurant id from api call and passes to review retriever
function getResID(name, location, callback, errorCallback) {
    $.ajax({
        url: "https://api.yelp.com/v3/businesses/search",
        type: "get",
        data: {
            term: name,
            location: location,
            limit: 1
        },
        headers: {"Authorization": "Bearer placeholder"},
        success: function(response){
            if(response.length < 1) {
                errorCallback('Restaurant not found');
                return;
            }

            var $resID = response.businesses[0].id;
            var $resRating = response.businesses[0].rating;
            var $resLink = response.businesses[0].url;
            var $resTotalCount = response.businesses[0].review_count;
            callback($resID, $resRating, $resLink, $resTotalCount);

        },
        error: function() {
            errorCallback('Error retrieving business information.');
        }

    });
}

// callback is function(array, double, string)
// grabs reviews from 2nd api call and passes result and avgRating to renderer
function getReviews(id, rating, link, callback, errorCallback) {

    $.ajax({
        url: "https://api.yelp.com/v3/businesses/" + id + "/reviews",
        type: "get",
        headers: {"Authorization": "Bearer placeholder"},
        success: function(response){
            if(response.length < 1) {
                errorCallback('No reviews found');
                return;
            }

            var result = [];               // store reviews in an array
            var avgRating = rating;
            for(var x = 0; x < 3; x++) {
                result.push({
                    text: response.reviews[x].text,
                    score: response.reviews[x].rating,
                    url: response.reviews[x].url,
                    name: response.reviews[x].user.name,
                    time: response.reviews[x].time_created
                });
            }

            callback(result, avgRating, link);

        },
        error: function() {
            errorCallback('Error grabbing reviews');
        }

    })
}

// Overall construction of review section before review insertion
function renderOverall(avgResult, link, count) {
    var $row = $(document.createElement('div'));
    $row.addClass('row');

    var $leftCol1 = $(document.createElement('div'));
    $leftCol1.addClass('column small-3 medium-2');
    var $leftCol2 = $(document.createElement('div'));
    $leftCol2.addClass('review-overall-score');
    var $msg1 = $(document.createElement('h1'));

    var $linkWrapper2 = $(document.createElement('a'));
    $linkWrapper2.attr('href', link);
    $linkWrapper2.append(avgResult);

    $msg1.append($linkWrapper2);
    $leftCol2.append($msg1);
    $leftCol1.append($leftCol2);
    $row.append($leftCol1);

    var $rightCol1 = $(document.createElement('div'));
    $rightCol1.addClass('column small-9 medium-10');
    var $rightCol2 = $(document.createElement('div'));
    $rightCol2.addClass('reviews-overall-info');

    var $rightCol3 = $(document.createElement('div'));
    $rightCol3.addClass('star-rating margin-bottom-small');

    var $newLink = $(document.createElement('a'));
    $newLink.text('Average Yelp Score');
    $newLink.prop('href', link);
    var $linkHolder = $(document.createElement('h4'));
    $linkHolder.append($newLink);

    var $span = $(document.createElement('span'));
    var $newMsg = "Based on " + count + " Yelp reviews";

    var $linkWrapper3 = $(document.createElement('a'));
    $linkWrapper3.attr('href', link);
    $linkWrapper3.append($newMsg);

    $span.append($linkWrapper3);
    $span.addClass('star-rating-text color-light hide-for-xsmall-only');

    var $starW = $(document.createElement('div'));
    $starW.addClass('star-wrapper small');

    var $yelpStars = $(document.createElement('img'));
    var $chooser = toStar(avgResult);
    $yelpStars.attr('src', $chooser);

    var $linkWrapper = $(document.createElement('a'));
    $linkWrapper.attr('href', this.url);
    $linkWrapper.append($yelpStars);

    $starW.append($linkWrapper);
    $rightCol3.append($starW);
    $rightCol3.append($span);

    $rightCol2.append($linkHolder);
    $rightCol2.append($rightCol3);
    $rightCol1.append($rightCol2);
    $row.append($rightCol1);
    $yelp.append($row);

    var $img = $(document.createElement('img'));
    var imgURL = chrome.extension.getURL("images/logo.png");
    $img.attr('src', imgURL);
    var $imgLink = $(document.createElement('a'));
    $imgLink.attr('href', "https://www.yelp.com/");
    $imgLink.append($img);
    $yelpBox.append($imgLink);

    $yelpBox.css({
        "position" : "relative"
    });
    $img.css({
        "position" : "absolute",
        "top" : "0px",
        "right" : "0px"
    });
    $leftCol1.css({
        "padding-left" : "70px"
    });
}

function renderReviews() {
    var msg = this.text;
    var $row = $(document.createElement('div'));
    $row.addClass('row');

    var $container = $(document.createElement('div'));
    $container.addClass('column medium-9');

    var $main = $(document.createElement('div'));
    $main.addClass('review-main');

    var $content = $(document.createElement('div'));
    $content.addClass('review-content');
    $content.prop('lang', 'en-US');

    var $review = $(document.createElement('p'));
    var $link = $(document.createElement('a'));
    $link.prop('href', this.url);
    $link.append("Click here to read more on Yelp...");
    $review.append(msg);
    $review.append($link);
    $content.append($review);

    var $meta = $(document.createElement('div'));
    $meta.addClass('review-meta');

    var $stars = $(document.createElement('div'));
    $stars.addClass('star-rating');

    var $starW = $(document.createElement('div'));
    $starW.addClass('star-wrapper');

    var $yelpStars = $(document.createElement('img'));
    var $chooser = toStar(this.score);
    $yelpStars.attr('src', $chooser);

    var $linkWrapper = $(document.createElement('a'));
    $linkWrapper.attr('href', this.url);
    $linkWrapper.append($yelpStars);

    $starW.append($linkWrapper);
    $stars.append($starW);
    $meta.append($stars);

    var $span1 = $(document.createElement('span'));
    $span1.addClass('color-light');

    var $spanSpan = $(document.createElement('span'));
    $spanSpan.addClass('review-meta-user');
    var $spanDiv = $(document.createElement('div'));
    $spanDiv.addClass('review-diner-info');

    var $spanWrap = $(document.createElement('span'));
    var $spanAuth = $(document.createElement('span'));
    $spanAuth.append(this.name);

    $spanWrap.append($spanAuth);
    $spanDiv.append($spanWrap);
    $span1.append($spanSpan);
    $span1.append($spanDiv);

    var $span2 = $(document.createElement('span'));
    $span2.addClass('color-light review-meta-separator');
    $span2.append('.');

    var $span3 = $(document.createElement('span'));
    $span3.addClass('color-light');
    var date = "Dined on " + this.time;
    $span3.append(date);

    $meta.append($span1);
    $meta.append($span2);
    $meta.append($span3);

    var $text = $(document.createElement('h4'));
    $text.addClass('review-title hide');
    $text.prop('lang','en-US');
    $text.text(this.text);
    $main.append($text);

    $main.append($meta);
    $main.append($content);
    $container.append($main);
    $row.append($container);
    $yelpBox.find('.reviews-results').append($row);
    $yelpBox.find('.reviews-results').append('<br>');
    $starW.css({
        "padding-top" : "3px"
    });
    $span3.css({
        "padding-top" : "11px"
    });
    $span2.css({
        "padding-top" : "6px"
    });
}

// returns extension rooted URL for appropriate stars image
function toStar(rating) {
    var star0 = chrome.extension.getURL("images/small_0.png");
    var star1 = chrome.extension.getURL("images/small_1.png");
    var star1half = chrome.extension.getURL("images/small_1_half.png");
    var star2 = chrome.extension.getURL("images/small_2.png");
    var star2half = chrome.extension.getURL("images/small_2_half.png");
    var star3 = chrome.extension.getURL("images/small_3.png");
    var star3half = chrome.extension.getURL("images/small_3_half.png");
    var star4 = chrome.extension.getURL("images/small_4.png");
    var star4half = chrome.extension.getURL("images/small_4_half.png");
    var star5 = chrome.extension.getURL("images/small_5.png");

    if (rating >= 5) {
        return star5;
    } else if (rating >= 4.5) {
        return star4half;
    } else if (rating >= 4) {
        return star4;
    } else if (rating >= 3.5) {
        return star3half;
    } else if (rating >= 3) {
        return star3;
    } else if (rating >=2.5) {
        return star2half;
    } else if (rating >=2) {
        return star2;
    } else if (rating >= 1.5) {
        return star1half;
    } else if (rating >= 1) {
        return star1;
    } else return star0;
}

// sets up page in preparation for api request
function init() {
    var $yelpLink = $(document.createElement('li'));
    $yelpLink.addClass('yelp-link');
    var $inside = $(document.createElement('a'));
    $inside.addClass('page-nav-link');
    $inside.text('Yelp Reviews');
    $inside.attr('href', '#yelp');
    $yelpLink.append($inside);
    $('nav.page-nav ul').append($yelpLink);  // finished inserting link

    var $yelpBox = $(document.createElement('div'));
    $yelpBox.addClass('content-block main-container');
    $yelpBox.attr('id', 'yelp');

    var $yelpSubBox = $(document.createElement('div'));
    $yelpSubBox.addClass('content-block-header');
    $yelpSubBox.html('<h3> Loading Yelp reviews.... </h3>');
    $yelpBox.append($yelpSubBox);
    var $appendSpot = $('div.column').not('.small-6, .medium-6, .medium-3, .medium-9, .medium-10, .small-3, .medium-2, .medium-12, .large-2, .small-9');
    $appendSpot.children().last().before($yelpBox);
}

var $yelp = $('#yelp div');
var $yelpBox = $('#yelp');
});

<|endoftext|>


<commit_before>'use strict';

var React = require('react');
var zip = require('annozip');

var Table = require('./table.jsx');

var App = React.createClass({
    getInitialState() {
        var that = this;
        var countries = {
            'de': 'Germany',
            'fi': 'Finland',
            'se': 'Sweden'
        };

        return {
            data: [
                {
                    name: 'Jack Jackson',
                    position: 'Boss',
                    salary: 10000,
                    country: 'se',
                    active: true,
                },
                {
                    name: 'Bo Bobson',
                    position: 'Contractor',
                    salary: 4650.9234,
                    country: 'de',
                    active: false,
                },
                {
                    name: 'Cecilia Robertson',
                    position: 'Client',
                    salary: 6499.1038,
                    country: 'fi',
                    active: true,
                }
            ],
            columns: [
                {
                    property: 'name',
                    header: 'Name',
                    editable: true,
                },
                {
                    property: 'position',
                    header: 'Position',
                },
                {
                    property: 'country',
                    header: 'Country',
                    formatter: (country) => countries[country],
                    editable: true,
                    editor: (active, done) => {
                        var handleChange = (e) =>
                            done(e.target.value);

                        return <select onChange={handleChange} value={active}>
                            {zip(countries).map((pair, i) =>
                                <option
                                    key={i}
                                    value={pair[0]}
                                >{pair[1]}</option>
                            )}
                        </select>
                    },
                },
                {
                    property: 'salary',
                    header: 'Salary',
                    editable: true,
                    formatter: (salary) => parseFloat(salary).toFixed(2),
                },
                {
                    property: 'active',
                    header: 'Active',
                    editable: true,
                    editor: (active, done) =>

                            <button
                                disabled={active}
                                onClick={done.bind(null, true)}
                            >✓
                            </button>
                            <button
                                disabled={!active}
                                onClick={done.bind(null, false)}
                            >✗
                            </button>

                    ,
                    formatter: (active) => active && ✓,
                },
                {
                    cell: (i) => {
                        var remove = () => {
                            // this could go through flux etc.
                            delete that.state.data[i];

                            that.setState({
                                data: that.state.data
                            });
                        };

                        return
                            ✗
                        ;
                    },
                }
            ]
        };
    },

    render() {
        var that = this;
        var columns = this.state.columns;
        var data = this.state.data;

        var config = {
            columns: columns,
            events: {
                // you could hook these with flux etc.
                selectedHeader: (column) => {
                    var property = column.property;

                    columns.map((column) => {
                        column.classes = {};

                        return column;
                    });

                    column.sort = column.sort? -column.sort: 1;
                    column.classes = {
                        'sort-asc': column.sort === 1,
                        'sort-desc': column.sort === -1
                    };

                    data.sort((a, b) => {
                        if(a[property].localeCompare) {
                            return a[property].localeCompare(b[property]) * column.sort;
                        }

                        return a[property] - b[property] * column.sort;
                    });

                    that.setState({
                        columns: columns,
                        data: data
                    });
                },
                edited: (i, property, value) => {
                    data[i][property] = value;

                    that.setState({
                        data: data
                    });
                }
            }
        };

        return

;
    }
});

module.exports = App;
<commit_msg>Move country editor handler inline<commit_after>'use strict';

var React = require('react');
var zip = require('annozip');

var Table = require('./table.jsx');

var App = React.createClass({
    getInitialState() {
        var that = this;
        var countries = {
            'de': 'Germany',
            'fi': 'Finland',
            'se': 'Sweden'
        };

        return {
            data: [
                {
                    name: 'Jack Jackson',
                    position: 'Boss',
                    salary: 10000,
                    country: 'se',
                    active: true,
                },
                {
                    name: 'Bo Bobson',
                    position: 'Contractor',
                    salary: 4650.9234,
                    country: 'de',
                    active: false,
                },
                {
                    name: 'Cecilia Robertson',
                    position: 'Client',
                    salary: 6499.1038,
                    country: 'fi',
                    active: true,
                }
            ],
            columns: [
                {
                    property: 'name',
                    header: 'Name',
                    editable: true,
                },
                {
                    property: 'position',
                    header: 'Position',
                },
                {
                    property: 'country',
                    header: 'Country',
                    formatter: (country) => countries[country],
                    editable: true,
                    editor: (active, done) => {
                        return <select onChange={(e) => done(e.target.value)} value={active}>
                            {zip(countries).map((pair, i) =>
                                <option
                                    key={i}
                                    value={pair[0]}
                                >{pair[1]}</option>
                            )}
                        </select>
                    },
                },
                {
                    property: 'salary',
                    header: 'Salary',
                    editable: true,
                    formatter: (salary) => parseFloat(salary).toFixed(2),
                },
                {
                    property: 'active',
                    header: 'Active',
                    editable: true,
                    editor: (active, done) =>

                            <button
                                disabled={active}
                                onClick={done.bind(null, true)}
                            >✓
                            </button>
                            <button
                                disabled={!active}
                                onClick={done.bind(null, false)}
                            >✗
                            </button>

                    ,
                    formatter: (active) => active && ✓,
                },
                {
                    cell: (i) => {
                        var remove = () => {
                            // this could go through flux etc.
                            delete that.state.data[i];

                            that.setState({
                                data: that.state.data
                            });
                        };

                        return
                            ✗
                        ;
                    },
                }
            ]
        };
    },

    render() {
        var that = this;
        var columns = this.state.columns;
        var data = this.state.data;

        var config = {
            columns: columns,
            events: {
                // you could hook these with flux etc.
                selectedHeader: (column) => {
                    var property = column.property;

                    columns.map((column) => {
                        column.classes = {};

                        return column;
                    });

                    column.sort = column.sort? -column.sort: 1;
                    column.classes = {
                        'sort-asc': column.sort === 1,
                        'sort-desc': column.sort === -1
                    };

                    data.sort((a, b) => {
                        if(a[property].localeCompare) {
                            return a[property].localeCompare(b[property]) * column.sort;
                        }

                        return a[property] - b[property] * column.sort;
                    });

                    that.setState({
                        columns: columns,
                        data: data
                    });
                },
                edited: (i, property, value) => {
                    data[i][property] = value;

                    that.setState({
                        data: data
                    });
                }
            }
        };

        return

;
    }
});

module.exports = App;
<|endoftext|>


<commit_before>/**
 * Stupid angularjs doesn't block this event
 * @param  {[type]} e [description]
 * @return {[type]}   [description]
 */
$($(document).keydown(function(e) {
	if (e.which === 8) {
		//your custom action here
		return false;
	}
}));

/**
 * Just one controller no need of fancy angular.module syntax
 * @param {object} $scope
 */
function MainController($scope, $parse) {
	$scope.swimlanes = []
	$scope.keySequence = '';
	$scope.err = '';
	var allCommands = [];
	var counter = 0;

	/**
	 * Restores state or creates new one
	 * @return {[type]} [description]
	 */
	function boot() {
		var lanes = window.localStorage.getItem('wq') || [];
		if (lanes.length !== 0) {
			$scope.swimlanes = JSON.parse(lanes);
		}
	}

	/**
	 * Main command map, delegates responsibilities to respective functions
	 * @type {Object}
	 */
	var commandMap = {
		'ns': newSwimlane,
		'nt': newTask,
		'dn': toggleTask,
		'mv': 'mv',
		'delt': deleteTask,
		'dels': deleteSwimlane,
		'eds': editSwimlane,
		'edt': editTask,
		'help': showHelp,
		'x': closeHelp,
		'clean': 'clean',
		'exp': 'exp'
	};

	function showHelp() {
		$scope.help = true;
	}

	function closeHelp() {
		$scope.help = false;
	}

	/**
	 * changes the name of a swimlane
	 * @param  {[type]} cmd [description]
	 * @return {[type]}     [description]
	 */
	function editSwimlane(cmd) {
		var laneId = makeInt(cmd.args.shift());
		var name = cmd.args.join(" ") || promptForText("Give me a new name", $scope.swimlanes[laneId].name);
		$scope.swimlanes[laneId].name = name;
	}

	/**
	 * Edit a task
	 * @param  {object} cmd [description]
	 * @return {[type]}     [description]
	 */
	function editTask(cmd) {
		var laneId = makeInt(cmd.args.shift());
		var taskId = makeInt(cmd.args.shift());
		var name = cmd.args.join(" ") || promptForText("Give me a new name", $scope.swimlanes[laneId].tasks[taskId].name);
		$scope.swimlanes[laneId].tasks[taskId].name = name;
	}

	/**
	 * Removes a task
	 * @param  {[type]} cmd [description]
	 * @return {[type]}     [description]
	 */
	function deleteTask(cmd) {
		var laneId = makeInt(cmd.args.shift());
		var taskId = makeInt(cmd.args.shift());
		$scope.swimlanes[laneId].tasks = $scope.swimlanes[laneId].tasks.splice(taskId, 1);
	}

	/**
	 * toggles the state of task from done to normal
	 * @param  {[type]} cmd [description]
	 * @return {[type]}     [description]
	 */
	function toggleTask(cmd) {
		var laneId = getSwimlaneId(cmd);
		var taskIdExp = cmd.args.shift();
		parseTaskIdExpression(taskIdExp).forEach(function(d) {
			$scope.swimlanes[laneId].tasks[d].state = $scope.swimlanes[laneId].tasks[d].state === 'done' ? '' : 'done';
		})
	}

	/**
	 * Add a new swimlane
	 * @param  {object} cmd
	 * @return {[type]}     [description]
	 */
	function newSwimlane(cmd) {
		var name = cmd.args.join(" ") || promptForText("Give your new swimlane a name", "work");
		$scope.swimlanes.push({
			name: name,
			tasks: []
		});
	}

	/**
	 * Creates a new task
	 * @param  {object}  cmd         [description]
	 * @param  {Boolean} isImportant [description]
	 * @return {[type]}              [description]
	 */
	function newTask(cmd) {
		var laneId = getSwimlaneId(cmd);
		var name = cmd.args.join(" ") || promptForText("So you wanna add a task ?", "this is so awesome");
		$scope.swimlanes[laneId].tasks.push({
			name: name,
			important: cmd.args.indexOf("-i") != -1 ? 'important' : ''
		});
	}

	/**
	 * deletes a swimlane
	 * @param  {[type]} id [description]
	 * @return {[type]}    [description]
	 */
	function deleteSwimlane(cmd) {
		var id = makeInt(cmd.args.shift());
		$scope.swimlanes = $scope.swimlanes.splice(id, 1);
	}

	/**
	 * Primary interface for keypress event throughout the window
	 * @param  {[type]} ev [description]
	 * @return {[type]}    [description]
	 */
	$scope.keyPressed = function(ev) {

		switch (ev.which) {
			case 8: //if backspace
				$scope.keySequence = $scope.keySequence.substring(0, $scope.keySequence.length - 1)
				return;

			case 27: //if esc clear sequence
				$scope.keySequence = '';
				return;

			case 38: //Up arrow
				$scope.keySequence = allCommands[counter++ % allCommands.length];
				return

			case 40: //Down arrow
				$scope.keySequence = allCommands[--counter % allCommands.length];
				return

			case 13: //its enter, time to execute stuff
				executeCommand();
				allCommands.push($scope.keySequence);
				$scope.keySequence = '';
				return;

			case 37: //left
			case 39: //right keys, return by default
				return;
		}
		//not any of above ? needs to added as sequence
		$scope.keySequence += getCharacter(ev);
		//clear previous errors if any;
		$scope.err = '';
	}

	function getCharacter(ev) {
		if (ev.which === 188) return ",";
		if (ev.which === 189) return "-";
		return String.fromCharCode(ev.keyCode || ev.which).toLowerCase();
	}

	/**
	 * Main magic
	 * @return {[type]} [description]
	 */
	function executeCommand() {
		var cmdObj = parseCommand();
		if (commandMap[cmdObj.cmd]) {
			try {
				commandMap[cmdObj.cmd](cmdObj);
			} catch (e) {
				$scope.err = e.message;
				throw e;
			}
		} else {
			$scope.err = "No such commnad " + $scope.keySequence;
		}
	}

	/**
	 * extracts commands and arguments from input string
	 * @return {[type]} [description]
	 */
	function parseCommand() {
		var commands = $scope.keySequence.trim().split(" ");
		return {
			cmd: commands.shift(),
			args: commands.map(function(d) {
				return d.trim();
			})
		};
	}

	/**
	 * Helper function for string to int conversion
	 * @param  {string} number [description]
	 * @return {[type]}        [description]
	 */
	function makeInt(number) {
		if (isNaN(parseInt(number, 10))) {
			throw new Error("invalid number entered");
		}
		return parseInt(number, 10);
	}

	function getSwimlaneId(cmd) {
		var laneId = makeInt(cmd.args.shift());
		return laneId;
	}

	function promptForText(title, defaultVal) {
		var name = prompt(title, defaultVal);
		if (!name) {
			throw new Error("Nah, empty string won't work, try again")
		}
		return name;
	}

	/**
	 * converts 1,2,3 and 1-3 to [1 2 3]
	 * Don't change the sequence, its crucial
	 * @param  {[type]} exp [description]
	 * @return {[type]}     [description]
	 */
	function parseTaskIdExpression(exp) {
		var taskIds = [];
		var sep = '';
		//comma seperated values
		if (exp.indexOf(",") !== -1) {
			sep = ',';
		}

		//range expression
		if (exp.indexOf("-") !== -1) {
			if (exp.split("-").length !== 2) {
				throw new Error("invalid range expression");
			}
			var temp = [];
			for (var i = makeInt(exp.split("-")[0]); i <= makeInt(exp.split("-")[1]); i++) {
				temp.push(i);
			};
			exp = temp.join(",");
			sep = ',';
		}

		exp.split(sep).forEach(function(d) {
			taskIds.push(makeInt(d));
		});
		return taskIds;
	}

	//save immedietly as the object changes
	$scope.$watch('swimlanes', function() {
		window.localStorage.setItem('wq', angular.toJson($scope.swimlanes));
	}, true);

	//load old things
	boot();
}<commit_msg>added mv functionality<commit_after>/**
 * Stupid angularjs doesn't block this event
 * @param  {[type]} e [description]
 * @return {[type]}   [description]
 */
$($(document).keydown(function(e) {
	if (e.which === 8) {
		//your custom action here
		return false;
	}
}));

/**
 * Just one controller no need of fancy angular.module syntax
 * @param {object} $scope
 */
function MainController($scope, $parse) {
	$scope.swimlanes = []
	$scope.keySequence = '';
	$scope.err = '';
	var allCommands = [];
	var counter = 0;

	/**
	 * Restores state or creates new one
	 * @return {[type]} [description]
	 */
	function boot() {
		var lanes = window.localStorage.getItem('wq') || [];
		if (lanes.length !== 0) {
			$scope.swimlanes = JSON.parse(lanes);
		}
	}

	/**
	 * Main command map, delegates responsibilities to respective functions
	 * @type {Object}
	 */
	var commandMap = {
		'ns': newSwimlane,
		'nt': newTask,
		'dn': toggleTask,
		'mv': moveTasks,
		'delt': deleteTask,
		'dels': deleteSwimlane,
		'eds': editSwimlane,
		'edt': editTask,
		'help': showHelp,
		'x': closeHelp,
		'clean': 'clean',
		'exp': 'exp'
	};

	function showHelp() {
		$scope.help = true;
	}

	function closeHelp() {
		$scope.help = false;
	}

	function moveTasks(cmd) {
		var laneId = getSwimlaneId(cmd);
		var taskIdExp = cmd.args.shift();
		var targetLaneId = getSwimlaneId(cmd);

		parseTaskIdExpression(taskIdExp).forEach(function(d) {
			var task = $scope.swimlanes[laneId].tasks.splice(d, 1);
			$scope.swimlanes[targetLaneId].tasks.push(task[0]);
		})
	}

	/**
	 * changes the name of a swimlane
	 * @param  {[type]} cmd [description]
	 * @return {[type]}     [description]
	 */
	function editSwimlane(cmd) {
		var laneId = makeInt(cmd.args.shift());
		var name = cmd.args.join(" ") || promptForText("Give me a new name", $scope.swimlanes[laneId].name);
		$scope.swimlanes[laneId].name = name;
	}

	/**
	 * Edit a task
	 * @param  {object} cmd [description]
	 * @return {[type]}     [description]
	 */
	function editTask(cmd) {
		var laneId = makeInt(cmd.args.shift());
		var taskId = makeInt(cmd.args.shift());
		var name = cmd.args.join(" ") || promptForText("Give me a new name", $scope.swimlanes[laneId].tasks[taskId].name);
		$scope.swimlanes[laneId].tasks[taskId].name = name;
	}

	/**
	 * Removes a task
	 * @param  {[type]} cmd [description]
	 * @return {[type]}     [description]
	 */
	function deleteTask(cmd) {
		var laneId = makeInt(cmd.args.shift());
		var taskId = makeInt(cmd.args.shift());
		$scope.swimlanes[laneId].tasks.splice(taskId, 1);
	}

	/**
	 * toggles the state of task from done to normal
	 * @param  {[type]} cmd [description]
	 * @return {[type]}     [description]
	 */
	function toggleTask(cmd) {
		var laneId = getSwimlaneId(cmd);
		var taskIdExp = cmd.args.shift();
		parseTaskIdExpression(taskIdExp).forEach(function(d) {
			$scope.swimlanes[laneId].tasks[d].state = $scope.swimlanes[laneId].tasks[d].state === 'done' ? '' : 'done';
		})
	}

	/**
	 * Add a new swimlane
	 * @param  {object} cmd
	 * @return {[type]}     [description]
	 */
	function newSwimlane(cmd) {
		var name = cmd.args.join(" ") || promptForText("Give your new swimlane a name", "work");
		$scope.swimlanes.push({
			name: name,
			tasks: []
		});
	}

	/**
	 * Creates a new task
	 * @param  {object}  cmd         [description]
	 * @param  {Boolean} isImportant [description]
	 * @return {[type]}              [description]
	 */
	function newTask(cmd) {
		var laneId = getSwimlaneId(cmd);
		var name = cmd.args.join(" ") || promptForText("So you wanna add a task ?", "this is so awesome");
		$scope.swimlanes[laneId].tasks.push({
			name: name,
			important: cmd.args.indexOf("-i") != -1 ? 'important' : ''
		});
	}

	/**
	 * deletes a swimlane
	 * @param  {[type]} id [description]
	 * @return {[type]}    [description]
	 */
	function deleteSwimlane(cmd) {
		var id = makeInt(cmd.args.shift());
		$scope.swimlanes = $scope.swimlanes.splice(id, 1);
	}

	/**
	 * Primary interface for keypress event throughout the window
	 * @param  {[type]} ev [description]
	 * @return {[type]}    [description]
	 */
	$scope.keyPressed = function(ev) {

		switch (ev.which) {
			case 8: //if backspace
				$scope.keySequence = $scope.keySequence.substring(0, $scope.keySequence.length - 1)
				return;

			case 27: //if esc clear sequence
				$scope.keySequence = '';
				return;

			case 38: //Up arrow
				$scope.keySequence = allCommands[counter++ % allCommands.length];
				return

			case 40: //Down arrow
				$scope.keySequence = allCommands[--counter % allCommands.length];
				return

			case 13: //its enter, time to execute stuff
				executeCommand();
				allCommands.push($scope.keySequence);
				$scope.keySequence = '';
				return;

			case 37: //left
			case 39: //right keys, return by default
				return;
		}
		//not any of above ? needs to added as sequence
		$scope.keySequence += getCharacter(ev);
		//clear previous errors if any;
		$scope.err = '';
	}

	function getCharacter(ev) {
		if (ev.which === 188) return ",";
		if (ev.which === 189) return "-";
		return String.fromCharCode(ev.keyCode || ev.which).toLowerCase();
	}

	/**
	 * Main magic
	 * @return {[type]} [description]
	 */
	function executeCommand() {
		var cmdObj = parseCommand();
		if (commandMap[cmdObj.cmd]) {
			try {
				commandMap[cmdObj.cmd](cmdObj);
			} catch (e) {
				$scope.err = e.message;
				throw e;
			}
		} else {
			$scope.err = "No such commnad " + $scope.keySequence;
		}
	}

	/**
	 * extracts commands and arguments from input string
	 * @return {[type]} [description]
	 */
	function parseCommand() {
		var commands = $scope.keySequence.trim().split(" ");
		return {
			cmd: commands.shift(),
			args: commands.map(function(d) {
				return d.trim();
			})
		};
	}

	/**
	 * Helper function for string to int conversion
	 * @param  {string} number [description]
	 * @return {[type]}        [description]
	 */
	function makeInt(number) {
		if (isNaN(parseInt(number, 10))) {
			throw new Error("invalid number entered");
		}
		return parseInt(number, 10);
	}

	function getSwimlaneId(cmd) {
		var laneId = makeInt(cmd.args.shift());
		return laneId;
	}

	function promptForText(title, defaultVal) {
		var name = prompt(title, defaultVal);
		if (!name) {
			throw new Error("Nah, empty string won't work, try again")
		}
		return name;
	}

	/**
	 * converts 1,2,3 and 1-3 to [1 2 3]
	 * Don't change the sequence, its crucial
	 * @param  {[type]} exp [description]
	 * @return {[type]}     [description]
	 */
	function parseTaskIdExpression(exp) {
		var taskIds = [];
		var sep = '';
		//comma seperated values
		if (exp.indexOf(",") !== -1) {
			sep = ',';
		}

		//range expression
		if (exp.indexOf("-") !== -1) {
			if (exp.split("-").length !== 2) {
				throw new Error("invalid range expression");
			}
			var temp = [];
			for (var i = makeInt(exp.split("-")[0]); i <= makeInt(exp.split("-")[1]); i++) {
				temp.push(i);
			};
			exp = temp.join(",");
			sep = ',';
		}

		exp.split(sep).forEach(function(d) {
			taskIds.push(makeInt(d));
		});
		return taskIds;
	}

	//save immedietly as the object changes
	$scope.$watch('swimlanes', function() {
		window.localStorage.setItem('wq', angular.toJson($scope.swimlanes));
	}, true);

	//load old things
	boot();
}<|endoftext|>


<commit_before>'use strict';

var defaultConnectionString = "mongodb://localhost:27017/database-dev";

var http = require('https');
var fs = require('fs');
var path = require('path');
var request = require('request');

var NO_MORE_TO_PROCESS = 1;
var CONTINUE_TO_PROCESS = 0;

var resetForReprocessing = function resetForReprocessing(conn, limit) {
    console.log("Running conversion...");
    console.log("Batch size is ", limit);

    var MongoClient = require('mongodb').MongoClient;
    // Connect to the default db if not set
    if (undefined === conn) {
        conn = defaultConnectionString;
    }
    MongoClient.connect(conn, function (err, db) {
        if (err) {
            console.error(err);
            process.exit(-1);
        }

        var collection = db.collection('documents');

        var options = {
            "limit": parseInt(limit)
        };

        // Must start with http ...
        var query = {documentFileURL: new RegExp('^migrated')};

        collection.find(query, options).toArray(function (err, items) {

            if (items) {
                console.log("Item found: ", items.length);

                var item = items[0];

                if (item) {
                    items.forEach(function (item) {
                        item.documentFileURL = item.documentFileURL.replace("migrated:", "");

                        collection.update({_id: item._id}, {$set: item}, function () {
                            console.log(item._id + " was reset for re-importing");
                        });
                    });
                }
            }
        });
    });
};

var documentConversion = function documentConversion(conn, downloads_dir, limit) {
    console.log("Running conversion...");
    console.log("Batch size is ", limit);

    var MongoClient = require('mongodb').MongoClient;
    // Connect to the default db if not set
    if (undefined === conn) {
        conn = defaultConnectionString;
    }
    MongoClient.connect(conn, function (err, db) {
        if (err) {
            console.error(err);
            process.exit(-1);
        }

        var collection = db.collection('documents');

        var options = {
            "limit": parseInt(limit)
        };

        // Must start with http ...
        var query = {documentFileURL: new RegExp('^http')};

        collection.find(query, options).toArray(function (err, items) {
            // console.log("err",err);
            if (items) {

                if (!fs.existsSync(downloads_dir)) {
                    console.log("Downloads dir does not exist. Creating...", downloads_dir);
                    fs.mkdirSync(downloads_dir);
                }

                var total = items.length;
                if (total === 0) {
                    console.log("no items to process");
                    process.exit(NO_MORE_TO_PROCESS);
                }
                console.log("found items.. processing ", total);
                var item = items[0];
                var count = 0;
                var shouldExit = function () {
                    count++;
                    if (count == total) {
                        console.log("finished");
                        process.exit(total == limit ? CONTINUE_TO_PROCESS : NO_MORE_TO_PROCESS);
                    }
                };
                if (item) {
                    items.forEach(function (item) {
                        var downloadURL = item.documentFileURL;
                        var projectID = item.project._id;
                        var dataLength = 0;
                        var uuid = require('node-uuid');
                        var generatedFilename = uuid.v1() + path.extname(downloadURL);
                        var stream = downloads_dir + path.sep + projectID + path.sep + generatedFilename;
                        console.log("Writing to: ", stream);
                        var file = fs.createWriteStream(stream);
                        console.log("Attempting to migrate: ", item._id);
                        console.log("Retrieving: ", downloadURL);
                        var request = http.get(downloadURL, function (response) {
                            response.on('data', function (chunk) {
                                // Record the size & write to disk
                                dataLength += chunk.length;
                                file.write(chunk);
                            }).on('end', function () {  // done
                                file.end();
                                console.log(item._id + " Download Complete, size written: " + dataLength);
                                item.internalURL = path.sep + stream;
                                item.internalOriginalName = item.documentFileName;
                                item.internalName = generatedFilename;
                                // TODO
                                // item.internalMime = "x-pdf";
                                item.internalExt = path.extname(item.documentFileURL);
                                item.internalSize = dataLength;
                                // Chagange URL to migrated, but save the pointer just in case
                                // The rest of the model won't use this.
                                item.documentFileURL = "migrated:" + item.documentFileURL;

                                // TODO
                                // item.internalEncoding "7bit";
                                collection.update({_id: item._id}, {$set: item}, function () {
                                    console.log(item._id + " Entry Updated");
                                    shouldExit();
                                });
                            });
                        }).on('error', function (err) {
                            console.log("****************");
                            console.log("Server error:", err);
                            console.log("Document id:" + item._id);
                            fs.unlink(stream);
                        });
                    });
                }
            } else {
                console.log("No more items to process.");
                process.exit(total == limit ? CONTINUE_TO_PROCESS : NO_MORE_TO_PROCESS);
            }
        });
    });
};

// Needed for invalid certs
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0';

var reprocess = process.env.REPROCESS || "false";

if (reprocess.toLowerCase() === "true") {
    console.log("Documents will be reprocessed...");
    resetForReprocessing(process.env.MONGO_CONNECTION, process.env.LIMIT);
}

documentConversion(process.env.MONGO_CONNECTION, process.env.DOWNLOADS_DIR || "uploads", process.env.LIMIT);

<commit_msg>Fix for undefined projectID<commit_after>'use strict';

var defaultConnectionString = "mongodb://localhost:27017/database-dev";

var http = require('https');
var fs = require('fs');
var path = require('path');
var request = require('request');

var NO_MORE_TO_PROCESS = 1;
var CONTINUE_TO_PROCESS = 0;

var resetForReprocessing = function resetForReprocessing(conn, limit) {
    console.log("Running conversion...");
    console.log("Batch size is ", limit);

    var MongoClient = require('mongodb').MongoClient;
    // Connect to the default db if not set
    if (undefined === conn) {
        conn = defaultConnectionString;
    }
    MongoClient.connect(conn, function (err, db) {
        if (err) {
            console.error(err);
            process.exit(-1);
        }

        var collection = db.collection('documents');

        var options = {
            "limit": parseInt(limit)
        };

        // Must start with http ...
        var query = {documentFileURL: new RegExp('^migrated')};

        collection.find(query, options).toArray(function (err, items) {

            if (items) {
                console.log("Item found: ", items.length);

                var item = items[0];

                if (item) {
                    items.forEach(function (item) {
                        item.documentFileURL = item.documentFileURL.replace("migrated:", "");

                        collection.update({_id: item._id}, {$set: item}, function () {
                            console.log(item._id + " was reset for re-importing");
                        });
                    });
                }
            }
        });
    });
};

var documentConversion = function documentConversion(conn, downloads_dir, limit) {
    console.log("Running conversion...");
    console.log("Batch size is ", limit);

    var MongoClient = require('mongodb').MongoClient;
    // Connect to the default db if not set
    if (undefined === conn) {
        conn = defaultConnectionString;
    }
    MongoClient.connect(conn, function (err, db) {
        if (err) {
            console.error(err);
            process.exit(-1);
        }

        var collection = db.collection('documents');

        var options = {
            "limit": parseInt(limit)
        };

        // Must start with http ...
        var query = {documentFileURL: new RegExp('^http')};

        collection.find(query, options).toArray(function (err, items) {
            // console.log("err",err);
            if (items) {

                if (!fs.existsSync(downloads_dir)) {
                    console.log("Downloads dir does not exist. Creating...", downloads_dir);
                    fs.mkdirSync(downloads_dir);
                }

                var total = items.length;
                if (total === 0) {
                    console.log("no items to process");
                    process.exit(NO_MORE_TO_PROCESS);
                }
                console.log("found items.. processing ", total);
                var item = items[0];
                var count = 0;
                var shouldExit = function () {
                    count++;
                    if (count == total) {
                        console.log("finished");
                        process.exit(total == limit ? CONTINUE_TO_PROCESS : NO_MORE_TO_PROCESS);
                    }
                };
                if (item) {
                    items.forEach(function (item) {
                        var downloadURL = item.documentFileURL;
                        var projectID = item.project;
                        var dataLength = 0;
                        var uuid = require('node-uuid');
                        var generatedFilename = uuid.v1() + path.extname(downloadURL);
                        var stream = downloads_dir + path.sep + projectID + path.sep + generatedFilename;
                        console.log("Writing to: ", stream);
                        var file = fs.createWriteStream(stream);
                        console.log("Attempting to migrate: ", item._id);
                        console.log("Retrieving: ", downloadURL);
                        var request = http.get(downloadURL, function (response) {
                            response.on('data', function (chunk) {
                                // Record the size & write to disk
                                dataLength += chunk.length;
                                file.write(chunk);
                            }).on('end', function () {  // done
                                file.end();
                                console.log(item._id + " Download Complete, size written: " + dataLength);
                                item.internalURL = path.sep + stream;
                                item.internalOriginalName = item.documentFileName;
                                item.internalName = generatedFilename;
                                // TODO
                                // item.internalMime = "x-pdf";
                                item.internalExt = path.extname(item.documentFileURL);
                                item.internalSize = dataLength;
                                // Chagange URL to migrated, but save the pointer just in case
                                // The rest of the model won't use this.
                                item.documentFileURL = "migrated:" + item.documentFileURL;

                                // TODO
                                // item.internalEncoding "7bit";
                                collection.update({_id: item._id}, {$set: item}, function () {
                                    console.log(item._id + " Entry Updated");
                                    shouldExit();
                                });
                            });
                        }).on('error', function (err) {
                            console.log("****************");
                            console.log("Server error:", err);
                            console.log("Document id:" + item._id);
                            fs.unlink(stream);
                        });
                    });
                }
            } else {
                console.log("No more items to process.");
                process.exit(total == limit ? CONTINUE_TO_PROCESS : NO_MORE_TO_PROCESS);
            }
        });
    });
};

// Needed for invalid certs
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = '0';

var reprocess = process.env.REPROCESS || "false";

if (reprocess.toLowerCase() === "true") {
    console.log("Documents will be reprocessed...");
    resetForReprocessing(process.env.MONGO_CONNECTION, process.env.LIMIT);
}

documentConversion(process.env.MONGO_CONNECTION, process.env.DOWNLOADS_DIR || "uploads", process.env.LIMIT);

<|endoftext|>


<commit_before>'use strict';

var BN = require('bn.js');
var util = require('../lib/utils/util');
var constants = require('../lib/protocol/constants');
var TX = require('../lib/primitives/tx');
var Block = require('../lib/primitives/block');
var Script = require('../lib/script/script');
var Opcode = require('../lib/script/opcode');
var networks = require('../lib/protocol/networks');
var opcodes = constants.opcodes;
var main, testnet, regtest;

function createGenesisBlock(options) {
  var flags = options.flags;
  var script = options.script;
  var content = options.content;
  var tx, block;

  if (!flags) {
    flags = new Buffer(
      'The Times 03/Jan/2009 Chancellor on brink of second bailout for banks',
      'ascii');
  }

  if (!content) {
    content = new Buffer(constants.NULL_HASH, 'hex');
  }

  if (!script) {
    script = Script.fromArray([
      new Buffer('04678afdb0fe5548271967f1a67130b7105cd6a828e039'
        + '09a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c3'
        + '84df7ba0b8d578a4c702b6bf11d5f', 'hex'),
      opcodes.OP_CHECKSIG
    ]);
  }

  tx = new TX({
    version: 1,
    flag: 1,
    inputs: [{
      prevout: {
        hash: constants.NULL_HASH,
        index: 0xffffffff
      },
      script: [
        Opcode.fromNumber(new BN(486604799)),
        Opcode.fromPush(new Buffer([4])),
        Opcode.fromData(flags)
      ],
      sequence: 0xffffffff
    }],
    outputs: [{
      content,
      x: 0,
      y: 0,
      script: script
    }],
    locktime: 0
  });

  block = new Block({
    version: options.network.genesis.version,
    prevBlock: constants.NULL_HASH,
    merkleRoot: tx.hash('hex'),
    ts: options.network.genesis.ts,
    bits: options.network.genesis.bits,
    nonce: options.network.genesis.nonce,
    height: 0,
  });

  block.addTX(tx);

  return block;
}

module.exports = createGenesisBlock;

if (require.main === module) {

  main = createGenesisBlock({
    network: networks.main,
  });

  testnet = createGenesisBlock({
    network: networks.testnet,
  });

  regtest = createGenesisBlock({
    network: networks.regtest,
  });

  util.log(main);
  util.log('');
  util.log(testnet);
  util.log('');
  util.log(regtest);
  util.log('');
  util.log('');
  util.log('main hash: %s', main.rhash());
  util.log('main merkleroot: %s', main.merkleRoot);
  util.log('main raw: %s', main.toRaw().toString('hex'));
  util.log('');
  util.log('testnet hash: %s', testnet.rhash());
  util.log('testnet merkleroot: %s', testnet.merkleRoot);
  util.log('testnet raw: %s', testnet.toRaw().toString('hex'));
  util.log('');
  util.log('regtest hash: %s', regtest.rhash());
  util.log('regtest merkleroot: %s', regtest.merkleRoot);
  util.log('regtest raw: %s', regtest.toRaw().toString('hex'));
}
<commit_msg>Add genesis block data<commit_after>'use strict';

var BN = require('bn.js');
var util = require('../lib/utils/util');
var constants = require('../lib/protocol/constants');
var TX = require('../lib/primitives/tx');
var Block = require('../lib/primitives/block');
var Script = require('../lib/script/script');
var Opcode = require('../lib/script/opcode');
var networks = require('../lib/protocol/networks');
var opcodes = constants.opcodes;
var main, testnet, regtest;

function createGenesisBlock(options) {
  var flags = options.flags;
  var script = options.script;
  var content = options.content;
  var tx, block;

  if (!flags) {
    flags = new Buffer(
      'The Times 03/Jan/2009 Chancellor on brink of second bailout for banks',
      'ascii');
  }

  if (!content) {
    content = new Buffer(constants.NULL_HASH, 'hex');
  }

  if (!script) {
    script = Script.fromArray([
      new Buffer('04678afdb0fe5548271967f1a67130b7105cd6a828e039'
        + '09a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c3'
        + '84df7ba0b8d578a4c702b6bf11d5f', 'hex'),
      opcodes.OP_CHECKSIG
    ]);
  }

  tx = new TX({
    version: 1,
    flag: 1,
    inputs: [{
      prevout: {
        hash: constants.NULL_HASH,
        index: 0xffffffff
      },
      script: [
        Opcode.fromNumber(new BN(486604799)),
        Opcode.fromPush(new Buffer([4])),
        Opcode.fromData(flags)
      ],
      sequence: 0xffffffff
    }],
    outputs: [{
      content,
      x: 0,
      y: 0,
      script: script
    }],
    locktime: 0
  });

  block = new Block({
    version: options.network.genesis.version,
    prevBlock: constants.NULL_HASH,
    merkleRoot: tx.hash('hex'),
    ts: options.network.genesis.ts,
    bits: options.network.genesis.bits,
    nonce: options.network.genesis.nonce,
    height: 0,
  });

  block.addTX(tx);

  return block;
}

module.exports = createGenesisBlock;

if (require.main === module) {

  main = createGenesisBlock({
    network: networks.main,
  });

  testnet = createGenesisBlock({
    network: networks.testnet,
    content: '',
    script: new Script('76a9144780ee849be547b5ec9efde07fbcfe2d87b69a3088ac'),
    flags: new Buffer('000000000000000001cc2b47d703cfc27abfe07fca9e127347c4b5651f107709', 'hex'),
  });

  regtest = createGenesisBlock({
    network: networks.regtest,
  });

  util.log(main);
  util.log('');
  util.log(testnet);
  util.log('');
  util.log(regtest);
  util.log('');
  util.log('');
  util.log('main hash: %s', main.rhash());
  util.log('main merkleroot: %s', main.merkleRoot);
  util.log('main raw: %s', main.toRaw().toString('hex'));
  util.log('');
  util.log('testnet hash: %s', testnet.rhash());
  util.log('testnet merkleroot: %s', testnet.merkleRoot);
  util.log('testnet raw: %s', testnet.toRaw().toString('hex'));
  util.log('');
  util.log('regtest hash: %s', regtest.rhash());
  util.log('regtest merkleroot: %s', regtest.merkleRoot);
  util.log('regtest raw: %s', regtest.toRaw().toString('hex'));
}
<|endoftext|>


<commit_before>import { cancel, later } from '@ember/runloop';
import { alias } from '@ember/object/computed';
import { inject as service } from '@ember/service';
import Controller, { inject as controller } from '@ember/controller';

export default Controller.extend({
  scope: service(),
  settings: service(),
  clusterController: controller('authenticated.cluster'),
  cluster: alias('clusterController.model'),

  loading: alias('cluster.isTransitioning'),
  registrationCommand: alias('cluster.registrationToken.clusterCommand'),

  refreshTimer: null,
  init() {
     this._super(...arguments);
    let cluster = this.get('cluster');
    if(cluster.state==="inactive"){
        this.scheduleRefresh();
    }else{
        this.scheduleRefresh();
      }
  },

  willDestroyElement() {
    this.cancelRefresh();
  },

  cancelRefresh() {
    cancel(this.get('refreshTimer'));
  },

  scheduleRefresh() {
    this.cancelRefresh();
    this.set('refreshTimer', later(this, 'refreshCluster', 5000));
  },

  refreshCluster() {
    let cluster = this.get('cluster');
    cluster.reload().then(() => {
      if ( cluster.get('state') === 'inactive' ) {
        this.scheduleRefresh();
      } else {
        let project = this.get('scope.current');
        if ( project.get('clusterId') !== cluster.get('id') ) {
          project = cluster.get('defaultProject');
        }

        if ( project ) {
          this.send('switchProject', project.get('id'), 'hosts', [project.get('id')]);
        } else {
          this.send('cancel');
        }
      }
    }).catch(() => {
      this.scheduleRefresh();
    });
  },

  actions: {
    hostSet() {
      this.set('model.apiHostSet', true);
    },

    cancel() {
      this.transitionToRoute('global-admin.clusters');
    }
  },

  configSet: function() {
    return (this.get('kubeconfig')||'').includes('clusters:');
  }.property('kubeconfig'),
});
<commit_msg>spacing style changed<commit_after>import { cancel, later } from '@ember/runloop';
import { alias } from '@ember/object/computed';
import { inject as service } from '@ember/service';
import Controller, { inject as controller } from '@ember/controller';

export default Controller.extend({
  scope: service(),
  settings: service(),
  clusterController: controller('authenticated.cluster'),
  cluster: alias('clusterController.model'),

  loading: alias('cluster.isTransitioning'),
  registrationCommand: alias('cluster.registrationToken.clusterCommand'),

  refreshTimer: null,
  init() {
     this._super(...arguments);
    let cluster = this.get('cluster');
    if(cluster.state==="inactive"){
        this.scheduleRefresh();
    }else{
        this.scheduleRefresh();
    }
  },

  willDestroyElement() {
    this.cancelRefresh();
  },

  cancelRefresh() {
    cancel(this.get('refreshTimer'));
  },

  scheduleRefresh() {
    this.cancelRefresh();
    this.set('refreshTimer', later(this, 'refreshCluster', 5000));
  },

  refreshCluster() {
    let cluster = this.get('cluster');
    cluster.reload().then(() => {
      if ( cluster.get('state') === 'inactive' ) {
        this.scheduleRefresh();
      } else {
        let project = this.get('scope.current');
        if ( project.get('clusterId') !== cluster.get('id') ) {
          project = cluster.get('defaultProject');
        }

        if ( project ) {
          this.send('switchProject', project.get('id'), 'hosts', [project.get('id')]);
        } else {
          this.send('cancel');
        }
      }
    }).catch(() => {
      this.scheduleRefresh();
    });
  },

  actions: {
    hostSet() {
      this.set('model.apiHostSet', true);
    },

    cancel() {
      this.transitionToRoute('global-admin.clusters');
    }
  },

  configSet: function() {
    return (this.get('kubeconfig')||'').includes('clusters:');
  }.property('kubeconfig'),
});
<|endoftext|>


<commit_before>#! /usr/bin/env node
/* eslint-disable camelcase */
const github = require('octonode');
const normalizeUrl = require('normalize-url');
const spawn = require('cross-spawn');
const travisAfterAll = require('travis-after-all');
const urlRegex = require('url-regex');
const argv = require('yargs').argv;

const nowCli = require.resolve('now/download/dist/now');

if (!process.env.CI || !process.env.TRAVIS) {
  throw new Error('Could not detect Travis CI environment');
}

const githubToken = process.env.GH_TOKEN;
const nowToken = process.env.NOW_TOKEN;

if (!githubToken) {
  throw new Error('Missing required environment variable GH_TOKEN');
}

if (!nowToken) {
  throw new Error('Missing required environment variable NOW_TOKEN');
}

console.log(process.env.TRAVIS_PULL_REQUEST);

const client = github.client(githubToken);
const ghRepo = client.repo(process.env.TRAVIS_REPO_SLUG);
let ghPR;

if (process.env.TRAVIS_PULL_REQUEST) {
  ghPR = client.pr(
    process.env.TRAVIS_REPO_SLUG,
    process.env.TRAVIS_PULL_REQUEST,
  );
}

function noop() {}

function getUrl(content) {
  const urls = content.match(urlRegex()) || [];

  return urls.map(url => normalizeUrl(url.trim().replace(/\.+$/, '')))[0];
}

function deploy(context, sha) {
  ghRepo.status(
    sha,
    {
      context,
      state: 'pending',
      description: `Δ Now ${context} deployment pending`,
    },
    noop,
  );

  const args = [
    '--token',
    nowToken,
    '--team',
    'coderplex',
    '--no-clipboard',
    '-n',
    'coderplex-app',
  ];
  const alias = context === 'production' && process.env.NOW_ALIAS;
  let stdout = '';

  if (alias) {
    args.push(...['--alias', alias]);
  }

  if (argv.p || argv.public) {
    args.push(...['-p']);
  }

  if (argv.folder) {
    args.push(argv.folder);
  }

  const child = spawn(nowCli, args);

  if (!alias) {
    child.stdout.on('data', data => {
      stdout += data;
    });
  }

  child.on('error', err => {
    console.error(err);
    ghRepo.status(
      sha,
      {
        context,
        state: 'error',
        description: `Δ Now ${context} deployment failed. See Travis logs for details.`,
      },
      noop,
    );
  });

  child.on('close', () => {
    const target_url = alias || getUrl(stdout);
    if (ghPR) {
      const comment = `
      ### Δ Now ${context} deployment complete
      - ✅ **Build Passed**
      - 🚀 **Staging URL** : ${target_url}
      ---
      Note: **This is autogenerated through Travis build**
    `;
      ghPR.createComment(
        {
          body: comment,
          in_reply_to: 147402206,
        },
        (err, res) => {
          console.log(err, res);
        },
      );
    } else {
      console.log('No PR found');
    }
    ghRepo.status(
      sha,
      {
        context,
        target_url,
        state: 'success',
        description: `Δ Now ${context} deployment complete`,
      },
      noop,
    );
  });
}

travisAfterAll((code, err) => {
  // Don't do anything if there was an error of if the build returned a failing code
  if (err || code) {
    return;
  }

  switch (process.env.TRAVIS_EVENT_TYPE) {
    case 'pull_request':
      return deploy('staging', process.env.TRAVIS_PULL_REQUEST_SHA);
    case 'push':
      return deploy('production', process.env.TRAVIS_COMMIT);
    default:
      return '';
  }
});
<commit_msg>test again if comment works from travis<commit_after>#! /usr/bin/env node
/* eslint-disable camelcase */
const github = require('octonode');
const normalizeUrl = require('normalize-url');
const spawn = require('cross-spawn');
const travisAfterAll = require('travis-after-all');
const urlRegex = require('url-regex');
const argv = require('yargs').argv;

const nowCli = require.resolve('now/download/dist/now');

if (!process.env.CI || !process.env.TRAVIS) {
  throw new Error('Could not detect Travis CI environment');
}

const githubToken = process.env.GH_TOKEN;
const nowToken = process.env.NOW_TOKEN;

if (!githubToken) {
  throw new Error('Missing required environment variable GH_TOKEN');
}

if (!nowToken) {
  throw new Error('Missing required environment variable NOW_TOKEN');
}

console.log(process.env.TRAVIS_PULL_REQUEST);

const client = github.client(githubToken);
const ghRepo = client.repo(process.env.TRAVIS_REPO_SLUG);
let ghPR;

if (process.env.TRAVIS_PULL_REQUEST) {
  ghPR = client.issue(
    process.env.TRAVIS_REPO_SLUG,
    process.env.TRAVIS_PULL_REQUEST,
  );
}

function noop() {}

function getUrl(content) {
  const urls = content.match(urlRegex()) || [];

  return urls.map(url => normalizeUrl(url.trim().replace(/\.+$/, '')))[0];
}

function deploy(context, sha) {
  ghRepo.status(
    sha,
    {
      context,
      state: 'pending',
      description: `Δ Now ${context} deployment pending`,
    },
    noop,
  );

  const args = [
    '--token',
    nowToken,
    '--team',
    'coderplex',
    '--no-clipboard',
    '-n',
    'coderplex-app',
  ];
  const alias = context === 'production' && process.env.NOW_ALIAS;
  let stdout = '';

  if (alias) {
    args.push(...['--alias', alias]);
  }

  if (argv.p || argv.public) {
    args.push(...['-p']);
  }

  if (argv.folder) {
    args.push(argv.folder);
  }

  const child = spawn(nowCli, args);

  if (!alias) {
    child.stdout.on('data', data => {
      stdout += data;
    });
  }

  child.on('error', err => {
    console.error(err);
    ghRepo.status(
      sha,
      {
        context,
        state: 'error',
        description: `Δ Now ${context} deployment failed. See Travis logs for details.`,
      },
      noop,
    );
  });

  child.on('close', () => {
    const target_url = alias || getUrl(stdout);
    if (ghPR) {
      const comment = `
      ### Δ Now ${context} deployment complete
      - ✅ **Build Passed**
      - 🚀 **Staging URL** : ${target_url}
      ---
      Note: **This is autogenerated through Travis build**
    `;
      ghPR.createComment(
        {
          body: comment,
        },
        (err, res) => {
          console.log(err, res);
        },
      );
    } else {
      console.log('No PR found');
    }
    ghRepo.status(
      sha,
      {
        context,
        target_url,
        state: 'success',
        description: `Δ Now ${context} deployment complete`,
      },
      noop,
    );
  });
}

travisAfterAll((code, err) => {
  // Don't do anything if there was an error of if the build returned a failing code
  if (err || code) {
    return;
  }

  switch (process.env.TRAVIS_EVENT_TYPE) {
    case 'pull_request':
      return deploy('staging', process.env.TRAVIS_PULL_REQUEST_SHA);
    case 'push':
      return deploy('production', process.env.TRAVIS_COMMIT);
    default:
      return '';
  }
});
<|endoftext|>


<commit_before>/* eslint ember/order-in-components: 0 */
import { inject as service } from '@ember/service';
import Component from '@ember/component';
import { computed } from '@ember/object';
import RSVP from 'rsvp';
import { isEmpty, isPresent } from '@ember/utils';

export default Component.extend({
  store: service(),
  tagName: 'section',
  classNames: ['school-competencies-expanded'],
  school: null,
  isManaging: false,
  bufferedCompetencies: null,
  competencies: computed('school.competencies.[]', async function(){
    const school = this.get('school');
    const competencies = await school.get('competencies');

    return competencies;
  }),
  domains: computed('school.competencies.[]', async function(){
    const competencies = await this.get('competencies');
    const domains = competencies.filterBy('isDomain');

    return domains;
  }),
  childCompetencies: computed('school.competencies.[]', async function(){
    const competencies = await this.get('competencies');
    const childCompetencies = competencies.filterBy('isNotDomain');

    return childCompetencies;
  }),
  showCollapsible: computed('isManaging', 'school.competencies.length', function(){
    const isManaging = this.get('isManaging');
    const school = this.get('school');
    const competencyIds = school.hasMany('competencies').ids();
    return competencyIds.length && ! isManaging;
  }),
  didReceiveAttrs(){
    this._super(...arguments);
    if (this.get('isManaging') && isEmpty(this.get('bufferedCompetencies'))) {
      const school = this.get('school');
      school.get('competencies').then(competencies => {
        this.set('bufferedCompetencies', competencies.toArray());
      });
    }

  },
  actions: {
    collapse(){
      const collapse = this.get('collapse');
      this.get('school.competencies').then(competencies => {
        if(competencies.length){
          collapse();
        }
      });
    },
    addCompetencyToBuffer(domain, title){
      let competency = this.get('store').createRecord('competency', {title});
      if (isPresent(domain)) {
        competency.set('parent', domain);
        domain.get('children').then(children => {
          children.pushObject(competency);
          this.get('bufferedCompetencies').pushObject(competency);
        });
      } else {
        this.get('bufferedCompetencies').pushObject(competency);
      }
    },
    removeCompetencyFromBuffer(competency){
      let buffer = this.get('bufferedCompetencies');
      if (buffer.includes(competency)) {
        buffer.removeObject(competency);
      }
    },
    save(){
      this.set('isSaving', true);
      let school = this.get('school');
      school.get('competencies').then(schoolCompetencies => {
        let promises = [];
        let domainsToRemove = [];
        let bufferedCompetencies = this.get('bufferedCompetencies');
        schoolCompetencies.filter(competency => {
          return !bufferedCompetencies.includes(competency);
        }).forEach(competency => {
          competency.deleteRecord();
          if (competency.get('isDomain')) {
            domainsToRemove.pushObject(competency);
          } else {
            promises.pushObject(competency.save());
          }

        });
        bufferedCompetencies.filterBy('isNew').forEach(competency => {
          competency.set('school', school);
        });
        promises.pushObjects(bufferedCompetencies.filterBy('hasDirtyAttributes').invoke('save'));
        schoolCompetencies.clear();
        bufferedCompetencies.forEach(competency=>{
          schoolCompetencies.pushObject(competency);
        });
        RSVP.all(promises).then(() => {
          RSVP.all(domainsToRemove.invoke('save')).then(() => {
            this.set('isManaging', false);
            this.set('bufferedTopics', []);
            this.set('isSaving', false);
          });
        });
      });
    },
    cancel(){
      const setSchoolManageCompetencies = this.get('setSchoolManageCompetencies');
      this.set('bufferedCompetencies', []);
      setSchoolManageCompetencies(false);
    },
    manage(){
      const setSchoolManageCompetencies = this.get('setSchoolManageCompetencies');
      this.get('school.competencies').then(competencies => {
        this.set('bufferedCompetencies', competencies.toArray());
        setSchoolManageCompetencies(true);
      });
    }
  }
});
<commit_msg>save new competencies as active.<commit_after>/* eslint ember/order-in-components: 0 */
import { inject as service } from '@ember/service';
import Component from '@ember/component';
import { computed } from '@ember/object';
import RSVP from 'rsvp';
import { isEmpty, isPresent } from '@ember/utils';

export default Component.extend({
  store: service(),
  tagName: 'section',
  classNames: ['school-competencies-expanded'],
  school: null,
  isManaging: false,
  bufferedCompetencies: null,
  competencies: computed('school.competencies.[]', async function(){
    const school = this.get('school');
    const competencies = await school.get('competencies');

    return competencies;
  }),
  domains: computed('school.competencies.[]', async function(){
    const competencies = await this.get('competencies');
    const domains = competencies.filterBy('isDomain');

    return domains;
  }),
  childCompetencies: computed('school.competencies.[]', async function(){
    const competencies = await this.get('competencies');
    const childCompetencies = competencies.filterBy('isNotDomain');

    return childCompetencies;
  }),
  showCollapsible: computed('isManaging', 'school.competencies.length', function(){
    const isManaging = this.get('isManaging');
    const school = this.get('school');
    const competencyIds = school.hasMany('competencies').ids();
    return competencyIds.length && ! isManaging;
  }),
  didReceiveAttrs(){
    this._super(...arguments);
    if (this.get('isManaging') && isEmpty(this.get('bufferedCompetencies'))) {
      const school = this.get('school');
      school.get('competencies').then(competencies => {
        this.set('bufferedCompetencies', competencies.toArray());
      });
    }

  },
  actions: {
    collapse(){
      const collapse = this.get('collapse');
      this.get('school.competencies').then(competencies => {
        if(competencies.length){
          collapse();
        }
      });
    },
    addCompetencyToBuffer(domain, title){
      let competency = this.get('store').createRecord('competency', {title});
      if (isPresent(domain)) {
        competency.set('parent', domain);
        domain.get('children').then(children => {
          children.pushObject(competency);
          this.get('bufferedCompetencies').pushObject(competency);
        });
      } else {
        this.get('bufferedCompetencies').pushObject(competency);
      }
    },
    removeCompetencyFromBuffer(competency){
      let buffer = this.get('bufferedCompetencies');
      if (buffer.includes(competency)) {
        buffer.removeObject(competency);
      }
    },
    save(){
      this.set('isSaving', true);
      let school = this.get('school');
      school.get('competencies').then(schoolCompetencies => {
        let promises = [];
        let domainsToRemove = [];
        let bufferedCompetencies = this.get('bufferedCompetencies');
        schoolCompetencies.filter(competency => {
          return !bufferedCompetencies.includes(competency);
        }).forEach(competency => {
          competency.deleteRecord();
          if (competency.get('isDomain')) {
            domainsToRemove.pushObject(competency);
          } else {
            promises.pushObject(competency.save());
          }

        });
        bufferedCompetencies.filterBy('isNew').forEach(competency => {
          competency.set('school', school);
          competency.set('active', true);
        });
        promises.pushObjects(bufferedCompetencies.filterBy('hasDirtyAttributes').invoke('save'));
        schoolCompetencies.clear();
        bufferedCompetencies.forEach(competency=>{
          schoolCompetencies.pushObject(competency);
        });
        RSVP.all(promises).then(() => {
          RSVP.all(domainsToRemove.invoke('save')).then(() => {
            this.set('isManaging', false);
            this.set('bufferedTopics', []);
            this.set('isSaving', false);
          });
        });
      });
    },
    cancel(){
      const setSchoolManageCompetencies = this.get('setSchoolManageCompetencies');
      this.set('bufferedCompetencies', []);
      setSchoolManageCompetencies(false);
    },
    manage(){
      const setSchoolManageCompetencies = this.get('setSchoolManageCompetencies');
      this.get('school.competencies').then(competencies => {
        this.set('bufferedCompetencies', competencies.toArray());
        setSchoolManageCompetencies(true);
      });
    }
  }
});
<|endoftext|>


<commit_before>
// JSON example
var candidates = [ {
  "name": "Ellie Phanta",
  "party": "Republican",
  "stances" : [-2,-2]
  },
  {
  "name": "Jack Bass",
  "party": "Democrat",
  "stances" : [-2,-2]
  },
  {
  "name": "Paul Stanton",
  "party": "Libertarian",
  "stances" : [2,2]
  }
 ];

Questions = [
  {
  "Issue" : "Force",
  "Question" : "Should goods and services be provided by force?",
  "Responses" : [
    ["Absolutely",-2],
    ["Yes", -1],
    ["Maybe", 0],
    ["No", 1],
    ["Never", 2]]
},
   {
  "Issue" : "Roads",
  "Question" : "Without government, Who will build the roads?",
  "Responses" : [
    ["No one at all",-2],
    ["Shady people you can't trust", -1],
    ["Someone might maybe possibly", 0],
    ["Construction companies", 1],
    ["Where we're going, we won't need roads.", 2]]
}
];

Imports = [["Could not care less",1],["Don't care",2],["Might care",3],["Care",4],["Care a lot",5]];

responses = [];
importance = [];
results = [];

for (i = 0; i < Questions.length; i++) {
  responses.push(0);
  importance.push(0);
}

for (j = 0; j < candidates.length; j++) {
  results.push(responses);
}

function loadQuestions() {
  var chunk = '';
  for (i = 0; i < Questions.length; i++) {
    chunk += '
';
    chunk += '
' + Questions[i].Question + '
';
    chunk += '
';
    for (j = 0; j < Questions[i].Responses.length; j++) {
     var qr = Questions[i].Responses[j];
     chunk += '<button onclick="tally(' + i + ',' + qr[1] + ')">' + qr[0] + '</button>';
    }
    chunk += '
';
    chunk += '
';
    for (k = 0; k < Imports.length; k++) {
     chunk += '<button onclick="tallyImports(' + i + ',' + Imports[k][1] + ')">' + Imports[k][0] + '</button>';
    }
    chunk += '

';
  }
  chunk += '
<button onclick="compareToCandidates()">Calculate</button>
';
  document.getElementById("questionArea").innerHTML = chunk;
};

function tally(questionNumber,response) {
  //qId = 'q' + questionNumber;
  responses[questionNumber] = response;
  document.getElementById("test").innerHTML = responses;
  //document.getElementById(qId).innerHTML = 'Response Recorded';
};

function tallyImports(questionNumber,response) {
  //qId = 'q' + questionNumber;
  importance[questionNumber] = response;
  document.getElementById("test2").innerHTML = importance;
  //document.getElementById(qId).innerHTML = 'Response Recorded';
};

function compareToCandidates() {
  var resultsStr = '

Candidates	';
  for (i = 0; i < Questions.length; i++) {
    resultsStr += '' + Questions[i].Issue + '	';
  }
  resultsStr += '
';
  for (i = 0; i < candidates.length; i++) {
    resultsStr += '' + candidates[i].name + '	';
    for (j = 0; j < Questions.length; j++) {
      max = 5*importance[j]; // Maximum possible weighted difference
      diff = Math.abs(responses[j] - candidates[i].stances[j]); // difference between candidate score and your score
      weightedDiff = diff*importance[j]; // Difference weighted based on importance
      diffDiff = max - weightedDiff; // Difference between the max and weightedDiff
      results[i][j] = diffDiff;
      percent = Math.floor(diffDiff/max*100);

      resultsStr += '' + percent + '%	';
    }
    resultsStr += '
';
  }
  resultsStr += '
';
  document.getElementById("results").innerHTML = resultsStr;
  document.getElementById("test3").innerHTML = results;
};

loadQuestions();
<commit_msg>Update wme.js<commit_after>
// JSON example
var candidates = [ {
  "name": "Ellie Phanta",
  "party": "Republican",
  "stances" : [-2,-2]
  },
  {
  "name": "Jack Bass",
  "party": "Democrat",
  "stances" : [-2,-2]
  },
  {
  "name": "Paul Stanton",
  "party": "Libertarian",
  "stances" : [2,2]
  }
 ];

Questions = [
  {
  "Issue" : "Force",
  "Question" : "Should goods and services be provided by force?",
  "Responses" : [
    ["Absolutely",-2],
    ["Yes", -1],
    ["Maybe", 0],
    ["No", 1],
    ["Never", 2]]
},
   {
  "Issue" : "Roads",
  "Question" : "Without government, Who will build the roads?",
  "Responses" : [
    ["No one at all",-2],
    ["Shady people you can't trust", -1],
    ["Someone might maybe possibly", 0],
    ["Construction companies", 1],
    ["Where we're going, we won't need roads.", 2]]
}
];

Imports = [["Could not care less",1],["Don't care",2],["Might care",3],["Care",4],["Care a lot",5]];

responses = [];
importance = [];
results = [];

for (i = 0; i < Questions.length; i++) {
  responses.push(0);
  importance.push(0);
}

for (j = 0; j < candidates.length; j++) {
  results.push(responses);
}

function loadQuestions() {
  var chunk = '';
  for (i = 0; i < Questions.length; i++) {
    chunk += '
';
    chunk += '
' + Questions[i].Question + '
';
    chunk += '
';
    for (j = 0; j < Questions[i].Responses.length; j++) {
     var qr = Questions[i].Responses[j];
     chunk += '<button onclick="tally(' + i + ',' + qr[1] + ')">' + qr[0] + '</button>';
    }
    chunk += '
';
    chunk += '
';
    for (k = 0; k < Imports.length; k++) {
     chunk += '<button onclick="tallyImports(' + i + ',' + Imports[k][1] + ')">' + Imports[k][0] + '</button>';
    }
    chunk += '

';
  }
  chunk += '
<button onclick="compareToCandidates()">Calculate</button>
';
  document.getElementById("questionArea").innerHTML = chunk;
};

function tally(questionNumber,response) {
  //qId = 'q' + questionNumber;
  responses[questionNumber] = response;
  document.getElementById("test").innerHTML = responses;
  //document.getElementById(qId).innerHTML = 'Response Recorded';
};

function tallyImports(questionNumber,response) {
  //qId = 'q' + questionNumber;
  importance[questionNumber] = response;
  document.getElementById("test2").innerHTML = importance;
  //document.getElementById(qId).innerHTML = 'Response Recorded';
};

function compareToCandidates() {
  var resultsStr = '

Candidates	';
  var max = 25;
  var diff = 0;
  var weightedDiff = 0;
  var diffDiff = 0;
  var percent = 0;

  for (i = 0; i < Questions.length; i++) {
    resultsStr += '' + Questions[i].Issue + '	';
  }
  resultsStr += '
';
  for (i = 0; i < candidates.length; i++) {
    resultsStr += '' + candidates[i].name + '	';
    for (j = 0; j < Questions.length; j++) {
      max = 5*importance[j]; // Maximum possible weighted difference
      diff = Math.abs(responses[j] - candidates[i].stances[j]); // difference between candidate score and your score
      weightedDiff = diff*importance[j]; // Difference weighted based on importance
      diffDiff = max - weightedDiff; // Difference between the max and weightedDiff
      results[i][j] = diffDiff;
      percent = Math.floor(diffDiff/max*100);

      resultsStr += '' + percent.toString() + '%	';
    }
    resultsStr += '
';
  }
  resultsStr += '
';
  document.getElementById("results").innerHTML = resultsStr;
  document.getElementById("test3").innerHTML = results;
};

loadQuestions();
<|endoftext|>