问:
Parallel tree traversal in C#
I need to traverse a tree quickly, and I would like to do it in parallel. I'd rather use the parallel extensions than manually spin up a bunch of threads.

My current code looks something like this:

```<code>   public void Traverse(Node root)
    {
        var nodeQueue = new Queue<Node>();
        nodeQueue.Enqueue(root);
        while (nodeQueue.Count!=0)
        {
            var node = nodeQueue.Dequeue();
            if (node.Property = someValue) DoSomething(node);
            foreach (var node in node.Children)
            {
                nodeQueue.Enqueue(node);
            }
        }
    }
</code>```

I was really hoping that Parallel.ForEach had a Parallel.While analog. I came across Stephen Toub's article on Implementing Parallel While with Parallel.ForEach. If read it correctly this still won't work because I am mutating the queue I am trying to iterate.

Do I need to use a task factory and recursion (and is that risky?) ? or is there some simple solution I am overlooking?

Edit:
@svick

The tree has just over 250,000 nodes.
The maximum depth right now is 14 nodes deep including the root.

There are about 500 nodes off the root, and the balance after that has a fairly random distribution.
I'll get some better stats on the distribution soon.

@Enigmativity:

Yes, the tree is being modified, concurrently by many users, but I will usually have a shared read lock for the tree or sub tree, or allow for dirty reads.

Calls to node.Children can be considered atomic.

DoSomething is really one of several delegates, for some expensive operations I will probably gather a snapshot list of nodes and process them outside the traversal.

I realized that I should probably look at the general case (a sub-tree being traversed instead of the entire tree.) To that end I ran traverse on every node of the tree and looked at the total time.

I used a Parallel.ForEach(nodes, Traverse) for each traversal algorithm, where nodes contained all ~250k nodes. This simulated (sort of) a lot of users simultaneously requesting a lot of different nodes.

00256ms Breadth First Sequential

00323ms Breadth First Sequential with work       (i incremented a static counter as "work")

01495ms Kirks First answer

01143ms Svicks Second answer

00000ms Recursive Single Threaded didn't finish after 60s

00000ms Enigmativity's answer didn't finish after 60s

@Enigma, I think it's possible I might have messed up your alogrithm somehow, because it seems like it should be much quicker.

The results surprised me to say the least.
I had to add some work to the breadth first sequential just to convince myself that the compiler wasn't magically optimizing away the traversals.

For the single traversal of the head, parallelizing the first level only had the best performance. But just barely, this number improved as I added more nodes to the second level (2000 instead of 500).

答:
Assuming you have p processors maybe you do a Parallel.For over root.Children with p partitions. Each of these would do the traditional single-thread traverse over the subtrees, compare, and, rather than DoSomething, would enqueue a delegate to DoSomething to a concurrent queue. If the distribution is basically random and balanced and since traversal only does traversal/enqueue, that portion takes 1/p th the time. Also, traversal would likely exhaust itself before all the DoSomethings would execute, so you could have p consumers (executors of DoSomething) giving you maximum parallel execution, assuming all these operations are independent.

With this naive partitioning across the number of root children with randomly distributed subtrees, traversal itself will be speedy. With your consumers roughly allocated per processor, you also get max parallel DoSomething action.

Title: Parallel tree traversal in C#

Body:
I need to traverse a tree quickly, and I would like to do it in parallel. I'd rather use the parallel extensions than manually spin up a bunch of threads.

My current code looks something like this:

   public void Traverse(Node root)
    {
        var nodeQueue = new Queue<Node>();
        nodeQueue.Enqueue(root);
        while (nodeQueue.Count!=0)
        {
            var node = nodeQueue.Dequeue();
            if (node.Property = someValue) DoSomething(node);
            foreach (var node in node.Children)
            {
                nodeQueue.Enqueue(node);
            }
        }
    }

I was really hoping that Parallel.ForEach had a Parallel.While analog. I came across Stephen Toub's article on Implementing Parallel While with Parallel.ForEach. If read it correctly this still won't work because I am mutating the queue I am trying to iterate.

Do I need to use a task factory and recursion (and is that risky?) ? or is there some simple solution I am overlooking?

Edit:
@svick

The tree has just over 250,000 nodes.
The maximum depth right now is 14 nodes deep including the root.

There are about 500 nodes off the root, and the balance after that has a fairly random distribution.
I'll get some better stats on the distribution soon.

@Enigmativity:

Yes, the tree is being modified, concurrently by many users, but I will usually have a shared read lock for the tree or sub tree, or allow for dirty reads.

Calls to node.Children can be considered atomic.

DoSomething is really one of several delegates, for some expensive operations I will probably gather a snapshot list of nodes and process them outside the traversal.

I realized that I should probably look at the general case (a sub-tree being traversed instead of the entire tree.) To that end I ran traverse on every node of the tree and looked at the total time.

I used a Parallel.ForEach(nodes, Traverse) for each traversal algorithm, where nodes contained all ~250k nodes. This simulated (sort of) a lot of users simultaneously requesting a lot of different nodes.

00256ms Breadth First Sequential

00323ms Breadth First Sequential with work       (i incremented a static counter as "work")

01495ms Kirks First answer

01143ms Svicks Second answer

00000ms Recursive Single Threaded didn't finish after 60s

00000ms Enigmativity's answer didn't finish after 60s

@Enigma, I think it's possible I might have messed up your alogrithm somehow, because it seems like it should be much quicker.

The results surprised me to say the least.
I had to add some work to the breadth first sequential just to convince myself that the compiler wasn't magically optimizing away the traversals.

For the single traversal of the head, parallelizing the first level only had the best performance. But just barely, this number improved as I added more nodes to the second level (2000 instead of 500).


来源: stackexchange

答:
Most of it is resolved with dec=",",

# saved your data to 'file.csv'
out <- read.csv("file.csv", dec=",")
head(out)
#   praf pmek  plcg  PIP2  PIP3 p44.42 pakts473    PKA   PKC  P38  pjnk
# 1 26.4 13.2  8.82  18.3 58.80   6.61     17.0 414,00 17.00 44.9 40.00
# 2 35.9 16.5 12.30  16.8  8.13  18.60     32.5 352,00  3.37 16.5 61.50
# 3 59.4 44.1 14.60  10.2 13.00  14.90     32.5 403,00 11.40 31.9 19.50
# 4 62.1 51.9 13.60  30.2 10.60  14.30     37.9 692,00  6.49 25.0 91.40
# 5 75.0 33.4  1.00  31.6  1.00  19.80     27.6 505,00 18.60 31.1  7.64
# 6 20.4 15.1  7.99 101.0 35.90   9.14     22.9 400,00 11.70 22.7  6.85
```
<p>Only one column is string:</p>
<pre class="lang-r prettyprint-override"><code>sapply(out, class)
#        praf        pmek        plcg        PIP2        PIP3      p44.42    pakts473         PKA         PKC         P38
#   "numeric"   "numeric"   "numeric"   "numeric"   "numeric"   "numeric"   "numeric" "character"   "numeric"   "numeric"
#        pjnk
#   "numeric"
</code>```

This can be resolved post-read with:

ischr <- sapply(out, is.character)
out[ischr] <- lapply(out[ischr], function(z) as.numeric(gsub(" ", "", chartr(",.", ". ", z))))
out$PKA
#  [1]  414  352  403  692  505  400  956 1407  207 3051
```
<hr />
<p>If you'd rather read it in without post-processing, you can <code>pipe(.)</code> it, assuming you have <code>sed</code> available[^1]:</p>
<pre class="lang-r prettyprint-override"><code>out <- read.csv(pipe("sed -E 's/([0-9])[.]([0-9])/\\1\\2/g;s/([0-9]),([0-9])/\\1.\\2/g' < file.csv"))
</code>```

Notes:

sed is generally available on all linux/macos systems, and on windows computers it is included within Rtools.

ContentLicense: CC BY-SA 4.0

Title: Read in CSV in mixed English and French number format

Body:
I would like to read the a CSV into R that is quoted, comma-separated (i.e. sep = "," not sep = ";" as read.csv2 defaults to) but that

uses the comma inside fields as the decimal separator

contains periods to separate each group of three digits from the right

An example of a problematic entry is "3.051,00" in the final line of the excerpt from the CSV shown.

I tried

dat <- read.csv2("path_to_csv.csv", sep = ",", stringsAsFactors = FALSE)

and a variant using read.csv (both are identical except for their defaults as noted in Difference between read.csv() and read.csv2() in R. Both return improperly-formatted data.frames (e.g. containing 3.051,00).

Can I read this comma-separated file in directly with read.table without having to perform text-preprocessing?

Excerpt of CSV

praf,pmek,plcg,PIP2,PIP3,p44/42,pakts473,PKA,PKC,P38,pjnk
"26,40","13,20","8,82","18,30","58,80","6,61","17,00","414,00","17,00","44,90","40,00"
"35,90","16,50","12,30","16,80","8,13","18,60","32,50","352,00","3,37","16,50","61,50"
"59,40","44,10","14,60","10,20","13,00","14,90","32,50","403,00","11,40","31,90","19,50"
"62,10","51,90","13,60","30,20","10,60","14,30","37,90","692,00","6,49","25,00","91,40"
"75,00","33,40","1,00","31,60","1,00","19,80","27,60","505,00","18,60","31,10","7,64"
"20,40","15,10","7,99","101,00","35,90","9,14","22,90","400,00","11,70","22,70","6,85"
"47,80","19,60","17,50","33,10","82,00","17,90","35,20","956,00","22,50","43,30","20,00"
"59,90","53,30","11,80","77,70","12,90","11,10","37,90","1.407,00","18,80","29,40","16,80"
"46,60","27,10","12,40","109,00","21,90","21,50","38,20","207,00","11,00","31,30","12,00"
"51,90","21,30","49,10","58,80","10,80","58,80","200,00","3.051,00","15,30","39,20","15,70"

Note: I am aware of the question European and American decimal format for thousands, which is not sufficient. This user preprocesses the file they want to read in whereas I would like a direct means of reading a CSV of the kind shown into R.

Body:
Most of it is resolved with dec=",",

# saved your data to 'file.csv'
out <- read.csv("file.csv", dec=",")
head(out)
#   praf pmek  plcg  PIP2  PIP3 p44.42 pakts473    PKA   PKC  P38  pjnk
# 1 26.4 13.2  8.82  18.3 58.80   6.61     17.0 414,00 17.00 44.9 40.00
# 2 35.9 16.5 12.30  16.8  8.13  18.60     32.5 352,00  3.37 16.5 61.50
# 3 59.4 44.1 14.60  10.2 13.00  14.90     32.5 403,00 11.40 31.9 19.50
# 4 62.1 51.9 13.60  30.2 10.60  14.30     37.9 692,00  6.49 25.0 91.40
# 5 75.0 33.4  1.00  31.6  1.00  19.80     27.6 505,00 18.60 31.1  7.64
# 6 20.4 15.1  7.99 101.0 35.90   9.14     22.9 400,00 11.70 22.7  6.85

Only one column is string:

sapply(out, class)
#        praf        pmek        plcg        PIP2        PIP3      p44.42    pakts473         PKA         PKC         P38
#   "numeric"   "numeric"   "numeric"   "numeric"   "numeric"   "numeric"   "numeric" "character"   "numeric"   "numeric"
#        pjnk
#   "numeric"

This can be resolved post-read with:

ischr <- sapply(out, is.character)
out[ischr] <- lapply(out[ischr], function(z) as.numeric(gsub(" ", "", chartr(",.", ". ", z))))
out$PKA
#  [1]  414  352  403  692  505  400  956 1407  207 3051

If you'd rather read it in without post-processing, you can pipe(.) it, assuming you have sed available[^1]:

out <- read.csv(pipe("sed -E 's/([0-9])[.]([0-9])/\\1\\2/g;s/([0-9]),([0-9])/\\1.\\2/g' < file.csv"))

Notes:

sed is generally available on all linux/macos systems, and on windows computers it is included within Rtools.


问:
multiprocessing a function execution with python
i have a pandas dataframe which consists of approximately 1M rows , it contains information entered by users. i wrote a function that validates if the number entered by the user is correct or not . what im trying to do,  is to execute the function on multiple processors to overcome the issue of doing heavy computation on a single processor. what i did is i split my dataframe into multiple chunks where each chunk contains 50K rows and then used the python multiprocessor module to perform the processing on each chunk separately . the issue is that only the first process is starting and its still using one processor instead of distributing the load on all processors . here is the code i wrote :

```<code> pool = multiprocessing.Pool(processes=16)
 r7 = pool.apply_async(validate.validate_phone_number, (has_phone_num_list[0],fields ,dictionary))
 r8 = pool.apply_async(validate.validate_phone_number, (has_phone_num_list[1],fields ,dictionary))
 print(r7.get())
 print(r8.get())
 pool.close()
 pool.join()
</code>```

i have attached a screenshot that shows how the CPU usage when executing the above code

any advice on how can i overcome this issue?

答:
I suggest you try this:

```<code>from concurrent.futures import ProcessPoolExecutor

with ProcessPoolExecutor() as executor:
    params = [(pnl, fields, dictionary) for pnl in has_phone_num_list]
    for result in executor.map(validate.validate_phone_number, params):
        pass # process results here
</code>```

By constructing the ProcessPoolExecutor with no parameters, most of your CPUs will be fully utilised. This is a very portable approach because there's no explicit assumption about the number of CPUs available. You could, of course, construct with max_workers=N where N is a low number to ensure that a minimal number of CPUs are used concurrently. You might do that if you're not too concerned about how long the overall process is going to take.

Body:
i have a pandas dataframe which consists of approximately 1M rows , it contains information entered by users. i wrote a function that validates if the number entered by the user is correct or not . what im trying to do,  is to execute the function on multiple processors to overcome the issue of doing heavy computation on a single processor. what i did is i split my dataframe into multiple chunks where each chunk contains 50K rows and then used the python multiprocessor module to perform the processing on each chunk separately . the issue is that only the first process is starting and its still using one processor instead of distributing the load on all processors . here is the code i wrote :

 pool = multiprocessing.Pool(processes=16)
 r7 = pool.apply_async(validate.validate_phone_number, (has_phone_num_list[0],fields ,dictionary))
 r8 = pool.apply_async(validate.validate_phone_number, (has_phone_num_list[1],fields ,dictionary))
 print(r7.get())
 print(r8.get())
 pool.close()
 pool.join()

i have attached a screenshot that shows how the CPU usage when executing the above code

any advice on how can i overcome this issue?

Body:
I suggest you try this:

from concurrent.futures import ProcessPoolExecutor

with ProcessPoolExecutor() as executor:
    params = [(pnl, fields, dictionary) for pnl in has_phone_num_list]
    for result in executor.map(validate.validate_phone_number, params):
        pass # process results here

By constructing the ProcessPoolExecutor with no parameters, most of your CPUs will be fully utilised. This is a very portable approach because there's no explicit assumption about the number of CPUs available. You could, of course, construct with max_workers=N where N is a low number to ensure that a minimal number of CPUs are used concurrently. You might do that if you're not too concerned about how long the overall process is going to take.


问:
RecyclerView RTL some items not adjusted
I'm using a RecyclerView to show a list of country codes, countries and flags respecively. The app is supporting RTL, so the layout of item is a simple Constraintlayout with 3 elements:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/selectable_background">

    <ImageView
        android:id="@+id/countryFlag"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:scaleType="centerInside"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/countryName"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:textAlignment="viewStart"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/countryCode"
        app:layout_constraintStart_toEndOf="@+id/countryFlag"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/countryCode"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

But sometimes I get this visual representation in RTL (Arabic) like this, where some items are not aligned properly. See Angola and Anguilla country items:

答: You need a fixed width for the country code, this is what is misaligning the text</p>

Body:
I'm using a RecyclerView to show a list of country codes, countries and flags respecively. The app is supporting RTL, so the layout of item is a simple Constraintlayout with 3 elements:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/selectable_background">

    <ImageView
        android:id="@+id/countryFlag"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:scaleType="centerInside"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/countryName"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:textAlignment="viewStart"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/countryCode"
        app:layout_constraintStart_toEndOf="@+id/countryFlag"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/countryCode"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

But sometimes I get this visual representation in RTL (Arabic) like this, where some items are not aligned properly. See Angola and Anguilla country items:


答:
As suggested in this answer, you can use pandarallel for using Pandas' apply function in parallel. Unfortunately as I cannot try your code I am not able to find the problem. Did you try to use less processors (like 8 instead of 16)?

Note that in some cases the parallelization doesn't work.

Title: multiprocessing a function execution with python


问:
malloc convert memory for struct
What is the right way to malloc memory ? And what is the difference between them ?

```<code>void parse_cookies(const char *cookie, cookie_bank **my_cookie, int *cookies_num)
{
   *my_cookie = malloc(sizeof(cookie_bank) * 1);
   *my_cookie = (cookie_bank *)malloc(sizeof(cookie_bank) * 1);
   my_cookie = (cookie_bank **)malloc(sizeof(cookie_bank) * 1);
   ///
}
</code>```

I'm trying to malloc array of cookie_bank structs function.

答:
I just would like to recommend you to read some C textbook.  It seems to me that you do not have clear understanding on how pointers work in C language.

Anyway, here is some example to allocate memory with malloc.

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

void parse_cookies(const char *cookie, cookie_bank **my_cookie, int *cookies_num)
{
    if (cookies_num == NULL || *cookies_num == 0) {
        return;
    }
    if (my_cookie == NULL) {
        my_cookie = (cookie_bank**)malloc(sizeof(cookie_bank*) * *cookies_num);
    }
    for (int i = 0; i < *cookies_num; i++) {
        *my_cookie = (cookie_bank*)malloc(sizeof(cookie_bank));
        my_cookie++;
    }
}
</code>```

Of course, this example does not cover any error handling.  Basically, my_cookie is pointer to pointer which means my_cookie is just pointer to point memory location where it holds array of pointers.  The first malloc allocate the memory using size of pointer and requested number of cookie structure.  Then second malloc actually allocate memory for each structure.

The problem of this function is that it can easily cause memory leak unless using this very carefully.

Anyway, it is important to understand how C pointer works.

ContentLicense: CC BY-SA 3.0

Title: malloc convert memory for struct

Body:
What is the right way to malloc memory ? And what is the difference between them ?

void parse_cookies(const char *cookie, cookie_bank **my_cookie, int *cookies_num)
{
   *my_cookie = malloc(sizeof(cookie_bank) * 1);
   *my_cookie = (cookie_bank *)malloc(sizeof(cookie_bank) * 1);
   my_cookie = (cookie_bank **)malloc(sizeof(cookie_bank) * 1);
   ///
}

I'm trying to malloc array of cookie_bank structs function.

Body:
I just would like to recommend you to read some C textbook.  It seems to me that you do not have clear understanding on how pointers work in C language.

Anyway, here is some example to allocate memory with malloc.

#include <stdlib.h>

void parse_cookies(const char *cookie, cookie_bank **my_cookie, int *cookies_num)
{
    if (cookies_num == NULL || *cookies_num == 0) {
        return;
    }
    if (my_cookie == NULL) {
        my_cookie = (cookie_bank**)malloc(sizeof(cookie_bank*) * *cookies_num);
    }
    for (int i = 0; i < *cookies_num; i++) {
        *my_cookie = (cookie_bank*)malloc(sizeof(cookie_bank));
        my_cookie++;
    }
}

Of course, this example does not cover any error handling.  Basically, my_cookie is pointer to pointer which means my_cookie is just pointer to point memory location where it holds array of pointers.  The first malloc allocate the memory using size of pointer and requested number of cookie structure.  Then second malloc actually allocate memory for each structure.

The problem of this function is that it can easily cause memory leak unless using this very carefully.

Anyway, it is important to understand how C pointer works.


问:
Can I send a Image to whatsApp using html hyperlink / a tag?
we can send text using html a tag with the following code

Hello, world!

or

Hello, World!

now If I want to send a Image attachment , how can do that?

答: U can't. The closest to it would be to send a link in the message that has a image preview, but that's not that usefull. I'm guessing this wouldn't even be possible to add in whatsapp because to access a user file like an image I believe this has to be done with a direct user interaction (like manually selecting the image), but not by clicking a link, just by doing that whatsapp can't get the image from user storage.</p>


问:
Settimeout in javascript performance issue

Problem

I am building algorithms simulator tool to simulate how algorithms work.
In BFS Algorithm I wanted to slow down the result display

So I used setTimeout function after each step to wait about 10ms before hitting the next step.
I used promise to be able to use async to easily wait the whole period and force the algorithm to stop till the wait function finishes

function implementation

```<code>function wait(time) {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve();
        }, time);
    })
}
</code>```

BFS

```<code>while (queue.length) {
    let currentId = queue[index++];
    let tile = board.tileOf(currentId);
    tile.visit();
    if (currentId == targetId) {
        return;
    }
    await wait(10);
    for (let direction of DIRECTIONS) {
        let childId = moveId(currentId, direction);
        if (childId == undefined)
            continue;
        childId = parseInt(childId);
        let child = board.tileOf(childId);
        if (child.available()) {
            child.visit(true);
            queue.push(childId);
            pervNode[childId] = currentId;
        }
    }
}
</code>```

the problem is when I run the code it works fine but sometimes it takes very long time to display the solution more and more than just 10ms.

I am wondering why it's not accurate?
is this because of the approach that I am using?
and if there is a better solution what could it be?

Try the tool from here

答: As JavaScript is a single-thread language, when you place a function call inside setTimeout(), this function gets in a queue and waits until other functions in a call stack (that were called before it) are finished and the call stack become empty. Time you specify as a second parameter to setTimeout() starts counting from the moment of placing the function in the queue, but not always the queue is empty

Body:
Problem

I am building algorithms simulator tool to simulate how algorithms work.
In BFS Algorithm I wanted to slow down the result display

So I used setTimeout function after each step to wait about 10ms before hitting the next step.
I used promise to be able to use async to easily wait the whole period and force the algorithm to stop till the wait function finishes

function implementation

function wait(time) {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve();
        }, time);
    })
}

BFS

while (queue.length) {
    let currentId = queue[index++];
    let tile = board.tileOf(currentId);
    tile.visit();
    if (currentId == targetId) {
        return;
    }
    await wait(10);
    for (let direction of DIRECTIONS) {
        let childId = moveId(currentId, direction);
        if (childId == undefined)
            continue;
        childId = parseInt(childId);
        let child = board.tileOf(childId);
        if (child.available()) {
            child.visit(true);
            queue.push(childId);
            pervNode[childId] = currentId;
        }
    }
}

the problem is when I run the code it works fine but sometimes it takes very long time to display the solution more and more than just 10ms.

I am wondering why it's not accurate?
is this because of the approach that I am using?
and if there is a better solution what could it be?

Try the tool from here


问:
Reactive forms - Warning when using the disabled attribute
I want to disable a select box in one of my forms while there is nothing to select in it until the data for this select box was returned from the server. I need to do this because the data shown in the select box depends on what was selected in another select box. Whenever something is selected in that other select box, I need to load the corresponding options from the server. To disable the select box while there is no data available for it, I am using the disabled attribute like this:

```<code><mat-select formControlName="formId" [disabled]="formNames.length === 0">
  <mat-option
    *ngFor="let formName of formNames"
    [value]="formName.id"
  >
    {{ formName.formName }}
  </mat-option>
</mat-select>
</code>```

I then subscribed to the valueChanges event of the other select box like this:

```<code>this.createForm.controls.formTypeId.valueChanges.subscribe((value: number) => {
  this.formsService.getFormNames(value).subscribe((formNames) => {
    this.formNames = formNames;
  });
});
</code>```

While this seems to work perfectly fine, I keep getting the following warning in the browser console:

```<code>  It looks like you're using the disabled attribute with a reactive form directive. If you set disabled to true
  when you set up this control in your component class, the disabled attribute will actually be set in the DOM for
  you. We recommend using this approach to avoid 'changed after checked' errors.

  Example:
  form = new FormGroup({
    first: new FormControl({value: 'Nancy', disabled: true}, Validators.required),
    last: new FormControl('Drew', Validators.required)
  });
</code>```

I do not understand what this warning means and the suggested solution also doesn't really help me because I do not simply want to set the disabled property to true. What am I supposed to actually do to achieve the desired behavior of disabling the select box while there are no form names available? Or is my approach fine and I should just ignore this warning?

答:
Angular is telling you that you are mixing two different types of approaches to forms. One is template-driven, while the other is reactive forms. As you are using reactive forms angular warning you that you should use the reactive approach to disable your form control instead of using the HTML attribute [disabled]

In your use case you can just enable or disable the field depending upon it's length in the subscribe block which should look like this:

this.createForm.controls.formTypeId.valueChanges.subscribe((value: number) => {
  this.formsService.getFormNames(value).subscribe((formNames) => {
    if(formNames.length > 0){
        this.createForm.controls.formControlName.enable();
    } else {
        this.createForm.controls.formControlName.disable()
    }
    this.formNames = formNames;
  });
});
```
<p>Read this for better insight: https://indepth.dev/posts/1474/disable-form-controls-using-forms-api-or-html-attributes</p>
<p>Also, you are using nested subscribes. i.e. one <code>subscribe</code> in another <code>subscribe</code>, which is a bad practice and should be avoided. I advise you to look into RxJs maps such as <code>switchMap</code>, <code>mergeMap</code> etc whichever fulfills your use-case. For example, if you want to cancel the previous subscription when a new event comes you can use <code>switchMap</code>:</p>
<pre class="lang-js prettyprint-override"><code>this.createForm.controls.formTypeId.valueChanges
      .pipe(
          switchMap((value: number) => {
              return this.formsService.getFormNames(value);
          })
      )
      .subscribe(formNames => {
          if (formNames.length > 0) {
              this.createForm.controls.formControlName.enable();
          } else {
              this.createForm.controls.formControlName.disable();
          }
          this.formNames = formNames;
      });
</code>```

Body:
I want to disable a select box in one of my forms while there is nothing to select in it until the data for this select box was returned from the server. I need to do this because the data shown in the select box depends on what was selected in another select box. Whenever something is selected in that other select box, I need to load the corresponding options from the server. To disable the select box while there is no data available for it, I am using the disabled attribute like this:

<mat-select formControlName="formId" [disabled]="formNames.length === 0">
  <mat-option
    *ngFor="let formName of formNames"
    [value]="formName.id"
  >
    {{ formName.formName }}
  </mat-option>
</mat-select>

I then subscribed to the valueChanges event of the other select box like this:

this.createForm.controls.formTypeId.valueChanges.subscribe((value: number) => {
  this.formsService.getFormNames(value).subscribe((formNames) => {
    this.formNames = formNames;
  });
});

While this seems to work perfectly fine, I keep getting the following warning in the browser console:

  It looks like you're using the disabled attribute with a reactive form directive. If you set disabled to true
  when you set up this control in your component class, the disabled attribute will actually be set in the DOM for
  you. We recommend using this approach to avoid 'changed after checked' errors.

  Example:
  form = new FormGroup({
    first: new FormControl({value: 'Nancy', disabled: true}, Validators.required),
    last: new FormControl('Drew', Validators.required)
  });

I do not understand what this warning means and the suggested solution also doesn't really help me because I do not simply want to set the disabled property to true. What am I supposed to actually do to achieve the desired behavior of disabling the select box while there are no form names available? Or is my approach fine and I should just ignore this warning?

Body:
Angular is telling you that you are mixing two different types of approaches to forms. One is template-driven, while the other is reactive forms. As you are using reactive forms angular warning you that you should use the reactive approach to disable your form control instead of using the HTML attribute [disabled]

In your use case you can just enable or disable the field depending upon it's length in the subscribe block which should look like this:

this.createForm.controls.formTypeId.valueChanges.subscribe((value: number) => {
  this.formsService.getFormNames(value).subscribe((formNames) => {
    if(formNames.length > 0){
        this.createForm.controls.formControlName.enable();
    } else {
        this.createForm.controls.formControlName.disable()
    }
    this.formNames = formNames;
  });
});

Read this for better insight: https://indepth.dev/posts/1474/disable-form-controls-using-forms-api-or-html-attributes

Also, you are using nested subscribes. i.e. one subscribe in another subscribe, which is a bad practice and should be avoided. I advise you to look into RxJs maps such as switchMap, mergeMap etc whichever fulfills your use-case. For example, if you want to cancel the previous subscription when a new event comes you can use switchMap:

this.createForm.controls.formTypeId.valueChanges
      .pipe(
          switchMap((value: number) => {
              return this.formsService.getFormNames(value);
          })
      )
      .subscribe(formNames => {
          if (formNames.length > 0) {
              this.createForm.controls.formControlName.enable();
          } else {
              this.createForm.controls.formControlName.disable();
          }
          this.formNames = formNames;
      });


问:
How to not show parsing error in MathJax?
I am using MathJax for showing equations on my webpage. Using the below config script.
But in case of syntax error, I Don't wanna show the exception instead it should show the Jax as it is. Gone through about formatError in here https://docs.mathjax.org/en/latest/options/input/tex.html but How to use it? tried a couple of methods but it does not help.

```<code><script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    showMathMenu: false,
    extensions: ["tex2jax.js"],
    messageStyle: "none",
    showProcessingMessages : false,
    jax: ["input/TeX", "output/SVG"],
    tex2jax: {
      inlineMath: [ ['$','$'], ["\\(","\\)"] ],
      displayMath: [ ['$$','$$'], ["\\[","\\]"] ],
      processEscapes: true,
      preview: "none",

    },
    processEnvironments: true,
  });
</script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/MathJax.js"></script>
</code>```

答:
You probably want to use the noUndefined and noErrors extensions.  The first will cause undefined macros to show as a red version of the macro name, but will typeset the rest of the expression.  For example x + \3 would appear as

rather than the undefined control sequence message that you are seeing above.

The second causes any other type of error to just display the original TeX code rather than the error message.  So \frac{a}{b with a missing close brace would just display as \frac{a}{b rather than the error message.

To do this, you would add

TeX: {
  extensions: ['noErrors.js', 'noUndefined.js']
},
```

to your configuration.  See the documentation for noUndefined and noErrors for more details.

Body:
You probably want to use the noUndefined and noErrors extensions.  The first will cause undefined macros to show as a red version of the macro name, but will typeset the rest of the expression.  For example x + \3 would appear as

rather than the undefined control sequence message that you are seeing above.

The second causes any other type of error to just display the original TeX code rather than the error message.  So \frac{a}{b with a missing close brace would just display as \frac{a}{b rather than the error message.

To do this, you would add

TeX: {
  extensions: ['noErrors.js', 'noUndefined.js']
},

to your configuration.  See the documentation for noUndefined and noErrors for more details.


问:
Starting up an Intel SGX Enclave from a Java application
Good evening, and thanks to everyone in advance.

I am currently working on My MsC Thesis, and for the proposed solution so far, I am to use an existing Java application (BFT-SMART, built with gradle version 7.3.3) and add it a layer of confidentiality using Intel SGX, with the objective of each replica containing its own Intel SGX enclave.

My problem however, is not being able to start an enclave from a Java application other than a given example.

The given example was all I found, and after some changes to its make File, I was able to successfully execute this simple Java application in Simulation Mode.
https://github.com/lishen-nt/sgx-language-adapter/

However, how do I adapt this to something different? The given code:

```<code>static {

        System.loadLibrary("Sgx");
    }

    /* Initialize the enclave */
    public native int jni_initialize_enclave();

</code>```

Seems to only work with this given example, not working with other tests that I have personally been trying, with the project being unable to find said library. Is there a way to add Make File statements to a gradle build in order to link Intel SGX Libraries to the project?

Before considering adding Intel SGX to the aforementioned project, I was trying to build my own sample project to base myself off of, any tips on this?

I do apologize for the extremely ambiguous and open-ended question, I am just at a complete loss of where to begin looking for options or examples I could base myself off of.

Thanks for everyone's help!

答: Rather than trying this old alternative (updated 4 years ago), I would try something newer, such as Scone or SGX-LKL. I think it would be easier to get some help and get success with your project.</p>

Body:
Good evening, and thanks to everyone in advance.

I am currently working on My MsC Thesis, and for the proposed solution so far, I am to use an existing Java application (BFT-SMART, built with gradle version 7.3.3) and add it a layer of confidentiality using Intel SGX, with the objective of each replica containing its own Intel SGX enclave.

My problem however, is not being able to start an enclave from a Java application other than a given example.

The given example was all I found, and after some changes to its make File, I was able to successfully execute this simple Java application in Simulation Mode.
https://github.com/lishen-nt/sgx-language-adapter/

However, how do I adapt this to something different? The given code:

static {

        System.loadLibrary("Sgx");
    }

    /* Initialize the enclave */
    public native int jni_initialize_enclave();

Seems to only work with this given example, not working with other tests that I have personally been trying, with the project being unable to find said library. Is there a way to add Make File statements to a gradle build in order to link Intel SGX Libraries to the project?

Before considering adding Intel SGX to the aforementioned project, I was trying to build my own sample project to base myself off of, any tips on this?

I do apologize for the extremely ambiguous and open-ended question, I am just at a complete loss of where to begin looking for options or examples I could base myself off of.

Thanks for everyone's help!


问:
Double-notched corner in CSS
Is it possible to produce the following shape containing a number with CSS:

I've found tons of examples with a solid background and no border, but those don't apply.

答:
Yes, it is possible with CSS. You would have to use a container element for the shape, clip-path to make the polygon and add the border with a pseudo element:

div.shape {
  box-sizing: border-box;

  /* position */
  position: relative;
  display: grid;
  justify-content: center;
  align-content: center;

  --color: blue;
  --size: 2rem;
  --slant: 30%;
  width: var(--size);
  height: var(--size);
  background: blue;
}

/* the border is the ::before pseudo element, it has the same polygon but is slightly smaller */
div.shape::before {
    content: "";
  --border-width: 4px;
  position: absolute;
  top: calc(var(--border-width) / 2);
  left: calc(var(--border-width) / 2);
  width: calc(var(--size) - var(--border-width));
  height: calc(var(--size) - var(--border-width));

  background: white;
}

div.shape, div.shape::before {
  /* notches */
  clip-path: polygon(0 var(--slant), var(--slant) 0, 100% 0, 100% calc(100% - var(--slant)),  calc(100% - var(--slant)) 100%, 0 100%);
}

p {
  position: relative;
  color: var(--color);
  font-size: 1.2rem;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="shape">
  <p>1</p>
</div></code>```

Title: Double-notched corner in CSS

Body:
Yes, it is possible with CSS. You would have to use a container element for the shape, clip-path to make the polygon and add the border with a pseudo element:

div.shape {
  box-sizing: border-box;

  /* position */
  position: relative;
  display: grid;
  justify-content: center;
  align-content: center;

  --color: blue;
  --size: 2rem;
  --slant: 30%;
  width: var(--size);
  height: var(--size);
  background: blue;
}

/* the border is the ::before pseudo element, it has the same polygon but is slightly smaller */
div.shape::before {
    content: "";
  --border-width: 4px;
  position: absolute;
  top: calc(var(--border-width) / 2);
  left: calc(var(--border-width) / 2);
  width: calc(var(--size) - var(--border-width));
  height: calc(var(--size) - var(--border-width));

  background: white;
}

div.shape, div.shape::before {
  /* notches */
  clip-path: polygon(0 var(--slant), var(--slant) 0, 100% 0, 100% calc(100% - var(--slant)),  calc(100% - var(--slant)) 100%, 0 100%);
}

p {
  position: relative;
  color: var(--color);
  font-size: 1.2rem;
}

<div class="shape">
  <p>1</p>
</div>


问:
Office 365 SMTP starts firing net_io_connectionclosed
A while ago I've configured my ASP.NET C# project to send e-mail via Office 365, but last week it's starting to throw a lot of exceptions.

```<code>System.IO.IOException: Unable to read data from the transport connection: net_io_connectionclosed.
at System.Net.Mail.SmtpReplyReaderFactory.ProcessRead(Byte[] buffer, Int32 offset, Int32 read, Boolean readLine)
at System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader caller, Boolean oneLine)
at System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader caller)
at System.Net.Mail.CheckCommand.Send(SmtpConnection conn, String& response)
at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, Boolean allowUnicode, SmtpFailedRecipientException& exception)
at System.Net.Mail.SmtpClient.Send(MailMessage message)
</code>```

How can I prevent this from happening?

```<code>  MailMessage message = new MailMessage(System.Configuration.ConfigurationManager.AppSettings["smtpfrom"], email, strOnderwerp, strBody);
            message.Priority = MailPriority.Normal;
            message.IsBodyHtml = true;
            SmtpClient client = new SmtpClient(System.Configuration.ConfigurationManager.AppSettings["smtpserver"], Convert.ToInt32((System.Configuration.ConfigurationManager.AppSettings["smtpport"])));

            client.EnableSsl = Boolean.Parse(System.Configuration.ConfigurationManager.AppSettings["smtpssl"]); ;
            client.Credentials = new System.Net.NetworkCredential(System.Configuration.ConfigurationManager.AppSettings["smtpuser"], System.Configuration.ConfigurationManager.AppSettings["smtppass"]);

            client.Send(message);
            client.Dispose();
</code>```

The exceptions seems to be thrown on the Dispose.

答:
The holy grail of all this bothering with the net_io_connectionclosed Errors while connecting to Office365 in VB.NET or c# is the TSL Version.

When you are working with a VB.NET oder c# Application wanting to connect, send an receive Msg. to/from O365 you have to force TLS12 in you code.

Just put the last line below your EnableSSL = True an you will be fine:

Last Line to force TLS12

Body:
A while ago I've configured my ASP.NET C# project to send e-mail via Office 365, but last week it's starting to throw a lot of exceptions.

System.IO.IOException: Unable to read data from the transport connection: net_io_connectionclosed.
at System.Net.Mail.SmtpReplyReaderFactory.ProcessRead(Byte[] buffer, Int32 offset, Int32 read, Boolean readLine)
at System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader caller, Boolean oneLine)
at System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader caller)
at System.Net.Mail.CheckCommand.Send(SmtpConnection conn, String& response)
at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, Boolean allowUnicode, SmtpFailedRecipientException& exception)
at System.Net.Mail.SmtpClient.Send(MailMessage message)

How can I prevent this from happening?

  MailMessage message = new MailMessage(System.Configuration.ConfigurationManager.AppSettings["smtpfrom"], email, strOnderwerp, strBody);
            message.Priority = MailPriority.Normal;
            message.IsBodyHtml = true;
            SmtpClient client = new SmtpClient(System.Configuration.ConfigurationManager.AppSettings["smtpserver"], Convert.ToInt32((System.Configuration.ConfigurationManager.AppSettings["smtpport"])));

            client.EnableSsl = Boolean.Parse(System.Configuration.ConfigurationManager.AppSettings["smtpssl"]); ;
            client.Credentials = new System.Net.NetworkCredential(System.Configuration.ConfigurationManager.AppSettings["smtpuser"], System.Configuration.ConfigurationManager.AppSettings["smtppass"]);

            client.Send(message);
            client.Dispose();

The exceptions seems to be thrown on the Dispose.


问:
PHP Regex Match those which start with Capital letter
It sounds pretty simple but I cant figure this out, please help me out.

So... I have file with following data:

```<code>Name: Santi
Surname: Dore
Name: Rob
Surname: Doe
and so on..
</code>```

I need to match only the whole part that starts with "Name:" ... NOT "Surname:" ...

Here is what I am using right now to match it:

```<code>/Name(:)(.*)/i
</code>```

It will match both but I need just Name: ...

Please dont suggest any other way of finding, just please help me out with regex to work the way I described.

答:
Leave off the i modifier, which makes the regex case-insensitive.

And/or, add some word boundaries:

```<code>/\bName(:) (.*)\b/
</code>```

Body:
It sounds pretty simple but I cant figure this out, please help me out.

So... I have file with following data:

Name: Santi
Surname: Dore
Name: Rob
Surname: Doe
and so on..

I need to match only the whole part that starts with "Name:" ... NOT "Surname:" ...

Here is what I am using right now to match it:

/Name(:)(.*)/i

It will match both but I need just Name: ...

Please dont suggest any other way of finding, just please help me out with regex to work the way I described.

Body:
Leave off the i modifier, which makes the regex case-insensitive.

And/or, add some word boundaries:

/\bName(:) (.*)\b/


问:
How to pass Auth in a "get" request using urllib.request Python
To make a get request with Python I was using urllib.request.urlopen(url) but I am having problem passing username and password to http://httpbin.org/basic-auth/ali/pass

```<code>import urllib.request
data={"user": "ali","passwd":"pass"}

data = urllib.parse.urlencode(data)
data = data.encode('utf-8')

url = "http://httpbin.org/basic-auth/ali/pass"
response = urllib.request.Request(url,data=data)

print(urllib.request.urlopen(response))
</code>```

答:
I tried using requests module which work perfectly but I am trying to learn about urllib.request module so that is why.</p>
```<code>from requests.auth import HTTPBasicAuth
import requests
r=requests.get('http://httpbin.org/basic-auth/ali/pass', auth=HTTPBasicAuth('ali', 'pass'))
print(r.status_code)
</code>```

Body:
To make a get request with Python I was using urllib.request.urlopen(url) but I am having problem passing username and password to http://httpbin.org/basic-auth/ali/pass

import urllib.request
data={"user": "ali","passwd":"pass"}

data = urllib.parse.urlencode(data)
data = data.encode('utf-8')

url = "http://httpbin.org/basic-auth/ali/pass"
response = urllib.request.Request(url,data=data)

print(urllib.request.urlopen(response))

Body:
I tried using requests module which work perfectly but I am trying to learn about urllib.request module so that is why.

from requests.auth import HTTPBasicAuth
import requests
r=requests.get('http://httpbin.org/basic-auth/ali/pass', auth=HTTPBasicAuth('ali', 'pass'))
print(r.status_code)


问:
PHP can you convert unicode from within a string
I have a php string with the following

```<code>$string="Br\xFCtal"
</code>```

Is it possible to convert the \xFC part to the correct special character?

I know this works

```<code>$string="\xFC";
echo utf8_encode($string);
</code>```

but I don't know if it can be done as part of a string with other characters.

Thanks

答:
If the encoded string is a literal encoding in JSON string, you could replace '\x' to unicode format '\u00'.

$string = '"Br\xFCtal"';
echo json_decode(str_replace('\x', '\u00', $string));
```
<p>Output:</p>
```Brütal
```

Body:
I have a php string with the following

$string="Br\xFCtal"

Is it possible to convert the \xFC part to the correct special character?

I know this works

$string="\xFC";
echo utf8_encode($string);

but I don't know if it can be done as part of a string with other characters.

Thanks

Body:
If the encoded string is a literal encoding in JSON string, you could replace '\x' to unicode format '\u00'.

$string = '"Br\xFCtal"';
echo json_decode(str_replace('\x', '\u00', $string));

Output:

Brütal


问:
Is there a way to access the "previous row" value in a SELECT statement?
I need to calculate the difference of a column between two lines of a table. Is there any way I can do this directly in SQL? I'm using Microsoft SQL Server 2008.

I'm looking for something like this:

```<code>SELECT value - (previous.value) FROM table
</code>```

Imagining that the "previous" variable reference the latest selected row. Of course with a select like that I will end up with n-1 rows selected in a table with n rows, that's not a probably, actually is exactly what I need.

Is that possible in some way?

答:
LEFT JOIN the table to itself, with the join condition worked out so the row matched in the joined version of the table is one row previous, for your particular definition of "previous".

Update: At first I was thinking you would want to keep all rows, with NULLs for the condition where there was no previous row.  Reading it again you just want that rows culled, so you should an inner join rather than a left join.

Update:

Newer versions of Sql Server also have the LAG and LEAD Windowing functions that can be used for this, too.

OwnerDisplayName: Augusto Radtke

Body:
I need to calculate the difference of a column between two lines of a table. Is there any way I can do this directly in SQL? I'm using Microsoft SQL Server 2008.

I'm looking for something like this:

SELECT value - (previous.value) FROM table

Imagining that the "previous" variable reference the latest selected row. Of course with a select like that I will end up with n-1 rows selected in a table with n rows, that's not a probably, actually is exactly what I need.

Is that possible in some way?

OwnerDisplayName: Joel Coehoorn


问:
Pandas aggregate order for monthly/weekly changes
I am retrieving data from a SQL database using django, and then convert it to a pandas dataframe.
The goal is to calculate some metrics for each person well as metrics overall across all persons.

After calculating my metrics, I want to compare the values to the previous month and calculate the changes as percentage.

This works roughly like this:

member_frame = member_frame.truncate(before=(previous_start - timedelta(days=1)))
```
<p>which gives me all entries from the last month up to including the end of this month.</p>
<p>I then calculate the sum of some values:</p>
<pre class="lang-py prettyprint-override"><code>aggregate_avgs = member_frame.groupby(member_frame.index.month).mean().replace(np.inf, 1).fillna(0)
</code>```

And finally calculate the percentage changes:

avgs_change = aggregate_avgs.pct_change().replace(np.inf, 1).fillna(-1)
```
<p>Which, if we look at the changes from january to february, like that:</p>
```target_date
1           -1.000000 -1.000000 -1.000000           -1.0 -1.000000 -1.000000  -1.000000
2            0.142857  0.076923 -0.828571            0.0 -0.587774 -0.699994  -0.507199
```
<p>This works... fine? Since I am only interested in the changes from the first to the second date, I simply take the values from the second row.</p>
<p>But if I do the same for december and january, I get this:</p>
```target_date
1           -1.00000 -1.000000 -1.000000           -1.0 -1.000000 -1.000000  -1.000000
12           0.02682  0.273444  0.449811            0.0  0.259059  0.424178   0.223225
```

As you can see, this is somewhat reversed, and the changes are actually for the wrong month.
The target_date index is a datetime index.

I suspect that the same will happen if I do that with weekly changes, when crossing years.

What am I doing wrong?
I am quite new to pandas, so it might as well be a very easy mistake.

答: I think you could write aggregate_avgs = member_frame.groupby(pd.Grouper(freq="M")).mean() as is described here.

Body:
I am retrieving data from a SQL database using django, and then convert it to a pandas dataframe.
The goal is to calculate some metrics for each person well as metrics overall across all persons.

After calculating my metrics, I want to compare the values to the previous month and calculate the changes as percentage.

This works roughly like this:

member_frame = member_frame.truncate(before=(previous_start - timedelta(days=1)))

which gives me all entries from the last month up to including the end of this month.

I then calculate the sum of some values:

aggregate_avgs = member_frame.groupby(member_frame.index.month).mean().replace(np.inf, 1).fillna(0)

And finally calculate the percentage changes:

avgs_change = aggregate_avgs.pct_change().replace(np.inf, 1).fillna(-1)

Which, if we look at the changes from january to february, like that:

target_date
1           -1.000000 -1.000000 -1.000000           -1.0 -1.000000 -1.000000  -1.000000
2            0.142857  0.076923 -0.828571            0.0 -0.587774 -0.699994  -0.507199

This works... fine? Since I am only interested in the changes from the first to the second date, I simply take the values from the second row.

But if I do the same for december and january, I get this:

target_date
1           -1.00000 -1.000000 -1.000000           -1.0 -1.000000 -1.000000  -1.000000
12           0.02682  0.273444  0.449811            0.0  0.259059  0.424178   0.223225

As you can see, this is somewhat reversed, and the changes are actually for the wrong month.
The target_date index is a datetime index.

I suspect that the same will happen if I do that with weekly changes, when crossing years.

What am I doing wrong?
I am quite new to pandas, so it might as well be a very easy mistake.


问:
Does the ITfoxtec.Identity.Saml2 .NET Core library support RedHat SSO with SAML 2.0 or has anyone gotten it to work?
Looking for the easiest way to authenticate with RedHat SSO SAML 2.0 (not OpenId) in a .NET Core application.  I stumbled upon the ITfoxtec.Identity.Saml2 library and was wondering if anyone has gotten this to work before struggling with an endless array of trial-and-error scenarios.

Thanks!

答: Answering my own question- yes it does seem to work.  The Startup.cs given in the sample code mostly works as-is, except SAML wants the Issuer to be the client ID in RedHat SSO and you need to fill in your AssertionConsumerServiceUrl in the redirect binding on the login.</p>


问:
Django: add new column by function ( datetimefield to datefield )

Change datetimefield to datefield and put in in new column

python ways are useless because i want to be able to use order_by and distinct

i don't want to use sorted() and etc

my django model is something like this

class Product(models.Model):
    price = models.PositiveIntegerField(null=False, default=0)
    discounted_price = models.PositiveIntegerField(null=False, default=0)
    date = models.DateTimeField(auto_now_add=True)
```
<p>And i want to be able to call <strong>date()</strong> function<br />
and put it in another column and <strong>order_by</strong> it</p>
<pre class="lang-py prettyprint-override"><code>Product.objects.annotate(day=date.date()).order_by('-day').distinct('day')
</code>```

答:
After lots of search i found my answer

from django.db.models.functions import TruncDate

Product.objects.annotate(day=TruncDate('date')).order_by('-day').distinct('day')
```

Body:
Change datetimefield to datefield and put in in new column

python ways are useless because i want to be able to use order_by and distinct

i don't want to use sorted() and etc

my django model is something like this

class Product(models.Model):
    price = models.PositiveIntegerField(null=False, default=0)
    discounted_price = models.PositiveIntegerField(null=False, default=0)
    date = models.DateTimeField(auto_now_add=True)

And i want to be able to call date() function

and put it in another column and order_by it

Product.objects.annotate(day=date.date()).order_by('-day').distinct('day')


问:
Cannot upload any new bundle on google play store (does nothing) after removing from the bundle explorer
I tried uploading an app bundle, it worked fine, but I wanted to check a few things and ended up with the error message "Version code 1 has already been used. Try another version code"

So I did what was written in here https://stackoverflow.com/a/68058512/14027901
-> I removed the aab from the bundle explorer.

The problem is that now I cannot add any bundle anymore - when I go in "create new release" I cannot drag and drop, it does not do anything.

When I go back to "all apps" it says I have updated the app today although I have not validated anything.

Looks like something is unsync, how do I reinitialise the google play state?

(I have tried to log out and log in, and clear cache and it did not work)

答: So the next day, I created a new bundle with an increased version number and it worked, google let me drag and drop it!</p>


问:
plotly - remove or ignore "Non-leaves rows" for sunburst diagram
I have a DataFrame with some "Non-leaves rows" in it. Is there any way to get plotly to ignore them, or a way to automatically remove them?

Here's a sample DataFrame:

0
1
2
3

0
Alice
Bob

1
Alice
Bob
Carol
David

2
Alice
Bob
Chuck
Delia

3
Alice
Bob
Chuck
Ella

4
Alice
Bob
Frank

In this case, I get the error Non-leaves rows are not permitted in the dataframe because the 0th row is not a distinct leaf.

I've tried using df = df.replace(np.NaN, pd.NA).where(df.notnull(), None) to add the None to the empty values, but the error persists.

Is there any way to have the non-leaves ignored? If not, is there a simple way to prune them? My real dataset is several thousand rows.

答:
One way is to reshape your dataframe with unique relations parent-child. Here is one way:</p>
```<code>import plotly.express as px

cols = df.columns
data = (
    pd.concat(
        [df[[i,j]].rename(columns={i:'parents',j:'childs'})
         for i,j in zip(cols[:-1], cols[1:])])
      .drop_duplicates()
)

fig = px.sunburst(data, names='childs', parents='parents')
fig.show()
</code>```

Body:
One way is to reshape your dataframe with unique relations parent-child. Here is one way:

import plotly.express as px

cols = df.columns
data = (
    pd.concat(
        [df[[i,j]].rename(columns={i:'parents',j:'childs'})
         for i,j in zip(cols[:-1], cols[1:])])
      .drop_duplicates()
)

fig = px.sunburst(data, names='childs', parents='parents')
fig.show()


问:
Why is the select() function not available in Flutter's cloud_firestore package?
This question might be more targeted for the FlutterFirebase team.

When looking at the API documentation for the Firestore, we see that there is a function inside of the Query class called select() (See the documentation here). However this function is not available in the cloud_firestore package. Is there any reasons why it has not been made available for the Flutter package?

I am guessing that we could work around and call the API directly instead of going through the package but that wouldn't be optimal.

答: The select() is a function in the Admin SDK, so on the server side. The cloud_firestore package is done to be used in the client side, it can be compared to Javascript Firebase client SDK which also doesn't have the select() function.


问:
Writing and editing a PHP config file from a HTML form?
Hi just looking for some direction, I have a HTML form which has several fields and basically what I am wanting to do is save the data entered from the form to a PHP config file and also have the ability to edit the saved data by accessing and submitting the form again. I would prefer to do this without the use of a database.

So here's an example:

```<code><form method="post" name="config_form">
<div id="field">
<label>Keywords</label>
<br />
<input type="text" name="keyword">
</div>

<br />

<select name="color">
<option value="green">Green</option>
<option value="orange">Orange</option>
<option value="blue">Blue</option>
<option value="red">Red</option>
</select>

</form>
</code>```

So the user enters 'computer' as the keyword and selects the color 'blue'. I want to then save this data into my config.php file as variables allowing my other website pages to access this data. Should this all be in an array as well?

```<code><?php
//config file
$keyword = "computer";
$color = "blue";

?>
</code>```

Also when I go back access the form again can I make it so the fields are prefilled with the data from the config.php file?

Any help would be much appreciated thank you!

答:
You can do this in multiple ways. Best way would be to use a database such as MYSQL. You are asking for persistence and that is what DBs are for. Try this.

```<code>$key = $_POST["key"];
$color = $_POST["color"];
mysql_query("INSERT INTO smeTbl VALUES ('1',$key,$color)");
</code>```

THen in the config file or what ever other file you have you can retrieve these values.

```<code> $query = mysql_query("SELECT * FROM smeTbl WHERE id='1'");
 $fetch = mysql_fetch_array($query);
 $keyword = $fetch["key"];
 $color = $fetch["color"];
</code>```

This is just an example and you can refine it based on your needs

Body:
Hi just looking for some direction, I have a HTML form which has several fields and basically what I am wanting to do is save the data entered from the form to a PHP config file and also have the ability to edit the saved data by accessing and submitting the form again. I would prefer to do this without the use of a database.

So here's an example:

<form method="post" name="config_form">

Keywords

<input type="text" name="keyword">

<select name="color">
<option value="green">Green</option>
<option value="orange">Orange</option>
<option value="blue">Blue</option>
<option value="red">Red</option>
</select>

</form>

So the user enters 'computer' as the keyword and selects the color 'blue'. I want to then save this data into my config.php file as variables allowing my other website pages to access this data. Should this all be in an array as well?

<?php
//config file
$keyword = "computer";
$color = "blue";

?>

Also when I go back access the form again can I make it so the fields are prefilled with the data from the config.php file?

Any help would be much appreciated thank you!

Body:
You can do this in multiple ways. Best way would be to use a database such as MYSQL. You are asking for persistence and that is what DBs are for. Try this.

$key = $_POST["key"];
$color = $_POST["color"];
mysql_query("INSERT INTO smeTbl VALUES ('1',$key,$color)");

THen in the config file or what ever other file you have you can retrieve these values.

 $query = mysql_query("SELECT * FROM smeTbl WHERE id='1'");
 $fetch = mysql_fetch_array($query);
 $keyword = $fetch["key"];
 $color = $fetch["color"];

This is just an example and you can refine it based on your needs


问:
How to solve "java.lang.illegalargumentexception collector already registered that provides name"?

How to solve "java.lang.illegalargumentexception collector already registered that provides name" ?
Meter registry class is below :

```<code>    @Configuration
public class RegistryConfig {

    @Bean
    public MeterRegistryCustomizer<MeterRegistry> metricsCommonTags() {
        return registry -> registry.config().commonTags("app.name", "appname");
    }

    @Bean
    public CountedAspect countedAspect(MeterRegistry registry) {
        return new CountedAspect(registry);
    }

    @Bean
    public TimedAspect timedAspect(MeterRegistry meterRegistry) {
        return new TimedAspect(meterRegistry);
    }

}
</code>```

i found a link in which it was suggested to make your metric static  :
https://github.com/prometheus/client_java/issues/279
Please help me what exactly need to be done ? where i need to make static?

答:
If you are using CollectorRegistry.defaultRegistry, then don't forget to clear it between the runs/reloads:

```<code>CollectorRegistry.defaultRegistry.clear();
</code>```

Body:
How to solve "java.lang.illegalargumentexception collector already registered that provides name" ?
Meter registry class is below :

    @Configuration
public class RegistryConfig {

    @Bean
    public MeterRegistryCustomizer<MeterRegistry> metricsCommonTags() {
        return registry -> registry.config().commonTags("app.name", "appname");
    }

    @Bean
    public CountedAspect countedAspect(MeterRegistry registry) {
        return new CountedAspect(registry);
    }

    @Bean
    public TimedAspect timedAspect(MeterRegistry meterRegistry) {
        return new TimedAspect(meterRegistry);
    }

}

i found a link in which it was suggested to make your metric static  :
https://github.com/prometheus/client_java/issues/279
Please help me what exactly need to be done ? where i need to make static?

Body:
If you are using CollectorRegistry.defaultRegistry, then don't forget to clear it between the runs/reloads:

CollectorRegistry.defaultRegistry.clear();


问:
Godot - How do you make Player and Enemy bounce when damaged
In my game I want it so when either the player or the enemy gets damaged they bounce but i do not know how to do so.

code for player:

extends KinematicBody2D

var speed = 200  # speed in pixels/sec
var velocity = Vector2.ZERO
var hasDagger = false

func get_input():
    velocity = Vector2.ZERO
    if Input.is_action_pressed('right'):
        velocity.x += 1
    if Input.is_action_pressed('left'):
        velocity.x -= 1
    if Input.is_action_pressed('down'):
        velocity.y += 1
    if Input.is_action_pressed('up'):
        velocity.y -= 1
    if Input.is_action_just_pressed("sprint"):
        speed += 100
    if Input.is_action_just_released("sprint"):
        speed -= 100

    # Make sure diagonal movement isn't faster
    velocity = velocity.normalized() * speed

func _physics_process(delta):
    get_input()
    velocity = move_and_slide(velocity)
```
<p>enemy code:</p>
<pre class="lang-gdscript prettyprint-override"><code>extends KinematicBody2D

var run_speed = 201
var velocity = Vector2.ZERO
var collider = null
var health = 3

func _physics_process(delta):
    velocity = Vector2.ZERO
    if collider:
        #print(collider)
        velocity = global_position.direction_to(collider.global_position) * run_speed
    velocity = move_and_slide(velocity)

func _on_DetectRadius_body_entered(body):
    collider = body

func _on_DetectRadius_body_exited(body):
    collider = null

func _on_hit_box_body_entered(body):
    health -= 1

    if health == 0:
        get_tree().change_scene("res://scenes/game over.tscn")
</code>```

the health you see in the enemy script is for the player

the player is a kinematicbody2D with a colilistionshape2D and the enemy is the same as that

答:
What I'm going to show is not the only way to go about this - In fact, we should be talking about animations and states - instead it is just one way to tackle this.

I'll define a variable target. I'll leave it without specifying a type, so it is variant. However, I'll have it be Vector2. The reason I leave it variant, is so it can be null. If I could, I'd type it as a nullable Vector2, but Godot does not support that.

The idea is to have the KinematicBody2D go to the target position if it is a Vector2. But if it isn't, let the regular movement continue. Something like this:

```<code>export var speed:float
var velocity := Vector2.ZERO
var target = null

func _physics_process(_delta:float) -> void:
    if target != null:
        velocity = global_position.direction_to(target) * speed
    else:
        # call get_input or whatever
        pass

    velocity = move_and_slide(velocity)
</code>```

I'll add a method for this, it will make things easier:

```<code>export var speed:float
var velocity := Vector2.ZERO
var target = null

func _physics_process(_delta:float) -> void:
    if not advance_to_target():
        # call get_input or whatever
        pass

    velocity = move_and_slide(velocity)

func advance_to_target() -> bool:
    if target == null:
        return false

    velocity = global_position.direction_to(target) * speed
    return true
</code>```

Well, we should clear target when we reach it, and we should not overshoot. Let us fix that:

```<code>export var speed:float
var velocity := Vector2.ZERO
var target = null

func _physics_process(_delta:float) -> void:
    if not advance_to_target():
        target = null
        # call get_input or whatever

    velocity = move_and_slide(velocity)

func advance_to_target() -> bool:
    if target == null:
        return false

    var displacement := target - global_position
    var distance := displacement.length()
    if is_zero_approx(distance):
        return false

    var time := get_physics_process_delta_time()
    var max_speed := distance / time
    var direction := displacement / distance
    velocity = direction * min(speed, max_speed)
    return true
</code>```

Here we are computing max_speed, which is the speed at which the KinematicBody2D would have to move to reach the target in the current physics frame. Any faster than that, and it would overshoot. So we use min(speed, max_speed) to make sure the actual speed is capped at that.

And when the target is reached we would have found that the distance is zero. Well, almost zero. Because of rounding errors we cannot rely on it hitting zero exactly. That is why I use is_zero_approx(distance). This also avoids a division by zero at displacement / distance.

For the enemy we can co-opt this system to chase the collider… Let us refactor to make that easier:

```<code>export var speed:float
var velocity := Vector2.ZERO
var target = null

var collider = null

func _physics_process(_delta:float) -> void:
    var target_position = null
    if target != null:
        target_position = target
    elif collider != null:
        target_position = collider.global_position

    if not advance_to(target_position):
        target = null

    velocity = move_and_slide(velocity)

func advance_to(target_position) -> bool:
    if target_position == null:
        return false

    var displacement := position - global_position
    var distance := displacement.length()
    if is_zero_approx(distance):
        return false

    var time := get_physics_process_delta_time()
    var max_speed := distance / time
    var direction := displacement / distance
    velocity = direction * min(speed, max_speed)
    return true
</code>```

Or we can add get_input into it:

```<code>export var speed:float
var velocity := Vector2.ZERO
var target = null

func _physics_process(_delta:float) -> void:
    if not advance_to(target):
        target = null
        get_input()

    velocity = move_and_slide(velocity)

func advance_to(target_position) -> bool:
    if target_position == null:
        return false

    var displacement := position - global_position
    var distance := displacement.length()
    if is_zero_approx(distance):
        return false

    var time := get_physics_process_delta_time()
    var max_speed := distance / time
    var direction := displacement / distance
    velocity = direction * min(speed, max_speed)
    return true

func get_input():
    velocity = Vector2.ZERO
    if Input.is_action_pressed('right'):
        velocity.x += 1
    if Input.is_action_pressed('left'):
        velocity.x -= 1
    if Input.is_action_pressed('down'):
        velocity.y += 1
    if Input.is_action_pressed('up'):
        velocity.y -= 1
    if Input.is_action_just_pressed("sprint"):
        speed += 100
    if Input.is_action_just_released("sprint"):
        speed -= 100

    # Make sure diagonal movement isn't faster
    velocity = velocity.normalized() * speed
</code>```

Ah, yes, the damage. We are going to set a target when we register the collision. Something like this:

```<code>export var push_back_distance:float

func _on_hit_box_body_entered(body):
    var direction := global_position.direction_to(body.global_position)
    target = global_position - direction * push_back_distance
    # the rest of the code here
</code>```

That should make the KinematicBody2D move away from whatever it collided with.

Body:
In my game I want it so when either the player or the enemy gets damaged they bounce but i do not know how to do so.

code for player:

extends KinematicBody2D

var speed = 200  # speed in pixels/sec
var velocity = Vector2.ZERO
var hasDagger = false

func get_input():
    velocity = Vector2.ZERO
    if Input.is_action_pressed('right'):
        velocity.x += 1
    if Input.is_action_pressed('left'):
        velocity.x -= 1
    if Input.is_action_pressed('down'):
        velocity.y += 1
    if Input.is_action_pressed('up'):
        velocity.y -= 1
    if Input.is_action_just_pressed("sprint"):
        speed += 100
    if Input.is_action_just_released("sprint"):
        speed -= 100

    # Make sure diagonal movement isn't faster
    velocity = velocity.normalized() * speed

func _physics_process(delta):
    get_input()
    velocity = move_and_slide(velocity)

enemy code:

extends KinematicBody2D

var run_speed = 201
var velocity = Vector2.ZERO
var collider = null
var health = 3

func _physics_process(delta):
    velocity = Vector2.ZERO
    if collider:
        #print(collider)
        velocity = global_position.direction_to(collider.global_position) * run_speed
    velocity = move_and_slide(velocity)

func _on_DetectRadius_body_entered(body):
    collider = body

func _on_DetectRadius_body_exited(body):
    collider = null

func _on_hit_box_body_entered(body):
    health -= 1

    if health == 0:
        get_tree().change_scene("res://scenes/game over.tscn")

the health you see in the enemy script is for the player

the player is a kinematicbody2D with a colilistionshape2D and the enemy is the same as that

Body:
What I'm going to show is not the only way to go about this - In fact, we should be talking about animations and states - instead it is just one way to tackle this.

I'll define a variable target. I'll leave it without specifying a type, so it is variant. However, I'll have it be Vector2. The reason I leave it variant, is so it can be null. If I could, I'd type it as a nullable Vector2, but Godot does not support that.

The idea is to have the KinematicBody2D go to the target position if it is a Vector2. But if it isn't, let the regular movement continue. Something like this:

export var speed:float
var velocity := Vector2.ZERO
var target = null

func _physics_process(_delta:float) -> void:
    if target != null:
        velocity = global_position.direction_to(target) * speed
    else:
        # call get_input or whatever
        pass

    velocity = move_and_slide(velocity)

I'll add a method for this, it will make things easier:

export var speed:float
var velocity := Vector2.ZERO
var target = null

func _physics_process(_delta:float) -> void:
    if not advance_to_target():
        # call get_input or whatever
        pass

    velocity = move_and_slide(velocity)

func advance_to_target() -> bool:
    if target == null:
        return false

    velocity = global_position.direction_to(target) * speed
    return true

Well, we should clear target when we reach it, and we should not overshoot. Let us fix that:

export var speed:float
var velocity := Vector2.ZERO
var target = null

func _physics_process(_delta:float) -> void:
    if not advance_to_target():
        target = null
        # call get_input or whatever

    velocity = move_and_slide(velocity)

func advance_to_target() -> bool:
    if target == null:
        return false

    var displacement := target - global_position
    var distance := displacement.length()
    if is_zero_approx(distance):
        return false

    var time := get_physics_process_delta_time()
    var max_speed := distance / time
    var direction := displacement / distance
    velocity = direction * min(speed, max_speed)
    return true

Here we are computing max_speed, which is the speed at which the KinematicBody2D would have to move to reach the target in the current physics frame. Any faster than that, and it would overshoot. So we use min(speed, max_speed) to make sure the actual speed is capped at that.

And when the target is reached we would have found that the distance is zero. Well, almost zero. Because of rounding errors we cannot rely on it hitting zero exactly. That is why I use is_zero_approx(distance). This also avoids a division by zero at displacement / distance.

For the enemy we can co-opt this system to chase the collider… Let us refactor to make that easier:

export var speed:float
var velocity := Vector2.ZERO
var target = null

var collider = null

func _physics_process(_delta:float) -> void:
    var target_position = null
    if target != null:
        target_position = target
    elif collider != null:
        target_position = collider.global_position

    if not advance_to(target_position):
        target = null

    velocity = move_and_slide(velocity)

func advance_to(target_position) -> bool:
    if target_position == null:
        return false

    var displacement := position - global_position
    var distance := displacement.length()
    if is_zero_approx(distance):
        return false

    var time := get_physics_process_delta_time()
    var max_speed := distance / time
    var direction := displacement / distance
    velocity = direction * min(speed, max_speed)
    return true

Or we can add get_input into it:

export var speed:float
var velocity := Vector2.ZERO
var target = null

func _physics_process(_delta:float) -> void:
    if not advance_to(target):
        target = null
        get_input()

    velocity = move_and_slide(velocity)

func advance_to(target_position) -> bool:
    if target_position == null:
        return false

    var displacement := position - global_position
    var distance := displacement.length()
    if is_zero_approx(distance):
        return false

    var time := get_physics_process_delta_time()
    var max_speed := distance / time
    var direction := displacement / distance
    velocity = direction * min(speed, max_speed)
    return true

func get_input():
    velocity = Vector2.ZERO
    if Input.is_action_pressed('right'):
        velocity.x += 1
    if Input.is_action_pressed('left'):
        velocity.x -= 1
    if Input.is_action_pressed('down'):
        velocity.y += 1
    if Input.is_action_pressed('up'):
        velocity.y -= 1
    if Input.is_action_just_pressed("sprint"):
        speed += 100
    if Input.is_action_just_released("sprint"):
        speed -= 100

    # Make sure diagonal movement isn't faster
    velocity = velocity.normalized() * speed

Ah, yes, the damage. We are going to set a target when we register the collision. Something like this:

export var push_back_distance:float

func _on_hit_box_body_entered(body):
    var direction := global_position.direction_to(body.global_position)
    target = global_position - direction * push_back_distance
    # the rest of the code here

That should make the KinematicBody2D move away from whatever it collided with.


问:
Django: email sender is the same as the recipient sender , How i can resolve that
I have developed a form contact where the user can contact us he will type his email, the subject and the message, But am stuck on after some tries I didn't succeed to reach my goal , everything is good the email is send to the email recipient that i have mentioned in settings.py

```<code>EMAIL_HOST_USER
</code>```

But the email sender is registered as the email recipient i do no why ,Here is the code:

```<code>def contact_view(request):
    if request.method == 'GET':
        form = ContactForm()
    else:
        form = ContactForm(request.POST)
        if form.is_valid():
            subject = form.cleaned_data['subject']
            from_email = form.cleaned_data['email']
            message = form.cleaned_data['message']
            try:
                send_mail(subject, message, from_email, [settings.EMAIL_HOST_USER])
            except BadHeaderError:
                return HttpResponse('Invalid header found.')
        return render(request, 'pages/success.html')
    return render(request, 'pages/contact.html', {'form': form})
</code>```

How i can resolve that i don't want the sender email be the recipient email , i want it to be the email that user will entered during fill out the form.

答:
Funtion send_email accepts arguments: subject, message, from_email, [to]. You are basically sending mail from and to your EMAIL_HOST_USER, because practically from_email does not matter this much (it might change name, but definitely not e-mail address itself). Backend is taken from EMAIL_HOST_USER and it's password, port etc.

Think about that on this way:

Should it be really that easy to send e-mail as any address?

Body:
I have developed a form contact where the user can contact us he will type his email, the subject and the message, But am stuck on after some tries I didn't succeed to reach my goal , everything is good the email is send to the email recipient that i have mentioned in settings.py

EMAIL_HOST_USER

But the email sender is registered as the email recipient i do no why ,Here is the code:

def contact_view(request):
    if request.method == 'GET':
        form = ContactForm()
    else:
        form = ContactForm(request.POST)
        if form.is_valid():
            subject = form.cleaned_data['subject']
            from_email = form.cleaned_data['email']
            message = form.cleaned_data['message']
            try:
                send_mail(subject, message, from_email, [settings.EMAIL_HOST_USER])
            except BadHeaderError:
                return HttpResponse('Invalid header found.')
        return render(request, 'pages/success.html')
    return render(request, 'pages/contact.html', {'form': form})

How i can resolve that i don't want the sender email be the recipient email , i want it to be the email that user will entered during fill out the form.


答:
If you're dedicated to storing this sort of thing in a file, then probably the easiest way is to just store all the data in an array in the form of $keyword => $value then use the serialize() and unserialize() functions to transform them into a format that can be easily stored into and read from a file.

Keep in mind that if there is only one file, then a change made by one user will affect them all, so if that's not acceptable, then you'll need to come up with a way to determine the user and which file to use.

A much better way of doing this is to just store these values in a database. Create a table called options with two fields - option and value - which will store the configuration options. If you want different users to have their own options, then you could add another field - userid (as a foreign key to a users table) - to track which user an option pair applies to.

Further, if there are a predefined set of options a user can set, then you could have fields in the table for each option, with default values, and you can create a row for each user with the specific config options set in a single record for that user.

Title: Writing and editing a PHP config file from a HTML form?


问:
× TypeError: Cannot read properties of undefined (reading 'name') react js
i am not able to display country name,image and rating can anyone explain me why this is happening [https://api.tvmaze.com/search/shows?q=avengers] it is the API link.all other data are displaying but these 3 are not working and throwing error.</p>
```<code>import React, {useState, useEffect} from 'react'
import ReactDOM from 'react-dom'
import axios from 'axios'

const App = () => {
  const url = 'https://api.tvmaze.com/search/shows?q=avengers'

  const [data, setData] = useState([])

  useEffect(() => {
    axios.get(url).then((json) => setData(json.data))
  }, [])

  const renderTable = () => {
    return data.map((user) => {
      return (
        <tr>
          <td>{user.show.name}</td>
          <td>{user.show.language}</td>
          <td>{user.show.genres}</td>
          <td>{user.show.runtime}</td>
          <td>{user.show.premiered}</td>
          <td>{user.show.rating}</td>
          <td>{user.show.country.name}</td>
          <td>{user.image.medium}</td>

        </tr>
      )
    })
  }

  return (
    <div>
      <h1 id="title">API Table</h1>
      <table id="users">
        <thead>
          <tr>
            <th>Name</th>
            <th>language</th>
            <th>genres</th>
            <th>runtime</th>
            <th>premiered</th>
            <th>Rating</th>
            <th>country name</th>
            <th>image</th>

          </tr>
        </thead>
        <tbody>{renderTable()}</tbody>
      </table>
    </div>
  )
}
export default App
</code>```

答:
There are few errors in your code:

You should use optional chaining when destructuring nested values

You should add a key for every item returned through map

You are destructuring rating incorrectly. It should be user?.show?.rating?.average instead of user.show.rating which is an object.

Update code:

```<code>import React, { useState, useEffect } from "react";
import axios from "axios";

const App = () => {
  const url = "https://api.tvmaze.com/search/shows?q=avengers";

  const [data, setData] = useState([]);

  useEffect(() => {
    axios.get(url).then((json) => setData(json.data));
  }, []);

  const renderTable = () => {
    return data.map((user, i) => {
     return (
     <tr key={i}>
      <td>{user.show?.name}</td>
      <td>{user.show?.language}</td>
      <td>{user.show?.genres}</td>
      <td>{user.show?.runtime}</td>
      <td>{user.show?.premiered}</td>
      <td>{user.show?.rating?.average}</td>
      <td>{user.show?.network?.country?.name}</td>
      <td>
        <img src={user?.show?.image?.medium} alt="poster" />
      </td>
    </tr>
      );
    });
  };

  return (
    <div>
      <h1 id="title">API Table</h1>
      <table id="users">
        <thead>
          <tr>
            <th>Name</th>
            <th>language</th>
            <th>genres</th>
            <th>runtime</th>
            <th>premiered</th>
            <th>Rating</th>
            <th>country name</th>
            <th>image</th>
          </tr>
        </thead>
        <tbody>{renderTable()}</tbody>
      </table>
    </div>
  );
};
export default App;
</code>```

Body:
i am not able to display country name,image and rating can anyone explain me why this is happening [https://api.tvmaze.com/search/shows?q=avengers] it is the API link.all other data are displaying but these 3 are not working and throwing error.

import React, {useState, useEffect} from 'react'
import ReactDOM from 'react-dom'
import axios from 'axios'

const App = () => {
  const url = 'https://api.tvmaze.com/search/shows?q=avengers'

  const [data, setData] = useState([])

  useEffect(() => {
    axios.get(url).then((json) => setData(json.data))
  }, [])

  const renderTable = () => {
    return data.map((user) => {
      return (

          {user.show.name}
          {user.show.language}
          {user.show.genres}
          {user.show.runtime}
          {user.show.premiered}
          {user.show.rating}
          {user.show.country.name}
          {user.image.medium}

      )
    })
  }

  return (

API Table

            Name
            language
            genres
            runtime
            premiered
            Rating
            country name
            image

{renderTable()}

  )
}
export default App

Body:
There are few errors in your code:

You should use optional chaining when destructuring nested values

You should add a key for every item returned through map

You are destructuring rating incorrectly. It should be user?.show?.rating?.average instead of user.show.rating which is an object.

Update code:

import React, { useState, useEffect } from "react";
import axios from "axios";

const App = () => {
  const url = "https://api.tvmaze.com/search/shows?q=avengers";

  const [data, setData] = useState([]);

  useEffect(() => {
    axios.get(url).then((json) => setData(json.data));
  }, []);

  const renderTable = () => {
    return data.map((user, i) => {
     return (
     <tr key={i}>
      <td>{user.show?.name}</td>
      <td>{user.show?.language}</td>
      <td>{user.show?.genres}</td>
      <td>{user.show?.runtime}</td>
      <td>{user.show?.premiered}</td>
      <td>{user.show?.rating?.average}</td>
      <td>{user.show?.network?.country?.name}</td>
      <td>
        <img src={user?.show?.image?.medium} alt="poster" />
      </td>
    </tr>
      );
    });
  };

  return (
    <div>
      <h1 id="title">API Table</h1>
      <table id="users">
        <thead>
          <tr>
            <th>Name</th>
            <th>language</th>
            <th>genres</th>
            <th>runtime</th>
            <th>premiered</th>
            <th>Rating</th>
            <th>country name</th>
            <th>image</th>
          </tr>
        </thead>
        <tbody>{renderTable()}</tbody>
      </table>
    </div>
  );
};
export default App;


问:
How to display data values on Chart.js
Is it possible using Chart.js to display data values?

I want to print the graph.

Thanks for any advice..

答:
Adapted the @Ross answer to work with 3.7.0 version of the Chartjs

```<code>animation: {
        duration: 0,
        onComplete: function() {
            ctx = this.ctx;
            ctx.font = Chart.helpers.fontString(Chart.defaults.font.size, Chart.defaults.font.style, Chart.defaults.font.family);
            ctx.textAlign = 'center';
            ctx.textBaseline = 'bottom';
            chartinst = this;
            this.data.datasets.forEach(function(dataset, i) {
                if(chartinst.isDatasetVisible(i)){
                    var meta = chartinst.getDatasetMeta(i);
                    meta.data.forEach(function(bar, index) {
                        var data = dataset.data[index];
                        ctx.fillText(data, bar.x, bar.y - 5);
                    });
                }
            });
        }
    }
</code>```

In this case, animation can be 0
To have a nicer looking, you can disable the hover and the tooltip if you want a more "static" visualization

Also, the isDataSetVisible works to get rid of the numbers that stay shown when you hide the dataset in case of multiple datasets

Title: How to display data values on Chart.js

Body:
Adapted the @Ross answer to work with 3.7.0 version of the Chartjs

animation: {
        duration: 0,
        onComplete: function() {
            ctx = this.ctx;
            ctx.font = Chart.helpers.fontString(Chart.defaults.font.size, Chart.defaults.font.style, Chart.defaults.font.family);
            ctx.textAlign = 'center';
            ctx.textBaseline = 'bottom';
            chartinst = this;
            this.data.datasets.forEach(function(dataset, i) {
                if(chartinst.isDatasetVisible(i)){
                    var meta = chartinst.getDatasetMeta(i);
                    meta.data.forEach(function(bar, index) {
                        var data = dataset.data[index];
                        ctx.fillText(data, bar.x, bar.y - 5);
                    });
                }
            });
        }
    }

In this case, animation can be 0
To have a nicer looking, you can disable the hover and the tooltip if you want a more "static" visualization

Also, the isDataSetVisible works to get rid of the numbers that stay shown when you hide the dataset in case of multiple datasets


问:
Sorting a vector of objects in C++
say I have a class "Information" and it stores the Name and Age of people in a vector.

so...

```<code>class Information {

private:
int age;
string name;

//etc, etc...
};
</code>```

How would I sort the vector in either ascending/descending order with respect to age?

I believe you use something like this.

```<code>sort(listOfPeople.begin(), listOfPeople.end(), greater<Information>());
</code>```

listOfPeople would be the vector.

Any help would be greatly appreciated.

答:
If you want to sort them in non-descending order by age, one way to do it is to define a functor for comparison:

```<code>class CompareInformations {
    public:
    // after making CompareInformations a friend class to Information...
    operator(const Information& rhs, const Information& lhs) {
        return rhs.age < lhs.age;
    }
};
</code>```

And then do your sort:

```<code>sort(listOfPeople.begin(), listOfPeople.end(), CompareInformations());
</code>```

You could also overload operator< for your class, and do without the comparison object:

```<code>// inside your class
bool operator <(const Information& rhs) {
    return age < rhs.age;
}
</code>```

Then sort it:

```<code>sort(listOfPeople.begin(), listOfPeople.end());
</code>```

The above examples assume you want to sort in non-descending (almost ascending, but not quite) order. To do non-ascending order, just change all occurrences of < to >.

Title: Sorting a vector of objects in C++

Body:
say I have a class "Information" and it stores the Name and Age of people in a vector.

so...

class Information {

private:
int age;
string name;

//etc, etc...
};

How would I sort the vector in either ascending/descending order with respect to age?

I believe you use something like this.

sort(listOfPeople.begin(), listOfPeople.end(), greater<Information>());

listOfPeople would be the vector.

Any help would be greatly appreciated.

Body:
If you want to sort them in non-descending order by age, one way to do it is to define a functor for comparison:

class CompareInformations {
    public:
    // after making CompareInformations a friend class to Information...
    operator(const Information& rhs, const Information& lhs) {
        return rhs.age < lhs.age;
    }
};

And then do your sort:

sort(listOfPeople.begin(), listOfPeople.end(), CompareInformations());

You could also overload operator< for your class, and do without the comparison object:

// inside your class
bool operator <(const Information& rhs) {
    return age < rhs.age;
}

Then sort it:

sort(listOfPeople.begin(), listOfPeople.end());

The above examples assume you want to sort in non-descending (almost ascending, but not quite) order. To do non-ascending order, just change all occurrences of < to >.