问:
C# - How to use ListView and SQLite database
I'm trying to add some data from a SQLite database, inside a ListView.
I'm having some difficulties as I want to insert all the data of the column and not a single record.

TEST CODE:

Form1.cs {Load}

```<code>private void home_form_Load(object sender, EventArgs e)
        {
            listView1.Refresh();

            listView1.View = View.Details;
            listView1.Columns.Add("ID");
            listView1.Columns.Add("Grado");
            listView1.Columns.Add("Cognome");
            listView1.Columns.Add("Nome");
            listView1.Columns.Add("Status");
        }
</code>```

Form1.cs {menu_button_gestionepax}

```<code>private void menu_button_gestionepax_Click(object sender, EventArgs e)
        {
            menu_button_dashboard.BackColor = System.Drawing.Color.DeepSkyBlue;
            panel_dashboard.Visible = false;
            gestionepersonale_panel.Visible = true;
            menu_button_gestionepax.BackColor = System.Drawing.Color.Blue;

            listView1.Refresh();
            ListViewItem lst = new ListViewItem();
            lst.SubItems.Add(LoadUsers.ManagerFind());
            lst.SubItems.Add(LoadUsers.ManagerFind());
            lst.SubItems.Add(LoadUsers.ManagerFind());
            lst.SubItems.Add(LoadUsers.ManagerFind());
            lst.SubItems.Add(LoadUsers.ManagerFind());

            listView1.Items.Add(lst);

            /*
            string[] row = { LoadUsers.ManagerFindid(), LoadUsers.ManagerFindid() };
            var listViewItem = new ListViewItem(row);
            infobox_listview.Items.Add(listViewItem);
            */
        }
</code>```

LoadUsers.cs

```<code>public dynamic string ManagerFind()
{
    using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
    {
        var select = cnn.Query($"select id from utenti");

        if (select.Any())
        { return select[0].ToString(); }
        else return "wrong";
    }
}
</code>```

I have also done various other tests and one of the difficulties in some cases is to call string ManagerFind() from LoadUsers.cs

答:
Try something like this to get your rows and columns from your sql i know this is how you do it in SQL im sure there is a similar way to do it with sqlLite</p>

```<code>         using (SqlConnection connection = new SqlConnection(_sqlConnectionStringFromUserImput))
                {
                    connection.Open();
                    if (connection.State == ConnectionState.Open)
                    {
                        SqlCommand sqlCommand =
                            new SqlCommand(
                                "select id from utenti",
                                connection)
                            {
                                CommandType = CommandType.Text,
                                CommandTimeout = 20
                            };
                        SqlDataReader reader = sqlCommand.ExecuteReader();
                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                DateTime datetimefield = reader.GetFieldValue<DateTime>(0);
                                string stringField = reader.GetFieldValue<string>(1);
                            }
                        }
                        reader.Close();
    }
                    connection.Close();
                }
</code>```

Body:
I'm trying to add some data from a SQLite database, inside a ListView.
I'm having some difficulties as I want to insert all the data of the column and not a single record.

TEST CODE:

Form1.cs {Load}

private void home_form_Load(object sender, EventArgs e)
        {
            listView1.Refresh();

            listView1.View = View.Details;
            listView1.Columns.Add("ID");
            listView1.Columns.Add("Grado");
            listView1.Columns.Add("Cognome");
            listView1.Columns.Add("Nome");
            listView1.Columns.Add("Status");
        }

Form1.cs {menu_button_gestionepax}

private void menu_button_gestionepax_Click(object sender, EventArgs e)
        {
            menu_button_dashboard.BackColor = System.Drawing.Color.DeepSkyBlue;
            panel_dashboard.Visible = false;
            gestionepersonale_panel.Visible = true;
            menu_button_gestionepax.BackColor = System.Drawing.Color.Blue;

            listView1.Refresh();
            ListViewItem lst = new ListViewItem();
            lst.SubItems.Add(LoadUsers.ManagerFind());
            lst.SubItems.Add(LoadUsers.ManagerFind());
            lst.SubItems.Add(LoadUsers.ManagerFind());
            lst.SubItems.Add(LoadUsers.ManagerFind());
            lst.SubItems.Add(LoadUsers.ManagerFind());

            listView1.Items.Add(lst);

            /*
            string[] row = { LoadUsers.ManagerFindid(), LoadUsers.ManagerFindid() };
            var listViewItem = new ListViewItem(row);
            infobox_listview.Items.Add(listViewItem);
            */
        }

LoadUsers.cs

public dynamic string ManagerFind()
{
    using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
    {
        var select = cnn.Query($"select id from utenti");

        if (select.Any())
        { return select[0].ToString(); }
        else return "wrong";
    }
}

I have also done various other tests and one of the difficulties in some cases is to call string ManagerFind() from LoadUsers.cs

Body:
Try something like this to get your rows and columns from your sql i know this is how you do it in SQL im sure there is a similar way to do it with sqlLite

         using (SqlConnection connection = new SqlConnection(_sqlConnectionStringFromUserImput))
                {
                    connection.Open();
                    if (connection.State == ConnectionState.Open)
                    {
                        SqlCommand sqlCommand =
                            new SqlCommand(
                                "select id from utenti",
                                connection)
                            {
                                CommandType = CommandType.Text,
                                CommandTimeout = 20
                            };
                        SqlDataReader reader = sqlCommand.ExecuteReader();
                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                DateTime datetimefield = reader.GetFieldValue<DateTime>(0);
                                string stringField = reader.GetFieldValue<string>(1);
                            }
                        }
                        reader.Close();
    }
                    connection.Close();
                }


来源: stackexchange

问:
GIT merge conflict: after create new branch and deleting some files
I have a problem with a GIT merge. In fact, I have a master branch with this architecture:

```<code>.git
doc
   \__ some files

src
   \__ tools 1
              \__ some files

   \__ tools 2
              \__ some files
</code>```

In my project, I developed tools and I will add other tools in the "src" directory. For that, for each time I want to create a new tool, I will create a new branch named "tools3" from master branch and then remove all directories that I do not need, here "tools 1", "tools 2" and "doc". The reason is that I do not need documentation and other tools to develop.

So now, after those deleting I code my "tools 3" and I commit and push it into the new branch "tools3". It's time to merge my two branches with a git merge tools3 -m "Merge tools3 branch with master branch" (in master branch).

I have two problems, first some conflicts among with documentation files:

CONFLICT MESSAGE:
CONFLICT (modify/delete): doc/api_project.json deleted in tools3 and modified in HEAD. Version HEAD of doc/api_project.json left in tree.

In the second time, the merging removes my "src" files (the ones I deleted earlier in "tools3" branch).

So, how can I fix this merge conflict and then how can I retrieve my removing files in master branch? I think I do not have the best practice to do this type of things with GIT so I am open to any suggestions about GIT practices.

答: Every time you create new tool you are creating the branch by cloning your master branch. once you added a new tool into the newly created branch, you are comparing the master and newly created branch in the background. So whatever the new changes are there will be added in the master branch and what is the modified changes will be updated/removed from the master branch. So you must not delete the code from any branch as it will be removed at the time of merging.</p>

ContentLicense: CC BY-SA 4.0

Body:
I have a problem with a GIT merge. In fact, I have a master branch with this architecture:

.git
doc
   \__ some files

src
   \__ tools 1
              \__ some files

   \__ tools 2
              \__ some files

In my project, I developed tools and I will add other tools in the "src" directory. For that, for each time I want to create a new tool, I will create a new branch named "tools3" from master branch and then remove all directories that I do not need, here "tools 1", "tools 2" and "doc". The reason is that I do not need documentation and other tools to develop.

So now, after those deleting I code my "tools 3" and I commit and push it into the new branch "tools3". It's time to merge my two branches with a git merge tools3 -m "Merge tools3 branch with master branch" (in master branch).

I have two problems, first some conflicts among with documentation files:

CONFLICT MESSAGE:
CONFLICT (modify/delete): doc/api_project.json deleted in tools3 and modified in HEAD. Version HEAD of doc/api_project.json left in tree.

In the second time, the merging removes my "src" files (the ones I deleted earlier in "tools3" branch).

So, how can I fix this merge conflict and then how can I retrieve my removing files in master branch? I think I do not have the best practice to do this type of things with GIT so I am open to any suggestions about GIT practices.


问:
Splitting words in a list
How to split a list into separate words. I know that you can split strings with split but I need to split a list.

Here is my code:

```<code>text = ['a,b', 'c,d']
text = text.replace(',', ' ')
for i in text:
  print(text.split())
</code>```

When I run it, an error pops up and when I try to convert the list into a string there are random extras like \n, ' and [] that shouldn't be there.

Expected result: I want the outcome to be a list that contains ['a', 'b', 'c', 'd'] that when I print, comes up with that.

The error comes up on line two and says:

AttributeError: 'list' object has no attribute 'replace'

答:
One more approach:</p>

```<code>text = ['a,b', 'c,d']
text = ','.join(text)
text = text.split(',')
print(text)
# ['a', 'b', 'c', 'd']
</code>```

Title: Splitting words in a list

Body:
How to split a list into separate words. I know that you can split strings with split but I need to split a list.

Here is my code:

text = ['a,b', 'c,d']
text = text.replace(',', ' ')
for i in text:
  print(text.split())

When I run it, an error pops up and when I try to convert the list into a string there are random extras like \n, ' and [] that shouldn't be there.

Expected result: I want the outcome to be a list that contains ['a', 'b', 'c', 'd'] that when I print, comes up with that.

The error comes up on line two and says:

AttributeError: 'list' object has no attribute 'replace'

Body:
One more approach:

text = ['a,b', 'c,d']
text = ','.join(text)
text = text.split(',')
print(text)
# ['a', 'b', 'c', 'd']


问:
How to get a CheckBoxField from a DetailsView
I have been trying to figure this out for hours. So sad! The structure of my ascx is like

```<code><asp:DetailsView ...>
    <Fields>
        .
        .
        <asp:CheckBoxField DataField="ThingEnabled" HeaderText="Thing Enabled"/>
        .
        .
        .
    </Fields>
</asp:DetailsView>
</code>```

and the element I want is the ThingEnabled one.

Setup:

```<code>DetailsView dv = (DetailsView)sender;
CheckBoxField cbf = ????
</code>```

Note that CheckBoxFields do not have ID properties, so I can't use FindControl.

答:
Its also possible to use linq to get any field within a DetailsView in this way.</p>

```<code>// Page_Load is just an example event here, change to any event you need
protected void Page_Load(object sender, EventArgs e)
{
    DetailsView dv = sender as DetailsView;

    //using linq to get the CheckBoxField control
    var field = dv.Fields.Cast<DataControlField>().Single(x => x.HeaderText == "TitleOfCheckboxField") as CheckBoxField;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have been trying to figure this out for hours. So sad! The structure of my ascx is like

<asp:DetailsView ...>
    <Fields>
        .
        .
        <asp:CheckBoxField DataField="ThingEnabled" HeaderText="Thing Enabled"/>
        .
        .
        .
    </Fields>
</asp:DetailsView>

and the element I want is the ThingEnabled one.

Setup:

DetailsView dv = (DetailsView)sender;
CheckBoxField cbf = ????

Note that CheckBoxFields do not have ID properties, so I can't use FindControl.

Body:
Its also possible to use linq to get any field within a DetailsView in this way.

// Page_Load is just an example event here, change to any event you need
protected void Page_Load(object sender, EventArgs e)
{
    DetailsView dv = sender as DetailsView;

    //using linq to get the CheckBoxField control
    var field = dv.Fields.Cast<DataControlField>().Single(x => x.HeaderText == "TitleOfCheckboxField") as CheckBoxField;
}


问:
Replace after specific text
I would like to remove after specific text in rows whatever exist.

I use this:

```<code>dframe$col1 <- gsub("Stock Amazon|Or Another|Google","",dframe$col1)
</code>```

but it removes the whole row and not whatever after the string. What can I do to fix it?

答:
If, as you say, you want to remove whatever text exists after some text, then lookaround may help you:

DATA:

```<code>text <- c("some text Stock Amazon more text", "text again Or Another text", "yet more Google and this")
</code>```

SOLUTION:

This pattern says, "if you see Stock Amazon or Or Another or Googleon the left delete whatever comes next":

```<code>gsub("(?<=Stock Amazon|Or Another|Google).*", "", text, perl = T)
[1] "some text Stock Amazon" "text again Or Another"  "yet more Google"
</code>```

Title: Replace after specific text

Body:
I would like to remove after specific text in rows whatever exist.

I use this:

dframe$col1 <- gsub("Stock Amazon|Or Another|Google","",dframe$col1)

but it removes the whole row and not whatever after the string. What can I do to fix it?

Body:
If, as you say, you want to remove whatever text exists after some text, then lookaround may help you:

DATA:

text <- c("some text Stock Amazon more text", "text again Or Another text", "yet more Google and this")

SOLUTION:

This pattern says, "if you see Stock Amazon or Or Another or Googleon the left delete whatever comes next":

gsub("(?<=Stock Amazon|Or Another|Google).*", "", text, perl = T)
[1] "some text Stock Amazon" "text again Or Another"  "yet more Google"


问:
Get duration of an audio file - Android
I am trying to the duration of my audio files by clicking on them through a ListView. In this list view I am correctly displaying the names on them and I am able to play them, but I would like to know its duration.

I have looked for different questions in Stackoverflow which actually seem to answer this question but I am not truly able to do it so I will leave here my attempt. I have tried to follow this answer but it does not work so I assume that I am falling getting or understanding the Uri.

The file is stored at /raw/

JAVA - 1st attempt

```<code>listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // play desired audio
            Field[] fields = R.raw.class.getFields();
            if(soundMap.selectedEncoder != null) {
                //Log.d(TAG,  String.valueOf(soundMap.getX()) + " " + String.valueOf(soundMap.getY()));
                soundMap.selectedEncoder.play(position, audioFiles[position]);

                // Get duration of the audio file
                Uri uri = Uri.parse("/raw/"+fields[position].getName());
                MediaMetadataRetriever mmr = new MediaMetadataRetriever();
                mmr.setDataSource(getApplicationContext(), uri);
                String durationStr = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
                //int audioFileDuration = Integer.parseInt(durationStr);

            }
        }
    });
</code>```

The audios are stored at the raw folder. I have also tried to add .mp3 to the uri

ERROR

E/AndroidRuntime: FATAL EXCEPTION: main
      Process: myapp, PID: 26303
      java.lang.IllegalArgumentException

JAVA - 2nd attempt

```<code>File audioFile = new File("/raw/"+fields[position].getName()+ ".mp3");
                    mmr.setDataSource(context, Uri.fromFile(audioFile));
                    String time = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
                    long timeInMillisec = Long.parseLong(time );
</code>```

EDIT - 3rd attempt
In the end I have used MediaPlayer

```<code>AssetFileDescriptor afd = context.getResources().openRawResourceFd(R.raw.andthenturnleft);
                if (afd == null) return;
                try {
                    mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
                } catch (IOException e) {
                    e.printStackTrace();
                }

                int audioFileDuration = mediaPlayer.getDuration();
                /*try {
</code>```

and I get the duration of the file. Nevertheless, first I get the following error:

E/MediaPlayerNative: Attempt to call getDuration in wrong state:
  mPlayer=0xf6f4e7a0, mCurrentState=2

I assume that the error is generated because during the first attempt to get the duration the MediaPlayer is not ready yet. I would like to stop the code until is ready. Nevertheless, in the end I get audioFileDuration with a value of 24 which is not possible because it should return the value in milliseconds and the file is 2seconds long.

4th attempt

```<code>String path = context.getFilesDir().getAbsolutePath();
                try {
                    mediaPlayer.setDataSource(path + fields[position].getName() + ".mp3");
                } catch (IOException e) {
                    e.printStackTrace();
                }

                int audioFileDuration = mediaPlayer.getDuration();
</code>```

the problem is this case is that I get  a value of 0 because it does not find the file

open failed: ENOENT (No such file or directory)

How could I properly get the path of the file?

SOLVED
I have posted my own solution. I just needed to find a new way to set the path of the file and I finally managed to do it.

答:
At the end I used another way to get the path of the file and I was able to solve this error. I copy here the code that I used:

```<code> Uri mediaPath = Uri.parse("android.resource://com.package.name/" + R.raw.audioname);
                mmr.setDataSource(context, mediaPath);
                String duration = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
                Log.d(TAG, duration);
                mmr.release();
</code>```

Title: Get duration of an audio file - Android

Body:
I am trying to the duration of my audio files by clicking on them through a ListView. In this list view I am correctly displaying the names on them and I am able to play them, but I would like to know its duration.

I have looked for different questions in Stackoverflow which actually seem to answer this question but I am not truly able to do it so I will leave here my attempt. I have tried to follow this answer but it does not work so I assume that I am falling getting or understanding the Uri.

The file is stored at /raw/

JAVA - 1st attempt

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // play desired audio
            Field[] fields = R.raw.class.getFields();
            if(soundMap.selectedEncoder != null) {
                //Log.d(TAG,  String.valueOf(soundMap.getX()) + " " + String.valueOf(soundMap.getY()));
                soundMap.selectedEncoder.play(position, audioFiles[position]);

                // Get duration of the audio file
                Uri uri = Uri.parse("/raw/"+fields[position].getName());
                MediaMetadataRetriever mmr = new MediaMetadataRetriever();
                mmr.setDataSource(getApplicationContext(), uri);
                String durationStr = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
                //int audioFileDuration = Integer.parseInt(durationStr);

            }
        }
    });

The audios are stored at the raw folder. I have also tried to add .mp3 to the uri

ERROR

E/AndroidRuntime: FATAL EXCEPTION: main
      Process: myapp, PID: 26303
      java.lang.IllegalArgumentException

JAVA - 2nd attempt

File audioFile = new File("/raw/"+fields[position].getName()+ ".mp3");
                    mmr.setDataSource(context, Uri.fromFile(audioFile));
                    String time = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
                    long timeInMillisec = Long.parseLong(time );

EDIT - 3rd attempt
In the end I have used MediaPlayer

AssetFileDescriptor afd = context.getResources().openRawResourceFd(R.raw.andthenturnleft);
                if (afd == null) return;
                try {
                    mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
                } catch (IOException e) {
                    e.printStackTrace();
                }

                int audioFileDuration = mediaPlayer.getDuration();
                /*try {

and I get the duration of the file. Nevertheless, first I get the following error:

E/MediaPlayerNative: Attempt to call getDuration in wrong state:
  mPlayer=0xf6f4e7a0, mCurrentState=2

I assume that the error is generated because during the first attempt to get the duration the MediaPlayer is not ready yet. I would like to stop the code until is ready. Nevertheless, in the end I get audioFileDuration with a value of 24 which is not possible because it should return the value in milliseconds and the file is 2seconds long.

4th attempt

String path = context.getFilesDir().getAbsolutePath();
                try {
                    mediaPlayer.setDataSource(path + fields[position].getName() + ".mp3");
                } catch (IOException e) {
                    e.printStackTrace();
                }

                int audioFileDuration = mediaPlayer.getDuration();

the problem is this case is that I get  a value of 0 because it does not find the file

open failed: ENOENT (No such file or directory)

How could I properly get the path of the file?

SOLVED
I have posted my own solution. I just needed to find a new way to set the path of the file and I finally managed to do it.

Body:
At the end I used another way to get the path of the file and I was able to solve this error. I copy here the code that I used:

 Uri mediaPath = Uri.parse("android.resource://com.package.name/" + R.raw.audioname);
                mmr.setDataSource(context, mediaPath);
                String duration = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
                Log.d(TAG, duration);
                mmr.release();


问:
Fill blank values with data from following columns
Having a dataframe like this:

```<code>data.frame(id = c(1,2,3,4), text1 = c("sth","","another",""), text2 = c("more","another","add",""), text3 = c("final","and","where","all"))
</code>```

How is it possible to detect if in the text1 column a row is blank and fill the blank with a value exist in text2, text3 or text4 column and leave from this NA after the process

Example of expected output

```<code>data.frame(id = c(1,2,3,4), text1 = c("sth","another","another","all"), text2 = c("more","","add",""), text3 = c("final","and","where",""))
</code>```

答:
Another base R solution is to define your custom function swap and apply it by rows, i.e.,

```<code>swap <- function(v) {v[inds]<-v[rev(inds <- c(1,head(which(nchar(v)>0),1)))];v}
df[-1]<-t(apply(df[-1], 1, swap))
</code>```

such that

```<code>> df
  id   text1 text2 text3
1  1     sth  more final
2  2 another         and
3  3 another   add where
4  4     all
</code>```

Body:
Having a dataframe like this:

data.frame(id = c(1,2,3,4), text1 = c("sth","","another",""), text2 = c("more","another","add",""), text3 = c("final","and","where","all"))

How is it possible to detect if in the text1 column a row is blank and fill the blank with a value exist in text2, text3 or text4 column and leave from this NA after the process

Example of expected output

data.frame(id = c(1,2,3,4), text1 = c("sth","another","another","all"), text2 = c("more","","add",""), text3 = c("final","and","where",""))

Body:
Another base R solution is to define your custom function swap and apply it by rows, i.e.,

swap <- function(v) {v[inds]<-v[rev(inds <- c(1,head(which(nchar(v)>0),1)))];v}
df[-1]<-t(apply(df[-1], 1, swap))

such that

> df
  id   text1 text2 text3
1  1     sth  more final
2  2 another         and
3  3 another   add where
4  4     all


答:
You could do to the following:

```<code>text = ['a,b', 'c,d']
text_str = "".join(text).replace(",", "")
arr = [c for c in text_str]
</code>```

its a bit verbose, but those are the steps

Title: Splitting words in a list

Body:
You could do to the following:

text = ['a,b', 'c,d']
text_str = "".join(text).replace(",", "")
arr = [c for c in text_str]

its a bit verbose, but those are the steps


问:
OpenCV - Fastest method to check if two images are 100% same or not
There are many questions over here which checks if two images are "nearly" similar or not.

My task is simple. With OpenCV, I want to find out if two images are 100% identical or not.

They will be of same size but can be saved with different filenames.

答:
Importing the packages we’ll need — matplotlib for plotting, NumPy for numerical processing, and cv2 for our OpenCV bindings. Structural Similarity Index method is already implemented for us by scikit-image, so we’ll just use their implementation

```<code># import the necessary packages
from skimage.measure import structural_similarity as ssim
import matplotlib.pyplot as plt
import numpy as np
import cv2
</code>```

Then define the compare_images function which we’ll use to compare two images using both MSE and SSIM. The mse function takes three arguments: imageA and imageB, which are the two images we are going to compare, and then the title of our figure.

We then compute the MSE and SSIM between the two images.
We also simply display the MSE and SSIM associated with the two images we are comparing.

```<code>def mse(imageA, imageB):
    # the 'Mean Squared Error' between the two images is the
    # sum of the squared difference between the two images;
    # NOTE: the two images must have the same dimension
    err = np.sum((imageA.astype("float") - imageB.astype("float")) ** 2)
    err /= float(imageA.shape[0] * imageA.shape[1])

    # return the MSE, the lower the error, the more "similar"
    # the two images are
    return err
def compare_images(imageA, imageB, title):
    # compute the mean squared error and structural similarity
    # index for the images
    m = mse(imageA, imageB)
    s = ssim(imageA, imageB)
    # setup the figure
    fig = plt.figure(title)
    plt.suptitle("MSE: %.2f, SSIM: %.2f" % (m, s))
    # show first image
    ax = fig.add_subplot(1, 2, 1)
    plt.imshow(imageA, cmap = plt.cm.gray)
    plt.axis("off")
    # show the second image
    ax = fig.add_subplot(1, 2, 2)
    plt.imshow(imageB, cmap = plt.cm.gray)
    plt.axis("off")
    # show the images
    plt.show()
</code>```

Load images off disk using OpenCV. We’ll be using original image, contrast adjusted image, and our Photoshopped image

We then convert our images to grayscale

```<code># load the images -- the original, the original + contrast,
# and the original + photoshop
original = cv2.imread("images/jp_gates_original.png")
contrast = cv2.imread("images/jp_gates_contrast.png")
shopped = cv2.imread("images/jp_gates_photoshopped.png")
# convert the images to grayscale
original = cv2.cvtColor(original, cv2.COLOR_BGR2GRAY)
contrast = cv2.cvtColor(contrast, cv2.COLOR_BGR2GRAY)
shopped = cv2.cvtColor(shopped, cv2.COLOR_BGR2GRAY)
</code>```

We will generate a matplotlib figure, loop over our images one-by-one, and add them to our plot. Our plot is then displayed to us.

Finally, we can compare our images together using the compare_images function.

```<code># initialize the figure
fig = plt.figure("Images")
images = ("Original", original), ("Contrast", contrast), ("Photoshopped", shopped)
# loop over the images
for (i, (name, image)) in enumerate(images):
    # show the image
    ax = fig.add_subplot(1, 3, i + 1)
    ax.set_title(name)
    plt.imshow(image, cmap = plt.cm.gray)
    plt.axis("off")
# show the figure
plt.show()
# compare the images
compare_images(original, original, "Original vs. Original")
compare_images(original, contrast, "Original vs. Contrast")
compare_images(original, shopped, "Original vs. Photoshopped")
</code>```

Reference- https://www.pyimagesearch.com/2014/09/15/python-compare-two-images/

Body:
Importing the packages we’ll need — matplotlib for plotting, NumPy for numerical processing, and cv2 for our OpenCV bindings. Structural Similarity Index method is already implemented for us by scikit-image, so we’ll just use their implementation

# import the necessary packages
from skimage.measure import structural_similarity as ssim
import matplotlib.pyplot as plt
import numpy as np
import cv2

Then define the compare_images function which we’ll use to compare two images using both MSE and SSIM. The mse function takes three arguments: imageA and imageB, which are the two images we are going to compare, and then the title of our figure.

We then compute the MSE and SSIM between the two images.
We also simply display the MSE and SSIM associated with the two images we are comparing.

def mse(imageA, imageB):
    # the 'Mean Squared Error' between the two images is the
    # sum of the squared difference between the two images;
    # NOTE: the two images must have the same dimension
    err = np.sum((imageA.astype("float") - imageB.astype("float")) ** 2)
    err /= float(imageA.shape[0] * imageA.shape[1])

    # return the MSE, the lower the error, the more "similar"
    # the two images are
    return err
def compare_images(imageA, imageB, title):
    # compute the mean squared error and structural similarity
    # index for the images
    m = mse(imageA, imageB)
    s = ssim(imageA, imageB)
    # setup the figure
    fig = plt.figure(title)
    plt.suptitle("MSE: %.2f, SSIM: %.2f" % (m, s))
    # show first image
    ax = fig.add_subplot(1, 2, 1)
    plt.imshow(imageA, cmap = plt.cm.gray)
    plt.axis("off")
    # show the second image
    ax = fig.add_subplot(1, 2, 2)
    plt.imshow(imageB, cmap = plt.cm.gray)
    plt.axis("off")
    # show the images
    plt.show()

Load images off disk using OpenCV. We’ll be using original image, contrast adjusted image, and our Photoshopped image

We then convert our images to grayscale

# load the images -- the original, the original + contrast,
# and the original + photoshop
original = cv2.imread("images/jp_gates_original.png")
contrast = cv2.imread("images/jp_gates_contrast.png")
shopped = cv2.imread("images/jp_gates_photoshopped.png")
# convert the images to grayscale
original = cv2.cvtColor(original, cv2.COLOR_BGR2GRAY)
contrast = cv2.cvtColor(contrast, cv2.COLOR_BGR2GRAY)
shopped = cv2.cvtColor(shopped, cv2.COLOR_BGR2GRAY)

We will generate a matplotlib figure, loop over our images one-by-one, and add them to our plot. Our plot is then displayed to us.

Finally, we can compare our images together using the compare_images function.

# initialize the figure
fig = plt.figure("Images")
images = ("Original", original), ("Contrast", contrast), ("Photoshopped", shopped)
# loop over the images
for (i, (name, image)) in enumerate(images):
    # show the image
    ax = fig.add_subplot(1, 3, i + 1)
    ax.set_title(name)
    plt.imshow(image, cmap = plt.cm.gray)
    plt.axis("off")
# show the figure
plt.show()
# compare the images
compare_images(original, original, "Original vs. Original")
compare_images(original, contrast, "Original vs. Contrast")
compare_images(original, shopped, "Original vs. Photoshopped")

Reference- https://www.pyimagesearch.com/2014/09/15/python-compare-two-images/


问:
UISegmentedControl change number of segments programmatically
Is there a way to change the number of segments programmatically?</p>

答:
adding and deleting segments in swift4 using code

```<code>class ViewController: UIViewController {

  @IBOutlet weak var segment1: UISegmentedControl!

  override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
  }

  @IBAction func insert(_ sender: Any) {
    segment1.insertSegment(withTitle: "\(segment1.numberOfSegments+1)", at: segment1.numberOfSegments, animated: true)
  }

  @IBAction func remove(_ sender: Any) {
    segment1.removeSegment(at: segment1.numberOfSegments-1, animated: true)
  }
}
</code>```

Body:
adding and deleting segments in swift4 using code

class ViewController: UIViewController {

  @IBOutlet weak var segment1: UISegmentedControl!

  override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
  }

  @IBAction func insert(_ sender: Any) {
    segment1.insertSegment(withTitle: "\(segment1.numberOfSegments+1)", at: segment1.numberOfSegments, animated: true)
  }

  @IBAction func remove(_ sender: Any) {
    segment1.removeSegment(at: segment1.numberOfSegments-1, animated: true)
  }
}


问:
debuild - dependencies set but without version
Lets say I have the following package: zs-boost_1.71.0_armhf.deb. This is custom package that installs boost 1.71 to some custom location (assume /opt/deps).

I also have project that uses this library. It builds and runs fine. Now I'm packaging it. I have the following in debian/control file:

Depends: ${shlibs:Depends}, ${misc:Depends}
```

<p>I build package using: <code>debuild -b -us -uc -aarmhf</code>. Package can be built and works as expected. My only problem is that its <code>Depends</code> entry in deb's <code>control</code> file is as follows:</p>

<pre class="lang-sh prettyprint-override"><code>Depends: Depends: libc6 (>= 2.9), libpq5 (>= 9.0~), zs-boost, init-system-helpers (>= 1.18~)
</code>```

Note that zs-boost has no version. How can I fix it? Is it caused by installation to custom directory? I'd assume that if package was identified correctly, then its version should be used as well?

debian/package.substvars contains the following line for shlibs:

shlibs:Depends=libc6 (>= 2.9), libssl1.1 (>= 1.1.0), libuuid1 (>= 2.16), zs-boost
```

What should I do for the dependencies to be properly versioned? Note that I am not interested in providing version numbers manually, this is only one package and we have 20+ packages that are constantly updated and rebuilt and doing it by hand is out of question.

Thanks in advance.

答:
If you want a versioned dependency, put one in debian/control.

```<code>Depends: zs-boost (>= 1.71.0)
</code>```

The versioned dependency on a specific version of libc6 you see in the generated shlibs is ultimately down to a similar explicit declaration determined (usually conservatively and with great care) by a package maintainer.

Body:
Lets say I have the following package: zs-boost_1.71.0_armhf.deb. This is custom package that installs boost 1.71 to some custom location (assume /opt/deps).

I also have project that uses this library. It builds and runs fine. Now I'm packaging it. I have the following in debian/control file:

Depends: ${shlibs:Depends}, ${misc:Depends}

I build package using: debuild -b -us -uc -aarmhf. Package can be built and works as expected. My only problem is that its Depends entry in deb's control file is as follows:

Depends: Depends: libc6 (>= 2.9), libpq5 (>= 9.0~), zs-boost, init-system-helpers (>= 1.18~)

Note that zs-boost has no version. How can I fix it? Is it caused by installation to custom directory? I'd assume that if package was identified correctly, then its version should be used as well?

debian/package.substvars contains the following line for shlibs:

shlibs:Depends=libc6 (>= 2.9), libssl1.1 (>= 1.1.0), libuuid1 (>= 2.16), zs-boost

What should I do for the dependencies to be properly versioned? Note that I am not interested in providing version numbers manually, this is only one package and we have 20+ packages that are constantly updated and rebuilt and doing it by hand is out of question.

Thanks in advance.

Body:
If you want a versioned dependency, put one in debian/control.

Depends: zs-boost (>= 1.71.0)

The versioned dependency on a specific version of libc6 you see in the generated shlibs is ultimately down to a similar explicit declaration determined (usually conservatively and with great care) by a package maintainer.


问:
Use variable from DataTables ajax response to populate yadcf filter
I have a DataTables table defined like this:

```<code>$(function () {
  var yadcf_data_3;
  var oTable = $('#example').DataTable({
    "serverSide": true,
    "ajax": {"url": "/platform/elements/?format=datatables",
             "dataSrc": function(json){
               yadcf_data_3 = json.options.yadcf_data_3
               //this line returns the appropriate list of values
               console.log(yadcf_data_3)
               return json.data;
              }
            }
          });

   //this line returns undefined
   console.log(yadcf_data_3)

   //other stuff

  yadcf.exRefreshColumnFilterWithDataProp(oTable, 3, yadcf_data_3);
});
</code>```

How do I use yadcf_data_3 to populate a filter for the table? yadcf_data_3 returns undefined outside of the oTable variable.

答:
```<code>var table = $("#employeetable").DataTable({
                "ajax": {
                    "url": "/url",
                    "type": "POST",
                    "datatype": "json"
                    , dataSrc: function (data) {
                        CalculateSum= data.CalculateSum;
                        return data.data;
                    }
                }

....
 drawCallback: function (settings) {
                    var api = this.api();
                    $('#CalculateSum').html(CalculateSum);
                },
                "serverSide": "true",
                "order": [0, "desc"],
</code>```

Body:
I have a DataTables table defined like this:

$(function () {
  var yadcf_data_3;
  var oTable = $('#example').DataTable({
    "serverSide": true,
    "ajax": {"url": "/platform/elements/?format=datatables",
             "dataSrc": function(json){
               yadcf_data_3 = json.options.yadcf_data_3
               //this line returns the appropriate list of values
               console.log(yadcf_data_3)
               return json.data;
              }
            }
          });

   //this line returns undefined
   console.log(yadcf_data_3)

   //other stuff

  yadcf.exRefreshColumnFilterWithDataProp(oTable, 3, yadcf_data_3);
});

How do I use yadcf_data_3 to populate a filter for the table? yadcf_data_3 returns undefined outside of the oTable variable.


问:
Eclipse: change JDK for all projects in Workspace
I have received a whole bunch of Eclipse Projects as a ZIP-File. I imported all of them into my new Workspace dedicated for this Task. They are all preconfigured from the other Dev's Workspace. In general I don't mind, so i do not have to setup every one of these Plugin-Projects.

What i do mind is that each and every Project is set to run with a specific JRE from the other guys installation (which I obviously don't have). Is there a convenient Way to change all the Projects in my Workspace to the Workspace default JRE?

I am really not looking forward to right click on every of these ~30 Projects and change it manually.

答: If they are not Maven or Gradle projects, you can change the .classpath XML files accordingly (<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/..."/>) using a shell/batch or Ant script. Then do a refresh (e.g. by selecting all projects and hitting F5) so that Eclipse is aware of the change.


答:
Maybe this?</p>

```<code>>>> from itertools import chain
>>> text = ['a,b', 'c,d']
>>> list(chain(*[item.split(',') for item in text]))
['a', 'b', 'c', 'd']
</code>```

Title: Splitting words in a list

Body:
Maybe this?

>>> from itertools import chain
>>> text = ['a,b', 'c,d']
>>> list(chain(*[item.split(',') for item in text]))
['a', 'b', 'c', 'd']


问:
UIPrinterPickerController not showing on iOS 13
I've been trying to get a UIPrinterPicker to show up but for some reason it just never does. The completion handler gets called immediately. The UIPrintInteractionController shows up just fine but this one refuses to show for some reason. This is the code I am using currently </p>

<pre class="lang-swift prettyprint-override"><code>    let picker = UIPrinterPickerController(initiallySelectedPrinter: nil)
    picker.present(animated: true) { (controller, complete, error) in
        print("done")
    }
</code>```

答:
Implement UIPrinterPickerControllerDelegate so it works for iOS 13
  https://developer.apple.com/documentation/uikit/uiprinterpickercontroller/1620514-present

```<code>class ViewController: UIViewController {

    @IBAction func btnTapped(_ sender: Any) {
        let picker = UIPrinterPickerController(initiallySelectedPrinter: nil)
        picker.delegate = self
        picker.present(animated: true) { (controller, complete, error) in
            print("done")
        }
    }
}

// MARK:- UIPrinterPickerControllerDelegate
extension ViewController: UIPrinterPickerControllerDelegate {
    func printerPickerControllerParentViewController(_ printerPickerController: UIPrinterPickerController) -> UIViewController? {
        return self
    }
}
</code>```

Body:
I've been trying to get a UIPrinterPicker to show up but for some reason it just never does. The completion handler gets called immediately. The UIPrintInteractionController shows up just fine but this one refuses to show for some reason. This is the code I am using currently

    let picker = UIPrinterPickerController(initiallySelectedPrinter: nil)
    picker.present(animated: true) { (controller, complete, error) in
        print("done")
    }

Body:
Implement UIPrinterPickerControllerDelegate so it works for iOS 13
  https://developer.apple.com/documentation/uikit/uiprinterpickercontroller/1620514-present

class ViewController: UIViewController {

    @IBAction func btnTapped(_ sender: Any) {
        let picker = UIPrinterPickerController(initiallySelectedPrinter: nil)
        picker.delegate = self
        picker.present(animated: true) { (controller, complete, error) in
            print("done")
        }
    }
}

// MARK:- UIPrinterPickerControllerDelegate
extension ViewController: UIPrinterPickerControllerDelegate {
    func printerPickerControllerParentViewController(_ printerPickerController: UIPrinterPickerController) -> UIViewController? {
        return self
    }
}


问:
Need advice assigning XY coordinates with dataset
I am currently building a human predictive model using received signal strength indicator(rssi). I was wondering if its possible to assign the dataset to the XY coordinates and train the model with k nearest neighbour to predict human location thus returning a XY coordinate within the setup? I have been trying to use numpy to create an array of the specific data collected XY coordinates. However as I have collected 10 samples of rssi data of each location, I am in a dilemma on how to proceed with the assigning of the dataset.

If this isn't a feasible method, could anyone point me the right direction to achieve my desired result?

Appreciate any help, please feel free to ask if you require additional information.

答:
I believe X and Y cordinate will form 2 columns of your dataset which can further be trained using KNN. Have a look at simple example here:
https://www.analyticsvidhya.com/blog/2018/03/introduction-k-neighbours-algorithm-clustering/</p>


问:
How to handle "single click" and "double click" on the same html DOM element using typescript:Angular 2 or 4?
My issue is, the methods used for both the events is getting triggered when I perform "double click"

For example, I need to perform specific functionality when specific event is triggered.

```<code><a (click)="method1()" (dblclick)="method2()">
</code>```

Both method1() and method2() are getting triggered when I perform "double click".

答:
```<code>clickCount = 0;
click() {
    this.clickCount++;
    setTimeout(() => {
        if (this.clickCount === 1) {
             // single
        } else if (this.clickCount === 2) {
            // double
        }
        this.clickCount = 0;
    }, 250)
}
</code>```

Body:
My issue is, the methods used for both the events is getting triggered when I perform "double click"

For example, I need to perform specific functionality when specific event is triggered.

Both method1() and method2() are getting triggered when I perform "double click".


问:
What is the best practice for adding constants in laravel? (Long List)
I am rather new to laravel. I have a basic question, What is the best way to add constants in laravel.
I know the .env method that we use to add the constants.
Also I have made one constants file to use them for my project.
For example:

```<code>define('OPTION_ATTACHMENT', 13);
define('OPTION_EMAIL', 14);
define('OPTION_MONETERY', 15);
define('OPTION_RATINGS', 16);
define('OPTION_TEXTAREA', 17);
</code>```

And so on. It can reach upto 100 or more records. So What should be the best approach to write the constants. The .env method. Or adding the constant.php file?

Thanks

答:
You can simply do this:

Put your constants to 'config/app.php' on main array, like:

```<code>'CONSTANT_NAME' => 'CONSTANT_VALUE',
</code>```

Use them where ever you want with:

```<code>{{ Config::get('CONSTANT_NAME') }}
</code>```

Body:
I am rather new to laravel. I have a basic question, What is the best way to add constants in laravel.
I know the .env method that we use to add the constants.
Also I have made one constants file to use them for my project.
For example:

define('OPTION_ATTACHMENT', 13);
define('OPTION_EMAIL', 14);
define('OPTION_MONETERY', 15);
define('OPTION_RATINGS', 16);
define('OPTION_TEXTAREA', 17);

And so on. It can reach upto 100 or more records. So What should be the best approach to write the constants. The .env method. Or adding the constant.php file?

Thanks

Body:
You can simply do this:

Put your constants to 'config/app.php' on main array, like:

'CONSTANT_NAME' => 'CONSTANT_VALUE',

Use them where ever you want with:

{{ Config::get('CONSTANT_NAME') }}


问:
Android Kotlin how to pass named function as parameter into another function to be executed when JsonObjectRequest return success?
I have a function named doReq it will do a JsonObjectRequest and when success i need it to execute a named function i pass in with the success response return from the request. Please take a look at code below,

```<code>package mypackage1
fun reqSuccess(resp: JSONObject) {
}
</code>```

```<code>package mypackage2
fun doReq(url: String, how do i pass in reqSuccess function here?) {
    val req: JsonObjectRequest = object : JsonObjectRequest(Request.Method.POST, url, json,
            Response.Listener { response ->
                // need to perform reqSuccess here passing in response
            },
            Response.ErrorListener { error ->
            }
    )
}
</code>```

Additional note, doReq will be called in other packages and each package has it's own reqSuccess function. Ok below is correct now,

```<code>    package mypackage2
    fun doReq(url: String, onSuccess: (response: JSONObject) -> Unit) {
        val req: JsonObjectRequest = object : JsonObjectRequest(Request.Method.POST, url, json,
                Response.Listener { response ->
                   onSuccess(response)
                },
                Response.ErrorListener { error ->
                }
        )
    }
</code>```

```<code>package mypackage1
fun reqSuccess(resp: JSONObject) {
}

doReg("someurl",::reqSuccess)
</code>```

答:
You should add lambda parameter to doReq() function:

```<code>fun doReq(url: String, onSuccess: (response: JSONObject) -> Unit = ::reqSuccess) {
    val req: JsonObjectRequest = object : JsonObjectRequest(Request.Method.POST, url, json,
            Response.Listener { response ->
               onSuccess(response)
            },
            Response.ErrorListener { error ->
            }
    )
}
</code>```

You can call that function like following:

```<code>doReq("someurl")
</code>```

Body:
I have a function named doReq it will do a JsonObjectRequest and when success i need it to execute a named function i pass in with the success response return from the request. Please take a look at code below,

package mypackage1
fun reqSuccess(resp: JSONObject) {
}

package mypackage2
fun doReq(url: String, how do i pass in reqSuccess function here?) {
    val req: JsonObjectRequest = object : JsonObjectRequest(Request.Method.POST, url, json,
            Response.Listener { response ->
                // need to perform reqSuccess here passing in response
            },
            Response.ErrorListener { error ->
            }
    )
}

Additional note, doReq will be called in other packages and each package has it's own reqSuccess function. Ok below is correct now,

    package mypackage2
    fun doReq(url: String, onSuccess: (response: JSONObject) -> Unit) {
        val req: JsonObjectRequest = object : JsonObjectRequest(Request.Method.POST, url, json,
                Response.Listener { response ->
                   onSuccess(response)
                },
                Response.ErrorListener { error ->
                }
        )
    }

package mypackage1
fun reqSuccess(resp: JSONObject) {
}

doReg("someurl",::reqSuccess)

Body:
You should add lambda parameter to doReq() function:

fun doReq(url: String, onSuccess: (response: JSONObject) -> Unit = ::reqSuccess) {
    val req: JsonObjectRequest = object : JsonObjectRequest(Request.Method.POST, url, json,
            Response.Listener { response ->
               onSuccess(response)
            },
            Response.ErrorListener { error ->
            }
    )
}

You can call that function like following:

doReq("someurl")


问:
CrystalDecisions.Shared.CrystalReportsException:Load report failed. The document has not opened
I have method and I am using crystal-decision report and its throwing an inner exception. How do I fix this issue? I have seen similar topic, but mine does not really solve similar problem as I have attempted to do the same. Please see my logic below and screen shot for more detail. In another words my load method does not open.

// Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AdvertReport(FormCollection fc)
{
    DataSet ds = obIlReports.Generate_AdvertDetailsReport();
    ds.Tables[0].TableName = "Tbl_TrainingAcademy";

    if(ds.Tables[0].Rows.Count > 0)
    {
        ReportClass rptH = new ReportClass();
        rptH.FileName = Server.MapPath("~/Reports/AdvertReport.rpt");
        rptH.Load(); // The document do not open error is thrown here.
        rptH.SetDataSource(ds.Tables[0]);
        Response.Buffer = false;
        Response.ClearContent();
        Response.ClearHeaders();

        Stream stream = rptH.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
        stream.Seek(0, SeekOrigin.Begin);
        return File(stream, "application/pdf", "AdvertReport.pdf");
    }
    return View();
}
```

<pre class="lang-cs prettyprint-override"><code>// Ilreport here with store procedure.
public class ReportsMaster : IlReports
{
    public DataSet Generate_AdvertDetailsReport()
    {
        using(SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["eNtsaOnlineRegistrationDB"].ToString()))
        {
            con.Open();
            DataSet ds = new DataSet();

            // Handling Exception
            try
            {
                SqlCommand cmd = new SqlCommand("dbo.GetAdvertReport", con);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = cmd;
                da.Fill(ds);

                if(ds.Tables.Count > 0)
                {
                    return ds;
                }
                else
                {
                    return ds = null;
                }

            }
            catch(Exception )
            {
                throw;
            }
            finally
            {
                ds.Dispose();
            }
        }
    }
}
</code>```

// ConnectionString
<connectionStrings>
    <add name="eNtsaOnlineRegistrationDB" connectionString="Data Source=GcobaniM-L\SQLEXPRESS; DataBase=eNtsaOnlineRegistrationDB; Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
```

答:
The problem i had was simple, i created report file without having an extension report like crystal report install for Microsoft Visual Studio. Here is the link for Windows for your compatibility.

https://www.sap.com/cmp/td/sap-crystal-reports-visual-studio-trial.html?trial=%2F%2Fwww.sap.com%2Fregistration%2Ftrial.9a4afb3b-7eaa-42af-98ce-abeae5deb784.html

After the installation of this software, the Visual Studio will have Reporting. See my screen shot for idea or clue.

Make sure your VS is closed until the software is done.

Then you create your report and give a its path based on your project application.

If you get an exception like one below;

Could not load file or assembly CrystalDecisions.CrystalReports.Engine

Follow the steps as mentioned from the forum and your application should work, if not troubleshoot.

Body:
I have method and I am using crystal-decision report and its throwing an inner exception. How do I fix this issue? I have seen similar topic, but mine does not really solve similar problem as I have attempted to do the same. Please see my logic below and screen shot for more detail. In another words my load method does not open.

// Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AdvertReport(FormCollection fc)
{
    DataSet ds = obIlReports.Generate_AdvertDetailsReport();
    ds.Tables[0].TableName = "Tbl_TrainingAcademy";

    if(ds.Tables[0].Rows.Count > 0)
    {
        ReportClass rptH = new ReportClass();
        rptH.FileName = Server.MapPath("~/Reports/AdvertReport.rpt");
        rptH.Load(); // The document do not open error is thrown here.
        rptH.SetDataSource(ds.Tables[0]);
        Response.Buffer = false;
        Response.ClearContent();
        Response.ClearHeaders();

        Stream stream = rptH.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
        stream.Seek(0, SeekOrigin.Begin);
        return File(stream, "application/pdf", "AdvertReport.pdf");
    }
    return View();
}

// Ilreport here with store procedure.
public class ReportsMaster : IlReports
{
    public DataSet Generate_AdvertDetailsReport()
    {
        using(SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["eNtsaOnlineRegistrationDB"].ToString()))
        {
            con.Open();
            DataSet ds = new DataSet();

            // Handling Exception
            try
            {
                SqlCommand cmd = new SqlCommand("dbo.GetAdvertReport", con);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlDataAdapter da = new SqlDataAdapter();
                da.SelectCommand = cmd;
                da.Fill(ds);

                if(ds.Tables.Count > 0)
                {
                    return ds;
                }
                else
                {
                    return ds = null;
                }

            }
            catch(Exception )
            {
                throw;
            }
            finally
            {
                ds.Dispose();
            }
        }
    }
}

// ConnectionString
<connectionStrings>
    <add name="eNtsaOnlineRegistrationDB" connectionString="Data Source=GcobaniM-L\SQLEXPRESS; DataBase=eNtsaOnlineRegistrationDB; Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>


问:
Optimizing SQL INSERT query
I have recently been looking into possible ways how to optimize my INSERT queries. I am doing usually an INSERT with a batch size of 100.

My current example query:

```<code>IF EXISTS (SELECT * FROM [db].[Prices] WHERE Source = 'Cars' AND TradeDate = convert(datetime,'18-02-20',5) AND Product = 'Audi' AND Price=NULLIF('5.00000',''))

BEGIN DELETE FROM [db].[Prices] WHERE Source = 'Cars' AND TradeDate = convert(datetime,'18-02-20',5) AND Product = 'Audi' AND Price=NULLIF('5.00000','') END;

INSERT INTO [db].[Prices] VALUES( 'Cars', convert(datetime,'18-02-20',5), 'APR25', NULL, 'Audi', NULLIF('5.00000',''), convert(datetime,'15-04-25',5), '1', GETUTCDATE(), convert(date,NULL,105), convert(date,NULL,105));
</code>```

The possible optimizations that I have found from research are as following:

Replace * with fields

Replace WHERE with INNER JOIN

As this is rather new to me, any suggestions are welcome. It seems like the highest potential is in changing the core structure (IF EXISTS - DELETE - INSERT INTO).

Thank you for any help.

答:
EXISTS will not necessary here you can use DELETE statement :

```<code> DELETE
 FROM [db].[Prices]
 WHERE Source = 'Cars' AND TradeDate = CONVERT(DATETIME,'18-02-20', 5) AND
       Contract = 'APR25' AND ProductCode = 'Audi' AND
       Price = NULLIF('5.00000','') -- this will always 5.00000 `NULLIF` will not required
       AND Strike = '27.7500';
</code>```

Then you can use INSERT Statement :

```<code>INSERT INTO [db].[Prices] (col1, col2, col3, . . .) -- Qualify all columns
    VALUES( 'Cars', convert(datetime,'18-02-20',5), 'APR25', NULL, 'Audi',
             NULLIF('5.00000',''), convert(datetime,'15-04-25',5), '1',
             GETUTCDATE(), convert(date,NULL,105),
             convert(date,NULL,105), 04, 2025, NULL, NULL, '27.7500', '20',
             NULL, '0.5',NULL
          );
</code>```

You can remove nullif() & conversation style in where clause :

```<code>WHERE Source = 'Cars' AND TradeDate = '2020-02-18' AND
      Contract = 'APR25' AND ProductCode = 'Audi' AND
      Price = 5.00000 AND Strike = '27.7500';
</code>```

You might need NULLIF() on Price :

```<code>NULLIF(Price, '')
</code>```

Note : Always qualify all columns explicitly while using INSERT INTO . . statement.

Title: Optimizing SQL INSERT query

Body:
I have recently been looking into possible ways how to optimize my INSERT queries. I am doing usually an INSERT with a batch size of 100.

My current example query:

IF EXISTS (SELECT * FROM [db].[Prices] WHERE Source = 'Cars' AND TradeDate = convert(datetime,'18-02-20',5) AND Product = 'Audi' AND Price=NULLIF('5.00000',''))

BEGIN DELETE FROM [db].[Prices] WHERE Source = 'Cars' AND TradeDate = convert(datetime,'18-02-20',5) AND Product = 'Audi' AND Price=NULLIF('5.00000','') END;

INSERT INTO [db].[Prices] VALUES( 'Cars', convert(datetime,'18-02-20',5), 'APR25', NULL, 'Audi', NULLIF('5.00000',''), convert(datetime,'15-04-25',5), '1', GETUTCDATE(), convert(date,NULL,105), convert(date,NULL,105));

The possible optimizations that I have found from research are as following:

Replace * with fields

Replace WHERE with INNER JOIN

As this is rather new to me, any suggestions are welcome. It seems like the highest potential is in changing the core structure (IF EXISTS - DELETE - INSERT INTO).

Thank you for any help.

Body:
EXISTS will not necessary here you can use DELETE statement :

 DELETE
 FROM [db].[Prices]
 WHERE Source = 'Cars' AND TradeDate = CONVERT(DATETIME,'18-02-20', 5) AND
       Contract = 'APR25' AND ProductCode = 'Audi' AND
       Price = NULLIF('5.00000','') -- this will always 5.00000 `NULLIF` will not required
       AND Strike = '27.7500';

Then you can use INSERT Statement :

INSERT INTO [db].[Prices] (col1, col2, col3, . . .) -- Qualify all columns
    VALUES( 'Cars', convert(datetime,'18-02-20',5), 'APR25', NULL, 'Audi',
             NULLIF('5.00000',''), convert(datetime,'15-04-25',5), '1',
             GETUTCDATE(), convert(date,NULL,105),
             convert(date,NULL,105), 04, 2025, NULL, NULL, '27.7500', '20',
             NULL, '0.5',NULL
          );

You can remove nullif() & conversation style in where clause :

WHERE Source = 'Cars' AND TradeDate = '2020-02-18' AND
      Contract = 'APR25' AND ProductCode = 'Audi' AND
      Price = 5.00000 AND Strike = '27.7500';

You might need NULLIF() on Price :

NULLIF(Price, '')

Note : Always qualify all columns explicitly while using INSERT INTO . . statement.


问:
Python 3.8: IndexError when using append()
I made a little "console" that splits the command with split(). I am separating the "command" (the first "word" from the input()) from the "arguments" coming after the first word. Here's the code that generates an error:

```<code>cmdCompl = input(prompt).strip().split()
cmdRaw = cmdCompl[0]
args = addArgsToList(cmdCompl)
</code>```

addArgsToList() function:

```<code>def addArgsToList(lst=[]):
    newList = []
    for i in range(len(lst)):
        newList.append(lst[i+1])
    return newList
</code>```

I try to add every word after cmdRaw to a list called args which is returned by addArgsToList(). But what I get instead is:

```<code>Welcome to the test console!

Type help or ? for a list of commands

testconsole >>> help
Traceback (most recent call last):
  File "testconsole.py", line 25, in <module>
    args = addArgsToList(cmdCompl)
  File "testconsole.py", line 15, in addArgsToList
    newList.append(lst[i+1])
IndexError: list index out of range
</code>```

I cannot figure out why I get an IndexError because as far as I know, newList can be dynamically allocated.

Any help?

答:
You should do like this:

if you wish to avoid first element to be appended

```<code>def addArgsToList(lst=[]):
    newList = []
    for i in range(1,len(lst)):
        newList.append(lst[i])
    return newList
</code>```

if you just trying to copy the elements in a new list just do this:

```<code>newList = lst[1:].copy()
</code>```

Body:
I made a little "console" that splits the command with split(). I am separating the "command" (the first "word" from the input()) from the "arguments" coming after the first word. Here's the code that generates an error:

cmdCompl = input(prompt).strip().split()
cmdRaw = cmdCompl[0]
args = addArgsToList(cmdCompl)

addArgsToList() function:

def addArgsToList(lst=[]):
    newList = []
    for i in range(len(lst)):
        newList.append(lst[i+1])
    return newList

I try to add every word after cmdRaw to a list called args which is returned by addArgsToList(). But what I get instead is:

Welcome to the test console!

Type help or ? for a list of commands

testconsole >>> help
Traceback (most recent call last):
  File "testconsole.py", line 25, in <module>
    args = addArgsToList(cmdCompl)
  File "testconsole.py", line 15, in addArgsToList
    newList.append(lst[i+1])
IndexError: list index out of range

I cannot figure out why I get an IndexError because as far as I know, newList can be dynamically allocated.

Any help?

Body:
You should do like this:

if you wish to avoid first element to be appended

def addArgsToList(lst=[]):
    newList = []
    for i in range(1,len(lst)):
        newList.append(lst[i])
    return newList

if you just trying to copy the elements in a new list just do this:

newList = lst[1:].copy()


问:
Derived type's properties missing in JSON response from ASP.NET Core API
The JSON response from my ASP.NET Core 3.1 API controller is missing properties. This happens when a property uses a derived type; any properties defined in the derived type but not in the base/interface will not be serialized to JSON. It seems there is some lack of support for polymorphism in the response, as if serialization is based on a property's defined type instead of its runtime type. How can I change this behavior to ensure that all public properties are included in the JSON response?

Example:

My .NET Core Web API Controller returns this object that has a property with an interface type.

    // controller returns this object
    public class Result
    {
        public IResultProperty ResultProperty { get; set; }   // property uses an interface type
    }

    public interface IResultProperty
    { }
```

<p>Here is a derived type that defines a new public property named <code>Value</code>.</p>

<pre class="lang-cs prettyprint-override"><code>    public class StringResultProperty : IResultProperty
    {
        public string Value { get; set; }
    }
</code>```

If I return the derived type from my controller like this:

    return new MainResult {
        ResultProperty = new StringResultProperty { Value = "Hi there!" }
    };
```

<p>then the actual response includes an empty object (the <code>Value</code> property is missing):</p>

<p><img src="https://i.stack.imgur.com/gy6Ie.png" alt="enter image description here"></p>

<p>I want the response to be:</p>

```    {
        "ResultProperty": { "Value": "Hi there!" }
    }
```

答:
While the other answers are good and solves the problem, if all you want is the general behavior to be like pre netcore3, you can use the Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet package and in Startup.cs do:

services.AddControllers().AddNewtonsoftJson()
```

More info here. This way, you don't need to create any extra json-converters.

Body:
The JSON response from my ASP.NET Core 3.1 API controller is missing properties. This happens when a property uses a derived type; any properties defined in the derived type but not in the base/interface will not be serialized to JSON. It seems there is some lack of support for polymorphism in the response, as if serialization is based on a property's defined type instead of its runtime type. How can I change this behavior to ensure that all public properties are included in the JSON response?

Example:

My .NET Core Web API Controller returns this object that has a property with an interface type.

    // controller returns this object
    public class Result
    {
        public IResultProperty ResultProperty { get; set; }   // property uses an interface type
    }

    public interface IResultProperty
    { }

Here is a derived type that defines a new public property named Value.

    public class StringResultProperty : IResultProperty
    {
        public string Value { get; set; }
    }

If I return the derived type from my controller like this:

    return new MainResult {
        ResultProperty = new StringResultProperty { Value = "Hi there!" }
    };

then the actual response includes an empty object (the Value property is missing):

I want the response to be:

    {
        "ResultProperty": { "Value": "Hi there!" }
    }

Body:
While the other answers are good and solves the problem, if all you want is the general behavior to be like pre netcore3, you can use the Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet package and in Startup.cs do:

services.AddControllers().AddNewtonsoftJson()

More info here. This way, you don't need to create any extra json-converters.


问:
Graphql syntax for single query for same field with different parameters from an array
I am looking for something like the below pseudo query:

```<code>query users($ids: [String!]) {
 "id from $ids": getUser(id){
    id
    name
    dob
  }
}
</code>```

To get a response like:

```<code>data: {
 '039ccf5c-3070-4368-b790-0884669e759d': {id: '039ccf5c-3070-4368-b790-0884669e759d', name: 'u1', 'dob': 12-12-12'},
'139ccf5c-3070-4368-b790-0884669e759d': {id: '139ccf5c-3070-4368-b790-0884669e759d', name: 'u1', 'dob': 12-12-12'},
}
</code>```

Is this possible?

答:
You can use aliases to query to the same field multiple times:

```<code>query users($id1: String!, $id2: String!) {
  user1: getUser(id: $id1) {
    ...UserFragment
  }
  user2: getUser(id: $id1) {
    ...UserFragment
  }
}

fragment UserFragment on User {
  id
  name
  dob
}
</code>```

There are no control structures in GraphQL, so there's no way to loop through a value that is a list. If your list of IDs is of variable length, then you'll have to construct a query similar to the above programmatically, dynamically generating both the variable definitions and the aliased fields.

Body:
I am looking for something like the below pseudo query:

query users($ids: [String!]) {
 "id from $ids": getUser(id){
    id
    name
    dob
  }
}

To get a response like:

data: {
 '039ccf5c-3070-4368-b790-0884669e759d': {id: '039ccf5c-3070-4368-b790-0884669e759d', name: 'u1', 'dob': 12-12-12'},
'139ccf5c-3070-4368-b790-0884669e759d': {id: '139ccf5c-3070-4368-b790-0884669e759d', name: 'u1', 'dob': 12-12-12'},
}

Is this possible?

Body:
You can use aliases to query to the same field multiple times:

query users($id1: String!, $id2: String!) {
  user1: getUser(id: $id1) {
    ...UserFragment
  }
  user2: getUser(id: $id1) {
    ...UserFragment
  }
}

fragment UserFragment on User {
  id
  name
  dob
}

There are no control structures in GraphQL, so there's no way to loop through a value that is a list. If your list of IDs is of variable length, then you'll have to construct a query similar to the above programmatically, dynamically generating both the variable definitions and the aliased fields.


问:
Date is in numeric data type field, would like to group by month using SQL Developer
I've been tasked to query a database using SQL Developer where the date is in a field type "numeric" (e.g. '20190101'). The ask is to provide an output by month and year, so DATEID between 20190101 and 20190131 would be January 2019. After searching online, I'm really at a loss on how to simplify this so I don't have to run a separate query for each month. Could someone provide some guidance?</p>

答:
Another answer</p>

```<code>SELECT TO_CHAR(TO_date(20190101, 'YYYYMMDD'), 'MONTH YYYY') AS SOME_DATE FROM dual;

#result
SOME_DATE     |
--------------|
JANUARY   2019|
</code>```

Body:
Another answer

SELECT TO_CHAR(TO_date(20190101, 'YYYYMMDD'), 'MONTH YYYY') AS SOME_DATE FROM dual;

#result
SOME_DATE     |
--------------|
JANUARY   2019|


问:
How to activate component only when data comes from server?
There is a parent component where I call its child component:

```<code> <app-add-object-layer-component></app-add-object-layer-component>
</code>```

Child has a service inside:

```<code> constructor(private editService: editService) {

 }

 getEditData(){
    return this.editService.get();
 }
</code>```

Child component is initialised always even there is no data returned.

Sure, I can move editService upper and use it like:

```<code><app-add-object-layer-component *ngIf="editService.getEditData()"></app-add-object-layer-component>
</code>```

But in this case parent component has alien dependency constructor(private editService: editService) {}

How to show/hide child component in parent component according to data returned by getEditData method?

答:
declare the component variable data:any;
Then in ngOnInit() {} get this data from server using your service function like this.editService.getEditData.subscribe(res=> this.data = res)

then in html you use it like <app-add-object-layer-component *ngIf="data"></app-add-object-layer-component>

Body:
There is a parent component where I call its child component:

 <app-add-object-layer-component></app-add-object-layer-component>

Child has a service inside:

 constructor(private editService: editService) {

 }

 getEditData(){
    return this.editService.get();
 }

Child component is initialised always even there is no data returned.

Sure, I can move editService upper and use it like:

<app-add-object-layer-component *ngIf="editService.getEditData()"></app-add-object-layer-component>

But in this case parent component has alien dependency constructor(private editService: editService) {}

How to show/hide child component in parent component according to data returned by getEditData method?


问:
How to implement a ScheduledExecutorService on top of a ExecutorService instance?
We have one central ExecutorService instance, that we try to use everywhere in our application server.

Unfortunately, we should now also use some library that wants a ScheduledExecutorService.

How do I get a ScheduledExecutorService, that is a wrapper on top of our ExecutorService instance?

It looks like Guava and Apache commons-* do not have that (or I was not able to recognize it).

EDIT: I've researched why we have a custom ExecutorService. Some "tasks" (Runnables) should be run as daemon, and others not. But you cannot change the "daemon" flag after thread creation. So we have 2 ExecutorService instances, which extend ThreadPoolExecutor. Also, we do some stuff before and after running the Runnables (like setting up the "logging configuration"). Finally, we have a custom ExecutorService "wrapper", which act as our central ExecutorService instance, and based on "task instanceof DaemonRunnable", delegates to either of the real ExecutorServices.

So, if there isn't a better option, we could extend ScheduledThreadPoolExecutor instead of ThreadPoolExecutor, and implement delegation for the missing methods from ScheduledExecutorService into the "wrapper".

Basically, my question was if we need to do this, or if some ScheduledExecutorService implementation wrapping an ExecutorService already exists in a "standard" library, that we could just use.

答: ScheduledExecutorService is available as part of Java language. If you want to make a separate wrapper over ExecutorService that would provide ScheduledExecutorService functionality you will have to write it yourself, but that would be a waste of time. What you need to do is to have your central ExecutorService instance to be an instance of ScheduledExecutorService. Note that ScheduledExecutorService extends ExecutorService and thus could be used as ExecutorService or ScheduledExecutorService as needed.</p>


问:
Passing in tags to Gradle cucumber task
I know that we can pass cucumber tags to Gradle by specifying the following in build.gradle file:

```<code>test {
    systemProperty "cucumber.options", System.getProperty("cucumber.options")
}
</code>```

So when you run gradlew test -Dcucumber.options="--tags @CDC" it will only runs scenarios with CDC tag.

But my question is whether I can pass the cucumber options to the cucumber task. The reason I need to do this is because my cucumber task creates a JSON file after running the task, and I'm using gradle-cucumber-reporting plugin (https://github.com/SpacialCircumstances/gradle-cucumber-reporting) to generate a report based on the JSON file.

cucumber task

```<code>task cucumber() {
    dependsOn assemble, compileTestJava
    doLast {
        javaexec {
            main = "io.cucumber.core.cli.Main"
            classpath = configurations.cucumberRuntime + sourceSets.main.output + sourceSets.test.output
            args = [
            '--plugin', 'html:cucumber-report',
            '--plugin', 'json:cucumber.json', //generates a .json report file
            '--plugin', 'pretty',
            '--plugin', 'usage:cucumber-usage.json',
            '--glue', 'hellocucumber', 'src/test/resources']
        }
    }
}
</code>```

Running the test task in Gradle doesn't update the JSON file.

Here's the snippet for gradle-cucumber-reporting:

```<code>cucumberReports {
  outputDir = file('cucumber-pretty-report')
  buildId = '0'
  reports = files('cucumber.json')
}
</code>```

答:
You can add something like this to your cucumber task:

```<code>def tags = getProperty("tags")
args = [
'--plugin', 'html:cucumber-report',
'--plugin', 'json:cucumber.json', //generates a .json report file
'--plugin', 'pretty',
'--plugin', 'usage:cucumber-usage.json',
'--glue', 'hellocucumber', 'src/test/resources',
'--tags', tags]
</code>```

Then you can run your task this way:

```<code>gradle cucumber -P tags=smoke
</code>```

Title: Passing in tags to Gradle cucumber task

Body:
I know that we can pass cucumber tags to Gradle by specifying the following in build.gradle file:

test {
    systemProperty "cucumber.options", System.getProperty("cucumber.options")
}

So when you run gradlew test -Dcucumber.options="--tags @CDC" it will only runs scenarios with CDC tag.

But my question is whether I can pass the cucumber options to the cucumber task. The reason I need to do this is because my cucumber task creates a JSON file after running the task, and I'm using gradle-cucumber-reporting plugin (https://github.com/SpacialCircumstances/gradle-cucumber-reporting) to generate a report based on the JSON file.

cucumber task

task cucumber() {
    dependsOn assemble, compileTestJava
    doLast {
        javaexec {
            main = "io.cucumber.core.cli.Main"
            classpath = configurations.cucumberRuntime + sourceSets.main.output + sourceSets.test.output
            args = [
            '--plugin', 'html:cucumber-report',
            '--plugin', 'json:cucumber.json', //generates a .json report file
            '--plugin', 'pretty',
            '--plugin', 'usage:cucumber-usage.json',
            '--glue', 'hellocucumber', 'src/test/resources']
        }
    }
}

Running the test task in Gradle doesn't update the JSON file.

Here's the snippet for gradle-cucumber-reporting:

cucumberReports {
  outputDir = file('cucumber-pretty-report')
  buildId = '0'
  reports = files('cucumber.json')
}

Body:
You can add something like this to your cucumber task:

def tags = getProperty("tags")
args = [
'--plugin', 'html:cucumber-report',
'--plugin', 'json:cucumber.json', //generates a .json report file
'--plugin', 'pretty',
'--plugin', 'usage:cucumber-usage.json',
'--glue', 'hellocucumber', 'src/test/resources',
'--tags', tags]

Then you can run your task this way:

gradle cucumber -P tags=smoke


问:
ERR_CONNECTION_REFUSED in POST data to Mysql using NodeJs and ReactJs
I am working on ReactJs and NodeJS in sending data to MySql, in my frontPage.js The problem is I already tested the API to post data using Postman and no error appears. And the problem comes when I tried in ReactJs, I coded this :

```<code>class InputEndUser extends Component {
    constructor(props){
        super(props);

        this.state = {
            project_type: '',
            status : '',
            subject : '',
            enduser_name : '',
            location : '',
            cp_1 : '',
            cp1_hp : '',
            cp1_jpos: '',
            cp_2 : '',
            cp2_hp : '',
            cp2_jpos : '',
            quot_num : '',
            quot_date : '',
            note : ''

        }
        this.handleProject_type = this.handleProject_type.bind(this);
        this.handleStatus = this.handleStatus.bind(this);
        this.handleSubject = this.handleSubject.bind(this);
        this.handleEnduser_name = this.handleEnduser_name.bind(this);
        this.handleLocation = this.handleLocation.bind(this);
        this.handleCP1 = this.handleCP1.bind(this);
        this.handleCP1_hp = this.handleCP1_hp.bind(this);
        this.handleCP1_jpos = this.handleCP1_jpos.bind(this);
        this.handleCP2 = this.handleCP2.bind(this);
        this.handleCP2 = this.handleCP2.bind(this);
        this.handleCP2_hp = this.handleCP2_hp.bind(this);
        this.handleCP2_jpos = this.handleCP2_jpos.bind(this);
        this.handleQuot_num = this.handleQuot_num.bind(this);
        this.handleQuot_date = this.handleQuot_date.bind (this);
        this.handleNotes = this.handleNotes.bind(this);
    }

    handleProject_type(event){
        this.setState ({
            project_type : event.target.value
        })
    }

    handleStatus(event){
        this.setState({
            status: event.target.value
        })
    }

    handleSubject(event){
        this.setState({
            subject: event.target.value
        })
    }

    handleEnduser_name (event) {
        this.setState({
            enduser_name: event.target.value
        })
    }

    handleLocation(event){
        this.setState({
            location: event.target.value
        })
    }

    handleCP1(event){
        this.setState({
            cp_1: event.target.value
        })
    }

    handleCP1_hp(event){
        this.setState ({
            cp1_hp : event.target.value
        })
    }

    handleCP1_jpos(event){
        this.setState ({
            cp1_jpos : event.target.value
        })
    }

    handleCP2(event){
        this.setState({
            cp_2: event.target.value
        })
    }

    handleCP2_hp(event){
        this.setState ({
            cp2_hp : event.target.value
        })
    }

    handleCP2_jpos(event){
        this.setState ({
            cp2_jpos : event.target.value
        })
    }

    handleQuot_num(event) {
        this.setState ({
            quot_num : event.target.value
        })
    }

    handleQuot_date (event) {
        this.setState({
            quot_date : event.target.value
        })
    }

    handleNotes(event) {
        this.setState({
            note : event.target.value
        })
    }

    submitEndUser(event){
        event.preventDefault();
        fetch('http://localhost:4000/enduser', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            }
        })
        .then ((response) => {
            return response.json;
        })
        .then ((body) => {
            console.log(body);
        })
        .catch((error) => {
            console.log(error)
        })
    }
</code>```

and My API in server.js :

```<code>app.post('/enduser', (req, res) => {
  let POST_ENDUSER_QUERY =  {
    project_id: req.body.project_id,
    project_type: req.body.project_type,
    status: req.body.status,
    subject: req.body.subject,
    endUser_name: req.body.endUser_name,
    location: req.body.location,
    cp_1: req.body.cp_1,
    cp1_hp: req.body.cp1_hp,
    cp1_jpos: req.body.cp1_jpos,
    cp_2: req.body.cp_1,
    cp2_hp: req.body.cp1_hp,
    cp2_jpos: req.body.cp1_jpos,
    quot_num: req.body.quot_num,
    quot_date: req.body.quot_date,
    note: req.body.note,
    image: req.body.image,
    estimated_value: req.body.estimated_value
  };
  if (!POST_ENDUSER_QUERY) {
    return res.status(400).send({ err: true, message: 'Please project name' });
  }

  let query = `INSERT INTO enduser_tbl (project_id, project_type, status, subject, endUser_name, location, cp_1, cp1_hp, cp1_jpos, cp_2, cp2_hp, cp2_jpos, quot_num,quot_date, note, image, estimated_value) VALUES (
    '${POST_ENDUSER_QUERY.project_id}',
    '${POST_ENDUSER_QUERY.project_type}',
    '${POST_ENDUSER_QUERY.status}',
    '${POST_ENDUSER_QUERY.subject}',
    '${POST_ENDUSER_QUERY.endUser_name}',
    '${POST_ENDUSER_QUERY.location}',
    '${POST_ENDUSER_QUERY.cp_1}',
    '${POST_ENDUSER_QUERY.cp1_hp}',
    '${POST_ENDUSER_QUERY.cp1_jpos}',
    '${POST_ENDUSER_QUERY.cp_2}',
    '${POST_ENDUSER_QUERY.cp2_hp}',
    '${POST_ENDUSER_QUERY.cp2_jpos}',
    '${POST_ENDUSER_QUERY.quot_num}',
    '${POST_ENDUSER_QUERY.quot_date}',
    '${POST_ENDUSER_QUERY.note}',
    '${POST_ENDUSER_QUERY.image}',
    '${POST_ENDUSER_QUERY.estimated_value}'
    )`;
  dbConn.query(query, ( err, results) => {
    if(err) throw err;
    return res.status(200).json({"status": 200, "err" : null, "data": results});
  });
});

</code>```

and the error came :

also in terminal when I test it with some kind of data, appears like this:

答: Please setup CORS in order to make your Api's work</p>

Body:
I am working on ReactJs and NodeJS in sending data to MySql, in my frontPage.js The problem is I already tested the API to post data using Postman and no error appears. And the problem comes when I tried in ReactJs, I coded this :

class InputEndUser extends Component {
    constructor(props){
        super(props);

        this.state = {
            project_type: '',
            status : '',
            subject : '',
            enduser_name : '',
            location : '',
            cp_1 : '',
            cp1_hp : '',
            cp1_jpos: '',
            cp_2 : '',
            cp2_hp : '',
            cp2_jpos : '',
            quot_num : '',
            quot_date : '',
            note : ''

        }
        this.handleProject_type = this.handleProject_type.bind(this);
        this.handleStatus = this.handleStatus.bind(this);
        this.handleSubject = this.handleSubject.bind(this);
        this.handleEnduser_name = this.handleEnduser_name.bind(this);
        this.handleLocation = this.handleLocation.bind(this);
        this.handleCP1 = this.handleCP1.bind(this);
        this.handleCP1_hp = this.handleCP1_hp.bind(this);
        this.handleCP1_jpos = this.handleCP1_jpos.bind(this);
        this.handleCP2 = this.handleCP2.bind(this);
        this.handleCP2 = this.handleCP2.bind(this);
        this.handleCP2_hp = this.handleCP2_hp.bind(this);
        this.handleCP2_jpos = this.handleCP2_jpos.bind(this);
        this.handleQuot_num = this.handleQuot_num.bind(this);
        this.handleQuot_date = this.handleQuot_date.bind (this);
        this.handleNotes = this.handleNotes.bind(this);
    }

    handleProject_type(event){
        this.setState ({
            project_type : event.target.value
        })
    }

    handleStatus(event){
        this.setState({
            status: event.target.value
        })
    }

    handleSubject(event){
        this.setState({
            subject: event.target.value
        })
    }

    handleEnduser_name (event) {
        this.setState({
            enduser_name: event.target.value
        })
    }

    handleLocation(event){
        this.setState({
            location: event.target.value
        })
    }

    handleCP1(event){
        this.setState({
            cp_1: event.target.value
        })
    }

    handleCP1_hp(event){
        this.setState ({
            cp1_hp : event.target.value
        })
    }

    handleCP1_jpos(event){
        this.setState ({
            cp1_jpos : event.target.value
        })
    }

    handleCP2(event){
        this.setState({
            cp_2: event.target.value
        })
    }

    handleCP2_hp(event){
        this.setState ({
            cp2_hp : event.target.value
        })
    }

    handleCP2_jpos(event){
        this.setState ({
            cp2_jpos : event.target.value
        })
    }

    handleQuot_num(event) {
        this.setState ({
            quot_num : event.target.value
        })
    }

    handleQuot_date (event) {
        this.setState({
            quot_date : event.target.value
        })
    }

    handleNotes(event) {
        this.setState({
            note : event.target.value
        })
    }

    submitEndUser(event){
        event.preventDefault();
        fetch('http://localhost:4000/enduser', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            }
        })
        .then ((response) => {
            return response.json;
        })
        .then ((body) => {
            console.log(body);
        })
        .catch((error) => {
            console.log(error)
        })
    }

and My API in server.js :

app.post('/enduser', (req, res) => {
  let POST_ENDUSER_QUERY =  {
    project_id: req.body.project_id,
    project_type: req.body.project_type,
    status: req.body.status,
    subject: req.body.subject,
    endUser_name: req.body.endUser_name,
    location: req.body.location,
    cp_1: req.body.cp_1,
    cp1_hp: req.body.cp1_hp,
    cp1_jpos: req.body.cp1_jpos,
    cp_2: req.body.cp_1,
    cp2_hp: req.body.cp1_hp,
    cp2_jpos: req.body.cp1_jpos,
    quot_num: req.body.quot_num,
    quot_date: req.body.quot_date,
    note: req.body.note,
    image: req.body.image,
    estimated_value: req.body.estimated_value
  };
  if (!POST_ENDUSER_QUERY) {
    return res.status(400).send({ err: true, message: 'Please project name' });
  }

  let query = `INSERT INTO enduser_tbl (project_id, project_type, status, subject, endUser_name, location, cp_1, cp1_hp, cp1_jpos, cp_2, cp2_hp, cp2_jpos, quot_num,quot_date, note, image, estimated_value) VALUES (
    '${POST_ENDUSER_QUERY.project_id}',
    '${POST_ENDUSER_QUERY.project_type}',
    '${POST_ENDUSER_QUERY.status}',
    '${POST_ENDUSER_QUERY.subject}',
    '${POST_ENDUSER_QUERY.endUser_name}',
    '${POST_ENDUSER_QUERY.location}',
    '${POST_ENDUSER_QUERY.cp_1}',
    '${POST_ENDUSER_QUERY.cp1_hp}',
    '${POST_ENDUSER_QUERY.cp1_jpos}',
    '${POST_ENDUSER_QUERY.cp_2}',
    '${POST_ENDUSER_QUERY.cp2_hp}',
    '${POST_ENDUSER_QUERY.cp2_jpos}',
    '${POST_ENDUSER_QUERY.quot_num}',
    '${POST_ENDUSER_QUERY.quot_date}',
    '${POST_ENDUSER_QUERY.note}',
    '${POST_ENDUSER_QUERY.image}',
    '${POST_ENDUSER_QUERY.estimated_value}'
    )`;
  dbConn.query(query, ( err, results) => {
    if(err) throw err;
    return res.status(200).json({"status": 200, "err" : null, "data": results});
  });
});

and the error came :

also in terminal when I test it with some kind of data, appears like this:


问:
Usage of [mat-dialog-close]
I am a bit confused about the usage of [mat-dialog-close].

So, I have a dialog with a form. If the user clicks the submit button, the form is validated. If the input is valid, the dialog is closed and the form is submitted. However, if the input is invalid, the dialog remains opened and an error message is shown. For that I want to use [mat-dialog-close] as it is described in the official documentation where it is used as follows:

```<code><button mat-button [mat-dialog-close]="true">Yes</button>
</code>```

I thought that I can just pass it a boolean and whether the tag is active depends on the boolean value of the variable. However, this does not work. I tried it like this:

```<code><button type="submit" (click)="addUser()" [mat-dialog-close]="formisvalid" mat-button>Submit</button>
</code>```

I passed it the variable formisvalid. It's value is true unless the input is invalid. But now the dialog closes always, regardless of the value of formisvalid.
I also tried replacing it with false. I thought the dialog would remain opened no matter what happens, but it would also always close.

So, my question is: am I mistaken about the use of [mat-dialog-close] or am I just doing something wrong? If this is not achievable with the [mat-dialog-close] directive, what would be another way to achieve what I'm trying to do?

答:
Here you can pass any number of values as a array to an attribute [mat-dialog-close]

```<code><button [mat-dialog-close]="[organizationId,costCenterId,partnerDepartmentId]" cdkFocusInitial class="iport_primary_btn"mat-raised-button>Go</button>
</code>```

In parent component you can subscribe to the result after closing dialog like below

```<code>dialogRef.afterClosed().subscribe(result => {
console.log(result);
});
</code>```

Title: Usage of [mat-dialog-close]

Body:
I am a bit confused about the usage of [mat-dialog-close].

So, I have a dialog with a form. If the user clicks the submit button, the form is validated. If the input is valid, the dialog is closed and the form is submitted. However, if the input is invalid, the dialog remains opened and an error message is shown. For that I want to use [mat-dialog-close] as it is described in the official documentation where it is used as follows:

<button mat-button [mat-dialog-close]="true">Yes</button>

I thought that I can just pass it a boolean and whether the tag is active depends on the boolean value of the variable. However, this does not work. I tried it like this:

<button type="submit" (click)="addUser()" [mat-dialog-close]="formisvalid" mat-button>Submit</button>

I passed it the variable formisvalid. It's value is true unless the input is invalid. But now the dialog closes always, regardless of the value of formisvalid.
I also tried replacing it with false. I thought the dialog would remain opened no matter what happens, but it would also always close.

So, my question is: am I mistaken about the use of [mat-dialog-close] or am I just doing something wrong? If this is not achievable with the [mat-dialog-close] directive, what would be another way to achieve what I'm trying to do?

Body:
Here you can pass any number of values as a array to an attribute [mat-dialog-close]

<button [mat-dialog-close]="[organizationId,costCenterId,partnerDepartmentId]" cdkFocusInitial class="iport_primary_btn"mat-raised-button>Go</button>

In parent component you can subscribe to the result after closing dialog like below

dialogRef.afterClosed().subscribe(result => {
console.log(result);
});


问:
Akka-actor java.lang.NoClassDefFoundError: akka/actor/CoordinatedShutdown$$anonfun$totalTimeout
While running mvn clean install I am getting below error after all the test cases are passed.</p>

```<code>Exception in thread "Thread-3" java.lang.NoClassDefFoundError: akka/actor/CoordinatedShutdown$$anonfun$totalTimeout$1
        at akka.actor.CoordinatedShutdown.totalTimeout(CoordinatedShutdown.scala:377)
        at akka.actor.CoordinatedShutdown$$anonfun$initJvmHook$1.apply(CoordinatedShutdown.scala:109)
        at akka.actor.CoordinatedShutdown$$anon$2.run(CoordinatedShutdown.scala:395)
Caused by: java.lang.ClassNotFoundException: akka.actor.CoordinatedShutdown$$anonfun$totalTimeout$1
        at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        ... 3 more
</code>```

答:
If it happens after all your tests has completed it is likely triggered by tests leaking a running ActorSystem rather than stopping it before they complete. Make sure you always terminate the ActorSystems that you start in the tests.

The actual exception could also indicate that you have mixed versions of Akka modules in your project, they must all be of the same Akka version. This can happen if you have some transitive dependency pulling in modules of Akka that you do not explicitly use yourself. If that is the case you will need to add explicit dependencies to make sure all modules are from the same Akka version.

Body:
While running mvn clean install I am getting below error after all the test cases are passed.

Exception in thread "Thread-3" java.lang.NoClassDefFoundError: akka/actor/CoordinatedShutdown$$anonfun$totalTimeout$1
        at akka.actor.CoordinatedShutdown.totalTimeout(CoordinatedShutdown.scala:377)
        at akka.actor.CoordinatedShutdown$$anonfun$initJvmHook$1.apply(CoordinatedShutdown.scala:109)
        at akka.actor.CoordinatedShutdown$$anon$2.run(CoordinatedShutdown.scala:395)
Caused by: java.lang.ClassNotFoundException: akka.actor.CoordinatedShutdown$$anonfun$totalTimeout$1
        at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        ... 3 more


问:
Azure Bot Authentication from different machines
I'm using sample Azure MSGraph Bot Authentication (https://learn.microsoft.com/en-us/azure/bot-service/bot-builder-authentication?view=azure-bot-service-4.0&tabs=csharp), without any code changes (only changing APP id's and connection name).
I have an html page with WebChat example, and in the back of Azure portal, i have MSGraph authentication. Here are the steps, that working wrong:

I've deployed my bot to Azure and created an html page with WebChat

I'm logging in in WebChat window, and bot returns my domain name, everything is ok here

If i'll open the same page with bot on second machine, by another user, i expect, that i should see authentication dialog again. But i see my own credentials from first machine whithout any authentication process.

If i click "log out" on second machine and try to log in, i see second users domain name - as expected. So authentication process is working fine, bot understands who is trying to log in.

In other words, my authentication session keeps alive in other browser and on the other machines, for other domain users. How can i prevent this?

答:
(...) If userID is not specified, it will default to a random user ID. Multiple users sharing the same user ID is not recommended; their user state will be shared. (API documentation)

You are setting the userID to YOUR_USER_ID, which means that state will be shared over all users. This is causing your problems and is a security risk when you are authenticating users.

Remove the line which states userID in your code, as seen in the example below. If there is no userID set, it will default to a random user ID.

   window.WebChat.renderWebChat(
            {
               directLine: window.WebChat.createDirectLine({
                  token: 'YOUR_DIRECT_LINE_TOKEN'
               }),
               userID: 'YOUR_USER_ID',
               username: 'Web Chat User',
               locale: 'en-US',
               botAvatarInitials: 'WC',
               userAvatarInitials: 'WW'
            },
            document.getElementById('webchat')
         );
```

Body:
(...) If userID is not specified, it will default to a random user ID. Multiple users sharing the same user ID is not recommended; their user state will be shared. (API documentation)

You are setting the userID to YOUR_USER_ID, which means that state will be shared over all users. This is causing your problems and is a security risk when you are authenticating users.

Remove the line which states userID in your code, as seen in the example below. If there is no userID set, it will default to a random user ID.

   window.WebChat.renderWebChat(
            {
               directLine: window.WebChat.createDirectLine({
                  token: 'YOUR_DIRECT_LINE_TOKEN'
               }),
               userID: 'YOUR_USER_ID', <!-- REMOVE THIS LINE -->
               username: 'Web Chat User',
               locale: 'en-US',
               botAvatarInitials: 'WC',
               userAvatarInitials: 'WW'
            },
            document.getElementById('webchat')
         );