问:
undefined object in loop result
I have my code below here and I noticed that when I display it in my html, I get a [object Object] result in my index 0 which is actually supposed to give me 153826-00.

Weirdly in my console.log, I get the result wanted.

Can someone please explain to me what's happening?

var db = {"Root":{"DataPage":[{"Record":{"PPS_NUM":"3207987   ","PO_NUM":"153826-00                     ","OB_TYPE":"SOLK","SHIPMENT":"S258028   "}},{"Record":{"PPS_NUM":"3207500   ","PO_NUM":"10086398                      ","OB_TYPE":"SOLK","SHIPMENT":"S257877   "}},{"Record":{"PPS_NUM":"3207562   ","PO_NUM":"","OB_TYPE":"XFLK","SHIPMENT":"S257881X  "}},{"Record":{"PPS_NUM":"3198033   ","PO_NUM":"SAMPLES 6-14-17               ","OB_TYPE":"SOLK","SHIPMENT":"S255956   "}},{"Record":{"PPS_NUM":"3207443   ","PO_NUM":"491754-2279                   ","OB_TYPE":"SOLK","SHIPMENT":"S257873   "}},{"Record":{"PPS_NUM":"3204961   ","PO_NUM":"","OB_TYPE":"XFLK","SHIPMENT":"S257368   "}},{"Record":{"PPS_NUM":"3207635   ","PO_NUM":"","OB_TYPE":"XFLK","SHIPMENT":"S257904   "}},{"Record":{"PPS_NUM":"3205331   ","PO_NUM":"0188502                       ","OB_TYPE":"SOLK","SHIPMENT":"S257450   "}}]}};
var p = db.Root.DataPage;
for (var key in p) {
  if (p.hasOwnProperty(key)) {
     db+='
'+p[key].Record.PO_NUM+'
';
     $('#display').html(db);
      console.log(p[key].Record.PO_NUM);
 }
 }
$('#display').html(db);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="display"></p></code>```

答:
That's because you allready defined db as your first array, so when you += it just add the data.
just change your second db for output and it works.

var db = {"Root":{"DataPage":[{"Record":{"PPS_NUM":"3207987   ","PO_NUM":"153826-00                     ","OB_TYPE":"SOLK","SHIPMENT":"S258028   "}},{"Record":{"PPS_NUM":"3207500   ","PO_NUM":"10086398                      ","OB_TYPE":"SOLK","SHIPMENT":"S257877   "}},{"Record":{"PPS_NUM":"3207562   ","PO_NUM":"","OB_TYPE":"XFLK","SHIPMENT":"S257881X  "}},{"Record":{"PPS_NUM":"3198033   ","PO_NUM":"SAMPLES 6-14-17               ","OB_TYPE":"SOLK","SHIPMENT":"S255956   "}},{"Record":{"PPS_NUM":"3207443   ","PO_NUM":"491754-2279                   ","OB_TYPE":"SOLK","SHIPMENT":"S257873   "}},{"Record":{"PPS_NUM":"3204961   ","PO_NUM":"","OB_TYPE":"XFLK","SHIPMENT":"S257368   "}},{"Record":{"PPS_NUM":"3207635   ","PO_NUM":"","OB_TYPE":"XFLK","SHIPMENT":"S257904   "}},{"Record":{"PPS_NUM":"3205331   ","PO_NUM":"0188502                       ","OB_TYPE":"SOLK","SHIPMENT":"S257450   "}}]}};
var p = db.Root.DataPage;
var output = "";
for (var key in p) {
  if (p.hasOwnProperty(key)) {
     output+='
'+p[key].Record.PO_NUM+'
';
     $('#display').html(output);
      console.log(p[key].Record.PO_NUM);
 }
 }
$('#display').html(output);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="display"></p></code>```

Title: undefined object in loop result

Body:
That's because you allready defined db as your first array, so when you += it just add the data.
just change your second db for output and it works.

var db = {"Root":{"DataPage":[{"Record":{"PPS_NUM":"3207987   ","PO_NUM":"153826-00                     ","OB_TYPE":"SOLK","SHIPMENT":"S258028   "}},{"Record":{"PPS_NUM":"3207500   ","PO_NUM":"10086398                      ","OB_TYPE":"SOLK","SHIPMENT":"S257877   "}},{"Record":{"PPS_NUM":"3207562   ","PO_NUM":"","OB_TYPE":"XFLK","SHIPMENT":"S257881X  "}},{"Record":{"PPS_NUM":"3198033   ","PO_NUM":"SAMPLES 6-14-17               ","OB_TYPE":"SOLK","SHIPMENT":"S255956   "}},{"Record":{"PPS_NUM":"3207443   ","PO_NUM":"491754-2279                   ","OB_TYPE":"SOLK","SHIPMENT":"S257873   "}},{"Record":{"PPS_NUM":"3204961   ","PO_NUM":"","OB_TYPE":"XFLK","SHIPMENT":"S257368   "}},{"Record":{"PPS_NUM":"3207635   ","PO_NUM":"","OB_TYPE":"XFLK","SHIPMENT":"S257904   "}},{"Record":{"PPS_NUM":"3205331   ","PO_NUM":"0188502                       ","OB_TYPE":"SOLK","SHIPMENT":"S257450   "}}]}};
var p = db.Root.DataPage;
var output = "";
for (var key in p) {
  if (p.hasOwnProperty(key)) {
     output+='<p>'+p[key].Record.PO_NUM+'</p>';
     $('#display').html(output);
      console.log(p[key].Record.PO_NUM);
 }
 }
$('#display').html(output);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="display"></p>


来源: stackexchange

问:
SyncAdapter: Account created, requestSync OK, but setSyncAutomatically not Working
I just created an Account for my app.

The account is visible in settings

I set syncable="true" in my XML

I can perform a manual sync by pressing the settings -> onPerformSync
is called

I can perform a "code" sync by calling ContentResolver.requestSync -> onPerformSync is called

And of course, yes, the sync is enabled in settings. I don't use any power saver.

I also followed all the steps from here: https://stackoverflow.com/a/5255360/327402

This is my code to get the sync by code

```<code>AccountManager am = AccountManager.get(this);
Account[] accounts = am.getAccountsByType(ACCOUNT);
//Log.e("DEBUG", "Accounts: " + accounts.length);
if (accounts.length == 0) {
    Account account = new Account(getString(R.string.app_name), ACCOUNT);
    ContentResolver.setIsSyncable(account, AUTHORITY, 1);
    ContentResolver.addPeriodicSync(account, AUTHORITY, new Bundle(), 7200);
    ContentResolver.setSyncAutomatically(account, AUTHORITY, true);
    if (am.addAccountExplicitly(account, "pass1", null))
        Log.i("DEBUG", "account Created: " + account.name + ", " + account.type);
    else
        Log.i("DEBUG", "addAccountExplicitly returned false");
    }
else{
    ContentResolver.requestSync(accounts[0], AUTHORITY, new Bundle());// THIS IS WORKING!!!
    }
}
</code>```

So, everything looks correct and fine.

But unfortunately, I cannot get a periodic sync! When I open the settings, accounts, I see the account and the date and time is the time when I performed the sync by code, or manually.

Any idea on what I did wrong, or what I forgot?

答:
Rewrite

I have put together a sample project on GitHub that demonstrates a working SyncAdapter. The project is here.

I have only tried this on an emulator with API 17 since I didn't want to wait around an hour or so (maybe longer now) for a sync to happen. I would suggest that you take this route as well.

On API 17, this demo will do a sync every 30 seconds or so. Everything runs out of the main activity with stub support classes: SyncAdapter, StubProvider, etc. The only thing the sync adapter does is to log a message to logcat that it has run.

I don't really see anything wrong with your code other than, perhaps, the order of the calls to set up the sync is incorrect. Take a look at the call order in the demo for an example of what works.

I hope you find this useful.

(I did this on Android Studio 3.0 Canary 5. I hope this is not an issue.)

ContentLicense: CC BY-SA 3.0

Body:
I just created an Account for my app.

The account is visible in settings

I set syncable="true" in my XML

I can perform a manual sync by pressing the settings -> onPerformSync
is called

I can perform a "code" sync by calling ContentResolver.requestSync -> onPerformSync is called

And of course, yes, the sync is enabled in settings. I don't use any power saver.

I also followed all the steps from here: https://stackoverflow.com/a/5255360/327402

This is my code to get the sync by code

AccountManager am = AccountManager.get(this);
Account[] accounts = am.getAccountsByType(ACCOUNT);
//Log.e("DEBUG", "Accounts: " + accounts.length);
if (accounts.length == 0) {
    Account account = new Account(getString(R.string.app_name), ACCOUNT);
    ContentResolver.setIsSyncable(account, AUTHORITY, 1);
    ContentResolver.addPeriodicSync(account, AUTHORITY, new Bundle(), 7200);
    ContentResolver.setSyncAutomatically(account, AUTHORITY, true);
    if (am.addAccountExplicitly(account, "pass1", null))
        Log.i("DEBUG", "account Created: " + account.name + ", " + account.type);
    else
        Log.i("DEBUG", "addAccountExplicitly returned false");
    }
else{
    ContentResolver.requestSync(accounts[0], AUTHORITY, new Bundle());// THIS IS WORKING!!!
    }
}

So, everything looks correct and fine.

But unfortunately, I cannot get a periodic sync! When I open the settings, accounts, I see the account and the date and time is the time when I performed the sync by code, or manually.

Any idea on what I did wrong, or what I forgot?


问:
Applying CSS to Label and Input Elements Using Values in jQuery
Edit :
I am aware that their is a question mark in the jQuery, CSS and HTML. Due to it being generated automatically by Yii I cannot remove it.

Using jQuery I am attempting to add and remove styling to an input and label within my HTML. I get no response when I am trying this, I believe it is due to the abnormal for="" and/or val= values of the elements generated by Yii.

Can't seem to get it working with the if else statement. When removed it applies the CSS.

It should do as follows; select Yes, with the value "Yes", and the second label and input appear.

I have created a CodePen for this as I am having issues with JSFiddle.
https://codepen.io/CallumRocks/pen/rwrrvE

I have also included the relevant code below.

$(document).ready(function(){
    $('#event_Do_you_require_any_accessibility_assistance?').on('change',function(){
    if($(this).val() == 'Yes'){
        $("label[for='event_Please specify']").css('display', 'block');
        $("input#event_Please_specify").css('display', 'block');
    }
    else {
        $("label[for='event_Please specify']").css('display', 'none');
        $("#event_Please_specify").css('display', 'none');
    }
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>label[for="event_Would you like to stay informed about updates and changes to this event?"] {
    width: 100% !important;
    line-height: 20px;
}
label[for="event_Please specify"] {
    display: none;
}
input#event_Please_specify{
    display: none;
}</code>```

  Do you require any accessibility assistance? *
  <select class="form-control user-success" required="required" name="event_Do you require any accessibility assistance?" id="event_Do_you_require_any_accessibility_assistance?">
    <option value="">Please choose</option>
    <option value="Yes">Yes</option>
    <option value="No"> No</option>
  </select>

  Please specify
  <input class="col-md-5 form-control" placeholder="Please specify" autocomplete="off" type="text" value="" name="event_Please specify" id="event_Please_specify">

```

答:
Typo in select 'id'. Just remove the question mark.
$('#event_Do_you_require_any_accessibility_assistance?')

In your codepen code, if you remove the question mark in HTML select id, everything is alright.

Body:
Edit :
I am aware that their is a question mark in the jQuery, CSS and HTML. Due to it being generated automatically by Yii I cannot remove it.

Using jQuery I am attempting to add and remove styling to an input and label within my HTML. I get no response when I am trying this, I believe it is due to the abnormal for="" and/or val= values of the elements generated by Yii.

Can't seem to get it working with the if else statement. When removed it applies the CSS.

It should do as follows; select Yes, with the value "Yes", and the second label and input appear.

I have created a CodePen for this as I am having issues with JSFiddle.
https://codepen.io/CallumRocks/pen/rwrrvE

I have also included the relevant code below.

$(document).ready(function(){
    $('#event_Do_you_require_any_accessibility_assistance?').on('change',function(){
    if($(this).val() == 'Yes'){
        $("label[for='event_Please specify']").css('display', 'block');
        $("input#event_Please_specify").css('display', 'block');
    }
    else {
        $("label[for='event_Please specify']").css('display', 'none');
        $("#event_Please_specify").css('display', 'none');
    }
    });
});

label[for="event_Would you like to stay informed about updates and changes to this event?"] {
    width: 100% !important;
    line-height: 20px;
}
label[for="event_Please specify"] {
    display: none;
}
input#event_Please_specify{
    display: none;
}

  Do you require any accessibility assistance? *
  <select class="form-control user-success" required="required" name="event_Do you require any accessibility assistance?" id="event_Do_you_require_any_accessibility_assistance?">
    <option value="">Please choose</option>
    <option value="Yes">Yes</option>
    <option value="No"> No</option>
  </select>

  Please specify
  <input class="col-md-5 form-control" placeholder="Please specify" autocomplete="off" type="text" value="" name="event_Please specify" id="event_Please_specify">


问:
Npm Please try using this command again as root/administrator
I've been desperately trying to install modules using node.js but it always fails getting packages with npm.

I logged in as Administrator and used powershell/cmd with "run as administrator". I also had problems with the registry so I used npm set registry http://registry.npmjs.org/

I tried everything... it just drives me nuts.

Here are the errors:

npm ERR! Please try running this command again as root/Administrator.

```<code>npm ERR! System Windows_NT 6.2.9200
npm ERR! command "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "generator-knockout"
npm ERR! cwd D:\Sergiu\Knockout Test
npm ERR! node -v v0.10.26
npm ERR! npm -v 1.4.3
npm ERR! path D:\Sergiu\Knockout Test\node_modules\generator-knockout\node_modules\yeoman-generator\node_modules\tar\node_modules\block-stream\block-stream.js
npm ERR! fstream_path D:\Sergiu\Knockout Test\node_modules\generator-knockout\node_modules\yeoman-generator\node_modules\tar\node_modules\block-stream\block-stream.js
npm ERR! fstream_type File
npm ERR! fstream_class FileWriter
npm ERR! code EPERM
npm ERR! errno 50
npm ERR! stack Error: EPERM, lstat 'D:\Sergiu\Knockout Test\node_modules\generator-knockout\node_modules\yeoman-generator\node_modules\tar\node_modules\block-stream\block-stream.js'
npm ERR! fstream_stack C:\Program Files\nodejs\node_modules\npm\node_modules\fstream\lib\writer.js:284:26
npm ERR! fstream_stack Object.oncomplete (fs.js:107:15)
npm ERR! Error: EPERM, lstat 'D:\Sergiu\Knockout Test\node_modules\generator-knockout\node_modules\yeoman-generator\node_modules\tar\node_modules\fstream\LICENSE'
npm ERR!  { [Error: EPERM, lstat 'D:\Sergiu\Knockout Test\node_modules\generator-knockout\node_modules\yeoman-generator\node_modules\tar\node_modules\fstream\LICENSE']
npm ERR!   errno: 50,
npm ERR!   code: 'EPERM',
npm ERR!   path: 'D:\\Sergiu\\Knockout Test\\node_modules\\generator-knockout\\node_modules\\yeoman-generator\\node_modules\\tar\\node_modules\\fstream\\LICENSE',
npm ERR!   fstream_type: 'File',
npm ERR!   fstream_path: 'D:\\Sergiu\\Knockout Test\\node_modules\\generator-knockout\\node_modules\\yeoman-generator\\node_modules\\tar\\node_modules\\fstream\\LICENSE',
npm ERR!   fstream_class: 'FileWriter',
npm ERR!   fstream_stack:
npm ERR!    [ 'C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\fstream\\lib\\writer.js:284:26',
npm ERR!      'Object.oncomplete (fs.js:107:15)' ] }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.
</code>```

答:
I messed with this problem 2 times and tried all suggestions here with mediocre success.

First time I tried (and succeeded luckily) by:

delete the node_modules folder in your project

npm clean cache -f

check your %APPDATA%/npm-cache and delete everything if not empty

start the terminal as administrator (in my opinion, it isnt a problem of rights, but it wont hurt if you do so)

npm install and then npm update

you will get errors, just install every module that throws an error manually and step by step try to eliminate everything whats wrong

However, this method is quite frustrating and not working everytime. So try this:

Second time I had no luck with the steps above, so I tried to completely reinstall npm and it failed. So I thought there must something be wrong with my node.js installation. My team is running 6.10. and I had the 6.11. and tried it with the 6.10. with no luck.

So I completely wiped everything off my system. Deleted all node modules, checked every path where node or npm could be and cleaned my system.

Then I installed newest 8.1.3

Deleted my project and cloned it to a complete different directory.

Now I installed and updated everything with npm install npm update

Then I compiled with just 2 modules missing and installed them manually

Tadaaaaa, its working now. So all in all it was a problem with node.js. I recommend to everyone who runs into this problem: Try different node versions! And clean ABSOLUTE everything.

Body:
I've been desperately trying to install modules using node.js but it always fails getting packages with npm.

I logged in as Administrator and used powershell/cmd with "run as administrator". I also had problems with the registry so I used npm set registry http://registry.npmjs.org/

I tried everything... it just drives me nuts.

Here are the errors:

npm ERR! Please try running this command again as root/Administrator.

npm ERR! System Windows_NT 6.2.9200
npm ERR! command "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "generator-knockout"
npm ERR! cwd D:\Sergiu\Knockout Test
npm ERR! node -v v0.10.26
npm ERR! npm -v 1.4.3
npm ERR! path D:\Sergiu\Knockout Test\node_modules\generator-knockout\node_modules\yeoman-generator\node_modules\tar\node_modules\block-stream\block-stream.js
npm ERR! fstream_path D:\Sergiu\Knockout Test\node_modules\generator-knockout\node_modules\yeoman-generator\node_modules\tar\node_modules\block-stream\block-stream.js
npm ERR! fstream_type File
npm ERR! fstream_class FileWriter
npm ERR! code EPERM
npm ERR! errno 50
npm ERR! stack Error: EPERM, lstat 'D:\Sergiu\Knockout Test\node_modules\generator-knockout\node_modules\yeoman-generator\node_modules\tar\node_modules\block-stream\block-stream.js'
npm ERR! fstream_stack C:\Program Files\nodejs\node_modules\npm\node_modules\fstream\lib\writer.js:284:26
npm ERR! fstream_stack Object.oncomplete (fs.js:107:15)
npm ERR! Error: EPERM, lstat 'D:\Sergiu\Knockout Test\node_modules\generator-knockout\node_modules\yeoman-generator\node_modules\tar\node_modules\fstream\LICENSE'
npm ERR!  { [Error: EPERM, lstat 'D:\Sergiu\Knockout Test\node_modules\generator-knockout\node_modules\yeoman-generator\node_modules\tar\node_modules\fstream\LICENSE']
npm ERR!   errno: 50,
npm ERR!   code: 'EPERM',
npm ERR!   path: 'D:\\Sergiu\\Knockout Test\\node_modules\\generator-knockout\\node_modules\\yeoman-generator\\node_modules\\tar\\node_modules\\fstream\\LICENSE',
npm ERR!   fstream_type: 'File',
npm ERR!   fstream_path: 'D:\\Sergiu\\Knockout Test\\node_modules\\generator-knockout\\node_modules\\yeoman-generator\\node_modules\\tar\\node_modules\\fstream\\LICENSE',
npm ERR!   fstream_class: 'FileWriter',
npm ERR!   fstream_stack:
npm ERR!    [ 'C:\\Program Files\\nodejs\\node_modules\\npm\\node_modules\\fstream\\lib\\writer.js:284:26',
npm ERR!      'Object.oncomplete (fs.js:107:15)' ] }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.


问:
C++ String Interview Question
I was recently in a C++ technical interview, where I was given a bit of simple string manipulation code, which is intended to take a string and return a string that is comprised of the first and last n-characters, and then proceed to correct any bugs and to also make the function as efficient as possible, I came up with the solution below, however the interviewer claimed there was an even faster more optimal way:

Original code:

```<code>std::string first_last_n(int n, std::string s)
{
   std::string first_n = s.substr(0,n);
   std::string last_n = s.substr(s.size()-n-1,n);
   return first_n + last_n;
}
</code>```

My code:

```<code>bool first_last_n(const std::size_t& n, const std::string& s, std::string& r)
{
   if (s.size() < n)
      return false;
   r.reserve(2 * n);
   r.resize(0);
   r.append(s.data(),s.data() + n);
   r.append(s.data() + (s.size() - n), s.data() + s.size());
   return true;
}
</code>```

Summary of my changes:

Changed the interface to take a return string as reference (assuming RVO and rvalues are not available yet)

Removed temporary strings being constructed via substr

Passed input string as a const reference inorder to get around temporary instantiation of input

Fixed off-by-1 error in last_n string

Reduced the number of times each character is touched down to once, or twice (in the event of an overlapping scenario)

Placed a check in the event the string s's size is less than n, returning false for failure.

Assuming only native C++ is allowed, is there some other way of doing the above more efficiently or optimally?

Note 1: The original input string instance is not to be modified.

Note 2: All solutions must pass the following test case, otherwise they are not valid.

```<code>void test()
{
   {
      std::string s = "0123456789";
      std::string r = first_last_n(10,s);
      assert(r == "01234567890123456789");
   }

   {
      std::string s = "0123456789ABC0123456789";
      std::string r = first_last_n(10,s);
      assert(r == "01234567890123456789");
   }

   {
      std::string s = "1234321";
      std::string r = first_last_n(5,s);
      assert(r == "1234334321");
   }

}
</code>```

答:
Memcpy is a cheat?

```<code>#include <cstring>
#include <iostream>
#include <string>

std::string first_last_n(int n, const std::string& s)
{
  if (s.size() < n)
      return "";

    char str[n*2];
    memcpy(str, s.data(), n);
    memcpy(str+n, s.data() + s.size()-n, n);

    return (const char *)str;
}

int main()
{
    std::cout << first_last_n(2, "123454321") << std::endl;
}
</code>```

EDIT
So I removed the other one. This is not a cheat.

OwnerDisplayName: Matthieu N.

LastEditorDisplayName: Matthieu N.

ContentLicense: CC BY-SA 2.5

Title: C++ String Interview Question

Body:
I was recently in a C++ technical interview, where I was given a bit of simple string manipulation code, which is intended to take a string and return a string that is comprised of the first and last n-characters, and then proceed to correct any bugs and to also make the function as efficient as possible, I came up with the solution below, however the interviewer claimed there was an even faster more optimal way:

Original code:

std::string first_last_n(int n, std::string s)
{
   std::string first_n = s.substr(0,n);
   std::string last_n = s.substr(s.size()-n-1,n);
   return first_n + last_n;
}

My code:

bool first_last_n(const std::size_t& n, const std::string& s, std::string& r)
{
   if (s.size() < n)
      return false;
   r.reserve(2 * n);
   r.resize(0);
   r.append(s.data(),s.data() + n);
   r.append(s.data() + (s.size() - n), s.data() + s.size());
   return true;
}

Summary of my changes:

Changed the interface to take a return string as reference (assuming RVO and rvalues are not available yet)

Removed temporary strings being constructed via substr

Passed input string as a const reference inorder to get around temporary instantiation of input

Fixed off-by-1 error in last_n string

Reduced the number of times each character is touched down to once, or twice (in the event of an overlapping scenario)

Placed a check in the event the string s's size is less than n, returning false for failure.

Assuming only native C++ is allowed, is there some other way of doing the above more efficiently or optimally?

Note 1: The original input string instance is not to be modified.

Note 2: All solutions must pass the following test case, otherwise they are not valid.

void test()
{
   {
      std::string s = "0123456789";
      std::string r = first_last_n(10,s);
      assert(r == "01234567890123456789");
   }

   {
      std::string s = "0123456789ABC0123456789";
      std::string r = first_last_n(10,s);
      assert(r == "01234567890123456789");
   }

   {
      std::string s = "1234321";
      std::string r = first_last_n(5,s);
      assert(r == "1234334321");
   }

}

Body:
Memcpy is a cheat?

#include <cstring>
#include <iostream>
#include <string>

std::string first_last_n(int n, const std::string& s)
{
  if (s.size() < n)
      return "";

    char str[n*2];
    memcpy(str, s.data(), n);
    memcpy(str+n, s.data() + s.size()-n, n);

    return (const char *)str;
}

int main()
{
    std::cout << first_last_n(2, "123454321") << std::endl;
}

EDIT
So I removed the other one. This is not a cheat.


问:
An issue with rangesearch (Matlab)
I am trying to find the nearest neighbors using the rangesearch function in matlab. I have been doing this for a long time and Now I started facing some unknown issues.

I have previously run rangesearch for huge sizes ( 6 Mil.) and was successful. Now I was trying to run it for 0.3 M and it is taking forever and it consumes ~ 50 GB of memory. Could anyone help ?

I have attached the test file here and the simple code is given below -

```<code>Glist =dlmread('test');
[idx,dist]= rangesearch(Glist,Glist,12);
</code>```

答:
I have a suggestion, but couldn't put it in the comment section as I have less points.

Anyway, are you sure you have to search each and every point in Glist? As it has around .3M points, it's going to take some time. And of course, it going to occupy a huge memory space because for each point one cell is create which contains points ranging from some hundreds to thousands. So, I would suggest start with small bunch of points and keep increasing the size of the bunch. For example,

```<code>tic; [idx,dist]= rangesearch(Glist,Glist(1:50000,:),12);toc
</code>```

tic-toc combination gives you the time elapsed. By the way, on my machine the above command took ~80 seconds. And, I didn't want to go beyond that as the time is going to increase along with the memory.

Title: An issue with rangesearch (Matlab)

Body:
I am trying to find the nearest neighbors using the rangesearch function in matlab. I have been doing this for a long time and Now I started facing some unknown issues.

I have previously run rangesearch for huge sizes ( 6 Mil.) and was successful. Now I was trying to run it for 0.3 M and it is taking forever and it consumes ~ 50 GB of memory. Could anyone help ?

I have attached the test file here and the simple code is given below -

Glist =dlmread('test');
[idx,dist]= rangesearch(Glist,Glist,12);

Body:
I have a suggestion, but couldn't put it in the comment section as I have less points.

Anyway, are you sure you have to search each and every point in Glist? As it has around .3M points, it's going to take some time. And of course, it going to occupy a huge memory space because for each point one cell is create which contains points ranging from some hundreds to thousands. So, I would suggest start with small bunch of points and keep increasing the size of the bunch. For example,

tic; [idx,dist]= rangesearch(Glist,Glist(1:50000,:),12);toc

tic-toc combination gives you the time elapsed. By the way, on my machine the above command took ~80 seconds. And, I didn't want to go beyond that as the time is going to increase along with the memory.


问:
undo ax.set_yticks([])
I use an existing script to plot a very specific data type. The script returns an ax object.
These ax objects are used to populate subplots in an new bigger main plot.

In the main script somewhere,

```<code>ax.set_yticks([])
</code>```

is called. Usually this is wanted. For one of the individual plotting scripts I would like to simply undo this and have matplotlib set my y ticks automatically depending on the data just as if ax.set_yticks([]) had never been called.

答:
you can store the tick locator before you call set_yticks([]) and restore it later</p>

```<code>import matplotlib.pyplot as plt

ax = plt.gca()
ax.plot(range(10), range(10), 'ko')

#store the yticks locator
l = ax.yaxis.get_major_locator()

#hide ticks and display the figure
ax.set_yticks([])
plt.gcf().show()
raw_input('pause') # => no more yticks

#restore the tick locator to its originale state
ax.yaxis.set_major_locator(l)
plt.gcf().canvas.draw()  #refresh the plot to sow the yticks again

plt.show()
</code>```

Title: undo ax.set_yticks([])

Body:
I use an existing script to plot a very specific data type. The script returns an ax object.
These ax objects are used to populate subplots in an new bigger main plot.

In the main script somewhere,

ax.set_yticks([])

is called. Usually this is wanted. For one of the individual plotting scripts I would like to simply undo this and have matplotlib set my y ticks automatically depending on the data just as if ax.set_yticks([]) had never been called.

Body:
you can store the tick locator before you call set_yticks([]) and restore it later

import matplotlib.pyplot as plt

ax = plt.gca()
ax.plot(range(10), range(10), 'ko')

#store the yticks locator
l = ax.yaxis.get_major_locator()

#hide ticks and display the figure
ax.set_yticks([])
plt.gcf().show()
raw_input('pause') # => no more yticks

#restore the tick locator to its originale state
ax.yaxis.set_major_locator(l)
plt.gcf().canvas.draw()  #refresh the plot to sow the yticks again

plt.show()


问:
nodejs:mysql not able to access global variable inside connection query callback
Below is my code

I am sending data object from client side javascript to this function
data prints its values

inside socket.on

and

inside socket.on -> connection.query(sql,[], function(err,rows){data prints here})

and

inside socket.on -> connection.query(sql,[], function(err,rows){data prints here})-> connection.query(sql,[], function(err,rows){data prints undefined})

```<code>socket.on('sendmessage', function (data) {
    var data = JSON.parse(data);
    console.log(data);
    if (data.cuserid != '' && users_connected.hasOwnProperty(data.cuserid) && fs.existsSync(users_connected[data.cuserid]['sessionfile'])) {
        sql = "update hired set echat='Y' where eid=? and jobid=? and jid=? and status in ('given','finished')";
        connection.query(sql, [data.cuserid, data.jobid, data.userid], function (err, rows) {/*console.log(this.sql);*/ });
        sql = "insert into chat_messages(fromid,toid,jobid,message,received_date) select ?,?,?,?,NOW() from hired where echat='Y' and jchat='Y' and jobid=? and jid in(?,?) and eid in(?,?) and status in ('given','finished')";
        connection.query(sql, [data.cuserid, data.userid, data.jobid, data.message, data.jobid, data.cuserid, data.userid, data.cuserid, data.userid], function (err, rows) {
            console.log("dataretrieved : ", data); if (!err && users_connected[data.userid] != '') {
                socid = users_connected[data.userid]['socket'];
                sql = "select id as userid,username, userphoto from us_signup where id=?";
                connection.query(sql, [data.userid], function (err, rows) {
                    console.log(data);  //prints undefined
                    if (!err) {
                        var data = {
                            'userphoto': rows[0].userphoto,
                            'username': rows[0].username,
                            'userid': rows[0].userid,
                            'cuserid': data.cuserid,
                            'message': data.message,
                            'jobid': data.jobid
                        }
                        io.to(socid).emit('message', JSON.stringify(data));
                    }
                })
            }
        });
    }

})
</code>```

答:
You are creating a newly scoped data in the deepest level:

```<code>if (!err) {
  var data = { ... }
  ...
}
</code>```

This variable is hoisted to the top of the containing function, so the code becomes the equivalent of this:

```<code>var data;          // clobbers the existing `data` variable...
console.log(data); // ...so here it will log `undefined`...
if (!err) {
  data = { ... }   // ...because it receives a value here.
  ...
}
</code>```

Solutions:

don't use var there

start using let

Body:
Below is my code

I am sending data object from client side javascript to this function
data prints its values

inside socket.on

and

inside socket.on -> connection.query(sql,[], function(err,rows){data prints here})

and

inside socket.on -> connection.query(sql,[], function(err,rows){data prints here})-> connection.query(sql,[], function(err,rows){data prints undefined})

socket.on('sendmessage', function (data) {
    var data = JSON.parse(data);
    console.log(data);
    if (data.cuserid != '' && users_connected.hasOwnProperty(data.cuserid) && fs.existsSync(users_connected[data.cuserid]['sessionfile'])) {
        sql = "update hired set echat='Y' where eid=? and jobid=? and jid=? and status in ('given','finished')";
        connection.query(sql, [data.cuserid, data.jobid, data.userid], function (err, rows) {/*console.log(this.sql);*/ });
        sql = "insert into chat_messages(fromid,toid,jobid,message,received_date) select ?,?,?,?,NOW() from hired where echat='Y' and jchat='Y' and jobid=? and jid in(?,?) and eid in(?,?) and status in ('given','finished')";
        connection.query(sql, [data.cuserid, data.userid, data.jobid, data.message, data.jobid, data.cuserid, data.userid, data.cuserid, data.userid], function (err, rows) {
            console.log("dataretrieved : ", data); if (!err && users_connected[data.userid] != '') {
                socid = users_connected[data.userid]['socket'];
                sql = "select id as userid,username, userphoto from us_signup where id=?";
                connection.query(sql, [data.userid], function (err, rows) {
                    console.log(data);  //prints undefined
                    if (!err) {
                        var data = {
                            'userphoto': rows[0].userphoto,
                            'username': rows[0].username,
                            'userid': rows[0].userid,
                            'cuserid': data.cuserid,
                            'message': data.message,
                            'jobid': data.jobid
                        }
                        io.to(socid).emit('message', JSON.stringify(data));
                    }
                })
            }
        });
    }

})

Body:
You are creating a newly scoped data in the deepest level:

if (!err) {
  var data = { ... }
  ...
}

This variable is hoisted to the top of the containing function, so the code becomes the equivalent of this:

var data;          // clobbers the existing `data` variable...
console.log(data); // ...so here it will log `undefined`...
if (!err) {
  data = { ... }   // ...because it receives a value here.
  ...
}

Solutions:

don't use var there

start using let


问:
Make PHP code with MySQL work with MsSQL
We have had a project developed by a group of students as part of their masters degree final project. The overall solution turned out to work great, unfortunately it was developed for MySQL database and we are using a MsSQL Server databases.

I have been trying to work out a wait to make it work but I am not really getting anywhere. On the local machine I am running an Apache server with PHP 5.3.29 and Sql Server 2012.

Info from phpinfo();
Apache Version  Apache/2.2.25 (Win32) PHP/5.3.29
I can't see mention of mssql in the phpinfo() but in PHP.ini I do have the following:

```<code>[MSSQL]
; Allow or prevent persistent links.
mssql.allow_persistent = On

; Maximum number of persistent links.  -1 means no limit.
mssql.max_persistent = -1

; Maximum number of links (persistent+non persistent).  -1 means no limit.
mssql.max_links = -1

; Minimum error severity to display.
mssql.min_error_severity = 10

; Minimum message severity to display.
mssql.min_message_severity = 10

; Compatibility mode with old versions of PHP 3.0.
mssql.compatability_mode = Off

; Connect timeout
;mssql.connect_timeout = 5

; Query timeout
;mssql.timeout = 60

; Valid range 0 - 2147483647.  Default = 4096.
;mssql.textlimit = 4096

; Valid range 0 - 2147483647.  Default = 4096.
;mssql.textsize = 4096

; Limits the number of records in each batch.  0 = all records in one batch.
;mssql.batchsize = 0

; Specify how datetime and datetim4 columns are returned
; On => Returns data converted to SQL server settings
; Off => Returns values as YYYY-MM-DD hh:mm:ss
;mssql.datetimeconvert = On

; Use NT authentication when connecting to the server
mssql.secure_connection = On

; Specify max number of processes. -1 = library default
; msdlib defaults to 25
; FreeTDS defaults to 4096
;mssql.max_procs = -1

; Specify client character set.
; If empty or not set the client charset from freetds.conf is used
; This is only used when compiled with FreeTDS
;mssql.charset = "ISO-8859-1"
</code>```

I have tried the following:
dbconnect.php

```<code>$myServer = "localhost";
$myUser = "sa";
$myPass = "sa123";
$myDB = "st";

//connection to the database
$dbhandle = mssql_connect($myServer, $myUser, $myPass)
  or die("Couldn't connect to SQL Server on $myServer");

die();
  $selected = mssql_select_db($myDB, $dbhandle)
  or die("Couldn't open database $myDB");
</code>```

I am first trying to get the system to even allow me to login, so the login.php code is as follows. I have change the queries to mssql:

```<code>    <?php
error_reporting(E_ALL);
session_start(); // Starting Session
require("includes/db_connect.php");
$hint = "";
$username=$_POST["username"];
$password=$_POST["password"];
/*=============================================================
                    SQL INJECTION PREVENTION
===============================================================*/
$PRElist = array();
$PREsql = "SELECT Username, Password FROM tblUsers ;";
$PREresult = mssql_query($PREsql);
//if (mysqli_num_rows($PREresult)>0)
if (1 == 1){
    // output data of each row
    while($row = mssql_fetch_assoc($PREresult)) {
        $PRElist[]= strtolower($row['Username']);
        $PRElist[strtolower($row['Username'])]=$row['Password'];
    }
}//to prevent sql injection
//=======================START LOOKING UP THE USER==================
if ((in_array(strtolower($username), $PRElist))&&($PRElist[strtolower($username)]==$password))
    {
        $sql = "SELECT UserId, Username, Password FROM tblUsers where Username='$username' AND Password='$password'";
        $result = mssql_query($sql);
        $numRows = mssql_num_rows($result);
        if ($numRows > 0) {
            // output data of each row
            while($row = mssql_fetch_assoc($result)) {
                $hint="";                   //initialize the hint string..
                if (strtolower($username)==strtolower($row["Username"])){
                    $userID= $row["UserId"];
                    $sql = "SELECT GroupId FROM tblUserGroups where UserId='$userID'";
                    $result = mssql_query($sql);
                    $numRows1 = mssql_num_rows($result);
                    if ($numRows1 > 0) {
                        // output data of each row
                        while($row = mssql_fetch_assoc($result)) {
                            switch ($row["GroupId"]) {
                                case '1':
                                        header("location: home.php"); // Redirecting To Other Page
                                        $hint="<span style='color:green'> This username is registered </span>";
                                        $_SESSION['login_user']=$username; // Initializing Session
                                        $_SESSION['login_pass']=$password; // Initializing Session# code...
                                        $_SESSION['userID']=$userID; // Initializing Session# code...
                                    break;
                                case '2':
                                        header("location: Team_Home.php"); // Redirecting To Other Page
                                        $hint="<span style='color:green'> This username is registered </span>";
                                        $_SESSION['login_user']=$username; // Initializing Session
                                        $_SESSION['login_pass']=$password; // Initializing Session# code...
                                        $_SESSION['userID']=$userID; // Initializing Session# code...
                                    break;
                                case '3':
                                        header("location: Staff_Home.php"); // Redirecting To Other Page
                                        $hint="<span style='color:green'> This username is registered </span>";
                                        $_SESSION['login_user']=$username; // Initializing Session
                                        $_SESSION['login_pass']=$password; // Initializing Session# code...
                                        $_SESSION['userID']=$userID; // Initializing Session# code...
                                    break;
                                default:
                                        $hint="<span style='color:red'>Not registered...</span>";
                                        header("location: index.php"); // Redirecting To Other Page
                                    break;
                            }
                        }
                    }

                }
                else
                {
                    $hint="<span style='color:red'>Not registered...</span>";
                    header("location: index.php"); // Redirecting To Other Page

                }
            }
        }
    }
    else{
        header("location: index.php"); // Redirecting To Other Page
        $hint="<span style='color:red'>Not registered...</span>";
    }
    echo $hint;
    mssql_close($conn);
</code>```

I am unable to really see what is happening as when I try to login I just get a white screen with no information or errors in the console.

答:
```<code>$myServer = "localhost";
$myUser = "sa";
$myPass = "sa123";
$myDB = "st";

//connection to the database
$dbhandle = mssql_connect($myServer, $myUser, $myPass)
  or die("Couldn't connect to SQL Server on $myServer");

die();   // whats this for? it can cause white screen.**

$selected = mssql_select_db($myDB, $dbhandle)
  or die("Couldn't open database $myDB");
</code>```

Body:
We have had a project developed by a group of students as part of their masters degree final project. The overall solution turned out to work great, unfortunately it was developed for MySQL database and we are using a MsSQL Server databases.

I have been trying to work out a wait to make it work but I am not really getting anywhere. On the local machine I am running an Apache server with PHP 5.3.29 and Sql Server 2012.

Info from phpinfo();
Apache Version  Apache/2.2.25 (Win32) PHP/5.3.29
I can't see mention of mssql in the phpinfo() but in PHP.ini I do have the following:

[MSSQL]
; Allow or prevent persistent links.
mssql.allow_persistent = On

; Maximum number of persistent links.  -1 means no limit.
mssql.max_persistent = -1

; Maximum number of links (persistent+non persistent).  -1 means no limit.
mssql.max_links = -1

; Minimum error severity to display.
mssql.min_error_severity = 10

; Minimum message severity to display.
mssql.min_message_severity = 10

; Compatibility mode with old versions of PHP 3.0.
mssql.compatability_mode = Off

; Connect timeout
;mssql.connect_timeout = 5

; Query timeout
;mssql.timeout = 60

; Valid range 0 - 2147483647.  Default = 4096.
;mssql.textlimit = 4096

; Valid range 0 - 2147483647.  Default = 4096.
;mssql.textsize = 4096

; Limits the number of records in each batch.  0 = all records in one batch.
;mssql.batchsize = 0

; Specify how datetime and datetim4 columns are returned
; On => Returns data converted to SQL server settings
; Off => Returns values as YYYY-MM-DD hh:mm:ss
;mssql.datetimeconvert = On

; Use NT authentication when connecting to the server
mssql.secure_connection = On

; Specify max number of processes. -1 = library default
; msdlib defaults to 25
; FreeTDS defaults to 4096
;mssql.max_procs = -1

; Specify client character set.
; If empty or not set the client charset from freetds.conf is used
; This is only used when compiled with FreeTDS
;mssql.charset = "ISO-8859-1"

I have tried the following:
dbconnect.php

$myServer = "localhost";
$myUser = "sa";
$myPass = "sa123";
$myDB = "st";

//connection to the database
$dbhandle = mssql_connect($myServer, $myUser, $myPass)
  or die("Couldn't connect to SQL Server on $myServer");

die();
  $selected = mssql_select_db($myDB, $dbhandle)
  or die("Couldn't open database $myDB");

I am first trying to get the system to even allow me to login, so the login.php code is as follows. I have change the queries to mssql:

    <?php
error_reporting(E_ALL);
session_start(); // Starting Session
require("includes/db_connect.php");
$hint = "";
$username=$_POST["username"];
$password=$_POST["password"];
/*=============================================================
                    SQL INJECTION PREVENTION
===============================================================*/
$PRElist = array();
$PREsql = "SELECT Username, Password FROM tblUsers ;";
$PREresult = mssql_query($PREsql);
//if (mysqli_num_rows($PREresult)>0)
if (1 == 1){
    // output data of each row
    while($row = mssql_fetch_assoc($PREresult)) {
        $PRElist[]= strtolower($row['Username']);
        $PRElist[strtolower($row['Username'])]=$row['Password'];
    }
}//to prevent sql injection
//=======================START LOOKING UP THE USER==================
if ((in_array(strtolower($username), $PRElist))&&($PRElist[strtolower($username)]==$password))
    {
        $sql = "SELECT UserId, Username, Password FROM tblUsers where Username='$username' AND Password='$password'";
        $result = mssql_query($sql);
        $numRows = mssql_num_rows($result);
        if ($numRows > 0) {
            // output data of each row
            while($row = mssql_fetch_assoc($result)) {
                $hint="";                   //initialize the hint string..
                if (strtolower($username)==strtolower($row["Username"])){
                    $userID= $row["UserId"];
                    $sql = "SELECT GroupId FROM tblUserGroups where UserId='$userID'";
                    $result = mssql_query($sql);
                    $numRows1 = mssql_num_rows($result);
                    if ($numRows1 > 0) {
                        // output data of each row
                        while($row = mssql_fetch_assoc($result)) {
                            switch ($row["GroupId"]) {
                                case '1':
                                        header("location: home.php"); // Redirecting To Other Page
                                        $hint=" This username is registered ";
                                        $_SESSION['login_user']=$username; // Initializing Session
                                        $_SESSION['login_pass']=$password; // Initializing Session# code...
                                        $_SESSION['userID']=$userID; // Initializing Session# code...
                                    break;
                                case '2':
                                        header("location: Team_Home.php"); // Redirecting To Other Page
                                        $hint=" This username is registered ";
                                        $_SESSION['login_user']=$username; // Initializing Session
                                        $_SESSION['login_pass']=$password; // Initializing Session# code...
                                        $_SESSION['userID']=$userID; // Initializing Session# code...
                                    break;
                                case '3':
                                        header("location: Staff_Home.php"); // Redirecting To Other Page
                                        $hint=" This username is registered ";
                                        $_SESSION['login_user']=$username; // Initializing Session
                                        $_SESSION['login_pass']=$password; // Initializing Session# code...
                                        $_SESSION['userID']=$userID; // Initializing Session# code...
                                    break;
                                default:
                                        $hint="Not registered...";
                                        header("location: index.php"); // Redirecting To Other Page
                                    break;
                            }
                        }
                    }

                }
                else
                {
                    $hint="Not registered...";
                    header("location: index.php"); // Redirecting To Other Page

                }
            }
        }
    }
    else{
        header("location: index.php"); // Redirecting To Other Page
        $hint="Not registered...";
    }
    echo $hint;
    mssql_close($conn);

I am unable to really see what is happening as when I try to login I just get a white screen with no information or errors in the console.


问:
Django REST Framework + Django REST Swagger
Having a hard time configuring Swagger UI Here are the very explanatory docs in - https://django-rest-swagger.readthedocs.io/en/latest/. My settings.py looks like this.

urls.py looks like this.

But the swagger web page isn't loading properly.

and the console log is as follows.

What might be the problem here?

答:
Take a look at django-rest-swagger schema documentation, there is some code examples there about how this ties into DRF. You can read some more about this by visiting the DRF Schema Generator documentation.

If you just want to get up and running without learning more about the library, this article does a good job about showing project architecture and integrating DRS with DRF.


问:
Find large number of consecutive values fulfilling condition in a numpy array
I have some audio data loaded in a numpy array and I wish to segment the data by finding silent parts, i.e. parts where the audio amplitude is below a certain threshold over a period in time.

An extremely simple way to do this is something like this:

```<code>values = ''.join(("1" if (abs(x) < SILENCE_THRESHOLD) else "0" for x in samples))
pattern = re.compile('1{%d,}'%int(MIN_SILENCE))
for match in pattern.finditer(values):
   # code goes here
</code>```

The code above finds parts where there are at least MIN_SILENCE consecutive elements smaller than SILENCE_THRESHOLD.

Now, obviously, the above code is horribly inefficient and a terrible abuse of regular expressions. Is there some other method that is more efficient, but still results in equally simple and short code?

答:
Slightly sloppy, but simple and fast-ish, if you don't mind using scipy:

```<code>from scipy.ndimage import gaussian_filter
sigma = 3
threshold = 1
above_threshold = gaussian_filter(data, sigma=sigma) > threshold
</code>```

The idea is that quiet portions of the data will smooth down to low amplitude, and loud regions won't. Tune 'sigma' to affect how long a 'quiet' region must be; tune 'threshold' to affect how quiet it must be. This slows down for large sigma, at which point using FFT-based smoothing might be faster.

This has the added benefit that single 'hot pixels' won't disrupt your silence-finding, so you're a little less sensitive to certain types of noise.

ContentLicense: CC BY-SA 4.0

Body:
I have some audio data loaded in a numpy array and I wish to segment the data by finding silent parts, i.e. parts where the audio amplitude is below a certain threshold over a period in time.

An extremely simple way to do this is something like this:

values = ''.join(("1" if (abs(x) < SILENCE_THRESHOLD) else "0" for x in samples))
pattern = re.compile('1{%d,}'%int(MIN_SILENCE))
for match in pattern.finditer(values):
   # code goes here

The code above finds parts where there are at least MIN_SILENCE consecutive elements smaller than SILENCE_THRESHOLD.

Now, obviously, the above code is horribly inefficient and a terrible abuse of regular expressions. Is there some other method that is more efficient, but still results in equally simple and short code?

Body:
Slightly sloppy, but simple and fast-ish, if you don't mind using scipy:

from scipy.ndimage import gaussian_filter
sigma = 3
threshold = 1
above_threshold = gaussian_filter(data, sigma=sigma) > threshold

The idea is that quiet portions of the data will smooth down to low amplitude, and loud regions won't. Tune 'sigma' to affect how long a 'quiet' region must be; tune 'threshold' to affect how quiet it must be. This slows down for large sigma, at which point using FFT-based smoothing might be faster.

This has the added benefit that single 'hot pixels' won't disrupt your silence-finding, so you're a little less sensitive to certain types of noise.


问:
Can same GUID produce different hash codes?
Given same GUID Object.GetHashCode produces different hash codes but Object.Equals shows that same GUID equals.

The whole GUID:

Not same hash code:

Equals == true:

And, obviously, both are System.Guid:

Even when it's the same GUID, they're different values as they are deserialized from two sources.

Is this the expected behavior?

答:
The screenshots do not show the type of the watched variable, only the value. That value is controlled by the DebuggerDisplay attribute.

I'd bet that the lists contain a Tag class with a DebuggerDisplay attribute that shows a GUID, perhaps the ID that appeared in the last screenshot, eg:

```<code>[DebuggerDisplay("{ID}"]
public class Tag
{
    public Guid ID{get;set;}
    //...
}
</code>```

The Watch window will display the contents of the ID property in the Value column and the actual type Tag in the Type column.

The ID of the Tag may be the same, but the contents may be different, resulting in a different hash code. Equals may work simply because it doesn't use the same fields that GetHashCode() does

Body:
The screenshots do not show the type of the watched variable, only the value. That value is controlled by the DebuggerDisplay attribute.

I'd bet that the lists contain a Tag class with a DebuggerDisplay attribute that shows a GUID, perhaps the ID that appeared in the last screenshot, eg:

[DebuggerDisplay("{ID}"]
public class Tag
{
    public Guid ID{get;set;}
    //...
}

The Watch window will display the contents of the ID property in the Value column and the actual type Tag in the Type column.

The ID of the Tag may be the same, but the contents may be different, resulting in a different hash code. Equals may work simply because it doesn't use the same fields that GetHashCode() does


答:
You need to initialise your variable to empty string. Its considering it as an array and with + sign, it's adding to an array. Hence, you are getting [object Object]

var db = {
  "Root": {
    "DataPage": [{
      "Record": {
        "PPS_NUM": "3207987   ",
        "PO_NUM": "153826-00                     ",
        "OB_TYPE": "SOLK",
        "SHIPMENT": "S258028   "
      }
    }, {
      "Record": {
        "PPS_NUM": "3207500   ",
        "PO_NUM": "10086398                      ",
        "OB_TYPE": "SOLK",
        "SHIPMENT": "S257877   "
      }
    }, {
      "Record": {
        "PPS_NUM": "3207562   ",
        "PO_NUM": "",
        "OB_TYPE": "XFLK",
        "SHIPMENT": "S257881X  "
      }
    }, {
      "Record": {
        "PPS_NUM": "3198033   ",
        "PO_NUM": "SAMPLES 6-14-17               ",
        "OB_TYPE": "SOLK",
        "SHIPMENT": "S255956   "
      }
    }, {
      "Record": {
        "PPS_NUM": "3207443   ",
        "PO_NUM": "491754-2279                   ",
        "OB_TYPE": "SOLK",
        "SHIPMENT": "S257873   "
      }
    }, {
      "Record": {
        "PPS_NUM": "3204961   ",
        "PO_NUM": "",
        "OB_TYPE": "XFLK",
        "SHIPMENT": "S257368   "
      }
    }, {
      "Record": {
        "PPS_NUM": "3207635   ",
        "PO_NUM": "",
        "OB_TYPE": "XFLK",
        "SHIPMENT": "S257904   "
      }
    }, {
      "Record": {
        "PPS_NUM": "3205331   ",
        "PO_NUM": "0188502                       ",
        "OB_TYPE": "SOLK",
        "SHIPMENT": "S257450   "
      }
    }]
  }
};
var p = db.Root.DataPage;
var htmlToAppend = '';
for (var key in p) {
  if (p.hasOwnProperty(key)) {
    htmlToAppend += '
' + p[key].Record.PO_NUM + '
';
    console.log(p[key].Record.PO_NUM);
  }
}
$('#display').html(htmlToAppend);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="display"></p></code>```

Title: undefined object in loop result

Body:
I have my code below here and I noticed that when I display it in my html, I get a [object Object] result in my index 0 which is actually supposed to give me 153826-00.

Weirdly in my console.log, I get the result wanted.

Can someone please explain to me what's happening?

var db = {"Root":{"DataPage":[{"Record":{"PPS_NUM":"3207987   ","PO_NUM":"153826-00                     ","OB_TYPE":"SOLK","SHIPMENT":"S258028   "}},{"Record":{"PPS_NUM":"3207500   ","PO_NUM":"10086398                      ","OB_TYPE":"SOLK","SHIPMENT":"S257877   "}},{"Record":{"PPS_NUM":"3207562   ","PO_NUM":"","OB_TYPE":"XFLK","SHIPMENT":"S257881X  "}},{"Record":{"PPS_NUM":"3198033   ","PO_NUM":"SAMPLES 6-14-17               ","OB_TYPE":"SOLK","SHIPMENT":"S255956   "}},{"Record":{"PPS_NUM":"3207443   ","PO_NUM":"491754-2279                   ","OB_TYPE":"SOLK","SHIPMENT":"S257873   "}},{"Record":{"PPS_NUM":"3204961   ","PO_NUM":"","OB_TYPE":"XFLK","SHIPMENT":"S257368   "}},{"Record":{"PPS_NUM":"3207635   ","PO_NUM":"","OB_TYPE":"XFLK","SHIPMENT":"S257904   "}},{"Record":{"PPS_NUM":"3205331   ","PO_NUM":"0188502                       ","OB_TYPE":"SOLK","SHIPMENT":"S257450   "}}]}};
var p = db.Root.DataPage;
for (var key in p) {
  if (p.hasOwnProperty(key)) {
     db+='
'+p[key].Record.PO_NUM+'
';
     $('#display').html(db);
      console.log(p[key].Record.PO_NUM);
 }
 }
$('#display').html(db);

Body:
You need to initialise your variable to empty string. Its considering it as an array and with + sign, it's adding to an array. Hence, you are getting [object Object]

var db = {
  "Root": {
    "DataPage": [{
      "Record": {
        "PPS_NUM": "3207987   ",
        "PO_NUM": "153826-00                     ",
        "OB_TYPE": "SOLK",
        "SHIPMENT": "S258028   "
      }
    }, {
      "Record": {
        "PPS_NUM": "3207500   ",
        "PO_NUM": "10086398                      ",
        "OB_TYPE": "SOLK",
        "SHIPMENT": "S257877   "
      }
    }, {
      "Record": {
        "PPS_NUM": "3207562   ",
        "PO_NUM": "",
        "OB_TYPE": "XFLK",
        "SHIPMENT": "S257881X  "
      }
    }, {
      "Record": {
        "PPS_NUM": "3198033   ",
        "PO_NUM": "SAMPLES 6-14-17               ",
        "OB_TYPE": "SOLK",
        "SHIPMENT": "S255956   "
      }
    }, {
      "Record": {
        "PPS_NUM": "3207443   ",
        "PO_NUM": "491754-2279                   ",
        "OB_TYPE": "SOLK",
        "SHIPMENT": "S257873   "
      }
    }, {
      "Record": {
        "PPS_NUM": "3204961   ",
        "PO_NUM": "",
        "OB_TYPE": "XFLK",
        "SHIPMENT": "S257368   "
      }
    }, {
      "Record": {
        "PPS_NUM": "3207635   ",
        "PO_NUM": "",
        "OB_TYPE": "XFLK",
        "SHIPMENT": "S257904   "
      }
    }, {
      "Record": {
        "PPS_NUM": "3205331   ",
        "PO_NUM": "0188502                       ",
        "OB_TYPE": "SOLK",
        "SHIPMENT": "S257450   "
      }
    }]
  }
};
var p = db.Root.DataPage;
var htmlToAppend = '';
for (var key in p) {
  if (p.hasOwnProperty(key)) {
    htmlToAppend += '<p>' + p[key].Record.PO_NUM + '</p>';
    console.log(p[key].Record.PO_NUM);
  }
}
$('#display').html(htmlToAppend);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="display"></p>


问:
React Navigation + Redux: How to pass props into StackNavigator?
I'm trying to set up my StackNavigator with redux.

```<code>import { connect } from "react-redux";
import { StackNavigator } from "react-navigation";

import ChatList from "../chat/chat-list";
import ChatDetail from "../chat/chat-detail";

// how do we pass props into this??
const ChatContainer = StackNavigator({
  ChatList: {
    screen: ChatList
  },
  ChatDetail: {
    screen: ChatDetail,
    navigationOptions: ({ navigation }) => ({
      title: "Jesus",
      tabBarVisible: false
    })
  }
});

export default connect(state => ({
  cool: state.cool,
}), dispatch => ({}))(ChatContainer);
</code>```

how would I pass cool into StackNavigator and down to ChatList?

答:
you can use Navigator Props

```<code>const SomeStack = StackNavigator({
  // config
});

<SomeStack
  screenProps={/* this prop will get passed to the screen components as this.props.screenProps */}
/>
</code>```

https://reactnavigation.org/docs/navigators/stack#Navigator-Props

new link for react-navigation 3.x

https://reactnavigation.org/docs/en/stack-navigator.html#navigator-props

Body:
I'm trying to set up my StackNavigator with redux.

import { connect } from "react-redux";
import { StackNavigator } from "react-navigation";

import ChatList from "../chat/chat-list";
import ChatDetail from "../chat/chat-detail";

// how do we pass props into this??
const ChatContainer = StackNavigator({
  ChatList: {
    screen: ChatList
  },
  ChatDetail: {
    screen: ChatDetail,
    navigationOptions: ({ navigation }) => ({
      title: "Jesus",
      tabBarVisible: false
    })
  }
});

export default connect(state => ({
  cool: state.cool,
}), dispatch => ({}))(ChatContainer);

how would I pass cool into StackNavigator and down to ChatList?

Body:
you can use Navigator Props

const SomeStack = StackNavigator({
  // config
});

<SomeStack
  screenProps={/* this prop will get passed to the screen components as this.props.screenProps */}
/>

https://reactnavigation.org/docs/navigators/stack#Navigator-Props

new link for react-navigation 3.x

https://reactnavigation.org/docs/en/stack-navigator.html#navigator-props


答:
db variable is an object and when you append string to this variable, it converts to string and you get [object Object].

Just change your variable name

var db = {"Root":{"DataPage":[{"Record":{"PPS_NUM":"3207987   ","PO_NUM":"153826-00                     ","OB_TYPE":"SOLK","SHIPMENT":"S258028   "}},{"Record":{"PPS_NUM":"3207500   ","PO_NUM":"10086398                      ","OB_TYPE":"SOLK","SHIPMENT":"S257877   "}},{"Record":{"PPS_NUM":"3207562   ","PO_NUM":"","OB_TYPE":"XFLK","SHIPMENT":"S257881X  "}},{"Record":{"PPS_NUM":"3198033   ","PO_NUM":"SAMPLES 6-14-17               ","OB_TYPE":"SOLK","SHIPMENT":"S255956   "}},{"Record":{"PPS_NUM":"3207443   ","PO_NUM":"491754-2279                   ","OB_TYPE":"SOLK","SHIPMENT":"S257873   "}},{"Record":{"PPS_NUM":"3204961   ","PO_NUM":"","OB_TYPE":"XFLK","SHIPMENT":"S257368   "}},{"Record":{"PPS_NUM":"3207635   ","PO_NUM":"","OB_TYPE":"XFLK","SHIPMENT":"S257904   "}},{"Record":{"PPS_NUM":"3205331   ","PO_NUM":"0188502                       ","OB_TYPE":"SOLK","SHIPMENT":"S257450   "}}]}};
var p = db.Root.DataPage;
var htmlValue = "";
for (var key in p) {
  if (p.hasOwnProperty(key)) {
     htmlValue +='
'+p[key].Record.PO_NUM+'
';
     $('#display').html(htmlValue);
      console.log(p[key].Record.PO_NUM);
 }
 }
$('#display').html(htmlValue);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="display"></p></code>```

Title: undefined object in loop result

Body:
db variable is an object and when you append string to this variable, it converts to string and you get [object Object].

Just change your variable name

var db = {"Root":{"DataPage":[{"Record":{"PPS_NUM":"3207987   ","PO_NUM":"153826-00                     ","OB_TYPE":"SOLK","SHIPMENT":"S258028   "}},{"Record":{"PPS_NUM":"3207500   ","PO_NUM":"10086398                      ","OB_TYPE":"SOLK","SHIPMENT":"S257877   "}},{"Record":{"PPS_NUM":"3207562   ","PO_NUM":"","OB_TYPE":"XFLK","SHIPMENT":"S257881X  "}},{"Record":{"PPS_NUM":"3198033   ","PO_NUM":"SAMPLES 6-14-17               ","OB_TYPE":"SOLK","SHIPMENT":"S255956   "}},{"Record":{"PPS_NUM":"3207443   ","PO_NUM":"491754-2279                   ","OB_TYPE":"SOLK","SHIPMENT":"S257873   "}},{"Record":{"PPS_NUM":"3204961   ","PO_NUM":"","OB_TYPE":"XFLK","SHIPMENT":"S257368   "}},{"Record":{"PPS_NUM":"3207635   ","PO_NUM":"","OB_TYPE":"XFLK","SHIPMENT":"S257904   "}},{"Record":{"PPS_NUM":"3205331   ","PO_NUM":"0188502                       ","OB_TYPE":"SOLK","SHIPMENT":"S257450   "}}]}};
var p = db.Root.DataPage;
var htmlValue = "";
for (var key in p) {
  if (p.hasOwnProperty(key)) {
     htmlValue +='<p>'+p[key].Record.PO_NUM+'</p>';
     $('#display').html(htmlValue);
      console.log(p[key].Record.PO_NUM);
 }
 }
$('#display').html(htmlValue);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="display"></p>


问:
How to import js file in typescript?
I want to import js file in typescript.
And I want to access object and function in the js files.
Also I added js file in index.html but It doesn't working too.
so I find a clue that "import '[js file path]'" but it doesn't working.

```<code>import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { NavParams } from 'ionic-angular';
import '../../pages/mobile.js';

@Component({
  selector: 'page-success',
  templateUrl: 'success.html'
})

export class SuccessPage {
  constructor(public navCtrl: NavController, public navParms: NavParams) {

let centerPos =  new atlan.maps.UTMK(953933.75, 1952050.75);

 }
}
</code>```

This is success.ts file. I want to find 'atlan' object.
Give me a solution please. Thx a lot!

答:
You have to use the declare keyword so you do not get any compilation errors. You can do the following</p>

```<code>    import { Component } from '@angular/core';
     ....
    /* Here you are telling typescript compiler to
       ignore this variable it did not originate with typescript.*/
    declare var atlan: any;

    @Component({
      selector: 'page-success',
      templateUrl: 'success.html'
    })

export class SuccessPage {
    ....
}
</code>```

Title: How to import js file in typescript?

Body:
I want to import js file in typescript.
And I want to access object and function in the js files.
Also I added js file in index.html but It doesn't working too.
so I find a clue that "import '[js file path]'" but it doesn't working.

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { NavParams } from 'ionic-angular';
import '../../pages/mobile.js';

@Component({
  selector: 'page-success',
  templateUrl: 'success.html'
})

export class SuccessPage {
  constructor(public navCtrl: NavController, public navParms: NavParams) {

let centerPos =  new atlan.maps.UTMK(953933.75, 1952050.75);

 }
}

This is success.ts file. I want to find 'atlan' object.
Give me a solution please. Thx a lot!

Body:
You have to use the declare keyword so you do not get any compilation errors. You can do the following

    import { Component } from '@angular/core';
     ....
    /* Here you are telling typescript compiler to
       ignore this variable it did not originate with typescript.*/
    declare var atlan: any;

    @Component({
      selector: 'page-success',
      templateUrl: 'success.html'
    })

export class SuccessPage {
    ....
}


问:
Android - chronometer start and stop
I want to create a chronometer which I can start and stop with one button. With my code below I just get a nullpointer exception. How can I avoid it, or set the two functions to the button anyway?</p>

```<code>public class MainActivity extends ActionBarActivity {
  Chronometer focus;
  Button start, stop, reset;
  long timeElapsed = SystemClock.elapsedRealtime() - focus.getBase();
  int x;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    timeElapsed = x;
    start = (Button) findViewById(R.id.button1);
    focus = (Chronometer) findViewById(R.id.chronometer1);

    start.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if(x == 0){
            focus.start();
            }

            if(x != 0){
            focus.stop();
            }
        }
    });

}

}
</code>```

答:
The problem with your code is this line:

```<code>long timeElapsed = SystemClock.elapsedRealtime() - focus.getBase();
</code>```

Since focus variable has not been initialized you get NullPointer.
You should call getBase() after initialization.

Also, you should use ToggleButton instead of Button for this App.

Title: Android - chronometer start and stop

Body:
I want to create a chronometer which I can start and stop with one button. With my code below I just get a nullpointer exception. How can I avoid it, or set the two functions to the button anyway?

public class MainActivity extends ActionBarActivity {
  Chronometer focus;
  Button start, stop, reset;
  long timeElapsed = SystemClock.elapsedRealtime() - focus.getBase();
  int x;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    timeElapsed = x;
    start = (Button) findViewById(R.id.button1);
    focus = (Chronometer) findViewById(R.id.chronometer1);

    start.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if(x == 0){
            focus.start();
            }

            if(x != 0){
            focus.stop();
            }
        }
    });

}

}

Body:
The problem with your code is this line:

long timeElapsed = SystemClock.elapsedRealtime() - focus.getBase();

Since focus variable has not been initialized you get NullPointer.
You should call getBase() after initialization.

Also, you should use ToggleButton instead of Button for this App.


问:
json arrays of object with quotaions mark
I am trying to send an json object to my apiController :

myJson Object that I construct dynamicaly like this :

```<code>var course= new Object();
course.info= $scope.info;
course.studentList = [];
course.studentList = $scope.results;
</code>```

$scope.results is an array that I get from my view :

```<code><select  ng-model="results[$index]" >
    <option value=""></option>
    <option ng-repeat="r in myList" value={{r}}>{{r.studlastname}}</option>
</select>
</code>```

what I expect :

```<code>{
"course": {
     "courseName":"yyy",
     "courseDesc":"xxxx",
     "prof":"prof1"
},
"studentList" :[
    {"studfirstname":"2","studlastname":"","studAge":"21"},
    {"studfirstname":"4","studlastname":"","studAge":"40"},
    {"studfirstname":"6","studlastname":"","studAge":"60"}
]
}
</code>```

what  I have :

```<code>{
"course": {
     "courseName":"yyy",
     "courseDesc":"xxxx",
     "prof":"prof1"
},
"studentList" :[
    "{"studfirstname":"2","studlastname":"","studAge":"21"}",
    "{"studfirstname":"4","studlastname":"","studAge":"40"}",
    "{"studfirstname":"6","studlastname":"","studAge":"60"}"
]
}
</code>```

notice the quotations on every studentList element, this is causing deserialization problem on server side.

please can you help me to remove the quotations ?

thank you in advance.

答:
From what I can see, Problem here is this

```<code>course.studentList = $scope.results;
</code>```

because this line is adding string into your JSON Object as ng-model gives you string instead of object what you are adding in JSON Array.

```<code>course.studentList = JSON.parse($scope.results);
</code>```

Body:
I am trying to send an json object to my apiController :

myJson Object that I construct dynamicaly like this :

var course= new Object();
course.info= $scope.info;
course.studentList = [];
course.studentList = $scope.results;

$scope.results is an array that I get from my view :

<select  ng-model="results[$index]" >
    <option value=""></option>
    <option ng-repeat="r in myList" value={{r}}>{{r.studlastname}}</option>
</select>

what I expect :

{
"course": {
     "courseName":"yyy",
     "courseDesc":"xxxx",
     "prof":"prof1"
},
"studentList" :[
    {"studfirstname":"2","studlastname":"","studAge":"21"},
    {"studfirstname":"4","studlastname":"","studAge":"40"},
    {"studfirstname":"6","studlastname":"","studAge":"60"}
]
}

what  I have :

{
"course": {
     "courseName":"yyy",
     "courseDesc":"xxxx",
     "prof":"prof1"
},
"studentList" :[
    "{"studfirstname":"2","studlastname":"","studAge":"21"}",
    "{"studfirstname":"4","studlastname":"","studAge":"40"}",
    "{"studfirstname":"6","studlastname":"","studAge":"60"}"
]
}

notice the quotations on every studentList element, this is causing deserialization problem on server side.

please can you help me to remove the quotations ?

thank you in advance.

Body:
From what I can see, Problem here is this

course.studentList = $scope.results;

because this line is adding string into your JSON Object as ng-model gives you string instead of object what you are adding in JSON Array.

course.studentList = JSON.parse($scope.results);


问:
Messenger bot with checkbox plugin how to keep track of the conversation with user ref and user id
We'd like to add the facebook messenger checkbox plugin at the end of a request form so users can opt-in for notifications via messenger.

When the user opts in, our webhook receives a callback with the user_ref that we set in the form.

We send a confirmation of opt-in to this user_ref

But other messages we receive like delivery, read receipt or actual messages from the user do contain the user ref anymore but the user id.

This is the official documentation of facebook:

After you receive the callback event, you can call the Send API to start messaging the user using the user_ref identifier in recipient as shown below. Note that this field is the same as the unique user_ref param used before when the plugin was rendered and in confirming the opt-in.

If the call to the Send API is successful, the response will contain a recipient_id parameter, which is a stable user ID that you can now use in future API calls.

Therefore it's impossible to keep track between the initial message and new ones. Does anyone found a solution for this?

Thank you very much in advance.

答:
You can, for example, send additional information when the user opts in using the optional ref parameter. You can send the username of the user logged on my website:

```<code>function confirmOptIn() {
      FB.AppEvents.logEvent('MessengerCheckboxUserConfirmation', null, {
        'app_id':'APP_ID',
        'page_id':'PAGE_ID',
        'ref': 'myuser@mywebsite.com',
        'user_ref':'UNIQUE_REF_PARAM'
      });
</code>```

You will receive the username within optin in your webhook event:

```<code>{
  "recipient":{
    "id":"PAGE_ID"
  },
  "timestamp":1234567890,
  "optin":{
    "ref":"myuser@mywebsite.com",
    "user_ref":"UNIQUE_REF_PARAM"
  }
}
</code>```

Then, you can call the Send API to start messaging the user using the user_ref.

If the call to the Send API is successful, the response will contain a recipient_id parameter, which is a stable user ID that you can now use in future API calls.

...so you will received the Messenger ID which you can map to the username of your website you already have. Here, I modified a little the example from the official developers site to call the send API with user_ref and map the user ID I get in the response to the username of my website:

```<code>function callSendAPICheckbox(messageData, userApplicationId) {
((userApplicationId) => {
    request({
            uri: 'https://graph.facebook.com/v2.6/me/messages',
            qs: {
                access_token: PAGE_ACCESS_TOKEN
            },
            method: 'POST',
            json: messageData

        },
        function(error, response, body) {
            if (!error && response.statusCode == 200) {
                var recipientId = body.recipient_id;
                var messageId = body.message_id;

                if (messageId) {
                    console.log("Map messenger user ID %s with the username of my website %s", recipientId, userApplicationId);
                } else {
                    console.log("Successfully called Send API for recipient %s",
                        recipientId);
                }
            } else {
                console.error("Failed calling Send API for userId " +
                    recipientId, response.statusCode, response.statusMessage, body.error);
            }
        });

})(userApplicationId)
}
</code>```

Body:
You can, for example, send additional information when the user opts in using the optional ref parameter. You can send the username of the user logged on my website:

function confirmOptIn() {
      FB.AppEvents.logEvent('MessengerCheckboxUserConfirmation', null, {
        'app_id':'APP_ID',
        'page_id':'PAGE_ID',
        'ref': 'myuser@mywebsite.com',
        'user_ref':'UNIQUE_REF_PARAM'
      });

You will receive the username within optin in your webhook event:

{
  "recipient":{
    "id":"PAGE_ID"
  },
  "timestamp":1234567890,
  "optin":{
    "ref":"myuser@mywebsite.com",
    "user_ref":"UNIQUE_REF_PARAM"
  }
}

Then, you can call the Send API to start messaging the user using the user_ref.

If the call to the Send API is successful, the response will contain a recipient_id parameter, which is a stable user ID that you can now use in future API calls.

...so you will received the Messenger ID which you can map to the username of your website you already have. Here, I modified a little the example from the official developers site to call the send API with user_ref and map the user ID I get in the response to the username of my website:

function callSendAPICheckbox(messageData, userApplicationId) {
((userApplicationId) => {
    request({
            uri: 'https://graph.facebook.com/v2.6/me/messages',
            qs: {
                access_token: PAGE_ACCESS_TOKEN
            },
            method: 'POST',
            json: messageData

        },
        function(error, response, body) {
            if (!error && response.statusCode == 200) {
                var recipientId = body.recipient_id;
                var messageId = body.message_id;

                if (messageId) {
                    console.log("Map messenger user ID %s with the username of my website %s", recipientId, userApplicationId);
                } else {
                    console.log("Successfully called Send API for recipient %s",
                        recipientId);
                }
            } else {
                console.error("Failed calling Send API for userId " +
                    recipientId, response.statusCode, response.statusMessage, body.error);
            }
        });

})(userApplicationId)
}


问:
VHDL implementation of pipeline calculating Y=A*B+C
I have VHDL code, which implements Y=A*B+C pipeline in three stages, as illustrated below

```<code>library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;

entity pipeline is
   Port (A : in std_logic_vector (15 downto 0);
      B : in std_logic_vector (15 downto 0);
      C : in std_logic_vector (15 downto 0);
      Y : out std_logic_vector (32 downto 0);
      CLK : in std_logic;
      RESET : in std_logic);
end pipeline;

architecture Behavioral3 of pipeline is
   signal OUT_A, OUT_B, OUT_C : std_logic_vector (15 downto 0);
   signal OUT_MUL_2, OUT_C_2 : std_logic_vector (31 downto 0);

   begin
      Stage1: process(CLK, RESET)
         begin
            if RESET ='0' then
               OUT_A <= x"0000";
               OUT_B <= x"0000";
               OUT_C <= x"0000";
            elsif CLK ='1' and CLK'event then
               OUT_A <= A;
               OUT_B <= B;
               OUT_C <= C;
            end if;
       end process;

       Stage2: process(CLK, RESET)
          begin
             if RESET = '0' then
                OUT_MUL_2 <= x"00000000";
                OUT_C_2 <= x"00000000";
             elsif CLK ='1' and CLK'event then
                OUT_MUL_2 <= OUT_A * OUT_B ;
                OUT_C_2 <= x"0000" & OUT_C ;
             end if;
       end process;

       Stage3: process(CLK, RESET)
          begin
             if RESET ='0' then
                Y <= (others => ‘0’);
             elsif CLK ='1' and CLK'event then
                Y <= (‘0’ & OUT_MUL_2) + (‘0’ & OUT_C_2);
             end if;
       end process;
end Behavioral3;
</code>```

Question:
Why in the process "Stage3" the code is :

Y <= (‘0’ & OUT_MUL_2) + (‘0’ & OUT_C_2);

rather than :

Y <= OUT_MUL_2 + OUT_C_2;

Wouldn't the implementation as written yield an OUT signal Y of always 0 (low), because anything&0 is always 0 and 0+0 is again 0 ?

答: Y is the result of an addition of two words of 32 bits. This means Y must be on 33 bits in order to get the carry. So you add a '0' as MSB on your signals in order to compute this carry correctly and fit the result size.</p>

Body:
I have VHDL code, which implements Y=A*B+C pipeline in three stages, as illustrated below

library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.STD_LOGIC_UNSIGNED.ALL;

entity pipeline is
   Port (A : in std_logic_vector (15 downto 0);
      B : in std_logic_vector (15 downto 0);
      C : in std_logic_vector (15 downto 0);
      Y : out std_logic_vector (32 downto 0);
      CLK : in std_logic;
      RESET : in std_logic);
end pipeline;

architecture Behavioral3 of pipeline is
   signal OUT_A, OUT_B, OUT_C : std_logic_vector (15 downto 0);
   signal OUT_MUL_2, OUT_C_2 : std_logic_vector (31 downto 0);

   begin
      Stage1: process(CLK, RESET)
         begin
            if RESET ='0' then
               OUT_A <= x"0000";
               OUT_B <= x"0000";
               OUT_C <= x"0000";
            elsif CLK ='1' and CLK'event then
               OUT_A <= A;
               OUT_B <= B;
               OUT_C <= C;
            end if;
       end process;

       Stage2: process(CLK, RESET)
          begin
             if RESET = '0' then
                OUT_MUL_2 <= x"00000000";
                OUT_C_2 <= x"00000000";
             elsif CLK ='1' and CLK'event then
                OUT_MUL_2 <= OUT_A * OUT_B ;
                OUT_C_2 <= x"0000" & OUT_C ;
             end if;
       end process;

       Stage3: process(CLK, RESET)
          begin
             if RESET ='0' then
                Y <= (others => ‘0’);
             elsif CLK ='1' and CLK'event then
                Y <= (‘0’ & OUT_MUL_2) + (‘0’ & OUT_C_2);
             end if;
       end process;
end Behavioral3;

Question:
Why in the process "Stage3" the code is :

Y <= (‘0’ & OUT_MUL_2) + (‘0’ & OUT_C_2);

rather than :

Y <= OUT_MUL_2 + OUT_C_2;

Wouldn't the implementation as written yield an OUT signal Y of always 0 (low), because anything&0 is always 0 and 0+0 is again 0 ?


问:
Ember 2, which differences in this code?
I'm using this code to simulate a server delay for my gets.

```<code>let promises = [];
child.get('authors').forEach(author => author.get('books').forEach(book => {
  var promise = new RSVP.Promise(function (resolve, reject) {
    let time = (Math.floor(Math.random() * 10) + 1) * 1000;
    Ember.run.later(() => {
      favoriteList.pushObject(book);
      resolve();
    }, time);
    if (somethingWrong) {
      reject(error);
    }
  });
  promises.push(promise)
}));

RSVP.all(promises).then(function () {
  console.log('Yoo! Finally!')
}).catch(function (error) {});
</code>```

I'm wondering (except for the Ember.run.later() which I use to simulate a server delay for all my "gets") if there are differences in this code below?

```<code>child.get('authors').forEach(author => author.get('books').forEach(book => {
  favoriteList.pushObject(book);
}));

console.log('Yoo! Finally!')
</code>```

And what differences with this code?

```<code>child.get('authors').forEach(author => author.get('books')
  .reduce((accumulator, book) => {
    favoriteList.pushObject(book);
  })
);
console.log('Yoo! Finally!')
</code>```

I'm wondering also performances differences and server delay handle ones...

答:
This is a link that shows a benchmark test around different functions that iterates over one array: https://jsperf.com/array-reduce-vs-foreach/9

This shows that forEach is slower than the reduce for a sum operation.

Apart from that, you are not using reduce appropriately. You can see you are not using the previous result in your current operation. So why use reduce? You are confusing the programmer because it is expected to use the previous result and return the result in reduce operations.

(I guess that's what happenedd to you? You got this code from someone else and got confused. Right? So, use the functions for what they were designed for)

Body:
I'm using this code to simulate a server delay for my gets.

let promises = [];
child.get('authors').forEach(author => author.get('books').forEach(book => {
  var promise = new RSVP.Promise(function (resolve, reject) {
    let time = (Math.floor(Math.random() * 10) + 1) * 1000;
    Ember.run.later(() => {
      favoriteList.pushObject(book);
      resolve();
    }, time);
    if (somethingWrong) {
      reject(error);
    }
  });
  promises.push(promise)
}));

RSVP.all(promises).then(function () {
  console.log('Yoo! Finally!')
}).catch(function (error) {});

I'm wondering (except for the Ember.run.later() which I use to simulate a server delay for all my "gets") if there are differences in this code below?

child.get('authors').forEach(author => author.get('books').forEach(book => {
  favoriteList.pushObject(book);
}));

console.log('Yoo! Finally!')

And what differences with this code?

child.get('authors').forEach(author => author.get('books')
  .reduce((accumulator, book) => {
    favoriteList.pushObject(book);
  })
);
console.log('Yoo! Finally!')

I'm wondering also performances differences and server delay handle ones...


问:
What message causes a button to send a WM_COMMAND message
I know that a Button, when clicked, sends the WM_COMMAND message to it's parent, but what message does it receive that makes it send this message? I am overriding the default WndProc of a button and the button does not receive the WM_COMMAND message, so I need to know what message causes a button to send the WM_COMMAND message so I can replicate that functionality.</p>

答: I found that it's actually a combination of WM_LBUTTONDOWN, WM_MOUSELEAVE, and a few other things. For example, the WM_COMMAND will only be fired if the mouse was depressed on the button, and is still on the button when WM_LBUTTONUP is fired. As for space, enter, etc, I believe it just handles the VK_ENTER message and stuff.</p>


问:
How to enable LocalStorage on iOS Safari browser on private mode?
I am working on project SPA angular app which requires localstorage of browser to store values. We came to notice that iOS doesn't allow to access localstorage on private mode.

We fixed the issue by checking the browser compatibility for localstorage. If it's not allowing local storage we use $rootScope object of AngularJS to store values temporarily.

Only challenge of this approach is when page is refreshed data will be cleared which make sense as we are using $rootScope which will be destroyed upon page refresh

Here are my questions:

Is their any way to enable localstorage through javascript?

Is their any better alternative approach? Ideally we want to retain values upon page refresh. How's that possible? (Is it good to use localstorage)

Thanks,
Gokul

答:
No, you can't enable localstorage through js or another hacky way.

The best alternative I think is to use cookies

You can learn how to use cookies from here https://www.w3schools.com/js/js_cookies.asp

And for angularJS
https://docs.angularjs.org/api/ngCookies/service/$cookies


问:
calculated field using if and or in ms-sql
```<code>IF(
    [dbo.tblx.Category] = 'WS' OR [dbo.tblx.Category] = 'SEM',
    0,
    [dbo.tblx.Tonnes] * [dbo.tblx.Grade] / 1000
)
</code>```

this returns the entire text and not the "calculation"

can someone help me...what am I doing wrong?

i tried

```<code>CASE WHEN dbo.tblx.Category = 'WS' OR dbo.tblx.Category = 'SEM' THEN 0
     ELSE  dbo.tblx.Tonnes * dbo.tblx.Grade / 1000
END AS Metal
</code>```

Do perhaps insert something before "CASE WHEN"? it is not running

答:
As I understood, you are trying to create a computed column, using value from other table.
I think in this case you have to use a User Defined function in the formula for computed column.  If you give more information I can try to write some code for you.

Instead, if you just want to add a column in a query you can use:

```<code>CASE WHEN dbo.tblx.Category = 'WS' OR dbo.tblPTx.Category = 'SEM' THEN 0
   ELSE  dbo.tblx.Tonnes * dbo.tblx.Grade / 1000 END AS NAME_OF_YOUR_NEW_COLUMN
</code>```

Body:
IF(
    [dbo.tblx.Category] = 'WS' OR [dbo.tblx.Category] = 'SEM',
    0,
    [dbo.tblx.Tonnes] * [dbo.tblx.Grade] / 1000
)

this returns the entire text and not the "calculation"

can someone help me...what am I doing wrong?

i tried

CASE WHEN dbo.tblx.Category = 'WS' OR dbo.tblx.Category = 'SEM' THEN 0
     ELSE  dbo.tblx.Tonnes * dbo.tblx.Grade / 1000
END AS Metal

Do perhaps insert something before "CASE WHEN"? it is not running

Body:
As I understood, you are trying to create a computed column, using value from other table.
I think in this case you have to use a User Defined function in the formula for computed column.  If you give more information I can try to write some code for you.

Instead, if you just want to add a column in a query you can use:

CASE WHEN dbo.tblx.Category = 'WS' OR dbo.tblPTx.Category = 'SEM' THEN 0
   ELSE  dbo.tblx.Tonnes * dbo.tblx.Grade / 1000 END AS NAME_OF_YOUR_NEW_COLUMN


问:
Knockout viewmodel passed to action coming empty
I have a controller action where I'm trying to post a model from knockout:

```<code>    [HttpPost]
    public void AddItems(MyViewModel model)
    {
        [...]
    }
</code>```

knockout action:

```<code>self.AddItems = function (data, event) {
    var url = "/MyController/AddItems";
    var target = event.target || event.srcElement;
    var model = ko.toJSON(self);
    $.post(url,
            model,
            function (result) {

            })
        .success(function () { console.log("AddItems second success"); })
        .error(function () { console.log("AddItems error"); })
        .complete(function () { console.log("AddItems complete"); });

    // this doesn't work either
    //var model2 = ko.toJSON({ model: self });
    //$.ajax(url, {
    //    data: model,
    //    type: "post",
    //    async: false,
    //    contentType: "application/json",
    //    success: function (data) {
    //        console.log("AddItems second success");
    //    },
    //    error: function (xmlHttpRequest, textStatus, errorThrown) {
    //        console.log("AddItems error");
    //    }
    //});
}
</code>```

I have commented out another post action which I tried as well - this one doesn't reach the controller action at all returning a 500 error in js console.

The model:

```<code>public class MyViewModel
{
    public int Id { get; set; }

    public string Ref { get; set; }

    public List<ItemViewModel> Items { get; set; }

    public decimal PriceTotal { get; set; }
}
</code>```

The model which gets posted to action has the correct structure but all properties are either empty or null.

How to pass a knockout viewmodel to the action with correct object data?

***** EDIT *****

I think the action doesn't get the json model.

Because when I pass a hand written raw object model:

```<code>var model4 = {
  "Ref": "sgsgsasg",
  "Id": 1,
  "PriceTotal": 382
}
</code>```

it gets to the action nicely and with correct values.

While the knockout passes json and then the action cannot convert it to the mvc model.

答:
I am pretty sure you are only missing a content type header.

By default jQuery posts data as application/x-www-form-urlencoded. You want application/json. jQuery $.ajax() lets you configure the content type:

```<code>self.AddItems = function () {
    return $.ajax({
        url: "/MyController/AddItems",
        data: ko.toJSON(self),
        contentType: "application/json"
    })
    .done(function () { console.log("AddItems success"); })
    .fail(function () { console.log("AddItems error"); })
    .always(function () { console.log("AddItems complete"); });
}
</code>```

Side note: Returning the request from the function enables you to attach more behavior to it elsewhere:

```<code>self.something = function () {
    // do some work on the viewmodel
    self.AddItems().done(function () {
        // we are done
    });
}
</code>```

Body:
I have a controller action where I'm trying to post a model from knockout:

    [HttpPost]
    public void AddItems(MyViewModel model)
    {
        [...]
    }

knockout action:

self.AddItems = function (data, event) {
    var url = "/MyController/AddItems";
    var target = event.target || event.srcElement;
    var model = ko.toJSON(self);
    $.post(url,
            model,
            function (result) {

            })
        .success(function () { console.log("AddItems second success"); })
        .error(function () { console.log("AddItems error"); })
        .complete(function () { console.log("AddItems complete"); });

    // this doesn't work either
    //var model2 = ko.toJSON({ model: self });
    //$.ajax(url, {
    //    data: model,
    //    type: "post",
    //    async: false,
    //    contentType: "application/json",
    //    success: function (data) {
    //        console.log("AddItems second success");
    //    },
    //    error: function (xmlHttpRequest, textStatus, errorThrown) {
    //        console.log("AddItems error");
    //    }
    //});
}

I have commented out another post action which I tried as well - this one doesn't reach the controller action at all returning a 500 error in js console.

The model:

public class MyViewModel
{
    public int Id { get; set; }

    public string Ref { get; set; }

    public List<ItemViewModel> Items { get; set; }

    public decimal PriceTotal { get; set; }
}

The model which gets posted to action has the correct structure but all properties are either empty or null.

How to pass a knockout viewmodel to the action with correct object data?

***** EDIT *****

I think the action doesn't get the json model.

Because when I pass a hand written raw object model:

var model4 = {
  "Ref": "sgsgsasg",
  "Id": 1,
  "PriceTotal": 382
}

it gets to the action nicely and with correct values.

While the knockout passes json and then the action cannot convert it to the mvc model.

Body:
I am pretty sure you are only missing a content type header.

By default jQuery posts data as application/x-www-form-urlencoded. You want application/json. jQuery $.ajax() lets you configure the content type:

self.AddItems = function () {
    return $.ajax({
        url: "/MyController/AddItems",
        data: ko.toJSON(self),
        contentType: "application/json"
    })
    .done(function () { console.log("AddItems success"); })
    .fail(function () { console.log("AddItems error"); })
    .always(function () { console.log("AddItems complete"); });
}

Side note: Returning the request from the function enables you to attach more behavior to it elsewhere:

self.something = function () {
    // do some work on the viewmodel
    self.AddItems().done(function () {
        // we are done
    });
}


问:
Protected and private methods in Rails
Method visibility in Ruby (public, protected, and private methods) has been well explained in places like this blog post. But in Ruby on Rails it seems slightly different than it would be in a regular Ruby application because of the way the framework is set up. So, in Rails models, controllers, helpers, tests, etc., when is/isn't it appropriate to use protected or private methods?

Edit: Thanks for the answers so far. I understand the concept of protected and private in Ruby, but I'm looking more for an explanation of the typical way those types of visibility are used within the context of the various pieces of a Rails app (models, controllers, helpers, tests). For example, public controller methods are action methods, protected methods in the application controller are used for "helper methods" that need to be accessed by multiple controllers, etc.

答:
The difference between protected and
  private is subtle. If a method is
  protected, it may be called by any
  instance of the defining class or its
  subclasses. If a method is private, it
  may be called only within the context
  of the calling object---it is never
  possible to access another object
  instance's private methods directly,
  even if the object is of the same
  class as the caller. For protected
  methods, they are accessible from
  objects of the same class (or
  children).

http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Classes#Declaring_Visibility

Title: Protected and private methods in Rails