text:
import _dom from "../../utils/dom-utils.js";
import _net from "../../utils/net-utils.js";

import CsapUser from "../../utils/CsapUser.js"

import utils from "../utils.js"

import events from "./events.js"
import eventDetails from "./event-details.js"

import health from "./health.js"
import meters from "./meters.js"

import "../../libs/jqplot.js";
import summaryTrends from "./summary-trends.js";
import kubernetes from "../services/kubernetes.js"

const performance = performance_views();

export default performance;

function performance_views() {

    _dom.logHead( "Module loaded" );

    let kubernetesServiceName = "kubelet";
    let containerServiceName = "docker";

    const $healthServiceNames = utils.findContent( "#health-service-names" );
    const $kubernetesNav = utils.findNavigation( ".kubernetes-active" );
    const $kubernetesNavLabel = utils.findNavigation( "label.kubernetes-active" );

    const $performanceTab = $( "#performance-tab-content" );
    const $trendTime = $( "select.trend-time", $performanceTab );
    const $trendTop = $( "select.trend-top", $performanceTab );

    const $alertsPanel = $( "#performance-tab-alerts", $performanceTab );
    const $alertTrends = $( ".alert-trends", $alertsPanel );
    const $alertOptions = $( ".options", $alertsPanel );
    const $alertWeeks = $( "select", $alertOptions );
    const $alertByHost = $( "input.by-host", $alertOptions );

    const $activityPanel = $( "#performance-tab-activity-trends", $performanceTab );
    const $activityTrends = $( ".activity-trends", $activityPanel );
    const $activityDays = $( "select", $activityPanel );
    const $activityByHost = $( "input.by-host", $activityPanel );

    const $kubernetesRtPanel = $( "#performance-tab-kubernetes-rt", $performanceTab );
    const $kubernetesRtNodeTableBody = $( "#node-table-div table tbody", $kubernetesRtPanel );
    const $kubernetesRtContainerTableBody = $( "#container-table-div table tbody", $kubernetesRtPanel );
    const $kubernetesRtPodTableBody = $( "#pod-table-div table tbody", $kubernetesRtPanel );
    const $kubeRtPodFilter = $( "#k8-top-filter", $kubernetesRtPanel );
    const $kubeRtClearPodFilter = $( "#clear-pod-filter", $kubernetesRtPanel );
    const $kubeRtSummaryCategory = $( "#metric-summary-category", $kubernetesRtPanel );
    const $kubeRtDetailCategory = $( "#metric-detail-category", $kubernetesRtPanel );
    const $kubeNodeScroll = $( "#node-table-height", $kubernetesRtPanel );
    let _latestKubernetesReport;

    let _kubeRtFilterTimer;

    const $appPanel = $( "#performance-tab-app", $performanceTab );
    const $appTrends = $( ".app-trends", $appPanel );
    const $appTrendFilter = $( "#app-trend-filter", $appPanel );
    let _appTrendFilterTimer;
    const $appDays = $( "select.trend-time", $appPanel );
    const $appByHost = $( "input.by-host", $appPanel );
    const $appSlideShow = $( "input.slide-show", $appPanel );

    const $servicePanel = $( "#performance-tab-service", $performanceTab );
    const $serviceTrends = $( ".service-trends", $servicePanel );
    const $serviceDays = $( "select.trend-time", $servicePanel );
    const $serviceByService = $( "input.by-host", $servicePanel );
    const $serviceSlideShow = $( "input.slide-show", $servicePanel );

    const $hostPanel = $( "#performance-tab-host", $performanceTab );
    const $hostTrends = $( ".host-trends", $hostPanel );
    const $hostDays = $( "select.trend-time", $hostPanel );
    const $hostByHost = $( "input.by-host", $hostPanel );
    const $hostSlideShow = $( "input.slide-show", $hostPanel );

    const $infraPanel = $( "#performance-tab-infra", $performanceTab );
    const $infraTrends = $( ".infra-trends", $infraPanel );
    const $infraDays = $( "select.trend-time", $infraPanel );
    const $infraByHost = $( "input.by-host", $infraPanel );
    const $infraSlideShow = $( "input.slide-show", $infraPanel );

    const $dockerPanel = $( "#performance-tab-docker", $performanceTab );
    const $dockerTrends = $( ".docker-trends", $dockerPanel );
    const $dockerDays = $( "select.trend-time", $dockerPanel );
    const $dockerByHost = $( "input.by-host", $dockerPanel );
    const $dockerSlideShow = $( "input.slide-show", $dockerPanel );

    const $kubeletPanel = $( "#performance-tab-kubelet", $performanceTab );
    const $kubeletTrends = $( ".kubelet-trends", $kubeletPanel );
    const $kubeletDays = $( "select.trend-time", $kubeletPanel );
    const $kubeletByHost = $( "input.by-host", $kubeletPanel );
    const $kubeletSlideShow = $( "input.slide-show", $kubeletPanel );

    let csapUser = new CsapUser();

    const navigationOperations = {
        "health-reports": health.show,
        "alerts": refreshStatus,
        "events": events.show,
        "event-details": eventDetails.show,
        "infra": showInfraTrends,
        "app": showAppTrends,
        "host": showHostTrends,
        "service": showServiceTrends,
        "docker": showContainerTrends,
        "kubelet": showKubeletTrends,
        "activity-trends": showUserActivityTrends,
        "meters": function ( $menuContainer, forceHostRefresh, menuPath ) {
            return meters.show(
                forceHostRefresh,
                utils.getActiveProject(),
                utils.getActiveProject( false ) );
        },
        "kubernetes-rt": showKubernetesRealTime
    };

    return {

        initialize: function () {
            initialize();
        },

        refreshStatus: function ( forceHostRefresh ) {
            return refreshStatus( null, forceHostRefresh );
        },

        reDraw: function () {
            $trendTime.filter( ":visible" ).trigger( "change" );
        },

        show: function ( $menuContainer, forceHostRefresh, menuPath ) {

            let activeMenuId = $menuContainer.attr( "id" );

            console.log( `active menuPath: ${ menuPath }` );

            let operation = navigationOperations[ menuPath ];

            let $menuLoaded;

            if ( operation ) {
                $menuLoaded = operation( $menuContainer, forceHostRefresh, menuPath );

            } else {
                console.warn( ` no operation for ${ menuPath }` );
            }

            return $menuLoaded;

        }

    };

    function initialize() {

        $trendTop.change( function () {
            $trendTime.filter( ":visible" ).trigger( "change" );
        } );

        $trendTime.change( function () {
            console.log( ` syncing time selection` );
            let newDayCount = $( this ).val();
            let currentServiceDayCount = $serviceDays.val();
            $trendTime.val( newDayCount );

            if ( newDayCount > 0 ) {
                $serviceDays.val( newDayCount )
            } else {
                $serviceDays.val( currentServiceDayCount );
            }
        } );

        $appTrendFilter.off().keyup( function () {
            console.log( "Applying trend filter" );
            clearTimeout( _appTrendFilterTimer );
            let trendFilter = $appTrendFilter.val();
            _appTrendFilterTimer = setTimeout( function () {
                if ( trendFilter.length > 0 ) {
                    $( "div.the-plot", $appPanel ).hide();
                    $( "div.the-plot", $appPanel ).each( function () {
                        let $title = $( ".jqplot-title", $( this ) );
                        if ( $title.text().toLowerCase().includes( trendFilter.toLowerCase() ) ) {
                            $( this ).show();
                        }
                    } )
                } else {
                    $( "div.the-plot", $appPanel ).show();
                    if ( !$appSlideShow.is( ":checked" ) ) {
                        $( "div#app-master-slide", $appPanel ).hide();
                    }
                }
            }, 200 );
        } );

        $appDays.change( showAppTrends );
        $infraDays.change( showInfraTrends );
        $( "input.show-by-env", $performanceTab ).change( function () {
            showInfraTrends();
        } );
        $serviceDays.change( showServiceTrends );
        $hostDays.change( showHostTrends );
        $dockerDays.change( showContainerTrends );
        $kubeletDays.change( showKubeletTrends );
        $activityDays.change( showUserActivityTrends );
        $alertWeeks.change( showAlertSummaryGraph );

        meters.initialize();

        health.initialize();

        events.initialize();

        $kubernetesRtNodeTableBody.parent().tablesorter( {
            sortList: [ [ 1, 1 ] ],
            theme: 'csapSummary',
            //            widgets: [ 'uitheme', 'default', 'filter', 'scroller' ],
            //            widgetOptions: {
            //                scroller_height: 100,
            //                // scroll tbody to top after sorting
            //                scroller_upAfterSort: true,
            //                // pop table header into view while scrolling up the page
            //                scroller_jumpToHeader: true,
            //                // In tablesorter v2.19.0 the scroll bar width is auto-detected
            //                // add a value here to override the auto-detected setting
            //                scroller_barWidth: null
            //                        // scroll_idPrefix was removed in v2.18.0
            //                        // scroller_idPrefix : 's_'
            //            }
        } );

        $kubernetesRtContainerTableBody.parent().tablesorter( {
            sortList: [ [ 1, 1 ] ],
            theme: 'csapSummary'
        } );

        $kubernetesRtPodTableBody.parent().tablesorter( {
            sortList: [ [ 2, 1 ] ],
            theme: 'csapSummary'
        } );

        let $hostServiceNames = utils.getServiceSelector();
        $hostServiceNames.change( function () {
            $( "span", $hostServiceNames.parent() ).text( $( this ).val() );
        } );
    }

    function refreshStatus( $menuContainer, forceHostRefresh ) {
        //$contentLoaded = new $.Deferred();
        getStatusReport( $menuContainer, forceHostRefresh );
        //return $contentLoaded;
    }

    function getStatusReport( $displayContainer, forceHostRefresh ) {

        let parameters = {
            project: utils.getActiveProject(),
            blocking: forceHostRefresh
        };

        if ( utils.isObject( forceHostRefresh ) ) {
            console.trace( "invalid force parameter" );
            parameters = {
                project: utils.getActiveProject(),
                blocking: false
            };
        }
        console.debug( `getStatusReport() forceHostRefresh: ${ forceHostRefresh }` );

        $.getJSON(
            APP_BROWSER_URL + "/status-report",
            parameters )

            .done( function ( statusReport ) {

                utils.setStatusReport( statusReport );

                kubernetesServiceName = statusReport[ "kubernetes-service" ];
                containerServiceName = statusReport[ "container-service" ];

                if ( statusReport.serviceIdMapping ) {
                    addServiceNames( statusReport.serviceIdMapping );
                }

                if ( statusReport.servicesWithHealth ) {
                    addServiceHealthNames( statusReport.servicesWithHealth );
                }

                if ( statusReport.kubernetesNodes === 0 ) {
                    $kubernetesNav.hide();
                } else {
                    $kubernetesNav.show();
                    utils.navigationCount( "#kevent-count", statusReport.kubernetesEvents, 500 );
                    utils.navigationCount( "#pod-count", statusReport.podCount, 5000 );
                    utils.navigationCount( "#node-count", statusReport.kubernetesNodes, 5000 );
                    utils.navigationCount( "#volume-count", statusReport.volumeCount, 5000 );

                    if ( statusReport.kubernetesMetrics ) {
                        $( "button", $kubernetesNavLabel ).remove();
                        utils.flash( $kubernetesNavLabel, false );
                    } else {

                        let msg = "Kubernetes metrics collection is currently disabled - very metrics-server is deployed and running";
                        $( "button", $kubernetesNavLabel ).remove();
                        let $metrics = jQuery( '<button/>', {
                            class: "csap-icon csap-warn",
                            title: "Metrics Disabled"
                        } )
                            .css( "float", "right" )
                            .click( function () {
                                alertify.csapWarning( msg );
                            } );
                        $kubernetesNavLabel.append( $metrics );
                        utils.flash( $kubernetesNavLabel, true );

                    }

                }

                utils.navigationCount( "#host-count", statusReport.hosts );
                if ( statusReport.cpuCount ) {
                    // Agent dashboard - update settings
                    let $loadCountIndicator = utils.navigationCount( "#cpu-load-count", statusReport.cpuLoad, statusReport.cpuCount - 1 );
                    $loadCountIndicator.attr( "title",
                        `  cpu load: ${ statusReport.cpuLoad }`
                        + `\ncpu count: ${ statusReport.cpuCount }` );
                    utils.findNavigation( "#hosts-tab .tab-primary span:first-child()" ).text( "Host" );
                    utils.navigationCount( "#host-count", statusReport.cpu, 60, "%" );
                }
                utils.navigationCount( "#service-count", statusReport.services );

                $( "#bar-backlog" ).text( statusReport.deploymentBacklog );
                $( "#backlog-count" ).text( statusReport.deploymentBacklog )
                if ( statusReport.deploymentBacklog > 0 ) {
                    $( "#backlog-count" ).show();
                    utils.flash( $( "#backlog-count" ), true );
                    $( "#bar-backlog" ).parent().addClass( "bar-high" );
                } else {
                    $( "#backlog-count" ).hide();
                    $( "#bar-backlog" ).parent().removeClass( "bar-high" );
                }

                updateUsers( statusReport.users );
                $( "#last-operation" ).text( statusReport.lastOp );
                $( "#last-operation" ).attr( "title", statusReport.lastOp );

                let $alertsList = buildAlertsList( statusReport );
                if ( $displayContainer ) {
                    // only update ui when tab is active
                    $( ".alerts", $alertsPanel )
                        .empty()
                        .append( $alertsList );
                    showAlertSummaryGraph();
                }
                console.debug( `getStatusReport() : backlog: ${ statusReport.deploymentBacklog }` );
                //$contentLoaded.resolve();

            } )

            .fail( function ( jqXHR, textStatus, errorThrown ) {

                handleConnectionError( `retrieving alerts '${ textStatus }'`, errorThrown );
            } );
    }

    function addServiceNames( serviceIdMapping ) {

        //console.log( `checking: `, serviceIdMapping )

        let $hostServiceNames = utils.getServiceSelector();

        let currentServiceCount = $( "option", $hostServiceNames ).length;
        if ( ( currentServiceCount - 1 ) !== Object.keys( serviceIdMapping ).length ) {

            $hostServiceNames.empty();

            jQuery( '<option/>', {
                text: utils.agentServiceSelect()
            } ).appendTo( $hostServiceNames );

            // statusReport.serviceNames.sort()
            for ( let name of utils.keysSortedCaseIgnored( serviceIdMapping ) ) {
                let $option = jQuery( '<option/>', {
                    text: name,
                    "data-service": serviceIdMapping[ name ]
                } ).appendTo( $hostServiceNames );
            }

            if ( utils.getDefaultService() ) {
                $hostServiceNames.val( utils.getDefaultService() );
                $( "span", $hostServiceNames.parent() ).text( utils.getDefaultService() );
            }
        }
    }

    function addServiceHealthNames( serviceNames ) {

        let currentServiceCount = $( "option", $healthServiceNames ).length;
        if ( ( currentServiceCount - 1 ) !== serviceNames.length ) {

            $healthServiceNames.empty();

            jQuery( '<option/>', {
                html: " ",
                value: 0
            } ).appendTo( $healthServiceNames );

            for ( let name of serviceNames.sort() ) {
                jQuery( '<option/>', {
                    text: name
                } ).appendTo( $healthServiceNames );
            }

            $healthServiceNames.off().change( function () {
                utils.getServiceSelector()
                    .val( $( this ).val() )
                    .trigger( "change" );
                $healthServiceNames.val( 0 );
            } );

        }
    }

    function showAppTrends() {

        summaryTrends.cleanUp();

        let numberOfDays = $appDays.val() * 7;
        if ( $appDays.val() < 1 ) {
            numberOfDays = $appDays.val();
        }

        $appByHost.off().change( showAppTrends );
        $appSlideShow.off().change( showAppTrends );

        summaryTrends.showApplication(
            $appTrends,
            numberOfDays,
            $appByHost.is( ":checked" ),
            $appSlideShow );
    }

    function showInfraTrends() {

        summaryTrends.cleanUp();

        let numberOfDays = $infraDays.val() * 7;
        if ( $infraDays.val() < 1 ) {
            numberOfDays = $infraDays.val();
        }

        $infraByHost.off().change( showInfraTrends );
        $infraSlideShow.off().change( function () {
            if ( $infraSlideShow.is( ":checked" ) ) {
                $( ".comment", $infraPanel ).hide();
            } else {
                $( ".comment", $infraPanel ).show();
            }

            showInfraTrends();
        } );

        summaryTrends.showTrend( $( "#infra-cpu", $infraTrends ),
            "CPU Test",
            $infraByHost.is( ":checked" ),
            4,
            "host",
            numberOfDays,
            "totalCpuTestTime",
            "",
            "numberOfSamples" );

        summaryTrends.showTrend( $( "#infra-disk", $infraTrends ),
            "Disk Test",
            $infraByHost.is( ":checked" ),
            4,
            "host",
            numberOfDays,
            "totalDiskTestTime",
            "",
            "numberOfSamples" );

        summaryTrends.showTrend( $( "#agent-ms", $infraTrends ),
            "Host Response (ms)",
            $infraByHost.is( ":checked" ),
            2,
            "application",
            numberOfDays,
            "AdminPingsMeanMs",
            "csap-agent",
            "numberOfSamples" );

    }

    function showHostTrends() {

        summaryTrends.cleanUp();

        let numberOfDays = $hostDays.val() * 7;
        if ( $hostDays.val() < 1 ) {
            numberOfDays = $hostDays.val();
        }
        let $containers = $( ".the-plot", $hostTrends );
        $containers.empty();

        $hostByHost.off().change( showHostTrends );
        $hostSlideShow.off().change( showHostTrends );

        summaryTrends.showTrend( $( "#host-alerts", $hostTrends ),
            "Alerts",
            $hostByHost.is( ":checked" ),
            4,
            "host",
            numberOfDays,
            "alertsCount",
            null,
            null );

        summaryTrends.showTrend( $( "#host-cores", $hostTrends ),
            "CPU Cores Active",
            $hostByHost.is( ":checked" ),
            4,
            "custom/core",
            numberOfDays,
            "coresUsed",
            "",
            "numberOfSamples" );

        summaryTrends.showTrend( $( "#host-load", $hostTrends ),
            "CPU Load",
            $hostByHost.is( ":checked" ),
            4,
            "host",
            numberOfDays,
            "totalLoad",
            "",
            "numberOfSamples" );

        summaryTrends.showTrend( $( "#host-threads", $hostTrends ),
            "Threads (1000's)",
            $hostByHost.is( ":checked" ),
            4,
            "host",
            numberOfDays,
            "threadsTotal",
            "",
            "numberOfSamples,1000" );

        summaryTrends.showTrend( $( "#host-files", $hostTrends ),
            "Files (1000's)",
            $hostByHost.is( ":checked" ),
            4,
            "host",
            numberOfDays,
            "totalFiles",
            "",
            "numberOfSamples,1000" );

        summaryTrends.showTrend( $( "#host-sockets-active", $hostTrends ),
            "Network Connections: Active",
            $hostByHost.is( ":checked" ),
            4,
            "host",
            numberOfDays,
            "socketTotal",
            "",
            "numberOfSamples" );

        summaryTrends.showTrend( $( "#host-sockets-wait", $hostTrends ),
            "Network Connections: Wait",
            $hostByHost.is( ":checked" ),
            4,
            "host",
            numberOfDays,
            "socketWaitTotal",
            "",
            "numberOfSamples" );

        summaryTrends.showTrend( $( "#host-sockets-time-wait", $hostTrends ),
            "Network Connections: Time Wait",
            $hostByHost.is( ":checked" ),
            4,
            "host",
            numberOfDays,
            "socketTimeWaitTotal",
            "",
            "numberOfSamples" );

        summaryTrends.showTrend( $( "#host-network-received", $hostTrends ),
            "Network: Received",
            $hostByHost.is( ":checked" ),
            4,
            "host",
            numberOfDays,
            "totalNetworkReceived",
            "",
            "numberOfSamples" );

        summaryTrends.showTrend( $( "#host-network-transmitted", $hostTrends ),
            "Network: Transmitted",
            $hostByHost.is( ":checked" ),
            4,
            "host",
            numberOfDays,
            "totalNetworkTransmitted",
            "",
            "numberOfSamples" );

        summaryTrends.showTrend( $( "#host-io-reads", $hostTrends ),
            "IO: Reads",
            $hostByHost.is( ":checked" ),
            4,
            "host",
            numberOfDays,
            "totalIoReads",
            "",
            "numberOfSamples" );

        summaryTrends.showTrend( $( "#host-io-writes", $hostTrends ),
            "IO: Writes",
            $hostByHost.is( ":checked" ),
            4,
            "host",
            numberOfDays,
            "totalIoWrites",
            "",
            "numberOfSamples" );
    }

    function showServiceTrends() {

        summaryTrends.cleanUp();

        let numberOfDays = $serviceDays.val() * 7;
        if ( $serviceDays.val() < 1 ) {
            numberOfDays = $serviceDays.val();
        }
        $serviceByService.off().change( showServiceTrends );
        let $containers = $( ".the-plot", $serviceTrends );
        $containers.empty();

        $serviceSlideShow.off().change( showServiceTrends );

        let byService = $serviceByService.is( ":checked" );

        let units = ",1000";
        let desc = "(1000's)"
        if ( byService ) {
            units = "";
            desc = "";
        }

        summaryTrends.showTrend( $( "#service-cpu", $serviceTrends ),
            `CPU ${ desc }`,
            byService,
            3,
            "os-process",
            numberOfDays,
            "topCpu",
            null,
            `numberOfSamples${ units }` );

        summaryTrends.showTrend( $( "#service-threads", $serviceTrends ),
            `Threads ${ desc }`,
            byService,
            3,
            "os-process",
            numberOfDays,
            "threadCount",
            null,
            `numberOfSamples${ units }` );

        summaryTrends.showTrend( $( "#service-sockets", $serviceTrends ),
            "Connections",
            byService,
            3,
            "os-process",
            numberOfDays,
            "socketCount",
            null,
            "numberOfSamples" );

        summaryTrends.showTrend( $( "#service-memory", $serviceTrends ),
            "Memory (Gb)",
            byService,
            3,
            "os-process",
            numberOfDays,
            "rssMemory",
            null,
            `numberOfSamples,1000` );

        summaryTrends.showTrend( $( "#service-files", $serviceTrends ),
            `Files ${ desc }`,
            byService,
            3,
            "os-process",
            numberOfDays,
            "fileCount",
            null,
            `numberOfSamples${ units }` );

        summaryTrends.showTrend( $( "#service-disk", $serviceTrends ),
            "Disk Space (Gb)",
            byService,
            3,
            "os-process",
            numberOfDays,
            "diskUtil",
            null,
            `numberOfSamples,1000` );

        summaryTrends.showTrend( $( "#service-reads", $serviceTrends ),
            "Disk Reads (Kb/s)",
            byService,
            3,
            "os-process",
            numberOfDays,
            "diskReadKb",
            null,
            "numberOfSamples" );

        summaryTrends.showTrend( $( "#service-writes", $serviceTrends ),
            "Disk Writes (Kb/s)",
            byService,
            3,
            "os-process",
            numberOfDays,
            "diskWriteKb",
            null,
            "numberOfSamples" );

    }

    function showContainerTrends() {

        summaryTrends.cleanUp();

        let numberOfDays = $dockerDays.val() * 7;
        if ( $dockerDays.val() < 1 ) {
            numberOfDays = $dockerDays.val();
        }
        let $containers = $( ".the-plot", $dockerTrends );
        $containers.empty();

        $dockerByHost.off().change( showContainerTrends );
        $dockerSlideShow.off().change( showContainerTrends );

        summaryTrends.showTrend( $( "#is-healthy", $dockerTrends ),
            `${ containerServiceName } Healthy Hosts`,
            $dockerByHost.is( ":checked" ),
            4,
            "application",
            numberOfDays,
            "isHealthy",
            containerServiceName,
            "numberOfSamples" );

        if ( !containerServiceName.includes( "docker" ) ) {

            summaryTrends.showTrend( $( "#crio-containers", $dockerTrends ),
                "CRIO Containers",
                $dockerByHost.is( ":checked" ),
                4,
                "application",
                numberOfDays,
                "crioContainerCount",
                containerServiceName,
                "numberOfSamples" );

        } else {
            $( "#crio-containers", $dockerTrends ).hide();
        }

        summaryTrends.showTrend( $( "#running-containers", $dockerTrends ),
            "Running Containers",
            $dockerByHost.is( ":checked" ),
            4,
            "application",
            numberOfDays,
            "containerRunning",
            containerServiceName,
            "numberOfSamples" );

        summaryTrends.showTrend(
            $( "#all-containers", $dockerTrends ),
            "All Containers",
            $dockerByHost.is( ":checked" ),
            4,
            "application",
            numberOfDays,
            "containerCount",
            containerServiceName,
            "numberOfSamples" );

        summaryTrends.showTrend(
            $( "#images", $dockerTrends ),
            "Images",
            $dockerByHost.is( ":checked" ),
            4,
            "application",
            numberOfDays,
            "imageCount",
            containerServiceName,
            "numberOfSamples" );

        summaryTrends.showTrend(
            $( "#volumes", $dockerTrends ),
            "Volumes",
            $dockerByHost.is( ":checked" ),
            4,
            "application",
            numberOfDays,
            "volumeCount",
            containerServiceName,
            "numberOfSamples" );
    }

    function showKubeletTrends() {

        summaryTrends.cleanUp();

        let numberOfDays = $kubeletDays.val() * 7;
        if ( $kubeletDays.val() < 1 ) {
            numberOfDays = $kubeletDays.val();
        }
        let $containers = $( ".the-plot", $kubeletTrends );
        $containers.empty();

        $kubeletByHost.off().change( showKubeletTrends );
        $kubeletSlideShow.off().change( showKubeletTrends );

        summaryTrends.showTrend( $( "#is-healthy", $kubeletTrends ),
            "Kubernetes Healthy Hosts",
            $kubeletByHost.is( ":checked" ),
            4,
            "application",
            numberOfDays,
            "isHealthy",
            kubernetesServiceName,
            "numberOfSamples" );

        summaryTrends.showTrend( $( "#event-count", $kubeletTrends ),
            "Event Count",
            $kubeletByHost.is( ":checked" ),
            4,
            "application",
            numberOfDays,
            "eventCount",
            kubernetesServiceName,
            "numberOfSamples" );

        summaryTrends.showTrend(
            $( "#node-cores", $kubeletTrends ),
            "Node Cores",
            $kubeletByHost.is( ":checked" ),
            4,
            "application",
            numberOfDays,
            "nodeCores",
            kubernetesServiceName,
            "numberOfSamples" )

        summaryTrends.showTrend(
            $( "#node-memory", $kubeletTrends ),
            "Node Memory (GB)",
            $kubeletByHost.is( ":checked" ),
            4,
            "application",
            numberOfDays,
            "nodeMemory",
            kubernetesServiceName,
            "numberOfSamples" ); // 1024 or 1

        summaryTrends.showTrend( $( "#running-pods", $kubeletTrends ),
            "Pods Running",
            $kubeletByHost.is( ":checked" ),
            4,
            "application",
            numberOfDays,
            "podRunningCount",
            kubernetesServiceName,
            "numberOfSamples" );

        summaryTrends.showTrend(
            $( "#resources-cores-available", $kubeletTrends ),
            "Resources: Cores Capacity",
            $kubeletByHost.is( ":checked" ),
            4,
            "application",
            numberOfDays,
            "capacityCores",
            kubernetesServiceName,
            "numberOfSamples" );

        summaryTrends.showTrend(
            $( "#resources-cores-requested", $kubeletTrends ),
            "Resources: Requested Cpu Cores",
            $kubeletByHost.is( ":checked" ),
            4,
            "application",
            numberOfDays,
            "requestedCores",
            kubernetesServiceName,
            "numberOfSamples" );

        summaryTrends.showTrend(
            $( "#resources-coresPercent-requested", $kubeletTrends ),
            "Resources: Requested Cores %",
            $kubeletByHost.is( ":checked" ),
            4,
            "application",
            numberOfDays,
            "requestedCores",
            kubernetesServiceName,
            "numberOfSamples" );

        summaryTrends.showTrend(
            $( "#resources-cores-limits", $kubeletTrends ),
            "Resources: Limits Cores",
            $kubeletByHost.is( ":checked" ),
            4,
            "application",
            numberOfDays,
            "limitsCores",
            kubernetesServiceName,
            "numberOfSamples" );

        summaryTrends.showTrend(
            $( "#resources-memory-available", $kubeletTrends ),
            "Resources: Capacity Memory Gb",
            $kubeletByHost.is( ":checked" ),
            4,
            "application",
            numberOfDays,
            "capacityMemory",
            kubernetesServiceName,
            "numberOfSamples" );

        summaryTrends.showTrend(
            $( "#resources-memory-requested", $kubeletTrends ),
            "Resources: Requested Memory Gb",
            $kubeletByHost.is( ":checked" ),
            4,
            "application",
            numberOfDays,
            "requestedMemory",
            kubernetesServiceName,
            "numberOfSamples" );

        summaryTrends.showTrend(
            $( "#resources-memoryPercent-requested", $kubeletTrends ),
            "Resources: Requested Memory %",
            $kubeletByHost.is( ":checked" ),
            4,
            "application",
            numberOfDays,
            "requestedMemoryPercent",
            kubernetesServiceName,
            "numberOfSamples" );

        summaryTrends.showTrend(
            $( "#resources-memory-limits", $kubeletTrends ),
            "Resources: Limits Memory GB",
            $kubeletByHost.is( ":checked" ),
            4,
            "application",
            numberOfDays,
            "limitsMemory",
            kubernetesServiceName,
            "numberOfSamples" );

    }

    function showUserActivityTrends() {

        let numberOfDays = $activityDays.val() * 7;
        let $container = $( ".the-plot", $activityTrends );
        ;

        $activityByHost.off().change( showUserActivityTrends );

        return summaryTrends.showUserActivity( $container, numberOfDays, $activityByHost.is( ":checked" ), 1 );
    }

    function showAlertSummaryGraph() {

        let numberOfDays = $alertWeeks.val() * 7;
        let $container = $( ".the-plot", $alertTrends );

        $alertByHost.off().change( showAlertSummaryGraph );

        summaryTrends.showHealth( $container, numberOfDays, $alertByHost.is( ":checked" ) );
    }

    function showKubernetesRealTime( $menuContainer, forceHostRefresh, menuPath ) {
        let parameters = {
            project: utils.getActiveProject(),
            blocking: forceHostRefresh
        };

        let viewLoadedPromise = _net.httpGet( `${ APP_BROWSER_URL }/kubernetes/realtime`, parameters );

        viewLoadedPromise
            .then( kubernetesReport => {
                _dom.logArrow( `kubernetesReport`, kubernetesReport );
                _latestKubernetesReport = kubernetesReport;
                buildKubernetesRealTimeReport( kubernetesReport );
            } )
            .catch( ( e ) => {
                console.warn( e );
            } );;

        return viewLoadedPromise;

    }

    function buildFilterCell( item, style ) {

        let $cell = jQuery( '<td/>', {
            class: style
        } );

        let $container = jQuery( '<div/>', {
            text: item,
            class: "flex-container"
        } ).appendTo( $cell );

        jQuery( '<button/>', {
            title: "click to apply as filter",
            class: "csap-icon csap-filter"
        } )
            .prependTo( $container )
            .click( function () {
                $kubeRtPodFilter.val( item );
                if ( style === `namespace` ) {
                    $kubeRtSummaryCategory.val( "Namespace" );
                }
                $kubeRtSummaryCategory.trigger( "change" );
                // $kubeRtPodFilter.trigger( "keyup" ) ;
                return false;
            } );

        return $cell;
    }

    function buildCoresCell( cores ) {

        let coresDesc = cores;
        if ( cores != 0 ) {
            coresDesc = cores.toFixed( 2 )
        }

        let $cell = jQuery( '<td/>', {
            class: "numeric",
            text: coresDesc
        } );

        return $cell;
    }

    function buildSimpleCell( item, style ) {

        let $cell = jQuery( '<td/>', {
            class: style,
            text: item
        } );

        //        jQuery( '<div/>', {
        //            text: item,
        //            class: "flex-container"
        //        } ).appendTo( $cell ) ;

        return $cell;
    }

    function buildFlexCell( item, style ) {

        let $cell = jQuery( '<td/>', {
            class: style
        } );

        jQuery( '<div/>', {
            text: item,
            class: "flex-container"
        } ).appendTo( $cell );

        return $cell;
    }

    function applyK8TopFilter( $tableBody ) {

        let $rows = $( 'tr', $tableBody );

        let filterSpaceSeparated = $kubeRtPodFilter.val();

        console.log( "filter", filterSpaceSeparated );

        if ( filterSpaceSeparated.length > 0 ) {

            $kubeRtPodFilter.addClass( "modified" );

            $kubeRtClearPodFilter.css( "visibility", "visible" );
            $rows.hide();
            for ( let filter of filterSpaceSeparated.split( " " ) ) {
                $( 'td:contains("' + filter + '")', $rows ).parent().show();
            }
        } else {
            $kubeRtPodFilter.removeClass( "modified" );
            $rows.show();
            $kubeRtClearPodFilter.css( "visibility", "hidden" );
        }
    }

    function buildKubernetesRealTimeReport( kubernetesReport ) {

        $kubernetesRtNodeTableBody.empty();

        if ( kubernetesReport.error ) {
            let $row = jQuery( '<tr/>', {} )
                .appendTo( $kubernetesRtNodeTableBody );
            jQuery( '<td/>', {
                text: `Kubernetes metrics not available`,
                colspan: 99
            } ).appendTo( $row );

            $kubernetesRtNodeTableBody.trigger( "update", "resort" );
            return;
        }

        let sortedNodeNames = utils.keysSortedCaseIgnored( kubernetesReport.nodes );
        console.log( `buildKubernetesRealTimeReport() ${ sortedNodeNames }` );
        for ( let nodeName of sortedNodeNames ) {

            let nodeDef = kubernetesReport.nodes[ nodeName ];
            let $row = jQuery( '<tr/>', {} )
                .appendTo( $kubernetesRtNodeTableBody );

            let $nodeCell = buildSimpleCell( nodeName, "" );
            $row.append( $nodeCell );
            $row.append( buildCoresCell( nodeDef.cores ) );

            let memoryInMb = Math.round( parseFloat( nodeDef.memoryGb ) * 1024 );
            $row.append( utils.buildMemoryCell( memoryInMb * 1024 * 1024 ) );
            //$row.append( nodeDef.memoryGb ) ;

            $row.append( buildSimpleCell( nodeDef.podsRunning, "numeric" ) );
            $row.append( buildSimpleCell( nodeDef.podsNotRunning, "numeric" ) );

            jQuery( '<button/>', {
                title: "Open Host Dashboard",
                class: "csap-icon csap-window"
            } )
                .prependTo( $( "div", $nodeCell ) )
                .click( function () {
                    //kubernetes.browseToPod( podName, podDef.namespace ) ;
                    utils.openAgentWindow( nodeName, "/app-browser#agent-tab,system" );
                } );

        }

        //
        //  Container or namespace
        //
        $kubernetesRtNodeTableBody.trigger( "update", "resort" );
        $kubernetesRtContainerTableBody.empty();

        let targetCategory = kubernetesReport.containers;

        let isNamespaceMode = ( $kubeRtSummaryCategory.val() === "Namespace" );
        if ( isNamespaceMode ) {
            targetCategory = kubernetesReport.namespaces;
        }

        for ( let categoryName in targetCategory ) {

            let containerDef = targetCategory[ categoryName ];

            let $row = jQuery( '<tr/>', {} );
            $kubernetesRtContainerTableBody.append( $row );

            let $containerCell = buildFilterCell( categoryName, "" );
            $row.append( $containerCell );
            $row.append( buildCoresCell( containerDef.cores ) );

            $row.append( utils.buildMemoryCell( containerDef.memoryInMb * 1024 * 1024 ) );
            // $row.append( buildSimpleCell( containerDef.memoryInMb, "num" ) ) ;

            let containerCount = containerDef.containerCount;
            let containerDesc = containerDef.containerCount;

            if ( isNamespaceMode
                && containerDef.containerCount !== containerDef.pods ) {

                containerDesc = `${ containerDef.containerCount }, ${ containerDef.pods } pods`;

            }

            if ( containerCount && containerCount > 1 ) {
                jQuery( '<span/>', {
                    title: "number of containers and pods",
                    class: "flex-right-info",
                    text: containerDesc
                } )
                    .appendTo( $( "div", $containerCell ) );
            }

        }

        $kubernetesRtContainerTableBody.trigger( "update", "resort" );

        applyK8TopFilter( $kubernetesRtContainerTableBody );

        $kubernetesRtPodTableBody.empty();

        let isPodMode = ( $kubeRtDetailCategory.val() === "Pod" );

        let detailItems = kubernetesReport.containerNamespace;
        if ( isPodMode ) {
            detailItems = new Array();
            for ( let podName in kubernetesReport.pods ) {
                let detailItem = kubernetesReport.pods[ podName ];
                detailItem.name = podName;
                detailItems.push( detailItem );
            }
        }

        //for ( let podName in kubernetesReport.pods ) {
        for ( let detailItem of detailItems ) {
            //let detailItem = kubernetesReport.pods[podName] ;

            let $row = jQuery( '<tr/>', {} );
            $kubernetesRtPodTableBody.append( $row );

            let $nameCell = buildFlexCell( detailItem.name, "" );
            $row.append( $nameCell );

            let $namespaceCell = buildFilterCell( detailItem.namespace, "namespace" );
            if ( !isPodMode
                && detailItem.containerCount
                && detailItem.containerCount > 1 ) {
                jQuery( '<span/>', {
                    title: "containers",
                    class: "flex-right-info",
                    text: detailItem.containerCount
                } ).appendTo( $( ".flex-container", $namespaceCell ) );
            }

            jQuery( '<button/>', {
                title: "view in deployment/pod browser (navigate back using browser back button).",
                class: "csap-icon csap-go  right-2"
            } )
                .prependTo( $namespaceCell )
                .click( function () {
                    kubernetes.browsePodNamespace( detailItem.namespace );
                } );

            $row.append( $namespaceCell );
            $row.append( buildCoresCell( detailItem.cores ) );
            $row.append( utils.buildMemoryCell( detailItem.memoryInMb * 1024 * 1024 ) );

            let containerNames = detailItem.name;
            if ( Array.isArray( detailItem.containers ) ) {
                containerNames = detailItem.containers.join( " " );
            }

            jQuery( '<span/>', {
                title: "container names in pod",
                class: "container-name",
                text: containerNames
            } )
                .appendTo( $( "div", $nameCell ) );

            jQuery( '<button/>', {
                title: `filter using pod container names: ${ containerNames }`,
                class: "csap-icon csap-filter"
            } )
                .prependTo( $( "div", $nameCell ) )
                .click( function () {
                    // kubernetes.browseToPod( podName, podDef.namespace ) ;
                    $kubeRtPodFilter.val( containerNames );
                    $kubeRtSummaryCategory.val( "Container" );
                    $kubeRtSummaryCategory.trigger( "change" );
                } );
            if ( isPodMode ) {
                jQuery( '<button/>', {
                    title: "view in deployment/pod browser (navigate back using browser back button).",
                    class: "csap-icon csap-go right-2"
                } )
                    .appendTo( $( "div", $nameCell ) )
                    .click( function () {
                        kubernetes.browseToPod( detailItem.name, detailItem.namespace );
                    } );
            }

        }

        $kubernetesRtPodTableBody.trigger( "update", "resort" );

        applyK8TopFilter( $kubernetesRtPodTableBody );

        $kubeRtPodFilter.off().keyup( function () {
            console.log( "Applying cluster filter" );
            clearTimeout( _kubeRtFilterTimer );
            _kubeRtFilterTimer = setTimeout( function () {
                applyK8TopFilter( $kubernetesRtContainerTableBody );
                applyK8TopFilter( $kubernetesRtPodTableBody );
            }, 200 );
        } );

        $kubeRtClearPodFilter.off().click( function () {
            $kubeRtPodFilter.val( "" );
            $kubeRtPodFilter.trigger( "keyup" );
        } );

        $kubeNodeScroll.off().change( function () {
            $kubeNodeScroll.parent().css( "max-height", $( this ).val() );
        } );

        $kubeRtSummaryCategory.off().change( function () {
            buildKubernetesRealTimeReport( _latestKubernetesReport );
        } );
        $kubeRtDetailCategory.off().change( function () {
            buildKubernetesRealTimeReport( _latestKubernetesReport );
        } );
    }

    function updateUsers( users ) {
        let $users = $( '#users' );
        $users.empty();
        let allUsers = "";
        for ( let user of users ) {
            for ( let i = 0; i < 1; i++ ) {
                allUsers += ` ${ user }`;

                jQuery( '<span/>', {
                    id: 'user_' + user,
                    class: 'userids',
                    text: user
                } ).appendTo( $users );

            }
        }

        csapUser.onHover( $( ".userids" ), 500 );

        jQuery( '<span/>', {
            title: allUsers,
            text: "users: "
        } ).prependTo( $users );
    }

    function buildAlertsList( statusReport ) {

        let errors = statusReport.alerts;
        let hostSessionReport = statusReport[ "host-sessions" ];

        //console.log(`Processing errors`, errors) ;

        let $errorList = jQuery( '<div/>', { class: "alert-listing" } );
        let errorItemNumber = 1;

        let errorGroupContainers = new Object();
        let errorGroupHostNames = new Object();

        let errorCount = 0;
        if ( errors.length !== 0 ) {

            for ( let errorRawMessage of errors ) {

                //console.debug( "error: ", errorRawMessage ) ;
                errorCount++;
                let firstWordInErrorMessage = errorRawMessage.split( " " )[ 0 ];
                if ( firstWordInErrorMessage.contains( ":" ) ) {
                    try {
                        let hostName = firstWordInErrorMessage.substring( 0, firstWordInErrorMessage.length - 1 );
                        let targetMessage = errorRawMessage.substring( errorRawMessage.indexOf( ":" ) + 1 );

                        //console.debug( `${hostName} : targetMessage: ${ targetMessage }` ) ;

                        let healthReportToken = "service live:";

                        let $healthLink = null;
                        if ( targetMessage.contains( healthReportToken ) ) {

                            let reportStartIndex = targetMessage.indexOf( healthReportToken );
                            let healthUrl = targetMessage.substring( reportStartIndex + healthReportToken.length )
                            targetMessage = targetMessage.substring( 0, reportStartIndex );

                            $healthLink = jQuery( '<a/>', {
                                target: "_blank",
                                title: "Open service live dashboard on " + hostName,
                                class: "csap-link healthReport",
                                href: healthUrl,
                                html: " service live."
                            } );
                        }

                        let $hostPortalLink = utils.buildAgentLink( hostName );
                        //
                        // Group errors by type. Eg the same error could be on multiple hosts
                        //
                        let first4words = getWords( targetMessage, 5 ).trim();
                        let first3words = getWords( targetMessage, 4 ).trim();
                        let first2words = getWords( targetMessage, 2 ).trim();
                        let firstWord = getWords( targetMessage, 2 ).trim();
                        let errorGroup = first4words;
                        if ( firstWord == "current" ) {
                            // host stats
                            errorGroup = first2words;
                        } else if ( firstWord.endsWith( ":" ) ) {
                            // service name:
                            // trim the colon and the last char in case of kubernetes
                            errorGroup = firstWord.substring( 0, firstWord.length - 2 )
                                + first3words.substring( firstWord.length );
                        }

                        //console.debug( `firstWord: '${ firstWord }' errorGroup: ${ errorGroup }` ) ;
                        if ( errorGroupContainers[ errorGroup ] !== undefined ) {

                            let $existingItem = errorGroupContainers[ errorGroup ];
                            let $subDiv = jQuery( '<div/>', { class: "sub-alert" } );
                            $existingItem.append( $subDiv );
                            //$existingItem.append( $hostPortalLink ) ;

                            $subDiv.append( targetMessage );
                            if ( $healthLink ) {
                                $subDiv.append( $healthLink );
                            }

                            if ( errorGroupHostNames[ errorGroup ] !== hostName ) {
                                $subDiv.append( " (" );
                                $subDiv.append( $hostPortalLink );
                                $subDiv.append( ") " );
                            }

                        } else {

                            $errorList.append( jQuery( '<span/>', {
                                text: errorItemNumber++ + ")"
                            } ) );

                            $errorList.append( $hostPortalLink );

                            let $note = jQuery( '<div/>', {
                                text: targetMessage
                            } );
                            $errorList.append( $note );

                            if ( $healthLink ) {
                                $note.append( $healthLink );
                            }
                            errorGroupContainers[ errorGroup ] = $note;
                            errorGroupHostNames[ errorGroup ] = hostName;
                            //$errorList.append( $errorItem ) ;
                        }

                    } catch ( e ) {
                        console.error( `alertProcessing() Failed parsing error:  '${ errorRawMessage }'`, e );
                        $errorList.append( jQuery( '<span/>', {
                            text: errorItemNumber++ + ")"
                        } ) );
                        $errorList.append( jQuery( '<span/>', {
                            text: "-"
                        } ) );
                        $errorList.append( jQuery( '<span/>', {
                            text: errorRawMessage
                        } ) );
                    }
                } else {
                    $errorList.append( jQuery( '<span/>', {
                        text: errorItemNumber++ + ")"
                    } ) );
                    $errorList.append( jQuery( '<span/>', {
                        text: "-"
                    } ) );
                    $errorList.append( jQuery( '<span/>', {
                        text: errorRawMessage
                    } ) );
                }
            }
        }

        // vmsession reporting
        for ( let hostReport of hostSessionReport ) {
            let hostName = hostReport.name;
            let hostLoginSessions = hostReport.sessions;

            if ( hostLoginSessions ) {

                for ( let hostLoginSession of hostLoginSessions ) {

                    errorCount++;
                    $errorList.append( jQuery( '<span/>', {
                        text: errorItemNumber++ + ")"
                    } ) );
                    $errorList.append( utils.buildAgentLink( hostName ) );
                    $errorList.append( jQuery( '<span/>', {
                        text: " login:" + hostLoginSession
                    } ) );

                    //                    let $errorItem = jQuery( '<li/>', { class: "decimal" } ) ;
                    //                    $errorList.append( $errorItem ) ;
                    //
                    //                    $errorItem.append( utils.buildAgentLink( hostName ) ) ;
                    //                    $errorItem.append( " login:" + hostLoginSession ) ;

                }
            }
        }

        let $statusContainer = jQuery( '<div/>', {
            class: "csap-white"
        } );

        $( "#bar-alerts" ).text( errorCount );
        if ( errorCount > 0 ) {

            jQuery( '<span/>', {
                class: "status-red",
                text: `${ errorCount } Alerts`
            } ).appendTo( $statusContainer );

            $statusContainer.append( $errorList );

            $( ".alert-count" ).text( `${ errorCount }` );
            utils.flash( $( ".alert-count" ), true );
            $( "#bar-alerts" ).parent().addClass( "bar-high" );
        } else {
            $( ".alert-count" ).empty();
            utils.flash( $( ".alert-count" ), false );

            jQuery( '<span/>', {
                class: "status-green",
                text: "No active alerts"
            } ).appendTo( $statusContainer );
        }

        return $statusContainer;
    }

    function getWords( str, count ) {
        return str.split( /\s+/ ).slice( 0, count ).join( " " );
    }

    function buildAlertsTable( alertsReport ) {

        let $tempDiv = jQuery( '<div/>', {} )
        let $alertTable = jQuery( '<table/>', {
            id: "service-alerts-table",
            class: "simple "
        } )
        let $head = jQuery( '<thead/>', {} ).appendTo( $alertTable );
        let $trow = jQuery( '<tr/>', {} ).appendTo( $head );

        jQuery( '<th/>', { html: "Host source" } ).appendTo( $trow );
        jQuery( '<th/>', { html: "Category" } ).appendTo( $trow );
        jQuery( '<th/>', { html: "Type" } ).appendTo( $trow );
        jQuery( '<th/>', { html: "Notes" } ).appendTo( $trow );

        $alertTable.appendTo( $tempDiv );

        for ( let alert of alertsReport ) {
            let $row = jQuery( '<tr/>', {} )
                .appendTo( $alertTable );
            let hostInfo = alert.host;
            if ( alert.podIp ) {
                hostInfo += ` pod: '${ alert.podIp }'`;
            } else {
                hostInfo += ` pid: '${ alert.pids[ 0 ] }'`;
            }
            jQuery( '<td/>', {
                html: hostInfo
            } ).appendTo( $row );

            jQuery( '<td/>', {
                html: alert.category
            } ).appendTo( $row );

            jQuery( '<td/>', {
                html: alert.type
            } ).appendTo( $row );

            let notes = "";

            if ( alert.id ) {
                notes += ` id: '${ alert.id }'`;
            }

            if ( alert.description ) {
                notes += ` description: '${ alert.description }'`;
            }

            if ( alert.current ) {
                notes += ` current: '${ alert.current }'`;
            }
            if ( alert.max ) {
                notes += ` max: '${ alert.max }'`;
            }
            jQuery( '<td/>', {
                html: notes
            } ).appendTo( $row );

        }

        return $tempDiv.html();
    }

}


text:
package org.elasticsearch.search.facet;

import java.util.List;

/**
 *
 */
public class SearchContextFacets {

    private final List<FacetCollector> facetCollectors;

    public SearchContextFacets(List<FacetCollector> facetCollectors) {
        this.facetCollectors = facetCollectors;
    }

    public List<FacetCollector> facetCollectors() {
        return facetCollectors;
    }
}

redpajama_set_name: RedPajamaGithub


text:
import React from 'react';
import PropTypes from 'prop-types';
import withstyles from 'isomorphic-style-loader/withStyles';
import cn from 'classnames';
import { connect } from 'react-redux';
import { loadFeed } from '../../actions/feed';
import {
  getActivities,
  getFeedIsFetching,
  getFeedErrorMessage,
} from '../../reducers/index';
import s from './FeedContainer.css';
import FetchError from '../../components/FetchError';
import Activity from '../../components/Activity';
import ActivitySkeleton from '../../components/ActivitySkeleton';

class FeedContainer extends React.Component {
  static propTypes = {
    activities: PropTypes.arrayOf(
      PropTypes.shape({
        id: PropTypes.string.isRequired,
      }),
    ).isRequired,
    isFetching: PropTypes.bool.isRequired,
    fetchFeed: PropTypes.func.isRequired,
    errorMessage: PropTypes.string,
    locale: PropTypes.string.isRequired,
  };

  static defaultProps = {
    errorMessage: '',
  };

  constructor(props) {
    super(props);
    this.fetchFeed = this.fetchFeed.bind(this);
  }

  fetchFeed() {
    const { fetchFeed } = this.props;
    fetchFeed();
  }

  render() {
    const { activities, isFetching, errorMessage, locale } = this.props;
    if (isFetching && !activities.length) {
      let n = 1;
      // eslint-disable-next-line
      const placeHolder = Array.apply(null, { length: 5 }).map(() => ({
        id: (n += 1),
      }));
      return (

          {placeHolder.map(() => (
            <ActivitySkeleton />
          ))}

      );
    }

    if (errorMessage && !activities.length) {
      return <FetchError message={errorMessage} onRetry={this.fetchFeed} />;
    }

    const outDated = {};
    const polls = {};
    const proposals = {};
    const votes = {};
    return (

        {activities.map(activity => {
          if (!activity.object) return null; // hotfix - problem is ondelete cascade for votes
          if (activity.type === 'statement') {
            if (activity.verb === 'update') {
              if (activity.objectId in outDated) {
                return null;
              }
              if (
                activity.object.pollId in polls &&
                activity.object.author.id === polls[activity.object.pollId]
              ) {
                return null;
              }
              outDated[activity.objectId] = activity.objectId;
              polls[activity.object.pollId] = activity.object.author.id;
            } else if (activity.verb === 'delete') {
              outDated[activity.objectId] = activity.object.author.id;
              polls[activity.object.pollId] = activity.object.author.id;

              return null;
            } else if (activity.objectId in outDated) {
              return null;
            } else if (activity.verb === 'create') {
              if (activity.object) {
                if (
                  activity.object.pollId in outDated &&
                  activity.object.author.id === outDated[activity.object.pollId]
                ) {
                  return null;
                }
                if (
                  activity.object.pollId in polls &&
                  activity.object.author.id === polls[activity.object.pollId]
                ) {
                  return null;
                }
                outDated[activity.object.pollId] = activity.object.author.id;
              } else {
                return null;
              }
            }
          } else if (activity.type === 'proposal') {
            if (activity.objectId in proposals) {
              return null;
            }
            proposals[activity.objectId] = activity.objectId;
          } else if (activity.type === 'vote') {
            if (votes[activity.objectId]) {
              return null;
            }
            votes[activity.objectId] = activity.objectId;
            if (activity.verb === 'delete') {
              return null;
            }
          }

          return (
            <Activity
              key={activity.id}
              actor={activity.actor}
              date={activity.createdAt}
              verb={activity.verb}
              content={activity.object}
              info={activity.info}
              locale={locale}
            />
          );
        })}

    );
  }
}
// TODO implement memoiziation with reselect
const mapStateToProps = state => ({
  activities: getActivities(state, 'feed'),
  isFetching: getFeedIsFetching(state, 'feed'),
  errorMessage: getFeedErrorMessage(state, 'feed'),
  locale: state.intl.locale,
});

const mapDispatch = {
  fetchFeed: loadFeed,
};

export default connect(
  mapStateToProps,
  mapDispatch,
)(withstyles(s)(FeedContainer));


text:
using namespace dlib;
using namespace std;

DLLEXPORT void load_mnist_dataset(const char* folder_name,
                                  const int folder_name_length,
                                  std::vector<matrix<unsigned char>*>** training_images,
                                  std::vector<uint32_t>** training_labels,
                                  std::vector<matrix<unsigned char>*>** testing_images,
                                  std::vector<uint32_t>** testing_labels)
{
    std::string tmp(folder_name, folder_name_length);
    std::vector<matrix<unsigned char>> tmp_training_images;
    std::vector<unsigned long>         tmp_training_labels;
    std::vector<matrix<unsigned char>> tmp_testing_images;
    std::vector<unsigned long>         tmp_testing_labels;
    load_mnist_dataset(tmp, tmp_training_images, tmp_training_labels, tmp_testing_images, tmp_testing_labels);

    auto ret_training_images = new std::vector<matrix<unsigned char>*>();
    auto ret_training_labels = new std::vector<uint32_t>();
    auto ret_testing_images = new std::vector<matrix<unsigned char>*>();
    auto ret_testing_labels = new std::vector<uint32_t>();

    for (int i = 0; i < tmp_training_images.size(); i++)
        ret_training_images->push_back(new matrix<unsigned char>(tmp_training_images[i]));
    for (int i = 0; i < tmp_training_labels.size(); i++)
        ret_training_labels->push_back(tmp_training_labels[i]);
    for (int i = 0; i < tmp_testing_images.size(); i++)
        ret_testing_images->push_back(new matrix<unsigned char>(tmp_testing_images[i]));
    for (int i = 0; i < tmp_testing_labels.size(); i++)
        ret_testing_labels->push_back(tmp_testing_labels[i]);

    *training_images = ret_training_images;
    *training_labels = ret_training_labels;
    *testing_images = ret_testing_images;
    *testing_labels = ret_testing_labels;
}

#endif


text:
var util = require('util');

var TcpCommand = require('../systemData/tcpCommand');
var InspectionDecision = require('../systemData/inspectionDecision');
var InspectionResult = require('./../systemData/inspectionResult');
var ClientMessage = require('../messages/clientMessage');
var EventStoreTransaction = require('../eventStoreTransaction');
var AccessDeniedError = require('../errors/accessDeniedError');
var WrongExpectedVersionError = require('../errors/wrongExpectedVersionError');
var StreamDeletedError = require('../errors/streamDeletedError');
var OperationBase = require('../clientOperations/operationBase');

function StartTransactionOperation(log, cb, requireMaster, stream, expectedVersion, parentConnection, userCredentials) {
  OperationBase.call(this, log, cb, TcpCommand.TransactionStart, TcpCommand.TransactionStartCompleted, userCredentials);
  this._responseType = ClientMessage.TransactionStartCompleted;

  this._requireMaster = requireMaster;
  this._stream = stream;
  this._expectedVersion = expectedVersion;
  this._parentConnection = parentConnection;
}
util.inherits(StartTransactionOperation, OperationBase);

StartTransactionOperation.prototype._createRequestDto = function() {
  return new ClientMessage.TransactionStart({
      eventStreamId: this._stream,
      expectedVersion: this._expectedVersion,
      requireMaster: this._requireMaster
  });
};

StartTransactionOperation.prototype._inspectResponse = function(response) {
  switch (response.result)
  {
    case ClientMessage.OperationResult.Success:
      this._succeed();
      return new InspectionResult(InspectionDecision.EndOperation, "Success");
    case ClientMessage.OperationResult.PrepareTimeout:
      return new InspectionResult(InspectionDecision.Retry, "PrepareTimeout");
    case ClientMessage.OperationResult.CommitTimeout:
      return new InspectionResult(InspectionDecision.Retry, "CommitTimeout");
    case ClientMessage.OperationResult.ForwardTimeout:
      return new InspectionResult(InspectionDecision.Retry, "ForwardTimeout");
    case ClientMessage.OperationResult.WrongExpectedVersion:
      this.fail(new WrongExpectedVersionError("Start transaction", this._stream, this._expectedVersion));
      return new InspectionResult(InspectionDecision.EndOperation, "WrongExpectedVersion");
    case ClientMessage.OperationResult.StreamDeleted:
      this.fail(new StreamDeletedError(this._stream));
      return new InspectionResult(InspectionDecision.EndOperation, "StreamDeleted");
    case ClientMessage.OperationResult.InvalidTransaction:
      this.fail(new Error("Invalid transaction."));
      return new InspectionResult(InspectionDecision.EndOperation, "InvalidTransaction");
    case ClientMessage.OperationResult.AccessDenied:
      this.fail(new AccessDeniedError("Write", this._stream));
      return new InspectionResult(InspectionDecision.EndOperation, "AccessDenied");
    default:
      throw new Error(util.format("Unexpected OperationResult: %s.", response.result));
  }
};

StartTransactionOperation.prototype._transformResponse = function(response) {
  return new EventStoreTransaction(response.transactionId, this.userCredentials, this._parentConnection);
};

StartTransactionOperation.prototype.toString = function() {
  return util.format("Stream: %s, ExpectedVersion: %d", this._stream, this._expectedVersion);
};

module.exports = StartTransactionOperation;


text:
ACCEPTED

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

#### Published in
Abh. K. K. Zool. -Bot. Ges. Wien 1(3):75. 1902

#### Original name
null

### Remarks
null


text:
class AddAssignedExams < ActiveRecord::Migration
  def change
    create_table :assigned_exams do |t|
      t.integer :course_id
      t.integer :exam_id
      t.integer :instructor_id
      t.integer :student_id
      t.integer :testing_center_id
      t.string  :status, default: "assigned"
      t.timestamps null: false
    end
  end
end


text:
from runner.koan import *

class AboutTuples(Koan):
    def test_creating_a_tuple(self):
        count_of_three = (1, 2, 5)
        self.assertEqual(5, count_of_three[2])

    def test_tuples_are_immutable_so_item_assignment_is_not_possible(self):
        count_of_three = (1, 2, 5)
        try:
            count_of_three[2] = "three"
        except TypeError as ex:
            self.assertMatch("'tuple' object does not support item assignment", ex[0])

    def test_tuples_are_immutable_so_appending_is_not_possible(self):
        count_of_three = (1, 2, 5)
        try:
            count_of_three.append("boom")
        except Exception as ex:
            self.assertEqual(AttributeError, type(ex))

            # Note, assertMatch() uses regular expression pattern matching,
            # so you don't have to copy the whole message.
            self.assertMatch("'tuple' object has no attribute 'append'", ex[0])

        # Tuples are less flexible than lists, but faster.

    def test_tuples_can_only_be_changed_through_replacement(self):
        count_of_three = (1, 2, 5)

        list_count = list(count_of_three)
        list_count.append("boom")
        count_of_three = tuple(list_count)

        self.assertEqual((1, 2, 5, "boom"), count_of_three)

    def test_tuples_of_one_look_peculiar(self):
        self.assertEqual(int, (1).__class__)
        self.assertEqual(tuple, (1,).__class__)
        self.assertEqual(("Hello comma!", ), ("Hello comma!", ))

    def test_tuple_constructor_can_be_surprising(self):
        self.assertEqual(('S', 'u', 'r', 'p', 'r', 'i', 's', 'e', '!'), tuple("Surprise!"))

    def test_creating_empty_tuples(self):
        self.assertEqual((), ())
        self.assertEqual((), tuple())  # Sometimes less confusing

    def test_tuples_can_be_embedded(self):
        lat = (37, 14, 6, 'N')
        lon = (115, 48, 40, 'W')
        place = ('Area 51', lat, lon)
        self.assertEqual(('Area 51', (37, 14, 6, 'N'), (115, 48, 40, 'W')), place)

    def test_tuples_are_good_for_representing_records(self):
        locations = [
            ("Illuminati HQ", (38, 52, 15.56, 'N'), (77, 3, 21.46, 'W')),
            ("Stargate B", (41, 10, 43.92, 'N'), (1, 49, 34.29, 'W')),
        ]

        locations.append(
            ("Cthulhu", (26, 40, 1, 'N'), (70, 45, 7, 'W'))
        )

        self.assertEqual("Cthulhu", locations[2][0])
        self.assertEqual(15.56, locations[0][1][2])


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingLeft="10dp"
    android:paddingRight="10dp" >

    <EditText
        android:id="@+id/title"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:hint="@string/app_title_hint"
        android:imeOptions="actionNext"
        android:singleLine="true"
        android:textColor="@color/AppTextColor" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <EditText
            android:id="@+id/date"
            android:layout_width="0sp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="@string/app_date_hint"
            android:inputType="date"
            android:textColor="@color/AppTextColor" />

        <EditText
            android:id="@+id/time"
            android:layout_width="0sp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="@string/app_time_hint"
            android:inputType="time"
            android:textColor="@color/AppTextColor" />
    </LinearLayout>

    <EditText
        android:id="@+id/description"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="top"
        android:hint="@string/app_description_hint"
        android:inputType="textMultiLine"
        android:minLines="6"
        android:textColor="@color/AppTextColor" />

</LinearLayout>


text:
package com.dumontierlab.pdb2rdf.parser;

import java.util.Collection;
import java.util.Map;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

import com.dumontierlab.pdb2rdf.model.PdbRdfModel;
import com.dumontierlab.pdb2rdf.parser.vocabulary.PdbOwlVocabulary;
import com.dumontierlab.pdb2rdf.parser.vocabulary.PdbXmlVocabulary;
import com.dumontierlab.pdb2rdf.parser.vocabulary.uri.Bio2RdfPdbUriPattern;
import com.dumontierlab.pdb2rdf.parser.vocabulary.uri.UriBuilder;
import com.dumontierlab.pdb2rdf.util.UriUtil;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.vocabulary.RDF;
import com.hp.hpl.jena.vocabulary.RDFS;

/**
 * @author Alexander De Leon
 */
public class ChemCompCategory extends ContentHandlerState {

	private final String pdbId;
	private String componentId;
	private Resource componentType;
	private final Map<String, Collection<Resource>> residues;

	public ChemCompCategory(PdbRdfModel rdfModel, UriBuilder uriBuilder, String pdbId,
			Map<String, Collection<Resource>> residues) {
		super(rdfModel, uriBuilder);
		this.pdbId = pdbId;
		this.residues = residues;
	}

	@Override
	public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
		if (PdbXmlVocabulary.CHEMICAL_COMPONENT.equals(localName)) {
			componentId = attributes.getValue(PdbXmlVocabulary.ID_ATT);
		} else if (PdbXmlVocabulary.FORMULA_WEIGHT.equals(localName) && !isNil(attributes)) {
			startBuffering();
		} else if (PdbXmlVocabulary.NAME.equals(localName) && !isNil(attributes)) {
			startBuffering();
		} else if (PdbXmlVocabulary.NUMBER_OF_ATOMS_ALL.equals(localName) && !isNil(attributes)) {
			startBuffering();
		} else if (PdbXmlVocabulary.NUMBER_OF_NON_HYDROGEN_ATOMS.equals(localName) && !isNil(attributes)) {
			startBuffering();
		} else if (PdbXmlVocabulary.FORMULA.equals(localName) && !isNil(attributes)) {
			startBuffering();
		}
		super.startElement(uri, localName, name, attributes);
	}

	@Override
	public void endElement(String uri, String localName, String name) throws SAXException {
		if (PdbXmlVocabulary.CHEMICAL_COMPONENT.equals(localName)) {
			clear();
		} else if (PdbXmlVocabulary.FORMULA_WEIGHT.equals(localName) && isBuffering()) {
			createFormulaWeight(getBufferContent());
			stopBuffering();
		} else if (PdbXmlVocabulary.NAME.equals(localName) && isBuffering()) {
			createResidueType(getBufferContent());
			stopBuffering();
		} else if (PdbXmlVocabulary.NUMBER_OF_ATOMS_ALL.equals(localName) && isBuffering()) {
			createNumberOfAtoms(getBufferContent());
			stopBuffering();
		} else if (PdbXmlVocabulary.NUMBER_OF_NON_HYDROGEN_ATOMS.equals(localName) && isBuffering()) {
			createNumberOfNonHydrogenAtoms(getBufferContent());
			stopBuffering();
		} else if (PdbXmlVocabulary.FORMULA.equals(localName) && isBuffering()) {
			createFormula(getBufferContent());
			stopBuffering();
		}
		super.endElement(uri, localName, name);
	}

	private void createFormula(String formula) {
		if (!residues.containsKey(componentId)) {
			return;
		}
		for (Resource residue : residues.get(componentId)) {
			Resource formulaQuality = createResource(Bio2RdfPdbUriPattern.RESIDUE_FORMULA, residue.getURI());
			getRdfModel().add(residue, PdbOwlVocabulary.ObjectProperty.hasChemicalFormula.property(), formulaQuality);
			getRdfModel().add(formulaQuality, RDF.type, PdbOwlVocabulary.Class.ChemicalFormula.resource());
			getRdfModel().add(formulaQuality, PdbOwlVocabulary.DataProperty.hasValue.property(), formula);
		}
	}

	private void createNumberOfNonHydrogenAtoms(String numberOfAtoms) {
		if (!residues.containsKey(componentId)) {
			return;
		}
		for (Resource residue : residues.get(componentId)) {
			Resource numberOfAtomsQuality = createResource(Bio2RdfPdbUriPattern.RESIDUE_NUMBER_OF_NON_HYDROGEN_ATOMS,
					residue.getURI());
			getRdfModel().add(residue, PdbOwlVocabulary.ObjectProperty.hasNumberOfNonHydrogenAtoms.property(),
					numberOfAtomsQuality);
			getRdfModel().add(numberOfAtomsQuality, RDF.type,
					PdbOwlVocabulary.Class.NumberOfNonHydrogenAtoms.resource());
			getRdfModel().add(numberOfAtomsQuality, PdbOwlVocabulary.DataProperty.hasValue.property(),
					createDecimalLiteral(numberOfAtoms));
		}

	}

	private void createNumberOfAtoms(String numberOfAtoms) {
		if (!residues.containsKey(componentId)) {
			return;
		}
		for (Resource residue : residues.get(componentId)) {
			Resource numberOfAtomsQuality = createResource(Bio2RdfPdbUriPattern.RESIDUE_NUMBER_OF_ATOMS,
					residue.getURI());
			getRdfModel().add(residue, PdbOwlVocabulary.ObjectProperty.hasNumberOfAtoms.property(),
					numberOfAtomsQuality);
			getRdfModel().add(numberOfAtomsQuality, RDF.type, PdbOwlVocabulary.Class.NumberOfAtoms.resource());
			getRdfModel().add(numberOfAtomsQuality, PdbOwlVocabulary.DataProperty.hasValue.property(),
					createDecimalLiteral(numberOfAtoms));
		}

	}

	private void createResidueType(String typeName) {
		if (!residues.containsKey(componentId)) {
			return;
		}

		componentType = createResource(Bio2RdfPdbUriPattern.RESIDUE_TYPE, UriUtil.hash(typeName));

		for (Resource residue : residues.get(componentId)) {
			getRdfModel().add(residue, RDF.type, componentType);
			// getRdfModel().add(componentType, RDF.type, OWL.Class);
			getRdfModel().add(residue, RDFS.label, typeName);
		}
	}

	private void createFormulaWeight(String formulaWeight) {
		if (!residues.containsKey(componentId)) {
			return;
		}
		for (Resource residue : residues.get(componentId)) {
			Resource formulaWeightQuality = createResource(Bio2RdfPdbUriPattern.RESIDUE_FORMULA_WEIGH, residue.getURI());
			getRdfModel().add(residue, PdbOwlVocabulary.ObjectProperty.hasTheoreticalFormulaWeight.property(),
					formulaWeightQuality);
			getRdfModel().add(formulaWeightQuality, RDF.type,
					PdbOwlVocabulary.Class.TheoreticalFormulaWeight.resource());
			getRdfModel().add(formulaWeightQuality, PdbOwlVocabulary.DataProperty.hasValue.property(),
					createDecimalLiteral(formulaWeight));
		}
	}

}


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using Microsoft.CodeAnalysis.LanguageServices;

namespace Microsoft.CodeAnalysis.Shared.Extensions
{
    internal static class PredefinedTypeExtensions
    {
        public static SpecialType ToSpecialType(this PredefinedType predefinedType)
        {
            switch (predefinedType)
            {
                case PredefinedType.Object:
                    return SpecialType.System_Object;
                case PredefinedType.Void:
                    return SpecialType.System_Void;
                case PredefinedType.Boolean:
                    return SpecialType.System_Boolean;
                case PredefinedType.Char:
                    return SpecialType.System_Char;
                case PredefinedType.SByte:
                    return SpecialType.System_SByte;
                case PredefinedType.Byte:
                    return SpecialType.System_Byte;
                case PredefinedType.Int16:
                    return SpecialType.System_Int16;
                case PredefinedType.UInt16:
                    return SpecialType.System_UInt16;
                case PredefinedType.Int32:
                    return SpecialType.System_Int32;
                case PredefinedType.UInt32:
                    return SpecialType.System_UInt32;
                case PredefinedType.Int64:
                    return SpecialType.System_Int64;
                case PredefinedType.UInt64:
                    return SpecialType.System_UInt64;
                case PredefinedType.Decimal:
                    return SpecialType.System_Decimal;
                case PredefinedType.Single:
                    return SpecialType.System_Single;
                case PredefinedType.Double:
                    return SpecialType.System_Double;
                case PredefinedType.String:
                    return SpecialType.System_String;
                case PredefinedType.DateTime:
                    return SpecialType.System_DateTime;
                default:
                    return SpecialType.None;
            }
        }
    }
}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/undo_delete_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/deleted"
            android:textColor="@color/md_white_1000"
            android:textSize="@dimen/abc_text_size_medium_material"
            android:paddingTop="20dp"
            android:paddingLeft="25dp"
            android:layout_alignParentLeft="true"/>

        <TextView
            android:id="@+id/undo_delete_undo_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/undo_caps"
            android:textColor="@color/md_amber_500"
            android:textSize="@dimen/abc_text_size_medium_material"
            android:paddingTop="20dp"
            android:paddingRight="25dp"
            android:layout_alignParentRight="true"/>
    </RelativeLayout>
</LinearLayout>


text:
import { NullEngine } from "core/Engines";
import { FresnelParameters, StandardMaterial } from "core/Materials";
import { Color3 } from "core/Maths";
import { MeshBuilder } from "core/Meshes";
import { Scene } from "core/scene";

/**
 * Test Suite for FresnelParameters.
 */
describe("Babylon Material FresnelParameters", () => {
    describe("#FresnelParameters", () => {
        it("empty constructor has default values", () => {
            const subject = new FresnelParameters();
            expect(subject.bias).toBe(0);
            expect(subject.power).toBe(1);
            expect(subject.isEnabled).toBeTruthy();
            expect(subject.leftColor.equals(Color3.White())).toBeTruthy();
            expect(subject.rightColor.equals(Color3.Black())).toBeTruthy();
        });

        it("serialized empty constructor is serialized correctly", () => {
            const subject = new FresnelParameters().serialize();
            expect(subject).toStrictEqual({
                isEnabled: true,
                leftColor: [1, 1, 1],
                rightColor: [0, 0, 0],
                bias: 0,
                power: 1,
            });
        });

        it("new FresnelParameters({...}) with options specified", () => {
            const subject = new FresnelParameters({
                bias: 1,
                power: 0,
                isEnabled: false,
                leftColor: Color3.Black(),
                rightColor: Color3.White(),
            });
            expect(subject.bias).toBe(1);
            expect(subject.power).toBe(0);
            expect(subject.isEnabled).toBeFalsy();
            expect(subject.leftColor.equals(Color3.Black())).toBeTruthy();
            expect(subject.rightColor.equals(Color3.White())).toBeTruthy();
        });

        it("FresnelParameters.Parse({...}) with equality check", () => {
            const subject = FresnelParameters.Parse({
                isEnabled: true,
                leftColor: [1, 1, 1],
                rightColor: [0, 0, 0],
                bias: 0,
                power: 1,
            });

            expect(new FresnelParameters().equals(subject)).toBeTruthy();
        });

        it("disabling FresnelParameters should mark materials as dirty (not ready)", () => {
            const engine = new NullEngine({
                renderHeight: 256,
                renderWidth: 256,
                textureSize: 256,
                deterministicLockstep: false,
                lockstepMaxSteps: 1,
            });

            const scene = new Scene(engine);
            const mesh = MeshBuilder.CreateBox("mesh", { size: 1 }, scene);
            const material = new StandardMaterial("material", scene);
            mesh.material = material;

            const subject = new FresnelParameters();
            material.refractionFresnelParameters = subject;

            expect(scene._cachedMaterial).not.toBeNull();

            // should mark materials as dirty and clear scene cache
            subject.isEnabled = false;
            expect(scene._cachedMaterial).toBeNull();
        });
    });
});


text:
BSLS_IDENT_RCSID(bslmt_readerwriterwmuteximpl_cpp,"$Id$ $CSID$")

///Implementation Note
///===================
// The core of the implementation is a direct interpretation of the
// requirements of a reader-writer lock: the writer has exclusive access to
// this lock and the readers may share access to this lock only with other
// readers.  The implementation -- ignoring an optimization -- requires all
// threads to first acquire a mutex.
//
// For writer threads, acquiring the mutex prevents other threads from
// obtaining read locks and ensures only this thread can proceed to obtaining a
// write lock.  Now, this thread waits for the outstanding read locks to be
// returned.  Then, this thread is granted the write lock.  To efficiently wait
// for the outstanding read locks to be returned, a count of outstanding read
// locks is maintained and a semaphore is used to wait when necessary.
//
// For reader threads, acquiring the mutex ensures there is no outstanding
// write lock.  Now, this thread updates the reader count.  Then, this thread
// releases the mutex.  The presence of a non-zero reader count prevents a
// write lock from being obtained while this read lock is outstanding.  Note
// that another reader thread may obtain a read lock at this point, assuming no
// writer threads have intervened.
//
// Releasing a write lock is equivalant, at the moment, to unlocking the mutex.
// Releasing a read lock is more complicated.  The count of readers must be
// decremented and this must be done with appropriate memory barriers to allow
// the write lock procedure to work correctly.  Furthermore, the last returned
// read lock must also post to the semaphore if, and only if, there is a writer
// that is, or will be, blocked on the semphore.  This implies the need for an
// indicator that there is a writer and the need to access this indicator and
// update the outstanding read lock count atomically.
//
// At this point, the implementation requires a mutex, a semaphore, and atomic
// state that indicates the presence of a writer and the count of the number of
// outstanding read locks.
//
// Note that, if there are no writers, obtaining a read lock currently requires
// locking and unlocking a mutex and this implies substantial overhead and
// possible poor performance if a reader thread is swapped out while holding
// the mutex.  To optimize this procedure, while preventing readers from being
// able to starve writers, a count of the pending writers (those blocked on the
// mutex lock) is maintained and, when this count of pending writers and the
// original writer indicator are zero, a reader thread will first attempt to
// update the atomic state to indicate an additional outstanding read lock.  If
// successful, the lock has been obtained.  Otherwise, the original algorithm
// of obtaining the mutex is used.

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


text:
* Ensure [node.js](https://nodejs.org) is installed on your machine. CommonGround was built using Node(6.2.0) and npm(3.8.9). Previous versions may or may not work.
* Run `npm install` in the server directory

*Note*: The server is designed to work with an sqlite database (see schema description bellow), though it's very simple to adopt it to work with other SQL databases.
The server expects the db at `../data/cg.sqlite` or `$CG_DIR/cg.sqlite`.

#### Web-app
*Note:* add *./node_modules/.bin* to your PATH, e.g. `PATH=./node_modules/.bin:$PATH`, in order to use the local jspm tool (ver +17.2).

```shell
cd app
npm install
jspm install
```

## Running CommonGround
1. Start the server
```
cd server
CG_DIR=<path-to-the-db-directory> node server.js   // or add CG_DIR to your environment.
```
2. Open a browser and point it to localhost:4000

## User Interactions
tdb

### Database schema

tbd


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bryologist 74(2): 191 (1971)

#### Original name
Pertusaria gyalectoides Vezda

### Remarks
null


text:
package org.jongo;

import com.mongodb.CommandResult;
import com.mongodb.DB;
import com.mongodb.DBObject;
import org.jongo.marshall.Unmarshaller;
import org.jongo.query.Query;
import org.jongo.query.QueryFactory;

import java.util.ArrayList;
import java.util.List;

import static org.jongo.ResultHandlerFactory.newResultHandler;

public class Command {

    private final DB db;
    private final Unmarshaller unmarshaller;
    private Query query;
    private boolean throwOnError;

    public Command(DB db, Unmarshaller unmarshaller, QueryFactory queryFactory, String query, Object... parameters) {
        this.db = db;
        this.unmarshaller = unmarshaller;
        this.query = queryFactory.createQuery(query, parameters);
    }

    public Command throwOnError() {
        throwOnError = true;
        return this;
    }

    public ResultCommand field(String fieldName) {
        return new ResultCommand(fieldName);
    }

    public <T> T as(final Class<T> clazz) {
        return map(newResultHandler(clazz, unmarshaller));
    }

    public <T> T map(ResultHandler<T> resultHandler) {
        CommandResult commandResult = executeCommand();
        return resultHandler.map(commandResult);
    }

    private CommandResult executeCommand() {
        CommandResult commandResult = db.command(query.toDBObject());
        if (throwOnError) {
            commandResult.throwOnError();
        }
        return commandResult;
    }

    public class ResultCommand {

        private String fieldName;

        public ResultCommand(String fieldName) {
            this.fieldName = fieldName;
        }

        public <T> List<T> as(final Class<T> clazz) {
            return map(newResultHandler(clazz, unmarshaller));
        }

        public <T> List<T> map(ResultHandler<T> resultHandler) {
            CommandResult commandResult = executeCommand();
            List<DBObject> results = (List<DBObject>) commandResult.get(fieldName);
            if (results == null) {
                return new ArrayList<T>();
            }
            List<T> mappedResult = new ArrayList<T>(results.size());
            for (DBObject dbObject : results) {
                mappedResult.add(resultHandler.map(dbObject));
            }
            return mappedResult;
        }
    }
}


text:
/*
 * This file is part of COMPASS. It is subject to the license terms in
 * the LICENSE file found in the top-level directory of this distribution.
 * (Also available at http://www.apache.org/licenses/LICENSE-2.0.txt)
 * You may not use this file except in compliance with the License.
 */
package de.dfki.asr.compass.rest.mixins.model.math;

import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.vecmath.Matrix3f;

@SuppressWarnings("PMD.AbstractNaming")
public abstract class Quat4fMixin {
		@JsonIgnore
		public abstract de.dfki.asr.compass.math.Quat4f setFromMatrix(Matrix3f m);
}


text:
FROM alpine:3.3
CMD /bin/sh -c "while true; do echo hello world; sleep 1; done"


text:
origpwd=$PWD
source ~/Utils/vs2019.sh
cd $origpwd

set -e

if [[ $PFX_PATH == "" || $PFX_PASSWORD == "" ]]
then
  echo "Please set PFX_PATH and PFX_PASSWORD"
  exit 1
fi

# Build executables
dotnet build -c Release -v quiet VDrumExplorer.Gui
# Sign executable in-place
signtool sign -a -fd SHA256 -f $PFX_PATH -p $PFX_PASSWORD -t http://timestamp.comodoca.com/authenticode VDrumExplorer.Gui/bin/Release/net472/VDrumExplorer.Gui.exe

version=$(grep \<Version\> VDrumExplorer.Gui/VDrumExplorer.Gui.csproj | sed s/\<[^\>]*\>//g | sed 's/ //g')

rm -rf tmp
mkdir tmp
cd tmp

# .NET Core build has been removed due to NAudio requirements

# Desktop
release_dir=VDrumExplorer-$version
mkdir $release_dir
cp ../VDrumExplorer.Gui/bin/Release/net472/* $release_dir
cp ../td17.vdrum $release_dir
cp ../LICENSE* $release_dir
cp ../README.md $release_dir
zip -rq VDrumExplorer-$version.zip $release_dir

# Setup
msbuild.exe -property:Configuration=Release -verbosity:quiet ../VDrumExplorer.Setup
cp ../VDrumExplorer.Setup/bin/Release/en-us/VDrumExplorer-Setup.msi VDrumExplorer-Setup-$version.msi
# Sign the installer as well
signtool sign -a -fd SHA256 -f $PFX_PATH -p $PFX_PASSWORD -t http://timestamp.comodoca.com/authenticode VDrumExplorer-Setup-$version.msi

cd ..


text:
namespace philameter.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class initial : DbMigration
    {
        public override void Up()
        {
            CreateTable(
                "dbo.Stats",
                c => new
                    {
                        Id = c.Int(nullable: false, identity: true),
                        Name = c.String(),
                        Details = c.String(),
                        Source = c.String(),
                        Stat = c.Int(nullable: false),
                    })
                .PrimaryKey(t => t.Id);

            CreateTable(
                "dbo.StatTags",
                c => new
                    {
                        Id = c.Int(nullable: false, identity: true),
                        StatId = c.Int(nullable: false),
                        TagId = c.Int(nullable: false),
                    })
                .PrimaryKey(t => t.Id);

            CreateTable(
                "dbo.Tags",
                c => new
                    {
                        Id = c.Int(nullable: false, identity: true),
                        Name = c.String(),
                    })
                .PrimaryKey(t => t.Id);

        }

        public override void Down()
        {
            DropTable("dbo.Tags");
            DropTable("dbo.StatTags");
            DropTable("dbo.Stats");
        }
    }
}


text:
using System.Collections.Generic;
using Bjd;
using Bjd.ctrl;
using Bjd.option;

namespace DnsServer {
    public class OptionDnsDomain : OneOption{

        public override char Mnemonic { get { return 'A'; } }

        public OptionDnsDomain(Kernel kernel, string path, string nameTag)
            : base(kernel.IsJp(), path, nameTag){

            var pageList = new List<OnePage>();
            var key = "Basic";
            pageList.Add(Page1(key,Lang.Value(key),kernel));
            Add(new OneVal("tab", null, Crlf.Nextline, new CtrlTabPage("tabPage", pageList)));

            Read(kernel.IniDb); //�@���W�X�g������̓ǂݍ���
        }

        private OnePage Page1(string name, string title,Kernel kernel) {
            var onePage = new OnePage(name, title);
            var list = new ListVal();
            var key = "name";
            list.Add(new OneVal(key, "", Crlf.Nextline, new CtrlTextBox(Lang.Value(key), 80)));
            key = "authority";
            list.Add(new OneVal(key, true, Crlf.Nextline, new CtrlCheckBox(Lang.Value(key))));
            onePage.Add(new OneVal("domainList", null, Crlf.Nextline, new CtrlDat("", list, 400, Lang.LangKind)));
            return onePage;
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Demo on Nan's Website</title>
    <link>https://strideradu.github.io/tags/demo/index.xml</link>
    <description>Recent content in Demo on Nan's Website</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en-us</language>
    <copyright>&copy; 2017 Nan Du</copyright>
    <atom:link href="/tags/demo/index.xml" rel="self" type="application/rss+xml" />

    <item>
      <title>External Project</title>
      <link>https://strideradu.github.io/example-external-project/</link>
      <pubDate>Wed, 27 Apr 2016 00:00:00 +0000</pubDate>

      <guid>https://strideradu.github.io/example-external-project/</guid>
      <description></description>
    </item>

  </channel>
</rss>