问:
BadRequestKeyError: 400 Bad Request Python Web Scraping
I´m getting the following error on python when I trying to do some scraping:

Traceback (most recent call last):

File "", line 26, in
signin2.fields["ctl06$txtParam_1"].value = '139210'

File "C:\Users\Alvaro
Pabon\Anaconda3\lib\site-packages\werkzeug\datastructures.py", line
781, in getitem
raise exceptions.BadRequestKeyError(key)

BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a
request that this server could not understand.

I provide the html and the python code, what am I doing wrong?

HTML:

```<code>    <form method="post" action="Default.aspx?IdControl=SolicitarReporteUC&TipoProceso=G" id="Form1">
<div class="aspNetHidden">
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKLTE2MjczMjc4MQ9kFgICAw9kFgICBQ9kFgJmD2QWDgIBDxAPFgYeDkRhdGFWYWx1ZUZpZWxkBQpDb2RSZXBvcnRlHg1EYXRhVGV4dEZpZWxkBQdSZXBvcnRlHgtfIURhdGFCb3VuZGdkEBUBI0NlcnRpZmljYWRvIGRlIGhpc3RvcmlhIGxhYm9yYWwgRlBNFQEFMTAwOTUUKwMBZxYBZmQCAw9kFgJmD2QWAgIBD2QWAgIBDw9kFgIeB29uY2xpY2sFdmphdmFzY3JpcHQ6cmV0dXJuIEJ1c2NhckNvblBvc3RCYWNrKCdFbXBsZWFkb19WSVBQJywnQ29kRW1wbGVhZG8nLCdFbXBsZWFkbycsJycsJ2N0bDA2X3R4dFBhcmFtXzEnLCdjdGwwNl90eHREZXNjXzEnKTtkAgcPDxYCHgRUZXh0ZWRkAgkPEA8WAh4HVmlzaWJsZWdkEBUBA1BERhUBA1BERhQrAwFnZGQCCw8PFgIeB0VuYWJsZWRnZGQCDQ8PFgIfBGVkZAIRDzwrAAsBAA8WCB4IRGF0YUtleXMWAB4LXyFJdGVtQ291bnQCAR4JUGFnZUNvdW50AgEeFV8hRGF0YVNvdXJjZUl0ZW1Db3VudAIBZBYCZg9kFgICAg9kFgxmD2QWAgIDDw8WAh4LTmF2aWdhdGVVcmwFOkRlZmF1bHQuYXNweD9JZENvbnRyb2w9UGV0aWNpb25lc1ZlclVDJkNvZFBldGljaW9uPTk4NDI0NjZkZAIBDw8WAh8EBQc5ODQyNDY2ZGQCAg8PFgIfBAUKMDQvMDcvMjAxN2RkAgMPDxYCHwQFLENlcnRpZmljYWRvIGRlIGhpc3RvcmlhIGxhYm9yYWwgRlBNKDEzOTIxMCwpZGQCBA8PFgIfBAUBVGRkAgUPDxYCHwQFCVRlcm1pbmFkb2RkZG9xWba643oqthJTATkgc95Acvr6oJVDDdMGc4QiUOHQ" />
</div>

<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['Form1'];
if (!theForm) {
    theForm = document.Form1;
}
function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
}
//]]>
</script>

<script src="/peoploEL/WebResource.axd?d=Vo5dwRm0erdgUaaz932BKtVNZGJOgXKXcR91FZwwFfehyhj6Sl2EkKnl2mAONakSWUxeINyfjibWOjKY8z8OLswtutIQ6CR4NPqhOOhW3-c1&t=635195493660000000" type="text/javascript"></script>

<script type="text/javascript">
//<![CDATA[
var __cultureInfo = {"name":"es-CO","numberFormat":{"CurrencyDecimalDigits":2,"CurrencyDecimalSeparator":",","IsReadOnly":true,"CurrencyGroupSizes":[3],"NumberGroupSizes":[3],"PercentGroupSizes":[3],"CurrencyGroupSeparator":".","CurrencySymbol":"$","NaNSymbol":"NeuN","CurrencyNegativePattern":14,"NumberNegativePattern":1,"PercentPositivePattern":0,"PercentNegativePattern":0,"NegativeInfinitySymbol":"-Infinito","NegativeSign":"-","NumberDecimalDigits":2,"NumberDecimalSeparator":",","NumberGroupSeparator":".","CurrencyPositivePattern":2,"PositiveInfinitySymbol":"Infinito","PositiveSign":"+","PercentDecimalDigits":2,"PercentDecimalSeparator":",","PercentGroupSeparator":".","PercentSymbol":"%","PerMilleSymbol":"‰","NativeDigits":["0","1","2","3","4","5","6","7","8","9"],"DigitSubstitution":1},"dateTimeFormat":{"AMDesignator":"a.m.","Calendar":{"MinSupportedDateTime":"\/Date(-62135578800000)\/","MaxSupportedDateTime":"\/Date(253402300799999)\/","AlgorithmType":1,"CalendarType":1,"Eras":[1],"TwoDigitYearMax":2029,"IsReadOnly":true},"DateSeparator":"/","FirstDayOfWeek":0,"CalendarWeekRule":0,"FullDateTimePattern":"dddd, dd\u0027 de \u0027MMMM\u0027 de \u0027yyyy hh:mm:ss tt","LongDatePattern":"dddd, dd\u0027 de \u0027MMMM\u0027 de \u0027yyyy","LongTimePattern":"hh:mm:ss tt","MonthDayPattern":"dd MMMM","PMDesignator":"p.m.","RFC1123Pattern":"ddd, dd MMM yyyy HH\u0027:\u0027mm\u0027:\u0027ss \u0027GMT\u0027","ShortDatePattern":"dd/MM/yyyy","ShortTimePattern":"hh:mm tt","SortableDateTimePattern":"yyyy\u0027-\u0027MM\u0027-\u0027dd\u0027T\u0027HH\u0027:\u0027mm\u0027:\u0027ss","TimeSeparator":":","UniversalSortableDateTimePattern":"yyyy\u0027-\u0027MM\u0027-\u0027dd HH\u0027:\u0027mm\u0027:\u0027ss\u0027Z\u0027","YearMonthPattern":"MMMM\u0027 de \u0027yyyy","AbbreviatedDayNames":["dom","lun","mar","mié","jue","vie","sáb"],"ShortestDayNames":["do","lu","ma","mi","ju","vi","sá"],"DayNames":["domingo","lunes","martes","miércoles","jueves","viernes","sábado"],"AbbreviatedMonthNames":["ene","feb","mar","abr","may","jun","jul","ago","sep","oct","nov","dic",""],"MonthNames":["enero","febrero","marzo","abril","mayo","junio","julio","agosto","septiembre","octubre","noviembre","diciembre",""],"IsReadOnly":true,"NativeCalendarName":"calendario gregoriano","AbbreviatedMonthGenitiveNames":["ene","feb","mar","abr","may","jun","jul","ago","sep","oct","nov","dic",""],"MonthGenitiveNames":["enero","febrero","marzo","abril","mayo","junio","julio","agosto","septiembre","octubre","noviembre","diciembre",""]},"eras":[1,"d.C.",null,0]};//]]>
</script>

<script src="/peoploEL/ScriptResource.axd?d=oxaJQOalmF_Pc9FHyAFTk_k6TF1NEbUrjIYsB44pk6WCbYo_nSIw4yk5tC2xEtvEorNRA5gOfFsIU4ZnWzjKxobYxQm7qlMyDI-yMbMSd2l6ZDbJap8N8TY6mfiS7PCqS0ZD_N1nysIMDoEuJENdCQ2&t=23c9c237" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
if (typeof(Sys) === 'undefined') throw new Error('ASP.NET Ajax client-side framework failed to load.');
//]]>
</script>

<div class="aspNetHidden">

    <input type="hidden" name="__SCROLLPOSITIONX" id="__SCROLLPOSITIONX" value="0" />
    <input type="hidden" name="__SCROLLPOSITIONY" id="__SCROLLPOSITIONY" value="0" />
    <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEdAArkW6hVSYy1X/RA+Sj0CGQLGp+bdMCDYaJlV2GIWm9IvBdcfX0kLMsTvDhzcFP+5BCmu+5iWjvwd5K06ry8EbPN8eAu30BFMFNpn4fF9w5RD0sfx0Rt1Zoo22r6RgHWIEvbk+/Q0viP1b4fioHhV6vuLByhWnJD/fsZOTyD54nbDa+qASD48033XmTIh5CNr4axLA/MabVFryGhaiI+QVUeJtZhbNAXh60wJUXNyENePpp0PUjhju74p8tImEJGpMk=" />
</div>
            <TABLE id="Table1" border="0" cellSpacing="0" cellPadding="0" width="80%" align="center"
                height="72%">
                <TR>
                    <TD height="25" vAlign="top" width="165" align="center"></TD>
                    <TD height="25" width="10"></TD>
                    <TD height="25" vAlign="top"></TD>
                </TR>
                <TR>
                    <TD vAlign="top" width="165" align="center">
<LINK rel="stylesheet" type="text/css" href="EstilosWeb.css">
<LINK rel="stylesheet" type="text/css" href="EstilosWeb.css">
<TABLE style="WIDTH: 160px; HEIGHT: 64px" id="tMain" class="main" cellPadding="0" width="160">
    <TR vAlign="top">
        <TD id="NavTd">
            <DIV id="Nav">
                <H4 align="center">Menu
                    <table id="PanelIzquierdoUC1_htbCategorias" cellspacing="0" cellpadding="0" style="border-width:0px;width:160px;border-collapse:collapse;">
    <tr>
        <td><a id="PanelIzquierdoUC1_ConsultarLiquidacion" title="Consulta de Liquidación" href="Default.aspx?IdControl=ConsultaLiquidacionFltUC">Consultar Liquidación</a></td>
    </tr><tr>
        <td><a id="PanelIzquierdoUC1_Reportes" title="Certificado Ing. y Ret." href="Default.aspx?IdControl=ReportesUC">Certificado Ing. y Ret.</a></td>
    </tr><tr>
        <td><a id="PanelIzquierdoUC1_CambiarClave" title="Cambio de Clave" href="Default.aspx?IdControl=CambioClaveUC">Cambio de Clave</a></td>
    </tr><tr>
        <td><a id="PanelIzquierdoUC1_ReportesGeneral" title="Reportes" href="Default.aspx?IdControl=SolicitarReporteUC&TipoProceso=G">Reportes</a></td>
    </tr><tr>
        <td><a id="PanelIzquierdoUC1_CerrarSesion" title="Cerrar Sesion" href="Default.aspx?IdControl=CerrarSesionUC">Cerrar Sesion</a></td>
    </tr>
</table></H4>
            </DIV>
        </TD>
    </TR>
</TABLE>

</TD>
                    <td width="10"> </td>
                    <TD vAlign="top">

                        <div id="pnlCargaUserControl" style="width:100%;">

<LINK href="EstilosWeb.css" type="text/css" rel="stylesheet">
<style type="text/css">
    .style1
    {
        height: 26px;
        width: 36px;
    }
</style>
<TABLE class="FormaTabla" id="Table1" cellSpacing="1" cellPadding="1" width="300" border="0">
    <TR>
        <TD class="FormaEncabezado" colSpan="2">Reportes</TD>
    </TR>
    <TR>
        <TD colSpan="2">
            <P align="center"> </P>
        </TD>
    </TR>
    <TR>
        <TD colSpan="2"><select size="4" name="ctl06$lstReportes" onchange="javascript:setTimeout('__doPostBack(\'ctl06$lstReportes\',\'\')', 0)" id="ctl06_lstReportes" class="FormaInfo" style="height:215px;width:564px;">
        <option selected="selected" value="10095">Certificado de historia laboral FPM</option>

    </select></TD>
    </TR>
    <TR>
        <TD colSpan="2">Parametros</TD>
    </TR>
    <TR>
        <TD style="HEIGHT: 45px" colSpan="2"><table id="ctl06_tbParametros" rules="all" border="1">
        <tr>
            <td>Empleado</td><td><input name="ctl06$txtParam_1" type="text" value="139211" readonly="readonly" onchange="javascript:setTimeout('__doPostBack(\'ctl06$txtParam_1\',\'\')', 0)" onkeypress="if (WebForm_TextBoxKeyHandler(event) == false) return false;" id="ctl06_txtParam_1" Tabla="Empleado_VIPP" CodigoCampo="CodEmpleado" DescripcionCampo="Empleado" Condicion="" TipoDato="N" Parametro="Empleado" /><input type="submit" name="ctl06$btnParam_1" value="..." id="ctl06_btnParam_1" disabled="disabled" class="aspNetDisabled" onclick="javascript:return BuscarConPostBack('Empleado_VIPP','CodEmpleado','Empleado','','ctl06_txtParam_1','ctl06_txtDesc_1');" style="width:25px;" /></td><td><input name="ctl06$txtDesc_1" type="text" value="JUAN DE LOS PALOTES" readonly="readonly" id="ctl06_txtDesc_1" style="width:250px;" /></td>
        </tr>
    </table></TD>
    </TR>
    <TR>
        <TD class="style1">

        </TD>
        <td>
         <P align="center"><select name="ctl06$ddlFormato" id="ctl06_ddlFormato" style="width:104px;">
        <option value="PDF">PDF</option>

    </select> <input type="submit" name="ctl06$btnAceptar" value="Aceptar" id="ctl06_btnAceptar" />
         </P>
        </td>
    </TR>
    <TR>
        <TD colSpan="2">
            <P align="left"><span id="ctl06_lblMensaje" style="color:Red;font-family:Arial;"></span></P>
        </TD>
    </TR>
</TABLE>
<P>
    <input type="submit" name="ctl06$ButActualizar" value="Actualizar" id="ctl06_ButActualizar" /></P>
<P><table class="FormaGrid" cellspacing="0" rules="all" border="1" id="ctl06_dtgDatos" style="border-collapse:collapse;">
        <tr>
            <td> </td><td>CodPeticion</td><td>FechaHora</td><td>Peticion</td><td>Estado</td><td>DetalleEstado</td>
        </tr><tr>
            <td style="white-space:nowrap;">
                     <a id="ctl06_dtgDatos_ctl03_cmdVer" href="javascript:__doPostBack('ctl06$dtgDatos$ctl03$cmdVer','')">Ver</a>

                </td><td>9842466</td><td>04/07/2017</td><td>Certificado(139211,)</td><td>T</td><td>Terminado</td>
        </tr><tr>
            <td colspan="6"><span>1</span></td>
        </tr>
    </table></P>

</div>
                    </TD>
                </TR>
            </TABLE>
</code>```

PYTHON:

```<code>form2 = browser.get_form(id='Form1')
form2["ctl06$txtParam_1"].value = '139211'
form2["ctl06$txtDesc_1"].value = 'JUAN DE LOS POTES'
form2["ctl06$ddlFormato"].value = 'PDF'
form2["ctl06$lstReportes"].value = '10095'
form2["__EVENTTARGET"].value = 'ctl06$dtgDatos$ctl03$cmdVer'
form2["__EVENTARGUMENT"].value = ''
browser.submit_form(signin2)
</code>```

答:
Use python request lib for that

Create Json and pass it through the headers and remember <__EVENTTARGET>
<__EVENTARGUMENT> This previous <> mention parameter always changing after few minute (based on website).

It Will easy if you use POST method and for before sending request check it in POSTMAN once.

```<code>        header = {

            "ctl00$ContentPlaceHolder1$txt_tradename": str(index),
            "ctl00$ContentPlaceHolder1$txtSearchTin": "",
            "ctl00$ContentPlaceHolder1$ddl_dist": 2,
            "ctl00$ContentPlaceHolder1$btnDlrSearch": "Search",
            "__EVENTVALIDATION": token.get("__EVENTVALIDATION", "")
            , "__VIEWSTATEGENERATOR": token.get("__VIEWSTATEGENERATOR"),
            "__VIEWSTATE": token.get("__VIEWSTATE")
        }
        try:
            req = requests.post(url, header)
</code>```

Body:
I´m getting the following error on python when I trying to do some scraping:

Traceback (most recent call last):

File "", line 26, in
signin2.fields["ctl06$txtParam_1"].value = '139210'

File "C:\Users\Alvaro
Pabon\Anaconda3\lib\site-packages\werkzeug\datastructures.py", line
781, in getitem
raise exceptions.BadRequestKeyError(key)

BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a
request that this server could not understand.

I provide the html and the python code, what am I doing wrong?

HTML:

    <form method="post" action="Default.aspx?IdControl=SolicitarReporteUC&TipoProceso=G" id="Form1">

<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKLTE2MjczMjc4MQ9kFgICAw9kFgICBQ9kFgJmD2QWDgIBDxAPFgYeDkRhdGFWYWx1ZUZpZWxkBQpDb2RSZXBvcnRlHg1EYXRhVGV4dEZpZWxkBQdSZXBvcnRlHgtfIURhdGFCb3VuZGdkEBUBI0NlcnRpZmljYWRvIGRlIGhpc3RvcmlhIGxhYm9yYWwgRlBNFQEFMTAwOTUUKwMBZxYBZmQCAw9kFgJmD2QWAgIBD2QWAgIBDw9kFgIeB29uY2xpY2sFdmphdmFzY3JpcHQ6cmV0dXJuIEJ1c2NhckNvblBvc3RCYWNrKCdFbXBsZWFkb19WSVBQJywnQ29kRW1wbGVhZG8nLCdFbXBsZWFkbycsJycsJ2N0bDA2X3R4dFBhcmFtXzEnLCdjdGwwNl90eHREZXNjXzEnKTtkAgcPDxYCHgRUZXh0ZWRkAgkPEA8WAh4HVmlzaWJsZWdkEBUBA1BERhUBA1BERhQrAwFnZGQCCw8PFgIeB0VuYWJsZWRnZGQCDQ8PFgIfBGVkZAIRDzwrAAsBAA8WCB4IRGF0YUtleXMWAB4LXyFJdGVtQ291bnQCAR4JUGFnZUNvdW50AgEeFV8hRGF0YVNvdXJjZUl0ZW1Db3VudAIBZBYCZg9kFgICAg9kFgxmD2QWAgIDDw8WAh4LTmF2aWdhdGVVcmwFOkRlZmF1bHQuYXNweD9JZENvbnRyb2w9UGV0aWNpb25lc1ZlclVDJkNvZFBldGljaW9uPTk4NDI0NjZkZAIBDw8WAh8EBQc5ODQyNDY2ZGQCAg8PFgIfBAUKMDQvMDcvMjAxN2RkAgMPDxYCHwQFLENlcnRpZmljYWRvIGRlIGhpc3RvcmlhIGxhYm9yYWwgRlBNKDEzOTIxMCwpZGQCBA8PFgIfBAUBVGRkAgUPDxYCHwQFCVRlcm1pbmFkb2RkZG9xWba643oqthJTATkgc95Acvr6oJVDDdMGc4QiUOHQ" />

    <input type="hidden" name="__SCROLLPOSITIONX" id="__SCROLLPOSITIONX" value="0" />
    <input type="hidden" name="__SCROLLPOSITIONY" id="__SCROLLPOSITIONY" value="0" />
    <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEdAArkW6hVSYy1X/RA+Sj0CGQLGp+bdMCDYaJlV2GIWm9IvBdcfX0kLMsTvDhzcFP+5BCmu+5iWjvwd5K06ry8EbPN8eAu30BFMFNpn4fF9w5RD0sfx0Rt1Zoo22r6RgHWIEvbk+/Q0viP1b4fioHhV6vuLByhWnJD/fsZOTyD54nbDa+qASD48033XmTIh5CNr4axLA/MabVFryGhaiI+QVUeJtZhbNAXh60wJUXNyENePpp0PUjhju74p8tImEJGpMk=" />

<LINK rel="stylesheet" type="text/css" href="EstilosWeb.css">
<LINK rel="stylesheet" type="text/css" href="EstilosWeb.css">

Menu

        Consultar Liquidación

        Certificado Ing. y Ret.

        Cambio de Clave

        Reportes

        Cerrar Sesion

<LINK href="EstilosWeb.css" type="text/css" rel="stylesheet">

        Reportes

        <select size="4" name="ctl06$lstReportes" onchange="javascript:setTimeout('__doPostBack(\'ctl06$lstReportes\',\'\')', 0)" id="ctl06_lstReportes" class="FormaInfo" style="height:215px;width:564px;">
        <option selected="selected" value="10095">Certificado de historia laboral FPM</option>

    </select>

        Parametros

            Empleado	<input name="ctl06$txtParam_1" type="text" value="139211" readonly="readonly" onchange="javascript:setTimeout('__doPostBack(\'ctl06$txtParam_1\',\'\')', 0)" onkeypress="if (WebForm_TextBoxKeyHandler(event) == false) return false;" id="ctl06_txtParam_1" Tabla="Empleado_VIPP" CodigoCampo="CodEmpleado" DescripcionCampo="Empleado" Condicion="" TipoDato="N" Parametro="Empleado" /><input type="submit" name="ctl06$btnParam_1" value="..." id="ctl06_btnParam_1" disabled="disabled" class="aspNetDisabled" onclick="javascript:return BuscarConPostBack('Empleado_VIPP','CodEmpleado','Empleado','','ctl06_txtParam_1','ctl06_txtDesc_1');" style="width:25px;" />	<input name="ctl06$txtDesc_1" type="text" value="JUAN DE LOS PALOTES" readonly="readonly" id="ctl06_txtDesc_1" style="width:250px;" />

<select name="ctl06$ddlFormato" id="ctl06_ddlFormato" style="width:104px;">
        <option value="PDF">PDF</option>

    </select> <input type="submit" name="ctl06$btnAceptar" value="Aceptar" id="ctl06_btnAceptar" />

    <input type="submit" name="ctl06$ButActualizar" value="Actualizar" id="ctl06_ButActualizar" />

             	CodPeticion	FechaHora	Peticion	Estado	DetalleEstado

                     Ver

                	9842466	04/07/2017	Certificado(139211,)	T	Terminado

            1

PYTHON:

form2 = browser.get_form(id='Form1')
form2["ctl06$txtParam_1"].value = '139211'
form2["ctl06$txtDesc_1"].value = 'JUAN DE LOS POTES'
form2["ctl06$ddlFormato"].value = 'PDF'
form2["ctl06$lstReportes"].value = '10095'
form2["__EVENTTARGET"].value = 'ctl06$dtgDatos$ctl03$cmdVer'
form2["__EVENTARGUMENT"].value = ''
browser.submit_form(signin2)

Body:
Use python request lib for that

Create Json and pass it through the headers and remember <__EVENTTARGET>
<__EVENTARGUMENT> This previous <> mention parameter always changing after few minute (based on website).

It Will easy if you use POST method and for before sending request check it in POSTMAN once.

        header = {

            "ctl00$ContentPlaceHolder1$txt_tradename": str(index),
            "ctl00$ContentPlaceHolder1$txtSearchTin": "",
            "ctl00$ContentPlaceHolder1$ddl_dist": 2,
            "ctl00$ContentPlaceHolder1$btnDlrSearch": "Search",
            "__EVENTVALIDATION": token.get("__EVENTVALIDATION", "")
            , "__VIEWSTATEGENERATOR": token.get("__VIEWSTATEGENERATOR"),
            "__VIEWSTATE": token.get("__VIEWSTATE")
        }
        try:
            req = requests.post(url, header)


来源: stackexchange

问:
How to return an element from the function that return a list in r?
I built my own function like this:

```<code>library(VineCopula)

Matrix <- c(5, 2, 3, 1, 4,
            0, 2, 3, 4, 1,
            0, 0, 3, 4, 1,
            0, 0, 0, 4, 1,
            0, 0, 0, 0, 1)
Matrix <- matrix(Matrix, 5, 5)
family <-par <- par2 <-  list()
for(i in 1:3){
# define R-vine pair-copula family matrix
family[[i]] <- c(0, 1, 3, 4, 4,
            0, 0, 3, 4, 1,
            0, 0, 0, 4, 1,
            0, 0, 0, 0, 3,
            0, 0, 0, 0, 0)
family[[i]] <- matrix(family[[i]], 5, 5)
# define R-vine pair-copula parameter matrix
par[[i]] <- c(0, 0.2, 0.9, 1.5, 3.9,
         0, 0, 1.1, 1.6, 0.9,
         0, 0, 0, 1.9, 0.5,
         0, 0, 0, 0, 4.8,
         0, 0, 0, 0, 0)
par[[i]] <- matrix(par[[i]], 5, 5)
# define second R-vine pair-copula parameter matrix
par2[[i]] <- matrix(0, 5, 5)
}
my_func <- function(Matrix, family, par, par2){
     x <- list()
     for(i in 1:3){
          x[[i]] <- RVineMatrix(Matrix = Matrix,family=family[[i]],par=par[[i]],par2 = par2[[i]])
     }
     x
}
</code>```

This will return me a list. How can I then extract specific element from my function. For example, how I can get my_func$Matrix or my_func$par[1]
Note: family <– par <– par2 <– list(). I also tried return(x[i]$family[i]) and return NULL.

To run the function:

```<code>y <- my_func(Matrix = Matrix,family = family,par = par,par2 = par2)

> y$Matrix
NULL
</code>```

答:
Your function's return value is a listof class RVineMatrix with an element named Matrix. See the help page ?RVineMatrix, section Value. So you need y[[1]]$Matrix.

```<code>y <- my_func(Matrix, family, par, par2)
class(y)
[1] "list"
class(y[[1]])
[1] "RVineMatrix"

y[[1]]$Matrix
     [,1] [,2] [,3] [,4] [,5]
[1,]    5    0    0    0    0
[2,]    2    2    0    0    0
[3,]    3    3    3    0    0
[4,]    1    4    4    4    0
[5,]    4    1    1    1    1
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I built my own function like this:

library(VineCopula)

Matrix <- c(5, 2, 3, 1, 4,
            0, 2, 3, 4, 1,
            0, 0, 3, 4, 1,
            0, 0, 0, 4, 1,
            0, 0, 0, 0, 1)
Matrix <- matrix(Matrix, 5, 5)
family <-par <- par2 <-  list()
for(i in 1:3){
# define R-vine pair-copula family matrix
family[[i]] <- c(0, 1, 3, 4, 4,
            0, 0, 3, 4, 1,
            0, 0, 0, 4, 1,
            0, 0, 0, 0, 3,
            0, 0, 0, 0, 0)
family[[i]] <- matrix(family[[i]], 5, 5)
# define R-vine pair-copula parameter matrix
par[[i]] <- c(0, 0.2, 0.9, 1.5, 3.9,
         0, 0, 1.1, 1.6, 0.9,
         0, 0, 0, 1.9, 0.5,
         0, 0, 0, 0, 4.8,
         0, 0, 0, 0, 0)
par[[i]] <- matrix(par[[i]], 5, 5)
# define second R-vine pair-copula parameter matrix
par2[[i]] <- matrix(0, 5, 5)
}
my_func <- function(Matrix, family, par, par2){
     x <- list()
     for(i in 1:3){
          x[[i]] <- RVineMatrix(Matrix = Matrix,family=family[[i]],par=par[[i]],par2 = par2[[i]])
     }
     x
}

This will return me a list. How can I then extract specific element from my function. For example, how I can get my_func$Matrix or my_func$par[1]
Note: family <– par <– par2 <– list(). I also tried return(x[i]$family[i]) and return NULL.

To run the function:

y <- my_func(Matrix = Matrix,family = family,par = par,par2 = par2)

> y$Matrix
NULL

Body:
Your function's return value is a listof class RVineMatrix with an element named Matrix. See the help page ?RVineMatrix, section Value. So you need y[[1]]$Matrix.

y <- my_func(Matrix, family, par, par2)
class(y)
[1] "list"
class(y[[1]])
[1] "RVineMatrix"

y[[1]]$Matrix
     [,1] [,2] [,3] [,4] [,5]
[1,]    5    0    0    0    0
[2,]    2    2    0    0    0
[3,]    3    3    3    0    0
[4,]    1    4    4    4    0
[5,]    4    1    1    1    1


问:
Need help converting Matlab's bsxfun to numpy
I'm trying to convert a piece of MATLAB code, and this is a line I'm struggling with:

```<code>f = 0
wlab = reshape(bsxfun(@times,cat(3,1-f,f/2,f/2),lab),[],3)
</code>```

I've come up with

```<code>wlab = lab*(np.concatenate((3,1-f,f/2,f/2)))
</code>```

How do I reshape it now?

答:
In Python, if you use numpy you do not need to do any broadcasting, as this is done automatically for you.

For instance, looking at the following code should make it clearer:

```<code>>>> import numpy as np
>>> a = np.array([[1, 2, 3], [3, 4, 5], [6, 7, 8], [9, 10, 100]])
>>> b = np.array([1, 2, 3])
>>>
>>> a
    array([[  1,   2,   3],
           [  3,   4,   5],
           [  6,   7,   8],
           [  9,  10, 100]])
>>> b
array([1, 2, 3])
>>>
>>> a - b
    array([[ 0,  0,  0],
           [ 2,  2,  2],
           [ 5,  5,  5],
           [ 8,  8, 97]])
>>>
</code>```

Body:
I'm trying to convert a piece of MATLAB code, and this is a line I'm struggling with:

f = 0
wlab = reshape(bsxfun(@times,cat(3,1-f,f/2,f/2),lab),[],3)

I've come up with

wlab = lab*(np.concatenate((3,1-f,f/2,f/2)))

How do I reshape it now?

Body:
In Python, if you use numpy you do not need to do any broadcasting, as this is done automatically for you.

For instance, looking at the following code should make it clearer:

>>> import numpy as np
>>> a = np.array([[1, 2, 3], [3, 4, 5], [6, 7, 8], [9, 10, 100]])
>>> b = np.array([1, 2, 3])
>>>
>>> a
    array([[  1,   2,   3],
           [  3,   4,   5],
           [  6,   7,   8],
           [  9,  10, 100]])
>>> b
array([1, 2, 3])
>>>
>>> a - b
    array([[ 0,  0,  0],
           [ 2,  2,  2],
           [ 5,  5,  5],
           [ 8,  8, 97]])
>>>


问:
Installing a puppet module on master with Puppetfile
I'm using R10K to manage my configuration files.

I want to install a puppet module on my master server using a Puppet file.

I go to the branch and add the following to Puppetfile:

```<code>mod 'puppetlabs-certregen', '0.2.0'
</code>```

I then run puppet agent -t on the server. It seems the command is successful, in that the commands in my manifest are run, but when I run puppet certregen healthcheck the module doesn't seem to be installed.

What's the correct way to use the Puppetfile to install a module?

答:
The Puppetfile is similar to a Ruby Gemfile, Python requirements.txt: it lists dependancies which are then installed by a separate tool.

For Puppetfiles, this is r10k.

It's documented here https://puppet.com/docs/pe/2018.1/puppetfile.html

You can also directly download the module with the command line:

```<code>puppet module install puppetlabs-certregen
Notice: Downloading from https://forgeapi.puppet.com ...
Notice: Installing -- do not interrupt ...
/Users/petersouter/.puppetlabs/etc/code/modules
└─┬ puppetlabs-certregen (v0.2.0)
  └── puppetlabs-stdlib (v4.17.1)
</code>```

Note, however, that r10k and puppet module install don't play well together:

Restriction: If you are using Code Manager or r10k, do not install, update, or uninstall modules with the puppet module command. With code management, you must install modules with a Puppetfile. Code management purges modules that were installed with the puppet module command. See the Puppetfile documentation for instructions.

Body:
I'm using R10K to manage my configuration files.

I want to install a puppet module on my master server using a Puppet file.

I go to the branch and add the following to Puppetfile:

mod 'puppetlabs-certregen', '0.2.0'

I then run puppet agent -t on the server. It seems the command is successful, in that the commands in my manifest are run, but when I run puppet certregen healthcheck the module doesn't seem to be installed.

What's the correct way to use the Puppetfile to install a module?

Body:
The Puppetfile is similar to a Ruby Gemfile, Python requirements.txt: it lists dependancies which are then installed by a separate tool.

For Puppetfiles, this is r10k.

It's documented here https://puppet.com/docs/pe/2018.1/puppetfile.html

You can also directly download the module with the command line:

puppet module install puppetlabs-certregen
Notice: Downloading from https://forgeapi.puppet.com ...
Notice: Installing -- do not interrupt ...
/Users/petersouter/.puppetlabs/etc/code/modules
└─┬ puppetlabs-certregen (v0.2.0)
  └── puppetlabs-stdlib (v4.17.1)

Note, however, that r10k and puppet module install don't play well together:

Restriction: If you are using Code Manager or r10k, do not install, update, or uninstall modules with the puppet module command. With code management, you must install modules with a Puppetfile. Code management purges modules that were installed with the puppet module command. See the Puppetfile documentation for instructions.

ContentLicense: CC BY-SA 4.0


问:
Angular - MdDatepicker not working exactly as expected
I'm using two datepickers coming from @angular/material (the first one represents the "FromDate" and the second one represents "ToDate"

I managed to implement it by following instructions provided by Angular Material team on their site but I couldn't find a way to :
- On clicking the input field, the calendar should appear (not just by clicking on the icon)
- Avoid the user to type anything in the input field

For the first problem, nothing is written about this use case on their site, I even tried to play with focus property but didn't work.
For the second problem, the only way I found is to disable the input field (but it's not a solution for me)

Here's what I have in my HTML :

```<code><div class="input-group">
    <input mdInput [mdDatepicker]="datepickerFrom" [max]="endDate">
    <button mdSuffix [mdDatepickerToggle]="datepickerFrom"></button>
    <md-datepicker #datepickerFrom [startAt]="startDate" (selectedChanged)="onSelectStartDate($event)"></md-datepicker>
</div

<div class="input-group">
     <input mdInput [mdDatepicker]="datepickerEnd" [min]="startDate" [disabled]="true" [max]="endDate">
     <button class="input-group-addon" [mdDatepickerToggle]="datepickerEnd"></button>
     <md-datepicker #datepickerEnd [startAt]="startDate" (selectedChanged)="onSelectEndDate($event)"></md-datepicker>
</div>
</code>```

To explain some of the attributes provided, if I select a date in the first datepicker (FromDate), then the second datepicker will begin at this date.

Thank you for your help :)

答:
You can use the open method to open datepicker dialog on focus or click in the input tag.

To disable keyboard input, add an event handler (keydown)="false"

```<code><div class="input-group">
    <input mdInput [mdDatepicker]="datepickerFrom" [max]="endDate" (click)="datepickerFrom.open()" (keydown)="false">
    <button mdSuffix [mdDatepickerToggle]="datepickerFrom"></button>
    <md-datepicker #datepickerFrom [startAt]="startDate" (selectedChanged)="onSelectStartDate($event)"></md-datepicker>
</div

<div class="input-group">
     <input mdInput [mdDatepicker]="datepickerEnd" [min]="startDate" [disabled]="true" [max]="endDate" (click)="datepickerEnd.open()" (keydown)="false">
     <button class="input-group-addon" [mdDatepickerToggle]="datepickerEnd"></button>
     <md-datepicker #datepickerEnd [startAt]="startDate" (selectedChanged)="onSelectEndDate($event)"></md-datepicker>
</div>
</code>```

If you need more reference, you can see this demo

Body:
I'm using two datepickers coming from @angular/material (the first one represents the "FromDate" and the second one represents "ToDate"

I managed to implement it by following instructions provided by Angular Material team on their site but I couldn't find a way to :
- On clicking the input field, the calendar should appear (not just by clicking on the icon)
- Avoid the user to type anything in the input field

For the first problem, nothing is written about this use case on their site, I even tried to play with focus property but didn't work.
For the second problem, the only way I found is to disable the input field (but it's not a solution for me)

Here's what I have in my HTML :

    <input mdInput [mdDatepicker]="datepickerFrom" [max]="endDate">
    <button mdSuffix [mdDatepickerToggle]="datepickerFrom"></button>
    <md-datepicker #datepickerFrom [startAt]="startDate" (selectedChanged)="onSelectStartDate($event)"></md-datepicker>
</div

     <input mdInput [mdDatepicker]="datepickerEnd" [min]="startDate" [disabled]="true" [max]="endDate">
     <button class="input-group-addon" [mdDatepickerToggle]="datepickerEnd"></button>
     <md-datepicker #datepickerEnd [startAt]="startDate" (selectedChanged)="onSelectEndDate($event)"></md-datepicker>

To explain some of the attributes provided, if I select a date in the first datepicker (FromDate), then the second datepicker will begin at this date.

Thank you for your help :)

Body:
You can use the open method to open datepicker dialog on focus or click in the input tag.

To disable keyboard input, add an event handler (keydown)="false"

<div class="input-group">
    <input mdInput [mdDatepicker]="datepickerFrom" [max]="endDate" (click)="datepickerFrom.open()" (keydown)="false">
    <button mdSuffix [mdDatepickerToggle]="datepickerFrom"></button>
    <md-datepicker #datepickerFrom [startAt]="startDate" (selectedChanged)="onSelectStartDate($event)"></md-datepicker>
</div

<div class="input-group">
     <input mdInput [mdDatepicker]="datepickerEnd" [min]="startDate" [disabled]="true" [max]="endDate" (click)="datepickerEnd.open()" (keydown)="false">
     <button class="input-group-addon" [mdDatepickerToggle]="datepickerEnd"></button>
     <md-datepicker #datepickerEnd [startAt]="startDate" (selectedChanged)="onSelectEndDate($event)"></md-datepicker>
</div>

If you need more reference, you can see this demo


问:
karaf & jax-rs : The namespace attribute, 'http://cxf.apache.org/blueprint/jaxrs', of an element information item must be identical
I got some troubles making a jax-rs client with the version 4.0.8 of karaf. Everything is working on an older karaf (tested on a 4.0.3)

Any idea?

How to test/reproduce :

Just create a sample bundle with a blueprint.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:cm="http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.1.0"
           xmlns:jaxrs="http://cxf.apache.org/blueprint/jaxrs"
           xmlns:jaxrs-client="http://cxf.apache.org/blueprint/jaxrs-client"
           xsi:schemaLocation="
  http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd
  http://cxf.apache.org/blueprint/jaxrs http://cxf.apache.org/schemas/blueprint/jaxrs.xsd
  http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.1.0 http://aries.apache.org/schemas/blueprint-cm/blueprint-cm-1.1.0.xsd
  http://cxf.apache.org/blueprint/jaxrs-client http://cxf.apache.org/schemas/blueprint/jaxrs-client.xsd
  ">

    <jaxrs-client:client id="testClient"
                  serviceClass="org.test..."
                  address="{url}">

    </jaxrs-client:client>
</blueprint>
</code>```

Stacktrace:

```<code>org.xml.sax.SAXParseException: src-import.3.1: The namespace attribute, 'xxx://cxf.apache.org/blueprint/jaxrs', of an <import> element information item must be identical to the targetNamespace attribute, 'xxx://cxf.apache.org/jaxrs', of the imported document.

2017-06-26 14:58:40,024 | WARN  | nsole user karaf | NamespaceHandlerRegistryImpl     | 12 - org.apache.aries.blueprint.core - 1.7.1 | NamespaceHandler org.apache.cxf.jaxrs.client.blueprint.JAXRSBPNam espaceHandler is behaving badly and should be fixed
2017-06-26 14:58:40,041 | WARN  | nsole user karaf | NamespaceHandlerRegistryImpl     | 12 - org.apache.aries.blueprint.core - 1.7.1 | Unable to find namespace handler for ://cxf.apache.org/configuration/beans
2017-06-26 14:58:40,100 | WARN  | nsole user karaf | NamespaceHandlerRegistryImpl     | 12 - org.apache.aries.blueprint.core - 1.7.1 | Unable to find namespace handler for ://cxf.apache.org/blueprint/jaxrs
2017-06-26 14:58:40,123 | ERROR | nsole user karaf | BlueprintContainerImpl           | 12 - org.apache.aries.blueprint.core - 1.7.1 | Unable to start blueprint container for bundle /1.0.0.SNAPSHOT
org.xml.sax.SAXParseException: src-import.3.1: The namespace attribute, '://cxf.apache.org/blueprint/jaxrs', of an <import> element information item must be identical to the targetNamespace attribute, '://cxf.apache.org/jaxrs', of the imported document.
    at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)[:]
    at org.apache.xerces.util.ErrorHandlerWrapper.error(Unknown Source)[:]
    at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)[:]
    at org.apache.xerces.impl.xs.traversers.XSDHandler.reportSchemaError(Unknow
</code>```

答:
As mentionned in https://issues.apache.org/jira/browse/ARIES-1540 and https://issues.apache.org/jira/browse/CXF-7183, CXF Blueprint namespace don't work well with blueprint-core 1.7.x.

Try to update the cxf version that you are using. Try those versions 3.1.10, 3.0.13, 3.2.0 or above.

```<code><dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-frontend-jaxrs</artifactId>
    <version>3.1.11 for example</version>
</dependency>
</code>```

Don't forget to check that the deployed version of CXF is also 3.1.10, 3.0.13, 3.2.0 or above. You can tap feature:list | grep cxf in your karaf command line.

Body:
I got some troubles making a jax-rs client with the version 4.0.8 of karaf. Everything is working on an older karaf (tested on a 4.0.3)

Any idea?

How to test/reproduce :

Just create a sample bundle with a blueprint.xml

<?xml version="1.0" encoding="UTF-8"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:cm="http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.1.0"
           xmlns:jaxrs="http://cxf.apache.org/blueprint/jaxrs"
           xmlns:jaxrs-client="http://cxf.apache.org/blueprint/jaxrs-client"
           xsi:schemaLocation="
  http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd
  http://cxf.apache.org/blueprint/jaxrs http://cxf.apache.org/schemas/blueprint/jaxrs.xsd
  http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.1.0 http://aries.apache.org/schemas/blueprint-cm/blueprint-cm-1.1.0.xsd
  http://cxf.apache.org/blueprint/jaxrs-client http://cxf.apache.org/schemas/blueprint/jaxrs-client.xsd
  ">

    <jaxrs-client:client id="testClient"
                  serviceClass="org.test..."
                  address="{url}">

    </jaxrs-client:client>
</blueprint>

Stacktrace:

org.xml.sax.SAXParseException: src-import.3.1: The namespace attribute, 'xxx://cxf.apache.org/blueprint/jaxrs', of an <import> element information item must be identical to the targetNamespace attribute, 'xxx://cxf.apache.org/jaxrs', of the imported document.

2017-06-26 14:58:40,024 | WARN  | nsole user karaf | NamespaceHandlerRegistryImpl     | 12 - org.apache.aries.blueprint.core - 1.7.1 | NamespaceHandler org.apache.cxf.jaxrs.client.blueprint.JAXRSBPNam espaceHandler is behaving badly and should be fixed
2017-06-26 14:58:40,041 | WARN  | nsole user karaf | NamespaceHandlerRegistryImpl     | 12 - org.apache.aries.blueprint.core - 1.7.1 | Unable to find namespace handler for ://cxf.apache.org/configuration/beans
2017-06-26 14:58:40,100 | WARN  | nsole user karaf | NamespaceHandlerRegistryImpl     | 12 - org.apache.aries.blueprint.core - 1.7.1 | Unable to find namespace handler for ://cxf.apache.org/blueprint/jaxrs
2017-06-26 14:58:40,123 | ERROR | nsole user karaf | BlueprintContainerImpl           | 12 - org.apache.aries.blueprint.core - 1.7.1 | Unable to start blueprint container for bundle /1.0.0.SNAPSHOT
org.xml.sax.SAXParseException: src-import.3.1: The namespace attribute, '://cxf.apache.org/blueprint/jaxrs', of an <import> element information item must be identical to the targetNamespace attribute, '://cxf.apache.org/jaxrs', of the imported document.
    at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)[:]
    at org.apache.xerces.util.ErrorHandlerWrapper.error(Unknown Source)[:]
    at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source)[:]
    at org.apache.xerces.impl.xs.traversers.XSDHandler.reportSchemaError(Unknow

Body:
As mentionned in https://issues.apache.org/jira/browse/ARIES-1540 and https://issues.apache.org/jira/browse/CXF-7183, CXF Blueprint namespace don't work well with blueprint-core 1.7.x.

Try to update the cxf version that you are using. Try those versions 3.1.10, 3.0.13, 3.2.0 or above.

<dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-frontend-jaxrs</artifactId>
    <version>3.1.11 for example</version>
</dependency>

Don't forget to check that the deployed version of CXF is also 3.1.10, 3.0.13, 3.2.0 or above. You can tap feature:list | grep cxf in your karaf command line.


问:
Dispatch queue from another queue in laravel 5.1
enter code hereI'm trying to dispatch queue from another queue in laravel rightnow. So for example I have created a job like this :

```<code>class CandidateQueue extends Job implements SelfHandling
{
    protected $request;
    public function __construct($request)
    {

        $this->request = $request;
    }

 public function handle()
 {
      ....
      $this->dispatch($queueEmail);

    }
}
</code>```

The problem is when executing $this->dispatch(), laravel said "Call to undefined method ....::dispatch()". So How do I trigger this queue from current queue ?

Thanks in advance

答:
Old question, but how I did was instead of </p>

```<code>$this->dipatch(new queueEmail);
</code>```

<p>I did </p>

```<code>dispatch(new queueEmail);
</code>```

Body:
enter code hereI'm trying to dispatch queue from another queue in laravel rightnow. So for example I have created a job like this :

class CandidateQueue extends Job implements SelfHandling
{
    protected $request;
    public function __construct($request)
    {

        $this->request = $request;
    }

 public function handle()
 {
      ....
      $this->dispatch($queueEmail);

    }
}

The problem is when executing $this->dispatch(), laravel said "Call to undefined method ....::dispatch()". So How do I trigger this queue from current queue ?

Thanks in advance

Body:
Old question, but how I did was instead of

$this->dipatch(new queueEmail);

I did

dispatch(new queueEmail);


问:
What is the purpose of setting a client character set when connecting to mySQL in PHP?
Using mysqli I might do:

```<code>$mysqli = new mysqli(...);
$mysqli->set_charset("utf8");
</code>```

I assume that $mysqli->get_charset gets the current setting which is otherwise set by this.

This is the character set used for the client-server connection (PHP to talk to the MySQL server) - not the collation on the database I believe?

What is the significance of this? What is it used for? If there is a chunk of utf8 encoded data being passed from PHP to the MySQL Server (say in an INSERT query) what difference will this setting make? If this setting was latin1 would it matter?

Should it be the same as the collation used in the database?

答:
do you use notepadd++ ? if you can see the images in notepadd ++ in dependence of encode is show "í" ... mysql set_charset work at same

enter image description here

enter image description here

Body:
Using mysqli I might do:

$mysqli = new mysqli(...);
$mysqli->set_charset("utf8");

I assume that $mysqli->get_charset gets the current setting which is otherwise set by this.

This is the character set used for the client-server connection (PHP to talk to the MySQL server) - not the collation on the database I believe?

What is the significance of this? What is it used for? If there is a chunk of utf8 encoded data being passed from PHP to the MySQL Server (say in an INSERT query) what difference will this setting make? If this setting was latin1 would it matter?

Should it be the same as the collation used in the database?


问:
EFCore, many-to-many, DB First, navigation properties not working
I am trying to map to an existing database. When I use the below code and pull a list of results for a given entity, I get back the results I expect.

However, when I attempt to add .Include(x => x.Book) to a simple list query against the UserBook table, my result set returns empty.

```<code>[Table("User")]
public class User
{
    [Key]
    public Guid UserId { get; set; }
    public string UserName{ get; set; }

    // Reference
    public ICollection<UserBook> UserBooks { get; set; }
}

[Table("Book")]
public class Book
{
    [Key]
    public Guid BookId { get; set; }
    public string BookName{ get; set; }

    // Reference
    public ICollection<UserBook> UserBooks { get; set; }
}

[Table("UserBook")]
public class UserBook
{
    public Guid UserId { get; set; }
    public Guid BookId { get; set; }
    public int PermissionMask { get; set; }
    public bool Deleted { get; set; }

    // Ref
    public User User { get; set; }
    public Book Book { get; set; }
}
</code>```

I'm following the instructions layed out here: http://www.learnentityframeworkcore.com/configuration/many-to-many-relationship-configuration

To better illustrate the issue, here are the queries I'm using:

```<code>// Returns 1,000+ rows.
_context.UserBooks.ToList();

// Returns 1 row
_context.UserBooks
    .Where(x => x.UserId == "SomeGuid")
    .ToList();

// Returns 0 rows
_context.UserBooks
    .Include(x => x.Book)
    .Where(x => x.UserId == "SomeGuid")
    .ToList();

// Returns 0 rows
_context.UserBooks.Include(x => x.Book).ToList();
</code>```

答: Your mapping indicates a non-nullable foreign key (so EF will generate an inner join in the query). Try changing datatype on the foreign keys from Guid to Guid? and try again.</p>

Body:
I am trying to map to an existing database. When I use the below code and pull a list of results for a given entity, I get back the results I expect.

However, when I attempt to add .Include(x => x.Book) to a simple list query against the UserBook table, my result set returns empty.

[Table("User")]
public class User
{
    [Key]
    public Guid UserId { get; set; }
    public string UserName{ get; set; }

    // Reference
    public ICollection<UserBook> UserBooks { get; set; }
}

[Table("Book")]
public class Book
{
    [Key]
    public Guid BookId { get; set; }
    public string BookName{ get; set; }

    // Reference
    public ICollection<UserBook> UserBooks { get; set; }
}

[Table("UserBook")]
public class UserBook
{
    public Guid UserId { get; set; }
    public Guid BookId { get; set; }
    public int PermissionMask { get; set; }
    public bool Deleted { get; set; }

    // Ref
    public User User { get; set; }
    public Book Book { get; set; }
}

I'm following the instructions layed out here: http://www.learnentityframeworkcore.com/configuration/many-to-many-relationship-configuration

To better illustrate the issue, here are the queries I'm using:

// Returns 1,000+ rows.
_context.UserBooks.ToList();

// Returns 1 row
_context.UserBooks
    .Where(x => x.UserId == "SomeGuid")
    .ToList();

// Returns 0 rows
_context.UserBooks
    .Include(x => x.Book)
    .Where(x => x.UserId == "SomeGuid")
    .ToList();

// Returns 0 rows
_context.UserBooks.Include(x => x.Book).ToList();


问:
Jsmin on folder with subfolders
I am running jsmin to compress all the javascript files of my ASP.Net web application as a postbuild event in the csproj file like this:

"JsMin.exe"
  "$(ProjectDir)script"
  "$(ProjectDir)script\minified.js"

This was working fine when I kept all js files in the root of the script folder. But as it was starting to become alot of files in this folder, I decided to divide the files into subfolders. Now it seems that jsmin only fetches the js files in the root folder, and I cannot see that it has any option to include files in sub-folders. Does anyone have a good solution for a situation like this? Would seem to me that it should be a pretty common thing to do, so that is why I was a bit surprised it was not a parameter to jsmin.exe enabling sub-folders.

答:
You should be able to use DOS' for command to do that:

```<code>for /R "$(ProjectDir)scripts/debug" %s in (*.js) do JsMin.exe %s > "$(ProjectDir)scripts/release/%~ns.min.js"
</code>```

That assumes the scripts are in (or in directories within) a directory named ~/scripts/debug and minifies them to ~/scripts/release with the .js replaced by .min.js.

I've tested that in CMD, but not as a build event in VS.  So, you may need to tweak the syntax slightly.

ContentLicense: CC BY-SA 2.5

Title: Jsmin on folder with subfolders

Body:
You should be able to use DOS' for command to do that:

for /R "$(ProjectDir)scripts/debug" %s in (*.js) do JsMin.exe %s > "$(ProjectDir)scripts/release/%~ns.min.js"

That assumes the scripts are in (or in directories within) a directory named ~/scripts/debug and minifies them to ~/scripts/release with the .js replaced by .min.js.

I've tested that in CMD, but not as a build event in VS.  So, you may need to tweak the syntax slightly.


问:
Is it possible to achieve USB baud rate bigger than 115200 baud on Android?
I am building an Android app that communicates via USB OTG with an Arduino Nano. I'm trying to send data from the Arduino to my phone. My app uses this library. At baud rates <= 115200 Baud it works properly, but if I set the rate for example 230400 Baud, the UsbSerialPort throws an IOException, saying that "Baud rate 230400 currently not supported".
However, between the Arduino and the computer, baud rates works up to 2 MBaud with the same Arduino sketch.
My question is: Is there any way to reach higher baud rate than 115200 Baud?</p>

答:
Yes you can achieve USB baud rate bigger than 115200, these are the supported values:</p>

```<code>            case 300:
                baudrate=0x2710;
                break;
            case 600:
                baudrate=0x1388;
                break;
            case 1200:
                baudrate=0x09C4;
                break;
            case 2400:
                baudrate=0x0271;
                break;
            case 4800:
                baudrate=0x4138;
                break;
            case 9600:
                baudrate=0x4138;
                break;
            case 19200:
                baudrate=0x809C;
                break;
            case 38400:
                baudrate=0xC04E;
                break;
            case 57600:
                baudrate=0x0034;
                break;
            case 115200:
                baudrate=0x001A;
                break;
            case 460800:
                baudrate=0x4006;
                break;
            case 921600:
</code>```

Body:
Yes you can achieve USB baud rate bigger than 115200, these are the supported values:

            case 300:
                baudrate=0x2710;
                break;
            case 600:
                baudrate=0x1388;
                break;
            case 1200:
                baudrate=0x09C4;
                break;
            case 2400:
                baudrate=0x0271;
                break;
            case 4800:
                baudrate=0x4138;
                break;
            case 9600:
                baudrate=0x4138;
                break;
            case 19200:
                baudrate=0x809C;
                break;
            case 38400:
                baudrate=0xC04E;
                break;
            case 57600:
                baudrate=0x0034;
                break;
            case 115200:
                baudrate=0x001A;
                break;
            case 460800:
                baudrate=0x4006;
                break;
            case 921600:


问:
Dropping files onto the app's dock icon works except for proxy icons
I want to be able to accept drops on my app's dock icon from files, URLs, and text.  Since files (public.file-url) are a subtype of URL (public.url), I added just two Services entries to my Info.plist:

```<code>Services
  Item 0 (processURL)
    Instance method Name = processURL
    Send Types
      Item 0 = public.url
    Menu
      Menu item title = Process URL
  Item 1 (processString)
    Instance method Name = processString
    Send Types
      Item 0 = public.plain-text
    Menu
      Menu item title = Process Text
</code>```

Then I made my -applicationDidFinishLaunching call [NSApp setServicesProvider: self], and wrote a couple methods (-processString:userData:error and -processURL:userData:error) there in my application delegate.  The app icon now accepts drops of all three types.  In the -processURL:... method, it's easy to check if it's a local file or not, so that handles both of those cases.

One case still eludes me, though.  When I try dragging a window's proxy icon to the app, it highlights the icon as if it can accept the drop, but then my method isn't called.

I tried dropping proxy icons from Xcode, Terminal, Preview, and some third-party apps: none would call my services method.  But strangely, a proxy icon dropped from the Finder worked fine.

I tried changing public.url to public.item (the base type of the physical hierarchy), but my method is still not called for non-Finder proxy icons.

When the Finder successfully drops a proxy icon on my app, the pboard -types it provides are:

"public.file-url",

"CorePasteboardFlavorType 0x6675726C",

"dyn.ah62d4rv4gu8y6y4grf0gn5xbrzw1gydcr7u1e3cytf2gn",

NSFilenamesPboardType,

"dyn.ah62d4rv4gu8yc6durvwwaznwmuuha2pxsvw0e55bsmwca7d3sbwu",

"Apple URL pasteboard type"

I tried using each of these directly as the "Send Types".  "public.file-url" and "NSFilenamesPboardType" highlight the icon as if it'll accept the drop, but don't.  The others, unsurprisingly, don't even highlight the dock icon.

I can't find any reference to proxy icons having a different UTI than normal files.  Do they?  That would be weird.

I know this must be possible, because I can drag proxy icons from any window onto a Terminal window.  What am I missing?

UPDATE: From an NSView, if I -registerForDraggedTypes including "public.url", I do get drops of proxy icons from all apps, with exactly the same -types list as from the Finder, listed above.  So it's clearly something special to receiving drops via the dock icon.  This should still be possible somehow: you can drag a proxy icon from a (non-Finder) window (e.g., an .xcworkspace from Xcode) onto the Terminal dock window, and it catches that just fine.

答:
Swift 4 for your app delegate</p>

```<code>func application(_ sender: NSApplication, openFile: String) -> Bool {
    Swift.print("sender \(sender) file \(openFile)")
    return true
}

func application(_ sender: NSApplication, openFiles: [String]) {
    Swift.print("sender \(sender) list \(openFiles)")
    // Create a FileManager instance
    let fileManager = FileManager.default

    for path in openFiles {

        do {
            let files = try fileManager.contentsOfDirectory(atPath: path)
            for file in files {
                _ = self.application(sender, openFile: file)// void return
            }
        }
        catch let error as NSError {
            print("Yoink \(error.localizedDescription)")
        }
    }
}
</code>```

Body:
I want to be able to accept drops on my app's dock icon from files, URLs, and text.  Since files (public.file-url) are a subtype of URL (public.url), I added just two Services entries to my Info.plist:

Services
  Item 0 (processURL)
    Instance method Name = processURL
    Send Types
      Item 0 = public.url
    Menu
      Menu item title = Process URL
  Item 1 (processString)
    Instance method Name = processString
    Send Types
      Item 0 = public.plain-text
    Menu
      Menu item title = Process Text

Then I made my -applicationDidFinishLaunching call [NSApp setServicesProvider: self], and wrote a couple methods (-processString:userData:error and -processURL:userData:error) there in my application delegate.  The app icon now accepts drops of all three types.  In the -processURL:... method, it's easy to check if it's a local file or not, so that handles both of those cases.

One case still eludes me, though.  When I try dragging a window's proxy icon to the app, it highlights the icon as if it can accept the drop, but then my method isn't called.

I tried dropping proxy icons from Xcode, Terminal, Preview, and some third-party apps: none would call my services method.  But strangely, a proxy icon dropped from the Finder worked fine.

I tried changing public.url to public.item (the base type of the physical hierarchy), but my method is still not called for non-Finder proxy icons.

When the Finder successfully drops a proxy icon on my app, the pboard -types it provides are:

"public.file-url",

"CorePasteboardFlavorType 0x6675726C",

"dyn.ah62d4rv4gu8y6y4grf0gn5xbrzw1gydcr7u1e3cytf2gn",

NSFilenamesPboardType,

"dyn.ah62d4rv4gu8yc6durvwwaznwmuuha2pxsvw0e55bsmwca7d3sbwu",

"Apple URL pasteboard type"

I tried using each of these directly as the "Send Types".  "public.file-url" and "NSFilenamesPboardType" highlight the icon as if it'll accept the drop, but don't.  The others, unsurprisingly, don't even highlight the dock icon.

I can't find any reference to proxy icons having a different UTI than normal files.  Do they?  That would be weird.

I know this must be possible, because I can drag proxy icons from any window onto a Terminal window.  What am I missing?

UPDATE: From an NSView, if I -registerForDraggedTypes including "public.url", I do get drops of proxy icons from all apps, with exactly the same -types list as from the Finder, listed above.  So it's clearly something special to receiving drops via the dock icon.  This should still be possible somehow: you can drag a proxy icon from a (non-Finder) window (e.g., an .xcworkspace from Xcode) onto the Terminal dock window, and it catches that just fine.

Body:
Swift 4 for your app delegate

func application(_ sender: NSApplication, openFile: String) -> Bool {
    Swift.print("sender \(sender) file \(openFile)")
    return true
}

func application(_ sender: NSApplication, openFiles: [String]) {
    Swift.print("sender \(sender) list \(openFiles)")
    // Create a FileManager instance
    let fileManager = FileManager.default

    for path in openFiles {

        do {
            let files = try fileManager.contentsOfDirectory(atPath: path)
            for file in files {
                _ = self.application(sender, openFile: file)// void return
            }
        }
        catch let error as NSError {
            print("Yoink \(error.localizedDescription)")
        }
    }
}


问:
Python PyMongo Count Occurrences of Array Item
The values I need to count are an array of values so rather than $myField being the key to an item, it's the array elements I need to count so the number of corn, wheat, barley in all the documents.

```<code>"myField": [
  "corn",
  "wheat"
],
</code>```

This is the code for a single item:

```<code>for result in c.aggregate([{
    "$group": {
        "_id": "$myField",
        "count": {"$sum": 1}
    }
}]):
    print("%s: %d" % (result["_id"], result["count"]))
</code>```

答:
Now it's time for $unwind, which transforms an array of values into a series of documents, each with a single value where the array had been:

```<code>c = MongoClient().test.collection
c.delete_many({})
c.insert_many([
    {"myField": ["corn", "wheat"]},
    {"myField": ["corn", "barley"]},
    {"myField": ["hops"]},
])

for result in c.aggregate([{
    "$unwind": "$myField"
}, {
    "$group": {
        "_id": "$myField",
        "count": {"$sum": 1}
    }
}]):
    print("%s: %d" % (result["_id"], result["count"]))
</code>```

The output:

```<code>barley: 1
wheat: 1
hops: 1
corn: 2
</code>```

Body:
The values I need to count are an array of values so rather than $myField being the key to an item, it's the array elements I need to count so the number of corn, wheat, barley in all the documents.

"myField": [
  "corn",
  "wheat"
],

This is the code for a single item:

for result in c.aggregate([{
    "$group": {
        "_id": "$myField",
        "count": {"$sum": 1}
    }
}]):
    print("%s: %d" % (result["_id"], result["count"]))

Body:
Now it's time for $unwind, which transforms an array of values into a series of documents, each with a single value where the array had been:

c = MongoClient().test.collection
c.delete_many({})
c.insert_many([
    {"myField": ["corn", "wheat"]},
    {"myField": ["corn", "barley"]},
    {"myField": ["hops"]},
])

for result in c.aggregate([{
    "$unwind": "$myField"
}, {
    "$group": {
        "_id": "$myField",
        "count": {"$sum": 1}
    }
}]):
    print("%s: %d" % (result["_id"], result["count"]))

The output:

barley: 1
wheat: 1
hops: 1
corn: 2


问:
Image starts rotating from starting position after one click
I have an image which is rotated by 36°.
I used setFillAfter() and setFillEnabled(). It's saving the position but if I rotate it again it is starting from the original position. I want it to start from the position it was after rotation.</p>

```<code>Animation animation = new Animation (0,36, Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
animation.setDuration(3000);
animation.setInterpolator(new LinearInterpolator());
animation.setFillAfter(true);

myImage.startAnimation(animation);
</code>```

答: For that after performing rotation set x y coordinate of image to new position where it got rotated ...</p>

Body:
I have an image which is rotated by 36°.
I used setFillAfter() and setFillEnabled(). It's saving the position but if I rotate it again it is starting from the original position. I want it to start from the position it was after rotation.

Animation animation = new Animation (0,36, Animation.RELATIVE_TO_SELF,0.5f,Animation.RELATIVE_TO_SELF,0.5f);
animation.setDuration(3000);
animation.setInterpolator(new LinearInterpolator());
animation.setFillAfter(true);

myImage.startAnimation(animation);


问:
Two step SQL Statement in only one SQL
I want to perform a efficent SQL-statement, but I don't know how to build the query correctly.

I have the following tables:

```<code>t1(user_id, test_id, module_id, save_id)
t2(save_id, answer_id)
</code>```

save_id from t2 is a foreign key for t1.save_id

So some entries:

```<code>T1:
1, 3, 4, 40
1, 5, 33, 80
2, 5, 33, 90
2, 6, 7, 82
T2:
80, A2
</code>```

So now I want all user_ids and the value of the answer_id, which have an entry for test_id=3 and module_id=4 (only these users!). The value of the searched answer is always from test_id=5 and module_id=33, the only variable thing is the save_id of the answer. I think, this can be linked through a normal JOIN, but how can I isolate only users, for who a entry exists with test_id=3 and module_id=4. In this example I only want to get user 1, user 2 is not relevant, because there is noch entry for test_id=3 and module_id=4.

答:
Try this:</p>

```<code>SELECT
 t1.user_id
 ,t2.answer_id
 FROM t1
 LEFT JOIN t2 ON t1.save_id=t2.save_id
 WHERE t1.test_id=3
 AND t1.module_id=4;
</code>```

Title: Two step SQL Statement in only one SQL

Body:
I want to perform a efficent SQL-statement, but I don't know how to build the query correctly.

I have the following tables:

t1(user_id, test_id, module_id, save_id)
t2(save_id, answer_id)

save_id from t2 is a foreign key for t1.save_id

So some entries:

T1:
1, 3, 4, 40
1, 5, 33, 80
2, 5, 33, 90
2, 6, 7, 82
T2:
80, A2

So now I want all user_ids and the value of the answer_id, which have an entry for test_id=3 and module_id=4 (only these users!). The value of the searched answer is always from test_id=5 and module_id=33, the only variable thing is the save_id of the answer. I think, this can be linked through a normal JOIN, but how can I isolate only users, for who a entry exists with test_id=3 and module_id=4. In this example I only want to get user 1, user 2 is not relevant, because there is noch entry for test_id=3 and module_id=4.

Body:
Try this:

SELECT
 t1.user_id
 ,t2.answer_id
 FROM t1
 LEFT JOIN t2 ON t1.save_id=t2.save_id
 WHERE t1.test_id=3
 AND t1.module_id=4;


问:
Wrongly classified cases in a binary classification challenge (in keras)
The below defined neural network is used in order to classify the dataset seen in the image: .

Simulation statistics suggests that the classification accuracy is 50%, so my question is how do i know which cases of the dataset where not classified correctly?

```<code>from keras.models import Sequential
from keras.layers import Dense
from sklearn.cross_validation import train_test_split
import numpy
# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)

dataset = numpy.loadtxt("sorted output.csv", delimiter=",")
# split into input (X) and output (Y) variables
X = dataset[:,0:3]
Y = dataset[:,3]
# split into 67% for train and 33% for test
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.33, random_state=seed)
# create model
model = Sequential()
model.add(Dense(12, input_dim=3, init='uniform', activation='relu'))
model.add(Dense(3, init='uniform', activation='relu'))
model.add(Dense(1, init='uniform', activation='sigmoid'))
# Compile model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
# Fit the model
model.fit(X_train, y_train, validation_data=(X_test,y_test), nb_epoch=150, batch_size=10)
</code>```

答:
Compare model.predict(X_train) with y_train. In order to do that, you can add the rows

```<code>train_prediction=np.round(model.predict(X_train)).reshape(-1)
train_prediction=train_prediction.astype(int)
</code>```

to the end of your code. Then you can look at the nonzero entries in train_prediction-y_train. The positions of these entries are the places where the model made missclassification.

The reason for the np.round is that your last activation function is sigmoid. This means that values that are closer to 0 are classified as 0, and those that are closer to 1 are classified as 1.

Body:
The below defined neural network is used in order to classify the dataset seen in the image: .

Simulation statistics suggests that the classification accuracy is 50%, so my question is how do i know which cases of the dataset where not classified correctly?

from keras.models import Sequential
from keras.layers import Dense
from sklearn.cross_validation import train_test_split
import numpy
# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)

dataset = numpy.loadtxt("sorted output.csv", delimiter=",")
# split into input (X) and output (Y) variables
X = dataset[:,0:3]
Y = dataset[:,3]
# split into 67% for train and 33% for test
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.33, random_state=seed)
# create model
model = Sequential()
model.add(Dense(12, input_dim=3, init='uniform', activation='relu'))
model.add(Dense(3, init='uniform', activation='relu'))
model.add(Dense(1, init='uniform', activation='sigmoid'))
# Compile model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
# Fit the model
model.fit(X_train, y_train, validation_data=(X_test,y_test), nb_epoch=150, batch_size=10)

Body:
Compare model.predict(X_train) with y_train. In order to do that, you can add the rows

train_prediction=np.round(model.predict(X_train)).reshape(-1)
train_prediction=train_prediction.astype(int)

to the end of your code. Then you can look at the nonzero entries in train_prediction-y_train. The positions of these entries are the places where the model made missclassification.

The reason for the np.round is that your last activation function is sigmoid. This means that values that are closer to 0 are classified as 0, and those that are closer to 1 are classified as 1.


问:
cannot resolve symbol AlertDialog
This is the code in which i used AlertDialog, and it says symbol cant be resolved? how to resolve this error? what is the alternative for this?
and can anyone suggest a good and working tutorial for mysql php android ?
thanks in advance!!

```<code>public class BackgroundWorker extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker (Context ctx) {
    context = ctx;
}
@Override
protected String doInBackground(String... params) {
    String type = params[0];
    String login_url = "http://192.168.1.6/login.php";
    if(type.equals("login")) {
        try {
            String user_name = params[1];
            String password = params[2];
            URL url = new URL(login_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("user_name","UTF-8")+"="+URLEncoder.encode(user_name,"UTF-8")+"&"
                    +URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
            String result="";
            String line="";
            while((line = bufferedReader.readLine())!= null) {
                result += line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return result;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

@Override
protected void onPreExecute() {
    alertDialog = new AlertDialog.Builder(context).create();
    alertDialog.setTitle("Login Status");
}

@Override
protected void onPostExecute(String result) {
    alertDialog.setMessage(result);
    alertDialog.show();
}

@Override
protected void onProgressUpdate(Void... values) {
    super.onProgressUpdate(values);
}
</code>```

}

答:
import this class AlertDialog</p>

```<code>import android.app.AlertDialog;
</code>```

Title: cannot resolve symbol AlertDialog

Body:
This is the code in which i used AlertDialog, and it says symbol cant be resolved? how to resolve this error? what is the alternative for this?
and can anyone suggest a good and working tutorial for mysql php android ?
thanks in advance!!

public class BackgroundWorker extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker (Context ctx) {
    context = ctx;
}
@Override
protected String doInBackground(String... params) {
    String type = params[0];
    String login_url = "http://192.168.1.6/login.php";
    if(type.equals("login")) {
        try {
            String user_name = params[1];
            String password = params[2];
            URL url = new URL(login_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("user_name","UTF-8")+"="+URLEncoder.encode(user_name,"UTF-8")+"&"
                    +URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
            String result="";
            String line="";
            while((line = bufferedReader.readLine())!= null) {
                result += line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return result;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

@Override
protected void onPreExecute() {
    alertDialog = new AlertDialog.Builder(context).create();
    alertDialog.setTitle("Login Status");
}

@Override
protected void onPostExecute(String result) {
    alertDialog.setMessage(result);
    alertDialog.show();
}

@Override
protected void onProgressUpdate(Void... values) {
    super.onProgressUpdate(values);
}

}

Body:
import this class AlertDialog

import android.app.AlertDialog;


答:
You have to import this</p>

```<code>import android.app.AlertDialog;
</code>```

Title: cannot resolve symbol AlertDialog

Body:
You have to import this

import android.app.AlertDialog;


问:
Image source not readable with Laravel Image Intervention
So this has been a problem for me for a while now and it just doesn't seem to work, I have a form where users can submit a new profile picure:

```<code><form enctype="multipart/form-data" action="/profile" method="POST">
    <input type="file" name="avatar">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
    <input type="submit" class="pull-right btn btn-sm btn-primary">
</form>
</code>```

When the button is clicked they are being redirected to the controller which activates the following function:

```<code>public function update_avatar(Request $request)
{
    $avatar = $request->avatar;
    $extension = File::extension($avatar);
    $filename = time() . '.' . $extension;
    Image::make($avatar)->resize(350, 350)->save( public_path('/uploads/avatars/' . $filename ) );

    $user = Sentinel::getUser();
    $user->profile->avatar = $filename;
    $user->save();
}
</code>```

But whatever I do the controller always returns the message

(1/1) NotReadableException

Image source not readable

Does anyone know how I can fix this?

EDIT: I've changed my Image::make line to the following:

```<code>$image = Image::make($avatar->getRealPath())->resize(350, 350)->save( public_path('/uploads/avatars/' . $filename ) );
</code>```

But now I am encountering a new error:

(1/1) FatalErrorException

Call to a member function getRealPath() on string

答:
Try this instead :

```<code>Image::make($avatar->getRealPath())->resize(350, 350)->save( public_path('/uploads/avatars/' . $filename ) );
</code>```

Edit:
use this, to retrieve your UploadedFile

```<code>$avatar = $request->file('avatar');
</code>```

Edit #2:
For the extension use this instead :

```<code>$extension = $avatar->getClientOriginalExtension();
</code>```

Note: Do not forget to authorize only images files in your validation rules.

Intead, you can "hardcode" the extension, Intervention is able to save & convert into the specified image format (jpg, png ..)

Body:
So this has been a problem for me for a while now and it just doesn't seem to work, I have a form where users can submit a new profile picure:

<form enctype="multipart/form-data" action="/profile" method="POST">
    <input type="file" name="avatar">
    <input type="hidden" name="_token" value="{{ csrf_token() }}">
    <input type="submit" class="pull-right btn btn-sm btn-primary">
</form>

When the button is clicked they are being redirected to the controller which activates the following function:

public function update_avatar(Request $request)
{
    $avatar = $request->avatar;
    $extension = File::extension($avatar);
    $filename = time() . '.' . $extension;
    Image::make($avatar)->resize(350, 350)->save( public_path('/uploads/avatars/' . $filename ) );

    $user = Sentinel::getUser();
    $user->profile->avatar = $filename;
    $user->save();
}

But whatever I do the controller always returns the message

(1/1) NotReadableException

Image source not readable

Does anyone know how I can fix this?

EDIT: I've changed my Image::make line to the following:

$image = Image::make($avatar->getRealPath())->resize(350, 350)->save( public_path('/uploads/avatars/' . $filename ) );

But now I am encountering a new error:

(1/1) FatalErrorException

Call to a member function getRealPath() on string

Body:
Try this instead :

Image::make($avatar->getRealPath())->resize(350, 350)->save( public_path('/uploads/avatars/' . $filename ) );

Edit:
use this, to retrieve your UploadedFile

$avatar = $request->file('avatar');

Edit #2:
For the extension use this instead :

$extension = $avatar->getClientOriginalExtension();

Note: Do not forget to authorize only images files in your validation rules.

Intead, you can "hardcode" the extension, Intervention is able to save & convert into the specified image format (jpg, png ..)


问:
Submitting form elements with the same name
I have a form which allows the user to create extra "rows" using JQuery (using .clone) so that they can decide how many of the same information they need to submit. My issue is that I cannot work out how to access these form items within my controller.

the form that is being submitted may look like this

```<code><input type="text" name="Amount" id="Amount">
   <select name="Item">
       <option value="1">Item 1"</option>
       <option value="2">Item 2"</option>
       <option value="3">Item 3"</option>
   </select>
<input type="text" name="Amount" id="Amount">
   <select name="Item">
       <option value="1">Item 1"</option>
       <option value="2">Item 2"</option>
       <option value="3">Item 3"</option>
   </select>
<input type="text" name="Amount" id="Amount">
   <select name="Item">
       <option value="1">Item 1"</option>
       <option value="2">Item 2"</option>
       <option value="3">Item 3"</option>
   </select>
</code>```

Basically, the block between input and the select could be repeated an infinite number of times. When I submit to the controller I am then using FormCollection form to access the form elements. from there I am unsure how I can access the items that have been submitted. I thought of using a for loop and then accessing them via something like form["Amount"][i] but obviously that is not going to work.

Am I going about this the right way and if so, does anyone have any suggestions about how this might work?

Thanks in advance.

答:
I ended up realising that (blush) the mechanism which JQuery uses to find the string within the cloned row (to replace) is basically regex. Thus I just needed to escape the square brackets and period. Once I did this I was able use JQuery to create form as Phil Haack's blog suggested.

Onto my next issue...!

OwnerDisplayName: dave

Body:
I have a form which allows the user to create extra "rows" using JQuery (using .clone) so that they can decide how many of the same information they need to submit. My issue is that I cannot work out how to access these form items within my controller.

the form that is being submitted may look like this

<input type="text" name="Amount" id="Amount">
   <select name="Item">
       <option value="1">Item 1"</option>
       <option value="2">Item 2"</option>
       <option value="3">Item 3"</option>
   </select>
<input type="text" name="Amount" id="Amount">
   <select name="Item">
       <option value="1">Item 1"</option>
       <option value="2">Item 2"</option>
       <option value="3">Item 3"</option>
   </select>
<input type="text" name="Amount" id="Amount">
   <select name="Item">
       <option value="1">Item 1"</option>
       <option value="2">Item 2"</option>
       <option value="3">Item 3"</option>
   </select>

Basically, the block between input and the select could be repeated an infinite number of times. When I submit to the controller I am then using FormCollection form to access the form elements. from there I am unsure how I can access the items that have been submitted. I thought of using a for loop and then accessing them via something like form["Amount"][i] but obviously that is not going to work.

Am I going about this the right way and if so, does anyone have any suggestions about how this might work?

Thanks in advance.

LastEditorDisplayName: dave


问:
How to convert a list of strings to numbers or float?
I have an output like this:

```<code>0.4481696971
0.3993220707
0.4006741959
0.1333734337
0.9441898513
</code>```

which is stored in a result variable.

What I'm trying to do is calculate the sum of all these lines and divide it by number_lines in this case 5. How could I achieve this?

```<code>values = [0.4, 0.0, 1.0, 0.25, 0.90]

print sum(values)
</code>```

答:
(Edited)

You can first split result by \n and convert each of them to float. Then do whatever you want (average).

```<code>numbers = list(map(float, result.split("\n")))
print(sum(numbers))  # Sum.
print(sum(numbers) / len(numbers))  # Average.
</code>```

Body:
I have an output like this:

0.4481696971
0.3993220707
0.4006741959
0.1333734337
0.9441898513

which is stored in a result variable.

What I'm trying to do is calculate the sum of all these lines and divide it by number_lines in this case 5. How could I achieve this?

values = [0.4, 0.0, 1.0, 0.25, 0.90]

print sum(values)

Body:
(Edited)

You can first split result by \n and convert each of them to float. Then do whatever you want (average).

numbers = list(map(float, result.split("\n")))
print(sum(numbers))  # Sum.
print(sum(numbers) / len(numbers))  # Average.


问:
Custom MKAnnotationView location drastically changes when rotate or zoom in/out of map
I've got two custom MKAnnotationViews, which display fine when they are initially added to the MKMapView.

The issue is, when rotating, or zooming out, their drawn locations seem to become more and more off. To reiterate, the closer I zoom in, the more accurate they appear, but when zooming out and rotating they are completely off. Any ideas?

Looks good (initial state):

Looks bad (and wrong):

My viewForAnnotation method is pretty basic, nothing fancy going on here.

```<code>func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

        if let annotation = annotation as? PKDriverAnnotation
            {
            let identifier = "driver"
            var annotationView: PKDriverAnnotationView
            if let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) { // 2
                dequeuedView.annotation = annotation
                annotationView = dequeuedView as! PKDriverAnnotationView
            } else {
                // 3
                annotationView = PKDriverAnnotationView(annotation: annotation, reuseIdentifier: identifier)
                annotationView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(PKTransactionMapViewController.annotationViewTapped(recognizer:))))
            }

            self.driverAnnotationView = annotationView

            return annotationView
        } else if let annotation = annotation as? PKAnnotation {
            let identifier = "pin"
            var view: MKAnnotationView
            if let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) { // 2
                dequeuedView.annotation = annotation
                view = dequeuedView
            } else {
                // 3
                view = MKAnnotationView(annotation: annotation, reuseIdentifier: identifier)
                view.image = UIImage(named: "TransactionAnnotation")
                view.canShowCallout = false
                view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(PKHomeViewController.annotationViewTapped(recognizer:))))

                let profilePic = FBSDKProfilePictureView(frame: CGRect(x: 4, y: 4, width: 43, height: 43))
                profilePic.center = CGPoint(x: view.bounds.midX, y: profilePic.center.y)
                profilePic.profileID = self.transaction!.availableParking.holder.fbid
                profilePic.layer.cornerRadius = 21.0
                profilePic.clipsToBounds = true
                view.addSubview(profilePic)
            }

            return view
        }
        return nil
    }
</code>```

Update

I suspected this was somewhat related to anchor points, and I was able to fix the "parking pin annotation views" rotation by view.layer.anchorPoint = CGPoint(x: 0.5, y: 1.0), but had no luck with driver annotation view (the one w/ the car)

Appreciate the help SO!

答:
You should set the centerOffset of your MKAnnotationView. As the documentation says:

By default, the center point of an annotation view is placed at the coordinate point of the associated annotation. You can use this property to reposition the annotation view as needed. This x and y offset values are measured in points. Positive offset values move the annotation view down and to the right, while negative values move it up and to the left.

Body:
I've got two custom MKAnnotationViews, which display fine when they are initially added to the MKMapView.

The issue is, when rotating, or zooming out, their drawn locations seem to become more and more off. To reiterate, the closer I zoom in, the more accurate they appear, but when zooming out and rotating they are completely off. Any ideas?

Looks good (initial state):

Looks bad (and wrong):

My viewForAnnotation method is pretty basic, nothing fancy going on here.

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

        if let annotation = annotation as? PKDriverAnnotation
            {
            let identifier = "driver"
            var annotationView: PKDriverAnnotationView
            if let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) { // 2
                dequeuedView.annotation = annotation
                annotationView = dequeuedView as! PKDriverAnnotationView
            } else {
                // 3
                annotationView = PKDriverAnnotationView(annotation: annotation, reuseIdentifier: identifier)
                annotationView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(PKTransactionMapViewController.annotationViewTapped(recognizer:))))
            }

            self.driverAnnotationView = annotationView

            return annotationView
        } else if let annotation = annotation as? PKAnnotation {
            let identifier = "pin"
            var view: MKAnnotationView
            if let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) { // 2
                dequeuedView.annotation = annotation
                view = dequeuedView
            } else {
                // 3
                view = MKAnnotationView(annotation: annotation, reuseIdentifier: identifier)
                view.image = UIImage(named: "TransactionAnnotation")
                view.canShowCallout = false
                view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(PKHomeViewController.annotationViewTapped(recognizer:))))

                let profilePic = FBSDKProfilePictureView(frame: CGRect(x: 4, y: 4, width: 43, height: 43))
                profilePic.center = CGPoint(x: view.bounds.midX, y: profilePic.center.y)
                profilePic.profileID = self.transaction!.availableParking.holder.fbid
                profilePic.layer.cornerRadius = 21.0
                profilePic.clipsToBounds = true
                view.addSubview(profilePic)
            }

            return view
        }
        return nil
    }

Update

I suspected this was somewhat related to anchor points, and I was able to fix the "parking pin annotation views" rotation by view.layer.anchorPoint = CGPoint(x: 0.5, y: 1.0), but had no luck with driver annotation view (the one w/ the car)

Appreciate the help SO!


问:
args must be a dictionary error while using ansible
I am working on Ansible playbook to execute some of my tasks. In one of my tasks, I need to switch to particular directory and then execute a command using sudo but I need to do all these things by switching to root user first otherwise it won't work. So in general this is what I do without ansible:

```<code>david@machineA:/tmp/parallel-20140422$ sudo su
root@machineA:/tmp/parallel-20140422# sudo ./configure && make && make install
</code>```

After above steps, I see GNU parallel library is installed in my system correctly. But with the below steps using Ansible, I am getting an error:

```<code>- name: install gnu parallel
  shell: ./configure && make && make install
  args:
    chdir=/tmp/parallel-20140422
  sudo: true
  sudo_user: root
</code>```

Below is the error I am getting:

```<code>fatal: [machineA] => args must be a dictionary, received chdir=/tmp/parallel-20140422
</code>```

I am working with 1.5.4 ansible. I am not sure what's wrong here with my ansible tasks?

答:
Your task should probably look like this:

```<code>- name: install gnu parallel
  shell: ./configure && make && make install
  args:
    chdir: /tmp/parallel-20140422
  sudo: true
  sudo_user: root
</code>```

I'm a bit confused that you have to give root as sudo_user, because that's the default as far as I know. But then again, if it works for you, it works.

Body:
I am working on Ansible playbook to execute some of my tasks. In one of my tasks, I need to switch to particular directory and then execute a command using sudo but I need to do all these things by switching to root user first otherwise it won't work. So in general this is what I do without ansible:

david@machineA:/tmp/parallel-20140422$ sudo su
root@machineA:/tmp/parallel-20140422# sudo ./configure && make && make install

After above steps, I see GNU parallel library is installed in my system correctly. But with the below steps using Ansible, I am getting an error:

- name: install gnu parallel
  shell: ./configure && make && make install
  args:
    chdir=/tmp/parallel-20140422
  sudo: true
  sudo_user: root

Below is the error I am getting:

fatal: [machineA] => args must be a dictionary, received chdir=/tmp/parallel-20140422

I am working with 1.5.4 ansible. I am not sure what's wrong here with my ansible tasks?

Body:
Your task should probably look like this:

- name: install gnu parallel
  shell: ./configure && make && make install
  args:
    chdir: /tmp/parallel-20140422
  sudo: true
  sudo_user: root

I'm a bit confused that you have to give root as sudo_user, because that's the default as far as I know. But then again, if it works for you, it works.


问:
How to set column width in Kendo Grid
I have to set some fixed column width in Kendo Grid which has no column headers.That means I get data simlar to below with single column "foo_data" and am hiding this column header and showing in the kendo Grid as is.The columns and rows in the Grid are dynamic ie.in the below example there are 9  columns  and 6 rows sometimes I may get 3 columns and 5 rows. I am using Kendo Ui,Angularjs and bootstrap frameworks.I want more space between columns in the Grid.How can I achieve this ? Any help would be highly appreciated.

```<code>var foo_data= [{"1 AAA BBB CCC 44444444444444444 555555555555555555 67777777777777777 333333333333333  99999999999"},
               "2  AAA BBB CCC 44444444444444444 555555555555555555 67777777777777777 333333333333333  99999999999"},
               "3  AAA BBB CCC 44444444444444444 555555555555555555 67777777777777777 333333333333333  99999999999"},
               "4  AAA BBB CCC 44444444444444444 555555555555555555 67777777777777777 333333333333333  99999999999"},
               "5  AAA BBB CCC 44444444444444444 555555555555555555 67777777777777777 333333333333333  99999999999"},
               "6  AAA BBB CCC 44444444444444444 555555555555555555 67777777777777777 333333333333333  99999999999"}];
</code>```

Hiding column header in the Kendo Grid:

```<code>columns: [{
    field: "foo_data",
    headerAttributes: {
           style: "display; none"
    }
</code>```

答:
You can set it as shown in below code. For more information refer kendo UI documentation (Grid / AngularJS)</p>

```<code> $scope.mainGridOptions = {
            dataSource: {
                type: "odata",
                transport: {
                    read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Employees"
                },
                pageSize: 5,
                serverPaging: true,
                serverSorting: true
            },
            sortable: true,
            pageable: true,
            dataBound: function() {
                this.expandRow(this.tbody.find("tr.k-master-row").first());
            },
            columns: [{
                field: "FirstName",
                title: "First Name",
                width: "120px"
                },{
                field: "LastName",
                title: "Last Name",
                width: "120px"
                },{
                field: "Country",
                width: "120px"
                },{
                field: "City",
                width: "120px"
                },{
                field: "Title"
            }]
        };
</code>```

Title: How to set column width in Kendo Grid

Body:
I have to set some fixed column width in Kendo Grid which has no column headers.That means I get data simlar to below with single column "foo_data" and am hiding this column header and showing in the kendo Grid as is.The columns and rows in the Grid are dynamic ie.in the below example there are 9  columns  and 6 rows sometimes I may get 3 columns and 5 rows. I am using Kendo Ui,Angularjs and bootstrap frameworks.I want more space between columns in the Grid.How can I achieve this ? Any help would be highly appreciated.

var foo_data= [{"1 AAA BBB CCC 44444444444444444 555555555555555555 67777777777777777 333333333333333  99999999999"},
               "2  AAA BBB CCC 44444444444444444 555555555555555555 67777777777777777 333333333333333  99999999999"},
               "3  AAA BBB CCC 44444444444444444 555555555555555555 67777777777777777 333333333333333  99999999999"},
               "4  AAA BBB CCC 44444444444444444 555555555555555555 67777777777777777 333333333333333  99999999999"},
               "5  AAA BBB CCC 44444444444444444 555555555555555555 67777777777777777 333333333333333  99999999999"},
               "6  AAA BBB CCC 44444444444444444 555555555555555555 67777777777777777 333333333333333  99999999999"}];

Hiding column header in the Kendo Grid:

columns: [{
    field: "foo_data",
    headerAttributes: {
           style: "display; none"
    }

Body:
You can set it as shown in below code. For more information refer kendo UI documentation (Grid / AngularJS)

 $scope.mainGridOptions = {
            dataSource: {
                type: "odata",
                transport: {
                    read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Employees"
                },
                pageSize: 5,
                serverPaging: true,
                serverSorting: true
            },
            sortable: true,
            pageable: true,
            dataBound: function() {
                this.expandRow(this.tbody.find("tr.k-master-row").first());
            },
            columns: [{
                field: "FirstName",
                title: "First Name",
                width: "120px"
                },{
                field: "LastName",
                title: "Last Name",
                width: "120px"
                },{
                field: "Country",
                width: "120px"
                },{
                field: "City",
                width: "120px"
                },{
                field: "Title"
            }]
        };


问:
How do stock market data feeds work?
or any other type of realtime data feed from server to client... I'm talking about a bunch of realtime data from server to client. i.e., an informational update every second.

Does the server magically push the data to the client, or does the client need to continuously poll the server for updates? And under what protocol does this usually work? (http, socket communication, etc?)

答:
In server-side financial applications used by brokers/banks etc. market data (quotes,trades etc) is transmitted over TCP via some application-level protocol which most probably won't be HTTP. Of course, there's no polling. Client is establishing TCP connection with server, server pushes data to client. One of common approaches to distribute market data is FIX.
Thomson-Reuters have bunch of cryptic proprietary protocols dating from mainframe days to distribute such data.

HTTP can be used for SOAP/RESTful to transmit/request data of not-so-large volume, like business news.

UPDATE Actually, even FIX is not enough in some cases, as it has big overhead because of it's "text" nature. Most brokers and exchanges transmit high-volume streams, such as quotes, using binary-format protocols (FAST or some proprietary).

Title: How do stock market data feeds work?


问:
python datetime incorrect sorted
I'm getting some database dates and they can get mixed up.
I use the sorted () method to print these dates on a regular basis

```<code>datelist = ["1 2017", "2 2017", "6 2017",  "7 2017", "8 2017", "3 2017", "4 2017", "5 2017", "9 2017", "10 2017", "11 2017", "12 2017"]

for i in sorted(datelist):
        print(i)
</code>```

But the result is terrible ..!

```<code>1 2017
10 2017
11 2017
12 2017
2 2017
3 2017
4 2017
5 2017
6 2017
7 2017
8 2017
9 2017
</code>```

How can I get these values regularly?
Thanks in advance for help

答:
It is because you are performing sort on the string values and the sorting on strings are done lexicographically. In order to sort the strings in your list in the numeric ascending order, you may pass key argument as a lambda function with the sorted as:

```<code>>>> datelist = ["1 2017", "2 2017", "6 2017",  "7 2017", "8 2017", "3 2017", "4 2017", "5 2017", "9 2017", "10 2017", "11 2017", "12 2017"]

>>> sorted(datelist, key=lambda x: [int(y) for y in x.split()])
['1 2017', '2 2017', '3 2017', '4 2017', '5 2017', '6 2017', '7 2017', '8 2017', '9 2017', '10 2017', '11 2017', '12 2017']
</code>```

Title: python datetime incorrect sorted

Body:
I'm getting some database dates and they can get mixed up.
I use the sorted () method to print these dates on a regular basis

datelist = ["1 2017", "2 2017", "6 2017",  "7 2017", "8 2017", "3 2017", "4 2017", "5 2017", "9 2017", "10 2017", "11 2017", "12 2017"]

for i in sorted(datelist):
        print(i)

But the result is terrible ..!

1 2017
10 2017
11 2017
12 2017
2 2017
3 2017
4 2017
5 2017
6 2017
7 2017
8 2017
9 2017

How can I get these values regularly?
Thanks in advance for help

Body:
It is because you are performing sort on the string values and the sorting on strings are done lexicographically. In order to sort the strings in your list in the numeric ascending order, you may pass key argument as a lambda function with the sorted as:

>>> datelist = ["1 2017", "2 2017", "6 2017",  "7 2017", "8 2017", "3 2017", "4 2017", "5 2017", "9 2017", "10 2017", "11 2017", "12 2017"]

>>> sorted(datelist, key=lambda x: [int(y) for y in x.split()])
['1 2017', '2 2017', '3 2017', '4 2017', '5 2017', '6 2017', '7 2017', '8 2017', '9 2017', '10 2017', '11 2017', '12 2017']


问:
Application not opening on notification click android hyrbrid ibm-mobilefirst
It's an hybrid application using mobilefirst 7.1.
On iOS it is working well. But on android when clicking on the notification nothing happened (not even one log)..</p>

答:
Refer to Idan Adar's response to the same query at :

1) Worklight 6.2 Android Application not launching on push notification

2) And
IBM Worklight 5.0.6.1 - Not getting Push Notifications when phone/app is closed