问:
Write vector values into multiple files at once in C++
I have the data in my vector. I am trying to write each vector value, say vector_name[0] into "examplezero.h" , vector_name[1] into "exampleone.h" and so on. The below code shows how I have created the files.

```<code>int co = 80;
string name ="example";
std::ofstream output_file[80];
for (int i = 0; i < co; i++)
{
     output_file[i].open(name + std::to_string(i) + ".h");
     output_file[i].close();
}
</code>```

I am trying to iterate over my vector and trying to write to my files.

```<code>std::vector<string> rowname;  //This has all the values
    for (auto i = rowname.begin(); i != rowname.end(); ++i)
    {

        std::ostream_iterator<std::string> \
                           output_iterator(output_file[80], "\n");
        std::copy(rowname.begin(), rowname.end(), output_iterator);

    }
</code>```

When I am trying to write to the files it is crashing. Can you let me know what's wrong? I know the basics of C++ and trying to learn the advanced concepts.
Thanks

答:
Your program is likely crashing because you wrote this code:

```<code>std::ostream_iterator<std::string> \
                           output_iterator(output_file[80], "\n");
</code>```

...and output_file[80] is one element past the end of the array.  You declared it as:

```<code>std::ofstream output_file[80];
</code>```

The first element of that array is output_file[0] and the last element of that array is output_file[79].

There are more things wrong

As @walnut pointed out, if your code is really as you posted it, then it appears to close each file immediately after opening it, without writing anything to the file.

```<code>for (int i = 0; i < co; i++)
{
     output_file[i].open(name + std::to_string(i) + ".h");
     output_file[i].close(); // Leaving so soon?
}
</code>```

Writing to an ofstream that has been closed does not crash the program, but sets an error condition on the ofstream (badbit).  So this will appear to be a silent failure to you.

To fix

To fix your problem you'll have to write to your file after you open it, but before you close it.

You'll also have to decide exactly which output_file you actually want to write to and provide the correct array index.  It's not obviously clear from your sample code what your intent was.  You'll have to decide which file(s) (of the 80 that you opened) you want to write each element of your rowname vector into.

The std::copy as you have written it will write all strings in the rowname vector to the same stream.  If your intent was to write each element to its own file, then you'll have to set it up substantially differently.

Something more along the lines of:

```<code>#include <fstream>
#include <vector>
#include <string>

int main() {
    std::vector<std::string> rowname = { "alpha", "bravo", "charlie" }; // example data
    std::string name = "example"; // base filename

    for (size_t i = 0; i < rowname.size(); ++i) {
        std::ofstream output_file;
        std::string filename = name + std::to_string(i) + ".h"; // e.g.: "example0.h"
        output_file.open(filename);
        output_file << rowname[i]; // write the string to the file
        output_file.close(); // if you want
    }
}
</code>```

This writes the text alpha into example0.h, bravo into example1.h, and charlie into example2.h.

Body:
I have the data in my vector. I am trying to write each vector value, say vector_name[0] into "examplezero.h" , vector_name[1] into "exampleone.h" and so on. The below code shows how I have created the files.

int co = 80;
string name ="example";
std::ofstream output_file[80];
for (int i = 0; i < co; i++)
{
     output_file[i].open(name + std::to_string(i) + ".h");
     output_file[i].close();
}

I am trying to iterate over my vector and trying to write to my files.

std::vector<string> rowname;  //This has all the values
    for (auto i = rowname.begin(); i != rowname.end(); ++i)
    {

        std::ostream_iterator<std::string> \
                           output_iterator(output_file[80], "\n");
        std::copy(rowname.begin(), rowname.end(), output_iterator);

    }

When I am trying to write to the files it is crashing. Can you let me know what's wrong? I know the basics of C++ and trying to learn the advanced concepts.
Thanks

Body:
Your program is likely crashing because you wrote this code:

std::ostream_iterator<std::string> \
                           output_iterator(output_file[80], "\n");

...and output_file[80] is one element past the end of the array.  You declared it as:

std::ofstream output_file[80];

The first element of that array is output_file[0] and the last element of that array is output_file[79].

There are more things wrong

As @walnut pointed out, if your code is really as you posted it, then it appears to close each file immediately after opening it, without writing anything to the file.

for (int i = 0; i < co; i++)
{
     output_file[i].open(name + std::to_string(i) + ".h");
     output_file[i].close(); // Leaving so soon?
}

Writing to an ofstream that has been closed does not crash the program, but sets an error condition on the ofstream (badbit).  So this will appear to be a silent failure to you.

To fix

To fix your problem you'll have to write to your file after you open it, but before you close it.

You'll also have to decide exactly which output_file you actually want to write to and provide the correct array index.  It's not obviously clear from your sample code what your intent was.  You'll have to decide which file(s) (of the 80 that you opened) you want to write each element of your rowname vector into.

The std::copy as you have written it will write all strings in the rowname vector to the same stream.  If your intent was to write each element to its own file, then you'll have to set it up substantially differently.

Something more along the lines of:

#include <fstream>
#include <vector>
#include <string>

int main() {
    std::vector<std::string> rowname = { "alpha", "bravo", "charlie" }; // example data
    std::string name = "example"; // base filename

    for (size_t i = 0; i < rowname.size(); ++i) {
        std::ofstream output_file;
        std::string filename = name + std::to_string(i) + ".h"; // e.g.: "example0.h"
        output_file.open(filename);
        output_file << rowname[i]; // write the string to the file
        output_file.close(); // if you want
    }
}

This writes the text alpha into example0.h, bravo into example1.h, and charlie into example2.h.


来源: stackexchange

问:
no such column: hey (code 1 SQLITE_ERROR[1]): , while compiling: SELECT ID FROM ALLWORKHOURS WHERE NOTEMEMOS = hey
Log Cat:

```<code>no such column: hey (code 1 SQLITE_ERROR[1]): , while compiling: SELECT ID FROM ALLWORKHOURS WHERE NOTEMEMOS = hey
</code>```

code:

```<code>    102) public String getID(String note){
    103)      SQLiteDatabase db = this.getWritableDatabase();
    104)      String  query = ("SELECT " + COL_0 + " FROM " + TABLE_NAME + " WHERE " + COL_5 + " = " + note);
    105)      db.rawQuery(query,null);
    106)      return query;
    107) }
</code>```

I do have a column name hey in my Database
Database Picture

答:
Your terminology is confused.

hey is a value, NOTEMEMOS is a column.

You need to quote the value hey to let the SQL compiler know that it is a string value, rather than a column you are trying to compare against.

String  query = ("SELECT " + COL_0 + " FROM " + TABLE_NAME + " WHERE " + COL_5 + " = '" + note + "'");
```

<p>Just a note, you would be better off using a parameterised query, as using raw values is insecure (see SQL injection).</p>

<pre class="lang-java prettyprint-override"><code>String  query = ("SELECT " + COL_0 + " FROM " + TABLE_NAME + " WHERE " + COL_5 + " = ?"); // That's right, quotes aren't needed for a parameterized query.
String result = "";
Cursor cursor = db.rawQuery(query,new String[] {note} );
if (cursor.moveToFirst()) {
    result = cursor.getString(cursor.getColumnIndex(COL_0));
}
cursor.close();
return result;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Log Cat:

no such column: hey (code 1 SQLITE_ERROR[1]): , while compiling: SELECT ID FROM ALLWORKHOURS WHERE NOTEMEMOS = hey

code:

    102) public String getID(String note){
    103)      SQLiteDatabase db = this.getWritableDatabase();
    104)      String  query = ("SELECT " + COL_0 + " FROM " + TABLE_NAME + " WHERE " + COL_5 + " = " + note);
    105)      db.rawQuery(query,null);
    106)      return query;
    107) }

I do have a column name hey in my Database
Database Picture

Body:
Your terminology is confused.

hey is a value, NOTEMEMOS is a column.

You need to quote the value hey to let the SQL compiler know that it is a string value, rather than a column you are trying to compare against.

String  query = ("SELECT " + COL_0 + " FROM " + TABLE_NAME + " WHERE " + COL_5 + " = '" + note + "'");

Just a note, you would be better off using a parameterised query, as using raw values is insecure (see SQL injection).

String  query = ("SELECT " + COL_0 + " FROM " + TABLE_NAME + " WHERE " + COL_5 + " = ?"); // That's right, quotes aren't needed for a parameterized query.
String result = "";
Cursor cursor = db.rawQuery(query,new String[] {note} );
if (cursor.moveToFirst()) {
    result = cursor.getString(cursor.getColumnIndex(COL_0));
}
cursor.close();
return result;


问:
Problem with SqlConnection, ASP.net C#
I have the following C# code:

```<code>public string TargetDate()
{
    SqlConnection con =
        new SqlConnection("Server=localhost;Database=Timer;Trusted_Connectopn=True");
    SqlCommand cmd = new SqlCommand("select * from Timer");
    con.Open();

    DataSet ds = new DataSet(cmd,con);
    SqlDataAdapter da = new SqlDataAdapter();
    da.Fill(ds);
    con.Close();
}
</code>```

but I get error at the: new DataSet(cmd,con); ...

the error: CS1502: The best overloaded
  method match for

```<code>'System.Data.DataSet.DataSet(System.Runtime.Serialization.SerializationInfo,
</code>```

System.Runtime.Serialization.StreamingContext)'
  has some invalid arguments

What is could be the problem?

答:
It seems you have mixed up the constructors:

Try the following:

```<code>DataSet ds = new DataSet();

SqlDataAdapter da = new SqlDataAdapter(con);
</code>```

Hope that helps

ContentLicense: CC BY-SA 3.0

Title: Problem with SqlConnection, ASP.net C#

Body:
I have the following C# code:

public string TargetDate()
{
    SqlConnection con =
        new SqlConnection("Server=localhost;Database=Timer;Trusted_Connectopn=True");
    SqlCommand cmd = new SqlCommand("select * from Timer");
    con.Open();

    DataSet ds = new DataSet(cmd,con);
    SqlDataAdapter da = new SqlDataAdapter();
    da.Fill(ds);
    con.Close();
}

but I get error at the: new DataSet(cmd,con); ...

the error: CS1502: The best overloaded
  method match for

'System.Data.DataSet.DataSet(System.Runtime.Serialization.SerializationInfo,

System.Runtime.Serialization.StreamingContext)'
  has some invalid arguments

What is could be the problem?

Body:
It seems you have mixed up the constructors:

Try the following:

DataSet ds = new DataSet();

SqlDataAdapter da = new SqlDataAdapter(con);

Hope that helps


问:
Calling Array.includes() on a accumulator raises a TypeError; .reduce()
I'm trying to reduce an Array that contains any duplicate words. Upon trying to return the result I get the follow error TypeError: acc.includes is not a function. The way I'm interpreting the error is that the method is not available for the array acc due to the version of JavaScript being used.

Am I correct in assuming this or is there something else going on here?

```<code>function removeDuplicateWords (s) {
  return s.split(" ").reduce(function(acc, value, index, array) {
    if (array.indexOf(value) === array.lastIndexOf(value)) {
      return acc.push(value);
    } else {
        return !acc.includes(value) ? acc.push(value) : "";
    }
  }, [])
}
</code>```

答:
You are not returning array in your function. Whatever you return from the callback of reduce() it will become acc for next iteration. You need to return the array.

push() method is inplace(it will modify original array) method which returns the length of new array not the new array with new value.

function removeDuplicateWords (s) {
  return s.split(" ").reduce(function(acc, value, index, array) {
    if (array.indexOf(value) === array.lastIndexOf(value)) {
      return [...acc, value]
    } else {
        return !acc.includes(value) ? [...acc, value] : acc;
    }
  }, [])
}

console.log(removeDuplicateWords("hello hello hey"))```
</div>
</div>
</p>

<p>The same thing could be achieved using <code>Set()</code> and spread operator.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const removeDups = str => [... new Set(str.split(' '))];

console.log(removeDups('hello hey hello'))</code>```

Body:
I'm trying to reduce an Array that contains any duplicate words. Upon trying to return the result I get the follow error TypeError: acc.includes is not a function. The way I'm interpreting the error is that the method is not available for the array acc due to the version of JavaScript being used.

Am I correct in assuming this or is there something else going on here?

function removeDuplicateWords (s) {
  return s.split(" ").reduce(function(acc, value, index, array) {
    if (array.indexOf(value) === array.lastIndexOf(value)) {
      return acc.push(value);
    } else {
        return !acc.includes(value) ? acc.push(value) : "";
    }
  }, [])
}

Body:
You are not returning array in your function. Whatever you return from the callback of reduce() it will become acc for next iteration. You need to return the array.

push() method is inplace(it will modify original array) method which returns the length of new array not the new array with new value.

function removeDuplicateWords (s) {
  return s.split(" ").reduce(function(acc, value, index, array) {
    if (array.indexOf(value) === array.lastIndexOf(value)) {
      return [...acc, value]
    } else {
        return !acc.includes(value) ? [...acc, value] : acc;
    }
  }, [])
}

console.log(removeDuplicateWords("hello hello hey"))

The same thing could be achieved using Set() and spread operator.

const removeDups = str => [... new Set(str.split(' '))];

console.log(removeDups('hello hey hello'))


问:
How to Display Multiple Labels in One Line with Python Tkinter?
I have a Program that displays text on GUI Screen with Multiple Labels. But all the Labels are showing text in the new line and I want to show text in single line. Code is Below:

```<code>from tkinter import *
import tkinter as tk

win = Tk()
win.title("Label Screen")
win.geometry("800x600+50+50")
win.config(bg='white')

label1=Label(win, text="Label 1", font=("Calibri",24,"bold"), bg='white')
label1.pack(pady=15)

label2=Label(win, text="Label 2", font=("Calibri",24,"bold"), bg='white')
label2.pack(pady=15)

label3=Label(win, text="Label 3", font=("Calibri",24,"bold"), bg='white')
label3.pack(pady=15)

win.mainloop()
</code>```

Output:

答:
Do this :

```<code>label1.pack(side=tk.LEFT,pady=15)
label2.pack(side=tk.LEFT,pady=15)
label3.pack(side=tk.LEFT,pady=15)
</code>```

Further read : https://effbot.org/tkinterbook/pack.htm

Body:
I have a Program that displays text on GUI Screen with Multiple Labels. But all the Labels are showing text in the new line and I want to show text in single line. Code is Below:

from tkinter import *
import tkinter as tk

win = Tk()
win.title("Label Screen")
win.geometry("800x600+50+50")
win.config(bg='white')

label1=Label(win, text="Label 1", font=("Calibri",24,"bold"), bg='white')
label1.pack(pady=15)

label2=Label(win, text="Label 2", font=("Calibri",24,"bold"), bg='white')
label2.pack(pady=15)

label3=Label(win, text="Label 3", font=("Calibri",24,"bold"), bg='white')
label3.pack(pady=15)

win.mainloop()

Output:

Body:
Do this :

label1.pack(side=tk.LEFT,pady=15)
label2.pack(side=tk.LEFT,pady=15)
label3.pack(side=tk.LEFT,pady=15)

Further read : https://effbot.org/tkinterbook/pack.htm


问:
Open firewall port on CentOS 7
I am using CentOS 7 and I have to ensure that ports 2888 and 3888 are open.

I read this article but this did not work because on CentOS 7 OS there is no iptables save command.

Someone told me that the above URL is not valid for CentOS 7. and I should follow this.
But this article is not clear to me on exactly what command I need to execute.

I also found

```<code>firewall-cmd --zone=public --add-port=2888/tcp
</code>```

but this does not survive reboots.

So how can I open the ports and make it survive reboots?

答:
Hello in Centos 7 firewall-cmd.
Yes correct if you use
firewall-cmd --zone=public --add-port=2888/tcp
but if you reload firewal
firewall-cmd --reload

your config not will be save

you need to add key

firewall-cmd --permanent --zone=public --add-port=2888/tcp

Title: Open firewall port on CentOS 7

Body:
I am using CentOS 7 and I have to ensure that ports 2888 and 3888 are open.

I read this article but this did not work because on CentOS 7 OS there is no iptables save command.

Someone told me that the above URL is not valid for CentOS 7. and I should follow this.
But this article is not clear to me on exactly what command I need to execute.

I also found

firewall-cmd --zone=public --add-port=2888/tcp

but this does not survive reboots.

So how can I open the ports and make it survive reboots?


问:
What is the best way to log all commands and responses in Akka.net?
What would be the best way to log all commands and response from an Akka.net cluster? The logging would be handled by a hierarchy of logger actors, but how would these loggers receive or intercept the various commands and responses?
I've tried using the event bus to subscribe to specific commands, but that does not seem to work as I thought, since no command is intercepted.</p>

答:
In Akka.NET every single actor has it's own message queue used to order incoming requests. There are few ways of doing that:

The simplest one is to create your own abstract actor type used by all other actors in your system, and override its AroundReceive method - it will let you to wrap inheriting actors receive handlers with any sort of logic you want:

class AppActor : ActorBase
{
    protected readonly ILoggingAdapter logger = Context.GetLogger();

    protected override bool AroundReceive(Receive receive, object message)
    {
        logger.Debug("Incoming request: {0}", message);
        return receive(message);
    }
}
```

This will also mean, that you need a separate type for every other variant of actors used in your system, like receive actors or persistent actors.

If you want out of the box solution - there's a commercial tool called Phobos, which can collect metrics of all messages in-flight inside of your actor system, log them and even trace causality between them (a.k.a. tracing).

Body:
In Akka.NET every single actor has it's own message queue used to order incoming requests. There are few ways of doing that:

The simplest one is to create your own abstract actor type used by all other actors in your system, and override its AroundReceive method - it will let you to wrap inheriting actors receive handlers with any sort of logic you want:

class AppActor : ActorBase
{
    protected readonly ILoggingAdapter logger = Context.GetLogger();

    protected override bool AroundReceive(Receive receive, object message)
    {
        logger.Debug("Incoming request: {0}", message);
        return receive(message);
    }
}

This will also mean, that you need a separate type for every other variant of actors used in your system, like receive actors or persistent actors.

If you want out of the box solution - there's a commercial tool called Phobos, which can collect metrics of all messages in-flight inside of your actor system, log them and even trace causality between them (a.k.a. tracing).


问:
Click not working after html append using ajax in Kendo UI
I'm working in kendo UI & I'm facing an issue while I give an ng-click option on the HTML content which was loaded later.

Here I'm adding a few codes related to what I have did:

HTML:

```<code><div ng-controller="KendoCtrl">
  <div class="show_html_here"><!-- Ajax inserts HTML here --></div>
</div>
</code>```

HTML & ng-click in RED box & which is working:

```<code><div ng-model="open_Filter" ng-click="onClick('open_Filter')">
  <span>Total Open</span>
  <span>0</span>
</div>
</code>```

HTML & ng-click in ajax HTML & which is not working:

```<code><ul>
  <li ng-model="stageFilter" ng-click="onClick('stageFilter')">PRT - 1</li>
  <li ng-model="stageFilter" ng-click="onClick('stageFilter')">PRT - 2</li>
  <li ng-model="stageFilter" ng-click="onClick('stageFilter')">PRT - 3</li>
  <li ng-model="stageFilter" ng-click="onClick('stageFilter')">PRT - 4</li>
</ul>
</code>```

While clicking in any of the li which has ng-click, the alert is not working.

I have also tried by adding the ajax HTML section directly to my view page without the ajax and at that point, the click was working fine.

Ajax:

```<code>$('body').on('change', '#dropdown_id', function(){
  $.post('controller/htmlsection', {'id': $this.val()}, function(data) {
    $('.show_html_here').html(data.html);
  });
});
</code>```

Kendo/Angular Codes:

```<code>angular.module("KendoApp", ["kendo.directives"]).controller("KendoCtrl", function ($scope, $http) {
  ...
  $scope.onClick = function(param) {
    alert(param); // Not working while we click in a section which is loaded in ajax(eg.: PRT-4)
  }
  ...
});
</code>```

alert(param); inside $scope.onClick not working while we click in a section which is loaded in ajax(eg.: PRT-4) to div with class show_html_here. I think that it is because of the reason that the ajax section is loaded later the Kendo/Angular code is initiated.
If you know some solution for this please help me.

答:
I do not get a solution from Stack & need to find a way to solve my issue. I found a solution for the issue, do not know whether its a proper way or not, but it solved my issue.

Update in HTML:

```<code><ul>
  <li class="customFilter" ng-model="stageFilter">PRT - 1</li>
  <li class="customFilter" ng-model="stageFilter">PRT - 2</li>
  <li class="customFilter" ng-model="stageFilter">PRT - 3</li>
  <li class="customFilter" ng-model="stageFilter">PRT - 4</li>
</ul>
</code>```

Kendo/Angular Codes:

```<code>// Custom Click
$('body').off('click', '.customFilter').on('click', '.customFilter', function () {
  if ($(this).hasClass('active')) {
    $(this).removeClass('active');
    active = 0;
  } else {
    $(this).addClass('active');
    active = 1;
  }
  $scope.onClick('stageFilter', active); // Click was working as required
});
</code>```

The custom click was working properly as I required because of the reason that the click was happening only after the HTML from ajax is loaded.

I do not say that this solution is a proper way, but it's my issue for this time.

Open to new or a proper solution

Body:
I'm working in kendo UI & I'm facing an issue while I give an ng-click option on the HTML content which was loaded later.

Here I'm adding a few codes related to what I have did:

HTML:

HTML & ng-click in RED box & which is working:

  Total Open
  0

HTML & ng-click in ajax HTML & which is not working:

PRT - 1

PRT - 2

PRT - 3

PRT - 4

While clicking in any of the li which has ng-click, the alert is not working.

I have also tried by adding the ajax HTML section directly to my view page without the ajax and at that point, the click was working fine.

Ajax:

$('body').on('change', '#dropdown_id', function(){
  $.post('controller/htmlsection', {'id': $this.val()}, function(data) {
    $('.show_html_here').html(data.html);
  });
});

Kendo/Angular Codes:

angular.module("KendoApp", ["kendo.directives"]).controller("KendoCtrl", function ($scope, $http) {
  ...
  $scope.onClick = function(param) {
    alert(param); // Not working while we click in a section which is loaded in ajax(eg.: PRT-4)
  }
  ...
});

alert(param); inside $scope.onClick not working while we click in a section which is loaded in ajax(eg.: PRT-4) to div with class show_html_here. I think that it is because of the reason that the ajax section is loaded later the Kendo/Angular code is initiated.
If you know some solution for this please help me.

Body:
I do not get a solution from Stack & need to find a way to solve my issue. I found a solution for the issue, do not know whether its a proper way or not, but it solved my issue.

Update in HTML:

<ul>
  <li class="customFilter" ng-model="stageFilter">PRT - 1</li>
  <li class="customFilter" ng-model="stageFilter">PRT - 2</li>
  <li class="customFilter" ng-model="stageFilter">PRT - 3</li>
  <li class="customFilter" ng-model="stageFilter">PRT - 4</li>
</ul>

Kendo/Angular Codes:

// Custom Click
$('body').off('click', '.customFilter').on('click', '.customFilter', function () {
  if ($(this).hasClass('active')) {
    $(this).removeClass('active');
    active = 0;
  } else {
    $(this).addClass('active');
    active = 1;
  }
  $scope.onClick('stageFilter', active); // Click was working as required
});

The custom click was working properly as I required because of the reason that the click was happening only after the HTML from ajax is loaded.

I do not say that this solution is a proper way, but it's my issue for this time.

Open to new or a proper solution


问:
I am using redux in react native application to fetch and display data but its not updating on data change from backend
I am using Redux in my React-Native application.
I am fetching the data from api call and on success rendoring it on ListItem.
I am able to fetch and display data but data is not auto updating unless and until I revisit the page.
Even values are not storing into the app
I am calling method from actions in constructor and componentDidMount method.
Can you Please check the code and tell me where am I going wrong.

Here is action.js

```<code>import {
    FETCHING_PRODUCT_REQUEST,
    FETCHING_PRODUCT_SUCCESS,
    FETCHING_PRODUCT_FAILURE
} from './types';

export const fetchingProductRequest = () => ({
    type : FETCHING_PRODUCT_REQUEST
});

export const fetchingProductSuccess = (json) => ({
    type : FETCHING_PRODUCT_SUCCESS,
    payload : json
});

export const fetchingProductFailure = (error) => ({
    type : FETCHING_PRODUCT_FAILURE,
    payload : error
});

export const fetchProduct = () => {
    return async dispatch => {
        dispatch(fetchingProductRequest());
        try {
            let response = await fetch("http://phplaravel-325095-1114213.cloudwaysapps.com/api/shop/shop");
            let json = await response.json();
            dispatch(fetchingProductSuccess(json));
        } catch(error) {
            dispatch(fetchingProductFailure(error));
        }
    }
}
</code>```

My reducer.js

```<code>import {
    FETCHING_PRODUCT_REQUEST,
    FETCHING_PRODUCT_SUCCESS,
    FETCHING_PRODUCT_FAILURE
} from './../actions/types';

const initialState = {
    loading : false,
    errorMessage : '',
    shops: []
}

const products = ( state = initialState, action ) => {
    switch(action.type) {
        case FETCHING_PRODUCT_REQUEST :
            return { ...state, loading: true} ;
        case FETCHING_PRODUCT_SUCCESS :
            return { ...this.state, loading: false, shops: action.payload };
        case FETCHING_PRODUCT_FAILURE :
            return { ...state, loading: false, errorMessage: action.payload};
    }
};

export default products;
</code>```

product.js

```<code>import * as React from 'react';

import { FlatList , ActivityIndicator} from 'react-native';

import { ListItem } from 'react-native-elements';

import { fetchProduct } from './../../actions/products';

import { connect } from 'react-redux';

import propTypes from 'prop-types';

class Product extends React.Component {

  constructor(props) {
    super(props);
    this.props.fetchProduct();
    this.state = {
      loading : true,
      shops : '',
     isFetching: false,
     active : true,
    }
   }

   fetchProducts() {
    const shopid = 13;
    fetch(`http://phplaravel-325095-1114213.cloudwaysapps.com/api/shop/shop`)
        .then(response => response.json())
          .then((responseJson)=> {
              this.setState({
                 loading: false,
                 shops: responseJson
              })
             alert(JSON.stringify(this.state.shops));
        })
    .catch(error=>console.log(error)) //to catch the errors if any
   }

    componentDidMount(){
      // this.fetchProducts();
      this.props.fetchProduct().then(this.setState({loading : false}));
    }

  renderItem = ({ item }) => (
  <ListItem
    title={item.name}
    subtitle={item.name}
    leftAvatar={{
      source: item.avatar && { uri: item.avatar },
      title: item.name[0]
    }}
    bottomDivider
    chevron
  />
)

render () {
    if(!this.state.loading)
    {
      if(this.props.shopsInfo.loading)
      {
        return (
        <ActivityIndicator/>
        )
      }
      else
      {
        return (
        <FlatList
                vertical
                showsVerticalScrollIndicator={false}
                data={this.props.shopsInfo.shops}
                renderItem={this.renderItem}
              />
      )
      }
    }
    else
    {
      return (
        <ActivityIndicator/>
        )
    }
  }
}

Product.propTypes = {
  fetchProduct:  propTypes.func.isRequired
};

const mapStateToProps = (state) => {
  return { shopsInfo: state };
}

function mapDispatchToProps (dispatch) {
  return {
    fetchProduct: () => dispatch(fetchProduct())
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Product);
</code>```

答:
The problem is your passing wrong props in mapStateToProps function.
In reducer your updating the response value in shop props.
In order to get the updated value you need to pass shops property to get the value.</p>

```<code>const mapStateToProps = (state) => {
   const { shops: state };
   return {shops};
}
</code>```

Body:
I am using Redux in my React-Native application.
I am fetching the data from api call and on success rendoring it on ListItem.
I am able to fetch and display data but data is not auto updating unless and until I revisit the page.
Even values are not storing into the app
I am calling method from actions in constructor and componentDidMount method.
Can you Please check the code and tell me where am I going wrong.

Here is action.js

import {
    FETCHING_PRODUCT_REQUEST,
    FETCHING_PRODUCT_SUCCESS,
    FETCHING_PRODUCT_FAILURE
} from './types';

export const fetchingProductRequest = () => ({
    type : FETCHING_PRODUCT_REQUEST
});

export const fetchingProductSuccess = (json) => ({
    type : FETCHING_PRODUCT_SUCCESS,
    payload : json
});

export const fetchingProductFailure = (error) => ({
    type : FETCHING_PRODUCT_FAILURE,
    payload : error
});

export const fetchProduct = () => {
    return async dispatch => {
        dispatch(fetchingProductRequest());
        try {
            let response = await fetch("http://phplaravel-325095-1114213.cloudwaysapps.com/api/shop/shop");
            let json = await response.json();
            dispatch(fetchingProductSuccess(json));
        } catch(error) {
            dispatch(fetchingProductFailure(error));
        }
    }
}

My reducer.js

import {
    FETCHING_PRODUCT_REQUEST,
    FETCHING_PRODUCT_SUCCESS,
    FETCHING_PRODUCT_FAILURE
} from './../actions/types';

const initialState = {
    loading : false,
    errorMessage : '',
    shops: []
}

const products = ( state = initialState, action ) => {
    switch(action.type) {
        case FETCHING_PRODUCT_REQUEST :
            return { ...state, loading: true} ;
        case FETCHING_PRODUCT_SUCCESS :
            return { ...this.state, loading: false, shops: action.payload };
        case FETCHING_PRODUCT_FAILURE :
            return { ...state, loading: false, errorMessage: action.payload};
    }
};

export default products;

product.js

import * as React from 'react';

import { FlatList , ActivityIndicator} from 'react-native';

import { ListItem } from 'react-native-elements';

import { fetchProduct } from './../../actions/products';

import { connect } from 'react-redux';

import propTypes from 'prop-types';

class Product extends React.Component {

  constructor(props) {
    super(props);
    this.props.fetchProduct();
    this.state = {
      loading : true,
      shops : '',
     isFetching: false,
     active : true,
    }
   }

   fetchProducts() {
    const shopid = 13;
    fetch(`http://phplaravel-325095-1114213.cloudwaysapps.com/api/shop/shop`)
        .then(response => response.json())
          .then((responseJson)=> {
              this.setState({
                 loading: false,
                 shops: responseJson
              })
             alert(JSON.stringify(this.state.shops));
        })
    .catch(error=>console.log(error)) //to catch the errors if any
   }

    componentDidMount(){
      // this.fetchProducts();
      this.props.fetchProduct().then(this.setState({loading : false}));
    }

  renderItem = ({ item }) => (
  <ListItem
    title={item.name}
    subtitle={item.name}
    leftAvatar={{
      source: item.avatar && { uri: item.avatar },
      title: item.name[0]
    }}
    bottomDivider
    chevron
  />
)

render () {
    if(!this.state.loading)
    {
      if(this.props.shopsInfo.loading)
      {
        return (
        <ActivityIndicator/>
        )
      }
      else
      {
        return (
        <FlatList
                vertical
                showsVerticalScrollIndicator={false}
                data={this.props.shopsInfo.shops}
                renderItem={this.renderItem}
              />
      )
      }
    }
    else
    {
      return (
        <ActivityIndicator/>
        )
    }
  }
}

Product.propTypes = {
  fetchProduct:  propTypes.func.isRequired
};

const mapStateToProps = (state) => {
  return { shopsInfo: state };
}

function mapDispatchToProps (dispatch) {
  return {
    fetchProduct: () => dispatch(fetchProduct())
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Product);

Body:
The problem is your passing wrong props in mapStateToProps function.
In reducer your updating the response value in shop props.
In order to get the updated value you need to pass shops property to get the value.

const mapStateToProps = (state) => {
   const { shops: state };
   return {shops};
}


问:
Fieldset HTML Styling using CSS
I have 5 fieldsets which I want to layout in a particular design.
All have the same width, but may have different heights.

```<code>┌-[Fieldset 1]----┐
|                 |
|                 |
└-----------------┘
┌-[Fieldset 2]----┐  ┌-[Fieldset 3]----┐
|                 |  |                 |
|                 |  |                 |
|                 |  |                 |
└-----------------┘  └-----------------┘
┌-[Fieldset 4]----┐  ┌-[Fieldset 5]----┐
|                 |  |                 |
|                 |  |                 |
|                 |  |                 |
|                 |  |                 |
└-----------------┘  └-----------------┘
</code>```

in my HTML source, I want to make the source "clean", which removes any unnecessary formatting tags which include "br" and "p". The container of the fieldsets is set to the full width of the window.

The only way where I can style in it this structure currently, is by placing "br" elements after the fieldsets I want to move to the next line:

```<code><fieldset style='width:200px;'><legend>Fieldset1</legend></fieldset><br/>
<fieldset style='width:200px;'><legend>Fieldset2</legend></fieldset>
<fieldset style='width:200px;'><legend>Fieldset3</legend></fieldset><br/>
<fieldset style='width:200px;'><legend>Fieldset4</legend></fieldset>
<fieldset style='width:200px;'><legend>Fieldset5</legend></fieldset>
</code>```

The container which holds the fieldsets is actually the full length of the screen, (ie:100%). If I take out the "br"s the fieldsets line-up next to each other in a haphazard way.

I have tried various ways to align and adjust the fieldsets in the order that I want them using CSS including using float, clear, padding-left but to no avail.

Is there a proper methodology using CSS that can be applied to get the desired effect wanted as shown above?

thankyou.

答:
If you want all but the first fieldset to flow use Anishs answe, if you always want a 1-2-2-2 etc lay out see this fiddle

EDIT
Just noticed this is almost identical to dtbarne's answer. Accept his and use mine to see it in action

Title: Fieldset HTML Styling using CSS

Body:
I have 5 fieldsets which I want to layout in a particular design.
All have the same width, but may have different heights.

┌-[Fieldset 1]----┐
|                 |
|                 |
└-----------------┘
┌-[Fieldset 2]----┐  ┌-[Fieldset 3]----┐
|                 |  |                 |
|                 |  |                 |
|                 |  |                 |
└-----------------┘  └-----------------┘
┌-[Fieldset 4]----┐  ┌-[Fieldset 5]----┐
|                 |  |                 |
|                 |  |                 |
|                 |  |                 |
|                 |  |                 |
└-----------------┘  └-----------------┘

in my HTML source, I want to make the source "clean", which removes any unnecessary formatting tags which include "br" and "p". The container of the fieldsets is set to the full width of the window.

The only way where I can style in it this structure currently, is by placing "br" elements after the fieldsets I want to move to the next line:

<fieldset style='width:200px;'><legend>Fieldset1</legend></fieldset>

<fieldset style='width:200px;'><legend>Fieldset2</legend></fieldset>
<fieldset style='width:200px;'><legend>Fieldset3</legend></fieldset>

<fieldset style='width:200px;'><legend>Fieldset4</legend></fieldset>
<fieldset style='width:200px;'><legend>Fieldset5</legend></fieldset>

The container which holds the fieldsets is actually the full length of the screen, (ie:100%). If I take out the "br"s the fieldsets line-up next to each other in a haphazard way.

I have tried various ways to align and adjust the fieldsets in the order that I want them using CSS including using float, clear, padding-left but to no avail.

Is there a proper methodology using CSS that can be applied to get the desired effect wanted as shown above?

thankyou.


问:
Get and display the selected variation SKU in WooCommerce
I have this code that works for simple product type but not for variable products in WooCommerce:

```<code>add_shortcode( 'product_sku_div', 'wc_product_sku_div');
function wc_product_sku_div() {
    global $product;

    return sprintf( '<div class="widget" sp-sku="%s"></div>', $product->get_sku() );
}
</code>```

How can I make it work for both simple and variable products?

答:
You need to use get_available_variations();.

```<code>add_shortcode( 'product_sku_div', 'wc_product_sku_div');
function wc_product_sku_div() {
    global $product;

    $variants_array = $product->get_available_variations();

    for ($i = 0; $i <  count($variants_array); $i++ ) {
        return sprintf( '<div class="widget" sp-sku="%s"></div>', $variants_array[$i]['sku'] );
    }
}
</code>```

Reference:

get_available_variations() ~ https://docs.woocommerce.com/wc-apidocs/class-WC_Product_Variable.html

Body:
I have this code that works for simple product type but not for variable products in WooCommerce:

add_shortcode( 'product_sku_div', 'wc_product_sku_div');
function wc_product_sku_div() {
    global $product;

    return sprintf( '

', $product->get_sku() );
}

How can I make it work for both simple and variable products?

Body:
You need to use get_available_variations();.

add_shortcode( 'product_sku_div', 'wc_product_sku_div');
function wc_product_sku_div() {
    global $product;

    $variants_array = $product->get_available_variations();

    for ($i = 0; $i <  count($variants_array); $i++ ) {
        return sprintf( '<div class="widget" sp-sku="%s"></div>', $variants_array[$i]['sku'] );
    }
}

Reference:

get_available_variations() ~ https://docs.woocommerce.com/wc-apidocs/class-WC_Product_Variable.html


问:
In Hapi.js server is not starting
```<code>const Hapi=require('hapi');

//Init server
const server=new Hapi.Server();

//Add connection
server.connection({
    port:3000,
    host:'localhost'
});

//Home route

server.route({
    method:'GET',
    path:'/',
    handler:(request,reply)=>{
        reply('Hello World');
}
})

// Start Server
server.start((err) => {
    if(err){
        throw err;
    }

    console.log(`Server started at: ${server.info.uri}`);
});
</code>```

Blockquote
  This is my first hapi.js server for printing hello world in home page but shows server.connection is not a function and also handlers are not promising.
  Plz help me.

答:
check you node.js  version older versions does not support the latest hapi format. there seems to be alot of diiference betwwen older versions and newer versions of hapi.js </p>

```<code>const Hapi = require('@hapi/hapi');

const port = process.env.PORT || 3000;

const init = async () => {

const server = Hapi.server({
    port: port,
    host: 'localhost'
});

server.route({
    method: 'GET',
    path: '/',
    handler: (request, h) => {
        return 'Hello World!';
    }
});

await server.start();
console.log('Server running on %s', server.info.uri);
};

init();
</code>```

Title: In Hapi.js server is not starting

Body:
const Hapi=require('hapi');

//Init server
const server=new Hapi.Server();

//Add connection
server.connection({
    port:3000,
    host:'localhost'
});

//Home route

server.route({
    method:'GET',
    path:'/',
    handler:(request,reply)=>{
        reply('Hello World');
}
})

// Start Server
server.start((err) => {
    if(err){
        throw err;
    }

    console.log(`Server started at: ${server.info.uri}`);
});

Blockquote
  This is my first hapi.js server for printing hello world in home page but shows server.connection is not a function and also handlers are not promising.
  Plz help me.

Body:
check you node.js  version older versions does not support the latest hapi format. there seems to be alot of diiference betwwen older versions and newer versions of hapi.js

const Hapi = require('@hapi/hapi');

const port = process.env.PORT || 3000;

const init = async () => {

const server = Hapi.server({
    port: port,
    host: 'localhost'
});

server.route({
    method: 'GET',
    path: '/',
    handler: (request, h) => {
        return 'Hello World!';
    }
});

await server.start();
console.log('Server running on %s', server.info.uri);
};

init();


问:
Momentjs format: apply italic text styling
I'm using momentjs in reactjs and I want hours of the date as italic. E.g. 18 Feb 20 11:11

```<code>moment().format('DD MMM YY HH:mm')
</code>```

I can create separate date and hours and apply italic styling to hours.
But how can I do the "HH:mm" italic without calculating separate date and hours?

答:
Square braces will do the job with  tag.

```<code>moment().format("DD MMM YY [<em>]HH:mm[</em>]")
</code>```

For more detail about the formatting, You can check on the documentation here.

Following is the code which I have tested,

```<code>var moment = require('moment');
var http = require('http')

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});

  res.write( moment().format('DD MMM YY [<em>]HH:mm[<em>]'));

  res.end();

}).listen(8000);
</code>```

It outputs as

18 Feb 20  11:59

Edit: Ok, so if you want to do it on the frontend in reactjs, then you can do it by the following code:

```<code>import React from 'react'
import ReactDOM from 'react-dom'
import moment from 'moment'

function App() {
  const date = moment().format('DD MMM YY')
  const hours = moment().format('HH:mm')

  return <div>{date}
    <span style={{ paddingLeft: '2px' , fontStyle: 'italic' }}>
      {hours}
    </span>
  </div>
}

ReactDOM.render(<App />, document.getElementById('root'))
</code>```

Body:
I'm using momentjs in reactjs and I want hours of the date as italic. E.g. 18 Feb 20 11:11

moment().format('DD MMM YY HH:mm')

I can create separate date and hours and apply italic styling to hours.
But how can I do the "HH:mm" italic without calculating separate date and hours?

Body:
Square braces will do the job with <em> tag.

moment().format("DD MMM YY [<em>]HH:mm[</em>]")

For more detail about the formatting, You can check on the documentation here.

Following is the code which I have tested,

var moment = require('moment');
var http = require('http')

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});

  res.write( moment().format('DD MMM YY [<em>]HH:mm[<em>]'));

  res.end();

}).listen(8000);

It outputs as

18 Feb 20  11:59

Edit: Ok, so if you want to do it on the frontend in reactjs, then you can do it by the following code:

import React from 'react'
import ReactDOM from 'react-dom'
import moment from 'moment'

function App() {
  const date = moment().format('DD MMM YY')
  const hours = moment().format('HH:mm')

  return <div>{date}
    <span style={{ paddingLeft: '2px' , fontStyle: 'italic' }}>
      {hours}
    </span>
  </div>
}

ReactDOM.render(<App />, document.getElementById('root'))


问:
How do I change Ionic 4's ion-range pin font and formatting?
As an example, I tried this in my global.scss file:

```<code>.range-pin {
  color: white;
  font-family: sans-serif;

  &after:{
    content: " %";
  }
}
</code>```

But this has no effect. I'm sure this has something to do with shadow root but I'm not sure what the right thing to do is here. Adding ion-range .range-pin to be more specific doesn't help either. How do I achieve this change?

答:
though my answer is not specific to your question but it may help someone as I was also stuck in this issue, I was unable to change the background color of pin and knob of ion-range because in template file, I had set color of ion-range like this

```<code><ion-range color="light" class="range" pin="true" min="18" max="32" step="1" debounce="1000</ion-range>
</code>```

so css custom properties were not working in scss

```<code>.range {
            --knob-size: 40px;
            --knob-background: green !important;
            --bar-background: white;
            --bar-background-active: white;
            display: block;
            height: 40px;
            padding: 0 15px;
        }
</code>```

so don't set the color property in template file

Body:
As an example, I tried this in my global.scss file:

.range-pin {
  color: white;
  font-family: sans-serif;

  &after:{
    content: " %";
  }
}

But this has no effect. I'm sure this has something to do with shadow root but I'm not sure what the right thing to do is here. Adding ion-range .range-pin to be more specific doesn't help either. How do I achieve this change?

Body:
though my answer is not specific to your question but it may help someone as I was also stuck in this issue, I was unable to change the background color of pin and knob of ion-range because in template file, I had set color of ion-range like this

<ion-range color="light" class="range" pin="true" min="18" max="32" step="1" debounce="1000</ion-range>

so css custom properties were not working in scss

.range {
            --knob-size: 40px;
            --knob-background: green !important;
            --bar-background: white;
            --bar-background-active: white;
            display: block;
            height: 40px;
            padding: 0 15px;
        }

so don't set the color property in template file


问:
MYSQL, slow performance group by with multiples tables with millions rows
I have three table with more than 1 millions of rows and one of my query take more than 30 seconds with a date range of 3 months. I have tried multiples index and I think I have respect index orders. I don't know what to do go get a better performance.

Here my query, create table statement, in my explain

```<code>SELECT
MAX(table2.id) as item_id,
MAX(table2.sampled_inspected) as sample_size,
table1.group_col AS ass_group_id

FROM

table1
INNER JOIN table2  ON table1.id = table2.assignment_id
LEFT OUTER JOIN table3  ON table1.po_id = table3.id
LEFT JOIN table4  ON table4.id = table3.supplier_id
LEFT JOIN table5  ON table5.id = table3.project_id

WHERE table1.recycled=0
    AND table2.inspection_status_id > 0
    AND table2.inspection_status_id != 50
    AND table3.importer_id = 215 AND table5.recycled = 0  AND table3.project_id IN ( '2062','2063','2064','2065' ) AND table2.inspection_completed_date >= DATE('2019-10-01')  AND table2.inspection_completed_date <= DATE('2020-01-29')
                        GROUP BY ass_group_id
</code>```

and here my 5 tables

```<code>CREATE TABLE `table1` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `recycled` int(1) NOT NULL DEFAULT '0',
  `group_col` varchar(25) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `po_id` int(11) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `index_assignment_po` (`po_id`),
  KEY `recycled` (`recycled`,`group_col`),
  KEY `group_col` (`group_col`)
) ENGINE=InnoDB AUTO_INCREMENT=3324705 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `table2` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `assignment_id` int(10) unsigned DEFAULT NULL,
  `sampling_size` int(11) DEFAULT NULL,
  `notes` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `photo_report` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `inspection_status_id` int(11) DEFAULT '0',
  `inspection_result_id` int(1) NOT NULL DEFAULT '0',
  `inspection_completed_date` datetime DEFAULT NULL,
  `recycled` int(1) NOT NULL DEFAULT '0',
  `qty_to_inspect` decimal(11,2) DEFAULT NULL,
  `defect_rate` decimal(16,13) DEFAULT NULL,
  `sampled_inspected` int(11) unsigned DEFAULT NULL,
  `inspection_report_id` int(11) unsigned DEFAULT NULL,
  `poline_id` int(11) unsigned DEFAULT NULL,
  `item_status_id` int(11) NOT NULL DEFAULT '0',
  `production_line` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `FK_wsxix_assignments` (`assignment_id`),
  KEY `index_inspection_report_reportid` (`inspection_report_id`),
  KEY `index_ai_inspection_completed_date` (`inspection_completed_date`),
  KEY `index_item_poline` (`poline_id`),
  KEY `index_item_poline_assignment` (`poline_id`,`assignment_id`),
  KEY `wsxix_assignments_items_inspection_status_id` (`inspection_status_id`),
  KEY `wsxix_assignments_items_inspection_result_id` (`inspection_result_id`),
  KEY `inspection_completed_date` (`inspection_completed_date`,`inspection_result_id`,`inspection_status_id`)

) ENGINE=InnoDB AUTO_INCREMENT=3324705 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `table3` (
                          `id` int(10) unsigned NOT NULL AUTO_INCREMENT,

                          `buyer_id` int(11) unsigned DEFAULT NULL,
                          `client_id` int(11) unsigned DEFAULT NULL,
                          `merchandiser_user_id` int(11) unsigned DEFAULT NULL,
                          `factory_id` int(11) unsigned DEFAULT NULL,
                          `dc_id` int(11) unsigned DEFAULT NULL,
                          `parent_id` int(10) unsigned DEFAULT NULL,
                          `supplier_id` int(11) unsigned NOT NULL,
                          `importer_id` int(11) unsigned NOT NULL,
                          `project_id` int(11) unsigned NOT NULL,
                          `tier_two_id` int(11) unsigned DEFAULT NULL,
                          `store_id` int(11) unsigned DEFAULT NULL,
                          PRIMARY KEY (`id`),
                          KEY `buyer_id` (`buyer_id`),
                          KEY `client_id` (`client_id`),
                          KEY `merchandiser_user_id` (`merchandiser_user_id`),
                          KEY `FK_po_factory_companies_id` (`factory_id`),
                          KEY `FK_po_dc_companies_id` (`dc_id`),
                          KEY `index_po_parentid` (`parent_id`),
                          KEY `index_purchaseorders_cie` (`supplier_id`),
                          KEY `index_poimporter_cie` (`importer_id`),
                          KEY `index_purchaseorders_project` (`project_id`),
                          KEY `facory_importer_id` (`factory_id`,`importer_id`),
                          KEY `posu` (`project_id`,`supplier_id`),
                          KEY `store_id` (`store_id`),
                          KEY `tier_two_id` (`tier_two_id`)

) ENGINE=InnoDB AUTO_INCREMENT=34959 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `table4` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `parent_company_id` int(11) DEFAULT NULL,
  `name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,

  PRIMARY KEY (`id`),
  KEY `parent_company_id` (`parent_company_id`)
) ENGINE=InnoDB AUTO_INCREMENT=272 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `table5` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `recycled` int(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `recycled` (`recycled`)
) ENGINE=InnoDB AUTO_INCREMENT=2066 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
</code>```

答:
Add these indexes:

```<code>table2:  (assignment_id, inspection_completed_date)
table2:  (inspection_completed_date, assignment_id)
table3:  (importer_id, project_id, supplier_id, id)
table3:  (project_id, importer_id, supplier_id, id)
table5:  (recycled, id)
table1:  (recycled, po_id, id, group_col)
</code>```

Remove this; it adds nothing, but slows down the query:

```<code>    LEFT JOIN  table4  ON table4.id = table3.supplier_id
</code>```

Body:
I have three table with more than 1 millions of rows and one of my query take more than 30 seconds with a date range of 3 months. I have tried multiples index and I think I have respect index orders. I don't know what to do go get a better performance.

Here my query, create table statement, in my explain

SELECT
MAX(table2.id) as item_id,
MAX(table2.sampled_inspected) as sample_size,
table1.group_col AS ass_group_id

FROM

table1
INNER JOIN table2  ON table1.id = table2.assignment_id
LEFT OUTER JOIN table3  ON table1.po_id = table3.id
LEFT JOIN table4  ON table4.id = table3.supplier_id
LEFT JOIN table5  ON table5.id = table3.project_id

WHERE table1.recycled=0
    AND table2.inspection_status_id > 0
    AND table2.inspection_status_id != 50
    AND table3.importer_id = 215 AND table5.recycled = 0  AND table3.project_id IN ( '2062','2063','2064','2065' ) AND table2.inspection_completed_date >= DATE('2019-10-01')  AND table2.inspection_completed_date <= DATE('2020-01-29')
                        GROUP BY ass_group_id

and here my 5 tables

CREATE TABLE `table1` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `recycled` int(1) NOT NULL DEFAULT '0',
  `group_col` varchar(25) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `po_id` int(11) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `index_assignment_po` (`po_id`),
  KEY `recycled` (`recycled`,`group_col`),
  KEY `group_col` (`group_col`)
) ENGINE=InnoDB AUTO_INCREMENT=3324705 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `table2` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `assignment_id` int(10) unsigned DEFAULT NULL,
  `sampling_size` int(11) DEFAULT NULL,
  `notes` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `photo_report` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  `inspection_status_id` int(11) DEFAULT '0',
  `inspection_result_id` int(1) NOT NULL DEFAULT '0',
  `inspection_completed_date` datetime DEFAULT NULL,
  `recycled` int(1) NOT NULL DEFAULT '0',
  `qty_to_inspect` decimal(11,2) DEFAULT NULL,
  `defect_rate` decimal(16,13) DEFAULT NULL,
  `sampled_inspected` int(11) unsigned DEFAULT NULL,
  `inspection_report_id` int(11) unsigned DEFAULT NULL,
  `poline_id` int(11) unsigned DEFAULT NULL,
  `item_status_id` int(11) NOT NULL DEFAULT '0',
  `production_line` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `FK_wsxix_assignments` (`assignment_id`),
  KEY `index_inspection_report_reportid` (`inspection_report_id`),
  KEY `index_ai_inspection_completed_date` (`inspection_completed_date`),
  KEY `index_item_poline` (`poline_id`),
  KEY `index_item_poline_assignment` (`poline_id`,`assignment_id`),
  KEY `wsxix_assignments_items_inspection_status_id` (`inspection_status_id`),
  KEY `wsxix_assignments_items_inspection_result_id` (`inspection_result_id`),
  KEY `inspection_completed_date` (`inspection_completed_date`,`inspection_result_id`,`inspection_status_id`)

) ENGINE=InnoDB AUTO_INCREMENT=3324705 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `table3` (
                          `id` int(10) unsigned NOT NULL AUTO_INCREMENT,

                          `buyer_id` int(11) unsigned DEFAULT NULL,
                          `client_id` int(11) unsigned DEFAULT NULL,
                          `merchandiser_user_id` int(11) unsigned DEFAULT NULL,
                          `factory_id` int(11) unsigned DEFAULT NULL,
                          `dc_id` int(11) unsigned DEFAULT NULL,
                          `parent_id` int(10) unsigned DEFAULT NULL,
                          `supplier_id` int(11) unsigned NOT NULL,
                          `importer_id` int(11) unsigned NOT NULL,
                          `project_id` int(11) unsigned NOT NULL,
                          `tier_two_id` int(11) unsigned DEFAULT NULL,
                          `store_id` int(11) unsigned DEFAULT NULL,
                          PRIMARY KEY (`id`),
                          KEY `buyer_id` (`buyer_id`),
                          KEY `client_id` (`client_id`),
                          KEY `merchandiser_user_id` (`merchandiser_user_id`),
                          KEY `FK_po_factory_companies_id` (`factory_id`),
                          KEY `FK_po_dc_companies_id` (`dc_id`),
                          KEY `index_po_parentid` (`parent_id`),
                          KEY `index_purchaseorders_cie` (`supplier_id`),
                          KEY `index_poimporter_cie` (`importer_id`),
                          KEY `index_purchaseorders_project` (`project_id`),
                          KEY `facory_importer_id` (`factory_id`,`importer_id`),
                          KEY `posu` (`project_id`,`supplier_id`),
                          KEY `store_id` (`store_id`),
                          KEY `tier_two_id` (`tier_two_id`)

) ENGINE=InnoDB AUTO_INCREMENT=34959 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `table4` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `parent_company_id` int(11) DEFAULT NULL,
  `name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,

  PRIMARY KEY (`id`),
  KEY `parent_company_id` (`parent_company_id`)
) ENGINE=InnoDB AUTO_INCREMENT=272 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `table5` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `recycled` int(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `recycled` (`recycled`)
) ENGINE=InnoDB AUTO_INCREMENT=2066 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

Body:
Add these indexes:

table2:  (assignment_id, inspection_completed_date)
table2:  (inspection_completed_date, assignment_id)
table3:  (importer_id, project_id, supplier_id, id)
table3:  (project_id, importer_id, supplier_id, id)
table5:  (recycled, id)
table1:  (recycled, po_id, id, group_col)

Remove this; it adds nothing, but slows down the query:

    LEFT JOIN  table4  ON table4.id = table3.supplier_id


问:
Why is my clientWidth and offsetWidth equal?

var mydiv = document.getElementById("mydiv");
console.log("offset width = " + mydiv.offsetWidth);
console.log("client width = " + mydiv.clientWidth);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#div1 {
  height: 5000px;
  width: 5000px;
  background-color: #000000;
}</code>```

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

<p>I have a div on a webpage where the content requires a vertical scrollbar. Using javascript, I'm trying to calculate the offsetWidth and clientWidth so that I can ultimately calculate the width of the vertical scrollbar but apparently they are equal. I have:</p>

<p>html:</p>

```

```

<p>css:</p>

```#div1 {
  height: 5000px;
  width: 5000px;
  background-color: #000000;
}
```

<p>js:</p>

```var mydiv = document.getElementById("mydiv");
console.log("offset width = " + mydiv.offsetWidth);
console.log("client width = " + mydiv.clientWidth);
```

答:
Take a look at the two snippet, you can see the difference with scrollbar and without scrollbar.

var mydiv = document.getElementById("mydiv");
console.log("offset width = " + mydiv.offsetWidth);
console.log("client width = " + mydiv.clientWidth);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#div1 {
  height: 100px;
  width: 200px;
  background-color: #000000;
}
#mydiv{
  height:80px;
  width:160px;
  overflow:scroll
}</code>```

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

<p>Below snippet has no scrollbar and overflow, so the client width and offset width are same</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var mydiv = document.getElementById("mydiv");
console.log("offset width = " + mydiv.offsetWidth);
console.log("client width = " + mydiv.clientWidth);</code>```

#div1 {
  height: 100px;
  width: 200px;
  background-color: purple;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="mydiv">
  <div id="div1"></div>
</div></code>```

Body:
var mydiv = document.getElementById("mydiv");
console.log("offset width = " + mydiv.offsetWidth);
console.log("client width = " + mydiv.clientWidth);

#div1 {
  height: 5000px;
  width: 5000px;
  background-color: #000000;
}

I have a div on a webpage where the content requires a vertical scrollbar. Using javascript, I'm trying to calculate the offsetWidth and clientWidth so that I can ultimately calculate the width of the vertical scrollbar but apparently they are equal. I have:

html:

css:

#div1 {
  height: 5000px;
  width: 5000px;
  background-color: #000000;
}

js:

var mydiv = document.getElementById("mydiv");
console.log("offset width = " + mydiv.offsetWidth);
console.log("client width = " + mydiv.clientWidth);

Body:
Take a look at the two snippet, you can see the difference with scrollbar and without scrollbar.

var mydiv = document.getElementById("mydiv");
console.log("offset width = " + mydiv.offsetWidth);
console.log("client width = " + mydiv.clientWidth);

#div1 {
  height: 100px;
  width: 200px;
  background-color: #000000;
}
#mydiv{
  height:80px;
  width:160px;
  overflow:scroll
}

<div id="mydiv">
  <div id="div1"></div>
</div>

Below snippet has no scrollbar and overflow, so the client width and offset width are same

var mydiv = document.getElementById("mydiv");
console.log("offset width = " + mydiv.offsetWidth);
console.log("client width = " + mydiv.clientWidth);

#div1 {
  height: 100px;
  width: 200px;
  background-color: purple;
}

<div id="mydiv">
  <div id="div1"></div>
</div>


问:
error while npm start - Undefined variable: "$grid-row-columns" in \node_modules\bootstrap\scss\mixins\_grid-framework.scss (line 37, column 30)
I am getting ERROR in

```<code>./src/styles/theme/bootstrap.scss (./node_modules/@angular-devkit/build-angular/src/angular-cli-files/plugins/raw-css-loader.js!./node_modules/postcss-loader/src??embedded!./node_modules/sass-loader/lib/loader.js??ref--14-3!./src/styles/theme/bootstrap.scss)
Module build failed (from ./node_modules/sass-loader/lib/loader.js):
</code>```

undefined ^Undefined variable:

```<code>"$grid-row-columns".
      in {path}\node_modules\bootstrap\scss\mixins\_grid-framework.scss (line 37, column 30)
</code>```

答: I just found the solution. I downgraded bootstrap to the version 4.3.1</p>

Body:
I am getting ERROR in

./src/styles/theme/bootstrap.scss (./node_modules/@angular-devkit/build-angular/src/angular-cli-files/plugins/raw-css-loader.js!./node_modules/postcss-loader/src??embedded!./node_modules/sass-loader/lib/loader.js??ref--14-3!./src/styles/theme/bootstrap.scss)
Module build failed (from ./node_modules/sass-loader/lib/loader.js):

undefined ^Undefined variable:

"$grid-row-columns".
      in {path}\node_modules\bootstrap\scss\mixins\_grid-framework.scss (line 37, column 30)


问:
How to place a a Shaded Line After DIV Tag in a HTML Page
Please see my image here:

http://www.tiikoni.com/tis/view/?id=10ca264

After placing the chart, my code starts like this as shown below

```<code><label style="font-weight: bold;">Select Period</label>
</code>```

My question is, as you can see from the image, after placing the chart, there is a line inserted.

Please tell me how to keep this line.

答: Depending on where you're trying to add the "line," it should be as simple as specifying a border-bottom rule on the element you want the line on. Here's a good reference: http://reference.sitepoint.com/css/border-bottom

Body:
Please see my image here:

http://www.tiikoni.com/tis/view/?id=10ca264

After placing the chart, my code starts like this as shown below

Select Period

My question is, as you can see from the image, after placing the chart, there is a line inserted.

Please tell me how to keep this line.


问:
CoreData: This NSPersistentStoreCoordinator has no persistent stores. It cannot perform a save operation
I am facing this issue once or twice a day for the last week when I open my app & the app tries any save operation on the context, I still can't find a way to reproduce it.

I have searched many question on SO for fix, but most of them point 2 issues

Core Data Migration issue(which I don't have as I am on the same Model version no.)

failure of loading the persistent store (which is also doesn't happen in my case as my Core Data Stack doesn't initialise the main UI if the loadPersistentStores method on the persistentContainer fails)

I am using the Core Data stack setup mentioned in the below link:
https://williamboles.me/progressive-core-data-migration/

Here is my CoreData Setup class:

```<code>lazy var persistentContainer: NSPersistentContainer = {

    let persistentContainer = NSPersistentContainer(name: "ABC")
    let description = persistentContainer.persistentStoreDescriptions.first
    description?.shouldInferMappingModelAutomatically = false //inferred mapping will be handled else where
    description?.shouldMigrateStoreAutomatically = false
    description?.type = storeType

    return persistentContainer
}()

lazy var managedObjectContext: NSManagedObjectContext = {
    let context =  self.persistentContainer.newBackgroundContext()
    context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
    context.automaticallyMergesChangesFromParent = true

    return context
}()

lazy var _managedObjectContext: NSManagedObjectContext = {
    let context = self.persistentContainer.viewContext
    context.automaticallyMergesChangesFromParent = true

    return context
}()

// MARK: - Singleton

private static var privateShared : CoreDataManager?

class func shared() -> CoreDataManager { // change class to final to prevent override
    guard let uwShared = privateShared else {
        privateShared = CoreDataManager()
        return privateShared!
    }
    return uwShared
}

class func destroy() {
    privateShared = nil
}

// MARK: - Init

init(storeType: String = NSSQLiteStoreType, migrator: CoreDataMigratorProtocol = CoreDataMigrator()) {
    self.storeType = storeType
    self.migrator = migrator
}

// MARK: - SetUp

func setup(completion: @escaping () -> Void) {
    loadPersistentStore {
        completion()
    }
}

// MARK: - Loading

private func loadPersistentStore(completion: @escaping () -> Void) {

    migrateStoreIfNeeded {
        self.persistentContainer.loadPersistentStores { description, error in
            guard error == nil else {
                fatalError("was unable to load store \(error!)")
            }

            completion()
        }
    }
}

private func migrateStoreIfNeeded(completion: @escaping () -> Void) {

    guard let storeURL = persistentContainer.persistentStoreDescriptions.first?.url else {
        fatalError("persistentContainer was not set up properly")
    }

    if migrator.requiresMigration(at: storeURL, toVersion: CoreDataMigrationVersion.current) {
        DispatchQueue.global(qos: .userInitiated).async {
            self.migrator.migrateStore(at: storeURL, toVersion: CoreDataMigrationVersion.current)

            DispatchQueue.main.async {
                completion()
            }
        }
    } else {
        completion()
    }
}
</code>```

And I initialise the Core Data stack using the following code in the App Delegate:

```<code> CoreDataManager.shared().setup {[unowned self] in

     self.showMainUI()
 }
</code>```

My App crashes after the Home Controller is loaded & some part of my code does a save operation on certain NSManagedObject Model

This how I save to Context:

```<code>let context  = CoreDataManager.shared().managedObjectContext // background context
context.performAndWait {
    if let entityDescription = NSEntityDescription.entity(forEntityName: Entity_Name, in: context) {
        if let runEntityObject =  NSManagedObject(entity: entityDescription, insertInto: context) as? MY_Model {

            // Create the Object
            guard context.hasChanges else { return }
            do {
                try context.save() // Crashes here once or twice a day :(
            }
            catch {
                print(error.localizedDescription)
            }
        }
    }
}
</code>```

Some SO answers also mention of threading issues but I am using the performAndWait Block so the save happen on the same queue

Would be really helpful If someone pointed me in the right direction regarding this issue

答:
After going through my AppDelegate file many times, I found that I was doing a Core Data save operation in the applicationDidBecomeActive method which is also called when the app starts from a suspended state.

So if my Core Data stack setup closure didn't finish before the applicationDidBecomeActive is called the app would crash.

After removing it, the app was working fine without any crashes

Body:
I am facing this issue once or twice a day for the last week when I open my app & the app tries any save operation on the context, I still can't find a way to reproduce it.

I have searched many question on SO for fix, but most of them point 2 issues

Core Data Migration issue(which I don't have as I am on the same Model version no.)

failure of loading the persistent store (which is also doesn't happen in my case as my Core Data Stack doesn't initialise the main UI if the loadPersistentStores method on the persistentContainer fails)

I am using the Core Data stack setup mentioned in the below link:
https://williamboles.me/progressive-core-data-migration/

Here is my CoreData Setup class:

lazy var persistentContainer: NSPersistentContainer = {

    let persistentContainer = NSPersistentContainer(name: "ABC")
    let description = persistentContainer.persistentStoreDescriptions.first
    description?.shouldInferMappingModelAutomatically = false //inferred mapping will be handled else where
    description?.shouldMigrateStoreAutomatically = false
    description?.type = storeType

    return persistentContainer
}()

lazy var managedObjectContext: NSManagedObjectContext = {
    let context =  self.persistentContainer.newBackgroundContext()
    context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
    context.automaticallyMergesChangesFromParent = true

    return context
}()

lazy var _managedObjectContext: NSManagedObjectContext = {
    let context = self.persistentContainer.viewContext
    context.automaticallyMergesChangesFromParent = true

    return context
}()

// MARK: - Singleton

private static var privateShared : CoreDataManager?

class func shared() -> CoreDataManager { // change class to final to prevent override
    guard let uwShared = privateShared else {
        privateShared = CoreDataManager()
        return privateShared!
    }
    return uwShared
}

class func destroy() {
    privateShared = nil
}

// MARK: - Init

init(storeType: String = NSSQLiteStoreType, migrator: CoreDataMigratorProtocol = CoreDataMigrator()) {
    self.storeType = storeType
    self.migrator = migrator
}

// MARK: - SetUp

func setup(completion: @escaping () -> Void) {
    loadPersistentStore {
        completion()
    }
}

// MARK: - Loading

private func loadPersistentStore(completion: @escaping () -> Void) {

    migrateStoreIfNeeded {
        self.persistentContainer.loadPersistentStores { description, error in
            guard error == nil else {
                fatalError("was unable to load store \(error!)")
            }

            completion()
        }
    }
}

private func migrateStoreIfNeeded(completion: @escaping () -> Void) {

    guard let storeURL = persistentContainer.persistentStoreDescriptions.first?.url else {
        fatalError("persistentContainer was not set up properly")
    }

    if migrator.requiresMigration(at: storeURL, toVersion: CoreDataMigrationVersion.current) {
        DispatchQueue.global(qos: .userInitiated).async {
            self.migrator.migrateStore(at: storeURL, toVersion: CoreDataMigrationVersion.current)

            DispatchQueue.main.async {
                completion()
            }
        }
    } else {
        completion()
    }
}

And I initialise the Core Data stack using the following code in the App Delegate:

 CoreDataManager.shared().setup {[unowned self] in

     self.showMainUI()
 }

My App crashes after the Home Controller is loaded & some part of my code does a save operation on certain NSManagedObject Model

This how I save to Context:

let context  = CoreDataManager.shared().managedObjectContext // background context
context.performAndWait {
    if let entityDescription = NSEntityDescription.entity(forEntityName: Entity_Name, in: context) {
        if let runEntityObject =  NSManagedObject(entity: entityDescription, insertInto: context) as? MY_Model {

            // Create the Object
            guard context.hasChanges else { return }
            do {
                try context.save() // Crashes here once or twice a day :(
            }
            catch {
                print(error.localizedDescription)
            }
        }
    }
}

Some SO answers also mention of threading issues but I am using the performAndWait Block so the save happen on the same queue

Would be really helpful If someone pointed me in the right direction regarding this issue


答:
By default, the pack() method packs to the top, so you'll get a vertical stack of labels by default. You want to pack to the left to easily get all the labels on the same row. To do that, change:

```<code>labelX.pack(pady=15)
</code>```

to

```<code>labelX.pack(side=tk.LEFT, pady=15)
</code>```

Also, it's not ideal to import tkinter twice. Best to import it just once, as

```<code>import tkinter as tk
</code>```

and then make sure to use tk. before all the methods, attributes, and classes.

Title: How to Display Multiple Labels in One Line with Python Tkinter?

Body:
I have a Program that displays text on GUI Screen with Multiple Labels. But all the Labels are showing text in the new line and I want to show text in single line. Code is Below:

from tkinter import *
import tkinter as tk

win = Tk()
win.title("Label Screen")
win.geometry("800x600+50+50")
win.config(bg='white')

label1=Label(win, text="Label 1", font=("Calibri",24,"bold"), bg='white')
label1.pack(pady=15)

label2=Label(win, text="Label 2", font=("Calibri",24,"bold"), bg='white')
label2.pack(pady=15)

label3=Label(win, text="Label 3", font=("Calibri",24,"bold"), bg='white')
label3.pack(pady=15)

win.mainloop()

Output:

Body:
By default, the pack() method packs to the top, so you'll get a vertical stack of labels by default. You want to pack to the left to easily get all the labels on the same row. To do that, change:

labelX.pack(pady=15)

to

labelX.pack(side=tk.LEFT, pady=15)

Also, it's not ideal to import tkinter twice. Best to import it just once, as

import tkinter as tk

and then make sure to use tk. before all the methods, attributes, and classes.


答:
The main problem is your y is strings, and strings do not get ordered when processed into the plot.

You don't need to use xlim or ylim unless you want the graph to show a padded or cropped version of your data. Otherwise, the most fitting size is chosen automatically.

You can use a list comprehension as shown, or map(int, y) to get a list of ints.

```<code>y_int = [int(y_i) for y_i in y]
x2 = range(0,len(y))

fig = plt.subplot()
plt.title('Test')
plt.plot(x2, y_int, 'o')
plt.ylabel('A')
plt.show()
</code>```

Title: I have a problem with Mathplotlib in python about the order of Y axis is wrong

Body:
I wanna create a sample graph. But something was wrong in the sorting order of the Y-Axis.

pic 1

I wonder why I defined X-axis as plt.xlim(0, 200). when I tried to show the plot, the order was correct, but in the same way, I also defined the y-axis, the result was wrong. Which part I missed or I was incorrect?

Here my code:

suppose that y is a list of many values (length = 110)

y = ['80', '35', '28', '25', '24', '25', '26', '27', '27', '26', '25', '27', '31', '25', '25', '25', '26', '29', '28', '27', '27', '26', '32', '27', '24', '25', '24', '31', '26', '28', '28', '26', '32', '27', '27', '25', '25', '26', '28', '26', '25', '25', '25', '27', '27', '27', '24', '23', '30', '28', '25', '23', '24', '26', '28', '25', '25', '26', '26', '25', '25', '24', '24', '24', '27', '28', '27', '25', '25', '26', '26', '26', '25', '24', '22', '31', '29', '26', '27', '26', '28', '26', '29', '24', '30', '31', '27', '28', '25', '31', '30', '28', '26', '24', '27', '27', '27', '27', '27', '27'...]

x2 = range(0,110)

fig = plt.subplot()
plt.title('Test')
plt.plot(x2, y, 'o-')
plt.ylim(0, 100)
plt.xlim(0,200)
plt.ylabel('A')
plt.show()

Anyone could explain the reason why Y-axis was wrong, despite I defined plt.ylim() already?

Body:
The main problem is your y is strings, and strings do not get ordered when processed into the plot.

You don't need to use xlim or ylim unless you want the graph to show a padded or cropped version of your data. Otherwise, the most fitting size is chosen automatically.

You can use a list comprehension as shown, or map(int, y) to get a list of ints.

y_int = [int(y_i) for y_i in y]
x2 = range(0,len(y))

fig = plt.subplot()
plt.title('Test')
plt.plot(x2, y_int, 'o')
plt.ylabel('A')
plt.show()


问:
writing values into csv file using single variable
I want to print the i value in csv file like i showed below output format.I can't find a way to write data to a new row in a .csv file using the C language.

I'm saving one variables to the .csv file, I want to display it row by row, I want output like

```<code>1,2
3,4
5,6
</code>```

but it is displaying

```<code>1
2
3
4
5
6 etc.
</code>```

my code is

```<code>    fp = fopen("testfile.csv","w");

    int i;
    for(i = 0 ; i < 100 ; i++)
    {
        printf(" %d", i);
        fprintf(fp , "%d", i);
        fprintf(fp, "\n");
    }

    printf("\n");
    fclose(fp);

    return 0;
}

</code>```

答:
Your printing loop puts \r\n after each field, dropping it to the next line. You can replace that loop with something like:

```<code>fprintf(fp, "%d", a[0]);         // Output first value.
for (int i = 1; i < 6; ++i)
    fprintf(fp, ", %d", a[i]);   // Subsequent value prefixed with comma.
fprintf(fp, "\n");               // Finally, the line end.
</code>```

That's assuming your six items should form a single row (as they did in your original question). If you want some other behaviour (like three rows of two), it's a minor change to do so, especially for a fixed size:

```<code>for (int i = 0; i < 6; i += 2)
    fprintf(fp, "%d, %d", a[i], a[i+1]);
</code>```

Better yet would be to hive that effort off to a function so you can call it from anywhere, with any set of data:

```<code>void outCsvInts(size_t sz, int *data, FILE *fp) {
    if (sz == 0) return;                // Zero size, no output.
    fprintf(fp, "%d", data[0]);         // Output first value.
    for (size_t i = 1; i < sz; ++i)
        fprintf(fp, ", %d", data[i]);   // Subsequent value with comma.
    fprintf(fp, "\n");                  // Line end.
}
</code>```

Call that with:

```<code>outCsvInts(6, a, fp);
</code>```

and it should do what you want (though you would be advised to use something other than the "magic" value 6, using sizeof, for example).

And, with that method, it a lot easier to create a three-by-two output (as per your changed question), with (for small sets):

```<code>outCsvInts(2, &a[0], fp);
outCsvInts(2, &a[2], fp);
outCsvInts(2, &a[4], fp);
</code>```

or (for larger sets):

```<code>for (int i = 0; i < 52; i += 2) // eg, 26 lines of two numbers each.
    outCsvInts(2, &a[i], fp);
</code>```

Body:
I want to print the i value in csv file like i showed below output format.I can't find a way to write data to a new row in a .csv file using the C language.

I'm saving one variables to the .csv file, I want to display it row by row, I want output like

1,2
3,4
5,6

but it is displaying

1
2
3
4
5
6 etc.

my code is

    fp = fopen("testfile.csv","w");

    int i;
    for(i = 0 ; i < 100 ; i++)
    {
        printf(" %d", i);
        fprintf(fp , "%d", i);
        fprintf(fp, "\n");
    }

    printf("\n");
    fclose(fp);

    return 0;
}

Body:
Your printing loop puts \r\n after each field, dropping it to the next line. You can replace that loop with something like:

fprintf(fp, "%d", a[0]);         // Output first value.
for (int i = 1; i < 6; ++i)
    fprintf(fp, ", %d", a[i]);   // Subsequent value prefixed with comma.
fprintf(fp, "\n");               // Finally, the line end.

That's assuming your six items should form a single row (as they did in your original question). If you want some other behaviour (like three rows of two), it's a minor change to do so, especially for a fixed size:

for (int i = 0; i < 6; i += 2)
    fprintf(fp, "%d, %d", a[i], a[i+1]);

Better yet would be to hive that effort off to a function so you can call it from anywhere, with any set of data:

void outCsvInts(size_t sz, int *data, FILE *fp) {
    if (sz == 0) return;                // Zero size, no output.
    fprintf(fp, "%d", data[0]);         // Output first value.
    for (size_t i = 1; i < sz; ++i)
        fprintf(fp, ", %d", data[i]);   // Subsequent value with comma.
    fprintf(fp, "\n");                  // Line end.
}

Call that with:

outCsvInts(6, a, fp);

and it should do what you want (though you would be advised to use something other than the "magic" value 6, using sizeof, for example).

And, with that method, it a lot easier to create a three-by-two output (as per your changed question), with (for small sets):

outCsvInts(2, &a[0], fp);
outCsvInts(2, &a[2], fp);
outCsvInts(2, &a[4], fp);

or (for larger sets):

for (int i = 0; i < 52; i += 2) // eg, 26 lines of two numbers each.
    outCsvInts(2, &a[i], fp);


问:
Calling Array.includes() on a accumulator raises a TypeError; .reduce()
I'm trying to reduce an Array that contains any duplicate words. Upon trying to return the result I get the follow error TypeError: acc.includes is not a function. The way I'm interpreting the error is that the method is not available for the array acc due to the version of JavaScript being used.

Am I correct in assuming this or is there something else going on here?

```<code>function removeDuplicateWords (s) {
  return s.split(" ").reduce(function(acc, value, index, array) {
    if (array.indexOf(value) === array.lastIndexOf(value)) {
      return acc.push(value);
    } else {
        return !acc.includes(value) ? acc.push(value) : "";
    }
  }, [])
}
</code>```

答:
You can use filter instead like shown below. filter has three parameters item, index & array. And indexOf will return index of first occurrence of value. So it will always return first value only thus duplicate value will be removed.

function removeDuplicateWords(s) {
  return s.split(" ").filter((x, i, a) => a.indexOf(x) === i);
}

console.log(removeDuplicateWords("hello hello hey"));```

Body:
I'm trying to reduce an Array that contains any duplicate words. Upon trying to return the result I get the follow error TypeError: acc.includes is not a function. The way I'm interpreting the error is that the method is not available for the array acc due to the version of JavaScript being used.

Am I correct in assuming this or is there something else going on here?

function removeDuplicateWords (s) {
  return s.split(" ").reduce(function(acc, value, index, array) {
    if (array.indexOf(value) === array.lastIndexOf(value)) {
      return acc.push(value);
    } else {
        return !acc.includes(value) ? acc.push(value) : "";
    }
  }, [])
}


问:
Differential code coverage in Azure DevOps
The documentation here says

In order to get coverage metrics for a pull request, first configure a pipeline that validates pull requests. In this pipeline, configure the test tool you are using to collect code coverage metrics. Coverage results must then be published to the server for reporting.

I am not able to understand this. Any example or futher detailed information will be really helpful.

答:
This is about create a pipeline to run a test and publish the test result (collect and publish code coverage results) to check how much the percentage of the changed code lines has been covered by your tests.

There's a .Net Core example mentioned in the doc you can refer to about how to test and publish the test result.

Notice: It's also mentioned in the doc:

the code coverage for pull requests feature discussed in this document is currently available only for .NET and .NET core projects using the Visual Studio code coverage results format (file extension .coverage).


问:
Firefox - How to view network request that opens new window
I am trying to debug (someone else's) site where there is a button that opens a new browser window that leads to a 404. I am trying to determine if the new window is opened with a POST, but the old window's dev network tools don't show the request since it occurs in a new window. And when I open the dev tools in the new window, the request has already been made and doesn't show up.

How do I view this network request in the dev tools?

答:
You can open the Browser Console, beware it's not the same as the Web Console.

From there, you'll be able to monitor all Requests made from all contexts, by switching-on the "Requests" toggle.


问:
How do I get my webserver to serve both my html file and the js file that was built via webpack?
I'm trying to write a webserver that will serve a react app that I am building using webpack but I'm running into an issue serving both the html file and the js file that has the very simple react app that I've written.

My html file looks like this:

```<code><html>
    <body>
        <div id="root" />
        <script src="./dist/main.js"></script>
    </body>
</html>
</code>```

Where main.js is the built webpack js file (sorry if my terminology is off, please let me know if this isn't clear). I'm assuming I need to serve both somehow, but I'm unsure of how to do it - or if that is even the right approach to begin with.

For some more context, my react app opens when I open it via the local path on my browser, and I've tested that my webserver serves really simple html files.

Thanks so much in advance!

答:
Try to use express.js ,
and create static folders as much as you need (You may need 1 if everything in same  main folder)(I named mines public and dist)
then

```<code>const express = require('express');
const app = express();
app.use(express.static("./public"));
app.use(express.static("./dist"));
app.listen(1299, () => {});
</code>```

EDIT : If you need more crude way , you need more improvements like error handling mime types etc.

```<code>
var http = require('http');
const fs = require("fs");
const pathUtils = require("path");

//create a server object:
http.createServer(function(req, res) {
    var path1 = pathUtils.resolve(__dirname, "public") + req.url.replace(/\//g, "\\");
    fs.exists(path1, (exists) => {
        if (exists) {
            fs.readFile(path1, "utf8", (error, content) => {
                if (content)
                    res.write(content);
                else if (error)
                    res.write(error)
                res.end();
            })
        } else {
            res.write("NotFound");
            res.end();
        }
    })
    console.log(path1);

}).listen(8080);
</code>```

Body:
I'm trying to write a webserver that will serve a react app that I am building using webpack but I'm running into an issue serving both the html file and the js file that has the very simple react app that I've written.

My html file looks like this:

Where main.js is the built webpack js file (sorry if my terminology is off, please let me know if this isn't clear). I'm assuming I need to serve both somehow, but I'm unsure of how to do it - or if that is even the right approach to begin with.

For some more context, my react app opens when I open it via the local path on my browser, and I've tested that my webserver serves really simple html files.

Thanks so much in advance!

Body:
Try to use express.js ,
and create static folders as much as you need (You may need 1 if everything in same  main folder)(I named mines public and dist)
then

const express = require('express');
const app = express();
app.use(express.static("./public"));
app.use(express.static("./dist"));
app.listen(1299, () => {});

EDIT : If you need more crude way , you need more improvements like error handling mime types etc.

var http = require('http');
const fs = require("fs");
const pathUtils = require("path");

//create a server object:
http.createServer(function(req, res) {
    var path1 = pathUtils.resolve(__dirname, "public") + req.url.replace(/\//g, "\\");
    fs.exists(path1, (exists) => {
        if (exists) {
            fs.readFile(path1, "utf8", (error, content) => {
                if (content)
                    res.write(content);
                else if (error)
                    res.write(error)
                res.end();
            })
        } else {
            res.write("NotFound");
            res.end();
        }
    })
    console.log(path1);

}).listen(8080);


问:
Can someone give me a simple qt example?
I want to implement a simple QT example: click the QPushButton to display a paragraph of text.

Like this:

I know there are many ways to implement it, but I don't know what's wrong with my code.

```<code>QPushButton *btn = new QPushButton;
//btn->show();
btn->setParent(this);
btn->setText("button 1");

QLabel *la = new QLabel(this);

connect(btn,&QPushButton::clicked,la,&QLabel::setText("show me"));
</code>```

Anyone who can help me？

答:
The idea is to create the QLabel with a predefined text and hide it. On clicking the button, show it. So, QLabel::hide and QLabel::show could be used here. Just take care of the coordinates where you show the label because it would overlap the button itself without layout or proper coordinates.

Example (mainwindow.cpp, constructor):

```<code>#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowTitle("My App");                      // title bar text

    QPushButton *btn = new QPushButton(this);
    btn->setText("Click Me!");

    QLabel *la = new QLabel(this);
    la->setText("Show Me!");                       // set label text in advance
    la->move(100, 100);                            // set label position
    la->hide();                                    // hide label on load

    connect(btn, &QPushButton::clicked, la, &QLabel::show);
}

MainWindow::~MainWindow()
{
    delete ui;
}
</code>```

Output (after clicking the image):

Body:
I want to implement a simple QT example: click the QPushButton to display a paragraph of text.

Like this:

I know there are many ways to implement it, but I don't know what's wrong with my code.

QPushButton *btn = new QPushButton;
//btn->show();
btn->setParent(this);
btn->setText("button 1");

QLabel *la = new QLabel(this);

connect(btn,&QPushButton::clicked,la,&QLabel::setText("show me"));

Anyone who can help me？

Body:
The idea is to create the QLabel with a predefined text and hide it. On clicking the button, show it. So, QLabel::hide and QLabel::show could be used here. Just take care of the coordinates where you show the label because it would overlap the button itself without layout or proper coordinates.

Example (mainwindow.cpp, constructor):

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowTitle("My App");                      // title bar text

    QPushButton *btn = new QPushButton(this);
    btn->setText("Click Me!");

    QLabel *la = new QLabel(this);
    la->setText("Show Me!");                       // set label text in advance
    la->move(100, 100);                            // set label position
    la->hide();                                    // hide label on load

    connect(btn, &QPushButton::clicked, la, &QLabel::show);
}

MainWindow::~MainWindow()
{
    delete ui;
}

Output (after clicking the image):


问:
Calculate average of specified range of values in pandas column and store as another column
I can calculate the average in a for loop but that doesn't seem an efficient solution. So consider the following DataFrame:

```<code>Index Numbers
    1      12
    2      19
    3      47
    4      78
    5      32
    6      63
    7      89
</code>```

I want to calculate the average of every number after the 4th value for the above four values and store it in an adjacent column. So the expected output is:

```<code>Index Numbers Average
    1      12
    2      19
    3      47
    4      78      39
    5      32      44
    6      63      55
    7      89    65.5
</code>```

So average of first four numbers i.e. Index (1 to 4) is 39, next (2 to 5) is 44 and so on. Is there an efficient way to do this? Thanks.

答:
Use Series.rolling with mean:

```<code>df['Average'] = df['Numbers'].rolling(4).mean()
print (df)
   Index  Numbers  Average
0      1       12      NaN
1      2       19      NaN
2      3       47      NaN
3      4       78     39.0
4      5       32     44.0
5      6       63     55.0
6      7       89     65.5
</code>```

Possible functions implemented for rolling:

Rolling.count
Rolling.sum
Rolling.mean
Rolling.median
Rolling.var
Rolling.std
Rolling.min
Rolling.max
Rolling.corr
Rolling.cov
Rolling.skew
Rolling.kurt
Rolling.apply
Rolling.aggregate
Rolling.quantile

Body:
I can calculate the average in a for loop but that doesn't seem an efficient solution. So consider the following DataFrame:

Index Numbers
    1      12
    2      19
    3      47
    4      78
    5      32
    6      63
    7      89

I want to calculate the average of every number after the 4th value for the above four values and store it in an adjacent column. So the expected output is:

Index Numbers Average
    1      12
    2      19
    3      47
    4      78      39
    5      32      44
    6      63      55
    7      89    65.5

So average of first four numbers i.e. Index (1 to 4) is 39, next (2 to 5) is 44 and so on. Is there an efficient way to do this? Thanks.

Body:
Use Series.rolling with mean:

df['Average'] = df['Numbers'].rolling(4).mean()
print (df)
   Index  Numbers  Average
0      1       12      NaN
1      2       19      NaN
2      3       47      NaN
3      4       78     39.0
4      5       32     44.0
5      6       63     55.0
6      7       89     65.5

Possible functions implemented for rolling:

Rolling.count
Rolling.sum
Rolling.mean
Rolling.median
Rolling.var
Rolling.std
Rolling.min
Rolling.max
Rolling.corr
Rolling.cov
Rolling.skew
Rolling.kurt
Rolling.apply
Rolling.aggregate
Rolling.quantile


问:
Send csv file data to sqlite table in django
Model.py

```<code>class Tag(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255, unique=True)

    def __str__(self):
        return self.name

class Question(models.Model):
    name = models.CharField(max_length=255, unique=True)
    Tag_name = models.ManyToManyField(Tag)
</code>```

I need to create an API for onboarding the data in the csv into the tables.

答:
It all depends on your CSV format. As your model has a many to many field in it, you should define CSV in such a way that you can add as many "many to many fields" as you want. Lets suppose your CSV has following format.

```<code>name        | type
Question 1  | question
Tag 11      | tag
Tag 12      | tag
Tag 13      | tag
Question 2  | question
Tag 21      | tag
Tag 22      | tag
Tag 23      | tag
Tag 24      | tag
</code>```

For this type of format, you can write your code like this

```<code>csv_rows = # write code to get CSV rows here
q_obj = None
for row in csv_rows:
    if row[1] == 'question':
       q_obj = Question.objects.create(name=row[0])
    elif row[1] == 'tag':
       if q_obj:
          tag_obj = Tag.objects.create(name=row[0])
          q_obj.Tag_name.add(tag_obj)
</code>```

This format and code will handle any number of tags for a question

Body:
Model.py

class Tag(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255, unique=True)

    def __str__(self):
        return self.name

class Question(models.Model):
    name = models.CharField(max_length=255, unique=True)
    Tag_name = models.ManyToManyField(Tag)

I need to create an API for onboarding the data in the csv into the tables.

Body:
It all depends on your CSV format. As your model has a many to many field in it, you should define CSV in such a way that you can add as many "many to many fields" as you want. Lets suppose your CSV has following format.

name        | type
Question 1  | question
Tag 11      | tag
Tag 12      | tag
Tag 13      | tag
Question 2  | question
Tag 21      | tag
Tag 22      | tag
Tag 23      | tag
Tag 24      | tag

For this type of format, you can write your code like this

csv_rows = # write code to get CSV rows here
q_obj = None
for row in csv_rows:
    if row[1] == 'question':
       q_obj = Question.objects.create(name=row[0])
    elif row[1] == 'tag':
       if q_obj:
          tag_obj = Tag.objects.create(name=row[0])
          q_obj.Tag_name.add(tag_obj)

This format and code will handle any number of tags for a question