问:
Specify what interface use to send multicast IGMP JOIN (c# socket)
I would like to choose which network interface to use to send a join request.
This is the code I tried but I don't think it's right:</p>
```<code>static int GetNicIndexByIP(String ipAddress)
{
    int adapterIndex = -1;
    IPAddressInformation[] adapterIPs;

    foreach (NetworkInterface adapter in nics)
    {
        adapterIPs = adapter.GetIPProperties().UnicastAddresses.ToArray();
        adapterIndex = (int)IPAddress.HostToNetworkOrder(adapter.GetIPProperties().GetIPv4Properties().Index);

        foreach (IPAddressInformation ip in adapterIPs)
        {
            if (ip.Address.ToString() == ipAddress)
                return adapterIndex;
        }
    }

    return -1;
}

string nicAddress = "192.168.1.100";
string multicastAddress = "229.1.0.1";
int nicIndex = GetNicIndexByIP(nicAddress);
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

// first try: ignored (sent from another interface)
client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, nicIndex);
client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse(multicastAddress)));

// second try: error argument "229.1.0.1" out of range
client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse(multicastAddress), nicIndex));
</code>```

答:
if anyone is interested, I found the answer myself:</p>

```<code>MulticastOption mcastOption = new MulticastOption(IPAddress.Parse(multicastAddress), IPAddress.Parse(nicAddress));
client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, mcastOption);
</code>```

Body:
I would like to choose which network interface to use to send a join request.
This is the code I tried but I don't think it's right:

static int GetNicIndexByIP(String ipAddress)
{
    int adapterIndex = -1;
    IPAddressInformation[] adapterIPs;

    foreach (NetworkInterface adapter in nics)
    {
        adapterIPs = adapter.GetIPProperties().UnicastAddresses.ToArray();
        adapterIndex = (int)IPAddress.HostToNetworkOrder(adapter.GetIPProperties().GetIPv4Properties().Index);

        foreach (IPAddressInformation ip in adapterIPs)
        {
            if (ip.Address.ToString() == ipAddress)
                return adapterIndex;
        }
    }

    return -1;
}

string nicAddress = "192.168.1.100";
string multicastAddress = "229.1.0.1";
int nicIndex = GetNicIndexByIP(nicAddress);
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

// first try: ignored (sent from another interface)
client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, nicIndex);
client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse(multicastAddress)));

// second try: error argument "229.1.0.1" out of range
client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse(multicastAddress), nicIndex));

Body:
if anyone is interested, I found the answer myself:

MulticastOption mcastOption = new MulticastOption(IPAddress.Parse(multicastAddress), IPAddress.Parse(nicAddress));
client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, mcastOption);


来源: stackexchange

问:
error: incompatible type for argument in c
I have to input min and max value of array by using function minmax(double *x,double *y).
When I compile it, there are some strange errors: incompatible type for argument 1 of minmax;  incompatible type for argument 2 of minmax. But idk where is a mistake. pls explain

The problem is to input max and min of array inputed from a file. I fulled file with some values.
and then sorted them from min to max.

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

void input (int *psize, double arr[]);
void output (int size, double arr[]);
void minmax (double *x, double *y);
int sorting(int size, double arr[]);

int main(){
    double arr[100];
    int size,i;
    input(&size,arr);
    output(size, arr);
    printf("\n");

    sorting(size, arr);
    output(size, arr);

    minmax(arr[0],arr[size-1]);

}

void input (int *psize, double arr[]){
    FILE *array;
    array = fopen("12_3.txt", "r");
    int t_size=0;
    if (array == NULL){
        printf("CANNOT OPEN FILE");
        exit(1);
    }
    if (array!=NULL)
    {
        while( !feof(array))
            {
            fscanf(array, "%lf", &arr[t_size]);
            t_size++;
            }
        *psize=t_size-1;
        fclose(array);

    }
}

void output (int size, double arr[]){
    for (int i=0; i<size; i++)
        {
            printf("%f \n",arr[i]);
        }
}

void minmax (double*x, double*y){
    printf("\nmax:  %f\n", *x);
    printf("min:  %f\n", *y);
}

int sorting(int size, double arr[]){
    for (int i = 0; i < size - 1; i++)
        {
        for (int j = 0; j < size - i - 1; j++)
            {
            if (arr[j] > arr[j + 1])
                {
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
                }
            }
        }
}
</code>```

答:
The parameters of minmax() - y and x - are of type pointer to double (double *).

The arguments of arr[0] and arr[size-1] at the call to minmax() are of type double.

There is a mismatch. Pointer to double vs. double.

Omit the * operator for x and y at the definition/declaration of minmax():

```<code>void minmax (double x, double y) { ...
</code>```

as well as as arguments at the calls to printf():

```<code>printf("\nmax:  %f\n", x);
printf("min:  %f\n", y);
</code>```

Result:

```<code>void minmax (double x, double y);      // Function prototype.

....

void minmax (double x, double y) {     // Function definition.
    printf("\nmax:  %f\n", x);
    printf("min:  %f\n", y);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have to input min and max value of array by using function minmax(double *x,double *y).
When I compile it, there are some strange errors: incompatible type for argument 1 of minmax;  incompatible type for argument 2 of minmax. But idk where is a mistake. pls explain

The problem is to input max and min of array inputed from a file. I fulled file with some values.
and then sorted them from min to max.

#include<stdio.h>
#include<math.h>

void input (int *psize, double arr[]);
void output (int size, double arr[]);
void minmax (double *x, double *y);
int sorting(int size, double arr[]);

int main(){
    double arr[100];
    int size,i;
    input(&size,arr);
    output(size, arr);
    printf("\n");

    sorting(size, arr);
    output(size, arr);

    minmax(arr[0],arr[size-1]);

}

void input (int *psize, double arr[]){
    FILE *array;
    array = fopen("12_3.txt", "r");
    int t_size=0;
    if (array == NULL){
        printf("CANNOT OPEN FILE");
        exit(1);
    }
    if (array!=NULL)
    {
        while( !feof(array))
            {
            fscanf(array, "%lf", &arr[t_size]);
            t_size++;
            }
        *psize=t_size-1;
        fclose(array);

    }
}

void output (int size, double arr[]){
    for (int i=0; i<size; i++)
        {
            printf("%f \n",arr[i]);
        }
}

void minmax (double*x, double*y){
    printf("\nmax:  %f\n", *x);
    printf("min:  %f\n", *y);
}

int sorting(int size, double arr[]){
    for (int i = 0; i < size - 1; i++)
        {
        for (int j = 0; j < size - i - 1; j++)
            {
            if (arr[j] > arr[j + 1])
                {
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
                }
            }
        }
}

Body:
The parameters of minmax() - y and x - are of type pointer to double (double *).

The arguments of arr[0] and arr[size-1] at the call to minmax() are of type double.

There is a mismatch. Pointer to double vs. double.

Omit the * operator for x and y at the definition/declaration of minmax():

void minmax (double x, double y) { ...

as well as as arguments at the calls to printf():

printf("\nmax:  %f\n", x);
printf("min:  %f\n", y);

Result:

void minmax (double x, double y);      // Function prototype.

....

void minmax (double x, double y) {     // Function definition.
    printf("\nmax:  %f\n", x);
    printf("min:  %f\n", y);
}


问:
How to animate images onslide of ViewPager?
How do I animate objects on swipe of fragments in Viewpager? I want to achieve something like this.

答:
I think you are looking for something called the MotionLayout

You will need to create a MotionScene file can contain all that is needed for specifying the animation.

You can find a detailed explanation here: https://medium.com/google-developers/introduction-to-motionlayout-part-iii-47cd64d51a5

What you want is motionlayout with viewpager

Best of luck


问:
Multiple refs in react
I have a Container, that should have references to some of it's children components:

```<code>const Container = () => {
  const blocks: HTMLDivElement[] = [];

  return (
    <div>
      <Navigation currentBlock={currentBlock} blocks={blocks} />
      <div ref={(ref) => ref && blocks.push(ref)}>
        // ...
      </div>
      <div ref={(ref) => ref && blocks.push(ref)}>
        // ...
      </div>
      <div ref={(ref) => ref && blocks.push(ref)}>
        // ...
      </div>
      <div ref={(ref) => ref && blocks.push(ref)}>
        // ...
      </div>
    </div>
  );
};
</code>```

But, when I try to render Navigation component, the blocks variable is an empty array.

I tried converting blocks variable to a reference using useRef hook:

```<code>const Container = () => {
  const blocks = useRef<HTMLDivElement[]>([]);

  return (
    <div>
      <Navigation currentBlock={currentBlock} blocks={blocks.current} />
      <div ref={(ref) => ref && blocks.current.push(ref)}>
        // ...
      </div>
      <div ref={(ref) => ref && blocks.current.push(ref)}>
        // ...
      </div>
      <div ref={(ref) => ref && blocks.current.push(ref)}>
        // ...
      </div>
      <div ref={(ref) => ref && blocks.current.push(ref)}>
        // ...
      </div>
    </div>
  );
};
</code>```

blocks is still an empty array on render, but after that it becomes a valid array of references that I wanted.

Is there any way to update Navigation component without rerendering Container?

EDIT:
Here's my Navigation component:

```<code>const Navigation = ({ currentBlock, blocks }: { currentBlock: number, blocks: MutableRefObject<HTMLDivElement[]>}) => {
  console.log(blocks.current);
  return (
    <nav>
      {blocks.current.map((_, idx) => (
        <NavigationLink key={idx} active={currentBlock === idx} />
      ))}
    </nav>
  );
}
</code>```

In my console, I have this output:

The Navigation component doesn't render any NavigationLinks, as if the array is empty.

答:
To store the refs, you should use the useRef hook. However you must pass on the refs to another component, not by using blocks.current but just blocks. This way it would ensure that the props used by the navigation component can then access the mutated properties since a re-render is not triggered when the refs are assigned

```<code>const Container = () => {
  const blocks = useRef<HTMLDivElement[]>([]);

  return (
    <div>
      <Navigation currentBlock={currentBlock} blocks={blocks} />
      <div ref={(ref) => ref && blocks.current.push(ref)}>
        // ...
      </div>
      <div ref={(ref) => ref && blocks.current.push(ref)}>
        // ...
      </div>
      <div ref={(ref) => ref && blocks.current.push(ref)}>
        // ...
      </div>
      <div ref={(ref) => ref && blocks.current.push(ref)}>
        // ...
      </div>
    </div>
  );
};
</code>```

Now inside the Navigation component you can make use of props.blocks.current

Title: Multiple refs in react

Body:
I have a Container, that should have references to some of it's children components:

const Container = () => {
  const blocks: HTMLDivElement[] = [];

  return (

      <Navigation currentBlock={currentBlock} blocks={blocks} />

 ref && blocks.push(ref)}>
        // ...

 ref && blocks.push(ref)}>
        // ...

 ref && blocks.push(ref)}>
        // ...

 ref && blocks.push(ref)}>
        // ...

  );
};

But, when I try to render Navigation component, the blocks variable is an empty array.

I tried converting blocks variable to a reference using useRef hook:

const Container = () => {
  const blocks = useRef<HTMLDivElement[]>([]);

  return (

      <Navigation currentBlock={currentBlock} blocks={blocks.current} />

 ref && blocks.current.push(ref)}>
        // ...

 ref && blocks.current.push(ref)}>
        // ...

 ref && blocks.current.push(ref)}>
        // ...

 ref && blocks.current.push(ref)}>
        // ...

  );
};

blocks is still an empty array on render, but after that it becomes a valid array of references that I wanted.

Is there any way to update Navigation component without rerendering Container?

EDIT:
Here's my Navigation component:

const Navigation = ({ currentBlock, blocks }: { currentBlock: number, blocks: MutableRefObject<HTMLDivElement[]>}) => {
  console.log(blocks.current);
  return (

      {blocks.current.map((_, idx) => (
        <NavigationLink key={idx} active={currentBlock === idx} />
      ))}

  );
}

In my console, I have this output:

The Navigation component doesn't render any NavigationLinks, as if the array is empty.

Body:
To store the refs, you should use the useRef hook. However you must pass on the refs to another component, not by using blocks.current but just blocks. This way it would ensure that the props used by the navigation component can then access the mutated properties since a re-render is not triggered when the refs are assigned

const Container = () => {
  const blocks = useRef<HTMLDivElement[]>([]);

  return (
    <div>
      <Navigation currentBlock={currentBlock} blocks={blocks} />
      <div ref={(ref) => ref && blocks.current.push(ref)}>
        // ...
      </div>
      <div ref={(ref) => ref && blocks.current.push(ref)}>
        // ...
      </div>
      <div ref={(ref) => ref && blocks.current.push(ref)}>
        // ...
      </div>
      <div ref={(ref) => ref && blocks.current.push(ref)}>
        // ...
      </div>
    </div>
  );
};

Now inside the Navigation component you can make use of props.blocks.current


问:
Can a single Blazor project contains both WebAssembly part and server-side part?
Now that Blazor WebAssembly is officially released, I gave it a try by creating my first Blazor wasm project using the template, but quickly noticed that one thing is pretty different what I would expect. It appears that there is no "server" part in the template, and the published result consists only of static assets (including all the .dll files). Naturally, I then wonder how may I access my online database? Allowing client-side to have direct access to my database sounds like a terrible idea (if it can be done at all), since I will have to include my connection string somewhere in my client-side code... definitely NO!

And after a quick search on Google, it seems that everyone is using another server to serve the data using API. OK, fine, but wouldn't it be much better if I can include my server part in the same project, and communicate with my client-side also using WebSocket (just like in Blazor server) rather than API? Is that possible?

答:
You can create an ASP.NET Core Hosted project, that gives you a Wasm client and an API server in one solution.

and communicate with my client-side also using WebSocket .. rather than API?

Yes, the SignalR client runs on .netstandard 2.x , just what Blazor/Wasm needs.

You can easily set up a Hub in the server part.

The official docs are here: Use ASP.NET Core SignalR with Blazor WebAssembly, they contain a complete example.


问:
Iterate array elements in specific order
I am trying to iterate a 1D-array/vector of integers in a specific order, but I can't wrap my head around it, to get the loop conditions right.

The input data is a one-dimensional vector of integers:

```<code>{1, 5, 9, 13, 17, 21, 2, 6, 10, 14, 18, 22, 3, 7, 11, 15, 19, 23, 4, 8, 12, 16, 20, 24, 25, 29, 33, 37, 41, 45, 26, 30, 34, 38, 42, 46, 27, 31, 35, 39, 43, 47, 28, 32, 36, 40, 44, 48}
</code>```

This input data is essentially a one dimensional representation of a 2D array/grid with subgroups:

```<code>+----+----+----+----+----+----+
| 1  | 5  | 9  | 13 | 17 | 21 |
+----+----+----+----+----+----+
| 2  | 6  | 10 | 14 | 18 | 22 |
+----+----+----+----+----+----+
| 3  | 7  | 11 | 15 | 19 | 23 |
+----+----+----+----+----+----+
| 4  | 8  | 12 | 16 | 20 | 24 |
+----+----+----+----+----+----+
| 25 | 29 | 33 | 37 | 41 | 45 |
+----+----+----+----+----+----+
| 26 | 30 | 34 | 38 | 42 | 46 |
+----+----+----+----+----+----+
| 27 | 31 | 35 | 39 | 43 | 47 |
+----+----+----+----+----+----+
| 28 | 32 | 36 | 40 | 44 | 48 |
+----+----+----+----+----+----+
</code>```

This table is is grouped into multiple 2x4 subgroups:

I want to iterate this 1D input vector/array in the order that is indicated by the numbers. (Essentially going through every 2x4 subgroup, one after another).
Inside of the loop, I want to load the 8 elements of the currently processed subgroup in a vector/int for further processing.
So in the end I should process 6 subgroups, the first one holding the numbers 1 to 8, the second one 9 to 16 and so fourth ..
The groups should be processed from left to right.

Note: The numbers in the input data just serve as an example, to make clear in which order the data should be processed. The input data could contain totally random values. The order of the values in each group should be kept. There should be no sorting/reordering inside a group. What is important are the constraints for the subgroup/array dimensions etc.

Together with the 1D array/vector I do know the dimensions of the grid and the size of the subgroups:

```<code>int grid_width = 6; // Variable, but will always be a multiple of 2, to match subgroup width
int grid_height = 8;  // Variable, but will always be a multiple of 4, to match subgroup height
const int group_width = 2; // Constant, subgroup width is always 2.
const int group_height = 4; // Constant, subgroup height is always 4.
</code>```

My idea was to have one loop that iterates over the entire data, and then two loops that process the subgroups accordingly. But I really struggle getting the loop conditions and indices for the elements correct. My thought-process was something like this:

```<code>// Iterate over entire data
for (int i = 0; i < grid_width * grid_height; i += (group_width * group_height))
{
    int block[8];
    // Iterate groups in correct order
    for (int j = 0; j < group_height; j++)
    {
        for (int k = 0; k < group_width; k++)
        {
            // Grab current element in group
            int value = input_array[i * grid_width + j]; // ?? This ain't right

            // Add element to group array/vector
            block[??] = ??;
        }
    }

    // Do further processing with the group array
}
</code>```

Can someone help me to loop over this correctly?
I hope the question is clear enough. If not, let me know.

答:
I could not see an understandable answer so far and therefore I will add one and also with very easy understandable and step by step code.

Code without comments and explanations has basically no meaning.

This problem at hand can be solved by using integer and modulo division and might be a training task for that. It is important to understand that we will of course need to calculate indices. Therefore, as a first abstraction, I show an example picture, but here using mainly indices. Please note: In C++ indices start with 0.

What you want to have, is groups, with indices as shown on the left side. The right side simple shows indices as per the source data given. We just have a new line or new row after all horizontal groups have been drawn.

The important properties are:

group width,

group height,

number of groups in horzontal direction

number of groups in vertical direction

From these basic given source properties we can calculate additionally and simply:

number of elements per group -> group width * group heigth

number of overall elements -> group width * group heigth * number of groups in horzontal direction * number of groups in vertical direction

There are more values that are important and can be calculated easily: For example

offfset in next row -> group width * number of groups in horzontal direction

offset in next vertical group -> offset in next row * group height

number of resulting groups ->  number of groups in horzontal direction * number of groups in vertical direction

Everything here is straightforward and easy understandable. Let us look at the example now.

Having a group width of 2 and a group height of 4, we have 8 elements per group.

Having 3 groups in horizontal direction, we observe that the index of an element in a next row is always: group width * number of groups in horizontal direction = 2 * 3 = 6 greater, than in the line above.

If we want to know the row offset in one group (with the height 4) for any row, regardless of the group, then we can first calculate index % group height, so, index % 4. which will result in a numbering sequence: 0,1,2,3,0,1,2,3,0,1,2,3 . . .

If we multiply this with the 6 above, we get: 0,6,12,18,0,6,12,18,0,6,12,18,...

Please look at the picture. If we go one row down in one group, we go 6 indices down. Lets call this as the row offset.

Next we need to check the columns. If we look at the columns, then we see that the first 4 elements of the target are in column 0, the next 4 elements are in column 1 and so on. So, we can simply calculate the columns by the integer division: index / group height. We get a sequence of: 0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6,7,7,7,7,8,8,8,8,...

This offset needs to be limited to the maximum column per row, which we do again with a modulo division by the previously calculated row width, in our example 6. Result is then 0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0,1,1,1,1,2,2,2,2,...

This we will call the column offset.

If we add the column offset with the row offset (with the above multiplied by 6 values), then we get already 0,6,12,18,1,7,13,19,2,8,14,20,3,9,15,21, . . .

So, this works already for the first horizontal groups.

The vertical group offset is simple. Basically the offset is: Index-Offset-To-Next-Vertical-Group = Index-Offset-To-Next-Row * GroupHeight = 6 * 4 = 24.

And, if we want to have the group-row-offset, then we simply make an integer division by the above calculated value (index / 24) and multiply that again with 24. This results in a sequence: 0....0,24....24,48....48,72....72,96....96,...

Lets call this thing vertical group offset.

If we add all offsets together, then we get the index in the source data by one simple calculation. Please note: For the ease of understanding, I splitted this in the below shown software into the described 3 parts.

Next come the target offsets. We need to calculate the group number: It is simply the index / number of elements per group, easy to understand. For a running source index this is 0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,.....

And the target index in the group is also simple. It is index % number of elements per group, so: 0,1,2,3,4,5,6,7,0,1,2,3,4,5,6,7,0,1,2,.....

Now, we splitted the one big problem into many smaller problems that could be solved by far more easier.

Basically, the whole copy loop can be done with a one liner, if we put all the calculated values directly in the assignment and omit the temporary constants.

Please see now the full and easy to understand and well commented code example.

```<code>#include <iostream>
#include <vector>
#include <array>

int main() {

    // This you may change --------------------------------------------------------------------------------------

    // Source data
    std::vector values{1, 5, 9, 13, 17, 21, 2, 6, 10, 14, 18, 22, 3, 7, 11, 15, 19, 23, 4, 8, 12, 16, 20, 24, 25, 29, 33, 37, 41, 45, 26, 30, 34, 38, 42, 46, 27, 31, 35, 39, 43, 47, 28, 32, 36, 40, 44, 48};

    // Define the dimension of one group
    constexpr unsigned int GroupWidth =  2;
    constexpr unsigned int GroupHeight = 4;

    // Define, how many groups we have in horizontal and vertical direction
    constexpr unsigned int NumberOfGroupsHorizontal = 3;
    constexpr unsigned int NumberOfGroupsVertical   = 2;

    // Calculated values ---------------------------------------------------------------------------

    // Resulting capacity values
    constexpr unsigned int NumberOfElementsPerGroup = GroupWidth * GroupHeight;
    constexpr unsigned int NumberOfOverallElements = GroupWidth * GroupHeight * NumberOfGroupsHorizontal * NumberOfGroupsVertical;

    // Resulting offset values for indices
    constexpr unsigned int IndexOffsetToNextRow = GroupWidth * NumberOfGroupsHorizontal;
    constexpr unsigned int IndexOffsetToNextVerticalGroup = IndexOffsetToNextRow * GroupHeight;

    // How many groups do we have overall
    constexpr unsigned int NumberOfResultingGroups = NumberOfGroupsHorizontal * NumberOfGroupsVertical;

    // First make a sanity check, if parameters are ok. Handles also 0-values
    if (values.size() == NumberOfOverallElements) {

        // Copy algorithm ------------------------------------------------------------------------------

        // Here, we will store the result
        std::array<std::array<int, NumberOfElementsPerGroup>, NumberOfResultingGroups> result{};

        // Iterate over all source data
        for (unsigned int index = 0; index < NumberOfOverallElements; ++index) {

            // Calculate index in array of source data -------------------------------------------------
            // Row offset per group
            const unsigned int  o1 = (index % GroupHeight) * IndexOffsetToNextRow;
            // Column offset
            const unsigned int  o2 = (index / GroupHeight) % IndexOffsetToNextRow;
            // Vertical group offset
            const unsigned int  o3 = (index / IndexOffsetToNextVerticalGroup) * IndexOffsetToNextVerticalGroup;

            // Overall calculated index / offset. (Above three lines could be put here as a one liner)
            const unsigned int sourceDataIndex = o1 + o2 + o3;

            // The target group index ------------------------------------------------------------------
            const unsigned int targetGroupIndex = index / NumberOfElementsPerGroup;

            // The index in the target group
            const unsigned int indexInTargetGroup = index % NumberOfElementsPerGroup;

            // Copy resulting value --------------------------------------------------------------------
            result[targetGroupIndex][indexInTargetGroup] = values[sourceDataIndex];
        }

        // Show result to the user
        for (const auto& a : result) {
            for (const int i : a) std::cout << i << ' ';
            std::cout << '\n';
        }
    }
    else {
        // Some problem occured
        std::cerr << "\n*** Error: Wrong source data size or parameters\n";
    }
    return 0;
}
</code>```

And with the above know how, you can now build one simple function:

```<code>std::vector<std::vector<int>> split(const std::vector<int>& v, const size_t ngh, const size_t ngv, const size_t gw=2U, const size_t gh=4U) {

    // Define resulting 2d vector
    std::vector<std::vector<int>> result(ngh * ngv, std::vector<int>(gw * gh,0));

    // Sanity check. Will also handle parameters being 0
    if (v.size() == gw*gh*ngv*ngh)
        // Copy values in simple for loop
        for (size_t i = 0U; i < v.size(); ++i)
            result[i/(gw*gh)][i%(gw*gh)] = v[((i%gh)*gw*ngh) + ((i/gh)%(gw*ngh)) + ((i/(gh*gw*ngh))*(gh*gw*ngh))] ;

    return result;
}
</code>```

Body:
I am trying to iterate a 1D-array/vector of integers in a specific order, but I can't wrap my head around it, to get the loop conditions right.

The input data is a one-dimensional vector of integers:

{1, 5, 9, 13, 17, 21, 2, 6, 10, 14, 18, 22, 3, 7, 11, 15, 19, 23, 4, 8, 12, 16, 20, 24, 25, 29, 33, 37, 41, 45, 26, 30, 34, 38, 42, 46, 27, 31, 35, 39, 43, 47, 28, 32, 36, 40, 44, 48}

This input data is essentially a one dimensional representation of a 2D array/grid with subgroups:

+----+----+----+----+----+----+
| 1  | 5  | 9  | 13 | 17 | 21 |
+----+----+----+----+----+----+
| 2  | 6  | 10 | 14 | 18 | 22 |
+----+----+----+----+----+----+
| 3  | 7  | 11 | 15 | 19 | 23 |
+----+----+----+----+----+----+
| 4  | 8  | 12 | 16 | 20 | 24 |
+----+----+----+----+----+----+
| 25 | 29 | 33 | 37 | 41 | 45 |
+----+----+----+----+----+----+
| 26 | 30 | 34 | 38 | 42 | 46 |
+----+----+----+----+----+----+
| 27 | 31 | 35 | 39 | 43 | 47 |
+----+----+----+----+----+----+
| 28 | 32 | 36 | 40 | 44 | 48 |
+----+----+----+----+----+----+

This table is is grouped into multiple 2x4 subgroups:

I want to iterate this 1D input vector/array in the order that is indicated by the numbers. (Essentially going through every 2x4 subgroup, one after another).
Inside of the loop, I want to load the 8 elements of the currently processed subgroup in a vector/int for further processing.
So in the end I should process 6 subgroups, the first one holding the numbers 1 to 8, the second one 9 to 16 and so fourth ..
The groups should be processed from left to right.

Note: The numbers in the input data just serve as an example, to make clear in which order the data should be processed. The input data could contain totally random values. The order of the values in each group should be kept. There should be no sorting/reordering inside a group. What is important are the constraints for the subgroup/array dimensions etc.

Together with the 1D array/vector I do know the dimensions of the grid and the size of the subgroups:

int grid_width = 6; // Variable, but will always be a multiple of 2, to match subgroup width
int grid_height = 8;  // Variable, but will always be a multiple of 4, to match subgroup height
const int group_width = 2; // Constant, subgroup width is always 2.
const int group_height = 4; // Constant, subgroup height is always 4.

My idea was to have one loop that iterates over the entire data, and then two loops that process the subgroups accordingly. But I really struggle getting the loop conditions and indices for the elements correct. My thought-process was something like this:

// Iterate over entire data
for (int i = 0; i < grid_width * grid_height; i += (group_width * group_height))
{
    int block[8];
    // Iterate groups in correct order
    for (int j = 0; j < group_height; j++)
    {
        for (int k = 0; k < group_width; k++)
        {
            // Grab current element in group
            int value = input_array[i * grid_width + j]; // ?? This ain't right

            // Add element to group array/vector
            block[??] = ??;
        }
    }

    // Do further processing with the group array
}

Can someone help me to loop over this correctly?
I hope the question is clear enough. If not, let me know.

Body:
I could not see an understandable answer so far and therefore I will add one and also with very easy understandable and step by step code.

Code without comments and explanations has basically no meaning.

This problem at hand can be solved by using integer and modulo division and might be a training task for that. It is important to understand that we will of course need to calculate indices. Therefore, as a first abstraction, I show an example picture, but here using mainly indices. Please note: In C++ indices start with 0.

What you want to have, is groups, with indices as shown on the left side. The right side simple shows indices as per the source data given. We just have a new line or new row after all horizontal groups have been drawn.

The important properties are:

group width,

group height,

number of groups in horzontal direction

number of groups in vertical direction

From these basic given source properties we can calculate additionally and simply:

number of elements per group -> group width * group heigth

number of overall elements -> group width * group heigth * number of groups in horzontal direction * number of groups in vertical direction

There are more values that are important and can be calculated easily: For example

offfset in next row -> group width * number of groups in horzontal direction

offset in next vertical group -> offset in next row * group height

number of resulting groups ->  number of groups in horzontal direction * number of groups in vertical direction

Everything here is straightforward and easy understandable. Let us look at the example now.

Having a group width of 2 and a group height of 4, we have 8 elements per group.

Having 3 groups in horizontal direction, we observe that the index of an element in a next row is always: group width * number of groups in horizontal direction = 2 * 3 = 6 greater, than in the line above.

If we want to know the row offset in one group (with the height 4) for any row, regardless of the group, then we can first calculate index % group height, so, index % 4. which will result in a numbering sequence: 0,1,2,3,0,1,2,3,0,1,2,3 . . .

If we multiply this with the 6 above, we get: 0,6,12,18,0,6,12,18,0,6,12,18,...

Please look at the picture. If we go one row down in one group, we go 6 indices down. Lets call this as the row offset.

Next we need to check the columns. If we look at the columns, then we see that the first 4 elements of the target are in column 0, the next 4 elements are in column 1 and so on. So, we can simply calculate the columns by the integer division: index / group height. We get a sequence of: 0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6,7,7,7,7,8,8,8,8,...

This offset needs to be limited to the maximum column per row, which we do again with a modulo division by the previously calculated row width, in our example 6. Result is then 0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0,1,1,1,1,2,2,2,2,...

This we will call the column offset.

If we add the column offset with the row offset (with the above multiplied by 6 values), then we get already 0,6,12,18,1,7,13,19,2,8,14,20,3,9,15,21, . . .

So, this works already for the first horizontal groups.

The vertical group offset is simple. Basically the offset is: Index-Offset-To-Next-Vertical-Group = Index-Offset-To-Next-Row * GroupHeight = 6 * 4 = 24.

And, if we want to have the group-row-offset, then we simply make an integer division by the above calculated value (index / 24) and multiply that again with 24. This results in a sequence: 0....0,24....24,48....48,72....72,96....96,...

Lets call this thing vertical group offset.

If we add all offsets together, then we get the index in the source data by one simple calculation. Please note: For the ease of understanding, I splitted this in the below shown software into the described 3 parts.

Next come the target offsets. We need to calculate the group number: It is simply the index / number of elements per group, easy to understand. For a running source index this is 0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,.....

And the target index in the group is also simple. It is index % number of elements per group, so: 0,1,2,3,4,5,6,7,0,1,2,3,4,5,6,7,0,1,2,.....

Now, we splitted the one big problem into many smaller problems that could be solved by far more easier.

Basically, the whole copy loop can be done with a one liner, if we put all the calculated values directly in the assignment and omit the temporary constants.

Please see now the full and easy to understand and well commented code example.

#include <iostream>
#include <vector>
#include <array>

int main() {

    // This you may change --------------------------------------------------------------------------------------

    // Source data
    std::vector values{1, 5, 9, 13, 17, 21, 2, 6, 10, 14, 18, 22, 3, 7, 11, 15, 19, 23, 4, 8, 12, 16, 20, 24, 25, 29, 33, 37, 41, 45, 26, 30, 34, 38, 42, 46, 27, 31, 35, 39, 43, 47, 28, 32, 36, 40, 44, 48};

    // Define the dimension of one group
    constexpr unsigned int GroupWidth =  2;
    constexpr unsigned int GroupHeight = 4;

    // Define, how many groups we have in horizontal and vertical direction
    constexpr unsigned int NumberOfGroupsHorizontal = 3;
    constexpr unsigned int NumberOfGroupsVertical   = 2;

    // Calculated values ---------------------------------------------------------------------------

    // Resulting capacity values
    constexpr unsigned int NumberOfElementsPerGroup = GroupWidth * GroupHeight;
    constexpr unsigned int NumberOfOverallElements = GroupWidth * GroupHeight * NumberOfGroupsHorizontal * NumberOfGroupsVertical;

    // Resulting offset values for indices
    constexpr unsigned int IndexOffsetToNextRow = GroupWidth * NumberOfGroupsHorizontal;
    constexpr unsigned int IndexOffsetToNextVerticalGroup = IndexOffsetToNextRow * GroupHeight;

    // How many groups do we have overall
    constexpr unsigned int NumberOfResultingGroups = NumberOfGroupsHorizontal * NumberOfGroupsVertical;

    // First make a sanity check, if parameters are ok. Handles also 0-values
    if (values.size() == NumberOfOverallElements) {

        // Copy algorithm ------------------------------------------------------------------------------

        // Here, we will store the result
        std::array<std::array<int, NumberOfElementsPerGroup>, NumberOfResultingGroups> result{};

        // Iterate over all source data
        for (unsigned int index = 0; index < NumberOfOverallElements; ++index) {

            // Calculate index in array of source data -------------------------------------------------
            // Row offset per group
            const unsigned int  o1 = (index % GroupHeight) * IndexOffsetToNextRow;
            // Column offset
            const unsigned int  o2 = (index / GroupHeight) % IndexOffsetToNextRow;
            // Vertical group offset
            const unsigned int  o3 = (index / IndexOffsetToNextVerticalGroup) * IndexOffsetToNextVerticalGroup;

            // Overall calculated index / offset. (Above three lines could be put here as a one liner)
            const unsigned int sourceDataIndex = o1 + o2 + o3;

            // The target group index ------------------------------------------------------------------
            const unsigned int targetGroupIndex = index / NumberOfElementsPerGroup;

            // The index in the target group
            const unsigned int indexInTargetGroup = index % NumberOfElementsPerGroup;

            // Copy resulting value --------------------------------------------------------------------
            result[targetGroupIndex][indexInTargetGroup] = values[sourceDataIndex];
        }

        // Show result to the user
        for (const auto& a : result) {
            for (const int i : a) std::cout << i << ' ';
            std::cout << '\n';
        }
    }
    else {
        // Some problem occured
        std::cerr << "\n*** Error: Wrong source data size or parameters\n";
    }
    return 0;
}

And with the above know how, you can now build one simple function:

std::vector<std::vector<int>> split(const std::vector<int>& v, const size_t ngh, const size_t ngv, const size_t gw=2U, const size_t gh=4U) {

    // Define resulting 2d vector
    std::vector<std::vector<int>> result(ngh * ngv, std::vector<int>(gw * gh,0));

    // Sanity check. Will also handle parameters being 0
    if (v.size() == gw*gh*ngv*ngh)
        // Copy values in simple for loop
        for (size_t i = 0U; i < v.size(); ++i)
            result[i/(gw*gh)][i%(gw*gh)] = v[((i%gh)*gw*ngh) + ((i/gh)%(gw*ngh)) + ((i/(gh*gw*ngh))*(gh*gw*ngh))] ;

    return result;
}


问:
Unique values of Dictionary comprehension, return dictionary instread of string
this is my data:

```<code>data = [{'id': 1, 'name': 'The Musical Hop', 'city': 'San Francisco', 'state': 'CA'},
{'id': 2, 'name': 'The Dueling Pianos Bar', 'city': 'New York', 'state': 'NY'},
{'id': 3, 'name': 'Park Square Live Music & Coffee', 'city': 'San Francisco', 'state': 'CA'}]
</code>```

I want to find out the unique values (thats why I use a set) of "city" and return them like this:

```<code>cities = set([x.get("city") for x in data])
cities ´

{'New York', 'San Francisco'}
</code>```

However, I also want to return the corresponding state, like this:

```<code>[{"city": "New York", "state": "NY"}, {"city":  "San Francisco", "state": "CA"}]
</code>```

Is there a way to do this?

答:
you can use a dict-comprehension to create a city->state mapping, then iterate it to create the list you want:

city_to_state = {x["city"]: x["state"] for x in data}
result = [{"city":k, "state":v} for k,v in city_to_state.items()]
```

Body:
this is my data:

data = [{'id': 1, 'name': 'The Musical Hop', 'city': 'San Francisco', 'state': 'CA'},
{'id': 2, 'name': 'The Dueling Pianos Bar', 'city': 'New York', 'state': 'NY'},
{'id': 3, 'name': 'Park Square Live Music & Coffee', 'city': 'San Francisco', 'state': 'CA'}]

I want to find out the unique values (thats why I use a set) of "city" and return them like this:

cities = set([x.get("city") for x in data])
cities ´

{'New York', 'San Francisco'}

However, I also want to return the corresponding state, like this:

[{"city": "New York", "state": "NY"}, {"city":  "San Francisco", "state": "CA"}]

Is there a way to do this?


问:
Mutable state update in react
For example, we have a state defined like this which is having some todos and we want to change done of that todo if they are completed

```<code>this.state = {
  // store an array of todo objects
  todos: [
    { task: 'do the dishes', done: false, id: 1 },
    { task: 'vacuum the floor', done: true, id: 2 }
  ]
};
</code>```

For that, we can do this away.

```<code>  const theTodo = this.state.todos.find(t => t.id === id);
  theTodo.done = true; // NOOOOO

  this.setState({
    todos: this.state.todos
  });
</code>```

}

But I am a little confused that find method on the array will return us the element which matches the condition inside it and we store it in a different variable and then access done to change it to true.
But still, we haven't changed the original state value as this was a copy one.

Then how come we can use this to save it?

```<code> this.setState({
    todos: this.state.todos // bad
  });
</code>```

答:
The reason the code works is because State Updates are Merged.

When you call setState(), React merges the object you provide into the current state.

But, it is just a bad practice You shouldn't mutate this.state directly.

Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.

For completeness, just pass a function to this.setState and use map to save the immutablillity rule.

Passing an update function allows you to access the current state value inside the updater.

```<code>this.setState((prevState) => {
  const todos = prevState.todos.map((todo) =>
    todo.id === id ? { ...todo, done: true } : todo
  );
  return { todos };
});
</code>```

Title: Mutable state update in react

Body:
For example, we have a state defined like this which is having some todos and we want to change done of that todo if they are completed

this.state = {
  // store an array of todo objects
  todos: [
    { task: 'do the dishes', done: false, id: 1 },
    { task: 'vacuum the floor', done: true, id: 2 }
  ]
};

For that, we can do this away.

  const theTodo = this.state.todos.find(t => t.id === id);
  theTodo.done = true; // NOOOOO

  this.setState({
    todos: this.state.todos
  });

}

But I am a little confused that find method on the array will return us the element which matches the condition inside it and we store it in a different variable and then access done to change it to true.
But still, we haven't changed the original state value as this was a copy one.

Then how come we can use this to save it?

 this.setState({
    todos: this.state.todos // bad
  });

Body:
The reason the code works is because State Updates are Merged.

When you call setState(), React merges the object you provide into the current state.

But, it is just a bad practice You shouldn't mutate this.state directly.

Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.

For completeness, just pass a function to this.setState and use map to save the immutablillity rule.

Passing an update function allows you to access the current state value inside the updater.

this.setState((prevState) => {
  const todos = prevState.todos.map((todo) =>
    todo.id === id ? { ...todo, done: true } : todo
  );
  return { todos };
});


问:
How to add a asterisk red mark for textview/edittext in android for making it as a mandatory field?
I have fields such as email, contact, address and city name in my android app.. I want to make that fields as mandatory to be filled by the user and for the same.. I need a asterisk red mark for such fields.. How would I do that? </p>

答:
Make a simple java class AestrickSpanAdjuster

```<code>import android.text.TextPaint;
import android.text.style.MetricAffectingSpan;

public class AestrickSpanAdjuster extends MetricAffectingSpan {
    double ratio = 0.5;

    public AestrickSpanAdjuster(double ratio) {
        this.ratio = ratio;
    }

    @Override
    public void updateDrawState(TextPaint paint) {
        paint.baselineShift += (int) (paint.ascent() * ratio);
    }

    @Override
    public void updateMeasureState(TextPaint paint) {
        paint.baselineShift += (int) (paint.ascent() * ratio);
    }
}
</code>```

Make another class named AestrickUtils

```<code>import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

public class AestrickUtils {

    public static void setAsterick(EditText edittext, String hint, String aestringWithSpace)
    {
        SpannableString mString = new SpannableString(hint+aestringWithSpace);
        if(mString.length() > 0) {
            mString.setSpan(new AestrickSpanAdjuster(0.2), mString.length() - 1,
                    mString.length(), SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        /*edittext.append("\n");
        edittext.append(mString);*/
        edittext.setHint(mString);
    }

    /**
     * This function will apply the a colorful mandatory field aestrick with different type of views mentioned and set as hint or text accordingly
     * @param view View to be modified
     * @param hint Text with black
     * @param aestrickWithSpace text with Custom color
     * @param isText weather to set text or hint with these values
     * @param colorCode color needed for aestrickWithSpace
     */
    public static void setTextViewAsterick(View view, String hint, String aestrickWithSpace, boolean isText, int colorCode)
    {
        SpannableString mString = new SpannableString(hint+aestrickWithSpace);
        if(mString.length() > 0) {
            mString.setSpan(new AestrickSpanAdjuster(0.2), mString.length() - 1,
                    mString.length(), SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
            mString.setSpan(new ForegroundColorSpan(colorCode), mString.length() - 1, mString.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        }
        /*txtView.append("\n");
        txtView.append(mString);*/
    //  txtView.setHint(mString);
        if (view instanceof TextView)
        {
            if (isText)
                ((TextView)view).setText(mString);
            else
            ((TextView)view).setHint(mString);
        }
        else if (view instanceof EditText)
        {
            if (isText)
                ((EditText)view).setText(mString);
            else
            ((EditText)view).setHint(mString);
        }
        else if (view instanceof CheckBox)
        {
            if (isText)
                ((CheckBox)view).setText(mString);
            else
                ((CheckBox)view).setHint(mString);
        }
    }
}
</code>```

Now you can do the following in ou Activity or Fragment class:

```<code>AestrickUtils.setTextViewAsterick(findViewById(R.id.txtLable), getString(R.string.txt_hint), " *",
                true, getResources().getColor(R.color.asterisk_red_color));
</code>```

Body:
Make a simple java class AestrickSpanAdjuster

import android.text.TextPaint;
import android.text.style.MetricAffectingSpan;

public class AestrickSpanAdjuster extends MetricAffectingSpan {
    double ratio = 0.5;

    public AestrickSpanAdjuster(double ratio) {
        this.ratio = ratio;
    }

    @Override
    public void updateDrawState(TextPaint paint) {
        paint.baselineShift += (int) (paint.ascent() * ratio);
    }

    @Override
    public void updateMeasureState(TextPaint paint) {
        paint.baselineShift += (int) (paint.ascent() * ratio);
    }
}

Make another class named AestrickUtils

import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

public class AestrickUtils {

    public static void setAsterick(EditText edittext, String hint, String aestringWithSpace)
    {
        SpannableString mString = new SpannableString(hint+aestringWithSpace);
        if(mString.length() > 0) {
            mString.setSpan(new AestrickSpanAdjuster(0.2), mString.length() - 1,
                    mString.length(), SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        /*edittext.append("\n");
        edittext.append(mString);*/
        edittext.setHint(mString);
    }

    /**
     * This function will apply the a colorful mandatory field aestrick with different type of views mentioned and set as hint or text accordingly
     * @param view View to be modified
     * @param hint Text with black
     * @param aestrickWithSpace text with Custom color
     * @param isText weather to set text or hint with these values
     * @param colorCode color needed for aestrickWithSpace
     */
    public static void setTextViewAsterick(View view, String hint, String aestrickWithSpace, boolean isText, int colorCode)
    {
        SpannableString mString = new SpannableString(hint+aestrickWithSpace);
        if(mString.length() > 0) {
            mString.setSpan(new AestrickSpanAdjuster(0.2), mString.length() - 1,
                    mString.length(), SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
            mString.setSpan(new ForegroundColorSpan(colorCode), mString.length() - 1, mString.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        }
        /*txtView.append("\n");
        txtView.append(mString);*/
    //  txtView.setHint(mString);
        if (view instanceof TextView)
        {
            if (isText)
                ((TextView)view).setText(mString);
            else
            ((TextView)view).setHint(mString);
        }
        else if (view instanceof EditText)
        {
            if (isText)
                ((EditText)view).setText(mString);
            else
            ((EditText)view).setHint(mString);
        }
        else if (view instanceof CheckBox)
        {
            if (isText)
                ((CheckBox)view).setText(mString);
            else
                ((CheckBox)view).setHint(mString);
        }
    }
}

Now you can do the following in ou Activity or Fragment class:

AestrickUtils.setTextViewAsterick(findViewById(R.id.txtLable), getString(R.string.txt_hint), " *",
                true, getResources().getColor(R.color.asterisk_red_color));


问:
Why StringBuilder can't hold huge strings and throwing OOM Exception
I am converting a HTML string to PDF by using iTextSharp XMLWorker. previuosly this was working fine and generates nice pdf files but later I added base64 string Images to My HTML string which I want to show in my PDF. it is working fine for few images( small string ) but when number of images increases parallelly the size of the string increases. I am returning HTML string from a function like this

```<code>sb = new StringBuilder();
tw = new StringWriter(sb);
hw = new HtmlTextWriter(tw);
tblDistrictwiseResults.RenderControl(hw);
return sb.ToString();
</code>```

and now returned HTML string is appending to another string like below

```<code>StringBuilder sb = new StringBuilder();

sbFooter = new StringBuilder();
tw = new StringWriter(sbFooter);
hw = new HtmlTextWriter(tw);
tblFooter.RenderControl(hw);

string pdfString = GetPDFString(paperCode, paperName, true);  //This is the string returned from anothe function
sb.Append(pdfString + "<br />" + sbFooter.ToString()); //concatinating returned string and footer string and saving in another stringbuilder( here I am gettiong OOM Exception )
</code>```

and the string becomes very large but it did not exceed maxcapacity of the StringBuilder.

Please someone help me

EDIT: I am using VS2010(32 bit) and DEV Server 32 bit

答:
.NET has memory limits depending on what binarity you run in. And ones that are leagues short of the OS limits, neveremind the hardware limits: https://learn.microsoft.com/en-us/windows/win32/memory/memory-limits-for-windows-releases

Plus the 2 GiB object limit. And strings or arrays (wich I am betting string builder uses) run into the object size or memory limits notoriously quickly.

By default all .NET code is bitness agnostic. The same code can run as x32 or x64 - or even x16 or x128, if we ever get a runtime for that. Fixing the process to only run on x64 binarity can fix the immediate problem. However the bigger problem is the process itself:

Strings are easily capable of breaking the Memory limits. But they got nothing on Images. Images are huge! They are the book example for a BLOB - Binary Large OBject - a scary thing to keep in memory.

Base64 encoding them makes them about 33% bigger. If you then try to keep a whole PDF document of such giant strings in memory, you can only run into issues. It is a wonder it worked thus far. You need to change your process, so you get way smaler strings in memory. Wich may actually mean a whole lot less concatenation, wich may even invalidate having to use StringBuilder in the first place.

Body:
I am converting a HTML string to PDF by using iTextSharp XMLWorker. previuosly this was working fine and generates nice pdf files but later I added base64 string Images to My HTML string which I want to show in my PDF. it is working fine for few images( small string ) but when number of images increases parallelly the size of the string increases. I am returning HTML string from a function like this

sb = new StringBuilder();
tw = new StringWriter(sb);
hw = new HtmlTextWriter(tw);
tblDistrictwiseResults.RenderControl(hw);
return sb.ToString();

and now returned HTML string is appending to another string like below

StringBuilder sb = new StringBuilder();

sbFooter = new StringBuilder();
tw = new StringWriter(sbFooter);
hw = new HtmlTextWriter(tw);
tblFooter.RenderControl(hw);

string pdfString = GetPDFString(paperCode, paperName, true);  //This is the string returned from anothe function
sb.Append(pdfString + "
" + sbFooter.ToString()); //concatinating returned string and footer string and saving in another stringbuilder( here I am gettiong OOM Exception )

and the string becomes very large but it did not exceed maxcapacity of the StringBuilder.

Please someone help me

EDIT: I am using VS2010(32 bit) and DEV Server 32 bit


问:
how to display a custom list data on the app page in flutter

1[https://i.stack.imgur.com/yI2Cp.png">]1

i have tried this code to retrieve data from subcollection of the same name(userProducts) stored in many firebase documents.How do i display this data in a container on the app page ? I tried using listiew.builder but it doesnt work.
The first function

```<code> static List<products> finalProductsList = [] ;
  productsList() async
  {
    List list_of_products = await Firestore.instance.collection("products")
        .getDocuments()
        .then((val) => val.documents);
    for (int i=0; i<list_of_products.length; i++)
    {
      Firestore.instance.collection("products").document(
          list_of_products[i].documentID.toString()).collection("userProducts").snapshots().listen(CreateListofProducts);
    }
  }
</code>```

Second function

```<code> CreateListofProducts(QuerySnapshot snapshot)async
  {
    var docs = snapshot.documents;
    for (var Doc in docs)
    {
      finalProductsList.add(products.fromFireStore(Doc));
    }
    }
</code>```

CourseModel

```<code>class products {
  final String prodId;
  final String ownerId;
  final String username;
  final String price;
  final String productname;
  final String details;
  final String color;
  final String composition;
  final String washandcare;
  final String sizeandfit;
  final String shopmediaUrl;
  final String id;
  final dynamic likes;
  products({ this.prodId,
    this.ownerId,
    this.username,
    this.price,
    this.details,
    this.productname,
    this.color,
    this.composition,
    this.washandcare,
    this.sizeandfit,
    this.shopmediaUrl,
    this.id,
    this.likes,});

  factory products.fromFireStore(DocumentSnapshot doc)
  {
    Map data = doc.data ;
    return products(
      prodId: doc['prodId'],
      ownerId: doc['ownerId'],
      username: doc['username'],
      price: doc['price'],
      productname: doc['productname'],
      details: doc['details'],
      shopmediaUrl: doc['shopmediaUrl'],
      color:doc['color'],
      composition:doc['composition'],
      washandcare:doc['washandcare'],
      sizeandfit:doc['sizeandfit'],
      likes: doc['likes'],
    );
</code>```

答:
SO if i understand you, you want to get data on multiple collections on multiple documents?

If so... you should use collecionGroup, you can learn how to use here, make sure to adjust your firestore rules.

Body:
1[https://i.stack.imgur.com/yI2Cp.png">]1

i have tried this code to retrieve data from subcollection of the same name(userProducts) stored in many firebase documents.How do i display this data in a container on the app page ? I tried using listiew.builder but it doesnt work.
The first function

 static List<products> finalProductsList = [] ;
  productsList() async
  {
    List list_of_products = await Firestore.instance.collection("products")
        .getDocuments()
        .then((val) => val.documents);
    for (int i=0; i<list_of_products.length; i++)
    {
      Firestore.instance.collection("products").document(
          list_of_products[i].documentID.toString()).collection("userProducts").snapshots().listen(CreateListofProducts);
    }
  }

Second function

 CreateListofProducts(QuerySnapshot snapshot)async
  {
    var docs = snapshot.documents;
    for (var Doc in docs)
    {
      finalProductsList.add(products.fromFireStore(Doc));
    }
    }

CourseModel

class products {
  final String prodId;
  final String ownerId;
  final String username;
  final String price;
  final String productname;
  final String details;
  final String color;
  final String composition;
  final String washandcare;
  final String sizeandfit;
  final String shopmediaUrl;
  final String id;
  final dynamic likes;
  products({ this.prodId,
    this.ownerId,
    this.username,
    this.price,
    this.details,
    this.productname,
    this.color,
    this.composition,
    this.washandcare,
    this.sizeandfit,
    this.shopmediaUrl,
    this.id,
    this.likes,});

  factory products.fromFireStore(DocumentSnapshot doc)
  {
    Map data = doc.data ;
    return products(
      prodId: doc['prodId'],
      ownerId: doc['ownerId'],
      username: doc['username'],
      price: doc['price'],
      productname: doc['productname'],
      details: doc['details'],
      shopmediaUrl: doc['shopmediaUrl'],
      color:doc['color'],
      composition:doc['composition'],
      washandcare:doc['washandcare'],
      sizeandfit:doc['sizeandfit'],
      likes: doc['likes'],
    );


问:
I have to edit one element in a dataframe. How to to it?
I have the following dataframe -

```<code>      first_name last_name  Location Qualification
1        Saif     Mehdi Hyderabad        M.Tech
2       Rishi     Gupta      Pune        B.Tech
3       Aditi    Pandey   unknown        unkown
4      Poorwa    Kunwar     Japan        B.Tech
5      Rajesh Choudhary    Jaipur        B.Tech
6        Hari     Desai    Mumbai        M.Tech
7       Sayan       Das   Kolkata        B.Tech
8   Deepjyoti     Borah   Kolkata        B.Tech
9    Bharathi Ganesan R    Trichy        M.Tech
10   Jayarama   Krishna     Vizag        M.Tech
11      Akhil  Gopinath  Banglore           M.S
</code>```

Now I want to edit the 4th row's Qualification column

How to do it?

I am new to R

答: You can access the Qualification column via df$Qualification, where df is your data frame. Then, you can access the 4th element of that via df$Qualification[4]. To replace the existing value with a new value, new_value, you can write: df$Qualification[4] <- new_value.

Body:
I have the following dataframe -

      first_name last_name  Location Qualification
1        Saif     Mehdi Hyderabad        M.Tech
2       Rishi     Gupta      Pune        B.Tech
3       Aditi    Pandey   unknown        unkown
4      Poorwa    Kunwar     Japan        B.Tech
5      Rajesh Choudhary    Jaipur        B.Tech
6        Hari     Desai    Mumbai        M.Tech
7       Sayan       Das   Kolkata        B.Tech
8   Deepjyoti     Borah   Kolkata        B.Tech
9    Bharathi Ganesan R    Trichy        M.Tech
10   Jayarama   Krishna     Vizag        M.Tech
11      Akhil  Gopinath  Banglore           M.S

Now I want to edit the 4th row's Qualification column

How to do it?

I am new to R


问:
Is it possible to create cross dependency on a file?
I want to run a job based on file availability in Tivoli Workload Scheduler. Is it possible to add cross dependency on a file , when the job is local.</p>

答:
Not sure what you mean with "cross" dependencies in this context.

To wait for a file in Tivoli Workload Scheduler you have the following alternative:

File dependencies (a.k.a. opens). The job will wait until the
specified test check is satisfied. This is the preferred solution is your workload is scheduled and you just want to wait for a file that you know would come.

Use a job or a start condition that runs filemonitor utility. This is the best solution if you have multiple files that arrives during the day, that you want to process one-by-one or in batches, and that you want to monitor their arrivals.

EDWA file events. Create an event rule that monitors for a file creation, update, deletion and that submits your job streams (or job). This is the most dynamic solution to trigger workload dynamically based on files to process one by one and that could come or not.


问:
Test class not running properly from loop in TestSuite... in seleniumRC+JUNIT
I am using SeleniumRC+Java+JUnit+Eclipse.

I have a test class as ABC and I'm running this test class from a TestSuite. I am following certain conditions to run the test class like this:

In an excel sheet I have 3 columns as colA, ColB, ColC and rows as Run, Username, Password.
colA, ColB, ColC have values in the Run row as Yes, No, Yes respectively.

My Condition is: only when a column has value the "Yes" in the Run row, the test class will execute taking corresponding username and password from that column.

But my problem is, everytime the loop is running till last "Yes" valued column and executing the test class for corresponding username and password, ignoring previous "Yes" valued columns. Why is this the case?

Code for TestSuite:

```<code>public class FinalTestSuite extends TestCase
{
    public static File sourceFile = new File("C:/Selenium/selenium-remote-control-1.0.3/Data.xls");
    public static WorkbookSettings ws;
    public static WritableWorkbook workbook;
    public static WritableSheet wSheet1, wSheet2;
    public static Sheet sh1, sh2, sheetFinal;
    public static Workbook sourceWorkbook;
    public static Label label;
    public Selenium selenium;
    public static int colCount, rowCount;
    public static int colNum;
    public static int rowNum;

    public static TestSuite suite() throws Exception
    {
        TestSuite suite = new TestSuite();
        sourceWorkbook = Workbook.getWorkbook(sourceFile);
        sheetFinal = sourceWorkbook.getSheet("Begin");
        colCount = sheetFinal.getColumns();
        System.out.println(colCount);
        rowCount = sheetFinal.getRows();
        System.out.println(rowCount);

        for(int col=1;col<colCount;col++)
        {
            if((sheetFinal.getCell(col,1).getContents()).equalsIgnoreCase("yes"))
            {
                for(rowNum = 1;rowNum<=rowCount;rowNum++)
                {
                    if((sheetFinal.getCell(0, rowNum-1).getContents()).equalsIgnoreCase("username"))
                    {
                        id = sheetFinal.getCell(col, rowNum-1).getContents();
                    }
                    else if((sheetFinal.getCell(0, rowNum-1).getContents()).equalsIgnoreCase("Password"))
                    {
                        pwd = sheetFinal.getCell(col, rowNum-1).getContents();
                    }

                }

                suite.addTestSuite(ABC.class);
            }
        }

        return suite;
    }

    public static void main(String a)
    {
        TestRunner.run(ABC.class);
    }

}
</code>```

Did I go wrong anywhere?

答:
I just removed:

```<code>public static void main(String a)
{
    TestRunner.run(ABC.class);
}
</code>```

And replaced suite.addTestSuite(ABC.class); with TestRunner.run(ABC.class);

Now it's working fine.

ContentLicense: CC BY-SA 3.0

Body:
I am using SeleniumRC+Java+JUnit+Eclipse.

I have a test class as ABC and I'm running this test class from a TestSuite. I am following certain conditions to run the test class like this:

In an excel sheet I have 3 columns as colA, ColB, ColC and rows as Run, Username, Password.
colA, ColB, ColC have values in the Run row as Yes, No, Yes respectively.

My Condition is: only when a column has value the "Yes" in the Run row, the test class will execute taking corresponding username and password from that column.

But my problem is, everytime the loop is running till last "Yes" valued column and executing the test class for corresponding username and password, ignoring previous "Yes" valued columns. Why is this the case?

Code for TestSuite:

public class FinalTestSuite extends TestCase
{
    public static File sourceFile = new File("C:/Selenium/selenium-remote-control-1.0.3/Data.xls");
    public static WorkbookSettings ws;
    public static WritableWorkbook workbook;
    public static WritableSheet wSheet1, wSheet2;
    public static Sheet sh1, sh2, sheetFinal;
    public static Workbook sourceWorkbook;
    public static Label label;
    public Selenium selenium;
    public static int colCount, rowCount;
    public static int colNum;
    public static int rowNum;

    public static TestSuite suite() throws Exception
    {
        TestSuite suite = new TestSuite();
        sourceWorkbook = Workbook.getWorkbook(sourceFile);
        sheetFinal = sourceWorkbook.getSheet("Begin");
        colCount = sheetFinal.getColumns();
        System.out.println(colCount);
        rowCount = sheetFinal.getRows();
        System.out.println(rowCount);

        for(int col=1;col<colCount;col++)
        {
            if((sheetFinal.getCell(col,1).getContents()).equalsIgnoreCase("yes"))
            {
                for(rowNum = 1;rowNum<=rowCount;rowNum++)
                {
                    if((sheetFinal.getCell(0, rowNum-1).getContents()).equalsIgnoreCase("username"))
                    {
                        id = sheetFinal.getCell(col, rowNum-1).getContents();
                    }
                    else if((sheetFinal.getCell(0, rowNum-1).getContents()).equalsIgnoreCase("Password"))
                    {
                        pwd = sheetFinal.getCell(col, rowNum-1).getContents();
                    }

                }

                suite.addTestSuite(ABC.class);
            }
        }

        return suite;
    }

    public static void main(String a)
    {
        TestRunner.run(ABC.class);
    }

}

Did I go wrong anywhere?

Body:
I just removed:

public static void main(String a)
{
    TestRunner.run(ABC.class);
}

And replaced suite.addTestSuite(ABC.class); with TestRunner.run(ABC.class);

Now it's working fine.


问:
Unresponsive UIButton in subview added to UIStackView
In the detailViewController of a UISplitView I have subviews added to a UIStackView inside a UIScrollView.

Just using system buttons without subviews or images, results in responsive buttons, but subviews seem to interfere.

Enabling touch is specifically coded.  I have attempted to keep each view inside the containing view so there will be no overlap to invalidate receiving touch events, but not sure if this is done properly.
Each subview contains a label and a custom button with an image. The subview is then added to the stackview, and the stackview to the scrollview.

Thanks for any help.

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    scrollView = UIScrollView()
    scrollView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(scrollView)

    // Constrain the scroll view within the detailView
    view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[scrollView]|", options: .AlignAllCenterX, metrics: nil, views: ["scrollView": scrollView]))
    view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[scrollView]|", options: .AlignAllCenterX, metrics: nil, views: ["scrollView": scrollView]))

    stackView = UIStackView()

    stackView.frame = CGRectMake(0,0,view.frame.width, 1000)
    stackView.translatesAutoresizingMaskIntoConstraints = false
    stackView.axis = .Vertical
    scrollView.contentSize = CGSizeMake(400, 1000)
    scrollView.addSubview(stackView)

    // Constrain the stackView within the scrollView
scrollView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[stackView]|", options: NSLayoutFormatOptions.AlignAllCenterX, metrics: nil, views: ["stackView": stackView]))
scrollView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[stackView]", options: NSLayoutFormatOptions.AlignAllCenterX, metrics: nil, views: ["stackView": stackView]))

    let selectedGroup: Group = GroupArray[5]

    let descriptorsArray = selectedGroup.descriptorsArray

    for descriptor in descriptorsArray {
        // Create a subview for each descriptor

        let subView = UIView()
        subView.frame = CGRectMake(0 , 0, self.stackView.frame.width-10, 54)
        subView.backgroundColor = UIColor.yellowColor()

        subView.heightAnchor.constraintEqualToConstant(54.0).active = true
        // Create a label for Descriptor subview

        let label = UILabel(frame: CGRectMake(20, 0, 200, 50))
        label.text = descriptor.name
        label.font = UIFont.boldSystemFontOfSize(22.0)
        label.textAlignment = .Left
        label.textColor = UIColor.brownColor()
        label.backgroundColor = UIColor.greenColor()
        label.heightAnchor.constraintEqualToConstant(50.0).active = true
        subView.addSubview(label)

        // Create a button for Checkbox
        let btn = UIButton()
        btn.frame = CGRectMake(220, 0, 50, 50)
        btn.backgroundColor = UIColor.blueColor()
        btn.setImage(UIImage(named:"checked.png"), forState: UIControlState.Normal)

        btn.heightAnchor.constraintLessThanOrEqualToConstant(50.0)
        btn.widthAnchor.constraintLessThanOrEqualToConstant(50.0)

        btn.addTarget(self, action: "btnPressed:", forControlEvents: UIControlEvents.TouchUpInside)

        subView.addSubview(btn)
        btn.userInteractionEnabled = true
        subView.userInteractionEnabled = true
        stackView.userInteractionEnabled = true
        scrollView.userInteractionEnabled = true
        stackView.addArrangedSubview(subView)

    }
}

func btnPressed(sender: UIButton!) {

    print("btn Pressed")

}
</code>```

答: In my case, it was just Xcode's bug. I've just closed and reopened it. It just worked. My current Xcode version is 11.4.1.</p>

Body:
In the detailViewController of a UISplitView I have subviews added to a UIStackView inside a UIScrollView.

Just using system buttons without subviews or images, results in responsive buttons, but subviews seem to interfere.

Enabling touch is specifically coded.  I have attempted to keep each view inside the containing view so there will be no overlap to invalidate receiving touch events, but not sure if this is done properly.
Each subview contains a label and a custom button with an image. The subview is then added to the stackview, and the stackview to the scrollview.

Thanks for any help.

override func viewDidLoad() {
    super.viewDidLoad()

    scrollView = UIScrollView()
    scrollView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(scrollView)

    // Constrain the scroll view within the detailView
    view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[scrollView]|", options: .AlignAllCenterX, metrics: nil, views: ["scrollView": scrollView]))
    view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[scrollView]|", options: .AlignAllCenterX, metrics: nil, views: ["scrollView": scrollView]))

    stackView = UIStackView()

    stackView.frame = CGRectMake(0,0,view.frame.width, 1000)
    stackView.translatesAutoresizingMaskIntoConstraints = false
    stackView.axis = .Vertical
    scrollView.contentSize = CGSizeMake(400, 1000)
    scrollView.addSubview(stackView)

    // Constrain the stackView within the scrollView
scrollView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[stackView]|", options: NSLayoutFormatOptions.AlignAllCenterX, metrics: nil, views: ["stackView": stackView]))
scrollView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[stackView]", options: NSLayoutFormatOptions.AlignAllCenterX, metrics: nil, views: ["stackView": stackView]))

    let selectedGroup: Group = GroupArray[5]

    let descriptorsArray = selectedGroup.descriptorsArray

    for descriptor in descriptorsArray {
        // Create a subview for each descriptor

        let subView = UIView()
        subView.frame = CGRectMake(0 , 0, self.stackView.frame.width-10, 54)
        subView.backgroundColor = UIColor.yellowColor()

        subView.heightAnchor.constraintEqualToConstant(54.0).active = true
        // Create a label for Descriptor subview

        let label = UILabel(frame: CGRectMake(20, 0, 200, 50))
        label.text = descriptor.name
        label.font = UIFont.boldSystemFontOfSize(22.0)
        label.textAlignment = .Left
        label.textColor = UIColor.brownColor()
        label.backgroundColor = UIColor.greenColor()
        label.heightAnchor.constraintEqualToConstant(50.0).active = true
        subView.addSubview(label)

        // Create a button for Checkbox
        let btn = UIButton()
        btn.frame = CGRectMake(220, 0, 50, 50)
        btn.backgroundColor = UIColor.blueColor()
        btn.setImage(UIImage(named:"checked.png"), forState: UIControlState.Normal)

        btn.heightAnchor.constraintLessThanOrEqualToConstant(50.0)
        btn.widthAnchor.constraintLessThanOrEqualToConstant(50.0)

        btn.addTarget(self, action: "btnPressed:", forControlEvents: UIControlEvents.TouchUpInside)

        subView.addSubview(btn)
        btn.userInteractionEnabled = true
        subView.userInteractionEnabled = true
        stackView.userInteractionEnabled = true
        scrollView.userInteractionEnabled = true
        stackView.addArrangedSubview(subView)

    }
}

func btnPressed(sender: UIButton!) {

    print("btn Pressed")

}


问:
Need to find '$word;' pattern in string
I have big text file and I have to find all words starts with '$' and ends with ';' like $word;.

```<code>import re

text = "$h;BREWERY$h_end;You've built yourself a brewery."
x = re.findall("$..;", text)
print(x)
</code>```

I want my output like ['$h;', '$h_end;'] How can I do that?

答:
You may use

```<code>\$\w+;
</code>```

See the regex demo. Details:

\$ - a $ char

\w+ - 1+ letters, digits, _ (=word) chars

; - a semi-colon.

Python demo:

```<code>import re

text = "$h;BREWERY$h_end;You've built yourself a brewery."
x = re.findall(r"\$\w+;", text)
print(x) # => ['$h;', '$h_end;']
</code>```

Title: Need to find '$word;' pattern in string

Body:
I have big text file and I have to find all words starts with '$' and ends with ';' like $word;.

import re

text = "$h;BREWERY$h_end;You've built yourself a brewery."
x = re.findall("$..;", text)
print(x)

I want my output like ['$h;', '$h_end;'] How can I do that?

Body:
You may use

\$\w+;

See the regex demo. Details:

\$ - a $ char

\w+ - 1+ letters, digits, _ (=word) chars

; - a semi-colon.

Python demo:

import re

text = "$h;BREWERY$h_end;You've built yourself a brewery."
x = re.findall(r"\$\w+;", text)
print(x) # => ['$h;', '$h_end;']


问:
How to find rows of a dataframe containing a date value?
There is a huge dataframe containing multiple data types in different columns. I want to find rows that contain date values in different columns.
Here a test dataframe:

```<code>   dt = pd.Series(['abc', datetime.now(), 12, '', None, np.nan, '2020-05-05'])
   dt1 = pd.Series([3, datetime.now(), 'sam', '', np.nan, 'abc-123', '2020-05-25'])
   dt3 = pd.Series([1,2,3,4,5,6,7])
   df = pd.DataFrame({"A":dt.values, "B":dt1.values, "C":dt3.values})
</code>```

Now, I want to create a new dataframe that contains only dates in both columns A and B, here rows 2nd and last.

Expected output:

```                            A                           B  C
1  2020-06-01 16:58:17.274311  2020-06-01 17:13:20.391394  2
6                  2020-05-05                  2020-05-25  7
```

What is the best way to do that? Thanks.

P.S.> Dates can be in any standard format.

答:
Solution for test only A,B columns is boolean indexing with DataFrame.notna and DataFrame.all for not match any non datetimes:

```<code>df = df[df[['A','B']].apply(pd.to_datetime, errors='coerce').notna().all(axis=1)]

print (df)
                            A                           B  C
1  2020-06-01 16:14:35.020855  2020-06-01 16:14:35.021855  2
6                  2020-05-05                  2020-05-25  7
</code>```

Body:
There is a huge dataframe containing multiple data types in different columns. I want to find rows that contain date values in different columns.
Here a test dataframe:

   dt = pd.Series(['abc', datetime.now(), 12, '', None, np.nan, '2020-05-05'])
   dt1 = pd.Series([3, datetime.now(), 'sam', '', np.nan, 'abc-123', '2020-05-25'])
   dt3 = pd.Series([1,2,3,4,5,6,7])
   df = pd.DataFrame({"A":dt.values, "B":dt1.values, "C":dt3.values})

Now, I want to create a new dataframe that contains only dates in both columns A and B, here rows 2nd and last.

Expected output:

                            A                           B  C
1  2020-06-01 16:58:17.274311  2020-06-01 17:13:20.391394  2
6                  2020-05-05                  2020-05-25  7

What is the best way to do that? Thanks.

P.S.> Dates can be in any standard format.

Body:
Solution for test only A,B columns is boolean indexing with DataFrame.notna and DataFrame.all for not match any non datetimes:

df = df[df[['A','B']].apply(pd.to_datetime, errors='coerce').notna().all(axis=1)]

print (df)
                            A                           B  C
1  2020-06-01 16:14:35.020855  2020-06-01 16:14:35.021855  2
6                  2020-05-05                  2020-05-25  7


问:
Website logo appears bigger in chrome browser on bigger screen
I have website which has a logo in size 250X277. The logo is correctly displayed across all browsers except Chrome running in bigger wondow, e.g. dekstop. In desktop, the logo stretches horizontally as it's shown in the image below. However, in other browsers it's displayed correctly across all monitor size. I will provide more code if that requires.
Could someone please have a look on my issue?

Here is my CSS code for logo:

style.css:

```<code>header {

  position: relative;

  z-index: 999;

}

header .header-logo {

  padding: 10px 10px;

  background: #fff;

  text-align: center;

}
</code>```

HTML

```<code>            <header class="sidebar-section">
            <div class="header-logo">
                <a class="logo" href="index.php"><img src="images/logo.png" alt="logo" width="250"></a>
            </div>
            <a class="elemadded responsive-link" href="#">Menu</a>
            <div class="navbar-vertical">
                <ul class="main-menu">

                </ul>
            </div>
        </header>
</code>```

答:
For me at least, the logo does not seem to stretch in neither Chrome nor FireFox.
Have you recently made changes to the dimensions of the logo, and viewed these changes in Chrome?
CSS will stick in chrome cache, so you should always do CTRL + F5 when watching newly changed CSS edits in browser.

Edited answer

The issue relies with your bootstrap configuration.

You use Responsive Design, to make the site change depending on how big the monitor it's being viewed on is.

To fix this issue, open your css/style.css file, and inside the media-query "@media (max-width: 1199px)" add something like .logo{width:219px}

Edited answer 2

You can also just set the static size of the image to 210px.
This will look good in all 3 breakpoints.

```

Body:
I have website which has a logo in size 250X277. The logo is correctly displayed across all browsers except Chrome running in bigger wondow, e.g. dekstop. In desktop, the logo stretches horizontally as it's shown in the image below. However, in other browsers it's displayed correctly across all monitor size. I will provide more code if that requires.
Could someone please have a look on my issue?

Here is my CSS code for logo:

style.css:

header {

  position: relative;

  z-index: 999;

}

header .header-logo {

  padding: 10px 10px;

  background: #fff;

  text-align: center;

}

HTML

            Menu

Body:
For me at least, the logo does not seem to stretch in neither Chrome nor FireFox.
Have you recently made changes to the dimensions of the logo, and viewed these changes in Chrome?
CSS will stick in chrome cache, so you should always do CTRL + F5 when watching newly changed CSS edits in browser.

Edited answer

The issue relies with your bootstrap configuration.

You use Responsive Design, to make the site change depending on how big the monitor it's being viewed on is.

To fix this issue, open your css/style.css file, and inside the media-query "@media (max-width: 1199px)" add something like .logo{width:219px}

Edited answer 2

You can also just set the static size of the image to 210px.
This will look good in all 3 breakpoints.

<img src="images/logo.png" alt="logo" width="210px">


问:
NodeJS Retriivng Record from DB 1 by 1 vs All
I have 2 Microservices

1 Auth Service : Store all the users Data

2 Club Service : Store userId Ref ( of a Auth Service User ) along with Service Specific Data

in the Club service i want to get all the users data but i only want the users subscribed to my Club Service (Not all users in Auth Service)
so i have 2 options
 2 functions in Club Service (Shared from Auth Service using RPC (MicroService))

1 - getUserById

2 - getAllUsers

should i make a for loop and supply the userId to getUserById Function to get all data related to Club Service only

or should i getAllUsers data from auth. Store them in an array and then loop through this array with the UserId to get the users data specific to my Club Service ?

Which is more Performant

It's all about which is more performant querying the data from DB one by one using getUserById method

or

getting all the Data from DB once. send them to Club Service. and on Club Service i loop through all the data to match the userId i have on Club Service and filter them?

答:
Communication between servers (i.e. micro services) is always more prone to errors than using "local" data.

Therefore (obviously within limits of security, privacy, bandwidth limits etc.) I'd recommend to make your calls in batches:

Fetching as many users as possible in a single call.

Authenticating as many users as possible at the same time.

This will guarantee less calls between your micro services, resulting in a more readable code, a more reliable and easily-read error handling and usually a slightly better performing code.


问:
Why local storage not persisting after page refresh
The button text 'completed' should persist after browser refresh based on whether var item is true (after button click). I am not sure what the issue is but I have tried Chrome as well so I don't think it is browser related.</p>

```<code><template>
<button type="button" v-bind:class="order_button_style" @click="on_order_button_click()">
  {{ buttonText }}
</button>
</div>
</template>

<script>
export default {

item: '',
data() {

  return {
  item2: this.item
  }
},
methods: {
on_order_button_click() {
 this.item2 = true;
  localStorage.setItem(this.item2);
}

},
mounted() {
const storedState = localStorage.getItem(this.item2) === 'false';
if (storedState) {
  this.item2 = storedState;
}
},
computed: {
buttonText() {
  return this.item2 === true ? "Completed" : "Complete";
},
order_button_style() {
  return this.item2 === true
    ? "btn btn-danger"
    : "btn btn-primary";
}

}

};
</script>
</code>```

答:
localStorage.setItem takes 2 params, name and value.

I believe you meant to write the following:

Setting an item in localStorage

localStorage.setItem('item', this.item2)

and retrieving it

localStorage.getItem('item')

A few comments on other parts of your code:

this.item2 === true can be shortened to this.item2 if item2 can never be anything other than a boolean.

You're currently only using the value from localStorage if it's false, which it will never be because you're only ever calling setItem with a value of true

I'm not sure what you're trying to do with the item prop in the top level of the object

Strongly consider using camelCase for your method names. Follow global conventions

UPDATE:

I think this is what you're trying to achieve:

```<code>on_order_button_click() { // Should probably rename this to `onOrderButtonClick`, the current method name hurts to look at
  this.clickedOrderButton = true;
  localStorage.setItem('clickedOrderButton', this.clickedOrderButton);
}

created() {
  this.clickedOrderButton = localStorage.getItem('clickedOrderButton') === "true";
}
</code>```

I've renamed item2 to clickedOrderButton. I have no idea why you'd name that variable item2 based on the code that is shown.

There's also no need to check whether clickedOrderButton is true before assigning it to clickedOrderButton, as it will resolve to false if it's not present (or intentionally set to something other than true) in localStorage.

Lastly, I've replaced mounted by created. As you're not accessing any DOM elements, there's no need to wait until the component is mounted to run that code

UPDATE#2:

If you have several instances of this component, you'll need to set use a different name than clickedOrderButton. You can use a unique identifier per button, which you can pass as a prop from above.

E.g.

```<code>props: {
  id: { type: String, required: true }
}
...
localStorage.setItem(`clickedOrderButton-${this.id}`, this.clickedOrderButton);
...
localStorage.getItem(`clickedOrderButton-${this.id}`);
</code>```

Body:
The button text 'completed' should persist after browser refresh based on whether var item is true (after button click). I am not sure what the issue is but I have tried Chrome as well so I don't think it is browser related.

<template>
<button type="button" v-bind:class="order_button_style" @click="on_order_button_click()">
  {{ buttonText }}
</button>

</template>

Body:
localStorage.setItem takes 2 params, name and value.

I believe you meant to write the following:

Setting an item in localStorage

localStorage.setItem('item', this.item2)

and retrieving it

localStorage.getItem('item')

A few comments on other parts of your code:

this.item2 === true can be shortened to this.item2 if item2 can never be anything other than a boolean.

You're currently only using the value from localStorage if it's false, which it will never be because you're only ever calling setItem with a value of true

I'm not sure what you're trying to do with the item prop in the top level of the object

Strongly consider using camelCase for your method names. Follow global conventions

UPDATE:

I think this is what you're trying to achieve:

on_order_button_click() { // Should probably rename this to `onOrderButtonClick`, the current method name hurts to look at
  this.clickedOrderButton = true;
  localStorage.setItem('clickedOrderButton', this.clickedOrderButton);
}

created() {
  this.clickedOrderButton = localStorage.getItem('clickedOrderButton') === "true";
}

I've renamed item2 to clickedOrderButton. I have no idea why you'd name that variable item2 based on the code that is shown.

There's also no need to check whether clickedOrderButton is true before assigning it to clickedOrderButton, as it will resolve to false if it's not present (or intentionally set to something other than true) in localStorage.

Lastly, I've replaced mounted by created. As you're not accessing any DOM elements, there's no need to wait until the component is mounted to run that code

UPDATE#2:

If you have several instances of this component, you'll need to set use a different name than clickedOrderButton. You can use a unique identifier per button, which you can pass as a prop from above.

E.g.

props: {
  id: { type: String, required: true }
}
...
localStorage.setItem(`clickedOrderButton-${this.id}`, this.clickedOrderButton);
...
localStorage.getItem(`clickedOrderButton-${this.id}`);


问:
Need a solution to replace ActiveX that can be used from web browsers\ HTML 5
I have a windows service that firing events and use local connected devices like scanners and such.
Until today if i wanted to use it from a web page i had to use an active x component that i created (a wrapper for my windows service SDK).
But the modern web browsers stopping their usage with Active X and HTML 5 not support active X.
I need an ideas or other solution that i cam move on to.
Any help is very helpful.
Thanks</p>

答:
We have been in this kind of situation before. What we have done is to create a browser extension (Chrome in our case) that uses Native Messaging to communicate with a locally deployed application. (exe in our case, which is also needed to be registered in Windows Registry). Extension serves as a message broker between the content script and the native application.

Native Messaging


问:
why is the construct  x =  (Condition and A or B) used?
One of the answers to this question is

```<code>print len(s)>5 and 'y' or 'n'
print(len(s)>5 and 'y' or 'n') #python3
</code>```

if the length of s > 5, then 'y' is printed otherwise 'n' is. Please explain how/why this works. Thanks.

I understand that this is not a recommended approach but I'd like to understand why it works.

答:
-- Logical Operators have a precedence from left to right.

-- OR operator does not check the second condition if first is True.

So your code first checks if

```<code> len(s)>5 and 'y'
</code>```

And this return True, it does not check the second condition of OR thus printing it.
Only if this becomes false the second OR condition is checked.
This prints 'n'.

For example:

```<code>print('a' or 'b')
#Output: a

print(False or 'b')
#Output : b
</code>```

Thus the OR operator does not check the second condition if first is True.

Body:
One of the answers to this question is

print len(s)>5 and 'y' or 'n'
print(len(s)>5 and 'y' or 'n') #python3

if the length of s > 5, then 'y' is printed otherwise 'n' is. Please explain how/why this works. Thanks.

I understand that this is not a recommended approach but I'd like to understand why it works.

Body:
-- Logical Operators have a precedence from left to right.

-- OR operator does not check the second condition if first is True.

So your code first checks if

 len(s)>5 and 'y'

And this return True, it does not check the second condition of OR thus printing it.
Only if this becomes false the second OR condition is checked.
This prints 'n'.

For example:

print('a' or 'b')
#Output: a

print(False or 'b')
#Output : b

Thus the OR operator does not check the second condition if first is True.


问:
Why can INDEX(...,COUNTA(...),..) find the last value of one array, but not another?
I'm learning basic =ARRAYFORMULA usage for a finance spreadsheet:

https://docs.google.com/spreadsheets/d/12cAGuUBzIo0LPbmtqWJZNFgjt94f1ybGoj6x2g0c2Y0/edit?usp=sharing

First, I used =GOOGLEFINANCE at B1 to pull up stock prices for a given date range in Column C

=GOOGLEFINANCE(A1,"price",DATE(2020,1,1),DATE(2020,5,30),"DAILY")

Then, I used simple arithmetic to multiply by number of shares at D2 and dragged the formulas down to get a nice column of values

=C2*20

Then, I used INDEX and COUNTA to pull out the last value of Column D at F3 === Great!

=INDEX(AAPL!D2:D,COUNTA(AAPL!D2:D),1)

Next, I turned my arithmetic formula into an ARRAYFORMULA at G2 === Cool!

=ARRAYFORMULA(C2:C103*20)

Of course, the problem with that ARRAYFORMULA is that I would have to manually change the array name in G2 every time the date range updated.

That is, instead of C2:C103, I would need to change the reference to C2:104 to get the columns to match === Rookie mistake!!!!!

So, I got smart with an ARRAYFORMULA containing a IF(ISBLANK(),...,...) at J2

=ARRAYFORMULA(IF(ISBLANK(B2:B),"",C2:C*20))

Column J stays fully populated with the correct values for any date range === !!!!!!!

But now the =INDEX(AAPL!J2:J,COUNTA(AAPL!J2:J),1) at L3 can't find the last value in Column J

Whaaat???

I've tried everything I can think of

It works if I use =INDEX(AAPL!J2:J104,COUNTA(AAPL!J2:J104),1) but that would defeat the purpose, since the reference J:J104 is going to change as the dates change

WHY???

答:
I get the same results in both cells "L3" and "L5" when using:

=ARRAYFORMULA(IF(ISBLANK(B2:B),,C2:C*20))

Check that you are not returning a blank string ("") in your IF like: "=ARRAYFORMULA(IF(ISBLANK(B2:B),"",C2:C*20))" doing so will fill the cells up to the last row in the sheet with empty strings, thus when you use COUNTA(AAPL!J2:J),1) you get a lot more cells than you would expect, these extra cells are the ones you filled with blank strings in the array formula.

On the contrary when you limit the =INDEX(AAPL!J2:J104,COUNTA(AAPL!J2:J104),1) to cells with numbers only it doesn't mix strings and numbers in the calculation and you are naturally get the expected results.


答:
Add width and height property in image tag.</p>

```<code><header class="sidebar-section">
            <div class="header-logo">
                <a class="logo" href="index.php"><img src="images/logo.png" alt="logo" width="250"></a>
            </div>
            <a class="elemadded responsive-link" href="#">Menu</a>
            <div class="navbar-vertical">
                <ul class="main-menu">

                </ul>
            </div>
        </header>
</code>```

Title: Website logo appears bigger in chrome browser on bigger screen

Body:
Add width and height property in image tag.

<header class="sidebar-section">
            <div class="header-logo">
                <a class="logo" href="index.php"><img src="images/logo.png" alt="logo" width="250"></a>
            </div>
            <a class="elemadded responsive-link" href="#">Menu</a>
            <div class="navbar-vertical">
                <ul class="main-menu">

                </ul>
            </div>
        </header>


问:
Reading from file into 2d Array in C without constant size
I have a text file that have content like this

```<code>5 6
01111
11110
01000
01111
11010
11111
</code>```

And i want to made a function read from this file and create 2d array out of the content.

Two Numbers from the first line is the size of array and the size of sub array.

The result of the function should be array like this

```<code>{{0,1,1,1,1}, {1,1,1,1,0},{0,1,0,0,0},{0,1,1,1,1},{1,1,0,1,0},{1,1,1,1,1}}
</code>```

So how would i be able to do that?

Right now i try to made a function like this but it error

```<code>int** createArray(FILE *fp)
{
    int xdim;
    int ydim;
    fscanf(fp, "%d %d", &xdim, &ydim);

    int** arr = malloc(ydim * sizeof(*arr));;
    for (int y = 0; y < ydim; y++)
    {
        arr[y] = malloc(xdim * sizeof(**arr));
        fscanf(fp, "%d %d %d %d", arr[y]);
    }
    return arr;
}
</code>```

答:
Just loop xdim times over arr[y] then and read numbers with fscanf. Note that a space " " in fscanf format specifier ignores all whitespaces - tabs, spaces and newlines - so it can just read it all.

```<code>int** arr = malloc(ydim * sizeof(*arr));;
if (arr == NULL) {
     abort();
}

for (int y = 0; y < ydim; y++) {

    arr[y] = malloc(xdim * sizeof(*arr[y]));
    if (arr[y] == NULL) {
        abort();
    }

    for (int i = 0; i < xdim; ++i) {
        char c;
        if (fscanf(fp, " %c", &c) != 1) {
            abort(); // handle error
        }
        arr[i][j] = c - '0';
    }
}
</code>```

Tested on godbolt.

Body:
I have a text file that have content like this

5 6
01111
11110
01000
01111
11010
11111

And i want to made a function read from this file and create 2d array out of the content.

Two Numbers from the first line is the size of array and the size of sub array.

The result of the function should be array like this

{{0,1,1,1,1}, {1,1,1,1,0},{0,1,0,0,0},{0,1,1,1,1},{1,1,0,1,0},{1,1,1,1,1}}

So how would i be able to do that?

Right now i try to made a function like this but it error

int** createArray(FILE *fp)
{
    int xdim;
    int ydim;
    fscanf(fp, "%d %d", &xdim, &ydim);

    int** arr = malloc(ydim * sizeof(*arr));;
    for (int y = 0; y < ydim; y++)
    {
        arr[y] = malloc(xdim * sizeof(**arr));
        fscanf(fp, "%d %d %d %d", arr[y]);
    }
    return arr;
}

Body:
Just loop xdim times over arr[y] then and read numbers with fscanf. Note that a space " " in fscanf format specifier ignores all whitespaces - tabs, spaces and newlines - so it can just read it all.

int** arr = malloc(ydim * sizeof(*arr));;
if (arr == NULL) {
     abort();
}

for (int y = 0; y < ydim; y++) {

    arr[y] = malloc(xdim * sizeof(*arr[y]));
    if (arr[y] == NULL) {
        abort();
    }

    for (int i = 0; i < xdim; ++i) {
        char c;
        if (fscanf(fp, " %c", &c) != 1) {
            abort(); // handle error
        }
        arr[i][j] = c - '0';
    }
}

Tested on godbolt.