<commit_before>if(!Array.indexOf) {
    Array.prototype.indexOf = function(obj) {
        for(var i=0; i<this.length; i++) {
            if(this[i]==obj) {
                return i;
            }
        }
        return -1;
    }
}

function region_append(region, obj, modname) {
    var wrp = [];
    wrp.push('<fieldset class="module aligned order-item">');
    wrp.push('
 '+modname+'  ('+gettext('Hide')+')
');
    wrp.push('

');
    wrp.push('</fieldset>');

    $("#"+REGION_MAP[region]+"_body").children("div.order-machine").append(wrp.join(""))
        .children("fieldset.order-item:last").children(".item-content").append(obj);
}

function create_new_spare_form(form, modvar, last_id) {
    // create new spare form
    var new_form = form.html().replace(
        new RegExp(modvar+'-'+last_id, 'g'),
        modvar+'-'+(last_id+1));
    new_form = '
'+new_form+'
';
    $("#"+modvar+"_set").append(new_form);
}

function set_item_field_value(item, field, value) {
    // item: DOM object created by 'region_append' function
    // field: "order-field" | "delete-field" | "region-choice-field"
    if (field=="delete-field")
        item.find("."+field).attr("checked",value);
    else if (field=="region-choice-field") {
        var old_region_id = REGION_MAP.indexOf(item.find("."+field).val());
        item.find("."+field).val(REGION_MAP[value]);

        old_region_item = $("#"+REGION_MAP[old_region_id]+"_body");
        if (old_region_item.children("div.order-machine").children().length == 0)
            old_region_item.children("div.empty-machine-msg").show();
        else
            old_region_item.children("div.empty-machine-msg").hide();

        new_region_item = $("#"+REGION_MAP[value]+"_body");
        new_region_item.children("div.empty-machine-msg").hide();
    }
    else
        item.find("."+field).val(value);
}

function move_item (region_id, item) {
    poorify_rich(item);
    $("#"+REGION_MAP[region_id]+"_body").children("div.order-machine").append(item);
    set_item_field_value(item, "region-choice-field", region_id);
    richify_poor(item);
}

function poorify_rich(item){
    item.children(".item-content").hide();
    // TODO: Change this to allow other editors:
    if (item.find("div[id^=richtext]").length > 0) {
        var editor_id = item.find(".mceEditor").prev().attr("id");
        tinyMCE.execCommand('mceRemoveControl', false, editor_id);
    }
}
function richify_poor(item){
    item.children(".item-content").show();
    // TODO: Change this to allow other editors:
    if (item.find("div[id^=richtext]").length > 0) {
        var editor_id = item.find('textarea[name*=richtext]').attr("id");
        tinyMCE.execCommand('mceAddControl', false, editor_id);
    }
}

function sort_by_ordering(e1, e2) {
  var v1 = parseInt($('.order-field', e1).val()) || 0;
  var v2 = parseInt($('.order-field', e2).val()) || 0;
  return  v1 > v2 ? 1 : -1;
};

function give_ordering_to_content_types() {
  for (var i=0; i<REGION_MAP.length;i++) {
    var container = $("#"+REGION_MAP[i]+"_body div.order-machine");
    for (var j=0; j<container.children().length; j++) {
      set_item_field_value(container.find("fieldset.order-item:eq("+j+")"), "order-field", j);
    }
  }
}

function order_content_types_in_regions() {
  for (var i=0; i<REGION_MAP.length;i++) {
    var container = $("#"+REGION_MAP[i]+"_body div.order-machine");
    container.children().sort(sort_by_ordering).each(function() {
      container.append(this);
    });
  }
}

function attach_dragdrop_handlers() {
    // hide content on drag n drop
    $("#main h2 span.handle").mousedown(function(){
        poorify_rich($(this).parents("fieldset.order-item"));
    });
    $("#main h2 span.handle").mouseup(function(){
        richify_poor($(this).parents("fieldset.order-item"));
    });
}

function init_contentblocks() {
    for(var i=0; i<contentblock_init_handlers.length; i++)
        contentblock_init_handlers[i]();
}

// global variable holding the current template key
var current_template;

$(document).ready(function(){
    $("#main_wrapper > .navi_tab").click(function(){
        var elem = $(this);
        $("#main_wrapper > .navi_tab").removeClass("tab_active");
        elem.addClass("tab_active");
        $("#main > div:visible, #main > fieldset:visible").hide();

        var tab_str = elem.attr("id").substr(0, elem.attr("id").length-4);
        $('#'+tab_str+'_body').show();
        ACTIVE_REGION = REGION_MAP.indexOf(tab_str);

        if (tab_str == "settings")
            $(".machine-control").hide();
        else
            $(".machine-control").show();

        // make it possible to open current tab on page reload
        window.location.hash = '#tab_'+tab_str;
    });

    $("input.order-machine-add-button").click(function(){
        var select = $(this).prev();
        var modvar = select.val();
        var modname = select.children("option:selected").html();
        var total_forms = $('#id_'+modvar+'-TOTAL_FORMS');
        var last_id = parseInt(total_forms.val()) - 1;
        var form = $("#"+modvar+"_set_item_"+last_id);

        // update formset bookkeeping value
        total_forms.val(last_id+2);
        create_new_spare_form(form, modvar, last_id);
        region_append(ACTIVE_REGION, form, modname, modvar);
        set_item_field_value(form, "region-choice-field", ACTIVE_REGION);

        attach_dragdrop_handlers();
        init_contentblocks();
    });

    $("input.order-machine-move-button").click(function(){
        var moveTo = $(this).prev().val();
        var active_item = $("#main div.order-machine fieldset.active-item");

        if (!active_item.length) {
            jAlert(NO_ITEM_SELECTED_MESSAGE);
            return false;
        }

        move_item(REGION_MAP.indexOf(moveTo), active_item);
    });

    $("h2 img.item-delete").live('click', function(){
        popup_bg = '

';
        $("body").append(popup_bg);
        var item = $(this).parents(".order-item");
        jConfirm(DELETE_MESSAGES[0], DELETE_MESSAGES[1], function(r) {
            if (r==true) {
                set_item_field_value(item,"delete-field","checked");
                item.fadeOut(200);
            }
            $(".popup_bg").remove();
        });
    });

    $('h2 span.collapse').live('click', function(){
        var node = this;
        $(this.parentNode.parentNode).children('.item-content').slideToggle(function(){
            $(node).text(gettext($(this).is(':visible') ? 'Hide' : 'Show'));
        });
        return false;
    });

    current_template = $('input[name=template_key][checked]').val();

    $('input[name=template_key]').click(function(){
        var input_element = this;
        var new_template = this.value;

        if(current_template==new_template)
            // Selected template did not change
            return false;

        current_regions = template_regions[current_template];
        new_regions = template_regions[new_template];

        not_in_new = [];
        for(var i=0; i<current_regions.length; i++)
            if(new_regions.indexOf(current_regions[i])==-1)
                not_in_new.push(current_regions[i]);

        popup_bg = '

';
        $("body").append(popup_bg);

        var msg = CHANGE_TEMPLATE_MESSAGES[1];

        if(not_in_new.length) {
            msg = interpolate(CHANGE_TEMPLATE_MESSAGES[2], {
                'source_regions': not_in_new,
                'target_region': new_regions[0]
            }, true);
        }

        jConfirm(msg, CHANGE_TEMPLATE_MESSAGES[0], function(ret) {
            if(ret) {
                for(var i=0; i<not_in_new.length; i++) {
                    var items = $('#'+not_in_new[i]+'_body div.order-machine').children();
                    move_item(0, items);
                }

                input_element.checked = true;

                $('form').append('<input type="hidden" name="_continue" value="1" />').submit();
            } else {
                $("div#popup_bg").remove();
            }
        });

        return false;
    });

    $("fieldset.order-item").live('click', function(){
        if(!$(this).hasClass('active-item')) {
            $("fieldset.active-item").removeClass("active-item");
            $(this).addClass("active-item");
        }
    });

    $('form').submit(function(){
        give_ordering_to_content_types();
        var form = $(this);
        form.attr('action', form.attr('action')+window.location.hash);
        return true;
    });

    // move contents into their corresponding regions and do some simple formatting
    $("div[id$=_set]").children().each(function(){
        var elem = $(this);

        if (!(elem.hasClass("header"))) {
            elem.find("input[name$=-region]").addClass("region-choice-field");
            elem.find("input[name$=-DELETE]").addClass("delete-field").parents("div.form-row").hide();
            elem.find("input[name$=-ordering]").addClass("order-field");

            var region_id = elem.find(".region-choice-field").val();
            region_id = REGION_MAP.indexOf(region_id);
            var content_type = elem.attr("id").substr(0, elem.attr("id").indexOf("_"));
            region_append(region_id,elem, CONTENT_NAMES[content_type]);
            set_item_field_value(elem,"region-choice-field",region_id)
        }
    });
    // register regions as sortable for drag N drop
    $(".order-machine").sortable({
        handle: '.handle',
        helper: 'clone',
        placeholder: 'highlight',
        stop: function(event, ui) {
            richify_poor($(ui.item));
        }
    });

    attach_dragdrop_handlers();

    order_content_types_in_regions();

    $('#inlines').hide();

    var errors = $('#main div.errors');

    if(errors.length) {
        var id = errors.parents('fieldset[id$=_body], div[id$=_body]').attr('id');
        $('#'+id.replace('_body', '_tab')).trigger('click');
    } else {
        if(window.location.hash) {
            var tab = $('#'+window.location.hash.substr(5)+'_tab');

            if(tab.length) {
                tab.trigger('click');
                return;
            }
        }

        $('#main_wrapper>div.navi_tab:first-child').trigger('click');
    }
});

$(window).load(function(){init_contentblocks()});
<commit_msg>Fixed broken tinyMCE in RichTextContent.<commit_after>if(!Array.indexOf) {
    Array.prototype.indexOf = function(obj) {
        for(var i=0; i<this.length; i++) {
            if(this[i]==obj) {
                return i;
            }
        }
        return -1;
    }
}

function region_append(region, obj, modname) {
    var wrp = [];
    wrp.push('<fieldset class="module aligned order-item">');
    wrp.push('
 '+modname+'  ('+gettext('Hide')+')
');
    wrp.push('

');
    wrp.push('</fieldset>');

    $("#"+REGION_MAP[region]+"_body").children("div.order-machine").append(wrp.join(""))
        .children("fieldset.order-item:last").children(".item-content").append(obj);
}

function create_new_spare_form(form, modvar, last_id) {
    // create new spare form
    var new_form = form.html().replace(
        new RegExp(modvar+'-'+last_id, 'g'),
        modvar+'-'+(last_id+1));
    new_form = '
'+new_form+'
';
    $("#"+modvar+"_set").append(new_form);
}

function set_item_field_value(item, field, value) {
    // item: DOM object created by 'region_append' function
    // field: "order-field" | "delete-field" | "region-choice-field"
    if (field=="delete-field")
        item.find("."+field).attr("checked",value);
    else if (field=="region-choice-field") {
        var old_region_id = REGION_MAP.indexOf(item.find("."+field).val());
        item.find("."+field).val(REGION_MAP[value]);

        old_region_item = $("#"+REGION_MAP[old_region_id]+"_body");
        if (old_region_item.children("div.order-machine").children().length == 0)
            old_region_item.children("div.empty-machine-msg").show();
        else
            old_region_item.children("div.empty-machine-msg").hide();

        new_region_item = $("#"+REGION_MAP[value]+"_body");
        new_region_item.children("div.empty-machine-msg").hide();
    }
    else
        item.find("."+field).val(value);
}

function move_item (region_id, item) {
    poorify_rich(item);
    $("#"+REGION_MAP[region_id]+"_body").children("div.order-machine").append(item);
    set_item_field_value(item, "region-choice-field", region_id);
    richify_poor(item);
}

function poorify_rich(item){
    item.children(".item-content").hide();

    // TODO: Find of way of telling feincms that a plugin uses richtext
    // and replace div.item-content by div.feincms-richtext (for example)
    var richtext_items = item.find("div.item-content").find('textarea:not([id*=rawcontent])');
    $.each(richtext_items, function(index, value) {
        tinyMCE.execCommand('mceRemoveControl', false, $(value).attr("id"));
    });

    // default feincms richtext
    if (item.find("div[id^=richtext]").length > 0) {
        var editor_id = item.find(".mceEditor").prev().attr("id");
        tinyMCE.execCommand('mceRemoveControl', false, editor_id);
    }
}
function richify_poor(item){
    item.children(".item-content").show();

    // TODO: Find of way of telling feincms that a plugin uses richtext
    // and replace div.item-content by div.feincms-richtext (for example)
    var richtext_items = item.find("div.item-content").find('textarea:not([id*=rawcontent])');
    $.each(richtext_items, function(index, value) {
        tinyMCE.execCommand('mceAddControl', false, $(value).attr("id"));
    });

    // default feincms richtext
    if (item.find("div[id^=richtext]").length > 0) {
        var editor_id = item.find('textarea[name*=richtext]').attr("id");
        tinyMCE.execCommand('mceAddControl', false, editor_id);
    }
}

function sort_by_ordering(e1, e2) {
  var v1 = parseInt($('.order-field', e1).val()) || 0;
  var v2 = parseInt($('.order-field', e2).val()) || 0;
  return  v1 > v2 ? 1 : -1;
};

function give_ordering_to_content_types() {
  for (var i=0; i<REGION_MAP.length;i++) {
    var container = $("#"+REGION_MAP[i]+"_body div.order-machine");
    for (var j=0; j<container.children().length; j++) {
      set_item_field_value(container.find("fieldset.order-item:eq("+j+")"), "order-field", j);
    }
  }
}

function order_content_types_in_regions() {
  for (var i=0; i<REGION_MAP.length;i++) {
    var container = $("#"+REGION_MAP[i]+"_body div.order-machine");
    container.children().sort(sort_by_ordering).each(function() {
      container.append(this);
    });
  }
}

function attach_dragdrop_handlers() {
    // hide content on drag n drop
    $("#main h2 span.handle").mousedown(function(){
        poorify_rich($(this).parents("fieldset.order-item"));
    });
    $("#main h2 span.handle").mouseup(function(){
        richify_poor($(this).parents("fieldset.order-item"));
    });
}

function init_contentblocks() {
    for(var i=0; i<contentblock_init_handlers.length; i++)
        contentblock_init_handlers[i]();
}

// global variable holding the current template key
var current_template;

$(document).ready(function(){
    $("#main_wrapper > .navi_tab").click(function(){
        var elem = $(this);
        $("#main_wrapper > .navi_tab").removeClass("tab_active");
        elem.addClass("tab_active");
        $("#main > div:visible, #main > fieldset:visible").hide();

        var tab_str = elem.attr("id").substr(0, elem.attr("id").length-4);
        $('#'+tab_str+'_body').show();
        ACTIVE_REGION = REGION_MAP.indexOf(tab_str);

        if (tab_str == "settings")
            $(".machine-control").hide();
        else
            $(".machine-control").show();

        // make it possible to open current tab on page reload
        window.location.hash = '#tab_'+tab_str;
    });

    $("input.order-machine-add-button").click(function(){
        var select = $(this).prev();
        var modvar = select.val();
        var modname = select.children("option:selected").html();
        var total_forms = $('#id_'+modvar+'-TOTAL_FORMS');
        var last_id = parseInt(total_forms.val()) - 1;
        var form = $("#"+modvar+"_set_item_"+last_id);

        // update formset bookkeeping value
        total_forms.val(last_id+2);
        create_new_spare_form(form, modvar, last_id);
        region_append(ACTIVE_REGION, form, modname, modvar);
        set_item_field_value(form, "region-choice-field", ACTIVE_REGION);

        attach_dragdrop_handlers();
        init_contentblocks();
    });

    $("input.order-machine-move-button").click(function(){
        var moveTo = $(this).prev().val();
        var active_item = $("#main div.order-machine fieldset.active-item");

        if (!active_item.length) {
            jAlert(NO_ITEM_SELECTED_MESSAGE);
            return false;
        }

        move_item(REGION_MAP.indexOf(moveTo), active_item);
    });

    $("h2 img.item-delete").live('click', function(){
        popup_bg = '

';
        $("body").append(popup_bg);
        var item = $(this).parents(".order-item");
        jConfirm(DELETE_MESSAGES[0], DELETE_MESSAGES[1], function(r) {
            if (r==true) {
                set_item_field_value(item,"delete-field","checked");
                item.fadeOut(200);
            }
            $(".popup_bg").remove();
        });
    });

    $('h2 span.collapse').live('click', function(){
        var node = this;
        $(this.parentNode.parentNode).children('.item-content').slideToggle(function(){
            $(node).text(gettext($(this).is(':visible') ? 'Hide' : 'Show'));
        });
        return false;
    });

    current_template = $('input[name=template_key][checked]').val();

    $('input[name=template_key]').click(function(){
        var input_element = this;
        var new_template = this.value;

        if(current_template==new_template)
            // Selected template did not change
            return false;

        current_regions = template_regions[current_template];
        new_regions = template_regions[new_template];

        not_in_new = [];
        for(var i=0; i<current_regions.length; i++)
            if(new_regions.indexOf(current_regions[i])==-1)
                not_in_new.push(current_regions[i]);

        popup_bg = '

';
        $("body").append(popup_bg);

        var msg = CHANGE_TEMPLATE_MESSAGES[1];

        if(not_in_new.length) {
            msg = interpolate(CHANGE_TEMPLATE_MESSAGES[2], {
                'source_regions': not_in_new,
                'target_region': new_regions[0]
            }, true);
        }

        jConfirm(msg, CHANGE_TEMPLATE_MESSAGES[0], function(ret) {
            if(ret) {
                for(var i=0; i<not_in_new.length; i++) {
                    var items = $('#'+not_in_new[i]+'_body div.order-machine').children();
                    move_item(0, items);
                }

                input_element.checked = true;

                $('form').append('<input type="hidden" name="_continue" value="1" />').submit();
            } else {
                $("div#popup_bg").remove();
            }
        });

        return false;
    });

    $("fieldset.order-item").live('click', function(){
        if(!$(this).hasClass('active-item')) {
            $("fieldset.active-item").removeClass("active-item");
            $(this).addClass("active-item");
        }
    });

    $('form').submit(function(){
        give_ordering_to_content_types();
        var form = $(this);
        form.attr('action', form.attr('action')+window.location.hash);
        return true;
    });

    // move contents into their corresponding regions and do some simple formatting
    $("div[id$=_set]").children().each(function(){
        var elem = $(this);

        if (!(elem.hasClass("header"))) {
            elem.find("input[name$=-region]").addClass("region-choice-field");
            elem.find("input[name$=-DELETE]").addClass("delete-field").parents("div.form-row").hide();
            elem.find("input[name$=-ordering]").addClass("order-field");

            var region_id = elem.find(".region-choice-field").val();
            region_id = REGION_MAP.indexOf(region_id);
            var content_type = elem.attr("id").substr(0, elem.attr("id").indexOf("_"));
            region_append(region_id,elem, CONTENT_NAMES[content_type]);
            set_item_field_value(elem,"region-choice-field",region_id)
        }
    });
    // register regions as sortable for drag N drop
    $(".order-machine").sortable({
        handle: '.handle',
        helper: 'clone',
        placeholder: 'highlight',
        stop: function(event, ui) {
            richify_poor($(ui.item));
        }
    });

    attach_dragdrop_handlers();

    order_content_types_in_regions();

    $('#inlines').hide();

    var errors = $('#main div.errors');

    if(errors.length) {
        var id = errors.parents('fieldset[id$=_body], div[id$=_body]').attr('id');
        $('#'+id.replace('_body', '_tab')).trigger('click');
    } else {
        if(window.location.hash) {
            var tab = $('#'+window.location.hash.substr(5)+'_tab');

            if(tab.length) {
                tab.trigger('click');
                return;
            }
        }

        $('#main_wrapper>div.navi_tab:first-child').trigger('click');
    }
});

$(window).load(function(){init_contentblocks()});
<|endoftext|>


<commit_before>"use strict"; // run code in ES5 strict mode

var pages = {};

/**
 * Registers a pageBundle and pageDataLoader to the given pageUrl. This method
 * wraps the pageBundle to be informed when the bundle is executed. Thus calling
 * pageRegistry.getPageBundle() won't return the original function.
 *
 * @param {!String} pageUrl
 * @param {!Function} pageBundle
 */
function setPage(pageUrl, pageBundle) {
    function wrappedBundle(callback) {
        pageBundle(function onBundleLoaded(module) {
            var entry = pages[pageUrl];

            entry.module = module;
            if (callback) {
                callback(entry.module);
            }
        });
    }

    pages[pageUrl] = {
        bundle: wrappedBundle,
        module: null
    };

}

/**
 * Returns the page bundle wrapped in another function. The returned function acts exactly
 * like the page bundle.
 *
 * Returns undefined when the pageUrl is unknown.
 *
 * @param {!String} pageUrl
 * @return {Function}
 */
function getPageBundle(pageUrl) {
    var entry = pages[pageUrl];

    if (entry) {
        return entry.bundle;
    } else {
        return undefined;
    }
}

/**
 * Returns the PageClass. This is a synchronous shortcut to retrieve the
 * PageClass if the bundle has been executed before.
 *
 * Returns null if the bundle has not been executed before.
 *
 * Returns undefined if the pageUrl is unknown.
 *
 * You can use this method to determine whether a bundle has been loaded or not.
 *
 * @param {!String} pageUrl
 * @return {Function}
 */
function getPageClass(pageUrl) {
    var entry = pages[pageUrl];

    if (entry) {
        return entry.module;
    } else {
        return undefined;
    }
}

exports.setPage = setPage;
exports.getPageBundle = getPageBundle;
exports.getPageClass = getPageClass;<commit_msg>- removed page registry (it's now just a simple object at PageLoader.bundles)<commit_after><|endoftext|>


<commit_before>function renderStatus(text){
    document.getElementById('status').textContent = text;
}

function updateStatus(title, url) {
    var listItem = document.createElement("p");
    var titleItem = document.createElement("span")
    titleItem.className = "tab-title";
    titleItem.textContent = title + " - ";
    listItem.appendChild(titleItem);
    listItem.innerHTML +=  url;
    document.getElementById('status').appendChild(listItem);
}

function findAuthor(url) {
	var author;
	var encodedUrl = encodeURI(url);
	console.log(encodedUrl);
	var HTTPrequest = "http://access.alchemyapi.com/calls/url/URLGetAuthor?"
	+"apikey="+ keys.alchemy +"&url=" + encodedUrl + "&outputMode=json";
	console.log(HTTPrequest);
	var xhr = new XMLHttpRequest();
	xhr.open("GET", HTTPrequest, true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            author = JSON.parse(xhr.responseText);
            console.log(author);
        }
    }
    xhr.send();

}

function createRequest(url) {

    return {
        "key": keys.easybib,
        "source": "website",
        "website": {
            "title": ""
        },
        "pubonline": {
            "title": "",
            "day": 1,
            "month": 1,
            "year": 1969,
            "url": "",
            "dayaccessed": Date.getDay(),
            "monthaccessed": Date.getMonth(),
            "yearaccessed": Date.getFullYear()
        }
    }
}
function cite(urlArray) {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "http://www.easybib.com/cite/bulk", true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            var res = JSON.parse(xhr.responseText);
            console.log(res);
        }
    }
    var request = [];
    for (var i = 0; i < urlArray.length; i++) {
        request.push(createRequest(urlArray[i]));
    }
    xhr.send(request);
}

document.addEventListener('DOMContentLoaded', function() {
    chrome.tabs.query({}, function (tabs) {
        for(var i = 0; i < tabs.length; i++) {
            var url = "";
            if(tabs[i].url.length > 36) {
                url = tabs[i].url.substring(0, 36) + "...";
            } else {
                url = tabs[i].url;
            }
            updateStatus(tabs[i].title, url);
            //findAuthor(url);
        }
    });
});<commit_msg>trying to figure out how encodeURIComponent works (will delete later)<commit_after>function renderStatus(text){
    document.getElementById('status').textContent = text;
}

function updateStatus(title, url) {
    var listItem = document.createElement("p");
    var titleItem = document.createElement("span")
    titleItem.className = "tab-title";
    titleItem.textContent = title + " - ";
    listItem.appendChild(titleItem);
    listItem.innerHTML +=  url;
    document.getElementById('status').appendChild(listItem);
}

function findAuthor(url) {
	var author;
	var encodedUrl = encodeURI(url);
	console.log(encodedUrl);
	var HTTPrequest = "http://access.alchemyapi.com/calls/url/URLGetAuthor?"
	+"apikey="+ keys.alchemy +"&url=" + encodedUrl + "&outputMode=json";
	console.log(HTTPrequest);
	var xhr = new XMLHttpRequest();
	xhr.open("GET", HTTPrequest, true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            author = JSON.parse(xhr.responseText);
            console.log(author);
        }
    }
    xhr.send();

//trying to understand how encodeURIComponent works (ignore, its just for kush ;)

//     // ECMA-262 - 15.1.3.4
// function URIEncodeComponent(component) {
//   var unescapePredicate = function(cc) {
//     if (isAlphaNumeric(cc)) return true;
//     // !
//     if (cc == 33) return true;
//     // '()*
//     if (39 <= cc && cc <= 42) return true;
//     // -.
//     if (45 <= cc && cc <= 46) return true;
//     // _
//     if (cc == 95) return true;
//     // ~
//     if (cc == 126) return true;

//     return false;
//   };

//   var string = ToString(component);
//   return Encode(string, unescapePredicate);
// }

}

function createRequest(url) {

    return {
        "key": keys.easybib,
        "source": "website",
        "website": {
            "title": ""
        },
        "pubonline": {
            "title": "",
            "day": 1,
            "month": 1,
            "year": 1969,
            "url": "",
            "dayaccessed": Date.getDay(),
            "monthaccessed": Date.getMonth(),
            "yearaccessed": Date.getFullYear()
        }
    }
}
function cite(urlArray) {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "http://www.easybib.com/cite/bulk", true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            var res = JSON.parse(xhr.responseText);
            console.log(res);
        }
    }
    var request = [];
    for (var i = 0; i < urlArray.length; i++) {
        request.push(createRequest(urlArray[i]));
    }
    xhr.send(request);
}

document.addEventListener('DOMContentLoaded', function() {
    chrome.tabs.query({}, function (tabs) {
        for(var i = 0; i < tabs.length; i++) {
            var url = "";
            if(tabs[i].url.length > 36) {
                url = tabs[i].url.substring(0, 36) + "...";
            } else {
                url = tabs[i].url;
            }
            updateStatus(tabs[i].title, url);
            //findAuthor(url);
        }
    });
});<|endoftext|>


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

'use strict';

var __ = require('underscore');
var fs = require('fs');
var path = require('path');
var request = require('request');
var through = require('through');
var util = require('util');

var validation = require('../../../util/validation');
var profile = require('../../../util/profile');
var utils = require('../../../util/utils');

var $ = utils.getLocaleString;

exports.getGroup = function getGroup(client, name, callback) {
  client.resourceGroups.get(name, function (err, group) {
    if (err) {
      // 404 means doesn't exist
      if (err.statusCode === 404) {
        callback(null, null);
      } else {
        // some other error, let it out
        callback(err);
      }
    } else {
      // No error, group exists
      callback(null, group.resourceGroup);
    }
  });
};

exports.getResource = function getResource(client, resourceGroup, identity, callback) {
  client.resources.get(resourceGroup, identity, function (err, resource) {
    if (err) {
      // 404 means doesn't exist
      if (err.statusCode === 404) {
        callback(null, null);
      } else {
        // some other error, let it out
        callback(err);
      }
    } else {
      // No error, resource exists
      callback(null, resource.resource);
    }
  });
};

exports.createDeployment = function (cli, resourceGroup, name, options, _) {
  var subscription = profile.current.getSubscription(options.subscription);
  var client = utils.createResourceClient(subscription);

  var templateParameters = createDeploymentParameters(cli, subscription, resourceGroup, options, _);

  //if not provided, derive it from the template file name
  if (!name) {
    var templateName = options.templateFile || options.templateUri;
    var baseTemplateName = path.basename(templateName);
    //if the file extension is '.json', get rid of it.
    if (utils.stringEndsWith(baseTemplateName, '.json', true)) {
      baseTemplateName = path.basename(baseTemplateName, path.extname(baseTemplateName));
    }
    name = baseTemplateName;
  }

  var result = cli.interaction.withProgress($('Creating a deployment'),
    function (log, _) {
      if (!options.novalidate) {
        client.deployments.validate(resourceGroup, name, templateParameters, _);
      }
      var createResponse = client.deployments.createOrUpdate(resourceGroup, name, templateParameters, _);
      return createResponse;
    }, _);

  cli.output.info(util.format($('Created template deployment "%s"'), name));

  return result.deployment;

};

exports.validateTemplate = function (cli, resourceGroup, options, _) {
  var subscription = profile.current.getSubscription(options.subscription);
  var client = utils.createResourceClient(subscription);

  var templateParameters = createDeploymentParameters(cli, subscription, resourceGroup, options, _);

  var response = cli.interaction.withProgress($('Validating the template'),
    function (log, _) {
      return client.deployments.validate(resourceGroup, 'fakedDeploymentName', templateParameters, _);
    }, _);

  response.requiredProviders = getTemplateProviders(response);

  return response;
};

exports.getTemplateDownloadUrl = function getTemplateDownloadUrl(templateData) {
  //TODO, simplify with build-in support
  var urls = [];
  templateData.artifacts.forEach(function (e) {
    if (e.type === 'template') {
      urls.push({
        name: e.name,
        uri: e.uri
      });
    }
  });
  return urls;
};

exports.getAllEvents = function (subscription, groupName) {
  var output = through();
  var client = utils.createEventsClient(subscription);

  client.eventData.listEventsForResourceGroup({
    resourceGroupName: groupName,
    startTime: new Date(Date.now() - eventRetentionPeriodMS),
    endTime: new Date()
  }, function (err, response) {
    if (err) {
      return output.emit('error', err);
    }

    response.eventDataCollection.value.forEach(function (e) {
      output.queue(e);
    });
    output.end();
  });
  return output;
};

exports.getDeploymentLog = function (subscription, name, deploymentName) {
  var output = through();
  var client = utils.createResourceClient(subscription);

  client.deployments.get(name, deploymentName, function (err, result) {
    if (err) {
      return output.emit('error', err);
    }
    getDeploymentLogs(subscription, result.deployment.properties.correlationId).pipe(output);
  });
  return output;
};

exports.getLastDeploymentLog = function (subscription, name) {
  var output = through();
  var client = utils.createResourceClient(subscription);

  client.deployments.list(name, { top: 1 }, function (err, response) {
    if (err) { return output.emit('error', err); }
    if (response.deployments.length === 0) {
      output.emit('error', new Error($('Deployment not found')));
    }
    getDeploymentLogs(subscription, response.deployments[0].properties.correlationId).pipe(output);
  });
  return output;
};

exports.normalizeDownloadFileName = function normalizeDownloadFileName(downloadFile, quiet, confirmer, callback) {
  function ensureDirExists(dirname) {
    if (!dirname) {
      return;
    }

    if (utils.pathExistsSync(dirname)) {
      if (!fs.statSync(dirname).isDirectory()) {
        throw new Error(util.format($('Path %s already exists and is not a directory.'), dirname));
      }
      return;
    }

    ensureDirExists(path.dirname(dirname));
    fs.mkdirSync(dirname);
  }

  try {
    ensureDirExists(path.dirname(downloadFile));
    if (utils.pathExistsSync(downloadFile) && !quiet) {
      confirmer(
        util.format($('The file %s already exists. Overwrite? [y/n]: '), downloadFile),
          function (err, confirmed) {
            if (confirmed) {
              callback(null, downloadFile);
            } else {
              callback(null, null);
            }
          }
      );
    } else {
      callback(null, downloadFile);
    }
  } catch (ex) {
    callback(ex);
  }
};

function createDeploymentParameters(cli, subscription, resourceGroup, options, _) {
  var templateOptions = [options.templateFile, options.templateUri];
  var templateOptionsProvided = templateOptions.filter(function (value) { return value !== undefined; }).length;
  if (templateOptionsProvided > 1) {
    throw new Error($('Specify exactly one of the --template-file, or template-uri options.'));
  } else if (templateOptionsProvided === 0) {
    throw new Error($('One of the --template-file, or --template-uri options is required.'));
  }

  if (options.parameters && options.parametersFile) {
    throw new Error($('Either --parameters or --parameters-file need to be specified. Not both.'));
  }

  var deploymentParameters;
  if (options.parametersFile) {
    var jsonFile = fs.readFileSync(options.parametersFile, 'utf8');
    deploymentParameters = JSON.parse(utils.stripBOM(jsonFile));
    // Handle v2 version of parameters file that has $schema
    if (deploymentParameters.parameters) {
      deploymentParameters = deploymentParameters.parameters;
    }
  } else if (options.parameters) {
    deploymentParameters = JSON.parse(options.parameters);
  } else {
    var log = cli.output;
    log.info('Supply values for the following parameters');
    var paramsRequired = getTemplateParams(cli, subscription, options, _);
    deploymentParameters = {};

    Object.keys(paramsRequired).forEach_(_, 1, function (_, key) {
      var val = {};
      val['value'] = paramsRequired[key];
      deploymentParameters[key] = val;
    });

  }

  var templateParameters = {};
  if (options.mode) {
    templateParameters['properties'] = { mode: options.mode.toString() };
  }
  else {
    templateParameters['properties'] = { mode: 'Incremental' };
  }

  cli.interaction.withProgress($('Initializing template configurations and parameters'),
    function (log, _) {

      var templateUri = options.templateUri;
      if (!templateUri) {
        var templateContent = getTemplateContent(subscription, options.templateFile, _);
        templateParameters['properties']['template'] = templateContent;
      } else {
        templateParameters['properties']['templateLink'] = { uri: templateUri };
        if (options.templateVersion) {
          templateParameters.properties.templateLink.contentVersion = options.templateVersion;
        }
      }

      if (deploymentParameters) {
        templateParameters.properties.parameters = deploymentParameters;
      }

    }, _);
  return templateParameters;
}

var eventRetentionPeriodMS = 89 * 24 * 60 * 60 * 1000; // 89 days in milliseconds

function getDeploymentLogs(subscription, correlationId) {
  var output = through();
  var client = utils.createEventsClient(subscription);
  client.eventData.listEventsForCorrelationId({
    correlationId: correlationId,
    startTime: new Date(Date.now() - eventRetentionPeriodMS),
    endTime: new Date()
  }, function (err, response) {
    if (err) {
      return output.emit('error', err);
    }
    response.eventDataCollection.value.forEach(function (e) {
      output.queue(e);
    });
    output.end();
  });
  return output;
}

function getTemplateProviders(validationResponse) {
  return __.map(validationResponse.properties.providers, function (provider) {
    return provider.namespace.toLowerCase();
  });
}

function getTemplateContent(subscription, templateFile, _) {
  function readTemplateFileContentFromUri(templateFileUri, callback) {
    request(templateFileUri, function (error, response, body) {
      callback(error, body);//need to filter on some errors?
    });
  }

  var templateFileUri;
  if (templateFile) {
    if (validation.isURL(templateFile)) {
      templateFileUri = templateFile;
    }
  }

  var content = {};
  if (templateFileUri) {
    content = readTemplateFileContentFromUri(templateFileUri, _);
  } else if (templateFile) {
    content = utils.stripBOM(fs.readFileSync(templateFile));
  }

  return JSON.parse(content);
}

function getTemplateParams(cli, subscription, options, _)
{
  var templateContent = options.templateFile ?
    getTemplateContent(subscription, options.templateFile, _) :
    getTemplateContent(subscription, options.templateUri, _);

  var paramKeys = {};

  Object.keys(templateContent.parameters).forEach_(_, 1, function (_, param) {
    paramKeys[param] = templateContent.parameters[param].defaultValue;
    if (!templateContent.parameters[param].defaultValue) {
      paramKeys[param] = cli.interaction.promptIfNotGiven(param + ': ', paramKeys[param], _);
      switch (templateContent.parameters[param].type.toLowerCase()) {
        case 'int':
          paramKeys[param] = utils.parseInt(paramKeys[param]);
          break;

        case 'object':
        case 'bool':
        case 'array':
          paramKeys[param] = JSON.parse(paramKeys[param]);
          break;
      }
    }
  });

  return paramKeys;
}

exports.getFailedDeploymentOperations = function (subscription, resourceGroup, deploymentName, _) {
  var subscription = profile.current.getSubscription(subscription);
  var client = utils.createResourceClient(subscription);

  var operations = client.deploymentOperations.list(resourceGroup, deploymentName, _).operations;
  var failedOperations = getFailedNestedOperations(client, resourceGroup, operations, _);
  return failedOperations;
};

function getFailedNestedOperations(client, resourceGroup, currentOperations, _) {
  var newOperations = [];
  currentOperations.forEach_(_, 1, function (_, operation) {
    //If current operation has a nested deployment, idenitified by target resource, get failed operations of that nested deployment as well
    if (operation.properties.targetResource.id.indexOf('Microsoft.Resources/deployments') !== -1 && operation.properties.statusCode !== 'Succeeded') {
      newOperations.push(operation);
      var nestedDeployment = operation.properties.targetResource.resourceName;
      var nestedOperations = client.deploymentOperations.list(resourceGroup, nestedDeployment, _).operations;
      var newNestedOperations = getFailedNestedOperations(client, resourceGroup, nestedOperations, _);
      newOperations.concat(newNestedOperations);
    }
  });
  return newOperations;
}
<commit_msg>Update groupUtils._js<commit_after>/**
* Copyright (c) Microsoft.  All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

'use strict';

var __ = require('underscore');
var fs = require('fs');
var path = require('path');
var request = require('request');
var through = require('through');
var util = require('util');

var validation = require('../../../util/validation');
var profile = require('../../../util/profile');
var utils = require('../../../util/utils');

var $ = utils.getLocaleString;

exports.getGroup = function getGroup(client, name, callback) {
  client.resourceGroups.get(name, function (err, group) {
    if (err) {
      // 404 means doesn't exist
      if (err.statusCode === 404) {
        callback(null, null);
      } else {
        // some other error, let it out
        callback(err);
      }
    } else {
      // No error, group exists
      callback(null, group.resourceGroup);
    }
  });
};

exports.getResource = function getResource(client, resourceGroup, identity, callback) {
  client.resources.get(resourceGroup, identity, function (err, resource) {
    if (err) {
      // 404 means doesn't exist
      if (err.statusCode === 404) {
        callback(null, null);
      } else {
        // some other error, let it out
        callback(err);
      }
    } else {
      // No error, resource exists
      callback(null, resource.resource);
    }
  });
};

exports.createDeployment = function (cli, resourceGroup, name, options, _) {
  var subscription = profile.current.getSubscription(options.subscription);
  var client = utils.createResourceClient(subscription);

  var templateParameters = createDeploymentParameters(cli, subscription, resourceGroup, options, _);

  //if not provided, derive it from the template file name
  if (!name) {
    var templateName = options.templateFile || options.templateUri;
    var baseTemplateName = path.basename(templateName);
    //if the file extension is '.json', get rid of it.
    if (utils.stringEndsWith(baseTemplateName, '.json', true)) {
      baseTemplateName = path.basename(baseTemplateName, path.extname(baseTemplateName));
    }
    name = baseTemplateName;
  }

  var result = cli.interaction.withProgress($('Creating a deployment'),
    function (log, _) {
      if (!options.novalidate) {
        client.deployments.validate(resourceGroup, name, templateParameters, _);
      }
      var createResponse = client.deployments.createOrUpdate(resourceGroup, name, templateParameters, _);
      return createResponse;
    }, _);

  cli.output.info(util.format($('Created template deployment "%s"'), name));

  return result.deployment;

};

exports.validateTemplate = function (cli, resourceGroup, options, _) {
  var subscription = profile.current.getSubscription(options.subscription);
  var client = utils.createResourceClient(subscription);

  var templateParameters = createDeploymentParameters(cli, subscription, resourceGroup, options, _);

  var response = cli.interaction.withProgress($('Validating the template'),
    function (log, _) {
      return client.deployments.validate(resourceGroup, 'fakedDeploymentName', templateParameters, _);
    }, _);

  response.requiredProviders = getTemplateProviders(response);

  return response;
};

exports.getTemplateDownloadUrl = function getTemplateDownloadUrl(templateData) {
  //TODO, simplify with build-in support
  var urls = [];
  templateData.artifacts.forEach(function (e) {
    if (e.type === 'template') {
      urls.push({
        name: e.name,
        uri: e.uri
      });
    }
  });
  return urls;
};

exports.getAllEvents = function (subscription, groupName) {
  var output = through();
  var client = utils.createEventsClient(subscription);

  client.eventData.listEventsForResourceGroup({
    resourceGroupName: groupName,
    startTime: new Date(Date.now() - eventRetentionPeriodMS),
    endTime: new Date()
  }, function (err, response) {
    if (err) {
      return output.emit('error', err);
    }

    response.eventDataCollection.value.forEach(function (e) {
      output.queue(e);
    });
    output.end();
  });
  return output;
};

exports.getDeploymentLog = function (subscription, name, deploymentName) {
  var output = through();
  var client = utils.createResourceClient(subscription);

  client.deployments.get(name, deploymentName, function (err, result) {
    if (err) {
      return output.emit('error', err);
    }
    getDeploymentLogs(subscription, result.deployment.properties.correlationId).pipe(output);
  });
  return output;
};

exports.getLastDeploymentLog = function (subscription, name) {
  var output = through();
  var client = utils.createResourceClient(subscription);

  client.deployments.list(name, { top: 1 }, function (err, response) {
    if (err) { return output.emit('error', err); }
    if (response.deployments.length === 0) {
      output.emit('error', new Error($('Deployment not found')));
    }
    getDeploymentLogs(subscription, response.deployments[0].properties.correlationId).pipe(output);
  });
  return output;
};

exports.normalizeDownloadFileName = function normalizeDownloadFileName(downloadFile, quiet, confirmer, callback) {
  function ensureDirExists(dirname) {
    if (!dirname) {
      return;
    }

    if (utils.pathExistsSync(dirname)) {
      if (!fs.statSync(dirname).isDirectory()) {
        throw new Error(util.format($('Path %s already exists and is not a directory.'), dirname));
      }
      return;
    }

    ensureDirExists(path.dirname(dirname));
    fs.mkdirSync(dirname);
  }

  try {
    ensureDirExists(path.dirname(downloadFile));
    if (utils.pathExistsSync(downloadFile) && !quiet) {
      confirmer(
        util.format($('The file %s already exists. Overwrite? [y/n]: '), downloadFile),
          function (err, confirmed) {
            if (confirmed) {
              callback(null, downloadFile);
            } else {
              callback(null, null);
            }
          }
      );
    } else {
      callback(null, downloadFile);
    }
  } catch (ex) {
    callback(ex);
  }
};

function createDeploymentParameters(cli, subscription, resourceGroup, options, _) {
  var templateOptions = [options.templateFile, options.templateUri];
  var templateOptionsProvided = templateOptions.filter(function (value) { return value !== undefined; }).length;
  if (templateOptionsProvided > 1) {
    throw new Error($('Specify exactly one of the --template-file, or template-uri options.'));
  } else if (templateOptionsProvided === 0) {
    throw new Error($('One of the --template-file, or --template-uri options is required.'));
  }

  if (options.parameters && options.parametersFile) {
    throw new Error($('Either --parameters or --parameters-file need to be specified. Not both.'));
  }

  var deploymentParameters;
  if (options.parametersFile) {
    var jsonFile = fs.readFileSync(options.parametersFile, 'utf8');
    deploymentParameters = JSON.parse(utils.stripBOM(jsonFile));
    // Handle v2 version of parameters file that has $schema
    if (deploymentParameters.parameters) {
      deploymentParameters = deploymentParameters.parameters;
    }
  } else if (options.parameters) {
    deploymentParameters = JSON.parse(options.parameters);
  } else {
    var log = cli.output;
    log.info('Supply values for the following parameters');
    var paramsRequired = getTemplateParams(cli, subscription, options, _);
    deploymentParameters = {};

    Object.keys(paramsRequired).forEach_(_, 1, function (_, key) {
      var val = {};
      val['value'] = paramsRequired[key];
      deploymentParameters[key] = val;
    });

  }

  var templateParameters = {};
  if (options.mode) {
    templateParameters['properties'] = { mode: options.mode.toString() };
  }
  else {
    templateParameters['properties'] = { mode: 'Incremental' };
  }

  cli.interaction.withProgress($('Initializing template configurations and parameters'),
    function (log, _) {

      var templateUri = options.templateUri;
      if (!templateUri) {
        var templateContent = getTemplateContent(subscription, options.templateFile, _);
        templateParameters['properties']['template'] = templateContent;
      } else {
        templateParameters['properties']['templateLink'] = { uri: templateUri };
        if (options.templateVersion) {
          templateParameters.properties.templateLink.contentVersion = options.templateVersion;
        }
      }

      if (deploymentParameters) {
        templateParameters.properties.parameters = deploymentParameters;
      }

    }, _);
  return templateParameters;
}

var eventRetentionPeriodMS = 89 * 24 * 60 * 60 * 1000; // 89 days in milliseconds

function getDeploymentLogs(subscription, correlationId) {
  var output = through();
  var client = utils.createEventsClient(subscription);
  client.eventData.listEventsForCorrelationId({
    correlationId: correlationId,
    startTime: new Date(Date.now() - eventRetentionPeriodMS),
    endTime: new Date()
  }, function (err, response) {
    if (err) {
      return output.emit('error', err);
    }
    response.eventDataCollection.value.forEach(function (e) {
      output.queue(e);
    });
    output.end();
  });
  return output;
}

function getTemplateProviders(validationResponse) {
  return __.map(validationResponse.properties.providers, function (provider) {
    return provider.namespace.toLowerCase();
  });
}

function getTemplateContent(subscription, templateFile, _) {
  function readTemplateFileContentFromUri(templateFileUri, callback) {
    request(templateFileUri, function (error, response, body) {
      callback(error, body);//need to filter on some errors?
    });
  }

  var templateFileUri;
  if (templateFile) {
    if (validation.isURL(templateFile)) {
      templateFileUri = templateFile;
    }
  }

  var content = {};
  if (templateFileUri) {
    content = readTemplateFileContentFromUri(templateFileUri, _);
  } else if (templateFile) {
    content = utils.stripBOM(fs.readFileSync(templateFile));
  }

  return JSON.parse(content);
}

function getTemplateParams(cli, subscription, options, _)
{
  var templateContent = options.templateFile ?
    getTemplateContent(subscription, options.templateFile, _) :
    getTemplateContent(subscription, options.templateUri, _);

  var paramKeys = {};

  Object.keys(templateContent.parameters).forEach_(_, 1, function (_, param) {
    paramKeys[param] = templateContent.parameters[param].defaultValue;
    if (!templateContent.parameters[param].defaultValue) {
      paramKeys[param] = cli.interaction.promptIfNotGiven(param + ': ', paramKeys[param], _);
      switch (templateContent.parameters[param].type.toLowerCase()) {
        case 'int':
          paramKeys[param] = utils.parseInt(paramKeys[param]);
          break;

        case 'object':
        case 'bool':
        case 'array':
          paramKeys[param] = JSON.parse(paramKeys[param]);
          break;
      }
    }
  });

  return paramKeys;
}

exports.getFailedDeploymentOperations = function (subscription, resourceGroup, deploymentName, _) {
  var client = utils.createResourceClient(subscription);

  var operations = client.deploymentOperations.list(resourceGroup, deploymentName, _).operations;
  var failedOperations = getFailedNestedOperations(client, resourceGroup, operations, _);
  return failedOperations;
};

function getFailedNestedOperations(client, resourceGroup, currentOperations, _) {
  var newOperations = [];
  currentOperations.forEach_(_, 1, function (_, operation) {
    //If current operation has a nested deployment, idenitified by target resource, get failed operations of that nested deployment as well
    if (operation.properties.targetResource.id.indexOf('Microsoft.Resources/deployments') !== -1 && operation.properties.statusCode !== 'Succeeded') {
      newOperations.push(operation);
      var nestedDeployment = operation.properties.targetResource.resourceName;
      var nestedOperations = client.deploymentOperations.list(resourceGroup, nestedDeployment, _).operations;
      var newNestedOperations = getFailedNestedOperations(client, resourceGroup, nestedOperations, _);
      newOperations.concat(newNestedOperations);
    }
  });
  return newOperations;
}
<|endoftext|>


<commit_before>/**
 * @fileOverview
 * Copyright (c) 2012 Adam Ranfelt
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge,
 * publish, distribute, sublicense, and/or sell copies of the Software,
 * and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
 * OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * Stage Module Definition
 * @author Adam Ranfelt <adamRenny@gmail.com>
 * @version 1.1
 */
define([
    'jquery',
    'layer/Layer',
    'layer/RenderCache'
], function(
    $,
    Layer,
    RenderCache
) {
    'use strict';

    /**
     * Hardware CSS Styles to modify for acceleration
     *
     * @private
     * @type {Array}
     * @constant
     * @since 1.0
     */
    var HARDWARE_STYLES = [
        '-webkit-transform'
    ];

    /**
     * Settings for each hardware CSS styles to modify for acceleration
     *
     * @private
     * @type {Array}
     * @constant
     * @since 1.0
     */
    var HARDWARE_SETTINGS = {
        '-webkit-transform': 'matrix3d(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)'
    };

    /**
     * Prepares and calculates the hardware settings
     * Attempts to apply settings only if unset
     *
     * @private
     * @function
     * @param {HTMLElement} element Element to prepare hardware acceleration for
     * @returns {Array}
     * @since 1.0
     */
    var _prepareHardwareSettings = function(element) {
        var $element = $(element);
        var i = 0;
        var length = HARDWARE_STYLES.length;
        var styles = {};
        for (; i < length; i++) {
            if ($element.css(HARDWARE_STYLES[i]) === "none") {
                styles[HARDWARE_STYLES[i]] = HARDWARE_SETTINGS[HARDWARE_STYLES[i]];
            }
        }

        return styles;
    };

    /**
     * Applies a statically generated layer name/id
     *
     * @private
     * @function
     * @since 1.0
     */
    var _applyAutoLayerName = function(layer) {
        layer.id = LAYER_PREFIX + _canvasId++;
    };

    /**
     *
Stage Constructor

     *
     *
Manager of the layers of the stage and controls hardware acceleration

     *
     * @name Stage
     * @class Container to manage the canvas elements and layers
     * @constructor
     *
     * @param {HTMLElement} viewport Container for the canvas elements
     * @param {number} width Base width of the stage
     * @param {number} height Base height of the stage
     * @since 1.0
     */
    var Stage = function(viewport, width, height) {
        this.init(viewport, width, height);
    };

    /**
     * Stage initialization
     *
     * Initializes the layer management container
     * Generates layers for canvas layer elements located within the container
     *
     * @throws {ArgumentsError} If the stage doesn't receive all the arguments
     *
     * @param {HTMLElement} viewport Container for the canvas elements
     * @param {number} width Base width of the stage
     * @param {number} height Base height of the stage
     * @returns {Stage}
     * @since 1.0
     */
    Stage.prototype.init = function(viewport, width, height) {
        if (arguments.length !== 3) {
            throw new Error('ArgumentsError: Stage expects arguments: new Stage(viewport, width, height) received ' + arguments.length);
        }

        /**
         * Viewport container object to contain the layers/canvases
         *
         * @name Stage#viewport
         * @type {HTMLElement}
         * @since 1.0
         */
        this.viewport = viewport;

        /**
         * jQuery object of viewport
         *
         * @name Stage#$viewport
         * @type {jQuery}
         */
        this.$viewport = $(this.viewport);

        /**
         * Width of the stage
         *
         * @name Stage#width
         * @type {number}
         * @since 1.0
         */
        this.width = width;

        /**
         * Height of the stage
         *
         * @name Stage#height
         * @type {number}
         * @since 1.0
         */
        this.height = height;

        /**
         * Layer list which mimics the DOM representation
         *
         * @default []
         * @name Stage#layers
         * @type {Array}
         * @since 1.0
         */
        var layers = this.layers = [];

        /**
         * Layer cache which stores layers by name for quick lookup
         *
         * @default {}
         * @name Stage#layerCache
         * @type {Array}
         * @since 1.0
         */
        this.layerCache = {};

        // Creates representative layers for existing canvases
        this.$viewport.children().each(function() {
            this.width = width;
            this.height = height;
            layers.push(new Layer(this));
        });

        /**
         * Count of the layers in the stage
         *
         * @name Stage#layerCount
         * @type {number}
         * @since 1.0
         */
        this.layerCount = layers.length;

        return this;
    };

    /**
     * Creates a layer with the dimensions of the stage and name provided
     *
     * @throws {ArgumentsError} If the name is undefined
     *
     * @param {string} name Layer name/id
     * @returns {Layer}
     * @since 1.0
     */
    Stage.prototype.createLayer = function(name) {
        if (name === undefined) {
            throw new Error('ArgumentsError: Layer name is undefined');
        }

        return new Layer(RenderCache.createCanvas(name, this.width, this.height));
    };

    /**
     * Enables hardware acceleration for all canvases
     *
     * @returns {Stage}
     * @since 1.0
     */
    Stage.prototype.enableCSSAcceleration = function() {
        var i = 0;
        var length = this.layers.length;
        var canvas;
        for (; i < length; i++) {
            canvas = this.layers[i].getCanvas();
            $(canvas).css(_prepareHardwareSettings(canvas));
        }

        return this;
    };

    /**
     * Enables hardware acceleration for a specific layer
     *
     * @param {Layer} layer Layer to enable acceleration for
     * @returns {Stage}
     * @since 1.0
     */
    Stage.prototype.enableCSSAccelerationForLayer = function(layer) {
        var canvas = layer.getCanvas();
        $(canvas).css(_prepareHardwareSettings(canvas));

        return this;
    };

    /**
     * Enables acceleration by a layer name contained within the stage
     *
     * @param {string} name Name of the layer to enable
     * @returns {Stage}
     * @since 1.0
     */
    Stage.prototype.enableCSSAccelerationByName = function(name) {
        return this.enableCSSAccelerationForLayer(this.getLayerByName(name));
    };

    /**
     * Enables acceleration by a layer index
     *
     * @param {string} index Index of the layer to enable acceleration
     * @returns {Stage}
     * @since 1.0
     */
    Stage.prototype.enableCSSAccelerationByIndex = function(index) {
        return this.enableCSSAccelerationForLayer(this.getLayerByIndex(index));
    };

    /**
     * Creates and prepends a layer into stage
     *
     * @param {string} name Name of the layer to create
     * @returns {Stage}
     * @since 1.0
     */
    Stage.prototype.createAndPrependLayer = function(name) {
        return this.prependLayer(this.createLayer(name));
    };

    /**
     * Creates and appends a layer into stage
     *
     * @param {string} name Name of the layer to create
     * @returns {Stage}
     * @since 1.0
     */
    Stage.prototype.createAndAppendLayer = function(name) {
        return this.appendLayer(this.createLayer(name));
    };

    /**
     * Creates and inserts a layer into stage
     *
     * @param {string} name Name of the layer to create
     * @param {number} index Index to insert into
     * @returns {Stage}
     * @since 1.0
     */
    Stage.prototype.createAndInsertLayerAtIndex = function(name, index) {
        return this.insertLayerAtIndex(this.createLayer(name), index);
    };

    /**
     * Using the cache, gets a layer by name
     *
     * @throws {UndefinedError} If the layer by the provided name doesn't exist
     *
     * @param {string} name Name of the layer to find
     * @returns {Layer}
     * @since 1.0
     */
    Stage.prototype.getLayerByName = function(name) {
        if (!this.layerCache.hasOwnProperty(name)) {
            throw new Error('UndefinedError: Layer with name ' + name + ' does not exist');
        }

        return this.layerCache[name];
    };

    /**
     * Gets a layer by index
     *
     * @throws {UndefinedError} If the index is out of bounds
     *
     * @param {number} index Index of the layer to find
     * @returns {Layer}
     * @since 1.0
     */
    Stage.prototype.getLayerByIndex = function(index) {
        if (index < 0 || index >= this.layerCount) {
            throw new Error('UndefinedError: Index ' + index + ' is out of bounds');
        }

        return this.layers[index];
    };

    /**
     * Prepends the layer to the viewport and stage
     *
     * @param {Layer} layer Layer to prepend
     * @returns {Layer}
     * @since 1.0
     */
    Stage.prototype.prependLayer = function(layer) {
        this.$viewport.prepend(layer.getCanvas());
        this.layerCache[layer.name] = layer;
        this.layers.unshift(layer);
        this.layerCount = this.layers.length;

        return this;
    };

    /**
     * Appends the layer to the viewport and stage
     *
     * @param {Layer} layer Layer to append
     * @returns {Layer}
     * @since 1.0
     */
    Stage.prototype.appendLayer = function(layer) {
        this.viewport.appendChild(layer.getCanvas());
        this.layerCache[layer.name] = layer;
        this.layers.push(layer);
        this.layerCount = this.layers.length;

        return this;
    };

    /**
     * Insert the layer to the viewport and stage
     *
     * @param {Layer} layer Layer to insert
     * @returns {Layer}
     * @since 1.0
     */
    Stage.prototype.insertLayerAtIndex = function(layer, index) {
        if (index < 0) {
            return this.prependLayer(layer);
        } else if (index >= this.layerCount) {
            return this.appendLayer(layer);
        }

        var targetLayer = this.layers[index];
        this.$viewport.find('#' + targetLayer.name).after(layer.getCanvas());
        this.layerCache[layer.name] = layer;
        this.layers.splice(index, 0, layer);
        this.layerCount = this.layers.length;

        return this;
    };

    /**
     * Public convenience function to loop on the layers with
     *
     * @param {function} callback Callback that expects layer as a parameter
     * @since 1.1
     */
    Stage.prototype.forEachLayer = function(callback) {
        var i = 0;
        var layerCount = this.layerCount;

        for (; i < layerCount; i++) {
            callback(this.getLayerByIndex(i));
        }
    };

    return Stage;
});<commit_msg>Fix JSDocs<commit_after>/**
 * @fileOverview
 * Copyright (c) 2012 Adam Ranfelt
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge,
 * publish, distribute, sublicense, and/or sell copies of the Software,
 * and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
 * OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * Stage Module Definition
 * @author Adam Ranfelt <adamRenny@gmail.com>
 * @version 1.1
 */
define([
    'jquery',
    'layer/Layer',
    'layer/RenderCache'
], function(
    $,
    Layer,
    RenderCache
) {
    'use strict';

    /**
     * Hardware CSS Styles to modify for acceleration
     *
     * @private
     * @type {Array}
     * @constant
     * @since 1.0
     */
    var HARDWARE_STYLES = [
        '-webkit-transform'
    ];

    /**
     * Settings for each hardware CSS styles to modify for acceleration
     *
     * @private
     * @type {Object}
     * @constant
     * @since 1.0
     */
    var HARDWARE_SETTINGS = {
        '-webkit-transform': 'matrix3d(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)'
    };

    /**
     * Prepares and calculates the hardware settings
     * Attempts to apply settings only if unset
     *
     * @private
     * @function
     * @param {HTMLElement} element Element to prepare hardware acceleration for
     * @returns {Array}
     * @since 1.0
     */
    var _prepareHardwareSettings = function(element) {
        var $element = $(element);
        var i = 0;
        var length = HARDWARE_STYLES.length;
        var styles = {};
        for (; i < length; i++) {
            if ($element.css(HARDWARE_STYLES[i]) === "none") {
                styles[HARDWARE_STYLES[i]] = HARDWARE_SETTINGS[HARDWARE_STYLES[i]];
            }
        }

        return styles;
    };

    /**
     * Applies a statically generated layer name/id
     *
     * @private
     * @function
     * @since 1.0
     */
    var _applyAutoLayerName = function(layer) {
        layer.id = LAYER_PREFIX + _canvasId++;
    };

    /**
     *
Stage Constructor

     *
     *
Manager of the layers of the stage and controls hardware acceleration

     *
     * @name Stage
     * @class Container to manage the canvas elements and layers
     * @constructor
     *
     * @param {HTMLElement} viewport Container for the canvas elements
     * @param {number} width Base width of the stage
     * @param {number} height Base height of the stage
     * @since 1.0
     */
    var Stage = function(viewport, width, height) {
        this.init(viewport, width, height);
    };

    /**
     * Stage initialization
     *
     * Initializes the layer management container
     * Generates layers for canvas layer elements located within the container
     *
     * @throws {ArgumentsError} If the stage doesn't receive all the arguments
     *
     * @param {HTMLElement} viewport Container for the canvas elements
     * @param {number} width Base width of the stage
     * @param {number} height Base height of the stage
     * @returns {Stage}
     * @since 1.0
     */
    Stage.prototype.init = function(viewport, width, height) {
        if (arguments.length !== 3) {
            throw new Error('ArgumentsError: Stage expects arguments: new Stage(viewport, width, height) received ' + arguments.length);
        }

        /**
         * Viewport container object to contain the layers/canvases
         *
         * @name Stage#viewport
         * @type {HTMLElement}
         * @since 1.0
         */
        this.viewport = viewport;

        /**
         * jQuery object of viewport
         *
         * @name Stage#$viewport
         * @type {jQuery}
         */
        this.$viewport = $(this.viewport);

        /**
         * Width of the stage
         *
         * @name Stage#width
         * @type {number}
         * @since 1.0
         */
        this.width = width;

        /**
         * Height of the stage
         *
         * @name Stage#height
         * @type {number}
         * @since 1.0
         */
        this.height = height;

        /**
         * Layer list which mimics the DOM representation
         *
         * @default []
         * @name Stage#layers
         * @type {Array}
         * @since 1.0
         */
        var layers = this.layers = [];

        /**
         * Layer cache which stores layers by name for quick lookup
         *
         * @default {}
         * @name Stage#layerCache
         * @type {Array}
         * @since 1.0
         */
        this.layerCache = {};

        // Creates representative layers for existing canvases
        this.$viewport.children().each(function() {
            this.width = width;
            this.height = height;
            layers.push(new Layer(this));
        });

        /**
         * Count of the layers in the stage
         *
         * @name Stage#layerCount
         * @type {number}
         * @since 1.0
         */
        this.layerCount = layers.length;

        return this;
    };

    /**
     * Creates a layer with the dimensions of the stage and name provided
     *
     * @throws {ArgumentsError} If the name is undefined
     *
     * @param {string} name Layer name/id
     * @returns {Layer}
     * @since 1.0
     */
    Stage.prototype.createLayer = function(name) {
        if (name === undefined) {
            throw new Error('ArgumentsError: Layer name is undefined');
        }

        return new Layer(RenderCache.createCanvas(name, this.width, this.height));
    };

    /**
     * Enables hardware acceleration for all canvases
     *
     * @returns {Stage}
     * @since 1.0
     */
    Stage.prototype.enableCSSAcceleration = function() {
        var i = 0;
        var length = this.layers.length;
        var canvas;
        for (; i < length; i++) {
            canvas = this.layers[i].getCanvas();
            $(canvas).css(_prepareHardwareSettings(canvas));
        }

        return this;
    };

    /**
     * Enables hardware acceleration for a specific layer
     *
     * @param {Layer} layer Layer to enable acceleration for
     * @returns {Stage}
     * @since 1.0
     */
    Stage.prototype.enableCSSAccelerationForLayer = function(layer) {
        var canvas = layer.getCanvas();
        $(canvas).css(_prepareHardwareSettings(canvas));

        return this;
    };

    /**
     * Enables acceleration by a layer name contained within the stage
     *
     * @param {string} name Name of the layer to enable
     * @returns {Stage}
     * @since 1.0
     */
    Stage.prototype.enableCSSAccelerationByName = function(name) {
        return this.enableCSSAccelerationForLayer(this.getLayerByName(name));
    };

    /**
     * Enables acceleration by a layer index
     *
     * @param {string} index Index of the layer to enable acceleration
     * @returns {Stage}
     * @since 1.0
     */
    Stage.prototype.enableCSSAccelerationByIndex = function(index) {
        return this.enableCSSAccelerationForLayer(this.getLayerByIndex(index));
    };

    /**
     * Creates and prepends a layer into stage
     *
     * @param {string} name Name of the layer to create
     * @returns {Stage}
     * @since 1.0
     */
    Stage.prototype.createAndPrependLayer = function(name) {
        return this.prependLayer(this.createLayer(name));
    };

    /**
     * Creates and appends a layer into stage
     *
     * @param {string} name Name of the layer to create
     * @returns {Stage}
     * @since 1.0
     */
    Stage.prototype.createAndAppendLayer = function(name) {
        return this.appendLayer(this.createLayer(name));
    };

    /**
     * Creates and inserts a layer into stage
     *
     * @param {string} name Name of the layer to create
     * @param {number} index Index to insert into
     * @returns {Stage}
     * @since 1.0
     */
    Stage.prototype.createAndInsertLayerAtIndex = function(name, index) {
        return this.insertLayerAtIndex(this.createLayer(name), index);
    };

    /**
     * Using the cache, gets a layer by name
     *
     * @throws {UndefinedError} If the layer by the provided name doesn't exist
     *
     * @param {string} name Name of the layer to find
     * @returns {Layer}
     * @since 1.0
     */
    Stage.prototype.getLayerByName = function(name) {
        if (!this.layerCache.hasOwnProperty(name)) {
            throw new Error('UndefinedError: Layer with name ' + name + ' does not exist');
        }

        return this.layerCache[name];
    };

    /**
     * Gets a layer by index
     *
     * @throws {UndefinedError} If the index is out of bounds
     *
     * @param {number} index Index of the layer to find
     * @returns {Layer}
     * @since 1.0
     */
    Stage.prototype.getLayerByIndex = function(index) {
        if (index < 0 || index >= this.layerCount) {
            throw new Error('UndefinedError: Index ' + index + ' is out of bounds');
        }

        return this.layers[index];
    };

    /**
     * Prepends the layer to the viewport and stage
     *
     * @param {Layer} layer Layer to prepend
     * @returns {Layer}
     * @since 1.0
     */
    Stage.prototype.prependLayer = function(layer) {
        this.$viewport.prepend(layer.getCanvas());
        this.layerCache[layer.name] = layer;
        this.layers.unshift(layer);
        this.layerCount = this.layers.length;

        return this;
    };

    /**
     * Appends the layer to the viewport and stage
     *
     * @param {Layer} layer Layer to append
     * @returns {Layer}
     * @since 1.0
     */
    Stage.prototype.appendLayer = function(layer) {
        this.viewport.appendChild(layer.getCanvas());
        this.layerCache[layer.name] = layer;
        this.layers.push(layer);
        this.layerCount = this.layers.length;

        return this;
    };

    /**
     * Insert the layer to the viewport and stage
     *
     * @param {Layer} layer Layer to insert
     * @param {number} index Index to insert layer after
     * @returns {Layer}
     * @since 1.0
     */
    Stage.prototype.insertLayerAtIndex = function(layer, index) {
        if (index < 0) {
            return this.prependLayer(layer);
        } else if (index >= this.layerCount) {
            return this.appendLayer(layer);
        }

        var targetLayer = this.layers[index];
        this.$viewport.find('#' + targetLayer.name).after(layer.getCanvas());
        this.layerCache[layer.name] = layer;
        this.layers.splice(index, 0, layer);
        this.layerCount = this.layers.length;

        return this;
    };

    /**
     * Public convenience function to loop on the layers with
     *
     * @param {function} callback Callback that expects layer as a parameter
     * @since 1.1
     */
    Stage.prototype.forEachLayer = function(callback) {
        var i = 0;
        var layerCount = this.layerCount;

        for (; i < layerCount; i++) {
            callback(this.getLayerByIndex(i));
        }
    };

    return Stage;
});<|endoftext|>


<commit_before>// Copyright 2016, University of Colorado Boulder

/**
 *
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Andrew Adare (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var assertInstanceOf = require( 'PHET_IO/assertions/assertInstanceOf' );
  var phetioInherit = require( 'PHET_IO/phetioInherit' );
  var phetioNamespace = require( 'PHET_IO/phetioNamespace' );
  var TObject = require( 'PHET_IO/types/TObject' );
  var toEventOnEmit = require( 'PHET_IO/events/toEventOnEmit' );

  /**
   * Wrapper type for phet/tandem's TandemDragHandler class.
   * @param tandemDragHandler
   * @param phetioID
   * @constructor
   */
  function TTandemDragHandler( tandemDragHandler, phetioID ) {
    TObject.call( this, tandemDragHandler, phetioID );
    assertInstanceOf( tandemDragHandler, phet.tandem.TandemDragHandler );

    var toXY = function( x, y ) { return { x: x, y: y }; };
    toEventOnEmit( tandemDragHandler.startedCallbacksForDragStartedEmitter, tandemDragHandler.endedCallbacksForDragStartedEmitter, 'user', phetioID, TTandemDragHandler, 'dragStarted', toXY );
    toEventOnEmit( tandemDragHandler.startedCallbacksForDraggedEmitter, tandemDragHandler.endedCallbacksForDraggedEmitter, 'user', phetioID, TTandemDragHandler, 'dragged', toXY );
    toEventOnEmit( tandemDragHandler.startedCallbacksForDragEndedEmitter, tandemDragHandler.endedCallbacksForDragEndedEmitter, 'user', phetioID, TTandemDragHandler, 'dragEnded' );
  }

  phetioInherit( TObject, 'TTandemDragHandler', TTandemDragHandler, {}, {
    documentation: 'Drag listener for objects that can be dragged by the user.',
    events: [ 'dragStarted', 'dragged', 'dragEnded' ]
  } );

  phetioNamespace.register( 'TTandemDragHandler', TTandemDragHandler );

  return TTandemDragHandler;
} );

<commit_msg>Renamed TandemDragHandler => TandemSimpleDragHandler to match naming conventions, see https://github.com/phetsims/phet-io/issues/889<commit_after>// Copyright 2016, University of Colorado Boulder

/**
 *
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Andrew Adare (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var assertInstanceOf = require( 'PHET_IO/assertions/assertInstanceOf' );
  var phetioInherit = require( 'PHET_IO/phetioInherit' );
  var phetioNamespace = require( 'PHET_IO/phetioNamespace' );
  var TObject = require( 'PHET_IO/types/TObject' );
  var toEventOnEmit = require( 'PHET_IO/events/toEventOnEmit' );

  /**
   * Wrapper type for phet/tandem's TandemSimpleDragHandler class.
   * @param tandemSimpleDragHandler
   * @param phetioID
   * @constructor
   */
  function TTandemSimpleDragHandler( tandemSimpleDragHandler, phetioID ) {
    TObject.call( this, tandemSimpleDragHandler, phetioID );
    assertInstanceOf( tandemSimpleDragHandler, phet.tandem.TandemSimpleDragHandler );

    var toXY = function( x, y ) { return { x: x, y: y }; };
    toEventOnEmit( tandemSimpleDragHandler.startedCallbacksForDragStartedEmitter, tandemSimpleDragHandler.endedCallbacksForDragStartedEmitter, 'user', phetioID, TTandemSimpleDragHandler, 'dragStarted', toXY );
    toEventOnEmit( tandemSimpleDragHandler.startedCallbacksForDraggedEmitter, tandemSimpleDragHandler.endedCallbacksForDraggedEmitter, 'user', phetioID, TTandemSimpleDragHandler, 'dragged', toXY );
    toEventOnEmit( tandemSimpleDragHandler.startedCallbacksForDragEndedEmitter, tandemSimpleDragHandler.endedCallbacksForDragEndedEmitter, 'user', phetioID, TTandemSimpleDragHandler, 'dragEnded' );
  }

  phetioInherit( TObject, 'TTandemSimpleDragHandler', TTandemSimpleDragHandler, {}, {
    documentation: 'Drag listener for objects that can be dragged by the user.',
    events: [ 'dragStarted', 'dragged', 'dragEnded' ]
  } );

  phetioNamespace.register( 'TTandemSimpleDragHandler', TTandemSimpleDragHandler );

  return TTandemSimpleDragHandler;
} );

<|endoftext|>


<commit_before>module.exports = function(model) {
    const Schema = require('js-data-schema');
    const schema = new Schema();

    let schemaRules = require('./schema-rules')(model);
    //let dataTypes = require('./schema-data-types');
    defineRules();

    let directorySchema = require('./directory-schema')(schema);
    let experimentSchema = require('./experiment-schema')(schema);
    let samplesSchema = require('./samples-schema')(schema);
    let processSchema = require('./process-schema')(schema);
    let userSchema = require('./user-schema')(schema);
    let datasetSchema = require('./dataset-schema')(schema);

    return {
        createSamples: samplesSchema.defineCreateSamplesSchema(),
        addSamplesMeasurements: samplesSchema.defineAddSamplesMeasurementsSchema(),
        samplesMeasurement: samplesSchema.defineSamplesMeasurementSchema(),
        measurement: samplesSchema.defineMeasurementSchema(),
        processes: processSchema.defineCreateProcessSchema(),
        updateProcess: processSchema.defineUpdateProcessSchema(),
        //measurements: measurementsSchema.defineMeasurementsSchema(),
        createDirectory: directorySchema.defineCreateDirectorySchema(),
        renameDirectory: directorySchema.defineRenameDirectorySchema(),
        moveDirectory: directorySchema.defineMoveDirectorySchema(),
        createExperiment: experimentSchema.defineCreateExperimentSchema(),
        updateExperiment: experimentSchema.defineUpdateExperimentSchema(),
        createExperimentTask: experimentSchema.defineCreateExperimentTaskSchema(),
        updateExperimentTask: experimentSchema.defineUpdateExperimentTaskSchema(),
        createExperimentNote: experimentSchema.defineCreateExperimentNoteSchema(),
        updateExperimentNote: experimentSchema.defineUpdateExperimentNoteSchema(),
        updateExperimentTaskTemplateProps: experimentSchema.defineUpdateExperimentTaskTemplatePropsSchema(),
        templateProperty: experimentSchema.defineTemplatePropertySchema(),
        templateCommand: experimentSchema.defineTemplateCommandSchema(),
        userAccountSchema: userSchema.defineUserAccountSchema(),
        createDatasetSchema: datasetSchema.defineCreateDatasetSchema(),
        updateDatasetSchema: datasetSchema.defineUpdateDatasetSchema(),
        datasetAuthor: datasetSchema.defineDatasetAuthorSchema(),
        datasetPaper: datasetSchema.defineDatasetPaperSchema(),
        validate,
        prepare,
        model
    };

    function validate(schema, body) {
        return schema.validateAsync(body).then(() => null, (errors) => errors);
    }

    function prepare(schema, body) {
        schema.stripNonSchemaAttrs(body);
        schema.addDefaultsToTarget(body);
    }

    /////////////// Define Rules ///////////////

    function defineRules() {
        schema.defineRule('mustExist', schemaRules.mustExist, true);
        schema.defineRule('mustNotExist', schemaRules.mustNotExist, true);
        schema.defineRule('mustNotExistInProject', schemaRules.mustNotExistInProject, true);
        schema.defineRule('mustExistInProject', schemaRules.mustExistInProject, true);
        schema.defineRule('mustBeForSample', schemaRules.mustBeForSample, true);
        schema.defineRule('mustBeForAttributeSet', schemaRules.mustBeForAttributeSet, true);
        schema.defineRule('mustBeValidMeasurements', schemaRules.mustBeValidMeasurements, true);
        schema.defineRule('isValidPropertyType', schemaRules.isValidPropertyType);
        schema.defineRule('isValidUnit', schemaRules.isValidUnit);
        schema.defineRule('isValidExperimentStatus', schemaRules.isValidExperimentStatus);
        schema.defineRule('oneOf', schemaRules.oneOf);
        schema.defineRule('mustNotStartWith', schemaRules.mustNotStartWith);
        schema.defineRule('mustNotExistInDirectory', schemaRules.mustNotExistInDirectory, true);
        schema.defineRule('mustNotExistInParentDirectory', schemaRules.mustNotExistInParentDirectory, true);
    }
};
<commit_msg>Convert how modules are setup and imported.<commit_after>const Schema = require('js-data-schema');
const schema = new Schema();

//let schemaRules = require('./schema-rules')(model);
//let dataTypes = require('./schema-data-types');
//defineRules();

let directorySchema = require('./directory-schema')(schema);
let experimentSchema = require('./experiment-schema')(schema);
let samplesSchema = require('./samples-schema')(schema);
let processSchema = require('./process-schema')(schema);
let userSchema = require('./user-schema')(schema);
let datasetSchema = require('./dataset-schema')(schema);

function validate(schema, body) {
    return schema.validateAsync(body).then(() => null, (errors) => errors);
}

function prepare(schema, body) {
    schema.stripNonSchemaAttrs(body);
    schema.addDefaultsToTarget(body);
}

/////////////// Define Rules ///////////////

function defineRules() {
    schema.defineRule('mustExist', schemaRules.mustExist, true);
    schema.defineRule('mustNotExist', schemaRules.mustNotExist, true);
    schema.defineRule('mustNotExistInProject', schemaRules.mustNotExistInProject, true);
    schema.defineRule('mustExistInProject', schemaRules.mustExistInProject, true);
    schema.defineRule('mustBeForSample', schemaRules.mustBeForSample, true);
    schema.defineRule('mustBeForAttributeSet', schemaRules.mustBeForAttributeSet, true);
    schema.defineRule('mustBeValidMeasurements', schemaRules.mustBeValidMeasurements, true);
    schema.defineRule('isValidPropertyType', schemaRules.isValidPropertyType);
    schema.defineRule('isValidUnit', schemaRules.isValidUnit);
    schema.defineRule('isValidExperimentStatus', schemaRules.isValidExperimentStatus);
    schema.defineRule('oneOf', schemaRules.oneOf);
    schema.defineRule('mustNotStartWith', schemaRules.mustNotStartWith);
    schema.defineRule('mustNotExistInDirectory', schemaRules.mustNotExistInDirectory, true);
    schema.defineRule('mustNotExistInParentDirectory', schemaRules.mustNotExistInParentDirectory, true);
}

module.exports = {
    createSamples: samplesSchema.defineCreateSamplesSchema(),
    addSamplesMeasurements: samplesSchema.defineAddSamplesMeasurementsSchema(),
    samplesMeasurement: samplesSchema.defineSamplesMeasurementSchema(),
    measurement: samplesSchema.defineMeasurementSchema(),
    processes: processSchema.defineCreateProcessSchema(),
    updateProcess: processSchema.defineUpdateProcessSchema(),
    //measurements: measurementsSchema.defineMeasurementsSchema(),
    createDirectory: directorySchema.defineCreateDirectorySchema(),
    renameDirectory: directorySchema.defineRenameDirectorySchema(),
    moveDirectory: directorySchema.defineMoveDirectorySchema(),
    createExperiment: experimentSchema.defineCreateExperimentSchema(),
    updateExperiment: experimentSchema.defineUpdateExperimentSchema(),
    createExperimentTask: experimentSchema.defineCreateExperimentTaskSchema(),
    updateExperimentTask: experimentSchema.defineUpdateExperimentTaskSchema(),
    createExperimentNote: experimentSchema.defineCreateExperimentNoteSchema(),
    updateExperimentNote: experimentSchema.defineUpdateExperimentNoteSchema(),
    updateExperimentTaskTemplateProps: experimentSchema.defineUpdateExperimentTaskTemplatePropsSchema(),
    templateProperty: experimentSchema.defineTemplatePropertySchema(),
    templateCommand: experimentSchema.defineTemplateCommandSchema(),
    userAccountSchema: userSchema.defineUserAccountSchema(),
    createDatasetSchema: datasetSchema.defineCreateDatasetSchema(),
    updateDatasetSchema: datasetSchema.defineUpdateDatasetSchema(),
    datasetAuthor: datasetSchema.defineDatasetAuthorSchema(),
    datasetPaper: datasetSchema.defineDatasetPaperSchema(),
    validate,
    prepare
};
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict"

let DEBUG = 1;
if (DEBUG)
  debug = function (s) { dump("-*- adbService: " + s + "\n"); };
else
  debug = function (s) { };

const LOCAL_PORT = 10010;

const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;

const ADBSERVICE_CONTRACT_ID = '@mozilla.org/adbservice;1';
const ADBSERVICE_CID = Components.ID('{ed7c329e-5b45-4e99-bdae-f4d159a8edc8}');

Cu.import("resource://gre/modules/XPCOMUtils.jsm");

XPCOMUtils.defineLazyModuleGetter(this, 'ctypes', 'resource://gre/modules/ctypes.jsm');
XPCOMUtils.defineLazyModuleGetter(this, 'Services', 'resource://gre/modules/Services.jsm');
XPCOMUtils.defineLazyModuleGetter(this, 'SocketConn', 'resource://adbservice/conn.jsm');

XPCOMUtils.defineLazyGetter(this, 'libadb', function() {
  // TODO open platform related library.
  let fileUri = Services.io.newURI('resource://adbservice-components/libadbservice.so', null, null);

  if (fileUri instanceof Ci.nsIFileURL) {
    let library = ctypes.open(fileUri.file.path);
    return {
      findDevice: library.declare('findDevice', ctypes.default_abi, ctypes.int),
      setupDevice: library.declare('setupDevice', ctypes.default_abi, ctypes.int)
    };
  } else {
    return {
      findDevice: function libadb_fake_findDevice() {
        return 0;
      },

      setupDevice: function libadb_fake_setupDevice() {
        return 0;
      }
    };
  }
});

// Local connection to adb forward port
var _conn = null;
// Registered callbacks
var _registeredCallbacks = null;

function ADBService() { }

ADBService.prototype = {
  classID: ADBSERVICE_CID,

  classInfo: XPCOMUtils.generateCI({
               classID: ADBSERVICE_CID,
               contractID: ADBSERVICE_CONTRACT_ID,
               classDescription: "adbService",
               interfaces: [Ci.nsIADBService],
               flags: Ci.nsIClassInfo.DOM_OBJECT
             }),

  QueryInterface: XPCOMUtils.generateQI([Ci.nsIADBService, Ci.nsIDOMGlobalPropertyInitializer]),

  // nsIDOMGlobalPropertyInitializer implementation
  init: function(aWindow) {
    // TODO add privileges checking
  },

  /* implementation */
  register: function(options) {
    if (_conn == null) {
      if (!libadb.findDevice()) {
        throw 'No Device';
      }

      let success = libadb.setupDevice();
      if (!success) {
        throw 'Can not establish the adb forward.';
      }

      _conn = new SocketConn({
        host: '127.0.0.1',

        port: LOCAL_PORT,

        onStartRequest: function conn_onstart() {
          if (_registeredCallbacks && _registeredCallbacks.onopen) {
            _registeredCallbacks.onopen();
          }
        },

        onStopRequest: function conn_onstop() {
          _conn = null;
          if (_registeredCallbacks && _registeredCallbacks.onclose) {
            _registeredCallbacks.onclose();
          }
        },

        onMessage: function conn_onmessage(message) {
          if (_registeredCallbacks && _registeredCallbacks.onmessage) {
            _registeredCallbacks.onmessage(message);
          }
        }
      });

      try {
        _conn.connect();
      } catch (e) {
        debug('Error occurs when connecting: ' + e);
        if (_registeredCallbacks && _registeredCallbacks.onerror) {
          _registeredCallbacks.onerror(e);
        }
      }
    }

    _registeredCallbacks = options;
  },

  uregister: function(options) {
    debug('Uregister');
    _registeredCallbacks = null;
    _conn.stop();
    _conn = null;
  },

  sendMessage: function(obj) {
    if (_conn) {
      try {
      _conn.sendData(obj);
      } catch (e) {
        if (_registeredCallbacks && _registeredCallbacks.onerror) {
          _registeredCallbacks.onerror(e);
        }
      }
    } else {
      if (_registeredCallbacks && _registeredCallbacks.onerror) {
        _registeredCallbacks.onerror({
          data: 'No connection'
        });
      }
    }
  }
};

this.NSGetFactory = XPCOMUtils.generateNSGetFactory([ADBService]);

<commit_msg>Expose readonly object<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict"

let DEBUG = 1;
if (DEBUG)
  debug = function (s) { dump("-*- adbService: " + s + "\n"); };
else
  debug = function (s) { };

const LOCAL_PORT = 10010;

const {classes: Cc, interfaces: Ci, utils: Cu, results: Cr} = Components;

const ADBSERVICE_CONTRACT_ID = '@mozilla.org/adbservice;1';
const ADBSERVICE_CID = Components.ID('{ed7c329e-5b45-4e99-bdae-f4d159a8edc8}');

Cu.import("resource://gre/modules/XPCOMUtils.jsm");

XPCOMUtils.defineLazyModuleGetter(this, 'ctypes', 'resource://gre/modules/ctypes.jsm');
XPCOMUtils.defineLazyModuleGetter(this, 'Services', 'resource://gre/modules/Services.jsm');
XPCOMUtils.defineLazyModuleGetter(this, 'SocketConn', 'resource://adbservice/conn.jsm');

XPCOMUtils.defineLazyGetter(this, 'libadb', function() {
  // TODO open platform related library.
  let fileUri = Services.io.newURI('resource://adbservice-components/libadbservice.so', null, null);

  if (fileUri instanceof Ci.nsIFileURL) {
    let library = ctypes.open(fileUri.file.path);
    return {
      findDevice: library.declare('findDevice', ctypes.default_abi, ctypes.int),
      setupDevice: library.declare('setupDevice', ctypes.default_abi, ctypes.int)
    };
  } else {
    return {
      findDevice: function libadb_fake_findDevice() {
        return 0;
      },

      setupDevice: function libadb_fake_setupDevice() {
        return 0;
      }
    };
  }
});

function exposeReadOnly(obj) {
  if (null == obj) {
    return obj;
  }

  if (typeof obj !== "object") {
    return obj;
  }

  if (obj["__exposedProps__"]) {
    return obj;
  }

  // If the obj is a navite wrapper, can not modify the attribute.
  try {
    obj.__exposedProps__ = {};
  } catch (e) {
    return;
  }

  var exposedProps = obj.__exposedProps__;
  for (let i in obj) {
    if (i === "__exposedProps__") {
      continue;
    }

    if (i[0] === "_") {
      continue;
    }

    exposedProps[i] = "r";

    exposeReadOnly(obj[i]);
  }

  return obj;
};

// Local connection to adb forward port
var _conn = null;
// Registered callbacks
var _registeredCallbacks = null;

function ADBService() { }

ADBService.prototype = {
  classID: ADBSERVICE_CID,

  classInfo: XPCOMUtils.generateCI({
               classID: ADBSERVICE_CID,
               contractID: ADBSERVICE_CONTRACT_ID,
               classDescription: "adbService",
               interfaces: [Ci.nsIADBService],
               flags: Ci.nsIClassInfo.DOM_OBJECT
             }),

  QueryInterface: XPCOMUtils.generateQI([Ci.nsIADBService, Ci.nsIDOMGlobalPropertyInitializer]),

  // nsIDOMGlobalPropertyInitializer implementation
  init: function(aWindow) {
    // TODO add privileges checking
  },

  _sendError: function(error) {
    if (_registeredCallbacks && _registeredCallbacks.onerror) {
      _registeredCallbacks.onerror(exposeReadOnly(error));
    }
  },

  /* implementation */
  register: function(options) {
    _registeredCallbacks = options;

    if (_conn == null) {
      if (!libadb.findDevice()) {
        this._sendError({
          data: 'No Device'
        });
        return;
      }

      let success = libadb.setupDevice();
      if (!success) {
        this._sendError({
          data: 'Can not establish the adb forward'
        });
        return;
      }

      _conn = new SocketConn({
        host: '127.0.0.1',

        port: LOCAL_PORT,

        onStartRequest: function conn_onstart() {
          if (_registeredCallbacks && _registeredCallbacks.onopen) {
            _registeredCallbacks.onopen();
          }
        },

        onStopRequest: function conn_onstop() {
          _conn = null;
          if (_registeredCallbacks && _registeredCallbacks.onclose) {
            _registeredCallbacks.onclose();
          }
        },

        onMessage: function conn_onmessage(message) {
          if (_registeredCallbacks && _registeredCallbacks.onmessage) {
            _registeredCallbacks.onmessage(exposeReadOnly(message));
          }
        }
      });

      try {
        _conn.connect();
      } catch (e) {
        debug('Error occurs when connecting: ' + e);
        this._sendError(e);
      }
    }
  },

  uregister: function(options) {
    debug('Uregister');
    _registeredCallbacks = null;
    _conn.stop();
    _conn = null;
  },

  sendMessage: function(obj) {
    if (_conn) {
      try {
        _conn.sendData(obj);
      } catch (e) {
        this._sendError(e);
      }
    } else {
      this._sendError({
        data: 'No connection'
      });
    }
  }
};

this.NSGetFactory = XPCOMUtils.generateNSGetFactory([ADBService]);

<|endoftext|>