问:
Warning that my Async function is actually running synchronously in VB.NET
My first time writing async code in VB.NET although I've done it in Java.

I have a WinForm with multiple combo boxes that need to be populated. The queries take about 12-14 seconds to finish, which is way too long to block the UI. So instead of populating them in the onLoad event handler directly, I'm calling an Async function that returns a DataTable.

My question is that Visual Studio (2019) is giving me a warning on the async functions saying that the method lacks an Await operator.  I've tried removing "Async" from the function and but this way works. More importantly it's still taking 12 seconds before the UI appears. Why am I getting the error?  How do I make it actually run the queries in the background? I've included the onLoad sub and the DataTable query function.

```<code>Private Async Sub Part_Entry_Form_Inventory_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    System.Diagnostics.Debug.WriteLine(System.Reflection.MethodInfo.GetCurrentMethod.Name & " starting @ " & DateTime.Now.ToString("hh:mm:ss.fff"))
    Me.TopMost = True
    Dim t1 = Await GetDataTable("SELECT BatchDate, Batchname
                             FROM [Inventory_Batches]
                             GROUP BY BatchDate, Batchname
                             ORDER BY BatchDate; ", "Batch")
    ChooseBatch.DataSource = t1
    ChooseBatch.DisplayMember = "BatchName"
    ChooseBatch.ValueMember = "BatchDate"
    ChooseBatch.SelectedIndex = -1

    Dim t2 = Await GetDataTable("SELECT CatID, CatName
                           FROM [Parts_Inventory_Owned_Parts_Query]
                           GROUP BY CatID, CatName
                           ORDER BY CatName;", "Category")
    ChooseCatName.DataSource = t2
    ChooseCatName.DisplayMember = "CatName"
    ChooseCatName.ValueMember = "CatID"
    ChooseCatName.SelectedIndex = -1

    Dim t3 = Await GetDataTable("SELECT PartID, PartID + ' | ' + [partName] AS PartString
                             FROM [Part_List]
                             GROUP BY PartID, PartID + ' | ' + [partName]
                             ORDER BY PartID;", "Part")
    ChoosePartNum.DataSource = t3
    ChoosePartNum.DisplayMember = "PartString"
    ChoosePartNum.ValueMember = "PartID"
    ChoosePartNum.SelectedIndex = -1

    Dim t4=Await GetDataTable("SELECT ColorID, ColorName
                               FROM [Color_List]
                               ORDER BY ColorName;","Color")
    ChooseColor.DataSource = t4
    ChooseColor.DisplayMember = "ColorName"
    ChooseColor.ValueMember = "ColorID"
    ChooseColor.SelectedIndex = -1

    Dim t5 = Await GetDataTable("SELECT LocationID, LocationName
                                 FROM [Inventory_Locations]
                                 WHERE LinkedToSet Is Null AND LinkedToOrder Is Null
                                 ORDER BY [LocationName];", "Location")
    ChooseLocation.DataSource = t5
    ChooseLocation.DisplayMember = "LocationName"
    ChooseLocation.ValueMember = "LocationID"
    ChooseLocation.SelectedIndex = -1
    System.Diagnostics.Debug.WriteLine(System.Reflection.MethodInfo.GetCurrentMethod.Name & " ending @ " & DateTime.Now.ToString("hh:mm:ss.fff"))
End Sub

Async Function GetDataTable(sql As String, title As String) As Task(Of DataTable)
    System.Diagnostics.Debug.WriteLine(System.Reflection.MethodInfo.GetCurrentMethod.Name & " " & title & " starting @ " & DateTime.Now.ToString("hh:mm:ss.fff"))
    Dim conn As New SqlConnection(My.Settings.partmanagerdataConnectionString)
    Dim cmd As New SqlCommand(sql, conn)
    Dim adapter As New SqlDataAdapter(cmd)
    Dim tbl As New DataTable()
    adapter.Fill(tbl)
    Return tbl
End Function
</code>```

The warning message appears as an underline highlighting each the function names (GetDataTable) and says,

BC42356: This async method lacks 'await' operators and will run
  synchronously. Consider using the 'await' operator to await
  non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work
  on a background thread

FWIW I also tried putting this in the MyBase.Shown handler and it's worse

答:
VB is complaining because you haven't used Await anywhere in GetDataTable yet you have declared it as Async

If you're coming from Java, async in the TAP sense should be easy to explain:

You know how, in Java you have to (or had to when I was coding it many years ago) declare that a method throws some exception and you have to be explicit about what it throws? The Async keyword is a bit like that. If you have a method in Java that throws, and you call it and you don't catch in that calling method then the calling method has to be declared as throws too.. and basically all the way up the call tree, if you never catch that exception your lowest-of-the-low method throws, then everything all the way up the tree to the very top (main) has to declare that it throws. Async as a modifier is similar; throughout your whole code if you mark something as Async, you mark everything else as Async all the way up the tree until you are outside your code.

You have to mark your method Async if you want to use await and should use Await if you want to properly wait on an async method. Microsoft provides the methods you're calling with dataAdapter.Fill and they aren't async, so you haven't actually called anything awaitable, so you haven't used Await, so vb is complaining that the GetDataTable is marked as async but doesn't await - just like Java would complain if you said a method throws SomeException when it doesn't.. So, if you're going to have your entire call tree be an async chain you either need to call an async method (and I don't think dataadapter has any) and await it, or you need to be the start of something async (Task.Run something synchronous) and await it (or return the Task so that something else can await it, but then you don't need the async modifier)

Awaiting async is a bit like throwing an uncaught exception; if you throw an exception your code stops where it is, picks up its ball and goes home up the call tree and out into code that is someone else's problem. Awaiting async behaves the same way, packing everything into a state machine (saving state) and going back up the tree til it disappears out of your code and the thread (probably a UI thread) goes back to what it was doing before (probably drawing a UI), making the app appear responsive/not hung. When the Task (returned by the async call you called in the lowest-low method) you're Awaiting on completes, the thread returns to where it left off, the saved state is loaded and things proceed as if the whole op was syncronous, it's just that in the interim while we were waiting the thread that kicked things off was free to go back to what it was doing before

In terms of what to do in your situation, you're probably going to have to do something like this in GetDataTable if you plan on doing any work inside GetDataTable after this completes:

```<code>Await Task.Run(Sub() adapter.Fill(x) )
</code>```

Or this (called eliding - see Stephen Cleary's blog for more info), if you don't do any work afterwards and you're not inside a Using block:

```<code>Return Task.Run(Sub() adapter.Fill(x) )
</code>```

You skip marking the method as Async if you straight up return a Task, because Async is used to let the compiler know "this method will do some work, and await something and do more work, so it needs to be able to save state so it can come back". Returning a Task doesn't need to save state; awaiting a task and doing something afterwards needs to save state, so the calling method will probably be the one to do this

But consider also, instead of awaiting the first fill, then awaiting the second, then the third.. You could instead not await each one in turn but instead collect all your tasks (you're returned a Task when you Task.Run a syncronous method) for your various operations into a collection of Tasks, and then Await Task.WhenAll(theListOfTasks). This means the tasks all start going simultaneously, when they are run and your code waits on all of them (essentially waiting on whichever turns out to be the longest one) and your code resumes executing when the last task finishes. Depending on how your database copes with the sudden influx of these multiple queries it might cut down that wait time a bit

Side note; when you write code that behaves in an Async way, name the method with an Async suffix, e.g. GetDataTableAsync - remember that it's more the case that "functions that can be used asyncy/be awaited should be named ...Async" rather than "functions that have the Async modifier should be named ...Async" - there's a subtle difference

Body:
My first time writing async code in VB.NET although I've done it in Java.

I have a WinForm with multiple combo boxes that need to be populated. The queries take about 12-14 seconds to finish, which is way too long to block the UI. So instead of populating them in the onLoad event handler directly, I'm calling an Async function that returns a DataTable.

My question is that Visual Studio (2019) is giving me a warning on the async functions saying that the method lacks an Await operator.  I've tried removing "Async" from the function and but this way works. More importantly it's still taking 12 seconds before the UI appears. Why am I getting the error?  How do I make it actually run the queries in the background? I've included the onLoad sub and the DataTable query function.

Private Async Sub Part_Entry_Form_Inventory_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    System.Diagnostics.Debug.WriteLine(System.Reflection.MethodInfo.GetCurrentMethod.Name & " starting @ " & DateTime.Now.ToString("hh:mm:ss.fff"))
    Me.TopMost = True
    Dim t1 = Await GetDataTable("SELECT BatchDate, Batchname
                             FROM [Inventory_Batches]
                             GROUP BY BatchDate, Batchname
                             ORDER BY BatchDate; ", "Batch")
    ChooseBatch.DataSource = t1
    ChooseBatch.DisplayMember = "BatchName"
    ChooseBatch.ValueMember = "BatchDate"
    ChooseBatch.SelectedIndex = -1

    Dim t2 = Await GetDataTable("SELECT CatID, CatName
                           FROM [Parts_Inventory_Owned_Parts_Query]
                           GROUP BY CatID, CatName
                           ORDER BY CatName;", "Category")
    ChooseCatName.DataSource = t2
    ChooseCatName.DisplayMember = "CatName"
    ChooseCatName.ValueMember = "CatID"
    ChooseCatName.SelectedIndex = -1

    Dim t3 = Await GetDataTable("SELECT PartID, PartID + ' | ' + [partName] AS PartString
                             FROM [Part_List]
                             GROUP BY PartID, PartID + ' | ' + [partName]
                             ORDER BY PartID;", "Part")
    ChoosePartNum.DataSource = t3
    ChoosePartNum.DisplayMember = "PartString"
    ChoosePartNum.ValueMember = "PartID"
    ChoosePartNum.SelectedIndex = -1

    Dim t4=Await GetDataTable("SELECT ColorID, ColorName
                               FROM [Color_List]
                               ORDER BY ColorName;","Color")
    ChooseColor.DataSource = t4
    ChooseColor.DisplayMember = "ColorName"
    ChooseColor.ValueMember = "ColorID"
    ChooseColor.SelectedIndex = -1

    Dim t5 = Await GetDataTable("SELECT LocationID, LocationName
                                 FROM [Inventory_Locations]
                                 WHERE LinkedToSet Is Null AND LinkedToOrder Is Null
                                 ORDER BY [LocationName];", "Location")
    ChooseLocation.DataSource = t5
    ChooseLocation.DisplayMember = "LocationName"
    ChooseLocation.ValueMember = "LocationID"
    ChooseLocation.SelectedIndex = -1
    System.Diagnostics.Debug.WriteLine(System.Reflection.MethodInfo.GetCurrentMethod.Name & " ending @ " & DateTime.Now.ToString("hh:mm:ss.fff"))
End Sub

Async Function GetDataTable(sql As String, title As String) As Task(Of DataTable)
    System.Diagnostics.Debug.WriteLine(System.Reflection.MethodInfo.GetCurrentMethod.Name & " " & title & " starting @ " & DateTime.Now.ToString("hh:mm:ss.fff"))
    Dim conn As New SqlConnection(My.Settings.partmanagerdataConnectionString)
    Dim cmd As New SqlCommand(sql, conn)
    Dim adapter As New SqlDataAdapter(cmd)
    Dim tbl As New DataTable()
    adapter.Fill(tbl)
    Return tbl
End Function

The warning message appears as an underline highlighting each the function names (GetDataTable) and says,

BC42356: This async method lacks 'await' operators and will run
  synchronously. Consider using the 'await' operator to await
  non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work
  on a background thread

FWIW I also tried putting this in the MyBase.Shown handler and it's worse

Body:
VB is complaining because you haven't used Await anywhere in GetDataTable yet you have declared it as Async

If you're coming from Java, async in the TAP sense should be easy to explain:

You know how, in Java you have to (or had to when I was coding it many years ago) declare that a method throws some exception and you have to be explicit about what it throws? The Async keyword is a bit like that. If you have a method in Java that throws, and you call it and you don't catch in that calling method then the calling method has to be declared as throws too.. and basically all the way up the call tree, if you never catch that exception your lowest-of-the-low method throws, then everything all the way up the tree to the very top (main) has to declare that it throws. Async as a modifier is similar; throughout your whole code if you mark something as Async, you mark everything else as Async all the way up the tree until you are outside your code.

You have to mark your method Async if you want to use await and should use Await if you want to properly wait on an async method. Microsoft provides the methods you're calling with dataAdapter.Fill and they aren't async, so you haven't actually called anything awaitable, so you haven't used Await, so vb is complaining that the GetDataTable is marked as async but doesn't await - just like Java would complain if you said a method throws SomeException when it doesn't.. So, if you're going to have your entire call tree be an async chain you either need to call an async method (and I don't think dataadapter has any) and await it, or you need to be the start of something async (Task.Run something synchronous) and await it (or return the Task so that something else can await it, but then you don't need the async modifier)

Awaiting async is a bit like throwing an uncaught exception; if you throw an exception your code stops where it is, picks up its ball and goes home up the call tree and out into code that is someone else's problem. Awaiting async behaves the same way, packing everything into a state machine (saving state) and going back up the tree til it disappears out of your code and the thread (probably a UI thread) goes back to what it was doing before (probably drawing a UI), making the app appear responsive/not hung. When the Task (returned by the async call you called in the lowest-low method) you're Awaiting on completes, the thread returns to where it left off, the saved state is loaded and things proceed as if the whole op was syncronous, it's just that in the interim while we were waiting the thread that kicked things off was free to go back to what it was doing before

In terms of what to do in your situation, you're probably going to have to do something like this in GetDataTable if you plan on doing any work inside GetDataTable after this completes:

Await Task.Run(Sub() adapter.Fill(x) )

Or this (called eliding - see Stephen Cleary's blog for more info), if you don't do any work afterwards and you're not inside a Using block:

Return Task.Run(Sub() adapter.Fill(x) )

You skip marking the method as Async if you straight up return a Task, because Async is used to let the compiler know "this method will do some work, and await something and do more work, so it needs to be able to save state so it can come back". Returning a Task doesn't need to save state; awaiting a task and doing something afterwards needs to save state, so the calling method will probably be the one to do this

But consider also, instead of awaiting the first fill, then awaiting the second, then the third.. You could instead not await each one in turn but instead collect all your tasks (you're returned a Task when you Task.Run a syncronous method) for your various operations into a collection of Tasks, and then Await Task.WhenAll(theListOfTasks). This means the tasks all start going simultaneously, when they are run and your code waits on all of them (essentially waiting on whichever turns out to be the longest one) and your code resumes executing when the last task finishes. Depending on how your database copes with the sudden influx of these multiple queries it might cut down that wait time a bit

Side note; when you write code that behaves in an Async way, name the method with an Async suffix, e.g. GetDataTableAsync - remember that it's more the case that "functions that can be used asyncy/be awaited should be named ...Async" rather than "functions that have the Async modifier should be named ...Async" - there's a subtle difference


来源: stackexchange

问:
How to make the input and output color different in Terminal?
In Pycharm-run, the input text color is always green and Italic while the output is always in plain text in white, which really helps me to distinguish the input from the output. How do I do that in Linux terminal or in VSCode? </p>

答: I use Linux mint and i can easily change the color of font , color of palette, output color, size and all by opening the terminal -> Edit -> Preferences. It has all the options .I hope this helps.</p>

ContentLicense: CC BY-SA 4.0


问:
How to store the address of the variable without pointer
how can we store the address of the variable without using the pointer?</p>

```<code>#include<stdio.h>
int main ()
{
    double sum;
    double x= ∑

    printf("\n %lf",x);
}
</code>```

答:
You did it almost right. But you stored it in a double, the memory address of a variable can be 4 bytes, or 8 bytes, depending on the implementation. You should always cast to a wider type though. Right now, storing it in a double may cause loss of information.

You'll need to use a data type wide enough. You could use an unsigned long long, however for cross platform compatibility, I recommend using uint64_t from stdint.h instead. And also the accompanying inttypes.h.

#include<stdio.h>
#include<stdint.h>
#include<inttypes.h>

int main()
{
    double sum;
    uint64_t x = (uint64_t) ∑

    printf("%" PRIx64 "\n", x);
}
```

This ensures that you use an unsigned 64 bit (8 byte) variable so you do not lose information.

Also print using the PRIx64 format specifier for getting output in 64 bit hexadecimal form.

Do note however, this is only good for printing the address, and address only. This really does not serve any practical purpose.

Body:
how can we store the address of the variable without using the pointer?

#include<stdio.h>
int main ()
{
    double sum;
    double x= ∑

    printf("\n %lf",x);
}

Body:
You did it almost right. But you stored it in a double, the memory address of a variable can be 4 bytes, or 8 bytes, depending on the implementation. You should always cast to a wider type though. Right now, storing it in a double may cause loss of information.

You'll need to use a data type wide enough. You could use an unsigned long long, however for cross platform compatibility, I recommend using uint64_t from stdint.h instead. And also the accompanying inttypes.h.

#include<stdio.h>
#include<stdint.h>
#include<inttypes.h>

int main()
{
    double sum;
    uint64_t x = (uint64_t) &sum;

    printf("%" PRIx64 "\n", x);
}

This ensures that you use an unsigned 64 bit (8 byte) variable so you do not lose information.

Also print using the PRIx64 format specifier for getting output in 64 bit hexadecimal form.

Do note however, this is only good for printing the address, and address only. This really does not serve any practical purpose.


问:
Starship symbols in Powershell
Is it at all possible to get a nice look, with symbols, with starship in PowerShell?
I've tried everything imaginable to get Fira Code font to show symbols in the console but always end up with ?? instead.

I know that the font is installed properly, because i can use Fira Code in notepad and other apps. But even when i select the correct font for PowerShell, it won't show any symbols. I've enabled the "Use unicode for world-wide language support" in Windows 10, and running chcp in Powershell returns Active code page: 65001.

Has anyone actually succeeded with this? Works great in Macos and Ubuntu, but i cannot get it right in Powershell. And by the way, i've tried both Powershell and Powershell Core.

答:
Fira Code seems to work fine in Windows Terminal, you just need to update the profile settings for your PowerShell(s):

```<code>"profiles":
[
    {
        "guid": "{574e775e-4f2a-5b96-ac1e-a2962a402336}",
        "hidden": false,
        "name": "PowerShell",
        "source": "Windows.Terminal.PowershellCore",
        "fontFace": "Fira Code",
        "fontSize": 16
    }

]
</code>```

Title: Starship symbols in Powershell

Body:
Fira Code seems to work fine in Windows Terminal, you just need to update the profile settings for your PowerShell(s):

"profiles":
[
    {
        "guid": "{574e775e-4f2a-5b96-ac1e-a2962a402336}",
        "hidden": false,
        "name": "PowerShell",
        "source": "Windows.Terminal.PowershellCore",
        "fontFace": "Fira Code",
        "fontSize": 16
    }

]


问:
Java HTTP getResponseCode returns 200 for non-existent URL
I was expecting this code to return a 404, however it produces the output :

"Response code is 200"

Would it be possible to learn how to differentiate between existent and non-existent web pages . . . thanks so much,

```<code>    try
    {
    // create the HttpURLConnection
    URL url = new URL("http://www.thisurldoesnotexist");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    System.out.println("Response code is " + connection.getResponseCode());
    }
</code>```

答:
You could:

Resolve the IP from the host of the page

Try to connect to port 80 on the resolved IP using plain sockets

This is a bit low level however and will add complexity since you will need to make a simple GET request through the socket. Then validate the response so you're sure that its actually a HTTP server running on port 80.

NMap might be able to help you here.

ContentLicense: CC BY-SA 3.0

Body:
I was expecting this code to return a 404, however it produces the output :

"Response code is 200"

Would it be possible to learn how to differentiate between existent and non-existent web pages . . . thanks so much,

    try
    {
    // create the HttpURLConnection
    URL url = new URL("http://www.thisurldoesnotexist");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    System.out.println("Response code is " + connection.getResponseCode());
    }


问:
Extract co-linear columns name - R
Based on the answer for this question and its script, how can I print to the console the co-linear columns names?

Script:

```<code>library(corrplot)
library(caret)

x <- seq(0, 100, 1)
# colinear with x
y <- x + 2.3
# almost colinear with x / some small gaussian noise
z <- x + rnorm(mean = 0, sd = 5, n = 101)
# uncorrrelated gaussian
w <- rnorm(mean = 0, sd = 1, n = 101)
a <- z+seq(101, 200, 1)/.33 + rnorm(mean = 0, sd = 5, n = 1001)
b <- a -2.3

# this frame is made to exemplify the procedure
df <- data.frame(x = x, y = y, z = z, w = w, a=a, b=b)

corrplot(cor(df))
#drop perfectly multicollinear variables
constant<-rep(1,nrow(df))
tmp<-lm(constant ~ ., data=df)
to_keep<-tmp$coefficients[!is.na(tmp$coefficients)]
to_keep<-names(to_keep[-which(names(to_keep) == "(Intercept)")])
df_result<-df[to_keep]
corrplot(cor(df_result))
</code>```

答:
You want the variables not included in to_keep. Based off how to_keep is defined, you can write to_drop <- tmp$coefficients[is.na(tmp$coefficients)] to get the coefficients with NA values (meaning there are no estimates for the corresponding variables because they are collinear with others). Then, to print the names of those coefficients, you can simply do print(names(to_drop)).

However, keep in mind that: 1. this will only drop perfectly collinear variables in a hacky way and 2. the way this method decides which variables out of a set of perfectly collinear variables to drop is rather arbitrary (it will depend on the other of variables in your data).

Title: Extract co-linear columns name - R

Body:
Based on the answer for this question and its script, how can I print to the console the co-linear columns names?

Script:

library(corrplot)
library(caret)

x <- seq(0, 100, 1)
# colinear with x
y <- x + 2.3
# almost colinear with x / some small gaussian noise
z <- x + rnorm(mean = 0, sd = 5, n = 101)
# uncorrrelated gaussian
w <- rnorm(mean = 0, sd = 1, n = 101)
a <- z+seq(101, 200, 1)/.33 + rnorm(mean = 0, sd = 5, n = 1001)
b <- a -2.3

# this frame is made to exemplify the procedure
df <- data.frame(x = x, y = y, z = z, w = w, a=a, b=b)

corrplot(cor(df))
#drop perfectly multicollinear variables
constant<-rep(1,nrow(df))
tmp<-lm(constant ~ ., data=df)
to_keep<-tmp$coefficients[!is.na(tmp$coefficients)]
to_keep<-names(to_keep[-which(names(to_keep) == "(Intercept)")])
df_result<-df[to_keep]
corrplot(cor(df_result))


问:
Flutter - How do I toggle the color of a RaisedButton on click depending on the value of an if and else statement
I am creating a logo quiz, and the color of the button shall change on press to green if the user choose the right answer or red otherwise. I have tried to solve this using this question Flutter - How do I toggle the color of a RaisedButton upon click? but it did not help much, the color would stay the same on press for the next question which is not what I am looking for. Please help.</p>

```<code>var pressAttention = false;
Padding(
                    padding: const EdgeInsets.only(bottom: 10.0),
                    child: ButtonTheme(
                      minWidth: 300.0,
                      height: 50.0,
                      child: RaisedButton(
                        child: Text(
                          multiChoice[count][0],
                          style: TextStyle(
                            fontSize: 20,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        color: Colors.white,
                        shape: RoundedRectangleBorder(
                          borderRadius: new BorderRadius.circular(30.0),
                          side: BorderSide(color: Colors.black),
                        ),
                        onPressed: () {
                          setState(() {
                            // checking if the user got the right answer
                            if (correctAnswer[count] == 0) {
                              correctAnswerCount++;
                              // do something to change the color of the button to green
                              // pressAttention = !pressAttention
                            }else{
                              // do something to change the color of the button to red
                            }
                          });
                          nextQuestion();
                        },
                        highlightColor: pressAttention ? Colors.green : Colors.red, //changing to green or red depending on the if and else statement,
                        hoverColor: pressAttention ? Colors.green : Colors.red, //changing to green or red depending on the if and else statement,
                      ),
                    ),
                  ),
</code>```

答:
Use a list to store the answers, and check if the answer matches the users answer. If it does then set the color only.

Set the color when the user changes question or answers the question.

Body:
I am creating a logo quiz, and the color of the button shall change on press to green if the user choose the right answer or red otherwise. I have tried to solve this using this question Flutter - How do I toggle the color of a RaisedButton upon click? but it did not help much, the color would stay the same on press for the next question which is not what I am looking for. Please help.

var pressAttention = false;
Padding(
                    padding: const EdgeInsets.only(bottom: 10.0),
                    child: ButtonTheme(
                      minWidth: 300.0,
                      height: 50.0,
                      child: RaisedButton(
                        child: Text(
                          multiChoice[count][0],
                          style: TextStyle(
                            fontSize: 20,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        color: Colors.white,
                        shape: RoundedRectangleBorder(
                          borderRadius: new BorderRadius.circular(30.0),
                          side: BorderSide(color: Colors.black),
                        ),
                        onPressed: () {
                          setState(() {
                            // checking if the user got the right answer
                            if (correctAnswer[count] == 0) {
                              correctAnswerCount++;
                              // do something to change the color of the button to green
                              // pressAttention = !pressAttention
                            }else{
                              // do something to change the color of the button to red
                            }
                          });
                          nextQuestion();
                        },
                        highlightColor: pressAttention ? Colors.green : Colors.red, //changing to green or red depending on the if and else statement,
                        hoverColor: pressAttention ? Colors.green : Colors.red, //changing to green or red depending on the if and else statement,
                      ),
                    ),
                  ),


问:
String encryption - generate unique pattern like Spotify codes
Yesterday I've read the question Algorithm to create costum Template/Code from String. Because the question was not formulated that well it was downvoted just instantly. However, the question itself was in my opinion not that bad, so I decided to ask a hopefully better version of this question again.

Ok, Im wondering how's the string encryption e.g. of the new Spotify codes is working. See the image below:

I would be super interested in the extent to which it is possible to implement something like this pattern-encryption in javascript.

The Spotify codes - I've already mentioned above - are structured in a row that is divided into different sized bars.

So let's say there is a row that is divided into 24 bars and all of the bars can have the size '3', '5', '7' or '9'.

```<code> string = 'hello'   -->  pattern = '3,3,5,7,9,3,7,9,9,3,3,5,3,9,5,3,3,7,5,9,3,9,3,9'
</code>```

What's a good method / easy way to translate a string (lets say 5 characters) into a unique pattern, that afterwards is also convertible back and read as a string?

This is my code I've developed till now, but in this code I used a key-array that includes 10 different possibilities (--> bar sizes) , but I just like to us 4 different sizes.

Explanation:

I' converting my string 'hello' to binary format and splitting the string up into groups of maximum 3 to get something like this: ['001', '110', '0'].

Afterwards I'm using the result array above and find the matches in my Key-array below and get the indexes (10 different indexed --> 10 different possibilities) and use them as bar-sizes.

But, There MUST BE a way more efficient method to translate a string into a unique pattern. I hope somebody can help me improve my small algorithm. Thanks a million in advance.

var key = ['0', '1', '000','001','010','100','110','101','011','111']

String.prototype.encode = function() {
  var code = this, result = [],encryped_string=[]
  for (var i=0; i<code.length;i++) result.push(code[i].charCodeAt(0).toString(2).match(/.{1,3}/g));
  for (var i=0; i<result.length; i++) for (var j=0; j<result[i].length; j++) encryped_string.push(key.indexOf(result[i][j]))
  return encryped_string
}

var code = 'hello';
console.log(code.encode())```

答:
Update: I asked a similar question and it was answered by someone linking the patent for this barcode. To summarize, they use an intermediate look-up-table to link the barcode to the unique Spotify ID.

I have been digging into Spotify Codes some to try and understand them.

Spotify has URIs for each song, album, artists, user, playlist, etc. They look something like this:

spotify:playlist:37i9dQZF1DXcBWIGoYBM5M

If you visit Spotify Codes you can generate a code from the URI. The code for the above URI looks like this:

As you noted, they encode the information in the heights of each of the bars, in the same way that the United States Postal Service does in their barcodes (see Intelligent Mail barcode).

The bars in Spotify Codes have 8 different heights they can be. The logo is the max height, and the first and the last bars are always the lowest height. In the image above, the max height is 96 pixels, and the bars fall into 8 different height bins: [96, 84, 74, 62, 52, 40, 28, 18].

Using this (sort of messy Python) code I can grab the octal sequence from the barcode image:

```<code>from skimage import io
from skimage.filters import threshold_otsu
from skimage.measure import label, regionprops
from skimage.morphology import square
from skimage.color import label2rgb, rgb2gray

def get_sequence(filename):
    image = io.imread(filename)
    image = rgb2gray(image)
    b_and_w = image > threshold_otsu(image)
    labeled = label(b_and_w)
    bar_dims = [r.bbox for r in regionprops(labeled)]
    bar_dims.sort(key=lambda x: x[1], reverse=False)
    spotify_logo = bar_dims[0]
    max_height = spotify_logo[2] - spotify_logo[0]
    sequence = []
    for bar in bar_dims[1:]:
        height = bar[2] - bar[0]
        ratio = height / max_height
        if ratio < 0.25:
            sequence.append(0)
        elif ratio < 0.33:
            sequence.append(1)
        elif ratio < 0.46:
            sequence.append(2)
        elif ratio < 0.5625:
            sequence.append(3)
        elif ratio < 0.677:
            sequence.append(4)
        elif ratio < 0.8:
            sequence.append(5)
        elif ratio < 0.9:
            sequence.append(6)
        elif ratio < 1.1:
            sequence.append(7)
        else:
            raise ValueError('ratio is too high')
    return sequence
</code>```

The sequence maps like this: 37i9dQZF1DXcBWIGoYBM5M -> [0, 6, 0, 2, 4, 5, 1, 4, 5, 2, 3, 7, 3, 7, 1, 5, 6, 2, 5, 7, 4, 3, 0]

The weird thing about this is the amount of information in the URI and the spotify code do not match up. The URI is 22 characters long, and contains 0-9 a-z A-Z. This means 62^22 potential URIs, or 2.7 e39. There are 23 bars in the spotify code, but the first and last are always 0, so there are only 21 usable bars. This means 8^21 or 9.22 e18 potential codes. The URI to code mapping is not straightforward since there is not 1 code to 1 URI.

I do not know how they map the URIs to the codes. My guess would be that they have a separate database/lookup table that they use to map the codes to URIs. When creating a code, they hash the URI to a code and store that to look up later. When someone looks up a code, they check that database and map it to the URI. Since there are so many more potential URIs, they just don't ever get used and they don't have to worry about them.

Body:
Yesterday I've read the question Algorithm to create costum Template/Code from String. Because the question was not formulated that well it was downvoted just instantly. However, the question itself was in my opinion not that bad, so I decided to ask a hopefully better version of this question again.

Ok, Im wondering how's the string encryption e.g. of the new Spotify codes is working. See the image below:

I would be super interested in the extent to which it is possible to implement something like this pattern-encryption in javascript.

The Spotify codes - I've already mentioned above - are structured in a row that is divided into different sized bars.

So let's say there is a row that is divided into 24 bars and all of the bars can have the size '3', '5', '7' or '9'.

 string = 'hello'   -->  pattern = '3,3,5,7,9,3,7,9,9,3,3,5,3,9,5,3,3,7,5,9,3,9,3,9'

What's a good method / easy way to translate a string (lets say 5 characters) into a unique pattern, that afterwards is also convertible back and read as a string?

This is my code I've developed till now, but in this code I used a key-array that includes 10 different possibilities (--> bar sizes) , but I just like to us 4 different sizes.

Explanation:

I' converting my string 'hello' to binary format and splitting the string up into groups of maximum 3 to get something like this: ['001', '110', '0'].

Afterwards I'm using the result array above and find the matches in my Key-array below and get the indexes (10 different indexed --> 10 different possibilities) and use them as bar-sizes.

But, There MUST BE a way more efficient method to translate a string into a unique pattern. I hope somebody can help me improve my small algorithm. Thanks a million in advance.

var key = ['0', '1', '000','001','010','100','110','101','011','111']

String.prototype.encode = function() {
  var code = this, result = [],encryped_string=[]
  for (var i=0; i<code.length;i++) result.push(code[i].charCodeAt(0).toString(2).match(/.{1,3}/g));
  for (var i=0; i<result.length; i++) for (var j=0; j<result[i].length; j++) encryped_string.push(key.indexOf(result[i][j]))
  return encryped_string
}

var code = 'hello';
console.log(code.encode())

Body:
Update: I asked a similar question and it was answered by someone linking the patent for this barcode. To summarize, they use an intermediate look-up-table to link the barcode to the unique Spotify ID.

I have been digging into Spotify Codes some to try and understand them.

Spotify has URIs for each song, album, artists, user, playlist, etc. They look something like this:

spotify:playlist:37i9dQZF1DXcBWIGoYBM5M

If you visit Spotify Codes you can generate a code from the URI. The code for the above URI looks like this:

As you noted, they encode the information in the heights of each of the bars, in the same way that the United States Postal Service does in their barcodes (see Intelligent Mail barcode).

The bars in Spotify Codes have 8 different heights they can be. The logo is the max height, and the first and the last bars are always the lowest height. In the image above, the max height is 96 pixels, and the bars fall into 8 different height bins: [96, 84, 74, 62, 52, 40, 28, 18].

Using this (sort of messy Python) code I can grab the octal sequence from the barcode image:

from skimage import io
from skimage.filters import threshold_otsu
from skimage.measure import label, regionprops
from skimage.morphology import square
from skimage.color import label2rgb, rgb2gray

def get_sequence(filename):
    image = io.imread(filename)
    image = rgb2gray(image)
    b_and_w = image > threshold_otsu(image)
    labeled = label(b_and_w)
    bar_dims = [r.bbox for r in regionprops(labeled)]
    bar_dims.sort(key=lambda x: x[1], reverse=False)
    spotify_logo = bar_dims[0]
    max_height = spotify_logo[2] - spotify_logo[0]
    sequence = []
    for bar in bar_dims[1:]:
        height = bar[2] - bar[0]
        ratio = height / max_height
        if ratio < 0.25:
            sequence.append(0)
        elif ratio < 0.33:
            sequence.append(1)
        elif ratio < 0.46:
            sequence.append(2)
        elif ratio < 0.5625:
            sequence.append(3)
        elif ratio < 0.677:
            sequence.append(4)
        elif ratio < 0.8:
            sequence.append(5)
        elif ratio < 0.9:
            sequence.append(6)
        elif ratio < 1.1:
            sequence.append(7)
        else:
            raise ValueError('ratio is too high')
    return sequence

The sequence maps like this: 37i9dQZF1DXcBWIGoYBM5M -> [0, 6, 0, 2, 4, 5, 1, 4, 5, 2, 3, 7, 3, 7, 1, 5, 6, 2, 5, 7, 4, 3, 0]

The weird thing about this is the amount of information in the URI and the spotify code do not match up. The URI is 22 characters long, and contains 0-9 a-z A-Z. This means 62^22 potential URIs, or 2.7 e39. There are 23 bars in the spotify code, but the first and last are always 0, so there are only 21 usable bars. This means 8^21 or 9.22 e18 potential codes. The URI to code mapping is not straightforward since there is not 1 code to 1 URI.

I do not know how they map the URIs to the codes. My guess would be that they have a separate database/lookup table that they use to map the codes to URIs. When creating a code, they hash the URI to a code and store that to look up later. When someone looks up a code, they check that database and map it to the URI. Since there are so many more potential URIs, they just don't ever get used and they don't have to worry about them.


问:
How to decrement items in array Incrementally based on the given quantity in Javascript
I have this sample array of objects

```<code>   mangoes:[
      { quantity:5},
      { quantity:8},
      { quantity:13},
      { quantity:4}
    ]
</code>```

When I remove x mangoes, that x should be subtracted from the first element in the array, and if that x exceed the first element then it should reduce the remained quantity in the second item in the array...and so forth.

This is to say, I need the quantity to be reduced starting from the first one in the array down to the second if it exceed, to the third etc..

For example, If I buy 2 mangoes, It should minus 2 in the first array element and the resulting mangoes array should be

```<code>   mangoes:[
      { quantity:3},
      { quantity:8},
      { quantity:13},
      { quantity:4}
    ]
</code>```

On the other hand, If I would have bought 7 mangoes, it should reduce all 5 from first array element and then remove 2 mangoes from the second element...and hence the final array would be like this below

```<code>   mangoes:[
      { quantity:0},
      { quantity:6},
      { quantity:13},
      { quantity:4}
    ]
</code>```

By Using Javascript, how can I achieve this?

WHAT I HAVE TRIED

I have tried like this below, It works only for the first element(case) when the x is less, but for other case it doesn't work;

```<code>var x = 2
var done = false

mangoes.forEach(function (item,i) {

  if(mangoes[i].quantity>=x && !done){
    item.quantity = mangoes[i].quantity - x
    done = true
  }

})
</code>```

答:
You can achieve that with forEach this way. But I wouldn't recommend it because even if a quantity is found to be greater than the value to be deducted, it will still loop through the whole item list as you can't break out of a forEach loop

  var mangoes = [
      { quantity:0},
      { quantity:6},
      { quantity:13},
      { quantity:4}
    ];

var x = 2
var done = false

mangoes.forEach(function (item,i) {

 if(item.quantity< x){
   item.quantity = 0;
   x = x- item.quantity;
  }else{
   item.quantity = item.quantity-x;
   x=0;
  }

});
console.log(mangoes)```
</div>
</div>
</p>

<p>However, I would recommend using <code>for..of..loop</code> so that you could conditionally break out of the loop, i.e if the quantity is found to be greater than the ones to be deducted, just deduct and break out of the loop. There's no need of further iteration.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>  var mangoes = [
      { quantity:5},
      { quantity:6},
      { quantity:13},
      { quantity:4}
    ];

var x = 1
var done = false

for(let i of mangoes){
  if(i.quantity >= x){
    i.quantity  = i.quantity -x;
    x = x - i.quantity;
    break;
  }else{
    x = x - i.quantity;
    i.quantity = 0;
  }
}

console.log(mangoes)</code>```

Body:
I have this sample array of objects

   mangoes:[
      { quantity:5},
      { quantity:8},
      { quantity:13},
      { quantity:4}
    ]

When I remove x mangoes, that x should be subtracted from the first element in the array, and if that x exceed the first element then it should reduce the remained quantity in the second item in the array...and so forth.

This is to say, I need the quantity to be reduced starting from the first one in the array down to the second if it exceed, to the third etc..

For example, If I buy 2 mangoes, It should minus 2 in the first array element and the resulting mangoes array should be

   mangoes:[
      { quantity:3},
      { quantity:8},
      { quantity:13},
      { quantity:4}
    ]

On the other hand, If I would have bought 7 mangoes, it should reduce all 5 from first array element and then remove 2 mangoes from the second element...and hence the final array would be like this below

   mangoes:[
      { quantity:0},
      { quantity:6},
      { quantity:13},
      { quantity:4}
    ]

By Using Javascript, how can I achieve this?

WHAT I HAVE TRIED

I have tried like this below, It works only for the first element(case) when the x is less, but for other case it doesn't work;

var x = 2
var done = false

mangoes.forEach(function (item,i) {

  if(mangoes[i].quantity>=x && !done){
    item.quantity = mangoes[i].quantity - x
    done = true
  }

})

Body:
You can achieve that with forEach this way. But I wouldn't recommend it because even if a quantity is found to be greater than the value to be deducted, it will still loop through the whole item list as you can't break out of a forEach loop

  var mangoes = [
      { quantity:0},
      { quantity:6},
      { quantity:13},
      { quantity:4}
    ];

var x = 2
var done = false

mangoes.forEach(function (item,i) {

 if(item.quantity< x){
   item.quantity = 0;
   x = x- item.quantity;
  }else{
   item.quantity = item.quantity-x;
   x=0;
  }

});
console.log(mangoes)

However, I would recommend using for..of..loop so that you could conditionally break out of the loop, i.e if the quantity is found to be greater than the ones to be deducted, just deduct and break out of the loop. There's no need of further iteration.

  var mangoes = [
      { quantity:5},
      { quantity:6},
      { quantity:13},
      { quantity:4}
    ];

var x = 1
var done = false

for(let i of mangoes){
  if(i.quantity >= x){
    i.quantity  = i.quantity -x;
    x = x - i.quantity;
    break;
  }else{
    x = x - i.quantity;
    i.quantity = 0;
  }
}

console.log(mangoes)


问:
Export more than one variable in ES6?
I'm trying to export more than one variable in ES6:

exports.js

```<code>var TestObject = Parse.Object.extend('TestObject')
var Post = Parse.Object.extend('Post')

export default TestObject
export Post
</code>```

main.js:

```<code>import TestObject from '../store'
import Post from '../store'

var testObject = new TestObject() // use Post in the same way
testObject.save(json).then(object => {
  console.log('yay! it worked', object)
})
</code>```

I understand that there's only one default value so I only used default in the first item.

However, I get this error message:

```<code>Module build failed: SyntaxError: /home/alex/node/my-project/src/store/index.js: Unexpected token (9:7)
   7 |
   8 | export default TestObject
>  9 | export Post
</code>```

Maybe I'm doing it the wrong way?

答:
export default
export {}

the name by which you are exporting must be same while importing.

You can also use * while importing .

Title: Export more than one variable in ES6?

Body:
I'm trying to export more than one variable in ES6:

exports.js

var TestObject = Parse.Object.extend('TestObject')
var Post = Parse.Object.extend('Post')

export default TestObject
export Post

main.js:

import TestObject from '../store'
import Post from '../store'

var testObject = new TestObject() // use Post in the same way
testObject.save(json).then(object => {
  console.log('yay! it worked', object)
})

I understand that there's only one default value so I only used default in the first item.

However, I get this error message:

Module build failed: SyntaxError: /home/alex/node/my-project/src/store/index.js: Unexpected token (9:7)
   7 |
   8 | export default TestObject
>  9 | export Post

Maybe I'm doing it the wrong way?


问:
tput cup in python on the commandline
Is there an elegant solution to do this shell script in Python without importing os ?

```<code>    tput cup 14 15; echo -ne "\033[1;32mtest\033[0m" ; tput cup 50 0
</code>```

This just has been gnawing in my mind for some time now :)

Thanks

答:
Thanks Ignacio Vazquez-Abrams for your input, it was a great push in the right direction.
In the end i came up with this little code that will help me conquer the world :)

```<code>from curses import *
setupterm()

#cols = tigetnum("cols")
#lines = tigetnum("lines")
#print str(cols) + "x" + str(lines)

place_begin = tparm(tigetstr("cup"), 15, 14)
place_end = tparm(tigetstr("cup"), 50, 0)

print place_begin + "-- some text --" + place_end
</code>```

@TZ.TZIOY, thanks, i think using stdout rather than using print indeed is a better solution.

Title: tput cup in python on the commandline

Body:
Is there an elegant solution to do this shell script in Python without importing os ?

    tput cup 14 15; echo -ne "\033[1;32mtest\033[0m" ; tput cup 50 0

This just has been gnawing in my mind for some time now :)

Thanks

Body:
Thanks Ignacio Vazquez-Abrams for your input, it was a great push in the right direction.
In the end i came up with this little code that will help me conquer the world :)

from curses import *
setupterm()

#cols = tigetnum("cols")
#lines = tigetnum("lines")
#print str(cols) + "x" + str(lines)

place_begin = tparm(tigetstr("cup"), 15, 14)
place_end = tparm(tigetstr("cup"), 50, 0)

print place_begin + "-- some text --" + place_end

@TZ.TZIOY, thanks, i think using stdout rather than using print indeed is a better solution.


问:
Python Tensorflow - Running model.fit multiple times without reinstantiating the model

Background

I am watching a popular YouTube crash course on machine learning.

At 3:35:50, he mentions that the model is likely overfit, so fits it again with less epochs.

Since he didn't reinstantiate the model, isn't this equivalent to fitting the model with that same data, thereby continuing to overtrain it?

My Question

Assume you have a model created and data ready to go.

You run:

```<code>model.fit(train_images, train_labels, epochs=10)
model.fit(train_images, train_labels, epochs=8)
</code>```

Is this equivalent to running:

```<code>model.fit(train_images, train_labels, epochs=18)
</code>```

Or:

```<code>model.fit(train_images, train_labels, epochs=8)
</code>```

If previously fitted data is overwritten, why does running model.fit a second time begin with the accuracy of the previous model?

In multiple other questions regarding saving and training models, the accepted solutions are to load the previously trained model, and run model.fit again.

If this will overwrite the pre-existing weights, doesn't that defeat the purpose of saving the model in the first place? Wouldn't training the model for the first time on the new data be equivalent?

What is the appropriate way to train a model across multiple, similar datasets while retaining accuracy across all of the data?

答:
Since he didn't reinstantiate the model, isn't this equivalent to
  fitting the model with that same data, thereby continuing to overtrain
  it?

You are correct! In order to check which number of epochs would do better in his example, he should have compiled the network again (that is, execute the above cell again).

Just remember that in general, whenever you instantiate a model again it most likely will start with completely new weights, totally different from past weights (unless you change this manually). So even though you keep the same amount of epochs, your final accuracy can change depending on the initial weights.

Are these two commands equivalent?

```<code>model.fit(train_images, train_labels, epochs=10)
model.fit(train_images, train_labels, epochs=8)
</code>```

and

```<code>model.fit(train_images, train_labels, epochs=18)
</code>```

No.

In the first case, you are training your network with some weights X going through all your training set 10 times, then you update your weights for some value y.
Then you will train your network again though all your training set 8 times but now you are using a network with weights X+y.

For the second case, you will train your network through all your training data 18 times with the weights X.

This is different!

Body:
Background

I am watching a popular YouTube crash course on machine learning.

At 3:35:50, he mentions that the model is likely overfit, so fits it again with less epochs.

Since he didn't reinstantiate the model, isn't this equivalent to fitting the model with that same data, thereby continuing to overtrain it?

My Question

Assume you have a model created and data ready to go.

You run:

model.fit(train_images, train_labels, epochs=10)
model.fit(train_images, train_labels, epochs=8)

Is this equivalent to running:

model.fit(train_images, train_labels, epochs=18)

Or:

model.fit(train_images, train_labels, epochs=8)

If previously fitted data is overwritten, why does running model.fit a second time begin with the accuracy of the previous model?

In multiple other questions regarding saving and training models, the accepted solutions are to load the previously trained model, and run model.fit again.

If this will overwrite the pre-existing weights, doesn't that defeat the purpose of saving the model in the first place? Wouldn't training the model for the first time on the new data be equivalent?

What is the appropriate way to train a model across multiple, similar datasets while retaining accuracy across all of the data?

Body:
Since he didn't reinstantiate the model, isn't this equivalent to
  fitting the model with that same data, thereby continuing to overtrain
  it?

You are correct! In order to check which number of epochs would do better in his example, he should have compiled the network again (that is, execute the above cell again).

Just remember that in general, whenever you instantiate a model again it most likely will start with completely new weights, totally different from past weights (unless you change this manually). So even though you keep the same amount of epochs, your final accuracy can change depending on the initial weights.

Are these two commands equivalent?

model.fit(train_images, train_labels, epochs=10)
model.fit(train_images, train_labels, epochs=8)

and

model.fit(train_images, train_labels, epochs=18)

No.

In the first case, you are training your network with some weights X going through all your training set 10 times, then you update your weights for some value y.
Then you will train your network again though all your training set 8 times but now you are using a network with weights X+y.

For the second case, you will train your network through all your training data 18 times with the weights X.

This is different!


问:
Display text according to a choice in drop-down list
I am trying to display a text according to a choice that I made in choice list with excel.
Any help please?</p>

答:
I imagine you mean a dropdown list.

Below is some information on creating and using one. Hope this helps.
https://support.office.com/en-us/article/Create-a-drop-down-list-7693307A-59EF-400A-B769-C5402DCE407B


问:
Removing non Printable values aftert Encoding.ASCII.GetString()
Suppose I have a Byte array and I use Encoding.ASCII.GetString() to convert the bytes into a string. Now the first few bytes will contain actual values, but the remaining ones will all have value of 0. After obtaining the string, when I show it on a WPF Form, there are some non printable characters. How can I remove these non printable characters. One way would be to loop through the array and only consider up to an index not containing 0, but I may also Encode using Unicode, that is Encoding.Unicode.GetString().

What would be the most generic way to solve the problem.

答: I'd just find the first zero in the array and strip off everything that follows.</p>


问:
R susbet matching "ANY" (union)
I'm attempting to subset from mtcars, such that the rows have a specific column which matches ANY of several values, stored in a list.

```<code>cylChoices = c(4,6)
subset(mtcars,cyl==cylChoices[1] | cyl== cylChoices[2])
</code>```

However, I'd like to do when cylChoices is of arbitrary length.

I've gotten close to this with for loops, but this results in what feels like unnecessarily long code, for example:

```<code>cars = list()
cylChoices = c(4,6)
count = 1
for(tempChoice in cylChoices){
count =count+1
cars[[count]] = subset(mtcars,cyl==tempChoice)
}
</code>```

This doesn't produce the same result, but it's getting closer.

Is there any way to match a subset easily?

Thank you very much for your time!

答:
An option with filter

```<code>library(dplyr)
mtcars %>%
     filter(cyl %in% cylChoices)
</code>```

Title: R susbet matching "ANY" (union)

Body:
I'm attempting to subset from mtcars, such that the rows have a specific column which matches ANY of several values, stored in a list.

cylChoices = c(4,6)
subset(mtcars,cyl==cylChoices[1] | cyl== cylChoices[2])

However, I'd like to do when cylChoices is of arbitrary length.

I've gotten close to this with for loops, but this results in what feels like unnecessarily long code, for example:

cars = list()
cylChoices = c(4,6)
count = 1
for(tempChoice in cylChoices){
count =count+1
cars[[count]] = subset(mtcars,cyl==tempChoice)
}

This doesn't produce the same result, but it's getting closer.

Is there any way to match a subset easily?

Thank you very much for your time!

Body:
An option with filter

library(dplyr)
mtcars %>%
     filter(cyl %in% cylChoices)


问:
Elegant tuple manipulation suggestions
I am working with images and pixel positions represented by tuples. I want to check if pixels are next to each other and came up with a working solution. I'm sure there is a more elegant solution than mine. Here is the function I have:

```<code>def test_neighbors(tup1, tup2):
    neighbors = lambda a, b: [(a + 1, b), (a - 1, b), (a, b + 1), (a, b - 1)]
    list1 = neighbors(tup1[0], tup1[1])
    list2 = neighbors(tup2[0], tup2[1])
    for item in list1:
        if item in list2:
            return True
    return False
</code>```

Again, this code works perfectly, so if this isn't a proper question I am sorry. Thanks in advance for the suggestions!

答:
Using @Alessandro idea but using NamedTuple to make code more readable</p>

```<code>from typing import NamedTuple

class Pixel(NamedTuple):
    x: int
    y: int

def test_neighbors(pix_a, pix_b):
    x_delta = abs(pix_a.x - pix_b.x)
    y_delta = abs(pix_a.y - pix_b.y)
    return x_delta + y_delta == 1

pix1 = Pixel(2,6)
pix2 = Pixel(2,8)
print(test_neighbors(pix1,pix2))

pix3 = Pixel(2,8)
pix4 = Pixel(3,8)
print(test_neighbors(pix3,pix4))
</code>```

Title: Elegant tuple manipulation suggestions

Body:
I am working with images and pixel positions represented by tuples. I want to check if pixels are next to each other and came up with a working solution. I'm sure there is a more elegant solution than mine. Here is the function I have:

def test_neighbors(tup1, tup2):
    neighbors = lambda a, b: [(a + 1, b), (a - 1, b), (a, b + 1), (a, b - 1)]
    list1 = neighbors(tup1[0], tup1[1])
    list2 = neighbors(tup2[0], tup2[1])
    for item in list1:
        if item in list2:
            return True
    return False

Again, this code works perfectly, so if this isn't a proper question I am sorry. Thanks in advance for the suggestions!

Body:
Using @Alessandro idea but using NamedTuple to make code more readable

from typing import NamedTuple

class Pixel(NamedTuple):
    x: int
    y: int

def test_neighbors(pix_a, pix_b):
    x_delta = abs(pix_a.x - pix_b.x)
    y_delta = abs(pix_a.y - pix_b.y)
    return x_delta + y_delta == 1

pix1 = Pixel(2,6)
pix2 = Pixel(2,8)
print(test_neighbors(pix1,pix2))

pix3 = Pixel(2,8)
pix4 = Pixel(3,8)
print(test_neighbors(pix3,pix4))


答:
const takeMangoes = (num, from) => from.map(x => {
  const take = Math.min(x.quantity, num);
  num -= take;
  // Original way, keep all properties, don't mutate original
  //return {...x, quantity: x.quantity - take};

  // Pick from below:

  // New way 1, mutate original in place
  x.quantity = x.quantity - take;
  return x;
  // New way 2, limit to OWN properties
  return Object.getOwnPropertyNames(x).reduce((a, c) => {
    a[c] = x[c];
    if (c === 'quantity') {
      a[c] -= take;
    }
    return a;
  }, {});
}).filter(x => x.quantity > 0);

console.log(takeMangoes(2, [
  {quantity: 5},
  {quantity: 8},
  {quantity: 13},
  {quantity: 4},
]));

console.log('------------------------');

console.log(takeMangoes(7, [
  {quantity: 5},
  {quantity: 8},
  {quantity: 13},
  {quantity: 4},
]));```

Title: How to decrement items in array Incrementally based on the given quantity in Javascript


问:
Any better way in Power BI to make REST API calls like HTTP GET to read data using a dynamic Access Token (Key)
Trying to generate few Power BI reports using REST API calls. This will require to generate an "Access Token" initially and then pass that Key to various API calls for authentication purposes, to read data.

I saw many threads that is using "Access Token" (Key) as a URL query-string or as HTTP header in power BI Web data source. But trying to achieve the Access Token created dynamically and then pass as headers in GET calls.

At the moment I am trying to read data from Adobe sign and they exposing data through REST API calls and authorized users can use HTTP GET to read data from their portal. There is a facility to create organisation-specific application and Access Tokens using their API's.

So please share if if you know a way to generate an Access Token dynamically during each dateset-refresh using POST and then call GET to fetch data needed for reports.

The below images are proposed API calls and tested through Postman

答:
I have achieved something like this by creating powerbi custom connector.
Which allows you to easily authenticate to any standard REST API (or any other sources). Of course, you can also do some work to authenticate to some more custom apis (I had this problem). But adobe sign api has quite good oauth2 implementation.
Custom connector is probably the best recommended solution. You can do very powerful things (I did). This is the way to do production-ready solutions.

How to create a custom connector:
https://github.com/Microsoft/DataConnectors/blob/master/docs/m-extensions.md#overview

Install the Power Query SDK from the Visual Studio Marketplace

Create a new Data Connector project

Define your connector logic

Build the project to produce an extension file

Create a [My Documents]\Power BI Desktop\Custom Connectors directory

Copy the extension file into this directory

Enable the Custom data connectors preview feature in Power BI
Desktop (under File | Options and settings | Custom data connectors)

Restart Power BI Desktop

When you have some basic connector you can implement OAuth authentication
https://learn.microsoft.com/en-us/power-query/handlingauthentication
and here you have almost copy&paste solution
https://learn.microsoft.com/en-us/power-query/samples/github/readme
(From above resource)

```<code>GithubSample = [
    Authentication = [
        OAuth = [
            StartLogin = StartLogin,
            FinishLogin = FinishLogin
        ]
    ],
    Label = Extension.LoadString("DataSourceLabel")
];
StartLogin = (resourceUrl, state, display) =>
        let
            AuthorizeUrl = "https://Github.com/login/oauth/authorize?" & Uri.BuildQueryString([
                client_id = client_id,
                scope = "user, repo",
                state = state,
                redirect_uri = redirect_uri])
        in
            [
                LoginUri = AuthorizeUrl,
                CallbackUri = redirect_uri,
                WindowHeight = windowHeight,
                WindowWidth = windowWidth,
                Context = null
            ];
FinishLogin = (context, callbackUri, state) =>
    let
        Parts = Uri.Parts(callbackUri)[Query]
    in
        TokenMethod(Parts[code]);
TokenMethod = (code) =>
    let
        Response = Web.Contents("https://Github.com/login/oauth/access_token", [
            Content = Text.ToBinary(Uri.BuildQueryString([
                client_id = client_id,
                client_secret = client_secret,
                code = code,
                redirect_uri = redirect_uri])),
            Headers=[#"Content-type" = "application/x-www-form-urlencoded",#"Accept" = "application/json"]]),
        Parts = Json.Document(Response)
    in
        Parts;
</code>```

Then when you first time run your connector it will ask user to authenticate and after it will store token.

Later on when you run your connector all requests to your API done by Web.Contents method
https://learn.microsoft.com/en-us/powerquery-m/web-contents
will be authenticated.

Body:
I have achieved something like this by creating powerbi custom connector.
Which allows you to easily authenticate to any standard REST API (or any other sources). Of course, you can also do some work to authenticate to some more custom apis (I had this problem). But adobe sign api has quite good oauth2 implementation.
Custom connector is probably the best recommended solution. You can do very powerful things (I did). This is the way to do production-ready solutions.

How to create a custom connector:
https://github.com/Microsoft/DataConnectors/blob/master/docs/m-extensions.md#overview

Install the Power Query SDK from the Visual Studio Marketplace

Create a new Data Connector project

Define your connector logic

Build the project to produce an extension file

Create a [My Documents]\Power BI Desktop\Custom Connectors directory

Copy the extension file into this directory

Enable the Custom data connectors preview feature in Power BI
Desktop (under File | Options and settings | Custom data connectors)

Restart Power BI Desktop

When you have some basic connector you can implement OAuth authentication
https://learn.microsoft.com/en-us/power-query/handlingauthentication
and here you have almost copy&paste solution
https://learn.microsoft.com/en-us/power-query/samples/github/readme
(From above resource)

GithubSample = [
    Authentication = [
        OAuth = [
            StartLogin = StartLogin,
            FinishLogin = FinishLogin
        ]
    ],
    Label = Extension.LoadString("DataSourceLabel")
];
StartLogin = (resourceUrl, state, display) =>
        let
            AuthorizeUrl = "https://Github.com/login/oauth/authorize?" & Uri.BuildQueryString([
                client_id = client_id,
                scope = "user, repo",
                state = state,
                redirect_uri = redirect_uri])
        in
            [
                LoginUri = AuthorizeUrl,
                CallbackUri = redirect_uri,
                WindowHeight = windowHeight,
                WindowWidth = windowWidth,
                Context = null
            ];
FinishLogin = (context, callbackUri, state) =>
    let
        Parts = Uri.Parts(callbackUri)[Query]
    in
        TokenMethod(Parts[code]);
TokenMethod = (code) =>
    let
        Response = Web.Contents("https://Github.com/login/oauth/access_token", [
            Content = Text.ToBinary(Uri.BuildQueryString([
                client_id = client_id,
                client_secret = client_secret,
                code = code,
                redirect_uri = redirect_uri])),
            Headers=[#"Content-type" = "application/x-www-form-urlencoded",#"Accept" = "application/json"]]),
        Parts = Json.Document(Response)
    in
        Parts;

Then when you first time run your connector it will ask user to authenticate and after it will store token.

Later on when you run your connector all requests to your API done by Web.Contents method
https://learn.microsoft.com/en-us/powerquery-m/web-contents
will be authenticated.


问:
Remove Numbers and Turn into a List
#

PYTHON
A clearer way of asking the question is:

If I have a string as follows:
'PALM BEACH.Race 6GaveaRace 5MaronasRace 7IOWARace 3ORANGE PARK.Race 5'

How do I turn that string into:
Palm Beach, Gavea, Maronas, Iowa, Orange Park

So that is, make each item in the list 'title'(ie. Uppercase first letter and the rest lower case), delete the numbers and the word 'Race'.

I am setting up to export to Excel.

Thanks in advance - Angus

#

答:
You can use re.split and some string manipulation:</p>

```<code>import re
>>> s = 'PALM BEACH.Race 6GaveaRace 5MaronasRace 7IOWARace 3ORANGE PARK.Race 5'
>>> # Split by the race and folowed by a digit
>>> race_names = re.split('Race \d+', s)
>>> def format_name(name):
...     # Remove the trailing period on some race names
...     name = name.rstrip('.')
...     # Change name to title case
...     name = name.title()
...     return name
>>> # Format the name and remove any empty entries in the list
>>> race_names = [format_name(name) for name in race_names if name]
>>> list(race_names)
['Palm Beach', 'Gavea', 'Maronas', 'Iowa', 'Orange Park']
</code>```

Title: Remove Numbers and Turn into a List

Body:
You can use re.split and some string manipulation:

import re
>>> s = 'PALM BEACH.Race 6GaveaRace 5MaronasRace 7IOWARace 3ORANGE PARK.Race 5'
>>> # Split by the race and folowed by a digit
>>> race_names = re.split('Race \d+', s)
>>> def format_name(name):
...     # Remove the trailing period on some race names
...     name = name.rstrip('.')
...     # Change name to title case
...     name = name.title()
...     return name
>>> # Format the name and remove any empty entries in the list
>>> race_names = [format_name(name) for name in race_names if name]
>>> list(race_names)
['Palm Beach', 'Gavea', 'Maronas', 'Iowa', 'Orange Park']


问:
Adding DISTINCT to a UNION query
How do I get distinct title.id's from this:

```<code> SELECT Title.id, Title.title FROM titles as Title HAVING points > 0
 UNION ALL
 SELECT Title.id, Title.title FROM titles as Title HAVING points > 1
</code>```

There is more to the query but this should be enough to go on.

答:
Isn't the simple way just get rid of the union and the second part altogether:

```<code>SELECT Title.id, Title.title FROM titles as Title HAVING points > 0
</code>```

since HAVING points > 0 includes anything with HAVING points > 1?

Title: Adding DISTINCT to a UNION query

Body:
How do I get distinct title.id's from this:

 SELECT Title.id, Title.title FROM titles as Title HAVING points > 0
 UNION ALL
 SELECT Title.id, Title.title FROM titles as Title HAVING points > 1

There is more to the query but this should be enough to go on.

Body:
Isn't the simple way just get rid of the union and the second part altogether:

SELECT Title.id, Title.title FROM titles as Title HAVING points > 0

since HAVING points > 0 includes anything with HAVING points > 1?


问:
Distance between segment and ellipse
I'm trying to find an efficient method to calculate the distance between a given segment and an ellipse:

Studying a bit I found that link on Youtube and tried to replicate the method using familiar C# functions.
I had to add some extensions for certain calculations, like finding an intersection between ellipse and segments/line (ellipses with rotation).
After a few hours, I have managed to replicate the method, but apparently it does not seem too efficient. or maybe yes, I don't know.

I will illustrate it in colors instead of using the traditional nomenclature because I did not have time to put the letters on the chart.

the magenta segment perpendicular to the initial segment is calculated using the distance from the first intersection between the auxiliary segment (Blue) and the circle (Red)

答:
By a similarity transformation (translate the center to the origin and rotate the Eigenvectors to the coordinate axis), you can bring the ellipse to its canonical form

```<code>x²/a² + y²/b² = 1.
</code>```

Simultaneously, the supporting line of the segment turns to equation

```<code>px + qy + r = 0.
</code>```

Now, by using a parametric equation of the ellipse, we minimize

```<code>(p a cosΘ + q b sinΘ + r)²
</code>```

and by cancelling the derivative,

```<code>-p a sinΘ + q b cosΘ = 0
</code>```

or

```<code>tanΘ = q b / p a.
</code>```

From the value of Θ, you get a point on the ellipse and check that it projects on the segment. If not, the shortest distance is to one of the segment endpoints. We minimize

```<code>(a cosΘ - x)² + (b sinΘ - y)²,
</code>```

by

```<code>-a sinΘ (a cosΘ - x) + b cosΘ (b sinΘ - y) = 0.
</code>```

Here it is advantageous to rationalize the expression by means of the Weierstrass substitution, and we get

```<code>- a 2t/(1+t²) (a (1-t²)/(1+t²) - x) + b (1-t²)/(1+t²) (b 2t/(1+t²) - y) = 0
</code>```

or

```<code>- a 2t (a (1-t²) - x (1+t²)) + b (1-t²) (b 2t - y (1+t²)) = 0.
</code>```

This is a quartic polynomial from which you can't escape, as there are as much as four solutions (of which you keep the shortest distance).

Title: Distance between segment and ellipse

Body:
By a similarity transformation (translate the center to the origin and rotate the Eigenvectors to the coordinate axis), you can bring the ellipse to its canonical form

x²/a² + y²/b² = 1.

Simultaneously, the supporting line of the segment turns to equation

px + qy + r = 0.

Now, by using a parametric equation of the ellipse, we minimize

(p a cosΘ + q b sinΘ + r)²

and by cancelling the derivative,

-p a sinΘ + q b cosΘ = 0

or

tanΘ = q b / p a.

From the value of Θ, you get a point on the ellipse and check that it projects on the segment. If not, the shortest distance is to one of the segment endpoints. We minimize

(a cosΘ - x)² + (b sinΘ - y)²,

by

-a sinΘ (a cosΘ - x) + b cosΘ (b sinΘ - y) = 0.

Here it is advantageous to rationalize the expression by means of the Weierstrass substitution, and we get

- a 2t/(1+t²) (a (1-t²)/(1+t²) - x) + b (1-t²)/(1+t²) (b 2t/(1+t²) - y) = 0

or

- a 2t (a (1-t²) - x (1+t²)) + b (1-t²) (b 2t - y (1+t²)) = 0.

This is a quartic polynomial from which you can't escape, as there are as much as four solutions (of which you keep the shortest distance).


问:
What will be the SQL query for ordering dates with respect to day name starting with tuesday?
It should order it by week day names i.e., tuesdays come first, wednesdays next, and so on.

Here's what I have done:

```<code>SELECT hire_date, TO_CHAR(hire_date,'Day')
FROM employee
ORDER BY TO_CHAR(hire_date,'Day');

</code>```

but it doesn't start ordering from tuesday...

答:
If you are looking for a solution that works internationally then do not use TO_CHAR as the day number is dependent on the NLS_TERRITORY setting which will be different for different users/databases around the world. For much of Europe, Monday will be the first day of the week; for much of the Americas and Africa, Sunday is the first day of the week; for the Middle East, Saturday is the first day of the week; and, in Bangladesh, Friday is the first day of the week. db<>fiddle

If you want a method independent of any NLS settings then use ISO weeks:

This will order it so that Monday is first, Tuesday second, ...

SELECT hire_date,
       TO_CHAR(hire_date, 'Day')
FROM   employee
ORDER BY
       TRUNC(hire_date) - TRUNC( hire_date, 'IW' ),
       hire_date
```

<p>To get Tuesday first, then you can subtract a day:</p>

<pre class="lang-sql prettyprint-override"><code>SELECT hire_date,
       TO_CHAR(hire_date, 'Day')
FROM   employee
ORDER BY
       TRUNC(hire_date - 1) - TRUNC(hire_date - 1, 'IW' ),
       hire_date
</code>```

Body:
It should order it by week day names i.e., tuesdays come first, wednesdays next, and so on.

Here's what I have done:

SELECT hire_date, TO_CHAR(hire_date,'Day')
FROM employee
ORDER BY TO_CHAR(hire_date,'Day');

but it doesn't start ordering from tuesday...

Body:
If you are looking for a solution that works internationally then do not use TO_CHAR as the day number is dependent on the NLS_TERRITORY setting which will be different for different users/databases around the world. For much of Europe, Monday will be the first day of the week; for much of the Americas and Africa, Sunday is the first day of the week; for the Middle East, Saturday is the first day of the week; and, in Bangladesh, Friday is the first day of the week. db<>fiddle

If you want a method independent of any NLS settings then use ISO weeks:

This will order it so that Monday is first, Tuesday second, ...

SELECT hire_date,
       TO_CHAR(hire_date, 'Day')
FROM   employee
ORDER BY
       TRUNC(hire_date) - TRUNC( hire_date, 'IW' ),
       hire_date

To get Tuesday first, then you can subtract a day:

SELECT hire_date,
       TO_CHAR(hire_date, 'Day')
FROM   employee
ORDER BY
       TRUNC(hire_date - 1) - TRUNC(hire_date - 1, 'IW' ),
       hire_date


问:
AutoMapper - Map Many-to-Many Relationships
In my DAL, I have the following models establishing a many-to-many relationship.

```<code>public class FamilyMember
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public ICollection<FamilyMemberPhone> FamilyMemberPhones { get; set; }
}
public class FamilyMemberPhone
{
    public int FamilyMemberId { get; set; }
    public int PhoneId { get; set; }
    public FamilyMember FamilyMember { get; set; }
    public Phone Phone { get; set; }
}
public class Phone : AuditableEntity
{
    public int Id { get; set; }
    public string PhoneNumber { get; set; }
    public bool IsPreferred { get; set; }
    public ICollection<FamilyMemberPhone> FamilyMemberPhones { get; set; }
}
</code>```

In my DTO, I have the following classes

```<code>public class FamilyMemberDto
{
    public int Id { get; set; }
    public int FamilyId { get; set; }
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
    public bool IsPrimary { get; set; }
    [Required]
    public List<Phone> FamilyMemberPhones { get; set; }
    public string FullName => $" {FirstName} {LastName}";
}
public class PhoneDto
{
    public int Id { get; set; }
    public string PhoneNumber { get; set; }
    public bool IsPreferred { get; set; }
    public PhoneType PhoneType { get; set; }
}
</code>```

My Mapping configuration looks like this:

```<code>CreateMap<Dal.Models.Phone, Dto.PhoneDto>().ReverseMap().IgnoreAuditableFields();

CreateMap<Dal.Models.FamilyMember, Dto.FamilyMemberDto>();

CreateMap<Dal.Models.FamilyMemberPhone, Dto.PhoneDto>()
            .ForMember(d => d.Id, opt => opt.MapFrom(s => s.Id))
            .ForMember(d => d.PhoneNumber, opt => opt.MapFrom(s => s.Phone.PhoneNumber))
            .ForMember(d => d.PhoneType, opt => opt.MapFrom(s => s.Phone.PhoneType));

CreateMap<Dto.FamilyMemberDto, Dal.Models.FamilyMember>()
            .AfterMap((s, d) =>
            {
                if (d.FamilyMemberPhones != null)
                    foreach (var fmp in d.FamilyMemberPhones)
                        fmp.Id = s.Id;
            });

CreateMap<Dto.PhoneDto, Dal.Models.FamilyMemberPhone>()
            .ForMember(d => d.PhoneId, opt => opt.MapFrom(s => s.Id));
</code>```

My Unit Test looks like this:

```<code>var member = new Bll.Dto.FamilyMemberDto
        {
            FamilyId = 12,
            FirstName = "Jane",
            LastName = "Doe",
            BirthDate = DateTime.Parse("11-01-1990"),
            Email = "test@test.com",
            FamilyMemberPhones = new List<Bll.Dto.PhoneDto>
            {
                new Bll.Dto.PhoneDto
                {
                    PhoneNumber = "test",
                    IsPreferred = true,
                },
                new Bll.Dto.Phone
                {
                    PhoneNumber = "hello",
                    IsPreferred = false,
                }
            }
        };
        await Manager.Save(member);
</code>```

When I'm trying to map the DTO to Model using Mapper.Map<Dal.Models.FamilyMember>(dto), in the entity.FamilyMemberPhones object, I see two items in the collection. However, digging deeper into the collection, all Dal.Models.Phone properties are null.

What am I doing wrong?

答:
@formula12's answer sparked a thought in my head. I need to account for every phone number that is being added to a family member. As the result, every time I am mapping FamilyMemberDto to FamilyMember, I need to also account for list of Phone inside of the map.

This is my new mapping profile:

```<code>CreateMap<Phone, Dto.PhoneDto>().ReverseMap().IgnoreAuditableFields();
        CreateMap<FamilyMember, Dto.FamilyMemberDto>();
        CreateMap<FamilyMemberPhone, Dto.PhoneDto>()
            .ForMember(d => d.Id, opt => opt.MapFrom(s => s.Id))
            .ForMember(d => d.PhoneNumber, opt => opt.MapFrom(s => s.Phone.PhoneNumber))
            .ForMember(d => d.PhoneType, opt => opt.MapFrom(s => s.Phone.PhoneType));
        CreateMap<Dto.FamilyMemberDto, FamilyMember>()
            .AfterMap((s, d) =>
            {
                var memberPhones = new List<FamilyMemberPhone>();
                foreach (var fmp in s.FamilyMemberPhones)
                {
                    var phone = new FamilyMemberPhone
                    {
                        Phone = new Phone
                        {
                            Id = fmp.Id,
                            PhoneNumber = fmp.PhoneNumber,
                            PhoneType = fmp.PhoneType
                        }
                    };
                    memberPhones.Add(phone);
                }
                d.FamilyMemberPhones = memberPhones;
            });
        CreateMap<Dto.PhoneDto, FamilyMemberPhone>()
            .ForMember(d => d.PhoneId, opt => opt.MapFrom(s => s.Id));
</code>```

Used case:
Let's say my family member has three (3) items in FaimlyMemberDto.FamilyMemberPhones which is a List<PhoneDto>, when going through the mapping process, My entity now has 3 FamilyMemberPhoneobjects in the ICollection<FamilyMemberPhones> in FamilyMember object. Inside of each of those, there is now a Phone object that maps to PhoneDto.

Body:
In my DAL, I have the following models establishing a many-to-many relationship.

public class FamilyMember
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public ICollection<FamilyMemberPhone> FamilyMemberPhones { get; set; }
}
public class FamilyMemberPhone
{
    public int FamilyMemberId { get; set; }
    public int PhoneId { get; set; }
    public FamilyMember FamilyMember { get; set; }
    public Phone Phone { get; set; }
}
public class Phone : AuditableEntity
{
    public int Id { get; set; }
    public string PhoneNumber { get; set; }
    public bool IsPreferred { get; set; }
    public ICollection<FamilyMemberPhone> FamilyMemberPhones { get; set; }
}

In my DTO, I have the following classes

public class FamilyMemberDto
{
    public int Id { get; set; }
    public int FamilyId { get; set; }
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
    public bool IsPrimary { get; set; }
    [Required]
    public List<Phone> FamilyMemberPhones { get; set; }
    public string FullName => $" {FirstName} {LastName}";
}
public class PhoneDto
{
    public int Id { get; set; }
    public string PhoneNumber { get; set; }
    public bool IsPreferred { get; set; }
    public PhoneType PhoneType { get; set; }
}

My Mapping configuration looks like this:

CreateMap<Dal.Models.Phone, Dto.PhoneDto>().ReverseMap().IgnoreAuditableFields();

CreateMap<Dal.Models.FamilyMember, Dto.FamilyMemberDto>();

CreateMap<Dal.Models.FamilyMemberPhone, Dto.PhoneDto>()
            .ForMember(d => d.Id, opt => opt.MapFrom(s => s.Id))
            .ForMember(d => d.PhoneNumber, opt => opt.MapFrom(s => s.Phone.PhoneNumber))
            .ForMember(d => d.PhoneType, opt => opt.MapFrom(s => s.Phone.PhoneType));

CreateMap<Dto.FamilyMemberDto, Dal.Models.FamilyMember>()
            .AfterMap((s, d) =>
            {
                if (d.FamilyMemberPhones != null)
                    foreach (var fmp in d.FamilyMemberPhones)
                        fmp.Id = s.Id;
            });

CreateMap<Dto.PhoneDto, Dal.Models.FamilyMemberPhone>()
            .ForMember(d => d.PhoneId, opt => opt.MapFrom(s => s.Id));

My Unit Test looks like this:

var member = new Bll.Dto.FamilyMemberDto
        {
            FamilyId = 12,
            FirstName = "Jane",
            LastName = "Doe",
            BirthDate = DateTime.Parse("11-01-1990"),
            Email = "test@test.com",
            FamilyMemberPhones = new List<Bll.Dto.PhoneDto>
            {
                new Bll.Dto.PhoneDto
                {
                    PhoneNumber = "test",
                    IsPreferred = true,
                },
                new Bll.Dto.Phone
                {
                    PhoneNumber = "hello",
                    IsPreferred = false,
                }
            }
        };
        await Manager.Save(member);

When I'm trying to map the DTO to Model using Mapper.Map<Dal.Models.FamilyMember>(dto), in the entity.FamilyMemberPhones object, I see two items in the collection. However, digging deeper into the collection, all Dal.Models.Phone properties are null.

What am I doing wrong?

Body:
@formula12's answer sparked a thought in my head. I need to account for every phone number that is being added to a family member. As the result, every time I am mapping FamilyMemberDto to FamilyMember, I need to also account for list of Phone inside of the map.

This is my new mapping profile:

CreateMap<Phone, Dto.PhoneDto>().ReverseMap().IgnoreAuditableFields();
        CreateMap<FamilyMember, Dto.FamilyMemberDto>();
        CreateMap<FamilyMemberPhone, Dto.PhoneDto>()
            .ForMember(d => d.Id, opt => opt.MapFrom(s => s.Id))
            .ForMember(d => d.PhoneNumber, opt => opt.MapFrom(s => s.Phone.PhoneNumber))
            .ForMember(d => d.PhoneType, opt => opt.MapFrom(s => s.Phone.PhoneType));
        CreateMap<Dto.FamilyMemberDto, FamilyMember>()
            .AfterMap((s, d) =>
            {
                var memberPhones = new List<FamilyMemberPhone>();
                foreach (var fmp in s.FamilyMemberPhones)
                {
                    var phone = new FamilyMemberPhone
                    {
                        Phone = new Phone
                        {
                            Id = fmp.Id,
                            PhoneNumber = fmp.PhoneNumber,
                            PhoneType = fmp.PhoneType
                        }
                    };
                    memberPhones.Add(phone);
                }
                d.FamilyMemberPhones = memberPhones;
            });
        CreateMap<Dto.PhoneDto, FamilyMemberPhone>()
            .ForMember(d => d.PhoneId, opt => opt.MapFrom(s => s.Id));

Used case:
Let's say my family member has three (3) items in FaimlyMemberDto.FamilyMemberPhones which is a List<PhoneDto>, when going through the mapping process, My entity now has 3 FamilyMemberPhoneobjects in the ICollection<FamilyMemberPhones> in FamilyMember object. Inside of each of those, there is now a Phone object that maps to PhoneDto.


问:
Using Numpy without getting extra dimensions in arrays
I'm getting started with Numpy, and I'm attempting to use some of it's functionality to fill in a 2 dimensional square matrix where all the rows sum to 1. This accomplishes what I've set out to do so far, however, there were several previous iterations of this code that were giving me variations of a list of 1 dimensional arrays. This solution doesn't feel very elegant- What would be the best practices to write this code legibly?</p>
```<code>import numpy as np

    class Markov:

        def __init__(self, states=5):
            self.prob_dist = []
            print(self.prob_dist)
            for i in range(states):
                change_prob = [1 for x in range(states)]
                print(change_prob)
                self.prob_dist.append(list(np.random.dirichlet(change_prob, size=1)[0]))
            print(self.prob_dist)

def main():
    output = Markov()

if __name__ == '__main__':
    main()
</code>```

答:
First create a random matrix of the desired size. In your case 5x5 since you have 5 states:

```<code>A = np.random.random((5, 5))
</code>```

Then normalize it so that each column sums to 1:

```<code>B = A / A.sum(axis = 0)
</code>```

Then transpose it so that each row sums to 1:

```<code>B = B.T
</code>```

Body:
I'm getting started with Numpy, and I'm attempting to use some of it's functionality to fill in a 2 dimensional square matrix where all the rows sum to 1. This accomplishes what I've set out to do so far, however, there were several previous iterations of this code that were giving me variations of a list of 1 dimensional arrays. This solution doesn't feel very elegant- What would be the best practices to write this code legibly?

import numpy as np

    class Markov:

        def __init__(self, states=5):
            self.prob_dist = []
            print(self.prob_dist)
            for i in range(states):
                change_prob = [1 for x in range(states)]
                print(change_prob)
                self.prob_dist.append(list(np.random.dirichlet(change_prob, size=1)[0]))
            print(self.prob_dist)

def main():
    output = Markov()

if __name__ == '__main__':
    main()

Body:
First create a random matrix of the desired size. In your case 5x5 since you have 5 states:

A = np.random.random((5, 5))

Then normalize it so that each column sums to 1:

B = A / A.sum(axis = 0)

Then transpose it so that each row sums to 1:

B = B.T


问:
SQLite: Tags and Products intersection
I'm new to SQLite and searching for a way to create a query to do the following:

I have 3 tables:

```<code>goods: List of goods
tags: list of tags
tag_goods: table used to associate a tag to a product
</code>```

This is the structure for each table:

Goods:

```<code>id (INTEGER, autoincrement)
name (TEXT, name of the product)
</code>```

Tags:

```<code>id (INTEGER, autoincrement)
name (TEXT, name of the tag)
</code>```

Tag_goods:

```<code>tag_id (INTEGER)
goods_id (INTEGER)
UNIQUE (tag_id, goods_id)
</code>```

What I want:

Obtain ONLY ids and names of the products that are tagged with ALL of the possible tags (NB: I need to reference all the tags in the query, not one by one).

(Meaning, for example I only have four tags: "yellow", "round", "eatable", "organic" and only goods "Cheese" and "Melon" match all of them)

With my very limited experience I understand, that I can try something like intersect, but it is impractical when there are too many tags.

答:
This query:

```<code>select goods_id
from tag_goods
group by goods_id
having count(*) = (select count(*) from tags)
</code>```

returns all the ids of goods that have all the tags from tags.

You can use it to return the rows from the table goods with the operator IN:

```<code>select * from goods
where id in (
  select goods_id
  from tag_goods
  group by goods_id
  having count(*) = (select count(*) from tags)
)
</code>```

Title: SQLite: Tags and Products intersection

Body:
I'm new to SQLite and searching for a way to create a query to do the following:

I have 3 tables:

goods: List of goods
tags: list of tags
tag_goods: table used to associate a tag to a product

This is the structure for each table:

Goods:

id (INTEGER, autoincrement)
name (TEXT, name of the product)

Tags:

id (INTEGER, autoincrement)
name (TEXT, name of the tag)

Tag_goods:

tag_id (INTEGER)
goods_id (INTEGER)
UNIQUE (tag_id, goods_id)

What I want:

Obtain ONLY ids and names of the products that are tagged with ALL of the possible tags (NB: I need to reference all the tags in the query, not one by one).

(Meaning, for example I only have four tags: "yellow", "round", "eatable", "organic" and only goods "Cheese" and "Melon" match all of them)

With my very limited experience I understand, that I can try something like intersect, but it is impractical when there are too many tags.

Body:
This query:

select goods_id
from tag_goods
group by goods_id
having count(*) = (select count(*) from tags)

returns all the ids of goods that have all the tags from tags.

You can use it to return the rows from the table goods with the operator IN:

select * from goods
where id in (
  select goods_id
  from tag_goods
  group by goods_id
  having count(*) = (select count(*) from tags)
)


问:
Dynamic page update using ftl template and Spring Boot
Me question related to using Spring Boot with FTL (Freemarker) templates.
Is there any way to update my page dynamically?
For example:
I have one general list for two accounts. When the second user change that list, I want to see those changes on my page without page reloading. Is there any way to realize that?
I know that React has this possibility, but I have a lot of code with ftl templates.
Will be glad for any answer</p>

答:
FreeMarker generates static HTML output and nothing more.

In a website the only way to do what you are asking for (change page content without reloading) is to use JavaScript (React also uses JavaScript underneath).

You could detect when someone changed something (eg user list) using WebSocket, long-polling, etc.

Spring guide on WebSockets

Baeldung's intro to WebSocket with Spring

Ps.: You will probably have to repeat some printing logic using JavaScript, for example

User A opens the view

User B opens the view

User B edits something

On the server-side, you broadcast new WebSocket message, to
inform every connected user that something has changed (could be
detailed, like user by ID 123 login has changed from "donald" to
"dolan")

On the client-side, you listen for the broadcasted message. When you get the message described in 4, you find the table row of user with id 123, and change his login to dolan.