问:
Should I make my REST client API library Async (Java 8)
I am creating client libraries for our REST server. For the C# library I use HttpClient.PostAsync() which works great, it returns an object that the caller can just wait on (making it synchronous), they can complete some other actions and then wait, or they can use the C# await mechanism. Great solution.

For Java I have to write the library for Java 8, because that's the version in the largest use. With Java 8 we cover 98% of the programmers out there. (If we get enough demand, I'll do a Java 11 one also and then we have native async calls.)

So here's my question, There are ways to get async behavior, either using DeferredResult or some 3rd party classes. But is there any advantage to my building my API around this and forcing it? Because if I create a synchronous API, the caller can still call it in their own DeferredResult code. Which is the same end result.

So it seems to me the way to provide a simple straightforward API is to deliver a synchronous one. And those that want async wrap it up in whatever mechanism they prefer to make it async. An important advantage here is I don't force a mechanism or 3rd party library they don't use on them.

Is there any downside to this approach?

Update: Here it is in more detail.

If all I have is a synchronous API, then the caller can wrap my synchronous API in many different ways. The easiest using vanilla Java 8 is:

```<code>// API is: public Metrics postMetrics(Template template)
CompletableFuture<Metrics> completableFuture = CompletableFuture.supplyAsync(() -> { return client.postMetrics(template); });
</code>```

If instead I create an async API, then I am choosing which of these approaches (I would use CompletableFuture) and so the API becomes:

```<code>// API is: public CompletableFuture<Metrics> postMetrics(Template template)
CompletableFuture<Metrics> completableFuture = client.postMetricsAsync(template);
</code>```

Granted, it's a bit easier with that async API. But very little difference. And the downside is I've now forced the async approach on them. Am I missing some larger advantage of providing  an async API?

答:
It is not the same end result.

Synchronous I/O consumes a lot of memory for blocked threads. This is the main disadvantage of synchronous approach. Making synchronous I/O as primary, your asynchronous I/O still will require synchronous I/O and so will consume a lot of resources.

Rational approach is to make asynchronous interface primary and augment it with synchronous methods. The user then can choose if he can afford to spend memory for blocked threads or to employ multiple I/O operations using minimal resources.

Body:
I am creating client libraries for our REST server. For the C# library I use HttpClient.PostAsync() which works great, it returns an object that the caller can just wait on (making it synchronous), they can complete some other actions and then wait, or they can use the C# await mechanism. Great solution.

For Java I have to write the library for Java 8, because that's the version in the largest use. With Java 8 we cover 98% of the programmers out there. (If we get enough demand, I'll do a Java 11 one also and then we have native async calls.)

So here's my question, There are ways to get async behavior, either using DeferredResult or some 3rd party classes. But is there any advantage to my building my API around this and forcing it? Because if I create a synchronous API, the caller can still call it in their own DeferredResult code. Which is the same end result.

So it seems to me the way to provide a simple straightforward API is to deliver a synchronous one. And those that want async wrap it up in whatever mechanism they prefer to make it async. An important advantage here is I don't force a mechanism or 3rd party library they don't use on them.

Is there any downside to this approach?

Update: Here it is in more detail.

If all I have is a synchronous API, then the caller can wrap my synchronous API in many different ways. The easiest using vanilla Java 8 is:

// API is: public Metrics postMetrics(Template template)
CompletableFuture<Metrics> completableFuture = CompletableFuture.supplyAsync(() -> { return client.postMetrics(template); });

If instead I create an async API, then I am choosing which of these approaches (I would use CompletableFuture) and so the API becomes:

// API is: public CompletableFuture<Metrics> postMetrics(Template template)
CompletableFuture<Metrics> completableFuture = client.postMetricsAsync(template);

Granted, it's a bit easier with that async API. But very little difference. And the downside is I've now forced the async approach on them. Am I missing some larger advantage of providing  an async API?


来源: stackexchange

问:
Does array initialize memory in c?
Having this linked list:

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

struct node {
    int value;
    struct node *next;
};
typedef struct node node_t;

void printlist(const node_t*);
node_t *create_node(int);

int main(void){
    int values[3] = {1,2,3};
    node_t *nodes[3];
    for(int i =0; i<3 ; i++)
    {
        nodes[i] = create_node(values[i]);
        if(i!=2)
            nodes[i]->next = nodes[i+1]; //HERE, can I assign next (un)initialized node?
    }

    node_t *header = nodes[0];
    printlist(header);
}

void printlist(const node_t* header){
    for(const node_t *i = header; i; i=i->next)
        printf("value is %i\n",i->value);
}

node_t *create_node(int value){
    node_t *new = malloc(sizeof(node_t));
    new->value=value;
    new->next = 0;
    return new;
}
</code>```

Which gives:

```<code>value is 1
value is 29590344

Command terminated
</code>```

As I can see from output, the first node (header), does not have assign next struct member, which should happened from the loop. But I am assigning the next (pointer to new node) to an (un)initialized member from array (of pointer to nodes). I expect a initilization of array should also initilize a memory, when it has size. But does it? If so, then I do not understand why the assignment does not work, otherwise I understand and have to implement other loop. Thanks for answers.

答:
Your code does not create the dynamic list as you have an array of 3 nodes. next is not needed.

You probably want something like this.

```<code>/* you need to check if memory allocation was successful */

#include <stdlib.h>
#include <stdio.h>

typedef struct node {
    int value;
    struct node *next;
} node_t;

void printlist(const node_t*);
node_t *append_node(node_t *, int);

int main()
{
    node_t *head = NULL, *parent = head;

    for(int x = 0; x < 10; x++)
        if(!head)
        {
            head = append_node(NULL, x);
            parent = head;
        }
        else
        {
            parent = append_node(parent, x);
        }

    printlist(head);
}

void printlist(const node_t* head){
    while(head)
    {
        printf("value is %i\n",head->value);
        head = head -> next;
    }
}

node_t *append_node(node_t *parent, int value){
    node_t *new = malloc(sizeof(*new));
    new->value=value;
    new->next = NULL;
    if(parent) parent -> next = new;
    return new;
}

</code>```

ContentLicense: CC BY-SA 4.0

Title: Does array initialize memory in c?

Body:
Having this linked list:

#include <stdio.h>
#include <stdlib.h>

struct node {
    int value;
    struct node *next;
};
typedef struct node node_t;

void printlist(const node_t*);
node_t *create_node(int);

int main(void){
    int values[3] = {1,2,3};
    node_t *nodes[3];
    for(int i =0; i<3 ; i++)
    {
        nodes[i] = create_node(values[i]);
        if(i!=2)
            nodes[i]->next = nodes[i+1]; //HERE, can I assign next (un)initialized node?
    }

    node_t *header = nodes[0];
    printlist(header);
}

void printlist(const node_t* header){
    for(const node_t *i = header; i; i=i->next)
        printf("value is %i\n",i->value);
}

node_t *create_node(int value){
    node_t *new = malloc(sizeof(node_t));
    new->value=value;
    new->next = 0;
    return new;
}

Which gives:

value is 1
value is 29590344

Command terminated

As I can see from output, the first node (header), does not have assign next struct member, which should happened from the loop. But I am assigning the next (pointer to new node) to an (un)initialized member from array (of pointer to nodes). I expect a initilization of array should also initilize a memory, when it has size. But does it? If so, then I do not understand why the assignment does not work, otherwise I understand and have to implement other loop. Thanks for answers.

Body:
Your code does not create the dynamic list as you have an array of 3 nodes. next is not needed.

You probably want something like this.

/* you need to check if memory allocation was successful */

#include <stdlib.h>
#include <stdio.h>

typedef struct node {
    int value;
    struct node *next;
} node_t;

void printlist(const node_t*);
node_t *append_node(node_t *, int);

int main()
{
    node_t *head = NULL, *parent = head;

    for(int x = 0; x < 10; x++)
        if(!head)
        {
            head = append_node(NULL, x);
            parent = head;
        }
        else
        {
            parent = append_node(parent, x);
        }

    printlist(head);
}

void printlist(const node_t* head){
    while(head)
    {
        printf("value is %i\n",head->value);
        head = head -> next;
    }
}

node_t *append_node(node_t *parent, int value){
    node_t *new = malloc(sizeof(*new));
    new->value=value;
    new->next = NULL;
    if(parent) parent -> next = new;
    return new;
}


问:
Upper bound with recursion tree
I need to find asymptotic upper bound using recursion tree.
The relation is T(n) = T(n-1) + 1/n
I suppose that it is O(logn) but i cannot show it. Any suggestions?

答: Hint: take a look at the Harmonic numbers.</p>

Title: Upper bound with recursion tree


问:
What is the safest way to split a "Floating Point Number String" into its Whole and Fractional Parts
I have developed the following short function to split a number passed to it in a string format into its Whole and Fractional Parts (also outputted as strings).

Note1: The Whole part of the number can run into large numbers (in excess of 50 digits).

Note 2: The output result (the Whole and the Fraction strings) will not be converted into an integer or a float but will be further manipulated only as a string due to the Javascript rounding for large numbers. So going back to numbers is not a concern here

Because the function detects the machine's locale automatically, it is therefore expected that the user enters (passes) the number in the locale of his local machine or otherwise the number is generated programmatically and passed to the function.

The number is expected to be passed as a "string" due to the very large length and also because there is no handling for numbers passed in exponent (e) format.

The function uses the toLocaleString() to detect the decimal and thousand separators.

I have tested the function with the major number systems (.,' space) and so far, so good.

The question is, how safe will this code be, and are there any alternative better and safer methods to do it or corrections/changes necessary?

Thanks

 function splitFloatString(NumString) {
    var decimalSeparator  = (1.1).toLocaleString().substring(1,2);  // Get Decimal Separator
    var thousandSeparator = (1000).toLocaleString().substring(1,2); // Get Thousands Separator
    NumString += "";                                                // ensure a string
    var fraction ="0";                                              // default no fractional part
    NumString = NumString.replace(RegExp("\\"+thousandSeparator,"g"),"");   //remove thousand separators if any

    if (RegExp("\\"+decimalSeparator,"g").test(NumString)) {        // test for decimal separator
       var n = NumString.split(decimalSeparator);                   // Split at Decimal Seprator
       NumString = n[0];                                            // The Whole part
       if (n.length==2) fraction = n[1];                            // The Fractional part
       if (fraction=="") fraction ="0";
       }

  console.log("Whole: ("+NumString+"), Fraction: ("+fraction+")");  // added for testing
  //return n=[NumString,fraction];                                  // normal return uncomment
}

 //------------------------------------------------------------------------------------
 // Tests assuming user's machine and user enters/passes US-EN separators as an example
 //------------------------------------------------------------------------------------
        splitFloatString("123456789123456699999887788812340786.45678907656912574321115194123123456789");
        splitFloatString("1,234,567,891,234,566,999,998,888,812,340.456520754186789075194123123456789");
        splitFloatString("200")
        splitFloatString("0.")
        splitFloatString(123456.2349999)
        splitFloatString("")
        splitFloatString()```

答:
Please try with this one. might help you.

```<code>number = "21212.32323";
var numberString = number + ''; // converts into string
var index = numberString.lastIndexOf("."); // get the index
var strFloat, wholeStr;
if(index === -1) {
  strFloat = '';
  wholeStr = numberString.replace(/[^\w\s]/gi, '').replace(/ /g,'')
} else {
 strFloat = numberString.substring(index + 1); // get the decimal part
 var strWhole = numberString.substring(0, index); // get the number
 wholeStr = strWhole.replace(/[^\w\s]/gi, '').replace(/ /g,'') // remove spcl character
}

console.log(`Whole: ${wholeStr}, Fraction: ${strFloat}`);
</code>```

And yes you can not exceed MAX_SAFE_INTEGER in javascript i.e 32-bits.
What is JavaScript's highest integer value that a number can go to without losing precision?

Body:
Please try with this one. might help you.

number = "21212.32323";
var numberString = number + ''; // converts into string
var index = numberString.lastIndexOf("."); // get the index
var strFloat, wholeStr;
if(index === -1) {
  strFloat = '';
  wholeStr = numberString.replace(/[^\w\s]/gi, '').replace(/ /g,'')
} else {
 strFloat = numberString.substring(index + 1); // get the decimal part
 var strWhole = numberString.substring(0, index); // get the number
 wholeStr = strWhole.replace(/[^\w\s]/gi, '').replace(/ /g,'') // remove spcl character
}

console.log(`Whole: ${wholeStr}, Fraction: ${strFloat}`);

And yes you can not exceed MAX_SAFE_INTEGER in javascript i.e 32-bits.
What is JavaScript's highest integer value that a number can go to without losing precision?


问:
Javascript – event delegation on dynamically created element not working
Sorry for another duplicate.

I'm trying to bind a click event listener to links which will be dynamically created later. Unfortunately this doesn't work:

```<code>document.querySelector('body').addEventListener('click', function(e) {
    if (e.target.tagName.toLowerCase() === 'a') {
        e.preventDefault();
        console.log("click")
    }
});
</code>```

Strangely it also doesn't work on a link which is not created dynamically. It is however working on the body, but that's not the target.

I also tried if (e.target.classList.contains("someclass")) {}

The DOM nodes are body->header->div->a if that makes a difference. (?)

Thanks for any advice on how to make it work!

答:
When using target, sometimes the target is not the expected element.

See for example this code: the dynamically generated  have inner  Elements.

On click the target will be that span.

To get around that minor problem we can use the .closest() selector, in both cases, span or no span:

document.querySelector('body').addEventListener('click', function(e) {
    if (e.target.closest('a')) { // All oyu need
        e.preventDefault();
        console.log("click")
    }
});

setTimeout(() => {
  document.querySelector("#links").insertAdjacentHTML("beforeend", `
    One
    Two
  `);
}, 1000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header><div id="links"></div></header></code>```

Body:
Sorry for another duplicate.

I'm trying to bind a click event listener to links which will be dynamically created later. Unfortunately this doesn't work:

document.querySelector('body').addEventListener('click', function(e) {
    if (e.target.tagName.toLowerCase() === 'a') {
        e.preventDefault();
        console.log("click")
    }
});

Strangely it also doesn't work on a link which is not created dynamically. It is however working on the body, but that's not the target.

I also tried if (e.target.classList.contains("someclass")) {}

The DOM nodes are body->header->div->a if that makes a difference. (?)

Thanks for any advice on how to make it work!

Body:
When using target, sometimes the target is not the expected element.

See for example this code: the dynamically generated <a> have inner <span> Elements.

On click the target will be that span.

To get around that minor problem we can use the .closest() selector, in both cases, span or no span:

document.querySelector('body').addEventListener('click', function(e) {
    if (e.target.closest('a')) { // All oyu need
        e.preventDefault();
        console.log("click")
    }
});

setTimeout(() => {
  document.querySelector("#links").insertAdjacentHTML("beforeend", `
    <a href="#"><span>One</span></a>
    <a href="#"><span>Two</span></a>
  `);
}, 1000);

<header><div id="links"></div></header>


问:
Doubly linked list - Update list->tail after a merge sort
In an implementation of a doubly linked list I am using the typical structure:

```<code>struct node
{
    void *data;
    struct node *prev;
    struct node *next;
};
</code>```

I will also insert at the end of the list in O(1) time, so I have another struct storing the head and the tail:

```<code>struct linklist
{
    struct node *head;
    struct node *tail;
    size_t size;
};
</code>```

The program works as expected for all insert and delete operations, but I have a problem with the sort function, I am using the merge-sort algorithm, as I understand it is the most effective or one of the most effective to sort lists, the algorithm works well:

```<code>static struct node *split(struct node *head)
{
    struct node *fast = head;
    struct node *slow = head;

    while ((fast->next != NULL) && (fast->next->next != NULL))
    {
        fast = fast->next->next;
        slow = slow->next;
    }

    struct node *temp = slow->next;

    slow->next = NULL;
    return temp;
}

static struct node *merge(struct node *first, struct node *second, int (*comp)(const void *, const void *))
{
    if (first == NULL)
    {
        return second;
    }
    if (second == NULL)
    {
        return first;
    }
    if (comp(first->data, second->data) < 0)
    {
        first->next = merge(first->next, second, comp);
        first->next->prev = first;
        first->prev = NULL;
        return first;
    }
    else
    {
        second->next = merge(first, second->next, comp);
        second->next->prev = second;
        second->prev = NULL;
        return second;
    }
}

static struct node *merge_sort(struct node *head, int (*comp)(const void *, const void *))
{
    if ((head == NULL) || (head->next == NULL))
    {
        return head;
    }

    struct node *second = split(head);

    head = merge_sort(head, comp);
    second = merge_sort(second, comp);
    return merge(head, second, comp);
}
</code>```

but I have no idea how to keep the address of list->tail updated:

```<code>void linklist_sort(struct linklist *list, int (*comp)(const void *, const void *))
{
    list->head = merge_sort(list->head, comp);
    // list->tail is no longer valid at this point
}
</code>```

Sure I can walk the whole list after ordering and update list->tail by brute force, but I'd like to know if there's a fancier way to do it.

I managed to solve the problem using a circular list, but I would like to avoid changing the structure of the program.

答:
Your algorithm uses O(N) stack space by recursing in the merge function for every step. With this method, it would be very cumbersome to keep track of the tail node. You can simply scan the list to find it and update the list structure in linklist_sort. This extra step does not change the complexity of the sorting operation. You can save some time by starting from the current value of link->tail: the loop will stop immediately if the list was already sorted.

Here is a modified version:

void linklist_sort(struct linklist *list, int (*comp)(const void *, const void *)) {
    list->head = merge_sort(list->head, comp);
    if (list->tail) {
        struct node *tail = list->tail;
        while (tail->next)
            tail = tail->next;
        list->tail = tail;
    }
}
```

<p>Sorting linked lists with merge sort should only use <strong>O(log(N))</strong> space and <strong>O(N log(N))</strong> time.</p>

<p>Here are some ideas to improve this algorithm:</p>

<ul>
<li><p>since you know the length of the list, you don't need to scan the full list for splitting. You can just pass the lengths along with the list pointers and use that to determine where to split and only scan half the list.</p></li>
<li><p>if you convert <code>merge</code> to a non-recursive version, you can keep track of the last node in the merge phase and update a pointer <code>struct node **tailp</code> passed as an argument to point to this last node. This would save the last scan, and removing the recursion will lower the space complexity. Whether this improves efficiency is not obvious, benchmarking will tell.</p></li>
<li><p>from experience, sorting a linked list, singly and, a fortiori, doubly linked, is more efficiently implemented with an auxiliary array N pointers to the list nodes. You would sort this array and relink the nodes according to the order of the sorted array. The extra requirement is <strong>O(N)</strong> size.</p></li>
</ul>

<p>Here is a modified version using the list lengths and with a non-recursive <code>merge</code>:</p>

<pre class="lang-c prettyprint-override"><code>struct node {
    void *data;
    struct node *prev;
    struct node *next;
};

struct linklist {
    struct node *head;
    struct node *tail;
    size_t size;
};

static struct node *split(struct node *head, size_t pos) {
    struct node *slow = head;

    while (pos-- > 1) {
        slow = slow->next;
    }
    struct node *temp = slow->next;
    slow->next = NULL;
    return temp;
}

static struct node *merge(struct node *first, struct node *second,
                          int (*comp)(const void *, const void *))
{
    struct node *head = NULL;
    struct node *prev = NULL;
    struct node **linkp = &head;

    for (;;) {
        if (first == NULL) {
            second->prev = prev;
            *linkp = second;
            break;
        }
        if (second == NULL) {
            first->prev = prev;
            *linkp = first;
            break;
        }
        if (comp(first->data, second->data)) <= 0 {
            first->prev = prev;
            prev = *linkp = first;
            linkp = &first->next;
        } else {
            second->prev = prev;
            prev = *linkp = second;
            linkp = &second->next;
        }
    }
    return head;
}

static struct node *merge_sort(struct node *head, size_t size,
                               int (*comp)(const void *, const void *))
{
    if (size < 2) {
        return head;
    }

    struct node *second = split(head, size / 2);

    head = merge_sort(head, size / 2, comp);
    second = merge_sort(second, size - size / 2, comp);
    return merge(head, second, comp);
}

void linklist_sort(struct linklist *list, int (*comp)(const void *, const void *)) {
    list->head = merge_sort(list->head, comp, list->size);
    if (list->tail) {
        struct node *tail = list->tail;
        while (tail->next)
            tail = tail->next;
        list->tail = tail;
    }
}
</code>```

Note that you could also simplify the merge function and not update the back pointers during the sort as you can relink the whole list during the last scan. This last scan would be longer and less cache friendly but it should still be more efficient and less error prone.

Body:
In an implementation of a doubly linked list I am using the typical structure:

struct node
{
    void *data;
    struct node *prev;
    struct node *next;
};

I will also insert at the end of the list in O(1) time, so I have another struct storing the head and the tail:

struct linklist
{
    struct node *head;
    struct node *tail;
    size_t size;
};

The program works as expected for all insert and delete operations, but I have a problem with the sort function, I am using the merge-sort algorithm, as I understand it is the most effective or one of the most effective to sort lists, the algorithm works well:

static struct node *split(struct node *head)
{
    struct node *fast = head;
    struct node *slow = head;

    while ((fast->next != NULL) && (fast->next->next != NULL))
    {
        fast = fast->next->next;
        slow = slow->next;
    }

    struct node *temp = slow->next;

    slow->next = NULL;
    return temp;
}

static struct node *merge(struct node *first, struct node *second, int (*comp)(const void *, const void *))
{
    if (first == NULL)
    {
        return second;
    }
    if (second == NULL)
    {
        return first;
    }
    if (comp(first->data, second->data) < 0)
    {
        first->next = merge(first->next, second, comp);
        first->next->prev = first;
        first->prev = NULL;
        return first;
    }
    else
    {
        second->next = merge(first, second->next, comp);
        second->next->prev = second;
        second->prev = NULL;
        return second;
    }
}

static struct node *merge_sort(struct node *head, int (*comp)(const void *, const void *))
{
    if ((head == NULL) || (head->next == NULL))
    {
        return head;
    }

    struct node *second = split(head);

    head = merge_sort(head, comp);
    second = merge_sort(second, comp);
    return merge(head, second, comp);
}

but I have no idea how to keep the address of list->tail updated:

void linklist_sort(struct linklist *list, int (*comp)(const void *, const void *))
{
    list->head = merge_sort(list->head, comp);
    // list->tail is no longer valid at this point
}

Sure I can walk the whole list after ordering and update list->tail by brute force, but I'd like to know if there's a fancier way to do it.

I managed to solve the problem using a circular list, but I would like to avoid changing the structure of the program.

Body:
Your algorithm uses O(N) stack space by recursing in the merge function for every step. With this method, it would be very cumbersome to keep track of the tail node. You can simply scan the list to find it and update the list structure in linklist_sort. This extra step does not change the complexity of the sorting operation. You can save some time by starting from the current value of link->tail: the loop will stop immediately if the list was already sorted.

Here is a modified version:

void linklist_sort(struct linklist *list, int (*comp)(const void *, const void *)) {
    list->head = merge_sort(list->head, comp);
    if (list->tail) {
        struct node *tail = list->tail;
        while (tail->next)
            tail = tail->next;
        list->tail = tail;
    }
}

Sorting linked lists with merge sort should only use O(log(N)) space and O(N log(N)) time.

Here are some ideas to improve this algorithm:

since you know the length of the list, you don't need to scan the full list for splitting. You can just pass the lengths along with the list pointers and use that to determine where to split and only scan half the list.

if you convert merge to a non-recursive version, you can keep track of the last node in the merge phase and update a pointer struct node **tailp passed as an argument to point to this last node. This would save the last scan, and removing the recursion will lower the space complexity. Whether this improves efficiency is not obvious, benchmarking will tell.

from experience, sorting a linked list, singly and, a fortiori, doubly linked, is more efficiently implemented with an auxiliary array N pointers to the list nodes. You would sort this array and relink the nodes according to the order of the sorted array. The extra requirement is O(N) size.

Here is a modified version using the list lengths and with a non-recursive merge:

struct node {
    void *data;
    struct node *prev;
    struct node *next;
};

struct linklist {
    struct node *head;
    struct node *tail;
    size_t size;
};

static struct node *split(struct node *head, size_t pos) {
    struct node *slow = head;

    while (pos-- > 1) {
        slow = slow->next;
    }
    struct node *temp = slow->next;
    slow->next = NULL;
    return temp;
}

static struct node *merge(struct node *first, struct node *second,
                          int (*comp)(const void *, const void *))
{
    struct node *head = NULL;
    struct node *prev = NULL;
    struct node **linkp = &head;

    for (;;) {
        if (first == NULL) {
            second->prev = prev;
            *linkp = second;
            break;
        }
        if (second == NULL) {
            first->prev = prev;
            *linkp = first;
            break;
        }
        if (comp(first->data, second->data)) <= 0 {
            first->prev = prev;
            prev = *linkp = first;
            linkp = &first->next;
        } else {
            second->prev = prev;
            prev = *linkp = second;
            linkp = &second->next;
        }
    }
    return head;
}

static struct node *merge_sort(struct node *head, size_t size,
                               int (*comp)(const void *, const void *))
{
    if (size < 2) {
        return head;
    }

    struct node *second = split(head, size / 2);

    head = merge_sort(head, size / 2, comp);
    second = merge_sort(second, size - size / 2, comp);
    return merge(head, second, comp);
}

void linklist_sort(struct linklist *list, int (*comp)(const void *, const void *)) {
    list->head = merge_sort(list->head, comp, list->size);
    if (list->tail) {
        struct node *tail = list->tail;
        while (tail->next)
            tail = tail->next;
        list->tail = tail;
    }
}

Note that you could also simplify the merge function and not update the back pointers during the sort as you can relink the whole list during the last scan. This last scan would be longer and less cache friendly but it should still be more efficient and less error prone.


问:
set state not working react hooks(string) asyncStorage
hey all so im using react-natives-community async storage and i can't for the life of me get the state to save and im not too sure why. the first console.log from the await variable returns the correct information, but when i set the state the second console.log returns null and im not sure what's going on

```<code>const [userEmail, setUserEmail] = useState<string | null>(null);

const getEmail = await AsyncStorage.getItem('email')
console.log(getEmail + 'first')
setUserEmail(getEmail);
console.log(userEmail + 'second')
</code>```

I made this custom hook but still no luck

const useGetAsyncStorage = (AsyncStorageItem: string): string => {
  try {
    const [data, setData] = useState<string | null>(null);
    useEffect(() => {
      const fetchAsyncStorage = async () => {
        const AsyncStorageData = await AsyncStorage.getItem(AsyncStorageItem);
        console.log(AsyncStorageData)
        setData(AsyncStorageData);
      };
      fetchAsyncStorage();
    }, [AsyncStorageItem]);

    return data as string
  } catch (error) {
    return error
  }
};```

答: The thing is state updates are asynchronous. You will end up seeing the null for the email what it was initially . If you want to see the change , you should do console.log in useEffect() hook</p>

Body:
hey all so im using react-natives-community async storage and i can't for the life of me get the state to save and im not too sure why. the first console.log from the await variable returns the correct information, but when i set the state the second console.log returns null and im not sure what's going on

const [userEmail, setUserEmail] = useState<string | null>(null);

const getEmail = await AsyncStorage.getItem('email')
console.log(getEmail + 'first')
setUserEmail(getEmail);
console.log(userEmail + 'second')

I made this custom hook but still no luck

const useGetAsyncStorage = (AsyncStorageItem: string): string => {
  try {
    const [data, setData] = useState<string | null>(null);
    useEffect(() => {
      const fetchAsyncStorage = async () => {
        const AsyncStorageData = await AsyncStorage.getItem(AsyncStorageItem);
        console.log(AsyncStorageData)
        setData(AsyncStorageData);
      };
      fetchAsyncStorage();
    }, [AsyncStorageItem]);

    return data as string
  } catch (error) {
    return error
  }
};


问:
Managed (.NET) library with HTML Tidy-like functionality?
Is there an HTML cleaner for .NET that can parse HTML and (for instance) convert it to a more machine friendly format such as XHTML?

I've tried the HTML Agility Pack, but that fails to correctly parse even fairly simple examples.

To give an example of HTML that should be parsed correctly:

```<code><html><title>test</title>
<body>
    <ul><li>TestElem1
        <li>TestElem2
        <li>TestElem3 List:
            <ul><li>Nested1
                <li>Nested2</li>
                <li>Nested3
            </ul>
        <li>TestElem4
    </ul>
    <p>paragraph 1
    <p>paragraph 2
    <p>paragraph 3
</body></html>
</code>```

li tags don't need to be closed (see specification), and neither do P tags. In other words, the above sample should be parsed as:

```<code><html><title>test</title>
<body>
    <ul><li>TestElem1</li>
        <li>TestElem2</li>
        <li>TestElem3 List:
            <ul><li>Nested1</li>
                <li>Nested2</li>
                <li>Nested3</li>
            </ul></li>
        <li>TestElem4</li>
    </ul>
    <p>paragraph 1</p>
    <p>paragraph 2</p>
    <p>paragraph 3</p>
</body></html>
</code>```

Since the aim is to use the library on various machines, it's a big disadvantage to need to fall back to native code (such as a wrapper around HTML Tidy) which would require extra deployment hassle and sacrifice platform independence, not to mention being impossible in sandboxed scenarios.

Any suggestions?
To recap, I'm looking for:

An HTML cleaner ala HTML Tidy

Must be able to deal with real world HTML, not just XHTML, at the very least correctly reading valid HTML 4

Must be able to convert to a more easily processable XML format

Should be a purely managed application.

答: Try TidyManaged. </p>

ContentLicense: CC BY-SA 3.0

Body:
Is there an HTML cleaner for .NET that can parse HTML and (for instance) convert it to a more machine friendly format such as XHTML?

I've tried the HTML Agility Pack, but that fails to correctly parse even fairly simple examples.

To give an example of HTML that should be parsed correctly:

<title>test</title>

TestElem1

TestElem2

TestElem3 List:

Nested1

Nested2

Nested3

TestElem4

paragraph 1

paragraph 2

paragraph 3

li tags don't need to be closed (see specification), and neither do P tags. In other words, the above sample should be parsed as:

<title>test</title>

TestElem1

TestElem2

TestElem3 List:

Nested1

Nested2

Nested3

TestElem4

paragraph 1

paragraph 2

paragraph 3

Since the aim is to use the library on various machines, it's a big disadvantage to need to fall back to native code (such as a wrapper around HTML Tidy) which would require extra deployment hassle and sacrifice platform independence, not to mention being impossible in sandboxed scenarios.

Any suggestions?
To recap, I'm looking for:

An HTML cleaner ala HTML Tidy

Must be able to deal with real world HTML, not just XHTML, at the very least correctly reading valid HTML 4

Must be able to convert to a more easily processable XML format

Should be a purely managed application.

Body: Try TidyManaged.


问:
Using R to count consecutive occurrences of a number and how long each occurrence lasts for?
I've got a large dataset (dt) which has a time columnn (where time is in seconds) and a column that records a 1 when some other variables meet a certain value and a 0 when they don't, e.g:

```<code>time (s) var
0        1
0.3      1
0.6      0
0.9      0
1.2      1
1.5      1
1.8      0
</code>```

Part 1) what I want to do is count each time 1 is repeated as a unique occurrence (more than twice) in a count column which would look like this:

```<code>time (s) var count
0        1   1
0.3      1   1
0.6      0   0
0.9      0   0
1.2      1   2
1.5      1   2
1.8      0   0

</code>```

where each occurrence in the same bout would have the same number and where 0 occurs is there is no counting.

For Part 1 I have this so far, but I would like it to print each unique occurrence as a count in a column which it doesn't do:

```<code>with(rle(dt$var), sum(lengths[values] > 2))
</code>```

Part 2) I also want to know the length of time each occurrence lasts.
(I also have a replicate column which has value of 1 for each row)

I tried this to calculate Part 2 but it doesn't work...

```<code>var_time <- dt %>%
  group_by(replicate) %>%
  mutate(var_time = cumsum(var != lag(var, default = ""))) %>%
  group_by(var, time) %>%
  summarise(start = min(time),
            end   = max(time),
            var = sum(var))
</code>```

答:
An option with data.table

```<code>library(data.table)
setDT(df1)[, count := rleid(var) * var][count != 0,
     count := match(count, unique(count))][]
#     time var count
#1:  0.0   1     1
#2:  0.3   1     1
#3:  0.6   0     0
#4:  0.9   0     0
#5:  1.2   1     2
#6:  1.5   1     2
#7:  1.8   0     0
</code>```

Or with base R using rle/inverse.rle

```<code>df1$count <- inverse.rle(within.list(rle(df1$var),
      values[as.logical(values)] <- seq_along(values[as.logical(values)])))
</code>```

data

```<code>df1 <- data.frame(time = c(0, 0.3, 0.6, 0.9, 1.2, 1.5, 1.8), var = c(1, 1, 0, 0, 1, 1, 0))
</code>```

Body:
I've got a large dataset (dt) which has a time columnn (where time is in seconds) and a column that records a 1 when some other variables meet a certain value and a 0 when they don't, e.g:

time (s) var
0        1
0.3      1
0.6      0
0.9      0
1.2      1
1.5      1
1.8      0

Part 1) what I want to do is count each time 1 is repeated as a unique occurrence (more than twice) in a count column which would look like this:

time (s) var count
0        1   1
0.3      1   1
0.6      0   0
0.9      0   0
1.2      1   2
1.5      1   2
1.8      0   0

where each occurrence in the same bout would have the same number and where 0 occurs is there is no counting.

For Part 1 I have this so far, but I would like it to print each unique occurrence as a count in a column which it doesn't do:

with(rle(dt$var), sum(lengths[values] > 2))

Part 2) I also want to know the length of time each occurrence lasts.
(I also have a replicate column which has value of 1 for each row)

I tried this to calculate Part 2 but it doesn't work...

var_time <- dt %>%
  group_by(replicate) %>%
  mutate(var_time = cumsum(var != lag(var, default = ""))) %>%
  group_by(var, time) %>%
  summarise(start = min(time),
            end   = max(time),
            var = sum(var))

Body:
An option with data.table

library(data.table)
setDT(df1)[, count := rleid(var) * var][count != 0,
     count := match(count, unique(count))][]
#     time var count
#1:  0.0   1     1
#2:  0.3   1     1
#3:  0.6   0     0
#4:  0.9   0     0
#5:  1.2   1     2
#6:  1.5   1     2
#7:  1.8   0     0

Or with base R using rle/inverse.rle

df1$count <- inverse.rle(within.list(rle(df1$var),
      values[as.logical(values)] <- seq_along(values[as.logical(values)])))

data

df1 <- data.frame(time = c(0, 0.3, 0.6, 0.9, 1.2, 1.5, 1.8), var = c(1, 1, 0, 0, 1, 1, 0))


问:
Consolidating different worksheets into a main excel worksheet
I am really new to VBA and I have just been learning the basics and the VBA language recently from Youtube and communities such as these. Therefore, any help will be really appreciated!

I am trying to consolidate excel worksheets from different excel workbooks into a main excel workbook. The excel workbooks are all found in the same file. However, they are named differently and I only have the partial names for the excel workbooks e.g. "ABG_RSPB_xxxxx-yyyy".

I will have a main workbook in the folder consolidating the data from all the different workbook and worksheets. Each workbook where the data is extracted from only has one worksheet and the template in each worksheet is the same. They have the same headers as well. All the workbooks are csv format. However the worksheets have partial names as well (the worksheet will have the same name as the workbook it is in).

Currently, I have a macro that provides a similar function however, it can't extract workbooks and worksheets with partial names.

Any help to amend the macro such that it can extract from partial workbooks and worksheets will be deeply appreciated. Thank you!

Current code:

```<code>Sub consolidation ()

Set mainWB = ActiveWorkbook
Dim mainPath As String
mainPath = ThisWorkbook.Path
Dim mainRowstart As Integer
mainRowstart = 2
Dim mainRC As Integer
mainRC = lastRow ("Consolidated Trades", "A") + 1

If mainRC < mainRowStart Then
        mainRC = mainRowStart
EndIf

Dim fso As Object
Dim folder As Object
Dim files As Object
Set fso = CreateObject ("Scripting.FileSystemObject")
Set folderPaths = fso.getfolder (mainPath)
set filePaths = folderPath.files

Dim curFile As String
Dim curPath As String
Dim curRC As Integer
Dim curWSName As String
curWSName = ""

For Each filePath In filePaths
        curPath = filePath
        curFile = Split (curPath, "\")(UBound(Split(curPath, "\")))

                    If Left (curFile, 1) <> "~" Then
                            If curFile <> "ABG_RSPB_xxxxx=yyy.csv" Then
                                    If Right (curFile, Len ("ABG_RSPB_xxxxx=yyy.xlsm")) =                                                                                "ABG_RSPB_xxxxx=yyy.xlsm" Or _ Right (curFile, Len("ABG_RSPB_xxxxx=yyy.xls")) = "ABG_RSPB_xxxxx=yyy.xls" Then

            Workbooks.Open Filename: = curPath
            Workbooks (curFile).Activate

            For Each ws In Worksheets
            If ws.Name = "ABG_RSPB_xxxxx=yyy.csv" Then
                    curWSName = ws.Name
            End If

    Next Ws

            curRC = lastRow(CurWSName, "A")
            mainWB.Activate
            mainRC = lastrow("Consolidated Trades", "A") + 1

    If curRC >= 2 Then

            mainWB.Worksheets("Consolidated Trades").Range("A" & mainRC & ":U: & mainRC + curRC - 2).Value = _ Workbooks(curFile).Worksheets(curWSName).Range("A2:U" & curRC).Value

            mainWB.Worksheets("Consolidated Trades").Range("V" & mainRC).Value = curFile & "with" & curRC -1 & "Rows of Data"

            EndIf

            Workbooks(curFile).Close

            EndIf
        EndIf
      EndIf
    NextfilePath

MsgBox "Process Complete"
End Sub
</code>```

答:
If I've understood you correctly, you have some csv files besides your main workbook and you want to iterate over all csv files and read all values in the first column of the first sheet of each file and then write them into the first column of the main workbook, right?
I've assumed that:

all csv files are desired and should be read (i.e., there is no csv file that you do not want to read it)

You have a subroutine called "lastrow" that finds the last row in a column of a sheet

Please see if the following code does the job correctly. If there is any problem, please leave a comment below, I'll see and edit my code as you want.

```<code>Sub consolidation()

    Dim mainRowstart As Integer
    mainRowstart = 2
    Dim mainRC As Integer
    mainRC = lastrow("Consolidated Trades", "A") + 1 'I've assumed that you have another sub called "lastrow"
    If mainRC < mainRowstart Then
            mainRC = mainRowstart
    End If

    '======================================================================================================
    '   1- Get all csv files in this workbook's path
    '======================================================================================================
    Dim allCsvFiles() As Variant
    allCsvFiles = GetFileList(ThisWorkbook.path, "csv")

    '======================================================================================================
    '   2- Loop over and read/write all data
    '======================================================================================================
    If IsArray(allCsvFiles) Then 'i.e., at least one file has found

        Dim file As Variant
        For Each file In allCsvFiles

            'Open file
            Workbooks.Open (file)

            'Activate
            Workbooks(file).Activate

            'How many rows do exist in the file?
            Dim curRC As Integer
            curRC = lastrow(Workbooks(file).Sheets(1).Name, "A") 'Hint: as the file is a "csv" file, it always contains only one sheet and there is no need to search and find a specific sheet

            If curRC > 2 Then

                mainRC = lastrow("Consolidated Trades", "A") + 1 'Is it required to run this function in every iteration???

                ThisWorkbook.Worksheets("Consolidated Trades").Range("V" & mainRC).Value = file & " with " & curRC - 1 & " rows of data"

                'Read and write data
                Dim row As Integer
                For row = 2 To curRC

                    ThisWorkbook.Worksheets("Consolidated Trades").Cells(mainRC, 1).Value = Workbooks(file).Sheets(1).Cells(row, 1).Value
                    mainRC = mainRC + 1

                Next row
            End If

            'Close file
            Workbooks(file).Close False

        Next

        MsgBox "Process Complete"

    End If

End Sub
</code>```

where GetFileList is:

```<code>Function GetFileList(path As String, FileSpec As String) As Variant

    Dim FileArray() As Variant
    Dim FileCount As Integer
    Dim FileName As String

    FileCount = 0
    FileName = Dir(path & "\*." & FileSpec)
    If FileName = "" Then GoTo NoFilesFound

'   Loop until no more matching files are found
    Do While FileName <> ""
        FileCount = FileCount + 1
        ReDim Preserve FileArray(1 To FileCount)

        FileArray(FileCount) = FileName
        FileName = Dir()
    Loop
    GetFileList = FileArray
    Exit Function

NoFilesFound:
    GetFileList = False
End Function
</code>```

Body:
I am really new to VBA and I have just been learning the basics and the VBA language recently from Youtube and communities such as these. Therefore, any help will be really appreciated!

I am trying to consolidate excel worksheets from different excel workbooks into a main excel workbook. The excel workbooks are all found in the same file. However, they are named differently and I only have the partial names for the excel workbooks e.g. "ABG_RSPB_xxxxx-yyyy".

I will have a main workbook in the folder consolidating the data from all the different workbook and worksheets. Each workbook where the data is extracted from only has one worksheet and the template in each worksheet is the same. They have the same headers as well. All the workbooks are csv format. However the worksheets have partial names as well (the worksheet will have the same name as the workbook it is in).

Currently, I have a macro that provides a similar function however, it can't extract workbooks and worksheets with partial names.

Any help to amend the macro such that it can extract from partial workbooks and worksheets will be deeply appreciated. Thank you!

Current code:

Sub consolidation ()

Set mainWB = ActiveWorkbook
Dim mainPath As String
mainPath = ThisWorkbook.Path
Dim mainRowstart As Integer
mainRowstart = 2
Dim mainRC As Integer
mainRC = lastRow ("Consolidated Trades", "A") + 1

If mainRC < mainRowStart Then
        mainRC = mainRowStart
EndIf

Dim fso As Object
Dim folder As Object
Dim files As Object
Set fso = CreateObject ("Scripting.FileSystemObject")
Set folderPaths = fso.getfolder (mainPath)
set filePaths = folderPath.files

Dim curFile As String
Dim curPath As String
Dim curRC As Integer
Dim curWSName As String
curWSName = ""

For Each filePath In filePaths
        curPath = filePath
        curFile = Split (curPath, "\")(UBound(Split(curPath, "\")))

                    If Left (curFile, 1) <> "~" Then
                            If curFile <> "ABG_RSPB_xxxxx=yyy.csv" Then
                                    If Right (curFile, Len ("ABG_RSPB_xxxxx=yyy.xlsm")) =                                                                                "ABG_RSPB_xxxxx=yyy.xlsm" Or _ Right (curFile, Len("ABG_RSPB_xxxxx=yyy.xls")) = "ABG_RSPB_xxxxx=yyy.xls" Then

            Workbooks.Open Filename: = curPath
            Workbooks (curFile).Activate

            For Each ws In Worksheets
            If ws.Name = "ABG_RSPB_xxxxx=yyy.csv" Then
                    curWSName = ws.Name
            End If

    Next Ws

            curRC = lastRow(CurWSName, "A")
            mainWB.Activate
            mainRC = lastrow("Consolidated Trades", "A") + 1

    If curRC >= 2 Then

            mainWB.Worksheets("Consolidated Trades").Range("A" & mainRC & ":U: & mainRC + curRC - 2).Value = _ Workbooks(curFile).Worksheets(curWSName).Range("A2:U" & curRC).Value

            mainWB.Worksheets("Consolidated Trades").Range("V" & mainRC).Value = curFile & "with" & curRC -1 & "Rows of Data"

            EndIf

            Workbooks(curFile).Close

            EndIf
        EndIf
      EndIf
    NextfilePath

MsgBox "Process Complete"
End Sub

Body:
If I've understood you correctly, you have some csv files besides your main workbook and you want to iterate over all csv files and read all values in the first column of the first sheet of each file and then write them into the first column of the main workbook, right?
I've assumed that:

all csv files are desired and should be read (i.e., there is no csv file that you do not want to read it)

You have a subroutine called "lastrow" that finds the last row in a column of a sheet

Please see if the following code does the job correctly. If there is any problem, please leave a comment below, I'll see and edit my code as you want.

Sub consolidation()

    Dim mainRowstart As Integer
    mainRowstart = 2
    Dim mainRC As Integer
    mainRC = lastrow("Consolidated Trades", "A") + 1 'I've assumed that you have another sub called "lastrow"
    If mainRC < mainRowstart Then
            mainRC = mainRowstart
    End If

    '======================================================================================================
    '   1- Get all csv files in this workbook's path
    '======================================================================================================
    Dim allCsvFiles() As Variant
    allCsvFiles = GetFileList(ThisWorkbook.path, "csv")

    '======================================================================================================
    '   2- Loop over and read/write all data
    '======================================================================================================
    If IsArray(allCsvFiles) Then 'i.e., at least one file has found

        Dim file As Variant
        For Each file In allCsvFiles

            'Open file
            Workbooks.Open (file)

            'Activate
            Workbooks(file).Activate

            'How many rows do exist in the file?
            Dim curRC As Integer
            curRC = lastrow(Workbooks(file).Sheets(1).Name, "A") 'Hint: as the file is a "csv" file, it always contains only one sheet and there is no need to search and find a specific sheet

            If curRC > 2 Then

                mainRC = lastrow("Consolidated Trades", "A") + 1 'Is it required to run this function in every iteration???

                ThisWorkbook.Worksheets("Consolidated Trades").Range("V" & mainRC).Value = file & " with " & curRC - 1 & " rows of data"

                'Read and write data
                Dim row As Integer
                For row = 2 To curRC

                    ThisWorkbook.Worksheets("Consolidated Trades").Cells(mainRC, 1).Value = Workbooks(file).Sheets(1).Cells(row, 1).Value
                    mainRC = mainRC + 1

                Next row
            End If

            'Close file
            Workbooks(file).Close False

        Next

        MsgBox "Process Complete"

    End If

End Sub

where GetFileList is:

Function GetFileList(path As String, FileSpec As String) As Variant

    Dim FileArray() As Variant
    Dim FileCount As Integer
    Dim FileName As String

    FileCount = 0
    FileName = Dir(path & "\*." & FileSpec)
    If FileName = "" Then GoTo NoFilesFound

'   Loop until no more matching files are found
    Do While FileName <> ""
        FileCount = FileCount + 1
        ReDim Preserve FileArray(1 To FileCount)

        FileArray(FileCount) = FileName
        FileName = Dir()
    Loop
    GetFileList = FileArray
    Exit Function

NoFilesFound:
    GetFileList = False
End Function


问:
onActivityResult not called after taking a photo in Android
I am using this code but my onActivityResult never gets called. I used to make the request without passing the extra intent to save the image to an SD card and that worked fine - onActivityResult() would get called as I expect it to. But since I added the SD card code - no luck!

Have I added (or missed) something ? I was following https://stackoverflow.com/a/12277455/2884981 as an example.

Here is my code,

```<code>    static final int CAPTURE_IMAGE_CALLBACK = 1;

    private void dispatchTakePictureIntent()
    {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    File photo = null;
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());

        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
        {
            photo = new File(android.os.Environment.getExternalStorageDirectory(), "myapp/images/" + File.separator + timeStamp + ".png");
        }
        else
        {
            photo = new File(getCacheDir(), "myapp/images/" + File.separator + timeStamp + ".png");
        }
        if ( photo != null)
        {
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
        }

        if (takePictureIntent.resolveActivity(getPackageManager()) != null)
        {
            startActivityForResult(takePictureIntent, CAPTURE_IMAGE_CALLBACK);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        // This never gets hit!
        if (requestCode == CAPTURE_IMAGE_CALLBACK)
        {
              // etc
</code>```

I just thought I'd add, inside the camera app once I click the tick - nothing happens. I click the tick repeatedly, it just stays on the camera screen. Control never gets returned to the main app.

答:
In my case, the onDestroy called instead. Because android system will try to release memory (if our apps in background, and we open camera apps), and the reason it never called onActivityResult method also due to this please make sure you were not using noHistory=true or intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)

e.g

```<code>// AbcActivity.kt
val intent = Intent(AbcActivity.this, RegistrationForm.class)
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)
startActivity(intent)

// RegistrationForm.kt
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
// do take pictures, and confirm the photo, never going back to the RegistrationForm, instead back to AbcActivity
</code>```

by removing flags and noHistory=true (in AndroidManifest.xml) my activity recreated and onActivityResult called again, but we need to save the previous state using ViewModel or (onSaveInstance & onRestoreInstance)

Body:
I am using this code but my onActivityResult never gets called. I used to make the request without passing the extra intent to save the image to an SD card and that worked fine - onActivityResult() would get called as I expect it to. But since I added the SD card code - no luck!

Have I added (or missed) something ? I was following https://stackoverflow.com/a/12277455/2884981 as an example.

Here is my code,

    static final int CAPTURE_IMAGE_CALLBACK = 1;

    private void dispatchTakePictureIntent()
    {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    File photo = null;
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());

        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
        {
            photo = new File(android.os.Environment.getExternalStorageDirectory(), "myapp/images/" + File.separator + timeStamp + ".png");
        }
        else
        {
            photo = new File(getCacheDir(), "myapp/images/" + File.separator + timeStamp + ".png");
        }
        if ( photo != null)
        {
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
        }

        if (takePictureIntent.resolveActivity(getPackageManager()) != null)
        {
            startActivityForResult(takePictureIntent, CAPTURE_IMAGE_CALLBACK);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        // This never gets hit!
        if (requestCode == CAPTURE_IMAGE_CALLBACK)
        {
              // etc

I just thought I'd add, inside the camera app once I click the tick - nothing happens. I click the tick repeatedly, it just stays on the camera screen. Control never gets returned to the main app.

Body:
In my case, the onDestroy called instead. Because android system will try to release memory (if our apps in background, and we open camera apps), and the reason it never called onActivityResult method also due to this please make sure you were not using noHistory=true or intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)

e.g

// AbcActivity.kt
val intent = Intent(AbcActivity.this, RegistrationForm.class)
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)
startActivity(intent)

// RegistrationForm.kt
val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
// do take pictures, and confirm the photo, never going back to the RegistrationForm, instead back to AbcActivity

by removing flags and noHistory=true (in AndroidManifest.xml) my activity recreated and onActivityResult called again, but we need to save the previous state using ViewModel or (onSaveInstance & onRestoreInstance)


问:
Why does the control goes back to the caller function after the execution of the first await statement in an async function?
Here's the code:

function B() {
  return 'B';
}

async function test(b) {
  await console.log('Z')
  await console.log(b())
  console.log('X')
  await console.log("hihihi")
}

console.log('A');
test(B);
console.log('C');
console.log('P');```

This output's to A Z C P B X hihihi

Question is:

Why does the control goes to the caller function(that called the async function) after executing the first await statement? How's it useful?

What's to be done to force execute all await statements one after the other somehow preventing it from going to the caller function?

答:
When a promise is done, any further execution is going into a queue there is executed after the code there is running at the moment,

first, console.log('A') is called as normal

then console.log('Z') is called as normal, but javascript is exception a promise, but it is fine for it to take a normal statement, but any code after the call stack is been emptying

then c and p is logged

now the callstack is empty, and now its time for evaluating the microtask queue

b is called. and another microtask is carried out

x is logged normal

hi hi hi is logged, and another microtask is started, but then the function exits

I really do recommend watching "the event loop" which goes into details with this functionality https://www.youtube.com/watch?v=cCOL7MC4Pl0 done by Jake which also have an article on it https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/

everthing is called on the same thread, see richytong's code block for your 2nd question

Body:
Here's the code:

function B() {
  return 'B';
}

async function test(b) {
  await console.log('Z')
  await console.log(b())
  console.log('X')
  await console.log("hihihi")
}

console.log('A');
test(B);
console.log('C');
console.log('P');

This output's to A Z C P B X hihihi

Question is:

Why does the control goes to the caller function(that called the async function) after executing the first await statement? How's it useful?

What's to be done to force execute all await statements one after the other somehow preventing it from going to the caller function?


问:
Challenging MySQL query
I'm working on a blogging app that requires a unique query.

Problem: I need to display one parent post, all it's children posts (up to a certain number before requiring pagination), and up to 5 comments associated with each child post, and the parent.

I wrote this query, but it doesn't work because it will return only 5 comments that belong to the parent post.

```<code>SELECT
    posts.id, posts.postTypeId, posts.parentId, posts.ownerUserId, posts.body
, users.id AS authorId, users.displayname AS authorDisplayName
, comments.id AS commentId, comments.text AS commentText
, comments.commentOwnerUserId, comments.commentOwnerDisplayName
FROM posts
JOIN users ON posts.owneruserid = users.id
LEFT JOIN ( SELECT comments.id, comments.postId, comments.text, commenters.id AS commentOwnerUserId, commenters.displayname AS commentOwnerDisplayName
        FROM comments
        JOIN users AS commenters ON comments.userid = commenters.id
        ORDER BY comments.createdat ASC
        LIMIT 0,5 ) AS comments ON comments.postid = posts.id
WHERE posts.id = @postId OR posts.parentId = @postId
ORDER BY posts.posttypeid, posts.createdAt
</code>```

The query returns the parent post, all it's children, and the first 5 comments it encounters, (usually they belong to the parent because we are ordering by postTypeId, and the parent is the first post). If the first post doesn't have 5 comments, it moves on the next post and returns those comments, until the 5 limit is reached.

What I need is to return one parent post and all it's children posts, and up to 5 comments for each child, the parent. I also need the owner data for each post and comment.

UPDATE I'm open to doing this with more than one query if it will scale well. The only condition is that the parent and children posts retrieval happens in the same query.

Any idea how I can write such a query? I included my schema below.

```<code>/* Posts table */
CREATE TABLE `posts` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `posttypeid` int(10) NOT NULL,
  `parentid` int(10) DEFAULT NULL,
  `body` text NOT NULL,
  `userid` int(10) NOT NULL,
  `createdat` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
KEY `parentId` (`parentid`)
KEY `userId` (`userid`)
) ENGINE=InnoDB AUTO_INCREMENT=572 DEFAULT CHARSET=utf8

/* Comments table */
CREATE TABLE `comments` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `postid` int(10) NOT NULL,
  `userid` int(10) NOT NULL,
  `text` text NOT NULL,
  `createdat` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `postId` (`postid`),
  KEY `userId` (`userid`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8

/* users table */
CREATE TABLE `users` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `email` varchar(50) NOT NULL,
  `displayname` varchar(50) NOT NULL,
  `createdat` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`),
) ENGINE=InnoDB AUTO_INCREMENT=66 DEFAULT CHARSET=utf8
</code>```

答: It sounds like you're looking to store hierarchical data.  This isn't so much a hard question as it is a bit of a time-consuming one.  I would suggest reading a really good article from a few years ago named Managing Hierarchical Data in MySQL by Mike Hillyer.  It's got some really good conceptual suggestions as well as example implementations of the kind of system it sounds like you're designing.  Definitely read the "Find the Immediate Subordinates of a Node" section.  :)

Title: Challenging MySQL query

Body:
I'm working on a blogging app that requires a unique query.

Problem: I need to display one parent post, all it's children posts (up to a certain number before requiring pagination), and up to 5 comments associated with each child post, and the parent.

I wrote this query, but it doesn't work because it will return only 5 comments that belong to the parent post.

SELECT
    posts.id, posts.postTypeId, posts.parentId, posts.ownerUserId, posts.body
, users.id AS authorId, users.displayname AS authorDisplayName
, comments.id AS commentId, comments.text AS commentText
, comments.commentOwnerUserId, comments.commentOwnerDisplayName
FROM posts
JOIN users ON posts.owneruserid = users.id
LEFT JOIN ( SELECT comments.id, comments.postId, comments.text, commenters.id AS commentOwnerUserId, commenters.displayname AS commentOwnerDisplayName
        FROM comments
        JOIN users AS commenters ON comments.userid = commenters.id
        ORDER BY comments.createdat ASC
        LIMIT 0,5 ) AS comments ON comments.postid = posts.id
WHERE posts.id = @postId OR posts.parentId = @postId
ORDER BY posts.posttypeid, posts.createdAt

The query returns the parent post, all it's children, and the first 5 comments it encounters, (usually they belong to the parent because we are ordering by postTypeId, and the parent is the first post). If the first post doesn't have 5 comments, it moves on the next post and returns those comments, until the 5 limit is reached.

What I need is to return one parent post and all it's children posts, and up to 5 comments for each child, the parent. I also need the owner data for each post and comment.

UPDATE I'm open to doing this with more than one query if it will scale well. The only condition is that the parent and children posts retrieval happens in the same query.

Any idea how I can write such a query? I included my schema below.

/* Posts table */
CREATE TABLE `posts` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `posttypeid` int(10) NOT NULL,
  `parentid` int(10) DEFAULT NULL,
  `body` text NOT NULL,
  `userid` int(10) NOT NULL,
  `createdat` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
KEY `parentId` (`parentid`)
KEY `userId` (`userid`)
) ENGINE=InnoDB AUTO_INCREMENT=572 DEFAULT CHARSET=utf8

/* Comments table */
CREATE TABLE `comments` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `postid` int(10) NOT NULL,
  `userid` int(10) NOT NULL,
  `text` text NOT NULL,
  `createdat` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `postId` (`postid`),
  KEY `userId` (`userid`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8

/* users table */
CREATE TABLE `users` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `email` varchar(50) NOT NULL,
  `displayname` varchar(50) NOT NULL,
  `createdat` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`),
) ENGINE=InnoDB AUTO_INCREMENT=66 DEFAULT CHARSET=utf8


问:
Ngx-bootstrap datepicker custom ranges
I would like to add some buttons with my custom ranges in datepicker. I'm using Quick select ranges from ngx-bootstrap: https://valor-software.com/ngx-bootstrap/#/datepicker#quick-select-ranges

I am able to use them, but in my case, I would like to ask, if there is a possibility to get an event from those buttons? I need exactly the event from those buttons, not from changing date directly by clicking on any button. Thanks for any help.

答:
Check the api reference you can subscribe to the bsValueChange event emitter under the Outputs section.

Emits when datepicker value has been changed

Here is an example of how to subscribe to the component api:

ts:

```<code>import { Component, ViewChild } from '@angular/core';
import { BsDaterangepickerDirective } from 'ngx-bootstrap/datepicker';

@Component({
  selector: 'app-daterangepicker',
  templateUrl: './date-range-picker.component.html'
})
export class DateRangePickerComponent {
  ranges: any = [{
    value: [new Date(new Date().setDate(new Date().getDate() - 7)), new Date()],
    label: 'Last 7 Days'
  }, {
    value: [new Date(), new Date(new Date().setDate(new Date().getDate() + 7))],
    label: 'Next 7 Days'
  }];

  @ViewChild(BsDaterangepickerDirective, { static: false }) dateRangePicker: BsDaterangepickerDirective;

  ngAfterViewInit() {
    this.dateRangePicker.bsValueChange.subscribe(res => console.log(res));
  }
}
</code>```

html:

```<code><input type="text"
       bsDaterangepicker
       [bsConfig]="{ ranges: ranges }">
</code>```

Title: Ngx-bootstrap datepicker custom ranges

Body:
Check the api reference you can subscribe to the bsValueChange event emitter under the Outputs section.

Emits when datepicker value has been changed

Here is an example of how to subscribe to the component api:

ts:

import { Component, ViewChild } from '@angular/core';
import { BsDaterangepickerDirective } from 'ngx-bootstrap/datepicker';

@Component({
  selector: 'app-daterangepicker',
  templateUrl: './date-range-picker.component.html'
})
export class DateRangePickerComponent {
  ranges: any = [{
    value: [new Date(new Date().setDate(new Date().getDate() - 7)), new Date()],
    label: 'Last 7 Days'
  }, {
    value: [new Date(), new Date(new Date().setDate(new Date().getDate() + 7))],
    label: 'Next 7 Days'
  }];

  @ViewChild(BsDaterangepickerDirective, { static: false }) dateRangePicker: BsDaterangepickerDirective;

  ngAfterViewInit() {
    this.dateRangePicker.bsValueChange.subscribe(res => console.log(res));
  }
}

html:

<input type="text"
       bsDaterangepicker
       [bsConfig]="{ ranges: ranges }">


问:
How to include bootstrap file in my ejs files?
So i have installed bootstrap using npm -bootstrap@3 but when i am trying to include bootstrap.min.css file from node_modules in my application, it shows this error in my console :

error message

In the network tab it shows

404 not found on the bootstrap source.

Below are some images on my project structue:

project folder structure

ejs code to include bootstrap file

Whats the issue here?

答:
This worked for me, using Bootstrap CDN

head.ejs

```<code>> <!-- views/partials/head.ejs --> <meta charset="UTF-8" /> <title>Super
> Awesome</title>
>
> <!-- Latest compiled and minified CSS --> <link   rel="stylesheet"
> href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
> integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
> crossorigin="anonymous" />
</code>```

Include this in index.ejs

```<code><!DOCTYPE html>
<html>
  <head>
    <%- include ('../partials/head') %>
  </head>
  <body>
    <div class="jumbotron">
      <%- include ('../partials/form') %>
    </div>
  </body>
</html>
</code>```

Body:
This worked for me, using Bootstrap CDN

head.ejs

> <!-- views/partials/head.ejs --> <meta charset="UTF-8" /> <title>Super
> Awesome</title>
>
> <!-- Latest compiled and minified CSS --> <link   rel="stylesheet"
> href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
> integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
> crossorigin="anonymous" />

Include this in index.ejs

<!DOCTYPE html>
<html>
  <head>
    <%- include ('../partials/head') %>
  </head>
  <body>
    <div class="jumbotron">
      <%- include ('../partials/form') %>
    </div>
  </body>
</html>


问:
FutureBuilder with Provider: List is not a subtype of type Future<List>
I need to create a list of elements in a dynamic way and that the user can modify them naturally, the idea is after inserting the data into an arrangement that shows me that or those elements

```<code>  FutureBuilder<List<Detalleconcepto>>(
                    future:  provider.listado,
                    builder: (BuildContext context,
                        AsyncSnapshot<List<Detalleconcepto>> snapshot) {
                      if (snapshot.hasData) {
                        return _listConceptos(snapshot.data);
                      } else {
                        return Center(
                          child: contenedor(),
                        );
                      }
                    },
                  ),
</code>```

I will leave references of my provider model and my list

```<code>class ProviderInfo with ChangeNotifier {
  List<Detalleconcepto> _listado = new List<Detalleconcepto>();

  get listado {
    return _listado;
  }

  set listado(List<Detalleconcepto> listado) {
    this._listado = listado;
    notifyListeners();
  }
}
</code>```

```<code>class Detalleconcepto {
  int idOperacionFinanciera;
  int idTipoConcepto;
  String tipoConcepto;
  double importe;
  String fecha;
  String numeroDocumento;

  Detalleconcepto({
    this.idOperacionFinanciera,
    this.idTipoConcepto,
    this.tipoConcepto,
    this.importe,
    this.fecha,
    this.numeroDocumento,
  });
</code>```

════════ Exception caught by widgets library ═══════════════════════════════════
type 'List' is not a subtype of type 'Future>'

The relevant error-causing widget was
    CreateList

答:
You only need a FutureBuilder when you have data that is returned in a Future, i.e. asynchronously.

As the data is returned synchronously in your case, you do not need a FutureBuilder:

_listConceptos(provider.listado), // instead of FutureBuilder
```

Body:
I need to create a list of elements in a dynamic way and that the user can modify them naturally, the idea is after inserting the data into an arrangement that shows me that or those elements

  FutureBuilder<List<Detalleconcepto>>(
                    future:  provider.listado,
                    builder: (BuildContext context,
                        AsyncSnapshot<List<Detalleconcepto>> snapshot) {
                      if (snapshot.hasData) {
                        return _listConceptos(snapshot.data);
                      } else {
                        return Center(
                          child: contenedor(),
                        );
                      }
                    },
                  ),

I will leave references of my provider model and my list

class ProviderInfo with ChangeNotifier {
  List<Detalleconcepto> _listado = new List<Detalleconcepto>();

  get listado {
    return _listado;
  }

  set listado(List<Detalleconcepto> listado) {
    this._listado = listado;
    notifyListeners();
  }
}

class Detalleconcepto {
  int idOperacionFinanciera;
  int idTipoConcepto;
  String tipoConcepto;
  double importe;
  String fecha;
  String numeroDocumento;

  Detalleconcepto({
    this.idOperacionFinanciera,
    this.idTipoConcepto,
    this.tipoConcepto,
    this.importe,
    this.fecha,
    this.numeroDocumento,
  });

════════ Exception caught by widgets library ═══════════════════════════════════
type 'List' is not a subtype of type 'Future>'

The relevant error-causing widget was
    CreateList


问:
QuickReport: keep Details Band and Child Band on one page
Environment: Delphi 2010, QuickReport 5.0.5

I have a report with 2 bands: Detail band and it's Child band.
Problem is sometimes they are splitted on different pages.

I would like to have detail band as a header for child and keep them on the same page always.

After some hours of studying I gave up.

UPDATE: The problem was in dynamically changed height of the child band. I solved it with analyzing of the height and ForceNewPage property.

Does anybody know a solution?

答:
Try using the detail band's LinkBand property.

If the child changes its size, you must calculate it on the parent's BeforePrint event.


问:
How to find first non zero value in a column?
in column A first value is 0, second is 0, third is 17, fourth is 0 and fifth is 32

in this case , first non zero value is 17. how to calculate it by formula

答:
Explanation for the above formula:

The inner Index function evaluates the values in the A1:A5 range to either TRUE or FALSE based on the specified condition, that is, not equal to 0. So 17 and 32 evaluate to TRUE, everything else to FALSE. The Match function returns the row number where the first instance of the specified condition TRUE is. This occurs on the 3rd row of the range, so Match evaluates to 3. Finally, the outer Index functions returns the value at row number 3 in the specified A1:A5 range, which is 17.


问:
Print values from HashMap
Currently, I am trying to write a method to locate the highest value product in my hashmap.

I am looking for a push in the right direction if that is possible. I appreciate any help that might be pointed my way. Thank you.

答:
Your print statement is the default format from the map entry. Change your print statement to something like this:</p>

```<code>println("${highestPricedProduct.key}\t${highestPricedProduct.value.first}\t${highestPricedProduct.value.second}")
</code>```

Title: Print values from HashMap

Body:
Your print statement is the default format from the map entry. Change your print statement to something like this:

println("${highestPricedProduct.key}\t${highestPricedProduct.value.first}\t${highestPricedProduct.value.second}")


问:
What is a receiver in JavaScript?
I am reading You Don't Know JS: ES6 & Beyond and found some confused wording like:

We declare a get(..) handler as a named method on the handler object (second argument to Proxy(..)), which receives a reference to the target object (obj), the key property name ("a"), and the self/receiver/proxy (pobj).

My question is, what does "receiver" mean above and where does its name come from?

It seems like if I have an object "a" with a member function "jump":

```<code>var a = { jump: function() { console.log('jump!'); } };
</code>```

If I run a.jump(); then "a" is the receiver.

Is that how it works?

For people who read the same book: when you come to the Proxy First, Proxy Last section, you can add one line in the code to get a more clear picture about the context in the "get" trap:

```<code>var handlers = {
    get(target, key, context) {
        console.log(greeter === context); //true, this line added
        return function() {
            context.speak(key + "!");
        };
    }
},
catchall = new Proxy({}, handlers),
var greeter = {
    speak(who = "someone") {
        console.log("hello", who);
    }
};

// setup `greeter` to fall back to `catchall`
Object.setPrototypeOf(greeter, catchall);

greeter.speak();                // hello someone
greeter.speak("world");       // hello world

greeter.everyone();             // hello everyone!
</code>```

As you can see, thanks to the naming of the third argument of the "get" trap above, "context", the receiver can vary according to lexical code -- greeter.everyone();. Please refer to Oriol's very detailed answer below for a better understanding.

答:
I spent some time trying to figure out exactly what this "receiver" could and would be used for when used with Reflect.get, and, perhaps unsuprisingly, it's all just as MDN explains:

receiver Optional

The value of this provided for the call to target if a getter is encountered. When used with Proxy, it can be an object that inherits from target.

Basically, as far as I could assess, the decisive role it plays with Reflect.get is when used to access getter properties. For instance, the Reflect.get call in the following snippet will return 2, and not undefined.

const obj = { get foo() { return this.bar; } };
Reflect.get(obj, "foo", { bar: 2 });
```
<p>The actual getter (<code>get foo()...</code>) is invoked with <code>{ bar: 2 }</code> as the "receiver". Without third argument to <code>Reflect.get</code>, the receiver is implied to be the object itself, naturally -- and since it does not have a <code>bar</code> property, <code>undefined</code> is returned. If it had defined a <code>bar</code> property, things are far simpler indeed:</p>
<pre class="lang-js prettyprint-override"><code>const obj = { bar: 1, get foo() { return this.bar } };
obj.foo; /// evaluates to 1
Reflect.get(obj, "foo"); /// evaluates to 1, equivalent to above
Reflect.get(obj, "foo", { bar: "soap" }) /// evaluates to, guess what, "soap"
</code>```

I don't think there is anything more than that to it, not with Reflect.get, anyway.

Title: What is a receiver in JavaScript?

Body:
I am reading You Don't Know JS: ES6 & Beyond and found some confused wording like:

We declare a get(..) handler as a named method on the handler object (second argument to Proxy(..)), which receives a reference to the target object (obj), the key property name ("a"), and the self/receiver/proxy (pobj).

My question is, what does "receiver" mean above and where does its name come from?

It seems like if I have an object "a" with a member function "jump":

var a = { jump: function() { console.log('jump!'); } };

If I run a.jump(); then "a" is the receiver.

Is that how it works?

For people who read the same book: when you come to the Proxy First, Proxy Last section, you can add one line in the code to get a more clear picture about the context in the "get" trap:

var handlers = {
    get(target, key, context) {
        console.log(greeter === context); //true, this line added
        return function() {
            context.speak(key + "!");
        };
    }
},
catchall = new Proxy({}, handlers),
var greeter = {
    speak(who = "someone") {
        console.log("hello", who);
    }
};

// setup `greeter` to fall back to `catchall`
Object.setPrototypeOf(greeter, catchall);

greeter.speak();                // hello someone
greeter.speak("world");       // hello world

greeter.everyone();             // hello everyone!

As you can see, thanks to the naming of the third argument of the "get" trap above, "context", the receiver can vary according to lexical code -- greeter.everyone();. Please refer to Oriol's very detailed answer below for a better understanding.

Body:
I spent some time trying to figure out exactly what this "receiver" could and would be used for when used with Reflect.get, and, perhaps unsuprisingly, it's all just as MDN explains:

receiver Optional

The value of this provided for the call to target if a getter is encountered. When used with Proxy, it can be an object that inherits from target.

Basically, as far as I could assess, the decisive role it plays with Reflect.get is when used to access getter properties. For instance, the Reflect.get call in the following snippet will return 2, and not undefined.

const obj = { get foo() { return this.bar; } };
Reflect.get(obj, "foo", { bar: 2 });

The actual getter (get foo()...) is invoked with { bar: 2 } as the "receiver". Without third argument to Reflect.get, the receiver is implied to be the object itself, naturally -- and since it does not have a bar property, undefined is returned. If it had defined a bar property, things are far simpler indeed:

const obj = { bar: 1, get foo() { return this.bar } };
obj.foo; /// evaluates to 1
Reflect.get(obj, "foo"); /// evaluates to 1, equivalent to above
Reflect.get(obj, "foo", { bar: "soap" }) /// evaluates to, guess what, "soap"

I don't think there is anything more than that to it, not with Reflect.get, anyway.


问:
Does every function get its own stack in c?
I recently learned about stacks, so I was experimenting to see what the stack size is and what happens when it overflows. I found out that on Unix the default stack size is 8 MiB, and that supports my findings since I cannot declare a string having size greater than or equal to 8 MiB in my main function. However, when I declare a variable in main() it affects other functions. For example:

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

void foo(void)
{
    long int size = 1024*1024*2;
    char str[size];
    str[size - 1] = 'a';
    printf("%c\n", str[size - 1]);
}

int main(int argc, char** argv)
{
    long int size = 1024*1024*6;
    char str[size];
    str[size - 1] = 'a';
    printf("%c\n", str[size - 1]);
    foo();
    return 0;
}
</code>```

This code results in segmentation fault but if I make the string size 5 MiB in main() then there is no segmentation fault. Does that mean my C program cannot allocate more than 8 MiB of RAM for local variables (of all functions)? If so, what IS the point of stacks?

答:
No, each function doesn't get its own independent stack space. There's only one stack in your program and there's an limited finite amount of stack space available to you.

How Stack works

This LIFO behavior is exactly what a function does when returning
to the function that called it.

Flow in the Stack

The caller pushes the return address onto the stack

When the called function finishes its execution, it pops the return
address off the call stack (this popped element is also known as
stack frame) and transfers control to that address.

If a called function calls on to yet another function, it will push
another return address onto the top of the same call stack, and
so on, with the information stacking up and unstacking as the
program dictates.

All of the above process happens in the same stack memory. Each function does have its own space in the stack but every function gets its space allocated  in the same stack. This is called the Global Call Stack of your program.
It is used to store local variables which are used inside the function.

However, dynamically allocated space is stored on the heap. Heap is used to store dynamic variables. It is a region of process’ memory. malloc(), calloc(), resize() all these inbuilt functions are generally used to store dynamic variables.

As for the stack overflow issue, the call stack size is limited. Only a certain amount of memory can be used. If many function calls happen, the stack space would eventually run out which would give you a stack overflow error which would most likely cause your program to crash.

If there are a lot of variables in your function or some variables which needs a huge amount of space in your program, then the stack space will eventually run out and it would cause a stack overflow. E.g. the following would probably give stack overflow in most cases and cause your program to crash:

```<code>int main() {
   int A[100000][100000];
}
</code>```

Hope this clears your doubt !

NOTE:

In an multi-threaded environment, each thread gets its own call stack space separately instead of having the same Global Call Stack. So, in an multi-threaded environment, the answer to your question will be YES.

Body:
I recently learned about stacks, so I was experimenting to see what the stack size is and what happens when it overflows. I found out that on Unix the default stack size is 8 MiB, and that supports my findings since I cannot declare a string having size greater than or equal to 8 MiB in my main function. However, when I declare a variable in main() it affects other functions. For example:

#include <stdio.h>

void foo(void)
{
    long int size = 1024*1024*2;
    char str[size];
    str[size - 1] = 'a';
    printf("%c\n", str[size - 1]);
}

int main(int argc, char** argv)
{
    long int size = 1024*1024*6;
    char str[size];
    str[size - 1] = 'a';
    printf("%c\n", str[size - 1]);
    foo();
    return 0;
}

This code results in segmentation fault but if I make the string size 5 MiB in main() then there is no segmentation fault. Does that mean my C program cannot allocate more than 8 MiB of RAM for local variables (of all functions)? If so, what IS the point of stacks?

Body:
No, each function doesn't get its own independent stack space. There's only one stack in your program and there's an limited finite amount of stack space available to you.

How Stack works

This LIFO behavior is exactly what a function does when returning
to the function that called it.

Flow in the Stack

The caller pushes the return address onto the stack

When the called function finishes its execution, it pops the return
address off the call stack (this popped element is also known as
stack frame) and transfers control to that address.

If a called function calls on to yet another function, it will push
another return address onto the top of the same call stack, and
so on, with the information stacking up and unstacking as the
program dictates.

All of the above process happens in the same stack memory. Each function does have its own space in the stack but every function gets its space allocated  in the same stack. This is called the Global Call Stack of your program.
It is used to store local variables which are used inside the function.

However, dynamically allocated space is stored on the heap. Heap is used to store dynamic variables. It is a region of process’ memory. malloc(), calloc(), resize() all these inbuilt functions are generally used to store dynamic variables.

As for the stack overflow issue, the call stack size is limited. Only a certain amount of memory can be used. If many function calls happen, the stack space would eventually run out which would give you a stack overflow error which would most likely cause your program to crash.

If there are a lot of variables in your function or some variables which needs a huge amount of space in your program, then the stack space will eventually run out and it would cause a stack overflow. E.g. the following would probably give stack overflow in most cases and cause your program to crash:

int main() {
   int A[100000][100000];
}

Hope this clears your doubt !

NOTE:

In an multi-threaded environment, each thread gets its own call stack space separately instead of having the same Global Call Stack. So, in an multi-threaded environment, the answer to your question will be YES.


问:
How to check if a "leave" member exists without testing existence of its parents
Imagine this code:

```<code>var obj = {};
obj.x = {};
obj.x.y = {};

if (obj.x.y.z) {
  //the test work, I know obj.x.z.z do not exist
}

if (obj.a.b) {
  //fail because "cannot read property 'b' of undefined
}
</code>```

The question is : How I can check the existence of a "leave" (if "b" exist, it must inside "a") without making the test of each its parents before ?

答:
Use to check if key exist or not.

var obj = {};
obj.x = {};
obj.x.y = {};

if (obj.x.y.z) {
  //the test work, I know obj.x.z.z do not exist
}

function isExist(arg){
   try{
      return arg();
   }catch(e){
      return false;
   }
}

console.log(isExist(()=>obj.x.y))
console.log(isExist(()=>obj.x.y.z))
console.log(isExist(()=>obj.a.b))```

Reference : Test for existence of nested JavaScript object key

Body:
Imagine this code:

var obj = {};
obj.x = {};
obj.x.y = {};

if (obj.x.y.z) {
  //the test work, I know obj.x.z.z do not exist
}

if (obj.a.b) {
  //fail because "cannot read property 'b' of undefined
}

The question is : How I can check the existence of a "leave" (if "b" exist, it must inside "a") without making the test of each its parents before ?

Body:
Use to check if key exist or not.

var obj = {};
obj.x = {};
obj.x.y = {};

if (obj.x.y.z) {
  //the test work, I know obj.x.z.z do not exist
}

function isExist(arg){
   try{
      return arg();
   }catch(e){
      return false;
   }
}

console.log(isExist(()=>obj.x.y))
console.log(isExist(()=>obj.x.y.z))
console.log(isExist(()=>obj.a.b))

Reference : Test for existence of nested JavaScript object key


问:
How to show total income and monthly income of a grouped column? (MySQL)
I have this table in my database:

I need a query that shows total cost, monthly totalcost, monthly count(roomId), total count(roomId), grouped by room ID.

I tried this query but the result wasn't like what I need

```<code>SELECT room_id, type, numberOfBeds,
       (SELECT SUM(total_cost)
         WHERE date_booked BETWEEN '".$dateFrom."' and '".$dateTo."') as monthlyIncome,
       SUM(total_cost) as totalIncome,
       COUNT(roomId) as totalReservations,
       (SELECT COUNT(roomId)
         WHERE date_booked BETWEEN '".$dateFrom."' and '".$dateTo."') as monthlyReservation
  FROM indvproj_rooms, indvproj_room_booking_details
 WHERE indvproj_rooms.room_id=indvproj_room_booking_details.roomId;
</code>```

答:
Question is not clear. Whats is difference between monthly and total cost when you are doing SUM??
Please check below query and results if it is same you needed.

```<code>SELECT
   *
FROM
   (
      SELECT
         roomId,
         SUM(total_cost) as monthly_cost,
         COUNT(roomId) as monthly_count
      FROM
         room
      group by
         roomId,
         YEAR(date_booked),
         MONTH(date_booked)
   )
   as r
   LEFT JOIN
      (
         SELECT
            roomId as rid,
            SUM(total_cost) as total_cost,
            COUNT(roomId) as total_count
         FROM
            room
         group by
            roomId
      )
      as t
      on r.roomId = t.rid
</code>```

https://www.db-fiddle.com/f/rEu6RzQTMdFBNS4QxtaAQR/0

Body:
I have this table in my database:

I need a query that shows total cost, monthly totalcost, monthly count(roomId), total count(roomId), grouped by room ID.

I tried this query but the result wasn't like what I need

SELECT room_id, type, numberOfBeds,
       (SELECT SUM(total_cost)
         WHERE date_booked BETWEEN '".$dateFrom."' and '".$dateTo."') as monthlyIncome,
       SUM(total_cost) as totalIncome,
       COUNT(roomId) as totalReservations,
       (SELECT COUNT(roomId)
         WHERE date_booked BETWEEN '".$dateFrom."' and '".$dateTo."') as monthlyReservation
  FROM indvproj_rooms, indvproj_room_booking_details
 WHERE indvproj_rooms.room_id=indvproj_room_booking_details.roomId;

Body:
Question is not clear. Whats is difference between monthly and total cost when you are doing SUM??
Please check below query and results if it is same you needed.

SELECT
   *
FROM
   (
      SELECT
         roomId,
         SUM(total_cost) as monthly_cost,
         COUNT(roomId) as monthly_count
      FROM
         room
      group by
         roomId,
         YEAR(date_booked),
         MONTH(date_booked)
   )
   as r
   LEFT JOIN
      (
         SELECT
            roomId as rid,
            SUM(total_cost) as total_cost,
            COUNT(roomId) as total_count
         FROM
            room
         group by
            roomId
      )
      as t
      on r.roomId = t.rid

https://www.db-fiddle.com/f/rEu6RzQTMdFBNS4QxtaAQR/0


答:
The "stack" is one, shared space in memory, and true to its name, every nested function invocation "pushes" a new "frame" (set of space for local variables) onto that shared stack. Yes, the total size of the stack's space in memory is shared between all functions which are (currently) executing, and if the total used space during the run of you program exceeds what the OS has set aside for it, you will cause an (ahem) "stack overflow" crash.

The point is to provide work space for each function's invocation. Typically, the amount of space used by any particular function on the stack is quite small-- perhaps some integers or a couple smallish arrays, etc. Think tens or hundreds of bytes, not usually kilobytes or certainly megabytes. This is mostly just idiomatic and you get used to what makes sense to have on the stack and what doesn't when you've worked with enough code of your own and others'. It would be exceptionally unusual in production code to have something megabytes large as an actual local variable.

In practice, the primary cause of stack overflow errors in the real world is accidental infinite recursion-- when you end up calling through into the same functions over and over without a recursive base case. Those stack frames may each be small, but if the call chain is unbounded eventually you'll overflow.

When you want to use actual larger pieces of memory, large string buffers, etc, you'll typically allocate them from a different shared chunk of memory referred to as "the heap". You can allocate (with malloc and its cousins) what you need and then free that when done. The heap's memory space is global to your program, and is not constrained or related to particular function invocations.

Title: Does every function get its own stack in c?