问:
why dynamic initialization occur before static initialization in gcc

#include <iostream>
struct NonConstant{
    NonConstant(int v):v_(v){
        std::cout<<"NonConstant\n";
    }
    int v_;
};

struct Constant{
    constexpr Constant(int v):v_(v){
        if(v_==0){
         std::cout<<"Constant\n";
        }
    }
    int v_;
};

NonConstant a = 2; //#1
Constant b = 0;   //#2

int main(){
}
```

<p>The outcome will be:</p>

```NonConstant
Constant
```

I'm confused about this outcome, Becuase, According to the standard rules, #1 is not static initialization, #2 is, because of these:

A constant initializer for a variable or temporary object o is an initializer whose full-expression is a constant expression, except that if o is an object, such an initializer may also invoke constexpr constructors for o and its subobjects even if those objects are of non-literal class types.

  Constant initialization is performed if a variable or temporary object with static or thread storage duration is initialized by a constant initializer for the entity.If constant initialization is not performed, a variable with static storage duration or thread storage duration is zero-initialized. Together, zero-initialization and constant initialization are called static initialization;all other initialization is dynamic initialization. All static initialization strongly happens before ([intro.races]) any dynamic initialization.

The constructor of class NonConstant is not specified by constexpr, the initialization of NonConstant a = 2; will invoke a non-constexpr constructor for object a, hence, the initialization for #1 is not static initialization, so it's a dynamic initialization. By contrast, the initialization of Constant b = 0; is a static initialization since the constructor be invoked is a constexpr constructor. And the rules say that All static initialization strongly happens before  any dynamic initialization. So, why the outcome implies that the evaluation of #1 occured before that of #2? If I miss something, please correct me.

UPDATE:

In the following comments of this question, someone says that except the constructor's class can be a non-literal type, the constexpr constructor  in any respects must be a valid core constant expression, that is,the invocation of std::cout will make the constexpr constructor not be a core constant expression. However,I have found another interpretation in cppreference, that is:

Constant initialization is performed after (until C++14)instead of (since C++14) zero initialization of the static and thread-local objects and before all other initialization. Only the following variables are constant initialized:

[...]

Static or thread-local object of class type that is initialized by a constructor call, if the constructor is constexpr and all constructor arguments (including implicit conversions) are constant expressions, and if the initializers in the constructor's initializer list and the brace-or-equal initializers of the class members only contain constant expressions.

It does not say that the constexpr constructor must be a core constant expression. As long as the constructor be invoked satisfies that it's qualified by constexpr and it's arguments all must be constant expressions and member-initializer must be constant expressions.  So, #2 is indeed a constant initialization, because the argument 0 is a constant expression and the selected constructor qualified by specifier constexpr and the member-initializer obey these rules mentioned in expr.const.

答:
b has dynamic initialization, not static initialization.

As already explained by your quote of [basic.start.static]/2, b has static initialization only if the full-expression of its initializer, which is the execution of the Constant(int) constructor, is a constant expression.

In [expr.const]/2, we read:

An expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine, would evaluate one of the following expressions:

...

an invocation of a function other than a constexpr constructor for a literal class, a constexpr function, or an implicit invocation of a trivial destructor ([class.dtor]) [ Note: Overload resolution is applied as usual  —  end note ] ;

...

Here the evaluation of the constructor "following the rules of the abstract machine" includes the constructor body. And since the initializer is 0, that evaluation would invoke std::operator<<(std::ostream&, const char*), which is not constexpr. So the initializer's full expression is not a core constant expression and is not a constant expression.

And of course, though it's not the strictly technical definition, the entire point of "constant expression" is to define when we're guaranteed that the compiler can deal with something at compile time. And writing to the program's standard output certainly won't happen at compile time.

cppreference.com is a good resource that tries to be as accurate as possible, but it does not substitute for the authority of the actual Standard. That quote about constant initialization using a class constructor is incorrect for C++14 and C++17. I suspect it's actually left over from C++11, in which the body of a constexpr constructor was not allowed to evaluate any function calls at all, and [expr.const] similarly described requirements on uses of constexpr constructors within a core constant expression in terms of the member initializers.

Body:
#include <iostream>
struct NonConstant{
    NonConstant(int v):v_(v){
        std::cout<<"NonConstant\n";
    }
    int v_;
};

struct Constant{
    constexpr Constant(int v):v_(v){
        if(v_==0){
         std::cout<<"Constant\n";
        }
    }
    int v_;
};

NonConstant a = 2; //#1
Constant b = 0;   //#2

int main(){
}

The outcome will be:

NonConstant
Constant

I'm confused about this outcome, Becuase, According to the standard rules, #1 is not static initialization, #2 is, because of these:

A constant initializer for a variable or temporary object o is an initializer whose full-expression is a constant expression, except that if o is an object, such an initializer may also invoke constexpr constructors for o and its subobjects even if those objects are of non-literal class types.

  Constant initialization is performed if a variable or temporary object with static or thread storage duration is initialized by a constant initializer for the entity.If constant initialization is not performed, a variable with static storage duration or thread storage duration is zero-initialized. Together, zero-initialization and constant initialization are called static initialization;all other initialization is dynamic initialization. All static initialization strongly happens before ([intro.races]) any dynamic initialization.

The constructor of class NonConstant is not specified by constexpr, the initialization of NonConstant a = 2; will invoke a non-constexpr constructor for object a, hence, the initialization for #1 is not static initialization, so it's a dynamic initialization. By contrast, the initialization of Constant b = 0; is a static initialization since the constructor be invoked is a constexpr constructor. And the rules say that All static initialization strongly happens before  any dynamic initialization. So, why the outcome implies that the evaluation of #1 occured before that of #2? If I miss something, please correct me.

UPDATE:

In the following comments of this question, someone says that except the constructor's class can be a non-literal type, the constexpr constructor  in any respects must be a valid core constant expression, that is,the invocation of std::cout will make the constexpr constructor not be a core constant expression. However,I have found another interpretation in cppreference, that is:

Constant initialization is performed after (until C++14)instead of (since C++14) zero initialization of the static and thread-local objects and before all other initialization. Only the following variables are constant initialized:

[...]

Static or thread-local object of class type that is initialized by a constructor call, if the constructor is constexpr and all constructor arguments (including implicit conversions) are constant expressions, and if the initializers in the constructor's initializer list and the brace-or-equal initializers of the class members only contain constant expressions.

It does not say that the constexpr constructor must be a core constant expression. As long as the constructor be invoked satisfies that it's qualified by constexpr and it's arguments all must be constant expressions and member-initializer must be constant expressions.  So, #2 is indeed a constant initialization, because the argument 0 is a constant expression and the selected constructor qualified by specifier constexpr and the member-initializer obey these rules mentioned in expr.const.


来源: stackexchange

问:
Jquery: How can disabled/enabled option dynamically
Can someone help me with the code that I need to activate / deactivate some option?
I have 4 different selects.
First of all I need that jquery check that there are no values greater than the variable stock (I think this is done).
After this I need that when one select changes, check the value of the other selects options and deactivate them if the value is greater than the available stock.
I need to dynamically handle the content of the selects and they are activated / deactivated according to the stock.

I have this code, It works "well" with the first select, but when I change the second select it affects the first one.
I don't know if I explained correctly, but in the jsfiddle/Code I think the idea is better explained
https://jsfiddle.net/apejqfsg/17/

HTML

<select id="select1" class="stock">
  <option value="0">0</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
  <option value="6">6</option>
  <option value="7">7</option>
  <option value="8">8</option>
  <option value="9">9</option>
  <option value="10">10</option>
</select>
<select id="select2" class="stock">
  <option value="0">0</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
  <option value="6">6</option>
  <option value="7">7</option>
  <option value="8">8</option>
  <option value="9">9</option>
  <option value="10">10</option>
</select>
<select id="select3" class="stock">
  <option value="0">0</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
  <option value="6">6</option>
  <option value="7">7</option>
  <option value="8">8</option>
  <option value="9">9</option>
  <option value="10">10</option>
</select>
<select id="select4" class="stock">
  <option value="0">0</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
  <option value="6">6</option>
  <option value="7">7</option>
  <option value="8">8</option>
  <option value="9">9</option>
  <option value="10">10</option>
</select>

Max Stock: 8

```

<p><strong>JQUERY</strong></p>

<pre class="lang-js prettyprint-override"><code>$(document).ready(function () {
  var previous;
  var maxStock = 8;
  $(".stock option")
    .filter(function () {
      return $(this).val() > maxStock;
    })
    .prop("disabled", true);

  $(".stock")
    .focus(function () {
      previous = this.value;
      $(".stock option").each(function () {});
    })
    .change(function () {
      maxStock = maxStock + (previous - this.value);
      var value = this.value;
      var id = $(this).attr("id");
      $(".stock option").each(function () {
        var idParent = $(this).parent().attr("id");
        if (id != idParent) {
          if (this.value > maxStock) {
            this.disabled = true;
          }
        }
      });
      previous = this.value;
      $("#disponibles").html(maxStock);
    });
});
</code>```

答:
probably best to perform disabling of options during focus rather than on change.

try this:

```<code>$(document).ready(function(){
    ...
    $(".stock").focus(function () {
        var otherMaxStock=maxStock;
        var currId=$(this).attr('id');
        $( ".stock" ).each(function( index ) {
            if (currId!=$(this).attr('id'))
                otherMaxStock-=$(this).val();
        });
        $(this).find("option:gt("+otherMaxStock+")").prop( "disabled", true );
    }).change(function() {
        /*
        maxStock=maxStock+(previous-this.value);
        ...
        $("#disponibles").html(maxStock); */
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Can someone help me with the code that I need to activate / deactivate some option?
I have 4 different selects.
First of all I need that jquery check that there are no values greater than the variable stock (I think this is done).
After this I need that when one select changes, check the value of the other selects options and deactivate them if the value is greater than the available stock.
I need to dynamically handle the content of the selects and they are activated / deactivated according to the stock.

I have this code, It works "well" with the first select, but when I change the second select it affects the first one.
I don't know if I explained correctly, but in the jsfiddle/Code I think the idea is better explained
https://jsfiddle.net/apejqfsg/17/

HTML

<select id="select1" class="stock">
  <option value="0">0</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
  <option value="6">6</option>
  <option value="7">7</option>
  <option value="8">8</option>
  <option value="9">9</option>
  <option value="10">10</option>
</select>
<select id="select2" class="stock">
  <option value="0">0</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
  <option value="6">6</option>
  <option value="7">7</option>
  <option value="8">8</option>
  <option value="9">9</option>
  <option value="10">10</option>
</select>
<select id="select3" class="stock">
  <option value="0">0</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
  <option value="6">6</option>
  <option value="7">7</option>
  <option value="8">8</option>
  <option value="9">9</option>
  <option value="10">10</option>
</select>
<select id="select4" class="stock">
  <option value="0">0</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
  <option value="6">6</option>
  <option value="7">7</option>
  <option value="8">8</option>
  <option value="9">9</option>
  <option value="10">10</option>
</select>

Max Stock: 8

JQUERY

$(document).ready(function () {
  var previous;
  var maxStock = 8;
  $(".stock option")
    .filter(function () {
      return $(this).val() > maxStock;
    })
    .prop("disabled", true);

  $(".stock")
    .focus(function () {
      previous = this.value;
      $(".stock option").each(function () {});
    })
    .change(function () {
      maxStock = maxStock + (previous - this.value);
      var value = this.value;
      var id = $(this).attr("id");
      $(".stock option").each(function () {
        var idParent = $(this).parent().attr("id");
        if (id != idParent) {
          if (this.value > maxStock) {
            this.disabled = true;
          }
        }
      });
      previous = this.value;
      $("#disponibles").html(maxStock);
    });
});

Body:
probably best to perform disabling of options during focus rather than on change.

try this:

$(document).ready(function(){
    ...
    $(".stock").focus(function () {
        var otherMaxStock=maxStock;
        var currId=$(this).attr('id');
        $( ".stock" ).each(function( index ) {
            if (currId!=$(this).attr('id'))
                otherMaxStock-=$(this).val();
        });
        $(this).find("option:gt("+otherMaxStock+")").prop( "disabled", true );
    }).change(function() {
        /*
        maxStock=maxStock+(previous-this.value);
        ...
        $("#disponibles").html(maxStock); */


问:
asp.net event handler for table click is called twice
I have a table with some column in a asp.net mvc core project.

My view file looks like this

```<code>    <h1>Items</h1>
<div class="panel-body">
    <table class="table table-bordered table-responsive table-hover">
        <thead>
            <tr>
                <th>Id</th>
                <th>Title</th>

                <th>Rating</th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model.Items)
            {
                <tr onclick="location.href='@(Url.Action("ShowItemDetails", "Item", new {Id = item.FilmId}))'">
                    <td>@item.Id</td>
                    <td>@item.Title</td>

                    <td>@item.Rating</td>
                    <td>@Html.ActionLink("Edit", "Edit", "Show", new { id = item.Id })  | @Html.ActionLink("Rate this", "RateItem", new { id = item.Id }) </td>

                </tr>
            }
        </tbody>
    </table>
</div>
</code>```

The problem is that when i click on a row, the controller method ShowItemDetails is called twice(!).
I can not see from the code above why this happens. Also, clicking on Edit or Rate this calls first ShowItemDetails and then immediately  Edit or RateItem method in controller. Any suggestion how this can be solved?

答:
Clicking on Edit or Rate this calls first ShowItemDetails and then immediately Edit or RateItem method because Edit is under a table row and on tablerow, you have called showitemdetails action.so, when you click on td , it gets first executed row action then td action.that's why it get called twice.

I hope,  you want to show details and edit options with data of table and Edit is controller name.

Tweak your table code like below:

```<code><tbody>
@foreach (var item in Model.Items)
  {
    <tr>
        <td>@Html.ActionLink("Show Details","ShowItemDetails","Item",new {Id = item.FilmId})</td>
        <td>@item.Id</td>
        <td>@item.Title</td>
        <td>@item.Rating</td>
        <td>@Html.ActionLink("Edit", "Edit", "Show", new { id = item.Id })  | @Html.ActionLink("Rate this", "RateItem", new { id = item.Id }) </td>
    </tr>
  }
</tbody>
</code>```

Body:
I have a table with some column in a asp.net mvc core project.

My view file looks like this

Items

                Id
                Title

                Rating

            @foreach (var item in Model.Items)
            {

                    @item.Id
                    @item.Title

                    @item.Rating
                    @Html.ActionLink("Edit", "Edit", "Show", new { id = item.Id })  | @Html.ActionLink("Rate this", "RateItem", new { id = item.Id })

            }

The problem is that when i click on a row, the controller method ShowItemDetails is called twice(!).
I can not see from the code above why this happens. Also, clicking on Edit or Rate this calls first ShowItemDetails and then immediately  Edit or RateItem method in controller. Any suggestion how this can be solved?

Body:
Clicking on Edit or Rate this calls first ShowItemDetails and then immediately Edit or RateItem method because Edit is under a table row and on tablerow, you have called showitemdetails action.so, when you click on td , it gets first executed row action then td action.that's why it get called twice.

I hope,  you want to show details and edit options with data of table and Edit is controller name.

Tweak your table code like below:

<tbody>
@foreach (var item in Model.Items)
  {
    <tr>
        <td>@Html.ActionLink("Show Details","ShowItemDetails","Item",new {Id = item.FilmId})</td>
        <td>@item.Id</td>
        <td>@item.Title</td>
        <td>@item.Rating</td>
        <td>@Html.ActionLink("Edit", "Edit", "Show", new { id = item.Id })  | @Html.ActionLink("Rate this", "RateItem", new { id = item.Id }) </td>
    </tr>
  }
</tbody>


问:
How to set selectedIndex of select element using display text?
How to set selectedIndex of select element using display text as reference?

Example:

```<code><input id="AnimalToFind" type="text" />
<select id="Animals">
    <option value="0">Chicken</option>
    <option value="1">Crocodile</option>
    <option value="2">Monkey</option>
</select>
<input type="button" onclick="SelectAnimal()" />

<script type="text/javascript">
    function SelectAnimal()
    {
        //Set selected option of Animals based on AnimalToFind value...
    }
 </script>
</code>```

Is there any other way to do this without a loop? You know, I'm thinking of a built-in JavaScript code or something. Also, I don't use jQuery...

答:
Try this:</p>

```<code>function SelectAnimal() {
    var sel = document.getElementById('Animals');
    var val = document.getElementById('AnimalToFind').value;
    for(var i = 0, j = sel.options.length; i < j; ++i) {
        if(sel.options[i].innerHTML === val) {
           sel.selectedIndex = i;
           break;
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How to set selectedIndex of select element using display text as reference?

Example:

<input id="AnimalToFind" type="text" />
<select id="Animals">
    <option value="0">Chicken</option>
    <option value="1">Crocodile</option>
    <option value="2">Monkey</option>
</select>
<input type="button" onclick="SelectAnimal()" />

Is there any other way to do this without a loop? You know, I'm thinking of a built-in JavaScript code or something. Also, I don't use jQuery...

Body:
Try this:

function SelectAnimal() {
    var sel = document.getElementById('Animals');
    var val = document.getElementById('AnimalToFind').value;
    for(var i = 0, j = sel.options.length; i < j; ++i) {
        if(sel.options[i].innerHTML === val) {
           sel.selectedIndex = i;
           break;
        }
    }
}


问:
Unable to read structures properly from binary
So my program creates an 2d-dynamic array of structures, reads these structures from a binary file, changes the information in the structures and writes them in the same file. The problem is, that it does not read the information from the file properly. For example, I expect the info from ptr[0][0].Flat_IDto be 101. But on the console it prints a random number, say10948144, and this jeopardizes my entire program. I tried to change the way it reads, but to no effect.
Here is my main():

```<code>#include "Header.h"

int main()
{
    while(1)
    {
        printf("Hello world!\n");
        unsigned int floors=0, flats_per_floor=0;
        S_Apartament Flats;
        char FileName[50];
        printf("0. Exit program.\n");
        printf("1. Enter a file name.\n");
        printf("Please, choose a command.\n");
        unsigned short choice;
        scanf("%hu", &choice);
        if(choice == 0)
        {
           break;
        }
        else
        {
            printf("Enter file name in the following format 'Name.bin' :");
            scanf("%s", FileName);
        }
        S_Apartament **ptr = memalloc(floors, flats_per_floor, Flats, FileName);
        printf("%u",ptr[0][0].Flat_ID);
        while(1)
        {
            choice = menu();
        if(choice==0)
        {
            break;
        }
        switch(choice)
        {
            case 1:
                enterNewResidents(ptr, floors, flats_per_floor);
                break;
            case 2:
                calculateTax(ptr, floors, flats_per_floor);
                break;
            case 3:
                Elevator(ptr, floors, flats_per_floor);
                break;
            case 4:
                emptyApartment(ptr, floors, flats_per_floor);
                break;
            default:
                printf("Invalid command\n");
                break;
        }
        writeInfo(ptr,floors,flats_per_floor, FileName);
        free(ptr);
        }
    }
    printf("Program exited successfully. Have a nice day");
    return 0;
}
</code>```

My header file:

```<code>#ifndef HEADER_H_INCLUDED
#define HEADER_H_INCLUDED
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
   unsigned int Flat_ID;
   unsigned short count_Rooms;
   unsigned short count_Adults;
   unsigned short count_Children;
   char Family_Surname[20];
   char Date[10];
   float rent;
}S_Apartament;
unsigned short menu();
S_Apartament** memalloc(unsigned int floors, unsigned int flats_per_floor, S_Apartament Apartment, char FileName[50]);
void enterNewResidents(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor);
void calculateTax(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor);
void emptyApartment(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor);
void Elevator(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor);
void writeInfo(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor, char FileName[50]);

#endif // HEADER_H_INCLUDED
</code>```

And my source file:

```<code>#include "Header.h"

unsigned short menu()
{
    unsigned short choice=0;
    printf("Welcome, to the smart House manager program! Here is a list of the available commands.\n");
    printf("1. Enter new residents.\n");
    printf("2. Calculate month tax.\n");
    printf("3. Set elevator\n");
    printf("4. Empty an apartment\n");
    printf("0. Exit the program\n");
    printf("Please choose a command:\n");
    scanf("%hu",&choice);
    return choice;
}
S_Apartament** memalloc(unsigned int floors, unsigned int flats_per_floor, S_Apartament Apartment, char FileName[50])
{
    FILE *f;
        f = fopen(FileName,"rb");
        if(f==NULL)
        {
            printf("Error opening file, or no such file.");
            fclose(f);
            exit(1);
        }
        fread(&floors,sizeof(unsigned),1,f);
        fread(&flats_per_floor,sizeof(unsigned),1,f);
        fclose(f);
        S_Apartament **arr = (S_Apartament **)malloc(sizeof(S_Apartament*) * floors);
        for (int i = 0; i <  floors; i++)
        {
            arr[i] = (S_Apartament *)malloc(sizeof(S_Apartament)*flats_per_floor);
            printf("Here");
        }
        for(int i = 0; i <  floors; i++)
        {
            for(int j = 0; j < flats_per_floor; j++)
            {

                fread(&Apartment,sizeof(S_Apartament),1,f);
                arr[i][j]=Apartment;
            }
        }
        fclose(f);
        return arr;
}
void enterNewResidents(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor)
{
    unsigned short a = 0, b = 0;
    printf("Enter the floor, where you wish to accommodate the new residents.\n");
    scanf("%hu", &a);
    printf("Good, now the flat.\n");
    scanf("%hu", &b);
    if((a > floors) || (b > flats_per_floor))
    {
        printf("Invalid coordinates.");
    }
    if(ptr[a-1][b-1].count_Adults==0)
    {
        printf("The apartment is free to use. Enter the following data:\n");
        printf("Enter the number of adults\n");
        scanf("%hu", &(ptr[a-1][b-1].count_Adults));
        printf("Enter the number of children\n");
        scanf("%hu", &(ptr[a-1][b-1].count_Children));
        printf("Enter the name of the Family\n");
        scanf("%s", ptr[a-1][b-1].Family_Surname);
        printf("Date of entry:\n");
        scanf("%s", ptr[a-1][b-1].Date);
        printf("Enter the rent\n");
        scanf("%f", &(ptr[a-1][b-1].rent));
    }
    else
    {
       printf("The apartment is occupied. Please, choose another one.\n");
    }

}
void calculateTax(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor)
{
    int Tax = 0;
    for(int i=0; i<floors; i++)
    {
        for(int j=0; i<flats_per_floor; j++)
        {
            if( (i==0) || (i==1) )
            {
                Tax = Tax + (3*ptr[i][j].count_Adults) + (1*ptr[i][j].count_Children);
            }
            else
            {
                Tax = Tax + (5*ptr[i][j].count_Adults) + (3*ptr[i][j].count_Children);
            }
        }
    }
    printf("Tax is: %d \n", Tax);
}
void Elevator(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor)
{
    unsigned short Elevator_location = 1;
    unsigned number_of_residents = 0;
    unsigned max_amount = 0;
    for(int i = 1; i < floors - 1; i++)
    {
        for(int j = 0; j<flats_per_floor; j++)
        {
            number_of_residents = number_of_residents + ptr[i][j].count_Adults + ptr[i][j].count_Children + ptr[i-1][j].count_Adults + ptr[i-1][j].count_Children + ptr[i+1][j].count_Adults + ptr[i+1][j].count_Children;
        }
        if(number_of_residents >= max_amount)
        {
            max_amount = number_of_residents;
            number_of_residents = 0;
            Elevator_location = i + 1;
        }
        else
        {
            number_of_residents = 0;
        }
    }
    printf("The elevator's default floor is to be set to ");
    if(Elevator_location == 2)
    {
        printf("%hu nd floor.\n", Elevator_location);
    }
    else if(Elevator_location == 3)
    {
        printf("%hu rd floor.\n", Elevator_location);
    }
    else
    {
        printf("%hu th floor.\n", Elevator_location);
    }
}
void emptyApartment(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor)
{
    unsigned short Entered_number = 0;
    int i = 0, j = 0;
    printf("Enter the number of the apartment you wish to empty:\n");
    scanf("%hu", &Entered_number);
    for(i=0; i<floors; i++)
    {
        for(j=0; j<flats_per_floor; j++)
        {
            if(Entered_number == ptr[i][j].Flat_ID)
            {
               ptr[i][j].count_Adults = 0;
               ptr[i][j].count_Children = 0;
               ptr[i][j].Family_Surname[0] = '\0';
               ptr[i][j].rent = 0.00;
               printf("Apartment is empty");
               break;
            }
        }
        if(Entered_number == ptr[i][j].Flat_ID)
        {
            printf("TEST");
            break;
        }
        else if(i == (floors - 1))
        {
            printf("No such apartment");
        }
    }
}
void writeInfo(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor, char FileName[50])
{
    FILE *fp;
    fp = fopen(FileName,"wb");
    if(fp==NULL)
    {
        printf("Error opening file");
        fclose(fp);
        exit(2);
    }
    fwrite(&floors,sizeof(unsigned),1,fp);
    fwrite(&flats_per_floor,sizeof(unsigned),1,fp);
    for(int i = 0; i <  floors; i++)
            {
                for(int j = 0; j < flats_per_floor; j++)
                {
                    fwrite(&ptr[i][j],sizeof(S_Apartament),1,fp);
                }
            }
    fclose(fp);
}
</code>```

I can think of no other way to fix this. Any help would be appretiated. Sorry for the huge amount of code.

答:
In your memalloc and these lines you close the file

```<code> fread(&floors,sizeof(unsigned),1,f);
 fread(&flats_per_floor,sizeof(unsigned),1,f);
 fclose(f);
</code>```

but later in your loop you try to read from it, and a few lines after this you close it again

```<code>for(int j = 0; j < flats_per_floor; j++)
{
   fread(&Apartment,sizeof(S_Apartament),1,f);
   arr[i][j]=Apartment;
}
</code>```

Try removing the first fclose call.

Body:
So my program creates an 2d-dynamic array of structures, reads these structures from a binary file, changes the information in the structures and writes them in the same file. The problem is, that it does not read the information from the file properly. For example, I expect the info from ptr[0][0].Flat_IDto be 101. But on the console it prints a random number, say10948144, and this jeopardizes my entire program. I tried to change the way it reads, but to no effect.
Here is my main():

#include "Header.h"

int main()
{
    while(1)
    {
        printf("Hello world!\n");
        unsigned int floors=0, flats_per_floor=0;
        S_Apartament Flats;
        char FileName[50];
        printf("0. Exit program.\n");
        printf("1. Enter a file name.\n");
        printf("Please, choose a command.\n");
        unsigned short choice;
        scanf("%hu", &choice);
        if(choice == 0)
        {
           break;
        }
        else
        {
            printf("Enter file name in the following format 'Name.bin' :");
            scanf("%s", FileName);
        }
        S_Apartament **ptr = memalloc(floors, flats_per_floor, Flats, FileName);
        printf("%u",ptr[0][0].Flat_ID);
        while(1)
        {
            choice = menu();
        if(choice==0)
        {
            break;
        }
        switch(choice)
        {
            case 1:
                enterNewResidents(ptr, floors, flats_per_floor);
                break;
            case 2:
                calculateTax(ptr, floors, flats_per_floor);
                break;
            case 3:
                Elevator(ptr, floors, flats_per_floor);
                break;
            case 4:
                emptyApartment(ptr, floors, flats_per_floor);
                break;
            default:
                printf("Invalid command\n");
                break;
        }
        writeInfo(ptr,floors,flats_per_floor, FileName);
        free(ptr);
        }
    }
    printf("Program exited successfully. Have a nice day");
    return 0;
}

My header file:

#ifndef HEADER_H_INCLUDED
#define HEADER_H_INCLUDED
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
   unsigned int Flat_ID;
   unsigned short count_Rooms;
   unsigned short count_Adults;
   unsigned short count_Children;
   char Family_Surname[20];
   char Date[10];
   float rent;
}S_Apartament;
unsigned short menu();
S_Apartament** memalloc(unsigned int floors, unsigned int flats_per_floor, S_Apartament Apartment, char FileName[50]);
void enterNewResidents(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor);
void calculateTax(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor);
void emptyApartment(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor);
void Elevator(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor);
void writeInfo(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor, char FileName[50]);

#endif // HEADER_H_INCLUDED

And my source file:

#include "Header.h"

unsigned short menu()
{
    unsigned short choice=0;
    printf("Welcome, to the smart House manager program! Here is a list of the available commands.\n");
    printf("1. Enter new residents.\n");
    printf("2. Calculate month tax.\n");
    printf("3. Set elevator\n");
    printf("4. Empty an apartment\n");
    printf("0. Exit the program\n");
    printf("Please choose a command:\n");
    scanf("%hu",&choice);
    return choice;
}
S_Apartament** memalloc(unsigned int floors, unsigned int flats_per_floor, S_Apartament Apartment, char FileName[50])
{
    FILE *f;
        f = fopen(FileName,"rb");
        if(f==NULL)
        {
            printf("Error opening file, or no such file.");
            fclose(f);
            exit(1);
        }
        fread(&floors,sizeof(unsigned),1,f);
        fread(&flats_per_floor,sizeof(unsigned),1,f);
        fclose(f);
        S_Apartament **arr = (S_Apartament **)malloc(sizeof(S_Apartament*) * floors);
        for (int i = 0; i <  floors; i++)
        {
            arr[i] = (S_Apartament *)malloc(sizeof(S_Apartament)*flats_per_floor);
            printf("Here");
        }
        for(int i = 0; i <  floors; i++)
        {
            for(int j = 0; j < flats_per_floor; j++)
            {

                fread(&Apartment,sizeof(S_Apartament),1,f);
                arr[i][j]=Apartment;
            }
        }
        fclose(f);
        return arr;
}
void enterNewResidents(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor)
{
    unsigned short a = 0, b = 0;
    printf("Enter the floor, where you wish to accommodate the new residents.\n");
    scanf("%hu", &a);
    printf("Good, now the flat.\n");
    scanf("%hu", &b);
    if((a > floors) || (b > flats_per_floor))
    {
        printf("Invalid coordinates.");
    }
    if(ptr[a-1][b-1].count_Adults==0)
    {
        printf("The apartment is free to use. Enter the following data:\n");
        printf("Enter the number of adults\n");
        scanf("%hu", &(ptr[a-1][b-1].count_Adults));
        printf("Enter the number of children\n");
        scanf("%hu", &(ptr[a-1][b-1].count_Children));
        printf("Enter the name of the Family\n");
        scanf("%s", ptr[a-1][b-1].Family_Surname);
        printf("Date of entry:\n");
        scanf("%s", ptr[a-1][b-1].Date);
        printf("Enter the rent\n");
        scanf("%f", &(ptr[a-1][b-1].rent));
    }
    else
    {
       printf("The apartment is occupied. Please, choose another one.\n");
    }

}
void calculateTax(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor)
{
    int Tax = 0;
    for(int i=0; i<floors; i++)
    {
        for(int j=0; i<flats_per_floor; j++)
        {
            if( (i==0) || (i==1) )
            {
                Tax = Tax + (3*ptr[i][j].count_Adults) + (1*ptr[i][j].count_Children);
            }
            else
            {
                Tax = Tax + (5*ptr[i][j].count_Adults) + (3*ptr[i][j].count_Children);
            }
        }
    }
    printf("Tax is: %d \n", Tax);
}
void Elevator(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor)
{
    unsigned short Elevator_location = 1;
    unsigned number_of_residents = 0;
    unsigned max_amount = 0;
    for(int i = 1; i < floors - 1; i++)
    {
        for(int j = 0; j<flats_per_floor; j++)
        {
            number_of_residents = number_of_residents + ptr[i][j].count_Adults + ptr[i][j].count_Children + ptr[i-1][j].count_Adults + ptr[i-1][j].count_Children + ptr[i+1][j].count_Adults + ptr[i+1][j].count_Children;
        }
        if(number_of_residents >= max_amount)
        {
            max_amount = number_of_residents;
            number_of_residents = 0;
            Elevator_location = i + 1;
        }
        else
        {
            number_of_residents = 0;
        }
    }
    printf("The elevator's default floor is to be set to ");
    if(Elevator_location == 2)
    {
        printf("%hu nd floor.\n", Elevator_location);
    }
    else if(Elevator_location == 3)
    {
        printf("%hu rd floor.\n", Elevator_location);
    }
    else
    {
        printf("%hu th floor.\n", Elevator_location);
    }
}
void emptyApartment(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor)
{
    unsigned short Entered_number = 0;
    int i = 0, j = 0;
    printf("Enter the number of the apartment you wish to empty:\n");
    scanf("%hu", &Entered_number);
    for(i=0; i<floors; i++)
    {
        for(j=0; j<flats_per_floor; j++)
        {
            if(Entered_number == ptr[i][j].Flat_ID)
            {
               ptr[i][j].count_Adults = 0;
               ptr[i][j].count_Children = 0;
               ptr[i][j].Family_Surname[0] = '\0';
               ptr[i][j].rent = 0.00;
               printf("Apartment is empty");
               break;
            }
        }
        if(Entered_number == ptr[i][j].Flat_ID)
        {
            printf("TEST");
            break;
        }
        else if(i == (floors - 1))
        {
            printf("No such apartment");
        }
    }
}
void writeInfo(S_Apartament **ptr, unsigned floors, unsigned flats_per_floor, char FileName[50])
{
    FILE *fp;
    fp = fopen(FileName,"wb");
    if(fp==NULL)
    {
        printf("Error opening file");
        fclose(fp);
        exit(2);
    }
    fwrite(&floors,sizeof(unsigned),1,fp);
    fwrite(&flats_per_floor,sizeof(unsigned),1,fp);
    for(int i = 0; i <  floors; i++)
            {
                for(int j = 0; j < flats_per_floor; j++)
                {
                    fwrite(&ptr[i][j],sizeof(S_Apartament),1,fp);
                }
            }
    fclose(fp);
}

I can think of no other way to fix this. Any help would be appretiated. Sorry for the huge amount of code.

Body:
In your memalloc and these lines you close the file

 fread(&floors,sizeof(unsigned),1,f);
 fread(&flats_per_floor,sizeof(unsigned),1,f);
 fclose(f);

but later in your loop you try to read from it, and a few lines after this you close it again

for(int j = 0; j < flats_per_floor; j++)
{
   fread(&Apartment,sizeof(S_Apartament),1,f);
   arr[i][j]=Apartment;
}

Try removing the first fclose call.


问:
I want to test a controller without using @SpringBootTest
I have the following test class:

```<code>@SpringBootTest
public class ChoreControllerTest
{
    @Autowired
    private ChoreController controller;

    @Test
    public void throwOnMissingChore()
    {
        assertThrows(ChoreNotFoundException.class, () -> this.controller.getChore(0L));
    }
}
</code>```

It takes about 5 seconds for Spring Boot to start up so the test can run. I want to reduce this time, but if I just remove the @SpringBootTest annotaton, I just get a NPE.

Is there a way to make this controller test more lightweight, or am I stuck with the startup time? I'm especially worried about what will happen to my test times if I ever want to test more than one controller....

答:
The @SpringBootTest annotations create a Spring Context for you therefore it takes a while to start up. This annotation is mostly used for integration tests where a Spring context is required. Here are a few tips for optimizing integration tests.
If you remove the annotation the ChoreController cannot be autowired (no context available) which results in a NullpointerException.

Depending on your needs you can just use a Mocking library like Mockito to inject mocks e.g. services that your controller class needs and run the test without the @SpringBootTest.

You might want to take a look at this article for setting up those mocks properly.

Body:
I have the following test class:

@SpringBootTest
public class ChoreControllerTest
{
    @Autowired
    private ChoreController controller;

    @Test
    public void throwOnMissingChore()
    {
        assertThrows(ChoreNotFoundException.class, () -> this.controller.getChore(0L));
    }
}

It takes about 5 seconds for Spring Boot to start up so the test can run. I want to reduce this time, but if I just remove the @SpringBootTest annotaton, I just get a NPE.

Is there a way to make this controller test more lightweight, or am I stuck with the startup time? I'm especially worried about what will happen to my test times if I ever want to test more than one controller....


问:
IExtensibleDataObject vs IExtensibleObject?
I am trying to figure out what is the difference between IExtensibleDataObject and IExtensibleObject.

MSDN say that the first one (IExtensibleDataObject) is to let the deserialization of object that may have added attribute and the second one (IExtensibleObject) look very similar, it does let the object add attribute too.

I am confused.

答:
IExtensibleDataObject is for accommodating extra data in a service message (perhaps data that wasn't specified by the contract when proxies were generated).

IExtensibleObject is used to extend certain aspects of the WCF engine (Such as ServiceHostBase and InstanceContext).

The names sound similar, but they are simply different interfaces for different purposes.


问:
JavaScript OOP in NodeJS: how?
I am used to the classical OOP as in Java.

What are the best practices to do OOP in JavaScript using NodeJS?

Each Class is a file with module.export?

How to create Classes?

```<code>this.Class = function() {
    //constructor?
    var privateField = ""
    this.publicField = ""
    var privateMethod = function() {}
    this.publicMethod = function() {}
}
</code>```

vs. (I am not even sure it is correct)

```<code>this.Class = {
    privateField: ""
    , privateMethod: function() {}

    , return {
        publicField: ""
        publicMethod: function() {}
    }
}
</code>```

vs.

```<code>this.Class = function() {}

this.Class.prototype.method = function(){}

...
</code>```

How would inheritance work?

Are there specific modules for implementing OOP in NodeJS?

I am finding a thousand different ways to create things that resemble OOP.. but I have no clue what is the most used/practical/clean way.

Bonus question: what is the suggested "OOP style" to use with MongooseJS? (can a MongooseJS document be seen as a Class and a model used as an instance?)

EDIT

here is an example in JsFiddle please provide feedback.

```<code>//http://javascriptissexy.com/oop-in-javascript-what-you-need-to-know/
function inheritPrototype(childObject, parentObject) {
    var copyOfParent = Object.create(parentObject.prototype)
    copyOfParent.constructor = childObject
    childObject.prototype = copyOfParent
}

//example
function Canvas (id) {
    this.id = id
    this.shapes = {} //instead of array?
    console.log("Canvas constructor called "+id)
}
Canvas.prototype = {
    constructor: Canvas
    , getId: function() {
        return this.id
    }
    , getShape: function(shapeId) {
        return this.shapes[shapeId]
    }
    , getShapes: function() {
        return this.shapes
    }
    , addShape: function (shape)  {
        this.shapes[shape.getId()] = shape
    }
    , removeShape: function (shapeId)  {
        var shape = this.shapes[shapeId]
        if (shape)
            delete this.shapes[shapeId]
        return shape
    }
}

function Shape(id) {
    this.id = id
    this.size = { width: 0, height: 0 }
    console.log("Shape constructor called "+id)
}
Shape.prototype = {
    constructor: Shape
    , getId: function() {
        return this.id
    }
    , getSize: function() {
        return this.size
    }
    , setSize: function (size)  {
        this.size = size
    }
}

//inheritance
function Square(id, otherSuff) {
    Shape.call(this, id) //same as Shape.prototype.constructor.apply( this, arguments ); ?
    this.stuff = otherSuff
    console.log("Square constructor called "+id)
}
inheritPrototype(Square, Shape)
Square.prototype.getSize = function() { //override
    return this.size.width
}

function ComplexShape(id) {
    Shape.call(this, id)
    this.frame = null
    console.log("ComplexShape constructor called "+id)
}
inheritPrototype(ComplexShape, Shape)
ComplexShape.prototype.getFrame = function() {
    return this.frame
}
ComplexShape.prototype.setFrame = function(frame) {
    this.frame = frame
}

function Frame(id) {
    this.id = id
    this.length = 0
}
Frame.prototype = {
    constructor: Frame
    , getId: function() {
        return this.id
    }
    , getLength: function() {
        return this.length
    }
    , setLength: function (length)  {
        this.length = length
    }
}

/////run
var aCanvas = new Canvas("c1")
var anotherCanvas = new Canvas("c2")
console.log("aCanvas: "+ aCanvas.getId())

var aSquare = new Square("s1", {})
aSquare.setSize({ width: 100, height: 100})
console.log("square overridden size: "+aSquare.getSize())

var aComplexShape = new ComplexShape("supercomplex")
var aFrame = new Frame("f1")
aComplexShape.setFrame(aFrame)
console.log(aComplexShape.getFrame())

aCanvas.addShape(aSquare)
aCanvas.addShape(aComplexShape)
console.log("Shapes in aCanvas: "+Object.keys(aCanvas.getShapes()).length)

anotherCanvas.addShape(aCanvas.removeShape("supercomplex"))
console.log("Shapes in aCanvas: "+Object.keys(aCanvas.getShapes()).length)
console.log("Shapes in anotherCanvas: "+Object.keys(anotherCanvas.getShapes()).length)

console.log(aSquare instanceof Shape)
console.log(aComplexShape instanceof Shape)
</code>```

答:
If you are working on your own, and you want the closest thing to OOP as you would find in Java or C# or C++, see the javascript library, CrxOop. CrxOop provides syntax somewhat familiar to Java developers.

Just be careful, Java's OOP is not the same as that found in Javascript. To get the same behavior as in Java, use CrxOop's classes, not CrxOop's structures, and make sure all your methods are virtual. An example of the syntax is,

```<code>crx_registerClass("ExampleClass",
{
    "VERBOSE": 1,

    "public var publicVar": 5,
    "private var privateVar": 7,

    "public virtual function publicVirtualFunction": function(x)
    {
        this.publicVar1 = x;
        console.log("publicVirtualFunction");
    },

    "private virtual function privatePureVirtualFunction": 0,

    "protected virtual final function protectedVirtualFinalFunction": function()
    {
        console.log("protectedVirtualFinalFunction");
    }
});

crx_registerClass("ExampleSubClass",
{
    VERBOSE: 1,
    EXTENDS: "ExampleClass",

    "public var publicVar": 2,

    "private virtual function privatePureVirtualFunction": function(x)
    {
        this.PARENT.CONSTRUCT(pA);
        console.log("ExampleSubClass::privatePureVirtualFunction");
    }
});

var gExampleSubClass = crx_new("ExampleSubClass", 4);

console.log(gExampleSubClass.publicVar);
console.log(gExampleSubClass.CAST("ExampleClass").publicVar);
</code>```

The code is pure javascript, no transpiling. The example is taken from a number of examples from the official documentation.

Title: JavaScript OOP in NodeJS: how?

Body:
I am used to the classical OOP as in Java.

What are the best practices to do OOP in JavaScript using NodeJS?

Each Class is a file with module.export?

How to create Classes?

this.Class = function() {
    //constructor?
    var privateField = ""
    this.publicField = ""
    var privateMethod = function() {}
    this.publicMethod = function() {}
}

vs. (I am not even sure it is correct)

this.Class = {
    privateField: ""
    , privateMethod: function() {}

    , return {
        publicField: ""
        publicMethod: function() {}
    }
}

vs.

this.Class = function() {}

this.Class.prototype.method = function(){}

...

How would inheritance work?

Are there specific modules for implementing OOP in NodeJS?

I am finding a thousand different ways to create things that resemble OOP.. but I have no clue what is the most used/practical/clean way.

Bonus question: what is the suggested "OOP style" to use with MongooseJS? (can a MongooseJS document be seen as a Class and a model used as an instance?)

EDIT

here is an example in JsFiddle please provide feedback.

//http://javascriptissexy.com/oop-in-javascript-what-you-need-to-know/
function inheritPrototype(childObject, parentObject) {
    var copyOfParent = Object.create(parentObject.prototype)
    copyOfParent.constructor = childObject
    childObject.prototype = copyOfParent
}

//example
function Canvas (id) {
    this.id = id
    this.shapes = {} //instead of array?
    console.log("Canvas constructor called "+id)
}
Canvas.prototype = {
    constructor: Canvas
    , getId: function() {
        return this.id
    }
    , getShape: function(shapeId) {
        return this.shapes[shapeId]
    }
    , getShapes: function() {
        return this.shapes
    }
    , addShape: function (shape)  {
        this.shapes[shape.getId()] = shape
    }
    , removeShape: function (shapeId)  {
        var shape = this.shapes[shapeId]
        if (shape)
            delete this.shapes[shapeId]
        return shape
    }
}

function Shape(id) {
    this.id = id
    this.size = { width: 0, height: 0 }
    console.log("Shape constructor called "+id)
}
Shape.prototype = {
    constructor: Shape
    , getId: function() {
        return this.id
    }
    , getSize: function() {
        return this.size
    }
    , setSize: function (size)  {
        this.size = size
    }
}

//inheritance
function Square(id, otherSuff) {
    Shape.call(this, id) //same as Shape.prototype.constructor.apply( this, arguments ); ?
    this.stuff = otherSuff
    console.log("Square constructor called "+id)
}
inheritPrototype(Square, Shape)
Square.prototype.getSize = function() { //override
    return this.size.width
}

function ComplexShape(id) {
    Shape.call(this, id)
    this.frame = null
    console.log("ComplexShape constructor called "+id)
}
inheritPrototype(ComplexShape, Shape)
ComplexShape.prototype.getFrame = function() {
    return this.frame
}
ComplexShape.prototype.setFrame = function(frame) {
    this.frame = frame
}

function Frame(id) {
    this.id = id
    this.length = 0
}
Frame.prototype = {
    constructor: Frame
    , getId: function() {
        return this.id
    }
    , getLength: function() {
        return this.length
    }
    , setLength: function (length)  {
        this.length = length
    }
}

/////run
var aCanvas = new Canvas("c1")
var anotherCanvas = new Canvas("c2")
console.log("aCanvas: "+ aCanvas.getId())

var aSquare = new Square("s1", {})
aSquare.setSize({ width: 100, height: 100})
console.log("square overridden size: "+aSquare.getSize())

var aComplexShape = new ComplexShape("supercomplex")
var aFrame = new Frame("f1")
aComplexShape.setFrame(aFrame)
console.log(aComplexShape.getFrame())

aCanvas.addShape(aSquare)
aCanvas.addShape(aComplexShape)
console.log("Shapes in aCanvas: "+Object.keys(aCanvas.getShapes()).length)

anotherCanvas.addShape(aCanvas.removeShape("supercomplex"))
console.log("Shapes in aCanvas: "+Object.keys(aCanvas.getShapes()).length)
console.log("Shapes in anotherCanvas: "+Object.keys(anotherCanvas.getShapes()).length)

console.log(aSquare instanceof Shape)
console.log(aComplexShape instanceof Shape)

Body:
If you are working on your own, and you want the closest thing to OOP as you would find in Java or C# or C++, see the javascript library, CrxOop. CrxOop provides syntax somewhat familiar to Java developers.

Just be careful, Java's OOP is not the same as that found in Javascript. To get the same behavior as in Java, use CrxOop's classes, not CrxOop's structures, and make sure all your methods are virtual. An example of the syntax is,

crx_registerClass("ExampleClass",
{
    "VERBOSE": 1,

    "public var publicVar": 5,
    "private var privateVar": 7,

    "public virtual function publicVirtualFunction": function(x)
    {
        this.publicVar1 = x;
        console.log("publicVirtualFunction");
    },

    "private virtual function privatePureVirtualFunction": 0,

    "protected virtual final function protectedVirtualFinalFunction": function()
    {
        console.log("protectedVirtualFinalFunction");
    }
});

crx_registerClass("ExampleSubClass",
{
    VERBOSE: 1,
    EXTENDS: "ExampleClass",

    "public var publicVar": 2,

    "private virtual function privatePureVirtualFunction": function(x)
    {
        this.PARENT.CONSTRUCT(pA);
        console.log("ExampleSubClass::privatePureVirtualFunction");
    }
});

var gExampleSubClass = crx_new("ExampleSubClass", 4);

console.log(gExampleSubClass.publicVar);
console.log(gExampleSubClass.CAST("ExampleClass").publicVar);

The code is pure javascript, no transpiling. The example is taken from a number of examples from the official documentation.


问:
How do I rerender my view in swiftUI after a user logged in with Google on Firebase?
I'm fairly new to iOS Programming and swiftUI in particular.
I have the issue that I try to integrate firebase auth in my App in order to manage users.
Now the login, and log out basically works, the issue is, that after logging in, my view (which conditionally renders eighter the Google sign-in button or a list of content does not rerender so I still see the sign-in button even though I'm signed in).

I have set an observable Object to hold my auth status but unfortunately, it does not reload the current user automatically. So I set up a function to reload it manually which I would like to trigger when logging in. This works for the logout button but the logging in finishes in the AppDelegate, where for some reason I can't access the reloadUser() function.

I'm sure there is a better way to do this and would appreciate any help!

The Environment:

```<code>final class UserData: ObservableObject {
    @Published var showFavoritesOnly = false
    @Published var qrTags = qrTagData
    @Published var user: User? = Auth.auth().currentUser

    func reloadUser() -> Void {
        self.user = Auth.auth().currentUser
    }
}
</code>```

The View I'd like to render:

```<code>struct MyQuaggsList: View {
        @EnvironmentObject private var userData: UserData

        var body: some View {
            Group {
                if getLogInState() != nil {
                    VStack {
                        NavigationView {
                            List {
                                Toggle(isOn: $userData.showFavoritesOnly) {
                                    Text("Show Favorites Only")
                                }

                                ForEach(userData.qrTags) { qrTag in
                                    if !self.userData.showFavoritesOnly || qrTag.isFavorite {
                                        NavigationLink(
                                            destination: QuagDetail(qrTag: qrTag)
                                                .environmentObject(self.userData)
                                        ) {
                                            QuaggRow(qrTag: qrTag)
                                        }
                                    }
                                }
                            }
                            .navigationBarTitle(Text("My Quaggs"))
                        }
                        SignOutButton()
                    }
                } else {
                    SignInView()
                }
            }.onAppear(perform: {self.userData.reloadUser()})
        }

        func getLogInState() -> User? {
            return Auth.auth().currentUser
        }
    }
</code>```

Also, note there is the .onAppear() function which unfortunately only triggers on the initial appear not on the reappearance of the view after the user logged in.

Thanks so much in advance! It has been really frustrating.

答:
@Ghazi Tozri thanks again for your answer, while it wasn't what I wanted to do exactly it pushed me in the right direction.
I just want to put here what I finally did so if anyone wants to not use Email / Password sign-in but Google sign-in they can benefit from it too.

I used the Combine Framework + the @Publisher Syntax to make it a bit more readable and I also don't need the Signing in and out Methods because Google Provides them.

The SwiftUI Button for Google sign-in would look something like this:

```<code>struct GoogleSignIn : UIViewRepresentable {
    @EnvironmentObject private var userData: SessionStore

    func makeUIView(context: UIViewRepresentableContext<GoogleSignIn>) -> GIDSignInButton {
        let button = GIDSignInButton()
        button.colorScheme = .dark
        GIDSignIn.sharedInstance()?.presentingViewController = UIApplication.shared.windows.last?.rootViewController

        //If you want to restore a session
        //GIDSignIn.sharedInstance()?.restorePreviousSignIn()
        return button
    }

    func updateUIView(_ uiView: GIDSignInButton, context: UIViewRepresentableContext<GoogleSignIn>) {
    }
}
</code>```

And the Used SessionStore like this:

```<code>import SwiftUI
import Combine
import Firebase
import GoogleSignIn

final class SessionStore: ObservableObject {
    @Published var showFavoritesOnly = false
    @Published var qrTags = qrTagData
    @Published var session: User?
    var handle: AuthStateDidChangeListenerHandle?

    func listen() {
        handle =  Auth.auth().addStateDidChangeListener { (auth, user) in
            if let user = user {
                self.session = user
            } else {
                self.session = nil
            }
        }
    }
}
</code>```

In a view that checks for the authentication state I use the .onAppear() function like this:

```<code>struct UserProfile: View {
    @EnvironmentObject private var session: SessionStore

    var body: some View {
        VStack {
            if session.session != nil {
                SignOutButton()
            } else {
                SignInView()
            }
        }.onAppear(perform: {self.session.listen()})
    }
}
</code>```

To sign out this function will do (from the Firebase Docs):

```<code>func signOut() -> Void {
        let firebaseAuth = Auth.auth()
        do {
            try firebaseAuth.signOut()
        }
        catch let signOutError as NSError {
            print ("Error signing out: %@", signOutError)
        }
    }
</code>```

Hope this can help somebody else too.

Body:
I'm fairly new to iOS Programming and swiftUI in particular.
I have the issue that I try to integrate firebase auth in my App in order to manage users.
Now the login, and log out basically works, the issue is, that after logging in, my view (which conditionally renders eighter the Google sign-in button or a list of content does not rerender so I still see the sign-in button even though I'm signed in).

I have set an observable Object to hold my auth status but unfortunately, it does not reload the current user automatically. So I set up a function to reload it manually which I would like to trigger when logging in. This works for the logout button but the logging in finishes in the AppDelegate, where for some reason I can't access the reloadUser() function.

I'm sure there is a better way to do this and would appreciate any help!

The Environment:

final class UserData: ObservableObject {
    @Published var showFavoritesOnly = false
    @Published var qrTags = qrTagData
    @Published var user: User? = Auth.auth().currentUser

    func reloadUser() -> Void {
        self.user = Auth.auth().currentUser
    }
}

The View I'd like to render:

struct MyQuaggsList: View {
        @EnvironmentObject private var userData: UserData

        var body: some View {
            Group {
                if getLogInState() != nil {
                    VStack {
                        NavigationView {
                            List {
                                Toggle(isOn: $userData.showFavoritesOnly) {
                                    Text("Show Favorites Only")
                                }

                                ForEach(userData.qrTags) { qrTag in
                                    if !self.userData.showFavoritesOnly || qrTag.isFavorite {
                                        NavigationLink(
                                            destination: QuagDetail(qrTag: qrTag)
                                                .environmentObject(self.userData)
                                        ) {
                                            QuaggRow(qrTag: qrTag)
                                        }
                                    }
                                }
                            }
                            .navigationBarTitle(Text("My Quaggs"))
                        }
                        SignOutButton()
                    }
                } else {
                    SignInView()
                }
            }.onAppear(perform: {self.userData.reloadUser()})
        }

        func getLogInState() -> User? {
            return Auth.auth().currentUser
        }
    }

Also, note there is the .onAppear() function which unfortunately only triggers on the initial appear not on the reappearance of the view after the user logged in.

Thanks so much in advance! It has been really frustrating.

Body:
@Ghazi Tozri thanks again for your answer, while it wasn't what I wanted to do exactly it pushed me in the right direction.
I just want to put here what I finally did so if anyone wants to not use Email / Password sign-in but Google sign-in they can benefit from it too.

I used the Combine Framework + the @Publisher Syntax to make it a bit more readable and I also don't need the Signing in and out Methods because Google Provides them.

The SwiftUI Button for Google sign-in would look something like this:

struct GoogleSignIn : UIViewRepresentable {
    @EnvironmentObject private var userData: SessionStore

    func makeUIView(context: UIViewRepresentableContext<GoogleSignIn>) -> GIDSignInButton {
        let button = GIDSignInButton()
        button.colorScheme = .dark
        GIDSignIn.sharedInstance()?.presentingViewController = UIApplication.shared.windows.last?.rootViewController

        //If you want to restore a session
        //GIDSignIn.sharedInstance()?.restorePreviousSignIn()
        return button
    }

    func updateUIView(_ uiView: GIDSignInButton, context: UIViewRepresentableContext<GoogleSignIn>) {
    }
}

And the Used SessionStore like this:

import SwiftUI
import Combine
import Firebase
import GoogleSignIn

final class SessionStore: ObservableObject {
    @Published var showFavoritesOnly = false
    @Published var qrTags = qrTagData
    @Published var session: User?
    var handle: AuthStateDidChangeListenerHandle?

    func listen() {
        handle =  Auth.auth().addStateDidChangeListener { (auth, user) in
            if let user = user {
                self.session = user
            } else {
                self.session = nil
            }
        }
    }
}

In a view that checks for the authentication state I use the .onAppear() function like this:

struct UserProfile: View {
    @EnvironmentObject private var session: SessionStore

    var body: some View {
        VStack {
            if session.session != nil {
                SignOutButton()
            } else {
                SignInView()
            }
        }.onAppear(perform: {self.session.listen()})
    }
}

To sign out this function will do (from the Firebase Docs):

func signOut() -> Void {
        let firebaseAuth = Auth.auth()
        do {
            try firebaseAuth.signOut()
        }
        catch let signOutError as NSError {
            print ("Error signing out: %@", signOutError)
        }
    }

Hope this can help somebody else too.


问:
How to convert timedelta to hours
I have a timedelta Dataframe

```<code>JC time
1 3days 21:02:05
2 1days 23:50:07
3 6days 19:28:36
</code>```

but i want

```<code>1 93:02:05
2 47:50:07
3 163:28:36
</code>```

How can I convert it?

答:
Here is another approach:</p>

```<code>def strf_delta(td):
    h, r = divmod(int(td.total_seconds()), 60*60)
    m, s = divmod(r, 60)
    h, m, s = (str(x).zfill(2) for x in (h, m, s))
    return f"{h}:{m}:{s}"

d['time'].apply(strf_delta)
</code>```

Title: How to convert timedelta to hours

Body:
I have a timedelta Dataframe

JC time
1 3days 21:02:05
2 1days 23:50:07
3 6days 19:28:36

but i want

1 93:02:05
2 47:50:07
3 163:28:36

How can I convert it?

Body:
Here is another approach:

def strf_delta(td):
    h, r = divmod(int(td.total_seconds()), 60*60)
    m, s = divmod(r, 60)
    h, m, s = (str(x).zfill(2) for x in (h, m, s))
    return f"{h}:{m}:{s}"

d['time'].apply(strf_delta)


问:
Looping each split string data until finished
I'm having a bit of a brain fart issue trying to decide the best way to approach this issue, my code is working fine, i just need to think of a way to add a small feature.

Code:

```<code>public async void SearchGoogle(string randomKeyword, bool debug) {

    // Ignore URLs containing these strings ...
    var ignore = File.ReadAllLines(@"LogicFiles\ignore.txt");

    // Google increments 10 at a time instead of 1 ...
    for (int x = 0; x <= 100; x+=10) {

        string url = "https://www.google.com/search?q=" + randomKeyword + "&client=firefox-b-d&channel=trow2&sxsrf=ALeKk0351-NMDQgTggMB6Vu6H7hNOQycpg:1590534216843&source=lnt&tbs=qdr:d&start=" + x + "&sa=X&ved=2ahUKEwi_y_3X0dLpAhWqQhUIHcjtDeoQpwV6BAhtEBs&biw=1360&bih=654";

        webBrowser.Navigate(url);

        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
        doc.LoadHtml(webBrowser.DocumentText);

        if (debug)
        {
            Helpers.SaveDebugToFile(@"Debug\[google.com]-" + DateTime.Now.ToString("hhmmssffffff") + "-debug.html", webBrowser.DocumentText);
        }

        foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//a[@href]"))
        {
            HtmlAttribute href = link.Attributes["href"];
            if (ignore.Any(href.Value.Contains) || href.Value.Length < 5)
            {

            }
            else
            {
                DataGridViewLinks.Rows.Add(href.Value.Trim(), randomKeyword, "");
            }
        }

        // Need a pause between page loads ...
        await SearchEngineDelay();

        // Update count ...
        UpdateLinksCount();

        // Update keyword ...
        UpdateKeywordBeingUsed(randomKeyword);

        // Remove duplicate links from the datagrid ...
        RemoveDuplicateRowsFromDataGridLinks();

    } // end for loop ...

    // Enable the button when finished ...
    BtnFindPotentialLinks.Enabled = true;

}
</code>```

What the code above does is, it will take a random keyword from a string of keywords in a datagrid which is formatted like: KEY1|KEY2|KEY3|etc feed in that random keyword, then loop 10 pages, which works fine.

I'm now wanting it instead of selecting a random keyword, search each keyword 1 at a time instead of just selecting 1 random keyword, i'm not sure the best way to approach this, i know i would need to use: string[] keywords = inputString.Split('|'); and somehow loop each keyword in the forloop but after this i'm not sure the best way.

Any tips or help would be appreciated.

答:
Since you can't search these keywords in parallel (you need to delay between calls), then just iterate and search one at the time </p>

```<code>foreach (var keyword in inputString.Split('|'))
{
    await SearchGoogle(keyword, false);
}
</code>```

Body:
I'm having a bit of a brain fart issue trying to decide the best way to approach this issue, my code is working fine, i just need to think of a way to add a small feature.

Code:

public async void SearchGoogle(string randomKeyword, bool debug) {

    // Ignore URLs containing these strings ...
    var ignore = File.ReadAllLines(@"LogicFiles\ignore.txt");

    // Google increments 10 at a time instead of 1 ...
    for (int x = 0; x <= 100; x+=10) {

        string url = "https://www.google.com/search?q=" + randomKeyword + "&client=firefox-b-d&channel=trow2&sxsrf=ALeKk0351-NMDQgTggMB6Vu6H7hNOQycpg:1590534216843&source=lnt&tbs=qdr:d&start=" + x + "&sa=X&ved=2ahUKEwi_y_3X0dLpAhWqQhUIHcjtDeoQpwV6BAhtEBs&biw=1360&bih=654";

        webBrowser.Navigate(url);

        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
        doc.LoadHtml(webBrowser.DocumentText);

        if (debug)
        {
            Helpers.SaveDebugToFile(@"Debug\[google.com]-" + DateTime.Now.ToString("hhmmssffffff") + "-debug.html", webBrowser.DocumentText);
        }

        foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//a[@href]"))
        {
            HtmlAttribute href = link.Attributes["href"];
            if (ignore.Any(href.Value.Contains) || href.Value.Length < 5)
            {

            }
            else
            {
                DataGridViewLinks.Rows.Add(href.Value.Trim(), randomKeyword, "");
            }
        }

        // Need a pause between page loads ...
        await SearchEngineDelay();

        // Update count ...
        UpdateLinksCount();

        // Update keyword ...
        UpdateKeywordBeingUsed(randomKeyword);

        // Remove duplicate links from the datagrid ...
        RemoveDuplicateRowsFromDataGridLinks();

    } // end for loop ...

    // Enable the button when finished ...
    BtnFindPotentialLinks.Enabled = true;

}

What the code above does is, it will take a random keyword from a string of keywords in a datagrid which is formatted like: KEY1|KEY2|KEY3|etc feed in that random keyword, then loop 10 pages, which works fine.

I'm now wanting it instead of selecting a random keyword, search each keyword 1 at a time instead of just selecting 1 random keyword, i'm not sure the best way to approach this, i know i would need to use: string[] keywords = inputString.Split('|'); and somehow loop each keyword in the forloop but after this i'm not sure the best way.

Any tips or help would be appreciated.

Body:
Since you can't search these keywords in parallel (you need to delay between calls), then just iterate and search one at the time

foreach (var keyword in inputString.Split('|'))
{
    await SearchGoogle(keyword, false);
}


问:
Referring to `this` vue component within an event handler
Given this Vue component that attaches a global event listener:

```<code>var app = new Vue({
    data: {
        foo: 0;
    },
    methods: {
        handle: function(e) {
            this.foo = 1; // this refers to handler, not app
        }
    },
    mounted: function() {
        window.addEventListener("keypress", this.handle);
    }
});
</code>```

What is the correct way to refer to this from within the event handler in order to update the component state? Alternatively, is there a better way to set event handlers on the entire window?

答:
Your data property should be a function, not an object.</p>

```<code>data(){
 return {
  foo: 1
 }
}
</code>```

Body:
Given this Vue component that attaches a global event listener:

var app = new Vue({
    data: {
        foo: 0;
    },
    methods: {
        handle: function(e) {
            this.foo = 1; // this refers to handler, not app
        }
    },
    mounted: function() {
        window.addEventListener("keypress", this.handle);
    }
});

What is the correct way to refer to this from within the event handler in order to update the component state? Alternatively, is there a better way to set event handlers on the entire window?

Body:
Your data property should be a function, not an object.

data(){
 return {
  foo: 1
 }
}


问:
Multiple database drivers scenario: passing interface as type
Scenario: I've got a database type implementing a number of CRUD operations.

I would like to:

abstract away the database layer to support multiple databases

put a cache layer "in front of it" as read-through cache

So my idea was to:

create a database interface for both postgres specific code, and the cache

pass the postgres type to the cache constructor so it can use it to from the database

See below for what I tried, resulting in an error for cacheNew() when assigning :

cannot use dbdriver (variable of type interface{}) as database value in struct literal: missing method GetUser

What is the best way to solve this?

```<code>package main

import "fmt"

type database interface {
    GetUser(string)
}

type postgres struct {
    hostname string
}

func (p *postgres) GetUser(u string) {
    fmt.Printf("Postgres: GetUser %s\n", u)
}

type cache struct {
    db database
}

func cacheNew(dbdriver interface{}) cache {
    return cache{
        db: dbdriver,
    }
}

func (c *cache) GetUser(u string) {
    fmt.Printf("Cache: GetUser %s\n", u)

    c.db.GetUser(u)
}

func main() {
    // var db database

    db := postgres{
        hostname: "x",
    }
    db.GetUser("joe")

    dbViaCache := cacheNew(db)
    dbViaCache.GetUser("joe")
}
</code>```

答:
Whether it's quite opinion-based I do not recommend to mix database and cache functionality.

I can recommend the following: first create package cache, and then start from interface in cache.go:

```<code>// Cache is an interface which abstracts cache providers details for testability and usability
type Cache interface {
    // Get retrieves the content associated with the given key. decoding it into the given
    // pointer.
    //
    // Returns:
    //   - nil if the value was successfully retrieved and ptrValue set
    //   - ErrCacheMiss if the value was not found in the cache
    //   - an implementation specific error otherwise
    Get(key string, ptrValue interface{}) error

    // set the given key/value in the cache, overwriting any existing value
    // associated with that key
    Set(key string, ptrValue interface{}, expires time.Duration) error

}
</code>```

Then you can create files in this package like inmem.go, redis.go, everything else implementing this interface. You can then prepare YAML config indicated which cache provider you want to use and instantiate it during your server startup.

```<code>cache:
  active: "redis"
  redis:
    address: "127.0.0.1:6379"
    password: #
    poolSize: #
</code>```

For database, everything is trickier. From my experience, it is easier to choose database provider once and use jmoiron/sqlx or even native driver, like pure pgx for high-loaded handlers. Because of lack of generics and relatively slow reflect, abstractions on database provider in most cases are not practical except for basic CRUD. For very simple situations you can mimic repository pattern

```<code>type UserRepository interface {
    Get(ctx context.Context, id uint64) (*User, error)
}

type userRepository struct {
    db *sqlx.DB
}

func (r *userRepository) Get(ctx context.Context, id uint64) (*User, error) {
    const query = `SELECT id, email, login, language_id FROM users WHERE id = $1`
    user := &User{}
    if err := r.db.GetContext(ctx, user, query, id); err != nil {
        return nil, err
    }
    return user, nil
}
</code>```

Then in your service you will have something like that

```<code>    key := "app:users#23"
    user := &User{}
    if err := svc.cache.Get(key, user); err != nil {
        user, err = svc.userRepo.Get(userID)
        if err != nil {
            // handle
        }
        // otherwise, set cache
        go svc.cache.Set(key, user, time.Minutes * 15)
    }

    // perform other actions with user
</code>```

Hope it helps!

Body:
Scenario: I've got a database type implementing a number of CRUD operations.

I would like to:

abstract away the database layer to support multiple databases

put a cache layer "in front of it" as read-through cache

So my idea was to:

create a database interface for both postgres specific code, and the cache

pass the postgres type to the cache constructor so it can use it to from the database

See below for what I tried, resulting in an error for cacheNew() when assigning :

cannot use dbdriver (variable of type interface{}) as database value in struct literal: missing method GetUser

What is the best way to solve this?

package main

import "fmt"

type database interface {
    GetUser(string)
}

type postgres struct {
    hostname string
}

func (p *postgres) GetUser(u string) {
    fmt.Printf("Postgres: GetUser %s\n", u)
}

type cache struct {
    db database
}

func cacheNew(dbdriver interface{}) cache {
    return cache{
        db: dbdriver,
    }
}

func (c *cache) GetUser(u string) {
    fmt.Printf("Cache: GetUser %s\n", u)

    c.db.GetUser(u)
}

func main() {
    // var db database

    db := postgres{
        hostname: "x",
    }
    db.GetUser("joe")

    dbViaCache := cacheNew(db)
    dbViaCache.GetUser("joe")
}

Body:
Whether it's quite opinion-based I do not recommend to mix database and cache functionality.

I can recommend the following: first create package cache, and then start from interface in cache.go:

// Cache is an interface which abstracts cache providers details for testability and usability
type Cache interface {
    // Get retrieves the content associated with the given key. decoding it into the given
    // pointer.
    //
    // Returns:
    //   - nil if the value was successfully retrieved and ptrValue set
    //   - ErrCacheMiss if the value was not found in the cache
    //   - an implementation specific error otherwise
    Get(key string, ptrValue interface{}) error

    // set the given key/value in the cache, overwriting any existing value
    // associated with that key
    Set(key string, ptrValue interface{}, expires time.Duration) error

}

Then you can create files in this package like inmem.go, redis.go, everything else implementing this interface. You can then prepare YAML config indicated which cache provider you want to use and instantiate it during your server startup.

cache:
  active: "redis"
  redis:
    address: "127.0.0.1:6379"
    password: #
    poolSize: #

For database, everything is trickier. From my experience, it is easier to choose database provider once and use jmoiron/sqlx or even native driver, like pure pgx for high-loaded handlers. Because of lack of generics and relatively slow reflect, abstractions on database provider in most cases are not practical except for basic CRUD. For very simple situations you can mimic repository pattern

type UserRepository interface {
    Get(ctx context.Context, id uint64) (*User, error)
}

type userRepository struct {
    db *sqlx.DB
}

func (r *userRepository) Get(ctx context.Context, id uint64) (*User, error) {
    const query = `SELECT id, email, login, language_id FROM users WHERE id = $1`
    user := &User{}
    if err := r.db.GetContext(ctx, user, query, id); err != nil {
        return nil, err
    }
    return user, nil
}

Then in your service you will have something like that

    key := "app:users#23"
    user := &User{}
    if err := svc.cache.Get(key, user); err != nil {
        user, err = svc.userRepo.Get(userID)
        if err != nil {
            // handle
        }
        // otherwise, set cache
        go svc.cache.Set(key, user, time.Minutes * 15)
    }

    // perform other actions with user

Hope it helps!


问:
How can I create a Laravel Resource relationship for a belongsTo?
I have created a UserResource that is successfully returning all of my user attributes, including the organization it belongs to. It looks something like this:

Resources/User.php

```<code>return [
    'type' => 'users',
    'id' => (string)$this->id,
    'attributes' => [
        'name' => $this->name,
        'email' => $this->email,
        ...
        'relationships' => [
            'organization' => $this->organization,
        ],
    ];
</code>```

In my User model, there is a belongsTo relationship for User->Organization.

Instead of returning the actual organization model, I'd like to return the organization resource.

For example, an organization hasMany locations:

Resources/Organization.php

```<code>return [
    'type' => 'organizations',
    'id' => (string)$this->id,
    'attributes' => [
        'name' => $this->name,
        ...
        'relationships' => [
            'locations' => Location::collection($this->locations),
        ],
    ];
</code>```

I can successfully return the collection of locations that belong to the organization. I have not been able to return a belongsTo relationship.

I've tried:

Resources/User.php

```<code>'relationships' => [
    'organization' => Organization::collection($this->organization),
],

// or this
'relationships' => [
    'organization' => Organization::class($this->organization),
],

// or this
use App\Http\Resources\Organization as OrganizationResource;
...

'relationships' => [
    'organization' => OrganizationResource($this->organization),
],
</code>```

How can I return a single model as a related resource? Thank you for any suggestions!

答:
Have you tried it with the new keyword?

```<code>'relationships' => [
    'organization' => new OrganizationResource($this->organization),
],
</code>```

Body:
I have created a UserResource that is successfully returning all of my user attributes, including the organization it belongs to. It looks something like this:

Resources/User.php

return [
    'type' => 'users',
    'id' => (string)$this->id,
    'attributes' => [
        'name' => $this->name,
        'email' => $this->email,
        ...
        'relationships' => [
            'organization' => $this->organization,
        ],
    ];

In my User model, there is a belongsTo relationship for User->Organization.

Instead of returning the actual organization model, I'd like to return the organization resource.

For example, an organization hasMany locations:

Resources/Organization.php

return [
    'type' => 'organizations',
    'id' => (string)$this->id,
    'attributes' => [
        'name' => $this->name,
        ...
        'relationships' => [
            'locations' => Location::collection($this->locations),
        ],
    ];

I can successfully return the collection of locations that belong to the organization. I have not been able to return a belongsTo relationship.

I've tried:

Resources/User.php

'relationships' => [
    'organization' => Organization::collection($this->organization),
],

// or this
'relationships' => [
    'organization' => Organization::class($this->organization),
],

// or this
use App\Http\Resources\Organization as OrganizationResource;
...

'relationships' => [
    'organization' => OrganizationResource($this->organization),
],

How can I return a single model as a related resource? Thank you for any suggestions!

Body:
Have you tried it with the new keyword?

'relationships' => [
    'organization' => new OrganizationResource($this->organization),
],


问:
Pivot a pandas dataframe with multiple columns
I have a sample data frame like below

```<code>df1 = pd.DataFrame({'Gender':['Male','Male','Male','Male','Female','Female','Female','Female','Male','Male','Male','Male','Female','Female','Female','Female'],
                'Year' :[2008,2008,2009,2009,2008,2008,2009,2009,2008,2008,2009,2009,2008,2008,2009,2009],
           'rate':[2.3,3.2,4.5,6.7,5.6,3.2,3.5,2.6,2.3,3.2,4.5,6.7,5.6,3.2,3.5,2.6],
           'Heading':['TNMAB123','TNMAB123','TNMAB123','TNMAB123','TNMAB123','TNMAB123','TNMAB123','TNMAB123',
                     'TNMAB456','TNMAB456','TNMAB456','TNMAB456','TNMAB456','TNMAB456','TNMAB456','TNMAB456'],
           'target':[31.2,33.4,33.4,35.2,35.2,36.4,36.4,37.2,31.2,33.4,33.4,35.2,35.2,36.4,36.4,37.2],
            'day_type':['wk','wkend','wk','wkend','wk','wkend','wk','wkend','wk','wkend','wk','wkend','wk','wkend','wk','wkend']})
</code>```

I would like to transpose/pivot them to get the output like as shown below but for my code, it throws an error as shown below

```<code>df1.pivot(index='Year', columns='Heading', values='rate')
</code>```

With the help of SO post, I wrote this but for 3 columns, I am not sure how to make it work?

```<code>df1 = df1.pivot_table(index=['Year','Gender','day_type'],columns='Heading',values='rate').unstack()
df1.columns = ['_'.join(i) for i in df1.columns.tolist()]
</code>```

I expect my output to be like as shown below where each year is made as a row and all the corresponding entries for that year are made as columns.

Please note I haven't filled in the values as table column structure is more important.

答:
Try with map, also you need unstack two level

```<code>df1 = df1.pivot_table(index=['Year','Gender','day_type'],columns='Heading',values='rate').unstack([1,2])
df1.columns=df1.columns.map('_'.join)
df1
      TNMAB123_Female_wk  ...  TNMAB456_Male_wkend
Year                      ...
2008                 5.6  ...                  3.2
2009                 3.5  ...                  6.7
[2 rows x 8 columns]
</code>```

Body:
I have a sample data frame like below

df1 = pd.DataFrame({'Gender':['Male','Male','Male','Male','Female','Female','Female','Female','Male','Male','Male','Male','Female','Female','Female','Female'],
                'Year' :[2008,2008,2009,2009,2008,2008,2009,2009,2008,2008,2009,2009,2008,2008,2009,2009],
           'rate':[2.3,3.2,4.5,6.7,5.6,3.2,3.5,2.6,2.3,3.2,4.5,6.7,5.6,3.2,3.5,2.6],
           'Heading':['TNMAB123','TNMAB123','TNMAB123','TNMAB123','TNMAB123','TNMAB123','TNMAB123','TNMAB123',
                     'TNMAB456','TNMAB456','TNMAB456','TNMAB456','TNMAB456','TNMAB456','TNMAB456','TNMAB456'],
           'target':[31.2,33.4,33.4,35.2,35.2,36.4,36.4,37.2,31.2,33.4,33.4,35.2,35.2,36.4,36.4,37.2],
            'day_type':['wk','wkend','wk','wkend','wk','wkend','wk','wkend','wk','wkend','wk','wkend','wk','wkend','wk','wkend']})

I would like to transpose/pivot them to get the output like as shown below but for my code, it throws an error as shown below

df1.pivot(index='Year', columns='Heading', values='rate')

With the help of SO post, I wrote this but for 3 columns, I am not sure how to make it work?

df1 = df1.pivot_table(index=['Year','Gender','day_type'],columns='Heading',values='rate').unstack()
df1.columns = ['_'.join(i) for i in df1.columns.tolist()]

I expect my output to be like as shown below where each year is made as a row and all the corresponding entries for that year are made as columns.

Please note I haven't filled in the values as table column structure is more important.

Body:
Try with map, also you need unstack two level

df1 = df1.pivot_table(index=['Year','Gender','day_type'],columns='Heading',values='rate').unstack([1,2])
df1.columns=df1.columns.map('_'.join)
df1
      TNMAB123_Female_wk  ...  TNMAB456_Male_wkend
Year                      ...
2008                 5.6  ...                  3.2
2009                 3.5  ...                  6.7
[2 rows x 8 columns]


问:
Regex to remove name titles leaving forename in Google Sheets
I have a set of names and wish to extract the forename from each. However, some have Mr, Mrs etc and others don't.

How can I extract the titles and then pull the first word(forename) out?

This is what I have so far.

^(Miss|Mr|Lady|Mrs|Ms|Dr|Mr.|Sir)\b

Here is an example sheet:
https://docs.google.com/spreadsheets/d/1dtKmQ_cGYcMTbG1GVAQwNTvHAns8926rU7bFakDH0dI/edit?usp=sharing

A copy can be made by using File-Make a copy

答:
You may use

```<code>=REGEXEXTRACT(A1, "^(?:(?:(?:Miss|Mr|Lady|Mrs|Ms|Dr|Sir)\b|Mr\.)\s+)?(\S+)")
</code>```

See the regex demo.

Details

^ - start of string

(?:(?:(?:Miss|Mr|Lady|Mrs|Ms|Dr|Sir)\b|Mr\.)\s+)? - an optional non-capturing group:

(?:(?:Miss|Mr|Lady|Mrs|Ms|Dr|Sir)\b|Mr\.) - a non-capturing group matching either

(?:Miss|Mr|Lady|Mrs|Ms|Dr|Sir)\b - a whole word Miss, Mr, Lady, Mrs, Ms, Dr, Sir

| - or

Mr\. - Mr. (\b after \. requires a word charon the right, hence it is a separate branch)

\s+ - 1+ whitespaces

(\S+) - Capturing group (actual output): 1 or more non-whitespace characters.

Body:
You may use

=REGEXEXTRACT(A1, "^(?:(?:(?:Miss|Mr|Lady|Mrs|Ms|Dr|Sir)\b|Mr\.)\s+)?(\S+)")

See the regex demo.

Details

^ - start of string

(?:(?:(?:Miss|Mr|Lady|Mrs|Ms|Dr|Sir)\b|Mr\.)\s+)? - an optional non-capturing group:

(?:(?:Miss|Mr|Lady|Mrs|Ms|Dr|Sir)\b|Mr\.) - a non-capturing group matching either

(?:Miss|Mr|Lady|Mrs|Ms|Dr|Sir)\b - a whole word Miss, Mr, Lady, Mrs, Ms, Dr, Sir

| - or

Mr\. - Mr. (\b after \. requires a word charon the right, hence it is a separate branch)

\s+ - 1+ whitespaces

(\S+) - Capturing group (actual output): 1 or more non-whitespace characters.


问:
Next.js and redux-persist; How do I persist a authenticated user across my web app?
Essentially, I am trying to persist a user across my next.js app after they're logged in i.e. upon any browser refresh it persists the data/state.

A way to do this when using redux, is to use redux-persist!

These the are the versions:

```<code>"next": "^9.0.5",
"redux-persist": "^6.0.0",
"redux": "^4.0.4",
</code>```

This is my pages/index.js file.

```<code>import { connect } from 'react-redux'
import Head from '../components/head'
import HomeLayout from '../components/Home/Home.jsx'
import 'semantic-ui-css/semantic.min.css'
import '../styles/styles.scss'

import {bindActionCreators} from 'redux'
import { logInUser } from '../store/index'

class Home extends React.Component {
   static getInitialProps ({  isLoggedIn }) {

    return {isLoggedIn}
  }

 componentDidMount() {
  logInUser()
 }

    render() {
        const { isLoggedIn } = this.props
        console.log("isLoggedIn ", isLoggedIn)
         return (
          <div>
           <Head title = 'Home' />
           <HomeLayout isLoggedIn = { isLoggedIn }/>
          </div>
         )
    }
}

const mapDispatchToProps = { logInUser }
export default connect(state =>
  state,
  mapDispatchToProps,
)(Home)
</code>```

And this is my store

```<code>import { createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import { persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage' // defaults to localStorage for web

import { createLogger } from 'redux-logger'
import thunkMiddleware from 'redux-thunk';

/* initial state */
var startState = { isLoggedIn: false }

/* action types */
export const actionTypes = {
    IS_LOGGED_IN: 'IS_LOGGED_IN'
}

/* reducer(s) */
export const reducer = (state = initialState, action) => {
    switch (action.type) {
        case 'IS_LOGGED_IN':
            return Object.assign({}, state, {
                isLoggedIn: action.isLoggedIn
            })
        default:
            return state
    }
};

/* actions */
export const logInUser = () => {
    return { type: actionTypes.IS_LOGGED_IN, isLoggedIn: true, }
}

const persistConfig = {
    key: 'root',
    storage,
    // whitelist: ['exampleData'] // place to select which state you want to persist
}

const persistedReducer = persistReducer(persistConfig, reducer)

// create a store
export const initializeStore = (initialState = startState) => {
    return createStore(
        persistedReducer,
        initialState,
        composeWithDevTools(applyMiddleware(
            thunkMiddleware,
            createLogger({ collapsed: true })
        ))
    )
}
</code>```

Any help would be appreciated!

UPDATE:

Also wanted to add my logger output from redux:

Strangely the action is not getting fired? The payload seems to still be false?

答:
Redux Persist sometimes works strangely in the server-side rendering. Maybe there is a problem with the persisted reducers. The actions and reducers seem good to me. I was in the same situation as you. So I wrote a boilerplate example of this. So

https://github.com/fazlulkarimweb/with-next-redux-wrapper-redux-persist

There are no official examples from the Next community for this for now. I think people who are trying to find a solution will be helped by this boilerplate.

Body:
Essentially, I am trying to persist a user across my next.js app after they're logged in i.e. upon any browser refresh it persists the data/state.

A way to do this when using redux, is to use redux-persist!

These the are the versions:

"next": "^9.0.5",
"redux-persist": "^6.0.0",
"redux": "^4.0.4",

This is my pages/index.js file.

import { connect } from 'react-redux'
import Head from '../components/head'
import HomeLayout from '../components/Home/Home.jsx'
import 'semantic-ui-css/semantic.min.css'
import '../styles/styles.scss'

import {bindActionCreators} from 'redux'
import { logInUser } from '../store/index'

class Home extends React.Component {
   static getInitialProps ({  isLoggedIn }) {

    return {isLoggedIn}
  }

 componentDidMount() {
  logInUser()
 }

    render() {
        const { isLoggedIn } = this.props
        console.log("isLoggedIn ", isLoggedIn)
         return (

           <HomeLayout isLoggedIn = { isLoggedIn }/>

         )
    }
}

const mapDispatchToProps = { logInUser }
export default connect(state =>
  state,
  mapDispatchToProps,
)(Home)

And this is my store

import { createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import { persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage' // defaults to localStorage for web

import { createLogger } from 'redux-logger'
import thunkMiddleware from 'redux-thunk';

/* initial state */
var startState = { isLoggedIn: false }

/* action types */
export const actionTypes = {
    IS_LOGGED_IN: 'IS_LOGGED_IN'
}

/* reducer(s) */
export const reducer = (state = initialState, action) => {
    switch (action.type) {
        case 'IS_LOGGED_IN':
            return Object.assign({}, state, {
                isLoggedIn: action.isLoggedIn
            })
        default:
            return state
    }
};

/* actions */
export const logInUser = () => {
    return { type: actionTypes.IS_LOGGED_IN, isLoggedIn: true, }
}

const persistConfig = {
    key: 'root',
    storage,
    // whitelist: ['exampleData'] // place to select which state you want to persist
}

const persistedReducer = persistReducer(persistConfig, reducer)

// create a store
export const initializeStore = (initialState = startState) => {
    return createStore(
        persistedReducer,
        initialState,
        composeWithDevTools(applyMiddleware(
            thunkMiddleware,
            createLogger({ collapsed: true })
        ))
    )
}

Any help would be appreciated!

UPDATE:

Also wanted to add my logger output from redux:

Strangely the action is not getting fired? The payload seems to still be false?


问:
Navigation with Material-UI Icons
How can I use a Material-UI Icon to do navigation using React router Dom?

I tried this but this doesn't work:

```<code> <NavigateBeforeIcon path="/vehicles"></NavigateBeforeIcon>
</code>```

In case of Buttons, I could do something like component={Link} and to="/vehicles" but I can't figure out how to navigate directly from the icon.

答:
You can use the useHistory Hook:

import { useHistory } from 'react-router-dom';

```<code>function Home() {
  const history = useHistory();

  return <NavigateBeforeIcon onClick={() => history.push('/profile')}
          ></NavigateBeforeIcon>
}
</code>```

With it you can build a custom component.

Title: Navigation with Material-UI Icons

Body:
How can I use a Material-UI Icon to do navigation using React router Dom?

I tried this but this doesn't work:

 <NavigateBeforeIcon path="/vehicles"></NavigateBeforeIcon>

In case of Buttons, I could do something like component={Link} and to="/vehicles" but I can't figure out how to navigate directly from the icon.

Body:
You can use the useHistory Hook:

import { useHistory } from 'react-router-dom';

function Home() {
  const history = useHistory();

  return <NavigateBeforeIcon onClick={() => history.push('/profile')}
          ></NavigateBeforeIcon>
}

With it you can build a custom component.