问:
How to use for in loop and query data from firebase
I have a query that gets all keys of users in my firebase database. Those keys er saved into an array. I would then like to loop through the array and inside the loop query for the users name. The problem is that it stops when the first name is loaded - the loop does not query through even though there are 1000 keys inside the array?

```<code>var i;

for (i = 0; i < emailArray.length; i++) {
    userIDgotten = emailArray[i];

    console.log(userIDgotten);

    return firebase.database().ref('/users/' + userIDgotten).once('value').then(function(snapshotUser) {
        const name = snapshotUser.val().name;

        console.log("NAME: " + name);

        allTicketEmailsFromUsers = allTicketEmailsFromUsers + ", " + name;

        console.log(allTicketEmailsFromUsers);
    });
}

</code>```

I get no errors but the loop just stops after the first name is retrieved.

答:
The once() method is asynchronous and returns a Promise.

Since you want to execute several queries with once() in parallel, you need to use Promise.all() as follows:

```<code>var promises = [];
for (var i = 0; i < emailArray.length; i++) {
   userIDgotten = emailArray[i];

   console.log(userIDgotten);

   promises.push(firebase.database().ref('/users/' + userIDgotten).once('value'));

}

Promise.all(promises)
.then(function(results) {
    var allTicketEmailsFromUsers = "";
    results.forEach(function(snapshotUser) {
        const name = snapshotUser.val().name;
        console.log("NAME: " + name);
        allTicketEmailsFromUsers = allTicketEmailsFromUsers + ", " + name;
    });
    console.log(allTicketEmailsFromUsers);
}
</code>```

Body:
I have a query that gets all keys of users in my firebase database. Those keys er saved into an array. I would then like to loop through the array and inside the loop query for the users name. The problem is that it stops when the first name is loaded - the loop does not query through even though there are 1000 keys inside the array?

var i;

for (i = 0; i < emailArray.length; i++) {
    userIDgotten = emailArray[i];

    console.log(userIDgotten);

    return firebase.database().ref('/users/' + userIDgotten).once('value').then(function(snapshotUser) {
        const name = snapshotUser.val().name;

        console.log("NAME: " + name);

        allTicketEmailsFromUsers = allTicketEmailsFromUsers + ", " + name;

        console.log(allTicketEmailsFromUsers);
    });
}

I get no errors but the loop just stops after the first name is retrieved.

Body:
The once() method is asynchronous and returns a Promise.

Since you want to execute several queries with once() in parallel, you need to use Promise.all() as follows:

var promises = [];
for (var i = 0; i < emailArray.length; i++) {
   userIDgotten = emailArray[i];

   console.log(userIDgotten);

   promises.push(firebase.database().ref('/users/' + userIDgotten).once('value'));

}

Promise.all(promises)
.then(function(results) {
    var allTicketEmailsFromUsers = "";
    results.forEach(function(snapshotUser) {
        const name = snapshotUser.val().name;
        console.log("NAME: " + name);
        allTicketEmailsFromUsers = allTicketEmailsFromUsers + ", " + name;
    });
    console.log(allTicketEmailsFromUsers);
}


来源: stackexchange

问:
No string after Escape Sequences '\b'
why print('abcd\b') is abcd Instead of abc

it is working if we put space after \b

```<code>>>> print('abcd\b')
abcd
>>> print('abcd\b ')
abc
</code>```

答:
\b is a backspace control character. Printing it moves the cursor back one space, just like on the typewriter. It does not delete anything. Unlike the typewriter, console output can only have one character in each position, so if you print one character over another, the old one is replaced by the new one.

So when you print "abcd\b", you print four characters, then backtrack, but you don't change anything else. When you print "abcd^b ", you print abcd, then return the cursor so it's over d, and replace the d with a space.

ContentLicense: CC BY-SA 4.0

Title: No string after Escape Sequences '\b'

Body:
why print('abcd\b') is abcd Instead of abc

it is working if we put space after \b

>>> print('abcd\b')
abcd
>>> print('abcd\b ')
abc


问:
run same method in multiple task replce the previous object sent as a parameter
i  am running the task which have method called createpdf(obj);
i have a list of the same object and with the help of forEach loop i am creating a task of the createpdf method ;

but when the last task called the method it will change the all the previous object values also.

```<code>createpdf(obj){

}

createtask(){

Parallel.ForEach(objeclist, m => createpdf(m) );
}
</code>```

now when the last task run it will change all the task result.

答:
That is normal behavior for reference types when you change property of the same object by different links. Your list contains the different links to the same object and when one property is changed with createpdf method all reference notes to modified property as well.
Could read this article about difference reference and structure types in C#:

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/reference-types

https://vegibit.com/reference-types-and-value-types-in-c/

If you want to separate instances for each objects in list  you should add to list new created instance of object or define them as structure instead class.

Body:
i  am running the task which have method called createpdf(obj);
i have a list of the same object and with the help of forEach loop i am creating a task of the createpdf method ;

but when the last task called the method it will change the all the previous object values also.

createpdf(obj){

}

createtask(){

Parallel.ForEach(objeclist, m => createpdf(m) );
}

now when the last task run it will change all the task result.


问:
Can this form be filled and submitted using python's responses module?
I am writing a data scraping script. It's purpose is to collect data on available broadband deals from BT's website. I cannot figure out why my simple requests code doesn't fill in the form and follow through to the next page.

Please help me figure out how to enter data into this form and save the output html for data scraping.

I have identified the relevant tags in the form that I am interested in. I am trying to populate the UPRN field and continue to the next page

Link to website: https://www.dslchecker.bt.com/#

My python code:
'''python

```<code>import requests
url = "https://www.dslchecker.bt.com/#"
payload = {'UPRN':'10033360983'}
r = requests.post(url, data = payload)
print(r.text)
</code>```

'''

Form from the website:

'''html

```<code><form method="post" action="adsl/ADSLChecker.UPRNoutput"><input type="hidden" name="URL"> <input value="a%20service%20provider" type="hidden" name="SP_NAME">
      <span class="subheading">UPRN:</span><br><input maxlength="13" size="14" name="UPRN" autocomplete="off" style="background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAASCAYAAABSO15qAAAAAXNSR0IArs4c6QAAAPhJREFUOBHlU70KgzAQPlMhEvoQTg6OPoOjT+JWOnRqkUKHgqWP4OQbOPokTk6OTkVULNSLVc62oJmbIdzd95NcuGjX2/3YVI/Ts+t0WLE2ut5xsQ0O+90F6UxFjAI8qNcEGONia08e6MNONYwCS7EQAizLmtGUDEzTBNd1fxsYhjEBnHPQNG3KKTYV34F8ec/zwHEciOMYyrIE3/ehKAqIoggo9inGXKmFXwbyBkmSQJqmUNe15IRhCG3byphitm1/eUzDM4qR0TTNjEixGdAnSi3keS5vSk2UDKqqgizLqB4YzvassiKhGtZ/jDMtLOnHz7TE+yf8BaDZXA509yeBAAAAAElFTkSuQmCC"); background-repeat: no-repeat; background-attachment: scroll; background-size: 16px 18px; background-position: 98% 50%; cursor: auto;"> <input value="56" type="hidden" name="VERSION"> <input value="E" type="hidden" name="MS"> <input value="no" type="hidden" name="CAP"> <input value="Y" type="hidden" name="AEA">   <input class="form_button" value="submit" type="submit"> </form>
</code>```

'''

Please follow this link :https://www.dslchecker.bt.com/# and enter 10033346575 in the UPRN field to see the desired output

My output when ran in a jupyter notebook:

'''html

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- saved from url=(0063)http://dslcheckerait.vade.bt.com:61065/adsl/adslchecker.welcome -->
<HTML><HEAD>
<STYLE>
.body {FONT-VARIANT: normal; FONT-FAMILY: Verdana, Arial, Helvetica, sans-serif; COLOR: #004d5f; FONT-SIZE: 11px; FONT-WEIGHT: normal; TEXT-DECORATION: none
}
.bodybold {FONT-VARIANT: normal; FONT-FAMILY: Verdana, Arial, Helvetica, sans-serif; COLOR: #333333; FONT-SIZE: 11px; FONT-WEIGHT: bold; TEXT-DECORATION: none
}
.errormessage {FONT-VARIANT: normal; FONT-FAMILY: Verdana, Arial, Helvetica, sans-serif; COLOR: #000000; FONT-SIZE: 11px; FONT-WEIGHT: bold; TEXT-DECORATION: none
}
.formDescription {FONT-VARIANT: normal; FONT-FAMILY: Verdana, Arial, Helvetica, sans-serif; COLOR: #666666; FONT-SIZE: 9px; FONT-WEIGHT: normal; TEXT-DECORATION: none
}
.form_button {BORDER-BOTTOM: #666666 1px solid; BORDER-LEFT: #666666 1px solid; BACKGROUND-COLOR: #6400AA; FONT-VARIANT: normal; FONT-FAMILY: Calibri Light, Arial, Helvetica, sans-serif; COLOR: #ffffff; FONT-SIZE: 10px; BORDER-TOP: #666666 1px solid; FONT-WEIGHT: bold; BORDER-RIGHT: #666666 1px solid; TEXT-DECORATION: none
}
.heading {FONT-VARIANT: normal; FONT-FAMILY: Arial, Helvetica, sans-serif; COLOR: #004d5f; FONT-SIZE: 14px; FONT-WEIGHT: bold; TEXT-DECORATION: none
}
.heading3 {FONT-VARIANT: normal; FONT-FAMILY: Verdana, Arial, Helvetica, sans-serif; COLOR: #333333; FONT-SIZE: 10px; FONT-WEIGHT: bold; TEXT-DECORATION: none
}
.heading4 {FONT-VARIANT: normal; FONT-FAMILY: Verdana, Arial, Helvetica, sans-serif; COLOR: #91b1b8; FONT-SIZE: 10px; FONT-WEIGHT: bold; TEXT-DECORATION: none
}
.subheading {FONT-VARIANT: normal; FONT-FAMILY: Calibri Light, Helvetica, sans-serif; COLOR: color: #333333; FONT-SIZE: 14px; FONT-WEIGHT: bold; TEXT-DECORATION: none
}
A:active {FONT-VARIANT: normal; FONT-FAMILY: Calibri Light, Arial, Helvetica, sans-serif; COLOR: #6400AA; FONT-SIZE: 12px; FONT-WEIGHT: bold; TEXT-DECORATION: underline
}
A:hover {FONT-VARIANT: normal; FONT-FAMILY: Calibri Light, Arial, Helvetica, sans-serif; COLOR: #6400AA; FONT-SIZE: 12px; FONT-WEIGHT: bold; TEXT-DECORATION: underline
}
A:link {FONT-VARIANT: normal; FONT-FAMILY: Calibri Light, Arial, Helvetica, sans-serif; COLOR: #6400AA; FONT-SIZE: 12px; FONT-WEIGHT: bold; TEXT-DECORATION: none
}
A:visited {FONT-VARIANT: normal; FONT-FAMILY: Calibri Light, Arial, Helvetica, sans-serif; COLOR: #6400AA; FONT-SIZE: 12px; FONT-WEIGHT: bold; TEXT-DECORATION: underline
}
BODY {PADDING-BOTTOM: 0px; BACKGROUND-COLOR: #ffffff; MARGIN: 10px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; PADDING-TOP: 0px
}

</STYLE>

<TITLE>BT Broadband</TITLE>
<META content="text/html; charset=utf-8" http-equiv=Content-Type><LINK
rel=stylesheet type=text/css
href="adslchecker_font.html">
<META content=text/css http-equiv=Content-Style-Type><META http-equiv="X-UA-Compatible" content="IE=5">
<SCRIPT>
<!--
function setFocus() {
    document.forms[0].elements[2].focus();
}
//-->
</SCRIPT>

<META name=GENERATOR content="MSHTML 8.00.7601.18751"></HEAD>
<BODY onload=setFocus()>
<TABLE width=500 align=center>
  <TBODY>
  <TR>
    <TD>
      <SCRIPT language=JavaScript>  var isNS = (navigator.appName == "Netscape") ? 1 : 0;var EnableRightClick = 0;if(isNS) document.captureEvents(Event.MOUSEDOWN||Event.MOUSEUP);function mischandler(){if(EnableRightClick==1){ return true;}else {return false; }}function mousehandler(e){  if(EnableRightClick==1){ return true; }  var myevent = (isNS) ? e : event;  var eventbutton = (isNS) ? myevent.which : myevent.button;  if((eventbutton==2)||(eventbutton==3)) return false;}function keyhandler(e) {var myevent = (isNS) ? e : window.event;if (myevent.keyCode==96)EnableRightClick = 1;return;}document.oncontextmenu = mischandler;document.onkeypress = keyhandler;document.onmousedown = mousehandlerdocument.onmouseup = mousehandler;</SCRIPT>

      <TABLE border=0 cellSpacing=0 cellPadding=0 width="100%"><!-- Start Header -->
        <TBODY>
        <TR><BR><BR>
          <!--<TD height=20 vAlign=top align=left><IMG border=0 alt="BT Wholesale"
            src="dsl_images/g_main_logo.gif" width=129
height=20></TD></TR>
        <TR>
          <TD class=body height=14 vAlign=top align=left><IMG alt=""
            src="dsl_images/spacer.gif" width=450 height=14></TD></TR>
        <TR>//-->
          <TD class=body vAlign=top align=left fontStyle="italic">
            <TABLE border=0 cellSpacing=0 cellPadding=0 width=450><!-- Start Page Title -->
              <TBODY>
              <TR>
                <TD height=45 vAlign=top width=600 align=left><FONT
                  style="FONT-FAMILY: Calibri Light" color=#6400AA size=6.5><B> BT BROADBAND
                  AVAILABILITY
              CHECKER</B></FONT></TD></TR><!-- End Page Title --></TD></TR></TBODY></TABLE></TD></TR></TBODY></TABLE><SPAN
      class=body><!--RESPONSE-START-->
      <P><SPAN class=body><font size="2" font face="Calibri Light" color="#333333">Welcome to the Broadband Availability checker. This
      will provide a provisional check of your ability to receive reliable
      Broadband services.</font></SPAN></P>
      <P><SPAN class=body><font size="2" font face="Calibri Light" color="#333333">Please enter your telephone number.</font></SPAN></P>
      <FORM method=post action=adsl/adslchecker.TelephoneNumberOutput><INPUT
      type=hidden name=URL> <INPUT value=a%20service%20provider type=hidden
      name=SP_NAME> <SPAN class=subheading>TELEPHONE:</SPAN><BR><INPUT
      maxLength=14 size=14 name=TelNo> <INPUT value=56 type=hidden name=VERSION>
      <INPUT value=E type=hidden name=MS> <INPUT value=no type=hidden name=CAP>
      <INPUT value=Y type=hidden name=AEA>   <INPUT class=form_button value=submit type=submit> </FORM>
      <P><SPAN class=body>Or</SPAN></P>
      <P><SPAN class=body><font size="2" font face="Calibri Light" color="#333333">Please enter your access line id.</font></SPAN></P>
      <FORM method=post action=adsl/adslchecker.AccessLineIDOutput><INPUT type=hidden
      name=URL> <INPUT value=a%20service%20provider type=hidden name=SP_NAME>
      <SPAN class=subheading>ACCESS LINE ID:</SPAN><BR><INPUT maxLength=13
      size=14 name=ALID> <INPUT value=56 type=hidden name=VERSION> <INPUT
      value=E type=hidden name=MS> <INPUT value=no type=hidden name=CAP> <INPUT
      value=Y type=hidden name=AEA>   <INPUT class=form_button value=submit type=submit> </FORM>
          <P><SPAN class=body>Or</SPAN></P>
      <P><SPAN class=body><font size="2" font face="Calibri Light" color="#333333">Please enter your UPRN.</font></SPAN></P>
      <FORM method=post action=adsl/ADSLChecker.UPRNoutput><INPUT type=hidden
      name=URL> <INPUT value=a%20service%20provider type=hidden name=SP_NAME>
      <SPAN class=subheading>UPRN:</SPAN><BR><INPUT maxLength=13
      size=14 name=UPRN> <INPUT value=56 type=hidden name=VERSION> <INPUT
      value=E type=hidden name=MS> <INPUT value=no type=hidden name=CAP> <INPUT
      value=Y type=hidden name=AEA>   <INPUT class=form_button value=submit type=submit> </FORM>
      <P><SPAN class=body><font size="2" font face="Calibri Light" color="#333333">If you do not have a telephone number or access line
      id, please select the</font>
<TABLE>
  <TR>
   <FORM method=post action=adsl/adslchecker.address>
          <INPUT value="" type=hidden name=url>
          <INPUT value=a%20service%20provider type=hidden name=SP_NAME>
          <INPUT value=56 type=hidden name=VERSION>
          <INPUT value=E type=hidden name=MS>
          <INPUT value=no type=hidden name=CAP>
          <INPUT value=Y type=hidden name=AEA>
          <TD><A href=# onclick="document.forms[3].submit()">Address Checker</A></TD>
   </FORM>
          <FONT>
          <TH><P><SPAN class=body><font size="2" font face="Calibri Light" color="#333333">or the</font></SPAN></P></TH>
          </FONT>
   <FORM method=post action=adsl/adslchecker.postcode>
          <TD><A href=# onclick="document.forms[4].submit()">Postcode Checker</A></TD>
          <INPUT value="" type=hidden name=url>
          <INPUT value=a%20service%20provider type=hidden name=SP_NAME>
          <INPUT value=56 type=hidden name=VERSION>
          <INPUT value=E type=hidden name=MS>
          <INPUT value=no type=hidden name=CAP>
          <INPUT value=Y type=hidden name=AEA>
   </FORM>
          <FONT>
          <TH><P><SPAN class=body><font size="2" font face="Calibri Light" color="#333333">or the</font></SPAN></P></TH>
          </FONT>
   <FORM method=post action=adsl/adslchecker.bbeuidform>
          <TD><A href=# onclick="document.forms[5].submit()">BBEU Checker</A></TD>
          <INPUT value="" type=hidden name=url>
          <INPUT value=a%20service%20provider type=hidden name=SP_NAME>
          <INPUT value=56 type=hidden name=VERSION>
          <INPUT value=E type=hidden name=MS>
          <INPUT value=no type=hidden name=CAP>
          <INPUT value=Y type=hidden name=AEA>
   </FORM>
  </TR>
</TABLE>
<P><SPAN class=body><font size="2" font face="Calibri Light" color="#333333">By submitting a query into this checker you accept <A
      href="https://www.btwholesale.com/pages/static/terms-of-use.htm" target="_blank">Terms of Use</A> for this checker.</font>
<!--RESPONSE-END--></SPAN></P></SPAN></TD></TR></TBODY></TABLE></BODY></HTML>
</code>```

'''

答:
So 1) you're posting to the wrong URL.

From the return HTML, the "action" for the form you want is "adsl/ADSLChecker.UPRNoutput"

2) there are hidden fields in the form you're not submitting

```<code><form method="post" action="adsl/ADSLChecker.UPRNoutput">
    <input type="hidden" name="URL">
    <input value="a%20service%20provider" type="hidden" name="SP_NAME">
    <span class="subheading">UPRN:</span><br>
    <input maxlength="13" size="14" name="UPRN">
    <input value="56" type="hidden" name="VERSION">
    <input value="E" type="hidden" name="MS">
    <input value="no" type="hidden" name="CAP">
    <input value="Y" type="hidden" name="AEA">
    <input class="form_button" value="submit" type="submit">
</form>
</code>```

Try:

```<code>payload = {
    "UPRN": "10033360983",
    "SP_NAME": "a%20service%20provider",
    "VERSION": "56",
    "MS": "E",
    "CAP": "no",
    "AEA": "Y"
}
url = 'https://www.dslchecker.bt.com/adsl/ADSLChecker.UPRNoutput'
r = requests.post(url, data = payload)
</code>```

Body:
I am writing a data scraping script. It's purpose is to collect data on available broadband deals from BT's website. I cannot figure out why my simple requests code doesn't fill in the form and follow through to the next page.

Please help me figure out how to enter data into this form and save the output html for data scraping.

I have identified the relevant tags in the form that I am interested in. I am trying to populate the UPRN field and continue to the next page

Link to website: https://www.dslchecker.bt.com/#

My python code:
'''python

import requests
url = "https://www.dslchecker.bt.com/#"
payload = {'UPRN':'10033360983'}
r = requests.post(url, data = payload)
print(r.text)

'''

Form from the website:

'''html

<form method="post" action="adsl/ADSLChecker.UPRNoutput"><input type="hidden" name="URL"> <input value="a%20service%20provider" type="hidden" name="SP_NAME">
      UPRN:
<input maxlength="13" size="14" name="UPRN" autocomplete="off" style="background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAASCAYAAABSO15qAAAAAXNSR0IArs4c6QAAAPhJREFUOBHlU70KgzAQPlMhEvoQTg6OPoOjT+JWOnRqkUKHgqWP4OQbOPokTk6OTkVULNSLVc62oJmbIdzd95NcuGjX2/3YVI/Ts+t0WLE2ut5xsQ0O+90F6UxFjAI8qNcEGONia08e6MNONYwCS7EQAizLmtGUDEzTBNd1fxsYhjEBnHPQNG3KKTYV34F8ec/zwHEciOMYyrIE3/ehKAqIoggo9inGXKmFXwbyBkmSQJqmUNe15IRhCG3byphitm1/eUzDM4qR0TTNjEixGdAnSi3keS5vSk2UDKqqgizLqB4YzvassiKhGtZ/jDMtLOnHz7TE+yf8BaDZXA509yeBAAAAAElFTkSuQmCC"); background-repeat: no-repeat; background-attachment: scroll; background-size: 16px 18px; background-position: 98% 50%; cursor: auto;"> <input value="56" type="hidden" name="VERSION"> <input value="E" type="hidden" name="MS"> <input value="no" type="hidden" name="CAP"> <input value="Y" type="hidden" name="AEA">   <input class="form_button" value="submit" type="submit"> </form>

'''

Please follow this link :https://www.dslchecker.bt.com/# and enter 10033346575 in the UPRN field to see the desired output

My output when ran in a jupyter notebook:

'''html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<TITLE>BT Broadband</TITLE>
<META content="text/html; charset=utf-8" http-equiv=Content-Type><LINK
rel=stylesheet type=text/css
href="adslchecker_font.html">
<META content=text/css http-equiv=Content-Style-Type><META http-equiv="X-UA-Compatible" content="IE=5">

<META name=GENERATOR content="MSHTML 8.00.7601.18751">

                 BT BROADBAND
                  AVAILABILITY
              CHECKER

Welcome to the Broadband Availability checker. This
      will provide a provisional check of your ability to receive reliable
      Broadband services.

Please enter your telephone number.

      <FORM method=post action=adsl/adslchecker.TelephoneNumberOutput><INPUT
      type=hidden name=URL> <INPUT value=a%20service%20provider type=hidden
      name=SP_NAME> TELEPHONE:
<INPUT
      maxLength=14 size=14 name=TelNo> <INPUT value=56 type=hidden name=VERSION>
      <INPUT value=E type=hidden name=MS> <INPUT value=no type=hidden name=CAP>
      <INPUT value=Y type=hidden name=AEA>   <INPUT class=form_button value=submit type=submit> </FORM>

Or

Please enter your access line id.

      <FORM method=post action=adsl/adslchecker.AccessLineIDOutput><INPUT type=hidden
      name=URL> <INPUT value=a%20service%20provider type=hidden name=SP_NAME>
      ACCESS LINE ID:
<INPUT maxLength=13
      size=14 name=ALID> <INPUT value=56 type=hidden name=VERSION> <INPUT
      value=E type=hidden name=MS> <INPUT value=no type=hidden name=CAP> <INPUT
      value=Y type=hidden name=AEA>   <INPUT class=form_button value=submit type=submit> </FORM>

Or

Please enter your UPRN.

      <FORM method=post action=adsl/ADSLChecker.UPRNoutput><INPUT type=hidden
      name=URL> <INPUT value=a%20service%20provider type=hidden name=SP_NAME>
      UPRN:
<INPUT maxLength=13
      size=14 name=UPRN> <INPUT value=56 type=hidden name=VERSION> <INPUT
      value=E type=hidden name=MS> <INPUT value=no type=hidden name=CAP> <INPUT
      value=Y type=hidden name=AEA>   <INPUT class=form_button value=submit type=submit> </FORM>

If you do not have a telephone number or access line
      id, please select the

   <FORM method=post action=adsl/adslchecker.address>
          <INPUT value="" type=hidden name=url>
          <INPUT value=a%20service%20provider type=hidden name=SP_NAME>
          <INPUT value=56 type=hidden name=VERSION>
          <INPUT value=E type=hidden name=MS>
          <INPUT value=no type=hidden name=CAP>
          <INPUT value=Y type=hidden name=AEA>
          Address Checker
   </FORM>

or the

   <FORM method=post action=adsl/adslchecker.postcode>
          Postcode Checker
          <INPUT value="" type=hidden name=url>
          <INPUT value=a%20service%20provider type=hidden name=SP_NAME>
          <INPUT value=56 type=hidden name=VERSION>
          <INPUT value=E type=hidden name=MS>
          <INPUT value=no type=hidden name=CAP>
          <INPUT value=Y type=hidden name=AEA>
   </FORM>

or the

   <FORM method=post action=adsl/adslchecker.bbeuidform>
          BBEU Checker
          <INPUT value="" type=hidden name=url>
          <INPUT value=a%20service%20provider type=hidden name=SP_NAME>
          <INPUT value=56 type=hidden name=VERSION>
          <INPUT value=E type=hidden name=MS>
          <INPUT value=no type=hidden name=CAP>
          <INPUT value=Y type=hidden name=AEA>
   </FORM>

By submitting a query into this checker you accept Terms of Use for this checker.

'''

Body:
So 1) you're posting to the wrong URL.

From the return HTML, the "action" for the form you want is "adsl/ADSLChecker.UPRNoutput"

2) there are hidden fields in the form you're not submitting

<form method="post" action="adsl/ADSLChecker.UPRNoutput">
    <input type="hidden" name="URL">
    <input value="a%20service%20provider" type="hidden" name="SP_NAME">
    <span class="subheading">UPRN:</span><br>
    <input maxlength="13" size="14" name="UPRN">
    <input value="56" type="hidden" name="VERSION">
    <input value="E" type="hidden" name="MS">
    <input value="no" type="hidden" name="CAP">
    <input value="Y" type="hidden" name="AEA"> &nbsp;
    <input class="form_button" value="submit" type="submit">
</form>

Try:

payload = {
    "UPRN": "10033360983",
    "SP_NAME": "a%20service%20provider",
    "VERSION": "56",
    "MS": "E",
    "CAP": "no",
    "AEA": "Y"
}
url = 'https://www.dslchecker.bt.com/adsl/ADSLChecker.UPRNoutput'
r = requests.post(url, data = payload)


问:
V-Lookup across multiple arrays
I am having trouble using lookup functions to achieve the following.

From Table-1, I need to look-up the Items list, and depending on what type of item it is (Fruit/Veg/Seed), pull in the corresponding percentage to Table-2.  I have tried to so this using Vlookup and nested IFs but its not working.

```<code>=IF((VLOOKUP($A$10:$A$16,$A$1:$E$8,2,FALSE)=$B$9),$C$1:$C$8,IF((VLOOKUP($A$10:$A$16,$A$1:$E$8,4,FALSE)= $E$1:$E$8,""))
</code>```

答:
You need to do two VLOOKUP's.  The first for Cat-1, and the second for Cat-2:

```<code>=IF(VLOOKUP($B13,$B$4:$F$10,2,FALSE)=C$12,VLOOKUP($B13,$B$4:$F$10,3,FALSE),
IF(VLOOKUP($B13,$B$4:$F$10,4,FALSE)=C$12,VLOOKUP($B13,$B$4:$F$10,5,FALSE),""))
</code>```

Enter in C13 and fill across and down.

The second VLOOKUP is entered into the value_if_false portion of the first IF.

Title: V-Lookup across multiple arrays

Body:
I am having trouble using lookup functions to achieve the following.

From Table-1, I need to look-up the Items list, and depending on what type of item it is (Fruit/Veg/Seed), pull in the corresponding percentage to Table-2.  I have tried to so this using Vlookup and nested IFs but its not working.

=IF((VLOOKUP($A$10:$A$16,$A$1:$E$8,2,FALSE)=$B$9),$C$1:$C$8,IF((VLOOKUP($A$10:$A$16,$A$1:$E$8,4,FALSE)= $E$1:$E$8,""))

Body:
You need to do two VLOOKUP's.  The first for Cat-1, and the second for Cat-2:

=IF(VLOOKUP($B13,$B$4:$F$10,2,FALSE)=C$12,VLOOKUP($B13,$B$4:$F$10,3,FALSE),
IF(VLOOKUP($B13,$B$4:$F$10,4,FALSE)=C$12,VLOOKUP($B13,$B$4:$F$10,5,FALSE),""))

Enter in C13 and fill across and down.

The second VLOOKUP is entered into the value_if_false portion of the first IF.


问:
How can I get only one row if only one column is different
I have a table with patient ID's, contact dates and actioncodes. I want to retrieve all rows with actioncodes equal to EPS or D, however i want to keep only one row if the actioncode exists on the same contactdate.

For example this is part of my table, journal:

```<code>PatientID  Contactdate  Actioncode
1          2010-5-6     EPS
1          2010-5-6     D
1          2012-3-4     CNT
1          2013-7-8     D
2          2010-1-4     EPS
2          2010-5-6     D
</code>```

This is the code i have now to retrieve all rows where actioncode is either EPS or D

```<code>select * from journal j where j.actioncode in ('EPS', 'D')
</code>```

I tried group by contactdate, but then i miss the rows where the patients are different. The same effect occurs with distinct(contactdate). What can i use here to return only one row when the date and the patientid are similar and the actioncode is either D or EPS?

Preferred outcome:

```<code>PatientID   Contactd   Actioncode
1           2010-5-6   D
1           2012-3-4   D
2           2010-1-4   EPS
2           2010-5-6   D
</code>```

答:
We can try using ROW_NUMBER here:

```<code>WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY PatientID, Contactdate
                                 ORDER BY Actioncode) rn
    FROM journal
    WHERE Actioncode in ('EPS', 'D')
)

SELECT PatientID, Contactdate, Actioncode
FROM cte
WHERE rn = 1;
</code>```

This arbitrarily would always retain the Actioncode='D' record, should both action codes appear.  If instead you would want to retain the EPS record, then modify the call to ROW_NUMBER to use ORDER BY Actioncode DESC.

Body:
I have a table with patient ID's, contact dates and actioncodes. I want to retrieve all rows with actioncodes equal to EPS or D, however i want to keep only one row if the actioncode exists on the same contactdate.

For example this is part of my table, journal:

PatientID  Contactdate  Actioncode
1          2010-5-6     EPS
1          2010-5-6     D
1          2012-3-4     CNT
1          2013-7-8     D
2          2010-1-4     EPS
2          2010-5-6     D

This is the code i have now to retrieve all rows where actioncode is either EPS or D

select * from journal j where j.actioncode in ('EPS', 'D')

I tried group by contactdate, but then i miss the rows where the patients are different. The same effect occurs with distinct(contactdate). What can i use here to return only one row when the date and the patientid are similar and the actioncode is either D or EPS?

Preferred outcome:

PatientID   Contactd   Actioncode
1           2010-5-6   D
1           2012-3-4   D
2           2010-1-4   EPS
2           2010-5-6   D

Body:
We can try using ROW_NUMBER here:

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY PatientID, Contactdate
                                 ORDER BY Actioncode) rn
    FROM journal
    WHERE Actioncode in ('EPS', 'D')
)

SELECT PatientID, Contactdate, Actioncode
FROM cte
WHERE rn = 1;

This arbitrarily would always retain the Actioncode='D' record, should both action codes appear.  If instead you would want to retain the EPS record, then modify the call to ROW_NUMBER to use ORDER BY Actioncode DESC.


问:
Compare values from two queries and return matching values in Ruby
I need to get IDs of a model from two separate queries and check if the same IDs are present in both queries. If not then I must pass the string Not present wherever it is not or else I must pass the value.

```<code>class Purchase
    belongs_to :customer
    belongs_to :selected_items

class SelectedItem
    has_many :purchases
    has_many :sub_categories
    has_many :categories, through: :sub_categories

class SubCategory
    belongs_to :selected_item
    belongs_to :categories

class Category
    has_many :sub_categories
    has_many :selected_items, through: :sub_categories

class Customer
    has_many :purchases
</code>```

```<code>selected_items = @category.selected_items

def get_values(customer, selected_items)
    purchases = Purchase.where(customer_id: customer.id)
    selected_items_ids = selected_items.collect { |selected_item| selected_item.id }
    purchased_selected_items_ids = purchases.collect { |purchase| purchase.selected_item_id }
    both_present = selected_items_ids & purchased_selected_items_ids
    # after this how can I send "Not purchased" string for whichever id is not present or send the send the purchased item name wherever ids present in both?
</code>```

In the get_values method I need to compare the ids of SelectedItem between purchases and selected_items. If the id of any item in selected_item is in any item in purchases then I should return purchased, if not then the purchase for that selected_item will not be in the database meaning it will return blank in the query. So then I must return Not purchased string. This is done for each customer. How can I do that? Here I am displaying the results in table in erb file. So the columns for each selected_item will be created. I should pass the values of whether each customer has purchased or not for each of the selected_item.

答:
```<code>def get_values(customer, selected_items)
  purchases = Purchase.where(customer_id: customer.id)
  selected_items_ids = selected_items.collect { |selected_item| selected_item.id }
  purchased_selected_items_ids = purchases.collect { |purchase| purchase.selected_item_id }
  purchased = selected_items_ids & purchased_selected_items_ids
  not_purchased = (selected_items_ids - purchased_selected_items_ids) +
                (purchased_selected_items_ids - selected_items_ids)
end
</code>```

I think now you will be able to return both the purchased items and not purchased items. You can simply return an array [purchased, not_purchased] where both purchased and not_purchased will be array and contain respective ids or you can iterate over them and create a hash with the id as key and value will be item_name(for purchased ids)/not_purchased(for the other ids) and retuen the hash.

Body:
I need to get IDs of a model from two separate queries and check if the same IDs are present in both queries. If not then I must pass the string Not present wherever it is not or else I must pass the value.

class Purchase
    belongs_to :customer
    belongs_to :selected_items

class SelectedItem
    has_many :purchases
    has_many :sub_categories
    has_many :categories, through: :sub_categories

class SubCategory
    belongs_to :selected_item
    belongs_to :categories

class Category
    has_many :sub_categories
    has_many :selected_items, through: :sub_categories

class Customer
    has_many :purchases

selected_items = @category.selected_items

def get_values(customer, selected_items)
    purchases = Purchase.where(customer_id: customer.id)
    selected_items_ids = selected_items.collect { |selected_item| selected_item.id }
    purchased_selected_items_ids = purchases.collect { |purchase| purchase.selected_item_id }
    both_present = selected_items_ids & purchased_selected_items_ids
    # after this how can I send "Not purchased" string for whichever id is not present or send the send the purchased item name wherever ids present in both?

In the get_values method I need to compare the ids of SelectedItem between purchases and selected_items. If the id of any item in selected_item is in any item in purchases then I should return purchased, if not then the purchase for that selected_item will not be in the database meaning it will return blank in the query. So then I must return Not purchased string. This is done for each customer. How can I do that? Here I am displaying the results in table in erb file. So the columns for each selected_item will be created. I should pass the values of whether each customer has purchased or not for each of the selected_item.

Body:
def get_values(customer, selected_items)
  purchases = Purchase.where(customer_id: customer.id)
  selected_items_ids = selected_items.collect { |selected_item| selected_item.id }
  purchased_selected_items_ids = purchases.collect { |purchase| purchase.selected_item_id }
  purchased = selected_items_ids & purchased_selected_items_ids
  not_purchased = (selected_items_ids - purchased_selected_items_ids) +
                (purchased_selected_items_ids - selected_items_ids)
end

I think now you will be able to return both the purchased items and not purchased items. You can simply return an array [purchased, not_purchased] where both purchased and not_purchased will be array and contain respective ids or you can iterate over them and create a hash with the id as key and value will be item_name(for purchased ids)/not_purchased(for the other ids) and retuen the hash.


问:
last friday of a given month in sql server
How do i get the date for last friday of the month in T-SQL?

I will be passing the year and month as parameter,e.g, 201211.
If I pass '201211' as parameter it should return me '20121130' as answer as it's the date of last friday of month of november'12.

答:
I created a scalar function for this:</p>

```<code>create function [dbo].[lastDWMonth]
    (
     @y int
    ,@m int
    ,@dw int
    )

returns date

as

begin

declare @d date

;with x as
    (
    select datefromparts(@y,@m,1) d

    union all

    select dateadd(day,1,d) from x where d < eomonth(datefromparts(@y,@m,1))
    )

select
    @d = max(d)
from
    x
where
    datepart(dw,d) = @dw

return @d

end
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I created a scalar function for this:

create function [dbo].[lastDWMonth]
    (
     @y int
    ,@m int
    ,@dw int
    )

returns date

as

begin

declare @d date

;with x as
    (
    select datefromparts(@y,@m,1) d

    union all

    select dateadd(day,1,d) from x where d < eomonth(datefromparts(@y,@m,1))
    )

select
    @d = max(d)
from
    x
where
    datepart(dw,d) = @dw

return @d

end


问:
Reflection using generics
I'd like to return the properties of a series of DbSet objects I have saved to a class using reflection, but in order to access this data in a single method I'd need to pass a variable as an accessor to return the properties of that object.

Currently I've managed to return the properties of all of the DbSet objects, but the code looks very DRY.

```<code>public DbSet<Foo> Foo {get;set;}
public DbSet<Bar> Bar {get;set;}

public List<string> GetPropertiesFoo()
{
    DbContext client = new DbContext();
    return client.Foo.GetType().GetProperties().Select(e => e.Name).ToList();
}
public List<string> GetPropertiesBar()
{
    DbContext client = new DbContext();
    return client.Bar.GetType().GetProperties().Select(e => e.Name).ToList();
}
</code>```

My intention is to refactor this so that it accepts a DbSet name as an argument and returns a single list of properties, rather than a list of all properties.

答:
I think you might be after something like this

public List<string> GetProperties(string model)
{
   var property =
      this.GetType()
      .GetProperties()
      .Where(p=>p.Name == model)
      .FirstOrDefault();

   if(property == null) return IEnumerable.Empty<string>().ToList();
   return property
      .PropertyType
      .GetGenericArguments()[0]
      .GetProperties()
      .Select(p=>p.Name)
      .ToList();
}
```

Title: Reflection using generics

Body:
I'd like to return the properties of a series of DbSet objects I have saved to a class using reflection, but in order to access this data in a single method I'd need to pass a variable as an accessor to return the properties of that object.

Currently I've managed to return the properties of all of the DbSet objects, but the code looks very DRY.

public DbSet<Foo> Foo {get;set;}
public DbSet<Bar> Bar {get;set;}

public List<string> GetPropertiesFoo()
{
    DbContext client = new DbContext();
    return client.Foo.GetType().GetProperties().Select(e => e.Name).ToList();
}
public List<string> GetPropertiesBar()
{
    DbContext client = new DbContext();
    return client.Bar.GetType().GetProperties().Select(e => e.Name).ToList();
}

My intention is to refactor this so that it accepts a DbSet name as an argument and returns a single list of properties, rather than a list of all properties.


问:
Divide Number Array into chunk of 3 using Reduce
There can be multiple approach to solve this but I am not sure why this one specifically is not working as expected.

```<code>[1,2,3,4,5,6,7,8].reduce((a, d, i, c) => [...a, c.splice(0, 3)], [])
</code>```

Result - [[1,2,3], [4,5,6]]

Expected Result - [[1,2,3], [4,5,6], [7,8]]

Please do not change the approach as I want to know why this one is not working as expected.

答:
I want to know why this one is not working as expected.

The problem is that you're removing entries from the original array, so reduce runs out of elements early because prior to each callback, it checks to see if the index it's about to visit is still less than the array length. After the second callback, the original array's length is 2, and the index is 2, so reduce stops, never producing the third chunk.

If you write it in its longer form, it's easier to see what's going on when you step through it in the debugger. Rather than recording a video, I'll just instrument the code:

[1,2,3,4,5,6,7,8].reduce((a, d, i, c) => {
  console.log("i", i, "c", JSON.stringify(c));
  return [...a, c.splice(0, 3)];
}, []);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {
    max-height: 100% !important;
 }</code>```

As you can see, in the first calback all is good:

```
i 0 c [1,2,3,4,5,6,7,8]
```

it's also okay in the second callback, but notice how c is shorter now:

```
i 1 c [4,5,6,7,8]
```

After splice has done its work in that second callback, though, c will be [7, 8] and so its length is just 2. reduce stops there, because i is now 2, and it only continues when i < length is true. 2 < 2 is false, so it stops.

You can't do this reasonably with reduce. Instead, see the canonical "chunk" array question's answers. You can do it with reduceRight as Nenad Vracar points out. (Hopefully, he/she posts that as an answer.)

Body:
There can be multiple approach to solve this but I am not sure why this one specifically is not working as expected.

[1,2,3,4,5,6,7,8].reduce((a, d, i, c) => [...a, c.splice(0, 3)], [])

Result - [[1,2,3], [4,5,6]]

Expected Result - [[1,2,3], [4,5,6], [7,8]]

Please do not change the approach as I want to know why this one is not working as expected.

Body:
I want to know why this one is not working as expected.

The problem is that you're removing entries from the original array, so reduce runs out of elements early because prior to each callback, it checks to see if the index it's about to visit is still less than the array length. After the second callback, the original array's length is 2, and the index is 2, so reduce stops, never producing the third chunk.

If you write it in its longer form, it's easier to see what's going on when you step through it in the debugger. Rather than recording a video, I'll just instrument the code:

[1,2,3,4,5,6,7,8].reduce((a, d, i, c) => {
  console.log("i", i, "c", JSON.stringify(c));
  return [...a, c.splice(0, 3)];
}, []);

.as-console-wrapper {
    max-height: 100% !important;
 }

As you can see, in the first calback all is good:

i 0 c [1,2,3,4,5,6,7,8]

it's also okay in the second callback, but notice how c is shorter now:

i 1 c [4,5,6,7,8]

After splice has done its work in that second callback, though, c will be [7, 8] and so its length is just 2. reduce stops there, because i is now 2, and it only continues when i < length is true. 2 < 2 is false, so it stops.

You can't do this reasonably with reduce. Instead, see the canonical "chunk" array question's answers. You can do it with reduceRight as Nenad Vracar points out. (Hopefully, he/she posts that as an answer.)


问:
disable Double tap zoom/resize on safari IOS12***
I search 99% website on internet...
nope answer can solve my problem..i am using ios 12...
does any jQuery can totally disable safari double tap now???

or can I have some code detect function when(if user is double tapped?

I spend 2weeks for that i still not find the solution..
This is what i tried...
CSS:

```<code>* {
  -webkit-text-size-adjust: none;
  zoom: 1;
  touch-action: manipulation;
}
* {
  cursor: pointer;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
</code>```

and
disable viewport zooming iOS 10+ safari?

I hate safari..

答:
Adding an empty click listener on HTML elements will prevent double tap zoom.

It's ugly but does the job.

```<code>myElement.addEventListener("click", event => {});
</code>```

Next thing i'm trying to figure out to disable all zooming is preventing pinch.

Unfortunately, touch events are not dispatched during iOs momentum scrolling.
The following code works as long as the page is not scrolling (tested only on 12.2) :

```<code>document.addEventListener("touchstart", event => {
    if(event.touches.length > 1) {
        console.log("zoom plz stahp");
        event.preventDefault();
        event.stopPropagation(); // maybe useless
    }
}, {passive: false});
</code>```

Body:
I search 99% website on internet...
nope answer can solve my problem..i am using ios 12...
does any jQuery can totally disable safari double tap now???

or can I have some code detect function when(if user is double tapped?

I spend 2weeks for that i still not find the solution..
This is what i tried...
CSS:

* {
  -webkit-text-size-adjust: none;
  zoom: 1;
  touch-action: manipulation;
}
* {
  cursor: pointer;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}

and
disable viewport zooming iOS 10+ safari?

I hate safari..

Body:
Adding an empty click listener on HTML elements will prevent double tap zoom.

It's ugly but does the job.

myElement.addEventListener("click", event => {});

Next thing i'm trying to figure out to disable all zooming is preventing pinch.

Unfortunately, touch events are not dispatched during iOs momentum scrolling.
The following code works as long as the page is not scrolling (tested only on 12.2) :

document.addEventListener("touchstart", event => {
    if(event.touches.length > 1) {
        console.log("zoom plz stahp");
        event.preventDefault();
        event.stopPropagation(); // maybe useless
    }
}, {passive: false});


问:
Disposed object error when dealing reading multipart form data in asp.net mv4 web api
The setup I have is an asp.net mvc 4 project using .net 4.5 and Entity Framework 5. The language is C#.

The code is mainly a straight copy from the microsoft tutorials with using multiform data to handle the post requests. What is happening is that when I attempt to access the ContentLength of the file, it throws a System.ObjectDisposedException. The full stacktrace follows the code snippet.

```<code>    public async Task<HttpResponseMessage> PostFormData()
    {
        // Check if the request contains multipart/form-data.
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        string root = HttpContext.Current.Server.MapPath("~/App_Data");
        var provider = new MultipartFormDataStreamProvider(root);

        try
        {
            // Read the form data.
            await Request.Content.ReadAsMultipartAsync(provider);

            // This illustrates how to get the file names.
            foreach (MultipartFileData file in provider.FileData)
            {
                Debug.WriteLine(file.Headers.ContentDisposition.FileName);
                Debug.WriteLine("Server file path: " + file.LocalFileName);
                Debug.WriteLine("Content type: " + file.Headers.ContentType);
                Debug.WriteLine("This wont work: " + file.Headers.ContentLength);
            }
            return Request.CreateResponse(HttpStatusCode.OK, "OK");
        }
        catch (System.Exception e)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
        }
    }
</code>```

Stacktrace:

A first chance exception of type 'System.ObjectDisposedException' occurred in System.Net.Http.dll
iisexpress.exe Error: 0 : Operation=ReflectedHttpActionDescriptor.ExecuteAsync, Exception=System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.Net.Http.StringContent'.
   at System.Net.Http.HttpContent.CheckDisposed()
   at System.Net.Http.HttpContent.GetComputedOrBufferLength()
   at System.Net.Http.Headers.HttpContentHeaders.get_ContentLength()
   at FieldAssistant.Controllers.SpeedTestController.<PostFormData>d__0.MoveNext() in c:\Users\matt.delves\blah\FieldAssistant\Controllers\SpeedTestController.cs:line 48
iisexpress.exe Error: 0 : Operation=ApiControllerActionInvoker.InvokeActionAsync, Exception=System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.Net.Http.StringContent'.
   at System.Net.Http.HttpContent.CheckDisposed()
   at System.Net.Http.HttpContent.GetComputedOrBufferLength()
   at System.Net.Http.Headers.HttpContentHeaders.get_ContentLength()
   at FieldAssistant.Controllers.SpeedTestController.<PostFormData>d__0.MoveNext() in c:\Users\matt.delves\blah\FieldAssistant\Controllers\SpeedTestController.cs:line 48
iisexpress.exe Error: 0 : Operation=SpeedTestController.ExecuteAsync, Exception=System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.Net.Http.StringContent'.
   at System.Net.Http.HttpContent.CheckDisposed()
   at System.Net.Http.HttpContent.GetComputedOrBufferLength()
   at System.Net.Http.Headers.HttpContentHeaders.get_ContentLength()
   at FieldAssistant.Controllers.SpeedTestController.<PostFormData>d__0.MoveNext() in c:\Users\matt.delves\blah\FieldAssistant\Controllers\SpeedTestController.cs:line 48
iisexpress.exe Information: 0 : Message='Will use same 'JsonMediaTypeFormatter' formatter', Operation=JsonMediaTypeFormatter.GetPerRequestFormatterInstance
iisexpress.exe Information: 0 : Message='Selected formatter='JsonMediaTypeFormatter', content-type='application/json; charset=utf-8'', Operation=DefaultContentNegotiator.Negotiate
iisexpress.exe Information: 0 : Response, Status=500 (InternalServerError), Method=POST, Url=http://192.168.2.63:51230/api/speedtest, Message='Content-type='application/json; charset=utf-8', content-length=unknown'
iisexpress.exe Information: 0 : Operation=JsonMediaTypeFormatter.WriteToStreamAsync
iisexpress.exe Information: 0 : Operation=SpeedTestController.Dispose
The program '[4436] iisexpress.exe: Managed (v4.0.30319)' has exited with code 0 (0x0).

There have been some suggestions that modifying the web.config with a couple of lines are meant to resolve the issue but having inserted those, I found that they didn't work.

I'm not primarily a microsoft / c# guy so as much explanation in the response would be greatly appreciated.

答:
I had the same issue and it was resolved as below:

```<code>var fileSize = new FileInfo(file.LocalFileName).Length;
</code>```

This code is added inside the loop instead of

```<code>Debug.WriteLine("This wont work: " + file.Headers.ContentLength);
</code>```

Body:
The setup I have is an asp.net mvc 4 project using .net 4.5 and Entity Framework 5. The language is C#.

The code is mainly a straight copy from the microsoft tutorials with using multiform data to handle the post requests. What is happening is that when I attempt to access the ContentLength of the file, it throws a System.ObjectDisposedException. The full stacktrace follows the code snippet.

    public async Task<HttpResponseMessage> PostFormData()
    {
        // Check if the request contains multipart/form-data.
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        string root = HttpContext.Current.Server.MapPath("~/App_Data");
        var provider = new MultipartFormDataStreamProvider(root);

        try
        {
            // Read the form data.
            await Request.Content.ReadAsMultipartAsync(provider);

            // This illustrates how to get the file names.
            foreach (MultipartFileData file in provider.FileData)
            {
                Debug.WriteLine(file.Headers.ContentDisposition.FileName);
                Debug.WriteLine("Server file path: " + file.LocalFileName);
                Debug.WriteLine("Content type: " + file.Headers.ContentType);
                Debug.WriteLine("This wont work: " + file.Headers.ContentLength);
            }
            return Request.CreateResponse(HttpStatusCode.OK, "OK");
        }
        catch (System.Exception e)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
        }
    }

Stacktrace:

A first chance exception of type 'System.ObjectDisposedException' occurred in System.Net.Http.dll
iisexpress.exe Error: 0 : Operation=ReflectedHttpActionDescriptor.ExecuteAsync, Exception=System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.Net.Http.StringContent'.
   at System.Net.Http.HttpContent.CheckDisposed()
   at System.Net.Http.HttpContent.GetComputedOrBufferLength()
   at System.Net.Http.Headers.HttpContentHeaders.get_ContentLength()
   at FieldAssistant.Controllers.SpeedTestController.<PostFormData>d__0.MoveNext() in c:\Users\matt.delves\blah\FieldAssistant\Controllers\SpeedTestController.cs:line 48
iisexpress.exe Error: 0 : Operation=ApiControllerActionInvoker.InvokeActionAsync, Exception=System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.Net.Http.StringContent'.
   at System.Net.Http.HttpContent.CheckDisposed()
   at System.Net.Http.HttpContent.GetComputedOrBufferLength()
   at System.Net.Http.Headers.HttpContentHeaders.get_ContentLength()
   at FieldAssistant.Controllers.SpeedTestController.<PostFormData>d__0.MoveNext() in c:\Users\matt.delves\blah\FieldAssistant\Controllers\SpeedTestController.cs:line 48
iisexpress.exe Error: 0 : Operation=SpeedTestController.ExecuteAsync, Exception=System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.Net.Http.StringContent'.
   at System.Net.Http.HttpContent.CheckDisposed()
   at System.Net.Http.HttpContent.GetComputedOrBufferLength()
   at System.Net.Http.Headers.HttpContentHeaders.get_ContentLength()
   at FieldAssistant.Controllers.SpeedTestController.<PostFormData>d__0.MoveNext() in c:\Users\matt.delves\blah\FieldAssistant\Controllers\SpeedTestController.cs:line 48
iisexpress.exe Information: 0 : Message='Will use same 'JsonMediaTypeFormatter' formatter', Operation=JsonMediaTypeFormatter.GetPerRequestFormatterInstance
iisexpress.exe Information: 0 : Message='Selected formatter='JsonMediaTypeFormatter', content-type='application/json; charset=utf-8'', Operation=DefaultContentNegotiator.Negotiate
iisexpress.exe Information: 0 : Response, Status=500 (InternalServerError), Method=POST, Url=http://192.168.2.63:51230/api/speedtest, Message='Content-type='application/json; charset=utf-8', content-length=unknown'
iisexpress.exe Information: 0 : Operation=JsonMediaTypeFormatter.WriteToStreamAsync
iisexpress.exe Information: 0 : Operation=SpeedTestController.Dispose
The program '[4436] iisexpress.exe: Managed (v4.0.30319)' has exited with code 0 (0x0).

There have been some suggestions that modifying the web.config with a couple of lines are meant to resolve the issue but having inserted those, I found that they didn't work.

I'm not primarily a microsoft / c# guy so as much explanation in the response would be greatly appreciated.

Body:
I had the same issue and it was resolved as below:

var fileSize = new FileInfo(file.LocalFileName).Length;

This code is added inside the loop instead of

Debug.WriteLine("This wont work: " + file.Headers.ContentLength);


问:
Getting mouse-position relatively to a control
I'm trying to find a way to get the mouse position relatively to the upper left corner of a control, is there a way to accomplish that?</p>

Body: yourControl.PointToClient(Control.MousePosition)


问:
Updated FacobookLogin Pod, Got Error: No known class method for selector 'objectForJSONString:error:'
Recently I have updated the Below mentioned pods for FacebookLogin Button implemented in my app

```<code>pod 'FacebookCore'
pod 'FacebookLogin'
</code>```

The versions of both pods are 0.7.0

I had updated the pods using the command

```<code>pod update
</code>```

After updating the when I built the project there is an error in the path

Pods/FBSDKLoginKit/FBSDKLoginKit/FBSDKLoginKit/Internal/FBSDKLoginManagerLogger.m:163:60: No known class method for selector 'objectForJSONString:error:'

Both these errors is occurring in two places in the same class

No known class method for selector 'objectForJSONString:error:'

```<code>NSDictionary<id, id> *clientState = [FBSDKBasicUtility objectForJSONString:parameters[FBSDKLoginManagerLoggingClientStateKey] error:NULL];
</code>```

答:
I did my R&D, there was no solution.
I solved it by just removing the entire FacebookLogin Pods,

```<code>#pod 'FacebookCore'
#pod 'FacebookLogin'
</code>```

Then Built the project, and then re-installed the same pods with the latest version to 5.0, then the issue seems to solved.

Body:
Recently I have updated the Below mentioned pods for FacebookLogin Button implemented in my app

pod 'FacebookCore'
pod 'FacebookLogin'

The versions of both pods are 0.7.0

I had updated the pods using the command

pod update

After updating the when I built the project there is an error in the path

Pods/FBSDKLoginKit/FBSDKLoginKit/FBSDKLoginKit/Internal/FBSDKLoginManagerLogger.m:163:60: No known class method for selector 'objectForJSONString:error:'

Both these errors is occurring in two places in the same class

No known class method for selector 'objectForJSONString:error:'

NSDictionary<id, id> *clientState = [FBSDKBasicUtility objectForJSONString:parameters[FBSDKLoginManagerLoggingClientStateKey] error:NULL];

Body:
I did my R&D, there was no solution.
I solved it by just removing the entire FacebookLogin Pods,

#pod 'FacebookCore'
#pod 'FacebookLogin'

Then Built the project, and then re-installed the same pods with the latest version to 5.0, then the issue seems to solved.


问:
Setting a protocol based theme in a View Controller
I managed to get protocol-based theming working based on this: https://basememara.com/protocol-oriented-themes-for-ios-apps/

However, while setting theme.apply(for: application) in AppDelegate works, using the same as theme.apply(for: UIApplication) inside a View Controller throws a error: Cannot convert value of type 'UIApplication.Type' to expected argument type 'UIApplication'

What’s going wrong here?

答:
In theme.apply(for: application) you pass an instance of UIApplication as argument.
In theme.apply(for: UIApplication) you pass UIApplication as type and it causes error because function expects instance of UIApplication to be passed.
Try to pass UIApplication.shared instead. Like this:

```<code>theme.apply(for: UIApplication.shared)
</code>```

It should help.

Body:
In theme.apply(for: application) you pass an instance of UIApplication as argument.
In theme.apply(for: UIApplication) you pass UIApplication as type and it causes error because function expects instance of UIApplication to be passed.
Try to pass UIApplication.shared instead. Like this:

theme.apply(for: UIApplication.shared)

It should help.


问:
How to set focus on show, where ngIf bind change to true?
I am trying to do editable cell:

```<code>  <ng-template pCellDef [column]="field.property" let-row="row" let-inEdit="false">
    <div style="height: 50px; width: 100%" (click)="inEdit=true" (blur)="inEdit=false">
    <div *ngIf="!inEdit">
      {{row[field.property]}}
    </div>
    <mat-form-field *ngIf="inEdit" class="example-full-width">
      <input matInput [(ngModel)]="row[field.property]">
    </mat-form-field>
    </div>
  </ng-template>
</code>```

It is working well, the final thing that I need to do , is to set focus on input, that let the user to type.

So, there is a way to do that, without exclude the input to component?

something like  (onShow)="this.focus()" ?

答:
Try autofocus :

```<code><mat-form-field *ngIf="inEdit" class="example-full-width">
  <input matInput [(ngModel)]="row[field.property]" autofocus>
</mat-form-field>
</code>```

Body:
I am trying to do editable cell:

  <ng-template pCellDef [column]="field.property" let-row="row" let-inEdit="false">

      {{row[field.property]}}

    <mat-form-field *ngIf="inEdit" class="example-full-width">
      <input matInput [(ngModel)]="row[field.property]">
    </mat-form-field>

  </ng-template>

It is working well, the final thing that I need to do , is to set focus on input, that let the user to type.

So, there is a way to do that, without exclude the input to component?

something like  (onShow)="this.focus()" ?

Body:
Try autofocus :

<mat-form-field *ngIf="inEdit" class="example-full-width">
  <input matInput [(ngModel)]="row[field.property]" autofocus>
</mat-form-field>


答:
You can use ElementRef here is the example

HTML

```<code> <ng-template pCellDef [column]="field.property" let-row="row" let-inEdit="false">
    <div style="height: 50px; width: 100%" (click)="inEdit=true" (blur)="inEdit=false">
    <div *ngIf="!inEdit">
      {{row[field.property]}}
    </div>
    <mat-form-field *ngIf="inEdit" class="example-full-width">
      <input matInput [(ngModel)]="row[field.property]" #inputRef>
    </mat-form-field>
    </div>
  </ng-template>

</code>```

TS

```<code>@ViewChild('inputRef') inputRefData : ElementRef

customFocus() {
  this.inputRefData.nativeElement.focus();
}

</code>```

Title: How to set focus on show, where ngIf bind change to true?

Body:
You can use ElementRef here is the example

HTML

 <ng-template pCellDef [column]="field.property" let-row="row" let-inEdit="false">
    <div style="height: 50px; width: 100%" (click)="inEdit=true" (blur)="inEdit=false">
    <div *ngIf="!inEdit">
      {{row[field.property]}}
    </div>
    <mat-form-field *ngIf="inEdit" class="example-full-width">
      <input matInput [(ngModel)]="row[field.property]" #inputRef>
    </mat-form-field>
    </div>
  </ng-template>

TS

@ViewChild('inputRef') inputRefData : ElementRef

customFocus() {
  this.inputRefData.nativeElement.focus();
}


问:
How to insert a random string into the sed 's//' replace string for each line actioned?
This:

echo "    " | tr ' ' '\n' | sed "s|.*|$RANDOM|"

Or this:

echo "    " | tr ' ' '\n' | sed "s|.*|$(echo $RANDOM)|"

Will print a list of 5 numbers (space is replaced by newline, sed replaces each line with $RANDOM), and those 5 numbers will all be the same:

```<code>$ echo "    " | tr ' ' '\n' | sed "s|.*|$(echo $RANDOM)|"
21590
21590
21590
21590
21590
</code>```

This is because the replace of $RANDOM to a random value happens only once.

What is the easiest and shortest way, preferably by only using sed, to actually print a different random number for each line. i.e. to provide some "secondary input stream" which differs for each line that sed handles?

I could do it with xargs, but I wonder if there is a way to do it with sed only.

答:
Question:

What is the easiest and shortest way, preferably by only using sed, to actually print a different random number for each line?

Answer:

```<code>echo "    " | tr ' ' '\n' | perl -pe 's|.*|int(rand(89999))+10000|e'
</code>```

or simply:

```<code>perl -e 'printf "%05s\n",int(rand(100000)) for (1..5)'
</code>```

Explanation:

I don't see why one shoudn't use Perl, or any tool that's possibly more suitable for the job. In the OP there's no hint of a reason to stick to sed, which is on the contrary only denoted as a preference.

I wonder why one would go through a substitution in order to print five random numbers. No details are given about the bigger picture, but it certainly makes me curious.

Body:
This:

echo "    " | tr ' ' '\n' | sed "s|.*|$RANDOM|"

Or this:

echo "    " | tr ' ' '\n' | sed "s|.*|$(echo $RANDOM)|"

Will print a list of 5 numbers (space is replaced by newline, sed replaces each line with $RANDOM), and those 5 numbers will all be the same:

$ echo "    " | tr ' ' '\n' | sed "s|.*|$(echo $RANDOM)|"
21590
21590
21590
21590
21590

This is because the replace of $RANDOM to a random value happens only once.

What is the easiest and shortest way, preferably by only using sed, to actually print a different random number for each line. i.e. to provide some "secondary input stream" which differs for each line that sed handles?

I could do it with xargs, but I wonder if there is a way to do it with sed only.

Body:
Question:

What is the easiest and shortest way, preferably by only using sed, to actually print a different random number for each line?

Answer:

echo "    " | tr ' ' '\n' | perl -pe 's|.*|int(rand(89999))+10000|e'

or simply:

perl -e 'printf "%05s\n",int(rand(100000)) for (1..5)'

Explanation:

I don't see why one shoudn't use Perl, or any tool that's possibly more suitable for the job. In the OP there's no hint of a reason to stick to sed, which is on the contrary only denoted as a preference.

I wonder why one would go through a substitution in order to print five random numbers. No details are given about the bigger picture, but it certainly makes me curious.


问:
SQLiteDatabase vs File storage
I want to store structure type data (i.e. information of call logs like name, number, type of number, date, time, duration). Which is the best way and which is faster? SQLiteDatabase (make table and insert, delete logs in it) or use file storage (means make one class for all parameters and write their objects in file using input/output Stream and serializable) or the another way i heard about it is XML parser but i don't know this.

Please help me. Thanks in advance.

答: I can't give a very informed answer here because I'm just as new to the subject as you are, but here is the link from the developers page that goes over the different types of data storage. I hope you find it useful. http://developer.android.com/guide/topics/data/data-storage.html</p>

Title: SQLiteDatabase vs File storage


问:
Specific reasons to favor pip vs. conda when installing Python packages
I use miniconda as my default python installation. What is the current (2019) wisdom regarding when to install something with conda vs. pip?

My usual behavior is to install everything with pip, and only using conda if a package is not available through pip or the pip version doesn't work correctly.

Are there advantages to always favoring conda install? Are there issues associated with mixing the two installers? What factors should I be considering?

OBJECTIVITY: This is not an opinion-based question! My question is when I have the option to install a python package with pip or conda, how do I make an informed decision? Not "tell me which is better, but "Why would I use one over the other, and will oscillating back & forth cause problems / inefficiencies?"

答:
When using an anaconda ecosystem, you should always prefer conda before pip.

The docs specifically mention this: (emphasis mine)

If a package is not available from conda or Anaconda.org, you may be
  able to find and install the package with another package manager like
  pip.

Pip packages do not have all the features of conda packages and we
  recommend first trying to install any package with conda. If the
  package is unavailable through conda, try installing it with pip. The
  differences between pip and conda packages cause certain unavoidable
  limits in compatibility but conda works hard to be as compatible with
  pip as possible.

Using conda packages can help your environment stay consistent, especially if you require managing a lot of dependencies within the same environment (or don't have an environment but use the base environment directly).


问:
How to ignore locked resources with 'Complete' mode deployment to Azure?
Our team is using a deployment that uses multiple ARM templates to setup our environment. The first ARM template is set to deployment mode 'Complete' and removes everything, but a storage account. We're using Azure CLI to make the deployment:

```<code>az group deployment create \
    --mode Incremental \
    --resource-group $resourceGroupName \
    --template-file $BUILD_SOURCESDIRECTORY'/Infrastructure/azuredeploy.json' \
    --parameters $BUILD_SOURCESDIRECTORY'/Infrastructure/azuredeploy.parameters.'$environment'.json' \
    --query $query \
    --output json
</code>```

However one of our resource groups contains a few locked resources (which are managed by a different team). In that particular case the strategy with a 'Complete' deployment mode fails, because Azure cannot remove the locked resources.

Understandably of course, but maybe there's a way around this? Can we, for example, instruct the ARM template to ignore specific resources? Or use CLI to instruct something similar?

The obvious way would be to move the resources to a separate resource group, but unfortunately that's not a possiblity for us. I couldn't find any other way yet, but maybe I missed something. Thanks for any answers in advance.

答:
Another way to get around this apart from moving resources to a separate resource group (which you say is ruled out in your case anyway), would be to use Conditions with your resources.

Do note that in complete mode, Resource Manager deletes resources that exist in the resource group but aren't specified in the template. Resources that are specified in the template, but not deployed because a condition evaluates to false, aren't deleted.

For more detail on the syntax and examples, please refer to the following resources:

Structure and syntax of Azure Resource Manager templates

Conditionally deploy a resource in an Azure Resource Manager template

Hope this helps!

Body:
Our team is using a deployment that uses multiple ARM templates to setup our environment. The first ARM template is set to deployment mode 'Complete' and removes everything, but a storage account. We're using Azure CLI to make the deployment:

az group deployment create \
    --mode Incremental \
    --resource-group $resourceGroupName \
    --template-file $BUILD_SOURCESDIRECTORY'/Infrastructure/azuredeploy.json' \
    --parameters $BUILD_SOURCESDIRECTORY'/Infrastructure/azuredeploy.parameters.'$environment'.json' \
    --query $query \
    --output json

However one of our resource groups contains a few locked resources (which are managed by a different team). In that particular case the strategy with a 'Complete' deployment mode fails, because Azure cannot remove the locked resources.

Understandably of course, but maybe there's a way around this? Can we, for example, instruct the ARM template to ignore specific resources? Or use CLI to instruct something similar?

The obvious way would be to move the resources to a separate resource group, but unfortunately that's not a possiblity for us. I couldn't find any other way yet, but maybe I missed something. Thanks for any answers in advance.


问:
How to change color of arrow in TextField Select from material-ui
I have a problem with changing color of my arrow icon in Material-ui TextField Select.

I give props:

```<code>icon: {
    fill: "white !important",
  },
</code>```

But the color doesn't change.
I've tried probably everything I've found on the internet.
Input props with icon doesn't work.

```<code><TextField
          id="outlined-select-currency"
          select
          label={label}
          name={this.props.name}
          className={classNames(this.props.classes.textField)}
          onChange={(e) => this.props.handleChange(e)}
          value={this.props.value}
          SelectProps={{
            MenuProps: {
              className: this.props.classes.menu,
              icon: "white !important"
            }
          }}
          InputLabelProps={{
            classes: {
              root: this.props.overrideCssLabel,
              focused: this.props.overrideCssFocusLabel,
              icon: {
                color: "white !important"
              }
            },
          }}
          InputProps={{
            classes: {
              root: this.props.overrideCssInputRoot,
              focused: this.props.overrideCssInputFocus,
              notchedOutline: this.props.overrideCssInputNotchedOutline,
              icon: this.props.icon
            },
            style: {
              color: this.props.color
            },
          }}
          margin="normal"
          variant="outlined"
        >
          {selectList.map(option => (
            <MenuItem key={option.value} value={option.value}>
              {option.label}
            </MenuItem>
          ))}
        </TextField>
</code>```

答:
Just remove the quotes.</p>

```<code>icon: {
    fill: white !important
  }
</code>```

Body:
I have a problem with changing color of my arrow icon in Material-ui TextField Select.

I give props:

icon: {
    fill: "white !important",
  },

But the color doesn't change.
I've tried probably everything I've found on the internet.
Input props with icon doesn't work.

<TextField
          id="outlined-select-currency"
          select
          label={label}
          name={this.props.name}
          className={classNames(this.props.classes.textField)}
          onChange={(e) => this.props.handleChange(e)}
          value={this.props.value}
          SelectProps={{
            MenuProps: {
              className: this.props.classes.menu,
              icon: "white !important"
            }
          }}
          InputLabelProps={{
            classes: {
              root: this.props.overrideCssLabel,
              focused: this.props.overrideCssFocusLabel,
              icon: {
                color: "white !important"
              }
            },
          }}
          InputProps={{
            classes: {
              root: this.props.overrideCssInputRoot,
              focused: this.props.overrideCssInputFocus,
              notchedOutline: this.props.overrideCssInputNotchedOutline,
              icon: this.props.icon
            },
            style: {
              color: this.props.color
            },
          }}
          margin="normal"
          variant="outlined"
        >
          {selectList.map(option => (
            <MenuItem key={option.value} value={option.value}>
              {option.label}
            </MenuItem>
          ))}
        </TextField>

Body:
Just remove the quotes.

icon: {
    fill: white !important
  }


问:
Is XMPP peer to peer connection without server possible?
I am using libjingle for my XMPP connection. Can I connect two XMPP clients without having server in between. If yes how can I do that if no then why it is not possible?

XMPP client1 <---------Direct Audio/Video/IM----------> XMPP client2

答:
You may not be able to do this directly with libjingle, but a protocol specification exists in the form of XEP-0174.  The gist is that you publish your presence and connection information over Multicast DNS (e.g. Bonjour), then connect directly when you want to chat.  Apple's iChat
implements essentially this approach for its peer-to-peer mode.</p>


问:
Connection reset by peer when sending from hardware (GPRS module) but fine when send from PC
tl;dr

Sending the same data from PC and Quectel GPRS module

When send from Quectel, server raises an exception Connection reset by peer

But Quectel works in production environment which has the same EC2-micro instance and a load balancer.

Except for Quectel, another GPRS module - Neoway M680 - works with this EC2 instance.

Setup

Local - Setup

I have a Quectel M66, a GPRS module that I'm using to connect to the server (AWS EC2) and transfer some data.

I also have a python script I've made to connect and send the same data using a PC. Here below is the python script

import socket
import sys
from io import open
from time import sleep

'''
Python script to send data to remote server
'''
#replace address with the remote server address
HOST, PORT = '127.0.0.1', 3000

if len(sys.argv) < 2:
    error = "Error:"
    print("{} {}".format(error, "Pass in the file to be send"))
    exit(1)

filename = sys.argv[1]

with open(filename, "r", newline="\r") as f:
    lines = f.readlines()

data = "".join(lines)

# Create a socket (SOCK_STREAM means a TCP socket)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    # Connect to server and send data
    sock.connect((HOST, PORT))
    sock.sendall(bytes(data, "utf-8"))

    # Receive data from the server and shut down
    received = r"{}".format(sock.recv(1024))
    sock.close()

print("Received: {}".format(received))
```

<p><strong>Remote - Setup</strong><br/>
I'm running an <code>EC2-micro</code> instance that's running a python script that just listens to a port and prints the data it received, also send a response which is hard-coded. Here is the script</p>

<pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python3

'''
Python code running on EC2-micro
'''

import socket
import errno
from datetime import datetime

print(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))

HOST = '0.0.0.0'  # Standard loopback interface address (localhost)
PORT = 3000       # Port to listen on (non-privileged ports are > 1023)

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    conn, addr = s.accept()
    with conn:
        print('Connected by', addr)
        while True:
            try:
                data = r"{}".format(conn.recv(1024))
                print("Received: {}".format(data))
                #respond back with $E0A0
                conn.sendall(bytes("$E0A0:8B\r$E0FF\r", "utf-8"))
                conn.close()
                s.close()
                break
            except socket.error as e:
                if e.errno != errno.ECONNRESET:
                    raise
                if e.errno == errno.ECONNRESET:
                    printf("Connection reset by peer error again")
                    raise #it is failing here
                pass
</code>```

Testing

Quectel GPRS Module

When I try sending data using the Quectel module the using the AT Commands, what I see from the hardware (quectel) side is that the connection has been CLOSED

```<code>17:29:05.652 [Tx] AT+QIOPEN="TCP","127.0.0.1",3000\r
17:29:05.672 [Rx] \r\nOK\r\n\r\nCONNECT OK\r\n
17:29:07.699 [Tx] AT+SEND=1\r
17:29:07.718 [Rx] >
17:29:08.603 [Tx] A
17:29:08.647 [Rx] \r\nSEND OK\r\n
17:29:09.446 [Rx] CLOSED
</code>```

And the code running on EC2 crashes with:

```<code>Connection reset by peer error again
Traceback (most recent call last):
  File "./server.py", line 22, in <module>
    data = r"{}".format(conn.recv(1024))
ConnectionResetError: [Errno 104] Connection reset by peer
</code>```

But this doesn't happen when I test using the python script (the first code given above)

Running python script from PC

```<code>$ python client.py data
Received: b'$E0A0:8B\r$E0FF\r'
</code>```

Some more observations:

This hardware (quectel) is being used in production environment and it works there as expected. Only in this new independent instance (with no load balancing) it fails with Connection reset by peer

I learned that this could be because of (from here)

Resource limitation at server side

High traffic

But this new instance doesn't do anything else. I have also checked CloudWatch and no spike in CPU usage was seen.

Question

Do you think this is an issue at the server side?

Since the Quectel module responded with SEND OK, from the documentation we can be sure that the data has left the module. And TCP promises delivery of data

But clearly, before data could be received/read we get Connection reset by peer

Is it a performance/infrastructure issue?

All I could find which sounded reasonable was that the server might be less on memory or other resources

答: This was a backend issue. A port white-listing issue.</p>

Body:
tl;dr

Sending the same data from PC and Quectel GPRS module

When send from Quectel, server raises an exception Connection reset by peer

But Quectel works in production environment which has the same EC2-micro instance and a load balancer.

Except for Quectel, another GPRS module - Neoway M680 - works with this EC2 instance.

Setup

Local - Setup

I have a Quectel M66, a GPRS module that I'm using to connect to the server (AWS EC2) and transfer some data.

I also have a python script I've made to connect and send the same data using a PC. Here below is the python script

import socket
import sys
from io import open
from time import sleep

'''
Python script to send data to remote server
'''
#replace address with the remote server address
HOST, PORT = '127.0.0.1', 3000

if len(sys.argv) < 2:
    error = "Error:"
    print("{} {}".format(error, "Pass in the file to be send"))
    exit(1)

filename = sys.argv[1]

with open(filename, "r", newline="\r") as f:
    lines = f.readlines()

data = "".join(lines)

# Create a socket (SOCK_STREAM means a TCP socket)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    # Connect to server and send data
    sock.connect((HOST, PORT))
    sock.sendall(bytes(data, "utf-8"))

    # Receive data from the server and shut down
    received = r"{}".format(sock.recv(1024))
    sock.close()

print("Received: {}".format(received))

Remote - Setup

I'm running an EC2-micro instance that's running a python script that just listens to a port and prints the data it received, also send a response which is hard-coded. Here is the script

#!/usr/bin/env python3

'''
Python code running on EC2-micro
'''

import socket
import errno
from datetime import datetime

print(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))

HOST = '0.0.0.0'  # Standard loopback interface address (localhost)
PORT = 3000       # Port to listen on (non-privileged ports are > 1023)

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen()
    conn, addr = s.accept()
    with conn:
        print('Connected by', addr)
        while True:
            try:
                data = r"{}".format(conn.recv(1024))
                print("Received: {}".format(data))
                #respond back with $E0A0
                conn.sendall(bytes("$E0A0:8B\r$E0FF\r", "utf-8"))
                conn.close()
                s.close()
                break
            except socket.error as e:
                if e.errno != errno.ECONNRESET:
                    raise
                if e.errno == errno.ECONNRESET:
                    printf("Connection reset by peer error again")
                    raise #it is failing here
                pass

Testing

Quectel GPRS Module

When I try sending data using the Quectel module the using the AT Commands, what I see from the hardware (quectel) side is that the connection has been CLOSED

17:29:05.652 [Tx] AT+QIOPEN="TCP","127.0.0.1",3000\r
17:29:05.672 [Rx] \r\nOK\r\n\r\nCONNECT OK\r\n
17:29:07.699 [Tx] AT+SEND=1\r
17:29:07.718 [Rx] >
17:29:08.603 [Tx] A
17:29:08.647 [Rx] \r\nSEND OK\r\n
17:29:09.446 [Rx] CLOSED

And the code running on EC2 crashes with:

Connection reset by peer error again
Traceback (most recent call last):
  File "./server.py", line 22, in <module>
    data = r"{}".format(conn.recv(1024))
ConnectionResetError: [Errno 104] Connection reset by peer

But this doesn't happen when I test using the python script (the first code given above)

Running python script from PC

$ python client.py data
Received: b'$E0A0:8B\r$E0FF\r'

Some more observations:

This hardware (quectel) is being used in production environment and it works there as expected. Only in this new independent instance (with no load balancing) it fails with Connection reset by peer

I learned that this could be because of (from here)

Resource limitation at server side

High traffic

But this new instance doesn't do anything else. I have also checked CloudWatch and no spike in CPU usage was seen.

Question

Do you think this is an issue at the server side?

Since the Quectel module responded with SEND OK, from the documentation we can be sure that the data has left the module. And TCP promises delivery of data

But clearly, before data could be received/read we get Connection reset by peer

Is it a performance/infrastructure issue?

All I could find which sounded reasonable was that the server might be less on memory or other resources


问:
How to make react native application detect current location using matchmore js SDK?
I'm using the js SDK to implement matchmore in my react native application.

The access to my location is allowed.
When I display the localPersistenceManager, I find that the location is null and displayed like this

```<code>location: { latitude: 0, longitude: 0, altitude: 0 }
</code>```

The whole result is like this

```<code>{ _devices:
       [ { name: 'Nexus_5X_API_28',
           location: { latitude: 0, longitude: 0, altitude: 0 },
           deviceType: 'MobileDevice',
           id: '20f4a1d9-6c55-49d2-aa7c-5278eec6ccc6',
           createdAt: 1555321201061,
           platform: 'android',
           deviceToken: 'Nexus_5X_API_28_device_token_is_unique' } ],
      _publications: [],
      _subscriptions: [],
      _defaultDevice:
       { name: 'Nexus_5X_API_28',
         location: { latitude: 0, longitude: 0, altitude: 0 },
         deviceType: 'MobileDevice',
         id: '20f4a1d9-6c55-49d2-aa7c-5278eec6ccc6',
         createdAt: 1555321201061,
         platform: 'android',
         deviceToken: 'Nexus_5X_API_28_device_token_is_unique' } }
</code>```

How can I make the application detect the right location?

Thank you

答:
You can set up the device location manually, by updating Matchmore manager:

```<code>navigator.geolocation.getCurrentPosition(
            position => {
              const location = JSON.stringify(position);
              console.log(location)
              this.setState({ location });
              if (this.manager){
                  this.manager.updateLocation({
                    latitude: position.coords.latitude,
                    longitude: position.coords.longitude,
                    altitude: 0
                  })
              }
            },
            error => Alert.alert(error.message),
            { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
          );
</code>```

Once it's done, the publication and subscriptions created on the device will have your current position.

Body:
I'm using the js SDK to implement matchmore in my react native application.

The access to my location is allowed.
When I display the localPersistenceManager, I find that the location is null and displayed like this

location: { latitude: 0, longitude: 0, altitude: 0 }

The whole result is like this

{ _devices:
       [ { name: 'Nexus_5X_API_28',
           location: { latitude: 0, longitude: 0, altitude: 0 },
           deviceType: 'MobileDevice',
           id: '20f4a1d9-6c55-49d2-aa7c-5278eec6ccc6',
           createdAt: 1555321201061,
           platform: 'android',
           deviceToken: 'Nexus_5X_API_28_device_token_is_unique' } ],
      _publications: [],
      _subscriptions: [],
      _defaultDevice:
       { name: 'Nexus_5X_API_28',
         location: { latitude: 0, longitude: 0, altitude: 0 },
         deviceType: 'MobileDevice',
         id: '20f4a1d9-6c55-49d2-aa7c-5278eec6ccc6',
         createdAt: 1555321201061,
         platform: 'android',
         deviceToken: 'Nexus_5X_API_28_device_token_is_unique' } }

How can I make the application detect the right location?

Thank you

Body:
You can set up the device location manually, by updating Matchmore manager:

navigator.geolocation.getCurrentPosition(
            position => {
              const location = JSON.stringify(position);
              console.log(location)
              this.setState({ location });
              if (this.manager){
                  this.manager.updateLocation({
                    latitude: position.coords.latitude,
                    longitude: position.coords.longitude,
                    altitude: 0
                  })
              }
            },
            error => Alert.alert(error.message),
            { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
          );

Once it's done, the publication and subscriptions created on the device will have your current position.


问:
LPCWSTR Find & Replace with escape characters
I am trying to figure out how to find and replace a string (that contains escape characters "\"). I can't seem to get this working, I am always short the number of escape characters.

I've tried changing my strings to raw-literal strings, but that did not work for me.

LPCWSTR ext1 = _wcslwr(ObjectAttributes->ObjectName->Buffer);

LPCWSTR ext2 = L"c:\\users\\vm1\\documents";

LPCWSTR ext3 = L"c:\\users\\vm1\\desktop";

wstring ext4 = Replace(ext1, ext2, ext3);

```

<p>The variable "_wcslwr(ObjectAttributes->ObjectName->Buffer)" is equal to L"\??\c:\users\vm1\documents\temp22.txt". </p>

<p>I keep getting result string of the Replace function below to equal "\??\c:\users\vm1\desktopp22.txt". The result should be "\??\c:\users\vm1\desktop\temp22.txt". Why did it strip out the "\tem" portion? I think it is due to the "\" actually being counted as one character instead of (2) characters.</p>

<p>The called function is below;</p>

<pre class="lang-cpp prettyprint-override"><code>
wstring Replace(const wstring& orig, const wstring& fnd, const wstring& repl)
{
    wstring ret = orig;
    size_t pos = 0;
    while (true)
    {
        pos = ret.find(fnd, pos);
        if (pos == wstring::npos)  // no more instances found
            break;
        ret.replace(pos, pos + fnd.size(), repl);  // replace old string with new string
        pos += repl.size();
    }
    return ret;
}

</code>```

I expect the output of the "Replace" function above to be;

"\\??\\c:\\users\\vm1\\desktop\\temp22.txt"
```

How do you do this type of find and replace?

答:
This isn't about escape characters, which are not actually part of the string but only present in your source code. The problem is your arguments to std::wstring::replace.

Your bounds are as if you were using the const_iterator, const_iterator overload, but actually you're using the start, length overload. That's not start, end!

So:

```<code>ret.replace(pos, fnd.size(), repl);
</code>```

i.e. remove pos +.

(live demo)

You've been replacing pos (4) more characters than you intended.

And, yes, the string library is full of little trip-up points like this, sadly.

Body:
I am trying to figure out how to find and replace a string (that contains escape characters "\"). I can't seem to get this working, I am always short the number of escape characters.

I've tried changing my strings to raw-literal strings, but that did not work for me.

LPCWSTR ext1 = _wcslwr(ObjectAttributes->ObjectName->Buffer);

LPCWSTR ext2 = L"c:\\users\\vm1\\documents";

LPCWSTR ext3 = L"c:\\users\\vm1\\desktop";

wstring ext4 = Replace(ext1, ext2, ext3);

The variable "_wcslwr(ObjectAttributes->ObjectName->Buffer)" is equal to L"\??\c:\users\vm1\documents\temp22.txt".

I keep getting result string of the Replace function below to equal "\??\c:\users\vm1\desktopp22.txt". The result should be "\??\c:\users\vm1\desktop\temp22.txt". Why did it strip out the "\tem" portion? I think it is due to the "\" actually being counted as one character instead of (2) characters.

The called function is below;

wstring Replace(const wstring& orig, const wstring& fnd, const wstring& repl)
{
    wstring ret = orig;
    size_t pos = 0;
    while (true)
    {
        pos = ret.find(fnd, pos);
        if (pos == wstring::npos)  // no more instances found
            break;
        ret.replace(pos, pos + fnd.size(), repl);  // replace old string with new string
        pos += repl.size();
    }
    return ret;
}

I expect the output of the "Replace" function above to be;

"\\??\\c:\\users\\vm1\\desktop\\temp22.txt"

How do you do this type of find and replace?

Body:
This isn't about escape characters, which are not actually part of the string but only present in your source code. The problem is your arguments to std::wstring::replace.

Your bounds are as if you were using the const_iterator, const_iterator overload, but actually you're using the start, length overload. That's not start, end!

So:

ret.replace(pos, fnd.size(), repl);

i.e. remove pos +.

(live demo)

You've been replacing pos (4) more characters than you intended.

And, yes, the string library is full of little trip-up points like this, sadly.


问:
Javascript ES6 'let' and 'var' - unexpected behavior inside function with argument name matching redeclared variable
Please note this is not duplicate of existing var vs let scope. I'm aware of the scope of var and let declarations and differences.

But below scenario I could not justify with the understanding I had with let and var difference.

In the below code, function foo accepts argument by name 'x' which has implicit let scope - as I cannot redeclare same variable name using let inside that function (uncommenting last line in function foo will throw JS error)

```<code>"use strict";

function foo(x) {
    console.log('Inside function x:', x);
    var x = 30; // 'x' redeclared overwriting argument/parameter 'x'
    console.log('Redeclared x:', x);
    // let x = 400; // uncommenting this line throws error even if you remove 'var x = 30;'
}

foo(100);
// global
let y = 100;
console.log('y:', y);
// var y = 300;
</code>```

Executing the above code with two lines commented out works perfectly, and you can see the output as:

```<code>Inside function x: 100      index.js:4
Redeclared x: 30            index.js:6
y: 100                      index.js:13
</code>```

Uncommenting last line // var y = 300; will throw error.

Question is: Why redeclaring 'x' using 'var' inside function foo works but throws error when 'y' is redeclared in the global scope using 'var'

答:
The var declaration syntax is original to the language, and has fairly permissive rules. The let and const declarations are newer and more strict. You cannot re-declare variables with let or const no matter how they were declared in the first place. And if a variable is declared with let or const, a subsequent var declaration is also an error.

Declarations via let and const will not allow references to the variables before the declaration; that's why you get the error mentioned in your first example. In other words,

```<code>console.log(x);
let x = 0;
</code>```

is an error because x is referenced before the declaration.

Body:
Please note this is not duplicate of existing var vs let scope. I'm aware of the scope of var and let declarations and differences.

But below scenario I could not justify with the understanding I had with let and var difference.

In the below code, function foo accepts argument by name 'x' which has implicit let scope - as I cannot redeclare same variable name using let inside that function (uncommenting last line in function foo will throw JS error)

"use strict";

function foo(x) {
    console.log('Inside function x:', x);
    var x = 30; // 'x' redeclared overwriting argument/parameter 'x'
    console.log('Redeclared x:', x);
    // let x = 400; // uncommenting this line throws error even if you remove 'var x = 30;'
}

foo(100);
// global
let y = 100;
console.log('y:', y);
// var y = 300;

Executing the above code with two lines commented out works perfectly, and you can see the output as:

Inside function x: 100      index.js:4
Redeclared x: 30            index.js:6
y: 100                      index.js:13

Uncommenting last line // var y = 300; will throw error.

Question is: Why redeclaring 'x' using 'var' inside function foo works but throws error when 'y' is redeclared in the global scope using 'var'

Body:
The var declaration syntax is original to the language, and has fairly permissive rules. The let and const declarations are newer and more strict. You cannot re-declare variables with let or const no matter how they were declared in the first place. And if a variable is declared with let or const, a subsequent var declaration is also an error.

Declarations via let and const will not allow references to the variables before the declaration; that's why you get the error mentioned in your first example. In other words,

console.log(x);
let x = 0;

is an error because x is referenced before the declaration.


问:
NativeScript: Virtual module path mapping
Is it possible to use module path mapping in NativeScript at runtime?

The TypeScript compiler option 'paths' allows to map virtual module ids to physical ones. If, for example, one needs to require the module node_modules/my_package/dist/commonjs/my_modules/my_module it is possible to define a mapping and then require the virtual module my_modules/my_module instead:

```<code>// tsconfig.json
{
  "compilerOptions": {
    "paths": {
      "my_modules/*": [ "node_modules/my_package/dist/commonjs/my_modules/*" ]
    }
  }
}
</code>```

This works fine at compile time but the TypeScript compiler won't emit the resolved module ids. Instead, it leaves the specified (virtual) module ids in place. As a result, the modules will not be found at runtime.

There is a node package called module-alias that adresses this issue in a nodejs environment. However, I was not able to set this up in the NativeScript runtime.

答:
For anyone who comes across the same issue, here's the thing:

After upgrading to NativeScript's new bundle workflow the issue was solved by simply adding the respective mapping to the webpack.config.js:

const config = {
  resolve: {
    alias: [
      "my_modules/*": "node_modules/my_package/dist/commonjs/my_modules/*"
    ]
  }
}```

Body:
Is it possible to use module path mapping in NativeScript at runtime?

The TypeScript compiler option 'paths' allows to map virtual module ids to physical ones. If, for example, one needs to require the module node_modules/my_package/dist/commonjs/my_modules/my_module it is possible to define a mapping and then require the virtual module my_modules/my_module instead:

// tsconfig.json
{
  "compilerOptions": {
    "paths": {
      "my_modules/*": [ "node_modules/my_package/dist/commonjs/my_modules/*" ]
    }
  }
}

This works fine at compile time but the TypeScript compiler won't emit the resolved module ids. Instead, it leaves the specified (virtual) module ids in place. As a result, the modules will not be found at runtime.

There is a node package called module-alias that adresses this issue in a nodejs environment. However, I was not able to set this up in the NativeScript runtime.