答: Try using list.extend instead of append.

Title: How to convert list of arrays to single list in python?

Body:
I have a list of arrays as follows:

list = [
         array([4.1,3.2,5.2]),
         array([4.1,8.5]),
         array([1.2,4.5,7.4])
        ]

I want to convert the above list into a single list as below:

list = [4.1,3.2,5.2,4.1,8.5,1.2,4.5,7.4]

I want to do the above thing in python.

EDIT:

The code I used to generate the list is

  result = []
  result.append(mfccs_processed)
  result.append(chroma_processed)
  result.append(mel_processed)

Now result is showing as follows:

[array([-445.43651286,  111.90097184,  -21.00590592,   31.34361885,
      9.39596702,   -4.40772227,    2.3648624 ,   -1.68017743,
     -6.39975114,   -1.12694295,   -9.34500736,   -1.13545822,
     -7.88168904,  -10.9743485 ,   -2.77344424,   -1.23599528,
     -7.39119564,   -2.44394294,   -3.75691633,   -4.80426688,
     -1.94571499,   -3.95747011,   -5.72427054,   -4.81378321,
     -3.70200738,   -5.19167481,   -4.47207894,   -4.2216418 ,
     -4.1305041 ,   -5.10309738,   -3.89591536,   -2.67058964,
     -4.04656319,   -4.78655754,   -2.44667325,   -3.05293339,
     -4.17915009,   -2.90706455,   -2.8132492 ]), array([0.548945  , 0.59981299, 0.58249648, 0.5834056 , 0.62918682,
   0.58651369, 0.51776701, 0.5152288 , 0.56039473, 0.5606346 ,
   0.59585897, 0.56108877]), array([5.36600691e-05, 3.20399714e-04, 1.19905308e-03, 3.57715592e-03,
   5.45226355e-03, 7.65769149e-02, 9.67304585e-01, 1.37048258e+00,
   2.20317190e+00, 1.47716846e+00, 7.10145651e-01, 7.23264577e-02,
   3.20378431e-02, 2.13741716e-01, 3.50276892e-01, 3.25545211e-01,
   8.23071739e-01, 1.10485735e+00, 5.16918943e-01, 8.84181377e-01,
   9.06340752e-01, 3.95779410e-01, 3.13891357e-01, 1.13048804e-01,
   6.61881599e-01, 1.70450985e+00, 1.82170031e+00, 6.18310782e-01,
   4.05325714e-01, 5.89335840e-01, 4.31023403e-01, 9.29283876e-02,
   4.11129880e-02, 1.71606268e-01, 1.41923368e-01, 9.29835332e-02,
   1.45740019e-01, 1.27688893e-01, 2.34819748e-02, 9.72517361e-03,
   3.63473003e-02, 5.93138929e-02, 3.11671706e-02, 1.18442648e-02,
   8.33423898e-03, 1.87190944e-02, 3.29460414e-02, 2.69168857e-02,
   9.29586223e-03, 6.80686607e-03, 9.94785389e-03, 1.27595168e-02,
   8.88170288e-03, 7.44158290e-03, 9.98228524e-03, 1.63925465e-02,
   9.53423946e-03, 1.05554487e-02, 1.54851110e-02, 2.05146191e-02,
   1.30264012e-02, 7.20523041e-03, 1.83835207e-02, 1.00800192e-02,
   9.16292185e-03, 2.75197205e-02, 1.26532376e-02, 5.50722000e-03,
   8.06991937e-03, 4.67484356e-03, 9.11601494e-03, 9.94969137e-03,
   8.82691376e-03, 1.35812921e-02, 3.38891723e-02, 5.48777803e-02,
   5.47833810e-02, 3.91788967e-02, 2.34909778e-02, 1.59119884e-02,
   1.76145638e-02, 2.31054147e-02, 2.95776919e-02, 4.17103322e-02,
   2.07705960e-02, 1.08400124e-02, 6.43834017e-03, 4.46195474e-03,
   4.44256498e-03, 5.25020141e-03, 1.14951221e-02, 1.41466409e-02,
   1.73377342e-02, 1.41098637e-02, 7.04262356e-03, 3.99505900e-03,
   2.48446049e-03, 1.61739298e-03, 9.00339387e-04, 3.25213392e-04,
   2.93450309e-04, 3.10071719e-04, 2.85876075e-04, 1.78957305e-04,
   1.38316595e-04, 1.07859368e-04, 1.15453318e-04, 8.50033585e-05,
   7.25839567e-05, 3.80280533e-05, 3.57639077e-05, 2.47069514e-05,
   1.57980270e-05, 1.50489378e-05, 1.12732923e-05, 1.08223414e-05,
   1.21111000e-05, 1.57062296e-05, 1.11814270e-05, 9.70704523e-06,
   8.27147728e-06, 6.56079447e-06, 5.53983257e-06, 5.31472585e-06,
   2.77939077e-06, 1.77413323e-06, 1.03589758e-06, 6.50496670e-08])]

Since I already converted my whole dataset using this code above. Now I want to convert the above generated lists into a single list as I explained above. I hope this clarifies the problem. Could you help me out.


来源: stackexchange

问:
Not able to make @Post request using retrofit2 in android
I am learning how to use retrofit in android but whenever I try to retrieve data from the internet my app doesn't return anything My response doesn't come successful and I don't know how to fix the error currently I am trying to post and retrieve data from this URL using https://jsonplaceholder.typicode.com. I am unable to figure out what is causing this.

MainActivity

```<code> private void createpost() {

        Post post2=new Post(1,"This is Title","10");

        Call<Post> postCall= mWebService.createPost(post2);

        postCall.enqueue(new Callback<Post>() {
            @Override
            public void onResponse(Call<Post> call, Response<Post> response) {

                if (response.isSuccessful())
                {
                    Log.d(TAG,"response.isSuccessful()");
                    mLog.setText(String.valueOf(response.code()));
                    showPost(response.body());

                }
            }

            @Override
            public void onFailure(Call<Post> call, Throwable t) {

            }
        });

    }
</code>```

Interface

```<code>public interface MyWebService {

 String BASE_URL="https://jsonplaceholder.typicode.com/";

Retrofit retrofit=new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    @POST("posts")
    Call<Post> createPost(@Body Post post);

}
</code>```

答:
For unknown reason https://jsonplaceholder.typicode.com is throwing socket timeout exception, in the mean time you can check another website with similar functionality https://reqres.in/ here is the sample code attached to post

final HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        final OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(httpLoggingInterceptor)
                .build();
        final String host = "https://reqres.in/";

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(HttpUrl.parse(host))
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        ReqResApi api = retrofit.create(ReqResApi.class);

        api.createUser(new User("silentsudo", "dev"))
                .enqueue(new Callback<User>() {
                    @Override
                    public void onResponse(Call<User> call, Response<User> response) {
                        System.out.println("Resp Success full: " + response.body().toString());
                    }

                    @Override
                    public void onFailure(Call<User> call, Throwable throwable) {
                        System.err.println("Error calling api");
                        throwable.printStackTrace();
                    }
                });

```

<p>Api</p>

<pre class="lang-java prettyprint-override"><code> interface ReqResApi {
        @POST("api/user")
        Call<User> createUser(@Body User post);
    }
</code>```

POJO

class User {
        private String name;
        private String job;

        public User(String name, String job) {
            this.name = name;
            this.job = job;
        }

        @Override
        public String toString() {
            return "User{" +
                    "name='" + name + '\'' +
                    ", job='" + job + '\'' +
                    '}';
        }
    }

```

ContentLicense: CC BY-SA 4.0

Body:
I am learning how to use retrofit in android but whenever I try to retrieve data from the internet my app doesn't return anything My response doesn't come successful and I don't know how to fix the error currently I am trying to post and retrieve data from this URL using https://jsonplaceholder.typicode.com. I am unable to figure out what is causing this.

MainActivity

 private void createpost() {

        Post post2=new Post(1,"This is Title","10");

        Call<Post> postCall= mWebService.createPost(post2);

        postCall.enqueue(new Callback<Post>() {
            @Override
            public void onResponse(Call<Post> call, Response<Post> response) {

                if (response.isSuccessful())
                {
                    Log.d(TAG,"response.isSuccessful()");
                    mLog.setText(String.valueOf(response.code()));
                    showPost(response.body());

                }
            }

            @Override
            public void onFailure(Call<Post> call, Throwable t) {

            }
        });

    }

Interface

public interface MyWebService {

 String BASE_URL="https://jsonplaceholder.typicode.com/";

Retrofit retrofit=new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    @POST("posts")
    Call<Post> createPost(@Body Post post);

}

Body:
For unknown reason https://jsonplaceholder.typicode.com is throwing socket timeout exception, in the mean time you can check another website with similar functionality https://reqres.in/ here is the sample code attached to post

final HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        final OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(httpLoggingInterceptor)
                .build();
        final String host = "https://reqres.in/";

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(HttpUrl.parse(host))
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        ReqResApi api = retrofit.create(ReqResApi.class);

        api.createUser(new User("silentsudo", "dev"))
                .enqueue(new Callback<User>() {
                    @Override
                    public void onResponse(Call<User> call, Response<User> response) {
                        System.out.println("Resp Success full: " + response.body().toString());
                    }

                    @Override
                    public void onFailure(Call<User> call, Throwable throwable) {
                        System.err.println("Error calling api");
                        throwable.printStackTrace();
                    }
                });

Api

 interface ReqResApi {
        @POST("api/user")
        Call<User> createUser(@Body User post);
    }

POJO

class User {
        private String name;
        private String job;

        public User(String name, String job) {
            this.name = name;
            this.job = job;
        }

        @Override
        public String toString() {
            return "User{" +
                    "name='" + name + '\'' +
                    ", job='" + job + '\'' +
                    '}';
        }
    }


问:
Click selected combobox the first textbox.Focus() work Incomplete in C#
Why textbox.Focus() work Incomplete?
When I click selected combobox the first textbox must be focus but It focus just a moment and lost
I don't have idea why it be like this.

It just have problem at combobox event. When I click button "CLEAR" it don't have problem. And when first text box text changed next textbox focus it don't have problem too.

What wrong with my code?

```<code>    private void combModel_SelectedIndexChanged(object sender, EventArgs e)
    {
        gFan.Visible = false;
        gCom.Visible = false;
        gCon.Visible = false;
        pictureBox1.Visible = false;

        clr();

        OleDbCommand cmd;
        OleDbDataReader reader;
        string sql = "select * from model where model = '"+ combModel.Text +"'";
        string model, part, valchk, type;
        conn.Open();
        cmd = new OleDbCommand(sql, conn);
        reader = cmd.ExecuteReader();

        if (reader.HasRows)
        {
            pictureBox1.Visible = true;

            while (reader.Read())
            {
                model = reader.GetValue(1).ToString();
                type = reader.GetValue(2).ToString();
                part = reader.GetValue(3).ToString();
                valchk = reader.GetValue(4).ToString();

                if (type == "Compressor")
                {
                    gCom.Visible = true;
                    pCom.Text = part;
                    vCom.Text = valchk;

                }
                else if (type == "Condenser")
                {
                    gCon.Visible = true;
                    pCon.Text = part;
                    vCon.Text = valchk;

                }
                else if (type == "Fan Motor")
                {
                    gFan.Visible = true;
                    pFan.Text = part;
                    vFan.Text = valchk;
                }
            }
            timeStatus.Start();
        }
        else
        {
            gFan.Visible = false;
            gCom.Visible = false;
            gCon.Visible = false;
            btnRun.Visible = false;
        }
        conn.Close();

        if (txtFan.Visible)
        {
            txtFan.Focus();
        }
        else if (txtComp.Visible)
        {
            txtComp.Focus();
        }
        else if (txtCond.Visible)
        {
            txtCond.Focus();
        }
    }
</code>```

答:
Many times (not always) the kind of wonky behavior you describe has to do with the processing of windows messages on the UI thread. Making calls on other UI controls in a message handler (setting Visibility but especially changing Focus) can interfere with the orderly execution of those messages.

It's good practice to allow SelectedIndexChanged hander to return immediately, and not attempt real work while the UI thread is blocked. The way to do this is to take the work and wrap in in a BeginInvoke using this syntax:

```<code>    private void combModel_SelectedIndexChanged(object sender, EventArgs e)
    {
        BeginInvoke((MethodInvoker)delegate { ExecCombModel(); });
    }
</code>```

...where the real work is put in a separate method. (I named that method ExecCombModel() but it doesn't matter what you call it.) This function will execute immediately after the combo box change is entirely completed and drawn in its new state.

```<code>    private void ExecCombModel()
    {
        gFan.Visible = false;
        gCom.Visible = false;
        gCon.Visible = false;
        pictureBox1.Visible = false;

        clr();

        OleDbCommand cmd;
        OleDbDataReader reader;
        string sql = "select * from model where model = '" + combModel.Text + "'";
        string model, part, valchk, type;
        conn.Open();
        cmd = new OleDbCommand(sql, conn);
        reader = cmd.ExecuteReader();

        if (reader.HasRows)
        {
            pictureBox1.Visible = true;

            while (reader.Read())
            {
                model = reader.GetValue(1).ToString();
                type = reader.GetValue(2).ToString();
                part = reader.GetValue(3).ToString();
                valchk = reader.GetValue(4).ToString();

                if (type == "Compressor")
                {
                    gCom.Visible = true;
                    pCom.Text = part;
                    vCom.Text = valchk;

                }
                else if (type == "Condenser")
                {
                    gCon.Visible = true;
                    pCon.Text = part;
                    vCon.Text = valchk;

                }
                else if (type == "Fan Motor")
                {
                    gFan.Visible = true;
                    pFan.Text = part;
                    vFan.Text = valchk;
                }
            }
            timeStatus.Start();
        }
        else
        {
            gFan.Visible = false;
            gCom.Visible = false;
            gCon.Visible = false;
            btnRun.Visible = false;
        }
        conn.Close();

        if (txtFan.Visible)
        {
            txtFan.Focus();
        }
        else if (txtComp.Visible)
        {
            txtComp.Focus();
        }
        else if (txtCond.Visible)
        {
            txtCond.Focus();
        }
    }
</code>```

I can't promise this will fix your particular issue, but it is good practice in general and has settled many, many similar issues I've dealt with in my own projects. Consider giving it a try.

Body:
Why textbox.Focus() work Incomplete?
When I click selected combobox the first textbox must be focus but It focus just a moment and lost
I don't have idea why it be like this.

It just have problem at combobox event. When I click button "CLEAR" it don't have problem. And when first text box text changed next textbox focus it don't have problem too.

What wrong with my code?

    private void combModel_SelectedIndexChanged(object sender, EventArgs e)
    {
        gFan.Visible = false;
        gCom.Visible = false;
        gCon.Visible = false;
        pictureBox1.Visible = false;

        clr();

        OleDbCommand cmd;
        OleDbDataReader reader;
        string sql = "select * from model where model = '"+ combModel.Text +"'";
        string model, part, valchk, type;
        conn.Open();
        cmd = new OleDbCommand(sql, conn);
        reader = cmd.ExecuteReader();

        if (reader.HasRows)
        {
            pictureBox1.Visible = true;

            while (reader.Read())
            {
                model = reader.GetValue(1).ToString();
                type = reader.GetValue(2).ToString();
                part = reader.GetValue(3).ToString();
                valchk = reader.GetValue(4).ToString();

                if (type == "Compressor")
                {
                    gCom.Visible = true;
                    pCom.Text = part;
                    vCom.Text = valchk;

                }
                else if (type == "Condenser")
                {
                    gCon.Visible = true;
                    pCon.Text = part;
                    vCon.Text = valchk;

                }
                else if (type == "Fan Motor")
                {
                    gFan.Visible = true;
                    pFan.Text = part;
                    vFan.Text = valchk;
                }
            }
            timeStatus.Start();
        }
        else
        {
            gFan.Visible = false;
            gCom.Visible = false;
            gCon.Visible = false;
            btnRun.Visible = false;
        }
        conn.Close();

        if (txtFan.Visible)
        {
            txtFan.Focus();
        }
        else if (txtComp.Visible)
        {
            txtComp.Focus();
        }
        else if (txtCond.Visible)
        {
            txtCond.Focus();
        }
    }

Body:
Many times (not always) the kind of wonky behavior you describe has to do with the processing of windows messages on the UI thread. Making calls on other UI controls in a message handler (setting Visibility but especially changing Focus) can interfere with the orderly execution of those messages.

It's good practice to allow SelectedIndexChanged hander to return immediately, and not attempt real work while the UI thread is blocked. The way to do this is to take the work and wrap in in a BeginInvoke using this syntax:

    private void combModel_SelectedIndexChanged(object sender, EventArgs e)
    {
        BeginInvoke((MethodInvoker)delegate { ExecCombModel(); });
    }

...where the real work is put in a separate method. (I named that method ExecCombModel() but it doesn't matter what you call it.) This function will execute immediately after the combo box change is entirely completed and drawn in its new state.

    private void ExecCombModel()
    {
        gFan.Visible = false;
        gCom.Visible = false;
        gCon.Visible = false;
        pictureBox1.Visible = false;

        clr();

        OleDbCommand cmd;
        OleDbDataReader reader;
        string sql = "select * from model where model = '" + combModel.Text + "'";
        string model, part, valchk, type;
        conn.Open();
        cmd = new OleDbCommand(sql, conn);
        reader = cmd.ExecuteReader();

        if (reader.HasRows)
        {
            pictureBox1.Visible = true;

            while (reader.Read())
            {
                model = reader.GetValue(1).ToString();
                type = reader.GetValue(2).ToString();
                part = reader.GetValue(3).ToString();
                valchk = reader.GetValue(4).ToString();

                if (type == "Compressor")
                {
                    gCom.Visible = true;
                    pCom.Text = part;
                    vCom.Text = valchk;

                }
                else if (type == "Condenser")
                {
                    gCon.Visible = true;
                    pCon.Text = part;
                    vCon.Text = valchk;

                }
                else if (type == "Fan Motor")
                {
                    gFan.Visible = true;
                    pFan.Text = part;
                    vFan.Text = valchk;
                }
            }
            timeStatus.Start();
        }
        else
        {
            gFan.Visible = false;
            gCom.Visible = false;
            gCon.Visible = false;
            btnRun.Visible = false;
        }
        conn.Close();

        if (txtFan.Visible)
        {
            txtFan.Focus();
        }
        else if (txtComp.Visible)
        {
            txtComp.Focus();
        }
        else if (txtCond.Visible)
        {
            txtCond.Focus();
        }
    }

I can't promise this will fix your particular issue, but it is good practice in general and has settled many, many similar issues I've dealt with in my own projects. Consider giving it a try.


问:
Resize event for textarea?
The current versions of Firefox and Chrome include a drag handler to resize a <textarea> box. I need to capture the resizing event, I thought it would be easy with jQuery's resize() event, but it doesn't work!

I have also tried the normal onResize event, but the result is the same. You can try it on JSFiddle.

Is there a way to capture it?

答:
I wrote this answer to another version of the same question. looks like it's old news in here. I like to stick to vanilla js for whatever reason, so here's a tidy little solution in vanilla:

<textarea
  onmousedown="storeDimensions(this)"
  onmouseup="onresizeMaybe(this)"
></textarea>

```
</div>
</div>
</p>

<p>and for homework, use <code>onmousemove</code> to trigger the resize event instead of <code>onmouseup</code> (I didn't need that in my particular case).</p>

<p>if you want to add this to every <code>textarea</code> in the DOM (not really tested):</p>

```let elementArray = document.getElementsByTagName("textarea");
for(var i=0; i<elementArray.length; i++){
  elementArray[i].setAttribute("onmousedown", "storeDimensions(this)");
  elementArray[i].setAttribute("onmouseup", "onresizeMaybe(this)");
}
```

:) hope it helps someone someday... seeing as how this question is now 9 years old.

NOTE: if you're going to want to trigger this on mousemove, the new fangled ResizeObserver(callback).observe(element) approach is great!

ContentLicense: CC BY-SA 2.5

Title: Resize event for textarea?

Body:
I wrote this answer to another version of the same question. looks like it's old news in here. I like to stick to vanilla js for whatever reason, so here's a tidy little solution in vanilla:

<textarea
  onmousedown="storeDimensions(this)"
  onmouseup="onresizeMaybe(this)"
></textarea>

<script>
  function storeDimensions(element){
    element.textWidth = element.offsetWidth;
    element.textHeight = element.offsetHeight;
    element.value = "is it gonna change? we don't know yet...";
  }

  function onresizeMaybe(element){
    if (element.textWidth===element.offsetWidth
     && element.textHeight===element.offsetHeight)
      element.value = "no change.\n";
    else element.value ="RESIZED!\n";

    element.value +=
       `width: ${element.textWidth}\n`
      +`height: ${element.textHeight}`;
  }
</script>

and for homework, use onmousemove to trigger the resize event instead of onmouseup (I didn't need that in my particular case).

if you want to add this to every textarea in the DOM (not really tested):

let elementArray = document.getElementsByTagName("textarea");
for(var i=0; i<elementArray.length; i++){
  elementArray[i].setAttribute("onmousedown", "storeDimensions(this)");
  elementArray[i].setAttribute("onmouseup", "onresizeMaybe(this)");
}

:) hope it helps someone someday... seeing as how this question is now 9 years old.

NOTE: if you're going to want to trigger this on mousemove, the new fangled ResizeObserver(callback).observe(element) approach is great!


问:
How to deal with variable number of columns in dataframe
In the dataframe I have there are so many columns of which I only need a few. For instance

```<code>Col_A      Col_B      Col_C      Col_D      Col_E      Col_F
...        ...        ...      ...      ...      ...      ...
</code>```

I only need columns Col_A, Col_C and Col_E so currently what I do is df = df[['Col_A', 'Col_C', 'Col_E']] but the issue here is that not always there will columns A, C and E maybe all these wont be present. So I need if Col_A is in df.columns add to the df and so on. Is there any simple method to do this ? rather than so many if? Now if a Column is missing I get a KeyError: "['Col_C'] not in index

答:
You could use a list comprehension. For example:

test_columns = ['Col_A', 'Col_C', 'Col_E']
df = df[[c for c in test_columns if c in df.columns]]
```

Body:
In the dataframe I have there are so many columns of which I only need a few. For instance

Col_A      Col_B      Col_C      Col_D      Col_E      Col_F
...        ...        ...      ...      ...      ...      ...

I only need columns Col_A, Col_C and Col_E so currently what I do is df = df[['Col_A', 'Col_C', 'Col_E']] but the issue here is that not always there will columns A, C and E maybe all these wont be present. So I need if Col_A is in df.columns add to the df and so on. Is there any simple method to do this ? rather than so many if? Now if a Column is missing I get a KeyError: "['Col_C'] not in index


问:
Tax classes on WooCommerce with Dokan
I have a marketplace with Dokan Pro installed.

I would like that when vendors create a product ,there is no tax.

But, I need 20% VAT on the products I sell as an administrator. I mean for example that vendors can buy different products to promote their stores. So I need 20% VAT on these products but no taxes on all the others products create by the vendors.

I hope I was clear ?

if someone can help me, I will appreciate !

答:
Well, if your requirements are as simple as described, you can just use other tax class(es) for your products than your vendors use.

However, in most business cases it is not as simple as that, starting with invoice requirements and reaching up to scenarios where you and your vendors need to collect taxes.

Then you need a solution that also

handles the invoicing stuff (VAT numbers on vendors end, etc..)

dynamically calculates and collect taxes based on many factors, like the customer and the vendor location, the products they are selling, businesses customers or private consumers and many more.

You may check out Global Tax for Dokan and Global Tax for Dokan Invoice for these use cases. Alternatively and more generally you can also check out Global Tax for Marketplaces and More (GT4M).

Title: Tax classes on WooCommerce with Dokan


问:
Cannot assign to read only property on deep copied object
I am using angular 9 and ngrx 9

I have a selector that do like this :

```<code>    this.store$
      .pipe(select(SettingsStoreSelectors.selectNavigationSettings), take(1))
      .subscribe((settings: SettingsStoreModels.INavigationSettings) => {
        let copy = JSON.parse(JSON.stringify(settings));
        this.settings = copy.vrMapSettings;
      });
</code>```

This is the only place settings is assigned in this component

In the component I then have a checkbox that edit a setting property

```<code>      <mat-checkbox
        class="setting-input"
        *ngIf="viewer"
        (click)="$event.stopPropagation()"
        (change)="onSettingChange(settings, true)"
        [(ngModel)]="settings.depthTestAgainstTerrain"
      >
        {{ "MAP.SETTINGS.DEPTH_TEST_AGAINST_TERRAIN" | translate }}
      </mat-checkbox>
</code>```

This keeps triggering

core.js:4117 ERROR TypeError: Cannot assign to read only property 'depthTestAgainstTerrain' of object '[object Object]'

But I don't understand anymore what to do. I deep cloned my store property, I want to edit to resubmit an action but it's not possible. why...

EDIT : actually I found out the reason why but I do not understand how to use it correctly then.

I deep clone the object like above from my selector

When a setting change, I dispatch an action to change the setting object in the store : this action setting object reference the same object that is used by the component.

```<code>this.store$.dispatch(new SettingsStoreAction.SetNavigationSettings({ settings: { vrMapSettings: settings } }));
</code>```

Which call this reducer :

```<code>const SET_NAVIGATION_SETTINGS = (state: State, action: featureAction.SetNavigationSettings) => {
  return {
    ...state,
    navigation: {
      ...state.navigation,
      ...action.payload.settings,
    },
  };
};
</code>```

But then, if I edit again, since the store reference directly the setting object of the component, it trigger the error....

If I deep clone here too

```<code>this.store$.dispatch(new SettingsStoreAction.SetNavigationSettings({ settings: { vrMapSettings: JSON.parse(JSON.stringify(settings))} }));
</code>```

The it works...

But if I have to create small action for EVERY property of settings, or deep clone for EVERY dispatch/selection of the store, there is going to be a HUGE flaw in the performance...

am I using it correctly ?

if need more information please comment I will provide.

答:
You need to share declaration of settings, looks like it has a readonly flag.

to fix it you can make this signature writable:

export declare type Writable<T> = {
  -readonly [P in keyof T]: T[P];
};

class Test {
  public settings: Writable<TypeYouNeed>;
}
```

Body:
I am using angular 9 and ngrx 9

I have a selector that do like this :

    this.store$
      .pipe(select(SettingsStoreSelectors.selectNavigationSettings), take(1))
      .subscribe((settings: SettingsStoreModels.INavigationSettings) => {
        let copy = JSON.parse(JSON.stringify(settings));
        this.settings = copy.vrMapSettings;
      });

This is the only place settings is assigned in this component

In the component I then have a checkbox that edit a setting property

      <mat-checkbox
        class="setting-input"
        *ngIf="viewer"
        (click)="$event.stopPropagation()"
        (change)="onSettingChange(settings, true)"
        [(ngModel)]="settings.depthTestAgainstTerrain"
      >
        {{ "MAP.SETTINGS.DEPTH_TEST_AGAINST_TERRAIN" | translate }}
      </mat-checkbox>

This keeps triggering

core.js:4117 ERROR TypeError: Cannot assign to read only property 'depthTestAgainstTerrain' of object '[object Object]'

But I don't understand anymore what to do. I deep cloned my store property, I want to edit to resubmit an action but it's not possible. why...

EDIT : actually I found out the reason why but I do not understand how to use it correctly then.

I deep clone the object like above from my selector

When a setting change, I dispatch an action to change the setting object in the store : this action setting object reference the same object that is used by the component.

this.store$.dispatch(new SettingsStoreAction.SetNavigationSettings({ settings: { vrMapSettings: settings } }));

Which call this reducer :

const SET_NAVIGATION_SETTINGS = (state: State, action: featureAction.SetNavigationSettings) => {
  return {
    ...state,
    navigation: {
      ...state.navigation,
      ...action.payload.settings,
    },
  };
};

But then, if I edit again, since the store reference directly the setting object of the component, it trigger the error....

If I deep clone here too

this.store$.dispatch(new SettingsStoreAction.SetNavigationSettings({ settings: { vrMapSettings: JSON.parse(JSON.stringify(settings))} }));

The it works...

But if I have to create small action for EVERY property of settings, or deep clone for EVERY dispatch/selection of the store, there is going to be a HUGE flaw in the performance...

am I using it correctly ?

if need more information please comment I will provide.


问:
How to test a simple rescue block in ruby
I have a custom fact in ruby that goes like this:

```<code>Facter.add(:some_random_fact) do
  setcode do
    output = execute_some_method
    if !output.nil? then
      begin
        pruned_output = output.split("\n")
        result = true
      rescue
        result = false
      end
    else
      result = false
    end
  end
end
</code>```

How do I write a unit test using rspec for the rescue block to raise an Exception?

EDIT: Please let me know if the below test is the correct way to test it

```<code>it "return fact as false when begin block raises exception" do
    output = double(:output)
    allow(output).to receive(:split).with(true).and_raise(RuntimeError.new("error occured"))
    expect(Facter.fact(:some_random_fact).vallue).to eq(false)
end
</code>```

答:
The code you've shown here is weird and I get the feeling we're missing context, but in general you can stub out a method to raise an error like so:

```<code>expect(output).to receive(:split).with("\n").and_raise(RuntimeError.new("some error"))
</code>```

but this is sort of an ugly way to go about things. If the error is raised conditionally depending the type of output, then it's better to find a way to set that variable to an error-producing value. How to do that, I can't tell you without seeing the test of your code.

For example, say you wrapped all this code in a def add_fact(output) - then from your tests you could intentionally pass an error-causing value for the output, and you no longer need to stub split (which is a wierd thing to do). This pattern is known as "dependency injection".

Body:
I have a custom fact in ruby that goes like this:

Facter.add(:some_random_fact) do
  setcode do
    output = execute_some_method
    if !output.nil? then
      begin
        pruned_output = output.split("\n")
        result = true
      rescue
        result = false
      end
    else
      result = false
    end
  end
end

How do I write a unit test using rspec for the rescue block to raise an Exception?

EDIT: Please let me know if the below test is the correct way to test it

it "return fact as false when begin block raises exception" do
    output = double(:output)
    allow(output).to receive(:split).with(true).and_raise(RuntimeError.new("error occured"))
    expect(Facter.fact(:some_random_fact).vallue).to eq(false)
end

Body:
The code you've shown here is weird and I get the feeling we're missing context, but in general you can stub out a method to raise an error like so:

expect(output).to receive(:split).with("\n").and_raise(RuntimeError.new("some error"))

but this is sort of an ugly way to go about things. If the error is raised conditionally depending the type of output, then it's better to find a way to set that variable to an error-producing value. How to do that, I can't tell you without seeing the test of your code.

For example, say you wrapped all this code in a def add_fact(output) - then from your tests you could intentionally pass an error-causing value for the output, and you no longer need to stub split (which is a wierd thing to do). This pattern is known as "dependency injection".


问:
http-proxy-middleware + express + node.js - unable to redirect to end-point with client side certificate authentication enabled
I am using the http-proxy-middleware (https://www.npmjs.com/package/http-proxy-middleware) to implement a proxy to another REST API that has client-side certificate based authentication enabled (requestCert: true, rejectUnauthorized: true).

Client calls to the Proxy API ( https://localhost:3000/auth ) where http-proxy-middleware is configured and is supposed to proxy it to another REST API ( https://localhost:3002/auth ) that has client-side certificate based authentication enabled (requestCert: true, rejectUnauthorized: true).

I don't want any specific authentication to happen at the proxy. When I invoke the proxy with a path that will route to this target end-point with client-side certs based authentication, it is failing with error message:

Error received in proxy server:

```<code>[HPM] Rewriting path from "/auth" to ""
[HPM] GET /auth ~> https://localhost:3002/auth

RAW REQUEST from the target {
  "host": "localhost:3000",
  "connection": "close"
}
redirecting to auth
[HPM] Error occurred while trying to proxy request  from localhost:3000 to https://localhost:3002/auth (EPROTO) (https://nodejs.org/api/errors.html#errors_common_system_errors)
</code>```

Error received in client side:

```<code>Proxy error: Error: write EPROTO 28628:error:14094410:SSL routines:ssl3_read_bytes:sslv3 alert handshake failure:c:\ws\deps\openssl\openssl\ssl\record\rec_layer_s3.c:1536:SSL alert number 40
</code>```

I don't need the proxy to validate/act on client-side certs coming with the incoming request in any way (I have set secure: false for this), but rather just forward it to the target end point. We are seeing the the certs received from the client are not being passed/proxied/forwarded to the target end-point and hence cert based auth fails on the target end-point.

The client request when sent to the target end-point directly is working, but NOT when sent via http-proxy-middleware proxy.

My test server, client code is given below for reference.

Is there some way to configure the http-proxy-middleware so that it forwards/proxies the client-side certs received from the client to the target end-point so that the client-side certs sent by the client are available for cert based validation on the target REST end-point?

Could you please guide me on how to do this with http-proxy-middleware package or any other suitable way? Thanks in advance.

Server code

```<code>// Certificate based HTTPS Server

var authOptions = {
    key: fs.readFileSync('./certs/server-key.pem'),
    cert: fs.readFileSync('./certs/server-crt.pem'),
    ca: fs.readFileSync('./certs/ca-crt.pem'),
    requestCert: true,
    rejectUnauthorized: true
};

var authApp = express();
authApp.get('/auth', function (req, res) {
    res.send("data from auth");
});

var authServer = https.createServer(authOptions, authApp);
authServer.listen(3002);

// HTTP Proxy Middleware

var authProxyConfig = proxy({
    target: 'https://localhost:3002/auth',
    pathRewrite: {
        '^/auth': '' // rewrite path
    },
    changeOrigin: true,
    logLevel: 'debug',
    secure: false,
    onProxyReq: (proxyReq, req, res) => {
        // Incoming request ( req ) : Not able to see the certificate that was passed by client.
        // Refer the following client code for the same
    },
    onError: (err, req, res) => {
         res.end(`Proxy error: ${err}.`);
    }
});

proxyApp.use('/auth', authProxyConfig);

var unAuthOptions = {
    key: fs.readFileSync('./certs/server-key.pem'),
    cert: fs.readFileSync('./certs/server-crt.pem'),
    ca: fs.readFileSync('./certs/ca-crt.pem'),
    requestCert: false,
    rejectUnauthorized: false
};

var proxyServer = https.createServer(unAuthOptions, proxyApp);
proxyServer.listen(3000);
</code>```

Client Code

```<code>var fs = require('fs');
var https = require('https');

process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
var options = {
    hostname: 'localhost',
    port: 3000,
    path: '/auth',
    method: 'GET',
    key: fs.readFileSync('./certs/client1-key.pem'),
    cert: fs.readFileSync('./certs/client1-crt.pem'),
    ca: fs.readFileSync('./certs/ca-crt.pem')
};

var req = https.request(options, function (res) {
    res.on('data', function (data) {
        process.stdout.write(data);
    });
});
req.end();
</code>```

答:
You specifically say // Incoming request ( req ) : Not able to see the certificate that was passed by client., so perhaps you have already looked at getPeerCertificate and found the connection closed.

That said, in the onProxyReq handler, you might try adding the cert to the proxyReq from the req with the getPeerCertificate method (docs).

This SO answer + comment shows how to get and convert to valid cert.

```<code>const parseReqCert = (req) => {
   const { socket } = req;
   const prefix = '-----BEGIN CERTIFICATE-----';
   const postfix = '-----END CERTIFICATE-----';
   const pemText = socket.getPeerCertificate(true).raw.toString('base64').match(/.{0,64}/g);

   return [prefix, pemText, postfix].join("\n");
}

const addClientCert = (proxyReq, req) => {
   proxyReq.cert = parseReqCert(req);
   return proxyReq;
}

const authProxyConfig = proxy({
    ...
    onProxyReq: (proxyReq, req, res) => {
       addClientCert(proxyReq, req);
    },
    ...
})
</code>```

Body:
I am using the http-proxy-middleware (https://www.npmjs.com/package/http-proxy-middleware) to implement a proxy to another REST API that has client-side certificate based authentication enabled (requestCert: true, rejectUnauthorized: true).

Client calls to the Proxy API ( https://localhost:3000/auth ) where http-proxy-middleware is configured and is supposed to proxy it to another REST API ( https://localhost:3002/auth ) that has client-side certificate based authentication enabled (requestCert: true, rejectUnauthorized: true).

I don't want any specific authentication to happen at the proxy. When I invoke the proxy with a path that will route to this target end-point with client-side certs based authentication, it is failing with error message:

Error received in proxy server:

[HPM] Rewriting path from "/auth" to ""
[HPM] GET /auth ~> https://localhost:3002/auth

RAW REQUEST from the target {
  "host": "localhost:3000",
  "connection": "close"
}
redirecting to auth
[HPM] Error occurred while trying to proxy request  from localhost:3000 to https://localhost:3002/auth (EPROTO) (https://nodejs.org/api/errors.html#errors_common_system_errors)

Error received in client side:

Proxy error: Error: write EPROTO 28628:error:14094410:SSL routines:ssl3_read_bytes:sslv3 alert handshake failure:c:\ws\deps\openssl\openssl\ssl\record\rec_layer_s3.c:1536:SSL alert number 40

I don't need the proxy to validate/act on client-side certs coming with the incoming request in any way (I have set secure: false for this), but rather just forward it to the target end point. We are seeing the the certs received from the client are not being passed/proxied/forwarded to the target end-point and hence cert based auth fails on the target end-point.

The client request when sent to the target end-point directly is working, but NOT when sent via http-proxy-middleware proxy.

My test server, client code is given below for reference.

Is there some way to configure the http-proxy-middleware so that it forwards/proxies the client-side certs received from the client to the target end-point so that the client-side certs sent by the client are available for cert based validation on the target REST end-point?

Could you please guide me on how to do this with http-proxy-middleware package or any other suitable way? Thanks in advance.

Server code

// Certificate based HTTPS Server

var authOptions = {
    key: fs.readFileSync('./certs/server-key.pem'),
    cert: fs.readFileSync('./certs/server-crt.pem'),
    ca: fs.readFileSync('./certs/ca-crt.pem'),
    requestCert: true,
    rejectUnauthorized: true
};

var authApp = express();
authApp.get('/auth', function (req, res) {
    res.send("data from auth");
});

var authServer = https.createServer(authOptions, authApp);
authServer.listen(3002);

// HTTP Proxy Middleware

var authProxyConfig = proxy({
    target: 'https://localhost:3002/auth',
    pathRewrite: {
        '^/auth': '' // rewrite path
    },
    changeOrigin: true,
    logLevel: 'debug',
    secure: false,
    onProxyReq: (proxyReq, req, res) => {
        // Incoming request ( req ) : Not able to see the certificate that was passed by client.
        // Refer the following client code for the same
    },
    onError: (err, req, res) => {
         res.end(`Proxy error: ${err}.`);
    }
});

proxyApp.use('/auth', authProxyConfig);

var unAuthOptions = {
    key: fs.readFileSync('./certs/server-key.pem'),
    cert: fs.readFileSync('./certs/server-crt.pem'),
    ca: fs.readFileSync('./certs/ca-crt.pem'),
    requestCert: false,
    rejectUnauthorized: false
};

var proxyServer = https.createServer(unAuthOptions, proxyApp);
proxyServer.listen(3000);

Client Code

var fs = require('fs');
var https = require('https');

process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
var options = {
    hostname: 'localhost',
    port: 3000,
    path: '/auth',
    method: 'GET',
    key: fs.readFileSync('./certs/client1-key.pem'),
    cert: fs.readFileSync('./certs/client1-crt.pem'),
    ca: fs.readFileSync('./certs/ca-crt.pem')
};

var req = https.request(options, function (res) {
    res.on('data', function (data) {
        process.stdout.write(data);
    });
});
req.end();

Body:
You specifically say // Incoming request ( req ) : Not able to see the certificate that was passed by client., so perhaps you have already looked at getPeerCertificate and found the connection closed.

That said, in the onProxyReq handler, you might try adding the cert to the proxyReq from the req with the getPeerCertificate method (docs).

This SO answer + comment shows how to get and convert to valid cert.

const parseReqCert = (req) => {
   const { socket } = req;
   const prefix = '-----BEGIN CERTIFICATE-----';
   const postfix = '-----END CERTIFICATE-----';
   const pemText = socket.getPeerCertificate(true).raw.toString('base64').match(/.{0,64}/g);

   return [prefix, pemText, postfix].join("\n");
}

const addClientCert = (proxyReq, req) => {
   proxyReq.cert = parseReqCert(req);
   return proxyReq;
}

const authProxyConfig = proxy({
    ...
    onProxyReq: (proxyReq, req, res) => {
       addClientCert(proxyReq, req);
    },
    ...
})


问:
Checking for numeric value entered in text box in Visual Basic
I am working on a program for my Visual Basic class and have a quick question. One of the things we were encouraged to do was to check to make sure the quantity entered in a text box is actually a number. Our professor suggested using IsNumeric to perform this check, but I'm running into some trouble. I already had a good bit of the code written before he added this to the instructions, so not sure how to integrate this into the code I already have.

The main purpose of the program is to allow the user to add ingredients from one list box to the recipe list box, input a quantity for each selected ingredient in a text box, and calculate the total calories for the recipe. The way I have the code written now, IsNumeric is part of a nested if statement at the beginning of where I will start adding the selected ingredients to  the recipe list box. I'm not sure if that's the correct place for it though.

Here is the code I have written so far.

```<code>Public Class Form1

    Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
        Dim i As Integer = lstIngredients.SelectedIndex
        Dim Quantity As Double
        Dim intCount As Integer = 0

        If Trim(txtQuantity.Text = "") Then
            Quantity = 1
        Else
            Quantity = Me.txtQuantity.Text
        End If

        If txtQuantity.Text Is IsNumeric() Then
            If intCount < Quantity Then
                lstRecipe.Items.Add(Quantity & " " & lstIngredients.Text)
                intCount += 1
            End If
        Else
            MessageBox.Show("The quantity entered is not numeric. Please add a numeric    quantity.")
        End If

    End Sub

    Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
        lstRecipe.Items.Clear()
        txtQuantity.Clear()
        txtAnswer.Clear()
    End Sub

    Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click

    End Sub
End Class
</code>```

Also, here is the error I receive when I attempt to run this program as it is written.

```<code>Error   1   Argument not specified for parameter 'Expression' of 'Public   Function IsNumeric(Expression As Object) As Boolean'.
</code>```

Any suggestions would be greatly appreciated.

答: Yes, Double.Tryparse is the best answer to this question, but to save you time on coding and ensure that the value entered is always numeric, use the NumericDropdown control instead of the plain Text Box so that you are sure that inputted value is always numeric and save you time checking the inputted value since that control will not accept anything but numeric values only.

ContentLicense: CC BY-SA 3.0

Body:
I am working on a program for my Visual Basic class and have a quick question. One of the things we were encouraged to do was to check to make sure the quantity entered in a text box is actually a number. Our professor suggested using IsNumeric to perform this check, but I'm running into some trouble. I already had a good bit of the code written before he added this to the instructions, so not sure how to integrate this into the code I already have.

The main purpose of the program is to allow the user to add ingredients from one list box to the recipe list box, input a quantity for each selected ingredient in a text box, and calculate the total calories for the recipe. The way I have the code written now, IsNumeric is part of a nested if statement at the beginning of where I will start adding the selected ingredients to  the recipe list box. I'm not sure if that's the correct place for it though.

Here is the code I have written so far.

Public Class Form1

    Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
        Dim i As Integer = lstIngredients.SelectedIndex
        Dim Quantity As Double
        Dim intCount As Integer = 0

        If Trim(txtQuantity.Text = "") Then
            Quantity = 1
        Else
            Quantity = Me.txtQuantity.Text
        End If

        If txtQuantity.Text Is IsNumeric() Then
            If intCount < Quantity Then
                lstRecipe.Items.Add(Quantity & " " & lstIngredients.Text)
                intCount += 1
            End If
        Else
            MessageBox.Show("The quantity entered is not numeric. Please add a numeric    quantity.")
        End If

    End Sub

    Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
        lstRecipe.Items.Clear()
        txtQuantity.Clear()
        txtAnswer.Clear()
    End Sub

    Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click

    End Sub
End Class

Also, here is the error I receive when I attempt to run this program as it is written.

Error   1   Argument not specified for parameter 'Expression' of 'Public   Function IsNumeric(Expression As Object) As Boolean'.

Any suggestions would be greatly appreciated.


问:
How to check if mocked inner function has been called in jest?
here is my file under test:

file.js:

```<code>function handleRequest(grpcRequestObj, callback){

    if(grpcRequestObj.type === REAL_CLIENT_REQUEST){
        log.trace("Запрос от реального клиента", refId);
        module.exports.realClientRequestWay(grpcRequestObj, callback);
        return;
    }
}
function realClientRequestWay(grpcRequestObj, callback){
    //some logic
}

module.exports = {
    handleRequest,
    realClientRequestWay
}
</code>```

test file:

```<code>
    test("should call real clients way", ()=>{
        jest.mock("../lib/grpc/state");

        const state = require("../lib/grpc/state");
        state.ready = true;
        const constants = require("../lib/grpc/constants");
        const handleRequestModule = require("../lib/grpc/handleRequest");
        const { handleRequest } = jest.requireActual("../lib/grpc/handleRequest");

        handleRequestModule.realClientRequestWay = jest.fn();

        const grpcRequest = {
            type: constants.REAL_CLIENT_REQUEST,
            refId: "123"
        };
        const mockCb = jest.fn();
        handleRequest(grpcRequest, mockCb);
        expect(handleRequestModule.realClientRequestWay).toHaveBeenCalledTimes(1);
    });
</code>```

I am mocking realClientRequestWay fucntion to be a jest mock function just to check if it runs,
but it is not calling, what am I doing wrong?

答:
You can use jest.spyOn(object, methodName) and mockImplementation to overwrite the original function with a mocked one.

E.g.

file.js:

const log = { trace: console.log };
const REAL_CLIENT_REQUEST = 'REAL_CLIENT_REQUEST';

function handleRequest(grpcRequestObj, callback) {
  const refId = '1';
  if (grpcRequestObj.type === REAL_CLIENT_REQUEST) {
    log.trace('Запрос от реального клиента', refId);
    module.exports.realClientRequestWay(grpcRequestObj, callback);
    return;
  }
}
function realClientRequestWay(grpcRequestObj, callback) {
  //some logic
}

module.exports = {
  handleRequest,
  realClientRequestWay,
};
```

<p><code>file.test.js</code>:</p>

<pre class="lang-js prettyprint-override"><code>const file = require('./file');

describe('62079376', () => {
  afterEach(() => {
    jest.restoreAllMocks();
  });
  it('should request', () => {
    jest.spyOn(file, 'realClientRequestWay').mockImplementationOnce();
    const mCallback = jest.fn();
    file.handleRequest({ type: 'REAL_CLIENT_REQUEST' }, mCallback);
    expect(file.realClientRequestWay).toBeCalledWith({ type: 'REAL_CLIENT_REQUEST' }, mCallback);
  });

  it('should do nothing if type not match', () => {
    jest.spyOn(file, 'realClientRequestWay').mockImplementationOnce();
    const mCallback = jest.fn();
    file.handleRequest({ type: '' }, mCallback);
    expect(file.realClientRequestWay).not.toBeCalled();
  });
});
</code>```

unit test results with 100% coverage:

 PASS  stackoverflow/62079376/file.test.js (10.044s)
  62079376
    ✓ should request (16ms)
    ✓ should do nothing if type not match (1ms)

  console.log
    Запрос от реального клиента 1

      at Object.handleRequest (stackoverflow/62079376/file.js:7:9)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |
 file.js  |     100 |      100 |     100 |     100 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        11.393s, estimated 12s
```

Body:
here is my file under test:

file.js:

function handleRequest(grpcRequestObj, callback){

    if(grpcRequestObj.type === REAL_CLIENT_REQUEST){
        log.trace("Запрос от реального клиента", refId);
        module.exports.realClientRequestWay(grpcRequestObj, callback);
        return;
    }
}
function realClientRequestWay(grpcRequestObj, callback){
    //some logic
}

module.exports = {
    handleRequest,
    realClientRequestWay
}

test file:

    test("should call real clients way", ()=>{
        jest.mock("../lib/grpc/state");

        const state = require("../lib/grpc/state");
        state.ready = true;
        const constants = require("../lib/grpc/constants");
        const handleRequestModule = require("../lib/grpc/handleRequest");
        const { handleRequest } = jest.requireActual("../lib/grpc/handleRequest");

        handleRequestModule.realClientRequestWay = jest.fn();

        const grpcRequest = {
            type: constants.REAL_CLIENT_REQUEST,
            refId: "123"
        };
        const mockCb = jest.fn();
        handleRequest(grpcRequest, mockCb);
        expect(handleRequestModule.realClientRequestWay).toHaveBeenCalledTimes(1);
    });

I am mocking realClientRequestWay fucntion to be a jest mock function just to check if it runs,
but it is not calling, what am I doing wrong?

Body:
You can use jest.spyOn(object, methodName) and mockImplementation to overwrite the original function with a mocked one.

E.g.

file.js:

const log = { trace: console.log };
const REAL_CLIENT_REQUEST = 'REAL_CLIENT_REQUEST';

function handleRequest(grpcRequestObj, callback) {
  const refId = '1';
  if (grpcRequestObj.type === REAL_CLIENT_REQUEST) {
    log.trace('Запрос от реального клиента', refId);
    module.exports.realClientRequestWay(grpcRequestObj, callback);
    return;
  }
}
function realClientRequestWay(grpcRequestObj, callback) {
  //some logic
}

module.exports = {
  handleRequest,
  realClientRequestWay,
};

file.test.js:

const file = require('./file');

describe('62079376', () => {
  afterEach(() => {
    jest.restoreAllMocks();
  });
  it('should request', () => {
    jest.spyOn(file, 'realClientRequestWay').mockImplementationOnce();
    const mCallback = jest.fn();
    file.handleRequest({ type: 'REAL_CLIENT_REQUEST' }, mCallback);
    expect(file.realClientRequestWay).toBeCalledWith({ type: 'REAL_CLIENT_REQUEST' }, mCallback);
  });

  it('should do nothing if type not match', () => {
    jest.spyOn(file, 'realClientRequestWay').mockImplementationOnce();
    const mCallback = jest.fn();
    file.handleRequest({ type: '' }, mCallback);
    expect(file.realClientRequestWay).not.toBeCalled();
  });
});

unit test results with 100% coverage:

 PASS  stackoverflow/62079376/file.test.js (10.044s)
  62079376
    ✓ should request (16ms)
    ✓ should do nothing if type not match (1ms)

  console.log
    Запрос от реального клиента 1

      at Object.handleRequest (stackoverflow/62079376/file.js:7:9)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |
 file.js  |     100 |      100 |     100 |     100 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        11.393s, estimated 12s


问:
FOREIGN KEY (`shiftid`, `groupid`, `sectionid`) REFERENCES `tbl_academic`(`id`, `id`, `id`) is not working in mysql database
```<code>ALTER TABLE `tbl_acc_payable` ADD CONSTRAINT `FK_APAY_SGS` FOREIGN KEY (`shiftid`, `groupid`, `sectionid`) REFERENCES `tbl_academic`(`id`, `id`, `id`) ON DELETE SET NULL ON UPDATE CASCADE
</code>```

why I cannot apply multiple columns references another table multiple column in MySQL database?

return Error Message:

#1005 - Can't create table fastpay.tbl_acc_payable (errno: 150 "Foreign key constraint is incorrectly formed") (Details…)

答: A composite foreign key should reference a composite primary key. As you can't create a primary key on triple ID column, you should create 3 foreign keys, each of them referencing the same primary key (on the tbl_academic.id column).

Body:
ALTER TABLE `tbl_acc_payable` ADD CONSTRAINT `FK_APAY_SGS` FOREIGN KEY (`shiftid`, `groupid`, `sectionid`) REFERENCES `tbl_academic`(`id`, `id`, `id`) ON DELETE SET NULL ON UPDATE CASCADE

why I cannot apply multiple columns references another table multiple column in MySQL database?

return Error Message:

#1005 - Can't create table fastpay.tbl_acc_payable (errno: 150 "Foreign key constraint is incorrectly formed") (Details…)


问:
add strikethrough for dynamically created lis
I can make an li created in my html file have a strike through when clicked, but I can't get it the dynamically created ones to work... Any advice would be greatly appreciated!

```<code><!DOCTYPE html>
<html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>To do</title>
    <link rel="stylesheet" href="todo.css">
    <script src="https://kit.fontawesome.com/ff289d152e.js" crossorigin="anonymous">
    </script>
    </head>
<body>

        <div class="container">
        <h1>To be done</h1>
            <input id="add-todo" type="text" placeholder="What do you have to do?">
        <ol id="tasks">
            <li>
               This one works <i class="fas fa-trash-alt"></i>
            </li>
        </ol>
    </div>
<script type="text/javascript" src="todo.js"></script>
</body>
</html>

html {
    box-sizing: border-box;
    height: 100vh;
    width: 100vw;
}
body{
    font-family: 'Raleway';
    background: url(https://i.gyazo.com/9024e4cc2d29408dd08bd67a54b355c8.png);
    background-size: cover;
    background-position: center;
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    width: 100%;
    height: 100%;
}

.container {
    display: flex;
    flex-direction: column;
    background-color: gray;
    margin: 10px;
    padding: 10px;
}
</code>```

Add this style when clicked...

```<code>.completed {
    text-decoration: line-through;
}

i {
    margin-left: 20px;
}

let addTaskField = document.getElementById('add-todo');
let tasks = document.getElementById('tasks');
let todos = document.querySelectorAll("li");

// create a todo
addTaskField.addEventListener('keypress', function(event){
if(event.which === 13 && this.value != ''){
    let li = document.createElement("li");
    let i = document.createElement("i");
    i.classList = "fas fa-trash-alt";
    li.innerHTML = this.value;
    li.appendChild(i);
    tasks.append(li);
    this.value = '';
}
});
</code>```

Can't I just select all lis, even if they're created later, and loop through them adding the event listener?

```<code>// add strikethrough
todos.forEach(function(todo) {
    todo.addEventListener('click', function() {
        this.classList.toggle('completed');
    });
})
</code>```

答:
If you check your 'todos' variable, it only has one 'li' element in it at all times. No matter how many new tasks you add. This is because todos('s) value get's updated when the page loads for the first time.

All I did is added the event listener before the 'li' get's appended. It's not the most elegant solution but it works. If you run this you'll notice it works only for the dynamically created elements.

```<code>let addTaskField = document.getElementById('add-todo');
let tasks = document.getElementById('tasks');
let todos = [];

// create a todo
addTaskField.addEventListener('keypress', function(event){
if(event.which === 13 && this.value != ''){
    let li = document.createElement("li");
    let i = document.createElement("i");
    i.classList = "fas fa-trash-alt";
    li.innerHTML = this.value;
    li.appendChild(i);
    li.addEventListener('click', function() {
        this.classList.toggle('completed');
    })
    tasks.append(li);
    todos = document.querySelectorAll("li");
    this.value = '';
}
});
</code>```

Body:
I can make an li created in my html file have a strike through when clicked, but I can't get it the dynamically created ones to work... Any advice would be greatly appreciated!

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>To do</title>
    <link rel="stylesheet" href="todo.css">

To be done

            <input id="add-todo" type="text" placeholder="What do you have to do?">

               This one works

html {
    box-sizing: border-box;
    height: 100vh;
    width: 100vw;
}
body{
    font-family: 'Raleway';
    background: url(https://i.gyazo.com/9024e4cc2d29408dd08bd67a54b355c8.png);
    background-size: cover;
    background-position: center;
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    width: 100%;
    height: 100%;
}

.container {
    display: flex;
    flex-direction: column;
    background-color: gray;
    margin: 10px;
    padding: 10px;
}

Add this style when clicked...

.completed {
    text-decoration: line-through;
}

i {
    margin-left: 20px;
}

let addTaskField = document.getElementById('add-todo');
let tasks = document.getElementById('tasks');
let todos = document.querySelectorAll("li");

// create a todo
addTaskField.addEventListener('keypress', function(event){
if(event.which === 13 && this.value != ''){
    let li = document.createElement("li");
    let i = document.createElement("i");
    i.classList = "fas fa-trash-alt";
    li.innerHTML = this.value;
    li.appendChild(i);
    tasks.append(li);
    this.value = '';
}
});

Can't I just select all lis, even if they're created later, and loop through them adding the event listener?

// add strikethrough
todos.forEach(function(todo) {
    todo.addEventListener('click', function() {
        this.classList.toggle('completed');
    });
})

Body:
If you check your 'todos' variable, it only has one 'li' element in it at all times. No matter how many new tasks you add. This is because todos('s) value get's updated when the page loads for the first time.

All I did is added the event listener before the 'li' get's appended. It's not the most elegant solution but it works. If you run this you'll notice it works only for the dynamically created elements.

let addTaskField = document.getElementById('add-todo');
let tasks = document.getElementById('tasks');
let todos = [];

// create a todo
addTaskField.addEventListener('keypress', function(event){
if(event.which === 13 && this.value != ''){
    let li = document.createElement("li");
    let i = document.createElement("i");
    i.classList = "fas fa-trash-alt";
    li.innerHTML = this.value;
    li.appendChild(i);
    li.addEventListener('click', function() {
        this.classList.toggle('completed');
    })
    tasks.append(li);
    todos = document.querySelectorAll("li");
    this.value = '';
}
});


问:
JSON to XML conversion in Node JS service (using xml2js)
I need some help/advice with JSON to XML conversion in Node js.
I have a service that gets a JSON object in request body that needs to convert to XML. I am able to achieve this using node-xml2js for json inputs with maximum one level of nested objects. But, it gets way more complicated with nested objects having attribute values. Attributes should be identified first, prefixed with $ sign and enclosed in curly braces before parsing through xml2js to get correct xml.
Is there a better way of doing this where this complicated layer of reformatting the json input can be simplified?
xml2js can converts this:

```<code>{
    "Level1":{  "$":{   "attribute":"value" },
                "Level2": {"$":{"attribute1":"05/29/2020",
                            "attribute2":"10","attribute3":"Pizza"}}
}
</code>```

to this:(which is correct):

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Level1 attribute="value">
  <Level2 attribute1="05/29/2020" attribute2="10" attribute3="Pizza"/>
</Level1>
</code>```

But actual json input is this:

```<code>{
    "Level1":{"attribute":"value",
              "Level2": {"attribute1":"05/29/2020",
                         "attribute2":"10","attribute3":"Pizza"} }
}
</code>```

Expected same result:

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Level1 attribute="value">
  <Level2 attribute1="05/29/2020" attribute2="10" attribute3="Pizza"/>
</Level1>
</code>```

Please let me know if you have worked on similar requirements. Appreciate any help.
Thank you.

答:
you can use this library :nashwaan/xml-js

Like This:

```<code>  let xmlJ=require('xml-js');
  let parseToJson=(xml)=>{
        return new Promise(resolve => {
              let convert;

              convert=xmlJ.xml2json(xml,{compact:true});
              resolve(convert);

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

Body:
I need some help/advice with JSON to XML conversion in Node js.
I have a service that gets a JSON object in request body that needs to convert to XML. I am able to achieve this using node-xml2js for json inputs with maximum one level of nested objects. But, it gets way more complicated with nested objects having attribute values. Attributes should be identified first, prefixed with $ sign and enclosed in curly braces before parsing through xml2js to get correct xml.
Is there a better way of doing this where this complicated layer of reformatting the json input can be simplified?
xml2js can converts this:

{
    "Level1":{  "$":{   "attribute":"value" },
                "Level2": {"$":{"attribute1":"05/29/2020",
                            "attribute2":"10","attribute3":"Pizza"}}
}

to this:(which is correct):

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Level1 attribute="value">
  <Level2 attribute1="05/29/2020" attribute2="10" attribute3="Pizza"/>
</Level1>

But actual json input is this:

{
    "Level1":{"attribute":"value",
              "Level2": {"attribute1":"05/29/2020",
                         "attribute2":"10","attribute3":"Pizza"} }
}

Expected same result:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Level1 attribute="value">
  <Level2 attribute1="05/29/2020" attribute2="10" attribute3="Pizza"/>
</Level1>

Please let me know if you have worked on similar requirements. Appreciate any help.
Thank you.

Body:
you can use this library :nashwaan/xml-js

Like This:

  let xmlJ=require('xml-js');
  let parseToJson=(xml)=>{
        return new Promise(resolve => {
              let convert;

              convert=xmlJ.xml2json(xml,{compact:true});
              resolve(convert);

   });
 };


问:
jQuery droppable - receiving events during drag over (not just on initial drag over)
I am using jQuery droppable (in conjunction with jQuery draggable) to allow the user to add rows to an HTML table by dragging items from a list and dropping them on the table.

This works well, however at present the logic is that when the user drag-drops on a table row the new row gets added below the row they dropped on.

It would be better if the new row's add position was based on whether the user dropped in the upper or lower half of an existing row.

This is easy enough to calculate in the drop event, but I need to give UI feedback as the user drags (which I would do by means of two CSS classes droppable-above and droppable-below for example).

This doesn't seem to be possible, as the over event only fires once; when the user initially drags over the droppable element.

Is it possible to get the over event to fire for every mouse move while the user is over a droppable element?

If so, then I'd be able to do this:

```<code>$("tr.droppable").droppable({
    over: function(event, ui) {
        if (/* mouse is in top half of row */) {
            $(this).addClass("droppable-above").removeClass("droppable-below");
        }
        else {
            $(this).removeClass("droppable-above").addClass("droppable-below");
        }
    },

    out: function(event, ui) {
        $(this).removeClass("droppable-above").removeClass("droppable-below");
    },

    drop: function(event, ui) {
        $(this).removeClass("droppable-above").removeClass("droppable-below");
        if (/* mouse is in top half of row */) {
            // Add new row above the dropped row
        }
        else {
            // Add new row below the dropped row
        }
    }
});
</code>```

The CSS styles would be something like...

```<code>droppable-above { border-top: solid 3px Blue; }
droppable-below { border-bottom: solid 3px Blue; }
</code>```

答:
This is a rather crude (and codeless) solution, but you could try using the hoverClass option with your Droppable and creating a new class called "hovering" to set Droppable behavior that only happens when the Draggable is hovering over the Droppable. This "hovering" class could then (this is the crude bit) run some sort of endless loop or some other sort of checker; I haven't used these classes before, so I can't think of any more specifics past this point. =/

Edit: Even cruder, you could alternate disabling and enabling the Droppable using the "hovering" class; I would definitely do this synchronously though, and with a generous time delineation as well. The alternating disable and enable calls should trigger one of the events, though which one you'll have to experiment with to find out.

Body:
I am using jQuery droppable (in conjunction with jQuery draggable) to allow the user to add rows to an HTML table by dragging items from a list and dropping them on the table.

This works well, however at present the logic is that when the user drag-drops on a table row the new row gets added below the row they dropped on.

It would be better if the new row's add position was based on whether the user dropped in the upper or lower half of an existing row.

This is easy enough to calculate in the drop event, but I need to give UI feedback as the user drags (which I would do by means of two CSS classes droppable-above and droppable-below for example).

This doesn't seem to be possible, as the over event only fires once; when the user initially drags over the droppable element.

Is it possible to get the over event to fire for every mouse move while the user is over a droppable element?

If so, then I'd be able to do this:

$("tr.droppable").droppable({
    over: function(event, ui) {
        if (/* mouse is in top half of row */) {
            $(this).addClass("droppable-above").removeClass("droppable-below");
        }
        else {
            $(this).removeClass("droppable-above").addClass("droppable-below");
        }
    },

    out: function(event, ui) {
        $(this).removeClass("droppable-above").removeClass("droppable-below");
    },

    drop: function(event, ui) {
        $(this).removeClass("droppable-above").removeClass("droppable-below");
        if (/* mouse is in top half of row */) {
            // Add new row above the dropped row
        }
        else {
            // Add new row below the dropped row
        }
    }
});

The CSS styles would be something like...

droppable-above { border-top: solid 3px Blue; }
droppable-below { border-bottom: solid 3px Blue; }


问:
Best Way to do Object Mapping with Nested Json
Currently I'm trying to write a site that interacts with a public API using Feign and Spring.
I'm having trouble deciding how to handle the object mapping for deeply nested JSON.

Ex:

```<code>[
  {
    "type": "console",
    "category": "Console",
    "result_count": 1,
    "shown_count": 1,
    "result": [
      {
        "name": "Nintendo Switch",
        "id": "nintendo-switch",
        "platform": {
          "name": "Nintendo",
          "category": "nintendo",
          "type": "platform"
        },
        "image": {
          "url": "https://encrypted-tbn1.gstatic.com/shopping?q=tbn:ANd9GcRqJYIheMDjTE9WAHjMSW4bjh7OplS7Bep9CdsBBLWMwGdXim7xOG4&usqp=CAc",
          "height": 409,
          "width": 631
        },
        "min_price": 205,
        "variations": [
          {
            "items": [
              {
                "hex_code": "#696969",
                "name": "Gray",
                "id": "space-gray",
                "type": "color"
              },
              {
                "hex_code": "#C0C0C0",
                "name": "Silver",
                "id": "silver",
                "type": "color"
              }
            ],
            "name": "Color",
            "type": "color"
          },
          {
            "items": [
              {
                "name": "Nintendo",
                "id": "nintendo",
                "type": "platform"
              }
            ],
            "name": "Platform",
            "type": "platform"
          }
        ]
      }
    ]
  }
]
</code>```

As of now, I have a single Java file with a class for each object in the JSON, and I've considered having the Object mapper just put everything into a HashMap. Is there a more elegant way to do this?

```<code>public class SearchResults {
    private List<SearchResult> products;
    private int resultCount;
    private String type;

}

class SearchResult {
    private String name;
    private String slug;
    private Image image;

}

class Image {
    private String URL;
    private String height;
    private String width;

}
</code>```

答:
Based on the json file provided i have designed the classes and also provided the code to parse the json file to java

```<code>public class  Console{
     String type;
     String category;
     int result_count;
     int show_count;
     Result [] result;
}

public class Result{
    String name;
    String id;
    Platform platform;
    Image image;
    int mini_price;
    Variation [] variations;
}

public class Platform{
    String name;
    String category;
    String type;
}

public class Image{
    String url;
    int height;
    int width;
}

public class Variation{
    String name;
    String type;
    Item [] items;

}

public class Item{
    String hex_code;
    String name;
    String id;
    String type;
}
</code>```

code to parse:

```<code>ObjectMapper objectMapper = new ObjectMapper();
         objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
         Console[] consoles = objectMapper.readValue(ResourceUtils.getFile("path of json file"), Console[].class);
         logger.info("Continents -> {}",(Object)continents);
         for(Console console:consoles) {
            //read the data accordingly
                     }
</code>```

Body:
Currently I'm trying to write a site that interacts with a public API using Feign and Spring.
I'm having trouble deciding how to handle the object mapping for deeply nested JSON.

Ex:

[
  {
    "type": "console",
    "category": "Console",
    "result_count": 1,
    "shown_count": 1,
    "result": [
      {
        "name": "Nintendo Switch",
        "id": "nintendo-switch",
        "platform": {
          "name": "Nintendo",
          "category": "nintendo",
          "type": "platform"
        },
        "image": {
          "url": "https://encrypted-tbn1.gstatic.com/shopping?q=tbn:ANd9GcRqJYIheMDjTE9WAHjMSW4bjh7OplS7Bep9CdsBBLWMwGdXim7xOG4&usqp=CAc",
          "height": 409,
          "width": 631
        },
        "min_price": 205,
        "variations": [
          {
            "items": [
              {
                "hex_code": "#696969",
                "name": "Gray",
                "id": "space-gray",
                "type": "color"
              },
              {
                "hex_code": "#C0C0C0",
                "name": "Silver",
                "id": "silver",
                "type": "color"
              }
            ],
            "name": "Color",
            "type": "color"
          },
          {
            "items": [
              {
                "name": "Nintendo",
                "id": "nintendo",
                "type": "platform"
              }
            ],
            "name": "Platform",
            "type": "platform"
          }
        ]
      }
    ]
  }
]

As of now, I have a single Java file with a class for each object in the JSON, and I've considered having the Object mapper just put everything into a HashMap. Is there a more elegant way to do this?

public class SearchResults {
    private List<SearchResult> products;
    private int resultCount;
    private String type;

}

class SearchResult {
    private String name;
    private String slug;
    private Image image;

}

class Image {
    private String URL;
    private String height;
    private String width;

}

Body:
Based on the json file provided i have designed the classes and also provided the code to parse the json file to java

public class  Console{
     String type;
     String category;
     int result_count;
     int show_count;
     Result [] result;
}

public class Result{
    String name;
    String id;
    Platform platform;
    Image image;
    int mini_price;
    Variation [] variations;
}

public class Platform{
    String name;
    String category;
    String type;
}

public class Image{
    String url;
    int height;
    int width;
}

public class Variation{
    String name;
    String type;
    Item [] items;

}

public class Item{
    String hex_code;
    String name;
    String id;
    String type;
}

code to parse:

ObjectMapper objectMapper = new ObjectMapper();
         objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
         Console[] consoles = objectMapper.readValue(ResourceUtils.getFile("path of json file"), Console[].class);
         logger.info("Continents -> {}",(Object)continents);
         for(Console console:consoles) {
            //read the data accordingly
                     }


问:
iOS Keeping old launch screen and app icon after update
I have an app where I recently replaced the launch images and app icons, I removed all of the old assets from everywhere in the project. When I upgrade the app from the old version to the new version by just building in Xcode, everything is fine. However, if I have the old version of my app installed then upgrade it from TestFlight, every time I kill the app then restart it the old launch image briefly appears before showing the new launch image. Similarly when I then close the app, the old app icon briefly flashes before switching back to my new one.

I opened up the App using iExplorer and noticed that there is an image of the old launch screen saved in the /Library/Caches/Shapshots directory (I don't know how or why it got there). When I delete it manually through iExplorer, it stops appearing. However, when I try to remove it with code using NSFileManager methods, I get errors saying I am forbidden from deleting files in this directory.

Has anyone experienced this before and have any advice?

答:
Solution Work For Me

Delete your app from the device

Switch off device

Switch on device

clean Build Folder

Again build and install and launch app.

Enjoy


答:
From what I have interpreted, you could create a copy of df, store it in another variable and then 'drop' the columns you don't require,

```<code>df_copy = df.copy()
df = df.drop(['Col_A', 'Col_C', 'Col_E'], axis = 1)

# If you want to add other columns to the df
df['Col_B'] = df_copy['Col_B']
</code>```

Title: How to deal with variable number of columns in dataframe

Body:
In the dataframe I have there are so many columns of which I only need a few. For instance

Col_A      Col_B      Col_C      Col_D      Col_E      Col_F
...        ...        ...      ...      ...      ...      ...

I only need columns Col_A, Col_C and Col_E so currently what I do is df = df[['Col_A', 'Col_C', 'Col_E']] but the issue here is that not always there will columns A, C and E maybe all these wont be present. So I need if Col_A is in df.columns add to the df and so on. Is there any simple method to do this ? rather than so many if? Now if a Column is missing I get a KeyError: "['Col_C'] not in index

Body:
From what I have interpreted, you could create a copy of df, store it in another variable and then 'drop' the columns you don't require,

df_copy = df.copy()
df = df.drop(['Col_A', 'Col_C', 'Col_E'], axis = 1)

# If you want to add other columns to the df
df['Col_B'] = df_copy['Col_B']


问:
How can I measure the coverage (in production system)?
I would like to measure the coverage of my Python code which gets executed in the production system.

I want an answer to this question:

Which lines get executed often (hot spots) and which lines are never used (dead code)?

Of course this must not slow down my production site.

I am not talking about measuring the coverage of tests.

答:
If i understand it right you want to learn which parts of your application is used most often by users.

TL;DR;

Use one of the metrics frameworks for python if you do not want to do it by hand. Some of them are above:

DataDog

Prometheus

Prometheus Python Client

Splunk

It is usually done by function level and it actually depends on application;

If it is a desktop app with internet access:

You can create a simple db and collect how many times your functions are called. For accomplish it you can write a simple function and call it inside every function that you want to track. After that you can define an asynchronous task to upload your data to internet.

If it is a web application:

You can track which functions are called from js (mostly preferred for user behaviour tracking) or from web api. It is a good practice to start from outer to go inner. First detect which end points are frequently called (If you are using a proxy like nginx you can analyze server logs to gather information. It is the easiest and cleanest way). After that insert a logger to every other function that you want to track and simply analyze your logs for every week or month.

But you want to analyze your production code line by line (it is a very bad idea) you can start your application with python profilers. Python has one already: cProfile.


问:
Escaping inner loop and go to the outer loop after action is done
There is a code for the BigestCountries class.

It consists of 2 arrays:

```<code>private String[][] biggestCountries; - holds country name and the continent, e.g. biggestCountries[CHINA][COUNTRY_NAME] = "China"; biggestCountries[CHINA][COUNTRY_CONTINENT] = "Asia";

private int[][] countryData; - holds populations and year founded, e.g. countryData[CHINA][COUNTRY_POPULATION] = 1433783686; countryData[CHINA][COUNTRY_AGE_FOUNDED] = 1949;
</code>```

```<code>public String[] getCountriesFoundedBetween(int min, int max){
    int countriesMatched;
    countriesMatched = 0;
    String[] countriesFoundedBetween;

    if(biggestCountries == null || biggestCountries.length == 0){
         return null;
    }

    for(int i = 0; i < biggestCountries.length; i++){
        if(countryData[i][COUNTRY_AGE_FOUNDED] >= min && countryData[i][COUNTRY_AGE_FOUNDED] <= max){

            System.out.println(String.format("%d %s", countryData[i][COUNTRY_AGE_FOUNDED], biggestCountries[i][COUNTRY_NAME]));
            countriesMatched++;
        }
    }

    if(countriesMatched > 0){
        countriesFoundedBetween = new String[countriesMatched];
    } else {
        return null;
    }

    for(int i = 0; i < biggestCountries.length; i++) { // outer loop for countries array length of NUMBER_OF_COUNTRIES

        String countryMatched = null;
        System.out.println("biggestCountries[i] " + biggestCountries[i][COUNTRY_NAME]);

        if(countryData[i][COUNTRY_AGE_FOUNDED] >= min && countryData[i][COUNTRY_AGE_FOUNDED] <= max){
            for(int j = 0; j < countriesFoundedBetween.length; j++){ // how to escape inner loop?

                countryMatched =  biggestCountries[i][COUNTRY_NAME];
                countriesFoundedBetween[j] = countryMatched;
                System.out.println("countriesFoundedBetween: " + countriesFoundedBetween[j] + "; biggestCountries[i][COUNTRY_NAME]: " + biggestCountries[i][COUNTRY_NAME]);

            }
        }
    }

    return countriesFoundedBetween;
}
</code>```

Unfortunately, It cannot escape from the inner loop and re-writes the matched country to all rows of the newly-generated array.

答:
If you name a Class BigestCountries still it has an attribute biggestCountries which is an array, holds information about biggest countries, I think you are not utilizing the potential of OO.

You can use Class to represent the data of a Country. With data encapsulation, you can get rid of nested array thus nested loop and control flow statement (break, continue etc), lookup index constant, keep sync-ing the index between biggestCountries and countryData etc.

Your code doing the same task twice. The first loop count the matched country and initialize a array. The second loop actually put the matched country name to the array.

Java collection framework provide data structure with dynamic size. I use ArrayList here

I think ageFound should be named yearFound?

Refactored Your code

Country.java

```<code>public class Country {

    private String name;
    private int population;
    private int yearFound;
    private String continent;

    public Country(String name, String continent, int year, int population) {
        this.name = name;
        this.population = population;
        this.continent = continent;
        this.yearFound = year;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPopulation() {
        return population;
    }

    public void setPopulation(int population) {
        this.population = population;
    }

    public String getContinent() {
        return continent;
    }

    public void setContinent(String continent) {
        this.continent = continent;
    }

    public int getYearFound() {
        return yearFound;
    }

    public void setYearFound(int yearFound) {
        this.yearFound = yearFound;
    }

    @Override
    public String toString() {
        return "Country [name=" + name + ", population=" + population + ", yearFound=" + yearFound + ", continent="
                + continent + "]";
    }

}
</code>```

BiggestCountries.java

```<code>import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class BiggestCountries {

    private List<Country> countries = new ArrayList<Country>() {
        {
            add(new Country("China", "Asia", 1949, 1433783686));
            add(new Country("Canada", "North America", 1867, 37590000));
            add(new Country("United States", "North America", 1776, 328200000));
        }
    };

    public List<Country> getCountriesFoundedBetween(int min, int max) {
        List<Country> matchedCountry = new ArrayList<Country>();
        Iterator<Country> itrCoutnry = countries.iterator();

        while (itrCoutnry.hasNext()) {
            Country country = itrCoutnry.next();
            int yearFound = country.getYearFound();
            if (min < yearFound && max > yearFound) {
                matchedCountry.add(country);
            }
        }
        return matchedCountry;
    }

}
</code>```

Test Run

```<code>public static void main(String[] args) {

    List<Country> matchedCountries = new BiggestCountries().getCountriesFoundedBetween(1700, 1899);
    System.out.println(matchedCountries);
}
</code>```

Result

```<code>[Country [name=Canada, population=37590000, yearFound=1867, continent=North America], Country [name=United States, population=328200000, yearFound=1776, continent=North America]]
</code>```

Body:
There is a code for the BigestCountries class.

It consists of 2 arrays:

private String[][] biggestCountries; - holds country name and the continent, e.g. biggestCountries[CHINA][COUNTRY_NAME] = "China"; biggestCountries[CHINA][COUNTRY_CONTINENT] = "Asia";

private int[][] countryData; - holds populations and year founded, e.g. countryData[CHINA][COUNTRY_POPULATION] = 1433783686; countryData[CHINA][COUNTRY_AGE_FOUNDED] = 1949;

public String[] getCountriesFoundedBetween(int min, int max){
    int countriesMatched;
    countriesMatched = 0;
    String[] countriesFoundedBetween;

    if(biggestCountries == null || biggestCountries.length == 0){
         return null;
    }

    for(int i = 0; i < biggestCountries.length; i++){
        if(countryData[i][COUNTRY_AGE_FOUNDED] >= min && countryData[i][COUNTRY_AGE_FOUNDED] <= max){

            System.out.println(String.format("%d %s", countryData[i][COUNTRY_AGE_FOUNDED], biggestCountries[i][COUNTRY_NAME]));
            countriesMatched++;
        }
    }

    if(countriesMatched > 0){
        countriesFoundedBetween = new String[countriesMatched];
    } else {
        return null;
    }

    for(int i = 0; i < biggestCountries.length; i++) { // outer loop for countries array length of NUMBER_OF_COUNTRIES

        String countryMatched = null;
        System.out.println("biggestCountries[i] " + biggestCountries[i][COUNTRY_NAME]);

        if(countryData[i][COUNTRY_AGE_FOUNDED] >= min && countryData[i][COUNTRY_AGE_FOUNDED] <= max){
            for(int j = 0; j < countriesFoundedBetween.length; j++){ // how to escape inner loop?

                countryMatched =  biggestCountries[i][COUNTRY_NAME];
                countriesFoundedBetween[j] = countryMatched;
                System.out.println("countriesFoundedBetween: " + countriesFoundedBetween[j] + "; biggestCountries[i][COUNTRY_NAME]: " + biggestCountries[i][COUNTRY_NAME]);

            }
        }
    }

    return countriesFoundedBetween;
}

Unfortunately, It cannot escape from the inner loop and re-writes the matched country to all rows of the newly-generated array.

Body:
If you name a Class BigestCountries still it has an attribute biggestCountries which is an array, holds information about biggest countries, I think you are not utilizing the potential of OO.

You can use Class to represent the data of a Country. With data encapsulation, you can get rid of nested array thus nested loop and control flow statement (break, continue etc), lookup index constant, keep sync-ing the index between biggestCountries and countryData etc.

Your code doing the same task twice. The first loop count the matched country and initialize a array. The second loop actually put the matched country name to the array.

Java collection framework provide data structure with dynamic size. I use ArrayList here

I think ageFound should be named yearFound?

Refactored Your code

Country.java

public class Country {

    private String name;
    private int population;
    private int yearFound;
    private String continent;

    public Country(String name, String continent, int year, int population) {
        this.name = name;
        this.population = population;
        this.continent = continent;
        this.yearFound = year;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPopulation() {
        return population;
    }

    public void setPopulation(int population) {
        this.population = population;
    }

    public String getContinent() {
        return continent;
    }

    public void setContinent(String continent) {
        this.continent = continent;
    }

    public int getYearFound() {
        return yearFound;
    }

    public void setYearFound(int yearFound) {
        this.yearFound = yearFound;
    }

    @Override
    public String toString() {
        return "Country [name=" + name + ", population=" + population + ", yearFound=" + yearFound + ", continent="
                + continent + "]";
    }

}

BiggestCountries.java

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class BiggestCountries {

    private List<Country> countries = new ArrayList<Country>() {
        {
            add(new Country("China", "Asia", 1949, 1433783686));
            add(new Country("Canada", "North America", 1867, 37590000));
            add(new Country("United States", "North America", 1776, 328200000));
        }
    };

    public List<Country> getCountriesFoundedBetween(int min, int max) {
        List<Country> matchedCountry = new ArrayList<Country>();
        Iterator<Country> itrCoutnry = countries.iterator();

        while (itrCoutnry.hasNext()) {
            Country country = itrCoutnry.next();
            int yearFound = country.getYearFound();
            if (min < yearFound && max > yearFound) {
                matchedCountry.add(country);
            }
        }
        return matchedCountry;
    }

}

Test Run

public static void main(String[] args) {

    List<Country> matchedCountries = new BiggestCountries().getCountriesFoundedBetween(1700, 1899);
    System.out.println(matchedCountries);
}

Result

[Country [name=Canada, population=37590000, yearFound=1867, continent=North America], Country [name=United States, population=328200000, yearFound=1776, continent=North America]]


问:
How do I use EFCore.BulkExtensions in ASP.NET Boilerplate
I need to do bulk insert in ASP.NET Boilerplate and I tried to implement EFCore.BulkExtensions after reading https://github.com/aspnetboilerplate/aspnetboilerplate/issues/4397 .

I installed the latest EFCore.BulkExtensions from nuget into the project and I tried to use doContext as below so that I can use wherever required.

```<code>public class MyQueryExecutor : IMyQueryExecutor, ITransientDependency
{
    private readonly IDbContextProvider<ModCoreDbContext> _dbContextProvider;

    public MyQueryExecutor(IDbContextProvider<ModCoreDbContext> dbContextProvider)
    {
        _dbContextProvider = dbContextProvider;
    }

    public void BulkImport<T>(IList<T> entities) where T : class
    {
        _dbContextProvider.GetDbContext().BulkInsert(entities);
    }
}

public interface IMyQueryExecutor
{
    void BulkImport<T>(IList<T> entities) where T : class;
}
</code>```

I referenced EFCore.BulkExtensions in the required projects and when I tried to run the project, I am getting an error when execution hit the following line in Startup.cs

```<code> app.UseAbp(); //Initializes ABP framework.
</code>```

Error:

```<code>TypeLoadException: Could not load type 'Microsoft.EntityFrameworkCore.Metadata.Internal.EntityMaterializerSource' from assembly 'Microsoft.EntityFrameworkCore, Version=3.1.3.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'.
</code>```

Actual Microsoft.EntityFrameworkCore that is part of the boilerplate framework is 2.2.4

答: I need to download a lower version of EFCore.BulkExtensions (2.4.7) nuget as the latest version did not support EF 2.2.4</p>

Body:
I need to do bulk insert in ASP.NET Boilerplate and I tried to implement EFCore.BulkExtensions after reading https://github.com/aspnetboilerplate/aspnetboilerplate/issues/4397 .

I installed the latest EFCore.BulkExtensions from nuget into the project and I tried to use doContext as below so that I can use wherever required.

public class MyQueryExecutor : IMyQueryExecutor, ITransientDependency
{
    private readonly IDbContextProvider<ModCoreDbContext> _dbContextProvider;

    public MyQueryExecutor(IDbContextProvider<ModCoreDbContext> dbContextProvider)
    {
        _dbContextProvider = dbContextProvider;
    }

    public void BulkImport<T>(IList<T> entities) where T : class
    {
        _dbContextProvider.GetDbContext().BulkInsert(entities);
    }
}

public interface IMyQueryExecutor
{
    void BulkImport<T>(IList<T> entities) where T : class;
}

I referenced EFCore.BulkExtensions in the required projects and when I tried to run the project, I am getting an error when execution hit the following line in Startup.cs

 app.UseAbp(); //Initializes ABP framework.

Error:

TypeLoadException: Could not load type 'Microsoft.EntityFrameworkCore.Metadata.Internal.EntityMaterializerSource' from assembly 'Microsoft.EntityFrameworkCore, Version=3.1.3.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'.

Actual Microsoft.EntityFrameworkCore that is part of the boilerplate framework is 2.2.4