<commit_before>angular.module('feedbackcontrol', [])
.directive('transform', function(FeedbackSignal) {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind('click', function(e) {
                var currentUrl = window.location.pathname;
                var me = $(element);
                var data = FeedbackSignal.data;

                if(currentUrl.match(/inbox\/all|deleted/g)) {
                    if(data.id.length > 0) {
                        hide_the_children(me);
                        $(".checky-box-container").show();
                    }
                }

                if(currentUrl.match(/published/g)) {

                    if(me.attr('return-policy') == 1) {
                        hide_the_children(me);
                        $(".checky-box-container").show();
                    }

                    if(data.status == "feature") {
                        var state = {
                            activate: {'background-position': '-64px -31px'}
                          , deactivate_sibling: {'background-position': '-32px 0px'}
                          , activation_color: {'background-color': '#ffffe0'}
                          , state_change_inbox: '{"status": "inbox", "id": ' + data.id + ', "catid": ' + data.catid + ', "origin": "feature"}'
                          , state_change: '{"status": "publish", "id": ' + data.id + ', "catid": ' + data.catid + ', "origin": "publish"}'
                          , present_status: "feature"
                        }
                        published_state(me, '.publish', 'publish feedback', state);
                    }

                    if(data.status == "publish") {
                        var state = {
                            activate: {'background-position': '-32px -31px'}
                          , deactivate_sibling: {'background-position': '-64px 0px'}
                          , activation_color: {'background-color': '#fff'}
                          , state_change_inbox: '{"status": "inbox", "id": ' + data.id + ', "catid": ' + data.catid + ', "origin": "publish"}'
                          , state_change: '{"status": "feature", "id": ' + data.id + ', "catid": ' + data.catid + ', "origin": "feature"}'
                          , present_status: "publish"
                        }
                        published_state(me, '.feature', 'feature feedback', state);
                    }

                    if(data.status == "delete" || data.status == "fileas") {
                        hide_the_children(me);
                        $(".checky-box-container").show();
                    }

                }

                if(currentUrl.match(/filed/g)) {

                    var data_status = data.status;

                    if(data_status == "publish" || data_status == "feature" || data_status == "delete") {
                        hide_the_children(me);
                        $(".checky-box-container").show();
                    }

                    if(data_status == "fileas") {
                        $(me).parents(".dashboard-feedback")
                               .children("div.feedback-contents")
                               .children(".responsive-padding")
                               .children(".feedback-details")
                               .children(".filed")
                               .html($(me).text())
                    }

                }

                e.preventDefault();
            });
        }
    }
})
.directive('undo', function(FeedbackSignal, FeedbackControlService) {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind("click", function(e) {

                var currentUrl = window.location.pathname;

                $(".checky-box-container").hide();
                if (FeedbackSignal.data.id instanceof Array) {
                    for(var i=0; i < FeedbackSignal.data.id.length ; i++) {
                        var feedback = $(".dashboard-feedback[feedback=" + FeedbackSignal.data.id[i] + "]");
                        feedback.show();
                        $(feedback).parents('.feedback-group').show();

                        if(currentUrl.match(/inbox\/all|deleted|published/g)) {
                            var catpicks = $(".dashboard-feedback[feedback=" + FeedbackSignal.data.id[i] + "] li .cat-picks");
                            catpicks.css({'background': '#598499'});
                        }

                    }
                } else {
                    var feedback = $(".dashboard-feedback[feedback=" + FeedbackSignal.data.id + "]");
                    console.log(feedback.attr('style'));
                    feedback.show();
                    $(feedback).parents('.feedback-group').show();

                    if(currentUrl.match(/inbox\/all|deleted|published/g)) {
                        var catpicks = $(".dashboard-feedback[feedback=" + FeedbackSignal.data.id + "] li .cat-picks");
                        catpicks.css({'background': '#598499'});
                    }

                    var checkbox = $(".feed-checkbox[value=" + FeedbackSignal.data.id + "]");

                    if(checkbox.is(":checked")) {
                        checkbox.click();
                    }
                }

                if($(".sorter-checkbox").is(":checked")) {
                    $(".sorter-checkbox").click();
                }

                if($('.feed-checkbox').is(":checked")) {
                    $('.feed-checkbox').prop("checked", false);
                }

                $(".dashboard-feedback").css({'background-color': '#FFF'});

                FeedbackControlService.expunge();
                e.preventDefault();
            });
        }
    }
})
.directive('close', function(FeedbackControlService) {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind("click", function(e) {
                $(".checky-box-container").hide();
                FeedbackControlService.expunge();
                e.preventDefault();
            });
        }
    }
})
.directive('feedcheckbox', function() {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            var checkbox = $(element);

            checkbox.bind('change', function() {
                if(checkbox.is(":checked")) {
                    checkbox.parents('.dashboard-feedback').css({'background-color': '#F7F7F7'});
                } else {
                    checkbox.parents('.dashboard-feedback').css({'background-color': '#FFF'});
                }
            });

        }
    }
})
.directive('statuschange', function(FeedbackService) {
    return {
        restrict: 'A'
      , scope: {
            feedid: "@feedid"
          , statustype: "@statustype"
        }
      , link: function(scope, element, attrs) {
            $(element).bind('change', function() {
                var status_class, value;
                var myvalue = $(this).val();
                if(scope.statustype == "status") {
                   status_class = ".status-line";
                   console.log(myvalue);
                   if(myvalue == "new") { value = "New"; }
                   if(myvalue == "inprogress") { value = "In Progress"; }
                   if(myvalue == "closed") { value = "Closed"; }
                } else {
                   status_class = ".priority-line";
                   console.log(myvalue);
                   if(myvalue == 0) { value = "Low"; }
                   if(myvalue == 60) { value = "Medium"; }
                   if(myvalue == 100) { value = "High"; }
                }

                $(this).parents(".dashboard-feedback")
                       .children("div.feedback-contents")
                       .children(".responsive-padding")
                       .children(".feedback-details")
                       .children(".feedback-details-status")
                       .children(status_class)
                       .html(value)

                FeedbackService.inline_change($(this).val(), scope.feedid, scope.statustype);

            })
        }
    }
})
.directive('deleteBlock', function() {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind('click', function(e) {
                $(this).parents('.custom-att').fadeOut(400, function() {
                     var new_uploaded_images = new Array;
                     var new_attached_link;

                     var div = $(this).parents('.uploaded-images-and-links');
                     var images = div.find('.uploaded_image');
                     var media_attachment = div.find('.attached_link');

                     var remove_image = {
                        'small_url'    :$(this).find('.small-image-url').val(),
                        'medium_url'   :$(this).find('.medium-image-url').val(),
                        'large_url'    :$(this).find('.large-image-url').val()
                     }

                    if(images.length > 0){
                        var us = images.not(":hidden");
                        for(var i=0; i < us.length; i++) {
                            new_uploaded_images.push({
                                'name': $(us[i]).find('.image-name').val()
                            });
                        }
                    }

                    if(!media_attachment.is(":hidden")) {
                        new_attached_link = {
                            title           : media_attachment.find('.link-title').val(),
                            description     : media_attachment.find('.link-description').val(),
                            image           : media_attachment.find('.link-image').val(),
                            url             : media_attachment.find('.link-url').val(),
                            video           : media_attachment.find('.link-video').val(),
                        }
                    }

                    var remaining = {
                        uploaded_images : new_uploaded_images
                      , attached_link   : new_attached_link
                    }

                    var attachment_data = {
                        feedbackId      : div.find('.attachment_feedback_id').val()
                      , attachments     : remaining
                      , remove_image    : remove_image
                    }

                    //place this in service you lazy bastard!
                    $.ajax({
                        type: "POST"
                      , url: "/inbox/update_feedback_attachment"
                      , dataType: "json"
                      , data: attachment_data
                    });
                });
                e.preventDefault();
            })
        }
    }
})
.directive('flag', function() {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind('click', function(e) {
                var policy = $(this).attr("return-policy");
                if(policy == 1) {
                    $(this).removeAttr("style");
                    $(this).attr("return-policy", 0);
                } else {
                    $(this).attr("style", "background-position: -194px -31px");
                    $(this).attr("return-policy", 1);
                }
                e.preventDefault();
            });
        }
    }
})

function published_state(obj, sibling_id, msg, state) {
    //kill me....
    obj.parents('.dashboard-feedback').css(state.activation_color);
    obj.css(state.activate);
    obj.children('.action-tooltip').children('span').html("Return to Inbox");
    obj.siblings(sibling_id).css(state.deactivate_sibling);
    obj.siblings(sibling_id).children('.action-tooltip').children('span').html(msg);
    obj.siblings(sibling_id).attr('return-policy', 0);
    obj.siblings(sibling_id).attr('data-feed', state.state_change);
    obj.attr('return-policy', 1);
    obj.attr('data-feed', state.state_change_inbox);

    var origin_cat_data = obj.siblings('.save')
                               .children('div.the-categories-menu')
                               .children('.the-categories-menu-content')
                               .children(".the-categories")
                               .children(".grids")
                               .children('li')
                               .children('a');

    for(var i=0;i<origin_cat_data.length;i++) {
        var cat = $(origin_cat_data[i]);

        var feed = $.parseJSON(cat.attr('data-feed'));
        feed.status = "fileas";
        feed.origin = state.present_status

        var repackaged_json = JSON.stringify(feed);
        cat.attr('data-feed', repackaged_json);
    }
}

function hide_the_children(obj) {
    obj.parents('.dashboard-feedback').hide();
    var child_count = obj.parents('.feedback-group').children('.dashboard-feedback:visible');
    if(child_count.length == 0) {
        obj.parents('.feedback-group').hide();
    }
}
<commit_msg>ticketing<commit_after>angular.module('feedbackcontrol', [])
.directive('transform', function(FeedbackSignal) {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind('click', function(e) {
                var currentUrl = window.location.pathname;
                var me = $(element);
                var data = FeedbackSignal.data;

                if(currentUrl.match(/inbox\/all|deleted/g)) {
                    if(data.id.length > 0) {
                        hide_the_children(me);
                        $(".checky-box-container").show();
                    }
                }

                if(currentUrl.match(/published/g)) {

                    if(me.attr('return-policy') == 1) {
                        hide_the_children(me);
                        $(".checky-box-container").show();
                    }

                    if(data.status == "feature") {
                        var state = {
                            activate: {'background-position': '-64px -31px'}
                          , deactivate_sibling: {'background-position': '-32px 0px'}
                          , activation_color: {'background-color': '#ffffe0'}
                          , state_change_inbox: '{"status": "inbox", "id": ' + data.id + ', "catid": ' + data.catid + ', "origin": "feature"}'
                          , state_change: '{"status": "publish", "id": ' + data.id + ', "catid": ' + data.catid + ', "origin": "publish"}'
                          , present_status: "feature"
                        }
                        published_state(me, '.publish', 'publish feedback', state);
                    }

                    if(data.status == "publish") {
                        var state = {
                            activate: {'background-position': '-32px -31px'}
                          , deactivate_sibling: {'background-position': '-64px 0px'}
                          , activation_color: {'background-color': '#fff'}
                          , state_change_inbox: '{"status": "inbox", "id": ' + data.id + ', "catid": ' + data.catid + ', "origin": "publish"}'
                          , state_change: '{"status": "feature", "id": ' + data.id + ', "catid": ' + data.catid + ', "origin": "feature"}'
                          , present_status: "publish"
                        }
                        published_state(me, '.feature', 'feature feedback', state);
                    }

                    if(data.status == "delete" || data.status == "fileas") {
                        hide_the_children(me);
                        $(".checky-box-container").show();
                    }

                }

                if(currentUrl.match(/filed/g)) {

                    var data_status = data.status;

                    if(data_status == "publish" || data_status == "feature" || data_status == "delete") {
                        hide_the_children(me);
                        $(".checky-box-container").show();
                    }

                    if(data_status == "fileas") {
                        $(me).parents(".dashboard-feedback")
                               .children("div.feedback-contents")
                               .children(".responsive-padding")
                               .children(".feedback-details")
                               .children(".filed")
                               .html($(me).text())
                    }

                }

                e.preventDefault();
            });
        }
    }
})
.directive('undo', function(FeedbackSignal, FeedbackControlService) {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind("click", function(e) {

                var currentUrl = window.location.pathname;

                $(".checky-box-container").hide();
                if (FeedbackSignal.data.id instanceof Array) {
                    for(var i=0; i < FeedbackSignal.data.id.length ; i++) {
                        var feedback = $(".dashboard-feedback[feedback=" + FeedbackSignal.data.id[i] + "]");
                        feedback.show();
                        $(feedback).parents('.feedback-group').show();

                        if(currentUrl.match(/inbox\/all|deleted|published/g)) {
                            var catpicks = $(".dashboard-feedback[feedback=" + FeedbackSignal.data.id[i] + "] li .cat-picks");
                            catpicks.css({'background': '#598499'});
                        }

                    }
                } else {
                    var feedback = $(".dashboard-feedback[feedback=" + FeedbackSignal.data.id + "]");
                    feedback.show();
                    $(feedback).parents('.feedback-group').show();

                    if(currentUrl.match(/inbox\/all|deleted|published/g)) {
                        var catpicks = $(".dashboard-feedback[feedback=" + FeedbackSignal.data.id + "] li .cat-picks");
                        catpicks.css({'background': '#598499'});
                    }

                    var checkbox = $(".feed-checkbox[value=" + FeedbackSignal.data.id + "]");

                    if(checkbox.is(":checked")) {
                        checkbox.click();
                    }
                }

                if($(".sorter-checkbox").is(":checked")) {
                    $(".sorter-checkbox").click();
                }

                if($('.feed-checkbox').is(":checked")) {
                    $('.feed-checkbox').prop("checked", false);
                }

                $(".dashboard-feedback").css({'background-color': '#FFF'});

                FeedbackControlService.expunge();
                e.preventDefault();
            });
        }
    }
})
.directive('close', function(FeedbackControlService) {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind("click", function(e) {
                $(".checky-box-container").hide();
                FeedbackControlService.expunge();
                e.preventDefault();
            });
        }
    }
})
.directive('feedcheckbox', function() {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            var checkbox = $(element);

            checkbox.bind('change', function() {
                if(checkbox.is(":checked")) {
                    checkbox.parents('.dashboard-feedback').css({'background-color': '#F7F7F7'});
                } else {
                    checkbox.parents('.dashboard-feedback').css({'background-color': '#FFF'});
                }
            });

        }
    }
})
.directive('statuschange', function(FeedbackService) {
    return {
        restrict: 'A'
      , scope: {
            feedid: "@feedid"
          , statustype: "@statustype"
        }
      , link: function(scope, element, attrs) {
            $(element).bind('change', function() {
                var status_class, value;
                var myvalue = $(this).val();
                if(scope.statustype == "status") {
                   status_class = ".status-line";
                   console.log(myvalue);
                   if(myvalue == "new") { value = "New"; }
                   if(myvalue == "inprogress") { value = "In Progress"; }
                   if(myvalue == "closed") { value = "Closed"; }
                } else {
                   status_class = ".priority-line";
                   console.log(myvalue);
                   if(myvalue == 0) { value = "Low"; }
                   if(myvalue == 60) { value = "Medium"; }
                   if(myvalue == 100) { value = "High"; }
                }

                $(this).parents(".dashboard-feedback")
                       .children("div.feedback-contents")
                       .children(".responsive-padding")
                       .children(".feedback-details")
                       .children(".feedback-details-status")
                       .children(status_class)
                       .html(value)

                FeedbackService.inline_change($(this).val(), scope.feedid, scope.statustype);

            })
        }
    }
})
.directive('deleteBlock', function() {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind('click', function(e) {
                $(this).parents('.custom-att').fadeOut(400, function() {
                     var new_uploaded_images = new Array;
                     var new_attached_link;

                     var div = $(this).parents('.uploaded-images-and-links');
                     var images = div.find('.uploaded_image');
                     var media_attachment = div.find('.attached_link');

                     var remove_image = {
                        'small_url'    :$(this).find('.small-image-url').val(),
                        'medium_url'   :$(this).find('.medium-image-url').val(),
                        'large_url'    :$(this).find('.large-image-url').val()
                     }

                    if(images.length > 0){
                        var us = images.not(":hidden");
                        for(var i=0; i < us.length; i++) {
                            new_uploaded_images.push({
                                'name': $(us[i]).find('.image-name').val()
                            });
                        }
                    }

                    if(!media_attachment.is(":hidden")) {
                        new_attached_link = {
                            title           : media_attachment.find('.link-title').val(),
                            description     : media_attachment.find('.link-description').val(),
                            image           : media_attachment.find('.link-image').val(),
                            url             : media_attachment.find('.link-url').val(),
                            video           : media_attachment.find('.link-video').val(),
                        }
                    }

                    var remaining = {
                        uploaded_images : new_uploaded_images
                      , attached_link   : new_attached_link
                    }

                    var attachment_data = {
                        feedbackId      : div.find('.attachment_feedback_id').val()
                      , attachments     : remaining
                      , remove_image    : remove_image
                    }

                    //place this in service you lazy bastard!
                    $.ajax({
                        type: "POST"
                      , url: "/inbox/update_feedback_attachment"
                      , dataType: "json"
                      , data: attachment_data
                    });
                });
                e.preventDefault();
            })
        }
    }
})
.directive('flag', function() {
    return {
        restrict: 'A'
      , link: function(scope, element, attrs) {
            $(element).bind('click', function(e) {
                var policy = $(this).attr("return-policy");
                if(policy == 1) {
                    $(this).removeAttr("style");
                    $(this).attr("return-policy", 0);
                } else {
                    $(this).attr("style", "background-position: -194px -31px");
                    $(this).attr("return-policy", 1);
                }
                e.preventDefault();
            });
        }
    }
})

function published_state(obj, sibling_id, msg, state) {
    //kill me....
    obj.parents('.dashboard-feedback').css(state.activation_color);
    obj.css(state.activate);
    obj.children('.action-tooltip').children('span').html("Return to Inbox");
    obj.siblings(sibling_id).css(state.deactivate_sibling);
    obj.siblings(sibling_id).children('.action-tooltip').children('span').html(msg);
    obj.siblings(sibling_id).attr('return-policy', 0);
    obj.siblings(sibling_id).attr('data-feed', state.state_change);
    obj.attr('return-policy', 1);
    obj.attr('data-feed', state.state_change_inbox);

    var origin_cat_data = obj.siblings('.save')
                               .children('div.the-categories-menu')
                               .children('.the-categories-menu-content')
                               .children(".the-categories")
                               .children(".grids")
                               .children('li')
                               .children('a');

    for(var i=0;i<origin_cat_data.length;i++) {
        var cat = $(origin_cat_data[i]);

        var feed = $.parseJSON(cat.attr('data-feed'));
        feed.status = "fileas";
        feed.origin = state.present_status

        var repackaged_json = JSON.stringify(feed);
        cat.attr('data-feed', repackaged_json);
    }
}

function hide_the_children(obj) {
    obj.parents('.dashboard-feedback').hide();

    console.log(obj.parents('.dashboard-feedback'));

    var child_count = obj.parents('.feedback-group').children('.dashboard-feedback:visible');
    if(child_count.length == 0) {
        obj.parents('.feedback-group').hide();
    }
}
<|endoftext|>


<commit_before>$(function () {

    lightbox();
    sticky();
    utils();

    demo();

});

/* for demo purpose only - can be deleted */

function demo() {

    $("#page").change(function () {

        if ($(this).val() !== '') {

            window.location.href = $(this).val();

        }

        return false;
    });
}

/* =========================================
 *  lightbox
 *  =======================================*/

function lightbox() {

    $(document).delegate('*[data-toggle="lightbox"]', 'click', function (event) {
        event.preventDefault();
        $(this).ekkoLightbox();
    });
}

/* =========================================
 *  sticky header
 *  =======================================*/

function sticky() {

    $(".header").sticky();

}

function utils() {

    /* tooltips */

    $('[data-toggle="tooltip"]').tooltip();

    /* click on the box activates the radio */

    $('#checkout').on('click', '.box.shipping-method, .box.payment-method', function (e) {
        var radio = $(this).find(':radio');
        radio.prop('checked', true);
    });
    /* click on the box activates the link in it */

    $('.box.clickable').on('click', function (e) {

        window.location = $(this).find('a').attr('href');
    });
    /* external links in new window*/

    $('.external').on('click', function (e) {

        e.preventDefault();
        window.open($(this).attr("href"));
    });
    /* animated scrolling */

    /* animated scrolling */

    $('.scroll-to, #navigation a').click(function (event) {
        event.preventDefault();
        var full_url = this.href;
        var parts = full_url.split("#");
        var trgt = parts[1];

        $('body').scrollTo($('#' + trgt), 800, {offset: -40});

    });

}

$.fn.alignElementsSameHeight = function () {
    $('.same-height-row').each(function () {

        var maxHeight = 0;
        var children = $(this).find('.same-height');
        children.height('auto');
        if ($(window).width() > 768) {
            children.each(function () {
                if ($(this).innerHeight() > maxHeight) {
                    maxHeight = $(this).innerHeight();
                }
            });
            children.innerHeight(maxHeight);
        }

        maxHeight = 0;
        children = $(this).find('.same-height-always');
        children.height('auto');
        children.each(function () {
            if ($(this).innerHeight() > maxHeight) {
                maxHeight = $(this).innerHeight();
            }
        });
        children.innerHeight(maxHeight);
    });
}

$(window).load(function () {

    windowWidth = $(window).width();
    windowHeight = $(window).height();

    $(this).alignElementsSameHeight();

});
$(window).resize(function () {

    newWindowWidth = $(window).width();
    newWindowHeight = $(window).height();

    if (windowWidth !== newWindowWidth) {
        setTimeout(function () {
            $(this).alignElementsSameHeight();
        }, 100);
        windowWidth = newWindowWidth;
        windowHeight = newWindowHeight;
    }

});
<commit_msg>collect static and template files to one directory<commit_after>$(function () {

    lightbox();
    sticky();
    utils();

    demo();

});

/* for demo purpose only - can be deleted */

function demo() {

    $("#page").change(function () {

        if ($(this).val() !== '') {

            window.location.href = $(this).val();

        }

        return false;
    });
}

/* =========================================
 *  lightbox
 *  =======================================*/

function lightbox() {

    $(document).delegate('*[data-toggle="lightbox"]', 'click', function (event) {
        event.preventDefault();
        $(this).ekkoLightbox();
    });
}

/* =========================================
 *  sticky header
 *  =======================================*/

function sticky() {

    $(".header").sticky();

}

function utils() {

    /* tooltips */

    $('[data-toggle="tooltip"]').tooltip();

    /* click on the box activates the radio */

    $('#checkout').on('click', '.box.shipping-method, .box.payment-method', function (e) {
        var radio = $(this).find(':radio');
        radio.prop('checked', true);
    });
    /* click on the box activates the link in it */

    $('.box.clickable').on('click', function (e) {

        window.location = $(this).find('a').attr('href');
    });
    /* external links in new window*/

    $('.external').on('click', function (e) {

        e.preventDefault();
        window.open($(this).attr("href"));
    });
    /* animated scrolling */

    /* animated scrolling */

    $('.scroll-to, #navigation a').click(function (event) {
        event.preventDefault();
        var full_url = this.href;
        var parts = full_url.split("#");
        var trgt = parts[1];

        $('body').scrollTo($('#' + trgt), 800, {offset: -40});

    });

}

$.fn.alignElementsSameHeight = function () {
    $('.same-height-row').each(function () {

        var maxHeight = 0;
        var children = $(this).find('.same-height');
        children.height('auto');
        if ($(window).width() > 768) {
            children.each(function () {
                if ($(this).innerHeight() > maxHeight) {
                    maxHeight = $(this).innerHeight();
                }
            });
            children.innerHeight(maxHeight);
        }

        maxHeight = 0;
        children = $(this).find('.same-height-always');
        children.height('auto');
        children.each(function () {
            if ($(this).innerHeight() > maxHeight) {
                maxHeight = $(this).innerHeight();
            }
        });
        children.innerHeight(maxHeight);
    });
};

$(window).load(function () {

    windowWidth = $(window).width();
    windowHeight = $(window).height();

    $(this).alignElementsSameHeight();

});
$(window).resize(function () {

    newWindowWidth = $(window).width();
    newWindowHeight = $(window).height();

    if (windowWidth !== newWindowWidth) {
        setTimeout(function () {
            $(this).alignElementsSameHeight();
        }, 100);
        windowWidth = newWindowWidth;
        windowHeight = newWindowHeight;
    }

});
<|endoftext|>


<commit_before>var JExpress = require("jexpress");
var config = require('config');
var mongoose = require("mongoose");
var Websocket = require('../libs/websockets.js');
var messagequeue = require("../libs/messagequeue");
var websocket = new Websocket();

var trimuser = function(user) {
	if (!user) {
		return null;
	}
	return {
		_id: user._id,
		email: user.email,
		name: user.name,
		organisation_id: user.organisation_id,
		location_id: user.location_id
	};
};

config.pre_hooks = {
	get: (req, res, next) => {
		console.log("Called Get Hook");
		if (!req.Model.schema.paths.location_id)
			return next();
		if (req.query.location_override)
			return next();
		if (req.query.filter && req.query.filter.location_id)
			return next();
		if (!req.user)
			return next();
		if (req.groups.indexOf("super_user") !== -1)
			return next();
		if (!req.query.filter)
			req.query.filter = {};
		req.query.filter.location_id = req.user.location_id + "";
		next();
	}
};

config.callbacks = {
	post: function(modelname, item, user) {
		websocket.emit(modelname, "post", item._id);
		messagequeue.action(modelname, "post", trimuser(user), item);
	},
	put: function(modelname, item, user) {
		websocket.emit(modelname, "put", item._id);
		messagequeue.action(modelname, "put", trimuser(user), item);
	},
	delete: function(modelname, item, user, opts) {
		websocket.emit(modelname, "delete", item._id);
		messagequeue.action(modelname, "delete", trimuser(user), item);
	}
};

//DB connection
mongoose.connect('mongodb://' + config.mongo.server + '/' + config.mongo.db, function(err) {
	if (err) {
		console.log("Connection error", err);
	}
}, { db: { safe:true } }); // connect to our database

var server = new JExpress(config);

server.listen(config.port || 3001, function() {
	console.log('%s listening at %s', server.name, server.url);
});

module.exports = server; //For Testing<commit_msg>Stop some startup warnings. Use JExpress as the name of our sever<commit_after>var JExpress = require("jexpress");
var config = require('config');
var mongoose = require("mongoose");
var Websocket = require('../libs/websockets.js');
var messagequeue = require("../libs/messagequeue");
var websocket = new Websocket();

var trimuser = function(user) {
	if (!user) {
		return null;
	}
	return {
		_id: user._id,
		email: user.email,
		name: user.name,
		organisation_id: user.organisation_id,
		location_id: user.location_id
	};
};

config.pre_hooks = {
	get: (req, res, next) => {
		if (!req.Model.schema.paths.location_id)
			return next();
		if (req.query.location_override)
			return next();
		if (req.query.filter && req.query.filter.location_id)
			return next();
		if (!req.user)
			return next();
		if (req.groups.indexOf("super_user") !== -1)
			return next();
		if (!req.query.filter)
			req.query.filter = {};
		req.query.filter.location_id = req.user.location_id + "";
		next();
	}
};

config.callbacks = {
	post: function(modelname, item, user) {
		websocket.emit(modelname, "post", item._id);
		messagequeue.action(modelname, "post", trimuser(user), item);
	},
	put: function(modelname, item, user) {
		websocket.emit(modelname, "put", item._id);
		messagequeue.action(modelname, "put", trimuser(user), item);
	},
	delete: function(modelname, item, user, opts) {
		websocket.emit(modelname, "delete", item._id);
		messagequeue.action(modelname, "delete", trimuser(user), item);
	}
};

//DB connection
mongoose.Promise = global.Promise;
mongoose.createConnection('mongodb://' + config.mongo.server + '/' + config.mongo.db, function(err) {
	if (err) {
		console.log("Connection error", err);
	}
}, { db: { safe:true } }); // connect to our database

var server = new JExpress(config);

server.listen(config.port || 3001, function() {
	console.log('%s listening at %s', "JExpress", server.url);
});

module.exports = server; //For Testing<|endoftext|>


<commit_before>/* globals jQuery, Firebase */

var getUserMedia = require('getusermedia');
var attachFastClick = require('fastclick');
var State = require('ampersand-state');

var MainView = require('./views/main');
var User = require('./models/user');

var App = State.extend({
    props: {
        firebaseId: ['string', true, 'torid-inferno-617'],
        env: ['string', true, window.location.host.split('.')[0].split(':')[0]],
        name: ['string', true, 'GifChess'],
        id: ['string', true, 'ss15-luke-js'],
        rendered: ['boolean', true, false],
        stream: 'object',
        streamRequest: 'boolean',
        streamError: 'object'
    },

    derived: {
        isLocal: {
            deps: ['env'],
            fn: function () {
                return this.env === 'localhost';
            }
        },
        lsKey: {
            deps: ['id', 'env'],
            fn: function () {
                return [this.id, this.env].join('.');
            }
        },
        firebaseUrl: {
            deps: ['firebaseId'],
            fn: function () {
                return 'https://' + this.firebaseId + '.firebaseio.com/';
            }
        },
        firebase: {
            deps: ['firebaseUrl'],
            fn: function () {
                return new Firebase(this.firebaseUrl);
            }
        },
        streamDenied: {
            deps: ['streamError'],
            fn: function () {
                return this.streamError && this.streamError.name === 'PermissionDeniedError';
            }
        },
        streamSuccess: {
            deps: ['stream', 'streamError'],
            fn: function () {
                return !!this.stream && !this.streamError;
            }
        },
    },

    initialize: function () {
        window.app = this;

        this.me = new User();
        this.firebase.onAuth(this._onAuth.bind(this));
    },
    renderMainView: function () {
        if (this.rendered) return;
        this.rendered = true;

        jQuery(function () {
            attachFastClick(document.body);

            this.view = new MainView({
                el: document.body,
                model: this,
                me: this.me
            });

            this.navigate = this.view.navigate.bind(this.view);
        }.bind(this));
    },

    // ------------------------
    // STREAM
    // ------------------------
    getUserMedia: function () {
        if (!this.streamRequest) {
            this.streamRequest = true;
            getUserMedia({video: true, audio: false}, this.getStream.bind(this));
        }
    },
    getStream: function (err, stream) {
        this.streamRequest = false;
        if (err) {
            this.streamError = err;
        } else {
            this.stream = stream;
        }
    },

    // ------------------------
    // AUTH
    // ------------------------
    login: function () {
        this.firebase.authWithOAuthPopup('twitter', this._tryAuth.bind(this));
    },
    logout: function () {
        this.firebase.unauth();
    },
    _tryAuth: function (err) {
        if (err && err.code === 'TRANSPORT_UNAVAILABLE') {
            this.authWithOAuthRedirect('twitter', this._tryAuth.bind(this));
        }
        else if (err) {
            console.error(err.code, err.message);
        }
    },
    _onAuth: function (auth) {
        this.me.auth(auth);
        this.renderMainView();
    },

    // ------------------------
    // LOCALSTORAGE
    // ------------------------
    localStorage: function (key, val) {
        var localStorageKey = this.lsKey;
        var current = localStorage[localStorageKey] || '{}';

        try {
            current = JSON.parse(current);
        } catch (e) {
            current = {};
        }

        if (key && typeof val !== 'undefined') {
            current[key] = val;
            localStorage[localStorageKey] = JSON.stringify(current);
            return val;
        } else if (key) {
            return current[key];
        }
    },
    __reset: function () {
        localStorage[this.lsKey] = '{}';
    }
});

new App({});
<commit_msg>new domain<commit_after>/* globals jQuery, Firebase */

var getUserMedia = require('getusermedia');
var attachFastClick = require('fastclick');
var State = require('ampersand-state');

var MainView = require('./views/main');
var User = require('./models/user');

var App = State.extend({
    props: {
        firebaseId: ['string', true, 'torid-inferno-617'],
        env: ['string', true, window.location.host.split('.')[0].split(':')[0]],
        name: ['string', true, 'GifChess'],
        id: ['string', true, 'ss15-luke-js'],
        rendered: ['boolean', true, false],
        stream: 'object',
        streamRequest: 'boolean',
        streamError: 'object'
    },

    derived: {
        isLocal: {
            deps: ['env'],
            fn: function () {
                return this.env === 'localhost';
            }
        },
        lsKey: {
            deps: ['id', 'env'],
            fn: function () {
                return [this.id, this.env].join('.');
            }
        },
        firebaseUrl: {
            deps: ['firebaseId'],
            fn: function () {
                return 'https://' + this.firebaseId + '.firebaseio.com/';
            }
        },
        firebase: {
            deps: ['firebaseUrl'],
            fn: function () {
                return new Firebase(this.firebaseUrl);
            }
        },
        streamDenied: {
            deps: ['streamError'],
            fn: function () {
                return this.streamError && this.streamError.name === 'PermissionDeniedError';
            }
        },
        streamSuccess: {
            deps: ['stream', 'streamError'],
            fn: function () {
                return !!this.stream && !this.streamError;
            }
        },
    },

    initialize: function () {
        // New domain
        return window.location.href = '//gifchess.club' + window.location.pathname;

        window.app = this;

        this.me = new User();
        this.firebase.onAuth(this._onAuth.bind(this));
    },
    renderMainView: function () {
        if (this.rendered) return;
        this.rendered = true;

        jQuery(function () {
            attachFastClick(document.body);

            this.view = new MainView({
                el: document.body,
                model: this,
                me: this.me
            });

            this.navigate = this.view.navigate.bind(this.view);
        }.bind(this));
    },

    // ------------------------
    // STREAM
    // ------------------------
    getUserMedia: function () {
        if (!this.streamRequest) {
            this.streamRequest = true;
            getUserMedia({video: true, audio: false}, this.getStream.bind(this));
        }
    },
    getStream: function (err, stream) {
        this.streamRequest = false;
        if (err) {
            this.streamError = err;
        } else {
            this.stream = stream;
        }
    },

    // ------------------------
    // AUTH
    // ------------------------
    login: function () {
        this.firebase.authWithOAuthPopup('twitter', this._tryAuth.bind(this));
    },
    logout: function () {
        this.firebase.unauth();
    },
    _tryAuth: function (err) {
        if (err && err.code === 'TRANSPORT_UNAVAILABLE') {
            this.authWithOAuthRedirect('twitter', this._tryAuth.bind(this));
        }
        else if (err) {
            console.error(err.code, err.message);
        }
    },
    _onAuth: function (auth) {
        this.me.auth(auth);
        this.renderMainView();
    },

    // ------------------------
    // LOCALSTORAGE
    // ------------------------
    localStorage: function (key, val) {
        var localStorageKey = this.lsKey;
        var current = localStorage[localStorageKey] || '{}';

        try {
            current = JSON.parse(current);
        } catch (e) {
            current = {};
        }

        if (key && typeof val !== 'undefined') {
            current[key] = val;
            localStorage[localStorageKey] = JSON.stringify(current);
            return val;
        } else if (key) {
            return current[key];
        }
    },
    __reset: function () {
        localStorage[this.lsKey] = '{}';
    }
});

new App({});
<|endoftext|>


<commit_before>
angular.module('receipter').controller('UploadController', function($scope, notification, camera) {
  'use strict';
  //data:image/jpeg;base64,{{imagedata}}

  $scope.imagesource = 'img/shutter.png';

  this.alert = function() {
    notification.alert('alert', function() {
      alert(Array.prototype.slice.call(arguments).join('\n'));
    });
  };

  this.confirm = function() {
    notification.confirm('confirm', function() {
      alert(Array.prototype.slice.call(arguments).join('\n'));
    }, 'Question', ['OK', 'ABORT!']);
  };

  this.prompt = function() { // message, callback, title, buttonLabels, defaultText
    notification.confirm('give it to me', function() {
      alert(Array.prototype.slice.call(arguments).join('\n'));
    }, 'Prompt', ['OK', 'ABORT!']);
  };

  this.beep = function() {
    notification.beep(1);
  };

  this.vibrate = function() {
    notification.vibrate(500);
  };

  this.newPicture = function() {
    camera.getPicture(
      function(data) {
        $scope.imagesource = 'data:image/jpeg;base64,' + data;
        camera.cleanup();
      },
      function() {});
  };

  this.pictureFromLibrary = function() {
    camera.getPicture(
      function(data) {
        $scope.imagesource = 'data:image/jpeg;base64,' + data;
        camera.cleanup();
      },
      function() {},
      {
        pictureSourceType: camera.PictureSourceType.PHOTOLIBRARY
      });
  };

});<commit_msg>sourceType  - not pictureSourceType<commit_after>
angular.module('receipter').controller('UploadController', function($scope, notification, camera) {
  'use strict';
  //data:image/jpeg;base64,{{imagedata}}

  $scope.imagesource = 'img/shutter.png';

  this.alert = function() {
    notification.alert('alert', function() {
      alert(Array.prototype.slice.call(arguments).join('\n'));
    });
  };

  this.confirm = function() {
    notification.confirm('confirm', function() {
      alert(Array.prototype.slice.call(arguments).join('\n'));
    }, 'Question', ['OK', 'ABORT!']);
  };

  this.prompt = function() { // message, callback, title, buttonLabels, defaultText
    notification.confirm('give it to me', function() {
      alert(Array.prototype.slice.call(arguments).join('\n'));
    }, 'Prompt', ['OK', 'ABORT!']);
  };

  this.beep = function() {
    notification.beep(1);
  };

  this.vibrate = function() {
    notification.vibrate(500);
  };

  this.newPicture = function() {
    camera.getPicture(
      function(data) {
        $scope.imagesource = 'data:image/jpeg;base64,' + data;
        camera.cleanup();
      },
      function() {});
  };

  this.pictureFromLibrary = function() {
    camera.getPicture(
      function(data) {
        $scope.imagesource = 'data:image/jpeg;base64,' + data;
        camera.cleanup();
      },
      function() {},
      {
        sourceType: camera.PictureSourceType.SAVEDPHOTOALBUM
      });
  };

});<|endoftext|>


<commit_before>// Copyright 2018-2019, University of Colorado Boulder
/* eslint-disable bad-text */

/**
 * Lint detector for invalid text.
 * Lint is disabled for this file so the bad texts aren't themselves flagged.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */

module.exports = function( context ) {

  const getBadTextTester = require( './getBadTextTester' );

  // see getBadTextTester for schema
  const forbiddenTextObjects = [

    // Proper casing for *boxes

    // toolbox is one word
    'toolBox', // prefer toolbox
    'ToolBox', // prefer Toolbox
    'TOOL_BOX', // prefer TOOLBOX

    // checkbox is one word
    'checkBox', // prefer checkbox
    'CheckBox', // prefer Checkbox
    'CHECK_BOX', // prefer CHECKBOX

    // combo box is two words
    'combobox', // prefer combo box
    'Combobox', // prefer Combo Box
    'COMBOBOX', // prefer COMBO_BOX

    'Overriden', // should have 2 "d"s
    'overriden', // should have 2 "d"s

    'iFrame', // should be iframe

    // event.keyCode according to spec, rather than event.keycode
    'keycode',

    // prefer hotkey (one word)
    'hot key',
    'hotKey',
    'HotKey',
    'HOT_KEY',

    // embarrassingly enough, zepumph is so bad at typing this word that he needs these lint rules, see https://github.com/phetsims/friction/issues/234
    'respones',
    'Respones',

    // In ES6, extending object causes methods to be dropped
    { id: 'extends Object ', codeTokens: [ 'extends', 'Object' ] },

    // Forbid common duplicate words
    ' the the ',
    ' a a ',
    'dipose', // happens more than you'd think

    // For phet-io use PHET_IO in constants
    'PHETIO',
    'PHET-IO',
    'Phet-iO',
    ' Phet ',
    'phetio element', // use "phet-io element" or "PhET-iO element"
    'Phet-iO',
    { id: 'IO type', regex: /\bIO type/ }, // https://github.com/phetsims/chipper/issues/977

    '@return ',

    'Util = require( \'', // Utils should now be plural, see https://github.com/phetsims/tasks/issues/966

    // if on a one line arrow function returning something, prefer instead `() => theReturn`, see https://github.com/phetsims/chipper/issues/790
    ' => { return ',

    'define( function( require ) {', // use define( require => { to standardize before es6 module migration

    // optional 'options' should use brackets and required 'config' shouldn't use brackets, see https://github.com/phetsims/chipper/issues/859
    '@param {Object} options',
    '@param {Object} [config]',

    // PhET prefers to use the term "position" to refer to the physical (x,y) position of objects.
    // The lint rule can be disabled for occurrences where we do prefer locationProperty, for instance if we
    // had a sim about people that are from three different named locations.
    'locationProperty',

    {
      id: 'Import from statements require a *.js suffix',
      predicate: line => {
        if ( line.trim().indexOf( 'import ' ) === 0 && line.indexOf( ' from ' ) > 0 && line.indexOf( '.js' ) === -1 ) {
          return false;
        }
        return true;
      }
    },

    {
      id: 'Import statements require a *.js suffix',
      predicate: line => {
        if ( line.trim().indexOf( 'import \'' ) === 0 && line.indexOf( ';' ) >= 0 && line.indexOf( '.js' ) === -1 ) {
          return false;
        }
        return true;
      }
    },

    {
      id: 'Export statements should not have a register call',
      predicate: line => {
        if ( line.trim().indexOf( 'export default' ) === 0 && line.indexOf( '.register(' ) >= 0 ) {
          return false;
        }
        return true;
      }
    },

    // Should have a period before "<", see https://github.com/phetsims/chipper/issues/1005 and https://github.com/phetsims/chipper/issues/1003
    { id: 'Type<Parameter> (add a dot)', regex: /{[^\n:]*[A-z]<[A-z][|'<>A-z]+>[^\n:{}]*}}/ }
  ];

  return {
    Program: getBadTextTester( forbiddenTextObjects, context )
  };
};

module.exports.schema = [
  // JSON Schema for rule options goes here
];<commit_msg>Forbid unparameterized optionize calls, see https://github.com/phetsims/chipper/issues/1128<commit_after>// Copyright 2018-2019, University of Colorado Boulder
/* eslint-disable bad-text */

/**
 * Lint detector for invalid text.
 * Lint is disabled for this file so the bad texts aren't themselves flagged.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */

module.exports = function( context ) {

  const getBadTextTester = require( './getBadTextTester' );

  // see getBadTextTester for schema
  const forbiddenTextObjects = [

    // Proper casing for *boxes

    // toolbox is one word
    'toolBox', // prefer toolbox
    'ToolBox', // prefer Toolbox
    'TOOL_BOX', // prefer TOOLBOX

    // checkbox is one word
    'checkBox', // prefer checkbox
    'CheckBox', // prefer Checkbox
    'CHECK_BOX', // prefer CHECKBOX

    // combo box is two words
    'combobox', // prefer combo box
    'Combobox', // prefer Combo Box
    'COMBOBOX', // prefer COMBO_BOX

    'Overriden', // should have 2 "d"s
    'overriden', // should have 2 "d"s

    'iFrame', // should be iframe

    // event.keyCode according to spec, rather than event.keycode
    'keycode',

    // prefer hotkey (one word)
    'hot key',
    'hotKey',
    'HotKey',
    'HOT_KEY',

    // embarrassingly enough, zepumph is so bad at typing this word that he needs these lint rules, see https://github.com/phetsims/friction/issues/234
    'respones',
    'Respones',

    // In ES6, extending object causes methods to be dropped
    { id: 'extends Object ', codeTokens: [ 'extends', 'Object' ] },

    // Forbid common duplicate words
    ' the the ',
    ' a a ',
    'dipose', // happens more than you'd think

    // For phet-io use PHET_IO in constants
    'PHETIO',
    'PHET-IO',
    'Phet-iO',
    ' Phet ',
    'phetio element', // use "phet-io element" or "PhET-iO element"
    'Phet-iO',
    { id: 'IO type', regex: /\bIO type/ }, // https://github.com/phetsims/chipper/issues/977

    '@return ',

    'Util = require( \'', // Utils should now be plural, see https://github.com/phetsims/tasks/issues/966

    // if on a one line arrow function returning something, prefer instead `() => theReturn`, see https://github.com/phetsims/chipper/issues/790
    ' => { return ',

    'define( function( require ) {', // use define( require => { to standardize before es6 module migration

    // optional 'options' should use brackets and required 'config' shouldn't use brackets, see https://github.com/phetsims/chipper/issues/859
    '@param {Object} options',
    '@param {Object} [config]',

    // PhET prefers to use the term "position" to refer to the physical (x,y) position of objects.
    // The lint rule can be disabled for occurrences where we do prefer locationProperty, for instance if we
    // had a sim about people that are from three different named locations.
    'locationProperty',

    // optionize cannot infer its type arguments
    'optionize(',

    {
      id: 'Import from statements require a *.js suffix',
      predicate: line => {
        if ( line.trim().indexOf( 'import ' ) === 0 && line.indexOf( ' from ' ) > 0 && line.indexOf( '.js' ) === -1 ) {
          return false;
        }
        return true;
      }
    },

    {
      id: 'Import statements require a *.js suffix',
      predicate: line => {
        if ( line.trim().indexOf( 'import \'' ) === 0 && line.indexOf( ';' ) >= 0 && line.indexOf( '.js' ) === -1 ) {
          return false;
        }
        return true;
      }
    },

    {
      id: 'Export statements should not have a register call',
      predicate: line => {
        if ( line.trim().indexOf( 'export default' ) === 0 && line.indexOf( '.register(' ) >= 0 ) {
          return false;
        }
        return true;
      }
    },

    // Should have a period before "<", see https://github.com/phetsims/chipper/issues/1005 and https://github.com/phetsims/chipper/issues/1003
    { id: 'Type<Parameter> (add a dot)', regex: /{[^\n:]*[A-z]<[A-z][|'<>A-z]+>[^\n:{}]*}}/ }
  ];

  return {
    Program: getBadTextTester( forbiddenTextObjects, context )
  };
};

module.exports.schema = [
  // JSON Schema for rule options goes here
];<|endoftext|>


<commit_before>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow strict-local
 * @format
 */

import React from 'react';
import type {Node} from 'react';
import {StyleSheet, Text, useColorScheme, View} from 'react-native';
import Colors from './Colors';

const HermesBadge = (): Node => {
  const isDarkMode = useColorScheme() === 'dark';
  return global.HermesInternal ? (
    <View style={styles.badge}>
      <Text
        style={[
          styles.badgeText,
          {
            color: isDarkMode ? Colors.light : Colors.dark,
          },
        ]}>
        Engine: Hermes
      </Text>
    </View>
  ) : null;
};

const styles = StyleSheet.create({
  badge: {
    position: 'absolute',
    top: 8,
    right: 12,
  },
  badgeText: {
    fontSize: 14,
    fontWeight: '600',
    textAlign: 'right',
  },
});

export default HermesBadge;
<commit_msg>Reflect Hermes release version from HermesBadge<commit_after>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow strict-local
 * @format
 */

import React from 'react';
import type {Node} from 'react';
import {StyleSheet, Text, useColorScheme, View} from 'react-native';
import Colors from './Colors';

const HermesBadge = (): Node => {
  const isDarkMode = useColorScheme() === 'dark';
  const version =
    global.HermesInternal?.getRuntimeProperties?.()['OSS Release Version'] ??
    '';
  return global.HermesInternal ? (
    <View style={styles.badge}>
      <Text
        style={[
          styles.badgeText,
          {
            color: isDarkMode ? Colors.light : Colors.dark,
          },
        ]}>
        {`Engine: Hermes ${version}`}
      </Text>
    </View>
  ) : null;
};

const styles = StyleSheet.create({
  badge: {
    position: 'absolute',
    top: 8,
    right: 12,
  },
  badgeText: {
    fontSize: 14,
    fontWeight: '600',
    textAlign: 'right',
  },
});

export default HermesBadge;
<|endoftext|>


<commit_before>var fs = require('fs');
var del = require('del');
var gulp = require('gulp');
var replace = require('gulp-replace');
var es = require('event-stream');
var runSequence = require('run-sequence');
var cloudfront_invalidate = require('gulp-cloudfront-invalidate');
var child_process = require('child_process');

var packageInfo = require('../package.json');

// Special travis package task that copies all outputs into travis/s3-upload folder for S3 upload
gulp.task('travis-package', function (cb) {
    del.sync(['travis']);

    var TRAVIS_OS = process.env['TRAVIS_OS_NAME'];

    if (TRAVIS_OS !== 'linux') {
        console.log('osx build');
    } else {
        runSequence(
            'package-linux',
            'unpack-linux',
            function () {
                console.log('FINISHED PACKING LINUX');
                const spawn = child_process.spawn('docker', ['exec', '-i', 'builder', 'snapcraft']);

                spawn.stdout.on('data', (data) => {
                  console.log(`stdout: ${data}`);
                });

                spawn.stderr.on('data', (data) => {
                  console.log(`stderr: ${data}`);
                });

                spawn.on('close', (code) => {
                    es.merge(
                        gulp
                            .src('dist/*.snap')
                            .pipe(gulp.dest('dist/_downloads/linux'))
                    ).on('end', function () {
                        fs.readdirSync('./').forEach(file => {
                          console.log(file);
                        });
                        cb();
                    });
                });
            }
        );
    }
});
<commit_msg>Delete travis.js<commit_after><|endoftext|>


<commit_before>// This module provides a framework for triggering notifications
// within the Apostrophe admin UI. Notifications may be triggered
// either on the browser or the server side, via `apos.notice`.
//
// ## Options
//
// ### `queryInterval`: interval in milliseconds between MongoDB
// queries while long polling for notifications. Defaults to 1000
// (1 second). Set it longer if you prefer fewer queries, however
// these are indexed queries on a small amount of information and
// should not significantly impact your app.
//
// ### `longPollingTimeout`: maximum lifetime in milliseconds of a long
// polling HTTP request before a response with no notifications is sent.
// Defaults to 10000 (10 seconds) to avoid typical proxy server timeouts.
// Until it times out the request will keep making MongoDB queries to
// see if any new notifications are available (long polling).

const Promise = require('bluebird');
const _ = require('lodash');

module.exports = {
  extend: '@apostrophecms/module',
  async init(self, options) {
    self.apos.notify = self.trigger;
    await self.ensureCollection();
  },
  apiRoutes(self, options) {
    return {
      post: {
        async trigger(req) {
          const type = self.apos.launder.select(req.body.type, [
            'error',
            'warn',
            'success',
            'info'
          ], 'info');
          const message = self.apos.launder.string(req.body.message);
          const strings = self.apos.launder.strings(req.body.strings);
          const dismiss = self.apos.launder.integer(req.body.dismiss);
          const pulse = self.apos.launder.boolean(req.body.pulse);
          const id = self.apos.launder.id(req.body.id);
          await self.trigger.apply(self, [
            req,
            message
          ].concat(strings).concat([{
            dismiss: dismiss,
            type: type,
            pulse: pulse,
            id: id
          }]));
        }
      }
    };
  },
  restApiRoutes: (self, options) => ({
    getOne(req, _id) {
      return self.find(req, { displayingIds: [_id] });
    },
    post(req) {
      return self.trigger(req, req.body.message, req.body.options || {});
    },
    put(req, _id) {
      throw self.apos.error('unimplemented');
    },
    patch(req, _id) {
      throw self.apos.error('unimplemented');
    },
    delete(req, _id) {
      return self.db.deleteMany({ _id });
    }
  }),
  methods(self, options) {
    return {

      // Call with `req`, then a message, followed by any interpolated strings
      // which must correspond to %s placeholders in `message` (variable number
      // of arguments), followed by an `options` object if desired.
      //
      // If you do not have a `req` it is acceptable to pass a user `_id` string
      // in place of `req`. Someone must be the recipient.
      //
      // `options.type` styles the notification and may be set to `error`,
      // `warn` or `success`. If not set, a "plain" default style is used.
      //
      // If `options.dismiss` is set to `true`, the message will auto-dismiss after 5 seconds.
      // If it is set to a number of seconds, it will dismiss after that number of seconds.
      // Otherwise it will not dismiss unless clicked.
      //
      // The message is internationalized, which is why the use of
      // %s placeholders for any inserted titles, etc. is important.
      //
      // Throws an error if there is no `req.user`.
      //
      // This method is aliased as `apos.notify` for convenience.
      //
      // The method is async, and you may `await` to be certain the
      // notification has reached the database, but this is not mandatory.
      // It is a good idea when triggering a notification just before exiting
      // the application, as in a command line task.

      async trigger(req, message, options) {
        if (typeof req === 'string') {
          // String was passed, assume it is a user _id
          req = { user: { _id: req } };
        }
        if (!req.user) {
          throw self.apos.error('forbidden');
        }
        if (!message) {
          throw self.apos.error('required');
        }
        let strings = [];
        let i = 2;
        let index = 0;
        while (true) {
          index = message.indexOf('%s', index);
          if (index === -1) {
            break;
          }
          // Don't match the same one over and over
          index += 2;
          if (i >= arguments.length || typeof arguments[i] === 'object') {
            throw new Error('Bad notification call: number of %s placeholders does not match number of string arguments after message');
          }
          strings.push(arguments[i++]);
        }
        if (i === arguments.length - 1 && typeof arguments[i] === 'object') {
          options = arguments[i++];
        } else {
          options = {};
        }

        if (i !== arguments.length) {
          throw new Error('Bad notification call: number of %s placeholders does not match number of string arguments after message');
        }

        let notification = {
          _id: self.apos.utils.generateId(),
          createdAt: new Date(),
          userId: req.user._id,
          message: message,
          strings: strings
        };

        if (options.dismiss === true) {
          options.dismiss = 5;
        }

        Object.assign(notification, options);

        return self.db.insertOne(notification);
      },

      // Resolves with an object with `notifications` and `dismissed`
      // properties.
      //
      // If `options.displayingIds` is set, notifications
      // whose `_id` properties appear in it are not returned.

      async find(req, options) {
        try {
          const notifications = await self.db.find({ userId: req.user._id }).sort({ createdAt: 1 }).toArray();
          return {
            notifications: _.filter(notifications, function (notification) {
              if (options.displayingIds && options.displayingIds.length > 0) {
                return _.includes(options.displayingIds || [], notification._id);
              }
              return notification;
            }),
            dismissed: _.difference(options.displayingIds || [], _.map(notifications, '_id'))
          };
        } catch (err) {
          if (self.apos.db.closed) {
            // The database connection was intentionally closed,
            // which often triggers a race condition with
            // long polling requests. Send an empty response
            return {
              notifications: [],
              dismissed: []
            };
          } else {
            throw err;
          }
        }
      },

      async ensureCollection() {
        self.db = self.apos.db.collection('aposNotifications');
        return self.db.createIndex({
          userId: 1,
          createdAt: 1
        });
      }
    };
  },
  middleware(self, options) {
    return {
      // This middleware is essentially a POST route at
      // `/api/v1/@apostrophecms/notifications/poll`. It is implemented
      // as middleware to allow it to run before `req.data.global` is loaded,
      // which can be a very expensive operation on some sites and should
      // thus not be required before a high-frequency polling operation.
      //
      // Poll for active notifications. Responds with:
      //
      // `{ status: 'ok', notifications: [ ... ], dismissed: [ id1... ] }`
      //
      // Each notification has an `html` property containing
      // its rendered, localized markup, as well as `_id`, `createdAt`
      // and `id` (if one was provided when it was triggered).
      //
      // The client must provide `req.body.displayingIds`,
      // an array of notification `_id` properties it is already displaying.
      // Without this, all notifications that have not been dismissed via the
      // dismiss route are sent.
      //
      // If any of the ids in `displayingIds` have been recently dismissed,
      // the response will include them in its `dismissed` property.
      //
      // Waits up to 10 seconds for new notifications (long polling),
      // but then respond with an empty array to avoid proxy server timeouts.
      //
      // As usual POST is used to avoid unwanted caching of the response.
      notifications: {
        before: '@apostrophecms/global',
        middleware: async (req, res, next) => {
          let start;
          let displayingIds;
          try {
            if (req.method.toUpperCase() !== 'GET' || req.url !== self.action) {
              return next();
            }
            if (!(req.user && req.user._id)) {
              throw self.apos.error('invalid');
            }
            start = Date.now();
            displayingIds = self.apos.launder.ids(req.body.displayingIds);
            await attempt();
          } catch (e) {
            return self.apiRouteSendError(res, e);
          }
          async function attempt() {
            if (Date.now() - start >= (self.options.longPollingTimeout || 10000)) {
              return {
                notifications: [],
                dismissed: []
              };
            }
            const result = await self.find(req, { displayingIds: displayingIds });
            const notifications = result.notifications;
            const dismissed = result.dismissed;
            if (!notifications.length && !dismissed.length) {
              await Promise.delay(self.options.queryInterval || 1000);
              return attempt();
            }
            return res.send({
              notifications: notifications,
              dismissed: dismissed
            });
          }
        }
      }
    };
  }
};
<commit_msg>Notifications: remove apiRoutes<commit_after>// This module provides a framework for triggering notifications
// within the Apostrophe admin UI. Notifications may be triggered
// either on the browser or the server side, via `apos.notice`.
//
// ## Options
//
// ### `queryInterval`: interval in milliseconds between MongoDB
// queries while long polling for notifications. Defaults to 1000
// (1 second). Set it longer if you prefer fewer queries, however
// these are indexed queries on a small amount of information and
// should not significantly impact your app.
//
// ### `longPollingTimeout`: maximum lifetime in milliseconds of a long
// polling HTTP request before a response with no notifications is sent.
// Defaults to 10000 (10 seconds) to avoid typical proxy server timeouts.
// Until it times out the request will keep making MongoDB queries to
// see if any new notifications are available (long polling).

const Promise = require('bluebird');
const _ = require('lodash');

module.exports = {
  extend: '@apostrophecms/module',
  async init(self, options) {
    self.apos.notify = self.trigger;
    await self.ensureCollection();
  },
  restApiRoutes: (self, options) => ({
    getOne(req, _id) {
      return self.find(req, { displayingIds: [_id] });
    },
    async post(req) {
      const type = self.apos.launder.select(req.body.type, [
        'error',
        'warn',
        'success',
        'info'
      ], 'info');
      const message = self.apos.launder.string(req.body.message);
      const strings = self.apos.launder.strings(req.body.strings);
      const dismiss = self.apos.launder.integer(req.body.dismiss);
      const pulse = self.apos.launder.boolean(req.body.pulse);
      const id = self.apos.launder.id(req.body.id);
      await self.trigger.apply(self, [
        req,
        message
      ].concat(strings).concat([{
        dismiss,
        type,
        pulse,
        id
      }]));
      return self.trigger(req, req.body.message, req.body.options || {});
    },
    put(req, _id) {
      throw self.apos.error('unimplemented');
    },
    patch(req, _id) {
      throw self.apos.error('unimplemented');
    },
    delete(req, _id) {
      return self.db.deleteMany({ _id });
    }
  }),
  methods(self, options) {
    return {

      // Call with `req`, then a message, followed by any interpolated strings
      // which must correspond to %s placeholders in `message` (variable number
      // of arguments), followed by an `options` object if desired.
      //
      // If you do not have a `req` it is acceptable to pass a user `_id` string
      // in place of `req`. Someone must be the recipient.
      //
      // `options.type` styles the notification and may be set to `error`,
      // `warn` or `success`. If not set, a "plain" default style is used.
      //
      // If `options.dismiss` is set to `true`, the message will auto-dismiss after 5 seconds.
      // If it is set to a number of seconds, it will dismiss after that number of seconds.
      // Otherwise it will not dismiss unless clicked.
      //
      // The message is internationalized, which is why the use of
      // %s placeholders for any inserted titles, etc. is important.
      //
      // Throws an error if there is no `req.user`.
      //
      // This method is aliased as `apos.notify` for convenience.
      //
      // The method is async, and you may `await` to be certain the
      // notification has reached the database, but this is not mandatory.
      // It is a good idea when triggering a notification just before exiting
      // the application, as in a command line task.

      async trigger(req, message, options) {
        if (typeof req === 'string') {
          // String was passed, assume it is a user _id
          req = { user: { _id: req } };
        }
        if (!req.user) {
          throw self.apos.error('forbidden');
        }
        if (!message) {
          throw self.apos.error('required');
        }
        let strings = [];
        let i = 2;
        let index = 0;
        while (true) {
          index = message.indexOf('%s', index);
          if (index === -1) {
            break;
          }
          // Don't match the same one over and over
          index += 2;
          if (i >= arguments.length || typeof arguments[i] === 'object') {
            throw new Error('Bad notification call: number of %s placeholders does not match number of string arguments after message');
          }
          strings.push(arguments[i++]);
        }
        if (i === arguments.length - 1 && typeof arguments[i] === 'object') {
          options = arguments[i++];
        } else {
          options = {};
        }

        if (i !== arguments.length) {
          throw new Error('Bad notification call: number of %s placeholders does not match number of string arguments after message');
        }

        let notification = {
          _id: self.apos.utils.generateId(),
          createdAt: new Date(),
          userId: req.user._id,
          message: message,
          strings: strings
        };

        if (options.dismiss === true) {
          options.dismiss = 5;
        }

        Object.assign(notification, options);

        return self.db.insertOne(notification);
      },

      // Resolves with an object with `notifications` and `dismissed`
      // properties.
      //
      // If `options.displayingIds` is set, notifications
      // whose `_id` properties appear in it are not returned.

      async find(req, options) {
        try {
          const notifications = await self.db.find({ userId: req.user._id }).sort({ createdAt: 1 }).toArray();
          return {
            notifications: _.filter(notifications, function (notification) {
              if (options.displayingIds && options.displayingIds.length > 0) {
                return _.includes(options.displayingIds || [], notification._id);
              }
              return notification;
            }),
            dismissed: _.difference(options.displayingIds || [], _.map(notifications, '_id'))
          };
        } catch (err) {
          if (self.apos.db.closed) {
            // The database connection was intentionally closed,
            // which often triggers a race condition with
            // long polling requests. Send an empty response
            return {
              notifications: [],
              dismissed: []
            };
          } else {
            throw err;
          }
        }
      },

      async ensureCollection() {
        self.db = self.apos.db.collection('aposNotifications');
        return self.db.createIndex({
          userId: 1,
          createdAt: 1
        });
      }
    };
  },
  middleware(self, options) {
    return {
      // This middleware is essentially a POST route at
      // `/api/v1/@apostrophecms/notifications/poll`. It is implemented
      // as middleware to allow it to run before `req.data.global` is loaded,
      // which can be a very expensive operation on some sites and should
      // thus not be required before a high-frequency polling operation.
      //
      // Poll for active notifications. Responds with:
      //
      // `{ status: 'ok', notifications: [ ... ], dismissed: [ id1... ] }`
      //
      // Each notification has an `html` property containing
      // its rendered, localized markup, as well as `_id`, `createdAt`
      // and `id` (if one was provided when it was triggered).
      //
      // The client must provide `req.body.displayingIds`,
      // an array of notification `_id` properties it is already displaying.
      // Without this, all notifications that have not been dismissed via the
      // dismiss route are sent.
      //
      // If any of the ids in `displayingIds` have been recently dismissed,
      // the response will include them in its `dismissed` property.
      //
      // Waits up to 10 seconds for new notifications (long polling),
      // but then respond with an empty array to avoid proxy server timeouts.
      //
      // As usual POST is used to avoid unwanted caching of the response.
      notifications: {
        before: '@apostrophecms/global',
        middleware: async (req, res, next) => {
          let start;
          let displayingIds;
          try {
            if (req.method.toUpperCase() !== 'GET' || req.url !== self.action) {
              return next();
            }
            if (!(req.user && req.user._id)) {
              throw self.apos.error('invalid');
            }
            start = Date.now();
            displayingIds = self.apos.launder.ids(req.body.displayingIds);
            await attempt();
          } catch (e) {
            return self.apiRouteSendError(res, e);
          }
          async function attempt() {
            if (Date.now() - start >= (self.options.longPollingTimeout || 10000)) {
              return {
                notifications: [],
                dismissed: []
              };
            }
            const result = await self.find(req, { displayingIds: displayingIds });
            const notifications = result.notifications;
            const dismissed = result.dismissed;
            if (!notifications.length && !dismissed.length) {
              await Promise.delay(self.options.queryInterval || 1000);
              return attempt();
            }
            return res.send({
              notifications: notifications,
              dismissed: dismissed
            });
          }
        }
      }
    };
  }
};
<|endoftext|>


<commit_before>'use strict';

const fs = require('fs');
const webpack = require('webpack');
const webpackMerge = require('webpack-merge');

const ExtractTextPlugin = require("extract-text-webpack-plugin");
const ContextReplacementPlugin = webpack.ContextReplacementPlugin;
const LoaderOptionsPlugin = webpack.LoaderOptionsPlugin;

const webpackUtils = require('./webpack.utils');

const getCommonConfig = (type) => {
    const tsconfigType = type !== 'dev' ? `.${ type }` : '';

    return {
        module: {
            rules: [
                {
                    exclude: /node_modules/,
                    test: /\.ts$/,
                    use: [
                        'awesome-typescript-loader?configFileName=' + webpackUtils.rootPath(`tsconfig${ tsconfigType }.json`),
                        'angular2-template-loader?keepUrl=true'
                    ]
                },
                { test: /\.html$/, use: 'raw-loader' },
                {
                    use: ['url-loader?limit=10000'],
                    test: /\.(woff2?|ttf|eot|svg|jpg|jpeg|json|gif|png)(\?v=\d+\.\d+\.\d+)?$/
                }
            ]
        },
        performance: { hints: false },
        plugins: [
            new ContextReplacementPlugin(
                /angular(\\|\/)core(\\|\/)@angular/,
                __dirname
            ),
            new LoaderOptionsPlugin({
                debug: true,
                options: {
                    emitErrors: true
                }
            }),
            new ExtractTextPlugin("*.css")
        ],
        resolve: {
            extensions: [ '.js', '.ts' ],
            modules: [ webpackUtils.rootPath('node_modules') ]
        }
    };
};

module.exports = (type, typeConfig) => {
    const configs = [getCommonConfig(type), typeConfig];
    const customConfigPath = webpackUtils.rootPath('configs', `webpack.${ type }.js`);

    if (fs.existsSync(customConfigPath)) {
        let customConfig = require(customConfigPath);

        if (Object.prototype.toString.call(customConfig) === '[object Function]') {
            customConfig = customConfig();
        }

        configs.push(customConfig);
    }

    return webpackMerge.apply(null, configs);
};
<commit_msg>Allow webpack to find esm-directory modules<commit_after>'use strict';

const fs = require('fs');
const webpack = require('webpack');
const webpackMerge = require('webpack-merge');

const ExtractTextPlugin = require("extract-text-webpack-plugin");
const ContextReplacementPlugin = webpack.ContextReplacementPlugin;
const LoaderOptionsPlugin = webpack.LoaderOptionsPlugin;

const webpackUtils = require('./webpack.utils');

const getCommonConfig = (type) => {
    const tsconfigType = type !== 'dev' ? `.${ type }` : '';

    return {
        module: {
            rules: [
                {
                    exclude: /node_modules/,
                    test: /\.ts$/,
                    use: [
                        'awesome-typescript-loader?configFileName=' + webpackUtils.rootPath(`tsconfig${ tsconfigType }.json`),
                        'angular2-template-loader?keepUrl=true'
                    ]
                },
                { test: /\.html$/, use: 'raw-loader' },
                {
                    use: ['url-loader?limit=10000'],
                    test: /\.(woff2?|ttf|eot|svg|jpg|jpeg|json|gif|png)(\?v=\d+\.\d+\.\d+)?$/
                }
            ]
        },
        performance: { hints: false },
        plugins: [
            new ContextReplacementPlugin(
                /angular(\\|\/)core(\\|\/)(@angular|esm5)/,
                __dirname
            ),
            new LoaderOptionsPlugin({
                debug: true,
                options: {
                    emitErrors: true
                }
            }),
            new ExtractTextPlugin("*.css")
        ],
        resolve: {
            extensions: [ '.js', '.ts' ],
            modules: [ webpackUtils.rootPath('node_modules') ]
        }
    };
};

module.exports = (type, typeConfig) => {
    const configs = [getCommonConfig(type), typeConfig];
    const customConfigPath = webpackUtils.rootPath('configs', `webpack.${ type }.js`);

    if (fs.existsSync(customConfigPath)) {
        let customConfig = require(customConfigPath);

        if (Object.prototype.toString.call(customConfig) === '[object Function]') {
            customConfig = customConfig();
        }

        configs.push(customConfig);
    }

    return webpackMerge.apply(null, configs);
};
<|endoftext|>


<commit_before>/*jshint node:true, mocha:true*/
describe('ConstraintResults Router', function() {
    var testFixture = require('../../globals'),
        superagent = testFixture.superagent,
        expect = testFixture.expect,
        gmeConfig = testFixture.getGmeConfig(),
        server = testFixture.WebGME.standaloneServer(gmeConfig),
        mntPt = require('../../../webgme-setup.json').components.routers['ConstraintResults'].mount,
        webHookHandler = require('../../../src/webhooks/ConstraintChecker/ConstraintChecker'),
        gmeAuth,
        urlFor = function(action) {
            return [
                server.getUrl(),
                mntPt,
                action
            ].join('/');
        };

    before(function(done) {
        testFixture.clearDBAndGetGMEAuth(gmeConfig)
            .then(function (gmeAuth_) {
                gmeAuth = gmeAuth_;
                server.start(done);
            })
            .catch(done)
    });

    after(function(done) {
        server.stop(done);
    });

    it.skip('should add hook at creation', function(done) {
        superagent.put(server.getUrl(), '/api/projects/guest/ShouldHaveHook')
            .send({
                type: 'file',
                seedName: 'EmptyProject'
            })
            .end(function(err, res) {
                expect(res.statusCode).to.equal(204);
                done();
            });
    });

    it('should return 403 if no project access', function(done) {
        superagent.get(urlFor('guest/doesNotExist/status/1a040796c8ce0a957ba152d1f94d9ec453667acf'))
            .end(function(err, res) {
                expect(res.statusCode).to.equal(403);
                done();
            });
    });

    it.skip('should return 200 for webhookStatus', function(done) {
        superagent.get(urlFor('webhookStatus'))
            .end(function(err, res) {
                expect(res.statusCode).to.equal(403);
                done();
            });
    });
});
<commit_msg>Fix failing test.<commit_after>/*jshint node:true, mocha:true*/
describe('ConstraintResults Router', function() {
    var testFixture = require('../../globals'),
        superagent = testFixture.superagent,
        expect = testFixture.expect,
        gmeConfig = testFixture.getGmeConfig(),
        server = testFixture.WebGME.standaloneServer(gmeConfig),
        mntPt = require('../../../webgme-setup.json').components.routers['ConstraintResults'].mount,
        gmeAuth,
        urlFor = function(action) {
            return [
                server.getUrl(),
                mntPt,
                action
            ].join('/');
        };

    before(function(done) {
        testFixture.clearDBAndGetGMEAuth(gmeConfig)
            .then(function (gmeAuth_) {
                gmeAuth = gmeAuth_;
                server.start(done);
            })
            .catch(done)
    });

    after(function(done) {
        server.stop(done);
    });

    it.skip('should add hook at creation', function(done) {
        superagent.put(server.getUrl(), '/api/projects/guest/ShouldHaveHook')
            .send({
                type: 'file',
                seedName: 'EmptyProject'
            })
            .end(function(err, res) {
                expect(res.statusCode).to.equal(204);
                done();
            });
    });

    it('should return 403 if no project access', function(done) {
        superagent.get(urlFor('guest/doesNotExist/status/1a040796c8ce0a957ba152d1f94d9ec453667acf'))
            .end(function(err, res) {
                expect(res.statusCode).to.equal(403);
                done();
            });
    });

    it.skip('should return 200 for webhookStatus', function(done) {
        superagent.get(urlFor('webhookStatus'))
            .end(function(err, res) {
                expect(res.statusCode).to.equal(403);
                done();
            });
    });
});
<|endoftext|>


<commit_before>/**
 * @class UTIL
 * A utility class.
 * @private
 * @experimental
 * @singleton
 */
var obj = {};

// Utilities
Object.defineProperties(obj,{

  // STATICS
  testing: {
    enumerable: false,
    writable: true,
    configurable: false,
    value: false
  },

  /**
   * @property {Boolean} PROXY_SUPPORT
   * Indicates the environment has ES6 Direct Proxy Support
   * @readonly
   * @private
   */
  PROXY_SUPPORT: {
    enumerable: false,
    get: function(){
      return process.execArgv.indexOf('--harmony') > -1;
    }
  },

  _cfg:{
    enumerable: false,
    writable: true,
    value: null
  },

  // METHODS
  /**
   * @method bufferjoiner
   * A custom buffer joiner.
   */
  bufferjoiner: {
    enumerable: true,
    get: function(){return require('./bufferjoiner');}
  },

  /**
   * @method watch
   * The watch module.
   * @return {Object}
   */
  watch: {
    enumerable: false,
    get: function(){
      return require('watch');
    }
  },

  /**
   * @method wrench
   * The wrench utility library.
   * @return {Object}
   */
  wrench: {
    enumerable: false,
    get: function(){
      return require('wrench');
    }
  },

  /**
   * @method writeableDir
   * Determines whether the directory is writeable or not.
   * @param {String} dir
   * The directory in question.
   * @returns {Boolean}
   */
  writeableDir: {
    enumerable: false,
    writable: true,
    value: function(dir){
      var fs = require('fs');
      if (!dir || !fs.existsSync(dir))
        return undefined;

      if (!fs.statSync(dir).isDirectory())
        return undefined;

      /*var testFile = dir+'/'+;
      try {
        fs.writeFileSync(testFile, ' ');
        fs.unlinkSync(testFile);
        return dir;
      } catch (e) {
        return undefined;
      }*/
     return dir;
    }
  },

  tempDir: {
    enumerable: true,
    writable: false,
    value: require('os').tmpDir()
  },

  /**
   * @method notImplemented
   * Log a `NOT IMPLEMENTED` message to the console, indicating what method is not yet implemented in the API.
   * @param {String} filename
   * The absolute path of the file that contains the non-implemented function.
   * @param {String} msg
   * The message to display (such as method name and/or line number).
   */
  notImplemented: {
    enumerable: true,
    writable: false,
    configurable: false,
    value: function(filename,msg){
      if (!this.testing){
        console.log('NOT IMPLEMENTED:'.bold.cyan);
        console.log((filename+':').cyan,msg.yellow,'\n');
      }
    }
  },

  /**
   * @method sleep
   * A generic method to sleep for a specific amount of time.
   */
  sleep: {
    enumerable: false,
    writable: false,
    configurable: false,
    value: function(period){
      var st = new Date().getTime();
      while(new Date().getTime() <= st+(period*1000)){}
      return;
    }
  },

  /**
   * @method unrequire
   * Reverts `require('some_module')`. Requires the full path of the module in order to work.
   * @param file (required)
   * The absolute path of the file that should be *un*required.
   * @private
   */
  unrequire: {
    enumerable: true,
    writable: false,
    configurable: false,
    value: function(file){
      delete require.cache[file];
    }
  },

  /**
   * @method uuid
   * Generate a UUID.
   *
   * **Simple Example**
   *
   *     console.log(UTIL.uuid()); // --> Outputs a time-based UUID.
   *     console.log(UTIL.uuid(true)); // --> Outputs a random UUID.
   *
   * @param {Boolean} [random=false]
   * Setting this to `true` generates a random UUID. Otherwise, a time-based UUID is created.
   * @param {Object} [options]
   * Properties may include:
   *
   * * `random` - {@link Number}[16] Array of 16 numbers (0-255) to use in place of randomly generated values
   * * `rng` - {@link Function} Random # generator to use.  Set to one of the built-in generators - `uuid.mathRNG` (all platforms), `uuid.nodeRNG` (node.js only), `uuid.whatwgRNG` (WebKit only) - or a custom function that returns an array[16] of byte values.
   * * `buffer` - {@link Array}/{@link Buffer}) Array or buffer where UUID bytes are to be written.
   * * `offset` - {@link Number} Starting index in `buffer` at which to begin writing.
   * @param {Array/Buffer} [buffer]
   * Array or buffer where UUID bytes are to be written.
   * @param {Number} [offset]
   * Starting index in `buffer` at which to begin writing.
   * @returns {String}
   */
  uuid: {
    enumerable: true,
    writable: false,
    configurable: false,
    value: function(random, options, buffer, offset){
      random = typeof random == 'boolean' ? random : false;
      return random == true ? require('node-uuid').v4(options||null,buffer||null,offset||null) : require('node-uuid').v1(options||null,buffer||null,offset||null);
    }
  }
});

module.exports = obj;<commit_msg>Removed WAMP<commit_after>/**
 * @class UTIL
 * A utility class.
 * @private
 * @experimental
 * @singleton
 */
var obj = {};

// Utilities
Object.defineProperties(obj,{

  // STATICS
  testing: {
    enumerable: false,
    writable: true,
    configurable: false,
    value: false
  },

  /**
   * @property {Boolean} PROXY_SUPPORT
   * Indicates the environment has ES6 Direct Proxy Support
   * @readonly
   * @private
   */
  PROXY_SUPPORT: {
    enumerable: false,
    get: function(){
      return process.execArgv.indexOf('--harmony') > -1;
    }
  },

  _cfg:{
    enumerable: false,
    writable: true,
    value: null
  },

  // METHODS
  /**
   * @property {Object} bufferjoiner
   * A custom buffer joiner.
   */
  bufferjoiner: {
    enumerable: true,
    get: function(){
			return require('./bufferjoiner');
		}
  },

  /**
   * @property {Object" watch
   * The watch module.
   * @return {Object}
   */
  watch: {
    enumerable: false,
    get: function(){
      return require('watch');
    }
  },

  /**
   * @method {Object} wrench
   * The wrench utility library.
   * @return {Object}
   */
  wrench: {
    enumerable: false,
    get: function(){
      return require('wrench');
    }
  },

  /**
   * @method writeableDir
   * Determines whether the directory is writeable or not.
   * @param {String} dir
   * The directory in question.
   * @returns {Boolean}
   */
  writeableDir: {
    enumerable: false,
    writable: true,
    value: function(dir){
      var fs = require('fs');
      if (!dir || !fs.existsSync(dir))
        return undefined;

      if (!fs.statSync(dir).isDirectory())
        return undefined;

      /*var testFile = dir+'/'+;
      try {
        fs.writeFileSync(testFile, ' ');
        fs.unlinkSync(testFile);
        return dir;
      } catch (e) {
        return undefined;
      }*/
     return dir;
    }
  },

  tempDir: {
    enumerable: true,
    writable: false,
    value: require('os').tmpDir()
  },

  /**
   * @method notImplemented
   * Log a `NOT IMPLEMENTED` message to the console, indicating what method is not yet implemented in the API.
   * @param {String} filename
   * The absolute path of the file that contains the non-implemented function.
   * @param {String} msg
   * The message to display (such as method name and/or line number).
   */
  notImplemented: {
    enumerable: true,
    writable: false,
    configurable: false,
    value: function(filename,msg){
      if (!this.testing){
        console.log('NOT IMPLEMENTED:'.bold.cyan);
        console.log((filename+':').cyan,msg.yellow,'\n');
      }
    }
  },

  /**
   * @method sleep
   * A generic method to sleep for a specific amount of time.
   * @param {Number} period
   * The number of seconds to sleep.
   */
  sleep: {
    enumerable: false,
    writable: false,
    configurable: false,
    value: function(period){
      var st = new Date().getTime();
      while(new Date().getTime() <= st+(period*1000)){}
      return;
    }
  },

  /**
   * @method unrequire
   * Reverts `require('some_module')`. Requires the full path of the module in order to work.
   * @param {String} file (required)
   * The absolute path of the file that should be *un*required.
   * @private
   */
  unrequire: {
    enumerable: true,
    writable: false,
    configurable: false,
    value: function(file){
      delete require.cache[file];
    }
  },

  /**
   * @method uuid
   * Generate a UUID.
   *
   * **Simple Example**
   *
   *     console.log(UTIL.uuid()); // --> Outputs a time-based UUID.
   *     console.log(UTIL.uuid(true)); // --> Outputs a random UUID.
   *
   * @param {Boolean} [random=false]
   * Setting this to `true` generates a random UUID. Otherwise, a time-based UUID is created.
   * @param {Object} [options]
   * Properties may include:
   *
   * * `random` - {@link Number}[16] Array of 16 numbers (0-255) to use in place of randomly generated values
   * * `rng` - {@link Function} Random # generator to use.  Set to one of the built-in generators - `uuid.mathRNG` (all platforms), `uuid.nodeRNG` (node.js only), `uuid.whatwgRNG` (WebKit only) - or a custom function that returns an array[16] of byte values.
   * * `buffer` - {@link Array}/{@link Buffer}) Array or buffer where UUID bytes are to be written.
   * * `offset` - {@link Number} Starting index in `buffer` at which to begin writing.
   * @param {Array/Buffer} [buffer]
   * Array or buffer where UUID bytes are to be written.
   * @param {Number} [offset]
   * Starting index in `buffer` at which to begin writing.
   * @returns {String}
   */
  uuid: {
    enumerable: true,
    writable: false,
    configurable: false,
    value: function(random, options, buffer, offset){
      random = typeof random == 'boolean' ? random : false;
      return random == true ? require('node-uuid').v4(options||null,buffer||null,offset||null) : require('node-uuid').v1(options||null,buffer||null,offset||null);
    }
  }
});

module.exports = obj;<|endoftext|>