问:
Free-JQGrid Multiselect toolbar to refreshing when reloading data from server
I have the below code and when I make a call back to the server to reload the grid, my drop down filters are not refreshing based on the column data.

Upon page load, the grid loads fine and the drop down filters are loaded with the appropriate data, excluding quotes that are in a canceled or expired status.  When the user clicks on the Canceled checkbox, the grid reloads and the data now includes the canceled status.  The issue is the status name drop down toolbar filter now does not include the new status of canceled (or expired if selected).  From what I can find online, it looks like the drop down filters should reload based on the new data. What am I missing?

```<code>$(document).ready(function () {
    $("#ckRecentViewed").on('change', function (e) {
        loadGrid();
    });

    $("#ckCanceled").on('change', function (e) {
        loadGrid();
    });

    $("#ckExpired").on('change', function (e) {
        loadGrid();
    });

    $("input:radio:checked").data("chk", true);
    $("input:radio").click(function () {
        $("input[name='" + $(this).attr("name") + "']:radio").not(this).removeData("chk");
        $(this).data("chk", !$(this).data("chk"));
        $(this).prop("checked", $(this).data("chk"));
        $(this).button('refresh'); // in case you change the radio elements dynamically
        loadGrid();
    });

    $("#chkInMyStep").on('change', function (e) {
        loadGrid();
    });

    $('#dvWrapperFilter').on('click', function () {
        $("#dvFilters").slideToggle(function () {
            if ($('#imgHdrPlusMinus').attr('src').indexOf("plus") > 0) {
                $('#imgHdrPlusMinus').attr('src', $('#imgHdrPlusMinus').attr('src').replace("plus", "minus"));
            } else {
                $('#imgHdrPlusMinus').attr('src', $('#imgHdrPlusMinus').attr('src').replace("minus", "plus"));
            }
        });
    });
});

var statusIds = '0,1,3,4,5,6';

var cols = [
    { index: 'CTSID', name: 'CTSID', align: 'left', sortable: true, search: true, width: '20%' },
    { index: 'CustomerName', name: 'CustomerName', align: 'left', sortable: true, search: true, width: '60%' },
    { label: 'Terr', index: 'Territory', name: 'Territory', align: 'center', sortable: true, search: true, width: '20%' },
    { label: 'Zone Manager', index: 'CZMName', name: 'CZMName', align: 'left', sortable: true, search: true, width: '50%' },
    { label: 'Status', index: 'StatusName', name: 'StatusName', align: 'left', sortable: true, width: '30%' },
    { label: 'Version', index: 'VersionNumber', name: 'VersionNumber', align: 'center', sortable: true, search: true, width: '18%' },
    { label: 'Workflow Step', index: 'WorkflowName', name: 'WorkflowName', align: 'left', sortable: true, width: '30%' },
    {
        label: 'Expiration Date', index: 'EffectiveEndDate', name: 'EffectiveEndDate', sortable: true, width: '40%', sorttype: "date", formatter: "date", formatoptions: { newformat: "m/d/y" }, align: 'center',
        searchoptions: {
            sopt: ["eq"], // or any other search operation
            dataInit: function (element) {
                var self = this; // save the reference to the grid
                $(element).datepicker({
                    dateFormat: 'mm/dd/yy',
                    changeYear: true,
                    changeMonth: true,
                    showButtonPanel: true,
                    onSelect: function () {
                        setTimeout(function () {
                            self.triggerToolbar();
                        }, 0);
                    }
                });
            }
        }
    },
    {
        label: '', index: 'action', name: 'action', sortable: false, align: 'center', search: false, width: '20%', formatter: addLink, cellattr: function () {
            return "title=\"Click to view quote details\"";
        }
    }
];

var actionUrl = 'Dashboard/GetUserWorkflowDashboard';

var getUniqueNames = function (columnName, mydata) {
    var texts = $.map(mydata, function (item) {
        return item[columnName];
    }),
        uniqueTexts = [], textsLength = texts.length, text, textsMap = {}, i;

    for (i = 0; i < textsLength; i++) {
        text = texts[i];
        if (text !== undefined && textsMap[text] === undefined) {
            // to test whether the texts is unique we place it in the map.
            textsMap[text] = true;
            uniqueTexts.push(text);
        }
    }
    return uniqueTexts;
},
    buildSearchSelect = function (uniqueNames) {
        var values = "";
        $.each(uniqueNames, function () {
            values += this + ":" + this + ";";
        });
        return values.slice(0, -1);
    },
    initMultiselect = function (searchOptions) {
        var $elem = $(searchOptions.elem),
            options = {
                selectedList: 2,
                height: "auto",
                checkAllText: "all",
                uncheckAllText: "no",
                noneSelectedText: "Any",
                open: function () {
                    var $menu = $(".ui-multiselect-menu:visible");
                    $menu.addClass("ui-jqdialog").width("auto");
                    $menu.find(">ul").css("maxHeight", "200px");
                }
            };
        if (searchOptions.mode === "filter") {
            options.minWidth = "auto";
        }
        $elem.multiselect(options);
        $elem.siblings("button.ui-multiselect").css({
            width: "100%",
            margin: "1px 0",
            paddingTop: ".3em",
            paddingBottom: "0"
        });
    },
    setSearchSelect = function (columnName, data) {
        var values = buildSearchSelect(getUniqueNames.call(this, columnName, data));
        $(this).jqGrid("setColProp", columnName, {
            stype: "select",
            searchoptions: {
                value: values,
                sopt: ["in"],
                attr: {
                    multiple: "multiple",
                    size: 4
                },
                selectFilled: initMultiselect
            }
        });
    },
    myDefaultSearch = "cn",

beforeProcessingHandler1 = function (data) {
    var $this = $(this), p = $this.jqGrid("getGridParam");
    // !!! it will be called only after loading from the server
    // datatype is always "json" here
    setSearchSelect.call(this, "WorkflowName", data);
    setSearchSelect.call(this, "StatusName", data);
    setSearchSelect.call(this, "CZMName", data);

    if (this.ftoolbar === true) {
        //if the filter toolbar is not already created
        $("#gs_" + this.id + "WorkflowName").multiselect("destroy");
        $this.jqGrid('destroyFilterToolbar');

        $("#gs_" + this.id + "StatusName").multiselect("destroy");
        $this.jqGrid('destroyFilterToolbar');

        $("#gs_" + this.id + "CZMName").multiselect("destroy");
        $this.jqGrid('destroyFilterToolbar');
    }

    if (p.postData.filters) {
        p.search = true;
    }

    $this.jqGrid("filterToolbar", {
        stringResult: true,
        defaultSearch: myDefaultSearch,
        beforeClear: function () {
            $(this.grid.hDiv)
                .find(".ui-search-toolbar button.ui-multiselect")
                .each(function () {
                    $(this).prev("select[multiple]").multiselect("refresh");
                });
            $(this.grid.hDiv)
                .find(".ui-search-toolbar button.ui-multiselect")
                .each(function () {
                    // synchronize jQuery UI Multiselect with <select>
                    $(this).prev("select[multiple]").multiselect("refresh");
                }
                ).css({
                    width: "98%",
                    marginTop: "1px",
                    marginBottom: "1px",
                    paddingTop: "3px"
                });
        }
    });
};

$(function () {
    //Initialize jqgrid
    $("#gridWorkflowDashboard").jqGrid({
        datatype: 'json',
        url: actionUrl,
        mType: 'GET',
        colModel: cols,
        rowList: [25, 50, 100],
        pager: "#dvDashboardPager",
        forceClientSorting: true,
        loadonce: true,
        beforeProcessing: beforeProcessingHandler1,
        sortname: "EffectiveEndDate",
        sorttype: "date",
        sortorder: "desc",
        rownumbers: false,
        rowNum: 25,
        gridview: true,
        hidegrid: false,
        height: "100%",
        autowidth: true,
        search: true,
        altclass: "GridRows",
        recreateFilter: true,
        hoverrows: true,
        viewsortcols: [true, 'vertical', true],
        ignoreCase: true,
        viewrecords: true
    }).jqGrid("navGrid", { add: false, edit: false, del: false, search: false, refresh: true });
});

function loadGrid() {
    page = $("#gridWorkflowDashboard").getGridParam('page');
    var ids = statusIds;

    var pExperationDate = $('input:radio[name="rdExpiration"]:checked').val();
    var pToDate = $("#datepickerTo").val();
    var pFromDate = $("#datepickerFrom").val();
    var pRecentView = $("#ckRecentViewed")[0].checked;
    var pInMyStep = $("#chkInMyStep")[0].checked;
    var pCanceled = $("#ckCanceled")[0].checked;
    var pExpired = $("#ckExpired")[0].checked;

    if (pCanceled) {
        ids += ',-1';
    }
    else {
        ids = statusIds;
    }

    if (pExpired) {
        ids += ',2';
    }
    else {
        ids = statusIds;

        if (pCanceled) {
            ids += ',-1';
        }
    }

    var data = { ExperationDays: pExperationDate, toDate: pToDate, fromDate: pFromDate, recentView: pRecentView, InMyStep: pInMyStep, StatusIds: ids };

    $.ajax(actionUrl, {
        contentType: 'application/json',
        type: 'GET',
        datatype: 'json',
        loadonce: true,
        data: data,
        success: function (result) {
            $("#gridWorkflowDashboard").jqGrid('clearGridData');
            //$("#gridWorkflowDashboard").jqGrid('destroyFilterToolbar');
            $("#gridWorkflowDashboard").jqGrid('setGridParam',
                {
                    datatype: 'local',
                    data: result
                }).trigger("reloadGrid", [{ page: page }]);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert(jqXHR.responseText);
        }
    });
}

function addLink(cellvalue, options, rowObject) {
    return "<input type='button' class='btn btn-info btn-xs grid-btn' value='View' onclick='ViewQuote(\"" + rowObject.CTSID + "\")'\>";
}

function ViewQuote(value) {
    window.location.href = '/CPQ/Quote/EditQuote/' + value;
}

$(function () {
    $("#datepickerFrom").datepicker({
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        dateFormat: 'mm/dd/yy',
        minDate: "-8Y",
        maxDate: "0Y",
        onClose: function (dateText, inst) {
            loadGrid();
        }
    });

    $("#datepickerTo").datepicker({
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        dateFormat: 'mm/dd/yy',
        minDate: "-8Y",
        maxDate: "0Y",
        onClose: function (dateText, inst) {
            loadGrid();
        }
    });
});
</code>```

答: I ended up switching over to Guriddo jqGrid since i found more documentation and helpful examples and was able to solve my issue.  Thanks for your help Tony.</p>

Body:
I have the below code and when I make a call back to the server to reload the grid, my drop down filters are not refreshing based on the column data.

Upon page load, the grid loads fine and the drop down filters are loaded with the appropriate data, excluding quotes that are in a canceled or expired status.  When the user clicks on the Canceled checkbox, the grid reloads and the data now includes the canceled status.  The issue is the status name drop down toolbar filter now does not include the new status of canceled (or expired if selected).  From what I can find online, it looks like the drop down filters should reload based on the new data. What am I missing?

$(document).ready(function () {
    $("#ckRecentViewed").on('change', function (e) {
        loadGrid();
    });

    $("#ckCanceled").on('change', function (e) {
        loadGrid();
    });

    $("#ckExpired").on('change', function (e) {
        loadGrid();
    });

    $("input:radio:checked").data("chk", true);
    $("input:radio").click(function () {
        $("input[name='" + $(this).attr("name") + "']:radio").not(this).removeData("chk");
        $(this).data("chk", !$(this).data("chk"));
        $(this).prop("checked", $(this).data("chk"));
        $(this).button('refresh'); // in case you change the radio elements dynamically
        loadGrid();
    });

    $("#chkInMyStep").on('change', function (e) {
        loadGrid();
    });

    $('#dvWrapperFilter').on('click', function () {
        $("#dvFilters").slideToggle(function () {
            if ($('#imgHdrPlusMinus').attr('src').indexOf("plus") > 0) {
                $('#imgHdrPlusMinus').attr('src', $('#imgHdrPlusMinus').attr('src').replace("plus", "minus"));
            } else {
                $('#imgHdrPlusMinus').attr('src', $('#imgHdrPlusMinus').attr('src').replace("minus", "plus"));
            }
        });
    });
});

var statusIds = '0,1,3,4,5,6';

var cols = [
    { index: 'CTSID', name: 'CTSID', align: 'left', sortable: true, search: true, width: '20%' },
    { index: 'CustomerName', name: 'CustomerName', align: 'left', sortable: true, search: true, width: '60%' },
    { label: 'Terr', index: 'Territory', name: 'Territory', align: 'center', sortable: true, search: true, width: '20%' },
    { label: 'Zone Manager', index: 'CZMName', name: 'CZMName', align: 'left', sortable: true, search: true, width: '50%' },
    { label: 'Status', index: 'StatusName', name: 'StatusName', align: 'left', sortable: true, width: '30%' },
    { label: 'Version', index: 'VersionNumber', name: 'VersionNumber', align: 'center', sortable: true, search: true, width: '18%' },
    { label: 'Workflow Step', index: 'WorkflowName', name: 'WorkflowName', align: 'left', sortable: true, width: '30%' },
    {
        label: 'Expiration Date', index: 'EffectiveEndDate', name: 'EffectiveEndDate', sortable: true, width: '40%', sorttype: "date", formatter: "date", formatoptions: { newformat: "m/d/y" }, align: 'center',
        searchoptions: {
            sopt: ["eq"], // or any other search operation
            dataInit: function (element) {
                var self = this; // save the reference to the grid
                $(element).datepicker({
                    dateFormat: 'mm/dd/yy',
                    changeYear: true,
                    changeMonth: true,
                    showButtonPanel: true,
                    onSelect: function () {
                        setTimeout(function () {
                            self.triggerToolbar();
                        }, 0);
                    }
                });
            }
        }
    },
    {
        label: '', index: 'action', name: 'action', sortable: false, align: 'center', search: false, width: '20%', formatter: addLink, cellattr: function () {
            return "title=\"Click to view quote details\"";
        }
    }
];

var actionUrl = 'Dashboard/GetUserWorkflowDashboard';

var getUniqueNames = function (columnName, mydata) {
    var texts = $.map(mydata, function (item) {
        return item[columnName];
    }),
        uniqueTexts = [], textsLength = texts.length, text, textsMap = {}, i;

    for (i = 0; i < textsLength; i++) {
        text = texts[i];
        if (text !== undefined && textsMap[text] === undefined) {
            // to test whether the texts is unique we place it in the map.
            textsMap[text] = true;
            uniqueTexts.push(text);
        }
    }
    return uniqueTexts;
},
    buildSearchSelect = function (uniqueNames) {
        var values = "";
        $.each(uniqueNames, function () {
            values += this + ":" + this + ";";
        });
        return values.slice(0, -1);
    },
    initMultiselect = function (searchOptions) {
        var $elem = $(searchOptions.elem),
            options = {
                selectedList: 2,
                height: "auto",
                checkAllText: "all",
                uncheckAllText: "no",
                noneSelectedText: "Any",
                open: function () {
                    var $menu = $(".ui-multiselect-menu:visible");
                    $menu.addClass("ui-jqdialog").width("auto");
                    $menu.find(">ul").css("maxHeight", "200px");
                }
            };
        if (searchOptions.mode === "filter") {
            options.minWidth = "auto";
        }
        $elem.multiselect(options);
        $elem.siblings("button.ui-multiselect").css({
            width: "100%",
            margin: "1px 0",
            paddingTop: ".3em",
            paddingBottom: "0"
        });
    },
    setSearchSelect = function (columnName, data) {
        var values = buildSearchSelect(getUniqueNames.call(this, columnName, data));
        $(this).jqGrid("setColProp", columnName, {
            stype: "select",
            searchoptions: {
                value: values,
                sopt: ["in"],
                attr: {
                    multiple: "multiple",
                    size: 4
                },
                selectFilled: initMultiselect
            }
        });
    },
    myDefaultSearch = "cn",

beforeProcessingHandler1 = function (data) {
    var $this = $(this), p = $this.jqGrid("getGridParam");
    // !!! it will be called only after loading from the server
    // datatype is always "json" here
    setSearchSelect.call(this, "WorkflowName", data);
    setSearchSelect.call(this, "StatusName", data);
    setSearchSelect.call(this, "CZMName", data);

    if (this.ftoolbar === true) {
        //if the filter toolbar is not already created
        $("#gs_" + this.id + "WorkflowName").multiselect("destroy");
        $this.jqGrid('destroyFilterToolbar');

        $("#gs_" + this.id + "StatusName").multiselect("destroy");
        $this.jqGrid('destroyFilterToolbar');

        $("#gs_" + this.id + "CZMName").multiselect("destroy");
        $this.jqGrid('destroyFilterToolbar');
    }

    if (p.postData.filters) {
        p.search = true;
    }

    $this.jqGrid("filterToolbar", {
        stringResult: true,
        defaultSearch: myDefaultSearch,
        beforeClear: function () {
            $(this.grid.hDiv)
                .find(".ui-search-toolbar button.ui-multiselect")
                .each(function () {
                    $(this).prev("select[multiple]").multiselect("refresh");
                });
            $(this.grid.hDiv)
                .find(".ui-search-toolbar button.ui-multiselect")
                .each(function () {
                    // synchronize jQuery UI Multiselect with <select>
                    $(this).prev("select[multiple]").multiselect("refresh");
                }
                ).css({
                    width: "98%",
                    marginTop: "1px",
                    marginBottom: "1px",
                    paddingTop: "3px"
                });
        }
    });
};

$(function () {
    //Initialize jqgrid
    $("#gridWorkflowDashboard").jqGrid({
        datatype: 'json',
        url: actionUrl,
        mType: 'GET',
        colModel: cols,
        rowList: [25, 50, 100],
        pager: "#dvDashboardPager",
        forceClientSorting: true,
        loadonce: true,
        beforeProcessing: beforeProcessingHandler1,
        sortname: "EffectiveEndDate",
        sorttype: "date",
        sortorder: "desc",
        rownumbers: false,
        rowNum: 25,
        gridview: true,
        hidegrid: false,
        height: "100%",
        autowidth: true,
        search: true,
        altclass: "GridRows",
        recreateFilter: true,
        hoverrows: true,
        viewsortcols: [true, 'vertical', true],
        ignoreCase: true,
        viewrecords: true
    }).jqGrid("navGrid", { add: false, edit: false, del: false, search: false, refresh: true });
});

function loadGrid() {
    page = $("#gridWorkflowDashboard").getGridParam('page');
    var ids = statusIds;

    var pExperationDate = $('input:radio[name="rdExpiration"]:checked').val();
    var pToDate = $("#datepickerTo").val();
    var pFromDate = $("#datepickerFrom").val();
    var pRecentView = $("#ckRecentViewed")[0].checked;
    var pInMyStep = $("#chkInMyStep")[0].checked;
    var pCanceled = $("#ckCanceled")[0].checked;
    var pExpired = $("#ckExpired")[0].checked;

    if (pCanceled) {
        ids += ',-1';
    }
    else {
        ids = statusIds;
    }

    if (pExpired) {
        ids += ',2';
    }
    else {
        ids = statusIds;

        if (pCanceled) {
            ids += ',-1';
        }
    }

    var data = { ExperationDays: pExperationDate, toDate: pToDate, fromDate: pFromDate, recentView: pRecentView, InMyStep: pInMyStep, StatusIds: ids };

    $.ajax(actionUrl, {
        contentType: 'application/json',
        type: 'GET',
        datatype: 'json',
        loadonce: true,
        data: data,
        success: function (result) {
            $("#gridWorkflowDashboard").jqGrid('clearGridData');
            //$("#gridWorkflowDashboard").jqGrid('destroyFilterToolbar');
            $("#gridWorkflowDashboard").jqGrid('setGridParam',
                {
                    datatype: 'local',
                    data: result
                }).trigger("reloadGrid", [{ page: page }]);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert(jqXHR.responseText);
        }
    });
}

function addLink(cellvalue, options, rowObject) {
    return "<input type='button' class='btn btn-info btn-xs grid-btn' value='View' onclick='ViewQuote(\"" + rowObject.CTSID + "\")'\>";
}

function ViewQuote(value) {
    window.location.href = '/CPQ/Quote/EditQuote/' + value;
}

$(function () {
    $("#datepickerFrom").datepicker({
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        dateFormat: 'mm/dd/yy',
        minDate: "-8Y",
        maxDate: "0Y",
        onClose: function (dateText, inst) {
            loadGrid();
        }
    });

    $("#datepickerTo").datepicker({
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        dateFormat: 'mm/dd/yy',
        minDate: "-8Y",
        maxDate: "0Y",
        onClose: function (dateText, inst) {
            loadGrid();
        }
    });
});


来源: stackexchange

答:
So you set up stopOnException=true and asked why your route stopped when exception wasn't catched =) ? As workaround forget about throwing exception and validate your body and if it has inappropriate data just set empty body and then sum them in your AggregationStrategy like in pseudo-route below. I haven't used the xml description for a very long time so i hope your will understand this example with Java DSL.

```<code>public class ExampleRoute extends RouteBuilder {

AggregationStrategy aggregationStrategy = new AggregationStrategy() {
    @Override
    public Exchange aggregate(final Exchange oldExchange, final Exchange newExchange) {
        log.debug("Aggregation Strategy :: start");
        if (oldExchange != null) {
            newExchange.getIn().setBody(newExchange.getIn().getBody(String.class) + oldExchange.getIn().getBody(String.class));
        }
        log.debug("Aggregation Strategy :: finish");
        return newExchange;
    }
};

@Override
public void configure() throws Exception {
    from("{{fileEntranceEndpoint}}")
            .convertBodyTo(String.class)
            .split(tokenize("\n"), aggregationStrategy).streaming().stopOnException()
                .choice()
                .when(body().regex(",+\\$"))
                    .setBody(constant(""))
                .otherwise()
                    .process("toCsvFormat")
    ;
}
</code>```

I recommend you use Java DSL. As you can see, many things are easy to use with it.

ContentLicense: CC BY-SA 4.0

Title: can the camel splitter skip on messages rows of some value like empty or null?

Body:
I have camel route on ingress of files recieved, sometimes these files contain multiple can be thousands of empty rows or records. these occur at the end of the files.

help or advice on how to handle this situation.

2/3/20 0:25,12.0837099,22.07255971,51.15338002,52.76662495,52.34712651,51.12155216,45.7655507,49.96555147,54.47205637,50.66135512,54.43864717,54.31627797,112.11765,1305.89126,1318.734411,52.31780487,44.27374363,48.72548294,43.01383257,23.85434055,41.98898447,47.50916052,31.13055873,112.2747269,0.773642045,1.081464888,2.740194779,1.938788885,1.421660186,0.617588546,21.28219363,25.03362771,26.76627344,40.21132809,29.72854555,33.45911109
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

The route goes to a splitter.

    <route autoStartup="true" id="core.predix.accept.file.type.route">
        <from id="_from3" uri="{{fileEntranceEndpoint}}"/>
        <convertBodyTo id="_convertBodyTo1" type="java.lang.String"/>
        <split id="_split1" strategyRef="csvAggregationStrategy" streaming="true" stopOnException="true">
            <tokenize token="\n"/>
            <process id="_process3" ref="toCsvFormat"/>

        </split>
        <log id="_log1" loggingLevel="INFO" message="CSV body: ${body}"/>
        <choice id="_choice1">
            <when id="_when1">
                <simple>${header.CamelFileName} regex '^.*\.(csv|CSV|txt|gpg)$'</simple>
                <log id="_log2" message="${file:name} accepted for processing..."/>
                <choice id="_choice2">
                    <when id="_when2">
                        <simple>${header.CamelFileName} regex '^.*\.(CSV|txt|gpg)$'</simple>
                        <setHeader headerName="CamelFileName" id="_setHeader1">
                            <simple>${file:name.noext.single}.csv</simple>
                        </setHeader>
                        <log id="_log3" message="${file:name} changed file name."/>
                    </when>
                </choice>
                <split id="_split2" streaming="true">
                    <tokenize prop:group="noOfLines" token="\n"/>
                    <log id="_log4" message="Split Group Body: ${body}"/>
                    <to id="_to1" uri="bean:extractHeader"/>
                    <to id="acceptedFileType" ref="predixConsumer"/>
                </split>
                <to id="_to2" uri="bean:extractHeader?method=cleanHeader"/>
            </when>
            <otherwise id="_otherwise1">
                <log id="_log5" loggingLevel="INFO" message="${file:name} is an unknown file type, sending to unhandled repo."/>
                <to id="_to3" uri="{{unhandledArchive}}"/>
            </otherwise>
        </choice>
    </route>

The simple aggregator

public class CsvAggregationStrategy implements AggregationStrategy {

private Logger log = LoggerFactory.getLogger(CsvAggregationStrategy.class.getName());

@Override
public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {

    //Theory
    //-------------------------------------------------------------------------------------
    // Arrived    | oldExchange  |  newExchange | Description
    //-------------------------------------------------------------------------------------
    // A         | NULL         |  A            | first message arrives for the first group
    // B         | A            |  B            | second message arrives for the first group
    // F         | NULL         |  F            | first message arrives for the second group
    // C         | AB           |  C            | third message arrives for the first group
    //---------------------------------------------------------------------------------------
    log.debug("Aggregation Strategy :: start");

    if ( newExchange.getException() != null ) {
      if ( oldExchange == null ) {
        return newExchange;
      } else {
        oldExchange.setException(newExchange.getException());
        return oldExchange;
        }
    }

    if ( oldExchange == null ) {  //This will set the 1st record with the Header
        return newExchange;
    }

String newBody = newExchange.getIn().getBody(String.class);
String oldBody = oldExchange.getIn().getBody(String.class);
String body = oldBody + newBody;
oldExchange.getIn().setBody( body );

log.debug("Aggregation Strategy :: finish");
return oldExchange;

} //Exchange process
} //class AggregationStrategy

I thought I would handle the empty rows in the class toCsvFormat

The class ToCsvFormat simply changes the inbound csv delimiter to a comma.

public class ToCsvFormat implements Processor {

private static final Logger LOG = LoggerFactory.getLogger(ToCsvFormat.class);

@Override
public void process(Exchange exchange) throws Exception {

    String body = exchange.getIn().getBody(String.class);

    body = body.replaceAll("\\t|;",",");

    String bodyCheck = body.replaceAll(",","").trim();
    LOG.info("BODY CHECK: " + bodyCheck);
    if ( bodyCheck.isEmpty() || bodyCheck == null ) {

        throw new IllegalArgumentException("Data record is Empty or NULL. Invalid Data!");

    } else {

        StringBuilder sb = new StringBuilder(body.trim());

        LOG.debug("CSV Format Body In: " + sb.toString());
        LOG.debug("sb length: " + sb.length());

        if ( sb.toString().endsWith(",") ) {

            sb.deleteCharAt(sb.lastIndexOf(",", sb.length()));
        }

        LOG.info("CSV Format Body Out: " + sb.toString());
        sb.append(System.lineSeparator());
        exchange.getIn().setBody(sb.toString());
    }

}

}

*** the problem I'm having is I need the splitter to finish processing until it hits all the empty rows, or skip over or stop the splitter on empty records. but I need what was previously split or processed.  Throwing and capture of exception stops the splitter I get nothing.  I'm using the splitter stoponexception but like it says, it stops on the exception.

thank you

Body:
So you set up stopOnException=true and asked why your route stopped when exception wasn't catched =) ? As workaround forget about throwing exception and validate your body and if it has inappropriate data just set empty body and then sum them in your AggregationStrategy like in pseudo-route below. I haven't used the xml description for a very long time so i hope your will understand this example with Java DSL.

public class ExampleRoute extends RouteBuilder {

AggregationStrategy aggregationStrategy = new AggregationStrategy() {
    @Override
    public Exchange aggregate(final Exchange oldExchange, final Exchange newExchange) {
        log.debug("Aggregation Strategy :: start");
        if (oldExchange != null) {
            newExchange.getIn().setBody(newExchange.getIn().getBody(String.class) + oldExchange.getIn().getBody(String.class));
        }
        log.debug("Aggregation Strategy :: finish");
        return newExchange;
    }
};

@Override
public void configure() throws Exception {
    from("{{fileEntranceEndpoint}}")
            .convertBodyTo(String.class)
            .split(tokenize("\n"), aggregationStrategy).streaming().stopOnException()
                .choice()
                .when(body().regex(",+\\$"))
                    .setBody(constant(""))
                .otherwise()
                    .process("toCsvFormat")
    ;
}

I recommend you use Java DSL. As you can see, many things are easy to use with it.


问:
Alignment in textflow
I'm placing a textflow with UTF-16 text in PHP (PDF_create_textflow,PDF_fit_textflow) which works fine.

How do I get justified Text "" without seeing the BOM sign (Up Arrow) in the Document?

Any other way I could style text justified rather than with inline option alignment?

```<code>$compo_txt = html_entity_decode($compo_txt, ENT_QUOTES, 'UTF-8');
$compo_txt = "<alignment=justify>".$compo_txt;
$compo_txt = iconv("UTF-8", "UTF-16", $compo_txt);
$len = strlen($compo_txt);
$compo_flow = PDF_create_textflow($p, $compo_txt, "fontname=arial fontsize=".$compo_size." encoding=unicode textlen=" . $len . " embedding=true");

$flow_warning = PDF_fit_textflow(
    $p, $compo_flow, $compo_x + $compo_w,
    $compo_y, $compo_x, $compo_y - $compo_h,
    'orientate=' . $compo_o
);
</code>```

答:
Using alignment in optlist not as inline otption did the job:</p>

```<code>PDF_create_textflow($p, $compo_txt, "fontname=arial fontsize=".$compo_size." encoding=unicode textlen=" . $len . " embedding=true alignment=justify");
</code>```

Title: Alignment in textflow

Body:
I'm placing a textflow with UTF-16 text in PHP (PDF_create_textflow,PDF_fit_textflow) which works fine.

How do I get justified Text "" without seeing the BOM sign (Up Arrow) in the Document?

Any other way I could style text justified rather than with inline option alignment?

$compo_txt = html_entity_decode($compo_txt, ENT_QUOTES, 'UTF-8');
$compo_txt = "<alignment=justify>".$compo_txt;
$compo_txt = iconv("UTF-8", "UTF-16", $compo_txt);
$len = strlen($compo_txt);
$compo_flow = PDF_create_textflow($p, $compo_txt, "fontname=arial fontsize=".$compo_size." encoding=unicode textlen=" . $len . " embedding=true");

$flow_warning = PDF_fit_textflow(
    $p, $compo_flow, $compo_x + $compo_w,
    $compo_y, $compo_x, $compo_y - $compo_h,
    'orientate=' . $compo_o
);

Body:
Using alignment in optlist not as inline otption did the job:

PDF_create_textflow($p, $compo_txt, "fontname=arial fontsize=".$compo_size." encoding=unicode textlen=" . $len . " embedding=true alignment=justify");


问:
How to find a sum of even numbers in range recursively?
How can I write this function recursively?

```<code>def sum_even(n):
    total = 0
    for i in range(2, n+1,2):
        total = total + i
    return total
</code>```

I've tried to write it recursively but failed since I just took the lesson.

答:
Recursive functions can be difficult:

```<code>def sum_even(n):
    if n == 0:
        return n
    if n % 2 == 0:
        # Add the current number + the previous even number
        return n + sum_even(n - 2)
    return add_even(n - 1) # If the number is odd, add the previous number
</code>```

```<code>i.e. sum_even(6)
    n % 2 == 0:
        return 6 + sum_even(4)
        return 6 + 4 + sum_even(2)
        return 6 + 4 + 2 + sum_even(0)
Then n == 0
        return 6 + 4 + 2 + return 0
12
</code>```

Similarly:

```<code>sum_even(7)
return sum_even(7 -1)
return sum_even(6)
...
return 12
</code>```

Body:
How can I write this function recursively?

def sum_even(n):
    total = 0
    for i in range(2, n+1,2):
        total = total + i
    return total

I've tried to write it recursively but failed since I just took the lesson.

Body:
Recursive functions can be difficult:

def sum_even(n):
    if n == 0:
        return n
    if n % 2 == 0:
        # Add the current number + the previous even number
        return n + sum_even(n - 2)
    return add_even(n - 1) # If the number is odd, add the previous number

i.e. sum_even(6)
    n % 2 == 0:
        return 6 + sum_even(4)
        return 6 + 4 + sum_even(2)
        return 6 + 4 + 2 + sum_even(0)
Then n == 0
        return 6 + 4 + 2 + return 0
12

Similarly:

sum_even(7)
return sum_even(7 -1)
return sum_even(6)
...
return 12


问:
"internal/modules/cjs/loader.js:582 throw err"
I'm getting the following error in the console:
Error : Cannot find module.

Here is the full error. What should I do?

```<code>internal/modules/cjs/loader.js:582
    throw err;
    ^

Error: Cannot find module 'C:\Users\User\Desktop\NodeJsProject\app.js'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:580:15)
    at Function.Module._load (internal/modules/cjs/loader.js:506:25)
    at Function.Module.runMain (internal/modules/cjs/loader.js:741:12)
    at startup (internal/bootstrap/node.js:285:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:739:3)
</code>```

答:
try the following command

remove node_modules and package-lock.json

```<code>rm -rf node_modules package-lock.json
</code>```

then run the following command to install dependencies

```<code>npm install
</code>```

finally, run your package by the following command.

```<code>npm start
</code>```

Body:
I'm getting the following error in the console:
Error : Cannot find module.

Here is the full error. What should I do?

internal/modules/cjs/loader.js:582
    throw err;
    ^

Error: Cannot find module 'C:\Users\User\Desktop\NodeJsProject\app.js'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:580:15)
    at Function.Module._load (internal/modules/cjs/loader.js:506:25)
    at Function.Module.runMain (internal/modules/cjs/loader.js:741:12)
    at startup (internal/bootstrap/node.js:285:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:739:3)

Body:
try the following command

remove node_modules and package-lock.json

rm -rf node_modules package-lock.json

then run the following command to install dependencies

npm install

finally, run your package by the following command.

npm start


问:
How to prevent escaping a blade syntax?
I wanted to use the helper to set an e-mail address:

```<code>Email: contact@{{ request()->getHost() }}
</code>```

But apparently, @ before {{ is used to escape Blade instructions!

How can we prevent this escaping functionality?

答:
You should use @ as a string:

```<code>Email: contact{{ '@'. $request()->getHost() }}
</code>```

Title: How to prevent escaping a blade syntax?

Body:
I wanted to use the helper to set an e-mail address:

Email: contact@{{ request()->getHost() }}

But apparently, @ before {{ is used to escape Blade instructions!

How can we prevent this escaping functionality?

Body:
You should use @ as a string:

Email: contact{{ '@'. $request()->getHost() }}


问:
Sorting a dictionary by its sub value
I currently have a dictionary in Python3 that looks like this

```<code>{'parentkey1': {'value1': 3, 'value2': 0},
 'parentkey2': {'value1': 2, 'value2': 5},
 'parentkey3': {'value1': 6, 'value2': 9},
 'parentkey4': {'value1': 8, 'value2': 3}
 }
</code>```

Is there a way that I can arrange the nested dictionary that it becomes

```<code>{'parentkey1': {'value2': 0, 'value1': 3},
 'parentkey2': {'value1': 2, 'value2': 5},
 'parentkey3': {'value1': 6, 'value2': 9},
 'parentkey4': {'value2': 3, 'value1': 8}
}
</code>```

答:
Can do by simply switching values if value2 > value1 for each item</p>

```<code>data = {'parentkey1': {'value1': 3, 'value2': 0},
  'parentkey2': {'value1': 2, 'value2': 5},
  'parentkey3': {'value1': 6, 'value2': 9},
  'parentkey4': {'value1': 8, 'value2': 3}
  }

for key, value in data.items():
    if value['value1'] > value['value2']:
        value['value1'], value['value2'] = value['value2'], value['value1']
</code>```

Title: Sorting a dictionary by its sub value

Body:
I currently have a dictionary in Python3 that looks like this

{'parentkey1': {'value1': 3, 'value2': 0},
 'parentkey2': {'value1': 2, 'value2': 5},
 'parentkey3': {'value1': 6, 'value2': 9},
 'parentkey4': {'value1': 8, 'value2': 3}
 }

Is there a way that I can arrange the nested dictionary that it becomes

{'parentkey1': {'value2': 0, 'value1': 3},
 'parentkey2': {'value1': 2, 'value2': 5},
 'parentkey3': {'value1': 6, 'value2': 9},
 'parentkey4': {'value2': 3, 'value1': 8}
}

Body:
Can do by simply switching values if value2 > value1 for each item

data = {'parentkey1': {'value1': 3, 'value2': 0},
  'parentkey2': {'value1': 2, 'value2': 5},
  'parentkey3': {'value1': 6, 'value2': 9},
  'parentkey4': {'value1': 8, 'value2': 3}
  }

for key, value in data.items():
    if value['value1'] > value['value2']:
        value['value1'], value['value2'] = value['value2'], value['value1']


问:
matching consecutive pairs in pd.Series
I have a DataFrame which looks like this :-

```<code>ID | act
 1    A
 1    B
 1    C
 1    D
 2    A
 2    B
 3    A
 3    C
</code>```

I am trying to get the IDs where an activity act1 is followed by another act2, for example, A is followed by B. In that case, I want to get [1,2] as the ids. How do I go about this in a vectorized manner?

Edit :- Expected output : For the sample df defined above, the output should be a list/Series of all the IDs where A is followed immediately by B

```<code>IDs
 1
 2
</code>```

答:
Here is a simple, vectorised way to do it!

```<code>df.loc[(df.act == 'A') & (df.act.shift(-1) == 'B') & (df.ID == df.ID.shift(-1)), 'ID']
</code>```

Output:

```<code>0    1
4    2
Name: ID, dtype: int64
</code>```

Another way of writing this, possibly clearer:

```<code>conditions = (df.act == 'A') & (df.act.shift(-1) == 'B') & (df.ID == df.ID.shift(-1))
df.loc[conditions, 'ID']
</code>```

Numpy makes it easy to filter for one or many boolean conditions. The resulting vector is used to filter your dataframe.

Title: matching consecutive pairs in pd.Series

Body:
I have a DataFrame which looks like this :-

ID | act
 1    A
 1    B
 1    C
 1    D
 2    A
 2    B
 3    A
 3    C

I am trying to get the IDs where an activity act1 is followed by another act2, for example, A is followed by B. In that case, I want to get [1,2] as the ids. How do I go about this in a vectorized manner?

Edit :- Expected output : For the sample df defined above, the output should be a list/Series of all the IDs where A is followed immediately by B

IDs
 1
 2

Body:
Here is a simple, vectorised way to do it!

df.loc[(df.act == 'A') & (df.act.shift(-1) == 'B') & (df.ID == df.ID.shift(-1)), 'ID']

Output:

0    1
4    2
Name: ID, dtype: int64

Another way of writing this, possibly clearer:

conditions = (df.act == 'A') & (df.act.shift(-1) == 'B') & (df.ID == df.ID.shift(-1))
df.loc[conditions, 'ID']

Numpy makes it easy to filter for one or many boolean conditions. The resulting vector is used to filter your dataframe.


问:
Cumulative quantity of type X products in javascript
This is the case: Every order can contain many types, with different quantities. I want, for each order item, the total quantity for each type.

```<code>[{
  "order" : 1,
  "orderDetails" : [{
    "quantity" : 10,
    "product" : {
      "productType" : "A"
    },
    "quantity" : 20,
    "product" : {
      "productType" : "A"
    },
    "quantity" : 10,
    "product" : {
      "productType" : "B"
    }
  }]
}]
</code>```

this is my code, it does the job but I am trying to make it a bit more elegant, somehow. I am pretty sure there is redundant code there, I am not sure I am using reduce correctly

```<code>    const orders = data.map(h => {
    const newArray = [];
    h.orderDetails_ = h.orderDetails.reduce(function(a, b, i) {
        if (newArray[b.product.productType] == undefined) {
          newArray[b.product.productType] = b.quantity;
          return newArray;
        } else {
          newArray[b.product.productType] += b.quantity;
          return newArray;
        }
      }, 0);
      return h;
    });
</code>```

答:
well, for anyone out there, this is the better and correct version</p>

```<code>    const orders = data.map(h => {
      h.orderDetails_ = h.orderDetails.reduce((orderTotals, order) => {
        orderTotals[order.product.productType] =
          (orderTotals[order.product.productType] || 0) + order.quantity;
        return orderTotals;
      }, {});
      return h;
    });
</code>```

Body:
This is the case: Every order can contain many types, with different quantities. I want, for each order item, the total quantity for each type.

[{
  "order" : 1,
  "orderDetails" : [{
    "quantity" : 10,
    "product" : {
      "productType" : "A"
    },
    "quantity" : 20,
    "product" : {
      "productType" : "A"
    },
    "quantity" : 10,
    "product" : {
      "productType" : "B"
    }
  }]
}]

this is my code, it does the job but I am trying to make it a bit more elegant, somehow. I am pretty sure there is redundant code there, I am not sure I am using reduce correctly

    const orders = data.map(h => {
    const newArray = [];
    h.orderDetails_ = h.orderDetails.reduce(function(a, b, i) {
        if (newArray[b.product.productType] == undefined) {
          newArray[b.product.productType] = b.quantity;
          return newArray;
        } else {
          newArray[b.product.productType] += b.quantity;
          return newArray;
        }
      }, 0);
      return h;
    });

Body:
well, for anyone out there, this is the better and correct version

    const orders = data.map(h => {
      h.orderDetails_ = h.orderDetails.reduce((orderTotals, order) => {
        orderTotals[order.product.productType] =
          (orderTotals[order.product.productType] || 0) + order.quantity;
        return orderTotals;
      }, {});
      return h;
    });


问:
DAX: Classifying employees based on outcome of measure
I'm trying to classify employees by how many times they've called in sick in a given time period. I already have a measure which calculates the number of times an employee calls in sick in a given context. Below is a rough sketch of what I want the result to look like:

The data set I have has the date of calling in sick as well as the date the employee started working again (given that they have recovered already) for each date that the given employee is employed (so it also shows days that an employee is not sick) example below.

So for the above example I want employee 1 to be classified as "2" if I look at this entire year, however if I drill down to the months I want employee 1 to be classified as "1" in both january and february.

Does anyone know if and how this can be done?

I'm using Visual Studio 2017 SSAS Tabular.

Please tell me if something is not clear :).

答:
I figured out how to do it with the link posted below:

https://www.daxpatterns.com/dynamic-segmentation/


问:
Excel formula position of minimum value
EDIT: Likely an easy question, basically I have three values, let's say 9, 4 and 7 in different cells (not in a table), I want to find the minimum in an order then return its relative position, for example: 9,4,7 would return 2 as 4 is the minimum and is positioned second.

What is the correct excel formula to do so? Thanks .

Solution: Thanks all for your help, I didn't think excel could do if it wasn't continuous. I've ended up using a series of nested IF statements, an AND statement and < signs, to get the job done :)

答:
Unfortunately, Excel lookup functions want continuos range of data.

For a set of random cells, use something like:

```<code>Public Function Match2(ByVal What As Variant, ByVal Where As Range) As Long
  Dim a As Range
  Dim c As Range
  Dim g As Long

  For Each a In Where.Areas
    For Each c In a.Cells
      g = g + 1

      If c.Value = What Then
        Match2 = g
        Exit Function
      End If
    Next
  Next
End Function
</code>```

Usage:

```<code>=Match2(MIN(B6,F9,I16),(B6,F9,I16))
</code>```

ContentLicense: CC BY-SA 3.0

Title: Excel formula position of minimum value

Body:
Unfortunately, Excel lookup functions want continuos range of data.

For a set of random cells, use something like:

Public Function Match2(ByVal What As Variant, ByVal Where As Range) As Long
  Dim a As Range
  Dim c As Range
  Dim g As Long

  For Each a In Where.Areas
    For Each c In a.Cells
      g = g + 1

      If c.Value = What Then
        Match2 = g
        Exit Function
      End If
    Next
  Next
End Function

Usage:

=Match2(MIN(B6,F9,I16),(B6,F9,I16))


问:
Bash exceute multuple commands after || if non 0
I have a line of code in my scripts to make sure a conda environment exists and then if not install the environment and download the database for a programme in the environment. I have this code:

```<code>   test -d ~/miniconda3/envs/antismash_v5 || echo "Conda environment does not exist. Initialising conda environment......" && conda env create -f antismash.yml &&  conda activate antismash_v5 && download-antismash-databases
</code>```

But this just exceute everything after the first && regardless of if the test function returns non zero before ||. How can I get this to work as intended?

答:
When you call a || b && c it first evaluates a:

if a returns nonzero, it evaluates b and if b returns 0 it evaluates c

if a returns 0, it ignores b and evaluates c

This operation is very similar to how boolean expressions are evaluated in C with the && and || operator, except that unlike C, there is no operator precedence of && over ||.

Just like C, you can to use parentheses to make sure the condition is limited to the block of your choice, e.g.:

a || (b && c)

You could do something like that in your example:

test -d ~/miniconda3/envs/antismash_v5 ||
 (echo "Conda environment does not exist. Initialising conda environment......" &&
  conda env create -f antismash.yml &&
  conda activate antismash_v5 &&
  download-antismash-databases)
```

<p>I have put the code on several lines for clarity but this can be done in one line.</p>

<p>Also, as @picklerick pointed out, parentheses will create a subshell. In your case it should not make a difference, but should you need to call your commands in the same shell, just use curly braces instead.</p>

<pre class="lang-sh prettyprint-override"><code>test -d ~/miniconda3/envs/antismash_v5 ||
 { echo "Conda environment does not exist. Initialising conda environment......" &&
  conda env create -f antismash.yml &&
  conda activate antismash_v5 &&
  download-antismash-databases;}
</code>```

You need to use a whitespace after {.
You need to use a semicolon before } if you want to write it in one line.

Body:
I have a line of code in my scripts to make sure a conda environment exists and then if not install the environment and download the database for a programme in the environment. I have this code:

   test -d ~/miniconda3/envs/antismash_v5 || echo "Conda environment does not exist. Initialising conda environment......" && conda env create -f antismash.yml &&  conda activate antismash_v5 && download-antismash-databases

But this just exceute everything after the first && regardless of if the test function returns non zero before ||. How can I get this to work as intended?

Body:
When you call a || b && c it first evaluates a:

if a returns nonzero, it evaluates b and if b returns 0 it evaluates c

if a returns 0, it ignores b and evaluates c

This operation is very similar to how boolean expressions are evaluated in C with the && and || operator, except that unlike C, there is no operator precedence of && over ||.

Just like C, you can to use parentheses to make sure the condition is limited to the block of your choice, e.g.:

a || (b && c)

You could do something like that in your example:

test -d ~/miniconda3/envs/antismash_v5 ||
 (echo "Conda environment does not exist. Initialising conda environment......" &&
  conda env create -f antismash.yml &&
  conda activate antismash_v5 &&
  download-antismash-databases)

I have put the code on several lines for clarity but this can be done in one line.

Also, as @picklerick pointed out, parentheses will create a subshell. In your case it should not make a difference, but should you need to call your commands in the same shell, just use curly braces instead.

test -d ~/miniconda3/envs/antismash_v5 ||
 { echo "Conda environment does not exist. Initialising conda environment......" &&
  conda env create -f antismash.yml &&
  conda activate antismash_v5 &&
  download-antismash-databases;}

You need to use a whitespace after {.
You need to use a semicolon before } if you want to write it in one line.


问:
SQL Server substring throws error "multiple results"
I use Microsoft SQL Server 2016.

I have a column that is called Failover and looks like his:

```<code>  $D$Failov:12345:54362:28564
  $D$Failov:12345:
  $D$Failov:86905:45634
</code>```

I want that number so I use :

```<code>select substring(failover, 10, 5)
from dbo.f009
where failover like '$D$Failov:%'
</code>```

It works fine, but if I want a second column called Account, it crashed with multiple results…

```<code>Select
    account,
    (Select substring(failover, 10, 5) AS "1.Result"
     from dbo.f009
     where Failover like '$D$Failov:%')
from
    f009
where
    Failover like '$D$Failov:%'
</code>```

How to fix this ?

Is there a simple way to take the second number and third? I can do it with:

```<code>substring(failover, 16, 5), substring(failover, 22, 5)
</code>```

etc etc but it don't want to repeat myself.

答:
You can repeat the string operations:

```<code>select substring(failover, 11, 5) as num1,
       substring(failover, 17, 5) as num2,
       substring(failover, 23, 5) as num3
from dbo.f009
where failover like '$D$Failov:%';
</code>```

You can also phrase this as a recursive CTE, if you have an indefinite number of values:

```<code>with t as (
      select * from (values ('$D$Failov:12345:54362:28564'), ('$D$Failov:12345:')) v(failover)
     ),
     cte as (
      select failover, convert(varchar(max), NULL) as acct, convert(varchar(max), stuff(failover, 1, 10, '')) as rest, 0 as lev
      from t
      union all
      select failover, left(rest, 5), stuff(rest, 1, 6, ''), lev + 1
      from cte
      where rest > ':'
     )
select failover, acct, lev
from cte
where lev > 0;
</code>```

Here is a db<>fiddle.

Body:
I use Microsoft SQL Server 2016.

I have a column that is called Failover and looks like his:

  $D$Failov:12345:54362:28564
  $D$Failov:12345:
  $D$Failov:86905:45634

I want that number so I use :

select substring(failover, 10, 5)
from dbo.f009
where failover like '$D$Failov:%'

It works fine, but if I want a second column called Account, it crashed with multiple results…

Select
    account,
    (Select substring(failover, 10, 5) AS "1.Result"
     from dbo.f009
     where Failover like '$D$Failov:%')
from
    f009
where
    Failover like '$D$Failov:%'

How to fix this ?

Is there a simple way to take the second number and third? I can do it with:

substring(failover, 16, 5), substring(failover, 22, 5)

etc etc but it don't want to repeat myself.

Body:
You can repeat the string operations:

select substring(failover, 11, 5) as num1,
       substring(failover, 17, 5) as num2,
       substring(failover, 23, 5) as num3
from dbo.f009
where failover like '$D$Failov:%';

You can also phrase this as a recursive CTE, if you have an indefinite number of values:

with t as (
      select * from (values ('$D$Failov:12345:54362:28564'), ('$D$Failov:12345:')) v(failover)
     ),
     cte as (
      select failover, convert(varchar(max), NULL) as acct, convert(varchar(max), stuff(failover, 1, 10, '')) as rest, 0 as lev
      from t
      union all
      select failover, left(rest, 5), stuff(rest, 1, 6, ''), lev + 1
      from cte
      where rest > ':'
     )
select failover, acct, lev
from cte
where lev > 0;

Here is a db<>fiddle.


问:
System screen started from intent does not survive orientation change
In my android app I want to want to save contacts in the addressbook via Intent. The Intent works just fine. However, the following screen (Choose in which address book the contact should be saved) does not survive an orientation change of the activity and the devices goes back into my app.

Effectively, my user has to press my button "Save contact" again, and the system screen is shown again.

What I want to achieve is that this system screen will not be killed by an orientation change.

In case my English has failed me, here have a screenshot:

答:
I don't know if you can avoid the screen being killed, as the system needs to recreate it to fit the changed screen dimensions.

But you could implement that after killing the screen while orientation change you instantly open the dialog again(maybe even pre filled with the data it contained before).

How to build that workarround

You could hold some Boolean variable like 'isDialogActive' in your activity which you set true when the dialog is opened and set to false when the dialog gets closed.

Next up you can save that Boolean to the Bundle in onSaveInstanceState lifecycle function.

```<code>protected void onSaveInstanceState(Bundle bundle) {
   super.onSaveInstanceState(bundle);
   bundle.putBoolean("is_dialog_active", this.isDialogActive);
}
</code>```

So now when your orientation changes, you safe information whether the dialog was active before the rotation or not to a Bundle. This Bundle survives the orientation change and gets passed to onCreate after the change.So now we can use this information(the Bundle) when the activity is recreated in the onCreate lifecycle function.

```<code>@Override
protected void onCreate(Bundle bundle) {
    boolean dialogWasActiveBeforeChange =
             bundle.getBoolean("is_dialog_active")

    if ( dialogWasActiveBeforeChange){
       //use your logic that opens the dialog ( that logic should also set
       // this.isDialogActive to true )
    }
}
</code>```

Body:
I don't know if you can avoid the screen being killed, as the system needs to recreate it to fit the changed screen dimensions.

But you could implement that after killing the screen while orientation change you instantly open the dialog again(maybe even pre filled with the data it contained before).

How to build that workarround

You could hold some Boolean variable like 'isDialogActive' in your activity which you set true when the dialog is opened and set to false when the dialog gets closed.

Next up you can save that Boolean to the Bundle in onSaveInstanceState lifecycle function.

protected void onSaveInstanceState(Bundle bundle) {
   super.onSaveInstanceState(bundle);
   bundle.putBoolean("is_dialog_active", this.isDialogActive);
}

So now when your orientation changes, you safe information whether the dialog was active before the rotation or not to a Bundle. This Bundle survives the orientation change and gets passed to onCreate after the change.So now we can use this information(the Bundle) when the activity is recreated in the onCreate lifecycle function.

@Override
protected void onCreate(Bundle bundle) {
    boolean dialogWasActiveBeforeChange =
             bundle.getBoolean("is_dialog_active")

    if ( dialogWasActiveBeforeChange){
       //use your logic that opens the dialog ( that logic should also set
       // this.isDialogActive to true )
    }
}


问:
Website makes IE8 crash
I'm having a simple but still very annoying issue and i have no idea where to start looking. Its a website i've been taking over and it crashes hard right away when opening in IE8 version 8.0.6001.18702.

The site is http://www.dhf.dk/DHF.aspx and i have to suspect some invalid manipulation of DOM but i like i said i have no idea where to start looking.

Error message is

```<code>AppName: iexplore.exe    AppVer: 8.0.6001.18702  ModName: mshtml.dll
ModVer:  8.0.6001.18975  Offset: 00067838
</code>```

I suspect the object-embed code to be faulty but im not hardcore enough in html to be sure if its the case

```<code><object id="DhfSlideshow" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="610px" height="417px" codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab">
    <param name="movie" value="/Frontend/Flash/slideshow.swf" />
    <param name="quality" value="high" />
    <param name="allowScriptAccess" value="sameDomain" />
    <param name="wmode" value="transparent" />
    <param name="flashvars" value="dataUrl=/Frontend/DHF/DHF.Widget.Slideshows.Album/Server/DHF.Widget.Slideshows.Album.ashx?albumId=a68eae5f-955b-4ba0-aa11-6e4d68ead5df&color_scheme=/red/flash/&overviewUrl=s" />
    <embed align="middle" wmode="transparent" width="610px" quality="high" height="417px" pluginspage="http://www.adobe.com/go/getflashplayer" loop="false" name="DhfSlideshow" type="application/x-shockwave-flash" flashvars="dataUrl=/Frontend/DHF/DHF.Widget.Slideshows.Album/Server/DHF.Widget.Slideshows.Album.ashx?albumId=a68eae5f-955b-4ba0-aa11-6e4d68ead5df&color_scheme=/red/flash/&overviewUrl=s" play="true" allowScriptAccess="sameDomain" src="/Frontend/Flash/slideshow.swf"></embed>

</object>
</code>```

答:
It turned out that all the other templates for the website had a <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" /> tag on them, and correctly... after inserting on the frontpage as well the page rendered in IE without crashing.

I can't even begin to imagine where to look, so i'll guess that has to wait until a makeover at some point.

Title: Website makes IE8 crash

Body:
I'm having a simple but still very annoying issue and i have no idea where to start looking. Its a website i've been taking over and it crashes hard right away when opening in IE8 version 8.0.6001.18702.

The site is http://www.dhf.dk/DHF.aspx and i have to suspect some invalid manipulation of DOM but i like i said i have no idea where to start looking.

Error message is

AppName: iexplore.exe    AppVer: 8.0.6001.18702  ModName: mshtml.dll
ModVer:  8.0.6001.18975  Offset: 00067838

I suspect the object-embed code to be faulty but im not hardcore enough in html to be sure if its the case

<object id="DhfSlideshow" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="610px" height="417px" codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab">
    <param name="movie" value="/Frontend/Flash/slideshow.swf" />
    <param name="quality" value="high" />
    <param name="allowScriptAccess" value="sameDomain" />
    <param name="wmode" value="transparent" />
    <param name="flashvars" value="dataUrl=/Frontend/DHF/DHF.Widget.Slideshows.Album/Server/DHF.Widget.Slideshows.Album.ashx?albumId=a68eae5f-955b-4ba0-aa11-6e4d68ead5df&color_scheme=/red/flash/&overviewUrl=s" />
    <embed align="middle" wmode="transparent" width="610px" quality="high" height="417px" pluginspage="http://www.adobe.com/go/getflashplayer" loop="false" name="DhfSlideshow" type="application/x-shockwave-flash" flashvars="dataUrl=/Frontend/DHF/DHF.Widget.Slideshows.Album/Server/DHF.Widget.Slideshows.Album.ashx?albumId=a68eae5f-955b-4ba0-aa11-6e4d68ead5df&color_scheme=/red/flash/&overviewUrl=s" play="true" allowScriptAccess="sameDomain" src="/Frontend/Flash/slideshow.swf"></embed>

</object>


问:
How to limite scroll move of Recyclerview?
In my vertical recyclerview, I have multiple horizontal recyclerviews and I have a problem: when I want to scroll left or right, if I'm scrolling a bit up or down at the same time, the horizontal scrolling doesn't work.

So my idea was to redefine what is up, down, left and right for the recycler view. So I stumbled upon this thread : How to detect swipe direction between left/right and up/down

First I though it was what I need but then I understood, it was just redefining directions at the end of a swipe (not during), so I tried to do all the angle computation during the swipe. I ended with this :

```<code>var initialX: Float
var initialY: Float

    ui_recyclerView?.setOnTouchListener(object: View.OnTouchListener{

            override fun onTouch(v: View?, event: MotionEvent?): Boolean {
                val action = event?.actionMasked

                if (action == MotionEvent.ACTION_DOWN) {
                    initialX = event.x
                    initialY = event.y

                }
                else if(action == MotionEvent.ACTION_MOVE) {
                    val swipeDirection = GestureUtils.getSwipeDirection(initialX, initialY, event.x, event.y)

                    if (swipeDirection == GestureUtils.Direction.UP || swipeDirection == GestureUtils.Direction.DOWN) {
                        return false
                    }

                }

                return true
            }

        })
</code>```

It worked but then I didn't have the smooth scrolling any more (it was very robotic), and neither the click.

Is there a built-in function with recycler view to limit MoveEvent to a certain angle ? If not, how can I put back the smooth scrolling effect of a normal recycler view ?

That would help me a lot !

Body:
In my vertical recyclerview, I have multiple horizontal recyclerviews and I have a problem: when I want to scroll left or right, if I'm scrolling a bit up or down at the same time, the horizontal scrolling doesn't work.

So my idea was to redefine what is up, down, left and right for the recycler view. So I stumbled upon this thread : How to detect swipe direction between left/right and up/down

First I though it was what I need but then I understood, it was just redefining directions at the end of a swipe (not during), so I tried to do all the angle computation during the swipe. I ended with this :

var initialX: Float
var initialY: Float

    ui_recyclerView?.setOnTouchListener(object: View.OnTouchListener{

            override fun onTouch(v: View?, event: MotionEvent?): Boolean {
                val action = event?.actionMasked

                if (action == MotionEvent.ACTION_DOWN) {
                    initialX = event.x
                    initialY = event.y

                }
                else if(action == MotionEvent.ACTION_MOVE) {
                    val swipeDirection = GestureUtils.getSwipeDirection(initialX, initialY, event.x, event.y)

                    if (swipeDirection == GestureUtils.Direction.UP || swipeDirection == GestureUtils.Direction.DOWN) {
                        return false
                    }

                }

                return true
            }

        })

It worked but then I didn't have the smooth scrolling any more (it was very robotic), and neither the click.

Is there a built-in function with recycler view to limit MoveEvent to a certain angle ? If not, how can I put back the smooth scrolling effect of a normal recycler view ?

That would help me a lot !

Body: recyclerView.setNestedScrollingEnabled(false);


问:
Export xlsx file through executing scripts in SQL developer
I know that we can use SPOOL command to export query result in CSV format from sql developer. However, I would like to export the query result as xlsx format instead of CSV format. Is there any command that I can use ??</p>

答:
In SQL Developer you can export a gridresult by right-click -> export -> Format = "excel 2003+ ( xlsx ) ... but think you know this already.

Last time I created an XLSX file I used https://technology.amis.nl/wp-content/uploads/2011/02/as_xlsx18.txt

Probably I would use jasper or a different tool now.


问:
Hibernate extra query after JOIN FETCH on the same entity
I'm trying to query a large set of entity though Hibernate by using this query:

```<code>        "Select * " +
        " From Dossier as dossier" +
        " LEFT  JOIN FETCH dossier.candidat as candidat " +
        " LEFT  JOIN FETCH candidat.roles as role " +
        " LEFT  JOIN FETCH dossier.infoPerso as infoPerso " +
        " LEFT  JOIN FETCH dossier.etablissementOrigine as etablissementOrigine " +
        " LEFT  JOIN FETCH etablissementOrigine.filieres as filieres " +
        " LEFT OUTER JOIN FETCH etablissementOrigine.ville as villeOrigine " +
        " LEFT  JOIN FETCH dossier.etatDossier as etatDossier " +
        " LEFT OUTER JOIN FETCH infoPerso.fichierCNIRecto as fichierCNIRecto " +
        " LEFT OUTER JOIN FETCH fichierCNIRecto.type " +
        " LEFT OUTER JOIN FETCH infoPerso.fichierCNIVerso as fichierCNIVerso " +
        " LEFT OUTER JOIN FETCH fichierCNIVerso.type " +
        " LEFT OUTER JOIN FETCH infoPerso.fichierCV as fichierCV " +
        " LEFT OUTER JOIN FETCH fichierCV.type " +
        " LEFT OUTER JOIN FETCH infoPerso.fichierJAPD as fichierJAPD " +
        " LEFT OUTER JOIN FETCH fichierJAPD.type " +
        " LEFT OUTER JOIN FETCH infoPerso.fichierCNIVerso as fichierCNIVerso " +
        " LEFT OUTER JOIN FETCH fichierCNIVerso.type " +
        " LEFT OUTER JOIN FETCH infoPerso.situationFamilliale as situation "

            dossiers = getEntityManager()
                    .createQuery(sql, Dossier.class)
                    .getResultList();
</code>```

I can see hibernate doing the first big native  SQL query. But just after that, Hibernate generates 1 more query for each row to load DOssier, I don't know why, Dossier is already a part of fetchs elements...

```<code> /* load org.ema.ecandidature.dossier.Dossier */ select
    dossier0_.id as id1_61_0_,
    dossier0_.version as version2_61_0_,
    dossier0_.valid as valid3_61_0_,
    dossier0_.validSecretariat as validSec4_61_0_,
    dossier0_.candidat_id as candidat7_17_0_,
    dossier0_.casParticulier as casParti1_17_0_,
    dossier0_.dateInscription as dateInsc2_17_0_,
    dossier0_.dateSoumission as dateSoum3_17_0_,
    dossier0_.entreprise_id as entrepri8_17_0_,
    dossier0_.etablissementOrigine_id as etabliss9_17_0_,
    dossier0_.etatDossier_id as etatDos10_17_0_,
    dossier0_.infoPaiement_id as infoPai11_17_0_,
    dossier0_.infoPerso_id as infoPer12_17_0_,
    dossier0_.listCursusAcademique_id as listCur13_17_0_,
    dossier0_.listDocumentsSupplementaires_id as listDoc14_17_0_,
    dossier0_.listExpEntreprise_id as listExp15_17_0_,
    dossier0_.listFormations_id as listFor16_17_0_,
    dossier0_.listLangues_id as listLan17_17_0_,
    dossier0_.listReferents_id as listRef18_17_0_,
    dossier0_.listSejourEtranger_id as listSej19_17_0_,
    dossier0_.motivationCentreInteret_id as motivat20_17_0_,
    dossier0_.secretariatChangeDate as secretar4_17_0_,
    dossier0_.secretariatChangeDateBackup as secretar5_17_0_,
    dossier0_.validationCommentaire as validati6_17_0_
from
    Dossier dossier0_
where
    dossier0_.candidat_id=?
</code>```

Dossier.class:

```<code>@Entity
@BatchSize(size=100)
public class Dossier extends ValidableEntity {

    /** The Constant serialVersionUID. */
    private static final long serialVersionUID = 1L;

    /** The etablissement origine. */
    @SecretaryExport
    @ManyToOne( fetch=FetchType.LAZY)
    @JoinColumn()
    private Etablissement etablissementOrigine;

    /** The date inscription. */
    @SecretaryExport
    private Date dateInscription;

    /** The date soumission. */
    @SecretaryExport
    private Date dateSoumission;

    /** The date modification. */
    @SecretaryExport
    private Date secretariatChangeDate;

    /** The date de modification backup. */
    @SecretaryExport
    private Date secretariatChangeDateBackup;

    /** The cas particulier. */
    @SecretaryExport
    private Boolean casParticulier;

    /** The etat dossier. */
    @SecretaryExport
    @ManyToOne( fetch=FetchType.LAZY)
    @JoinColumn()
    private EtatDossier etatDossier;

    /** The candidat. */
    @SecretaryExport
    @OneToOne(fetch=FetchType.LAZY)
    private Candidat candidat;

    /** The info perso. */
    @SecretaryExport
    @Obligatoire
    @ObligatoireSecretariat
    @OneToOne(cascade = { CascadeType.ALL },fetch=FetchType.LAZY,orphanRemoval = true)
    private InfoPerso infoPerso;

    /** The list formations. */
    //@SecretaryExport
    @Obligatoire
    @ObligatoireSecretariat
    @OneToOne(cascade = { CascadeType.ALL },fetch=FetchType.LAZY,orphanRemoval = true)
    private ListFormations listFormations;

    /** The list cursus academique. */
    @SecretaryExport
    @Obligatoire
    @ObligatoireSecretariat
    @OneToOne(cascade = { CascadeType.ALL },fetch=FetchType.LAZY,orphanRemoval = true)
    private ListCursusAcademique listCursusAcademique;

    /** The motivation centre interet. */
    @SecretaryExport
    @Obligatoire
    @ObligatoireSecretariat
    @OneToOne(cascade = { CascadeType.ALL },fetch=FetchType.LAZY,orphanRemoval = true)
    private MotivationCentreInteret motivationCentreInteret;

    /** The entreprise. */
    @SecretaryExport
    @Obligatoire
    @ObligatoireSecretariat
    @OneToOne(cascade = { CascadeType.ALL },fetch=FetchType.LAZY,orphanRemoval = true)
    private Entreprise entreprise;

    /** The list langues. */
    @SecretaryExport
    @Obligatoire
    @ObligatoireSecretariat
    @OneToOne(cascade = { CascadeType.ALL },fetch=FetchType.LAZY,orphanRemoval = true)
    private ListLangues listLangues;

    /** The list sejour etranger. */
    @SecretaryExport
    @Obligatoire
    @ObligatoireSecretariat
    @OneToOne(cascade = { CascadeType.ALL },fetch=FetchType.LAZY,orphanRemoval = true)
    private ListSejourEtranger listSejourEtranger;

    /** The list exp entreprise. */
    @SecretaryExport
    @Obligatoire
    @ObligatoireSecretariat
    @OneToOne(cascade = { CascadeType.ALL },fetch=FetchType.LAZY,orphanRemoval = true)
    private ListExpEntreprise listExpEntreprise;

    /** The list referents. */
    @SecretaryExport
    @Obligatoire
    @ObligatoireSecretariat
    @OneToOne(cascade = { CascadeType.ALL},fetch=FetchType.LAZY,orphanRemoval = true)
    private ListReferents listReferents;

    /** The info paiement. */
    @SecretaryExport
    @Obligatoire
    @ObligatoireSecretariat
    @OneToOne(cascade = { CascadeType.ALL},fetch=FetchType.LAZY,orphanRemoval = true)
    private InfoPaiement infoPaiement;

    /** The avis jury. */
    @OneToMany(mappedBy= "dossier" , cascade = { CascadeType.ALL},fetch=FetchType.LAZY,orphanRemoval = true)
    private Set<AvisJury> avisJury = new HashSet<>();

    /** The list documents supplementaires. */
    @Obligatoire
    @ObligatoireSecretariat
    @OneToOne(cascade = { CascadeType.ALL },fetch=FetchType.LAZY,orphanRemoval = true)
    private ListDocumentsSupplementaires listDocumentsSupplementaires;

    /** The list fichier. */
    @OneToMany(mappedBy = "dossier", cascade = { CascadeType.ALL },fetch=FetchType.LAZY,orphanRemoval = true)
    private Set<Fichier> listFichier;

    /** The list avis examinateur. */
    @OneToMany(mappedBy= "dossier" , cascade = { CascadeType.ALL},fetch=FetchType.LAZY,orphanRemoval = true)
    private Set<AvisExaminateur> listAvisExaminateur;

    /** The list commentaire. */
    @OneToMany(cascade = { CascadeType.ALL},fetch=FetchType.LAZY,orphanRemoval = true)
    private Set<Commentaire> listCommentaire;

    /** The validation commentaire. */
    @Column(length = 500)
    @Pattern(regexp="^(.|\n|\r|\t)*$")//accepte tous les caractères et les retours lignes
    private String validationCommentaire;

}
</code>```

What is wrong with that?

答:
I have encountered same behavior.
Lets say you have master class

```<code>@OneToMany
@Fetch(FetchMode.JOIN)
private List<Detail> details = new ArrayList<>();
</code>```

with this config if i pull all details hibernates executes select join first and then selects every one of detail with their ids.
The solution was to remove @Fetch(FetchMode.JOIN) in Master class.

Body:
I'm trying to query a large set of entity though Hibernate by using this query:

        "Select * " +
        " From Dossier as dossier" +
        " LEFT  JOIN FETCH dossier.candidat as candidat " +
        " LEFT  JOIN FETCH candidat.roles as role " +
        " LEFT  JOIN FETCH dossier.infoPerso as infoPerso " +
        " LEFT  JOIN FETCH dossier.etablissementOrigine as etablissementOrigine " +
        " LEFT  JOIN FETCH etablissementOrigine.filieres as filieres " +
        " LEFT OUTER JOIN FETCH etablissementOrigine.ville as villeOrigine " +
        " LEFT  JOIN FETCH dossier.etatDossier as etatDossier " +
        " LEFT OUTER JOIN FETCH infoPerso.fichierCNIRecto as fichierCNIRecto " +
        " LEFT OUTER JOIN FETCH fichierCNIRecto.type " +
        " LEFT OUTER JOIN FETCH infoPerso.fichierCNIVerso as fichierCNIVerso " +
        " LEFT OUTER JOIN FETCH fichierCNIVerso.type " +
        " LEFT OUTER JOIN FETCH infoPerso.fichierCV as fichierCV " +
        " LEFT OUTER JOIN FETCH fichierCV.type " +
        " LEFT OUTER JOIN FETCH infoPerso.fichierJAPD as fichierJAPD " +
        " LEFT OUTER JOIN FETCH fichierJAPD.type " +
        " LEFT OUTER JOIN FETCH infoPerso.fichierCNIVerso as fichierCNIVerso " +
        " LEFT OUTER JOIN FETCH fichierCNIVerso.type " +
        " LEFT OUTER JOIN FETCH infoPerso.situationFamilliale as situation "

            dossiers = getEntityManager()
                    .createQuery(sql, Dossier.class)
                    .getResultList();

I can see hibernate doing the first big native  SQL query. But just after that, Hibernate generates 1 more query for each row to load DOssier, I don't know why, Dossier is already a part of fetchs elements...

 /* load org.ema.ecandidature.dossier.Dossier */ select
    dossier0_.id as id1_61_0_,
    dossier0_.version as version2_61_0_,
    dossier0_.valid as valid3_61_0_,
    dossier0_.validSecretariat as validSec4_61_0_,
    dossier0_.candidat_id as candidat7_17_0_,
    dossier0_.casParticulier as casParti1_17_0_,
    dossier0_.dateInscription as dateInsc2_17_0_,
    dossier0_.dateSoumission as dateSoum3_17_0_,
    dossier0_.entreprise_id as entrepri8_17_0_,
    dossier0_.etablissementOrigine_id as etabliss9_17_0_,
    dossier0_.etatDossier_id as etatDos10_17_0_,
    dossier0_.infoPaiement_id as infoPai11_17_0_,
    dossier0_.infoPerso_id as infoPer12_17_0_,
    dossier0_.listCursusAcademique_id as listCur13_17_0_,
    dossier0_.listDocumentsSupplementaires_id as listDoc14_17_0_,
    dossier0_.listExpEntreprise_id as listExp15_17_0_,
    dossier0_.listFormations_id as listFor16_17_0_,
    dossier0_.listLangues_id as listLan17_17_0_,
    dossier0_.listReferents_id as listRef18_17_0_,
    dossier0_.listSejourEtranger_id as listSej19_17_0_,
    dossier0_.motivationCentreInteret_id as motivat20_17_0_,
    dossier0_.secretariatChangeDate as secretar4_17_0_,
    dossier0_.secretariatChangeDateBackup as secretar5_17_0_,
    dossier0_.validationCommentaire as validati6_17_0_
from
    Dossier dossier0_
where
    dossier0_.candidat_id=?

Dossier.class:

@Entity
@BatchSize(size=100)
public class Dossier extends ValidableEntity {

    /** The Constant serialVersionUID. */
    private static final long serialVersionUID = 1L;

    /** The etablissement origine. */
    @SecretaryExport
    @ManyToOne( fetch=FetchType.LAZY)
    @JoinColumn()
    private Etablissement etablissementOrigine;

    /** The date inscription. */
    @SecretaryExport
    private Date dateInscription;

    /** The date soumission. */
    @SecretaryExport
    private Date dateSoumission;

    /** The date modification. */
    @SecretaryExport
    private Date secretariatChangeDate;

    /** The date de modification backup. */
    @SecretaryExport
    private Date secretariatChangeDateBackup;

    /** The cas particulier. */
    @SecretaryExport
    private Boolean casParticulier;

    /** The etat dossier. */
    @SecretaryExport
    @ManyToOne( fetch=FetchType.LAZY)
    @JoinColumn()
    private EtatDossier etatDossier;

    /** The candidat. */
    @SecretaryExport
    @OneToOne(fetch=FetchType.LAZY)
    private Candidat candidat;

    /** The info perso. */
    @SecretaryExport
    @Obligatoire
    @ObligatoireSecretariat
    @OneToOne(cascade = { CascadeType.ALL },fetch=FetchType.LAZY,orphanRemoval = true)
    private InfoPerso infoPerso;

    /** The list formations. */
    //@SecretaryExport
    @Obligatoire
    @ObligatoireSecretariat
    @OneToOne(cascade = { CascadeType.ALL },fetch=FetchType.LAZY,orphanRemoval = true)
    private ListFormations listFormations;

    /** The list cursus academique. */
    @SecretaryExport
    @Obligatoire
    @ObligatoireSecretariat
    @OneToOne(cascade = { CascadeType.ALL },fetch=FetchType.LAZY,orphanRemoval = true)
    private ListCursusAcademique listCursusAcademique;

    /** The motivation centre interet. */
    @SecretaryExport
    @Obligatoire
    @ObligatoireSecretariat
    @OneToOne(cascade = { CascadeType.ALL },fetch=FetchType.LAZY,orphanRemoval = true)
    private MotivationCentreInteret motivationCentreInteret;

    /** The entreprise. */
    @SecretaryExport
    @Obligatoire
    @ObligatoireSecretariat
    @OneToOne(cascade = { CascadeType.ALL },fetch=FetchType.LAZY,orphanRemoval = true)
    private Entreprise entreprise;

    /** The list langues. */
    @SecretaryExport
    @Obligatoire
    @ObligatoireSecretariat
    @OneToOne(cascade = { CascadeType.ALL },fetch=FetchType.LAZY,orphanRemoval = true)
    private ListLangues listLangues;

    /** The list sejour etranger. */
    @SecretaryExport
    @Obligatoire
    @ObligatoireSecretariat
    @OneToOne(cascade = { CascadeType.ALL },fetch=FetchType.LAZY,orphanRemoval = true)
    private ListSejourEtranger listSejourEtranger;

    /** The list exp entreprise. */
    @SecretaryExport
    @Obligatoire
    @ObligatoireSecretariat
    @OneToOne(cascade = { CascadeType.ALL },fetch=FetchType.LAZY,orphanRemoval = true)
    private ListExpEntreprise listExpEntreprise;

    /** The list referents. */
    @SecretaryExport
    @Obligatoire
    @ObligatoireSecretariat
    @OneToOne(cascade = { CascadeType.ALL},fetch=FetchType.LAZY,orphanRemoval = true)
    private ListReferents listReferents;

    /** The info paiement. */
    @SecretaryExport
    @Obligatoire
    @ObligatoireSecretariat
    @OneToOne(cascade = { CascadeType.ALL},fetch=FetchType.LAZY,orphanRemoval = true)
    private InfoPaiement infoPaiement;

    /** The avis jury. */
    @OneToMany(mappedBy= "dossier" , cascade = { CascadeType.ALL},fetch=FetchType.LAZY,orphanRemoval = true)
    private Set<AvisJury> avisJury = new HashSet<>();

    /** The list documents supplementaires. */
    @Obligatoire
    @ObligatoireSecretariat
    @OneToOne(cascade = { CascadeType.ALL },fetch=FetchType.LAZY,orphanRemoval = true)
    private ListDocumentsSupplementaires listDocumentsSupplementaires;

    /** The list fichier. */
    @OneToMany(mappedBy = "dossier", cascade = { CascadeType.ALL },fetch=FetchType.LAZY,orphanRemoval = true)
    private Set<Fichier> listFichier;

    /** The list avis examinateur. */
    @OneToMany(mappedBy= "dossier" , cascade = { CascadeType.ALL},fetch=FetchType.LAZY,orphanRemoval = true)
    private Set<AvisExaminateur> listAvisExaminateur;

    /** The list commentaire. */
    @OneToMany(cascade = { CascadeType.ALL},fetch=FetchType.LAZY,orphanRemoval = true)
    private Set<Commentaire> listCommentaire;

    /** The validation commentaire. */
    @Column(length = 500)
    @Pattern(regexp="^(.|\n|\r|\t)*$")//accepte tous les caractères et les retours lignes
    private String validationCommentaire;

}

What is wrong with that?

Body:
I have encountered same behavior.
Lets say you have master class

@OneToMany
@Fetch(FetchMode.JOIN)
private List<Detail> details = new ArrayList<>();

with this config if i pull all details hibernates executes select join first and then selects every one of detail with their ids.
The solution was to remove @Fetch(FetchMode.JOIN) in Master class.


问:
Submit button won't line up vertically with other fields on the same line
Can anybody shed some light on why this submit button won't line up vertically with the other form fields on the line?

http://www.e-fluential.com/offline/castoff/

答:
Does vertical-align: middle or vertical-align: text-bottom help at all?

I always have a nightmare with vertical alignment of form fields.


问:
Kubectl always returns a error: yaml: mapping values are not allowed in this context
Kubectl command alway returns this error yaml: line 2: mapping values are not allowed in this context. Even when i call normal version command, config command, etc. Not sure whats causing this.

```<code>tessact@tessact-sys-1:~$ kubectl version
Client Version: version.Info{Major:"1", Minor:"4",
GitVersion:"v1.4.4",
GitCommit:"3b417cc4ccd1b8f38ff9ec96bb50a81ca0ea9d56",
GitTreeState:"clean", BuildDate:"2016-10-21T02:48:38Z",
GoVersion:"go1.6.3", Compiler:"gc", Platform:"linux/amd64"}
error: yaml: line 2: mapping values are not allowed in this context

tessact@tessact-sys-1:~/[some path]$ kubectl create -f kubernetes_configs/frontend.yaml
error: yaml: line 2: mapping values are not allowed in this context
</code>```

The only yaml file i used is

```<code>apiVersion: v1
kind: ReplicationController
metadata:
  name: frontend
  labels:
    name: frontend
spec:
  replicas: 3
  template:
    metadata:
      labels:
        name: frontend
    spec:
      containers:
      - name: trigger
        # Replace  with your project ID or use `make template`
        image: asia.gcr.io/trigger-backend/trigger-backend

        # This setting makes nodes pull the docker image every time before
        # starting the pod. This is useful when debugging, but should be turned
        # off in production.
        imagePullPolicy: Always
        ports:
        - containerPort: 8080

apiVersion: v1
kind: Service
metadata:
  name: frontend
  labels:
    name: frontend
spec:
  type: LoadBalancer
  ports:
  - port: 80
    targetPort: 8080
  selector:
    name: frontend
</code>```

Whatever I try with kubectl it returns this error. What should I do to solve this?

```<code>> tessact@tessact-sys-1:~/developer/trigger-backend-dev/trigger-backend$
> kubectl get service error: yaml: line 2: mapping values are not
> allowed in this context
</code>```

Output of :

```<code>strace kubectl version
</code>```

is here

答:
Just to add...
I have seen this error today after performing a copy/paste operation into my YAML file. The process brought in some whitespace characters that kubectl could not decipher.

If you are unsure, paste the YAML into a text editor first that will show all non-visible characters and make sure they are consistent with the rest of your YAML file.

Body:
Kubectl command alway returns this error yaml: line 2: mapping values are not allowed in this context. Even when i call normal version command, config command, etc. Not sure whats causing this.

tessact@tessact-sys-1:~$ kubectl version
Client Version: version.Info{Major:"1", Minor:"4",
GitVersion:"v1.4.4",
GitCommit:"3b417cc4ccd1b8f38ff9ec96bb50a81ca0ea9d56",
GitTreeState:"clean", BuildDate:"2016-10-21T02:48:38Z",
GoVersion:"go1.6.3", Compiler:"gc", Platform:"linux/amd64"}
error: yaml: line 2: mapping values are not allowed in this context

tessact@tessact-sys-1:~/[some path]$ kubectl create -f kubernetes_configs/frontend.yaml
error: yaml: line 2: mapping values are not allowed in this context

The only yaml file i used is

apiVersion: v1
kind: ReplicationController
metadata:
  name: frontend
  labels:
    name: frontend
spec:
  replicas: 3
  template:
    metadata:
      labels:
        name: frontend
    spec:
      containers:
      - name: trigger
        # Replace  with your project ID or use `make template`
        image: asia.gcr.io/trigger-backend/trigger-backend

        # This setting makes nodes pull the docker image every time before
        # starting the pod. This is useful when debugging, but should be turned
        # off in production.
        imagePullPolicy: Always
        ports:
        - containerPort: 8080

apiVersion: v1
kind: Service
metadata:
  name: frontend
  labels:
    name: frontend
spec:
  type: LoadBalancer
  ports:
  - port: 80
    targetPort: 8080
  selector:
    name: frontend

Whatever I try with kubectl it returns this error. What should I do to solve this?

> tessact@tessact-sys-1:~/developer/trigger-backend-dev/trigger-backend$
> kubectl get service error: yaml: line 2: mapping values are not
> allowed in this context

Output of :

strace kubectl version

is here


问:
Problem with using dynamic allocation in c++
```<code>#include<iostream>
using namespace std;

int d(int num) {
   int dn = num;
   while (num != 0) {
      dn += num % 10;
      num = num / 10;
   }
   return dn;
}

int main() {
   int* arr = new int[10000];
   for (int i = 0; i < 10000; i++) {
      arr[i] = i + 1;
   }
   for (int i = 0; i < 10000; i++) {
      arr[d(i)] = 0;
   }
   for (int i = 0; i < 10000; i++) {
      if (arr[i] > 0) {
         cout << arr[i]-1<<endl;
      }
   }
   delete[] arr;
   return 0;
}
</code>```

I'm tying to code Self Number of D.R. Kaprekar but it doesent show any result in console with dynamic allocation but it does in using of static array.

答:
Your trouble in function

```<code>int d(int num) {
  int dn = num;
  while (num != 0) {
    dn += num % 10;
    num = num / 10;
  }
  return dn;
}
</code>```

Due to, dn = num at start, return walue isn't less than num.
Don't you want to set dn to zero at start?

Body:
#include<iostream>
using namespace std;

int d(int num) {
   int dn = num;
   while (num != 0) {
      dn += num % 10;
      num = num / 10;
   }
   return dn;
}

int main() {
   int* arr = new int[10000];
   for (int i = 0; i < 10000; i++) {
      arr[i] = i + 1;
   }
   for (int i = 0; i < 10000; i++) {
      arr[d(i)] = 0;
   }
   for (int i = 0; i < 10000; i++) {
      if (arr[i] > 0) {
         cout << arr[i]-1<<endl;
      }
   }
   delete[] arr;
   return 0;
}

I'm tying to code Self Number of D.R. Kaprekar but it doesent show any result in console with dynamic allocation but it does in using of static array.

Body:
Your trouble in function

int d(int num) {
  int dn = num;
  while (num != 0) {
    dn += num % 10;
    num = num / 10;
  }
  return dn;
}

Due to, dn = num at start, return walue isn't less than num.
Don't you want to set dn to zero at start?


问:
Using id in place of an NSString
I'm parsing some JSON.

Sometimes the JSON returns an NSNull which i was allowing to go into a string and then i would check the String to see if it contrained the NSNull and then handled it. The code worked as intended but the compiler complained with a warning.

```<code>if ((theMonograph.cautions != nil) && (theMonograph.cautions != [NSNull null]))
{
    //draw string
}
</code>```

In Monograph.h

```<code>NSString *cautions;
@property (nonatomic, retain) NSString *cautions;
</code>```

So I though maybe the correct way to handle it would be to change to an id in the place of the NSString

Monograph.h

```<code>id *cautions;
@property (nonatomic, retain) id *cautions;
</code>```

But this still generated another warning

passing argument 1 of 'setCautions:' from incompatible pointer type

What is the correct way to handle this? I'm guessing letting NSNull go into an NSString object was wrong. But putting an id object in its place didnt seem right.

Many Thanks
-Code

答:
Using NSString is perfect; just modify the condition to

if ((theMonograph.cautions != nil) && (theMonograph.cautions != [NSNull null]) && [theMonograph.cautions length])

Hope it works.

Title: Using id in place of an NSString

Body:
I'm parsing some JSON.

Sometimes the JSON returns an NSNull which i was allowing to go into a string and then i would check the String to see if it contrained the NSNull and then handled it. The code worked as intended but the compiler complained with a warning.

if ((theMonograph.cautions != nil) && (theMonograph.cautions != [NSNull null]))
{
    //draw string
}

In Monograph.h

NSString *cautions;
@property (nonatomic, retain) NSString *cautions;

So I though maybe the correct way to handle it would be to change to an id in the place of the NSString

Monograph.h

id *cautions;
@property (nonatomic, retain) id *cautions;

But this still generated another warning

passing argument 1 of 'setCautions:' from incompatible pointer type

What is the correct way to handle this? I'm guessing letting NSNull go into an NSString object was wrong. But putting an id object in its place didnt seem right.

Many Thanks
-Code


问:
Angular Karma + Jasmine zero specs found
I want to write test cases for existing angular project. I using the default angular configuration but when I run ng test, I get errors in build process and browser opens up and displays zero specs found.

How can I ignore node_modules files for testing. If possible please correct me where I've configured wrong.

test.js

import 'zone.js/dist/zone-testing';
import { getTestBed } from '@angular/core/testing';
import {
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';

declare const require: any;

// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting()
);
// Then we find all the tests.
const context = require.context('./', true, /\.spec\.ts$/);
// And load the modules.
context.keys().map(context);
```

<blockquote>
  <p><code>angular.json</code></p>
</blockquote>

```"test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.spec.json",
            "karmaConfig": "src/karma.conf.js",
            "styles": ["src/styles.css"],
            "scripts": [],
            "assets": ["src/favicon.ico", "src/assets"]
          }
        }
```

<blockquote>
  <p><code>karma.conf.js</code></p>
</blockquote>

<pre class="lang-js prettyprint-override"><code>module.exports = function(config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular-devkit/build-angular/plugins/karma')
    ],
    client: {
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    coverageIstanbulReporter: {
      dir: require('path').join(__dirname, '../coverage'),
      reports: ['html', 'lcovonly'],
      fixWebpackSourcePaths: true
    },
    reporters: ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false
  });
};
</code>```

答:
How can I ignore node_modules files for testing

Add this below line in tsconfig.spec

```<code>"include": [
    "**/*.spec.ts",
    "**/*.d.ts"
  ]
</code>```

Body:
I want to write test cases for existing angular project. I using the default angular configuration but when I run ng test, I get errors in build process and browser opens up and displays zero specs found.

How can I ignore node_modules files for testing. If possible please correct me where I've configured wrong.

test.js

import 'zone.js/dist/zone-testing';
import { getTestBed } from '@angular/core/testing';
import {
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';

declare const require: any;

// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting()
);
// Then we find all the tests.
const context = require.context('./', true, /\.spec\.ts$/);
// And load the modules.
context.keys().map(context);

angular.json

"test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.spec.json",
            "karmaConfig": "src/karma.conf.js",
            "styles": ["src/styles.css"],
            "scripts": [],
            "assets": ["src/favicon.ico", "src/assets"]
          }
        }

karma.conf.js

module.exports = function(config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular-devkit/build-angular'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular-devkit/build-angular/plugins/karma')
    ],
    client: {
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    coverageIstanbulReporter: {
      dir: require('path').join(__dirname, '../coverage'),
      reports: ['html', 'lcovonly'],
      fixWebpackSourcePaths: true
    },
    reporters: ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false
  });
};

Body:
How can I ignore node_modules files for testing

Add this below line in tsconfig.spec

"include": [
    "**/*.spec.ts",
    "**/*.d.ts"
  ]


问:
RTSP h.264 in google chrome browser
After we are moving over to html5 and many browsers like Google chrome bans VLC web plugin....

Is there any way to play h.264 / h.265 Rtsp streams in browsers this days?

答:
Bhargav: I've deleted another answer, please undelete this one.

It's possible with media-stream-library-js
but you'll need to wrap RTSP into a WebSocket with websockify or websockify-nginx-module

Title: RTSP h.264 in google chrome browser