问:
Created at timestamp is null when retrieve
I am saving data using sensor where data is coming like this

```<code>$input = $request["date"].' '.$request["time"];

        $newDate= DateTime::createFromFormat('d/m/Y H:i:s',$input);
$created_date = $newDate->format('Y-m-d H:i:s'); // for example
    try{

           $SensorData = SensorData::create([
            'sensor_id' => $request['sensor']['id'],
            'created_at' => "".$created_date."",

        ]);

$sensor_data=SensorData::join('sensors','sensors.id','=','sensor_id')->orderBy('sensor_data.created_at','DESC')->get();
</code>```

its saving datetime in database as 2020-05-04 01:10:12 but when retrieve value it shows null

答:
Using DB clause has solved the problem

```<code>$sensor_data = DB::table('sensors')
            ->join('sensor_data', 'sensors.id', '=', 'sensor_data.sensor_id')
            ->get();
</code>```

Body:
I am saving data using sensor where data is coming like this

$input = $request["date"].' '.$request["time"];

        $newDate= DateTime::createFromFormat('d/m/Y H:i:s',$input);
$created_date = $newDate->format('Y-m-d H:i:s'); // for example
    try{

           $SensorData = SensorData::create([
            'sensor_id' => $request['sensor']['id'],
            'created_at' => "".$created_date."",

        ]);

$sensor_data=SensorData::join('sensors','sensors.id','=','sensor_id')->orderBy('sensor_data.created_at','DESC')->get();

its saving datetime in database as 2020-05-04 01:10:12 but when retrieve value it shows null

Body:
Using DB clause has solved the problem

$sensor_data = DB::table('sensors')
            ->join('sensor_data', 'sensors.id', '=', 'sensor_data.sensor_id')
            ->get();


来源: stackexchange

问:
How to use a sass $ declaration in useEffect (jsx?)
I have different styles set in a _variables.scss file. like

```<code>$secondary: #ffc500;
$tertiary: #ffdd69;
$quartiary: #fffbed;
</code>```

I want to use different body colors so I want to change the body background in different pages like so:

```<code>        document.body.style.backgroundColor = "red"  });
</code>```

this works nicely but now i want to use for example $primary instead of 'red'
I just can't make it work. does anybody have an idea?

答:
You can use the sass :export keyword to pass variables from sass files to js files:

```<code>// colors.scss
$primary: #123456;
:export {
  primary: $primary;
}
</code>```

```<code>// main.js
import colors from './colors.scss'

colors.primary; // '#123456'
</code>```

As far as I know this is a non-standard keyword, it is handled by webpack + sass-loader, but not all sass transpilers.

ContentLicense: CC BY-SA 4.0

Body:
I have different styles set in a _variables.scss file. like

$secondary: #ffc500;
$tertiary: #ffdd69;
$quartiary: #fffbed;

I want to use different body colors so I want to change the body background in different pages like so:

        document.body.style.backgroundColor = "red"  });

this works nicely but now i want to use for example $primary instead of 'red'
I just can't make it work. does anybody have an idea?

Body:
You can use the sass :export keyword to pass variables from sass files to js files:

// colors.scss
$primary: #123456;
:export {
  primary: $primary;
}

// main.js
import colors from './colors.scss'

colors.primary; // '#123456'

As far as I know this is a non-standard keyword, it is handled by webpack + sass-loader, but not all sass transpilers.


问:
How to find the support vectors for SVM?
I'm using the liblinear library to train a linear SVM on my data. I have access to the weights for each class of the trained model. But I need to figure out which training instances are acting as support vectors.

The liblinear library doesn't seem to provide these vectors as a model attribute. And I can't seem to figure out how I can find them manually. If I have the training data and I have the weights that define the hyperplane, how would I go about finding these support vectors?

答:
You can get the support vectors using clf.support_vectors_.

Plotting the support vectors:

```<code>import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm

# we create 40 separable points
np.random.seed(0)
X = np.r_[np.random.randn(20, 2) - [2, 2], np.random.randn(20, 2) + [2, 2]]
Y = [0] * 20 + [1] * 20

# fit the model
clf = svm.SVC(kernel='linear', C=1)
clf.fit(X, Y)

# get the separating hyperplane
w = clf.coef_[0]
a = -w[0] / w[1]
xx = np.linspace(-5, 5)
yy = a * xx - (clf.intercept_[0]) / w[1]

margin = 1 / np.sqrt(np.sum(clf.coef_ ** 2))
yy_down = yy - np.sqrt(1 + a ** 2) * margin
yy_up = yy + np.sqrt(1 + a ** 2) * margin

plt.figure(1, figsize=(4, 3))
plt.clf()
plt.plot(xx, yy, 'k-')
plt.plot(xx, yy_down, 'k--')
plt.plot(xx, yy_up, 'k--')

plt.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s=80,
            facecolors='none', zorder=10, edgecolors='k')
plt.scatter(X[:, 0], X[:, 1], c=Y, zorder=10, cmap=plt.cm.Paired,
            edgecolors='k')

plt.axis('tight')
x_min = -4.8
x_max = 4.2
y_min = -6
y_max = 6

XX, YY = np.mgrid[x_min:x_max:200j, y_min:y_max:200j]
Z = clf.predict(np.c_[XX.ravel(), YY.ravel()])

# Put the result into a color plot
Z = Z.reshape(XX.shape)
plt.figure(1, figsize=(4, 3))
plt.pcolormesh(XX, YY, Z, cmap=plt.cm.Paired)

plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)

plt.xticks(())
plt.yticks(())

plt.show()
</code>```

Body:
You can get the support vectors using clf.support_vectors_.

Plotting the support vectors:

import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm

# we create 40 separable points
np.random.seed(0)
X = np.r_[np.random.randn(20, 2) - [2, 2], np.random.randn(20, 2) + [2, 2]]
Y = [0] * 20 + [1] * 20

# fit the model
clf = svm.SVC(kernel='linear', C=1)
clf.fit(X, Y)

# get the separating hyperplane
w = clf.coef_[0]
a = -w[0] / w[1]
xx = np.linspace(-5, 5)
yy = a * xx - (clf.intercept_[0]) / w[1]

margin = 1 / np.sqrt(np.sum(clf.coef_ ** 2))
yy_down = yy - np.sqrt(1 + a ** 2) * margin
yy_up = yy + np.sqrt(1 + a ** 2) * margin

plt.figure(1, figsize=(4, 3))
plt.clf()
plt.plot(xx, yy, 'k-')
plt.plot(xx, yy_down, 'k--')
plt.plot(xx, yy_up, 'k--')

plt.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s=80,
            facecolors='none', zorder=10, edgecolors='k')
plt.scatter(X[:, 0], X[:, 1], c=Y, zorder=10, cmap=plt.cm.Paired,
            edgecolors='k')

plt.axis('tight')
x_min = -4.8
x_max = 4.2
y_min = -6
y_max = 6

XX, YY = np.mgrid[x_min:x_max:200j, y_min:y_max:200j]
Z = clf.predict(np.c_[XX.ravel(), YY.ravel()])

# Put the result into a color plot
Z = Z.reshape(XX.shape)
plt.figure(1, figsize=(4, 3))
plt.pcolormesh(XX, YY, Z, cmap=plt.cm.Paired)

plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)

plt.xticks(())
plt.yticks(())

plt.show()


问:
can sqlite UPDATE staments be processed line-by-line to help solve "sqlite calculate columns based on columns"
I have a table which includes large number of calculated columns based on other calculated columns. So there are:

x, f(x),g(f(x)),h(g(x)... and so on. Each function uses a large number of fields, so that writing out the formulas from first principles is tedious and error-prone.

I am aware of this solution using sub-queries. However, this becomes increasingly impractical as columns become calculated based on other calculated columns which themselves are calculated.  You would need a subquery for every level of calculation. For wide tables like mine, this would be prone to error.

I thought of a different solution, which is firstly to fill the calculated columns with dummy numbers, and then use UPDATE to calculate columns in the sequence desired.

Here is a MWE (not the real thing):

```<code>create table a (x ,y,z);
insert into  a(x,y,z)
    values (1,1,1),(2,1,1);
update a
    set y = x,
    z = 7 * y;
select * from a;
</code>```

Currently this doesn't work, and the calculation for z uses the un-refreshed value of y.

To solve this, I have to separate the update statements

```<code>update a
    set y = 3 * x;
update a
    set z = 7 * y;
</code>```

My question: is there any way to tell SQLITE to complete the calculations for the first line in the UPDATE statement, and then proceeed, so I can bundle all my calculations under one UPDATE statement?

答:
The only database I know that uses the changed values of columns in expressions in an UPDATE statement is MySql.

The standard behavior is to use the stored values.

In your case there is an easy solution.

The new value for y is 3 * x so instead of:

```<code>z = 7 * y
</code>```

use:

```<code>z = 7 * (3 * x)
</code>```

or

```<code>z = 21 * x
</code>```

and your statement will be:

```<code>update a
set y = 3 * x,
    z = 21 * x;
</code>```

See the demo.

Results:

```<code>| x   | y   | z   |
| --- | --- | --- |
| 1   | 3   | 21  |
| 2   | 6   | 42  |
</code>```

Body:
I have a table which includes large number of calculated columns based on other calculated columns. So there are:

x, f(x),g(f(x)),h(g(x)... and so on. Each function uses a large number of fields, so that writing out the formulas from first principles is tedious and error-prone.

I am aware of this solution using sub-queries. However, this becomes increasingly impractical as columns become calculated based on other calculated columns which themselves are calculated.  You would need a subquery for every level of calculation. For wide tables like mine, this would be prone to error.

I thought of a different solution, which is firstly to fill the calculated columns with dummy numbers, and then use UPDATE to calculate columns in the sequence desired.

Here is a MWE (not the real thing):

create table a (x ,y,z);
insert into  a(x,y,z)
    values (1,1,1),(2,1,1);
update a
    set y = x,
    z = 7 * y;
select * from a;

Currently this doesn't work, and the calculation for z uses the un-refreshed value of y.

To solve this, I have to separate the update statements

update a
    set y = 3 * x;
update a
    set z = 7 * y;

My question: is there any way to tell SQLITE to complete the calculations for the first line in the UPDATE statement, and then proceeed, so I can bundle all my calculations under one UPDATE statement?

Body:
The only database I know that uses the changed values of columns in expressions in an UPDATE statement is MySql.

The standard behavior is to use the stored values.

In your case there is an easy solution.

The new value for y is 3 * x so instead of:

z = 7 * y

use:

z = 7 * (3 * x)

or

z = 21 * x

and your statement will be:

update a
set y = 3 * x,
    z = 21 * x;

See the demo.

Results:

| x   | y   | z   |
| --- | --- | --- |
| 1   | 3   | 21  |
| 2   | 6   | 42  |


问:
Azure AD B2C with React Native Expo
I am new to mobile app development with react-native and expo. I'm trying to add authentication/authorization in my mobile app with Azure AD B2C but I find it more difficult to understand from Microsoft docs and even I couldn't find any clear directions on Google. Could anyone with this experience please guide me in right direction. Any help would be appreciated.</p>

答:
We have faced the same issue in Ionic native.

we have used the capacitor oauth2 library which helped us to achieve the login using Azure AD b2c in ionic native.

For react native, you can try this https://github.com/GSingh01/ad-b2c-react-native

Also, you can customize UI for the user flows with the help of Microsoft docs

Title: Azure AD B2C with React Native Expo


问:
php - how to increment a user's known earning every day for 4 months
I want to display  to a user an amount per day and increment it until the next 124 days assumed to be four months.

I have a system where a user invest and a total ernable profit is calculated with the percentage ROI for such stock. Assuming someone invested in a stockA that has 20% ROI and matures in 4 months; assuming a user purchased that stockA that is sold $100 and he bought 4 units meaning he spent $400 and will earn
as follows:

```<code>$units = 4;
$cost = 100;
$roi = 20/100;
$total_invested = $units * $cost;

$profit  = $total_invest *  $roi;
// $profit will be $80
</code>```

My problem is I want to display value of $profit/124 that is the displaying a fraction of total earning to the user daily until maturity of 4 months. I can't figure out how to do that daily not just with loop of 124 iterations.

that is if the user total earning is $80/124 giving 0.65 on the first day and increment it with same value the next day until it reached the end date which is 4 months from now

/**
 *
 * display and increment earning every day for 4 months or 124 days
 *
 */

function display_earning() {
  $profit = $profit_roi;
  $dateBegin = now();
  $dateEnd = "date of 4 month from now";
  $earning = 0;

  for ($i = 0; $i < 124; $i++) {
    $earning += $profit / 124;
    return $earning;
  }
}
```

答:
It's not clear what you want your code to do. Do you want it to give the total earned cumulatively by day x or give the total earned on any one day? If it is any one day and you don't want to take compound interest into account the earning will be the same every single day. In which case all your function has to do is return

```<code>function return_earnings($profit, $totalDays) {
  return $profit / $totalDays;
}
</code>```

as the amount earned each day will be the same as any other day. If you do want compound interest then you'll need to code that it. I assume you don't as there is no sign of it in the code you supplied.

I get the feeling what you are looking for instead is a list of how much was earned each day cumulatively. If that's the case, the code you've written is more appropriate but needs some modification. At the moment your code is returning $earning after the first iteration of the loop. Moving return to the end of the function should fix that.

```<code>function display_earning() {
  $profit = $profit_roi;
  $dateBegin = now();
  $dateEnd = "date of 4 month from now";
  $earning = 0;
  $totalDays = 124; // You might want to change '124' in future
                    // and having $totalDays in the for loop makes it more
                    // obvious what your code is trying to do.

  for ($i = 0; $i < $totalDays; $i++) {
    $earning += $profit / $totalDays;
  }
  return $earning;
}
</code>```

However now because of the line $earning += you will return the sum of earning at the end of $totalDays, ie the $profit, which you already know! You may want the cumulative earnings by a given day to be an item in an array, in which case:

```<code>function display_earning() {
  $profit = $profit_roi;
  $dateBegin = now();
  $dateEnd = "date of 4 month from now";
  $totalEarning = 0; //renamed to $totalEarning
  $earningsByDay = array();
  $totalDays = 124;

  for ($i = 0; $i < $totalDays; $i++) {
    $totalEarning += $profit / $totalDays;
    $earningsByDay[$i] = $totalEarning;
  }
  return $earningsByDay;
}
</code>```

This will now return an array with each element of the array amounting to the sum earned by that day. For example, $earningsByDay[0] will be the first day, $earningsByDay[11] will be the 10th day etc. If this is what you are looking for, you can use php's native range() function to make your life easier:

```<code>function display_earning() {
  $profit = $profit_roi;
  $dateBegin = now();
  $dateEnd = "date of 4 month from now";
  $totalEarning = 0; //renamed to $totalEarning
  $earningsByDay = array();
  $totalDays = 124;

  return range(0, $profit, $profit/$totalDays)
}
</code>```

A few final thoughts:

You say you want to display the amount earned each day. You function does not display anything it just calculates a value and returns it. That's good practise. Have your functions do one thing. Some other function can display the data from this one, or perhaps multiple functions can, each formatting it in a way that is appropriate for your current need. I can't help you with the display as I have no way of knowing what format you want. $dateEnd probably doesn't need to be in the function.
On a related note, another function name might lead to less confusion about what the function does.

I'm not sure what $dateBegin = now(); adds, unless as Moeez Saiyam suggests, you are trying to automate this somehow.

You've defined $profit = $profit_roi; without declaring what $profit_roi is in the scope of your function. I know it was in your introductory notes, but the function won't know that.

Is the function the right place to define $profit and $totalDays? They are probably passed to the function form elsewhere.

Combining these thoughts, this gives us:

```<code>function getIncrementalEarnings($profit, $totalDays) { //function renamed to clarify its purpose
  return range(0, $profit, $profit/$totalDays)
}
</code>```

Body:
I want to display  to a user an amount per day and increment it until the next 124 days assumed to be four months.

I have a system where a user invest and a total ernable profit is calculated with the percentage ROI for such stock. Assuming someone invested in a stockA that has 20% ROI and matures in 4 months; assuming a user purchased that stockA that is sold $100 and he bought 4 units meaning he spent $400 and will earn
as follows:

$units = 4;
$cost = 100;
$roi = 20/100;
$total_invested = $units * $cost;

$profit  = $total_invest *  $roi;
// $profit will be $80

My problem is I want to display value of $profit/124 that is the displaying a fraction of total earning to the user daily until maturity of 4 months. I can't figure out how to do that daily not just with loop of 124 iterations.

that is if the user total earning is $80/124 giving 0.65 on the first day and increment it with same value the next day until it reached the end date which is 4 months from now

/**
 *
 * display and increment earning every day for 4 months or 124 days
 *
 */

function display_earning() {
  $profit = $profit_roi;
  $dateBegin = now();
  $dateEnd = "date of 4 month from now";
  $earning = 0;

  for ($i = 0; $i < 124; $i++) {
    $earning += $profit / 124;
    return $earning;
  }
}

Body:
It's not clear what you want your code to do. Do you want it to give the total earned cumulatively by day x or give the total earned on any one day? If it is any one day and you don't want to take compound interest into account the earning will be the same every single day. In which case all your function has to do is return

function return_earnings($profit, $totalDays) {
  return $profit / $totalDays;
}

as the amount earned each day will be the same as any other day. If you do want compound interest then you'll need to code that it. I assume you don't as there is no sign of it in the code you supplied.

I get the feeling what you are looking for instead is a list of how much was earned each day cumulatively. If that's the case, the code you've written is more appropriate but needs some modification. At the moment your code is returning $earning after the first iteration of the loop. Moving return to the end of the function should fix that.

function display_earning() {
  $profit = $profit_roi;
  $dateBegin = now();
  $dateEnd = "date of 4 month from now";
  $earning = 0;
  $totalDays = 124; // You might want to change '124' in future
                    // and having $totalDays in the for loop makes it more
                    // obvious what your code is trying to do.

  for ($i = 0; $i < $totalDays; $i++) {
    $earning += $profit / $totalDays;
  }
  return $earning;
}

However now because of the line $earning += you will return the sum of earning at the end of $totalDays, ie the $profit, which you already know! You may want the cumulative earnings by a given day to be an item in an array, in which case:

function display_earning() {
  $profit = $profit_roi;
  $dateBegin = now();
  $dateEnd = "date of 4 month from now";
  $totalEarning = 0; //renamed to $totalEarning
  $earningsByDay = array();
  $totalDays = 124;

  for ($i = 0; $i < $totalDays; $i++) {
    $totalEarning += $profit / $totalDays;
    $earningsByDay[$i] = $totalEarning;
  }
  return $earningsByDay;
}

This will now return an array with each element of the array amounting to the sum earned by that day. For example, $earningsByDay[0] will be the first day, $earningsByDay[11] will be the 10th day etc. If this is what you are looking for, you can use php's native range() function to make your life easier:

function display_earning() {
  $profit = $profit_roi;
  $dateBegin = now();
  $dateEnd = "date of 4 month from now";
  $totalEarning = 0; //renamed to $totalEarning
  $earningsByDay = array();
  $totalDays = 124;

  return range(0, $profit, $profit/$totalDays)
}

A few final thoughts:

You say you want to display the amount earned each day. You function does not display anything it just calculates a value and returns it. That's good practise. Have your functions do one thing. Some other function can display the data from this one, or perhaps multiple functions can, each formatting it in a way that is appropriate for your current need. I can't help you with the display as I have no way of knowing what format you want. $dateEnd probably doesn't need to be in the function.
On a related note, another function name might lead to less confusion about what the function does.

I'm not sure what $dateBegin = now(); adds, unless as Moeez Saiyam suggests, you are trying to automate this somehow.

You've defined $profit = $profit_roi; without declaring what $profit_roi is in the scope of your function. I know it was in your introductory notes, but the function won't know that.

Is the function the right place to define $profit and $totalDays? They are probably passed to the function form elsewhere.

Combining these thoughts, this gives us:

function getIncrementalEarnings($profit, $totalDays) { //function renamed to clarify its purpose
  return range(0, $profit, $profit/$totalDays)
}


问:
AWS Cloudfront / S3 website redirection issue
We are using cloudfront for one of our website. So, to work with cloudfront we have setup s3 bucket and added all files in it. Then to use custom domain we have created a record set in Route53 and given cloudfront url. This everything is working fine.

However, we are facing redirection OR page refresh issue for our site. Let say if we are on some inner page 'https://www.example.com/my-page' and we refresh the page then page is not displayed and we are getting below error.

```<code><Error>
<Code>NoSuchKey</Code>
<Message>The specified key does not exist.</Message>
<Key>my-page</Key>
<RequestId><some-request-id></RequestId>
<HostId><some-host-id></HostId>
</Error>
</code>```

And this issue is occurring for all pages.

i have tried setting redirect url for s3 bucket; but it seems it always redirect to login page.

Any help on this appreciated !

答:
I'm assuming that you're using simple HTML. If you're using a framework like React or Angular then the problem might lie there rather than Cloudfront.

This can happen when the Cloudfront distribution is set up to point to the S3 bucket rather than the S3-as-website endpoint URL.

Go the the Cloudfront distribution and check the origin group. Your origin should look something like this BUCKET_NAME.s3-website-eu-west-1.amazonaws.com and NOT like this BUCKET_NAME.s3-eu-west-1.amazonaws.com.

This is an easy mistake to make as the option they give you when setting up the distribution - the bucket - is not actually the one you want. You need to copy the endpoint url from the S3 settings and paste it into the box.

Body:
We are using cloudfront for one of our website. So, to work with cloudfront we have setup s3 bucket and added all files in it. Then to use custom domain we have created a record set in Route53 and given cloudfront url. This everything is working fine.

However, we are facing redirection OR page refresh issue for our site. Let say if we are on some inner page 'https://www.example.com/my-page' and we refresh the page then page is not displayed and we are getting below error.

<Error>
NoSuchKey
<Message>The specified key does not exist.</Message>
<Key>my-page</Key>
<RequestId><some-request-id></RequestId>
<HostId><some-host-id></HostId>
</Error>

And this issue is occurring for all pages.

i have tried setting redirect url for s3 bucket; but it seems it always redirect to login page.

Any help on this appreciated !


问:
File execution error - No module named 'pywinauto'
I am trying to run the .exe file that I have created from my .py file using pyinstaller. The script was written in Spyder (Python 3.8). The python version on my computer is 3.8 as well. The pyisntaller command runs without any errors and creates .exe file in the dist folder. However, when I try to run the generated .exe file, nothing hapens (apart from the black screen coming up with some "light speed" dispayed error).

I have decided to run it in CMD, so I can see what error is being produced...here is the message I get upon execution of .exe file:

```<code>Traceback (most recent call last):
   File "myScript.py", line 8, in <module>
ModuleNotFoundError: No module named 'pywinauto'
[13024] Failed to execute script myScript
</code>```

The important thing to note, is that, while running the script directly from Spyder, it runs without any error.

I have tried installing pywinauto, using pip, but the error still persists.
Any idea would be much appreciated!

答:
Copy the following code as the first line of all your Python sources:

```<code> print('__file__={0:<35} | __name__={1:<20} | __package__={2:<20}'.format(__file__,__name__,str(__package__)))
</code>```

You have to make sure that for your main.py file:

```<code>__name__ is __main__ and __package__ must be None
</code>```

You have to make sure that for your packages files:

```<code>__name__ is the name of the file and __package__ must be the name of the package
</code>```

I fixed this issue reading this (Solution 1):

https://napuzba.com/a/import-error-relative-no-parent

Body:
I am trying to run the .exe file that I have created from my .py file using pyinstaller. The script was written in Spyder (Python 3.8). The python version on my computer is 3.8 as well. The pyisntaller command runs without any errors and creates .exe file in the dist folder. However, when I try to run the generated .exe file, nothing hapens (apart from the black screen coming up with some "light speed" dispayed error).

I have decided to run it in CMD, so I can see what error is being produced...here is the message I get upon execution of .exe file:

Traceback (most recent call last):
   File "myScript.py", line 8, in <module>
ModuleNotFoundError: No module named 'pywinauto'
[13024] Failed to execute script myScript

The important thing to note, is that, while running the script directly from Spyder, it runs without any error.

I have tried installing pywinauto, using pip, but the error still persists.
Any idea would be much appreciated!

Body:
Copy the following code as the first line of all your Python sources:

 print('__file__={0:<35} | __name__={1:<20} | __package__={2:<20}'.format(__file__,__name__,str(__package__)))

You have to make sure that for your main.py file:

__name__ is __main__ and __package__ must be None

You have to make sure that for your packages files:

__name__ is the name of the file and __package__ must be the name of the package

I fixed this issue reading this (Solution 1):

https://napuzba.com/a/import-error-relative-no-parent


问:
How to communicate between Fargate services on AWS ECS?
I have six docker containers all running in their own Tasks (6 tasks), and each task running in a separate Fargate service (6 services) on ECS.
I need the services to be able to communicate with each other, and some of them need to be publically accessible.
I keep seeing info about using either Service Discovery or a Load Balancer assigned to each service. I would like to try and avoid having to set up 6 load balancers as it's more expensive and more effort to maintain.

This is how I have set up Service Discovery currently:

All Tasks are setup to use awsvpc

All services have been set up to use Service Discovery (set up from within the Service Creation page)

All services are sharing the same Namespace, and they're all using the A DNS Record

When I try to ping <service_discovery_name>.<namespace> from within one of the docker containers I do not get a response. However, I can successfully ping another container when pinging the private IP Address.

Can I achieve what I need to do with Service Discovery?
If so, how exactly do the containers communicate with each other?

Thanks heaps! Please let me know if I haven't provided enough info.

EDIT: Recreating the services and setting them up with a new Service Discovery seemed to resolve the issue. No idea why the old discovery didn't work.

答: Based on the comments, the exact cause of the issue is undetermined. However, the problem was solved by creating a new Service Discovery in ECS.


问:
OptaPlanner - restricting matches to x amount
I'm rather new to OptaPlanner, and Java in general - but hopefully this makes sense.  What I'm trying to do is match, lets say, Client, to an Associate - what I'm looking to do is ensure that said Associate can only have X amount of clients assigned to them.  My domain is pretty simple right now, in that it is just the Associate and the ClientAssignment (which contains all of the client information) along with the planning solution/constraints to map them together.

Question:

How can I infer what has already been 'matched', to get a count?

答:
I'm going to assume that you're using the Constraint Streams API to implement your scoring function. If so, the following code should give you an idea of how to achieve what you need:

```<code>.from(ClientAssignment.class)
.groupBy(ClientAssignment::getAssociate,
    ConstraintCollectors.count())
.filter((associate, assignmentCount) -> assignmentCount > MAX_ALLOWED_CLIENT_COUNT)
.penalize("Overloaded associate",
    HardSoftScore.ONE_HARD,
    (associate, assignmentCount) -> assignmentCount - MAX_ALLOWED_CLIENT_COUNT)
</code>```

Obviously, I've made some assumptions about how your data model looks. Specifically, I've assumed that ClientAssignment is a unique pair of one Client and one Associate. If that assumption is not correct, please be more specific in your question and I'll edit my answer.

Also, you should replace HardSoftScore.ONE_HARD by whatever penalty you see applying to your problem, in whatever Score type that you need.

Body:
I'm going to assume that you're using the Constraint Streams API to implement your scoring function. If so, the following code should give you an idea of how to achieve what you need:

.from(ClientAssignment.class)
.groupBy(ClientAssignment::getAssociate,
    ConstraintCollectors.count())
.filter((associate, assignmentCount) -> assignmentCount > MAX_ALLOWED_CLIENT_COUNT)
.penalize("Overloaded associate",
    HardSoftScore.ONE_HARD,
    (associate, assignmentCount) -> assignmentCount - MAX_ALLOWED_CLIENT_COUNT)

Obviously, I've made some assumptions about how your data model looks. Specifically, I've assumed that ClientAssignment is a unique pair of one Client and one Associate. If that assumption is not correct, please be more specific in your question and I'll edit my answer.

Also, you should replace HardSoftScore.ONE_HARD by whatever penalty you see applying to your problem, in whatever Score type that you need.


问:
Hide all product's price for no logged users except for someone
I have hidden all product's price until the user isn't logged in. Now i want to show always the price of just someone of my products.

Can anyone help me with the code?

Here's my php code used in function.php :

```<code>    /**Hide price*/
add_filter('woocommerce_get_price_html','members_only_price_pages');
add_filter('woocommerce_cart_totals_order_total_html','members_only_price_pages');
add_filter('woocommerce_cart_item_subtotal','members_only_price_pages');
add_filter('woocommerce_cart_item_price','members_only_price_pages');
add_filter('wc_price','members_only_price_pages');
function members_only_price_pages($price){
    if( is_user_logged_in() ){
        return $price;      }
            else {
                return '<a href="https://www.dentaltechnologiesitalia.it/register/" class="bottone-c">LOGIN PER VEDERE IL PREZZO</a>';      }  }
</code>```

答:
is_product_category() Checks If Current Page is a Product Category.

What you need here is to check if the product belongs to a specific category with the has_term() function.

If not user is logged in and the product belongs to category private_cat (for example), the price is replaced:

```<code>   /**Hide price*/
add_filter('woocommerce_get_price_html','members_only_price_pages');
add_filter('woocommerce_cart_totals_order_total_html','members_only_price_pages');
add_filter('woocommerce_cart_item_subtotal','members_only_price_pages');
add_filter('woocommerce_cart_item_price','members_only_price_pages');
add_filter('wc_price','members_only_price_pages');
function members_only_price_pages($price){
    if( ! is_user_logged_in() && has_term( 'private_cat', 'product_cat' ) ){
         return '<a href="https://example.com/register/" class="bottone-c">LOGIN PER VEDERE IL PREZZO</a>';
      }
      else {
         return $price;
       }
      }
</code>```

Body:
I have hidden all product's price until the user isn't logged in. Now i want to show always the price of just someone of my products.

Can anyone help me with the code?

Here's my php code used in function.php :

    /**Hide price*/
add_filter('woocommerce_get_price_html','members_only_price_pages');
add_filter('woocommerce_cart_totals_order_total_html','members_only_price_pages');
add_filter('woocommerce_cart_item_subtotal','members_only_price_pages');
add_filter('woocommerce_cart_item_price','members_only_price_pages');
add_filter('wc_price','members_only_price_pages');
function members_only_price_pages($price){
    if( is_user_logged_in() ){
        return $price;      }
            else {
                return 'LOGIN PER VEDERE IL PREZZO';      }  }

Body:
is_product_category() Checks If Current Page is a Product Category.

What you need here is to check if the product belongs to a specific category with the has_term() function.

If not user is logged in and the product belongs to category private_cat (for example), the price is replaced:

   /**Hide price*/
add_filter('woocommerce_get_price_html','members_only_price_pages');
add_filter('woocommerce_cart_totals_order_total_html','members_only_price_pages');
add_filter('woocommerce_cart_item_subtotal','members_only_price_pages');
add_filter('woocommerce_cart_item_price','members_only_price_pages');
add_filter('wc_price','members_only_price_pages');
function members_only_price_pages($price){
    if( ! is_user_logged_in() && has_term( 'private_cat', 'product_cat' ) ){
         return '<a href="https://example.com/register/" class="bottone-c">LOGIN PER VEDERE IL PREZZO</a>';
      }
      else {
         return $price;
       }
      }


问:
Unable to trigger onchange event from select tag in ASP.Net
I want to change the textboxes that should be displayed based on accountType the user selects. However, the onchange event attached to select is not getting triggered. Any heads up?

This is the select tag.

```<code><div class="col-md-12 form-group" style="color:black">
    <select name="accountTypes" id="accountTypes" runat="server" onchange="javascript:document.forms[0].submit();" onserverchange="accountType_Changed">
            <option value="customer">Customer</option>
            <option value="pharmacy">Pharmacy</option>
            <option value="doctor">Doctor</option>
    </select>
</div>
</code>```

The accountType_Changed function is:

```<code>void accountType_Changed(Object sender, EventArgs e)
{
    cnic.Text = accountTypes.SelectedItem.Value;//or accountTypes.SelectedItem.Text
}
</code>```

Edit:
Based on the solution proposed by @mahesh_b, following edits were made that fixed the problem:

```<code>protected void Page_Load(object sender, EventArgs e)
{
    this.accountTypes.Attributes.Add("onchange", Page.ClientScript.GetPostBackEventReference(this.accountTypes, this.accountTypes.ID));
}

protected void accountType_Changed(object sender, EventArgs e)
{
    cnic.Text = "Working!!!"; //accountTypes.SelectedItem.Value;//or accountTypes.SelectedItem.Text
}
</code>```

Edit 2: Layout Rendering Issue after adding partial refresh

Login.aspx:

```<code><asp:ScriptManager EnablePartialRendering="true" ID="scriptManager" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
    <section class="login_part section_padding ">
    <div class="container">
        <div class="row align-items-center">
            <div class="col-lg-6 col-md-6">
                <div class="login_part_text text-center">
                    <div class="login_part_text_iner">
                        <h2>New to PHS?</h2>

                        <div class="row">

                            <div class="column col-md-12 form-group p_star">
                                <div class="col-md-12 form-group p_star">
                                    <asp:TextBox ID="firstname" placeholder="First Name" class="form-control" runat="server">
                                    </asp:TextBox>
                                </div>
                            </div>

                            <div class="column col-md-12 form-group p_star">
                                <div class="col-md-12 form-group p_star">
                                    <asp:TextBox ID="lastname" placeholder="Last Name" class="form-control" runat="server">
                                    </asp:TextBox>
                               </div>

                            </div>

                        </div>

                        <div class="col-md-12 form-group p_star">
                            <asp:TextBox ID="cnic" placeholder="CNIC" class="form-control" runat="server">
                            </asp:TextBox>
                       </div>

                        <div class="col-md-12 form-group p_star">
                            <asp:TextBox ID="email" placeholder="Email" class="form-control" runat="server">
                            </asp:TextBox>
                       </div>

                        <div class="col-md-12 form-group p_star">
                            <asp:TextBox ID="pass" placeholder="Password" class="form-control" runat="server">
                            </asp:TextBox>
                       </div>

                        <div class="col-md-12 form-group" style="color:black">
                            <select name="accountTypes" id="accountTypes" runat="server" onchange="javascript:document.forms[0].submit();" onserverchange="accountType_Changed">
                              <option value="customer">Customer</option>
                              <option value="pharmacy">Pharmacy</option>
                              <option value="doctor">Doctor</option>
                            </select>
                        </div>

                        <br /><br />
                        <div class="col-md-12 form-group p_star">
                            <asp:TextBox ID="taxNo" placeholder="Tax No" class="form-control" runat="server">
                            </asp:TextBox>
                       </div>

                        <div class="col-md-12 form-group p_star">
                            <asp:TextBox ID="pName" placeholder="Pharmacy Name" class="form-control" runat="server">
                            </asp:TextBox>
                       </div>

                        <div class="col-md-12 form-group p_star">
                            <asp:TextBox ID="pAddress" placeholder="Pharmacy Address" class="form-control" runat="server">
                            </asp:TextBox>
                       </div>

                        <div class="col-md-12 form-group p_star">
                            <asp:TextBox ID="cAddress" placeholder="Address" class="form-control" runat="server">
                            </asp:TextBox>
                       </div>

                        <div class="col-md-12 form-group p_star">
                            <asp:TextBox ID="docID" placeholder="Doctor Id" class="form-control" runat="server">
                            </asp:TextBox>
                       </div>

                        <div class="col-md-12 form-group p_star">
                            <asp:TextBox ID="experience" placeholder="Experience (Years)" class="form-control" runat="server">
                            </asp:TextBox>
                       </div>

                        <div class="col-md-12 form-group p_star">
                            <asp:TextBox ID="expertise" placeholder="Expertise (Specialization)" class="form-control" runat="server">
                            </asp:TextBox>
                       </div>

                        <br />
                        <p>Create an account today and avail the best deals on medics.</p>
                        <asp:Button ID="registerButton" class="btn_3" runat="server" width="50%" Text="Create Account" OnClick="createAccount_Clicked"/>

                    </div>
                </div>
            </div>
            <div class="col-lg-6 col-md-6">
                <div class="login_part_form">
                    <div class="login_part_form_iner">
                        <h3>Welcome Back ! <br>
                            Please Sign in now</h3>
                        <form class="row contact_form" action="#" method="post" novalidate="novalidate">
                            <div class="col-md-12 form-group p_star">
                                <input type="text" class="form-control" id="name" name="name" value=""
                                    placeholder="Username">
                            </div>
                            <div class="col-md-12 form-group p_star">
                                <input type="password" class="form-control" id="password" name="password" value=""
                                    placeholder="Password">
                            </div>
                            <div class="col-md-12 form-group">

                                <button type="submit" value="submit" class="btn_3">
                                    log in
                                </button>
                                <a class="lost_pass" href="#">forget password?</a>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>
</ContentTemplate>
</asp:UpdatePanel>
</code>```

These images show the original layout of select and what gets loaded after I change the value:

Original:

This is what gets loaded after changing the value in accountType:

How can I get to keep my original layout?

答:
You need to use ASP.NET Dropdownlist with using AutoPostBack=true to trigger OnChange event:

```<code><div class="col-md-12 form-group" style="color:black">
    <asp:DropDownList id="accountTypes" AutoPostBack="True" OnSelectedIndexChanged="accountType_Changed" runat="server">
      <asp:ListItem Value="account_type">Account Type</asp:ListItem>
      <asp:ListItem Value="customer"> Customer </asp:ListItem>
      <asp:ListItem Value="pharmacy"> Pharmacy </asp:ListItem>
      <asp:ListItem Value="doctor"> Doctor </asp:ListItem>
   </asp:DropDownList>
 </div>
</code>```

And server side accountType_Changed would be like this:

```<code>void accountType_Changed(Object sender, EventArgs e)
{
    username.Text = accountTypes.SelectedItem.Value;//or accountTypes.SelectedItem.Text
}
</code>```

Body:
I want to change the textboxes that should be displayed based on accountType the user selects. However, the onchange event attached to select is not getting triggered. Any heads up?

This is the select tag.

    <select name="accountTypes" id="accountTypes" runat="server" onchange="javascript:document.forms[0].submit();" onserverchange="accountType_Changed">
            <option value="customer">Customer</option>
            <option value="pharmacy">Pharmacy</option>
            <option value="doctor">Doctor</option>
    </select>

The accountType_Changed function is:

void accountType_Changed(Object sender, EventArgs e)
{
    cnic.Text = accountTypes.SelectedItem.Value;//or accountTypes.SelectedItem.Text
}

Edit:
Based on the solution proposed by @mahesh_b, following edits were made that fixed the problem:

protected void Page_Load(object sender, EventArgs e)
{
    this.accountTypes.Attributes.Add("onchange", Page.ClientScript.GetPostBackEventReference(this.accountTypes, this.accountTypes.ID));
}

protected void accountType_Changed(object sender, EventArgs e)
{
    cnic.Text = "Working!!!"; //accountTypes.SelectedItem.Value;//or accountTypes.SelectedItem.Text
}

Edit 2: Layout Rendering Issue after adding partial refresh

Login.aspx:

<asp:ScriptManager EnablePartialRendering="true" ID="scriptManager" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>

New to PHS?

                                    <asp:TextBox ID="firstname" placeholder="First Name" class="form-control" runat="server">
                                    </asp:TextBox>

                                    <asp:TextBox ID="lastname" placeholder="Last Name" class="form-control" runat="server">
                                    </asp:TextBox>

                            <asp:TextBox ID="cnic" placeholder="CNIC" class="form-control" runat="server">
                            </asp:TextBox>

                            <asp:TextBox ID="email" placeholder="Email" class="form-control" runat="server">
                            </asp:TextBox>

                            <asp:TextBox ID="pass" placeholder="Password" class="form-control" runat="server">
                            </asp:TextBox>

                            <select name="accountTypes" id="accountTypes" runat="server" onchange="javascript:document.forms[0].submit();" onserverchange="accountType_Changed">
                              <option value="customer">Customer</option>
                              <option value="pharmacy">Pharmacy</option>
                              <option value="doctor">Doctor</option>
                            </select>

                            <asp:TextBox ID="taxNo" placeholder="Tax No" class="form-control" runat="server">
                            </asp:TextBox>

                            <asp:TextBox ID="pName" placeholder="Pharmacy Name" class="form-control" runat="server">
                            </asp:TextBox>

                            <asp:TextBox ID="pAddress" placeholder="Pharmacy Address" class="form-control" runat="server">
                            </asp:TextBox>

                            <asp:TextBox ID="cAddress" placeholder="Address" class="form-control" runat="server">
                            </asp:TextBox>

                            <asp:TextBox ID="docID" placeholder="Doctor Id" class="form-control" runat="server">
                            </asp:TextBox>

                            <asp:TextBox ID="experience" placeholder="Experience (Years)" class="form-control" runat="server">
                            </asp:TextBox>

                            <asp:TextBox ID="expertise" placeholder="Expertise (Specialization)" class="form-control" runat="server">
                            </asp:TextBox>

Create an account today and avail the best deals on medics.

                        <asp:Button ID="registerButton" class="btn_3" runat="server" width="50%" Text="Create Account" OnClick="createAccount_Clicked"/>

Welcome Back !

                            Please Sign in now

                        <form class="row contact_form" action="#" method="post" novalidate="novalidate">

                                <input type="text" class="form-control" id="name" name="name" value=""
                                    placeholder="Username">

                                <input type="password" class="form-control" id="password" name="password" value=""
                                    placeholder="Password">

                                <button type="submit" value="submit" class="btn_3">
                                    log in
                                </button>
                                forget password?

                        </form>

</ContentTemplate>
</asp:UpdatePanel>

These images show the original layout of select and what gets loaded after I change the value:

Original:

This is what gets loaded after changing the value in accountType:

How can I get to keep my original layout?

Body:
You need to use ASP.NET Dropdownlist with using AutoPostBack=true to trigger OnChange event:

<div class="col-md-12 form-group" style="color:black">
    <asp:DropDownList id="accountTypes" AutoPostBack="True" OnSelectedIndexChanged="accountType_Changed" runat="server">
      <asp:ListItem Value="account_type">Account Type</asp:ListItem>
      <asp:ListItem Value="customer"> Customer </asp:ListItem>
      <asp:ListItem Value="pharmacy"> Pharmacy </asp:ListItem>
      <asp:ListItem Value="doctor"> Doctor </asp:ListItem>
   </asp:DropDownList>
 </div>

And server side accountType_Changed would be like this:

void accountType_Changed(Object sender, EventArgs e)
{
    username.Text = accountTypes.SelectedItem.Value;//or accountTypes.SelectedItem.Text
}


问:
What is the correct way to import modules when I'm writing my own module in python?
I've searched for similar questions, but what I've found doesn't work for me.

I'm writing the report of my analysis in a jupyter notebook (let's say main.ipynb). I want to import an external functions.py file with some functions that I use to plot some results. To be precise, my working directory has the following structure:

-main.ipynb

-utils

----functions.py

---- other files...

The functions.py file is something like this:

import matplotlib.pyplot as plt

def myPlot():
    plt.figure()
    plt.plot([0,1],[0,1])
    plt.show()
    ....
```

<p>and the first cell of the notebook is this:</p>

<pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt
from utils.functions import *

myPlot()
</code>```

When I run the notebook I get this error:
NameError: name 'plt' is not defined, although I have defined plt in both files (even if I think I really shouldn't need it in the main.ipynb).

S0, what is the correct way to import a package (matplotlib.pyplot in this case) in an external file? What am I doing wrong?

答:
I've found the flaw in my code and I think it's worth sharing, so here I am.

Maybe for beginners using jupyter notebook (as me) this could be tricky to detect: once you've run the cell with the import statement, it doesn't matter if you edit your file functions.py and re-run that cell. The kernel has already imported a file with that exact same name, so it won't notice the difference even if you've made changes.

The solution I found (and I think is the only one) is to restart the kernel every time you change the functions.py file.

Body:
I've searched for similar questions, but what I've found doesn't work for me.

I'm writing the report of my analysis in a jupyter notebook (let's say main.ipynb). I want to import an external functions.py file with some functions that I use to plot some results. To be precise, my working directory has the following structure:

-main.ipynb

-utils

----functions.py

---- other files...

The functions.py file is something like this:

import matplotlib.pyplot as plt

def myPlot():
    plt.figure()
    plt.plot([0,1],[0,1])
    plt.show()
    ....

and the first cell of the notebook is this:

import matplotlib.pyplot as plt
from utils.functions import *

myPlot()

When I run the notebook I get this error:
NameError: name 'plt' is not defined, although I have defined plt in both files (even if I think I really shouldn't need it in the main.ipynb).

S0, what is the correct way to import a package (matplotlib.pyplot in this case) in an external file? What am I doing wrong?


问:
quickly adding email address for .NetCore MailKit smtp utility
I found a little email utility for MailKit .NetCore.

I got it to work, but I can't figure out how to add more than one email recipient.

I can one like this:

```<code>EmailAddress toAddress = new EmailAddress()
{
    Name = "Ken Watanabe",
    Address = "kw100@xxxx.com"
};

var newMessage = new EmailMessage()
</code>```

And then it is added to a new EmailMessage like this:

```<code>newMessage.ToAddresses.Add(toAddress);
</code>```

The EmailMessage class looks like this:

```<code>public class EmailMessage
{
    public EmailMessage()
    {
        ToAddresses = new List<EmailAddress>();
        FromAddresses = new List<EmailAddress>();
    }

    public List<EmailAddress> ToAddresses { get; set; }
    public List<EmailAddress> FromAddresses { get; set; }
    public string Subject { get; set; }
    public string Content { get; set; }
}
</code>```

Then it is passed onto another method to be sent:

```<code>var message = new MimeMessage();
message.To.AddRange(emailMessage.ToAddresses.Select(x => new MailboxAddress(x.Name, x.Address)));
</code>```

I guess I can create new recipients like this:

```<code>EmailAddress toAddress1 = new EmailAddress()
{
    Name = "Ken Watanabe",
    Address = "kw100@xxxx.com"
};

    EmailAddress toAddress2 = new EmailAddress()
{
    Name = "Ryosuke Yamada",
    Address = "ry1010104@yyyy.com"
};

newMessage.ToAddresses.Add(toAddress1);
newMessage.ToAddresses.Add(toAddress2);
</code>```

But I was wondering if there would be an easier way that didn't require as much code.

Is there a way to just add the info instead of having to create a separate EmailAddress object for each one?

Thanks!

答:
If you can modify the EmailAddress class then the easiest change would be to make a class constructor with parameters for name and email e.g.

public class EmailAddress
{
    public EmailAddress() { }

    public EmailAddress(name, address)
    {
        Name = name;
        Address = address;
    }
    // ...
```

<p>Then you can create the new email address and add it directly to the list of addresses. e.g.</p>

<pre class="lang-cs prettyprint-override"><code>newMessage.ToAddresses.Add(new EmailAddress("Ken Watanabe", "kw100@xxxx.com"));
newMessage.ToAddresses.Add(new EmailAddress("Ryosuke Yamada", "ry1010104@yyyy.com"));
</code>```

Body:
I found a little email utility for MailKit .NetCore.

I got it to work, but I can't figure out how to add more than one email recipient.

I can one like this:

EmailAddress toAddress = new EmailAddress()
{
    Name = "Ken Watanabe",
    Address = "kw100@xxxx.com"
};

var newMessage = new EmailMessage()

And then it is added to a new EmailMessage like this:

newMessage.ToAddresses.Add(toAddress);

The EmailMessage class looks like this:

public class EmailMessage
{
    public EmailMessage()
    {
        ToAddresses = new List<EmailAddress>();
        FromAddresses = new List<EmailAddress>();
    }

    public List<EmailAddress> ToAddresses { get; set; }
    public List<EmailAddress> FromAddresses { get; set; }
    public string Subject { get; set; }
    public string Content { get; set; }
}

Then it is passed onto another method to be sent:

var message = new MimeMessage();
message.To.AddRange(emailMessage.ToAddresses.Select(x => new MailboxAddress(x.Name, x.Address)));

I guess I can create new recipients like this:

EmailAddress toAddress1 = new EmailAddress()
{
    Name = "Ken Watanabe",
    Address = "kw100@xxxx.com"
};

    EmailAddress toAddress2 = new EmailAddress()
{
    Name = "Ryosuke Yamada",
    Address = "ry1010104@yyyy.com"
};

newMessage.ToAddresses.Add(toAddress1);
newMessage.ToAddresses.Add(toAddress2);

But I was wondering if there would be an easier way that didn't require as much code.

Is there a way to just add the info instead of having to create a separate EmailAddress object for each one?

Thanks!

Body:
If you can modify the EmailAddress class then the easiest change would be to make a class constructor with parameters for name and email e.g.

public class EmailAddress
{
    public EmailAddress() { }

    public EmailAddress(name, address)
    {
        Name = name;
        Address = address;
    }
    // ...

Then you can create the new email address and add it directly to the list of addresses. e.g.

newMessage.ToAddresses.Add(new EmailAddress("Ken Watanabe", "kw100@xxxx.com"));
newMessage.ToAddresses.Add(new EmailAddress("Ryosuke Yamada", "ry1010104@yyyy.com"));


问:
Laravel Passport. Why can’t I create an access token?
When I execute login, access token is not created, in the log files I get the following errors:

local.ERROR: The resource owner or authorization server denied the request.

and

(InvalidArgumentException(code: 0): The JWT string must have two dots at.

I made a request using the insomnia program and everything works fine there, the access token appears in the database

My function login:

```<code>public function login(Request $request)
{
    $req = Request::create(route('passport.token'), 'POST', [
        'grant_type'    => 'password',
        'client_id'     => 2,
        'client_secret' => 'lvDjvx5UgzeYJxQMjjLMSFL3psqXj2iuw2xLL6Yh',
        'phone_number'  => $request->phone_number,
        'password'      => $request->password,
    ]);

    $response = app()->handle($req);

    if ($response->status() == 400) {

        return response()->json([
            'message' => 'Н',
        ]);
    } else if ($response->status() == 401) {

        return response()->json([
            'message' => '',
        ]);
    }

    return $response;
}
</code>```

答:
try this code:

```<code>public function login(Request $request)
  {
    $req = Request::create(route('passport.token'), 'POST', [
        'grant_type' => 'password',
        'client_id' => Your client_id,
        'client_secret' => 'Your client_secret ',
        'username' => $request->username,
        'password' => $request->password
    ]);

    $response = app()->handle($req);
    if ($response->status() === 400) {

        return response()->json([
            'message' => 'Н',
        ]);
    }
    if ($response->status() === 401) {

        return response()->json([
            'message' => '',
        ]);
    }

    return $response;
}
</code>```

In model User
```</p>

<code>public function findForPassport($identifier) {
        return $this->where('phone_number', $identifier)->first();
    }
</code>```

Body:
When I execute login, access token is not created, in the log files I get the following errors:

local.ERROR: The resource owner or authorization server denied the request.

and

(InvalidArgumentException(code: 0): The JWT string must have two dots at.

I made a request using the insomnia program and everything works fine there, the access token appears in the database

My function login:

public function login(Request $request)
{
    $req = Request::create(route('passport.token'), 'POST', [
        'grant_type'    => 'password',
        'client_id'     => 2,
        'client_secret' => 'lvDjvx5UgzeYJxQMjjLMSFL3psqXj2iuw2xLL6Yh',
        'phone_number'  => $request->phone_number,
        'password'      => $request->password,
    ]);

    $response = app()->handle($req);

    if ($response->status() == 400) {

        return response()->json([
            'message' => 'Н',
        ]);
    } else if ($response->status() == 401) {

        return response()->json([
            'message' => '',
        ]);
    }

    return $response;
}

Body:
try this code:

public function login(Request $request)
  {
    $req = Request::create(route('passport.token'), 'POST', [
        'grant_type' => 'password',
        'client_id' => Your client_id,
        'client_secret' => 'Your client_secret ',
        'username' => $request->username,
        'password' => $request->password
    ]);

    $response = app()->handle($req);
    if ($response->status() === 400) {

        return response()->json([
            'message' => 'Н',
        ]);
    }
    if ($response->status() === 401) {

        return response()->json([
            'message' => '',
        ]);
    }

    return $response;
}

In model User

public function findForPassport($identifier) {
        return $this->where('phone_number', $identifier)->first();
    }


问:
pytorch affine_grid: what is the theta input?
When trying to use torch.nn.functional.affine_grid, it requires a theta affine matrix of size (N x 3 x 4) according to the documentation. I thought a general affine matrix is (N x 4 x 4). What is the supposed affine matrix format in pytorch?

An example of 3D rotation affine input would be ideal. Appreciate your help.

答:
The dimensions you mention are applicable for the case of 3D inputs, that is you wish to apply 3D geometric transforms on the input tensor x of shape bxcxdxhxw.

A transformation to points in 3D (represented as 4-vector in homogeneous coordinates as (x, y, z, 1)) should be, in the general case, a 4x4 matrix as you noted.

However, since we restrict ourselves to homogeneous coordinates, i.e., the fourth coordinate must be 1, the 4th row of the matrix must be (0, 0, 0, 1) (see this).

Therefore, there's no need to explicitly code this last row.

To conclude, a 3D transformation composed of a 3x3 rotation R and 3d translation t is simply the 3x4 matrix:

```<code>theta = [R t]
</code>```

Body:
The dimensions you mention are applicable for the case of 3D inputs, that is you wish to apply 3D geometric transforms on the input tensor x of shape bxcxdxhxw.

A transformation to points in 3D (represented as 4-vector in homogeneous coordinates as (x, y, z, 1)) should be, in the general case, a 4x4 matrix as you noted.

However, since we restrict ourselves to homogeneous coordinates, i.e., the fourth coordinate must be 1, the 4th row of the matrix must be (0, 0, 0, 1) (see this).

Therefore, there's no need to explicitly code this last row.

To conclude, a 3D transformation composed of a 3x3 rotation R and 3d translation t is simply the 3x4 matrix:

theta = [R t]


问:
pandas filter by multiple conditions without chaining
I want to filter a pandas dataframe by multiple condiitons that have to hold together.

```<code>d = {'price': [1, 2, 0 ,0,1], 'description': ['a', 'a','b','c','e']}
df = pd.DataFrame(data=d)
li = ['a','b']
df = df[(df['price']!=0) & (~df['description'].isin(li))]
</code>```

The problem is, that it removes all prices that are 0 and then removes everything thats in li.
I want it to remove rows in the dataframe that hold both conditions together and not only one of it.

expected output would be:

```<code>   price description
      1           a
      2           a
      0           c
      1           e
</code>```

but instead it is:

```<code>   price description
      1           e
</code>```

答:
Based on your edited expected output,

Just replace the and & with an or |

```<code>df = df[(df['price']!=0) | (~df['description'].isin(li))]

#Output
price description
     1           a
     2           a
     0           c
     1           e
</code>```

Body:
I want to filter a pandas dataframe by multiple condiitons that have to hold together.

d = {'price': [1, 2, 0 ,0,1], 'description': ['a', 'a','b','c','e']}
df = pd.DataFrame(data=d)
li = ['a','b']
df = df[(df['price']!=0) & (~df['description'].isin(li))]

The problem is, that it removes all prices that are 0 and then removes everything thats in li.
I want it to remove rows in the dataframe that hold both conditions together and not only one of it.

expected output would be:

   price description
      1           a
      2           a
      0           c
      1           e

but instead it is:

   price description
      1           e

Body:
Based on your edited expected output,

Just replace the and & with an or |

df = df[(df['price']!=0) | (~df['description'].isin(li))]

#Output
price description
     1           a
     2           a
     0           c
     1           e


问:
Voxel Cone Tracing in Deferred pipeline?
I am working on a project where I have to implement voxel cone tracing for indirect light in C++/OpenGL. I already have a deferred renderer setup but most of the VCT examples I could find usually draw the scene once for voxelization and once with cone tracing shaders. Is it possible to run cone tracing shaders over a fullscreen quad and sample vertex data from the GBuffer or is that generally a stupid idea? Do I lose accuracy because I only have per pixel vertex data?</p>

答:
A question is perhaps, what's your motivation for trying doing both.

When you do Voxel Cone tracing you are trying to solve the exact same problem you would be trying to solve with deferred rendering and now have the overhead of both techniques, if you are already willing to deal with the overhead of Voxel Cone tracing then it's better to fully commit to that technique.

The reason is simple, if you are doing voxel cone tracing then you have a 3D texture of some sort (could be voxel oct tree, and actual 3D texture or some other structure). That is essentially a 3D Gbuffer.

If your idea is simply to eliminate the need for such a structure and use the existing planar GBuffer instead, then you are introducing artifacts that do not appear with traditional SSRT techniques.

In essence trying both at the same time is likely to give you the worst of both worlds rather than the best.


问:
Value of Table 1 needs to be permanent after changing value of inputs
I am new to React and am trying to add table rows on the click of a button. The problem is that the values in the input labels are getting added to the table. but the values need to be unchanged on adding another row. As soon as I change the value in the inputs the corresponding table row values also change. I want the table values to be permanent and different according to changing input in input labels.

Here is my code for KPI Details:

```<code>export class KPIDetails extends Component {
  state = {
    rows: [],
    idx: [1]
  };
  continue = e => {
    e.preventDefault();
    this.props.nextStep();
  };

  handleChangeRows = idx => e => {
    const { name, value } = e.target;
    const rows = [...this.state.rows];
    rows[idx] = {
      [name]: value
    };
    this.setState({
      rows
    });
  };

  //2
  handleAddRow = () => {
    const item = {
      KPI_Before: "",
      UOM_Before: "",
      Base_Before: "",
      Target_Before: "",
      dateTime: ""
    };
    this.setState({
      rows: [...this.state.rows, item]
    });
  };

  //3
  handleRemoveRow = () => {
    this.setState({
      rows: this.state.rows.slice(0, -1)
    });
  };
  setDate = dateTime => this.setState({ dateTime });

  render() {
    const { values, handleChange } = this.props;
    const {
      values: {
        Title,
        Details,
        What,
        Why,
        How,
        Status,
        Cost,
        Benefits,
        Kpi_Before,
        Kpi_After,
        UOM_Before,
        Base_Before,
        Target_Before,
        Time,
        dateTime
      }
    } = this.props;
    return (
      <MuiThemeProvider theme={theme}>
        <React.Fragment>
          <div className={useStyles.root}>
            <AppBar position="static">
              <Toolbar>
                <Typography
                  gutterBottom
                  align="center"
                  style={{ width: "100%", alignItems: "center" }}
                >
                  KPI Before Implementation
                </Typography>
              </Toolbar>
            </AppBar>
          </div>
          <br />
          <br />
          <Grid container>
            <Grid item xs={6}>
              <TextField
                label="KPI"
                id="Kpi_Before"
                variant="outlined"
                size="small"
                placeholder="Enter the KPI"
                onChange={handleChange("Kpi_Before")}
                defaultValue={values.Kpi_Before}
                style={{ width: "80%" }}
              />
            </Grid>
            <Grid item xs={6}>
              <FormControl style={{ width: "80%" }} size="small">
                <InputLabel
                  htmlFor="UOM_Before"
                  style={{
                    marginLeft: 10,
                    top: "50%",
                    transform: "translate(0,-50%"
                  }}
                >
                  UOM
                </InputLabel>
                <Select
                  labelId="UOM_Before"
                  name="name"
                  onChange={handleChange("UOM_Before")}
                  defaultValue={values.UOM_Before}
                  variant="outlined"
                  inputProps={{
                    id: "UOM_Before"
                  }}
                >
                  <MenuItem value="Nos">Nos</MenuItem>
                  <MenuItem value="Percentage">Percentage</MenuItem>
                  <MenuItem value="Metric">Metric</MenuItem>
                </Select>
              </FormControl>
            </Grid>
          </Grid>
          <br />
          <br />
          <br />
          <br />
          <Grid container>
            <Grid item xs={6}>
              <TextField
                label="Base Level"
                variant="outlined"
                size="small"
                placeholder="Enter the Base Level"
                onChange={handleChange("Base_Before")}
                style={{ width: "80%" }}
              />
            </Grid>
            <Grid item xs={6}>
              <TextField
                label="Target Level"
                variant="outlined"
                size="small"
                placeholder="Enter the Target Level"
                onChange={handleChange("Target_Before")}
                defaultValue={values.Target_Before}
                style={{ width: "80%" }}
              />
            </Grid>
          </Grid>
          <br />
          <br />
          <br />
          <br />
          <Grid container>
            <Grid item xs={6} direction="row" alignItems="center">
              <TextField
                id="date"
                label="Target Date"
                type="date"
                variant="outlined"
                size="small"
                defaultValue="2017-05-24"
                onChange={handleChange("dateTime")}
                style={{ width: "67%" }}
                InputLabelProps={{
                  shrink: true
                }}
              />

              <Button
                variant="outlined"
                color="primary"
                onClick={this.handleAddRow}
                size="small"
                style={styles.button}
              >
                +
              </Button>
            </Grid>

            <Grid item xs={6}>
              ...
            </Grid>
          </Grid>
          <Grid container>
            <Grid item xs={6} direction="row" alignItems="center">
              <table
                className="table table-bordered table-hover"
                id="tab_logic"
              >
                <thead>
                  <tr>
                    <th className="text-center"> # </th>
                    <th className="text-center"> KPI </th>
                    <th className="text-center"> UOM </th>
                    <th className="text-center"> Base </th>
                    <th className="text-center"> Target </th>
                    <th className="text-center"> Target Date </th>
                  </tr>
                </thead>
                <tbody>
                  {this.state.rows.map((item, idx) => (
                    <tr id="addr1" key={idx}>
                      <td>{idx}</td>
                      <td>
                        <input
                          type="text"
                          name="Kpi_Before"
                          value={Kpi_Before}
                          onChange={this.handleChangeRows(idx)}
                          className="form-control"
                        />
                      </td>
                      <td>
                        <input
                          type="text"
                          name="UOM_Before"
                          value={UOM_Before}
                          onChange={this.handleChangeRows(idx)}
                          className="form-control"
                        />
                      </td>
                      <td>
                        <input
                          type="text"
                          name="Base_Before"
                          value={Base_Before}
                          onChange={this.handleChangeRows(idx)}
                          className="form-control"
                        />
                      </td>
                      <td>
                        <input
                          type="text"
                          name="Target_Before"
                          value={Target_Before}
                          onChange={this.handleChangeRows(idx)}
                          className="form-control"
                        />
                      </td>
                      <td>
                        <input
                          type="text"
                          name="Target_Before"
                          value={dateTime}
                          onChange={this.handleChangeRows(idx)}
                          className="form-control"
                        />
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
              <button
                onClick={this.handleRemoveRow}
                className="pull-right btn btn-default"
              >
                Delete Row
              </button>
            </Grid>
          </Grid>
        </React.Fragment>
      </MuiThemeProvider>
    );
  }
}

const theme = createMuiTheme({
  palette: {
    primary: blue,
    secondary: purple
  },
  status: {
    danger: "orange"
  }
});

const styles = {
  button: {
    margin: 5,
    verticalAlign: "bottom"
  }
};

export default KPIDetails;
</code>```

Here is my code for User Form:

```<code>export class UserForm extends Component {

  state = {
    step: 1,
    Title: "",
    Details: "",
    What: "",
    Why: "",
    How: "",
    Status: "",
    Cost: "",
    Benefits: "",
    Kpi_Before: "",
    Kpi_After: "",
    Time: "",
    UOM_Before: "",
    Base_Before: "",
    Target_Before: "",
    dateTime: null,
    rows: []
  };

  //1
  handleChangeRows = idx => e => {
    const { Kpi_Before, value } = e.target;
    const rows = [...this.state.rows];
    rows[idx] = {
      [Kpi_Before]: value
    };
    this.setState({
      rows
    });
  };

  //2
  handleAddRow = () => {
    const item = {
      KPI_Before: "",
      UOM_Before: "",
      Base_Before: "",
      Target_Before: "",
      dateTime: ""
    };
    this.setState({
      rows: [...this.state.rows, item]
    });
  };

  //3
  handleRemoveRow = () => {
    this.setState({
      rows: this.state.rows.slice(0, -1)
    });
  };

  //Proceed to next step
  nextStep = () => {
    const { step } = this.state;
    this.setState({
      step: step + 1
    });
  };

  //Go back to previous step
  prevStep = () => {
    const { step } = this.state;
    this.setState({
      step: step - 1
    });
  };

  //Handle fields change
  handleChange = input => e => {
    this.setState({ [input]: e.target.value });
  };

  render() {
    const { step } = this.state;
    const {
      Title,
      Details,
      What,
      Why,
      How,
      Status,
      Cost,
      Benefits,
      Kpi_Before,
      Kpi_After,
      Time,
      UOM_Before,
      Base_Before,
      Target_Before,
      dateTime,
      rows
    } = this.state;

    const values = {
      Title,
      Details,
      What,
      Why,
      How,
      Status,
      Cost,
      Benefits,
      Kpi_Before,
      Kpi_After,
      Time,
      UOM_Before,
      Base_Before,
      Target_Before,
      dateTime,
      rows
    };
    switch (step) {
      case 1:
        return (
          <FormUserDetails
            nextStep={this.nextStep}
            handleChange={this.handleChange}
            values={values}
          />
        );
      case 2:
        return (
          <KPIDetails
            handleChange={this.handleChange}
            values={values}
            nextStep={this.nextStep}
            handleChangeRows={this.handleChangeRows}
            handleAddRow={this.handleAddRow}
            handleRemoveRow={this.handleRemoveRow}
          />
        );

      case 3:
        return (
          <Confirm
            nextStep={this.nextStep}
            prevStep={this.prevStep}
            values={values}
          />
        );
      case 4:
        return <Success />;
    }
  }
}

export default UserForm;
</code>```

Please Advice me on how to achieve this?

答: Used defaultValue instead of value and it solved the problem</p>

Body:
I am new to React and am trying to add table rows on the click of a button. The problem is that the values in the input labels are getting added to the table. but the values need to be unchanged on adding another row. As soon as I change the value in the inputs the corresponding table row values also change. I want the table values to be permanent and different according to changing input in input labels.

Here is my code for KPI Details:

export class KPIDetails extends Component {
  state = {
    rows: [],
    idx: [1]
  };
  continue = e => {
    e.preventDefault();
    this.props.nextStep();
  };

  handleChangeRows = idx => e => {
    const { name, value } = e.target;
    const rows = [...this.state.rows];
    rows[idx] = {
      [name]: value
    };
    this.setState({
      rows
    });
  };

  //2
  handleAddRow = () => {
    const item = {
      KPI_Before: "",
      UOM_Before: "",
      Base_Before: "",
      Target_Before: "",
      dateTime: ""
    };
    this.setState({
      rows: [...this.state.rows, item]
    });
  };

  //3
  handleRemoveRow = () => {
    this.setState({
      rows: this.state.rows.slice(0, -1)
    });
  };
  setDate = dateTime => this.setState({ dateTime });

  render() {
    const { values, handleChange } = this.props;
    const {
      values: {
        Title,
        Details,
        What,
        Why,
        How,
        Status,
        Cost,
        Benefits,
        Kpi_Before,
        Kpi_After,
        UOM_Before,
        Base_Before,
        Target_Before,
        Time,
        dateTime
      }
    } = this.props;
    return (
      <MuiThemeProvider theme={theme}>
        <React.Fragment>

            <AppBar position="static">
              <Toolbar>
                <Typography
                  gutterBottom
                  align="center"
                  style={{ width: "100%", alignItems: "center" }}
                >
                  KPI Before Implementation
                </Typography>
              </Toolbar>
            </AppBar>

          <Grid container>
            <Grid item xs={6}>
              <TextField
                label="KPI"
                id="Kpi_Before"
                variant="outlined"
                size="small"
                placeholder="Enter the KPI"
                onChange={handleChange("Kpi_Before")}
                defaultValue={values.Kpi_Before}
                style={{ width: "80%" }}
              />
            </Grid>
            <Grid item xs={6}>
              <FormControl style={{ width: "80%" }} size="small">
                <InputLabel
                  htmlFor="UOM_Before"
                  style={{
                    marginLeft: 10,
                    top: "50%",
                    transform: "translate(0,-50%"
                  }}
                >
                  UOM
                </InputLabel>
                <Select
                  labelId="UOM_Before"
                  name="name"
                  onChange={handleChange("UOM_Before")}
                  defaultValue={values.UOM_Before}
                  variant="outlined"
                  inputProps={{
                    id: "UOM_Before"
                  }}
                >
                  <MenuItem value="Nos">Nos</MenuItem>
                  <MenuItem value="Percentage">Percentage</MenuItem>
                  <MenuItem value="Metric">Metric</MenuItem>
                </Select>
              </FormControl>
            </Grid>
          </Grid>

          <Grid container>
            <Grid item xs={6}>
              <TextField
                label="Base Level"
                variant="outlined"
                size="small"
                placeholder="Enter the Base Level"
                onChange={handleChange("Base_Before")}
                style={{ width: "80%" }}
              />
            </Grid>
            <Grid item xs={6}>
              <TextField
                label="Target Level"
                variant="outlined"
                size="small"
                placeholder="Enter the Target Level"
                onChange={handleChange("Target_Before")}
                defaultValue={values.Target_Before}
                style={{ width: "80%" }}
              />
            </Grid>
          </Grid>

          <Grid container>
            <Grid item xs={6} direction="row" alignItems="center">
              <TextField
                id="date"
                label="Target Date"
                type="date"
                variant="outlined"
                size="small"
                defaultValue="2017-05-24"
                onChange={handleChange("dateTime")}
                style={{ width: "67%" }}
                InputLabelProps={{
                  shrink: true
                }}
              />

              <Button
                variant="outlined"
                color="primary"
                onClick={this.handleAddRow}
                size="small"
                style={styles.button}
              >
                +
              </Button>
            </Grid>

            <Grid item xs={6}>
              ...
            </Grid>
          </Grid>
          <Grid container>
            <Grid item xs={6} direction="row" alignItems="center">

                     #
                     KPI
                     UOM
                     Base
                     Target
                     Target Date

                  {this.state.rows.map((item, idx) => (

                      {idx}

                        <input
                          type="text"
                          name="Kpi_Before"
                          value={Kpi_Before}
                          onChange={this.handleChangeRows(idx)}
                          className="form-control"
                        />

                        <input
                          type="text"
                          name="UOM_Before"
                          value={UOM_Before}
                          onChange={this.handleChangeRows(idx)}
                          className="form-control"
                        />

                        <input
                          type="text"
                          name="Base_Before"
                          value={Base_Before}
                          onChange={this.handleChangeRows(idx)}
                          className="form-control"
                        />

                        <input
                          type="text"
                          name="Target_Before"
                          value={Target_Before}
                          onChange={this.handleChangeRows(idx)}
                          className="form-control"
                        />

                        <input
                          type="text"
                          name="Target_Before"
                          value={dateTime}
                          onChange={this.handleChangeRows(idx)}
                          className="form-control"
                        />

                  ))}

              <button
                onClick={this.handleRemoveRow}
                className="pull-right btn btn-default"
              >
                Delete Row
              </button>
            </Grid>
          </Grid>
        </React.Fragment>
      </MuiThemeProvider>
    );
  }
}

const theme = createMuiTheme({
  palette: {
    primary: blue,
    secondary: purple
  },
  status: {
    danger: "orange"
  }
});

const styles = {
  button: {
    margin: 5,
    verticalAlign: "bottom"
  }
};

export default KPIDetails;

Here is my code for User Form:

export class UserForm extends Component {

  state = {
    step: 1,
    Title: "",
    Details: "",
    What: "",
    Why: "",
    How: "",
    Status: "",
    Cost: "",
    Benefits: "",
    Kpi_Before: "",
    Kpi_After: "",
    Time: "",
    UOM_Before: "",
    Base_Before: "",
    Target_Before: "",
    dateTime: null,
    rows: []
  };

  //1
  handleChangeRows = idx => e => {
    const { Kpi_Before, value } = e.target;
    const rows = [...this.state.rows];
    rows[idx] = {
      [Kpi_Before]: value
    };
    this.setState({
      rows
    });
  };

  //2
  handleAddRow = () => {
    const item = {
      KPI_Before: "",
      UOM_Before: "",
      Base_Before: "",
      Target_Before: "",
      dateTime: ""
    };
    this.setState({
      rows: [...this.state.rows, item]
    });
  };

  //3
  handleRemoveRow = () => {
    this.setState({
      rows: this.state.rows.slice(0, -1)
    });
  };

  //Proceed to next step
  nextStep = () => {
    const { step } = this.state;
    this.setState({
      step: step + 1
    });
  };

  //Go back to previous step
  prevStep = () => {
    const { step } = this.state;
    this.setState({
      step: step - 1
    });
  };

  //Handle fields change
  handleChange = input => e => {
    this.setState({ [input]: e.target.value });
  };

  render() {
    const { step } = this.state;
    const {
      Title,
      Details,
      What,
      Why,
      How,
      Status,
      Cost,
      Benefits,
      Kpi_Before,
      Kpi_After,
      Time,
      UOM_Before,
      Base_Before,
      Target_Before,
      dateTime,
      rows
    } = this.state;

    const values = {
      Title,
      Details,
      What,
      Why,
      How,
      Status,
      Cost,
      Benefits,
      Kpi_Before,
      Kpi_After,
      Time,
      UOM_Before,
      Base_Before,
      Target_Before,
      dateTime,
      rows
    };
    switch (step) {
      case 1:
        return (
          <FormUserDetails
            nextStep={this.nextStep}
            handleChange={this.handleChange}
            values={values}
          />
        );
      case 2:
        return (
          <KPIDetails
            handleChange={this.handleChange}
            values={values}
            nextStep={this.nextStep}
            handleChangeRows={this.handleChangeRows}
            handleAddRow={this.handleAddRow}
            handleRemoveRow={this.handleRemoveRow}
          />
        );

      case 3:
        return (
          <Confirm
            nextStep={this.nextStep}
            prevStep={this.prevStep}
            values={values}
          />
        );
      case 4:
        return <Success />;
    }
  }
}

export default UserForm;

Please Advice me on how to achieve this?


问:
Unable to display progress bar on pandas_profiling
I wrote some code to read some data on an excel file using pandas and wanted to do some data analysis on it using pandas_profiling. However, since its taking too long, I wanted to see some sort of progress bar on how much work was done and ran profiling in minimal mode to speed up the work. I found two separate ways to display, the progress bar. One as follows: ( Link here. In in the advanced usage section I found code for the following).

```<code>prof = ProfileReport(data, minimal=True, progress_bar=True)
prof.to_file(output_file='output.html')
</code>```

Another way is as follows ( I found this in a stackoverflow post. Link Here ):

```<code>prof = ProfileReport(data, minimal=True, html={ 'style' : {'full_width' : True}})
prof.to_file(output_file='ouput.html')
</code>```

However both don't seem to work. The code is taking too long to execute ( I waited for around 5 hours but to no avail). Is there a way to display a progress bar? And if possible, please suggest ways to speed up the work too. Any help would be appreciated.

I'm using Python 3.7 on Spyder that comes along with Ananconda (If that's of any help).

答: Thanks to some snooping around and a question on the comments section by Simon, I found out the problem. I was running pandas-profiling 1.4 and when I updated it to the latest one (2.8) it started worked immediately and the code produced a report with 15 seconds. So updating pandas-profiling helped.</p>

Body:
I wrote some code to read some data on an excel file using pandas and wanted to do some data analysis on it using pandas_profiling. However, since its taking too long, I wanted to see some sort of progress bar on how much work was done and ran profiling in minimal mode to speed up the work. I found two separate ways to display, the progress bar. One as follows: ( Link here. In in the advanced usage section I found code for the following).

prof = ProfileReport(data, minimal=True, progress_bar=True)
prof.to_file(output_file='output.html')

Another way is as follows ( I found this in a stackoverflow post. Link Here ):

prof = ProfileReport(data, minimal=True, html={ 'style' : {'full_width' : True}})
prof.to_file(output_file='ouput.html')

However both don't seem to work. The code is taking too long to execute ( I waited for around 5 hours but to no avail). Is there a way to display a progress bar? And if possible, please suggest ways to speed up the work too. Any help would be appreciated.

I'm using Python 3.7 on Spyder that comes along with Ananconda (If that's of any help).


问:
Standalone jQuery "touch" method?
So, I'm looking to implement the ability for a plugin I wrote to read a touch "swipe" from a touch-capable internet device, like an iPhone, iPad or android.

Is there anything out there? I'm not looking for something as full as jQtouch, though was considering reverse engineering the code I would need out of it.

Any suggestions on the best way to approach this? A snippet of code already available?

Addendum: I realize in hindsight the solution won't strictly be jQuery, as I'm pretty sure there aren't any built-in methods to handle this. I would expect standard Javascript to find itself in the answer.

答: There's also jQuery.touchwipe at http://www.netcu.de/jquery-touchwipe-iphone-ipad-library</p>

ContentLicense: CC BY-SA 2.5

Title: Standalone jQuery "touch" method?

ContentLicense: CC BY-SA 3.0


问:
How to get a flatten dataframe from lists of dictionaries which contain lists?
I'm trying to flat this kind of data structure into a "plain" dataframe.

Raw data is a list of dictionaries, which contain lists.

Data looks like this( reproducible example):

```<code>data = [{'A':[1,2,3,4], 'B':[11,12,13,14]}, {'A':[5,6,7,8], 'B':[15,16,17,18]}]
</code>```

My desidered output should be the following pandas dataframe:

```<code>Out[01]:
   A   B
0  1  11
1  2  12
2  3  13
3  4  14
4  5  15
5  6  16
6  7  17
7  8  18
</code>```

How can i achieve this result?
Thanks

答:
You can use pd.Series.explode

```<code>data = [{'A':[1,2,3,4], 'B':[11,12,13,14]}, {'A':[5,6,7,8], 'B':[15,16,17,18]}]

df = pd.DataFrame(data).apply(pd.Series.explode).reset_index(drop=True)

   A   B
0  1  11
1  2  12
2  3  13
3  4  14
4  5  15
5  6  16
6  7  17
7  8  18
</code>```

Or using collections.defaultdict

```<code>from collections import defaultdict
new = defaultdict(list)

for d in data:
    for k, v in d.items():
        new[k].extend(v)

df = pd.DataFrame(new)

   A   B
0  1  11
1  2  12
2  3  13
3  4  14
4  5  15
5  6  16
6  7  17
7  8  18
</code>```

Body:
I'm trying to flat this kind of data structure into a "plain" dataframe.

Raw data is a list of dictionaries, which contain lists.

Data looks like this( reproducible example):

data = [{'A':[1,2,3,4], 'B':[11,12,13,14]}, {'A':[5,6,7,8], 'B':[15,16,17,18]}]

My desidered output should be the following pandas dataframe:

Out[01]:
   A   B
0  1  11
1  2  12
2  3  13
3  4  14
4  5  15
5  6  16
6  7  17
7  8  18

How can i achieve this result?
Thanks

Body:
You can use pd.Series.explode

data = [{'A':[1,2,3,4], 'B':[11,12,13,14]}, {'A':[5,6,7,8], 'B':[15,16,17,18]}]

df = pd.DataFrame(data).apply(pd.Series.explode).reset_index(drop=True)

   A   B
0  1  11
1  2  12
2  3  13
3  4  14
4  5  15
5  6  16
6  7  17
7  8  18

Or using collections.defaultdict

from collections import defaultdict
new = defaultdict(list)

for d in data:
    for k, v in d.items():
        new[k].extend(v)

df = pd.DataFrame(new)

   A   B
0  1  11
1  2  12
2  3  13
3  4  14
4  5  15
5  6  16
6  7  17
7  8  18


问:
Use gpx file to calculate distance from google maps
I want to calculate distance from a collection of geo coordinates. I have converted this to a GPX file and I am able to use in HERE Maps to calculate distance.

Now, I want to use this in Google Maps as per my customer requirement. Is there any option in Google Maps which accepts GPX file and return distance ? I have seen distancematrix option and believe this is in different format.

答:
There are some parts here. The calculation based on Google Maps docs.

Notice that if you need only to calculate the distances, you don't need even google maps api. The calculation is based on the coordinates only.

Parse GPX file

GPX is basically an xml as well as html. So After you parse the content of the file using window.DOMParser().parseFromString(str, "text/xml")); you can use the DOM API (such as querySelector, querySelectorAll etc.) to retrieve all the trkpt element and extract their lat and lon values.

const coords = Array.from(xml.querySelectorAll("trkpt")).map(
  element =>
    new google.maps.LatLng(
      Number(element.getAttribute("lat")),
      Number(element.getAttribute("lon"))
    )
);
```

<p>I used <code>google.maps.LatLng</code> but you can store it in a plain object if you don't need it to interact with your map.</p>

<h3>Calculate the distances</h3>

<p>Iterate over the coordinates array and measure from one point to another.</p>

```function haversine_distance(coord1, coord2) {
  const R = 3958.8; // Radius of the Earth in miles
  const rlat1 = coord1.lat() * (Math.PI/180); // Convert degrees to radians
  const rlat2 = coord2.lat() * (Math.PI/180); // Convert degrees to radians
  const difflat = rlat2-rlat1; // Radian difference (latitudes)
  const difflon = (coord2.lng()-coord1.lng()) * (Math.PI/180); // Radian difference (longitudes)

  const d = 2 * R * Math.asin(Math.sqrt(Math.sin(difflat/2)*Math.sin(difflat/2)+Math.cos(rlat1)*Math.cos(rlat2)*Math.sin(difflon/2)*Math.sin(difflon/2)));
  return d;
}
```

<p>Then you can the function to build the distances array</p>

<pre class="lang-js prettyprint-override"><code>const distances = coords.reduce((old, ne, index, original) => {
  if (index > 0) {
    old.push(haversine_distance(ne, original[index - 1]));
  }
  return old;
}, []);
</code>```

https://codesandbox.io/s/elegant-turing-tvhu1?file=/index.html

Body:
There are some parts here. The calculation based on Google Maps docs.

Notice that if you need only to calculate the distances, you don't need even google maps api. The calculation is based on the coordinates only.

Parse GPX file

GPX is basically an xml as well as html. So After you parse the content of the file using window.DOMParser().parseFromString(str, "text/xml")); you can use the DOM API (such as querySelector, querySelectorAll etc.) to retrieve all the trkpt element and extract their lat and lon values.

const coords = Array.from(xml.querySelectorAll("trkpt")).map(
  element =>
    new google.maps.LatLng(
      Number(element.getAttribute("lat")),
      Number(element.getAttribute("lon"))
    )
);

I used google.maps.LatLng but you can store it in a plain object if you don't need it to interact with your map.

Calculate the distances

Iterate over the coordinates array and measure from one point to another.

function haversine_distance(coord1, coord2) {
  const R = 3958.8; // Radius of the Earth in miles
  const rlat1 = coord1.lat() * (Math.PI/180); // Convert degrees to radians
  const rlat2 = coord2.lat() * (Math.PI/180); // Convert degrees to radians
  const difflat = rlat2-rlat1; // Radian difference (latitudes)
  const difflon = (coord2.lng()-coord1.lng()) * (Math.PI/180); // Radian difference (longitudes)

  const d = 2 * R * Math.asin(Math.sqrt(Math.sin(difflat/2)*Math.sin(difflat/2)+Math.cos(rlat1)*Math.cos(rlat2)*Math.sin(difflon/2)*Math.sin(difflon/2)));
  return d;
}

Then you can the function to build the distances array

const distances = coords.reduce((old, ne, index, original) => {
  if (index > 0) {
    old.push(haversine_distance(ne, original[index - 1]));
  }
  return old;
}, []);

https://codesandbox.io/s/elegant-turing-tvhu1?file=/index.html


问:
How to send html mail with Content-ID header using mutt in command line
I was trying to send a html mail with images. But I am not familiar with mail headers, how can I add a image tag using cid, i.e. attach an image and make it shown in the html content?

```<code><img src="cid:x">
</code>```

This is my testing command:

mutt -s "test" jason@example.com \
    -e "set content_type=text/html" \
    -a /path/to/image <<MAIL

MAIL
```

答:
It seems that this is a new feature onging in neomutt project.
Currently there's no way to add Content-ID header for attachments.
See PR: https://github.com/neomutt/neomutt/pull/2049.

Body:
I was trying to send a html mail with images. But I am not familiar with mail headers, how can I add a image tag using cid, i.e. attach an image and make it shown in the html content?

This is my testing command:

mutt -s "test" jason@example.com \
    -e "set content_type=text/html" \
    -a /path/to/image <<MAIL

MAIL