text:
/*jslint browser: true, node: true */
/*global $, PAPAYA_MENU_ICON_CSS, PAPAYA_MENU_LABEL_CSS, PAPAYA_TITLEBAR_CSS, PAPAYA_MENU_BUTTON_CSS, PAPAYA_MENU_CSS,
 PAPAYA_CUSTOM_PROTOCOL, PAPAYA_DIALOG_CSS, PAPAYA_DIALOG_BACKGROUND, alert, confirm */

"use strict";

var papaya = papaya || {};
papaya.ui = papaya.ui || {};

var papayaLoadableImages = papayaLoadableImages || [];

papaya.ui.Toolbar = papaya.ui.Toolbar || function (container) {
    this.container = container;
    this.viewer = container.viewer;
    this.imageMenus = null;
    this.spaceMenu = null;
};

papaya.ui.Toolbar.SIZE = 22;

// http://dataurl.net/#dataurlmaker
papaya.ui.Toolbar.ICON_IMAGESPACE = "data:image/gif;base64,R0lGODlhFAAUAPcAMf//////GP////////////////////////////////" +
    "////////////////////////////////////////////////////////////////////////////////////////////////////////////////" +
    "///////////////2f/ZNbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1t" +
    "bW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1tbW1qWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpa" +
    "WlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpa" +
    "WlpaWlpaWlpaWlpaWlpVpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWl" +
    "paWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWlpaWkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQk" +
    "JCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQk" +
    "JCQkJCQkJCQkJCQkJCQkJCQgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +
    "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAEAACoALAAAAAAUABQAAA" +
    "ipAFUIHEiwoMB/A1coXLiwisOHVf4hVLFCosWLGC9SzMgR48Z/VEJSUVjFj0mTESdWBCmS5EmU/6oIXCly5IqSLx/OlFjT5Us/DneybIkzp8yPDE" +
    "lChCjwj8Q/UKOqmkqVatOnUaGqmsaVq1UVTv+lGjv2z9SuXlVdFUs2ldmtaKeubev2bFy1YCXSfYt2mty8/6CS5XtXRcasVRMftJj1beK/hicanK" +
    "wiIAA7";

papaya.ui.Toolbar.ICON_WORLDSPACE = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAVCAYAAACpF6WWAAAAGXRFWHRTb2" +
    "Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAplJREFUeNqM1H1ozVEcx/Hr3p+7O08jQzbzMErznEItK0+Fv0Ye/tki20ia//wn+YMSaXkoEi" +
    "KkkCVKZhOipsnDstnFagzlrmGMNfeO6/Nd71unu2s59bq7O517ft/z/X7Pz+dLPUbLJrkqX+SbdEubfJZK2cC6PiOQYm61HJcpkintEpcmCcpryZ" +
    "V5spaHhvvbdJ9slsPyU67wgPlEli0X5aiMkMeyXSbKnVRRVxDRRtkm5czbZrv5vkgu8z1P9stWfleRHGkhT3xCLu1YzZIjpfKWnA6VEn43mwcWEa" +
    "Wlo1Ve2YZj5Jms53iP5BjFsFz9lg/yDj0U7JbslFpZQyBP2a83khoiLiWPA/h/OVGOk+GwnJ5y1iyRS5Im1VLm18cKOc+CYrlGjnxUuZPIOlAn0y" +
    "WdNXdlrMyRE7LM00eBjBT7niFVTvHsKJ8k6sw1yC4ZIl0EUMOcRT/X44v14xEZSBWfk+d8NpzKujgPGiYrOXI+XTGeGtjpewtjm16Qh3JT3sgvic" +
    "kfNo4yF6V4PVyE2wQUZvP7FmmIa/iDIpwkHRPkrC2iEIlhEZ2mtarIsz3sOoX0PPrP7nAWPRYjj51E85JiJEYO0VsfR5hL5wZal3T7aZl10kLiEy" +
    "NEHtOSbt4g/gaduRjzC+S9RwtZ332XBxQpzGZ+p72SR5BumUYHLaaDSiySUXKPig6Wj+SmjX5s4BQB0pFBQVo4dhenspfKC1kaYLKVa9pOAW5Q2W" +
    "w2qeU92kHbzZRDvK2sBSfLDLtNUp/82rOj7nDm9tJi7lhoeWNzG7Pkqxz8R5p8ByhcGVd0CzkOOWv28KBJvNGa+V2/Y5U08vQm8mgvmTNyjpxHSF" +
    "Uj6/9rZPKerGSTuCPCi7qIdX3GXwEGAPFYt+/OgAXDAAAAAElFTkSuQmCC";

papaya.ui.Toolbar.ICON_EXPAND =   "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAAE00lEQVR42u2d" +
    "jW3UQBCFJx3QAemAdJBQAVABTgekAqCC0EGOCoAKWDqADkIHKQGPfKdEh3Nr7493Z977pJWQwtk7+77ETs6zdyYEmrPWEyBtoQDgUABwKAA4FAAc" +
    "CgAOBQCHAoBDAcChAOBQAHAoADgUABwKAE6uALfjuGg094dx7Mbxo9H5D7wZxzCOF43O/3scN6kvzhXg5ziuGhV+4K20k0DD/964/jCO16kv9iCA" +
    "BvCu0bm/ySRgS4KAC7Abx3Wjc9/J9OO/JUGABXjYn/9Po/O/kimAVtd/EQMC6E1Krevkbhx/Kx17KSpBrcuAHjd2kx2kcwGUYRxfy60LBO9lEjxG" +
    "EAMCKINQgqUsDV8JYkQAZRBKEGNN+EqQzgTQa/6p69YglOA5YuHPrW2QzgT4NI77SCGDUIJjYuEP4ziXaX2fEqRDAT4vLIgSTCxdq49iSIA1hSGz" +
    "Zo3MCbC2QDTWro1JAVIKRSBlTcwKkFqwV1LXwrQAOYV7ImcNzAuQuwDWya3dhQAlFsIiJWp2I0CpBbFCqVpdCVByYXqmZI3uBCi9QL1RujaXAige" +
    "JahRk1sBFE8S1KrFtQCKBwlq1uBeAMWyBLXnDiGAYlGCLeYMI4BiSYKt5golgGJBgi3nCCeA0rMEW88NUgClRwlazKk7AeaaI3WCpQVQepKg1Vzm" +
    "BMhqjs0V4Lg9unavXg8StJzDS5keDX/ai5jVHl9ih5DDBgka/hep36jZMoAeBNRexA8ySaBzydobweoWMS2C6CH84lgVQNkyEJfhK5YFULYIxm34" +
    "inUBlFhA55K+h8DcTddTBjEcvuJBAOWUBIOkh3Qp0+/ZpY/bDV4EUJ6T4GocvxKP+ZwAgzgIX/EkgKIS6K+ihx/ZQTL+Srbn+K+dgzgJX/EmgKLX" +
    "7fP9v1O/84+53B8zSPs9iYriUQCyAgoADgUAhwKAQwHAoQDgUABwKAA4FAAcCgAOBQCHAoBDAcChAOB4FEDfDr6Sacfykm8Hy/6YfDu4Y46fCgpS" +
    "9oEQ7X3QZ/L5QEiH8JGwBLwIcOqh0CtJF6DWw6bd4EGAUyHpj2z9iJWcx8LvT3x9EOMSWBeAjSGZWBaArWEFsCoAm0MLwfZwO+c+0FV7+NwGETk3" +
    "XTF6CKDlHOY+rLrpBhHcImbbuXS3RQw3idp2Tt1tEsVt4rhNHDeK3HCOUAJYCH/rucIIYCn8LecMIYDF8Leau3sBLIe/RQ2uBfAQfu1a3ArgKfya" +
    "NbkUwGP4tWpzJ4Dn8GvU6EoAhPBL1+pGAKTwS9bsQgDE8EvVbl4A5PBLrIFpARj+I6lrYVYAhv8/KWtiUgCG/zxr18acAAw/zpo1MiUAw1/O0rUy" +
    "I8D9woLII0skOBcDAuhHrFxECmH488QkmFvbIJ0JcIpBGH6MmATHBDEiwCAMfylrJAhiQIBBGP5alkoQpHMB9Lr1PX6oJPS4tXsRY+geAkOlY2vX" +
    "1UXk/wTpXICa1P6w6hhzvXpbo+eHFUDZjeO60bnvpN53/1KCgAuQ1RyZyVxz7NYEARcgqz06k+P2+BYEaSjArcRvUmqh1/+dtAv/wGGDjFb3AXqT" +
    "fZP6YqtbxJBCUABwKAA4FAAcCgAOBQCHAoBDAcChAOBQAHAoADgUABwKAA4FAIcCgPMPvdAfn3qMP2kAAAAASUVORK5CYII=";

papaya.ui.Toolbar.ICON_COLLAPSE = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADEtGw7AAAEJGlDQ1BJQ0Mg" +
    "UHJvZmlsZQAAOBGFVd9v21QUPolvUqQWPyBYR4eKxa9VU1u5GxqtxgZJk6XtShal6dgqJOQ6N4mpGwfb6baqT3uBNwb8AUDZAw9IPCENBmJ72fbA" +
    "tElThyqqSUh76MQPISbtBVXhu3ZiJ1PEXPX6yznfOec7517bRD1fabWaGVWIlquunc8klZOnFpSeTYrSs9RLA9Sr6U4tkcvNEi7BFffO6+EdigjL" +
    "7ZHu/k72I796i9zRiSJPwG4VHX0Z+AxRzNRrtksUvwf7+Gm3BtzzHPDTNgQCqwKXfZwSeNHHJz1OIT8JjtAq6xWtCLwGPLzYZi+3YV8DGMiT4VVu" +
    "G7oiZpGzrZJhcs/hL49xtzH/Dy6bdfTsXYNY+5yluWO4D4neK/ZUvok/17X0HPBLsF+vuUlhfwX4j/rSfAJ4H1H0qZJ9dN7nR19frRTeBt4Fe9Fw" +
    "pwtN+2p1MXscGLHR9SXrmMgjONd1ZxKzpBeA71b4tNhj6JGoyFNp4GHgwUp9qplfmnFW5oTdy7NamcwCI49kv6fN5IAHgD+0rbyoBc3SOjczohby" +
    "S1drbq6pQdqumllRC/0ymTtej8gpbbuVwpQfyw66dqEZyxZKxtHpJn+tZnpnEdrYBbueF9qQn93S7HQGGHnYP7w6L+YGHNtd1FJitqPAR+hERCNO" +
    "Fi1i1alKO6RQnjKUxL1GNjwlMsiEhcPLYTEiT9ISbN15OY/jx4SMshe9LaJRpTvHr3C/ybFYP1PZAfwfYrPsMBtnE6SwN9ib7AhLwTrBDgUKcm06" +
    "FSrTfSj187xPdVQWOk5Q8vxAfSiIUc7Z7xr6zY/+hpqwSyv0I0/QMTRb7RMgBxNodTfSPqdraz/sDjzKBrv4zu2+a2t0/HHzjd2Lbcc2sG7GtsL4" +
    "2K+xLfxtUgI7YHqKlqHK8HbCCXgjHT1cAdMlDetv4FnQ2lLasaOl6vmB0CMmwT/IPszSueHQqv6i/qluqF+oF9TfO2qEGTumJH0qfSv9KH0nfS/9" +
    "TIp0Wboi/SRdlb6RLgU5u++9nyXYe69fYRPdil1o1WufNSdTTsp75BfllPy8/LI8G7AUuV8ek6fkvfDsCfbNDP0dvRh0CrNqTbV7LfEEGDQPJQad" +
    "BtfGVMWEq3QWWdufk6ZSNsjG2PQjp3ZcnOWWing6noonSInvi0/Ex+IzAreevPhe+CawpgP1/pMTMDo64G0sTCXIM+KdOnFWRfQKdJvQzV1+Bt8O" +
    "okmrdtY2yhVX2a+qrykJfMq4Ml3VR4cVzTQVz+UoNne4vcKLoyS+gyKO6EHe+75Fdt0Mbe5bRIf/wjvrVmhbqBN97RD1vxrahvBOfOYzoosH9bq9" +
    "4uejSOQGkVM6sN/7HelL4t10t9F4gPdVzydEOx83Gv+uNxo7XyL/FtFl8z9ZAHF4bBsrEwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAeJJREFUOBG1" +
    "lU1KA0EQhTP5c5MggkvFvQfQjS4iIcled3qBrDyCHsFsvEBcegBBkEBA0VuIW0UFBX8w4/c6VUMbAhoYG16qquvVm05Nd0+SpmlBI0mSogzxV5iY" +
    "8Yf6EiWUp6NQasJFWfPL7lucQIzzvoDAn6xxrsRDEXYVrE0S44dM86kJC1GtNKxeDy+ULFDiAbQsrpqtMFeXb3GNuDLBaVmtL6zkZH+qCPegGQm1" +
    "iftR3CduR3HTanxBY62I4OIiPoGOcoxdMIh4A81ZroMvblgINmiEnBcY0f++Cl6B2rMBzp0n3+aUE8cXEGqdVyaRDSY/FGDP2D4N3B64Bs/Ah/wd" +
    "sA4acG+U8Fr5GuHtIaItpb1cAW2gv18FEt0HC8CHfM0pVxXXavSSpRG0fMUK1NA5sAeWwSfQ6i7AEPhwf4mJAyDBO3AJVBO0dNLw8x+hFfnLsj0k" +
    "Slt0+kbYOuExiFuhng7JH2LFld0Ej2AeeCu6cF5cy3vs/XiDeAIWwS3Q298G8ZDoFuiBI7ACdKjegcZYSz2eBgjap1dAxafOkW9zyoUj7LnY/hCF" +
    "mNsByYQRzf9IR6L5XUKI/uXarHn/4Gvn/H5tQvqfi14rcXHzs6vPYh3RmT9N2ZHWxkYgt4/pN/LAOfka/AG9AAAAAElFTkSuQmCC";

papaya.ui.Toolbar.FILE_MENU_DATA = {"label": "File", "icons": null,
    "items": [
        {"label": "Add Image...", "action": "OpenImage", "type": "file", "hide": papaya.utilities.PlatformUtils.ios},
        {"label": "Add DICOM Folder...", "action": "OpenFolder", "type": "folder",
            "hide": ((papaya.utilities.PlatformUtils.browser !== "Chrome") || ((typeof(daikon) === "undefined"))) },
        {"type": "spacer"},
        {"label": "Close All", "action": "CloseAllImages"}
    ]
};

papaya.ui.Toolbar.RGB_FILE_MENU_DATA = {"label": "File", "icons": null,
    "items": [
        {"label": "Close All", "action": "CloseAllImages"}
    ]
};

papaya.ui.Toolbar.MENU_DATA = {
    "menus": [
        papaya.ui.Toolbar.FILE_MENU_DATA,
        {"label": "View", "icons": null,
            "items": [
                {"label": "Orientation", "action": "ShowOrientation", "type": "checkbox", "method": "isShowingOrientation"},
                {"label": "Ruler", "action": "ShowRuler", "type": "checkbox", "method": "isShowingRuler"},
                {"label": "Main Crosshairs", "action": "ShowMainCrosshairs", "type": "checkbox", "method": "isShowingMainCrosshairs"},
                {"label": "Lower Crosshairs", "action": "ShowLowerCrosshairs", "type": "checkbox", "method": "isShowingLowerCrosshairs"}
            ]
        },
        {"label": "Options", "icons": null,
            "items": [
                {"label": "Preferences", "action": "Preferences"},
                {"label": "Show Keyboard Reference", "action": "KeyboardRef"},
                {"label": "Show Mouse Reference", "action": "MouseRef"},
                {"label": "Show License", "action": "License"}
            ]
            },
        {"label": "", "icons": null, "titleBar": "true" },
        {"label": "EXPAND", "icons": [papaya.ui.Toolbar.ICON_EXPAND, papaya.ui.Toolbar.ICON_COLLAPSE], "items": [],
            "method": "isCollapsable", "required": "isExpandable" },
        {"label": "SPACE", "icons": [papaya.ui.Toolbar.ICON_IMAGESPACE, papaya.ui.Toolbar.ICON_WORLDSPACE],
            "items": [], "method": "isWorldMode", "menuOnHover": true }
    ]
};

papaya.ui.Toolbar.MENU_DATA_KIOSK = {
    "menus": [
        {"label": "EXPAND", "icons": [papaya.ui.Toolbar.ICON_EXPAND, papaya.ui.Toolbar.ICON_COLLAPSE], "items": [],
            "method": "isCollapsable", "required": "isExpandable" }
    ]
};

papaya.ui.Toolbar.OVERLAY_IMAGE_MENU_DATA = {
    "items": [
        {"label": "Show Header", "action": "ShowHeader"},
        {"label": "Show Image Info", "action": "ImageInfo"},
        {"type": "spacer", "required": "isParametricCombined"},
        {"label": "DisplayRange", "action": "ChangeRange", "type": "displayrange", "method": "getRange"},
        {"label": "Transparency", "action": "ChangeAlpha", "type": "range", "method": "getAlpha"},
        {"label": "Color Table...", "action": "ColorTable", "items": [], "required": "isNonParametricCombined" },
        {"type": "spacer", "required": "isParametricCombined"},
        {"label": "DisplayRange", "action": "ChangeRangeNeg", "type": "displayrange", "method": "getRangeNegative", "required": "isParametricCombined"},
        {"label": "Transparency", "action": "ChangeAlphaNeg", "type": "range", "method": "getAlpha", "required": "isParametricCombined"},
        {"type": "spacer", "required": "isParametricCombined"},
        {"label": "Close Overlay", "action": "CloseOverlay", "required": "isDesktopMode" },
        {"label": "Open in Mango", "action": "OpenInMango", "required" : "canOpenInMango" }
    ]
};

papaya.ui.Toolbar.BASE_IMAGE_MENU_DATA = {
    "items": [
        {"label": "Show Header", "action": "ShowHeader"},
        {"label": "Show Image Info", "action": "ImageInfo"},
        {"label": "DisplayRange", "action": "ChangeRange", "type": "displayrange", "method": "getRange"},
        papaya.ui.Toolbar.OVERLAY_IMAGE_MENU_DATA.items[5],
        {"label": "Open in Mango", "action": "OpenInMango", "required" : "canOpenInMango"  }
    ]
};

papaya.ui.Toolbar.RGB_IMAGE_MENU_DATA = {
    "items": [
        {"label": "Show Header", "action": "ShowHeader"},
        {"label": "Show Image Info", "action": "ImageInfo"},
        {"label": "Open in Mango", "action": "OpenInMango", "required" : "canOpenInMango"  }
    ]
};

papaya.ui.Toolbar.PREFERENCES_DATA = {
    "items": [
        {"label": "Coordinate display of:", "field": "atlasLocks", "options": ["Mouse", "Crosshairs"]},
        {"label": "Scroll wheel behavior:", "field": "scrollBehavior", "options": ["Zoom", "Increment Slice"],
            "disabled": "container.disableScrollWheel"},
        {"spacer": "true"},
        {"label": "Smooth display:", "field": "smoothDisplay", "options": ["Yes", "No"]},
        {"label": "Radiological display:", "field": "radiological", "options": ["Yes", "No"]}
    ]
};

papaya.ui.Toolbar.IMAGE_INFO_DATA = {
    "items": [
        {"label": "Filename:", "field": "getFilename", "readonly": "true"},
        {"spacer": "true"},
        {"label": "Image Dims:", "field": "getImageDimensionsDescription", "readonly": "true"},
        {"label": "Voxel Dims:", "field": "getVoxelDimensionsDescription", "readonly": "true"},
        {"spacer": "true"},
        {"label": "Byte Type:", "field": "getByteTypeDescription", "readonly": "true"},
        {"label": "Byte Order:", "field": "getByteOrderDescription", "readonly": "true"},
        {"spacer": "true"},
        {"label": "Orientation:", "field": "getOrientationDescription", "readonly": "true"},
        {"spacer": "true"},
        {"label": "Notes:", "field": "getImageDescription", "readonly": "true"}
    ]
};

papaya.ui.Toolbar.SERIES_INFO_DATA = {
    "items": [
        {"label": "Filename:", "field": "getFilename", "readonly": "true"},
        {"label": "File Length:", "field": "getFileLength", "readonly": "true"},
        {"spacer": "true"},
        {"label": "Image Dims:", "field": "getImageDimensionsDescription", "readonly": "true"},
        {"label": "Voxel Dims:", "field": "getVoxelDimensionsDescription", "readonly": "true"},
        {"label": "Series Points:", "field": "getSeriesDimensionsDescription", "readonly": "true"},
        {"label": "Series Point Size:", "field": "getSeriesSizeDescription", "readonly": "true"},
        {"spacer": "true"},
        {"label": "Byte Type:", "field": "getByteTypeDescription", "readonly": "true"},
        {"label": "Byte Order:", "field": "getByteOrderDescription", "readonly": "true"},
        {"label": "Compressed:", "field": "getCompressedDescription", "readonly": "true"},
        {"spacer": "true"},
        {"label": "Orientation:", "field": "getOrientationDescription", "readonly": "true"},
        {"label": "Notes:", "field": "getImageDescription", "readonly": "true"}
    ]
};

papaya.ui.Toolbar.HEADER_DATA = {
    "items": [
        {"label": "", "field": "getHeaderDescription", "readonly": "true"}
    ]
};

papaya.ui.Toolbar.LICENSE_DATA = {
    "items": [
        {"label": "", "field": "getLicense", "readonly": "true"}
    ]
};

papaya.ui.Toolbar.KEYBOARD_REF_DATA = {
    "items": [
        {"label": "", "field": "getKeyboardReference", "readonly": "true"}
    ]
};

papaya.ui.Toolbar.MOUSE_REF_DATA = {
    "items": [
        {"label": "", "field": "getMouseReference", "readonly": "true"}
    ]
};

papaya.ui.Toolbar.prototype.buildToolbar = function () {
    var ctr;

    this.imageMenus = null;
    this.spaceMenu = null;

    this.container.toolbarHtml.find("." + PAPAYA_MENU_ICON_CSS).remove();
    this.container.toolbarHtml.find("." + PAPAYA_MENU_LABEL_CSS).remove();
    this.container.toolbarHtml.find("." + PAPAYA_TITLEBAR_CSS).remove();

    if (this.container.kioskMode) {
        for (ctr = 0; ctr < papaya.ui.Toolbar.MENU_DATA_KIOSK.menus.length; ctr += 1) {
            this.buildMenu(papaya.ui.Toolbar.MENU_DATA_KIOSK.menus[ctr], null, this.viewer, null);
        }
    } else {
        if ((this.container.viewer.screenVolumes.length > 0) && this.container.viewer.screenVolumes[0].rgb) {
            papaya.ui.Toolbar.MENU_DATA.menus[0] = papaya.ui.Toolbar.RGB_FILE_MENU_DATA;
        } else {
            papaya.ui.Toolbar.MENU_DATA.menus[0] = papaya.ui.Toolbar.FILE_MENU_DATA;
            this.buildOpenMenuItems(papaya.ui.Toolbar.MENU_DATA);
        }

        for (ctr = 0; ctr < papaya.ui.Toolbar.MENU_DATA.menus.length; ctr += 1) {
            this.buildMenu(papaya.ui.Toolbar.MENU_DATA.menus[ctr], null, this.viewer, null);
        }

        this.buildAtlasMenu();
    }

    this.buildColorMenuItems();

    this.container.titlebarHtml = this.container.containerHtml.find("." + PAPAYA_TITLEBAR_CSS);
    if (this.container.getViewerDimensions()[0] < 600) {
        this.container.titlebarHtml.css({visibility: "hidden"});
    } else {
        this.container.titlebarHtml.css({visibility: "visible"});
    }
};

papaya.ui.Toolbar.prototype.buildAtlasMenu = function () {
    if (papaya.data) {
        if (papaya.data.Atlas) {
            var items = this.spaceMenu.items;

            items[0] = {"label": papaya.data.Atlas.labels.atlas.header.name, "action": "AtlasChanged-" +
                papaya.data.Atlas.labels.atlas.header.name, "type": "radiobutton", "method": "isUsingAtlas"};

            if (papaya.data.Atlas.labels.atlas.header.transformedname) {
                items[1] = {"label": papaya.data.Atlas.labels.atlas.header.transformedname, "action": "AtlasChanged-" +
                    papaya.data.Atlas.labels.atlas.header.transformedname, "type": "radiobutton",
                        "method": "isUsingAtlas"};
            }
        }
    }
};

papaya.ui.Toolbar.prototype.buildColorMenuItems = function () {
    var items, ctr, allColorTables, item, screenParams;

    screenParams = this.container.params.luts;
    if (screenParams) {
        for (ctr = 0; ctr < screenParams.length; ctr += 1) {
            papaya.viewer.ColorTable.addCustomLUT(screenParams[ctr]);
        }
    }

    allColorTables = papaya.viewer.ColorTable.TABLE_ALL;
    items = papaya.ui.Toolbar.OVERLAY_IMAGE_MENU_DATA.items;

    for (ctr = 0; ctr < items.length; ctr += 1) {
        if (items[ctr].label === "Color Table...") {
            items = items[ctr].items;
            break;
        }
    }

    for (ctr = 0; ctr < allColorTables.length; ctr += 1) {
        item = {"label": allColorTables[ctr].name, "action": "ColorTable-" + allColorTables[ctr].name,
            "type": "radiobutton", "method": "isUsingColorTable"};
        items[ctr] = item;
    }
};

papaya.ui.Toolbar.prototype.buildOpenMenuItems = function (menuData) {
    var ctr, items, menuItemName;

    for (ctr = 0; ctr < menuData.menus.length; ctr += 1) {
        if (menuData.menus[ctr].label === "File") {
            items = menuData.menus[ctr].items;
            break;
        }
    }

    if (items) {
        for (ctr = 0; ctr < papayaLoadableImages.length; ctr += 1) {
            if (!papayaLoadableImages[ctr].hide) {
                menuItemName = "Add " + papayaLoadableImages[ctr].nicename;
                if (!this.menuContains(items, menuItemName)) {
                    items.splice(2, 0, {"label": menuItemName, "action": "Open-" + papayaLoadableImages[ctr].name});
                }
            }
        }
    }
};

papaya.ui.Toolbar.prototype.menuContains = function (menuItems, name) {
    var ctr;

    if (menuItems) {
        for (ctr = 0; ctr < menuItems.length; ctr += 1) {
            if (menuItems[ctr].label === name) {
                return true;
            }
        }
    }

    return false;
};

papaya.ui.Toolbar.prototype.buildMenu = function (menuData, topLevelButtonId, dataSource, modifier) {
    var menu = null, items;

    if (!menuData.required || ((papaya.utilities.ObjectUtils.bind(this.container, papaya.utilities.ObjectUtils.dereferenceIn(this.container, menuData.required)))() === true)) {
        menu = new papaya.ui.Menu(this.viewer, menuData, papaya.utilities.ObjectUtils.bind(this, this.doAction), this.viewer, modifier);

        if (menuData.label === "SPACE") {
            this.spaceMenu = menuData;
        }

        if (topLevelButtonId) {
            menu.setMenuButton(topLevelButtonId);
        } else {
            topLevelButtonId = menu.buildMenuButton();
        }

        items = menuData.items;
        if (items) {
            this.buildMenuItems(menu, items, topLevelButtonId, dataSource, modifier);
        }
    }

    return menu;
};

papaya.ui.Toolbar.prototype.buildMenuItems = function (menu, itemData, topLevelButtonId, dataSource, modifier) {
    var ctrItems, item, menu2;

    if (modifier === undefined) {
        modifier = "";
    }

    for (ctrItems = 0; ctrItems < itemData.length; ctrItems += 1) {
        if (!itemData[ctrItems].required || ((papaya.utilities.ObjectUtils.bind(this.container,
                papaya.utilities.ObjectUtils.dereferenceIn(this.container,
                itemData[ctrItems].required)))(parseInt(modifier)) === true)) {
            if (itemData[ctrItems].type === "spacer") {
                item = new papaya.ui.MenuItemSpacer();
            } else if (itemData[ctrItems].type === "radiobutton") {
                item = new papaya.ui.MenuItemRadioButton(this.viewer, itemData[ctrItems].label, itemData[ctrItems].action,
                    papaya.utilities.ObjectUtils.bind(this, this.doAction), dataSource, itemData[ctrItems].method, modifier);
            } else if (itemData[ctrItems].type === "checkbox") {
                item = new papaya.ui.MenuItemCheckBox(this.viewer, itemData[ctrItems].label, itemData[ctrItems].action,
                    papaya.utilities.ObjectUtils.bind(this, this.doAction), dataSource, itemData[ctrItems].method, modifier);
            }else if (itemData[ctrItems].type === "file") {
                if (!itemData[ctrItems].hide) {
                    item = new papaya.ui.MenuItemFileChooser(this.viewer, itemData[ctrItems].label,
                        itemData[ctrItems].action, papaya.utilities.ObjectUtils.bind(this, this.doAction), false);
                }
            } else if (itemData[ctrItems].type === "folder") {
                if (!itemData[ctrItems].hide) {
                    item = new papaya.ui.MenuItemFileChooser(this.viewer, itemData[ctrItems].label,
                        itemData[ctrItems].action, papaya.utilities.ObjectUtils.bind(this, this.doAction), true);
                } else {
                    item = null;
                }
            } else if (itemData[ctrItems].type === "displayrange") {
                item = new papaya.ui.MenuItemRange(this.viewer, itemData[ctrItems].label, itemData[ctrItems].action,
                    papaya.utilities.ObjectUtils.bind(this, this.doAction), dataSource, itemData[ctrItems].method, modifier);
            } else if (itemData[ctrItems].type === "range") {
                if (papaya.utilities.PlatformUtils.isInputRangeSupported()) {
                    item = new papaya.ui.MenuItemSlider(this.viewer, itemData[ctrItems].label,
                        itemData[ctrItems].action, papaya.utilities.ObjectUtils.bind(this, this.doAction), dataSource,
                        itemData[ctrItems].method, modifier);
                }
            } else {
                item = new papaya.ui.MenuItem(this.viewer, itemData[ctrItems].label, itemData[ctrItems].action,
                    papaya.utilities.ObjectUtils.bind(this, this.doAction), modifier);
            }
        } else {
            item = null;
        }

        if (item) {
            menu.addMenuItem(item);

            if (itemData[ctrItems].items) {
                menu2 = this.buildMenu(itemData[ctrItems], topLevelButtonId, dataSource, modifier);
                item.callback = papaya.utilities.ObjectUtils.bind(menu2, menu2.showMenu);
            }
        }
    }
};

papaya.ui.Toolbar.prototype.updateImageButtons = function () {
    var ctr, screenVol, dataUrl, data;

    this.container.toolbarHtml.find("." + PAPAYA_MENU_BUTTON_CSS).remove();

    this.imageMenus = [];

    for (ctr = this.viewer.screenVolumes.length - 1; ctr >= 0; ctr -= 1) {
        screenVol = this.viewer.screenVolumes[ctr];
        dataUrl = screenVol.colorTable.icon;

        data = {
            "menus" : [
                {"label": "ImageButton", "icons": [dataUrl], "items": null, "imageButton": true}
            ]
        };

        if (ctr === 0) {
            if (screenVol.rgb) {
                data.menus[0].items = papaya.ui.Toolbar.RGB_IMAGE_MENU_DATA.items;
            } else {
                data.menus[0].items = papaya.ui.Toolbar.BASE_IMAGE_MENU_DATA.items;
            }
        } else {
            data.menus[0].items = papaya.ui.Toolbar.OVERLAY_IMAGE_MENU_DATA.items;
        }

        if (!this.container.combineParametric || !screenVol.parametric) {
            this.imageMenus.push((this.buildMenu(data.menus[0], null, screenVol, ctr.toString())));
        }
    }
};

papaya.ui.Toolbar.prototype.closeAllMenus = function () {
    var menuHtml, modalDialogHtml, modalDialogBackgroundHtml;

    menuHtml = this.container.toolbarHtml.find("." + PAPAYA_MENU_CSS);
    menuHtml.hide(100);
    menuHtml.remove();

    if (this.container.showControlBar) {
        menuHtml = this.container.sliderControlHtml.find("." + PAPAYA_MENU_CSS);
        menuHtml.hide(100);
        menuHtml.remove();
    }

    modalDialogHtml = this.container.toolbarHtml.find("." + PAPAYA_DIALOG_CSS);
    modalDialogHtml.hide(100);
    modalDialogHtml.remove();

    modalDialogBackgroundHtml = this.container.toolbarHtml.find("." + PAPAYA_DIALOG_BACKGROUND);
    modalDialogBackgroundHtml.hide(100);
    modalDialogBackgroundHtml.remove();
};

papaya.ui.Toolbar.prototype.isShowingMenus = function () {
    var menuVisible, dialogVisible;

    menuVisible = this.container.toolbarHtml.find("." + PAPAYA_MENU_CSS).is(":visible");
    dialogVisible = this.container.toolbarHtml.find("." + PAPAYA_DIALOG_CSS).is(":visible");

    return (menuVisible || dialogVisible);
};

papaya.ui.Toolbar.prototype.doAction = function (action, file, keepopen) {
    var imageIndex, colorTableName, dialog, atlasName, imageName, screenVol, screenVolNeg;

    if (!keepopen) {
        this.closeAllMenus();
    }

    if (action) {
        if (action.startsWith("ImageButton")) {
            imageIndex = parseInt(action.substr(action.length - 2, 1), 10);
            this.viewer.setCurrentScreenVol(imageIndex);
            this.updateImageButtons();
        } else if (action.startsWith("Open-")) {
            imageName = action.substring(action.indexOf("-") + 1);
            this.viewer.loadImage(imageName);
        } else if (action === "OpenImage") {
            this.container.display.drawProgress(0.1, "Loading");
            this.viewer.loadImage(file);
        } else if (action === "OpenFolder") {
            this.container.display.drawProgress(0.1, "Loading");
            this.viewer.loadImage(file);
        } else if (action.startsWith("ColorTable")) {
            colorTableName = action.substring(action.indexOf("-") + 1, action.lastIndexOf("-"));
            imageIndex = action.substring(action.lastIndexOf("-") + 1);
            this.viewer.screenVolumes[imageIndex].changeColorTable(this.viewer, colorTableName);
            this.updateImageButtons();
        } else if (action.startsWith("CloseAllImages")) {
            this.viewer.resetViewer();
            this.updateImageButtons();
        } else if (action === "Preferences") {
            dialog = new papaya.ui.Dialog(this.container, "Preferences", papaya.ui.Toolbar.PREFERENCES_DATA,
                this.container.preferences, papaya.utilities.ObjectUtils.bind(this.container.preferences,
                    this.container.preferences.updatePreference),
                    papaya.utilities.ObjectUtils.bind(this,
                        function() {
                            this.viewer.updateScreenSliceTransforms();
                            this.viewer.drawViewer(false, true);
                        }
                    )
            );
            dialog.showDialog();
        } else if (action === "License") {
            dialog = new papaya.ui.Dialog(this.container, "License", papaya.ui.Toolbar.LICENSE_DATA,
                papaya.Container, null, null, null, true);
            dialog.showDialog();
        } else if (action === "KeyboardRef") {
            dialog = new papaya.ui.Dialog(this.container, "Keyboard Reference", papaya.ui.Toolbar.KEYBOARD_REF_DATA,
                papaya.Container, null, null, null, true);
            dialog.showDialog();
        } else if (action === "MouseRef") {
            dialog = new papaya.ui.Dialog(this.container, "Mouse Reference", papaya.ui.Toolbar.MOUSE_REF_DATA,
                papaya.Container, null, null, null, true);
            dialog.showDialog();
        } else if (action.startsWith("ImageInfo")) {
            imageIndex = action.substring(action.lastIndexOf("-") + 1);

            if (this.viewer.screenVolumes[imageIndex].volume.numTimepoints > 1) {
                dialog = new papaya.ui.Dialog(this.container, "Image Info", papaya.ui.Toolbar.SERIES_INFO_DATA,
                    this.viewer, null, null, imageIndex.toString());
            } else {
                dialog = new papaya.ui.Dialog(this.container, "Image Info", papaya.ui.Toolbar.IMAGE_INFO_DATA,
                    this.viewer, null, null, imageIndex.toString());
            }

            dialog.showDialog();
        } else if (action.startsWith("ShowHeader")) {
            imageIndex = action.substring(action.lastIndexOf("-") + 1);

            dialog = new papaya.ui.Dialog(this.container, "Header", papaya.ui.Toolbar.HEADER_DATA,
                this.viewer, null, null, imageIndex.toString());

            dialog.showDialog();
        } else if (action.startsWith("SPACE")) {
            this.viewer.toggleWorldSpace();
            this.viewer.drawViewer(true);
        } else if (action.startsWith("AtlasChanged")) {
            atlasName = action.substring(action.lastIndexOf("-") + 1);
            this.viewer.atlas.currentAtlas = atlasName;
            this.viewer.drawViewer(true);
        } else if (action.startsWith("ShowRuler")) {
            if (this.container.preferences.showRuler === "Yes") {
                this.container.preferences.updatePreference("showRuler", "No");
            } else {
                this.container.preferences.updatePreference("showRuler", "Yes");
            }
            this.viewer.drawViewer();
            this.closeAllMenus();
        } else if (action.startsWith("ShowOrientation")) {
            if (this.container.preferences.showOrientation === "Yes") {
                this.container.preferences.updatePreference("showOrientation", "No");
            } else {
                this.container.preferences.updatePreference("showOrientation", "Yes");
            }
            this.viewer.drawViewer();
            this.closeAllMenus();
        } else if (action.startsWith("ShowMainCrosshairs")) {
            if (this.container.preferences.showCrosshairs === "All") {
                this.container.preferences.updatePreference("showCrosshairs", "Lower");
            } else if (this.container.preferences.showCrosshairs === "Main") {
                this.container.preferences.updatePreference("showCrosshairs", "None");
            } else if (this.container.preferences.showCrosshairs === "Lower") {
                this.container.preferences.updatePreference("showCrosshairs", "All");
            } else {
                this.container.preferences.updatePreference("showCrosshairs", "Main");
            }
            this.viewer.drawViewer();
            this.closeAllMenus();
        } else if (action.startsWith("ShowLowerCrosshairs")) {
            if (this.container.preferences.showCrosshairs === "All") {
                this.container.preferences.updatePreference("showCrosshairs", "Main");
            } else if (this.container.preferences.showCrosshairs === "Main") {
                this.container.preferences.updatePreference("showCrosshairs", "All");
            } else if (this.container.preferences.showCrosshairs === "Lower") {
                this.container.preferences.updatePreference("showCrosshairs", "None");
            } else {
                this.container.preferences.updatePreference("showCrosshairs", "Lower");
            }
            this.viewer.drawViewer();
            this.closeAllMenus();
        } else if (action.startsWith("EXPAND")) {
            if (this.container.collapsable) {
                this.container.collapseViewer();
            } else {
                this.container.expandViewer();
            }
        } else if (action.startsWith("OpenInMango")) {
            imageIndex = parseInt(action.substring(action.lastIndexOf("-") + 1), 10);

            if (imageIndex === 0) {
                if (this.container.viewer.volume.urls[0]) {
                    papaya.utilities.PlatformUtils.launchCustomProtocol(this.container, papaya.utilities.UrlUtils.getAbsoluteUrl(PAPAYA_CUSTOM_PROTOCOL,
                        this.container.viewer.volume.urls[0]), this.customProtocolResult);
                }
            } else {
                if (this.container.viewer.screenVolumes[imageIndex].volume.urls[0]) {
                    papaya.utilities.PlatformUtils.launchCustomProtocol(this.container, papaya.utilities.UrlUtils.getAbsoluteUrl(PAPAYA_CUSTOM_PROTOCOL,
                        this.container.viewer.screenVolumes[imageIndex].volume.urls[0]) + "?" +
                    encodeURIComponent("baseimage=" + this.container.viewer.volume.fileName + "&params=o"),
                        this.customProtocolResult);
                }
            }
        } else if (action.startsWith("CloseOverlay")) {
            imageIndex = parseInt(action.substring(action.lastIndexOf("-") + 1), 10);
            screenVol = this.container.viewer.screenVolumes[imageIndex];
            screenVolNeg = screenVol.negativeScreenVol;

            this.container.viewer.closeOverlayByRef(screenVol);

            if (this.container.combineParametric) {
                this.container.viewer.closeOverlayByRef(screenVolNeg);
            }

            this.container.viewer.drawViewer(true, false);
        }
    }
};

papaya.ui.Toolbar.prototype.customProtocolResult = function (success) {
    if (success === false) { // initiated by a setTimeout, so popup blocker will interfere with window.open
        if ((papaya.utilities.PlatformUtils.browser === "Chrome") || (papaya.utilities.PlatformUtils.browser === "Internet Explorer")) {
            alert("Mango does not appear to be installed.  You can download Mango at:\n\nhttp://ric.uthscsa.edu/mango");
        } else {
            if (papaya.utilities.PlatformUtils.ios) {
                if (confirm("iMango does not appear to be installed.  Would you like to download it now?")) {
                    window.open("http://itunes.apple.com/us/app/imango/id423626092");
                }
            } else {
                if (confirm("Mango does not appear to be installed.  Would you like to download it now?")) {
                    window.open("http://ric.uthscsa.edu/mango/mango.html");
                }
            }
        }
    }
};

papaya.ui.Toolbar.prototype.updateTitleBar = function (title) {
    var elem = this.container.titlebarHtml[0];

    if (elem) {
        elem.innerHTML = title;
    }

    this.container.titlebarHtml.css({top: (this.container.viewerHtml.position().top - 1.25 * papaya.ui.Toolbar.SIZE)});
};

papaya.ui.Toolbar.prototype.showImageMenu = function (index) {
    this.viewer.screenVolumes[index].resetDynamicRange();
    this.imageMenus[index].showMenu();
};

papaya.ui.Toolbar.prototype.updateImageMenuRange = function (index, min, max) {
    this.imageMenus[index].updateRangeItem(min, max);
};


text:
{% load i18n %}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">

<link rel="stylesheet" href="http://www.gilsonsoftware.com/jquery/jquery.mobile-1.0.1.min.css" />
<link rel="stylesheet" href="http://www.gilsonsoftware.com/jquery/index.css" >

{%  block  extra %}
{% endblock %}

{% block content %}

        {% csrf_token %}

{% trans 'Resident Complaint System' %}

                        {% trans 'Email Address' %}
                        <input type="input" name="email_address" id="login-email_address" value="{{ email_address }}" class="fields-interior" />

{% trans 'OR' %}

                        {% trans 'Last Name' %}
                        <input type="input" name="last_name" id="last_name" value="{{ last_name }}" class="fields-interior" />

{% trans 'Must fill out last 4 of SSN' %}

                        {% trans 'Last four digits of SSN' %}
                        <input type="input"  name="last_four" id="last_four" value="" class="fields-interior" maxlength="4" />

{% trans 'We could not find anyone with the credentials provided' %}

{% trans 'Please, try again' %}.

                <fieldset class="ui-grid-b">

                        {% trans 'Back' %}

                        {% trans 'Resident Log In' %}

                </fieldset>

{% trans 'Update Your E-MAIL Information' %}

{% trans 'Our system does not have your email information neccessary for communicating with you.' %}

                {% trans 'Please provide your email account information before continue.' %}
                {% trans 'If you still does not have an email account, you can use the links below to create your new email account.' %}
                {% trans 'All of these accounts are free and secure.' %}

            <fieldset class="ui-grid-c" >

                        Gmail

                        Yahoo

                        Hotmail

            </fieldset>

                {% trans 'Email Address' %}:
                <input type="text" id="create-id-email" name="email" value="" maxlength = "30" />

                {% trans 'Re-type Email Address' %}:
                <input type="text" id="create-id-email2" name="email2" value="" maxlength = "30" />

            <fieldset class="ui-grid-b">

 {% trans 'Back' %}

 {% trans 'Add Work Order' %}

            </fieldset>

{% trans 'New Resident Complaint' %}

            <fieldset  >

                    {% trans 'Project Name' %}:
                    <input type="text" id="id-project" name="project" value="" maxlength = "30" disabled="disabled" />

                    {% trans 'Building' %}:
                    <input type="text" id="id-building" name="building" value="" maxlength = "30" disabled="disabled"/>

                    {% trans 'Unit' %}:
                    <input type="text" id="id-unit" name="unit" value="" maxlength = "30" disabled="disabled" />

                    {% trans 'Tenant' %}:
                    <input type="text" id="id-tenant" name="tenant" value="" maxlength = "30" disabled="disabled"/>

                    {% trans 'Address' %}:
                    <input type="text" id="id-address" name="address" value="" maxlength = "30" disabled="disabled" />

            </fieldset>

                Complaint Type:
                <select name="log-type" id="id-log-types">
                    <option value="">---------</option>
                    <option value="18" selected="selected">{% trans 'Maintenance Issues' %}</option>
                    <option value="16">{% trans 'Tenant Health Issues' %}</option>
                    <option value="17">{% trans 'Safety Issues' %}</option>
                </select>

                    Issue Type
                    <select name="issue" id="id-issue">
                    </select>

                {% trans 'Complaint Notes' %}:
                <textarea id="id-notes" name="notes" cols="40" rows="12" ></textarea>

                    {% trans 'Back' %}

                    {% trans 'Add Complaint' %}

 {%  trans "Your complaint has been successfully processed" %}

                A message with the newly added resident complaint information was sent to your email address, the landlord and the CA

                <fieldset class="ui-grid-b">

 {% trans 'Add More Complaints' %}

{% trans 'Done - Log Out' %}

                </fieldset>

Action Selection

Please, choose an action to perform

                    Add New Complaint

                    View Complaints' Status

            <fieldset class="ui-grid-b">

 {% trans 'Back' %}

{% trans 'Done - Log Out' %}

            </fieldset>

{%  endblock %}

redpajama_set_name: RedPajamaGithub


text:
// Interface container and event handling   THIS SHOULD BE IN A SEPARATE LIBRARY  > > >>

#ifndef GFX_INTERFACE_H_INCLUDED
#define GFX_INTERFACE_H_INCLUDED

#include "gfx_scene.h"
#include "gfx_glu.h"
#include <sstream>
#include <map>

namespace gfx{

   struct MouseData {

        enum  {
            Up = 1, Down, Left, Right
        };

		float x, y, dx, dy, ddx, ddy, xrel, yrel; //< 2D Mouse Position, first and second derivatives of motion, position relative to TL corner

        Vec3f origin, click, pos, move, accel, cat, drag, dragAccum, dragCat, projectFar, projectNear, projectMid;

		Vec3f biv, bivCat, dragBiv, dragBivCat;

        int gesture;  // stores major direction of mouse movement

		bool isDown, isMoving, newClick;
		void toggle() { newClick = !newClick; }
	};

	struct ViewData  {
		float w, h;
        Vec3f z;
        Vec3f ray, clickray;
	};

	struct KeyboardData {
		bool shift, alt, caps, ctrl, meta, f, down;
		int code;
		KeyboardData() : shift(0), alt(0), caps(0), ctrl(0), code(0){}
	};

    /* Mapped Key values ripped from GLV */
    namespace Key{
        enum {

            // Standard ASCII non-printable characters
            Enter		=3,		/**< */
            Backspace	=8,		/**< */
            Tab			=9,		/**< */
            Return		=13,	/**< */
            Escape		=27,	/**< */
            Delete		=127,	/**< */

            // Non-standard, but common keys.
            F1=256, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12,
            Insert, Left, Up, Right, Down, PageDown, PageUp, End, Home
        };
    }

    /*! Abstract Interface Class */
    class Interface {

        int mMode;  ///< Edit Mode State (not implemented)
		float mRotVel, mVel, mModelRotVel;

    public:

        Scene * scene;

        typedef std::map<string,bool> SBMap;

        /// Map of object addresses and whether they are selected
        SBMap selectMap;

        /*! Abstract View Implementation Data to store info from Windowing System */

        struct Impl {

            Interface * interface;

            Impl(Interface * i) : interface(i) {}          // App must register with Interface  upon construction

            virtual ~Impl(){}

			// MPose * camera;
			// MPose * model;

            // All implementations should define fullScreenToggle method and getData methods
            virtual void fullScreenToggle() {};
            virtual void getViewData( void * udata){};
            virtual void getKeyboardData( void * udata){};
            virtual void getMouseData( void * udata){};
			virtual void getHIDData( void * udata ){}; //other input devic
        };

        Interface( Scene * s = NULL ) : scene(s), mRotVel(.02), mVel(.1), mModelRotVel(.1) {};

        virtual void init() = 0;

        void inputCalc();        ///< Calculate Mouse Movements based on x and dx
        void viewCalc();         ///< Calculate Window Matrices, Screen Coordinates of Mouse

        Impl * impl;       		 ///< Implementation of Window Information (Width, Height) and Inputs (Keyboard, Mouse)

		ViewData		view;
        MouseData       mouse;
        KeyboardData    keyboard;

		ViewData& vd() { return view; }//vimpl -> data; }
        //ViewData vd() const { return vimpl -> data; }

        KeyboardData& kd() { return keyboard; }
        MouseData& md() { return mouse; }

		Camera& camera() { return scene -> camera; }
		MPose& model() { return scene -> model; }

		template <class A> static Vec3f screenCoord(const A& p, const XformMat& );
        template <class A> bool pntClicked(const A&, float rad = .05);

        Vec3f click(){ return mouse.click;   }
        Vec3f pos(){ return mouse.pos;     }

        /*! Set Mode */
        int& mode() { return mMode; }
        /*! Get Mode */
        int mode() const { return mMode; }
        /// Check Interface Mode
        bool mode(int q) { return mMode & q; }
       /// Enable Mode
        void enable(int bitflag) { mMode |= bitflag; }
        void disable(int bitflag) { mMode &= ~bitflag; }
        void toggle(int bitflag)  { mMode & bitflag ? disable(bitflag) : enable(bitflag); }

        template <class A > bool isSelected( A * );
        template <class A > void select( A * );
        template <class A > void deselect( A * );
        template <class A > void toggleSelect( A * );

	        //NAVIGATION
	        void keyboardCamSpin(float acc, bool trigger);
	        void keyboardCamTranslate(float acc, bool trigger);
	        void keyboardModelTransform(float acc, bool trigger);
	        void mouseModelTransform(float acc, bool trigger);
	        void mouseCamTranslate(float acc, bool trigger);
	        void mouseCamSpin(float acc, bool trigger);

			void mouseNavigate();
			void mouseNavigateStop();
			void keyboardNavigate();
			void keyboardNavigateStop();

	        virtual void onMouseMove();
	        virtual void onMouseDown();
	        virtual void onMouseDrag();
	        virtual void onMouseUp();
	        virtual void onKeyDown();
	        virtual void onKeyUp();

			virtual void windowTransform(){}

			template<class A, class B>
			void touch( A& s, const B& b, float t = .1 );

			//Define this transformation rule somewhere
		    template <class A, class B>
		   	struct X {
				Interface * i;
				X( Interface * _i) : i (_i ) {}
				void f ( A * s, const B& pos, float t );
			};
		// void xf ( A * s, const B& pos, float t );

};

      template< class A > bool Interface :: isSelected ( A * a ){
        stringstream s; s << a;
        bool tmp = selectMap[ s.str() ];
        return tmp;
    }

    template < class A > void Interface :: select( A * a) {
        stringstream s; s << a;
		//cout << "selected: " << s.str() << endl;
        selectMap[ s.str() ] = true;
    }

    template < class A > void Interface :: deselect( A * a) {
        stringstream s; s << a;
        selectMap[ s.str() ] = false;
    }

    template < class A > void Interface :: toggleSelect( A * a) {
        stringstream s; s << a;
        selectMap[ s.str() ] = !selectMap[ s.str() ];
    }
 /// Screen Coordinates of Target point
 template <class A> Vec3f Interface :: screenCoord(const A& p, const XformMat& xf){
     Vec3f sc = GL::project( p[0], p[1], p[2], xf );
     sc[0] /= xf.viewport[2]; sc[1] /= xf.viewport[3]; sc[2] = 0;

     return sc;
 }

 template <class A> bool Interface :: pntClicked( const A& x, float rad ) {
     Vec3f v = mouse.click;  // [0,0] is bottom left corner [1.0,1.0] is top right
     Vec3f p = Vec3f( x[0], x[1], x[2] );

   // cout << "mouse: " << v << endl;
  //  cout << "x: " << p << endl;

     Vec3f sc = screenCoord( p, scene -> xf );
   // cout << "Screen: " << sc << endl ;
     Vec3f dist = (v - sc);
     return (dist.len() < rad) ? true : false;
 }

template <class A, class B> void Interface :: touch( A& s, const B& x, float t){

        if ( !keyboard.alt && !keyboard.shift && !keyboard.alt ){

            //physics
            static float dt = 1;
            static float acc = .9;
            dt *= acc;

            if ( mouse.isDown ){
                dt = t; // Reset acc
                if ( pntClicked( x ) ) {
                    select( &s );
                }
            }

            if ( isSelected( &s ) ){
				 X<A,B>(this).f(&s, x, dt);
				//xf(&s, x, dt);
            }

        }
    }

inline void Interface::viewCalc(){

        //Assumes data has been copied to (or created from) scene transformation matrices (xf)
        vd().z  = Quat::spin( Vec3f(0,0,1), !model().quat() * camera().quat() );

        /// Bottom Left (0,0) to top right (1,1)
        mouse.pos  = Vec3f( mouse.x / vd().w, 1 - mouse.y / vd().h, 0 ) ;
        mouse.move = Vec3f( mouse.dx / vd().w, - mouse.dy / vd().h, 0 ) ;

        mouse.cat     = Quat::spin( mouse.move * -1, !scene->cat() );
        mouse.bivCat = vd().z.cross( mouse.cat );

        //GLU FUNCS
        Vec3f v1 = gfx::GL::unproject( mouse.x, vd().h - mouse.y , 1.0,  scene->xf );
        Vec3f v2 = gfx::GL::unproject( mouse.x, vd().h - mouse.y , 0.0,  scene->xf );
        Vec3f v3 = gfx::GL::unproject( mouse.x, vd().h - mouse.y , 0.5,  scene->xf );

        //OWN FUNCS (in progress, seem to give results scaled differently)
//        Vec3f tv1 = XMat::UnProject( Vec3f( mouse.x, vd().h - mouse.y , 1.0), scene().xf );
//        Vec3f tv2 = XMat::UnProject( Vec3f( mouse.x, vd().h - mouse.y , 0.0),scene().xf );
//        Vec3f tv3 = XMat::UnProject( Vec3f( mouse.x, vd().h - mouse.y , 0.5),scene().xf );
//
//        Vec v1(tv1.x, tv1.y, tv1.z);
//        Vec v2(tv2.x, tv2.y, tv2.z);
//        Vec v3(tv3.x, tv3.y, tv3.z);

        //Get vec of Mouse Position into Z Space
		vd().ray	 = ( v3 - v2 ).unit();

		mouse.projectFar	= v1 ;
		mouse.projectNear	= v2 ;
		mouse.projectMid	= v3 ;

        mouse.biv     = mouse.pos.cross( vd().ray ); //not used?

        //Point on Line Closest to Origin (moved to versor)
        //mouse.origin = Ro::null( Fl::loc( vd().ray, Ori(1), true ) );

    }

	    inline void Interface :: onKeyDown(){

	        keyboard.down = true;

	    }

	   inline void Interface :: onKeyUp(){

	        keyboard.down = false;

	    }

	   inline void Interface :: keyboardModelTransform(float acc, bool trigger){

	        model().ab() = acc;

	        if (trigger) {
			   //printf("1\n");
	            // Get Rotor Ratio between camera and model view
				Quat ryz = Quat::Rotor( model().x(), camera().x() );
	            Quat rxz = Quat::Rotor( model().y(), camera().y() );

	            // Rotate By said Rotor
	            Vec3f tyz = Quat::spin( model().x(), ryz );
	            Vec3f txz = Quat::spin( model().y(), rxz );

	            switch( keyboard.code ){
	                case Key::Up:
	                {
	                    // camera().modelView().yz()
	                    model().db() += tyz * mModelRotVel;
	                    break;
	                }
	                case Key::Down:
	                {
	                    model().db() -= tyz * mModelRotVel;
	                    break;
	                }
	                case Key::Left:
	                {
	                    model().db() -= txz * mModelRotVel;
	                    break;
	                }
	                case Key::Right:
	                {
	                    model().db() += txz * mModelRotVel;
	                    break;
	                }
	            }
	        }
	    }

	    inline void Interface :: keyboardCamTranslate(float acc, bool trigger){
	        camera().ax() = acc;
	        if (trigger){
	            switch(keyboard.code){
	                case Key::Up:
	                    if (keyboard.ctrl) camera().dx() += camera().up() * mVel;
	                    else camera().dx() += camera().forward() * mVel;
	                    break;
	                case Key::Down:
	                    if (keyboard.ctrl) camera().dx() -= camera().up() * mVel;
	                    else camera().dx() -= camera().forward() * mVel;
	                    break;
	                case Key::Left:  camera().dx() -= camera().right() * mVel; break;
	                case Key::Right: camera().dx() += camera().right() * mVel; break;
	            }
	        }
	    }

	    inline void Interface :: keyboardCamSpin(float acc, bool trigger){
	        camera().ab() = acc;
	        if (trigger){
	            switch(keyboard.code){
	                case Key::Up:    camera().db() += camera().x() * mRotVel;	break;
	                case Key::Down:  camera().db() -= camera().x() * mRotVel; break;
	                case Key::Left:  camera().db() += camera().y() * mRotVel; break;
	                case Key::Right: camera().db() -= camera().y() * mRotVel; break;
	            }
	        }
	    }

	  inline void Interface :: mouseModelTransform(float acc, bool trigger){
	        model().ab() = acc;
	        if (trigger) model().db() += mouse.dragBiv * mModelRotVel;
	    }

	  inline void Interface :: mouseCamTranslate(float acc, bool trigger){
	        camera().ax() = acc;
	        if(trigger) {

	            switch(mouse.gesture){
	                case MouseData::Up:
	                    if (keyboard.ctrl) camera().dx() += camera().up() * mVel;
	                    else camera().dx() += camera().forward() * mVel * .5;
	                    break;
	                case MouseData::Down:
	                    if (keyboard.ctrl) camera().dx() -= camera().up() * mVel;
	                    else camera().dx() -= camera().forward() * mVel * .5;
	                    break;
	                case MouseData::Left:
	                   camera().dx() += camera().right() * mVel * .5; break;
	                case MouseData::Right:
	                    camera().dx() -= camera().right() * mVel * .5; break;
	            }

	        }
	    }

	   inline void Interface :: mouseCamSpin(float acc, bool trigger){
	        camera().ab() = acc;
	        if (trigger){
	            switch(mouse.gesture){
	                case MouseData::Up:    camera().db() += camera().x() * mRotVel * .5;	break;
	                case MouseData::Down:  camera().db() -= camera().x() * mRotVel * .5; break;
	                case MouseData::Left:  camera().db() -= camera().y() * mRotVel * .5; break;
	                case MouseData::Right: camera().db() += camera().y() * mRotVel * .5; break;
	            }
	        }
	    }

		   inline void Interface :: onMouseMove(){

		    }

		   inline void Interface :: onMouseDown(){

		        vd().clickray = vd().ray;
		        mouse.click = mouse.pos;
		        mouse.isDown  = 1;
		        mouse.newClick = 1;

		    }

		   inline void Interface :: onMouseUp(){
		        mouse.isDown = 0;
		        mouse.newClick = 0;
		    }

		   inline void Interface :: onMouseDrag(){

			        static float nx;
		            static float ny;

		            static float tdx;
		            static float tdy;

		            //relative top left (0.0 - .002 or so);
		            float dx = mouse.dx;
		            float dy = mouse.dy; //changed

		            //current position relative to top left (0.0 - 1.0)
		            float cx = mouse.pos[0];//mouse.xrel;
		            float cy = mouse.pos[1];//mouse.yrel;//changed

		            //Accumulated Movement
		            nx += dx; //+ or -?
		            ny += dy;

		            //Temporary Accumulated Movement
		            tdx = mouse.newClick ? 0 : tdx + dx; //+ or -?
		            tdy = mouse.newClick ? 0 : tdy + dy;

		            mouse.dragAccum = Vec3f(nx,ny,0);							//total dvector since program launch
		            mouse.drag		= Vec3f(tdx,tdy,0);							//vector from last click and hold to current position

		            mouse.dragCat = Quat::spin( mouse.drag, !scene->cat() );     //rotate drag by inverse concatenated orientation
		            mouse.dragBivCat = vd().z.cross( mouse.dragCat );

		            mouse.dragBiv = Vec3f(0,0,1).cross(mouse.drag);

		            Vec3f v1  = mouse.pos;
		            Vec3f v2  = mouse.move;
		            Vec3f v = v1 - camera().pos();

		            Vec3f rel ( .5-cx, .5-cy, 0.0 );
		            Vec3f nn  ( nx, ny, 0.0 );

		            mouse.newClick = 0;

		             int mdir = 0;
		             if ( fabs(tdx) > fabs(tdy) ) mdir = tdx > 0 ? MouseData::Right : MouseData::Left;
		             else if ( fabs(tdx) < fabs(tdy) ) mdir = tdy > 0 ? MouseData::Up : MouseData::Down;

		             mouse.gesture = mdir;

		}

		inline void Interface :: keyboardNavigate(){
			//Camera Controls

			//stateTransform();
	        switch(keyboard.code){
	            case 'c':
	                camera().reset(0,0,5);
	                model().reset();
	                break;

	        }

	        if (keyboard.alt) {
	            keyboardModelTransform(1.0, true);
	        } else if (keyboard.shift){
	            keyboardCamTranslate(1.0, true);
	        } else {
	            keyboardCamSpin(1.0, true);
	        }
		}

		inline void Interface :: keyboardNavigateStop(){
	        keyboardModelTransform(.7, false);
	        keyboardCamTranslate(.7, false);
	        keyboardCamSpin(.7, false);
		}

		inline void Interface :: mouseNavigate(){
		        if (keyboard.alt) {
	                mouseModelTransform(1.0, true);
	            } else if (keyboard.shift) {
	                mouseCamTranslate(1.0, true);
	            } else if (keyboard.ctrl){
	                mouseCamSpin(1.0,true);
	            }
		}

		inline void Interface :: mouseNavigateStop(){
			mouseModelTransform(.7, false);
	        mouseCamTranslate(.7, false);
	        mouseCamSpin(.7, false);
		}

} //gfx::

#endif


text:
flask_velox.admin.mixins.sqla.delete
====================================

.. automodule:: flask_velox.admin.mixins.sqla.delete
    :members:
    :private-members:
    :show-inheritance:


text:
package proguard.util;

/**
 * This StringMatcher tests whether strings match a given list of StringMatcher
 * instances. The instances are considered sequentially. Each instance in the
 * list can optionally be negated, meaning that a match makes the entire
 * remaining match fail.
 *
 * @author Eric Lafortune
 */
public class ListMatcher extends StringMatcher
{
    private final StringMatcher[] matchers;
    private final boolean[]       negate;

    public ListMatcher(StringMatcher[] matchers)
    {
        this(matchers, null);
    }

    public ListMatcher(StringMatcher[] matchers, boolean[] negate)
    {
        this.matchers = matchers;
        this.negate   = negate;
    }

    // Implementations for StringMatcher.

    protected boolean matches(String string, int offset, int length)
    {
        // Check the list of matchers.
        for (int index = 0; index < matchers.length; index++)
        {
            StringMatcher matcher = matchers[index];
            if (matcher.matches(string, offset, length))
            {
                return negate == null ||
                       !negate[index];
            }
        }

        return negate != null &&
               negate[negate.length - 1];

    }
}


text:
import Vue, { ComponentOptions } from 'vue';
import rivenMap from '../data/riven-map';

function isCompat(itemType: number, rivenType: string) {
  return !rivenType ||
        (rivenType === 'Projectile' && itemType < 2) ||
        (rivenType === 'Melee' && itemType === 2);
}

const statTypes: {
  name: string,
  p: string,
  s: string,
  type: '' | 'Projectile' | 'Melee',
  display_name: string | string[],
  display_amt_suffix: string
}[] = [];

for(const key in rivenMap) if(rivenMap[key] && typeof rivenMap[key] === 'object') {
  statTypes.push(Object.assign({ name: key }, rivenMap[key]));
}

const sampleItems = [
  { name: 'Opticor', type: 0 },
  { name: 'Paris', type: 0 },
  { name: 'Braton', type: 0 },
  { name: 'Lenz', type: 0 },
  { name: 'Vectis', type: 0 },

  { name: 'Lato', type: 1 },
  { name: 'Lex', type: 1 },
  { name: 'Twin Grakatas', type: 1 },
  { name: 'AkZani', type: 1 },

  { name: 'Bo', type: 2 },
  { name: 'War', type: 2 },
  { name: 'Orthos', type: 2 },
  { name: 'Reaper Prime', type: 2 },
  { name: 'Nikana', type: 2 },
];

const polarities = [
  'madurai',
  'naramon',
  'vazarin',
  'zenurik'
];

interface IApp extends Vue {
  itemName: string;
  itemType: number;
  cost: number;
  polarity: string;
  stats: { name: string, value: number }[];

  polarityIdx: number;

  polarities: string[];
  statTypes: typeof statTypes;

  updatedRoute: boolean;

  negatives: number;
  hasDuplicates: boolean;
  incompats: string[];

  randomize(): void;
  setFromRoute(): void;
  updateQuery(): void;
  updateSelectText(): void;
  reroll(): void;
}

export default {
  name: 'app',
  data: () => {
    return {
      itemName: '',
      itemType: 0,
      cost: 10,
      stats: [],

      polarityIdx: 0,

      polarities: polarities,
      statTypes: statTypes,

      updatedRoute: false,
    } as IApp;
  },
  computed: {
    polarity() {
      return polarities[this.polarityIdx];
    },
    negatives() {
      return this.stats.filter(a => a.value < 0).length;
    },
    hasDuplicates() {
      return this.stats.findIndex((a, i, arr) => arr.length - 1 > i && arr.slice(i + 1).findIndex(b => a.name === b.name) >= 0) >= 0;
    },
    incompats() {
      return this.stats.filter(a => !isCompat(this.itemType, rivenMap[a.name].type)).map(a => rivenMap[a.name].display_name);
    }
  },
  watch: {
    itemType(n, o) {
      this.updateSelectText();
    },
    stats(n, o) {
      this.updateSelectText();
    },
    cost(n, o) {
      if(o < 10 || o > 18) return;
      if(n < 10) { this.$nextTick(() => this.cost = 10); n = 10; }
      if(n > 18) { this.$nextTick(() => this.cost = 18); n = 18; }
      o -= 9;
      n -= 9;
      this.stats.forEach((a, i) => a.value = a.value / o * n);
    },
    $route(n, o) {
      if(this.updatedRoute) { this.updatedRoute = false; return; }

      if(this.$route.query.itemName && this.$route.query.itemName !== this.itemName)
      this.itemName = this.$route.query.itemName || this.polarity;

      let i = Number.parseInt(this.$route.query.itemType);
      if((i || i === 0) && i !== this.itemType) this.itemType = i;

      i = Number.parseInt(this.$route.query.cost);
      if((i || i === 0) && i !== this.cost) this.cost = i;

      const p = this.$route.query.polarity || this.polarity;
      const pi = polarities.findIndex(a => a === p) || 0;
      if(pi !== this.polarityIdx)
        this.polarityIdx = pi;

      const stats: { name: string, value: number }[] = [];
      for(const key in this.$route.query) if(!['itemName', 'itemType', 'cost', 'polarity'].find(a => a === key) && this.$route.query[key]) {
        const val = Number.parseFloat(this.$route.query[key]);
        if(!val && val !== 0) continue;
        stats.push({ name: key, value: val });
      }
      if(stats.length > 0 && !stats.every((a, ai) => this.stats[ai] && stats[ai].name === this.stats[ai].name))
        this.$nextTick(() => this.stats.splice(0, this.stats.length, ...stats));
    }
  },
  created() {

    const fromRoute = this.setFromRoute();

    if(!fromRoute)
      this.randomize();

    this.$nextTick(() => this.updateQuery());
  },
  methods: {
    setFromRoute() {
      let changed = this.$route.query.itemName ? true : false;
      this.itemName = this.$route.query.itemName || this.polarity;

      let i = Number.parseInt(this.$route.query.itemType);
      if(i || i === 0) { this.itemType = i; changed = true; }

      i = Number.parseInt(this.$route.query.cost);
      if(i || i === 0) { this.cost = i; changed = true; }

      const p = this.$route.query.polarity || this.polarity;
      this.polarityIdx = polarities.findIndex(a => a === p) || 0;
      changed = changed || (this.$route.query.polarity ? true : false);

      const stats: { name: string, value: number }[] = [];
      for(const key in this.$route.query) if(!['itemName', 'itemType', 'cost', 'polarity'].find(a => a === key) && this.$route.query[key]) {
        const val = Number.parseFloat(this.$route.query[key]);
        if(!val && val !== 0) continue;
        stats.push({ name: key, value: val });
      }
      if(stats.length > 0) {
        changed = true;
        this.$nextTick(() => this.stats.splice(0, this.stats.length, ...stats));
      }

      return changed;
    },
    randomize() {
      const sampleItem = sampleItems[Math.floor(Math.random() * sampleItems.length)];

      this.itemName = sampleItem.name;
      this.itemType = sampleItem.type;
      this.cost = 10 + Math.floor(Math.random() * 9);
      this.polarityIdx = Math.floor(Math.random() * polarities.length);
      this.$nextTick(() => this.reroll()); // gets around getting multiplied by cost twice & updates the query already
    },
    reroll() {
      this.stats = (() => {
        const amt = Math.floor(Math.random() * 3 + 2);
        const negative = (amt >= 4 || amt === 3 && Math.floor(Math.random())) ? true : false;
        const ret: { name: string, value: number }[] = [];
        for(let i = 0; i < amt; i++) {
          let s = statTypes[Math.floor(Math.random() * statTypes.length)];
          while(ret.find(a => a.name === s.name) || !isCompat(this.itemType, s.type))
            s = statTypes[Math.floor(Math.random() * statTypes.length)];
          const val = Math.round((Math.random() * 200 + 100) * (this.cost - 9)) / 10;
          if(i === amt - 1 && negative) ret.push({ name: s.name, value: -val });
          else ret.push({ name: s.name, value: val });
        }
        return ret;
      })();
      this.updateQuery();
    },
    reset() {
      this.itemName = '';
      this.itemType = 0;
      this.cost = 10;
      this.polarityIdx = 0;
      this.stats.splice(0, this.stats.length);
      this.updateQuery();
    },
    updateSelectText() {
      const statDOM = document.body.querySelectorAll('div.stat');
      for(let i = 0; i < statDOM.length && i < this.stats.length; i++) {

        const statSelectDOM = statDOM.item(i).querySelector('span.md-select-value');
        if(!statSelectDOM) { console.error(`Couldn't find the stat select dome!'`); return; }
        const r = rivenMap[this.stats[i].name].display_name;
        statSelectDOM.textContent = r instanceof Array ? r[this.itemType] : r;
      }
    },
    updateQuery() {
      const query: {[key: string]: string} = {
        itemName: this.itemName,
        itemType: '' + this.itemType,
        cost: '' + this.cost,
        polarity: polarities[this.polarityIdx],
      };
      this.stats.forEach(a => query[a.name] = a.value.toFixed(2));
      this.$router.replace({ path: this.$route.path, query: query });
      this.updatedRoute = true;
    },
    getDisplayName(stat) {
      if(stat.display_name instanceof Array) return stat.display_name[this.itemType];
      else return stat.display_name;
    },
    removeStat(idx) {
      const deleted = this.stats.splice(idx, 1);
      this.updateQuery();
    },
    addStat() {
      let s = statTypes[Math.floor(Math.random() * statTypes.length)];
      while(this.stats.find(a => a.name === s.name) || !isCompat(this.itemType, s.type))
        s = statTypes[Math.floor(Math.random() * statTypes.length)];

      let val = Math.round((Math.random() * 200 + 100) * (this.cost - 9)) / 10;

      if(!this.negatives && (this.stats.length === 3 || (this.stats.length === 2 && Math.round(Math.random()))))
        val = -val;

      this.stats.push({ name: s.name, value: val });
      this.updateQuery();
    }
  }
} as ComponentOptions<IApp>;


text:
FactoryGirl.define do
  factory :fireman_intervention do
    intervention_role

    fireman
  end
end


text:
package com.igormaznitsa.jbbp.plugin.mvn;

import com.igormaznitsa.jbbp.plugin.common.converters.Target;
import com.igormaznitsa.meta.annotation.MustNotContainNull;
import com.igormaznitsa.meta.common.utils.Assertions;
import java.io.File;
import java.util.HashSet;
import java.util.Set;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.compiler.util.scan.InclusionScanException;
import org.codehaus.plexus.compiler.util.scan.SimpleSourceInclusionScanner;
import org.codehaus.plexus.compiler.util.scan.SourceInclusionScanner;
import org.codehaus.plexus.compiler.util.scan.mapping.SuffixMapping;

public abstract class AbstractJBBPMojo extends AbstractMojo {
  /**
   * Provides an explicit list of all the JBBP scripts that should be included
   * in the generate phase of the plug-in.
   *

   * A set of Ant-like inclusion patterns used to select files from the source
   * directory for processing. By default, the pattern
   * **/*.jbbp is used to select JBBP script files.
   *

   */
  @Parameter(alias = "includes")
  protected final Set<String> includes = new HashSet<String>();
  /**
   * A set of Ant-like exclusion patterns used to prevent certain files from
   * being processed. By default, this set is empty such that no files are
   * excluded.
   */
  @Parameter(alias = "excludes")
  protected final Set<String> excludes = new HashSet<String>();
  /**
   * Current maven project.
   */
  @Parameter(property = "project", required = true, readonly = true)
  protected MavenProject project;
  /**
   * Specifies whether sources are added to the {@code compile} or {@code test}
   * scope.
   */
  @Parameter(alias = "generateTestSources", defaultValue = "false")
  protected boolean generateTestSources;
  /**
   * Package to override package name extracted from script file name, it will be
   * common for all processed classes.
   */
  @Parameter(alias = "packageName")
  protected String packageName;
  /**
   * Target for translation.
   *
   * @see Target
   */
  @Parameter(alias = "target", defaultValue = "JAVA")
  protected String target;
  /**
   * Flag to skip processing of the plug-in.
   */
  @Parameter(alias = "skip", defaultValue = "false")
  protected boolean skip;
  /**
   * Destination directory for generated Java classes, the default value is
   * "${project.build.directory}/generated-sources/jbbp"
   */
  @Parameter(alias = "output", defaultValue = "${project.build.directory}/generated-sources/jbbp")
  protected File output;
  /**
   * Flag to make plugin verbose.
   */
  @Parameter(alias = "verbose", defaultValue = "false")
  protected boolean verbose;
  /**
   * Source directory for JBBP scripts, the default value is
   * "${project.basedir}/src/jbbp"
   */
  @Parameter(alias = "source", defaultValue = "${project.basedir}/src/jbbp")
  protected File source;

  @Nullable
  public String getTarget() {
    return this.target;
  }

  public void setTarget(@Nullable final String value) {
    this.target = value;
  }

  @MustNotContainNull
  @Nonnull
  public Set<String> getExcludes() {
    return this.excludes;
  }

  @Nullable
  public String getPackageName() {
    return this.packageName;
  }

  public void setPackageName(@Nullable final String text) {
    this.packageName = text;
  }

  @MustNotContainNull
  @Nonnull
  public Set<String> getIncludes() {
    return this.includes;
  }

  @Nonnull
  public File getSource() {
    return this.source;
  }

  public void setSource(@Nonnull final File file) {
    this.source = Assertions.assertNotNull("Source must not be null", file);
  }

  public boolean getSkip() {
    return this.skip;
  }

  public void setSkip(final boolean value) {
    this.skip = value;
  }

  @Nonnull
  public File getOutput() {
    return this.output;
  }

  public void setOutput(@Nullable final File file) {
    this.output = file;
  }

  public boolean getVerbose() {
    return this.verbose;
  }

  public void setVerbose(final boolean flag) {
    this.verbose = flag;
  }

  public boolean getGenerateTestSources() {
    return this.generateTestSources;
  }

  public void setGenerateTestSources(final boolean flag) {
    this.generateTestSources = flag;
  }

  protected void registerSourceRoot(@Nonnull final File outputDir) {
    if (this.generateTestSources) {
      getLog().debug("Registering TEST source root : " + outputDir.getPath());
      this.project.addTestCompileSourceRoot(outputDir.getPath());
    } else {
      getLog().debug("Registering source root : " + outputDir.getPath());
      this.project.addCompileSourceRoot(outputDir.getPath());
    }
  }

  @Nonnull
  public Set<File> findSources(@Nonnull final File targetDirectory) throws MojoExecutionException {
    try {
      final SourceInclusionScanner scanner =
          new SimpleSourceInclusionScanner(this.includes, this.excludes);
      scanner.addSourceMapping(new SuffixMapping("JBBP", "jbbp"));
      return scanner.getIncludedSources(this.source, targetDirectory);
    } catch (InclusionScanException ex) {
      throw new MojoExecutionException("Error during sources scanning", ex);
    }
  }

  public void logInfo(@Nullable final String text, final boolean onlyIfVerbose) {
    if (text != null) {
      if (this.verbose) {
        getLog().info(text);
      } else {
        if (!onlyIfVerbose) {
          getLog().info(text);
        }
      }
    }
  }

  public boolean checkSetNonEmptyWithLogging(@Nonnull final Set<File> files) {
    boolean result = true;
    if (files.isEmpty()) {
      getLog().warn("There is not any detected JBBP script");
      result = false;
    }
    return result;
  }

  @Override
  public final void execute() throws MojoExecutionException, MojoFailureException {
    if (this.skip) {
      logInfo("Skip processing", false);
      return;
    }

    if (this.includes.isEmpty()) {
      this.includes.add("**/*.jbbp");
    }

    executeMojo();
  }

  @Nonnull
  public Target findTarget() throws MojoExecutionException {
    final Target theTarget;
    try {
      return Target.valueOf(this.target);
    } catch (IllegalArgumentException ex) {
      throw new MojoExecutionException("Unsupported target : " + this.target, ex);
    }
  }

  protected abstract void executeMojo() throws MojoExecutionException, MojoFailureException;
}


text:
BioDigital Human Content API using Node.js
========

Code samples using [Node.js](https://nodejs.org) to demonstrate making requests to the BioDigital Human Content API.  These examples provide basic approaches to:

* Requesting an access token from the BioDigital OAuth2 services
* Using an access token to make authorized requests to various Content API endpoints

## Getting Started

Below are the steps for getting this example running on your local machine for development and testing purposes.

### Prerequisites

1.  The **developer key and secret** of a [registered BioDigital developer application](https://devsupport.biodigital.com/hc/en-us/articles/234450188-How-to-register-my-App).  These credentials will be used as your *client id* and *client secret* when making requests to the BioDigital OAuth2 services.

2. [Node.js v4.2.2](https://nodejs.org/en/download/current/) or higher.
3. [npm v3](https://nodejs.org/en/download/current/) or higher (should be included with Node.js installation), along with the below packages, which are listed in the provided **package.json** file.  Running `npm install` on the provided **package.json** file should download and install these dependencies:
	*  [express](https://www.npmjs.com/package/express) - https://www.npmjs.com/package/express
	*  [minimist](https://www.npmjs.com/package/minimist) - https://www.npmjs.com/package/minimist
	*  [request](https://www.npmjs.com/package/request) - https://www.npmjs.com/package/request
	*  [utf8](https://www.npmjs.com/package/utf8) - https://www.npmjs.com/package/utf8

### Running on local machine

* Install any library prerequisites or dependencies on your local machine.

*  Download the code files to a directory.  Edit the **settings.js** script file by replacing `<DEVELOER_KEY>` and `<DEVELOPER_SECRET>` with your developer key and secret credentials.

```node
// Your API / Developer key you received when you registered your
// application at https://developer.biodigital.com
exports.CLIENT_ID = '<DEVELOPER_KEY>';

// Your API / Developer secret you received when you registered your
// application at https://developer.biodigital.com
exports.CLIENT_SECRET = '<DEVELOPER_SECRET>';

```

*  Open a command terminal and switch to the root directory of the code files.  Run the **client.js** script with the following command line parameters (unspecified optional parameters will use default values):

 	* **_--host=[VALUE]_**  (Optional):  server host value.  Default is 127.0.0.1.
 	* **_--port=[VALUE]_**   (Optional):  server port value.  Default is 5000.

```
node client.js --host localhost --port 5656
```

* Open a browser to the running server on http://localhost:5656/

## Official Documentation

* Developer APIs and services:   [developer.biodigital.com](https://developer.biodigital.com)
* Developer FAQs and troubleshooting topics:  [devsupport.biodigital.com](https://devsupport.biodigital.com)
* Integration trouble?  General questions?  Contact developers@biodigital.com

## Author

* [BioDigital, Inc.](https://www.biodigital.com/)

## License

See the [LICENSE](https://github.com/biodigital-inc/bdhuman-contentapi/blob/master/LICENSE) file for more info.

## Disclaimer

These code examples are provided as is and are only intended to be used for illustration purposes. This code is not production-ready and is not meant to be used in a production environment. This repository is to be used as a tool to help developers learn how to integrate with [BioDigital, Inc.](https://www.biodigital.com/) API services. Any use of this repository or any of its code in a production environment is highly discouraged.


text:
gzencode() and invalid params
--SKIPIF--
<?php if (!extension_loaded("zlib")) print "skip"; ?>
--FILE--
<?php

var_dump(gzencode());
var_dump(gzencode(1,1,1,1));
var_dump(gzencode("", -10));
var_dump(gzencode("", 100));
var_dump(gzencode("", 1, 100));

var_dump(gzencode("", -1, ZLIB_ENCODING_GZIP));
var_dump(gzencode("", 9, ZLIB_ENCODING_DEFLATE));

$string = "Light of my sun
Light in this temple
Light in my truth
Lies in the darkness";

var_dump(gzencode($string, 9, 3));

var_dump(gzencode($string, -1, ZLIB_ENCODING_GZIP));
var_dump(gzencode($string, 9, ZLIB_ENCODING_DEFLATE));

echo "Done\n";
?>
--EXPECTF--
Warning: gzencode() expects at least 1 parameter, 0 given in %s on line %d
NULL

Warning: gzencode() expects at most 3 parameters, 4 given in %s on line %d
NULL

Warning: gzencode(): compression level (-10) must be within -1..9 in %s on line %d
bool(false)

Warning: gzencode(): compression level (100) must be within -1..9 in %s on line %d
bool(false)

Warning: gzencode(): encoding mode must be either ZLIB_ENCODING_RAW, ZLIB_ENCODING_GZIP or ZLIB_ENCODING_DEFLATE in %s on line %d
bool(false)
string(%d) "%s"
string(%d) "%s"

Warning: gzencode(): encoding mode must be either ZLIB_ENCODING_RAW, ZLIB_ENCODING_GZIP or ZLIB_ENCODING_DEFLATE in %s on line %d
bool(false)
string(%d) "%s"
string(%d) "%s"
Done


text:
require 'fog/compute/models/server'

module Fog
  module Compute
    class Vsphere

      class Server < Fog::Compute::Server

        # This will be the instance uuid which is globally unique across
        # a vSphere deployment.
        identity  :id

        # JJM REVISIT (Extend the model of a vmware server)
        # SEE: http://www.vmware.com/support/developer/vc-sdk/visdk41pubs/ApiReference/vim.VirtualMachine.html
        # (Take note of the See also section.)
        # In particular:
        #   GuestInfo: information about the guest operating system
        #   VirtualMachineConfigInfo: Access to the VMX file and configuration

        attribute :name
        # UUID may be the same from VM to VM if the user does not select (I copied it)
        attribute :uuid
        # Instance UUID should be unique across a vCenter deployment.
        attribute :instance_uuid
        attribute :hostname
        attribute :operatingsystem
        attribute :ipaddress
        attribute :power_state,   :aliases => 'power'
        attribute :tools_state,   :aliases => 'tools'
        attribute :tools_version
        attribute :mac_addresses, :aliases => 'macs'
        attribute :hypervisor,    :aliases => 'host'
        attribute :is_a_template
        attribute :connection_state
        attribute :mo_ref
        attribute :path
        attribute :memory_mb
        attribute :cpus

        def vm_reconfig_memory(options = {})
          requires :instance_uuid, :memory
          connection.vm_reconfig_memory('instance_uuid' => instance_uuid, 'memory' => memory)
        end

        def vm_reconfig_cpus(options = {})
          requires :instance_uuid, :cpus
          connection.vm_reconfig_cpus('instance_uuid' => instance_uuid, 'cpus' => cpus)
        end

        def vm_reconfig_hardware(options = {})
          requires :instance_uuid, :hardware_spec
          connection.vm_reconfig_hardware('instance_uuid' => instance_uuid, 'hardware_spec' => hardware_spec)
        end

        def start(options = {})
          requires :instance_uuid
          connection.vm_power_on('instance_uuid' => instance_uuid)
        end

        def stop(options = {})
          options = { :force => !tools_installed? }.merge(options)
          requires :instance_uuid
          connection.vm_power_off('instance_uuid' => instance_uuid, 'force' => options[:force])
        end

        def reboot(options = {})
          options = { :force => false }.merge(options)
          requires :instance_uuid
          connection.vm_reboot('instance_uuid' => instance_uuid, 'force' => options[:force])
        end

        def destroy(options = {})
          requires :instance_uuid
          connection.vm_destroy('instance_uuid' => instance_uuid)
        end

        def migrate(options = {})
          options = { :priority => 'defaultPriority' }.merge(options)
          requires :instance_uuid
          connection.vm_migrate('instance_uuid' => instance_uuid, 'priority' => options[:priority])
        end

        def create(options ={})
          requires :name, :path
          new_vm = self.class.new(create_results['vm_attributes'])
          new_vm.collection = self.collection
          new_vm.connection = self.connection
          new_vm
        end

        def clone(options = {})
          requires :name, :path
          # Convert symbols to strings
          req_options = options.inject({}) { |hsh, (k,v)| hsh[k.to_s] = v; hsh }
          # Give our path to the request
          req_options['path'] ="#{path}/#{name}"
          # Perform the actual clone
          clone_results = connection.vm_clone(req_options)
          # Create the new VM model.
          new_vm = self.class.new(clone_results['vm_attributes'])
          # We need to assign the collection and the connection otherwise we
          # cannot reload the model.
          new_vm.collection = self.collection
          new_vm.connection = self.connection
          # Return the new VM model.
          new_vm
        end

        def ready?
          power_state == "poweredOn"
        end

        def tools_installed?
          tools_state != "toolsNotInstalled"
        end

        # defines VNC attributes on the hypervisor
        def config_vnc(options = {})
          requires :instance_uuid
          connection.vm_config_vnc(options.merge('instance_uuid' => instance_uuid))
        end

        # returns a hash of VNC attributes required for connection
        def vnc
          requires :instance_uuid
          connection.vm_get_vnc(instance_uuid)
        end

        def memory
          memory_mb * 1024 * 1024
        end

      end

    end
  end
end


text:
package com.intellij.lang.jsgraphql.psi.impl;

import com.intellij.lang.ASTNode;
import com.intellij.lang.jsgraphql.psi.GraphQLObjectField;
import com.intellij.lang.jsgraphql.psi.GraphQLTypeScopeProvider;
import com.intellij.lang.jsgraphql.schema.GraphQLSchemaUtil;
import com.intellij.lang.jsgraphql.types.schema.GraphQLInputFieldsContainer;
import com.intellij.lang.jsgraphql.types.schema.GraphQLInputObjectField;
import com.intellij.lang.jsgraphql.types.schema.GraphQLType;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.NotNull;

public abstract class GraphQLObjectFieldMixin extends GraphQLNamedElementImpl implements GraphQLObjectField, GraphQLTypeScopeProvider {
    public GraphQLObjectFieldMixin(@NotNull ASTNode node) {
        super(node);
    }

    @Override
    public GraphQLType getTypeScope() {
        if (getName() != null) {
            // the type scope for an object field the type of the field as defined in the parent type scope
            final GraphQLTypeScopeProvider typeScopeProvider = PsiTreeUtil.getParentOfType(this, GraphQLTypeScopeProvider.class);
            if (typeScopeProvider != null) {
                GraphQLType typeScope = typeScopeProvider.getTypeScope();
                if (typeScope != null) {
                    typeScope = GraphQLSchemaUtil.getUnmodifiedType(typeScope); // unwrap list, non-null since we want a specific field
                    if (typeScope instanceof GraphQLInputFieldsContainer) {
                        final GraphQLInputObjectField inputObjectField = ((GraphQLInputFieldsContainer) typeScope).getFieldDefinition(this.getName());
                        if (inputObjectField != null) {
                            return inputObjectField.getType();
                        }
                    }
                }
            }
        }

        return null;
    }
}


text:
/* eslint-disable max-len */
import React from "react";
import Immutable from "immutable";
import { Provider } from "react-redux";
import { shallow, mount } from "enzyme";

import renderer from "react-test-renderer";

import { displayOrder, transforms } from "@nteract/transforms";
import {
  NotebookApp,
  getCodeMirrorMode
} from "../../src/providers/notebook-app";

import { dummyStore, dummyCommutable } from "../../src/dummy";

const dummyCellStatuses = dummyCommutable
  .get("cellOrder")
  .reduce(
    (statuses, cellID) =>
      statuses.set(
        cellID,
        Immutable.fromJS({ outputHidden: false, inputHidden: false })
      ),
    new Immutable.Map()
  );

// Boilerplate test to make sure the testing setup is configured
describe("NotebookApp", () => {
  test("accepts an Immutable.List of cells", () => {
    const stickyCells = new Immutable.Set().add(
      dummyCommutable.getIn(["cellOrder", 0])
    );

    const component = shallow(
      <NotebookApp
        cellOrder={dummyCommutable.get("cellOrder")}
        cellMap={dummyCommutable.get("cellMap")}
        transient={new Immutable.Map({ cellMap: new Immutable.Map() })}
        cellPagers={new Immutable.Map()}
        cellStatuses={new Immutable.Map()}
        // Sticky the first cell of the notebook so that the sticky code gets
        // triggered.
        stickyCells={stickyCells}
      />
    );
    expect(component).not.toBeNull();
  });

  describe("getCodeMirrorMode", () => {
    test("determines the right mode from the notebook metadata", () => {
      const mode = getCodeMirrorMode(dummyCommutable.get("metadata"));
      expect(mode).toEqual(Immutable.fromJS({ name: "ipython", version: 3 }));

      const lang2 = getCodeMirrorMode(
        dummyCommutable
          .setIn(["metadata", "language_info", "codemirror_mode", "name"], "r")
          .get("metadata")
      );
      expect(lang2).toEqual(Immutable.fromJS({ name: "r", version: 3 }));
    });
  });

  describe("keyDown", () => {
    test("detects a cell execution keypress", () => {
      const focusedCell = dummyCommutable.getIn(["cellOrder", 1]);

      const context = { store: dummyStore() };

      context.store.dispatch = jest.fn();

      const component = shallow(
        <NotebookApp
          cellOrder={dummyCommutable.get("cellOrder")}
          cellMap={dummyCommutable.get("cellMap")}
          transient={new Immutable.Map({ cellMap: new Immutable.Map() })}
          cellPagers={new Immutable.Map()}
          cellStatuses={dummyCellStatuses}
          stickyCells={new Immutable.Set()}
          cellFocused={focusedCell}
        />,
        { context }
      );

      const inst = component.instance();

      const evt = new window.CustomEvent("keydown");
      evt.ctrlKey = true;
      evt.keyCode = 13;

      inst.keyDown(evt);

      expect(context.store.dispatch).toHaveBeenCalledWith({
        type: "EXECUTE_FOCUSED_CELL"
      });
    });
    test("detects a focus to next cell keypress", () => {
      const focusedCell = dummyCommutable.getIn(["cellOrder", 1]);

      const context = { store: dummyStore() };

      context.store.dispatch = jest.fn();

      const component = shallow(
        <NotebookApp
          cellOrder={dummyCommutable.get("cellOrder")}
          cellMap={dummyCommutable.get("cellMap")}
          transient={new Immutable.Map({ cellMap: new Immutable.Map() })}
          cellPagers={new Immutable.Map()}
          cellStatuses={dummyCellStatuses}
          stickyCells={new Immutable.Set()}
          cellFocused={focusedCell}
        />,
        { context }
      );

      const inst = component.instance();

      const evt = new window.CustomEvent("keydown");
      evt.shiftKey = true;
      evt.keyCode = 13;

      inst.keyDown(evt);

      expect(context.store.dispatch).toHaveBeenCalledWith({
        type: "FOCUS_NEXT_CELL_EDITOR"
      });
    });
    test("handles a focus to next cell keypress on a sticky cell", () => {
      const focusedCell = dummyCommutable.getIn(["cellOrder", 1]);

      const context = { store: dummyStore() };

      context.store.dispatch = jest.fn();

      const component = shallow(
        <NotebookApp
          cellOrder={dummyCommutable.get("cellOrder")}
          cellMap={dummyCommutable.get("cellMap")}
          transient={new Immutable.Map({ cellMap: new Immutable.Map() })}
          cellPagers={new Immutable.Map()}
          cellStatuses={dummyCellStatuses}
          stickyCells={new Immutable.Set([focusedCell])}
          cellFocused={focusedCell}
        />,
        { context }
      );

      const inst = component.instance();

      const evt = new window.CustomEvent("keydown");
      evt.shiftKey = true;
      evt.keyCode = 13;

      inst.keyDown(evt);

      expect(context.store.dispatch).not.toHaveBeenCalledWith({
        type: "FOCUS_NEXT_CELL",
        id: focusedCell,
        createCellIfUndefined: true
      });
    });
  });
});


text:
<?xml version="1.0" encoding="utf-8" ?>
<LabelPrint>
<Report>
<Title />
<ProjectTitle>ICH</ProjectTitle>
<User />
<Date>22/12/2020</Date>
</Report>
<LabelList>
<Label>
<Counter>1</Counter>
<CollectionSpecimen>
	<CollectionSpecimenID>223924801</CollectionSpecimenID>
	<AccessionNumber>ICH-000014</AccessionNumber>
	<AccessionNumberSpecimen>ICH-000014</AccessionNumberSpecimen>
	<DepositorsName>Sammlung A. Koenig</DepositorsName>
	<ExternalDatasourceID>19</ExternalDatasourceID>
	<AccessionNumberPart>ICH-000014</AccessionNumberPart>
	<MaterialCategory>preserved specimen</MaterialCategory>
</CollectionSpecimen>
<CollectionEvent>
	<CollectionMonth>6</CollectionMonth>
	<CollectionYear>1885</CollectionYear>
	<CollectionDateSupplement>Juni 1885</CollectionDateSupplement>
	<LocalityDescription>Neapel Fischmarkt bis zur linken Landzunge (Isoloa di Nisida)</LocalityDescription>
	<CountryCache>Italy</CountryCache>
</CollectionEvent>
<CollectionEventLocalisations>
	<Localisation>
		<LocalisationSystemName>Coordinates WGS84</LocalisationSystemName>
		<ParsingMethod>Coordinates</ParsingMethod>
		<MeasurementUnit />
		<Location1>14.240485</Location1>
		<Location2>40.844</Location2>
		<LocationNotes>Neapel (GeoNet Names (NIMA):68616323:countries 2nd order divisions) 40.8447229 14.2403411 7619</LocationNotes>
		<AverageLatitudeCache>40.844</AverageLatitudeCache>
		<AverageLongitudeCache>14.24049</AverageLongitudeCache>
		<CoordinatesDegMinSec LatPrefix="N" LatSec="38.4" LatMin="50" LatDeg="40" LongPrefix="E" LongSec="25.746688843" LongMin="14" LongDeg="14" Longitude="14° 14' 26''" Latitude="40° 50' 38''" />
	</Localisation>
</CollectionEventLocalisations>
<QRcode>
	<QRcode>ICH-000014</QRcode>
	<ImagePath>577384.png</ImagePath>
</QRcode>
<Collectors>
	<Collector>
		<CollectorsName>A. Koenig</CollectorsName>
		<Agent>
			<SecondName>Koenig</SecondName>
			<FirstName>A.</FirstName>
			<FirstNameAbbreviation>A.</FirstNameAbbreviation>
		</Agent>
	</Collector>
</Collectors>
<Units>
	<MainUnit>
		<FamilyCache>Triglidae</FamilyCache>
		<OrderCache>Scorpaeniformes</OrderCache>
		<TaxonomicGroup>fish</TaxonomicGroup>
		<NumberOfUnits>1</NumberOfUnits>
		<Identifications>
			 <Identification>
				<TaxonomicName>Trigla lyra Linnaeus 1758</TaxonomicName>
				<Taxon>
					 <TaxonPart>
						<Genus>Trigla</Genus>
						<Rank>sp.</Rank>
						<SpeciesEpithet>lyra</SpeciesEpithet>
						<AuthorsSpecies>Linnaeus 1758</AuthorsSpecies>
					</TaxonPart>
				</Taxon>
				<IdentificationQualifier />
				<QualifierText />
				<ResponsibleName>A. Koenig</ResponsibleName>
				<Agent>
					<SecondName>Koenig</SecondName>
					<FirstName>A.</FirstName>
					<FirstNameAbbreviation>A.</FirstNameAbbreviation>
				</Agent>
			</Identification>
		</Identifications>
		<ExternalIdentifiers>
			<ExternalIdentifier>
				<Type>FamilyNumber (Pisces)</Type>
				<Identifier>Triglidae 310</Identifier>
				<URL />
				<Notes />
			</ExternalIdentifier>
		</ExternalIdentifiers>
	</MainUnit>
</Units>
</Label>
</LabelList>
</LabelPrint>


text:
#region Copyright notice and license

// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc.  All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#endregion

using System;
using System.Reflection;

namespace Google.ProtocolBuffers
{
    /// <summary>
    /// Utilities for arbitrary messages of an unknown type. This class does not use
    /// generics precisely because it is designed for dynamically discovered types.
    /// </summary>
    public static class MessageUtil
    {
        /// <summary>
        /// Returns the default message for the given type. If an exception is thrown
        /// (directly from this code), the message will be suitable to be displayed to a user.
        /// </summary>
        /// <param name="type"></param>
        /// <exception cref="ArgumentNullException">The type parameter is null.</exception>
        /// <exception cref="ArgumentException">The type doesn't implement IMessage, or doesn't
        /// have a static DefaultMessage property of the same type, or is generic or abstract.</exception>
        /// <returns></returns>
        public static IMessage GetDefaultMessage(Type type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type", "No type specified.");
            }
            if (type.IsAbstract || type.IsGenericTypeDefinition)
            {
                throw new ArgumentException("Unable to get a default message for an abstract or generic type (" +
                                            type.FullName + ")");
            }
            if (!typeof(IMessage).IsAssignableFrom(type))
            {
                throw new ArgumentException("Unable to get a default message for non-message type (" + type.FullName +
                                            ")");
            }
            PropertyInfo property = type.GetProperty("DefaultInstance",
                                                     BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
            if (property == null)
            {
                throw new ArgumentException(type.FullName + " doesn't have a static DefaultInstance property");
            }
            if (property.PropertyType != type)
            {
                throw new ArgumentException(type.FullName + ".DefaultInstance property is of the wrong type");
            }
            return (IMessage) property.GetValue(null, null);
        }

        /// <summary>
        /// Returns the default message for the type with the given name. This is just
        /// a convenience wrapper around calling Type.GetType and then GetDefaultMessage.
        /// If an exception is thrown, the message will be suitable to be displayed to a user.
        /// </summary>
        /// <param name="typeName"></param>
        /// <exception cref="ArgumentNullException">The typeName parameter is null.</exception>
        /// <exception cref="ArgumentException">The type doesn't implement IMessage, or doesn't
        /// have a static DefaultMessage property of the same type, or can't be found.</exception>
        public static IMessage GetDefaultMessage(string typeName)
        {
            if (typeName == null)
            {
                throw new ArgumentNullException("typeName", "No type name specified.");
            }
            Type type = Type.GetType(typeName);
            if (type == null)
            {
                throw new ArgumentException("Unable to load type " + typeName);
            }
            return GetDefaultMessage(type);
        }
    }
}