text:
import logging

from rdmo.core.imports import (fetch_parents, get_foreign_field,
                               set_common_fields, validate_instance)

from .models import Attribute
from .validators import (AttributeLockedValidator, AttributeParentValidator,
                         AttributeUniqueURIValidator)

logger = logging.getLogger(__name__)

def import_attribute(element, parent_uri=False, save=False):
    try:
        if parent_uri is False:
            attribute = Attribute.objects.get(uri=element.get('uri'))
        else:
            attribute = Attribute.objects.get(key=element.get('key'), parent__uri=parent_uri)
    except Attribute.DoesNotExist:
        attribute = Attribute()

    set_common_fields(attribute, element)

    attribute.parent = get_foreign_field(attribute, parent_uri or element.get('parent'), Attribute)

    if save and validate_instance(attribute,
                                  AttributeLockedValidator,
                                  AttributeParentValidator,
                                  AttributeUniqueURIValidator):
        if attribute.id:
            logger.debug('Attribute created with uri %s.', element.get('uri'))
        else:
            logger.debug('Attribute %s updated.', element.get('uri'))

        attribute.save()
        attribute.imported = True

    return attribute

def fetch_attribute_parents(instances):
    return fetch_parents(Attribute, instances)

redpajama_set_name: RedPajamaGithub


text:
function NccMenuActionType() {
    this.Url = "Url";
    this.Page = "Page";
    this.BlogPost = "BlogPost";
    this.BlogCategory = "BlogCategory";
    this.Module = "Module";
    this.Tag = "Tag";
}

function NccMenuItemFor() {
    this.Site = "Site";
    this.Admin = "Admin";
}

function NccMenuItemTarget() {
    this.Blank = "_blank";
    this.Parent = "_parent";
    this.Self = "_self";
    this.Top = "_top";
}

function NccMenu() {
    this.Id = 0;
    this.Name = "";
    this.Position = "";
    this.MenuFor = "";
    this.Items = new Array();
}

function NccMenuItem() {
    this.Id = 0;
    this.ParentId = 0;
    this.Title;
    this.Type;
    this.Module = "";
    this.Area = "";
    this.Controller;
    this.Action;
    this.Data;
    this.Url;
    this.Target;
    this.Order = 0;
    this.Childrens = new Array();
}

function RemoveMenuItem(element) {
    var parent = $(element).parentsUntil(".list-group-item");
    parent.parent().remove();
}

function ShowEditor(src, dest) {
    var txtSpan = $("#" + src);
    var val = "";
    var newVal = "";
    if (txtSpan.is(":visible")) {
        val = txtSpan.html();
        txtSpan.hide();
    }
    else {
        txtSpan.show();
    }

    var next = $("#" + dest);
    if (next.is(":visible")) {
        newVal = next.val();
        console.log(newVal);
        next.val("");
        next.hide();
    }
    else {
        next.show();
        next.val(val);
        next.on("blur", function () {
            txtSpan.show();
            txtSpan.html(next.val());
            var li = txtSpan.closest("li");
            li.attr("ncc-menu-item-title", next.val());
            next.hide();
        });
    }

    setTimeout(function () {
        txtSpan.html(newVal);
        var li = txtSpan.closest("li");
        console.log(li);
        li.attr("ncc-menu-item-title", newVal);
    }, 50);

};

$(document).ready(function () {

    function toggleIcon(e) {
        $(e.target)
            .prev('.panel-heading')
            .find(".more-less")
            .toggleClass('glyphicon-chevron-down glyphicon-chevron-up');
    }
    $('.panel-group').on('hidden.bs.collapse', toggleIcon);
    $('.panel-group').on('shown.bs.collapse', toggleIcon);

    $('#selectedMenuTree').nestedSortable({
        handle: 'div',
        items: 'li',
        listType: 'ul',
        opacity: .6,
        toleranceElement: '> div',
        stop: function (event, ui) {
            console.log('new parent ' + ui.item.closest('ul').closest('li').attr('name'));
        }
    });

    $('#selectedMenuTree li').droppable({
        drop: function (event, ui) {
            console.log(ui);
            console.log($(this).text());
        }
    });

    function getMenuItemFromLi(listItem) {
        var mi          = new NccMenuItem();
        mi.Id           = $(listItem).attr("ncc-menu-item-id");
        mi.Title        = $(listItem).attr("ncc-menu-item-title");
        mi.Type         = $(listItem).attr("ncc-menu-item-action-type");
        mi.Controller   = $(listItem).attr("ncc-menu-item-controller");
        mi.Action       = $(listItem).attr("ncc-menu-item-action");
        mi.Data         = $(listItem).attr("ncc-menu-item-action-data");
        mi.Url          = $(listItem).attr("ncc-menu-item-url");
        mi.Target       = $(listItem).attr("ncc-menu-item-target");
        mi.Order        = $(listItem).attr("ncc-menu-item-order");
        mi.Module        = $(listItem).attr("ncc-menu-item-module");
        return mi;
    }

    function getMenuTree(parentUl, parent, position) {

        var order = position;
        var menuItemList = new Array();

        $(parentUl).children().each(function (index) {

            var menuItem = getMenuItemFromLi($(this));
            if (parent != null) {
                menuItem.ParentId = parent.Id;
            }
            menuItem.Order = order;
            order = order + 1;

            var ul = $(this).find(" > ul");
            if (ul.length > 0) {
                var menuItems = getMenuTree(ul, menuItem, order);
                $(menuItems).each(function (index) {
                    menuItem.Childrens.push(menuItems[index]);
                });
            }

            menuItemList.push(menuItem);
        });

        return menuItemList;
    }

    /*Page section start*/
    $("#selectAllPages").on("click", function () {
        $(".pageList .active").find("input[type='checkbox']").each(function (i, ob) {
            $(ob).prop("checked",true);
        });
    });
    $("#addPageToMenu").on("click", function () {
        $(".recentPagesCheckBoxList").each(function (index) {
            if ($(this).prop("checked") == true) {
                var src = GUID.NewGUID();
                var dest = GUID.NewGUID();
                var menuItem = '
'
                    + '
'
                    + '
'
                    + '{TITLE}
'
                    + '<input id="' + dest + '" class="ncc-menu-title-editor" type="text" style="display:none" />'
                    + '   '
                    + '<input type="button" class="closeMenuItem pull-right" value="x" onclick="RemoveMenuItem(this)" ></input>'
                    + '
'
                    + '
 ';
                menuItem = menuItem.replace("{MENU_ITEM_ID}", "0");
                menuItem = menuItem.replace("{MODEL_ID}", $(this).attr("value"));
                menuItem = menuItem.replace("{ACTION_TYPE}", "Page");
                menuItem = menuItem.replace("{CONTROLLER}", "CmsPage");
                menuItem = menuItem.replace("{ACTION}", "Index");
                menuItem = menuItem.replace("{DATA}", $(this).attr("value"));
                menuItem = menuItem.replace("{URL}", $(this).attr("ncc-slug"));
                menuItem = menuItem.replace("{TARGET}", "_self");
                menuItem = menuItem.replace("{ORDER}", 0);
                menuItem = menuItem.replace(/\{TITLE}/g, $(this).attr("ncc-title"));
                $("#selectedMenuTree").append($($.parseHTML(menuItem)));
                $(this).prop("checked", false);
            }
        });
    });
    var searchPageLastKey = "";
    function searchPage() {
        var searchKey = $("#searchPage").val();
        var languageKey = $("#languagePage").val();
        if (searchKey != (searchPageLastKey + languageKey)) {
            $("#searchPagesCheckBoxList").html("");
            if (searchKey != "") {
                $('#searchPagesCheckBoxList').append($('
Searching ... '));
            }
        }
        setTimeout(function () {
            var searchKey1 = $("#searchPage").val();
            //console.log(searchKey1);
            if (searchKey != "" && searchKey == searchKey1 && searchKey != (searchPageLastKey + languageKey)) {
                searchPageLastKey = searchKey + languageKey;
                $.ajax({
                    type: "POST",
                    url: "/CmsMenu/LoadPages",
                    data: { name: searchKey, lang: languageKey },
                    success: function (rsp) {
                        //console.log(rsp);
                        if (rsp.isSuccess) {
                            //NccAlert.ShowSuccess(rsp.message);
                            $("#searchPagesCheckBoxList").html("");
                            $.each(rsp.data, function (i, v) {
                                $('#searchPagesCheckBoxList').append($('
<input type="checkbox" class="recentPagesCheckBoxList" value="' + v.id + '" ncc-title="' + v.title + '" ncc-slug="' + v.slug + '">' + v.title + '
'));
                            });
                        }
                        else {
                            $("#searchPagesCheckBoxList").html("");
                            //NccAlert.ShowError("Error: " + rsp.message);
                            $('#searchPagesCheckBoxList').append($('
No result found'));
                        }
                    },
                    error: function (errorThrown) {
                        //NccAlert.ShowError("Error. Please try again.");
                    }
                });
            }
        }, 1000);
    }
    $("#searchPage").on("change keyup paste", function () {
        searchPage();
    });
    $("#languagePage").on("change", function () {
        searchPage();
    });
    /*Page section end*/

    /*Post section start*/
    $("#selectAllPosts").on("click", function () {
        $(".postList .active").find("input[type='checkbox']").each(function (i, ob) {
            $(ob).prop("checked", true);
        });
    });
    $("#addPostToMenu").on("click", function () {
        $(".recentPostCheckBoxList").each(function (index) {
            if ($(this).prop("checked") == true) {
                var src = GUID.NewGUID();
                var dest = GUID.NewGUID();
                var menuItem = '
'
                    + '
'
                    + '
'
                    + '{TITLE}
'
                    + '<input id="' + dest + '" class="ncc-menu-title-editor" type="text" style="display:none" />'
                    + '   '
                    + '<input type="button" class="closeMenuItem pull-right" value="x" onclick="RemoveMenuItem(this)" ></input>'
                    + '
'
                    + '
 ';
                menuItem = menuItem.replace("{MENU_ITEM_ID}", "0");
                menuItem = menuItem.replace("{MODEL_ID}", $(this).attr("value"));
                menuItem = menuItem.replace("{ACTION_TYPE}", "BlogPost");
                menuItem = menuItem.replace("{CONTROLLER}", "Post");
                menuItem = menuItem.replace("{ACTION}", "Index");
                menuItem = menuItem.replace("{DATA}", $(this).attr("value"));
                menuItem = menuItem.replace("{URL}", "Post/" + $(this).attr("ncc-slug"));
                menuItem = menuItem.replace("{TARGET}", "_self");
                menuItem = menuItem.replace("{ORDER}", 0);
                menuItem = menuItem.replace(/\{TITLE}/g, $(this).attr("ncc-title"));

                $("#selectedMenuTree").append($($.parseHTML(menuItem)));
                $(this).prop("checked", false);
            }
        });
    });
    var searchPostLastKey = "";
    function searchPost() {
        var searchKey = $("#searchPost").val();
        var languageKey = $("#languagePost").val();
        if (searchKey != (searchPostLastKey + languageKey)) {
            $("#searchPostsCheckBoxList").html("");
            if (searchKey != "") {
                $('#searchPostsCheckBoxList').append($('
Searching ... '));
            }
        }

        setTimeout(function () {
            var searchKey1 = $("#searchPost").val();
            //console.log(searchKey1);
            if (searchKey != "" && searchKey == searchKey1 && searchKey != (searchPostLastKey + languageKey)) {
                searchPostLastKey = searchKey + languageKey;
                $.ajax({
                    type: "POST",
                    url: "/CmsMenu/LoadPosts",
                    data: { name: searchKey, lang: languageKey },
                    success: function (rsp) {
                        //console.log(rsp);
                        if (rsp.isSuccess) {
                            $("#searchPostsCheckBoxList").html("");
                            //NccAlert.ShowSuccess(rsp.message);
                            $.each(rsp.data, function (i, v) {
                                $('#searchPostsCheckBoxList').append($('
<input type="checkbox" class="recentPostCheckBoxList" value="' + v.id + '" ncc-title="' + v.title + '" ncc-slug="' + v.slug + '">' + v.title + '
'));
                            });
                        }
                        else {
                            $("#searchPostsCheckBoxList").html("");
                            //NccAlert.ShowError("Error: " + rsp.message);
                            $('#searchPostsCheckBoxList').append($('
No result found'));
                        }
                    },
                    error: function (errorThrown) {
                        NccAlert.ShowError("Error. Please try again.");
                    }
                });
            }
        }, 1000);
    }
    $("#searchPost").on("change keyup paste", function () {
        searchPost();
    });
    $("#languagePost").on("change", function () {
        searchPost();
    });
    /*Post section end*/

    /*Category section start*/
    $("#selectAllCategories").on("click", function () {
        $(".categoryList .active").find("input[type='checkbox']").each(function (i, ob) {
            $(ob).prop("checked", true);
        });
    });
    $("#addCategoryToMenu").on("click", function () {
        $(".recentCategoryCheckBoxList").each(function (index) {
            if ($(this).prop("checked") == true) {
                var src = GUID.NewGUID();
                var dest = GUID.NewGUID();
                var menuItem = '
'
                    + '
'
                    + '
'
                    + '{TITLE}
'
                    + '<input id="' + dest + '" class="ncc-menu-title-editor" type="text" style="display:none" />'
                    + '   '
                    + '<input type="button" class="closeMenuItem pull-right" value="x" onclick="RemoveMenuItem(this)" ></input>'
                    + '
'
                    + '
 ';
                menuItem = menuItem.replace("{MENU_ITEM_ID}", "0");
                menuItem = menuItem.replace("{MODEL_ID}", $(this).attr("value"));
                menuItem = menuItem.replace("{ACTION_TYPE}", "BlogCategory");
                menuItem = menuItem.replace("{CONTROLLER}", "Category");
                menuItem = menuItem.replace("{ACTION}", "Index");
                menuItem = menuItem.replace("{DATA}", $(this).attr("value"));
                menuItem = menuItem.replace("{URL}", "Category/"+$(this).attr("ncc-slug"));
                menuItem = menuItem.replace("{TARGET}", "_self");
                menuItem = menuItem.replace("{ORDER}", 0);
                menuItem = menuItem.replace(/\{TITLE}/g, $(this).attr("ncc-title"));

                $("#selectedMenuTree").append($($.parseHTML(menuItem)));
                $(this).prop("checked", false);
            }
        });
    });
    var searchCategoryLastKey = "";
    function searchCategory() {
        var searchKey = $("#searchCategory").val();
        var languageKey = $("#languageCategory").val();
        if (searchKey != (searchCategoryLastKey + languageKey)) {
            $("#searchCategoriesCheckBoxList").html("");
            if (searchKey != "") {
                $('#searchCategoriesCheckBoxList').append($('
Searching ... '));
            }
        }
        setTimeout(function () {
            var searchKey1 = $("#searchCategory").val();
            //console.log(searchKey1);
            if (searchKey != "" && searchKey == searchKey1 && searchKey != (searchCategoryLastKey + languageKey)) {
                searchCategoryLastKey = searchKey + languageKey;
                $.ajax({
                    type: "POST",
                    url: "/CmsMenu/LoadCategories",
                    data: { name: searchKey, lang: languageKey },
                    success: function (rsp) {
                        //console.log(rsp);
                        if (rsp.isSuccess) {
                            $("#searchCategoriesCheckBoxList").html("");
                            //NccAlert.ShowSuccess(rsp.message);
                            $.each(rsp.data, function (i, v) {
                                $('#searchCategoriesCheckBoxList').append($('
<input type="checkbox" class="recentCategoryCheckBoxList" value="' + v.id + '" ncc-title="' + v.name + '" ncc-slug="' + v.slug + '">' + v.name + '
'));
                            });
                        }
                        else {
                            $("#searchCategoriesCheckBoxList").html("");
                            //NccAlert.ShowError("Error: " + rsp.message);
                            $('#searchCategoriesCheckBoxList').append($('
No result found'));
                        }
                    },
                    error: function (errorThrown) {
                        NccAlert.ShowError("Error. Please try again.");
                    }
                });
            }
        }, 1000);
    }
    $("#searchCategory").on("change keyup paste", function () {
        searchCategory();
    });
    $("#languageCategory").on("change", function () {
        searchCategory();
    });
    /*Category section end*/

    /*Module section start*/
    $("#selectAllModules").on("click", function () {
        $(".moduleList .active").find("input[type='checkbox']").each(function (i, ob) {
            $(ob).prop("checked", true);
        });
    });

    $("#addModuleToMenu").on("click", function () {
        $(".allModuleCheckBoxList").each(function (index) {
            if ($(this).prop("checked") == true) {
                var src = GUID.NewGUID();
                var dest = GUID.NewGUID();
                var menuItem = '
'
                    + '
'
                    + '
'
                    + '{TITLE}
'
                    + '<input id="' + dest + '" class="ncc-menu-title-editor" type="text" style="display:none" />'
                    + '   '
                    + '<input type="button" class="closeMenuItem pull-right" value="x" onclick="RemoveMenuItem(this)" ></input>'
                    + '
'
                    + '
 ';
                menuItem = menuItem.replace("{MENU_ITEM_ID}", "0");
                menuItem = menuItem.replace("{MODEL_ID}", "0");
                menuItem = menuItem.replace("{ACTION_TYPE}", "Module");
                menuItem = menuItem.replace("{CONTROLLER}", "");
                menuItem = menuItem.replace("{ACTION}", "");
                menuItem = menuItem.replace("{DATA}", $(this).attr("value"));
                menuItem = menuItem.replace("{URL}", $(this).attr("value"));
                menuItem = menuItem.replace("{TARGET}", "_self");
                menuItem = menuItem.replace("{ORDER}", 0);
                menuItem = menuItem.replace(/\{TITLE}/g, $(this).attr("ncc-title"));
                var moduleName = $(this).attr("data-module-name");
                if (moduleName == null || moduleName == undefined)
                    moduleName = "";
                menuItem = menuItem.replace("{MODULE_NAME}", moduleName);

                $("#selectedMenuTree").append($($.parseHTML(menuItem)));
                $(this).prop("checked", false);
            }
        });
    });

    var searchModuleLastKey = "";
    function searchModule() {
        var searchKey = $("#searchModule").val();
        if (searchKey != (searchModuleLastKey)) {
            $("#searchModulesCheckBoxList").html("");
            if (searchKey != "") {
                $('#searchModulesCheckBoxList').append($('
Searching ... '));
            }
        }
        setTimeout(function () {
            var searchKey1 = $("#searchModule").val();
            //console.log(searchKey1);
            if (searchKey != "" && searchKey == searchKey1 && searchKey != (searchModuleLastKey)) {
                searchModuleLastKey = searchKey;
                $.ajax({
                    type: "POST",
                    url: "/CmsMenu/LoadModules",
                    data: { name: searchKey },
                    success: function (rsp) {
                        //console.log(rsp);
                        if (rsp.isSuccess) {
                            $("#searchModulesCheckBoxList").html("");
                            //NccAlert.ShowSuccess(rsp.message);
                            var isFirstMenu = true;
                            var lastModuleName = "";
                            $.each(rsp.data, function (i, v) {
                                if (lastModuleName != v.moduleName) {
                                    lastModuleName = v.moduleName;
                                    if (isFirstMenu == true) {
                                        $('#searchModulesCheckBoxList').append('

 ' + v.moduleName + '

');
                                        isFirstMenu = false;
                                    }
                                    else {
                                        $('#searchModulesCheckBoxList').append('

 ' + v.moduleName + '

');
                                    }
                                }
                                $('#searchModulesCheckBoxList').append($('
<input type="checkbox" class="allModuleCheckBoxList" data-module-name="' + v.moduleName+'" value="' + v.menuUrl + '" ncc-title="' + v.menuItemName + '" >' + v.menuItemName + '
'));
                            });
                            $('#searchModulesCheckBoxList').append('
');
                        }
                        else {
                            $("#searchModulesCheckBoxList").html("");
                            //NccAlert.ShowError("Error: " + rsp.message);
                            $('#searchModulesCheckBoxList').append($('
No result found'));
                        }
                    },
                    error: function (errorThrown) {
                        NccAlert.ShowError("Error. Please try again.");
                    }
                });
            }
        }, 1000);
    }
    $("#searchModule").on("change keyup paste", function () {
        searchModule();
    });
    /*Module section end*/

    /*Tag section start*/
    $("#selectAllTags").on("click", function () {
        $(".tagList .active").find("input[type='checkbox']").each(function (i, ob) {
            $(ob).prop("checked", true);
        });
    });
    $("#addTagToMenu").on("click", function () {
        $(".recentTagCheckBoxList").each(function (index) {
            if ($(this).prop("checked") == true) {
                var src = GUID.NewGUID();
                var dest = GUID.NewGUID();
                var menuItem = '
'
                    + '
'
                    + '
'
                    + '{TITLE}
'
                    + '<input id="' + dest + '" class="ncc-menu-title-editor" type="text" style="display:none" />'
                    + '   '
                    + '<input type="button" class="closeMenuItem pull-right" value="x" onclick="RemoveMenuItem(this)" ></input>'
                    + '
'
                    + '
 ';
                menuItem = menuItem.replace("{MENU_ITEM_ID}", "0");
                menuItem = menuItem.replace("{MODEL_ID}", $(this).attr("value"));
                menuItem = menuItem.replace("{ACTION_TYPE}", "Tag");
                menuItem = menuItem.replace("{CONTROLLER}", "Tags");
                menuItem = menuItem.replace("{ACTION}", "Index");
                menuItem = menuItem.replace("{DATA}", $(this).attr("value"));
                menuItem = menuItem.replace("{URL}", "Tags/?name=" + $(this).attr("ncc-title"));
                menuItem = menuItem.replace("{TARGET}", "_self");
                menuItem = menuItem.replace("{ORDER}", 0);
                menuItem = menuItem.replace(/\{TITLE}/g, $(this).attr("ncc-title"));

                $("#selectedMenuTree").append($($.parseHTML(menuItem)));
                $(this).prop("checked", false);
            }
        });
    });
    var searchTagLastKey = "";
    function searchTag() {
        var searchKey = $("#searchTag").val();
        if (searchKey != (searchTagLastKey)) {
            $("#searchTagsCheckBoxList").html("");
            if (searchKey != "") {
                $('#searchTagsCheckBoxList').append($('
Searching ... '));
            }
        }
        setTimeout(function () {
            var searchKey1 = $("#searchTag").val();
            //console.log(searchKey1);
            if (searchKey != "" && searchKey == searchKey1 && searchKey != (searchTagLastKey)) {
                searchTagLastKey = searchKey;
                $.ajax({
                    type: "POST",
                    url: "/CmsMenu/LoadTags",
                    data: { name: searchKey },
                    success: function (rsp) {
                        //console.log(rsp);
                        if (rsp.isSuccess) {
                            $("#searchTagsCheckBoxList").html("");
                            //NccAlert.ShowSuccess(rsp.message);
                            $.each(rsp.data, function (i, v) {
                                $('#searchTagsCheckBoxList').append($('
<input type="checkbox" class="recentTagCheckBoxList" value="' + v.id + '" ncc-title="' + v.name + '" ncc-slug="">' + v.name + '
'));
                            });
                        }
                        else {
                            $("#searchTagsCheckBoxList").html("");
                            //NccAlert.ShowError("Error: " + rsp.message);
                            $('#searchTagsCheckBoxList').append($('
No result found'));
                        }
                    },
                    error: function (errorThrown) {
                        NccAlert.ShowError("Error. Please try again.");
                    }
                });
            }
        }, 1000);
    }
    $("#searchTag").on("change keyup paste", function () {
        searchTag();
    });
    /*Tag section end*/

    $("#addUrlToMenu").on("click", function () {
        var urlMenuName = $("#urlMenuName").val();
        var urlMenuUrl = $("#urlMenuUrl").val();
        var urlMenuTarget = $("#urlMenuTarget").val();
        if (urlMenuName != "" && urlMenuUrl != "") {

            var src = GUID.NewGUID();
            var dest = GUID.NewGUID();

            var menuItem = '
'
                + '
'
                + '
'
                + '{TITLE}
'
                + '<input id="'+dest+'" class="ncc-menu-title-editor" type="text" style="display:none" />'
                + '   '
                + '<input type="button" class="closeMenuItem pull-right" value="x" onclick="RemoveMenuItem(this)" ></input>'
                + '
'
                + '
 ';
            menuItem = menuItem.replace("{MENU_ITEM_ID}", "0");
            menuItem = menuItem.replace("{MODEL_ID}", "");
            menuItem = menuItem.replace("{ACTION_TYPE}", "");
            menuItem = menuItem.replace("{CONTROLLER}", "");
            menuItem = menuItem.replace("{ACTION}", "");
            menuItem = menuItem.replace("{DATA}", "");
            menuItem = menuItem.replace("{URL}", urlMenuUrl);
            menuItem = menuItem.replace("{TARGET}", urlMenuTarget);
            menuItem = menuItem.replace("{ORDER}", 0);
            menuItem = menuItem.replace(/\{TITLE}/g, urlMenuName);

            $("#selectedMenuTree").append($($.parseHTML(menuItem)));
            $("#urlMenuName").val("");
            $("#urlMenuUrl").val("");
            $("#urlMenuTarget").val("_self");
        }
    });

    $("#saveMenuBtn").on("click", function () {

        var menuItemTree = getMenuTree($("ul#selectedMenuTree"), null, 1);

        var menu = new NccMenu();
        menu.Id = $("#menuId").val();
        $(menuItemTree).each(function (index) {
            menu.Items.push(menuItemTree[index]);
        });

        menu.Name = $("#menuName").val();
        menu.Position = $("#menuLocation").val();
        menu.MenuFor = $("#menuFor").val();
        menu.MenuLanguage = $("#menuLanguage").val();

        NccPageMask.ShowLoadingMask();

        var menuJson = JSON.stringify(menu);
        console.log(menuJson);

        $.ajax({
            type: "POST",
            url: "/CmsMenu/CreateEditMenu",
            data: { model : menuJson },
            success: function (rsp, textStatus, jqXHR) {
                NccPageMask.HideLoadingMask();
                if (rsp.isSuccess) {
                    NccAlert.ShowSuccess(rsp.message);
                }
                else {
                    NccAlert.ShowError("Error: " + rsp.message);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                NccPageMask.HideLoadingMask();
                NccAlert.ShowError("Error. Please try again.");
            }
        });

    });
});


text:
struct udev_device;

namespace base {
class FilePath;
}

namespace storage_monitor {

// Helper for udev_device_new_from_syspath()/udev_device_get_property_value()
// pair. |device_path| is the absolute path to the device, including /sys.
bool GetUdevDevicePropertyValueByPath(const base::FilePath& device_path,
                                      const char* key,
                                      std::string* result);

}  // namespace storage_monitor

#endif  // COMPONENTS_STORAGE_MONITOR_UDEV_UTIL_LINUX_H_


text:
<title>Paged Table Page</title>

seven

eight

<wicket:panel>
	<<
	<

		1

		2

		3

		4

	>
	>>
</wicket:panel>


text:
/*
 * This source file is subject to the license that is bundled with this package in the file LICENSE.
 */
package com.montealegreluis.yelpv3.reviews;

import java.net.URL;
import java.util.Date;

public class Review {
    public final int rating;
    public final User user;
    public final String text;
    public final Date createdAt;
    public final URL url;

    public Review(int rating, User user, String text, Date createdAt, URL url) {
        this.rating = rating;
        this.user = user;
        this.text = text;
        this.createdAt = createdAt;
        this.url = url;
    }
}


text:
int main (int argc, char *argv[])
{
    zmq::context_t context(1);

    //  Socket to receive messages on
    zmq::socket_t receiver(context, ZMQ_PULL);
    receiver.connect("tcp://localhost:5557");

    //  Socket to send messages to
    zmq::socket_t sender(context, ZMQ_PUSH);
    sender.connect("tcp://localhost:5558");

    //  Socket for control input
    zmq::socket_t controller (context, ZMQ_SUB);
    controller.connect("tcp://localhost:5559");
   	controller.setsockopt(ZMQ_SUBSCRIBE, "", 0);

    //  Process messages from receiver and controller
    zmq::pollitem_t items [] = {
        { receiver, 0, ZMQ_POLLIN, 0 },
        { controller, 0, ZMQ_POLLIN, 0 }
    };
    //  Process messages from both sockets
    while (1) {
        zmq::message_t message;
        zmq::poll (&items [0], 2, -1);

        if (items [0].revents & ZMQ_POLLIN) {
			receiver.recv(&message);

            //  Process task
            int workload;           //  Workload in msecs

            std::string sdata(static_cast<char*>(message.data()), message.size());
            std::istringstream iss(sdata);
            iss >> workload;

            //  Do the work
            s_sleep(workload);

            //  Send results to sink
            message.rebuild();
            sender.send(message);

            //  Simple progress indicator for the viewer
            std::cout << "." << std::flush;

        }
        //  Any waiting controller command acts as 'KILL'
        if (items [1].revents & ZMQ_POLLIN)
        {
        	std::cout << std::endl;
            break;                      //  Exit loop
    	}
    }
    //  Finished
    return 0;
}


text:
package org.springframework.social.github.api;

import java.util.List;

/**
 * Interface defining the operations for working with GitHub repositories.
 *
 * @author Willie Wheeler (willie.wheeler@gmail.com)
 */
public interface RepoOperations {

	/**
	 * Public operation to return a repo.
	 *
	 * @param user GitHub user
	 * @param repo GitHub repo
	 * @return repo
	 */
	GitHubRepo getRepo(String user, String repo);

	/**
	 * Public operation to return a list of collaborators for the given repository.
	 *
	 * @param user GitHub user
	 * @param repo GitHub repository
	 * @return list of collaborators
	 */
	List<GitHubUser> getCollaborators(String user, String repo);

	/**
	 * Public operation to return a list of commits for the given repository.
	 *
	 * @param user GitHub user
	 * @param repo GitHub repository
	 * @return list of commits
	 */
	List<GitHubCommit> getCommits(String user, String repo);

	/**
	 * Public operation to return a list of downloads for the given repository.
	 *
	 * @param user GitHub user
	 * @param repo GitHub repository
	 * @return list of downloads
	 */
	List<GitHubDownload> getDownloads(String user, String repo);

	/**
	 * Public operation to return a single download.
	 *
	 * @param user GitHub user
	 * @param repo GitHub repository
	 * @param id download ID
	 * @return download
	 */
	GitHubDownload getDownload(String user, String repo, Long id);

	/**
	 * Public operation to return the forks for the given repository.
	 *
	 * @param user GitHub user
	 * @param repo GitHub repository
	 * @return list of repository forks
	 */
	List<GitHubRepo> getForks(String user, String repo);

	/**
	 * Public operation to return the forks for the given repository.
	 *
	 * @param user GitHub user
	 * @param repo GitHub repository
	 * @return list of repository issues
	 */
	List<GitHubIssue> getIssues(String user, String repo);

	/**
	 * Public operation to return a list of watchers for the given repository.
	 *
	 * @param user GitHub user
	 * @param repo GitHub repository
	 * @return list of watchers
	 */
	List<GitHubUser> getWatchers(String user, String repo);

	/**
	 * Authorized operation to return a list of hooks for the given repository.
	 *
	 * @param user GitHub user
	 * @param repo GitHub repository
	 * @return list of hooks
	 */
	List<GitHubHook> getHooks(String user, String repo);
}


text:
namespace CryptoNote {

bool validateAddress(const std::string& address, const CryptoNote::Currency& currency) {
  CryptoNote::AccountPublicAddress ignore;
  return currency.parseAccountAddressString(address, ignore);
}

}


text:
package provision

import (
	"context"
	"crypto/sha256"
	"fmt"
	"regexp"
	"strconv"
	"strings"

	"github.com/tsuru/tsuru/set"
	"k8s.io/apimachinery/pkg/util/validation"
)

const (
	LabelIsBuild  = "is-build"
	LabelIsDeploy = "is-deploy"

	labelIsTsuru           = "is-tsuru"
	labelIsStopped         = "is-stopped"
	labelIsAsleep          = "is-asleep"
	labelIsIsolatedRun     = "is-isolated-run"
	labelIsIsolatedRunNew  = "is-isolated-run-version"
	labelIsNodeContainer   = "is-node-container"
	labelIsService         = "is-service"
	labelIsHeadlessService = "is-headless-service"
	labelIsRoutable        = "is-routable"

	LabelAppName      = "app-name"
	LabelAppProcess   = "app-process"
	LabelAppPool      = "app-pool"
	LabelAppPlatform  = "app-platform"
	LabelAppVersion   = "app-version"
	LabelAppTeamOwner = "app-team"

	labelNodeContainerName = "node-container-name"
	labelNodeContainerPool = "node-container-pool"

	labelNodeInternalPrefix = "internal-"
	labelNodeAddr           = labelNodeInternalPrefix + "node-addr"
	LabelNodePool           = PoolMetadataName
	labelNodeIaaSID         = IaaSIDMetadataName

	labelVolumeName = "volume-name"
	labelVolumePool = "volume-pool"
	labelVolumePlan = "volume-plan"
	labelVolumeTeam = "volume-team"

	labelBuildImage = "build-image"
	labelRestarts   = "restarts"

	labelProvisioner = "provisioner"

	labelBuilder = "builder"

	labelClusterMetadata = "tsuru.io/cluster"

	labelCustomTagsPrefix = "custom-tag-"
)

type LabelSet struct {
	Labels    map[string]string
	RawLabels map[string]string
	Prefix    string
}

func (s *LabelSet) DeepCopy() *LabelSet {
	newLabels := &LabelSet{Prefix: s.Prefix}
	newLabels.Labels = make(map[string]string)
	newLabels.RawLabels = make(map[string]string)
	for k, v := range s.Labels {
		newLabels.Labels[k] = v
	}
	for k, v := range s.RawLabels {
		newLabels.RawLabels[k] = v
	}
	return newLabels
}

func (s *LabelSet) Merge(override *LabelSet) *LabelSet {
	if s == nil {
		return nil
	}
	l := s.DeepCopy()
	if override == nil {
		return l
	}
	for k, v := range override.Labels {
		l.Labels[k] = v
	}
	for k, v := range override.RawLabels {
		l.RawLabels[k] = v
	}
	if override.Prefix != "" {
		l.Prefix = override.Prefix
	}
	return l
}

func (s *LabelSet) ToLabels() map[string]string {
	result := withPrefix(s.Labels, s.Prefix)
	for k, v := range s.RawLabels {
		result[k] = v
	}
	return result
}

func (s *LabelSet) ToVersionSelector() map[string]string {
	return withPrefix(subMap(s.Labels, LabelAppName, LabelAppProcess, LabelIsBuild, labelIsIsolatedRun, labelIsIsolatedRunNew, LabelAppVersion), s.Prefix)
}

func (s *LabelSet) ToBaseSelector() map[string]string {
	return withPrefix(subMap(s.Labels, LabelAppName, LabelAppProcess, LabelIsBuild, labelIsIsolatedRun), s.Prefix)
}

func (s *LabelSet) ToAllVersionsSelector() map[string]string {
	return withPrefix(subMap(s.Labels, LabelAppName, LabelAppProcess, LabelIsBuild), s.Prefix)
}

func (s *LabelSet) ToRoutableSelector() map[string]string {
	return withPrefix(subMap(s.Labels, LabelAppName, LabelAppProcess, LabelIsBuild, labelIsRoutable), s.Prefix)
}

func (s *LabelSet) ToAppSelector() map[string]string {
	return withPrefix(subMap(s.Labels, LabelAppName), s.Prefix)
}

func (s *LabelSet) ToNodeContainerSelector() map[string]string {
	return withPrefix(subMap(s.Labels, labelNodeContainerName, labelNodeContainerPool), s.Prefix)
}

func (s *LabelSet) ToNodeSelector() map[string]string {
	return withPrefix(subMap(s.Labels, LabelNodePool, labelNodeAddr), s.Prefix)
}

func (s *LabelSet) ToNodeByPoolSelector() map[string]string {
	return withPrefix(subMap(s.Labels, LabelNodePool), s.Prefix)
}

func (s *LabelSet) ToIsServiceSelector() map[string]string {
	return withPrefix(subMap(s.Labels, labelIsService), s.Prefix)
}

func (s *LabelSet) ToVolumeSelector() map[string]string {
	return withPrefix(subMap(s.Labels, labelVolumeName), s.Prefix)
}

func (s *LabelSet) ToHPASelector() map[string]string {
	keys := []string{labelIsTsuru, LabelAppName}
	if s.getLabel(LabelAppProcess) != "" {
		keys = append(keys, LabelAppProcess)
	}
	return withPrefix(subMap(s.Labels, keys...), s.Prefix)
}

func (s *LabelSet) ToPDBSelector() map[string]string {
	return s.ToHPASelector()
}

func (s *LabelSet) AppName() string {
	return s.getLabel(LabelAppName)
}

func (s *LabelSet) AppProcess() string {
	return s.getLabel(LabelAppProcess)
}

func (s *LabelSet) AppPlatform() string {
	return s.getLabel(LabelAppPlatform)
}

func (s *LabelSet) AppPool() string {
	return s.getLabel(LabelAppPool)
}

func (s *LabelSet) NodeAddr() string {
	return s.getLabel(labelNodeAddr)
}

func (s *LabelSet) NodePool() string {
	return s.getLabel(LabelNodePool)
}

func (s *LabelSet) NodeIaaSID() string {
	return s.getLabel(labelNodeIaaSID)
}

func (s *LabelSet) AppVersion() int {
	v, _ := strconv.Atoi(s.getLabel(LabelAppVersion))
	return v
}

func (s *LabelSet) WithoutVersion() *LabelSet {
	ns := s.without(LabelAppVersion)
	delete(ns.RawLabels, "version")
	delete(ns.RawLabels, "app.kubernetes.io/version")
	return ns
}

func (s *LabelSet) WithoutRoutable() *LabelSet {
	return s.without(labelIsRoutable)
}

func (s *LabelSet) WithoutIsolated() *LabelSet {
	return s.without(labelIsIsolatedRun).without(labelIsIsolatedRunNew)
}

func (s *LabelSet) without(key string) *LabelSet {
	ns := s.DeepCopy()
	delete(ns.Labels, key)
	delete(ns.Labels, s.Prefix+key)
	return ns
}

func (s *LabelSet) ReplaceIsIsolatedRunWithNew() {
	if !s.hasLabel(labelIsIsolatedRunNew) {
		s.Labels[labelIsIsolatedRunNew] = s.Labels[labelIsIsolatedRun]
	}
	delete(s.Labels, labelIsIsolatedRun)
}

func (s *LabelSet) ReplaceIsIsolatedNewRunWithBase() {
	if !s.hasLabel(labelIsIsolatedRun) {
		s.Labels[labelIsIsolatedRun] = s.Labels[labelIsIsolatedRunNew]
	}
	delete(s.Labels, labelIsIsolatedRunNew)
}

func filterByPrefix(labels, raw map[string]string, prefix string, withPrefix bool) map[string]string {
	result := make(map[string]string, len(labels))
	for k, v := range labels {
		hasPrefix := strings.HasPrefix(k, prefix)
		if hasPrefix == withPrefix {
			result[k] = v
		}
	}
	if !withPrefix {
		for k, v := range raw {
			result[k] = v
		}
	}
	return result
}

func (s *LabelSet) NodeMetadata() map[string]string {
	m := filterByPrefix(s.Labels, s.RawLabels, s.Prefix, true)
	for k := range m {
		if strings.HasPrefix(k, s.Prefix+labelNodeInternalPrefix) {
			delete(m, k)
		}
	}
	return m
}

func (s *LabelSet) NodeMetadataNoPrefix() map[string]string {
	m := filterByPrefix(s.Labels, s.RawLabels, s.Prefix, true)
	for k, v := range m {
		delete(m, k)
		if !strings.HasPrefix(k, s.Prefix+labelNodeInternalPrefix) {
			m[strings.TrimPrefix(k, s.Prefix)] = v
		}

	}
	return m
}

func (s *LabelSet) NodeExtraData(cluster string) map[string]string {
	m := filterByPrefix(s.Labels, s.RawLabels, s.Prefix, false)
	for k, v := range s.Labels {
		if strings.HasPrefix(k, s.Prefix+labelNodeInternalPrefix) {
			m[k] = v
		}
	}
	if cluster != "" {
		m[labelClusterMetadata] = cluster
	}
	return m
}

func (s *LabelSet) Restarts() int {
	restarts, _ := strconv.Atoi(s.getLabel(labelRestarts))
	return restarts
}

func (s *LabelSet) BuildImage() string {
	return s.getLabel(labelBuildImage)
}

func (s *LabelSet) IsStopped() bool {
	return s.getBoolLabel(labelIsStopped)
}

func (s *LabelSet) IsAsleep() bool {
	return s.getBoolLabel(labelIsAsleep)
}

func (s *LabelSet) IsDeploy() bool {
	return s.getBoolLabel(LabelIsDeploy)
}

func (s *LabelSet) IsService() bool {
	return s.getBoolLabel(labelIsService)
}

func (s *LabelSet) IsIsolatedRun() bool {
	return s.getBoolLabel(labelIsIsolatedRun) || s.getBoolLabel(labelIsIsolatedRunNew)
}

func (s *LabelSet) IsBase() bool {
	return s.hasLabel(labelIsIsolatedRun)
}

func (s *LabelSet) IsRoutable() bool {
	return s.getBoolLabel(labelIsRoutable)
}

func (s *LabelSet) IsHeadlessService() bool {
	return s.getBoolLabel(labelIsHeadlessService)
}

func (s *LabelSet) SetRestarts(count int) {
	s.addLabel(labelRestarts, strconv.Itoa(count))
}

func (s *LabelSet) SetStopped() {
	s.addLabel(labelIsStopped, strconv.FormatBool(true))
}

func (s *LabelSet) SetAsleep() {
	s.addLabel(labelIsAsleep, strconv.FormatBool(true))
}

func (s *LabelSet) SetIsService() {
	s.addLabel(labelIsService, strconv.FormatBool(true))
}

func (s *LabelSet) SetIsHeadlessService() {
	s.addLabel(labelIsHeadlessService, strconv.FormatBool(true))
}

func (s *LabelSet) SetIsRoutable() {
	s.addLabel(labelIsRoutable, strconv.FormatBool(true))
}

func (s *LabelSet) ToggleIsRoutable(isRoutable bool) {
	s.addLabel(labelIsRoutable, strconv.FormatBool(isRoutable))
}

func (s *LabelSet) SetBuildImage(image string) {
	s.addLabel(labelBuildImage, image)
}

func (s *LabelSet) SetVersion(version int) {
	s.addLabel(LabelAppVersion, strconv.Itoa(version))
	if s.RawLabels == nil {
		s.RawLabels = make(map[string]string)
	}
	versionStr := fmt.Sprintf("v%d", version)
	s.RawLabels["version"] = versionStr
	s.RawLabels["app.kubernetes.io/version"] = versionStr
}

func (s *LabelSet) addLabel(k, v string) {
	if s.Labels == nil {
		s.Labels = make(map[string]string)
	}
	s.Labels[k] = v
}

func (s *LabelSet) hasLabel(k string) bool {
	if _, ok := s.Labels[s.Prefix+k]; ok {
		return ok
	}
	if _, ok := s.Labels[k]; ok {
		return ok
	}
	return false
}

func (s *LabelSet) getLabel(k string) string {
	if v, ok := s.Labels[s.Prefix+k]; ok {
		return v
	}
	if v, ok := s.Labels[k]; ok {
		return v
	}
	return ""
}

func (s *LabelSet) getBoolLabel(k string) bool {
	v, _ := strconv.ParseBool(s.getLabel(k))
	return v
}

type ServiceLabelsOpts struct {
	App     App
	Process string
	Version int
	ServiceLabelExtendedOpts
}

type ServiceLabelExtendedOpts struct {
	Provisioner   string
	Prefix        string
	BuildImage    string
	IsDeploy      bool
	IsIsolatedRun bool
	IsBuild       bool
	Builder       string
}

func ExtendServiceLabels(set *LabelSet, opts ServiceLabelExtendedOpts) {
	set.Prefix = opts.Prefix
	if opts.BuildImage != "" {
		set.Labels[labelBuildImage] = opts.BuildImage
	}
	set.Labels[labelProvisioner] = opts.Provisioner
	set.Labels[labelIsService] = strconv.FormatBool(true)
	set.Labels[LabelIsDeploy] = strconv.FormatBool(opts.IsDeploy)
	set.Labels[labelIsIsolatedRun] = strconv.FormatBool(opts.IsIsolatedRun)
	set.Labels[LabelIsBuild] = strconv.FormatBool(opts.IsBuild)
	set.Labels[labelBuilder] = opts.Builder
}

func ServiceLabels(ctx context.Context, opts ServiceLabelsOpts) (*LabelSet, error) {
	set, err := ProcessLabels(ctx, ProcessLabelsOpts{
		App:      opts.App,
		Process:  opts.Process,
		IsDeploy: opts.IsDeploy,
	})
	if err != nil {
		return nil, err
	}
	if set.RawLabels == nil {
		set.RawLabels = map[string]string{
			"app.kubernetes.io/name":       opts.App.GetName(),
			"app.kubernetes.io/component":  "tsuru-app",
			"app.kubernetes.io/managed-by": "tsuru",
		}
		if opts.Process != "" {
			appProcessName := AppProcessName(opts.App, opts.Process, 0, "")
			set.RawLabels["app"] = appProcessName
			set.RawLabels["app.kubernetes.io/instance"] = appProcessName
		}
	}
	if opts.Version != 0 {
		set.SetVersion(opts.Version)
	}
	ExtendServiceLabels(set, opts.ServiceLabelExtendedOpts)
	return set, nil
}

type ProcessLabelsOpts struct {
	App         App
	Process     string
	Provisioner string
	Builder     string
	Prefix      string
	IsDeploy    bool
}

func ProcessLabels(ctx context.Context, opts ProcessLabelsOpts) (*LabelSet, error) {
	ls := &LabelSet{
		Labels: map[string]string{
			labelIsTsuru:      strconv.FormatBool(true),
			labelIsStopped:    strconv.FormatBool(false),
			LabelIsDeploy:     strconv.FormatBool(opts.IsDeploy),
			LabelAppName:      opts.App.GetName(),
			LabelAppTeamOwner: opts.App.GetTeamOwner(),
			LabelAppProcess:   opts.Process,
			LabelAppPlatform:  opts.App.GetPlatform(),
			LabelAppPool:      opts.App.GetPool(),
			labelProvisioner:  opts.Provisioner,
			labelBuilder:      opts.Builder,
		},
		Prefix: opts.Prefix,
	}
	for _, tag := range opts.App.ListTags() {
		parts := strings.SplitN(tag, "=", 2)
		var key, value string
		if len(parts) > 0 {
			key = parts[0]
		}
		if len(parts) > 1 {
			value = parts[1]
		}
		if key == "" {
			continue
		}
		key = labelCustomTagsPrefix + key
		if len(validation.IsQualifiedName(key)) > 0 {
			// Ignoring tags that are not valid identifiers for labels or annotations
			continue
		}
		ls.Labels[key] = value
	}
	return ls, nil
}

type ServiceAccountLabelsOpts struct {
	App               App
	NodeContainerName string
	Provisioner       string
	Prefix            string
}

func ServiceAccountLabels(opts ServiceAccountLabelsOpts) *LabelSet {
	labelMap := map[string]string{
		labelIsTsuru:     strconv.FormatBool(true),
		labelProvisioner: opts.Provisioner,
	}
	if opts.App == nil {
		labelMap[labelNodeContainerName] = opts.NodeContainerName
	} else {
		labelMap[LabelAppName] = opts.App.GetName()
	}
	return &LabelSet{
		Labels: labelMap,
		Prefix: opts.Prefix,
	}
}

type NodeContainerLabelsOpts struct {
	Name         string
	CustomLabels map[string]string
	Pool         string
	Provisioner  string
	Prefix       string
}

func NodeContainerLabels(opts NodeContainerLabelsOpts) *LabelSet {
	labels := map[string]string{
		labelIsTsuru:           strconv.FormatBool(true),
		labelIsNodeContainer:   strconv.FormatBool(true),
		labelProvisioner:       opts.Provisioner,
		labelNodeContainerName: opts.Name,
		labelNodeContainerPool: opts.Pool,
	}
	for k, v := range opts.CustomLabels {
		labels[k] = v
	}
	return &LabelSet{Labels: labels, Prefix: opts.Prefix}
}

type NodeLabelsOpts struct {
	IaaSID       string
	Addr         string
	Pool         string
	Prefix       string
	CustomLabels map[string]string
}

func NodeLabels(opts NodeLabelsOpts) *LabelSet {
	labels := map[string]string{}
	for k, v := range opts.CustomLabels {
		labels[k] = v
	}
	for _, r := range []string{LabelNodePool, labelNodeAddr, labelNodeIaaSID} {
		delete(labels, r)
		delete(labels, opts.Prefix+r)
	}
	labels[LabelNodePool] = opts.Pool
	if opts.Addr != "" {
		labels[labelNodeAddr] = opts.Addr
	}
	if opts.IaaSID != "" {
		labels[labelNodeIaaSID] = opts.IaaSID
	}
	return &LabelSet{Labels: labels, Prefix: opts.Prefix}
}

type VolumeLabelsOpts struct {
	Name        string
	Provisioner string
	Pool        string
	Plan        string
	Team        string
	Prefix      string
}

func VolumeLabels(opts VolumeLabelsOpts) *LabelSet {
	labels := map[string]string{
		labelIsTsuru:     strconv.FormatBool(true),
		labelProvisioner: opts.Provisioner,
		labelVolumeName:  opts.Name,
		labelVolumePool:  opts.Pool,
		labelVolumePlan:  opts.Plan,
		labelVolumeTeam:  opts.Team,
	}
	return &LabelSet{Labels: labels, Prefix: opts.Prefix}
}

type ImageBuildLabelsOpts struct {
	Name         string
	CustomLabels map[string]string
	Provisioner  string
	Prefix       string
	IsBuild      bool
}

func ImageBuildLabels(opts ImageBuildLabelsOpts) *LabelSet {
	labels := map[string]string{
		labelIsTsuru:     strconv.FormatBool(true),
		labelProvisioner: opts.Provisioner,
		LabelIsBuild:     strconv.FormatBool(opts.IsBuild),
	}
	for k, v := range opts.CustomLabels {
		labels[k] = v
	}
	return &LabelSet{Labels: labels, Prefix: opts.Prefix}
}

type PDBLabelsOpts struct {
	App         App
	Prefix      string
	Process     string
	Provisioner string
}

func PDBLabels(opts PDBLabelsOpts) *LabelSet {
	return &LabelSet{
		Labels: map[string]string{
			labelIsTsuru:      strconv.FormatBool(true),
			labelProvisioner:  opts.Provisioner,
			LabelAppName:      opts.App.GetName(),
			LabelAppProcess:   opts.Process,
			LabelAppTeamOwner: opts.App.GetTeamOwner(),
		},
		Prefix: opts.Prefix,
	}
}

func withPrefix(m map[string]string, prefix string) map[string]string {
	result := make(map[string]string, len(m))
	for k, v := range m {
		if !strings.HasPrefix(k, prefix) {
			k = prefix + k
		}
		result[k] = v
	}
	return result
}

func subMap(m map[string]string, keys ...string) map[string]string {
	result := make(map[string]string, len(keys))
	s := set.FromValues(keys...)
	for k, v := range m {
		if s.Includes(k) {
			result[k] = v
		}
	}
	return result
}

func IsServiceLabelSet(prefix string) *LabelSet {
	labels := map[string]string{
		labelIsTsuru:   strconv.FormatBool(true),
		labelIsService: strconv.FormatBool(true),
	}
	return &LabelSet{Labels: labels, Prefix: prefix}
}

var kubeNameRegex = regexp.MustCompile(`(?i)[^a-z0-9.-]`)

func ValidKubeName(name string) string {
	return strings.ToLower(kubeNameRegex.ReplaceAllString(name, "-"))
}

func AppProcessName(a App, process string, version int, suffix string) string {
	const kubeLabelNameMaxLen = 55

	name := ValidKubeName(a.GetName())
	processVersion := ValidKubeName(process)
	if version > 0 {
		processVersion = fmt.Sprintf("%s-v%d", processVersion, version)
	} else if suffix != "" {
		processVersion = fmt.Sprintf("%s-%s", processVersion, suffix)
	}
	label := fmt.Sprintf("%s-%s", name, processVersion)
	if len(label) > kubeLabelNameMaxLen {
		h := sha256.New()
		h.Write([]byte(processVersion))
		hash := fmt.Sprintf("%x", h.Sum(nil))
		maxLen := kubeLabelNameMaxLen - len(name) - 1
		if len(hash) > maxLen {
			hash = hash[:maxLen]
		}
		label = fmt.Sprintf("%s-%s", name, hash)
	}
	return label
}


text:
import numpy as np
import librosa

from scipy.signal import filtfilt, butter, hilbert

from librosa import resample

from ..helper import preemphasize
from ..functions import BaseAnalysisFunction

def window_envelopes(env, win_len, time_step):
    if env.is_windowed:
        return
    nperseg = int(win_len * env.sampling_rate)
    if nperseg % 2 != 0:
        nperseg -= 1
    nperstep = int(time_step * env.sampling_rate)
    window = np.hanning(nperseg + 2)[1:nperseg + 1]
    halfperseg = int(nperseg / 2)

    print(nperseg, halfperseg)
    num_samps, num_bands = env.shape
    print(env.shape)
    indices = np.arange(halfperseg, num_samps - halfperseg + 1, nperstep)
    num_frames = len(indices)
    print(indices)
    rep = np.zeros((num_frames, num_bands))
    new_rep = dict()
    for i in range(num_frames):
        print(indices[i])
        time_key = indices[i] / env.sampling_rate
        rep_line = list()
        print(indices[i] - halfperseg, indices[i] + halfperseg)
        array = env[indices[i] - halfperseg, indices[i] + halfperseg]
        print(array.shape)
        for b in range(num_bands):
            rep_line.append(sum(array[:, b]))
        new_rep[time_key] = rep_line
    env._rep = new_rep
    env.is_windowed = True
    return env

class AmplitudeEnvelopeFunction(BaseAnalysisFunction):
    def __init__(self, num_bands=8, min_frequency=80, max_frequency=7800, mode='downsample'):
        super(AmplitudeEnvelopeFunction, self).__init__()
        self.arguments = [num_bands, min_frequency, max_frequency, mode]
        self._function = generate_amplitude_envelopes

def generate_amplitude_envelopes(signal, sr, num_bands, min_frequency, max_frequency, mode='downsample'):
    signal = preemphasize(signal, 0.97)
    proc = signal / np.sqrt(np.mean(signal ** 2)) * 0.03

    band_mins = [min_frequency * np.exp(np.log(max_frequency / min_frequency) / num_bands) ** x
                 for x in range(num_bands)]
    band_maxes = [min_frequency * np.exp(np.log(max_frequency / min_frequency) / num_bands) ** (x + 1)
                  for x in range(num_bands)]

    envs = []
    for i in range(num_bands):
        b, a = butter(2, (band_mins[i] / (sr / 2), band_maxes[i] / (sr / 2)), btype='bandpass')
        env = filtfilt(b, a, proc)
        env = abs(hilbert(env))
        if mode == 'downsample':
            env = resample(env, sr, 120)
        envs.append(env)
    envs = np.array(envs).T
    if mode == 'downsample':
        sr = 120
    output = dict()
    for i in range(envs.shape[0]):
        output[i / sr] = envs[i, :]
    return output


text:
set(wxAUILIB_NAME wxaui)

set(COMMON_CSOURCES
    ${CMAKE_CURRENT_SOURCE_DIR}/src/common/dummy.cpp
    ${CMAKE_CURRENT_SOURCE_DIR}/src/aui/auibar.cpp
    ${CMAKE_CURRENT_SOURCE_DIR}/src/aui/auibook.cpp
    ${CMAKE_CURRENT_SOURCE_DIR}/src/aui/dockart.cpp
    ${CMAKE_CURRENT_SOURCE_DIR}/src/aui/floatpane.cpp
    ${CMAKE_CURRENT_SOURCE_DIR}/src/aui/framemanager.cpp
    ${CMAKE_CURRENT_SOURCE_DIR}/src/aui/tabart.cpp
    ${CMAKE_CURRENT_SOURCE_DIR}/src/aui/tabmdi.cpp
    )
source_group("Common Sources" FILES ${COMMON_CSOURCES})

set(MSW_HEADERS
    ${CMAKE_CURRENT_SOURCE_DIR}/include/wx/msw/genrcdefs.h
    )
source_group("MSW Headers" FILES ${MSW_HEADERS})

set(MSW_CSOURCES
    ${CMAKE_CURRENT_SOURCE_DIR}/src/msw/version.rc
    )
source_group("MSW Sources" FILES ${MSW_CSOURCES})

set(COMMON_HHEADERS
    ${CMAKE_CURRENT_SOURCE_DIR}/include/wx/aui/aui.h
    ${CMAKE_CURRENT_SOURCE_DIR}/include/wx/aui/auibar.h
    ${CMAKE_CURRENT_SOURCE_DIR}/include/wx/aui/auibook.h
    ${CMAKE_CURRENT_SOURCE_DIR}/include/wx/aui/dockart.h
    ${CMAKE_CURRENT_SOURCE_DIR}/include/wx/aui/floatpane.h
    ${CMAKE_CURRENT_SOURCE_DIR}/include/wx/aui/framemanager.h
    ${CMAKE_CURRENT_SOURCE_DIR}/include/wx/aui/tabart.h
    ${CMAKE_CURRENT_SOURCE_DIR}/include/wx/aui/tabmdi.h
    )
source_group("Common Headers" FILES ${COMMON_HHEADERS})

set(SETUP_HHEADERS
    #${CMAKE_CURRENT_SOURCE_DIR}/include/wx/univ/setup.h
    ${CMAKE_CURRENT_SOURCE_DIR}/include/wx/msw/setup.h
    )
source_group("Setup Headers" FILES ${SETUP_HHEADERS})

set(PROJECT_HHEADERS ${COMMON_HHEADERS} ${SETUP_HHEADERS})
set(PROJECT_CSOURCES ${COMMON_CSOURCES} ${MSW_CSOURCES})

add_wxlib("${wxAUILIB_NAME}" "${PROJECT_CSOURCES}" "${PROJECT_HHEADERS}" "msw" "_aui" "aui")

set_target_properties(${wxAUILIB_NAME}
	PROPERTIES
    COMPILE_FLAGS "-D_LIB -DCRT_SECURE_NO_DEPRECATE=1 -D_CRT_NON_CONFORMING_SWPRINTFS=1 -D_SCL_SECURE_NO_WARNINGS=1"
)

target_link_libraries(${wxAUILIB_NAME} ${wxBASELIB_NAME} ${wxCORELIB_NAME} ${wxADVLIB_NAME})

install(TARGETS
    ${wxAUILIB_NAME}
    RUNTIME DESTINATION bin
    ARCHIVE DESTINATION lib
    LIBRARY DESTINATION lib)

install(FILES ${COMMON_HHEADERS} DESTINATION include/wx/aui)
install(FILES ${MSW_HEADERS} DESTINATION include/wx/msw)
install(FILES ${SETUP_HHEADERS} DESTINATION include/wx/msw)

include(BuildUtils)

install_external_lib_debug_pdb(${LIB_MOUTNAME}${LIB_DEBUG_POSTFIX} ${WX_OUTPUT_PATH})


text:
struct ClipmapObj::St_Def : StateT<St_Def> {
	void onDraw(const ClipmapObj& self, rs::IEffect& e) const override {
		self.draw(e);
	}
};
ClipmapObj::ClipmapObj(spn::PowInt n, const int l, const int upsamp_n):
	Clipmap(n,l,upsamp_n)
{
	setStateNew<St_Def>();
}
const std::string& ClipmapObj::getName() const {
	static const std::string name("ClipmapObj");
	return name;
}


text:
package com.langwen.admin.dao;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import com.langwen.admin.bean.Zsgdwk;
import com.ssh.HibernateSessionFactory;

public class ZsgdwkDao {
	public void addZsgdwk(Zsgdwk zsgdwk) {
		Session session = HibernateSessionFactory.getSession();
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			Date date = new Date();
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String curdate = df.format(date);
			zsgdwk.setTianjiashijian(curdate);
			String hql = "select count(*) from Zsgdwk gw";
			Query query = session.createQuery(hql);
			Long count = (Long) query.uniqueResult();
			Integer paixu = Integer.parseInt(count.toString()) + 1;
			zsgdwk.setPaixu(paixu);
			session.save(zsgdwk);
			transaction.commit();
		} catch (Exception e) {
			if (transaction != null) {
				System.out.println("¡¾ÏµÍ³´íÎó¡¿Ôڳ־û¯¶ÔÏóʱ³ö´í£¬ÔÒòÊÇ£º");
				e.printStackTrace();
			}
		} finally {
			HibernateSessionFactory.closeSession();
		}
	}

	public void deleteZsgdwk(Integer id) {
		Session session = HibernateSessionFactory.getSession();
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			Zsgdwk zsgdwk = (Zsgdwk) session.load(Zsgdwk.class, id);
			int paixu = zsgdwk.getPaixu();
			session.delete(zsgdwk);
			String hql = "update Zsgdwk gw set gw.paixu = gw.paixu -1 where gw.paixu > "
					+ paixu;
			Query query = session.createQuery(hql);
			query.executeUpdate();
			transaction.commit();
		} catch (Exception e) {
			if (transaction != null) {
				System.out.println("¡¾ÏµÍ³´íÎó¡¿Ôڳ־û¯¶ÔÏóʱ³ö´í£¬ÔÒòÊÇ£º");
				e.printStackTrace();
			}
		} finally {
			HibernateSessionFactory.closeSession();
		}
	}

	public Zsgdwk loadZsgdwk(Integer id) {
		Zsgdwk zsgdwk = null;
		Session session = HibernateSessionFactory.getSession();
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			zsgdwk = (Zsgdwk) session.get(Zsgdwk.class, id);
			transaction.commit();
		} catch (Exception e) {
			if (transaction != null) {
				System.out.println("¡¾ÏµÍ³´íÎó¡¿Ôڳ־û¯¶ÔÏóʱ³ö´í£¬ÔÒòÊÇ£º");
				e.printStackTrace();
			}
		} finally {
			HibernateSessionFactory.closeSession();
		}
		return zsgdwk;
	}

	public List<Zsgdwk> allZsgdwk() {
		List<Zsgdwk> zsgdwks = null;
		Session session = HibernateSessionFactory.getSession();
		Transaction transaction = null;
		try {
			// String hql =
			// "SELECT jj FROM Zsgdwk as jj WHERE jj.zhiding=1 ORDER BY zhidingshijian DESC";
			String hql = "from Zsgdwk as jj ORDER BY paixu DESC ";
			Query query = session.createQuery(hql);
			transaction = session.beginTransaction();
			zsgdwks = query.list();
			transaction.commit();
			if (!Hibernate.isInitialized(zsgdwks)) {
				Hibernate.initialize(zsgdwks);
			}
		} catch (Exception e) {
			if (transaction != null) {
				System.out.println("¡¾ÏµÍ³´íÎó¡¿Ôڳ־û¯¶ÔÏóʱ³ö´í£¬ÔÒòÊÇ£º");
				e.printStackTrace();
			}
		} finally {
			HibernateSessionFactory.closeSession();
		}
		return zsgdwks;
	}

	public List<Zsgdwk> allZsgdwkById() {
		List<Zsgdwk> zsgdwks = null;
		Session session = HibernateSessionFactory.getSession();
		Transaction transaction = null;
		try {
			// String hql =
			// "SELECT jj FROM Zsgdwk as jj WHERE jj.zhiding=1 ORDER BY zhidingshijian DESC";
			String hql = "from Zsgdwk as jj ORDER BY id ASC ";
			Query query = session.createQuery(hql);
			transaction = session.beginTransaction();
			zsgdwks = query.list();
			transaction.commit();
			if (!Hibernate.isInitialized(zsgdwks)) {
				Hibernate.initialize(zsgdwks);
			}
		} catch (Exception e) {
			if (transaction != null) {
				System.out.println("¡¾ÏµÍ³´íÎó¡¿Ôڳ־û¯¶ÔÏóʱ³ö´í£¬ÔÒòÊÇ£º");
				e.printStackTrace();
			}
		} finally {
			HibernateSessionFactory.closeSession();
		}
		return zsgdwks;
	}

	public void updateZsgdwk(Zsgdwk zsgdwk) {
		Session session = HibernateSessionFactory.getSession();
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			if (zsgdwk.getPaixu() == null) {
				zsgdwk.setPaixu(loadZsgdwk(zsgdwk.getId()).getPaixu());
			}
			if (!session.isOpen()) {
				session = HibernateSessionFactory.getSession();
				transaction = session.beginTransaction();
			}
			session.update(zsgdwk);
			transaction.commit();
		} catch (Exception e) {
			if (transaction != null) {
				System.out.println("¡¾ÏµÍ³´íÎó¡¿Ôڳ־û¯¶ÔÏóʱ³ö´í£¬ÔÒòÊÇ£º");
				transaction.rollback();
				e.printStackTrace();
			}
		} finally {
			HibernateSessionFactory.closeSession();
		}
	}

	// ½«Ö¸¶¨µÄͼÊ飬ÅÅÐòÏòÏÂÒƶ¯Ò»Î»
	public void moveDownZsgdwk(Integer id) {
		Session session = HibernateSessionFactory.getSession();
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			Zsgdwk zsgdwk = (Zsgdwk) session.load(Zsgdwk.class, id);
			if (zsgdwk.getPaixu() == 1) {
				return; // ÒѾÅÅÔÚ×îÇ°Ãæ
			}
			int oldPaixu = zsgdwk.getPaixu();
			String hql = "update Zsgdwk gw set gw.paixu = gw.paixu + 1 where gw.paixu = "
					+ (oldPaixu - 1);
			if (!session.isOpen()) {
				session = HibernateSessionFactory.getSession();
				// transaction = session.beginTransaction();
			}
			Query query = session.createQuery(hql);
			query.executeUpdate();
			if (!session.isOpen()) {
				session = HibernateSessionFactory.getSession();
				// transaction = session.beginTransaction();
			}
			zsgdwk.setPaixu(oldPaixu - 1);
			updateZsgdwk(zsgdwk);
			transaction.commit();
		} catch (Exception e) {
			if (transaction != null) {
				System.out.println("¡¾ÏµÍ³´íÎó¡¿Ôڳ־û¯¶ÔÏóʱ³ö´í£¬ÔÒòÊÇ£º");
				e.printStackTrace();
			}
		} finally {
			HibernateSessionFactory.closeSession();
		}
	}

	// ½«Ö¸¶¨µÄͼÊ飬ÅÅÐòÏòÉÏÒƶ¯Ò»Î»
	public void moveUpZsgdwk(Integer id) {
		Session session = HibernateSessionFactory.getSession();
		Transaction transaction = null;
		try {
			transaction = session.beginTransaction();
			Zsgdwk zsgdwk = (Zsgdwk) session.load(Zsgdwk.class, id);
			int oldPaixu = zsgdwk.getPaixu();
			String isMax = "select new Zsgdwk(jj.id) FROM Zsgdwk as jj WHERE jj.paixu = "
					+ (oldPaixu + 1);
			if (!session.isOpen()) {
				session = HibernateSessionFactory.getSession();
				// transaction = session.beginTransaction();
			}
			Query quMax = session.createQuery(isMax);
			List<Zsgdwk> gl = quMax.list();
			if (gl.size() == 0) {
				return; // ÒѾÅÅÔÚ×îºóÃæ
			}
			String hql = "update Zsgdwk gw set gw.paixu = gw.paixu - 1 where gw.paixu = "
					+ (oldPaixu + 1);
			if (!session.isOpen()) {
				session = HibernateSessionFactory.getSession();
				// transaction = session.beginTransaction();
			}
			Query query = session.createQuery(hql);
			query.executeUpdate();
			if (!session.isOpen()) {
				session = HibernateSessionFactory.getSession();
				// transaction = session.beginTransaction();
			}
			zsgdwk.setPaixu(oldPaixu + 1);
			updateZsgdwk(zsgdwk);
			transaction.commit();
		} catch (Exception e) {
			if (transaction != null) {
				System.out.println("¡¾ÏµÍ³´íÎó¡¿Ôڳ־û¯¶ÔÏóʱ³ö´í£¬ÔÒòÊÇ£º");
				e.printStackTrace();
			}
		} finally {
			HibernateSessionFactory.closeSession();
		}
	}

	// ÖØа´ÕÕÌí¼Óʱ¼äÅÅÐò
	public void rePaixuZsgdwk() {
		Session session = HibernateSessionFactory.getSession();
		Transaction transaction = null;
		try {
			List<Zsgdwk> zsgdwks = allZsgdwkById();
			if (!session.isOpen()) {
				session = HibernateSessionFactory.getSession();
				transaction = session.beginTransaction();
			}
			for (int i = 0; i < zsgdwks.size(); i++) {
				Zsgdwk temp = zsgdwks.get(i);
				temp.setPaixu(i + 1);
				session.update(temp);
				if (i % 20 == 0) {
					session.flush();
					session.clear();
				}
			}
			transaction.commit();
		} catch (Exception e) {
			if (transaction != null) {
				System.out.println("¡¾ÏµÍ³´íÎó¡¿Ôڳ־û¯¶ÔÏóʱ³ö´í£¬ÔÒòÊÇ£º");
				e.printStackTrace();
			}
		} finally {
			HibernateSessionFactory.closeSession();
		}
	}

	public List<Zsgdwk> pageZsgdwk(int page) {
		Session session = HibernateSessionFactory.getSession();
		Transaction transaction = null;
		List<Zsgdwk> zsgdwks = null;
		try {
			transaction = session.beginTransaction();
			String hql = "from Zsgdwk as jj ORDER BY paixu DESC ";
			Query query = session.createQuery(hql);
			query.setFirstResult(10 * (page - 1));
			query.setMaxResults(10);
			zsgdwks = query.list();
			transaction.commit();
		} catch (Exception e) {
			if (transaction != null) {
				System.out.println("¡¾ÏµÍ³´íÎó¡¿Ôڳ־û¯¶ÔÏóʱ³ö´í£¬ÔÒòÊÇ£º");
				e.printStackTrace();
			}
		} finally {
			HibernateSessionFactory.closeSession();
		}
		return zsgdwks;
	}

	@Test
	public void testZsgdwk() {
		for (int i = 1; i < 100; i++) {
			Zsgdwk zsgdwk = new Zsgdwk();
			zsgdwk.setShuming("No." + i + "Zsgdwk");
			addZsgdwk(zsgdwk);
		}
	}

}


text:
<!DOCTYPE html>

	<title>Example App</title>
	<link rel="stylesheet" type="text/css" href="css/bootstrap.css">

Hello World


text:
fMRI-adhd
=========

HMM for fMRI ADHD classification

Instructions
------------

1. Symlink dataset matrix file to the matlab working directory.
`ln -s /path/to/data.mat /path/to/repo/.`
2. Download and install [PMTK3](https://github.com/probml/pmtk3) for the newest version of Kevin Murphy's et al. HMM toolbox.


text:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <title></title>

    <!-- build:css styles/vendor.css -->
    <!-- bower:css -->
    <link rel="stylesheet" href="bower_components/ionic/release/css/ionic.css" />
    <!-- endbower -->
    <!-- endbuild -->
    <link href="styles/style.css" rel="stylesheet">

    <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
    <link href="styles/ionic.app.css" rel="stylesheet">
    -->

    <!-- ionic/angularjs js -->
    <!-- build:js scripts/vendor.js -->
    <!-- bower:js -->
    <script src="bower_components/angular/angular.js"></script>
    <script src="bower_components/angular-animate/angular-animate.js"></script>
    <script src="bower_components/angular-sanitize/angular-sanitize.js"></script>
    <script src="bower_components/angular-ui-router/release/angular-ui-router.js"></script>
    <script src="bower_components/ionic/release/js/ionic.js"></script>
    <script src="bower_components/ionic/release/js/ionic-angular.js"></script>
    <script src="bower_components/ngCordova/dist/ng-cordova.js"></script>
    <script src="bower_components/angular-dynamic-locale/src/tmhDynamicLocale.js"></script>
    <script src="bower_components/angular-translate/angular-translate.js"></script>
    <script src="bower_components/angular-translate-loader-url/angular-translate-loader-url.js"></script>
    <script src="bower_components/angular-translate-loader-static-files/angular-translate-loader-static-files.js"></script>
    <!-- endbower -->
    <!-- endbuild -->

    <!-- cordova script (this will be a 404 during development) -->
    <script src="cordova.js"></script>

    <!-- your app's js -->
    <!-- build:js scripts/scripts.js -->
    <script src="scripts/app.js"></script>
    <script src="scripts/controllers.js"></script>
    <script src="scripts/services.js"></script>
    <script src="scripts/configuration.js"></script>
    <!-- endbuild -->
  </head>
  <body ng-app="i18nTutorial">
    <!--
      The nav bar that will be updated as we navigate between views.
    -->
    <ion-nav-bar class="bar-stable">
      <ion-nav-back-button>
      </ion-nav-back-button>
    </ion-nav-bar>
    <!--
      The views will be rendered in the <ion-nav-view> directive below
      Templates are in the /templates folder (but you could also
      have templates inline in this html file if you'd like).
    -->
    <ion-nav-view></ion-nav-view>
  </body>
</html>


text:
#include "src/trace_processor/importers/fuchsia/fuchsia_trace_parser.h"
#include "src/trace_processor/importers/fuchsia/fuchsia_trace_tokenizer.h"

#include "perfetto/base/logging.h"
#include "perfetto/ext/base/string_view.h"
#include "perfetto/protozero/scattered_heap_buffer.h"
#include "perfetto/trace_processor/trace_blob.h"
#include "src/trace_processor/importers/additional_modules.h"
#include "src/trace_processor/importers/common/args_tracker.h"
#include "src/trace_processor/importers/common/args_translation_table.h"
#include "src/trace_processor/importers/common/clock_tracker.h"
#include "src/trace_processor/importers/common/event_tracker.h"
#include "src/trace_processor/importers/common/flow_tracker.h"
#include "src/trace_processor/importers/common/process_tracker.h"
#include "src/trace_processor/importers/common/slice_tracker.h"
#include "src/trace_processor/importers/common/track_tracker.h"
#include "src/trace_processor/importers/default_modules.h"
#include "src/trace_processor/importers/ftrace/sched_event_tracker.h"
#include "src/trace_processor/importers/proto/metadata_tracker.h"
#include "src/trace_processor/importers/proto/proto_trace_parser.h"
#include "src/trace_processor/importers/proto/stack_profile_tracker.h"
#include "src/trace_processor/storage/metadata.h"
#include "src/trace_processor/storage/trace_storage.h"
#include "src/trace_processor/trace_sorter.h"
#include "src/trace_processor/util/descriptors.h"
#include "test/gtest_and_gmock.h"

#include "protos/perfetto/common/builtin_clock.pbzero.h"
#include "protos/perfetto/common/sys_stats_counters.pbzero.h"
#include "protos/perfetto/config/trace_config.pbzero.h"
#include "protos/perfetto/trace/android/packages_list.pbzero.h"
#include "protos/perfetto/trace/chrome/chrome_benchmark_metadata.pbzero.h"
#include "protos/perfetto/trace/chrome/chrome_trace_event.pbzero.h"
#include "protos/perfetto/trace/clock_snapshot.pbzero.h"
#include "protos/perfetto/trace/ftrace/ftrace.pbzero.h"
#include "protos/perfetto/trace/ftrace/ftrace_event.pbzero.h"
#include "protos/perfetto/trace/ftrace/ftrace_event_bundle.pbzero.h"
#include "protos/perfetto/trace/ftrace/generic.pbzero.h"
#include "protos/perfetto/trace/ftrace/power.pbzero.h"
#include "protos/perfetto/trace/ftrace/sched.pbzero.h"
#include "protos/perfetto/trace/ftrace/task.pbzero.h"
#include "protos/perfetto/trace/interned_data/interned_data.pbzero.h"
#include "protos/perfetto/trace/profiling/profile_packet.pbzero.h"
#include "protos/perfetto/trace/ps/process_tree.pbzero.h"
#include "protos/perfetto/trace/sys_stats/sys_stats.pbzero.h"
#include "protos/perfetto/trace/trace.pbzero.h"
#include "protos/perfetto/trace/trace_packet.pbzero.h"
#include "protos/perfetto/trace/track_event/chrome_thread_descriptor.pbzero.h"
#include "protos/perfetto/trace/track_event/counter_descriptor.pbzero.h"
#include "protos/perfetto/trace/track_event/debug_annotation.pbzero.h"
#include "protos/perfetto/trace/track_event/log_message.pbzero.h"
#include "protos/perfetto/trace/track_event/process_descriptor.pbzero.h"
#include "protos/perfetto/trace/track_event/source_location.pbzero.h"
#include "protos/perfetto/trace/track_event/task_execution.pbzero.h"
#include "protos/perfetto/trace/track_event/thread_descriptor.pbzero.h"
#include "protos/perfetto/trace/track_event/track_descriptor.pbzero.h"
#include "protos/perfetto/trace/track_event/track_event.pbzero.h"

namespace perfetto {
namespace trace_processor {
namespace {
using ::testing::_;
using ::testing::Args;
using ::testing::AtLeast;
using ::testing::DoAll;
using ::testing::ElementsAreArray;
using ::testing::Eq;
using ::testing::HasSubstr;
using ::testing::IgnoreResult;
using ::testing::InSequence;
using ::testing::Invoke;
using ::testing::InvokeArgument;
using ::testing::NiceMock;
using ::testing::Pointwise;
using ::testing::Return;
using ::testing::ReturnRef;
using ::testing::UnorderedElementsAreArray;
class MockSchedEventTracker : public SchedEventTracker {
 public:
  explicit MockSchedEventTracker(TraceProcessorContext* context)
      : SchedEventTracker(context) {}

  MOCK_METHOD9(PushSchedSwitch,
               void(uint32_t cpu,
                    int64_t timestamp,
                    uint32_t prev_pid,
                    base::StringView prev_comm,
                    int32_t prev_prio,
                    int64_t prev_state,
                    uint32_t next_pid,
                    base::StringView next_comm,
                    int32_t next_prio));
};

class MockProcessTracker : public ProcessTracker {
 public:
  explicit MockProcessTracker(TraceProcessorContext* context)
      : ProcessTracker(context) {}

  MOCK_METHOD4(SetProcessMetadata,
               UniquePid(uint32_t pid,
                         base::Optional<uint32_t> ppid,
                         base::StringView process_name,
                         base::StringView cmdline));

  MOCK_METHOD3(UpdateThreadName,
               UniqueTid(uint32_t tid,
                         StringId thread_name_id,
                         ThreadNamePriority priority));
  MOCK_METHOD3(UpdateThreadNameByUtid,
               void(UniqueTid utid,
                    StringId thread_name_id,
                    ThreadNamePriority priority));
  MOCK_METHOD2(UpdateThread, UniqueTid(uint32_t tid, uint32_t tgid));

  MOCK_METHOD1(GetOrCreateProcess, UniquePid(uint32_t pid));
  MOCK_METHOD2(SetProcessNameIfUnset,
               void(UniquePid upid, StringId process_name_id));
};
class MockBoundInserter : public ArgsTracker::BoundInserter {
 public:
  MockBoundInserter()
      : ArgsTracker::BoundInserter(&tracker_, nullptr, 0u), tracker_(nullptr) {
    ON_CALL(*this, AddArg(_, _, _, _)).WillByDefault(ReturnRef(*this));
  }

  MOCK_METHOD4(
      AddArg,
      ArgsTracker::BoundInserter&(StringId flat_key,
                                  StringId key,
                                  Variadic v,
                                  ArgsTracker::UpdatePolicy update_policy));

 private:
  ArgsTracker tracker_;
};

class MockEventTracker : public EventTracker {
 public:
  explicit MockEventTracker(TraceProcessorContext* context)
      : EventTracker(context) {}
  virtual ~MockEventTracker() = default;

  MOCK_METHOD9(PushSchedSwitch,
               void(uint32_t cpu,
                    int64_t timestamp,
                    uint32_t prev_pid,
                    base::StringView prev_comm,
                    int32_t prev_prio,
                    int64_t prev_state,
                    uint32_t next_pid,
                    base::StringView next_comm,
                    int32_t next_prio));

  MOCK_METHOD3(PushCounter,
               base::Optional<CounterId>(int64_t timestamp,
                                         double value,
                                         TrackId track_id));
};

class MockSliceTracker : public SliceTracker {
 public:
  explicit MockSliceTracker(TraceProcessorContext* context)
      : SliceTracker(context) {}

  MOCK_METHOD5(Begin,
               base::Optional<SliceId>(int64_t timestamp,
                                       TrackId track_id,
                                       StringId cat,
                                       StringId name,
                                       SetArgsCallback args_callback));
  MOCK_METHOD5(End,
               base::Optional<SliceId>(int64_t timestamp,
                                       TrackId track_id,
                                       StringId cat,
                                       StringId name,
                                       SetArgsCallback args_callback));
  MOCK_METHOD6(Scoped,
               base::Optional<SliceId>(int64_t timestamp,
                                       TrackId track_id,
                                       StringId cat,
                                       StringId name,
                                       int64_t duration,
                                       SetArgsCallback args_callback));
  MOCK_METHOD4(StartSlice,
               base::Optional<SliceId>(int64_t timestamp,
                                       TrackId track_id,
                                       SetArgsCallback args_callback,
                                       std::function<SliceId()> inserter));
};

class FuchsiaTraceParserTest : public ::testing::Test {
 public:
  FuchsiaTraceParserTest() {
    context_.storage.reset(new TraceStorage());
    storage_ = context_.storage.get();
    context_.track_tracker.reset(new TrackTracker(&context_));
    context_.global_args_tracker.reset(
        new GlobalArgsTracker(context_.storage.get()));
    context_.global_stack_profile_tracker.reset(
        new GlobalStackProfileTracker());
    context_.args_tracker.reset(new ArgsTracker(&context_));
    context_.args_translation_table.reset(new ArgsTranslationTable(storage_));
    context_.metadata_tracker.reset(
        new MetadataTracker(context_.storage.get()));
    event_ = new MockEventTracker(&context_);
    context_.event_tracker.reset(event_);
    sched_ = new MockSchedEventTracker(&context_);
    context_.sched_tracker.reset(sched_);
    process_ = new NiceMock<MockProcessTracker>(&context_);
    context_.process_tracker.reset(process_);
    slice_ = new NiceMock<MockSliceTracker>(&context_);
    context_.slice_tracker.reset(slice_);
    context_.slice_translation_table.reset(new SliceTranslationTable(storage_));
    context_.clock_tracker.reset(new ClockTracker(context_.storage.get()));
    clock_ = context_.clock_tracker.get();
    context_.flow_tracker.reset(new FlowTracker(&context_));
    context_.sorter.reset(new TraceSorter(&context_, CreateParser(),
                                          TraceSorter::SortingMode::kFullSort));
    context_.descriptor_pool_.reset(new DescriptorPool());

    RegisterDefaultModules(&context_);
    RegisterAdditionalModules(&context_);
  }

  void push_word(uint64_t word) { trace_bytes_.push_back(word); }

  void ResetTraceBuffers() {
    trace_bytes_.clear();
    // Write the FXT Magic Bytes
    push_word(0x0016547846040010);
  }

  void SetUp() override { ResetTraceBuffers(); }

  util::Status Tokenize() {
    const size_t num_bytes = trace_bytes_.size() * sizeof(uint64_t);
    std::unique_ptr<uint8_t[]> raw_trace(new uint8_t[num_bytes]);
    memcpy(raw_trace.get(), trace_bytes_.data(), num_bytes);
    context_.chunk_reader.reset(new FuchsiaTraceTokenizer(&context_));
    auto status = context_.chunk_reader->Parse(TraceBlobView(
        TraceBlob::TakeOwnership(std::move(raw_trace), num_bytes)));

    ResetTraceBuffers();
    return status;
  }

 protected:
  std::vector<uint64_t> trace_bytes_;
  std::unique_ptr<TraceParser> CreateParser() {
    return std::unique_ptr<TraceParser>(new FuchsiaTraceParser(&context_));
  }

  TraceProcessorContext context_;
  MockEventTracker* event_;
  MockSchedEventTracker* sched_;
  MockProcessTracker* process_;
  MockSliceTracker* slice_;
  ClockTracker* clock_;
  TraceStorage* storage_;
};

TEST_F(FuchsiaTraceParserTest, CorruptedFxt) {
  // Invalid record of size 0
  push_word(0x0016547846040000);
  EXPECT_FALSE(Tokenize().ok());
}

TEST_F(FuchsiaTraceParserTest, InlineInstantEvent) {
  // Inline name of 8 bytes
  uint64_t name_ref = uint64_t{0x8008} << 48;
  // Inline category of 8 bytes
  uint64_t category_ref = uint64_t{0x8008} << 32;
  // Inline threadref
  uint64_t threadref = uint64_t{0};
  // Instant Event
  uint64_t event_type = 0 << 16;
  uint64_t size = 6 << 4;
  uint64_t record_type = 4;

  auto header =
      name_ref | category_ref | threadref | event_type | size | record_type;
  push_word(header);
  // Timestamp
  push_word(0xAAAAAAAAAAAAAAAA);
  // Pid + tid
  push_word(0xBBBBBBBBBBBBBBBB);
  push_word(0xCCCCCCCCCCCCCCCC);
  // Inline Category
  push_word(0xDDDDDDDDDDDDDDDD);
  // Inline Name
  push_word(0xEEEEEEEEEEEEEEEE);
  EXPECT_TRUE(Tokenize().ok());
  EXPECT_EQ(context_.storage->stats()[stats::fuchsia_invalid_event].value, 0);
}

TEST_F(FuchsiaTraceParserTest, FxtWithProtos) {
  // Serialize some protos to bytes
  protozero::HeapBuffered<protos::pbzero::Trace> protos;
  {
    auto* packet = protos->add_packet();
    packet->set_trusted_packet_sequence_id(1);
    packet->set_incremental_state_cleared(true);
    auto* thread_desc = packet->set_thread_descriptor();
    thread_desc->set_pid(15);
    thread_desc->set_tid(16);
    thread_desc->set_reference_timestamp_us(1000);
    thread_desc->set_reference_thread_time_us(2000);
  }
  {
    auto* packet = protos->add_packet();
    packet->set_trusted_packet_sequence_id(1);
    auto* event = packet->set_track_event();
    event->set_timestamp_delta_us(10);   // absolute: 1010.
    event->set_thread_time_delta_us(5);  // absolute: 2005.
    event->add_category_iids(1);
    auto* legacy_event = event->set_legacy_event();
    legacy_event->set_name_iid(1);
    legacy_event->set_phase('B');
  }
  {
    auto* packet = protos->add_packet();
    packet->set_trusted_packet_sequence_id(1);
    auto* event = packet->set_track_event();
    event->set_timestamp_delta_us(10);   // absolute: 1020.
    event->set_thread_time_delta_us(5);  // absolute: 2010.
    event->add_category_iids(1);
    auto* legacy_event = event->set_legacy_event();
    legacy_event->set_name_iid(1);
    legacy_event->set_phase('E');
  }
  {
    auto* packet = protos->add_packet();
    packet->set_trusted_packet_sequence_id(1);
    auto* event = packet->set_track_event();
    event->set_timestamp_absolute_us(1005);
    event->set_thread_time_absolute_us(2003);
    event->add_category_iids(2);
    event->add_category_iids(3);
    auto* legacy_event = event->set_legacy_event();
    legacy_event->set_name_iid(2);
    legacy_event->set_phase('X');
    legacy_event->set_duration_us(23);         // absolute end: 1028.
    legacy_event->set_thread_duration_us(12);  // absolute end: 2015.
  }

  protos->Finalize();
  std::vector<uint8_t> perfetto_bytes = protos.SerializeAsArray();

  // Set up an FXT Perfetto Blob Header
  uint64_t blob_type_perfetto = uint64_t{3} << 48;
  uint64_t unpadded_blob_size_bytes = uint64_t{perfetto_bytes.size()} << 32;
  uint64_t blob_name_ref = uint64_t{0x8008} << 16;
  uint64_t size_words = ((perfetto_bytes.size() + 7) / 8 + 2) << 4;
  uint64_t record_type = 5;

  uint64_t header = blob_type_perfetto | unpadded_blob_size_bytes |
                    blob_name_ref | size_words | record_type;

  // Pad the blob to a multiple of 8 bytes.
  while (perfetto_bytes.size() % 8) {
    perfetto_bytes.push_back(0);
  }

  push_word(header);
  // Inline Name Ref
  push_word(0xBBBBBBBBBBBBBBBB);
  trace_bytes_.insert(trace_bytes_.end(),
                      reinterpret_cast<uint64_t*>(perfetto_bytes.data()),
                      reinterpret_cast<uint64_t*>(perfetto_bytes.data() +
                                                  perfetto_bytes.size()));
  EXPECT_CALL(*process_, UpdateThread(16, 15)).WillRepeatedly(Return(1u));

  tables::ThreadTable::Row row(16);
  row.upid = 1u;
  storage_->mutable_thread_table()->Insert(row);

  MockBoundInserter inserter;

  StringId unknown_cat = storage_->InternString("unknown(1)");
  ASSERT_NE(storage_, nullptr);

  constexpr TrackId track{0u};
  constexpr TrackId thread_time_track{1u};

  InSequence in_sequence;  // Below slices should be sorted by timestamp.
  // Only the begin thread time can be imported into the counter table.
  EXPECT_CALL(*event_, PushCounter(1005000, testing::DoubleEq(2003000),
                                   thread_time_track));
  EXPECT_CALL(*slice_, StartSlice(1005000, track, _, _))
      .WillOnce(DoAll(IgnoreResult(InvokeArgument<3>()),
                      InvokeArgument<2>(&inserter), Return(SliceId(0u))));
  EXPECT_CALL(*event_, PushCounter(1010000, testing::DoubleEq(2005000),
                                   thread_time_track));
  EXPECT_CALL(*slice_, StartSlice(1010000, track, _, _))
      .WillOnce(DoAll(IgnoreResult(InvokeArgument<3>()),
                      InvokeArgument<2>(&inserter), Return(SliceId(1u))));
  EXPECT_CALL(*event_, PushCounter(1020000, testing::DoubleEq(2010000),
                                   thread_time_track));
  EXPECT_CALL(*slice_, End(1020000, track, unknown_cat, kNullStringId, _))
      .WillOnce(DoAll(InvokeArgument<4>(&inserter), Return(SliceId(1u))));

  auto status = Tokenize();
  EXPECT_TRUE(status.ok());
  context_.sorter->ExtractEventsForced();
}

}  // namespace
}  // namespace trace_processor
}  // namespace perfetto


text:
<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;

class AdminController extends Controller
{
    /**
     * @Route("/admin/", name="admin")
     */
    public function indexAction()
    {
        return $this->render('admin/index.html.twig', [
            'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..').DIRECTORY_SEPARATOR,
        ]);
    }
}


text:
package mf.org.w3c.dom.svg;

public interface SVGLocatable {
  public SVGElement              getNearestViewportElement( );
  public SVGElement              getFarthestViewportElement( );

  public SVGRect   getBBox (  );
  public SVGMatrix getCTM (  );
  public SVGMatrix getScreenCTM (  );
  public SVGMatrix getTransformToElement ( SVGElement element )
                  throws SVGException;
}


text:
from translator.hot.syntax.hot_resource import HotResource

# Name used to dynamically load appropriate map class.
TARGET_CLASS_NAME = 'ToscaPolicies'

class ToscaPolicies(HotResource):
    '''Translate TOSCA policy type tosca.policies.Placement.'''

    toscatype = 'tosca.policies.Placement'

    def __init__(self, policy, csar_dir=None):
        super(ToscaPolicies, self).__init__(policy,
                                            type='OS::Nova::ServerGroup',
                                            csar_dir=csar_dir)
        self.policy = policy

    def handle_properties(self, resources):
        group_policy = "%(soft-prefix)s%(policy)s" % {
            "soft-prefix": "soft-" if not self.get_tosca_props().get(
                "strict", True) else "",
            "policy": self.get_tosca_props().get("policy", "affinity"),
        }
        self.properties["name"] = self.name
        self.properties["policies"] = [group_policy]
        for resource in resources:
            if resource.name in self.policy.targets:
                if not resource.properties.get("scheduler_hints"):
                    resource.properties["scheduler_hints"] = {}
                resource.properties["scheduler_hints"].update(
                    {"group": {"get_resource": self.name}})


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
null

#### Original name
Cantharellus helvelloides

### Remarks
null


text:
package com.orange.clara.cloud.services.sandbox.ui;

import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.annotation.Profile;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = ElpaasoSandboxUiApplication.class)
@WebAppConfiguration
//@ActiveProfiles("orange")
@Ignore("Enable with an UAA is launch during test")
public class ElpaasoSandboxUiApplicationTests {

	@Test
	public void contextLoads() {
	}

}