问:
C Matrix Multiplication Dynamically Allocated Matrices
I am working within a specific matrix memory allocation constraint that creates matrices as such:

```<code>float * matrix_data = (float *) malloc(rows * cols * sizeof(float));
</code>```

I am storing this matrix inside an array of structs like this:

```<code>#define MAX_MATRICES 100

struct matrix{
    char matrixName[50];
    int rows;
    int columns;
    float* matrix_data;
};
typedef struct matrix matrix_t;

matrix_t our_matrix[MAX_MATRICES];
</code>```

Given that this is the case, and I am not creating matrices by way of a 2d array like MATRIX[SIZE][SIZE]: what is the correct way to multiply two matrices created in this way?

With this current implementation if I want to do something like subtract, I do it as follows:

```<code>int max_col = our_matrix[matrix_index1].columns;
      free(our_matrix[number_of_matrices].matrix_data);
      our_matrix[number_of_matrices].data = (float *) malloc(our_matrix[matrix_index1].rows * our_matrix[matrix_index1].columns * sizeof(float));
      float *data1 = our_matrix[matrix_index1].matrix_data;
      float *data2 = our_matrix[matrix_index2].matrix_data;

      int col, row;
      for(col = 1; col <= our_matrix[matrix_index2].columns; col++){
        for(row = 1; row <= our_matrix[matrix_index2].rows; row++){
          our_matrix[number_of_matrices].matrix_data[(col-1) + (row-1) * max_col] =
            (data1[(col-1) + (row-1) * (max_col)]) - (data2[(col-1) + (row-1) * (max_col)]);
        }
      }
</code>```

This is simple enough because the dimensions of matrix_index1 and matrix_index2 are identical and the matrix that they return is also of identical dimensions.

How might I achieve matrix multiplication with this method of matrix construction?

答:
There's several problems with this code: it is unreadable and it is very cache-unfriendly, meaning slow.

Regarding cache, you should always iterate over the outer-most dimension of the 2D array (doesn't matter if you call that one row or column), and you should only have a single malloc call in the code, so that you get adjacent memory. If you let the compiler calculate array indices instead of doing that manually, that usually helps performance as well.

We can simplify this significantly by using a flexible array member at the end of the struct, then using that as an old school "mangled array" whenever we access it. "Mangled array" meaning the array type is single dimension in the C syntax, but we access it as if it is a 2D array.

The struct type would be:

```<code>typedef struct
{
  char   name[50];
  size_t columns;
  size_t rows;
  float  data[];
} matrix_t;
</code>```

And we alloc memory for it once, with a single call:

```<code>matrix_t* matrix = malloc( sizeof *matrix + sizeof(float[c][r]) );
</code>```

Then when accessing the "mangled array", we can cast to a pointer to 2D array type and use that one every time we access the data:

```<code>float (*data)[r] = (float(*)[r]) matrix->data;
</code>```

Full example:

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

typedef struct
{
  char   name[50];
  size_t columns;
  size_t rows;
  float  data[];
} matrix_t;

int main (void)
{
  size_t c = 3;
  size_t r = 5;
  matrix_t* matrix = malloc(sizeof *matrix + sizeof(float[c][r]));

  float (*data)[r] = (float(*)[r]) matrix->data;
  for(size_t i=0; i<c; i++)
  {
    for(size_t j=0; j<r; j++)
    {
      data[i][j] = (float)i+j; // assign some random value
      printf("%.2f ", data[i][j]);
    }
    printf("\n");
  }

  free(matrix);
}
</code>```

Body:
I am working within a specific matrix memory allocation constraint that creates matrices as such:

float * matrix_data = (float *) malloc(rows * cols * sizeof(float));

I am storing this matrix inside an array of structs like this:

#define MAX_MATRICES 100

struct matrix{
    char matrixName[50];
    int rows;
    int columns;
    float* matrix_data;
};
typedef struct matrix matrix_t;

matrix_t our_matrix[MAX_MATRICES];

Given that this is the case, and I am not creating matrices by way of a 2d array like MATRIX[SIZE][SIZE]: what is the correct way to multiply two matrices created in this way?

With this current implementation if I want to do something like subtract, I do it as follows:

int max_col = our_matrix[matrix_index1].columns;
      free(our_matrix[number_of_matrices].matrix_data);
      our_matrix[number_of_matrices].data = (float *) malloc(our_matrix[matrix_index1].rows * our_matrix[matrix_index1].columns * sizeof(float));
      float *data1 = our_matrix[matrix_index1].matrix_data;
      float *data2 = our_matrix[matrix_index2].matrix_data;

      int col, row;
      for(col = 1; col <= our_matrix[matrix_index2].columns; col++){
        for(row = 1; row <= our_matrix[matrix_index2].rows; row++){
          our_matrix[number_of_matrices].matrix_data[(col-1) + (row-1) * max_col] =
            (data1[(col-1) + (row-1) * (max_col)]) - (data2[(col-1) + (row-1) * (max_col)]);
        }
      }

This is simple enough because the dimensions of matrix_index1 and matrix_index2 are identical and the matrix that they return is also of identical dimensions.

How might I achieve matrix multiplication with this method of matrix construction?

Body:
There's several problems with this code: it is unreadable and it is very cache-unfriendly, meaning slow.

Regarding cache, you should always iterate over the outer-most dimension of the 2D array (doesn't matter if you call that one row or column), and you should only have a single malloc call in the code, so that you get adjacent memory. If you let the compiler calculate array indices instead of doing that manually, that usually helps performance as well.

We can simplify this significantly by using a flexible array member at the end of the struct, then using that as an old school "mangled array" whenever we access it. "Mangled array" meaning the array type is single dimension in the C syntax, but we access it as if it is a 2D array.

The struct type would be:

typedef struct
{
  char   name[50];
  size_t columns;
  size_t rows;
  float  data[];
} matrix_t;

And we alloc memory for it once, with a single call:

matrix_t* matrix = malloc( sizeof *matrix + sizeof(float[c][r]) );

Then when accessing the "mangled array", we can cast to a pointer to 2D array type and use that one every time we access the data:

float (*data)[r] = (float(*)[r]) matrix->data;

Full example:

#include <stdlib.h>
#include <stdio.h>

typedef struct
{
  char   name[50];
  size_t columns;
  size_t rows;
  float  data[];
} matrix_t;

int main (void)
{
  size_t c = 3;
  size_t r = 5;
  matrix_t* matrix = malloc(sizeof *matrix + sizeof(float[c][r]));

  float (*data)[r] = (float(*)[r]) matrix->data;
  for(size_t i=0; i<c; i++)
  {
    for(size_t j=0; j<r; j++)
    {
      data[i][j] = (float)i+j; // assign some random value
      printf("%.2f ", data[i][j]);
    }
    printf("\n");
  }

  free(matrix);
}


来源: stackexchange

问:
when does useEffect fire in componentWillUnmount?
I read below statement in a blog, it says something like this

```<code>useEffect(() => {
  API.getUser(userId);
}, [userId]);
</code>```

Optionally the second parameter can also just be an empty array, in
  this case it will only execute on componentDidMount and
  componentWillUnmount and the effect won't run on componentDidUpdate.

Does the API.getUser got executed when the component got unmounted (componentWillUnmount)? as I know componentWillUnmount trigger when you go from page A to page B. I'm confused now, for me, above code act like componentDidMount, because userId will change from undefined to id once.

答:
You are a little confused with the wording, Its not the effect that is executed on unmount when you pass an empty array but the cleanup function which is the function returned from within the useEffect which will be executed.

for instance you can have the above effect like

```<code>useEffect(() => {
  API.getUser(userId);
  return () => {
      // cancel api here
  }
}, [userId]);
</code>```

So in the above example, the anonymous function which is returned by useEffect will be called before the effect is run for the second time(which happens when userId changes) or at the time of unmount

ContentLicense: CC BY-SA 4.0

Body:
I read below statement in a blog, it says something like this

useEffect(() => {
  API.getUser(userId);
}, [userId]);

Optionally the second parameter can also just be an empty array, in
  this case it will only execute on componentDidMount and
  componentWillUnmount and the effect won't run on componentDidUpdate.

Does the API.getUser got executed when the component got unmounted (componentWillUnmount)? as I know componentWillUnmount trigger when you go from page A to page B. I'm confused now, for me, above code act like componentDidMount, because userId will change from undefined to id once.

Body:
You are a little confused with the wording, Its not the effect that is executed on unmount when you pass an empty array but the cleanup function which is the function returned from within the useEffect which will be executed.

for instance you can have the above effect like

useEffect(() => {
  API.getUser(userId);
  return () => {
      // cancel api here
  }
}, [userId]);

So in the above example, the anonymous function which is returned by useEffect will be called before the effect is run for the second time(which happens when userId changes) or at the time of unmount


问:
How to show alertdialog for evey child in firebase has true in it
After executing an exercise, I wanted to show an alert dialog that says, "You have already executed this. Are you sure you want to do it again?"

So in my firebase, once the exercise has already been executed isProgramExerciseFinished will be set to true. But in my code, it seems that the dialog only shows once all of it is set to true.

```<code>public void onClick(View view) {
            currentWeek = programTrackers.get(0).getWeek();
            DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("ProgramTracker")
                    .child(GlobalUser.getmUser().getiD())
                    .child(programTrackers.get(0).getProgramId());
            databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    final int childCount = (int) dataSnapshot.getChildrenCount();
                    int count = 0;
                    for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                        ProgramTracker programTracker = snapshot.getValue(ProgramTracker.class);
                        if (programTracker.getProgramExerciseWeek() == currentWeek) {
                            programTrackChecker.add(programTracker);

                        }
                        count++;
                    }
                    if (count == childCount) {
                        boolean isFinished = false;
                        //last iteration
                        for (int i = 0; i < programTrackChecker.size(); i++) {
                            if (programTrackChecker.get(i).isProgramExerciseFinished()) {
                                isFinished = true;
                            } else
                                isFinished = false;
                        }
                        if (isFinished) {
                            AlertDialog.Builder builder = new AlertDialog.Builder(DayExerciseActivity.this);
                            builder.setMessage("You have already completed all exercises. Are you sure you want to do it again?");
                            builder.setPositiveButton("Yes", (dialogInterface, i) -> {
                                startActivity(new Intent(DayExerciseActivity.this, DoProgramActivity.class)
                                        .putExtra("programTrackers", programTrackers)
                                        .putExtra("exerciseNum", String.valueOf(0)));

                            });
                            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    dialogInterface.dismiss();
                                }
                            });
                            builder.show();

                        } else
                            startActivity(new Intent(DayExerciseActivity.this, DoProgramActivity.class)
                                    .putExtra("programTrackers", programTrackers)
                                    .putExtra("exerciseNum", String.valueOf(0)));

                    }

                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });

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

once it is true a dialog will show once it is false dialog will not be shown and automatically will be directed to doProgramActivity

答:
I believe that you are being returned with the data from firebase only once. As the callback function is called asynchronously. So by the time it is invoked, postsRef.on(...) has already returned and any code immediately after it will have run. Refer to the following question:
Firebase on() does not return anything</p>

Body:
After executing an exercise, I wanted to show an alert dialog that says, "You have already executed this. Are you sure you want to do it again?"

So in my firebase, once the exercise has already been executed isProgramExerciseFinished will be set to true. But in my code, it seems that the dialog only shows once all of it is set to true.

public void onClick(View view) {
            currentWeek = programTrackers.get(0).getWeek();
            DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("ProgramTracker")
                    .child(GlobalUser.getmUser().getiD())
                    .child(programTrackers.get(0).getProgramId());
            databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    final int childCount = (int) dataSnapshot.getChildrenCount();
                    int count = 0;
                    for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                        ProgramTracker programTracker = snapshot.getValue(ProgramTracker.class);
                        if (programTracker.getProgramExerciseWeek() == currentWeek) {
                            programTrackChecker.add(programTracker);

                        }
                        count++;
                    }
                    if (count == childCount) {
                        boolean isFinished = false;
                        //last iteration
                        for (int i = 0; i < programTrackChecker.size(); i++) {
                            if (programTrackChecker.get(i).isProgramExerciseFinished()) {
                                isFinished = true;
                            } else
                                isFinished = false;
                        }
                        if (isFinished) {
                            AlertDialog.Builder builder = new AlertDialog.Builder(DayExerciseActivity.this);
                            builder.setMessage("You have already completed all exercises. Are you sure you want to do it again?");
                            builder.setPositiveButton("Yes", (dialogInterface, i) -> {
                                startActivity(new Intent(DayExerciseActivity.this, DoProgramActivity.class)
                                        .putExtra("programTrackers", programTrackers)
                                        .putExtra("exerciseNum", String.valueOf(0)));

                            });
                            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    dialogInterface.dismiss();
                                }
                            });
                            builder.show();

                        } else
                            startActivity(new Intent(DayExerciseActivity.this, DoProgramActivity.class)
                                    .putExtra("programTrackers", programTrackers)
                                    .putExtra("exerciseNum", String.valueOf(0)));

                    }

                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });

        }
    });
}

once it is true a dialog will show once it is false dialog will not be shown and automatically will be directed to doProgramActivity


问:
Which is better: importing .py files or executing .txt files?
Which is better:
Importing .py files or executing .txt files?

For example, there is a .py file with this written, named "python.py":

def MyFunction():
    print(".py file")
```

<p>and there is a .txt file named "text.txt":</p>

<pre class="lang-py prettyprint-override"><code>def MyFunction()
    print(".txt file")
</code>```

I can use the first one like:

import python
```

<p>and the second one like:</p>

<pre class="lang-py prettyprint-override"><code>exec(open("text.txt", "r").read())
</code>```

Which method is better in terms of speed, reliability, and safety?
I am not really concerned about the length of each code

答: Definitely the first one with .py file. You should always save python scripts in files with .py extension. 4 reasons: Portability, Readability, Useability, Convention.

Body:
Which is better:
Importing .py files or executing .txt files?

For example, there is a .py file with this written, named "python.py":

def MyFunction():
    print(".py file")

and there is a .txt file named "text.txt":

def MyFunction()
    print(".txt file")

I can use the first one like:

import python

and the second one like:

exec(open("text.txt", "r").read())

Which method is better in terms of speed, reliability, and safety?
I am not really concerned about the length of each code


答:
If your storing python code.
Then python_code.py file is preferable.

If you are storing information like text, or some other raw data.
Then any type of file can be used. That can be in .txt, .xls, .csv, may be databases.

Note:

you have named your file name as python. Which is highly not recommended.

Title: Which is better: importing .py files or executing .txt files?


问:
use systemjs in a basic vanilla js page
I'm trying to use a chart component from Syncfusion in a simple application I'm developing.

It's pure JS, no Angular, no React, no TypeScript. I've not even used NPM

My problem is that I'm not able to import the necessary files to make the chart component works!

Following the documentation founded here
https://ej2.syncfusion.com/javascript/documentation/chart/es5-getting-started/

I've added a systemjs.config.js in my folder /_assets/systemjs.config.js and I've configured this way:

```<code>System.config({
    paths: {
        'syncfusion:': './_assets/vendors/Syncfusion/@syncfusion',
    },
    map: {
        app: 'app',

        //Syncfusion packages mapping
        "@syncfusion/ej2-base": "syncfusion:ej2-base/dist/ej2-base.umd.min.js",
        "@syncfusion/ej2-data": "syncfusion:ej2-data/dist/ej2-data.umd.min.js",
        "@syncfusion/ej2-charts": "syncfusion:ej2-charts/dist/ej2-charts.umd.min.js",
        "@syncfusion/ej2-popups": "syncfusion:ej2-popups/dist/ej2-popups.umd.min.js",
        "@syncfusion/ej2-buttons": "syncfusion:ej2-buttons/dist/ej2-buttons.umd.min.js",
        "@syncfusion/ej2-pdf-export": "syncfusion:ej2-pdf-export/dist/ej2-pdf-export.umd.min.js",
        "@syncfusion/ej2-file-utils": "syncfusion:ej2-file-utils/dist/ej2-file-utils.umd.min.js",
        "@syncfusion/ej2-compression": "syncfusion:ej2-compression/dist/ej2-compression.umd.min.js",
        "@syncfusion/ej2-navigations": "syncfusion:ej2-navigations/dist/ej2-navigations.umd.min.js",
        "@syncfusion/ej2-calendars": "syncfusion:ej2-calendars/dist/ej2-calendars.umd.min.js",
        "@syncfusion/ej2-lists": "syncfusion:ej2-lists/dist/ej2-lists.umd.min.js",
        "@syncfusion/ej2-inputs": "syncfusion:ej2-inputs/dist/ej2-inputs.umd.min.js",
        "@syncfusion/ej2-svg-base": "syncfusion:ej2-svg-base/dist/ej2-svg-base.umd.min.js",
        "@syncfusion/ej2-splitbuttons": "syncfusion:ej2-splitbuttons/dist/ej2-splitbuttons.umd.min.js"
        ,
    },
    packages: {
        'app': { main: 'app', defaultExtension: 'js' }
    }
});
</code>```

It talks about "app" but I don't have an app variable... I'm not using Angular neither React.

In the folder /_assets/vendors/Syncfusion/ I've inserted all the scripts files of Syncfusion:

Then in my HTML page I've added:

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
<script src="/_assets/js/systemjs.config.js"></script>
</code>```

but when I run the page from the local dev web server I get:

Test:94 Uncaught ReferenceError: ej is not defined

答:
We have analyzed your query. And we have prepared a sample based on your requirement. To render EJ2 charts, you need to just refer the following scripts. There is no need to config the system.cofig as like the configuration you have done. We have already change the documentation from our side. It will be refreshed in the month of June.

Please find the below code snippet to achieve this requirement,

```<code><head>
    <script src="https://cdn.syncfusion.com/ej2/dist/ej2.min.js" type="text/javascript"></script>
    <link href="https://cdn.syncfusion.com/ej2/material.css" rel="stylesheet">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>
<div id="line-container" align="center"></div>
 <script>
var chart = new ej.charts.Chart({
  //Initializing
});
chart.appendTo('#line-container');
  </script>
</body>
</code>```

Sample link: https://stackblitz.com/edit/3ugmn8?file=index.html

Kindly revert us, if you have any concerns.

Regards,

Baby.

Title: use systemjs in a basic vanilla js page

Body:
I'm trying to use a chart component from Syncfusion in a simple application I'm developing.

It's pure JS, no Angular, no React, no TypeScript. I've not even used NPM

My problem is that I'm not able to import the necessary files to make the chart component works!

Following the documentation founded here
https://ej2.syncfusion.com/javascript/documentation/chart/es5-getting-started/

I've added a systemjs.config.js in my folder /_assets/systemjs.config.js and I've configured this way:

System.config({
    paths: {
        'syncfusion:': './_assets/vendors/Syncfusion/@syncfusion',
    },
    map: {
        app: 'app',

        //Syncfusion packages mapping
        "@syncfusion/ej2-base": "syncfusion:ej2-base/dist/ej2-base.umd.min.js",
        "@syncfusion/ej2-data": "syncfusion:ej2-data/dist/ej2-data.umd.min.js",
        "@syncfusion/ej2-charts": "syncfusion:ej2-charts/dist/ej2-charts.umd.min.js",
        "@syncfusion/ej2-popups": "syncfusion:ej2-popups/dist/ej2-popups.umd.min.js",
        "@syncfusion/ej2-buttons": "syncfusion:ej2-buttons/dist/ej2-buttons.umd.min.js",
        "@syncfusion/ej2-pdf-export": "syncfusion:ej2-pdf-export/dist/ej2-pdf-export.umd.min.js",
        "@syncfusion/ej2-file-utils": "syncfusion:ej2-file-utils/dist/ej2-file-utils.umd.min.js",
        "@syncfusion/ej2-compression": "syncfusion:ej2-compression/dist/ej2-compression.umd.min.js",
        "@syncfusion/ej2-navigations": "syncfusion:ej2-navigations/dist/ej2-navigations.umd.min.js",
        "@syncfusion/ej2-calendars": "syncfusion:ej2-calendars/dist/ej2-calendars.umd.min.js",
        "@syncfusion/ej2-lists": "syncfusion:ej2-lists/dist/ej2-lists.umd.min.js",
        "@syncfusion/ej2-inputs": "syncfusion:ej2-inputs/dist/ej2-inputs.umd.min.js",
        "@syncfusion/ej2-svg-base": "syncfusion:ej2-svg-base/dist/ej2-svg-base.umd.min.js",
        "@syncfusion/ej2-splitbuttons": "syncfusion:ej2-splitbuttons/dist/ej2-splitbuttons.umd.min.js"
        ,
    },
    packages: {
        'app': { main: 'app', defaultExtension: 'js' }
    }
});

It talks about "app" but I don't have an app variable... I'm not using Angular neither React.

In the folder /_assets/vendors/Syncfusion/ I've inserted all the scripts files of Syncfusion:

Then in my HTML page I've added:

but when I run the page from the local dev web server I get:

Test:94 Uncaught ReferenceError: ej is not defined

Body:
We have analyzed your query. And we have prepared a sample based on your requirement. To render EJ2 charts, you need to just refer the following scripts. There is no need to config the system.cofig as like the configuration you have done. We have already change the documentation from our side. It will be refreshed in the month of June.

Please find the below code snippet to achieve this requirement,

<head>
    <script src="https://cdn.syncfusion.com/ej2/dist/ej2.min.js" type="text/javascript"></script>
    <link href="https://cdn.syncfusion.com/ej2/material.css" rel="stylesheet">
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>
<div id="line-container" align="center"></div>
 <script>
var chart = new ej.charts.Chart({
  //Initializing
});
chart.appendTo('#line-container');
  </script>
</body>

Sample link: https://stackblitz.com/edit/3ugmn8?file=index.html

Kindly revert us, if you have any concerns.

Regards,

Baby.


问:
Operation timed out while switching to webview(NewTab) context in Appium 1.13 IOS 12.3.1
After switching to native popup Allow is clicked then it will not switch to webview and control doesn't go to next tab. I am getting Native, Webview_4,Webview_5 like wise.

Error stack trace:

May 28, 2019 9:36:30 AM org.openqa.selenium.support.ui.ExpectedConditions findElement WARNING: WebDriverException thrown by findElement(By.xpath: //button[@class='little130 blue']) org.openqa.selenium.WebDriverException: An unknown server-side error occurred while processing the command. Original error: Did not get any response after 20s Build info: version: '3.13.0', revision: '2f0d292', time: '2018-06-25T15:32:19.891Z' System info: host: 'local', ip: 'fe80:0:0:0:c1a:bce1:50e1:ac1d%en0', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.14.4', java.version: '12' Driver info: io.appium.java_client.ios.IOSDriver Capabilities {appiumVersion:
1.9.1, autoAcceptAlerts: true, autoDismissAlerts: true, autoGrantPermissions: true, automationName: XCUITest, browserName: Safari, databaseEnabled: false, deviceName:TS, javascriptEnabled: true, locationContextEnabled: falsenetworkConnectionEnabled: false, newCommandTimeout: 2000,platform: MAC, platformName: iOS, platformVersion: 12.2, safariAllowPopups: false, startIWDP: true, takesScreenshot: true, udid: ****..., unexpectedAlertBehaviour: true, unhandledPromptBehavior: true, webStorageEnabled: false, webkitResponseTimeout: 20000, xcodeOrgId: BYKRN84M2R, xcodeSigningId: iPhone Developer} Session ID: fc7d6ca1-3901-4fb0-a001-69ff9a499308
*** Element info: {Using=xpath, value=//button[@class='little']} at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) atjava.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)atjava.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500) at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481) at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187) at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122) at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49) at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158) at io.appium.java_client.remote.AppiumCommandExecutor.execute(AppiumCommandExecutor.java:231) at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:548) at io.appium.java_client.DefaultGenericMobileDriver.execute(DefaultGenericMobileDriver.java:42) at io.appium.java_client.AppiumDriver.execute(AppiumDriver.java:1)
```

<p>the used following code but it doesn't work </p>

```Set<String> strcont=null; strcont=driver.getcontextHandles();
For(String s: strcont) {
  if(s.contains(WEBVIEW)) {
    driver.context(s);
  }
} catch (Exception e) {
     e.printStackTrace();
}
```

答:
```<code>After clicking the "popup" button again switch to webview,give break inside the condition find the below code

Set<String> strcont=null; strcont=driver.getcontextHandles();
For(String s: strcont) {
  if(s.contains(WEBVIEW)) {
    driver.context(s);
    break;
  }
} catch (Exception e) {
     e.printStackTrace();
}
</code>```

Body:
After switching to native popup Allow is clicked then it will not switch to webview and control doesn't go to next tab. I am getting Native, Webview_4,Webview_5 like wise.

Error stack trace:

May 28, 2019 9:36:30 AM org.openqa.selenium.support.ui.ExpectedConditions findElement WARNING: WebDriverException thrown by findElement(By.xpath: //button[@class='little130 blue']) org.openqa.selenium.WebDriverException: An unknown server-side error occurred while processing the command. Original error: Did not get any response after 20s Build info: version: '3.13.0', revision: '2f0d292', time: '2018-06-25T15:32:19.891Z' System info: host: 'local', ip: 'fe80:0:0:0:c1a:bce1:50e1:ac1d%en0', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.14.4', java.version: '12' Driver info: io.appium.java_client.ios.IOSDriver Capabilities {appiumVersion:
1.9.1, autoAcceptAlerts: true, autoDismissAlerts: true, autoGrantPermissions: true, automationName: XCUITest, browserName: Safari, databaseEnabled: false, deviceName:TS, javascriptEnabled: true, locationContextEnabled: falsenetworkConnectionEnabled: false, newCommandTimeout: 2000,platform: MAC, platformName: iOS, platformVersion: 12.2, safariAllowPopups: false, startIWDP: true, takesScreenshot: true, udid: ****..., unexpectedAlertBehaviour: true, unhandledPromptBehavior: true, webStorageEnabled: false, webkitResponseTimeout: 20000, xcodeOrgId: BYKRN84M2R, xcodeSigningId: iPhone Developer} Session ID: fc7d6ca1-3901-4fb0-a001-69ff9a499308
*** Element info: {Using=xpath, value=//button[@class='little']} at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) atjava.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)atjava.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:500) at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:481) at org.openqa.selenium.remote.http.W3CHttpResponseCodec.createException(W3CHttpResponseCodec.java:187) at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:122) at org.openqa.selenium.remote.http.W3CHttpResponseCodec.decode(W3CHttpResponseCodec.java:49) at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158) at io.appium.java_client.remote.AppiumCommandExecutor.execute(AppiumCommandExecutor.java:231) at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:548) at io.appium.java_client.DefaultGenericMobileDriver.execute(DefaultGenericMobileDriver.java:42) at io.appium.java_client.AppiumDriver.execute(AppiumDriver.java:1)

the used following code but it doesn't work

Set<String> strcont=null; strcont=driver.getcontextHandles();
For(String s: strcont) {
  if(s.contains(WEBVIEW)) {
    driver.context(s);
  }
} catch (Exception e) {
     e.printStackTrace();
}


问:
Concurrent set_secret calls to Azure KeyVault API in Python
I have a python script which currently writes secret strings to Azure KeyVault.
This works well if the list is small, but I have have 4000+ KVs to write and this is taking 50mins each time the pipe runs.

I'm using the library like this:

```<code>from azure.keyvault import KeyVaultClient, KeyVaultAuthentication, KeyVaultId
from azure.common.credentials import ServicePrincipalCredentials

def auth_callback(server, resource, scope):
...

client = KeyVaultClient(KeyVaultAuthentication(auth_callback))
data = sys.stdin.read()
if data:
    print('Writing outputs to keyvault '+kvURL)
    outputs = json.loads(data)
    n = 0
    for op in outputs.items():
        key = baseEnv + '-' + baseFunction + '-' + op[0]
        key = key.replace('_', '-')
        val = str(op[1]['value'])
        print('Storing: ' + key + ' = ' + val)
        try:
            secret_bundle = client.set_secret(kvURL, key, val)
        except:
            print('err in key'+key)
            exit(os.EX_SOFTWARE)
            n += 1
    print(str(n)+' secrets written.')
else:
    print('OK nothing to do.')
</code>```

As the script just needs to make concurrent calls to the API, I don't explicitly need multiprocessing or thread concurrency, just an async way of instantiating the client object.

The docs don't help me much, and I don't know any c# so I'm failing to translate any async methods I see.  Any idea of how I should approach this welcome.  Especially around instantiating multiple client objects.

答:
As I known, almost of all Azure SDK APIs are wrapped the related REST APIs. So after I reviewed Azure KeyVault REST APIs, there is not an API supports to set secrets in bulk in only one request.

Therefore, the only solution to reduce the time cost of running your script is make it parallelization via multiprocessing or third-party packages in Python.

Here is two ways as my recommended.

Follow the first code sample of multiprocessing to run it parallelly via a process Pool, such as below

```<code>from multiprocessing import Pool

def setSecret(op):
    key = baseEnv + '-' + baseFunction + '-' + op[0]
    key = key.replace('_', '-')
    val = str(op[1]['value'])
    print('Storing: ' + key + ' = ' + val)
    ret = (key, 1)
    try:
        secret_bundle = client.set_secret(kvURL, key, val)
    except:
        print('err in key'+key)
        ret = (key, 0)
    return ret

if __name__=='__main__':
    proc_num = 100
    with Pool(proc_num) as p:
        rets = p.map(setSecret, outputs.items())
    n_successed = sum([ok for _, ok in rets])
</code>```

You can refer to the blog Easy parallel HTTP requests with Python and asyncio to rewrite your code to directly call the REST API Set Secret - Set Secret and run concurrently.

Hope it helps.

Body:
I have a python script which currently writes secret strings to Azure KeyVault.
This works well if the list is small, but I have have 4000+ KVs to write and this is taking 50mins each time the pipe runs.

I'm using the library like this:

from azure.keyvault import KeyVaultClient, KeyVaultAuthentication, KeyVaultId
from azure.common.credentials import ServicePrincipalCredentials

def auth_callback(server, resource, scope):
...

client = KeyVaultClient(KeyVaultAuthentication(auth_callback))
data = sys.stdin.read()
if data:
    print('Writing outputs to keyvault '+kvURL)
    outputs = json.loads(data)
    n = 0
    for op in outputs.items():
        key = baseEnv + '-' + baseFunction + '-' + op[0]
        key = key.replace('_', '-')
        val = str(op[1]['value'])
        print('Storing: ' + key + ' = ' + val)
        try:
            secret_bundle = client.set_secret(kvURL, key, val)
        except:
            print('err in key'+key)
            exit(os.EX_SOFTWARE)
            n += 1
    print(str(n)+' secrets written.')
else:
    print('OK nothing to do.')

As the script just needs to make concurrent calls to the API, I don't explicitly need multiprocessing or thread concurrency, just an async way of instantiating the client object.

The docs don't help me much, and I don't know any c# so I'm failing to translate any async methods I see.  Any idea of how I should approach this welcome.  Especially around instantiating multiple client objects.

Body:
As I known, almost of all Azure SDK APIs are wrapped the related REST APIs. So after I reviewed Azure KeyVault REST APIs, there is not an API supports to set secrets in bulk in only one request.

Therefore, the only solution to reduce the time cost of running your script is make it parallelization via multiprocessing or third-party packages in Python.

Here is two ways as my recommended.

Follow the first code sample of multiprocessing to run it parallelly via a process Pool, such as below

from multiprocessing import Pool

def setSecret(op):
    key = baseEnv + '-' + baseFunction + '-' + op[0]
    key = key.replace('_', '-')
    val = str(op[1]['value'])
    print('Storing: ' + key + ' = ' + val)
    ret = (key, 1)
    try:
        secret_bundle = client.set_secret(kvURL, key, val)
    except:
        print('err in key'+key)
        ret = (key, 0)
    return ret

if __name__=='__main__':
    proc_num = 100
    with Pool(proc_num) as p:
        rets = p.map(setSecret, outputs.items())
    n_successed = sum([ok for _, ok in rets])

You can refer to the blog Easy parallel HTTP requests with Python and asyncio to rewrite your code to directly call the REST API Set Secret - Set Secret and run concurrently.

Hope it helps.


问:
Snackbar in SimpleDialog Flutter
I faced an error code below when adding a snackbar to an on-pressed method in my Simpledialog.
[Scaffold.of() called with a context that does not contain a Scaffold.]

I would like to seek your advice on how to provide the correct context to resolve it.

```<code>import 'package:flutter/material.dart';

void main() {
  runApp(new MaterialApp(home: new AlertApp()));
}

class AlertApp extends StatefulWidget {
  @override
  _AlertAppState createState() => _AlertAppState();
}

class _AlertAppState extends State<AlertApp> {

  SimpleDialog _simdalog;

  void sDialog(){
    _simdalog = new SimpleDialog(
      title: new Text("Add To Shopping Cart"),
      children: <Widget>[
        new SimpleDialogOption(
          child: new Text("Yes"),
          onPressed: (){
            final snackBar = SnackBar(content: Text('Purchase Successful'));
            Scaffold.of(context).showSnackBar(snackBar);
          },
        ),
        new SimpleDialogOption(
          child: new Text("Close"),
          onPressed:() {Navigator.pop(context);},
        ),
      ],
    );
    showDialog(context: context, builder: (BuildContext context){
      return _simdalog;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: new Center(
        child: Column(
          mainAxisSize: MainAxisSize.max,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
        new RaisedButton(
            child: new Text("Add to Shopping Cart [Simple]"),
            onPressed:(){
              sDialog();
            }),
          ],
        ),
      ),
    );
  }
}
</code>```

答:
Solution 1: as  Mazin Ibrahim mentioned in comments Scaffold.of() called with a context that does not contain a Scaffold

```<code>final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
...
Scaffold(
  key: _scaffoldKey,
...
onPressed: () {

                      _scaffoldKey.currentState.showSnackBar(
                          SnackBar(
                            content: Text('Purchase Successful'),
                            duration: Duration(seconds: 3),
                          ));
              }
</code>```

Solution 2:
With package flushbar, you can also display notification on top

Flushbar link : https://github.com/AndreHaueisen/flushbar

Another suggestion to use flushbar How to show snackbar after navigator.pop(context) in Flutter?

```<code>    Flushbar(
      title: "Hey Ninja",
      message: "Lorem Ipsum is simply dummy text of the printing and typesetting industry",
      flushbarPosition: FlushbarPosition.TOP,
      flushbarStyle: FlushbarStyle.FLOATING,
      reverseAnimationCurve: Curves.decelerate,
      forwardAnimationCurve: Curves.elasticOut,
      backgroundColor: Colors.red,
      boxShadows: [BoxShadow(color: Colors.blue[800], offset: Offset(0.0, 2.0), blurRadius: 3.0)],
      backgroundGradient: LinearGradient(colors: [Colors.blueGrey, Colors.black]),
      isDismissible: false,
      duration: Duration(seconds: 4),
      icon: Icon(
        Icons.check,
        color: Colors.greenAccent,
      ),
      mainButton: FlatButton(
        onPressed: () {},
        child: Text(
          "CLAP",
          style: TextStyle(color: Colors.amber),
        ),
      ),
      showProgressIndicator: true,
      progressIndicatorBackgroundColor: Colors.blueGrey,
      titleText: Text(
        "Hello Hero",
        style: TextStyle(
            fontWeight: FontWeight.bold, fontSize: 20.0, color: Colors.yellow[600], fontFamily: "ShadowsIntoLightTwo"),
      ),
      messageText: Text(
        "You killed that giant monster in the city. Congratulations!",
        style: TextStyle(fontSize: 18.0, color: Colors.green, fontFamily: "ShadowsIntoLightTwo"),
      ),
    )..show(context);
</code>```

Title: Snackbar in SimpleDialog Flutter

Body:
I faced an error code below when adding a snackbar to an on-pressed method in my Simpledialog.
[Scaffold.of() called with a context that does not contain a Scaffold.]

I would like to seek your advice on how to provide the correct context to resolve it.

import 'package:flutter/material.dart';

void main() {
  runApp(new MaterialApp(home: new AlertApp()));
}

class AlertApp extends StatefulWidget {
  @override
  _AlertAppState createState() => _AlertAppState();
}

class _AlertAppState extends State<AlertApp> {

  SimpleDialog _simdalog;

  void sDialog(){
    _simdalog = new SimpleDialog(
      title: new Text("Add To Shopping Cart"),
      children: <Widget>[
        new SimpleDialogOption(
          child: new Text("Yes"),
          onPressed: (){
            final snackBar = SnackBar(content: Text('Purchase Successful'));
            Scaffold.of(context).showSnackBar(snackBar);
          },
        ),
        new SimpleDialogOption(
          child: new Text("Close"),
          onPressed:() {Navigator.pop(context);},
        ),
      ],
    );
    showDialog(context: context, builder: (BuildContext context){
      return _simdalog;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: new Center(
        child: Column(
          mainAxisSize: MainAxisSize.max,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
        new RaisedButton(
            child: new Text("Add to Shopping Cart [Simple]"),
            onPressed:(){
              sDialog();
            }),
          ],
        ),
      ),
    );
  }
}

Body:
Solution 1: as  Mazin Ibrahim mentioned in comments Scaffold.of() called with a context that does not contain a Scaffold

final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
...
Scaffold(
  key: _scaffoldKey,
...
onPressed: () {

                      _scaffoldKey.currentState.showSnackBar(
                          SnackBar(
                            content: Text('Purchase Successful'),
                            duration: Duration(seconds: 3),
                          ));
              }

Solution 2:
With package flushbar, you can also display notification on top

Flushbar link : https://github.com/AndreHaueisen/flushbar

Another suggestion to use flushbar How to show snackbar after navigator.pop(context) in Flutter?

    Flushbar(
      title: "Hey Ninja",
      message: "Lorem Ipsum is simply dummy text of the printing and typesetting industry",
      flushbarPosition: FlushbarPosition.TOP,
      flushbarStyle: FlushbarStyle.FLOATING,
      reverseAnimationCurve: Curves.decelerate,
      forwardAnimationCurve: Curves.elasticOut,
      backgroundColor: Colors.red,
      boxShadows: [BoxShadow(color: Colors.blue[800], offset: Offset(0.0, 2.0), blurRadius: 3.0)],
      backgroundGradient: LinearGradient(colors: [Colors.blueGrey, Colors.black]),
      isDismissible: false,
      duration: Duration(seconds: 4),
      icon: Icon(
        Icons.check,
        color: Colors.greenAccent,
      ),
      mainButton: FlatButton(
        onPressed: () {},
        child: Text(
          "CLAP",
          style: TextStyle(color: Colors.amber),
        ),
      ),
      showProgressIndicator: true,
      progressIndicatorBackgroundColor: Colors.blueGrey,
      titleText: Text(
        "Hello Hero",
        style: TextStyle(
            fontWeight: FontWeight.bold, fontSize: 20.0, color: Colors.yellow[600], fontFamily: "ShadowsIntoLightTwo"),
      ),
      messageText: Text(
        "You killed that giant monster in the city. Congratulations!",
        style: TextStyle(fontSize: 18.0, color: Colors.green, fontFamily: "ShadowsIntoLightTwo"),
      ),
    )..show(context);


问:
Kotlin : Optional Dependency Injection Using Spring
What is the kotlin alternative for

```<code>@Autowired(required=false)
private DependencyC dependencyC;
</code>```

and

```<code>private Optional<HelloService> optionalHelloService;
public HelloController(Optional<HelloService> helloService) {
    this.optionalHelloService = helloService;
}
</code>```

答:
You should make that property nullable then:</p>

```<code>class HelloController(
    @Autowired(required = false) val helloService: HelloService?
)
</code>```

Body:
What is the kotlin alternative for

@Autowired(required=false)
private DependencyC dependencyC;

and

private Optional<HelloService> optionalHelloService;
public HelloController(Optional<HelloService> helloService) {
    this.optionalHelloService = helloService;
}

Body:
You should make that property nullable then:

class HelloController(
    @Autowired(required = false) val helloService: HelloService?
)


问:
RestTemplate throwing generic 400 Bad Request, but custom server sent message is not is lost
We have a rest controller API with POST mapping which takes an object as request param and creates the same on DB. We have got few validations on the input object, and if there is any error, then we are throwing exception with a custom message.

If we invoke this API from post man, we see the appropriate error.

Whereas when we invoke this in the caller method of other application with Spring's RestTemplate, all we see is a 400 Bad request with empty body. No error message is seen.

What could be the issue here. How can we get the custom message thrown from the API.

Here is how we are calling the API with rest template.

```<code>    String url = "https://localhost:8895/servuceUrl";
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    HttpEntity<AddRequest> entity = new HttpEntity<AddRequest>(obj, headers);
    ResponseEntity<String> data = null;
    adddata = restTemplate.exchange(syncurl, HttpMethod.POST, entity, String.class);
</code>```

And one server side we have an exception written as

```<code>@ResponseStatus(value=HttpStatus.BAD_REQUEST)
public class InvalidDataException extends Exception {

    public InvalidDataException(String msg) {
        super(msg);
    }
}
</code>```

The controller looks like

```<code>@PostMapping(RestUriMappings.POST_MAPPING)
public ResponseDto add(@Valid @RequestBody AddRequest data) throws InvalidDataException
{

    logger.debug("Incoming data for add: {}", data.toString());

    // validate the payload
    if(data.getName()==null)
       throw new InvalidDataException("Name shouldnt be null");
}
</code>```

答:
You are missing:</p>

```<code>headers.setContentType(MediaType.APPLICATION_JSON);
</code>```

Body:
We have a rest controller API with POST mapping which takes an object as request param and creates the same on DB. We have got few validations on the input object, and if there is any error, then we are throwing exception with a custom message.

If we invoke this API from post man, we see the appropriate error.

Whereas when we invoke this in the caller method of other application with Spring's RestTemplate, all we see is a 400 Bad request with empty body. No error message is seen.

What could be the issue here. How can we get the custom message thrown from the API.

Here is how we are calling the API with rest template.

    String url = "https://localhost:8895/servuceUrl";
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    HttpEntity<AddRequest> entity = new HttpEntity<AddRequest>(obj, headers);
    ResponseEntity<String> data = null;
    adddata = restTemplate.exchange(syncurl, HttpMethod.POST, entity, String.class);

And one server side we have an exception written as

@ResponseStatus(value=HttpStatus.BAD_REQUEST)
public class InvalidDataException extends Exception {

    public InvalidDataException(String msg) {
        super(msg);
    }
}

The controller looks like

@PostMapping(RestUriMappings.POST_MAPPING)
public ResponseDto add(@Valid @RequestBody AddRequest data) throws InvalidDataException
{

    logger.debug("Incoming data for add: {}", data.toString());

    // validate the payload
    if(data.getName()==null)
       throw new InvalidDataException("Name shouldnt be null");
}

Body:
You are missing:

headers.setContentType(MediaType.APPLICATION_JSON);


答:
A big problem with exec can appear if you exec a module that imports another module.
If this imported module uses relative paths I could imagine this to not work.

Apart from that the only reason I could imagine why you want to use the latter method is dynamic imports if you have a module system for example.
If that is the case, I would recommend you to have a look at importlib

So in terms of speed, reliably and safety always use import for normal imports and importlib for dynamic imports


问:
JSP Page not rendering in SpringBoot Application
I have seen lot of same problem but My problem is not resolving with all those solutions. My JSP page is not rendering.

I have added all required jars like thymeleaf, tomcat, jstl to run the application but still getting error

Below is my controller

```<code>@RequestMapping("/rest/user")
public class BookResource {

@GetMapping("/recommend")
    public List<String> recommend() {
        return bookrepo.BookDetail(bookname);

    }
@RequestMapping(value = "/recommendation", method = RequestMethod.GET)
    public String recommend(Model model) {
        model.addAttribute("recommendations", bookrepo.BookDetail(bookname));
        model.addAttribute("name", "Harsh");
        return "recommendation";

    }
}
</code>```

After i Hit the URL I am getiing below error:

```<code>Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Tue May 28 09:50:33 IST 2019
There was an unexpected error (type=Internal Server Error, status=500).
Error resolving template "recommendation", template might not exist or might not be accessible by any of the configured Template Resolvers
</code>```

The JSP Page I have created not rendering, I put my jsp page inside resources/templates and also at WEB-INF/jsp/.
And properties file is also updated

```<code>spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
</code>```

Pom.xml

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.springBootApp</groupId>
    <artifactId>FirstSpringBootApp</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.3.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>3.3.6</version>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap-datepicker</artifactId>
            <version>1.0.1</version>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>1.9.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- Redis Dependencies -->

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- GCP Dependencies -->

        <!-- <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-gcp-starter</artifactId>
            <version>1.0.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-gcp-starter-sql-mysql</artifactId>
            <version>1.0.0.RELEASE</version>
        </dependency> -->

    </dependencies>

    <build>
        <plugins>
             <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

            <!-- GCP plugin -->
            <!-- <plugin>
                <groupId>com.google.cloud.tools</groupId>
                <artifactId>appengine-maven-plugin</artifactId>
                <version>1.3.2</version>
            </plugin> -->
        </plugins>
    </build>

</project>
</code>```

Structure .

答:
Spring Boot does not support JSPs when using jar packaging. If you want to use JSPs then you must use war packaging. You can do that by adding the following to your pom.xml:

```<code><packaging>war</packaging>
</code>```

It's typically placed immediately after the line with the <version> tag.

Having made that change, you should tell Eclipse to update your Maven project by right-clicking FirstSpringBootApp and then selecting Maven -> Update Project….

Using war packaging will mean that src/main/webapp is recognised by Eclipse and your JSP files in src/main/webapp/WEB-INF/jsp should then be found. For further reference, Spring Boot has a sample project for JSPs that may be of interest.

Body:
I have seen lot of same problem but My problem is not resolving with all those solutions. My JSP page is not rendering.

I have added all required jars like thymeleaf, tomcat, jstl to run the application but still getting error

Below is my controller

@RequestMapping("/rest/user")
public class BookResource {

@GetMapping("/recommend")
    public List<String> recommend() {
        return bookrepo.BookDetail(bookname);

    }
@RequestMapping(value = "/recommendation", method = RequestMethod.GET)
    public String recommend(Model model) {
        model.addAttribute("recommendations", bookrepo.BookDetail(bookname));
        model.addAttribute("name", "Harsh");
        return "recommendation";

    }
}

After i Hit the URL I am getiing below error:

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Tue May 28 09:50:33 IST 2019
There was an unexpected error (type=Internal Server Error, status=500).
Error resolving template "recommendation", template might not exist or might not be accessible by any of the configured Template Resolvers

The JSP Page I have created not rendering, I put my jsp page inside resources/templates and also at WEB-INF/jsp/.
And properties file is also updated

spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp

Pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.springBootApp</groupId>
    <artifactId>FirstSpringBootApp</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.3.RELEASE</version>
        <relativePath />
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>3.3.6</version>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap-datepicker</artifactId>
            <version>1.0.1</version>
        </dependency>

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>1.9.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
             <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

        </plugins>
    </build>

</project>

Structure .

Body:
Spring Boot does not support JSPs when using jar packaging. If you want to use JSPs then you must use war packaging. You can do that by adding the following to your pom.xml:

<packaging>war</packaging>

It's typically placed immediately after the line with the <version> tag.

Having made that change, you should tell Eclipse to update your Maven project by right-clicking FirstSpringBootApp and then selecting Maven -> Update Project….

Using war packaging will mean that src/main/webapp is recognised by Eclipse and your JSP files in src/main/webapp/WEB-INF/jsp should then be found. For further reference, Spring Boot has a sample project for JSPs that may be of interest.


问:
Fetch config values from controller
I am using angular js for my project front end. I need to load config values in controller.

I used the normal import method but it keep showing the error

Uncaught Error: [$injector:nomod]

答:
config values- in sense of json in a seperate file and you want to use that file in your controller.

First you need to import file into your controller:
import {reservedWords} from '../mask/impala-reserved-words.config';

Now you have the complete json, you can use this in your controller.

Title: Fetch config values from controller


问:
getting back to folder in asp.net
protected void Button1_Click(object sender, EventArgs e)
{
     Response.Redirect("Page2.aspx");
}
this is code to go on .aspx but what if i want to go in Folder in my solution explorer, tried with location but it dont work
Who knows post it.

this is location >
website\admin
-news.aspx
-project.aspx
and i created in news.aspx button go back to admin, and when i hit button location is next > website\admin\admin why he  duplicate admin ?

答:
if you have admin folder in your application then redirect it

Response.Redirect("admin/page.aspx"); or
  Response.Redirect("~/admin/page.aspx");

if you don't have admin folder in your application then redirect it

Response.Redirect("page.aspx");

Try this all ...

ContentLicense: CC BY-SA 3.0

Title: getting back to folder in asp.net


问:
Sinon spy callCount returns 0
I can't seem to get my test working. I have a simple mixin like so:

```<code>export const mixin = superclass => class mixin extends superclass {
  constructor() {
    super();
    this.addEventListener('do-it', this.doIt);
  }

  doIt() {
    console.log('did it');
  }
};
</code>```

And a simple test as well:

```<code>describe('mixin', () => {
  it('should call doIt', () => {
    class TestElement extends mixin(HTMLElement) {}
    customElements.define('test-element', TestElement);

    const el = new TestElement();
    const spy = sinon.spy(el, 'doIt');

    el.dispatchEvent(new CustomEvent('do-it'));

    expect(spy.callCount).to.equal(1);
  });
});
</code>```

https://jsfiddle.net/nbuLhvkd/

It logs did it but the spy's callCount value is 0. If I do const spy = sinon.spy(console, 'log');, the spy's callCount is 1. What's the correct way of spying for instance methods?

答:
I used TestElement.prototype for spying and also moved it before instantiating new TestElement();. It now works but can someone explain why?

```<code>describe('Sinon examples', () => {
  it('logs test on do-it', () => {
    class TestElement extends mixin(HTMLElement) {}
    customElements.define('test-element', TestElement);

    const spy = sinon.spy(TestElement.prototype, 'doIt');
    const el = new TestElement();

    el.dispatchEvent(new CustomEvent('do-it'));

    expect(spy.calledOnce).to.be.true;
  });
});
</code>```

https://jsfiddle.net/h0f9Le16/

Title: Sinon spy callCount returns 0

Body:
I can't seem to get my test working. I have a simple mixin like so:

export const mixin = superclass => class mixin extends superclass {
  constructor() {
    super();
    this.addEventListener('do-it', this.doIt);
  }

  doIt() {
    console.log('did it');
  }
};

And a simple test as well:

describe('mixin', () => {
  it('should call doIt', () => {
    class TestElement extends mixin(HTMLElement) {}
    customElements.define('test-element', TestElement);

    const el = new TestElement();
    const spy = sinon.spy(el, 'doIt');

    el.dispatchEvent(new CustomEvent('do-it'));

    expect(spy.callCount).to.equal(1);
  });
});

https://jsfiddle.net/nbuLhvkd/

It logs did it but the spy's callCount value is 0. If I do const spy = sinon.spy(console, 'log');, the spy's callCount is 1. What's the correct way of spying for instance methods?

Body:
I used TestElement.prototype for spying and also moved it before instantiating new TestElement();. It now works but can someone explain why?

describe('Sinon examples', () => {
  it('logs test on do-it', () => {
    class TestElement extends mixin(HTMLElement) {}
    customElements.define('test-element', TestElement);

    const spy = sinon.spy(TestElement.prototype, 'doIt');
    const el = new TestElement();

    el.dispatchEvent(new CustomEvent('do-it'));

    expect(spy.calledOnce).to.be.true;
  });
});

https://jsfiddle.net/h0f9Le16/


问:
TrustPilot Create Invitation API always returns 415 response code
I'm trying to send a TrustPilot invitation using the Create Invitations API but no matter what I try, I get a response code of 415 and with no data returned, so it's virtually impossible for me to debug.

The URL I'm using is correct: https://invitations-api.trustpilot.com/v1/private/business-units/{businessUnitId}/email-invitations (where {businessUnitId} is my business ID)

I am sending a valid (and current) oAuth token in my header.

I am sending a POST request.

I have tested my details with other "Business user OAuth Token" APIs and everything works, so my details are definitely correct. It's just this create invitation API that's not working.

I've tried everything. I've submitted minimal details, a full request, somewhere in between, the example request in the API, and so on. Always a response code of 415.

I've set my "Invitation Settings" in the TrustPilot Business portal, and have even tried submitting those details with the request (ie. sender e-mail "noreply.invitations@trustpilotmail.com" and a valid reply-to e-mail that's been configured).

I've tried contacting the "Integration Engineers" at TrustPilot who after a few back and forth e-mails, also have no idea, which is VERY unsettling. So time for Stack Overflow.

I need to get this figured out, so any help would be great! Perhaps someone can provide a sample request that works in their application that I can try to duplicate in mine?

答:
Http status code 415 (Unsupported Media Type) is returned when Content-Type: application/json is not passed. You need to make sure that this header is added and that the content you are passing in the post body is valid json.

If you are already doing this then I would need an example of a request you are sending to help you further.


问:
Count of each column with non-null values in a table - Oracle
I have a table:

table1

```<code>col1        col2        col3        col4
a           b           (null)      c
a           b           (null)      c
a           (null)      (null)      c
(null)      b           (null)      (null)
a           b           (null)      (null)
a           b           (null)      (null)
</code>```

I have about 300 columns in the table. I need to find count of values for each column which are non-null without typing each column name in the table.

The output would be:

```<code>column_name         count_of_non_null
col1                5
col2                5
col3                0
col4                3
</code>```

Is there a way to do that?

答:
I hope you can achieve using the below query.</p>

```<code>select col,cnt from (
select col1 col, sum(case when col1 is not null then 1 else 0 end) cnt from tableA group by col1
union all
select col2 col, sum(case when col2 is not null then 1 else 0 end) cnt from tableA group by col2
union all
select col3 col, sum(case when col3 is not null then 1 else 0 end) cnt from tableA group by col3
union all
select col4 col, sum(case when col4 is not null then 1 else 0 end) cnt from tableA group by col4
)
</code>```

Body:
I have a table:

table1

col1        col2        col3        col4
a           b           (null)      c
a           b           (null)      c
a           (null)      (null)      c
(null)      b           (null)      (null)
a           b           (null)      (null)
a           b           (null)      (null)

I have about 300 columns in the table. I need to find count of values for each column which are non-null without typing each column name in the table.

The output would be:

column_name         count_of_non_null
col1                5
col2                5
col3                0
col4                3

Is there a way to do that?

Body:
I hope you can achieve using the below query.

select col,cnt from (
select col1 col, sum(case when col1 is not null then 1 else 0 end) cnt from tableA group by col1
union all
select col2 col, sum(case when col2 is not null then 1 else 0 end) cnt from tableA group by col2
union all
select col3 col, sum(case when col3 is not null then 1 else 0 end) cnt from tableA group by col3
union all
select col4 col, sum(case when col4 is not null then 1 else 0 end) cnt from tableA group by col4
)


问:
What do compilers do with compile-time branching?
EDIT: I took the "if/else" case as an example that can sometimes be resolved at compile time (eg when static values are involved, cf <type_traits>). Adapting the answers below to other types of static branching (eg, multiple branches or multi-criteria branches) should be straightforward. Note that compile-time branching using template-meta programming is not the topic here.

In a typical code like this

```<code>#include <type_traits>

template <class T>
T numeric_procedure( const T& x )
{
    if ( std::is_integral<T>::value )
    {
        // Integral types
    }
    else
    {
        // Floating point numeric types
    }
}
</code>```

will the compiler optimize the if/else statement out when I define specific template types later on in my code?

A simple alternative would be to write something like this:

```<code>#include <type_traits>

template <class T>
inline T numeric_procedure( const T& x )
{
    return numeric_procedure_impl( x, std::is_integral<T>() );
}

// ------------------------------------------------------------------------

template <class T>
T numeric_procedure_impl( const T& x, std::true_type const )
{
    // Integral types
}

template <class T>
T numeric_procedure_impl( const T& x, std::false_type const )
{
    // Floating point numeric types
}
</code>```

Is there a difference in terms of performance between these solutions? Is there any non-subjective grounds for saying that one is better than the other? Are there other (possibly better) solutions to deal with compile-time branching?

答:
To answer the title question about how compilers handle if(false):

They optimize away constant branch conditions (and the dead code)

The language standard does not of course require compilers to not be terrible, but the C++ implementations that people actually use are non-terrible in this way.  (So are most C implementations, except for maybe very simplistic non-optimizing ones like tinycc.)

One of the major reasons C++ is designed around if(something) instead of the C preprocessor's #ifdef SOMETHING is that they're equally efficient.  Many C++ features (like constexpr) only got added after compilers already implemented the necessary optimizations (inlining + constant propagation).  (The reason we put up with all the undefined-behaviour pitfalls and gotchas of C and C++ is performance, especially with modern compilers that aggressively optimize on the assumption of no UB.  The language design typically doesn't impose unnecessary performance costs.)

But if you care about debug-mode performance, the choice can be relevant depending on your compiler. (e.g. for a game or other program with real-time requirements for a debug build to even be testable).

e.g. clang++ -O0 ("debug mode") still evaluates an if(constexpr_function()) at compile time and treats it like if(false) or if(true).  Some other compilers only eval at compile-time if they're forced to (by template-matching).

There is no performance cost for if(false) with optimization enabled. (Barring missed-optimization bugs, which might depend on how early in the compile process the condition can be resolved to false and dead-code elimination can remove it before the compiler "thinks about" reserving stack space for its variables, or that the function may be non-leaf, or whatever.)

Any non-terrible compiler can optimize away dead code behind a compile-time-constant condition (Wikipedia: Dead Code Elimination).  This is part of the baseline expectations people have for a C++ implementation to be usable in the real world; it's one of the most basic optimizations and all compilers in real use do it for simple cases like a constexpr.

Often constant-propagation (especially after inlining) will make conditions compile-time constants even if they weren't obviously so in the source.  One of the more-obvious cases is optimizing away the compare on the first iterations of a for (int i=0 ; i<n ; i++) so it can turn into a normal asm loop with a conditional branch at the bottom (like a do{}while loop in C++) if n is constant or provably > 0.  (Yes, real compilers do value-range optimizations, not just constant propagation.)

Some compilers, like gcc and clang, remove dead code inside an if(false) even in "debug" mode, at the minimum level of optimization that's required for them to transform the program logic through their internal arch-neutral representations and eventually emit asm.  (But debug mode disables any kind of constant-propagation for variables that aren't declared const or constexpr in the source.)

Some compilers only do it when optimization is enabled; for example MSVC really likes to be literal in its translation of C++ to asm in debug mode and will actually create a zero in a register and branch on it being zero or not for if(false).

For gcc debug mode (-O0), constexpr functions aren't inlined if they don't have to be.  (In some places the language requires a constant, like an array size inside a struct.  GNU C++ supports C99 VLAs, but does choose to inline a constexpr function instead of actually making a VLA in debug mode.)

But non-function constexprs do get evaluated at compile time, not stored in memory and tested.

But just to reiterate, at any level of optimization, constexpr functions are fully inlined and optimized away, and then the if()

Examples (from the Godbolt compiler explorer)

```<code>#include <type_traits>
void baz() {
    if (std::is_integral<float>::value) f1();  // optimizes for gcc
    else f2();
}
</code>```

All compilers with -O2 optimization enabled (for x86-64):

```<code>baz():
        jmp     f2()    # optimized tailcall
</code>```

Debug-mode code quality, normally not relevant

GCC with optimization disabled still evaluates the expression and does dead-code elimination:

```<code>baz():
        push    rbp
        mov     rbp, rsp          # -fno-omit-frame-pointer is the default at -O0
        call    f2()              # still an unconditional call, no runtime branching
        nop
        pop     rbp
        ret
</code>```

To see gcc not inline something with optimization disabled

```<code>static constexpr bool always_false() { return sizeof(char)==2*sizeof(int); }
void baz() {
    if (always_false()) f1();
    else f2();
}
</code>```

```<code>static constexpr bool always_false() { return sizeof(char)==2*sizeof(int); }
void baz() {
    if (always_false()) f1();
    else f2();
}
</code>```

```<code>;; gcc9.1 with no optimization chooses not to inline the constexpr function
baz():
        push    rbp
        mov     rbp, rsp
        call    always_false()
        test    al, al              # the bool return value
        je      .L9
        call    f1()
        jmp     .L11
.L9:
        call    f2()
.L11:
        nop
        pop     rbp
        ret
</code>```

MSVC's braindead literal code-gen with optimization disabled:

```<code>void foo() {
    if (false) f1();
    else f2();
}
</code>```

```<code>;; MSVC 19.20 x86-64  no optimization
void foo(void) PROC                                        ; foo
        sub     rsp, 40                             ; 00000028H
        xor     eax, eax                     ; EAX=0
        test    eax, eax                     ; set flags from EAX (which were already set by xor)
        je      SHORT $LN2@foo               ; jump if ZF is set, i.e. if EAX==0
        call    void f1(void)                          ; f1
        jmp     SHORT $LN3@foo
$LN2@foo:
        call    void f2(void)                          ; f2
$LN3@foo:
        add     rsp, 40                             ; 00000028H
        ret     0
</code>```

Benchmarking with optimization disabled is not useful

You should always enable optimization for real code; the only time debug-mode performance matters is when that's a pre-condition for debugability.  It's not a useful proxy to avoid having your benchmark optimize away; different code gains more or less from debug mode depending on how it's written.

Unless that's a really big deal for your project, and you just can't find enough info about local vars or something with minimal optimization like g++ -Og, the headline of this answer is the full answer.  Ignore debug mode, only bother thinking about quality of the asm in optimized builds.  (Preferably with LTO enabled, if your project can enable that to allow cross-file inlining.)

Body:
EDIT: I took the "if/else" case as an example that can sometimes be resolved at compile time (eg when static values are involved, cf <type_traits>). Adapting the answers below to other types of static branching (eg, multiple branches or multi-criteria branches) should be straightforward. Note that compile-time branching using template-meta programming is not the topic here.

In a typical code like this

#include <type_traits>

template <class T>
T numeric_procedure( const T& x )
{
    if ( std::is_integral<T>::value )
    {
        // Integral types
    }
    else
    {
        // Floating point numeric types
    }
}

will the compiler optimize the if/else statement out when I define specific template types later on in my code?

A simple alternative would be to write something like this:

#include <type_traits>

template <class T>
inline T numeric_procedure( const T& x )
{
    return numeric_procedure_impl( x, std::is_integral<T>() );
}

// ------------------------------------------------------------------------

template <class T>
T numeric_procedure_impl( const T& x, std::true_type const )
{
    // Integral types
}

template <class T>
T numeric_procedure_impl( const T& x, std::false_type const )
{
    // Floating point numeric types
}

Is there a difference in terms of performance between these solutions? Is there any non-subjective grounds for saying that one is better than the other? Are there other (possibly better) solutions to deal with compile-time branching?

Body:
To answer the title question about how compilers handle if(false):

They optimize away constant branch conditions (and the dead code)

The language standard does not of course require compilers to not be terrible, but the C++ implementations that people actually use are non-terrible in this way.  (So are most C implementations, except for maybe very simplistic non-optimizing ones like tinycc.)

One of the major reasons C++ is designed around if(something) instead of the C preprocessor's #ifdef SOMETHING is that they're equally efficient.  Many C++ features (like constexpr) only got added after compilers already implemented the necessary optimizations (inlining + constant propagation).  (The reason we put up with all the undefined-behaviour pitfalls and gotchas of C and C++ is performance, especially with modern compilers that aggressively optimize on the assumption of no UB.  The language design typically doesn't impose unnecessary performance costs.)

But if you care about debug-mode performance, the choice can be relevant depending on your compiler. (e.g. for a game or other program with real-time requirements for a debug build to even be testable).

e.g. clang++ -O0 ("debug mode") still evaluates an if(constexpr_function()) at compile time and treats it like if(false) or if(true).  Some other compilers only eval at compile-time if they're forced to (by template-matching).

There is no performance cost for if(false) with optimization enabled. (Barring missed-optimization bugs, which might depend on how early in the compile process the condition can be resolved to false and dead-code elimination can remove it before the compiler "thinks about" reserving stack space for its variables, or that the function may be non-leaf, or whatever.)

Any non-terrible compiler can optimize away dead code behind a compile-time-constant condition (Wikipedia: Dead Code Elimination).  This is part of the baseline expectations people have for a C++ implementation to be usable in the real world; it's one of the most basic optimizations and all compilers in real use do it for simple cases like a constexpr.

Often constant-propagation (especially after inlining) will make conditions compile-time constants even if they weren't obviously so in the source.  One of the more-obvious cases is optimizing away the compare on the first iterations of a for (int i=0 ; i<n ; i++) so it can turn into a normal asm loop with a conditional branch at the bottom (like a do{}while loop in C++) if n is constant or provably > 0.  (Yes, real compilers do value-range optimizations, not just constant propagation.)

Some compilers, like gcc and clang, remove dead code inside an if(false) even in "debug" mode, at the minimum level of optimization that's required for them to transform the program logic through their internal arch-neutral representations and eventually emit asm.  (But debug mode disables any kind of constant-propagation for variables that aren't declared const or constexpr in the source.)

Some compilers only do it when optimization is enabled; for example MSVC really likes to be literal in its translation of C++ to asm in debug mode and will actually create a zero in a register and branch on it being zero or not for if(false).

For gcc debug mode (-O0), constexpr functions aren't inlined if they don't have to be.  (In some places the language requires a constant, like an array size inside a struct.  GNU C++ supports C99 VLAs, but does choose to inline a constexpr function instead of actually making a VLA in debug mode.)

But non-function constexprs do get evaluated at compile time, not stored in memory and tested.

But just to reiterate, at any level of optimization, constexpr functions are fully inlined and optimized away, and then the if()

Examples (<a href="https://godbolt.org/#g:!((g:!((g:!((h:codeEditor,i:(fontScale:1.2899450879999999,j:1,lang:c%2B%2B,source:'void+f1()%3B%0Avoid+f2()%3B%0A%0Astatic+const+bool+cond+%3D+false%3B%0Avoid+foo()+%7B%0A++++if+(cond)+f1()%3B%0A++++else+f2()%3B%0A%7D%0A%0A//+non-const,+but+still+static%0A//+and+nothing+in+this+compilation+unit+writes+it%0A//+therefore+compilers+prove+it+has+a+compile-time+constant+value%0Astatic+bool+cond2+%3D+false%3B%0Avoid+bar()+%7B%0A++++if+(cond2)+f1()%3B%0A++++else+f2()%3B%0A%7D%0A%0A%23include+%3Ctype_traits%3E%0A//+optimized+even+at+-O0+for+clang,+but+not+gcc+or+MSVC.+partially+for+ICC%0A//+With+optimization+enabled,+optimized+away+of+course%0Astatic+constexpr+bool+always_false()+%7B+return+sizeof(char)%3D%3D2*sizeof(int)%3B+%7D%0Avoid+baz()+%7B%0A++++//if+(std::is_integral%3Cfloat%3E::value)+f1()%3B++//+optimizes+for+gcc%0A++++if+(always_false())+f1()%3B%0A++++else+f2()%3B%0A%7D%0A%0A%0A//+Compilers+that+support+C99+VLAs+(like+GCC)+*could*+decide%0A//+not+to+actually+inline.++But+in+practice+GCC+-O0+does.%0Aint+test_inline_with_opt_disabled()%7B%0A++++volatile+int+a%5B1+%2B+always_false()%5D%3B%0A++++a%5B0%5D+%3D+1%3B%0A++++return+a%5B0%5D%3B%0A%7D%0A%0A'),l:'5',n:'0',o:'C%2B%2B+source+%231',t:'0')),k:36.99309810000209,l:'4',m:100,n:'0',o:'',s:0,t:'0'),(g:!((h:compiler,i:(compiler:g91,filters:(b:'0',binary:'1',commentOnly:'0',demangle:'0',directives:'0',execute:'1',intel:'0',libraryCode:'1',trim:'1'),fontScale:1.2899450879999999,lang:c%2B%2B,libs:!(),options:'-O3+-Wall+-std%3Dgnu%2B%2B17',source:1),l:'5',n:'0',o:'x86-64+gcc+9.1+(Editor+%231,+Compiler+%231)+C%2B%2B',t:'0')),k:29.673568566664592,l:'4',n:'0',o:'',s:0,t:'0'),(g:!((h:compiler,i:(compiler:vcpp_v19_20_x64,filters:(b:'0',binary:'1',commentOnly:'0',demangle:'0',directives:'0',execute:'1',intel:'0',libraryCode:'1',trim:'1'),fontScale:1.2899450879999999,lang:c%2B%2B,libs:!(),options:'-O2+-Wall',source:1),l:'5',n:'0',o:'x64+msvc+v19.20+(Editor+%231,+Compiler+%232)+C%2B%2B',t:'0')),k:33.33333333333333,l:'4',n:'0',o:'',s:0,t:'0')),l:'2',m:100,n:'0',o:'',t:'0')),version:4" rel="nofollow noreferrer">from the Godbolt compiler explorer)

#include <type_traits>
void baz() {
    if (std::is_integral<float>::value) f1();  // optimizes for gcc
    else f2();
}

All compilers with -O2 optimization enabled (for x86-64):

baz():
        jmp     f2()    # optimized tailcall

Debug-mode code quality, normally not relevant

GCC with optimization disabled still evaluates the expression and does dead-code elimination:

baz():
        push    rbp
        mov     rbp, rsp          # -fno-omit-frame-pointer is the default at -O0
        call    f2()              # still an unconditional call, no runtime branching
        nop
        pop     rbp
        ret

To see gcc not inline something with optimization disabled

static constexpr bool always_false() { return sizeof(char)==2*sizeof(int); }
void baz() {
    if (always_false()) f1();
    else f2();
}

static constexpr bool always_false() { return sizeof(char)==2*sizeof(int); }
void baz() {
    if (always_false()) f1();
    else f2();
}

;; gcc9.1 with no optimization chooses not to inline the constexpr function
baz():
        push    rbp
        mov     rbp, rsp
        call    always_false()
        test    al, al              # the bool return value
        je      .L9
        call    f1()
        jmp     .L11
.L9:
        call    f2()
.L11:
        nop
        pop     rbp
        ret

MSVC's braindead literal code-gen with optimization disabled:

void foo() {
    if (false) f1();
    else f2();
}

;; MSVC 19.20 x86-64  no optimization
void foo(void) PROC                                        ; foo
        sub     rsp, 40                             ; 00000028H
        xor     eax, eax                     ; EAX=0
        test    eax, eax                     ; set flags from EAX (which were already set by xor)
        je      SHORT $LN2@foo               ; jump if ZF is set, i.e. if EAX==0
        call    void f1(void)                          ; f1
        jmp     SHORT $LN3@foo
$LN2@foo:
        call    void f2(void)                          ; f2
$LN3@foo:
        add     rsp, 40                             ; 00000028H
        ret     0

Benchmarking with optimization disabled is not useful

You should always enable optimization for real code; the only time debug-mode performance matters is when that's a pre-condition for debugability.  It's not a useful proxy to avoid having your benchmark optimize away; different code gains more or less from debug mode depending on how it's written.

Unless that's a really big deal for your project, and you just can't find enough info about local vars or something with minimal optimization like g++ -Og, the headline of this answer is the full answer.  Ignore debug mode, only bother thinking about quality of the asm in optimized builds.  (Preferably with LTO enabled, if your project can enable that to allow cross-file inlining.)


问:
Managing cookies in a WPF WebBrowser control?
Is there a way to read/write the cookies that a WebBrowser control uses?  </p>

<p>I am doing something like this...  </p>

```<code>string resultHtml;
HttpWebRequest request = CreateMyHttpWebRequest(); // fills http headers and stuff
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
    resultHtml = sr.ReadToEnd();
}
WebBrowser browser = new WebBrowser();
browser.CookieContainer = request.CookieContainer; // i wish i could do this :(
browser.NavigateToString(resultHtml);
</code>```

答:
Yes you are right, InternetGetCookieEx is the only way to retrieve HttpOnly cookies and it is the preferred way to grab cookie from WebBrowser control.

I posted a complete example here

ContentLicense: CC BY-SA 2.5

Body:
Is there a way to read/write the cookies that a WebBrowser control uses?

I am doing something like this...

string resultHtml;
HttpWebRequest request = CreateMyHttpWebRequest(); // fills http headers and stuff
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
    resultHtml = sr.ReadToEnd();
}
WebBrowser browser = new WebBrowser();
browser.CookieContainer = request.CookieContainer; // i wish i could do this :(
browser.NavigateToString(resultHtml);


问:
Typescript method decorator : this is undefined
I'am trying to play a little with typescript decorators, as stated in the question in a method decorator the this is not set to anything (undefined).

in the code below I am trying to make a controller decorator that will create a koa-router on the controller class. the method decorator will wrap the method and call it with koa context.

index.ts:

```<code>import koa, { ParameterizedContext } from "koa";
import koarouter from "koa-router";

const app = new koa();

function Controller<T extends new (...args: any[]) => {}>(path: string) {
  return (controller: T) => {
    const router = new koarouter({ prefix: path });
    if (controller.prototype.routes) {
      const routes = controller.prototype.routes;
      Object.entries(routes).forEach((e) => {
        if (e[0] === "GET") {
          Object.entries(e[1]).forEach((r) => {
            router.get(r[0], r[1]);
          });
        }
      });
    }
    return class extends controller {
      public router: koarouter = router;
    };
  };
}

function HttpGet(path: string): MethodDecorator {
  // tslint:disable-next-line: only-arrow-functions
  return function(
    target: any,
    propertyName: string | symbol,
    descriptor: PropertyDescriptor,
  ) {
    const originalMethod = descriptor.value;
    descriptor.value = function(...args: any[]): any {
      return originalMethod(...args);
    };
    if (!target.routes) {
      target.routes = { GET: {}, POST: {} };
    }
    target.routes.GET = { ...target.routes.GET, [path]: descriptor.value };
    return descriptor;
  };
}

// tslint:disable-next-line: max-classes-per-file
@Controller("/adex")
class AdexController {
  constructor(private msg: string = "") {
    this.allAdexs = this.allAdexs.bind(this);
  }
  @HttpGet("/id")
  public allAdexs(ctx: ParameterizedContext) {
    console.log(this);
    ctx.body = `hi from adex ${this.msg}`;
  }
}

const adexController = new AdexController();

app.use(adexController.router.routes());
app.use(adexController.router.allowedMethods());

app.listen(3000);
</code>```

tsconfig.json:

```<code>{
  "exclude": ["node_modules"],
  "include": ["src"],
  "compilerOptions": {
    /* Basic Options */
    "target": "es2015" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */,
    "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
    "declaration": true /* Generates corresponding '.d.ts' file. */,
    "sourceMap": true /* Generates corresponding '.map' file. */,
    "outDir": "./lib" /* Redirect output structure to the directory. */,
    "rootDir": "./src" /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */,
    "strict": false /* Enable all strict type-checking options. */,
    "baseUrl": "./" /* Base directory to resolve non-absolute module names. */,
    "paths": {
      "@/*": ["src/*"]
    },
    "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
    "experimentalDecorators": true /* Enables experimental support for ES7 decorators. */,
    "emitDecoratorMetadata": true /* Enables experimental support for emitting type metadata for decorators. */
  }
}

</code>```

答:
the problem in my code is a classic this problem in JavaScript, I am using a class method outside a class and trying to access this. this problem can't be solved what I was trying to do is simply impossible, in order to construct a koa-router I need a controller instance and the methods on this instance need to be bound to this instance, which is impossible in a class or method decorator, when the decorator code is run we don't have instances yet.
I change the design from trying to construct the router in the decorator to delegate this task to another class that will do it at run time and let the decorators only annotate the classes.</p>

Body:
I'am trying to play a little with typescript decorators, as stated in the question in a method decorator the this is not set to anything (undefined).

in the code below I am trying to make a controller decorator that will create a koa-router on the controller class. the method decorator will wrap the method and call it with koa context.

index.ts:

import koa, { ParameterizedContext } from "koa";
import koarouter from "koa-router";

const app = new koa();

function Controller<T extends new (...args: any[]) => {}>(path: string) {
  return (controller: T) => {
    const router = new koarouter({ prefix: path });
    if (controller.prototype.routes) {
      const routes = controller.prototype.routes;
      Object.entries(routes).forEach((e) => {
        if (e[0] === "GET") {
          Object.entries(e[1]).forEach((r) => {
            router.get(r[0], r[1]);
          });
        }
      });
    }
    return class extends controller {
      public router: koarouter = router;
    };
  };
}

function HttpGet(path: string): MethodDecorator {
  // tslint:disable-next-line: only-arrow-functions
  return function(
    target: any,
    propertyName: string | symbol,
    descriptor: PropertyDescriptor,
  ) {
    const originalMethod = descriptor.value;
    descriptor.value = function(...args: any[]): any {
      return originalMethod(...args);
    };
    if (!target.routes) {
      target.routes = { GET: {}, POST: {} };
    }
    target.routes.GET = { ...target.routes.GET, [path]: descriptor.value };
    return descriptor;
  };
}

// tslint:disable-next-line: max-classes-per-file
@Controller("/adex")
class AdexController {
  constructor(private msg: string = "") {
    this.allAdexs = this.allAdexs.bind(this);
  }
  @HttpGet("/id")
  public allAdexs(ctx: ParameterizedContext) {
    console.log(this);
    ctx.body = `hi from adex ${this.msg}`;
  }
}

const adexController = new AdexController();

app.use(adexController.router.routes());
app.use(adexController.router.allowedMethods());

app.listen(3000);

tsconfig.json:

{
  "exclude": ["node_modules"],
  "include": ["src"],
  "compilerOptions": {
    /* Basic Options */
    "target": "es2015" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */,
    "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
    "declaration": true /* Generates corresponding '.d.ts' file. */,
    "sourceMap": true /* Generates corresponding '.map' file. */,
    "outDir": "./lib" /* Redirect output structure to the directory. */,
    "rootDir": "./src" /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */,
    "strict": false /* Enable all strict type-checking options. */,
    "baseUrl": "./" /* Base directory to resolve non-absolute module names. */,
    "paths": {
      "@/*": ["src/*"]
    },
    "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
    "experimentalDecorators": true /* Enables experimental support for ES7 decorators. */,
    "emitDecoratorMetadata": true /* Enables experimental support for emitting type metadata for decorators. */
  }
}


问:
How to Redirect Gecko Javascript Console messages to a file?
Is there any way to redirect the javascript console to a file?

I found this link

https://bitbucket.org/geckofx/geckofx-29.0/issues/9/how-to-get-javascript-consolelog-error

but it requires using devtools that im not going to have in the field.

There must be a simple way to redirect to a C# method.

Any help is appreciated.

答:
Capture the ConsoleMessage event and save each row to a file:</p>

```<code>geckoWebBrowser.ConsoleMessage += GeckoWebBrowserOnConsoleMessage;

void GeckoWebBrowserOnConsoleMessage(object sender, ConsoleMessageEventArgs e)
{
    AppendToFile(e.Message);
}
</code>```

Body:
Capture the ConsoleMessage event and save each row to a file:

geckoWebBrowser.ConsoleMessage += GeckoWebBrowserOnConsoleMessage;

void GeckoWebBrowserOnConsoleMessage(object sender, ConsoleMessageEventArgs e)
{
    AppendToFile(e.Message);
}