问:
Replace mongodb document without appending attributes
I think I have a weird one here.

I'm using mongoose in express to update a document in a collection. The model looks like this:

```<code>var customers = new Schema({
companyName: String,
addressLine1: String,
addressLine2: String,
city: String,
province: String,
postal: String,
businessPhone: String,
contacts: [{
    firstName: String,
    lastName: String,
    title: String,
    phone: String,
    email: String
}],
custCode: Number,
rep: String
});
</code>```

Above is a new model, as the old model looked like this:

```<code>var customers = new Schema({
companyName: String,
firstName: String,
lastName: String,
addressLine1: String,
addressLine2: String,
city: String,
province: String,
postal: String,
businessPhone: String,
email: String
custCode: Number,
rep: String
});
</code>```

The difference is that I broke out a "contacts" array so I can add more contacts in the future. Existing documents in the collection have the old style of model and the update object has the new model.

When I run the following code, the document ends up getting appended with the contacts array, but also keeps the firstName and lastName, email etc instead of losing it as per the rules of the new model.

```<code>var conditions = {custCode:req.body.customer.custCode}
, update = req.body.customer
, options = {upsert: false, new: true};

mongoose.model('customers').findOneAndUpdate(conditions, update, options, callback);
function callback (err, doc) {
    if(err) {
      console.log("Errors: " + err);
      res.sendStatus(500);
    } else {
      console.log("Customer Saved! Rows affected: ", doc);
      res.sendStatus(200);
    };
  };
</code>```

Is there a different mongoose function that I should be using? Should I be using $unset?

I'd rather not do two calls to the database (one to remove the matching collection and another to save a new model.

Thanks so much in advance!

答:
findOneAndUpdate modifies an existing document with the new data.

The options you have provided don't modify document replacement.

upsert affects creation of new documents when the current doesn't exist.

new affects which data is returned by the function. pre or post update.

If you have the complete set of data in the update variable, you can completely replace the existing document with replaceOne

```<code>mongoose.model('customers').replaceOne(conditions, update, options, callback);
function callback (err, doc) {
    if(err) {
      console.log("Errors: " + err);
      res.sendStatus(500);
    } else {
      console.log("Customer Saved! Rows affected: ", doc);
      res.sendStatus(200);
    };
  };
</code>```

Body:
I think I have a weird one here.

I'm using mongoose in express to update a document in a collection. The model looks like this:

var customers = new Schema({
companyName: String,
addressLine1: String,
addressLine2: String,
city: String,
province: String,
postal: String,
businessPhone: String,
contacts: [{
    firstName: String,
    lastName: String,
    title: String,
    phone: String,
    email: String
}],
custCode: Number,
rep: String
});

Above is a new model, as the old model looked like this:

var customers = new Schema({
companyName: String,
firstName: String,
lastName: String,
addressLine1: String,
addressLine2: String,
city: String,
province: String,
postal: String,
businessPhone: String,
email: String
custCode: Number,
rep: String
});

The difference is that I broke out a "contacts" array so I can add more contacts in the future. Existing documents in the collection have the old style of model and the update object has the new model.

When I run the following code, the document ends up getting appended with the contacts array, but also keeps the firstName and lastName, email etc instead of losing it as per the rules of the new model.

var conditions = {custCode:req.body.customer.custCode}
, update = req.body.customer
, options = {upsert: false, new: true};

mongoose.model('customers').findOneAndUpdate(conditions, update, options, callback);
function callback (err, doc) {
    if(err) {
      console.log("Errors: " + err);
      res.sendStatus(500);
    } else {
      console.log("Customer Saved! Rows affected: ", doc);
      res.sendStatus(200);
    };
  };

Is there a different mongoose function that I should be using? Should I be using $unset?

I'd rather not do two calls to the database (one to remove the matching collection and another to save a new model.

Thanks so much in advance!

Body:
findOneAndUpdate modifies an existing document with the new data.

The options you have provided don't modify document replacement.

upsert affects creation of new documents when the current doesn't exist.

new affects which data is returned by the function. pre or post update.

If you have the complete set of data in the update variable, you can completely replace the existing document with replaceOne

mongoose.model('customers').replaceOne(conditions, update, options, callback);
function callback (err, doc) {
    if(err) {
      console.log("Errors: " + err);
      res.sendStatus(500);
    } else {
      console.log("Customer Saved! Rows affected: ", doc);
      res.sendStatus(200);
    };
  };


来源: stackexchange

问:
Leaking memory with pthreads
I'm using pthreads and according to valgrind I am leaking memory, like in valgrind memory leak errors when using pthread_create

The top answer says that if you pthread_join all the threads this memory will be reclaimed, but it isn't for me.

```<code>pthread_t threads[NUM_THREADS];
...
for (i = 0; i < NUM_THREADS; i++) {
    pthread_create(&threads[i], &attr, Worker, NULL);
}
...
for (i = 0; i < NUM_THREADS; i++) {
    pthread_join(threads[i], NULL);
}
</code>```

valgrind output

```<code>==2707== HEAP SUMMARY:
==2707==     in use at exit: 954 bytes in 4 blocks
==2707==   total heap usage: 7,717 allocs, 7,713 frees, 79,563 bytes allocated
==2707==
==2707== 34 bytes in 1 blocks are still reachable in loss record 1 of 4
==2707==    at 0x402BE68: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==2707==    by 0x400541E: local_strdup (dl-load.c:162)
==2707==    by 0x40085D3: _dl_map_object (dl-load.c:2473)
==2707==    by 0x4012D5C: dl_open_worker (dl-open.c:225)
==2707==    by 0x400ECBE: _dl_catch_error (dl-error.c:178)
==2707==    by 0x4184D40: do_dlopen (dl-libc.c:89)
==2707==    by 0x404CD4B: start_thread (pthread_create.c:308)
==2707==    by 0x414BACD: clone (clone.S:130)
==2707==
==2707== 34 bytes in 1 blocks are still reachable in loss record 2 of 4
==2707==    at 0x402BE68: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==2707==    by 0x400B05A: _dl_new_object (dl-object.c:161)
==2707==    by 0x4006437: _dl_map_object_from_fd (dl-load.c:1051)
==2707==    by 0x400839F: _dl_map_object (dl-load.c:2568)
==2707==    by 0x4012D5C: dl_open_worker (dl-open.c:225)
==2707==    by 0x400ECBE: _dl_catch_error (dl-error.c:178)
==2707==    by 0x4184D40: do_dlopen (dl-libc.c:89)
==2707==    by 0x404CD4B: start_thread (pthread_create.c:308)
==2707==    by 0x414BACD: clone (clone.S:130)
==2707==
==2707== 256 bytes in 1 blocks are still reachable in loss record 3 of 4
==2707==    at 0x402A5E6: calloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==2707==    by 0x401045C: _dl_check_map_versions (dl-version.c:300)
==2707==    by 0x401336A: dl_open_worker (dl-open.c:268)
==2707==    by 0x400ECBE: _dl_catch_error (dl-error.c:178)
==2707==    by 0x4184D40: do_dlopen (dl-libc.c:89)
==2707==    by 0x404CD4B: start_thread (pthread_create.c:308)
==2707==    by 0x414BACD: clone (clone.S:130)
==2707==
==2707== 630 bytes in 1 blocks are still reachable in loss record 4 of 4
==2707==    at 0x402A5E6: calloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==2707==    by 0x400AE0F: _dl_new_object (dl-object.c:77)
==2707==    by 0x4006437: _dl_map_object_from_fd (dl-load.c:1051)
==2707==    by 0x400839F: _dl_map_object (dl-load.c:2568)
==2707==    by 0x4012D5C: dl_open_worker (dl-open.c:225)
==2707==    by 0x400ECBE: _dl_catch_error (dl-error.c:178)
==2707==    by 0x4184D40: do_dlopen (dl-libc.c:89)
==2707==    by 0x404CD4B: start_thread (pthread_create.c:308)
==2707==    by 0x414BACD: clone (clone.S:130)
==2707==
==2707== LEAK SUMMARY:
==2707==    definitely lost: 0 bytes in 0 blocks
==2707==    indirectly lost: 0 bytes in 0 blocks
==2707==      possibly lost: 0 bytes in 0 blocks
==2707==    still reachable: 954 bytes in 4 blocks
==2707==         suppressed: 0 bytes in 0 blocks
==2707==
==2707== For counts of detected and suppressed errors, rerun with: -v
==2707== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
</code>```

Am I doing something wrong or is the top answer incorrect?

答:
I am probably late to the show. As pointed out, it must not have any memory leak - I checked what you have done it is standard way of creating (create internal memory for thread) and joining a thread (auto reclaims this memory).

However, you have not shown the initialization of attr.

You may try doing:

```<code>pthread_create(&threads[i], NULL, Worker, NULL);
</code>```

I have placed NULL here, instead of any value for attr. The pthread initialization is tightly coupled to attribute (unless it is provided as NULL).

ContentLicense: CC BY-SA 3.0

Title: Leaking memory with pthreads

Body:
I'm using pthreads and according to valgrind I am leaking memory, like in valgrind memory leak errors when using pthread_create

The top answer says that if you pthread_join all the threads this memory will be reclaimed, but it isn't for me.

pthread_t threads[NUM_THREADS];
...
for (i = 0; i < NUM_THREADS; i++) {
    pthread_create(&threads[i], &attr, Worker, NULL);
}
...
for (i = 0; i < NUM_THREADS; i++) {
    pthread_join(threads[i], NULL);
}

valgrind output

==2707== HEAP SUMMARY:
==2707==     in use at exit: 954 bytes in 4 blocks
==2707==   total heap usage: 7,717 allocs, 7,713 frees, 79,563 bytes allocated
==2707==
==2707== 34 bytes in 1 blocks are still reachable in loss record 1 of 4
==2707==    at 0x402BE68: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==2707==    by 0x400541E: local_strdup (dl-load.c:162)
==2707==    by 0x40085D3: _dl_map_object (dl-load.c:2473)
==2707==    by 0x4012D5C: dl_open_worker (dl-open.c:225)
==2707==    by 0x400ECBE: _dl_catch_error (dl-error.c:178)
==2707==    by 0x4184D40: do_dlopen (dl-libc.c:89)
==2707==    by 0x404CD4B: start_thread (pthread_create.c:308)
==2707==    by 0x414BACD: clone (clone.S:130)
==2707==
==2707== 34 bytes in 1 blocks are still reachable in loss record 2 of 4
==2707==    at 0x402BE68: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==2707==    by 0x400B05A: _dl_new_object (dl-object.c:161)
==2707==    by 0x4006437: _dl_map_object_from_fd (dl-load.c:1051)
==2707==    by 0x400839F: _dl_map_object (dl-load.c:2568)
==2707==    by 0x4012D5C: dl_open_worker (dl-open.c:225)
==2707==    by 0x400ECBE: _dl_catch_error (dl-error.c:178)
==2707==    by 0x4184D40: do_dlopen (dl-libc.c:89)
==2707==    by 0x404CD4B: start_thread (pthread_create.c:308)
==2707==    by 0x414BACD: clone (clone.S:130)
==2707==
==2707== 256 bytes in 1 blocks are still reachable in loss record 3 of 4
==2707==    at 0x402A5E6: calloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==2707==    by 0x401045C: _dl_check_map_versions (dl-version.c:300)
==2707==    by 0x401336A: dl_open_worker (dl-open.c:268)
==2707==    by 0x400ECBE: _dl_catch_error (dl-error.c:178)
==2707==    by 0x4184D40: do_dlopen (dl-libc.c:89)
==2707==    by 0x404CD4B: start_thread (pthread_create.c:308)
==2707==    by 0x414BACD: clone (clone.S:130)
==2707==
==2707== 630 bytes in 1 blocks are still reachable in loss record 4 of 4
==2707==    at 0x402A5E6: calloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==2707==    by 0x400AE0F: _dl_new_object (dl-object.c:77)
==2707==    by 0x4006437: _dl_map_object_from_fd (dl-load.c:1051)
==2707==    by 0x400839F: _dl_map_object (dl-load.c:2568)
==2707==    by 0x4012D5C: dl_open_worker (dl-open.c:225)
==2707==    by 0x400ECBE: _dl_catch_error (dl-error.c:178)
==2707==    by 0x4184D40: do_dlopen (dl-libc.c:89)
==2707==    by 0x404CD4B: start_thread (pthread_create.c:308)
==2707==    by 0x414BACD: clone (clone.S:130)
==2707==
==2707== LEAK SUMMARY:
==2707==    definitely lost: 0 bytes in 0 blocks
==2707==    indirectly lost: 0 bytes in 0 blocks
==2707==      possibly lost: 0 bytes in 0 blocks
==2707==    still reachable: 954 bytes in 4 blocks
==2707==         suppressed: 0 bytes in 0 blocks
==2707==
==2707== For counts of detected and suppressed errors, rerun with: -v
==2707== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

Am I doing something wrong or is the top answer incorrect?

Body:
I am probably late to the show. As pointed out, it must not have any memory leak - I checked what you have done it is standard way of creating (create internal memory for thread) and joining a thread (auto reclaims this memory).

However, you have not shown the initialization of attr.

You may try doing:

pthread_create(&threads[i], NULL, Worker, NULL);

I have placed NULL here, instead of any value for attr. The pthread initialization is tightly coupled to attribute (unless it is provided as NULL).


问:
Script timed out before returning headers: wsgi.py on elastic beanstalk
I'm trying to deploy a Django application to Elastic Beanstalk. When I visit the page it never loads. The logs say:

```<code>Script timed out before returning headers: wsgi.py
</code>```

I can ssh into the server and run manage.py runserver and then curl 127.0.0.1:8000 from another terminal, which will return the page successfully. So I'm assuming it must be an issue with the Apache configuration that is set up as a part of Elastic Beanstalk.

Here is more of the logs:

```<code>[pid 15880] AH01232: suEXEC mechanism enabled (wrapper: /usr/sbin/suexec)
[so:warn] [pid 15880] AH01574: module wsgi_module is already loaded, skipping
[auth_digest:notice] [pid 15880] AH01757: generating secret for digest authentication ...
[lbmethod_heartbeat:notice] [pid 15880] AH02282: No slotmem from mod_heartmonitor
[mpm_prefork:notice] [pid 15880] AH00163: Apache/2.4.9 (Amazon) mod_wsgi/3.4 Python/2.7.5       configured -- resuming normal operations
[core:notice] [pid 15880] AH00094: Command line: '/usr/sbin/httpd -D FOREGROUND'
[:error] [pid 15881] /opt/python/run/venv/lib/python2.7/site-packages/numpy/oldnumeric/__init__.py:11: ModuleDeprecationWarning: The oldnumeric module will be dropped in Numpy 1.9
[:error] [pid 15881]   warnings.warn(_msg, ModuleDeprecationWarning)
[:error] [pid 15881]
[core:error] [pid 15884] [client 10.248.110.45:58996] Script timed out before returning headers: wsgi.py
</code>```

And my wsgi.py file:

```<code>import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "aurora.settings")

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
</code>```

Any clues as to what could be causing this?

UPDATE:

I rebuilt my environment and ran into this issue again. I updated /etc/httpd/conf.d/wsgi.conf to include WSGIApplicationGroup %{GLOBAL} as mentioned here. I am using Scipy, Numpy, and GeoDjango (which uses GDAL). I know GDAL is not entirely thread safe and I'm not sure about the others but I'm assuming it was a thread safety issue.

答:
The fix for us was to add the WSGIApplicationGroup %{GLOBAL} setting as per Meistro's answer.

You'll want to ensure you edit your wsgi config by way of your .ebextensions/foobar.config file, so that the changes are permanent. See the .ebextensions config docs.

Add the following to your .ebextensions/foobar.config file:

```<code>files:
  "/etc/httpd/conf.d/wsgi_custom.conf":
    mode: "000644"
    owner: root
    group: root
    content: |
      WSGIApplicationGroup %{GLOBAL}
</code>```

This will create (or overwrite) the contents of the /etc/httpd/conf.d/wsgi_custom.conf file with WSGIApplicationGroup %{GLOBAL}

Body:
I'm trying to deploy a Django application to Elastic Beanstalk. When I visit the page it never loads. The logs say:

Script timed out before returning headers: wsgi.py

I can ssh into the server and run manage.py runserver and then curl 127.0.0.1:8000 from another terminal, which will return the page successfully. So I'm assuming it must be an issue with the Apache configuration that is set up as a part of Elastic Beanstalk.

Here is more of the logs:

[pid 15880] AH01232: suEXEC mechanism enabled (wrapper: /usr/sbin/suexec)
[so:warn] [pid 15880] AH01574: module wsgi_module is already loaded, skipping
[auth_digest:notice] [pid 15880] AH01757: generating secret for digest authentication ...
[lbmethod_heartbeat:notice] [pid 15880] AH02282: No slotmem from mod_heartmonitor
[mpm_prefork:notice] [pid 15880] AH00163: Apache/2.4.9 (Amazon) mod_wsgi/3.4 Python/2.7.5       configured -- resuming normal operations
[core:notice] [pid 15880] AH00094: Command line: '/usr/sbin/httpd -D FOREGROUND'
[:error] [pid 15881] /opt/python/run/venv/lib/python2.7/site-packages/numpy/oldnumeric/__init__.py:11: ModuleDeprecationWarning: The oldnumeric module will be dropped in Numpy 1.9
[:error] [pid 15881]   warnings.warn(_msg, ModuleDeprecationWarning)
[:error] [pid 15881]
[core:error] [pid 15884] [client 10.248.110.45:58996] Script timed out before returning headers: wsgi.py

And my wsgi.py file:

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "aurora.settings")

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

Any clues as to what could be causing this?

UPDATE:

I rebuilt my environment and ran into this issue again. I updated /etc/httpd/conf.d/wsgi.conf to include WSGIApplicationGroup %{GLOBAL} as mentioned here. I am using Scipy, Numpy, and GeoDjango (which uses GDAL). I know GDAL is not entirely thread safe and I'm not sure about the others but I'm assuming it was a thread safety issue.

Body:
The fix for us was to add the WSGIApplicationGroup %{GLOBAL} setting as per Meistro's answer.

You'll want to ensure you edit your wsgi config by way of your .ebextensions/foobar.config file, so that the changes are permanent. See the .ebextensions config docs.

Add the following to your .ebextensions/foobar.config file:

files:
  "/etc/httpd/conf.d/wsgi_custom.conf":
    mode: "000644"
    owner: root
    group: root
    content: |
      WSGIApplicationGroup %{GLOBAL}

This will create (or overwrite) the contents of the /etc/httpd/conf.d/wsgi_custom.conf file with WSGIApplicationGroup %{GLOBAL}


问:
Getting the exception value in Python
If I have that code:

```<code>try:
    some_method()
except Exception, e:
</code>```

How can I get this Exception value (string
representation I mean)?

答:
Use repr() and The difference between using repr and str

Using repr:

```<code>>>> try:
...     print(x)
... except Exception as e:
...     print(repr(e))
...
NameError("name 'x' is not defined")
</code>```

Using str:

```<code>>>> try:
...     print(x)
... except Exception as e:
...     print(str(e))
...
name 'x' is not defined
</code>```

ContentLicense: CC BY-SA 4.0

Title: Getting the exception value in Python

Body:
If I have that code:

try:
    some_method()
except Exception, e:

How can I get this Exception value (string
representation I mean)?

Body:
Use repr() and The difference between using repr and str

Using repr:

>>> try:
...     print(x)
... except Exception as e:
...     print(repr(e))
...
NameError("name 'x' is not defined")

Using str:

>>> try:
...     print(x)
... except Exception as e:
...     print(str(e))
...
name 'x' is not defined


问:
How to add circle on click event in JavaScript?
Could you tell me how to add circle on click event in JavaScript? Actually, I want to achieve that if user click anywhere in div element, it add circle at that position. Currently, it added anywhere not added in correct position. It should be added where user clicks.

This is my code.

```<code>$(function(){
  $('#fx').click(function(e){
    var circle=$('<div class="circle"></div>');
    circle.css('top',e.pageX);
    circle.css('left',e.pageX);
    $('#fx').append(circle);
  });
});
</code>```

答:
If you want the circle to be positionned EXACTLY were the user clicks...

You have to know that pageX and pageY doesn't give you the position of the "tip" of the mouse arrow... But the center of the mouse icon displayed.

So, ""usual icons" dimentions are 20px x 20px.

I have updated your Plunker.

I have added a "dot" to show the exact position where a user expects it to be the center, which is the tip of the arrow.

I made the circle much bigger to be sure about the middle.

See by yourself on this forked and updated Plunker.

Code is:

```<code>$(function(){
  $('#fx').click(function(e){

    var width = 300;        // Width of the element has to be hard coded here;
    var radius = width/2;
    console.log(radius);    // Since element is a circle, the radius is enought to set position.

    var mouseTip = 10;      // But mouse arrow tip has to be taken in account.

    var circle=$('<div class="circle"></div>');
      circle.css('top',e.pageY-radius-mouseTip);
      circle.css('left',e.pageX-radius-mouseTip);
      $('#fx').append(circle);

    var dot=$('<div class="dot"></div>');       // This is only intended to show where user REALLY wants to clic
                                                // and the FACT that there is a correction to apply.
      dot.css('top',e.pageY-mouseTip);
      dot.css('left',e.pageX-mouseTip);
      $('#fx').append(dot);
  });
});
</code>```

So this is great for the "arrow" default cursor, it will need another mouse correction value if you use the "pointer" icon.

Body:
Could you tell me how to add circle on click event in JavaScript? Actually, I want to achieve that if user click anywhere in div element, it add circle at that position. Currently, it added anywhere not added in correct position. It should be added where user clicks.

This is my code.

$(function(){
  $('#fx').click(function(e){
    var circle=$('

');
    circle.css('top',e.pageX);
    circle.css('left',e.pageX);
    $('#fx').append(circle);
  });
});

Body:
If you want the circle to be positionned EXACTLY were the user clicks...

You have to know that pageX and pageY doesn't give you the position of the "tip" of the mouse arrow... But the center of the mouse icon displayed.

So, ""usual icons" dimentions are 20px x 20px.

I have updated your Plunker.

I have added a "dot" to show the exact position where a user expects it to be the center, which is the tip of the arrow.

I made the circle much bigger to be sure about the middle.

See by yourself on this forked and updated Plunker.

Code is:

$(function(){
  $('#fx').click(function(e){

    var width = 300;        // Width of the element has to be hard coded here;
    var radius = width/2;
    console.log(radius);    // Since element is a circle, the radius is enought to set position.

    var mouseTip = 10;      // But mouse arrow tip has to be taken in account.

    var circle=$('<div class="circle"></div>');
      circle.css('top',e.pageY-radius-mouseTip);
      circle.css('left',e.pageX-radius-mouseTip);
      $('#fx').append(circle);

    var dot=$('<div class="dot"></div>');       // This is only intended to show where user REALLY wants to clic
                                                // and the FACT that there is a correction to apply.
      dot.css('top',e.pageY-mouseTip);
      dot.css('left',e.pageX-mouseTip);
      $('#fx').append(dot);
  });
});

So this is great for the "arrow" default cursor, it will need another mouse correction value if you use the "pointer" icon.


问:
How to select a specific  with the same class names?
I am attempting to extract some data from this block of HTML.

```<code><div class="group-capitalization-content field-group-html-element">
    <h2><span>Capitalization</span></h2>
    <div  class="item">
        <div class="label-inline">Issued & Outstanding: </div>
        <span class="number">242906121</span>
    </div >
    <div class="item">
        <div class="label-inline">Reserved for Issuance: </div>
        <span  class="number">51423534</span >
    </div>
</div>
</code>```

I'm using an npm module called cheerio to scrape data from HTML. Thus I have the following code to try and get the "numbers".

```<code> var data = $('.group-capitalization-content .item .number').text();
</code>```

Running this code results in: 24290612151423534, which is both results appended together.

How do I select the individual numbers here / separate them?

答:
If you don't know ahead of time how many there will be you can loop through them with an .each

```<code>$('.group-capitalization-content .item .number').each(function() {
    $(this).text(); // Save this to a var or do something with it
});
</code>```

Title: How to select a specific <span> with the same class names?

Body:
I am attempting to extract some data from this block of HTML.

Capitalization

Issued & Outstanding:

        242906121

Reserved for Issuance:

        51423534

I'm using an npm module called cheerio to scrape data from HTML. Thus I have the following code to try and get the "numbers".

 var data = $('.group-capitalization-content .item .number').text();

Running this code results in: 24290612151423534, which is both results appended together.

How do I select the individual numbers here / separate them?

Body:
If you don't know ahead of time how many there will be you can loop through them with an .each

$('.group-capitalization-content .item .number').each(function() {
    $(this).text(); // Save this to a var or do something with it
});


问:
JQuery get checkbox id
I'm trying to get an id of a checkbox.
There are several checkboxes on a page that have ids like: channel_left_restream_ids_42, channel_left_restream_ids_44, etc. I need to handle an event when one of those checked and get an id of the checked.

So for checkbox with code <input type="checkbox" value="42" checked="checked" name="channel[left_restream_ids][]" id="channel_left_restream_ids_42"> and coffescript like this:

```<code>$("input[id*=channel_left_restream_ids]").change (e) =>
  alert($(this).attr("id"))
</code>```

I can't get it work. It says undefined. I've tried a lot of alternatives, none worked. Where am I doing a mistake?

JSFiddle is here

答:
In your jfiddle I gave each checkbox a class name of getId and used this code.

This should get you in the right direction.

```<code>$(".getId").each(function(){
  $(this).on("change", function(){
    var id = $(this).attr("id");
     console.log(id);
  });
});
</code>```

If the checkboxes all have the same name, you can use that too.

Title: JQuery get checkbox id

Body:
I'm trying to get an id of a checkbox.
There are several checkboxes on a page that have ids like: channel_left_restream_ids_42, channel_left_restream_ids_44, etc. I need to handle an event when one of those checked and get an id of the checked.

So for checkbox with code <input type="checkbox" value="42" checked="checked" name="channel[left_restream_ids][]" id="channel_left_restream_ids_42"> and coffescript like this:

$("input[id*=channel_left_restream_ids]").change (e) =>
  alert($(this).attr("id"))

I can't get it work. It says undefined. I've tried a lot of alternatives, none worked. Where am I doing a mistake?

JSFiddle is here

Body:
In your jfiddle I gave each checkbox a class name of getId and used this code.

This should get you in the right direction.

$(".getId").each(function(){
  $(this).on("change", function(){
    var id = $(this).attr("id");
     console.log(id);
  });
});

If the checkboxes all have the same name, you can use that too.


问:
Jspm SFX bundle for Aurelia
Is it possible in theory?
I've tried with jspm 0.16 and 0.17 and jspm build command. The bundle gets produced but loading it fails in aurelia-loader-default with an error

```<code>aurelia-loader-default.js:160 Uncaught (in promise) TypeError: require is not a function
    at DefaultLoader.loadModule (http://localhost:3000/dist/bundle.js:1466:9)
    at DefaultLoader.loadModule (http://localhost:3000/dist/bundle.js:1465:14)
    at http://localhost:3000/dist/bundle.js:554:25DefaultLoader.loadModule @ aurelia-loader-default.js:160DefaultLoader.loadModule @ aurelia-loader-default.js:157(anonymous function) @ aurelia-bootstrapper.js:85
</code>```

答: It is possible. The enhancement which is needed is tracked here</p>

Title: Jspm SFX bundle for Aurelia

Body:
Is it possible in theory?
I've tried with jspm 0.16 and 0.17 and jspm build command. The bundle gets produced but loading it fails in aurelia-loader-default with an error

aurelia-loader-default.js:160 Uncaught (in promise) TypeError: require is not a function
    at DefaultLoader.loadModule (http://localhost:3000/dist/bundle.js:1466:9)
    at DefaultLoader.loadModule (http://localhost:3000/dist/bundle.js:1465:14)
    at http://localhost:3000/dist/bundle.js:554:25DefaultLoader.loadModule @ aurelia-loader-default.js:160DefaultLoader.loadModule @ aurelia-loader-default.js:157(anonymous function) @ aurelia-bootstrapper.js:85


问:
How can I detect if user escapes out of Authentication Required dialog in browser?
How can I detect if user escapes out of Authentication Required dialog in browser?

Is there JS for this cancel / escape key event ?

I don't need to know which user, just to redirect them to a unauthorized page.

答:
I honestly have no experience with this specific popup, but it is part of the Basic Authentication protocol inherent to HTTP. What happens is when the browser requests a protected resource from a web server, the server responds with an unauthorized status code (401) and a header called WWW-Authenticate, and the browser shows this popup on its own. This popup is not related to JavaScript in any way, and as such, we can't detect it using JS.

We can, however, check for the presence of the Authorization header in the client's response on the server, and if the header exists, and is correct, then serve the protected route; otherwise, serve a different route. I don't know if it's possible to check for the header on the page, since it's not loaded yet, but you can definitely have your server make that decision before serving the response.


问:
Solving magic squares in Z3
I'm new to Z3 and as an exercise attempted a magic square solver by adapting an existing sudoku solver (http://lauri.võsandi.com/tub/qaoes/z3.html). I supply no facts (i.e. no specific numbers in specific boxes) other than the sum of all rows, columns and main diagonals are equal and entries are distinct and in the range [1,N*N]. It works fine for squares up to size 4. Any higher though and I give up waiting for a solution.

Is this normal? Or would experienced z3 programmers suggest my implementation has issues as problems of this size should be solvable?

Thanks.

答:
You might have better results by expressing the entry in each cell as a BitVec() variable rather than an Int() variable.

See https://github.com/0vercl0k/z3-playground/blob/master/magic_square_z3.py for an example implementation.  That implementation is able to find a solution for a 5x5 magic square in 1 second, a 6x6 magic square in 13 seconds, and a 7x7 magic square in 24 seconds (on my computer), so it seems to be doing significantly better than your formulation.

Title: Solving magic squares in Z3


问:
Closing All User Applications
I'm making a 'simple' program to close down all active applications on Windows 10 that I have running i.e. Chrome, Outlook, Notepadd++, etc.. After doing a lot of searching I came across this code:

```<code>foreach (Process p in Process.GetProcesses(Environment.MachineName))
{
    if ((p.Id != CurrentProcess.Id && p.MainWindowHandle != IntPtr.Zero))
    {
      p.kill();
    }
}
</code>```

First it asks the process to close nicely with p.CloseMainWindow(), then kills the process if exceptions are returned. I know it's not ideal, but this works for the most part.

When running my program it closes all of my applications and some underlying Windows applications/processes because the screen, taskbar, and desktop go black for a second and refresh.

My problem is that more than half the time I run this program I get a Win32Exception and the program won't finish closing anything left open.

I'm making a guess here that it's because I don't have sufficient permissions to close Windows background processes even running as administrator and that's why I'm getting the exception.

After each kill call, I put my program to sleep for a short amount of time to give the process time to close to avoid calling kill on a terminating process which will also throw the exception. Perhaps it isn't enough time, I'm using 250ms intervals.

TL;DR Is there a way to close everything that I, the user, have opened (or everything in the taskbar) and leave the main Windows processes alone?

答:
In Windows 10 (Maybe 8 has this too, I can't remember), the task manager has a "Processes" tab which splits processes in at least 3 categories, Apps / Background processes / Windows processes. My guess is that you would like to kill the Apps.

It seems that the way this work is by having the task manager check if each process has a top level window. I'm not very familiar with how to do this, but it would seem that Process.MainWindowHandle could be a place to start.

Title: Closing All User Applications

Body:
I'm making a 'simple' program to close down all active applications on Windows 10 that I have running i.e. Chrome, Outlook, Notepadd++, etc.. After doing a lot of searching I came across this code:

foreach (Process p in Process.GetProcesses(Environment.MachineName))
{
    if ((p.Id != CurrentProcess.Id && p.MainWindowHandle != IntPtr.Zero))
    {
      p.kill();
    }
}

First it asks the process to close nicely with p.CloseMainWindow(), then kills the process if exceptions are returned. I know it's not ideal, but this works for the most part.

When running my program it closes all of my applications and some underlying Windows applications/processes because the screen, taskbar, and desktop go black for a second and refresh.

My problem is that more than half the time I run this program I get a Win32Exception and the program won't finish closing anything left open.

I'm making a guess here that it's because I don't have sufficient permissions to close Windows background processes even running as administrator and that's why I'm getting the exception.

After each kill call, I put my program to sleep for a short amount of time to give the process time to close to avoid calling kill on a terminating process which will also throw the exception. Perhaps it isn't enough time, I'm using 250ms intervals.

TL;DR Is there a way to close everything that I, the user, have opened (or everything in the taskbar) and leave the main Windows processes alone?


问:
how to write a function in bash_profile
how can we write a simple regular function which i can put in my bashprofile
which can be used to secure console to any host i want.

but my secure console has to go through a jump host. that is the issue.

```<code>function func_name () {
 ssh jumphostname;
 sc $hostname # from jump host secure console to another host given as input from terminal
}
</code>```

this function only making to login in to jump host but not to secureconsole in to another host from there.

-bash-4.1$func_name host.me.com
should give me console to host.me.com via jumphost

is function for this not possible?
do i have to write a script?

答:
You should not use commands in a test [ ] unless you simulate a variable with $( ) arround the commands. Still not sure SSH will return something to the test. SSH needs the TTY you like connect to, and not the TTY you in at. This will causes problems!

An example without SSH ...

```<code>suleiman@antec:~$ if [ "$(cat ~/test.txt)" ]; then echo "Hello World"; else echo "failed"; fi
Hello World
suleiman@antec:~$ if [ "$(cat /this/file/dont/exsist 2>/dev/null)" ]; then echo "Hello World"; else echo "failed"; fi
failed
</code>```

Addition:

-bash: sc: command not found

This means you have NOT installed the spreadsheet on the host.

This function only making to login in to jump host but not to
  secureconsole in to another host from there.

What you trying to do ?

Do you know what SSH does ?
It opens remote TTYs, or with other words: it opens a remote secure console.

You cant run a script and put somewhere a ssh login in it, and then think all code after that will be in the new console, neither will that happen.

You can run ssh on a console, so you get your own TTY and put some commands in it. Or you use ssh in combination with some commands in a script, like

```<code>ssh user@host echo "Hello World!"
</code>```

You can also pass some variables or text though ssh via

```<code>echo "Hello World!" | ssh user@host cat
</code>```

There isnt much more you can do with it and you shouldn't!

Title: how to write a function in bash_profile

Body:
how can we write a simple regular function which i can put in my bashprofile
which can be used to secure console to any host i want.

but my secure console has to go through a jump host. that is the issue.

function func_name () {
 ssh jumphostname;
 sc $hostname # from jump host secure console to another host given as input from terminal
}

this function only making to login in to jump host but not to secureconsole in to another host from there.

-bash-4.1$func_name host.me.com
should give me console to host.me.com via jumphost

is function for this not possible?
do i have to write a script?

Body:
You should not use commands in a test [ ] unless you simulate a variable with $( ) arround the commands. Still not sure SSH will return something to the test. SSH needs the TTY you like connect to, and not the TTY you in at. This will causes problems!

An example without SSH ...

suleiman@antec:~$ if [ "$(cat ~/test.txt)" ]; then echo "Hello World"; else echo "failed"; fi
Hello World
suleiman@antec:~$ if [ "$(cat /this/file/dont/exsist 2>/dev/null)" ]; then echo "Hello World"; else echo "failed"; fi
failed

Addition:

-bash: sc: command not found

This means you have NOT installed the spreadsheet on the host.

This function only making to login in to jump host but not to
  secureconsole in to another host from there.

What you trying to do ?

Do you know what SSH does ?
It opens remote TTYs, or with other words: it opens a remote secure console.

You cant run a script and put somewhere a ssh login in it, and then think all code after that will be in the new console, neither will that happen.

You can run ssh on a console, so you get your own TTY and put some commands in it. Or you use ssh in combination with some commands in a script, like

ssh user@host echo "Hello World!"

You can also pass some variables or text though ssh via

echo "Hello World!" | ssh user@host cat

There isnt much more you can do with it and you shouldn't!


问:
How to add custom file field to user profile in wordpress?
I've found endless examples online on how to add extra custom fields to user profiles in wordpress. But non of them have shown how to add fields to upload files.

Heres what I got for my extra field:

```<code>add_action( 'show_user_profile', 'extra_user_profile_fields' );
add_action( 'edit_user_profile', 'extra_user_profile_fields' );

function extra_user_profile_fields( $user ) {
?>
    <h3><?php _e("Extra Information", "blank"); ?></h3>
    <table class="form-table">

        <tr>
            <th><label for="my_document"><?php _e("My Document"); ?></label></th>
            <td>
                <input type="file" name="my_document" id="my_document" value="<?php echo esc_attr( get_the_author_meta( 'my_document', $user->ID ) ); ?>" />
            </td>
        </tr>

    </table>

<?php
}
</code>```

Then for the form submit:

```<code>add_action( 'personal_options_update', 'yoursite_save_extra_user_profile_fields' );
add_action( 'edit_user_profile_update', 'yoursite_save_extra_user_profile_fields' );

function yoursite_save_extra_user_profile_fields( $user_id ) {
    $saved = false;

    if ( !current_user_can( 'edit_user', $user_id ) )
        return false;

    if(!empty($_FILES['my_document']['name'])) {

        // Use the WordPress API to upload the file
        $upload = wp_upload_bits($_FILES['my_document']['name'], null, file_get_contents($_FILES['my_document']['tmp_name']));

        if(isset($upload['error']) && $upload['error'] != 0) {
            wp_die('There was an error uploading your file. The error is: ' . $upload['error']);
        } else {
            add_post_meta($user_id, 'my_document', $upload);
            update_post_meta($user_id, 'my_document', $upload);
        } // end if/else

    } // end if

}
</code>```

The document isn't saving, I suspect the form in the edit profile hasn't the tags to upload files. I also don't know how to retrieve the document in the front end once its saved, as to show the user he has the file uploaded.

答:
This works for me:</p>

```<code>add_action( 'show_user_profile', 'extra_user_profile_fields' );
add_action( 'edit_user_profile', 'extra_user_profile_fields' );

function extra_user_profile_fields( $user ) {
?>
    <h3><?php _e("Extra Information", "blank"); ?></h3>
    <table class="form-table">
        <tr>
            <th scope="row">My Document</th>
            <td><input type="file" name="my_document" value="" />
            <?php
                $doc = get_user_meta( $user->ID, 'my_document', true );
                if (!isset($doc['error'])) {
                    $doc = $doc['url'];
                    echo "<img src='$doc' />";
                } else {
                    $doc = $doc['error'];
                    echo $doc;
                }
            ?>
            </td>
        </tr>
    </table>

<?php
}
add_action( 'personal_options_update', 'yoursite_save_extra_user_profile_fields' );
add_action( 'edit_user_profile_update', 'yoursite_save_extra_user_profile_fields' );

function yoursite_save_extra_user_profile_fields( $user_id ) {
    if ( !current_user_can( 'edit_user', $user_id ) )
        return false;
    if( $_FILES['my_document']['error'] === UPLOAD_ERR_OK ) {
        $_POST['action'] = 'wp_handle_upload';
        $upload_overrides = array( 'test_form' => false );
        $upload = wp_handle_upload( $_FILES['my_document'], $upload_overrides );
        update_user_meta( $user_id, 'my_document', $upload );
    }
}
</code>```

Body:
I've found endless examples online on how to add extra custom fields to user profiles in wordpress. But non of them have shown how to add fields to upload files.

Heres what I got for my extra field:

add_action( 'show_user_profile', 'extra_user_profile_fields' );
add_action( 'edit_user_profile', 'extra_user_profile_fields' );

function extra_user_profile_fields( $user ) {
?>

<?php _e("Extra Information", "blank"); ?>

            <?php _e("My Document"); ?>

                <input type="file" name="my_document" id="my_document" value="<?php echo esc_attr( get_the_author_meta( 'my_document', $user->ID ) ); ?>" />

<?php
}

Then for the form submit:

add_action( 'personal_options_update', 'yoursite_save_extra_user_profile_fields' );
add_action( 'edit_user_profile_update', 'yoursite_save_extra_user_profile_fields' );

function yoursite_save_extra_user_profile_fields( $user_id ) {
    $saved = false;

    if ( !current_user_can( 'edit_user', $user_id ) )
        return false;

    if(!empty($_FILES['my_document']['name'])) {

        // Use the WordPress API to upload the file
        $upload = wp_upload_bits($_FILES['my_document']['name'], null, file_get_contents($_FILES['my_document']['tmp_name']));

        if(isset($upload['error']) && $upload['error'] != 0) {
            wp_die('There was an error uploading your file. The error is: ' . $upload['error']);
        } else {
            add_post_meta($user_id, 'my_document', $upload);
            update_post_meta($user_id, 'my_document', $upload);
        } // end if/else

    } // end if

}

The document isn't saving, I suspect the form in the edit profile hasn't the tags to upload files. I also don't know how to retrieve the document in the front end once its saved, as to show the user he has the file uploaded.

Body:
This works for me:

add_action( 'show_user_profile', 'extra_user_profile_fields' );
add_action( 'edit_user_profile', 'extra_user_profile_fields' );

function extra_user_profile_fields( $user ) {
?>
    <h3><?php _e("Extra Information", "blank"); ?></h3>
    <table class="form-table">
        <tr>
            <th scope="row">My Document</th>
            <td><input type="file" name="my_document" value="" />
            <?php
                $doc = get_user_meta( $user->ID, 'my_document', true );
                if (!isset($doc['error'])) {
                    $doc = $doc['url'];
                    echo "<img src='$doc' />";
                } else {
                    $doc = $doc['error'];
                    echo $doc;
                }
            ?>
            </td>
        </tr>
    </table>

<?php
}
add_action( 'personal_options_update', 'yoursite_save_extra_user_profile_fields' );
add_action( 'edit_user_profile_update', 'yoursite_save_extra_user_profile_fields' );

function yoursite_save_extra_user_profile_fields( $user_id ) {
    if ( !current_user_can( 'edit_user', $user_id ) )
        return false;
    if( $_FILES['my_document']['error'] === UPLOAD_ERR_OK ) {
        $_POST['action'] = 'wp_handle_upload';
        $upload_overrides = array( 'test_form' => false );
        $upload = wp_handle_upload( $_FILES['my_document'], $upload_overrides );
        update_user_meta( $user_id, 'my_document', $upload );
    }
}


问:
Desktop App Converter how to pass a period in -PackageName
I have the same problem as the person in this question

Specifying a package identity name with Desktop App Converter

except I can not work out how in the form -PackageName string, It will not work with a period in the string or a number in the front of the string which is my problem, as my package identity contains both?

答:
A period will work in the -PackageName argument. PackageName is used as a fallback for several command line arguments (when not specified). Try something like the following (with your other arguments):

```<code>-PackageName "12103MyTech.CoolestAppEver" -PackageDisplayName "CoolestAppEver" -AppDisplayName "CoolestAppEver" -AppId "CoolestAppEver"
</code>```

This will create an appx with the name '12103MyTech.CoolestAppEver.appx', all of the values in AppxManifest.xml will be properly specified.

Body:
A period will work in the -PackageName argument. PackageName is used as a fallback for several command line arguments (when not specified). Try something like the following (with your other arguments):

-PackageName "12103MyTech.CoolestAppEver" -PackageDisplayName "CoolestAppEver" -AppDisplayName "CoolestAppEver" -AppId "CoolestAppEver"

This will create an appx with the name '12103MyTech.CoolestAppEver.appx', all of the values in AppxManifest.xml will be properly specified.


问:
In R, find whether two files differ
I would like a pure R way to test whether two arbitrary files are different. So, the equivalent to diff -q in Unix, but should work on Windows and without external dependencies.

I'm aware of tools::Rdiff, but it seems to only want to deal with R output files and complains loudly if I feed it something else.

答:
Example solution:
(Using all.equals utility from: https://stat.ethz.ch/R-manual/R-devel/library/base/html/all.equal.html)

```<code>filenameForA <- "my_file_A.txt"
filenameForB <- "my_file_B.txt"
all.equal(readLines(filenameForA), readLines(filenameForB))
</code>```

Note, that

```<code>readLines(filename)
</code>```

reads all the lines from given file specified by filename,
then all.equal can figure out if the files differ or not.

Make sure to read the documentation from above to understand fully.
I've to admit, that if the files are very large, this might not be the best option.

Title: In R, find whether two files differ

Body:
Example solution:
(Using all.equals utility from: https://stat.ethz.ch/R-manual/R-devel/library/base/html/all.equal.html)

filenameForA <- "my_file_A.txt"
filenameForB <- "my_file_B.txt"
all.equal(readLines(filenameForA), readLines(filenameForB))

Note, that

readLines(filename)

reads all the lines from given file specified by filename,
then all.equal can figure out if the files differ or not.

Make sure to read the documentation from above to understand fully.
I've to admit, that if the files are very large, this might not be the best option.


问:
Why another user is required to run hadoop?
I have a question regarding hadoop configuration
why we need to create a user for running hadoop can we not run hadoop on a root user?</p>

答:
This is not hadoop specific, it's a common good practice in IT to have specific users for running daemons ,for security reasons (for example in hadoop, if you run map reduce daemons as root, a malign  user could launch a map reduce job which deletes not only hdfs data, but operating system data), for best control ,etc. Take a look at this:
https://unix.stackexchange.com/questions/29159/why-is-it-recommended-to-create-a-group-and-user-for-some-applications</p>


问:
input text box for url redirect with jquery
I've an input type here which should redirect me to another page on the same site:
/Page1/Search!q= followed by the term(s) I've actually inserted in my input type box.
Any thoughts why the below code doesn't work?
On enter, nothing happens.
In Firefox I go to Tools > Web Developer > Debugger in order to set a breakpoint for debugging but in Debugger my Sources panel shows up empty. I was expecting to see my jquery function definitions there. Any ideas?
Thanks.</p>

```<code><script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>

<input class="myClass" id="q" name="q" type="text" value="" />

<script type="text/javascript">
$('.myClass').keypress(function (e) {
if (e.keyCode === 13) {
sp.myFunction($('.myClass').val());
return false;
}
return true;
});

myFunction: function (term) {
window.location.href = 'Page1/Search?q=' + term;
}

</script>
</code>```

答:
Try this code:</p>

```<code>$('.myClass').keypress(function (e) {
if (e.keyCode === 13) {
   myFunction($('.myClass').val());
   return false;
}
return true;
});

myFunction = function (term) {
window.location.href = 'Page1/Search?q=' + term;
}
</code>```

Body:
I've an input type here which should redirect me to another page on the same site:
/Page1/Search!q= followed by the term(s) I've actually inserted in my input type box.
Any thoughts why the below code doesn't work?
On enter, nothing happens.
In Firefox I go to Tools > Web Developer > Debugger in order to set a breakpoint for debugging but in Debugger my Sources panel shows up empty. I was expecting to see my jquery function definitions there. Any ideas?
Thanks.

<input class="myClass" id="q" name="q" type="text" value="" />

Body:
Try this code:

$('.myClass').keypress(function (e) {
if (e.keyCode === 13) {
   myFunction($('.myClass').val());
   return false;
}
return true;
});

myFunction = function (term) {
window.location.href = 'Page1/Search?q=' + term;
}


问:
MS Access Import Error Table
When importing data into an MS Access Database, sometimes there are errors in the formatting of the data source.

As I recall, when this happens, MS Access will put the offending row into a separate table called <something>.

What is this table's proper name?

答:
Import Errors is the name of the table, followed by an integer if you have had previous failed imports. (Access 2003: http://office.microsoft.com/en-us/access-help/import-or-link-data-and-objects-HP005187610.aspx?CTT=1)

Access will create a table called Paste Errors for pasted data.

I notice that in Access 2010, the file is called <name of import file>_ImportErrors, for example, importing try.txt would give try_ImportErrors:

```<code>Error                               Field   Row
Null value in an auto-number field     id     2
</code>```

ContentLicense: CC BY-SA 2.5

Title: MS Access Import Error Table

Body:
Import Errors is the name of the table, followed by an integer if you have had previous failed imports. (Access 2003: http://office.microsoft.com/en-us/access-help/import-or-link-data-and-objects-HP005187610.aspx?CTT=1)

Access will create a table called Paste Errors for pasted data.

I notice that in Access 2010, the file is called <name of import file>_ImportErrors, for example, importing try.txt would give try_ImportErrors:

Error                               Field   Row
Null value in an auto-number field     id     2


问:
Was javascript argument default?
Is there a way to tell the difference between this

```<code>((a=true)=>{return a})(true)
</code>```

And this?

```<code>((a=true)=>{return a})()
</code>```

They both return true - how can I tell whether that true is coming from the default value of the argument, or from the value passed in to that parameter?

Is it possible from outside the function?

Is it possible from inside the function?

答:
You cannot tell the difference in your specific examples, and there is no way to tell from outside the function definitely. The only exposed info is what you explicitly expose with your return value, which is just the boolean.

From inside the function, you can tell the difference if you rewrite your logic. You could change your function from

```<code>((a=true)=>{
  return a;
})(true)
</code>```

to

```<code>((...args)=>{
  const a = args[0] === undefined ? true : args[0];

  if (args.length > 0) console.log("passed arg");
  else console.log("passed no arg");

  return a;
})(true)
</code>```

Note that you cannot combine this with default value syntax, so if you'd have to rewrite it to use rest syntax.

Alternatively, you could use a normal function instead of an arrow, and use arguments, however that is also a potentially difficult change if your real-world case relies on the arrow-function's lexical this. e.g.

```<code>(function(a = true)=>{
  if (arguments.length > 0) console.log("passed arg");
  else console.log("passed no arg");

  return a;
})(true)
</code>```

Title: Was javascript argument default?

Body:
Is there a way to tell the difference between this

((a=true)=>{return a})(true)

And this?

((a=true)=>{return a})()

They both return true - how can I tell whether that true is coming from the default value of the argument, or from the value passed in to that parameter?

Is it possible from outside the function?

Is it possible from inside the function?

Body:
You cannot tell the difference in your specific examples, and there is no way to tell from outside the function definitely. The only exposed info is what you explicitly expose with your return value, which is just the boolean.

From inside the function, you can tell the difference if you rewrite your logic. You could change your function from

((a=true)=>{
  return a;
})(true)

to

((...args)=>{
  const a = args[0] === undefined ? true : args[0];

  if (args.length > 0) console.log("passed arg");
  else console.log("passed no arg");

  return a;
})(true)

Note that you cannot combine this with default value syntax, so if you'd have to rewrite it to use rest syntax.

Alternatively, you could use a normal function instead of an arrow, and use arguments, however that is also a potentially difficult change if your real-world case relies on the arrow-function's lexical this. e.g.

(function(a = true)=>{
  if (arguments.length > 0) console.log("passed arg");
  else console.log("passed no arg");

  return a;
})(true)


答:
Here is the correct code.

```<code><script src="https://code.jquery.com/jquery-3.2.1.js"></script>

<input class="myClass" id="q" name="q" type="text" value="">

<script type="text/javascript">
$('.myClass').keypress(function (e) {
    if (e.keyCode === 13) {
        myFunction( $('.myClass').val() );
        return false;
    }
    return true;
});

myFunction = function (term) {
    window.location.href = 'Page1/Search?q=' + term;
}
</script>
</code>```

You were missing jQuery library. jquery-ui.js is something else.
Secondly if you are viewing your files locally without any web server you need to add Protocol http or https in the src URL. The third mistake in your code was here myFunction: function (term) it should be myFunction = function (term)

Title: input text box for url redirect with jquery

Body:
Here is the correct code.

<script src="https://code.jquery.com/jquery-3.2.1.js"></script>

<input class="myClass" id="q" name="q" type="text" value="">

<script type="text/javascript">
$('.myClass').keypress(function (e) {
    if (e.keyCode === 13) {
        myFunction( $('.myClass').val() );
        return false;
    }
    return true;
});

myFunction = function (term) {
    window.location.href = 'Page1/Search?q=' + term;
}
</script>

You were missing jQuery library. jquery-ui.js is something else.
Secondly if you are viewing your files locally without any web server you need to add Protocol http or https in the src URL. The third mistake in your code was here myFunction: function (term) it should be myFunction = function (term)


问:
Why wait, notify and notifyAll are methods in Object class not like Cloneable
Recently, I was asked in interview why wait, notify, and notifyAll are used.  I explained them.

After that they asked me to assume an application is always single threaded.  Is it really required?  My answer was no.

Then, they asked why is design like wait, notify, and notifyAll are methods on the Object class.  Why doesn't Java have an interface and these methods are in that interface and which ever class wants to implement it can use it.  So, I was kind of stuck and unable to think over this design.  Can anyone please sow light over this?

答:
It was a design goal from the start that Java programs would be multithreaded. Remember the plan was for Java to make embedded programming less intimidating, the whole serverside web application thing    (leading to the commoditization of Sun's core business) was an accident.

Since the goal was to enable creating embedded applications that would talk to other devices, it had to be multithreaded in order to be network-friendly and event-driven. But writing efficient multithreaded servers wasn't high on the list for java.

Java didn't have ReentrantLock or nonblocking i/o for a long time. Initially the main data structures available were Vector,  Hashtable, and StringBuffer (all of which had synchronized on all public methods). From that choice it seems like the goal was good-enough, as opposed to being as efficient as possible. Later on it was clear Java needed to be more efficient for the use case of server applications and 1.2 introduced equivalents of Vector and Hashtable that were unsynchronized. This seemed like an afterthought, a course adjustment made once it was apparent Java had a new role it wasn't previously designed for.

If Java had stayed in the niche it was created for then possibly intrinsic locks might have been adequate. It seems the initial plan was for intrinsic locks only, so that the lock might as well be wired into the Object.


问:
Imgur gifv file doesn't load as expected using video tag
```<code><video width="320" height="240" controls>
<source src="http://i.imgur.com/91S22q6.gifv" type="video/webm">
Your browser does not support the video tag.
</video>
</code>```

This doesn't seem to load the video. I assume the .gifv is messing it up somehow when it needs to use .webm. When I change it to .webm, it still doesn't load. Is there any way to embed a .gifv?

答:
I recently had an issue with embedding a gifv using the webm extension.  I had success replacing the "webm" extension with "mp4".  This was only for a recently uploaded file, an older file did not have any issue.

```<code><video preload="auto" autoplay="autoplay" loop="loop" style="width: 200px; height: 200px;">
    <source src="//i.imgur.com/91S22q6.mp4" type="video/mp4"></source>
</video>
</code>```

This imgur support page seems to indicate using mp4 rather than webm: Sharing Posts, GIFs, GIFvs, and Images

Body:
<video width="320" height="240" controls>
<source src="http://i.imgur.com/91S22q6.gifv" type="video/webm">
Your browser does not support the video tag.
</video>

This doesn't seem to load the video. I assume the .gifv is messing it up somehow when it needs to use .webm. When I change it to .webm, it still doesn't load. Is there any way to embed a .gifv?

Body:
I recently had an issue with embedding a gifv using the webm extension.  I had success replacing the "webm" extension with "mp4".  This was only for a recently uploaded file, an older file did not have any issue.

<video preload="auto" autoplay="autoplay" loop="loop" style="width: 200px; height: 200px;">
    <source src="//i.imgur.com/91S22q6.mp4" type="video/mp4"></source>
</video>

This imgur support page seems to indicate using mp4 rather than webm: Sharing Posts, GIFs, GIFvs, and Images


问:
CIImage extent in pixels or points?
I'm working with a CIImage, and while I understand it's not a linear image, it does hold some data.

My question is whether or not a CIImage's extent property returns pixels or points? According to the documentation, which says very little, it's working space coordinates. Does this mean there's no way to get the pixels / points from a CIImage and I must convert to a UIImage to use the .size property to get the points?

I have a UIImage with a certain size, and when I create a CIImage using the UIImage, the extent is shown in points. But if I run a CIImage through a CIFilter that scales it, I sometimes get the extent returned in pixel values.

答:
I suggest you think of them as points. There is no scale and no screen (a CIImage is not something that is drawn), so there are no pixels. </p>

<p>A UIImage backed by a CGImage is the basis for drawing, and in addition to the CGImage it has a scale; together with the screen resolution, that gives us our translation from points to pixels. </p>

Title: CIImage extent in pixels or points?

Body:
I suggest you think of them as points. There is no scale and no screen (a CIImage is not something that is drawn), so there are no pixels.

A UIImage backed by a CGImage is the basis for drawing, and in addition to the CGImage it has a scale; together with the screen resolution, that gives us our translation from points to pixels.


问:
converting outputStream to byte array
How can I get the bytes of an outputStream, or how can I convert an outputStream to a byte array?</p>

答:
From a theoretical perspective (i.e., irrespective of whether it makes sense in practice as a use case), this is an interesting question that essentially requires the implementation of a method like

```<code>public abstract byte[] convert(OutputStream out);
</code>```

The Java OutputStream class, as its name implies, only supports an overridden write() method for I/O, and that write() method gets either an integer (representing 1 byte) or a byte array, the contents of which it sends to an output (e.g., a file).

For example, the following code saves the bytes already present in the data array, to the output.txt file:

```<code>byte[] data = ... // Get some data
OutputStream fos = new FileOutputStream("path/to/output.txt");
fos.write(data);
</code>```

In order to get all the data that a given OutputStream will be outputting and put it into a byte array (i.e., into a byte[] object), the class from which the corresponding OutputStream object was instantiated, should keep storing all the bytes processed via its write() methods and provide a special method, such as toByteArray(), that would return them all, upon invocation.

This is exactly what the ByteArrayOutputStream class does, making the convert() method trivial (and unnecessary):

```<code>public byte[] convert(ByteArrayOutputStream out) {
  return out.toByteArray();
}
</code>```

For any other type of OutputStream, not inherently supporting a similar conversion to a byte[] object, there is no way to make the conversion, before the OutputStream is drained, i.e. before the desired calls to its write() methods have been completed.

If such an assumption (of the writes to have been completed) can be made, and if the original OutputStream object can be replaced, then one option is to wrap it inside a delegate class that would essentially "grab" the bytes that would be supplied via its write() methods. For example:

```<code>public class DrainableOutputStream extends FilterOutputStream {
  private final ByteArrayOutputStream buffer;
  public DrainableOutputStream(OutputStream out) {
    super(out);
    this.buffer = new ByteArrayOutputStream();
  }
  @Override
  public void write(byte b[]) throws IOException {
    this.buffer.write(b);
    super.write(b);
  }
  @Override
  public void write(byte b[], int off, int len) throws IOException {
    this.buffer.write(b, off, len);
    super.write(b, off, len);
  }
  @Override
  public void write(int b) throws IOException {
    this.buffer.write(b);
    super.write(b);
  }
  public byte[] toByteArray() {
    return this.buffer.toByteArray();
  }
}
</code>```

The calls to the write() methods of the internal "buffer" (ByteArrayOutputStream) precede the calls to the original stream (which, in turn, can be accessed via super, or even via this.out, since the corresponding parameter of the FilterOutputStream is protected). This makes sure that the bytes will be buffered, even if there is an exception while writing to the original stream.

To reduce the overhead, the calls to super in the above class can be omitted - e.g., if only the "conversion" to a byte array is desired. Even the ByteArrayOutputStream or OutputStream classes can be used as parent classes, with a bit more work and some assumptions (e.g., about the reset() method).

In any case, enough memory has to be available for the draining to take place and for the toByteArray() method to work.

Title: converting outputStream to byte array

Body:
From a theoretical perspective (i.e., irrespective of whether it makes sense in practice as a use case), this is an interesting question that essentially requires the implementation of a method like

public abstract byte[] convert(OutputStream out);

The Java OutputStream class, as its name implies, only supports an overridden write() method for I/O, and that write() method gets either an integer (representing 1 byte) or a byte array, the contents of which it sends to an output (e.g., a file).

For example, the following code saves the bytes already present in the data array, to the output.txt file:

byte[] data = ... // Get some data
OutputStream fos = new FileOutputStream("path/to/output.txt");
fos.write(data);

In order to get all the data that a given OutputStream will be outputting and put it into a byte array (i.e., into a byte[] object), the class from which the corresponding OutputStream object was instantiated, should keep storing all the bytes processed via its write() methods and provide a special method, such as toByteArray(), that would return them all, upon invocation.

This is exactly what the ByteArrayOutputStream class does, making the convert() method trivial (and unnecessary):

public byte[] convert(ByteArrayOutputStream out) {
  return out.toByteArray();
}

For any other type of OutputStream, not inherently supporting a similar conversion to a byte[] object, there is no way to make the conversion, before the OutputStream is drained, i.e. before the desired calls to its write() methods have been completed.

If such an assumption (of the writes to have been completed) can be made, and if the original OutputStream object can be replaced, then one option is to wrap it inside a delegate class that would essentially "grab" the bytes that would be supplied via its write() methods. For example:

public class DrainableOutputStream extends FilterOutputStream {
  private final ByteArrayOutputStream buffer;
  public DrainableOutputStream(OutputStream out) {
    super(out);
    this.buffer = new ByteArrayOutputStream();
  }
  @Override
  public void write(byte b[]) throws IOException {
    this.buffer.write(b);
    super.write(b);
  }
  @Override
  public void write(byte b[], int off, int len) throws IOException {
    this.buffer.write(b, off, len);
    super.write(b, off, len);
  }
  @Override
  public void write(int b) throws IOException {
    this.buffer.write(b);
    super.write(b);
  }
  public byte[] toByteArray() {
    return this.buffer.toByteArray();
  }
}

The calls to the write() methods of the internal "buffer" (ByteArrayOutputStream) precede the calls to the original stream (which, in turn, can be accessed via super, or even via this.out, since the corresponding parameter of the FilterOutputStream is protected). This makes sure that the bytes will be buffered, even if there is an exception while writing to the original stream.

To reduce the overhead, the calls to super in the above class can be omitted - e.g., if only the "conversion" to a byte array is desired. Even the ByteArrayOutputStream or OutputStream classes can be used as parent classes, with a bit more work and some assumptions (e.g., about the reset() method).

In any case, enough memory has to be available for the draining to take place and for the toByteArray() method to work.


问:
Modifying state with promises

Why do my promises not actually update the state in Redux?

I'm using redux-promise-middleware. When I make a call to my API, it goes through the promise steps of _PENDING and _FULFILLED, but the state is never updated to reflect the changes.

How do I do this properly, so that I actually get my data.

Here's a picture of my state:

As you can see, isFetched does not become true after the promise is fulfilled, and data is never loading the returned response data into itself.

This is my API helper:

```<code>class UserAPI {

     ...

     async testPhone(user) {
         await axios.post(this.testPhonePath, {
             phone: user.phone
         })
         .then(function(response) {
             return response.data
         })
         .catch(function(error) {
             return error.response.data
         })
     }
}
</code>```

My action:

```<code>import { UserAPI } from '../../constants/api'

const userAPI = new UserAPI()

export const TEST_USER_PHONE = 'TEST_USER_PHONE'

export const testUserPhone = (user) => ({
    type: TEST_USER_PHONE,
    payload: userAPI.testPhone(user)
})
</code>```

And my reducer:

import {
    TEST_USER_PHONE
} from './actions'

const INITIAL_STATE = {
    testedByPhone: {
        data: [],
        isFetched: false,
        error: {
            on: false,
            message: null
        }
    }
}

export default (state = INITIAL_STATE, action) => {
    switch(action.type) {
        case '${TEST_USER_PHONE}_PENDING':
            return INITIAL_STATE
        case '${TEST_USER_PHONE}_FULFILLED':
            return {
                testedByPhone: {
                    data: action.payload,
                    isFetched: true,
                    error: {
                        on: false,
                        message: null
                    }
                }
            }
        case '${TEST_USER_PHONE}_REJECTED':
            return {
                testedByPhone: {
                    data: [],
                    isFetched: true,
                    error: {
                        on: true,
                        message: action.payload
                    }
                }
            }
        default:
            return state
    }
}```
</div>
</div>
</p>

<hr>

<p>Here's my Store</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { createStore, applyMiddleware, compose } from 'redux'
import promiseMiddleware from 'redux-promise-middleware'

import reducers from './reducers'

const middleware = [
    promiseMiddleware()
]

if (__DEV__) {
    const logger = require('redux-logger')

    middleware.push(logger())
}

const enhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose

export default createStore(
    reducers,
    undefined,
    enhancers(applyMiddleware(...middleware))
)</code>```

答:
The reason it isn't working, it is that you use a standard string instead of JS templates.
Replace:

```<code>'${TEST_USER_PHONE}_REJECTED'
</code>```

With:

```<code>`${TEST_USER_PHONE}_REJECTED`
</code>```

Title: Modifying state with promises

Body:
Why do my promises not actually update the state in Redux?

I'm using redux-promise-middleware. When I make a call to my API, it goes through the promise steps of _PENDING and _FULFILLED, but the state is never updated to reflect the changes.

How do I do this properly, so that I actually get my data.

Here's a picture of my state:

As you can see, isFetched does not become true after the promise is fulfilled, and data is never loading the returned response data into itself.

This is my API helper:

class UserAPI {

     ...

     async testPhone(user) {
         await axios.post(this.testPhonePath, {
             phone: user.phone
         })
         .then(function(response) {
             return response.data
         })
         .catch(function(error) {
             return error.response.data
         })
     }
}

My action:

import { UserAPI } from '../../constants/api'

const userAPI = new UserAPI()

export const TEST_USER_PHONE = 'TEST_USER_PHONE'

export const testUserPhone = (user) => ({
    type: TEST_USER_PHONE,
    payload: userAPI.testPhone(user)
})

And my reducer:

import {
    TEST_USER_PHONE
} from './actions'

const INITIAL_STATE = {
    testedByPhone: {
        data: [],
        isFetched: false,
        error: {
            on: false,
            message: null
        }
    }
}

export default (state = INITIAL_STATE, action) => {
    switch(action.type) {
        case '${TEST_USER_PHONE}_PENDING':
            return INITIAL_STATE
        case '${TEST_USER_PHONE}_FULFILLED':
            return {
                testedByPhone: {
                    data: action.payload,
                    isFetched: true,
                    error: {
                        on: false,
                        message: null
                    }
                }
            }
        case '${TEST_USER_PHONE}_REJECTED':
            return {
                testedByPhone: {
                    data: [],
                    isFetched: true,
                    error: {
                        on: true,
                        message: action.payload
                    }
                }
            }
        default:
            return state
    }
}

Here's my Store

import { createStore, applyMiddleware, compose } from 'redux'
import promiseMiddleware from 'redux-promise-middleware'

import reducers from './reducers'

const middleware = [
    promiseMiddleware()
]

if (__DEV__) {
    const logger = require('redux-logger')

    middleware.push(logger())
}

const enhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose

export default createStore(
    reducers,
    undefined,
    enhancers(applyMiddleware(...middleware))
)

Body:
The reason it isn't working, it is that you use a standard string instead of JS templates.
Replace:

'${TEST_USER_PHONE}_REJECTED'

With:

`${TEST_USER_PHONE}_REJECTED`


问:
How to select a specific  with the same class names?
I am attempting to extract some data from this block of HTML.

```<code><div class="group-capitalization-content field-group-html-element">
    <h2><span>Capitalization</span></h2>
    <div  class="item">
        <div class="label-inline">Issued & Outstanding: </div>
        <span class="number">242906121</span>
    </div >
    <div class="item">
        <div class="label-inline">Reserved for Issuance: </div>
        <span  class="number">51423534</span >
    </div>
</div>
</code>```

I'm using an npm module called cheerio to scrape data from HTML. Thus I have the following code to try and get the "numbers".

```<code> var data = $('.group-capitalization-content .item .number').text();
</code>```

Running this code results in: 24290612151423534, which is both results appended together.

How do I select the individual numbers here / separate them?

答:
i usually get all the dom elements and then loop over them to do my necessary functions. here is a working fiddle. https://jsfiddle.net/bbmtk7tm/</p>

```<code>var data = $('.group-capitalization-content .item .number');
for(var i=0; i<data.length;i++)
{
console.log(data[i].innerHTML);
}
</code>```

Body:
I am attempting to extract some data from this block of HTML.

Capitalization

Issued & Outstanding:

        242906121

Reserved for Issuance:

        51423534

I'm using an npm module called cheerio to scrape data from HTML. Thus I have the following code to try and get the "numbers".

 var data = $('.group-capitalization-content .item .number').text();

Running this code results in: 24290612151423534, which is both results appended together.

How do I select the individual numbers here / separate them?

Body:
i usually get all the dom elements and then loop over them to do my necessary functions. here is a working fiddle. https://jsfiddle.net/bbmtk7tm/

var data = $('.group-capitalization-content .item .number');
for(var i=0; i<data.length;i++)
{
console.log(data[i].innerHTML);
}


问:
Connecting to existing Heroku Postgres DB for Sinatra app
I am using Salesforce for my CRM, but need to query data (multiple records, so no Zapier) for a Heroku based Sinatra app. Heroku provides a service that replicates Salesforce objects to Postgres tables regularly which gets my data out of Salesforce.

I've coded a Sinatra app before and hosted it on Heroku so I'm a bit familiar with the process of setting up a dev db locally then pushing it to production via the many tutorials. However, i'm running into an issue finding any information that will allow me to connect to the existing production Postgres DB that already is populated with the data I need while having no need to create and connect to a local dev db.

Heroku provides me with the following

How and where to I plug in these various credentials securely so my following files have the right information to connect to tables Venue__c and Spaces__c?

app.rb

/config

- database.yml

- environments.rb

答:
Heroku publishes your database credentials to you through a URL in an environment variable. You should be able to access it through ENV.fetch("DATABASE_URL"). Depending on your ORM you will use different ways to connect to your database, e.g. Sequel is able to use this value directly as a parameter to Sequel.connect(ENV.fetch("DATABASE_URL")).

As you seem to use ActiveRecord you could be using ActiveRecord::Base.establish_connection(...) as suggested in this post which also exemplifies how to parse the URL (which might not be necessary anymore). This does not translate directly to a database.yml, but since you do not plan to use Rails you will have to provide your own version of environment.rb or some such and it should be easy enough to do in that place.


答:
Although not ideal in every way, one solution might be:</p>

```<code>(a=undefined) => {
  let is_default = false;
  if (a === undefined) {
    is_default = true;
    a = true;
  }

  return a
}
</code>```

Title: Was javascript argument default?

Body:
Although not ideal in every way, one solution might be:

(a=undefined) => {
  let is_default = false;
  if (a === undefined) {
    is_default = true;
    a = true;
  }

  return a
}


问:
Stop a textarea element leaving its parent?
I have the following code:

```<code><html>
    <body style="background-color:#800000;">
        <div style="background-color:#000;margin:0 auto;height:800px;width:800px;">
            <textarea style="background-color:#666666;"></textarea>
        </div>
    </body>
</html>
</code>```

As you can see, it has a dark red background, a black div and a grey textarea element. When I resize the textarea, the following happens: https://i.imgur.com/sfwTtd5.gifv. Even though the textarea is clearly inside the div (it's parent), it is still leaving it. How can I make it so the textarea cannot have a bigger width or height than its parent?

答:
Set a max-widthand a max-height.

            <textarea style="background-color:#666666;max-width:100%;max-height:100%;"></textarea>

```

Body:
I have the following code:

            <textarea style="background-color:#666666;"></textarea>

As you can see, it has a dark red background, a black div and a grey textarea element. When I resize the textarea, the following happens: https://i.imgur.com/sfwTtd5.gifv. Even though the textarea is clearly inside the div (it's parent), it is still leaving it. How can I make it so the textarea cannot have a bigger width or height than its parent?

Body:
Set a max-widthand a max-height.

<html>
    <body style="background-color:#800000;">
        <div style="background-color:#000;margin:0 auto;height:300px;width:300px;">
            <textarea style="background-color:#666666;max-width:100%;max-height:100%;"></textarea>
        </div>
    </body>
</html>


问:
Angular 2+ Observable and GroupBy
I have a json file that includes members (columns: name, lastname, section). I can read it like that and use it in *ngFor:

```<code> members: Observable<Member[]>;

 constructor(private _memberService: MemberService) { }

 ngOnInit() {
     this.members = this._memberService.getMembers();
 }
</code>```

Now i want to use a chart. But i can't figure out how i can reach and group by an observable. For example i want to group members by sections and use that values in chart. Any help?

Edit:

My Service:

```<code>  getMembers(){
    return this._http.get(URL_MEMBERS)
    .map((response: Response) => response.json());
  }
</code>```

My Class:

```<code>export class Member {
  section: number;
  number: number;
  firstName: string;
  lastName: string;
  status: string;
  yearOfSep: number;
  yearBook: number;
  class: string;
  lastPosition: string;
  city: string;
  info: string;
}
</code>```

What chart is expecting:

```<code>  public pieChartLabels: string[] = ['X', 'Y', 'Z'];
  public pieChartData: number[] = [300, 500, 100];
  public pieChartType: string = 'pie';
</code>```

答:
I can understand you're confused about Observables, but your question is somewhat heading in the wrong direction.

Your member property on your class is an Observable of Member arrays, right (Observable)? I'm pretty sure whatever charting library you're using doesn't expect to deal with Observables, but rather arrays (and objects and nested arrays etc).

So, in your case, your first port of call is to get an instance of your Member array out of your observable. Once you have that normal, everyday Javascript array, you then use normal javascript to massage that array into the format that your charting library uses.

So, at the point where you need to pass your data to your chart,

```<code> let chartData;
 this.members.subscribe(memberArray => {
   chartData = this.massageMemberArrayIntoChartDataFormat(memberData);
 });
</code>```

where you have to implement that logic to take your array of Members and convert it to whatever format your chart consumes. (I'm being ridiculous with the method name, but hopefully you get my point).

If you're having trouble figuring out how to do that mapping, you can provide samples of what your member array and the expected chart data looks like and you can probably get help with that mapping, but this really isn't a question about Observables per se.

EDIT:

No clue about what you want on your chart, but the expected data is pretty straight forward.

Let's say you want a chart of every person's full name and section:

You already have a Members[] with all your data. Your labels and chart data are also arrays so it's pretty straightforward to do something like this within your subscribe function above:

```<code>this.members.subscribe(memberArray => {

 // map the member objects in my array to a combined firstname and lastname string
 pieChartLabels = memberArray.map(m => m.firstName + ' ' + m.lastName);

 // map the member objects to their section numbers
 pieChartData = memberArray.map(m => m.section);
});
</code>```

then pass those pieChartLabels and pieChartData variables as properties to your chart object.

Title: Angular 2+ Observable and GroupBy

Body:
I have a json file that includes members (columns: name, lastname, section). I can read it like that and use it in *ngFor:

 members: Observable<Member[]>;

 constructor(private _memberService: MemberService) { }

 ngOnInit() {
     this.members = this._memberService.getMembers();
 }

Now i want to use a chart. But i can't figure out how i can reach and group by an observable. For example i want to group members by sections and use that values in chart. Any help?

Edit:

My Service:

  getMembers(){
    return this._http.get(URL_MEMBERS)
    .map((response: Response) => response.json());
  }

My Class:

export class Member {
  section: number;
  number: number;
  firstName: string;
  lastName: string;
  status: string;
  yearOfSep: number;
  yearBook: number;
  class: string;
  lastPosition: string;
  city: string;
  info: string;
}

What chart is expecting:

  public pieChartLabels: string[] = ['X', 'Y', 'Z'];
  public pieChartData: number[] = [300, 500, 100];
  public pieChartType: string = 'pie';

Body:
I can understand you're confused about Observables, but your question is somewhat heading in the wrong direction.

Your member property on your class is an Observable of Member arrays, right (Observable)? I'm pretty sure whatever charting library you're using doesn't expect to deal with Observables, but rather arrays (and objects and nested arrays etc).

So, in your case, your first port of call is to get an instance of your Member array out of your observable. Once you have that normal, everyday Javascript array, you then use normal javascript to massage that array into the format that your charting library uses.

So, at the point where you need to pass your data to your chart,

 let chartData;
 this.members.subscribe(memberArray => {
   chartData = this.massageMemberArrayIntoChartDataFormat(memberData);
 });

where you have to implement that logic to take your array of Members and convert it to whatever format your chart consumes. (I'm being ridiculous with the method name, but hopefully you get my point).

If you're having trouble figuring out how to do that mapping, you can provide samples of what your member array and the expected chart data looks like and you can probably get help with that mapping, but this really isn't a question about Observables per se.

EDIT:

No clue about what you want on your chart, but the expected data is pretty straight forward.

Let's say you want a chart of every person's full name and section:

You already have a Members[] with all your data. Your labels and chart data are also arrays so it's pretty straightforward to do something like this within your subscribe function above:

this.members.subscribe(memberArray => {

 // map the member objects in my array to a combined firstname and lastname string
 pieChartLabels = memberArray.map(m => m.firstName + ' ' + m.lastName);

 // map the member objects to their section numbers
 pieChartData = memberArray.map(m => m.section);
});

then pass those pieChartLabels and pieChartData variables as properties to your chart object.


问:
Running Product based on another column
I need to create a "running product" column in Excel. However, the running product is based on another column, a "group". Consider the example below.

Here, Column A is my group, and each group has multiple items in it (column B). Column C is what I need a running product on, and Column D is the output column. Cell D2 is 0.2 because it is the first item in group 0. Cell D3 is 0.02 since it is the product of item 0 and item 1 in group 0. This continues until we get to group 1, which is when the running product "resets" and starts applying the running product only to group 1, so on and so forth.

I'd like to do this with an formula, and not VBA if possible.

答:
Put this formula into D2, then copy\fill it down the D column: </p>

```<code>=IF(A2=A1,D1*C2,C2)
</code>```

Title: Running Product based on another column

Body:
Put this formula into D2, then copy\fill it down the D column:

=IF(A2=A1,D1*C2,C2)


问:
bitwise NOT of signed and unsigned integers in C
I was debugging an issue and figured out that the following snippet(sanitized) was the reason for the issue.

```<code>uint64_t testflag = 0;
testflag &= ~(0x08ul); //bug
testflag &= ~(0x08l);  //expected
</code>```

I compared the generated assembly and see this

```<code>  uint64_t testflag = 0;
804851e:    c7 45 d8 00 00 00 00    movl   $0x0,-0x28(%ebp)
8048525:    c7 45 dc 00 00 00 00    movl   $0x0,-0x24(%ebp)
  testflag &= ~(0x08ul);
804852c:    83 65 d8 f7             andl   $0xfffffff7,-0x28(%ebp)
8048530:    83 65 dc 00             andl   $0x0,-0x24(%ebp)
  testflag &= ~(0x08l);
8048534:    83 65 d8 f7             andl   $0xfffffff7,-0x28(%ebp)
8048538:    83 65 dc ff             andl   $0xffffffff,-0x24(%ebp)
</code>```

Why does the NOT operator of unsigned long cause the compiler to AND 0 with the higher bytes instead of ffffffff.

My gcc version is gcc (GCC) 4.9.2 (Red Hat 4.9.2) on a 64bit machine.

答:
Assuming 32-bit unsigned long/long...

```<code>uint64_t testflag;
</code>```

```<code> 0x08ul     --> 00 00 00 08
 ~(0x08ul)  --> FF FF FF F7
some_uint32_t = FF FF FF F7

testflag &= some_uint32_t;
testflag = testflag & some_uint32_t
testflag = testflag & (uint64_t) some_uint32_t
testflag = testflag & (uint64_t) FF FF FF F7  (or 4,294,967,288)
testflag = testflag & 00 00 00 00 FF FF FF F7
</code>```

Converting a 32-bit unsigned to uint64_t is a simply 0 extend.

Now with ~(0x08l)

```<code> 0x08l      --> 00 00 00 08
 ~(0x08l)   --> FF FF FF F7
some_int32_t  = FF FF FF F7

testflag &= some_int32_t;
testflag = testflag & some_int32_t
testflag = testflag & (uint64_t) some_int32_t
testflag = testflag & (uint64_t)  FF FF FF F7 (or - 8)
testflag = testflag & FF FF FF FF FF FF FF F7 (or 18,446,744,073,709,551,608)
</code>```

-8 as a uint64_t is very nearly the maximum value for uint64_t.

With 2's complement, the result is the sign bit of OP's long is extended. @Marc Glisse

Body:
I was debugging an issue and figured out that the following snippet(sanitized) was the reason for the issue.

uint64_t testflag = 0;
testflag &= ~(0x08ul); //bug
testflag &= ~(0x08l);  //expected

I compared the generated assembly and see this

  uint64_t testflag = 0;
804851e:    c7 45 d8 00 00 00 00    movl   $0x0,-0x28(%ebp)
8048525:    c7 45 dc 00 00 00 00    movl   $0x0,-0x24(%ebp)
  testflag &= ~(0x08ul);
804852c:    83 65 d8 f7             andl   $0xfffffff7,-0x28(%ebp)
8048530:    83 65 dc 00             andl   $0x0,-0x24(%ebp)
  testflag &= ~(0x08l);
8048534:    83 65 d8 f7             andl   $0xfffffff7,-0x28(%ebp)
8048538:    83 65 dc ff             andl   $0xffffffff,-0x24(%ebp)

Why does the NOT operator of unsigned long cause the compiler to AND 0 with the higher bytes instead of ffffffff.

My gcc version is gcc (GCC) 4.9.2 (Red Hat 4.9.2) on a 64bit machine.

Body:
Assuming 32-bit unsigned long/long...

uint64_t testflag;

 0x08ul     --> 00 00 00 08
 ~(0x08ul)  --> FF FF FF F7
some_uint32_t = FF FF FF F7

testflag &= some_uint32_t;
testflag = testflag & some_uint32_t
testflag = testflag & (uint64_t) some_uint32_t
testflag = testflag & (uint64_t) FF FF FF F7  (or 4,294,967,288)
testflag = testflag & 00 00 00 00 FF FF FF F7

Converting a 32-bit unsigned to uint64_t is a simply 0 extend.

Now with ~(0x08l)

 0x08l      --> 00 00 00 08
 ~(0x08l)   --> FF FF FF F7
some_int32_t  = FF FF FF F7

testflag &= some_int32_t;
testflag = testflag & some_int32_t
testflag = testflag & (uint64_t) some_int32_t
testflag = testflag & (uint64_t)  FF FF FF F7 (or - 8)
testflag = testflag & FF FF FF FF FF FF FF F7 (or 18,446,744,073,709,551,608)

-8 as a uint64_t is very nearly the maximum value for uint64_t.

With 2's complement, the result is the sign bit of OP's long is extended. @Marc Glisse


问:
C# 7 tuples and lambdas
With new c# 7 tuple syntax, is it possible to specify a lambda with a tuple as parameter and use unpacked values inside the lambda?

Example:

```<code>var list = new List<(int,int)>();
</code>```

normal way to use a tuple in lambda:

```<code>list.Select(value => value.Item1*2 + value.Item2/2);
</code>```

i expected some new sugar to avoid .Item1 .Item2, like:

```<code>list.Select((x,y) => x*2 + y/2);
</code>```

The last line does not work because it is treated as two parameters for lambda. I am not sure if there is a way to do it actually.

EDIT:

I tried double parentesis in lambda definition and it didn't work: ((x,y)) => ..., and maybe it was stupid to try, but double parenthesis actually work here:

```<code>list.Add((1,2));
</code>```

Also, my question is not quite about avoiding ugly default names .Item .Item2, it is about actual unpacking a tuple in lambda (and maybe why it's not implemented or not possible). If you came here for a solution to default names, read Sergey Berezovskiy's answer.

EDIT 2:

Just thought of a more general use case: is it possible (or why not) to "deconstruct" tuple passed to a method? Like this:

```<code>void Foo((int,int)(x,y)) { x+y; }
</code>```

Instead of this:

```<code>void Foo((int x,int y) value) { value.x+value.y }
</code>```

答:
You should specify names of tuple properties (well, ValueTuple have fields) otherwise default names will be used, as you have seen:

```<code>var list = new List<(int x, int y)>();
</code>```

Now tuple have nicely named fields which you can use

```<code>list.Select(t => t.x * 2 + t.y / 2)
</code>```

Don't forget to add System.ValueTuple package from NuGet and keep in mind that ValueTuples are mutable structs.

Update: Deconstruction currently represented only as an assignment to existing variables (deconstructon-assignment) or to newly created local variables (deconstruction-declaration). Applicable function member selection algorithm is the same as before:

Each argument in argument list corresponds to a parameter in the function member declaration as described in §7.5.1.1, and any parameter to which no argument corresponds is an optional parameter.

Tuple variable is a single argument. It cannot correspond to several parameters in the formal parameters list of the method.

Title: C# 7 tuples and lambdas

Body:
With new c# 7 tuple syntax, is it possible to specify a lambda with a tuple as parameter and use unpacked values inside the lambda?

Example:

var list = new List<(int,int)>();

normal way to use a tuple in lambda:

list.Select(value => value.Item1*2 + value.Item2/2);

i expected some new sugar to avoid .Item1 .Item2, like:

list.Select((x,y) => x*2 + y/2);

The last line does not work because it is treated as two parameters for lambda. I am not sure if there is a way to do it actually.

EDIT:

I tried double parentesis in lambda definition and it didn't work: ((x,y)) => ..., and maybe it was stupid to try, but double parenthesis actually work here:

list.Add((1,2));

Also, my question is not quite about avoiding ugly default names .Item .Item2, it is about actual unpacking a tuple in lambda (and maybe why it's not implemented or not possible). If you came here for a solution to default names, read Sergey Berezovskiy's answer.

EDIT 2:

Just thought of a more general use case: is it possible (or why not) to "deconstruct" tuple passed to a method? Like this:

void Foo((int,int)(x,y)) { x+y; }

Instead of this:

void Foo((int x,int y) value) { value.x+value.y }

Body:
You should specify names of tuple properties (well, ValueTuple have fields) otherwise default names will be used, as you have seen:

var list = new List<(int x, int y)>();

Now tuple have nicely named fields which you can use

list.Select(t => t.x * 2 + t.y / 2)

Don't forget to add System.ValueTuple package from NuGet and keep in mind that ValueTuples are mutable structs.

Update: Deconstruction currently represented only as an assignment to existing variables (deconstructon-assignment) or to newly created local variables (deconstruction-declaration). Applicable function member selection algorithm is the same as before:

Each argument in argument list corresponds to a parameter in the function member declaration as described in §7.5.1.1, and any parameter to which no argument corresponds is an optional parameter.

Tuple variable is a single argument. It cannot correspond to several parameters in the formal parameters list of the method.